/*
	This file contains any validation and menu choosing functions necessary for the operation of the 2ergo system
	Copyright 2004 2ergo - www.2ergo.com
	Version 1.00 25/03/04
	Author: Ian Winstanley
*/


/*
	Populates each option list based on
	1. The select object
	2. The value of the parent select that has been selected
	3. The array that pertains to the select or the next child
	4. Which indexes in the array above to use - ensures that options can be related without children in between having a relationship
	5. Even if the index does not match with the selected value if sellAll is called all options will be displayed
	6. Deselect the checkbox if set
	((i > 0 && arrayOb[i][valueIndex] != arrayOb[(i-1)][valueIndex]) || i == 0) && IGW 11 11 05 may need reinserting at line 32 after first (
*/
function populateSelect (chann, channValue ,arrayOb, valueIndex, textIndex, arrayIndex, sellAll, deselectsellAll, inverse) {
	if (sellAll && deselectsellAll) { // If we are not submitting via the checkbox
		sellAll.checked = false;
	}

	if (arrayOb.length > 0) {
		j = 1;
		var arr = 0;
		if (chann) {
			with (chann) {
				length = 1;
				for (var i in arrayOb) {

					if (((sellAll && sellAll.checked) || (inverse ? arrayOb[i][arrayIndex] != channValue.value : arrayOb[i][arrayIndex] == channValue.value) || channValue.value == '')) {
						length = j+1;
						options[j].value = arrayOb[i][valueIndex];
						options[j].text = arrayOb[i][textIndex];
						j++;
					}
				}
			}
		}
	}
}

/*	
	Selects the correct item in the drop down based on the value of another drop down
*/
//selectVals(this.form, this.form.inbound_number, this.value, keywords, 0, 1)
var arrayRemoved = new Array();
arrayRemoved[0] = new Array(2);
arrayRemoved[0]['value'] = '';
arrayRemoved[0]['text'] = '';
function selectVals(frm, fld, fldValue, fldArray, arrayIndex, valueIndex, inverse) {

	var numNumsAttached = 0;
	if (arrayRemoved[0]['text'] != '') {
		fld.length = arrayRemoved.length;
		for (var i in arrayRemoved	) {
			fld.options[i].value = arrayRemoved[i]['value'];
			fld.options[i].text = arrayRemoved[i]['text'];
		}
	}

	if (arrayRemoved[0]['text'] == '') {	
		for (j = 0; j < fld.length; j++) {
			arrayRemoved[j] = new Array(2);
			arrayRemoved[j]['value'] = fld.options[j].value;
			arrayRemoved[j]['text'] = fld.options[j].text;
		}
	}

	for (i = 0; i < fldArray.length; i++) {
		if (fldArray[i][arrayIndex] == fldValue) {
			var k = 0;
			for (j = 0; j < fld.length; j++) {
				if (inverse) {
					if (fld[j].value == fldArray[i][valueIndex]) {
						fld.options[k].value = fld.options[j].value;
						fld.options[k].text = fld.options[j].text;
						k++;
						fld.options.length = k;
					}				
				} else {
					if (fld[j].value == fldArray[i][valueIndex]) {
						var selectedIndex = j;
						numNumsAttached++;
					}
				}
			}
		}
	}

	if (numNumsAttached == 1) {
		fld.selectedIndex = selectedIndex;
	}
}

// Strips out non number characters
function checkForTelephone(fld) {
	var invalid = false, string = fld.value;
	//Stripping out any invalid characters.
	for (var i=0, output='', valid="0123456789"; i<string.length; i++) {
		if (valid.indexOf(string.charAt(i)) != -1) {
			output += string.charAt(i);
		} else if (string.charAt(i) != ' ') {
			invalid = true;
		}
	}
	fld.value = output
	if (invalid == true) {
		return false;
	} else {
		return true;
	}
}

// Checks the email address
function checkForEmail(fld) {
	
	if (fld.value.search(/^([-a-zA-Z0-9_.]+)@(([-a-zA-Z0-9_]+[.])+[a-zA-Z]+)(;([-a-zA-Z0-9_.]+)@(([-a-zA-Z0-9_]+[.])+[a-zA-Z]+))*$/) == -1) {
		return false;
	} else {
		return true;
	}
}

