// Generally useful functions that can be shared

// the occaisonal global variable is sometimes easiest...
var cw_global_msg;

// iterate through the radio group and return false if there is no selection, true if there is one
function radio_button_selected_checker(radio_group) {
	// set var radio_choice to false
	var radio_choice = false;

	for (counter = 0; counter < radio_group.length; counter++) {
		if (radio_group[counter].checked)
			radio_choice = true; 
	}
	return radio_choice;
}

// iterate through the radio group and set the radio value matching the arg to checked
function radio_button_selector(radio_group, val) {

	for (counter = 0; counter < radio_group.length; counter++) {
		if (radio_group[counter].value == val)
			radio_group[counter].checked = true; 
	}
}

// remove all child nodes from the element passed
function remove_any_child_nodes(parent) {
	// remove any children
	while(parent.hasChildNodes()) {
		parent.removeChild(parent.firstChild);
	}
}

// check if the element value property is not empty
function is_blank(elem) {	
	return is_blank_string(elem.value);
}

// check a string
function is_blank_string(str) {
	if (str == null || str == "") return true;
	return false;
}

// convenience method passing an "is logically completed" param (which could be an unselected radio set or an
// empty text input field). This decision is made outside this method. The message to be shown and the
// span element for the message are also passed.
function set_message_display(is_completed, msg, elem) {
	// remove any child nodes (i.e. existing messages) from the span element
	remove_any_child_nodes(elem);
	if (!is_completed) {
		var node = document.createTextNode(msg);
		elem.appendChild(node);
	}
}

// get the selection from the select node passed
function get_selection(list) {
	for (i = 0; i < list.options.length; ++i) {
		if (list.options[i].selected == true) {
			return list.options[i].value;
		}
	}
}

// populate the list with the array. Remove any child nodes first.
function populate_list(list, arr) {
	list.options.length = 0;

	for (var i = 0; i < arr.length; ++i) {
		list.options.add(new Option(arr[i], arr[i]));
	}
}

// check the passed mobile number conforms to our expectations
// use the global_msg variable to hand back specific errors
function check_mobile_number_format(num) {
	// 07952880762 is the number George gave me as the base. So, all numbers must:
	// - start with 07
	// - be eleven digits long
	// - only be numbers (i.e. no alpha)
	var str = new String(num);
	if (check_numbers_only(num) == false) {
		return false;
	}

	// msgs just make more sense being checked in this order. To me, anyway....
	if (str.length > 1) {
		if (str.charAt(0) != '0' || str.charAt(1) != '7') {
			cw_global_msg = "** Number must start with 07";
			return false;
		}
	}

	if (str.length != 11) {
		cw_global_msg = "** Number must be eleven digits long";
		return false;
	}

	return true;
}

// check the variable contains only numbers
function check_numbers_only(num) {
	var str = new String(num);
	var digits = new String("0123456789");
	global_msg = "";

	for (var i = 0; i < str.length; ++i) {
		if (digits.indexOf(str.charAt(i)) < 0) {
			cw_global_msg = "** Must contain numbers only";
			return false;
		}
	}
	return true;
}

// check password is a minmum length of 6 and contains alpha and numeric characters
function validate_password(val) {
	var alpha = new String("abcdefghijklmnopqrstuvwxyz");
	var digits = new String("0123456789");
	var str = new String(val).toLowerCase();

	// minimum legth of 6
	if (str.length < 6) {
		cw_global_msg = "** Password must be at least 6 chars long";
		return false;
	}

	var hasChar = false;
	var hasNum = false;
	for (var i = 0; i < str.length; ++i) {
		if (alpha.indexOf(str.charAt(i)) >= 0) {
			hasChar = true;
		}
		else if (digits.indexOf(str.charAt(i)) >= 0) {
			hasNum = true;
		}
		else {
			cw_global_msg = "** Only use characters (a-z) or numbers(0-9) for password";
			return false;
		}
	}

	if (!hasChar || !hasNum) {
		cw_global_msg = "** Must use characters (a-z) AND numbers (0-9) for password";
		return false;
	}

	return true;
}

// validate postcode format
function validate_postcode(test) {
	var size = test.length
 	test = test.toUpperCase(); //Change to uppercase
 	while (test.slice(0,1) == " ") { //Strip leading spaces
		test = test.substr(1,size-1);size = test.length
  	}
 	while(test.slice(size-1,size)== " "){ //Strip trailing spaces
		test = test.substr(0,size-1);size = test.length
  	}
 	if (size < 6 || size > 8){ //Code length rule
  		cw_global_msg = "** Not a valid postcode - wrong length";
  		return false;
  	}
 	if (!(isNaN(test.charAt(0)))){ //leftmost character must be alpha character rule
   		cw_global_msg = "** Not a valid postcode - cannot start with a number";
   		return false;
  	}
 	if (isNaN(test.charAt(size-3))){ //first character of inward code must be numeric rule
   		cw_global_msg = "** Not a valid postcode - alpha character in wrong position";
   		return false;
  	}
 	if (!(isNaN(test.charAt(size-2)))){ //second character of inward code must be alpha rule
   		cw_global_msg = "** Not a valid postcode - number in wrong position";
   		return false;
  	}
 	if (!(isNaN(test.charAt(size-1)))){ //third character of inward code must be alpha rule
   		cw_global_msg = "** Not a valid postcode - number in wrong position";
   		return false;
  	}
 	if (!(test.charAt(size-4) == " ")){//space in position length-3 rule
   		cw_global_msg = "** Not a valid postcode - no space or space in wrong position";
   		return false;
   	}
 	count1 = test.indexOf(" ");
	count2 = test.lastIndexOf(" ");
 	if (count1 != count2){//only one space rule
   		cw_global_msg = "** Not a valid postcode - only one space allowed";
   		return false;
  	}
	return true;
}

