//Emad Messiha - This file is used to validate Order Form
var mobileRegEx= /^[0-9]{10,11}$/;
var phoneRegex= /^[0-9]{8,11}$/;
var emailRegex = /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|arpa|root|asia|cat|coop|edu|int|pro|tel|travel)$/i;
var emailRegexOther = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var ccExpiryRegex= /^[0-9]{2}$/;
var howManyRegEx= /^[0-9]$/;

//an array of control Id's present in order form
orderFormControls = new Array(
		"time",
		"adults",
		"children",
		"name",
		"mobile",
		"phone",
		"emailInput",
		"pass1",
		"pass2",
		"description1",
		"specials"
	);

creditCardSection = new Array();

function validate(ctrl){
	var totalSeats = jQuery('#totalSeats').val();
	var ctrlName = ctrl.name;
	var errorLabel;
	if(ctrlName == 'children'){errorLabel = document.getElementById('adults_error');}
	else{
	errorLabel = document.getElementById(ctrlName + '_error');
	}
	var isValid = false;
	var errorMessage;
	
	switch(ctrlName)
	{
		case 'time':
			//validate delivery time
			errorMessage = 'choose booking time';
			if(ctrl.selectedIndex != 0){
				isValid = true;
				validateSpecial();
			}
			break;
		case 'name':
			errorMessage = 'name can not be empty';
			//validate First Name
			if (ctrl.value || ctrl.value != '') 
			{
				errorLabel.innerHTML = '';
				
				trimAndToUpperCase(ctrl);
				
				isValid = true;
			}
			
		  break;
		  
		case 'mobile':
			//validate mobile phone regex
			errorMessage = 'wrong mobile format';
			if (ctrl.value || ctrl.value != '') 
			{
				if(ctrl.value.match(mobileRegEx) != null)
				{
					isValid = true;
				}
			}
		  break;
		  
		case 'phone':
			//validate landline
			errorMessage = 'wrong phone format';
			if (ctrl.value || ctrl.value != '') 
			{
				if(ctrl.value.match(phoneRegex) != null)
				{
					isValid = true;
				}
			}
			break;
		 
		case 'email':
			//validate email address
			errorMessage = 'wrong email format';
			if (ctrl.value || ctrl.value != '') 
			{
				if(ctrl.value.match(emailRegex) != null)
				{
					isValid = true;
				}
			}
			break;
			
		case 'password':
			//validate password
			errorMessage = 'password must have at least 6 characters';
			if (ctrl.value || ctrl.value != '') 
			{
				if(ctrl.value.length >= 6)
				{
					isValid = true;
				}
			}
			break;
			
		case 'confirm':
			//validate password confirmation
			errorMessage = 'password confirmation does not match password';
			var passCtrl = document.getElementById('pass1');
			var passValue = passCtrl.value;
			if (ctrl.value || ctrl.value != '') 
			{
				if(ctrl.value == passCtrl.value)
				{
					isValid = true;
				}
			}
			break;
			
		
		case 'adults':
			//validate credit card expiry
			errorMessage = 'can not be empty';
			if ((ctrl.value || ctrl.value != '') && Number(ctrl.value) != 0) 
			{
				var e2 = document.getElementById('children');
				
					var totalChosenSeats = Number(ctrl.value) + Number(e2.value);
					if(!totalSeats){
						totalSeats = 50000;
					}
					if(totalChosenSeats <= totalSeats){
						isValid = true;
						validateSpecial();
					}else{
						errorMessage = 'max seats are '+totalSeats;
					}
				
			}
			break;
			
		case 'children':
			//validate credit card expiry
			errorMessage = 'can not be empty';
			
				var e1 = document.getElementById('adults');
				if((e1.value || e1.value != '') && Number(e1.value) != 0){
					var totalChosenSeats = Number(ctrl.value) + Number(e1.value);
					if(!totalSeats){
						totalSeats = 50000;
					}
					if(totalChosenSeats <= totalSeats){
						isValid = true;
						validateSpecial();
					}else{
						errorMessage = 'max seats are '+totalSeats;
					}
				}
			
			break;
			
		
		case 'description':
			//validate name on credit card
			errorMessage = 'instructions can not be too long';
			//if (ctrl.value || ctrl.value != '') 
			//{
			if (ctrl.value.length < 300) 
			{
				isValid = true;
			}
			//}
			break;
			
		case 'specials':
			
    		var spec = jQuery('#tempSpecials').val();
    		if(spec || spec != 0){
    			if(jQuery('#special_'+spec).css('text-decoration') == '' || jQuery('#special_'+spec).css('text-decoration') == 'none'){
    				jQuery('#specials').val(spec);
    			}
    		}
	    	
			isValid = true;
			break;
		
		default:
		    break;
	}
	
	
	var browser=navigator.appName;// to get browser name
	
	if(!isValid){
		if(errorLabel != null){
			if (browser=="Microsoft Internet Explorer"){
				errorLabel.style.display='';
			}
			errorLabel.innerHTML = errorMessage;
		}
		return false;
		
	}else{
		if(errorLabel != null){
			errorLabel.innerHTML = '';
			if (browser=="Microsoft Internet Explorer"){
				errorLabel.style.display='none';
			}
		}
		return true;
	}
}

