////////////////////////////////////////////////////////////////////////////////
function extractString (aString, arrCharToFilter, boolKeep) 
// boolKeep -- (true) return string only contains arrCharToFilter, 
// (false) return string contains char(s) other than arrCharToFilter	
{
	var result, arrChar, flag;
	arrChar = aString.split("");
				
	result = ' ';
			
	for (var i = 0; i < arrChar.length; i++) {
		 flag = true;
				 
		 for (var j = 0; j < arrCharToFilter.length; j++) {				
		      if (arrChar[i] == arrCharToFilter[j]) {
				  if (boolKeep) {
					  result += arrChar[i]; 
				  }
						  
				  flag = false;
							  
				  break;
			  }				
		 }
			     
		 if (flag && !boolKeep) {
			 result += arrChar[i];
		 }
	}
				
	return result.substr(1, result.length - 1);
} // extractString

////////////////////////////////////////////////////////////////////////////////
function string_count (input_string, target_string) 
// count target string
{
	var total = 0;
	
	result = input_string.split("");
	
	for (var i = 0; i < result.length; i++) {
		 var check = result[i];
		 
		 if (check == target_string) {
		 	 total++;
		 }		
    }
		
	return total;
} // string_count

////////////////////////////////////////////////////////////////////////////////
function validateISBN (str) 
// check ISBN is valid or not
{
	if (str.length != 10) {
 		return false;
    }
			
 	var isbn = str.toUpperCase();
 	var sum = 0;
			
 	for (var i = 0; i < 9; i++) { 
 		sum += (10 - i) * isbn.substr(i, 1); 
 	}

	if (isbn.substr(9, 1) == 'X') { 
		sum += 10;
	} else {
		sum += parseInt(isbn.substr(9, 1));
	}
			
	return (sum % 11 == 0);
} // validateISBN
		
////////////////////////////////////////////////////////////////////////////////		
function validateBarcode (str)
// check barcode is valid or not
{
	if (str.length != 13) {
		return false;
	}
			
	var barcode_pattern = new RegExp("^(978)[0-9]{10}$", 'i');
	
	if (!barcode_pattern.test(str)) {
		return false;
	}
			
	var checksum = 0;
	
	for (var i = 0; i < 12; i++) {
		 if (i % 2 == 0) {
		 	checksum += parseInt(str.substr(i, 1));
		 } else {
		 	checksum += parseInt(str.substr(i, 1)) * 3;
		 }
	}
	
	checksum = 10 - checksum % 10;
	checksum = (checksum == 10) ? 0 : checksum;
			
	return (checksum == str.substr(12, 1)) ;      
} // validateBarcode

