var validate_on_submit = 0; 

function validateOnSubmit()
{
	error_log = '';
	validate_on_submit = 1;
	validateAll();
	validate_on_submit = 0;
	if(error_log != '')
	{
		error_log = 'Please correct the following problems:\n'+error_log;
	   alert(error_log);
	   logError('contact_us: '+error_log, '/enquiry.js',13);
	   return false;	
	}
	return true;  
}


function validateAll()
{
   validate('from_name',1);
   validate('from',3);
   validate('telephone',2);
   validate('message',1);
   validate('word',11);   
}


var error_log = '';
function logSubmitError(field)
{
	error_log += '- ';
   switch(field)
   {
   	case 'from_name':
   	error_log += "Your  name is required when making an enquiry\n";
   	break;  	   	    	   		
   
   	case 'from':
   	error_log += "Your email address is required when making an enquiry\n";
   	break;
   	
   	case 'telephone':
   	error_log += "Please provide your phone number if you would like to be contacted by phone\n";
   	break;
   	
   	case 'message':
   	error_log += "Please ensure your enquiry is not blank\n";
   	break;    	
   	
   	case 'word':
   	error_log += "Please ensure you typed the word correctly\n";
   	break; 
   	
	}	
}

function check_email_address(email)
{
   var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/  
   return email.match(re); 	
}

function check_word(word)
{
   var url = '/ajax/check_captcha_word.ajax.php?word='+word;
   return (ajaxRequest(url, false) == '00') ? true : false;
}


function validate(field,type,flag)
{
	
	// Flag used to suppress alerts
	master_flag = flag;   
	
	var val = document.getElementById(field).value;
	   
	if(val == '' && (field != 'telephone' || (field == 'telephone' && document.getElementById('preference').value == 'By Phone'))) 
	{
	   if(document.getElementById('v_'+field))
	   {
   	   document.getElementById('v_'+field).innerHTML = (validate_on_submit == 1) ? '<img src="/images/error_s_trans.png" border="0" width="20" height="20">' : '<span class="mandatory_field">&laquo;</span>';             
		}
   	if(validate_on_submit == 1) logSubmitError(field);
	   return false;
	}
   var rv = true;
   switch(type)
   {
   	// Not blank
   	case 1:
   	if(val == '') 
   	{
   		rv = false;
   		if(validate_on_submit == 1) logSubmitError(field);  
		}
   	break;
   	
   	
   	// Telephone
   	case 2:
   	if(document.getElementById('preference').value == 'By Phone')
   	{
   		if(isNaN(val) || val.length <= 5) 
   		{
   			rv = false;
   			if(validate_on_submit == 1) logSubmitError(field); 
			}
		}
		else
		{
		   document.getElementById('v_telephone').innerHTML = '<span class="mandatory_field">&nbsp;</span>';   	
		   return;
		}
   	break;   	
   	
   	
   	// Email
   	case 3:
   	
		
   	// Check if 'customer_email' is blank
	   if(document.getElementById(field).value == '') 
	   {
	   	// Client side failed  
	   	rv = false;
   		if(validate_on_submit == 1) logSubmitError('email');
		}
		
		// If it's not blank, client side validation
		else
		{
		   if(!check_email_address(document.getElementById(field).value))
		   {
		   	// Client side failed
		   	rv = false;
				if(validate_on_submit == 1) logSubmitError('email'); 
			}	
			else
			{
				rv = true;
			}
		}
   	break;
   	
   	
  	   // Captcha word
   	case 11:
   	
		
   	// Check if 'word' is blank
	   if(document.getElementById('word').value == '') 
	   {
	   	// Client side failed  
	   	rv = false;
   		if(validate_on_submit == 1) logSubmitError('word');
		}
		
		// If it's not blank, client side validation
		else
		{
		   if(!check_word(document.getElementById('word').value))
		   {
		   	// Client side failed
		   	rv = false;
				if(validate_on_submit == 1) logSubmitError('word'); 
			}	
			else
			{
				rv = true;
			}
		}
   	break; 
   	
   	
   	// Preference
   	case 13:
   	
   	if(val == 'By Phone')
   	{	
   	   validate('telephone',2);
		}
		else
		{
		   document.getElementById('v_telephone').innerHTML = '<span class="mandatory_field">&nbsp;</span>';	
		}
		return;
		break;
   	
      
	}
	
	if(document.getElementById('v_'+field))
	{
	   var error_img = (validate_on_submit == 1) ? '<img src="/images/error_s_trans.png" border="0" width="20" height="20">' : '<img src="/images/facebook_x_trans.png" border="0" width="15" height="15">';
	   var iHTML = (rv) ? '<img src="/images/facebook_tick_trans.png" border="0" width="15" height="15">' : error_img;
	   document.getElementById('v_'+field).innerHTML = iHTML;	
	}
}

