var errorMessage = "";



function showRequest(formData, jqForm, options) { 
    
	    	var validform = true;
	    	var errorMessage = '';
	    	var phoneLength ='';
	    	var phoneNumber = '';
	    	setRegionId();
	    	var v1 = validateEnquiryName();
	    	
	    	if (v1 == false) {
	    	    errorMessage += 'Name field is required\n';
	    	}
	    	
	    	var v2 = validateEnquiryPhone();
            var v3 = validateEnquiryEmail();
            var v4 = validateEmailAddress();
            var v5 = validateEnquiryRegion();
            
            if (v2 == false && v3 == false ) {
                errorMessage += 'Phone or Email field is required\n';
            } 
            
            else if($('#contactEmail').is(':checked')) {
                if (v3 == true && v4 == false) {
                errorMessage += 'Email address field does not contain a valid email address\n';
                }
            }
                               
            else if($('#contactPhone').is(':checked')) {
                var phoneNumber = jQuery.trim($('#enq_prod_phone').val());
                phoneLength = phoneNumber.replace(/[^0-9]/g,'');
                phoneLength = phoneLength.length;
                if (phoneLength < 7) {
                    errorMessage += 'Phone number entered is too short\n'
                } 
            }                
  
            if (v5 == false) {
                errorMessage += "Region is required\n";
            };
            
            if (!errorMessage == '') {
                alert(errorMessage);
                return false;     
            };
            
	        $("#ajaxloader").show();	

} 

function showResponse(responseText, statusText) {
	var status = '';

	status = responseText.indexOf('success');
	
	var mode = $('#miniEquiryForm').find('input[name="Mode"]').val();
	var storyDescription = $('#miniEquiryForm').find('input[name="StoryDescription"]').val();
	
	if( status > -1) {
		$('#miniEquiryForm').html('');
		$('#miniEquiryForm').append('<p><strong>Thanks for your enquiry. Your details have been sent to one of our experienced travel consultants and they will get back to you shortly.</strong></p> <p>You can also call 0800 24 35 44 to speak with us right away.</p><img height="1" width="1" border="0" src="https://www.googleadservices.com/pagead/conversion/[conversionId]/?value=[conversionValue]&amp;label=[conversionLabel]&amp;script=0"/>');
		
		if (mode.search(/car/i)>-1) {
			pageTracker._trackPageview('/enquiryform/product_car');
		} else if (mode.search(/airfare/i)>-1) {
			if (storyDescription.search(/round the world/i)>-1 || storyDescription.search(/world trip/i)>-1) {
				pageTracker._trackPageview('/enquiryform/product_rtwflight');
			} else {
				pageTracker._trackPageview('/enquiryform/product_flight');
			}
			
		} else if (mode.search(/cruise/i)>-1) {
			pageTracker._trackPageview('/enquiryform/product_cruise');
		} else if (mode.search(/hotel/i)>-1) {
			pageTracker._trackPageview('/enquiryform/product_hotel');
		} else if (mode.search(/holiday/)>-1) {
			pageTracker._trackPageview('/enquiryform/product_holiday');
		} else if (mode.search(/tour/i)>-1) {
			pageTracker._trackPageview('/enquiryform/product_tour');
		} else if (mode.search(/activity/i)>-1) {
			pageTracker._trackPageview('/enquiryform/product_activity');
		} else {
			pageTracker._trackPageview('/enquiryform/productshort');
		}
		
		// Place the PCT Tracking Code
		FCNZ.ENQUIRY.thankYouTrackingCode();
		
		var axel = Math.random() + "";
        var num = axel * 1000000000000000000;
        var spotpix = new Image();
        //spotpix.src='http://fls.doubleclick.net/activityi;src=2229539;type=fc000000;cat=submi732;ord='+num+'?';
        spotpix.src='http://ad.doubleclick.net/activity;src=2229539;type=fc000000;cat=submi927;ord=1;num='+ num + '?';
        
	
	} else {
		$('#miniEquiryForm').html('');
		$('#miniEquiryForm').append('<p>Oops! We are unable to process your submission at this time. Please try again later or call 0800 24 35 44 to speak to a travel consultant.</p>');
	}

}