////////////////////////////////////////////////////////////////////////////////
function input_wizard (input_id, word_id, msg_id, button_id) 
// Parameter:
// input_id (str) : success / has_error
// word_id  (str) : id of the input tag
// msg_id   (str) : id for tag for valid/invalid message, also digit count
// arrVAlidMsg (str[]) : an array of string for :
//				   [0] : valid ISBN
//				   [1] : invalid ISBN
//				   [2] : valid Barcode
//				   [3] : invalid Barcode
///////////////////////////////////////////////////////////////////
{
	var arrValidMsg = new Array('Valid ISBN', 'Invalid ISBN', 'Valid Barcode', 'Invalid Barcode');
	
	var o_input  = document.getElementById(input_id);
	var o_word   = document.getElementById(word_id);
	var o_msg    = document.getElementById(msg_id);
	var o_button = document.getElementById(button_id);

	var status = o_msg.className;
	
	var pattern = /no_count/;
	
	if (status.match(pattern)) {
		return;
	}

	var phase_1 = extractString(o_word.value, new Array('-', ' '), false);
	var isbn_pattern    = new RegExp("^\\d\\d\\d\\d\\d\\d", 'i');
	var barcode_pattern = new RegExp("^(978)\\d\\d\\d", 'i');
	var max_length;
	var input_class;

	o_msg.saveSearchWordLabel = (o_msg.saveSearchWordLabel) ? o_msg.saveSearchWordLabel : o_msg.innerHTML;
	o_word.saveMaxLength = (o_word.saveMaxLength && o_word.maxLength) ? o_word.saveMaxLength : o_word.maxLength;

    // find out the possible type
	var inputType = 'keywords'; // default input type
	o_word.maxLength = 100;     // default max length
	
	var input = '';			
	input = extractString(phase_1, new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), true);
	
	if (barcode_pattern.test(phase_1) && input.length <= 13) { 
		inputType = 'barcode';
	} else if (isbn_pattern.test(phase_1)) { 
		input = extractString(phase_1, new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'x', 'X'), true);
		
		if (input.length <= 10) {
			inputType = 'isbn';
		}
	}
			
    // perform wizard tips after assumed the possible input type
	var isValidSoFar = true; 
	var labelText = '';

	switch (inputType) {
		case ('isbn') :
		    var total_minus = string_count(o_word.value, '-');
		    
		    if (input.length == 10) {
				o_word.maxLength = 10 + total_minus;
		    }
			
			labelText = 'Digit-count: <span style="background-color: yellow;">'+input.length+'</span>/'+10;
			// labelText = count_str.replace(/@/i, '<span style="background-color: yellow;">'+input.length+'</span>/'+10);

			if (input.length == 10) {
				isValidSoFar = validateISBN(input);
				
				labelText = 'Digit-count: <b>'+10+'</b>/'+10;
				// labelText = count_str.replace(/@/i, '<b>'+10+'</b>/'+10);
			} else if ('' != extractString(phase_1, new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'x', 'X'), false)) {
				isValidSoFar = false;	
			} 
									
			// perform visual effect
			if (o_msg.innerHTML != labelText) {
				o_msg.innerHTML = labelText;
			}

			input_class = '';
			// input_class = o_input.className;
			o_input.className = input_class;
			
			/*
			if (button_id) {
				o_button.disabled = false;
			}
			*/
			
			if (input.length == 10) {
				if (isValidSoFar) {
					input_class = 'success';
					o_msg.innerHTML = arrValidMsg[0];
					
					if (button_id) {
						o_button.disabled = false;
					}
				} else {
					input_class = 'has_error';
					o_msg.innerHTML = arrValidMsg[1];
					
					if (button_id) {
			    		o_button.disabled = true;
					}
				}
				
				o_input.className = input_class;
			} else {
				if (button_id) {
					o_button.disabled = true;
				}	
			}
	
			break;		
		case ('barcode') :
		    var total_minus = string_count(o_word.value, '-'); 
	
		    if (input.length == 13) {
		    	o_word.maxLength = 13 + total_minus;
		    }
			
			if (input.length == 13) {
				isValidSoFar = validateBarcode(input);
				
				labelText = 'Digit-count: <b>'+13+'</b>/'+13;
				// labelText = count_str.replace(/@/i, '<b>'+13+'</b>/'+13);
			} else if ('' != extractString(phase_1, new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), true)) {
				isValidSoFar = false;
				
				labelText = 'Digit-count: <span style="background-color: yellow;">'+input.length+'</span>/'+13;
				// labelText = count_str.replace(/@/i, '<span style="background-color: yellow;">'+input.length+'</span>/'+13);
			}

			// perform visual effect			
			if (o_msg.innerHTML != labelText) {
				o_msg.innerHTML = labelText;
			}
			
			input_class = '';
			// input_class = o_input.className;
			o_input.className = input_class;

			/*
			if (button_id) {
				o_button.disabled = false;
			}
			*/
			
			if (input.length == 13) {	
				if (isValidSoFar) {
					input_class = 'success';
				    o_msg.innerHTML = arrValidMsg[2];
				    
				    if (button_id) {
						o_button.disabled = false;
					}
				} else {
					input_class = 'has_error';
					o_msg.innerHTML = arrValidMsg[3];
					
					if (button_id) {
			    		o_button.disabled = true;
					}
				} 
				
				o_input.className = input_class;
			} else {
				if (button_id) {
					o_button.disabled = true;
				}	
			}

			break;
		case ('keywords') :
			default:
			    input_class = '';
			    // input_class = o_input.className;
				o_input.className = input_class;
			
			    o_msg.innerHTML = '<span class="invisible">.</span>';	
			    // o_msg.innerHTML = '';	

			    if (button_id) {
			    	if (trim(o_word.value) != '') {
			    	    o_button.disabled = false;
			    	} else {
			    		o_button.disabled = true;
			    	}
			    }
				
				break;
	}

	if (input_id == 'search_item_class') {
		o_input.className = 'input_wrap '+input_class;
	} 
	
	// var msg_check = document.getElementById(msg_id);
	
	if (o_msg.innerHTML == '<span class="invisible">.</span>') {
		o_msg.className = 'invisible';
	}
	
	return;
} // input_wizard

////////////////////////////////////////////////////////////////////////////////
function change_value (text_id, val)
// change the text value
{
	var text = document.getElementById(text_id);
	
	if (text) {
		text.value = val;
	} 
	
  	return;
} // change_value