function validateAll(){
	var isFormValid = true;
	
	for (ctrlNameIndex in orderFormControls)
	{
		var x=document.getElementById(orderFormControls[ctrlNameIndex]);
		if(x!=undefined || x!=null){
			if(conditionToValidate(x)){
				if(!validate(x))
				{
					isFormValid = false;
				}
			}
			else{
				clearValidation(x);
			}
		}
	}
	
	var orderForm = document.getElementById('order');
	var orderButton = jQuery('[name=order][type=submit]')[0]; 
	if(isFormValid){
		
		if(!orderButton.disabled){
			orderButton.disabled=true;//to block order button
			orderForm.submit();
		}else{
			return false;
		}
	}else{
		var t=setTimeout("var orderForm = document.getElementById('order');var orderButton = jQuery('[name=order][type=submit]');orderButton.val('Book');",2000);
		return false;
	}
}

function conditionToValidate(xctrl)//Emad Messiha - function to return whether a field should be validated or not
{  
	var ctrlId = xctrl.id
	var creditCardPayment = document.getElementById('paymentCard');// for credit card section
	var validateCreditCardSection=false;
	if(creditCardPayment != undefined || creditCardPayment != null){validateCreditCardSection=creditCardPayment.checked;}
	
	switch(ctrlId){
	
	case 'time':
		//delivery time should be validated if "Later" was chosen
		//var laterRadio = document.getElementById('laterOrder');
		//if(!laterRadio.checked){return false;}
		break;
	
	case 'mobile':
		//mobile or landline may be given, if add landline is chosen 
		//and phone is valid, then don't validate mobile
		var addPhone = document.getElementById('landline');
		var tel = document.getElementById('phone');
		if(addPhone.checked && validate(tel)){return false;}
		break;
		
	case 'phone':
		//if "add landline" is checked, then validate phone
		var addPhone = document.getElementById('landline');
		if(!addPhone.checked){return false;}
		break;

	case 'pass1':
		//password is validated if "to become member" is chosen
		var mem = document.getElementById('member');
		if(!mem.checked){return false;}
		break;
		
	case 'pass2':
		//password confirm is validated if "to become member" is chosen
		var mem = document.getElementById('member');
		if(!mem.checked){return false;}
		break;
		
		
	default:
		return true;//to validate everything by default
		
	}
	return true;
}

function isNumberKey(evt,initialVal,id)//Emad Messiha. function to allow only numbers
{
	var e = evt; // for trans-browser compatibility event || 
	var charCode = e.which || e.keyCode;
	
   	if (charCode > 31 && (charCode < 48 || charCode > 57))
   	{
	   return false;
   	}

   	if (e.shiftkey)
   	{
   		return false;
   	}
   	
   	if(initialVal){
   		var ctrl = document.getElementById(id);
	   	if(ctrl.value.substring(0,initialVal.length) != initialVal){
	   		ctrl.value = initialVal + ctrl.value; 
	   	}
   	}
   	
   	return true;
}