function personal_details(frm) {
	var Msg = '';
	
	if (frm['account_result[acc_name]'] || frm.insert.value == 'insert') {
		if (frm['account_result[acc_name]'].value == '') {
			Msg += 'Please enter a username\n\n';
		} else if (!checkuser()) {
			Msg += 'The username "' + frm['account_result[acc_name]'].value + '" is already allocated\n\n';
		}
	}

	if (frm['account_result[password]']) {
		if (frm['account_result[password]'].value.length > 0 || frm.insert_mode.value == 'insert') {
			if (frm['account_result[password]'].value.length < 3) {
				Msg += 'Please enter a password of at least 3 characters in length\n';
			}
			if (frm['confirm_password'].value.length < 3) {
				Msg += 'Please enter a confirmation password of at least 3 characters in length\n';
			} else if (frm['confirm_password'].value != frm['account_result[password]'].value) {
				Msg += 'Your password and confirmation password must match\n';
			}
		}
	}
	if (frm['account_result[contact_name]'].value == '') {
		Msg += 'Please enter your name\n';
	} else if (frm['account_result[contact_name]'].value.search(/[^a-zA-Z0-9-' ]+/) > 0) {
		Msg += 'Please enter only letters, space, commas or dashes for your name\n';
	}
	if (frm['account_result[company_add]'].value == '') {
		Msg += 'Please enter your address\n';
	}

	if (frm['account_result[contact_email]'].value == '') {
		Msg += 'Please enter your email address\n';
	} else if (!checkForEmail(frm['account_result[contact_email]'])) {
		Msg += 'Please enter a valid email address\n';
	}

	if (frm['account_result[contact_phone]'].value == '') {
		Msg += 'Please enter your telephone number\n';
	} else if (!checkForTelephone(frm['account_result[contact_phone]'])) {
		Msg += 'Please a valid UK telephone number including the area dialling code\n';
	}
	return Msg;
}

function company_details(frm) {
	var Msg = '';

	if (frm['account_result[company_name]'].value == '') {
		Msg += 'Please enter the company name\n';
	}
	if (frm['account_result[company_reg_add]'].value == '') {
		Msg += 'Please enter the registered address\n';
	}
	if (frm['account_result[company_num]'].value == '') {
		Msg += 'Please enter the company number\n';
	}
	if (frm['account_result[tech_contact_name]'].value == '') {
		Msg += 'Please enter the technical contact name\n';
	}
	if (frm['account_result[tech_contact_mobile]'].value == '') {
		Msg += 'Please enter the technical contact mobile number\n';
	}
	if (frm['account_result[tech_contact_phone]'].value == '') {
		Msg += 'Please enter the technical contact telephone number\n';
	}
	if (frm['account_result[tech_contact_email]'].value == '') {
		Msg += 'Please enter the technical contact email\n';
	} else if (!checkForEmail(frm['account_result[tech_contact_email]'])) {
		Msg += 'Please enter a valid technical contact email address\n';
	}
	if (frm['account_result[svc_stop_email]'].value == '') {
		Msg += 'Please enter the service removal email\n';
	} else if (!checkForEmail(frm['account_result[svc_stop_email]'])) {
		Msg += 'Please enter a valid service removal email address\n';
	}
	return Msg;
}

/* Checks that the values within the contact form are suitable for submission */
function checkAccountDetails(frm) {
	Msg = '';
	serviceMsg = '';
	var personalDisplayed = false;
	
	// Check each tab in turn
	Msg += personal_details(frm);
	if (Msg) {
		displayLayers('personal_details', 'personal_detailsLink');
		if (frm.insert_mode.value == 'insert') {
			personalDisplayed = true;
		}
	}

	if (frm['account_result[password]']) {
		Msg += company_details(frm);
		if (Msg && personalDisplayed == false) {
			displayLayers('company_details', 'company_detailsLink');
		}
	}

	if (frm['account_result[default_mo_url]']) {
		if (frm['account_result[default_mo_url]'].value != '') {
			if (frm['account_result[default_mo_url]'].value.search(/http:\/\/[-a-zA-Z0-9_.]+\.[-a-zA-Z0-9_.]+/) == -1) {
				Msg += 'Please enter the Default Mobile Originated URL in the form http://www.domain.com';
			}
		}
	}

	if (frm['account_result[default_dr_url]']) {
		if (frm['account_result[default_dr_url]'].value != '') {
			if (frm['account_result[default_dr_url]'].value.search(/http:\/\/[-a-zA-Z0-9_.]+\.[-a-zA-Z0-9_.]+/) == -1) {
				Msg += 'Please enter the Default Deliver Report URL in the form http://www.domain.com';
			}
		}
	}

	var alertString = 'You will be amending your account details as follows\n' + 
		'Personal Details\n';
	if (frm['account_result[password]']) {
		alertString += 'Username: ' + frm['account_result[acc_name]'].value + '\n';
		'Password: ' + frm['account_result[password]'].value + '\n';
	}
		alertString += 'Name: ' + frm['account_result[contact_name]'].value + '\n' + 
		'Address: ' + frm['account_result[company_add]'].value + '\n' + 
		'Contact Email: ' + frm['account_result[contact_email]'].value + '\n' + 
		'Telephone Number: ' + frm['account_result[contact_phone]'].value + '\n';
		if (frm['account_result[tech_contact_mobile]']) {
			alertString += 'Mobile Number: ' + frm['account_result[tech_contact_mobile]'].value + '\n';
		}
	if (frm['account_result[password]']) {
		alertString += '\nCompany Details\n' + 
			'Password: ' + frm['account_result[password]'].value + '\n' + 
			'Company Name: ' + frm['account_result[company_name]'].value + '\n' + 
			'Registered Address: ' + frm['account_result[company_reg_add]'].value + '\n' + 
			'Company Number: ' + frm['account_result[company_num]'].value + '\n' + 
			'Technical Contact Name: ' + frm['account_result[tech_contact_name]'].value + '\n' + 
			'Technical Mobile Number: ' + frm['account_result[tech_contact_mobile]'].value + '\n' +
			'Technical Telephone Number: ' + frm['account_result[tech_contact_phone]'].value + '\n' + 
			'Technical Contact Email: ' + frm['account_result[tech_contact_email]'].value + '\n' +
			'Service removal Email: ' + frm['account_result[svc_stop_email]'].value + '\n' +
			'\nServices Available\n'; 

		/*
		if (frm['service_result[express_notification]'][0].checked == true) {
			alertString += 'Express Notification enabled\n';
		}
		*/
		if (frm['service_result[premium_injection]'][0].checked == true) {
			alertString += 'Premium Injection Service enabled\n';
		}
		if (frm['service_result[location_based]'][0].checked == true) {
			alertString += 'Location Based Service enabled\n';
		}
		if (frm['service_result[multimedia]'][0].checked == true) {
			alertString += 'Multimedia Service enabled\n';
		}
		if (frm['service_result[wap_push]'][0].checked == true) {
			alertString += 'Wap Push Service enabled\n';
		}
		alertString += 'Reverse Bill Service enabled\n';
		if (frm['service_result[subscription]'][0].checked == true) {
			alertString += 'Subscription Engine Service enabled\n';
		}
		if (frm['service_result[autoresponder]'][0].checked == true) {
			alertString += 'Autoresponder Service enabled\n';
		}
		if (frm['service_result[voice]'][0].checked == true) {
			alertString += 'Voice Service enabled\n';
		}

		alertString += '\nMiscellaneous\n' + 
			'Staff member allocated: ' + frm['account_result[acc_mgr_id]'].options[frm['account_result[acc_mgr_id]'].selectedIndex].text + '\n';
		/*
		if (frm['account_result[delivery_reports_enabled]'][0].checked == true) {
			alertString += 'Delivery Reports enabled\n';
		}
		*/

		// Now check for the existence of services and whether one has been setup if the box has been checked
		if (frm['service_result[premium_injection]'][0].checked == true && premium_injection_service_enabled == false) {
			serviceMsg += 'You have enabled the Premium Injection Service by checking the box however you have not yet created the service.\n' +
								'You now need to either:\n' +
								'    a) Uncheck the Premium Injection Service checkbox\n' +
								'    b) Uncheck and then check the Premium Injection Service checkbox again. Next enter values for the service and\n' +
								'        ensure that it is submitted\n\n';		
		}
		if (frm['service_result[location_based]'][0].checked == true && location_based_service_enabled == false) {
			serviceMsg += 'You have enabled the Location Based Service by checking the box however you have not yet created the service.\n' +
								'You now need to either:\n' +
								'    a) Uncheck the Location Based Service checkbox\n' +
								'    b) Uncheck and then check the Location Based Service checkbox again. Next enter values for the service and\n' +
								'        ensure that the form is submitted\n\n';		
		}
		if (frm['service_result[multimedia]'][0].checked == true && multimedia_service_enabled == false) {
			serviceMsg += 'You have enabled the Multimedia Service by checking the box however you have not yet created the service.\n' +
								'You now need to either:\n' +
								'    a) Uncheck the Multimedia Messaging checkbox\n' +
								'    b) Uncheck and then check the Multimedia Messaging checkbox again. Next enter values for the service and\n' +
								'        ensure that the form is submitted\n\n';		
		}
		if (frm['service_result[wap_push]'][0].checked == true && wap_push_service_enabled == false) {
			serviceMsg += 'You have enabled Wap Push Service by checking the box however you have not yet created the service.\n' +
								'You now need to either:\n' +
								'    a) Uncheck the Wap Push Service checkbox\n' +
								'    b) Uncheck and then check the Wap Push Service checkbox again. Next enter values for the service and\n' +
								'        ensure that the form is submitted\n\n';		
		}
		if (frm['service_result[subscription]'][0].checked == true && subscription_engine_service_enabled == false) {
			serviceMsg += 'You have enabled the Subscription Engine Service by checking the box however you have not yet created a subscription.\n' +
								'You now need to either:\n' +
								'    a) Uncheck the Subscription Engine Service checkbox\n' +
								'    b) Uncheck and then check the Subscription Engine Service checkbox again. Next set up a subscription and\n' +
								'        ensure that you enter a valid subscription in the subscription box.\nEnsure that the form is submitted\n\n';		
		}
		if (frm['service_result[autoresponder]'][0].checked == true && autoresponder_service_enabled == false) {
			serviceMsg += 'You have enabled the Autoresponder Service by checking the box however you have not yet created an autoresponder.\n' +
								'You now need to either:\n' +
								'    a) Uncheck the Autoresponder Service checkbox\n' +
								'    b) Uncheck and then check the Autoresponder Service checkbox again. Next set up an autoresponder and\n' +
								'        ensure that the form is submitted\n\n';		
		}

	}
	if (serviceMsg) {
		alert(serviceMsg);
		return false;
	} else if (Msg) {
		alert(Msg);
		return false;
	} else if (confirm(alertString)) {
		return true;
	} else {
		return false;
	}
}

function confirmDeleteAccount(frm) {
	if (confirm('Are you sure that you want to disable this account?')) {
		frm.mode.value = 'disable_account_details';
		frm.submit();
	}
}

function confirmDeleteStaffAccount(frm) {
	if (confirm('Are you sure that you want to disable this account?')) {
		frm.mode.value = 'disable_staff_account_details';
		frm.submit();
	}
}

// Confirm that the user wants to delete the records
function checkDelete(frm, elem, multi) {
	var j = 0, shortened = subscriptionMessage = Msg = '';
	if (frm.mode.value == 'unsubscribe_subscription_service' || frm.mode.value == 'delete_autoresponders' || frm.mode.value == 'delete_media_sender_messages' || frm.mode.value == 'delete_keywords' || frm.sub_mode.value == 'delete_scheduled_send'  || frm.mode.value == 'wizard') {
		if (multi) { // If the values are coming from a textarea and are delimited by linkbreaks
			if (elem.value != '') {
				var origLength = elem.value.length;
				elem.value = elem.value.replace(/[^0-9\r\n]/gi, '');
				var unsubscribeArray = elem.value.split(/[\r\n]/); // Split on newlines
				j = unsubscribeArray.length;
				var newFormValue = ''

				for (var i in unsubscribeArray) {
					unsubscribeArray[i] = unsubscribeArray[i].replace(/^00(.*)/, '$1');
					unsubscribeArray[i] = unsubscribeArray[i].replace(/^0(.*)/, '44$1');
					if (unsubscribeArray[i].length < 9) {
						Msg += 'The number ' + unsubscribeArray[i] + ' is too short\n';
					} else if (unsubscribeArray[i].length > 14) {
						Msg += 'The number ' + unsubscribeArray[i] + ' is too long\n';
					}
					newFormValue += unsubscribeArray[i] + '\r\n';
				}
				elem.value = newFormValue;

				if (elem.value.length < origLength) {
					shortened = '\nInvalid characters have also been removed from the list of numbers.\nYou may wish to cancel this dialogue and review the list.';
				}
				if (frm.subscription.value) {
					var subscriptionSelectedIndex = frm.subscription.selectedIndex;
					var subscriptionName = frm.subscription.options[subscriptionSelectedIndex].text;

					subscriptionMessage = '\nYou will be unsubscribing customers from the ' + subscriptionName + ' list only';
				}
			}
		} else {
			if (elem) {
				j++;
			} else {
				for (var i = 0; i < frm.elements.length; i++) {
					if (frm.elements[i].type == 'checkbox' && frm.elements[i].checked == true) {
					  j++;
					}
				}
			}
		}

		var plur;
		if (j > 1) {
		  var plur = 's';
		  var thisPlur = 'these';
		} else if (j == 0) {
			Msg += 'You must either check at least one checkbox or paste in a list of values';
			return false;
		} else {
		  var plur = '';
		  var thisPlur = 'this';
		}
		if (Msg) {
			alert(Msg);
			return false;
		}

		if (frm.mode.value == 'unsubscribe_subscription_service') {
			chosenService = ' customer';
		} else if (frm.mode.value == 'delete_keywords') {
			chosenService = ' keyword';
		} else if (frm.mode.value == 'wizard') {
			chosenService = ' saved search';
		} else if (frm.mode.value == 'edit_premium_injection_service') {
			chosenService = ' scheduled premium message';
		} else if (frm.mode.value == 'delete_media_sender_messages') {
			chosenService = ' media sender message';
		} else {
			chosenService = ' autoresponder';
		}
		if (!confirm('Are you sure you want to ' + (frm.mode.value == 'unsubscribe_subscription_service' ? 'unsubscribe ' : 'remove ') + 
			thisPlur + ' ' + j + chosenService + plur + '?' + subscriptionMessage + shortened)) {
			return false;
		} else {
			return true;
		}
	}
}

// Pops up a confirm dialog asking the user whether they are sure that they want to update the specified text field
function confirmAutoResponseUpdate(frm, mainMsg) {
	var Msg = secondaryMsg = '', plur = 0;
	if(frm['schedule'] && frm['schedule'].value == 'MediaSender2') {
		if (frm['product_code_location'] && frm['subject_title']) {
			var product_code_location = frm['product_code_location'].value;
			var subject_title = frm['subject_title'].value;
			if(subject_title == '' || product_code_location == '' || isNaN(product_code_location)) {
				Msg += 'When selecting MediaSender2 you must enter a subject\n';
				Msg += 'And the product code must be numeric';
			}
		}
	}
	if (mainMsg.value.length > 160) {
		Msg += 'You have exceeded the 160 character maximum number of characters allowed for your primary autoresponder\n';
		plur++;
	} 

	finalMsg = 'Are you sure you want ' + frm.insert_mode.value + ' the auto_response message with this text?\n"' + mainMsg.value + '"\n\n';
	if (frm.chargeable) {
		if (frm.inbound_number) {
			if (frm.inbound_number.value.length == 0) {
				secondaryMsg += 'Please select an inbound number\n';
			}
			finalMsg += 'Inbound number: ' + frm.inbound_number.value + '\n';
		}
		if (frm.keyword.value.length == 0) {
			secondaryMsg += 'Please select a keyword\n';
		}
		if (frm.message_type) {
			finalMsg += 'Message Type: ' + frm.message_type.value + '\n';
		}
		if (frm.schedule) {
			finalMsg += 'Scheduled Event : ' + frm.schedule.value + '\n';
		}
		if (frm.network_name) {
			if (frm.network_name.value != '') {
				finalMsg += 'Network Name : ' + frm.network_name.value + '\n';
			}
		}
		finalMsg += 'Keyword: ' + frm.keyword.value + '\n';
		if (frm.chargeable.checked) {
			finalMsg += 'Chargeable: yes\n';
		} else {
			finalMsg += 'Chargeable: no\n';
		}
	}
	if (frm.originator) {
		if (frm.originator.value == '') {
			Msg += 'Please enter the originator\n';
		} else if (frm.originator.value.match(/[^\d]/) && frm.originator.value.length > 11) { // Now check the length
			Msg += 'The originator must be a maximum of 11 characters\n';
		} else if (frm.originator.value.length > 16) { // Now check the length
			Msg += 'The originator must be a maximum of 16 characters\n';
		}
		finalMsg += 'Originator: ' + frm.originator.value + '\n';
	}
	if (frm.subscription_mandatory) {
		if (frm.subscription_mandatory.value != '') {
			if (frm.subscription.value == '') {
				Msg += 'As you are adding a subscription please enter a subscription in the subscription list box\n';
			}
			finalMsg += 'Subscription: ' + frm.subscription.value + '\n';
		}
	}
	if (frm['auto_response_child_result_message[]']) {
		finalMsg += 'You are also submitting related messages as displayed below\n';
		if (frm['auto_response_child_result_message[]'].length == undefined) {
			var frmArray = new Array(frm['auto_response_child_result_message[]']);
		} else {
			frmArray = frm['auto_response_child_result_message[]'];
		}
		for (i = 0; i < frmArray.length; i++) {
			if (frmArray[i].value.length > 160) {
				Msg += 'You have exceeded the 160 character maximum number of characters allowed for your secondary autoresponder (Message ' + (i+2) + ')\n';
				plur++;
			} else if (frmArray[i].value.length == 0) {
				Msg += 'Please enter some text in the secondary message box (Message. ' + (i+2) + ')\n';
				plur++;
			}
			finalMsg += '"' + frmArray[i].value + '"\n';
		}
		if (frm['child_keyword[]']) {
			for (i = 0; i < frm['child_keyword[]'].length; i++) {
				if (frm['child_keyword[]'][i].value.length < 3) {
					Msg += 'Please enter a keyword for your secondary autoresponder (Message ' + (i+2) + ')\n';
					plur++;
				}
			}
		}
	}

	if (Msg || secondaryMsg) {
		alert(Msg + secondaryMsg);
		return false;
	} else if (confirm(finalMsg)) {
		return true;
	} else {
		return false;
	}
}

// Pops up a confirm dialog asking the user whether they are sure that they want to submit the messages
// Also alerts if certain limits have been reached
function confirmBulkSendToSubscribers(frm) {
	var Msg = '';
	if (frm.subscription.value == '') {
		Msg += 'Please choose an option from the subscription list drop down\n';
	} else if (frm['include[message]'].checked == false && frm['subscription_message[message]'].value == '' && frm['include[ringtone]'].checked == false && frm['subscription_message[ringtone]'].value == '') {
		Msg += 'You must enter either a message or a ringtone in order to schedule the message(s) for this subscription list\n';
	} else {

		if (frm['originator'] && getElementById('originatorRow').style.display != 'none') {
			if (frm['originator'].value == '') {
				Msg += 'When sending a non-chargeable message you must specify an originator.\n';
			}
		}

		if (frm['include[message]'].checked) {
			if (frm['subscription_message[message]'].value == '') {
				Msg += 'You have checked the "include" checkbox confirming that you wish to send a message, however the message box is empty.\n';
				Msg += 'Please enter some text in the message box or uncheck the "include" checkbox\n';
			} else { // Now check the textbox
				if (frm['subscription_message[message]'].value.length > 160) {
					Msg += 'You have exceeded the 160 character maximum number of characters allowed for a text message\n';
					Msg += 'Please remove some text or reformat your message';
				}
			}
		} else if (frm['subscription_message[message]'].value != '') {
			Msg += 'You have entered some text in the message box, however the the "include" checkbox confirming that you wish to send a message has not been checked.\n';
			Msg += 'Please remove the text from the message box or check the "include" checkbox\n';	
		}

		if (frm['include[ringtone]'].checked) {
			if (frm['subscription_message[ringtone]'].value == '') {
				Msg += 'You have checked the "include" checkbox confirming that you wish to send a ringtone, however the ringtone box is empty.\n';
				Msg += 'Please enter some text in the ringtone box or uncheck the "include" checkbox\n';
			} else { // Now check the textbox
				/*
				if (frm['subscription_message[ringtone]'].value.length > 280) {
					Msg += 'You have exceeded the 280 character maximum number of characters allowed for a ringtone\n';
					Msg += 'Please enter a shorter alternative ringtone';
				}
				*/
			}
		} else if (frm['subscription_message[ringtone]'].value != '') {
			Msg += 'You have entered some text in the ringtone box, however the the "include" checkbox confirming that you wish to send a ringtone has not been checked.\n';
			Msg += 'Please remove the text from the ringtone box or check the "include" checkbox\n';	
		}

	}

	if (Msg) { // There is a problem so alert this and halt the form submission
		alert (Msg);
		return false;
	} else if (confirm('Are you sure that you want to schedule this message to be sent to the ' + frm.subscription.value + ' list?\n' + 
			(frm['chargeable[message]'].checked == true ? 'You have also opted to charge for this message' : ''))) {
		return true;
	} else {
		return false;
	}
}

var dayDifference
function setReportingDateRange(frm, noDays) {
  noDays = noDays ? noDays : 7;
  var startdateArray = frm.tempbegdate.value.split('-');
  var startdate = new Date(startdateArray[2],startdateArray[1]-1,startdateArray[0]);
  var enddateArray = frm.tempenddate.value.split('-');
  var enddate = new Date(enddateArray[2],enddateArray[1]-1,enddateArray[0]);
  dayDifference = parseInt((enddate - startdate) / (1000 * 60 * 60 * 24));
  if (dayDifference >= noDays) { // More than noDays days
    return false;
  } else {
    return true;
  }
}

// Check whether the user has entered the date fields correctly when searching for message
function checkMessageDate(frm, doNotChkTel, noDays) {
	modifyPhoneNumber();
	var Msg = '';
	if (frm.tempbegdate.value == '') {
		Msg += 'You must select a start date\n';
	} else if (!frm.tempbegdate.value.match(/^\d{2}-\d{2}-\d{4}$/)) {
		Msg += 'You must enter a start date in the format DD-MM-YYYY\n';
	}
	if (frm.tempenddate.value == '') {
		Msg += 'You must select a start date\n';
	} else if (!frm.tempenddate.value.match(/^\d{2}-\d{2}-\d{4}$/)) {
		Msg += 'You must enter a start date in the format DD-MM-YYYY\n';
	}

	if (frm.telephone && !doNotChkTel) {
		if (frm.telephone.value.length < 9) {
			Msg += 'You must enter a mobile number of at least 9 characters\n';
		}
	}
	
	if (noDays) {
		if (!setReportingDateRange(frm, noDays)) {
			Msg += 'Please select a date range less than or equal to ' + noDays + ' days\nYour current date range spans ' + (dayDifference+1) + ' days.';
		}
	}

	if (Msg) { // There is a problem so alert this and halt the form submission
		alert (Msg);
		return false;
	} else {
		return true;
	}
}

// Alert the user re. conformity
function ringtoneWarning(fld) {
	if (fld.checked) {
		alert('Please check the code that you paste into the box on the right conforms to RTTTL or RTX standards.\n' + 
			'Your code will be checked and if found not to conform to the above standards your messages will not be scheduled.\n' + 
			'If your ringtone exceeds 280 characters it may be split up into 2 or messages, which you will be charged for if you have checked the "Chargeable" checkbox.');
	}
}

// Complete the time and date for subscriptions
function populateSubscriptionDate(fld) {
   var mydate=new Date();
    var minutes=mydate.getMinutes();
    var hours=mydate.getHours();
    var dy=mydate.getDate()
    var month=mydate.getMonth()
    var yr=mydate.getFullYear()
    if (hours<10) {
      hours="0"+hours
    }
    if (minutes<10) {
      minutes="0"+minutes
    }
    if (dy<10) {
      dy="0"+dy
    }
    month++;
    if (month<10) {
      month="0"+month
    }
    if (yr<10) {
      yr="0"+yr
    }
    fld.value = hours + ':' + minutes + ' ' + dy + '-' + month + '-' + yr;
}

// Validates submissions when a Premium Inject schedule is being updated
function checkPremiumBroadcastUpdate() {
	var frm = document.premium_injection;
	var Msg = '';

	if (frm.O.value == '') {
		Msg += 'Please enter the originator\n';
	} else if (frm.O.value.match(/[^\d]/) && frm.O.value.length > 11) { // Now check the length
		Msg += 'The originator must be a maximum of 11 characters\n';
	} else if (frm.O.value.length > 16) { // Now check the length
		Msg += 'The originator must be a maximum of 16 characters\n';
	}

	if (frm.M.value == '') {
		Msg += 'Please enter the Message\n';
	} else if (frm.M.value.length > 160) { // Now check the textbox
		Msg += 'You have exceeded the 160 character maximum number of characters allowed for a text message\n';
		Msg += 'Please remove some text or reformat your message\n';
	}
	
	// Check whether the cron date is at least an hour in the future
	var timeDate = frm.cron_date.value.split(' '); // Split on the space into time and date	
	var hourMinute = timeDate[0].split(':'); // Split on the : into hour and minute
	var dayMonthYear = timeDate[1].split('-'); // Split on the - into day, month and year
	var dateChosen = new Date( dayMonthYear[2], dayMonthYear[1]-1, dayMonthYear[0], hourMinute[0], hourMinute[1], 0);
	var dateFromServer = new Date(frm.year.value, parseInt(frm.month.value)-1, frm.day.value, frm.hours.value, frm.minutes.value, 0);
	if (dateChosen.getTime() < dateFromServer.getTime()) {
		Msg += 'You must choose a date that is at least one hour in the future\n';
	}

	if (Msg) { // There is a problem so alert this and halt the form submission
		alert(Msg);
		return false;
	} else if (confirm('Are you sure you want to update this message to:\nFrom - ' + frm.O.value + '\nMessage - ' + frm.M.value + '\nScheduled time - ' + frm.cron_date.value)) {
		return true;
	} else {
		return false;
	}
}

// Ensure that at least one value is being submitted
function validateSubscriptionSearch(frm) {
	var Msg = '';
	if (frm.subscription.value == '') {
		Msg += 'You must select a name from the subscription list drop down\n';
	}
	if (frm.telephone.value.match(/[^\d]/)) {
		Msg += 'You must enter only digits for the mobile number\n';
	}

	if (Msg) { // There is a problem so alert this and halt the form submission
		alert (Msg);
		return false;
	} else {
		return true;
	}

}

// Alters the submit button value, mode value
function validate(elem, frm, inputType) {
   	if (inputType == 'radio' && elem.checked) {
		frm.mode.value = 'display';
		frm.submitBut.value = 'Edit Selected Value';
		checkRadCheck(frm, 'checkbox')
	} else if (inputType == 'checkbox' && elem.checked) {
		frm.mode.value = 'delete_item';
		frm.submitBut.value = 'Delete Checked Values';
		checkRadCheck(frm, 'radio')
	}
}
// Deselects any opposing form elements
function checkRadCheck(frm, type) {
	for (var i =0; i < frm.elements.length; i++) {
		if (frm.elements[i].type == type) {
		  frm.elements[i].checked = false;
		}
	}
}

// Preload images
var myImages = new Array(); 
function preloadImages(imageName, imagePath) {
	for (var i in imageName) {
		myImages[imageName[i] + '_on'] = new Image();
		myImages[imageName[i] + '_on'].src  = imagePath + imageName[i] + '_on.gif';
		myImages[imageName[i] + '_off'] = new Image();
		myImages[imageName[i] + '_off'].src = imagePath + imageName[i] + '.gif';
	}
}

// Generic /images replace function
function imageChange(imgOb, imgReplace) {
	imgOb.src = myImages[imgReplace].src;
}

// Checks and unchecks multiple like named checkboxes
function checkAll(frm, fld) {
	var chkBoxes = frm.elements[fld];
	chkBoxesDefined = typeof chkBoxes.length;
	if (chkBoxesDefined == 'undefined') {
		if (frm[fld].checked == false) {
			frm[fld].checked = true;
		} else {
			frm[fld].checked = false;
		}
	} else {
		for(var i = 0; i < chkBoxes.length; i++) {
			if (chkBoxes[i].checked == false) {
				chkBoxes[i].checked = true;
			} else {
				chkBoxes[i].checked = false;
			}
		}
	}
}

function findObj(n, d) { //v4.01
  var p,i,x;  
  if(!d) 
  	d=document; 
	if((p=n.indexOf("?"))>0&&parent.frames.length) 
	{
    	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
  	if(!(x=d[n])&&d.all) 
		x=d.all[n]; 
		for (i=0;!x&&i<d.forms.length;i++) 
			x=d.forms[i][n];
  			for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
			x=findObj(n,d.layers[i].document);
  			if(!x && d.getElementById) x=d.getElementById(n); 
			return x;
			//alert(x);
}

function VerifyMobile(txtbox) {
	var txtboxVal1 = txtbox.value;
	var txtboxVal = txtboxVal1.replace(" ","");
	txtbox.value = txtboxVal;

	var firstTwo = new String(txtboxVal.substring(0,2));
	var firstThree = new String(txtboxVal.substring(0,3));
	if(txtboxVal == '') {
		txtbox.focus();
		return 'Please enter all mobile numbers';
	}
	if(isNaN(txtboxVal)) {
		txtbox.focus();
		return 'mobile numbers must be numeric';
	}
	if(firstTwo == '07')	{
		if(txtboxVal.length != 11) {
			txtbox.focus();
			return 'mobile numbers starting 07 must be 11 characters long';
		}
	}
	if(firstThree == '447')	{
		if(txtboxVal.length != 12) {
			return 'mobile numbers starting 447 must be 12 characters long';
			txtbox.focus();
			return false;
		}else {
			return true;
		} 
	}

	return '';
}


function checkMobile_number(frm) {
  if(frm.telephone.value == '') {
    alert('Please enter a mobile number to search for\n');
    return false;
  } else {
    return true;
  }
}


function checkDisplayStaffForm(frm, deleteEntry) {
	var Msg = '';

	if(deleteEntry) { // The user is being deleted
		if(!confirm('do you really want to disable the staff account ' + frm['staff_result[STAFF_NAME]'].value + '?')) {
			return false;
		} else {
			frm.insert_mode.value = 'delete';
			frm.submit();
			return true;
		}
	}

	if (frm['staff_result[STAFF_NAME]'].value == '') {
		Msg += 'Please enter a username\n\n';
	} else if (!checkuser()) {
		Msg += 'The username "' + frm['staff_result[STAFF_NAME]'].value + '" is already allocated either to a member of staff or another account\n';
	}

	if(frm['staff_result[STAFF_PASSWORD]'].value != '') {
		if(frm['staff_result[STAFF_PASSWORD]'].value.length < 3) {
			Msg += 'Please enter a password of at least 3 characters in length\n';
		}
	}

	//check boxes 
	var rolesChecked = false
	for (i = 0; i < document.staff_form.elements.length; i++) {
		if (document.staff_form.elements[i].name && document.staff_form.elements[i].name.match(/roles_results/)) {
			if (document.staff_form.elements[i].checked == true) {
				rolesChecked = true;
			}
		}
	}

	if (rolesChecked == false) {
		Msg += 'Please select at least one role\n';
	}

	if(frm['staff_result[STAFF_FULL_NAME]'].value == '') {
		Msg += 'Please enter a name for the member of staff\n';
	}

	if (frm['staff_result[STAFF_CONTACT_EMAIL]'].value == '') {
		Msg += 'Please enter the contact email address\n';
	} else if (!checkForEmail(frm['staff_result[STAFF_CONTACT_EMAIL]'])) {
		Msg += 'Please enter a valid contact email address\n';
	}

	Msg += VerifyMobile(frm['staff_result[STAFF_CONTACT_MOBILE]']);

	if(Msg) {
		alert(Msg); 
		return false;
	}
	
}


function chooseclient(name,id,number) {
	var currentlocation = new String(window.location);
	var locationArray = currentlocation.split('/');
	var page = locationArray[3].split('?');
	var server = locationArray[0] + "/" +  locationArray[1] + "/" + locationArray[2] + "/" + page[0];
	switch(number)
	{
		case 1:
		var pagelocation = page[0] + "?mode=set_client&client=" + name + "&client_id=" + id;
		document.cookie = "pagelocation=" + currentlocation;
		window.location.href= pagelocation;
		break;
		case 2:
		server += "?mode=display_account_details";
		document.cookie = "pagelocation= " + server ;
		var pagelocation = page[0] + "?mode=set_client&client=" + name + "&client_id=" + id;
		window.location.href = pagelocation;
		break
		case 3:
		server += "?mode=display_keyword_details";
		document.cookie = "pagelocation = " + server;
		var pagelocation = page[0] + "?mode=set_client&client=" + name + "&client_id=" + id;
		window.location.href = pagelocation;
		break
	}
}

function confirmDeleteMTRate(charge, network) {
	if (confirm('Are you sure that you want to delete this charge band?\nCharge: ' + charge + '\nNetwork: ' + network)) {
		window.location.href ='/?mode=delete_diplayratenum&charge=' + charge + '&network_name=' + network;
	}
}