////////////////////////////////////////////////////////////////////////////////
function control_button (text_id, button_id)
// hide/show button based on textbox value
{
 	var text = document.getElementById(text_id);
	var button = document.getElementById(button_id);
 	
	if (trim(text.value) != '') {
		button.disabled = false;
	} else {
		button.disabled = true;
	}
	
 	return;
} // control_button

////////////////////////////////////////////////////////////////////////////////
function div_control (div_id, s)
// expanded/contracted div class when onclick
{
	var div = document.getElementById(div_id);

	if (div.className == 'expanded') {
		div.className = 'contracted';

		if (s != '') {
			change_session_value(s, -1);
		}
	} else {
		div.className = 'expanded';
		
		if (s != '') {
			change_session_value(s, 1);
		}
	}

  	return;
} // div_control

////////////////////////////////////////////////////////////////////////////////
function focus_control (div_id, text_id, class_name)
// control focus of textbox
{
	var div  = document.getElementById(div_id);
	var text = document.getElementById(text_id);
	
	if (class_name) {
		if (div.className == class_name) {
			text.focus();
		} 
	} else {
		if (div.className == 'expanded') {
			text.focus();
		} 
	}

  	return;
} // focus_control

////////////////////////////////////////////////////////////////////////////////
function focus_id_control (text_id)
// control focus of textbox
{
	var text = document.getElementById(text_id);

	if (text) {
		text.focus();
	} 

  	return;
} // focus_id_control

////////////////////////////////////////////////////////////////////////////////
function openwin (url, width, height, scrollbar, resizable) 
// open pop up window
{
	window.open(url, 'newwindow', 'width = '+width+', height = '+height+', resizable = '+resizable+', scrollbars='+scrollbar+', toolbar=no, menubar=no, location=no, status=no');

	return;
} // openwin

////////////////////////////////////////////////////////////////////////////////
function select_all_box (total, all_id, box_id, target_id, class_id, class_name)
// select all box
{
	for (var i = 1; i <= total; i++) {
		 var box    = box_id+'_'+i;
		 var target = target_id+'_'+i;
	
		 if (document.getElementById(target).disabled == true) {
		 	 continue;
		 }
		 
		 if (document.getElementById(all_id).checked == false) {
		 	 document.getElementById(box).className  = ''; 
			 document.getElementById(target).checked = false;
			 
			 change_value(class_id+'_'+i, '');
		 } else {
		 	 if (class_name) {
		 	 	 document.getElementById(box).className = class_name; 
		 	 } else {
		 	 	 document.getElementById(box).className = 'highlighter'; 
		 	 }
		 	
			 document.getElementById(target).checked = true;
			 
			 if (class_name) {
		 	 	 change_value(class_id+'_'+i, class_name);
		 	 } else {
		 	 	 change_value(class_id+'_'+i, 'highlighter');
		 	 }
		 }
	}
	
  	return;
} // select_all_box

////////////////////////////////////////////////////////////////////////////////
function select_highlight (target_id, highlight_id, class_name, class_id) 
// give yellow background for selected check box / radio button
{
	var target    = document.getElementById(target_id);
	var highlight = document.getElementById(highlight_id);
	
	if (target.checked == true) {
		highlight.className = class_name;
		
		change_value(class_id, class_name);
	} else {
		highlight.className = '';
		
		change_value(class_id, '');
	}
	
	return;
} // select_highlight

////////////////////////////////////////////////////////////////////////////////
function change_id (input_id, value_1, value_2)
// change particular HTML ID
{
	var input = document.getElementById(input_id);
	
	if (!value_2) {
		if (input) {
			input.className = value_1;
		} 
	} else {
		if (input.className == value_1) {
			input.className = value_2;
		} else {
			input.className = value_1;
		}
	}
	
  	return;
} // change_id

///////////////////////////////////////////////////////
function control_id_class() 
{
	var argv = control_id_class.arguments;
	var argc = argv.length;
  
  	for (var i = 0; i < argc; i++) {
  		 var target = argv[i].split(";")
  		 
  		 var input_id   = document.getElementById(target[0]);
  		 var class_name = target[1];
  		 
  		 if (input_id) {
			 input_id.className = class_name;
		 } 
  	}
} // control_id_class 

////////////////////////////////////////////////////////////////////////////////
function change_html_value (target_id, val)
// change the HTML value
{
	var target = document.getElementById(target_id);
	
	if (target) {
		target.innerHTML = val;
	} 
	
  	return;
} // change_html_value

////////////////////////////////////////////////////////////////////////////////
function trim (s)
// remove leading and trainling withespace from a string 
{
	while (s.substring(0, 1) == ' ') {
    	s = s.substring(1, s.length);
  	}
  	
  	while (s.substring(s.length - 1, s.length) == ' ') {
    	s = s.substring(0, s.length - 1);
  	}
  	
  	return s;
} // trim