function checkKeyUp(id,initialVal){
	ctrl = document.getElementById(id);
   	if(ctrl.value.substring(0,initialVal.length) != initialVal){
   		ctrl.value = initialVal + ctrl.value; 
   	}
   	
   	if(id == 'mobile'){
   		if(ctrl.value.substring(0,initialVal.length+1) == '00'){
   			ctrl.value = initialVal + ctrl.value.substring(2,ctrl.value.length);
   		}
   	}
	return true;
}

function isLetterKey(evt,initialVal,id)//Emad Messiha. function to allow only Letters
{
	var e = evt; // for trans-browser compatibility event || 
	var charCode = e.which || e.keyCode;
	
   	if (charCode >= 48 && charCode <= 57)
   	{
	   return false;
   	}
   	
   	if(initialVal){
   		ctrl = document.getElementById(id);
	   	if(ctrl.value.substring(0,initialVal.length) != initialVal){
	   		ctrl.value = initialVal + ctrl.value; 
	   	}
   	}
   	
   	return true;
}

function clearValidation(ctrl){
	var ctrlName = ctrl.name;
	var errorLabel;
	if(ctrlName == 'children'){errorLabel = document.getElementById('adults_error');}
	else{
	errorLabel = document.getElementById(ctrlName + '_error');
	}
	
	var browser=navigator.appName;// to get browser name
	
	if(errorLabel != null){
		errorLabel.innerHTML = '';
		if (browser=="Microsoft Internet Explorer"){
			errorLabel.style.display='none';
		}
	}
	
}

function clearSectionValidation(sectionName){
	var controls = eval(sectionName);
	for (ctrlIndex in controls)
	{
		var x=document.getElementById(controls[ctrlIndex]);
		if(x!=undefined || x!=null){
			clearValidation(x);
		}
	}
}

function trimAndToUpperCase(cntrl){
	while(cntrl.value.charAt(0)==' ')
	{
		//triming white spaces at the begining
		cntrl.value = cntrl.value.substring(1);
	}
	
	var names = cntrl.value.split(' ');
	var namesIndex = 0;
	cntrl.value = '';
	while(namesIndex < names.length){
		if(names[namesIndex] != ''){
			names[namesIndex] = names[namesIndex].charAt(0).toUpperCase()+names[namesIndex].substring(1);
			
			if(namesIndex != 0){
				cntrl.value = cntrl.value + ' ' + names[namesIndex];
			}else{
				cntrl.value = cntrl.value + names[namesIndex];
			}
		}
		namesIndex++;
	}
}

function checkLandline(){
	//setting also landline number to '02' if it was '2'
    var landline = document.getElementById('phone');
    if(landline.value == '2'){landline.value='02';}

    //clearValidation(landline);
}

function validateSpecial(forSubmit){
	var specId = jQuery('#tempSpecials').val();
	jQuery('#errorSpecial_'+specId).attr('innerHTML',getSmallLoader());
	

	var peopleCount = Number(jQuery('#adults').val()) + Number(jQuery('#children').val());
	var chosenDate = jQuery('#date1').val();
	var chosenTime = jQuery('#time').find('option').filter(':selected').text();
	if(chosenTime == 'Time:'){
		chosenTime = '00:00am';
	}
	
	jQuery.getJSON('/Menu', {cmd:'checkSpecial', specId:specId, peopleCount:peopleCount, chosenDate:chosenDate, chosenTime:chosenTime}, function(data)

    {

		jQuery('#errorSpecial_'+data.specId).attr('innerHTML','');
		jQuery('#special_'+data.specId).css('text-decoration','');

        if(data.msg)
        {
        	jQuery('#errorSpecial_'+data.specId).attr('innerHTML',data.msg);
        	jQuery('#special_'+data.specId).css('text-decoration','line-through');
        	//jQuery('#tempSpecials').val(0);
        }

    });
	
	
}