$(document).ready(function() {
    
$('#region').bind('change', function(){
   var storeValue = this.value;
   
   if (storeValue != 'storediv-specialists' || storeValue !== 'storediv-lowersouthisland') {
       $('#storediv-specialists').hide();
       $('#storediv-lowersouthisland').hide();
   };    
   
   if (storeValue == 'storediv-lowersouthisland') {
        $('#storediv-specialists').hide();
        $('#storediv-lowersouthisland').show();
   };
   
    if (storeValue == 'storediv-specialists') {
        $('#storediv-specialists').show();
        $('#storediv-lowersouthisland').hide();
   };
 
});

$('#storediv-specialists').bind('change', function(){ 
    $('#storeID').val(this.value);
});

$('#storediv-lowersouthisland').bind('change', function(){ 
    $('#storeID').val(this.value);
});
    
	var options = { 
		beforeSubmit:  showRequest, 
		success:       showResponse  
	}; 

	$('#miniEquiryForm').submit(function() {        
			$(this).ajaxSubmit(options);
            return false; 
	});

});

function validateQuickEnquiryForm_v2(frm) {
	var validform = true;
	errorMessage = "";
//	var v1 = validateEnquiryName();
//	var v2 = validateEnquiryPhone();
//    var v3 = validateEnquiryEmail();
//	var v9 = validateEnquiryPhoneEmail()
//	if (v2==false && v3==false) errorMessage += "Phone or Email field is required\n";
//  var v4 = validateDepartureDate();
//	var v5 = validateReturnDate();
	var v6 = validateEnquiryRegion();
	var v7 = validateEnquiryStore();
	var v8 = validateEnquiryDetails();
	
	validform = v1 && v6 && v7 && v8;
	setRegionId();
	setReturnLocation();
	saveDestCookie();
	if (!validform) {
		//alert(errorMessage);
	}
	

	
	return validform;
}

/*
function validateEnquiryPhoneEmail() {
    var validated = true;
	var email=$('#enq_prod_email').val();
	var phone=$('#enq_prod_phone').val();
	if (email=="" || email == 'Email address' || phone == "" || phone == "(__) ___ ____") {
		validated = false;
		errorMessage += "Email address or Phone field is required\n";
	} else {
		if (!checkValidEmail(email)) {
			validated = false;
			errorMessage += "Email address field does not contain a valid email address\n";
		}
	}
	return validated;
}
*/
function setReturnLocation(){
	document.onlineEnquiryForm.ReturnLocation.value=location.href;
}
function setRegionId(){
	var sRegion = document.onlineEnquiryForm.region.options[document.onlineEnquiryForm.region.selectedIndex].value;
	var sStoreID = '';
	if(sRegion.indexOf('~')>-1){
		var aId = sRegion.split('~');
		if(aId.length>0){
			sStoreID = aId[1];
		}
	}else{
		if(sRegion!=''){
    		var oStore =document.onlineEnquiryForm.elements[sRegion];
    		if(oStore){
    	 		sStoreID = oStore.options[oStore.selectedIndex].value;
			}else{
				alert('couldn\'t find region'); 
			}	}
	}
	document.onlineEnquiryForm.regionid.value = sStoreID;
}
function validateEnquiryName() {
	var validated = true;
	var givenName=document.onlineEnquiryForm.givenNames.value;
	if (!document.onlineEnquiryForm.givenNames.value || document.onlineEnquiryForm.givenNames.value == 'Name') {
		validated = false;
		//errorMessage += "Name field is required\n";
	}
	return validated;
}
function validateEnquiryRegion(){
	var validated = true;
	if (document.onlineEnquiryForm.region.value=='') {
		validated = false;
		// errorMessage += "Region is required\n";
	}
	return validated;
}
function validateEnquiryStore(){
	var validated = true;
	var oForm = document.onlineEnquiryForm;
	if(oForm.region.value.indexOf('~')<0&&oForm.region.value!=''){
		    if (oForm.elements[oForm.region.value].value==''){
			    validated = false;
			    errorMessage += "Store is required\n";
			}
	}
	return validated;
}


function validateEmailAddress(){
	var validated = true;
	email=$('#enq_prod_email').val();
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (!filter.test(email)){ 
	    validated = false 
    }
	return validated;
}

function checkValidEmail(str){
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	testresults=false
	if (filter.test(str)) testresults=true
	return (testresults)
}

function validateEnquiryEmail() {
	var validated = true;
	email=$('#enq_prod_email').val();
	email= email.replace(/ /g,'');
	if (email=="") {
		validated = false;
	}	
	return validated;
}