////////////////////////////////////////////////////////////////////////////////
function form_input_check (input_id, div_id, error_id, error_message) 
// form value check
{
	var error = 0;
	
	var input = document.getElementById(input_id);

	if (input) {
		if (trim(input.value) == '' || input.value == '') {
			error = 1;
	
			change_id(div_id, 'input_wrap has_error');
			change_id(error_id, 'error');
			change_html_value(error_id, error_message);
		} else {
			change_id(div_id, 'input_wrap');
			change_id(error_id, 'hide');
			change_html_value(error_id, '');
		}
	}
	
	return error;
} // form_input_check

var Color = new Array();
Color[1] = 'ff';
Color[2] = 'ee';
Color[3] = 'dd';
Color[4] = 'cc';
Color[5] = 'bb';
Color[6] = 'aa';
Color[7] = '99';

///////////////////////////////////////////////////////
function waittofade() 
{
	if (document.getElementById('fade')) {
		setTimeout("fade_in(7, 'fade')", 500);
    }
    
    return;
} // waittofade

///////////////////////////////////////////////////////
function fade_in (where, div_id, target_class) 
{
	var target_class = document.getElementById(div_id).className;

	if (where >= 1) {
		document.getElementById(div_id).style.backgroundColor = '#ffff' + Color[where];
        // document.getElementById('fade').style.backgroundColor = '#ffff' + Color[where];
      
        if (where > 1) {
            where -= 1;
            
            setTimeout("fade_in("+where+", '"+div_id+"', '"+target_class+"')", 200);
            // setTimeout("fade_in("+where+")", 200);
        } else {
      	    where -= 1;
            setTimeout("fade_in("+where+", '"+div_id+"', '"+target_class+"')", 200);

            if (div_id == 'fade') {
            	if (target_class != '') {
            		if (target_class == 'item_div' || target_class == 'content') {
            			document.getElementById(div_id).style.backgroundColor = 'transparent';
            		} else {
            			document.getElementById(div_id).style.backgroundColor = '';
            		}
            	} else {
           	    	document.getElementById(div_id).style.backgroundColor = 'transparent';
            	}
            } else {
                document.getElementById(div_id).style.backgroundColor = '';
            }
            
            if (target_class) {
            	change_id(div_id, target_class);
            } else {
            	change_id(div_id, '');
            }
            
            // setTimeout("fade_in("+where+")", 200);
            // document.getElementById('fade').style.backgroundColor = 'transparent';
            // document.getElementById('fade').id = '';
        }
	}
} // fade_in

////////////////////////////////////////////////////////////////////////////////
function control_button_class (text_id, button_id, name)
// hide/show button based on textbox value
{
 	var text   = document.getElementById(text_id);
	var button = document.getElementById(button_id);
 	
	if (trim(text.value) != '') {
		button.className = name;
	} else {
		button.className = 'hide';
	}
	
 	return;
} // control_button_class

////////////////////////////////////////////////////////////////////////////////
function control_table_class (text_id, table_id, name)
// hide/show table based on textbox value
{
 	var text  = document.getElementById(text_id);
	var table = document.getElementById(table_id);
 	
	if (trim(text.value) != '') {
		table.className = name;
	} else {
		table.className = 'hide';
	}
	
 	return;
} // control_table_class

////////////////////////////////////////////////////////////////////////////////
function disableEnterKey (e)
// disable form submit on enter keypress
{
   var key;

   if (window.event) {
       key = window.event.keyCode;     // IE
   } else {
       key = e.which;     // firefox
   }

   if (key == 13) {
       return false;
   } else {
       return true;
   }
} // disableEnterKey

////////////////////////////////////////////////////////////////////////////////
function check_row (target_id) 
// check / uncheck the row
{
	var val = document.getElementById(target_id);
	
	if (val.checked == false) {
		val.checked = true;
	} else {
		val.checked = false;
	}
	
	return;
} // check_row

////////////////////////////////////////////////////////////////////////////////
function clear_form (target_id, target_class) 
// clear form value (only the default one) when mouse click
{
	var val = document.getElementById(target_id);

	if (val.className == target_class) {
	 	val.value = '';
	}
	
	return;
} // clear_form

////////////////////////////////////////////////////////////////////////////////
function clear_form_value (box) 
// clear form value (only the default one) when mouse click
{
	if (box.value == box.defaultValue) {
	 	box.value = '';
	}
	
	return;
} // clear_form_value