function getMostApplicableFAQsResponse()
{
   if (xmlHttp.readyState==4)
   {
      rc = xmlHttp.responseText;
      if(rc != '')
      {
         var applicable_faqs_div = document.getElementById("applicable_faqs_div");
         var x = findPosX(document.getElementById('message'));
         var y = findPosY(document.getElementById('message'));
         applicable_faqs_div.style.marginLeft = (x-270)+'px';
         applicable_faqs_div.style.marginTop = (y)+'px';
         applicable_faqs_div.innerHTML = rc;
         applicable_faqs_div.style.display = '';
      }
      else
      {
         var applicable_faqs_div = document.getElementById("applicable_faqs_div");
         applicable_faqs_div.innerHTML = '';
         applicable_faqs_div.style.display = 'none';
      }
   }
}


function getMostApplicableFAQs(text)
{
   if(text.length >= server_character_threshold_faqs_on_enquiry)
   {
      var url = '/ajax/get_applicable_faqs.ajax.php?text='+encodeURIComponent(text)+'&language_id=1';
      ajaxRequest(url, true, 'getMostApplicableFAQsResponse');
   }
   else
   {
      var applicable_faqs_div = document.getElementById("applicable_faqs_div");
      applicable_faqs_div.innerHTML = '';
      applicable_faqs_div.style.display = 'none';
   }
}


function closeApplicableFAQs()
{
   document.getElementById("applicable_faqs_div").innerHTML = '';
   document.getElementById("applicable_faqs_div").style.display = 'none';
}

function findPosX(obj)
{
 var curleft = 0;
 if(obj.offsetParent)
     while(1)
     {
       curleft += obj.offsetLeft;
       if(!obj.offsetParent)
         break;
       obj = obj.offsetParent;
     }
 else if(obj.x)
     curleft += obj.x;
 return curleft;
}



function findPosY(obj)
{
 var curtop = 0;
 if(obj.offsetParent)
     while(1)
     {
       curtop += obj.offsetTop;
       if(!obj.offsetParent)
         break;
       obj = obj.offsetParent;
     }
 else if(obj.y)
     curtop += obj.y;
 return curtop;
}




var current_button_text = '';
function sendEnquiry()
{
     current_button_text = document.getElementById('send_enquiry_button').childNodes[0].innerHTML;
     setButtonStatus('send_enquiry_button','rrg_inactive_button','Sending Enquiry... <img style="margin-left:5px;" src="/images/loading_small.gif" width="16" height="11" align="top" border="0">','this.blur(); return false;','#');	 
	 var from_name = document.getElementById('from_name').value;
	 var from = document.getElementById('from').value;
	 var telephone = document.getElementById('telephone').value;
	 var preference = document.getElementById('preference').value;
	 var message = document.getElementById('message').value;
	 var word = document.getElementById('word').value;
	 var qs = 'from_name='+encodeURIComponent(from_name)+'&from='+encodeURIComponent(from)+'&telephone='+encodeURIComponent(telephone)+'&preference='+encodeURIComponent(preference)+'&message='+encodeURIComponent(message)+'&word='+encodeURIComponent(word)+'&id='+server_id;
	 var url = '/ajax/send_enquiry.ajax.php?'+qs;
	 ajaxRequest(url, true, 'sendEnquiryResponse');
}