function validateEnquiryPhone() {
	var validated = true;
	var phone=$('#enq_prod_phone').val();
	phone = phone.replace(/ /g,'');
	
	if (phone=="") {
		validated = false;
		//errorMessage += "Phone or Email field is required\n";
	}
	return validated;
}
function validateEnquiryDetails() {
	var validated = true;
	if (!document.onlineEnquiryForm.details.value||document.onlineEnquiryForm.details.value==' ') {
		validated = false;
		errorMessage += "Details field is required\n";
	}
	return validated;
}
function validateDepartureDate() {
	var validated = true;
	if (!document.onlineEnquiryForm.departDate.value||document.onlineEnquiryForm.departDate.value=='DD/MM/YY') {
		validated = false;
		errorMessage += "Departure date field is required\n";
	}
	else if(!isValidDate(document.onlineEnquiryForm.departDate.value)){
		validated = false;
		errorMessage += "Departure date is not valid\n";
	}
	return validated;
}
function validateReturnDate() {
	var validated = true;
	if (!document.onlineEnquiryForm.returnDate.value||document.onlineEnquiryForm.returnDate.value=='DD/MM/YY') {
		validated = false;
		errorMessage += "Return date field is required\n";
	}
	else if(!isValidDate(document.onlineEnquiryForm.returnDate.value)){
		validated = false;
		errorMessage += "Return date is not valid\n";
	}
	else if (dateDiff(document.onlineEnquiryForm.departDate.value, document.onlineEnquiryForm.returnDate.value) < 0){
		validated = false;
		errorMessage +="Departure date cannot be greater than the return date\n";
	}
	return validated;
}
function clearDefaultText(elem)
{
	if (elem.value == 'DD/MM/YY') { elem.value=''; }
}
function fillDepartureDate() {
	var startDate = document.onlineEnquiryForm.departDate.value;
	var slashpos = startDate.split('/')
	if(slashpos.length==3){
		var d=slashpos[0];
		var m=slashpos[1];
		var y=slashpos[2];
		document.getElementById('startday').value=d;
		document.getElementById('startmonth').value=m;
		document.getElementById('startyear').value=y;
	}
}
function fillReturnDate() {
	var returnDate = document.onlineEnquiryForm.returnDate.value;
	var slashpos = returnDate.split('/')
	if(slashpos.length==3){
		var d=slashpos[0];
		var m=slashpos[1];
		var y=slashpos[2];
		document.getElementById('endday').value=d;
		document.getElementById('endmonth').value=m;
		document.getElementById('endyear').value=y;
	}
}
function dateDiff(firstDate, secondDate){
	//Set the two dates
		aD = firstDate.split('/');
		if(aD.length==3){
			iY = aD[2];
			iM = aD[1];
			iD = aD[0];
		}
		aE = secondDate.split('/');
		if(aE.length==3){
			eY = aE[2];
			eM = aE[1];
			eD = aE[0];
		}
	var stoday=new Date(iY,iM-1,iD) ;
	var etoday=new Date(eY,eM-1,eD) ;
	var one_day=1000*60*60*24
	
	//Calculate difference btw the two dates, and convert to days
	return Math.ceil((etoday.getTime()-stoday.getTime())/(one_day));
}
function isValidDate(dateStr) {
	// Checks for the following valid date formats:
	// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
	// Also separates date into month, day, and year variables
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
	
	// To require a 4 digit year entry, use this line instead:
	// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
	return false;
	}
	month = matchArray[3]; // parse date into variables
	day = matchArray[1];
	year = matchArray[4];
	if (month < 1 || month > 12) { // check month range
		return false;
	}
	if (day < 1 || day > 31) {
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false
	}
	if (month == 2) { // check for february 29th
	var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	if (day>29 || (day==29 && !isleap)) {
		return false;
	   }
	}
	return true;  // date is valid
}
function saveDestCookie(){
	var oForm = document.onlineEnquiryForm;
	var sCityValue =oForm.DestinationCity.value;
	var sCountryValue=oForm.DestinationCountry.value;
	var sValue;
	if (sCityValue != ''){
		sValue=sCityValue;
	}else if (sCountryValue != ''){
		sValue=sCountryValue;
	}else{
		sValue='no-value';
	}
	setCookie('FCEnquiryDest', sValue);
}