////////////////////////////////////////////////////////////////////////////////
function form_submit (form_id, button_id) 
// do some action if network connection has problem
{
	var form   = document.getElementById(form_id);
	var button = document.getElementById(button_id);
   
	form.submit();
	button.disabled = true;
	button.value = 'Wait';

	return;
} // form_submit

////////////////////////////////////////////////////////////////////////////////
function select_all (form_name, field_name, field_value) 
// select/unselect all check boxes
{
	formblock = document.getElementById(form_name);
	forminput = formblock.getElementsByTagName('input');
	
	for (i = 0; i < forminput.length; i++) {
		// regex here to check name attribute
		var regex = new RegExp(field_name, 'i');
		
		if (regex.test(forminput[i].getAttribute('name'))) {
			if (field_value == '1') {
				forminput[i].checked = true;
			} else {
				forminput[i].checked = false;
			}
		}
	}
	
	return;
} // select_all

////////////////////////////////////////////////////////////////////////////////
function hightlight_all (source_id, total, name) 
// hightlight/un-hightlight all check boxes
{
	for (var i = 1; i <= total; i++) {
 		 document.getElementById(source_id+'_'+i).className = name;
 	}
	
	return;
} // hightlight_all

///////////////////////////////////////////////////////////////////////////////
function search_item_timeout() 
// do some action if network connection has problem
{
	location.replace('no_record_found.php');
	// alert('Hm ... there seems to be a connection problem. Try again in a moment.');
	
	return;
} // search_item_timeout

////////////////////////////////////////////////////////////////////////////////
function preload_image() 
// preload some images
{
	var image_file = new Array('http://static.anobii.com/anobi/image/cover_background_hover_1.gif', 
	                           'http://static.anobii.com/anobi/image/cover_background_hover_2.gif',
	                           'http://static.anobii.com/anobi/image/cover_background_hover_3.gif', 
	                           'http://static.anobii.com/anobi/image/cover_background_hover_4.gif',
	                           'http://static.anobii.com/anobi/image/cover_background_hover_5.gif', 
	                           'http://static.anobii.com/anobi/image/cover_background_hover_6.gif',
	                           'http://static.anobii.com/anobi/image/cover_background_hover_7.gif', 
	                           'http://static.anobii.com/anobi/image/cover_background_hover_8.gif',
	                           'http://static.anobii.com/anobi/image/main_menu_bg.jpg', 
	                           'http://static.anobii.com/anobi/image/main_menu_bg_hl.jpg',
	                           'http://static.anobii.com/anobi/image/az_star_0.gif', 
	                           'http://static.anobii.com/anobi/image/az_star_1.gif', 
	                           'http://static.anobii.com/anobi/image/az_star_5.gif', 
	                           'http://static.anobii.com/anobi/image/view_1_0.gif', 
	                           'http://static.anobii.com/anobi/image/view_1_1.gif',
	                           'http://static.anobii.com/anobi/image/view_1_2.gif', 
	                           'http://static.anobii.com/anobi/image/view_2_0.gif',
	                           'http://static.anobii.com/anobi/image/view_2_1.gif', 
	                           'http://static.anobii.com/anobi/image/view_2_2.gif',
	                           'http://static.anobii.com/anobi/image/view_3_0.gif', 
	                           'http://static.anobii.com/anobi/image/view_3_1.gif',
	                           'http://static.anobii.com/anobi/image/view_3_2.gif', 
	                           'http://static.anobii.com/anobi/image/button_compare_prices_hover.gif',
	                           'http://static.anobii.com/anobi/image/button_compare_prices.gif')
    
	// start preloading
	var img = new Array();
	
    for (i = 0; i <= image_file.length; i++) {
    	 img[i] = new Image();
         img[i].src = image_file[i];
    }
    
    return;
} // preload_image

////////////////////////////////////////////////////////////////////////////////
function change_id_style (input_id, style)
// change particular HTML ID style
{
	var input = document.getElementById(input_id);
	
	if (input) { 
		input.style.display = style; 
	}
	
  	return;
} // change_id_style

////////////////////////////////////////////////////////////////////////////////
function disable_button (input_id)
// disable the submit button
{
	var input = document.getElementById(input_id);
	
	if (input) { 
		input.disabled = true; 
	}
	
  	return;
} // disable_button

////////////////////////////////////////////////////////////////////////////////
function check_select (source_id, div_id, total) 
// check if any checkbox was checked
{
	var div = document.getElementById(div_id);
    var sum = 0;
	
    div.className = 'hide';
    
	for (var i = 1; i <= total; i++) {
		 var status = document.getElementById(source_id+'_'+i);
		 
		 if (status.checked == true) {
		 	 sum = sum + 1;
		 	 break;
		 }
	}
		
	if (sum == 0) { 
	    div.className = 'error';
	}
	
	return;
} // check_select