// check upload file has an accepted image extension
function check_legal_image_extension(val) {
	var filename = new String(val);
	var idx = filename.lastIndexOf(".");
	if (idx > filename.length - 3) return false;
	var ext = filename.substr(idx + 1);
	switch (ext.toUpperCase()) {
		case 'GIF':
		case 'JPG':
		case 'JPEG':
		case 'PNG':
		case 'BMP':
		case 'AVI':
		case 'MPG':
		case 'MP4':
		case 'WMV':
		case '3GP':
			return true;
	}
	return false;
}
function replace_quote_escapes(str) {
	// should not be using this. Use html_special_chars_decode() instead.
	var dq = new RegExp('&#34;', 'g');
	var sq = new RegExp('&#39;', 'g');
	str = str.replace(dq, '"');
	str = str.replace(sq, "'");
	return str;
}

// trying to handle quotes that may be in the DB
function html_special_chars_decode(str) {
	str = str.replace(new RegExp('&#34;', 'g'), '"');
	str = str.replace(new RegExp('&#39;', 'g'), "'");
	str = str.replace(new RegExp('&#039;', 'g'), "'");
	str = str.replace(new RegExp('&quot;', 'gi'), '"');
	str = str.replace(new RegExp('&lt;', 'gi'), '<');
	str = str.replace(new RegExp('&gt;', 'gi'), '>');
	str = str.replace(new RegExp('&amp;', 'gi'), '&');
	return str;
}

// step 1 for dynamic select loading
function set_select_loading(select_elem) {
	select_elem.options.length = 0;
	select_elem.options.add(new Option('Loading....', '-1'));
}

/*
newer convenience method passing an "is logically completed" param (which could be an unselected radio set or an
empty text input field). This decision is made outside this method. Parms passed:

- toggle (to show or to hide)
- the message
- the span id to place the message in
- the form element id that we're going to change the background color of
*/
function set_message_display_v2(is_completed, msg, elem_msg, elem_td_id) {
	// remove any child nodes (i.e. existing messages) from the span element
	remove_any_child_nodes(elem_msg);
	if (!is_completed) {
		var node = document.createTextNode(msg);
		elem_msg.appendChild(node);
		elem_td_id.className='cw_form_error';
	}
	else {
		//elem_msg.innerHTML = '&nbsp;';
		elem_td_id.className='cw_copy';
	}
}

/*
	Set the selected option of the passed in select element to the option matching the passed in value
*/
function set_select_with_correct_option(elem, val) {
	for (var i = 0; i < elem.options.length; ++i) {
		if (elem.options[i].value == val) {
			elem.options[i].selected=true;
			break;
		}
	}
}
/*
Called on scheme selection. Generates an ajax call returning business data for the scheme
*/
function scheme_select() {
	$('bus_address').innerHTML = '';
	var url = '/userarea/ajax_functions.php';
	var pars = 'func=<?php echo AJAX_GET_BUSINESS_NAMES_IN_SCHEME; ?>&<?php echo REQ_SCHEME_CODE; ?>=' + $F('scheme');
	var myAjax = new Ajax.Request(
									url, 
									{
										method: 'get', 
										parameters: pars, 
										onComplete: scheme_select_cb
									});
}
/*
Update the business select with values for the selected scheme returned by the ajax call
*/
function scheme_select_cb(originalRequest) {
	var bs = eval("(" + originalRequest.responseText + ")");
	$('business').options.length = 0;
	for (var i = 0; i < bs.businesses.length; ++i) {
		$('business').options.add(new Option(html_special_chars_decode(bs.businesses[i].name), bs.businesses[i].id));
	}
	// go back & get display the address details too
	business_select();
}
/*
Called on business selection. Gets more details about this business through an ajax call
*/
function business_select() {
// override the ajax stuff for the moment
	var url = '/userarea/ajax_functions.php';
	var pars = 'func=<?php echo AJAX_GET_BUSINESS_DETAILS; ?>&<?php echo REQ_BUS_ID; ?>=' + $F('business');
	var myAjax = new Ajax.Request(
									url, 
									{
										method: 'get', 
										parameters: pars, 
										onComplete: business_select_cb
									});
}
/*
Update the business address div with the ajax values
*/
function business_select_cb(originalRequest) {
	var bs = eval("(" + originalRequest.responseText + ")");
	var txt = '';
	if (bs.establishment_name.length > 0) txt += bs.establishment_name + '<br />';
	if (bs.address_line_1.length > 0) txt += bs.address_line_1 + '<br />';
	if (bs.address_line_2.length > 0) txt += bs.address_line_2;
	$('bus_address').innerHTML = txt;

	if ($('page_mode').value == 'update') {
		// we need to get the mobile details too
		var url = '/userarea/ajax_functions.php';
		var pars = 'func=<?php echo AJAX_GET_MOBILES_AT_BUSINESS; ?>&<?php echo REQ_BUS_ID; ?>=' + $F('business');
		var myAjax = new Ajax.Request(
									url, 
									{
										method: 'get', 
										parameters: pars, 
										onComplete: mobiles_at_business_cb
									});
	}
}