function sendEnquiryResponse()
{
   if (xmlHttp.readyState==4)
   {
      rc = xmlHttp.responseText;
      if(rc.indexOf("|")!=-1)
      {
         var parts = rc.split("|");	
         if(parts.length == 2)
         {
            alert(parts[1]);
            // Success
            if(parts[0] == 0)
            {
                _gaq.push(['_trackPageview','/funnel_G3/property_enquiry/enquiry_sent.html']); 
				document.getElementById('from_name').value = '';
				document.getElementById('from').value = '';
				document.getElementById('telephone').value = '';
				document.getElementById('preference').value = 'By E-mail';
				document.getElementById('message').value = '';
				document.getElementById('word').value = '';
				validate('from_name',1);
				validate('from',3);
				validate('telephone',2);
				validate('word',11);
			}
		 }
	  }
      setButtonStatus('send_enquiry_button','rrg_orange_button',current_button_text,'this.blur(); return false;','javascript:sendEnquiry();');  	  
   }
}



function comboSelectDateCheckIn(d,m,y)
{
   from_day_obj = document.getElementById('combo_from_day');
   from_month_obj = document.getElementById('combo_from_month');
   from_year_obj = document.getElementById('combo_from_year');
   to_day_obj = document.getElementById('combo_to_day');
   to_month_obj = document.getElementById('combo_to_month');
   to_year_obj = document.getElementById('combo_to_year');
      
	from_day_obj.value = d;
	from_month_obj.value = m;   
	from_year_obj.value = y;   	
	_closeCalendar();
	_setComboDate(d,m,y,'checkin');
	
	var fromDate = new Date();
	var toDate = new Date();
   fromDate.setFullYear(y,m-1,d); 
   toDate.setFullYear(to_year_obj.value,to_month_obj.value-1,to_day_obj.value); 
   
	// if to date before from date, set to date = from date + 1 week
	if(toDate < fromDate)
	{
      toDate.setFullYear(y,m-1,d);  
      toDate.setDate(toDate.getDate()+7);
	   _setComboDate(toDate.getDate(),toDate.getMonth()+1,toDate.getFullYear(),'checkout');
	}
}

function comboSelectDateCheckOut(d,m,y)
{
	document.getElementById('combo_to_day').value = d;
	document.getElementById('combo_to_month').value = m;   
	document.getElementById('combo_to_year').value = y;   	
	_closeCalendar();
	_setComboDate(d,m,y,'checkout');
   // Check out callback
}

function _setComboDate(d,m,y,type)
{
   var year_target = (type == 'checkin') ? 'combo_from_year' : 'combo_to_year';
   var month_target = (type == 'checkin') ? 'combo_from_month' : 'combo_to_month'; 
   var day_target = (type == 'checkin') ? 'combo_from_day' : 'combo_to_day'; 
   year_target_obj = document.getElementById(year_target);
   month_target_obj = document.getElementById(month_target);
   day_target_obj = document.getElementById(day_target);
   
   var year_is_valid = false;
   for(i = 0; i < year_target_obj.options.length; i++)
   {
      if(year_target_obj.options[i].value == y)
	  {
         year_is_valid = true;
	  }
   }
   if(year_is_valid)
   {
      year_target_obj.value = y;
      month_target_obj.value = m;
      adjustDays(month_target,day_target,year_target);
      day_target_obj.value = d;
   }
   else
   {
      alert("Date cannot be selected as it is too far in the future");
      return;
   }
}

function setButtonStatus(id,class_name,text,handler,href)
{
   var obj = document.getElementById(id);
   obj.onClick = handler;
   obj.href = href;
   obj.className = class_name;
   obj.childNodes[0].innerHTML = text;
}