////////////////////////////////////////////////////////////////////////////////
function select_row_highlight (target_id, highlight_id, class_id, class_name) 
// give yellow background for selected row
{
	var target    = document.getElementById(target_id);
	var highlight = document.getElementById(highlight_id);
	
	if (target.checked == true) {
		target.checked = false;
		highlight.className = '';
		
		change_value(class_id, '');
	} else {
		target.checked = true;
		highlight.className = class_name;
		
		change_value(class_id, class_name);
	}
	
	return;
} // select_row_highlight

////////////////////////////////////////////////////////////////////////////////
function radio_button_highlight (name, total)
// highlight radio button option
{
	for (var i = 1; i <= total; i++) {
		 var opt   = document.getElementById(name+'_'+i);
         var opt_h = document.getElementById(name+'_highlight_'+i);
         
         if (opt.checked == true) {
         	 opt_h.className = 'selected_radio';
         } else {
         	 opt_h.className = '';
         }
	}
    	
	return;
} // radio_button_highlight

////////////////////////////////////////////////////////////////////////////////
function set_same_value (source_id, dest_id, total) 
// set all field to same value
{
	var source = document.getElementById(source_id);
	
	for (var i = 1; i <= total; i++) {
		 var s = source.value;
		
		 if (s != '--') {
		 	 if (dest_id == 'batch_rate') {
		 	 	 if (s != '0') {
		 	 	 	 document.getElementById(dest_id+'_'+i).value = s;
		 	 	 }
		 	 } else {
		 	 	 document.getElementById(dest_id+'_'+i).value = s;
		 	 }
		 
		 	 if (dest_id == 'batch_progress' || dest_id == 'batch_year' ||
		      	 dest_id == 'batch_month' || dest_id == 'batch_day') {
		 	   	 show_all_option('batch_progress_'+i, 'batch_year_'+i, 'batch_month_'+i, 'batch_day_'+i, 'batch_rate_'+i);
		 	 }
		 
			 if (dest_id == 'batch_month') {
		 		 date_pre_select('batch_year_'+i, 'batch_month_'+i, 'batch_day_'+i);
		 	 }
		 }
	}
	
	return;
} // set_same_value

////////////////////////////////////////////////////////////////////////////////
// for date function
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
function date_assist (year, month, day) 
// assist user to select correct date
{
	if (year.selectedIndex > 0) {
		month.disabled = false;
			
		if (month.selectedIndex > 0) {
			day.disabled = false;

			for (var i = 1; i <= 31; i++) {
				 day[i].disabled = false; 
				 day[i].style.display = '';
			}

			if (month.selectedIndex == 4 || month.selectedIndex == 6 || 
			    month.selectedIndex == 9 || month.selectedIndex == 11) {
				if (day.selectedIndex == 31) {
				    day.selectedIndex = 0;
				}	
				    
				day[31].selected = false; 
				day[31].style.display = 'none';
				// day[31].style.visibility = 'invisible';
			}
			
			if (month.selectedIndex == 2) {
				if (day.selectedIndex == 31 || day.selectedIndex == 30) {
				    day.selectedIndex = 0;
				}
				     	
				day[31].selected = false; 
				day[31].disabled = true; 
				day[31].style.display = 'none';
				        
				day[30].selected = false; 
				day[30].disabled = true; 
			    day[30].style.display = 'none';
				    
				if (!checkleapyear(year[year.selectedIndex].value)) {
					if (day.selectedIndex == 29) { 
					    day.selectedIndex = 0; 
					}
					    	
					day[29].selected = false; 
					day[29].disabled = true; 
					day[29].style.display = 'none';
				}
			}	
		} else {
			day.disabled = true;
		}
	} else {	
        month.disabled = true;		
		day.disabled = true;
	}
	
	return;
} // date_assist

////////////////////////////////////////////////////////////////////////////////
function date_helper (radioId, yearId, monthId, dayId) 
// assist user to select correct date (old version)
{
	if (!document.getElementById) {
		return;
	}

	var oRadio = document.getElementById(radioId);
	var oYear = document.getElementById(yearId);
	var oMonth = document.getElementById(monthId);
	var oDay = document.getElementById(dayId);
	
	if (!oRadio || !oYear || !oMonth || !oDay) {
		return;
	}
	
	oYear.disabled  = true; 
	oMonth.disabled = true; 
	oDay.disabled   = true;

	// if (oRadio.checked) {
	if ((oRadio.value == '1' && yearId == 'year') || radioId == 'reading_progress_div' ||
	     yearId == 'item_get_year' || yearId == 'due_date_year' || yearId == 'publication_year' ||
	     yearId == 'birth_year' || 
	    ((oRadio.value == '1' || oRadio.value == '3' || oRadio.value == '4') && 
	      yearId == 'reading_year')) {
		oYear.disabled = false;

		if (oYear.selectedIndex > 0) {
			oMonth.disabled = false;

			if (oMonth.selectedIndex > 0) {
				oDay.disabled = false;

				for (var i = 1; i <= 31; i++) {
					 oDay[i].disabled = false; 
				     oDay[i].style.display = '';
				}

			    if (oMonth.selectedIndex == 4 || oMonth.selectedIndex == 6 || 
			     	oMonth.selectedIndex == 9 || oMonth.selectedIndex == 11) {
				    if (oDay.selectedIndex == 31) {
				     	oDay.selectedIndex = 0;
				    }	
				    
				    oDay[31].selected = false; 
				    oDay[31].style.display = 'none';
			     }
			
			     if (oMonth.selectedIndex == 2) {
				     if (oDay.selectedIndex == 31 || oDay.selectedIndex == 30) {
				     	 oDay.selectedIndex = 0;
				     }
				     	
				     oDay[31].selected = false; 
				     oDay[31].disabled = true; 
				     oDay[31].style.display = 'none';
				        
				     oDay[30].selected = false; 
				     oDay[30].disabled = true; 
				     oDay[30].style.display = 'none';
				    
				     if (!checkleapyear(oYear[oYear.selectedIndex].value)) {
					     if (oDay.selectedIndex == 29) { 
					    	 oDay.selectedIndex = 0; 
					     }
					    	
					     oDay[29].selected = false; 
					     oDay[29].disabled = true; 
					     oDay[29].style.display = 'none';
				     }
			      }	
			}
		}
	}

	return;
} // date_helper

////////////////////////////////////////////////////////////////////////////////
function date_pre_select (year_id, month_id, day_id) 
// assist user to select correct date
{
	var today = new Date();
 
    var t_year  = today.getFullYear();
    var t_month = today.getMonth() + 1;
    var t_day   = today.getDate();
    
    var year = document.getElementById(year_id);
	var month = document.getElementById(month_id);
	var day = document.getElementById(day_id);
	
	var c_year  = year.value;
	var c_month = month.value;
	var c_day   = day.value;
	
	// select default month and day
	if (c_year == t_year && c_month == t_month && c_day == 'xx') {
		// month[n_month].selected = true;
		day[t_day].selected = true;  
	}
	
	return;
} // day_pre_select

///////////////////////////////////////////////////////
function checkleapyear (datea) 
// check given year is leap year or not
{
	datea = parseInt(datea);
	
	if (datea % 4 == 0) {
		if (datea % 10 != 0) {
			return true;
		} else {
			if (datea % 400 == 0) {
				return true;
		    } else {
				return false;
		    }    
		}
	}
	
	return false;
} // checkleapyear