function sendComboEnquiry()
{
     var from_name = document.getElementById('combo_name').value;
	 var contact = document.getElementById('combo_contact').value;
	 if(from_name == '' || from_name == 'Your Name')
	 {
	    alert('Please enter in your name to make an enquiry.');
	    return;
	 }
	 if(contact == '' || contact == 'Your Email or Phone')
	 {
	    alert('Please enter in either your email address or telephone number so we can get in contact with you.');
	    return;
	 }
     setButtonStatus('combo_send_enquiry_button','rrg_inactive_button','Sending Enquiry... <img style="margin-left:5px;" src="/images/loading_small.gif" width="16" height="11" align="top" border="0">','this.blur(); return false;','#');	 
	 var from = (contact.indexOf('@')!=-1) ? contact : '';
	 var telephone = (contact.indexOf('@')==-1) ? contact : '';
	 var preference = (contact.indexOf('@')==-1) ? 'By Phone' : 'By E-mail';
	 var message = document.getElementById('combo_message').value;
	 var fy = parseInt(document.getElementById('combo_from_year').value);
	 var fm = parseInt(document.getElementById('combo_from_month').value)-1;
	 var fd = parseInt(document.getElementById('combo_from_day').value);
	 var ty = parseInt(document.getElementById('combo_to_year').value);
	 var tm = parseInt(document.getElementById('combo_to_month').value)-1;
	 var td = parseInt(document.getElementById('combo_to_day').value);	 
	 var from_date = '';
	 var to_date = '';
	 if(fy != '' && fm != '' && fd != '' && ty != '' && tm != '' && td != '')
	 {
        from_date = Date.UTC(fy,fm,fd,0,0,0,0); 
        to_date = Date.UTC(ty,tm,td,0,0,0,0);   
	 }
	 var qs = 'bComboEnquiry=true&from_date='+from_date+'&to_date='+to_date+'&from_name='+encodeURIComponent(from_name)+'&from='+encodeURIComponent(from)+'&telephone='+encodeURIComponent(telephone)+'&preference='+encodeURIComponent(preference)+'&message='+encodeURIComponent(message)+'&id='+server_id;
	 var url = '/ajax/send_enquiry.ajax.php?'+qs;
	 ajaxRequest(url, true, 'sendComboEnquiryResponse');
}


function sendComboEnquiryResponse()
{
   if (xmlHttp.readyState==4)
   {
      rc = xmlHttp.responseText;
      document.getElementById('combo_div_response').innerHTML = rc;
      document.getElementById('combo_div').style.display = 'none';        
      document.getElementById('combo_div_response').style.display = '';      
      _gaq.push(['_trackPageview','/funnel_G3/property_enquiry/enquiry_sent.html']);   
      setButtonStatus('combo_send_enquiry_button','rrg_orange_button','Send us your enquiry now &raquo;','this.blur(); sendComboEnquiry(); return false','#');      
   }
}

function comboBack()
{
   document.getElementById('combo_div_response').style.display = 'none'; 
   document.getElementById('combo_div').style.display = '';
}

function comboBook(sd,sm,sy,fd,fm,fy)
{
   document.getElementById('booking_from_day').value = sd;
   document.getElementById('booking_from_month').value = sm;
   document.getElementById('booking_from_year').value = sy;
   document.getElementById('booking_to_day').value = fd;
   document.getElementById('booking_to_month').value = fm;
   document.getElementById('booking_to_year').value = fy;
   processButtonClick(2, '<?=getMultilingualContent(111,$LANGUAGE_CODE,46);?>');   
}

function updateComboCheckout()
{
   var sd = document.getElementById("combo_from_day").value;  
   var sm = document.getElementById("combo_from_month").value;
   var sy = document.getElementById("combo_from_year").value;
   if(sd == '' || sm == '' || sy == '') return;
   var fd = document.getElementById("combo_to_day").value;
   var fm = document.getElementById("combo_to_month").value;
   var fy = document.getElementById("combo_to_year").value;
   var sdate = new Date();
   var fdate = new Date();
   sdate.setDate(sd);
   sdate.setMonth(sm-1);
   sdate.setFullYear(sy);
   fdate.setDate(fd);
   fdate.setMonth(fm-1);
   fdate.setFullYear(fy);
   var _sdate = Date.UTC(sy,sm-1,sd,0,0,0,0);
   var _fdate = Date.UTC(fy,fm-1,fd,0,0,0,0); 
   if(_fdate < _sdate)
   {
      var nfdate = sdate;
      nfdate.setDate(sdate.getDate()+7);
      document.getElementById("combo_to_day").value = nfdate.getDate();
      document.getElementById("combo_to_month").value = nfdate.getMonth()+1;
      document.getElementById("combo_to_year").value = nfdate.getFullYear();
   }
}