////////////////////////////////////////////////////////////////////////////////
// for digit count
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
function digit_counter (word_id, label_id, isbn_word, digit_class) 
// check the word is ISBN or keyword
{
	var o_input = document.getElementById(word_id);
	var o_label = document.getElementById(label_id);
	
	var status = o_label.className;
    var pattern = /no_count/;
 
   	// if (status == 'invisible no_count' || status == 'digit_count invisible no_count' ||
	//     status == 'instruction invisible no_count') {
	if (status.match(pattern)) {  	
		return;	
	}

	var phase_1 = extractString(o_input.value, new Array('-', ' '), false);
	
	var isbn_pattern    = new RegExp("^\\d\\d\\d\\d\\d\\d.*$", 'i');
	var barcode_pattern = new RegExp("^(978)\\d\\d\\d.*$", 'i');
	var max_length;

	if (phase_1.length > 10) {
		var input = extractString(phase_1, new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'x', 'X'), true);
		
		if (input.length < 10) {
		    max_length = 10;
		} else {
			max_length = 13;
		}
	} else if (barcode_pattern.test(phase_1)) {
	    max_length = 13;
	} else if (isbn_pattern.test(phase_1)) {
		max_length = 10;
	}
	
	if (!o_input && !document.getElementById) {
		return;
	}

	var isbn_new_word = '';

	if (!o_label.saveSearchWordLabel) {
		o_label.saveSearchWordLabel = o_label.innerHTML;
	}
	
	if (!o_input.saveMaxLength && o_input.maxLength) {
		o_input.saveMaxLength = o_input.maxLength;
	}
	
	if (o_input.maxLength) {
		o_input.maxLength = o_input.saveMaxLength;
	}

	if (!(isbn_pattern.test(phase_1)) && !(barcode_pattern.test(phase_1))) {
		// Can't pass threshold	
		if (o_label.innerHTML != o_label.saveSearchWordLabel) {
			o_label.innerHTML = '';
			o_label.innerHTML = o_label.saveSearchWordLabel;
		}	

		if (digit_class) {
		    o_label.className = digit_class + ' invisible';
		} else {
			o_label.className = 'invisible';
		}

		o_label.innerHTML = 'no digit count';
	} else {
		// pass threshold
		if (max_length == 13) {
			var phase_2 = extractString(phase_1, new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), true);
		} else {
			var phase_2 = extractString(phase_1, new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'x', 'X'), true);
		}

		var digit_count = phase_2.length;

		if (digit_class) {
		    o_label.className = digit_class;
		} else {
			o_label.className = 'digit';
		}
		
		if (digit_count < max_length) { 	
			isbn_new_word = isbn_word.replace(/@/i, '<span style="background-color: yellow;">'+digit_count+'</span>/'+max_length);
		} else if (digit_count == max_length) {
			isbn_new_word = isbn_word.replace(/@/i, '<b>'+max_length+'</b>/'+max_length);
			
			if (o_input.maxLength) {
				o_input.maxLength = o_input.value.length;
			}
		} else { // digit_count > max_length - prevent digit overflow error
			if (digit_class) {
				o_label.className = digit_class + ' hide';
		    	// o_label.className = digit_class + ' invisible';
			} else {
				o_label.className = 'hide';
				// o_label.className = 'invisible';
			}
			
		    isbn_new_word = isbn_word.replace(/@/i, '');
		}
			
		if (o_label.innerHTML != isbn_new_word) {
			o_label.innerHTML = isbn_new_word;
		} 		
	}
	
	return;
} // digit_counter

////////////////////////////////////////////////////////////////////////////////
function product_type_other_control (total_product)
// control show/hide of the submit button
{
	var button = document.getElementById('submit_product');
	var total = 0;
	
	for (var i = 1; i <= total_product; i++) {
	     var prod = document.getElementById('product_'+i);
	     
	     if (prod.checked == true) {
	     	 total = 1;
	     	 break;
	     }
	}
	
	if (total == 0) {
		button.className = 'hide';
	} else {
		button.className = 'button';
	}
	
	return;
} // product_type_other_control

////////////////////////////////////////////////////////////////////////////////
function word_count (text_id, span_id, limit, start_display)
// textarea word count
{
 	var text = document.getElementById(text_id);
	var span = document.getElementById(span_id);
 	
	var text_length = text.value.length;
	
	if (text_length >= start_display) {
		text.value = text.value.substring(0, limit);
	}
	
	text_length = text.value.length;
	
    if (text_length >= start_display) {
	    span.innerHTML = text_length+' / '+limit+' characters'; 
    } else {
    	span.innerHTML = '';
    }
    
 	return;
} // word_count

////////////////////////////////////////////////////////////////////////////////
function blind_up_down_control (div_id, ul_id, s, show_all, show_less, see_more)
// expanded/contracted div class when onclick
{
	var div        = document.getElementById(div_id);
	var ul         = document.getElementById(ul_id);
	var s_expand   = document.getElementById(s+'_expand');
	var s_contract = document.getElementById(s+'_contract');
	var all        = document.getElementById(show_all);
	var less       = document.getElementById(show_less);
	var more       = document.getElementById(see_more);
	
	if (div.className == 'blind_expanded') {
		div.className = 'blind_contracted';

		s_expand.className   = 'key_link to_expand';
		s_contract.className = 'hide';
	
		if (ul_id == 'listing_author_wrap_ul' || ul_id == 'listing_tags_wrap_ul') {
			change_id(ul_id, 'hide');
		} else {
			Effect.BlindUp(ul);
		}
		
		if (all && less && more) {
		    all.className  = 'show_all';
		    less.className = 'hide';
		    more.className = 'hide';
		}
	
		if (s != '') {
			change_session_value(s, -1);
		}
	} else {
		div.className = 'blind_expanded';

		s_expand.className   = 'hide';
		s_contract.className = 'key_link to_contact';
	
		if (ul_id == 'listing_author_wrap_ul' || ul_id == 'listing_tags_wrap_ul') {
			change_id(ul_id, '');
		} else {
			Effect.BlindDown(ul);
		}
		
		if (s != '') {
			change_session_value(s, 1);
		}
	}
	
  	return;
} // blind_up_down_control