var xmlHttp;
var url='';
var url_search_results = '';
var search_results_found=false  //needed to display the details link
var search_process_completed=false  // used to indicated whether search completed or not.
var percent_complete = 0;
var where_id = 0;

var time_elapsed=0  // used to exit the AJAX LOOP
var ajax_window_refresh_delay = 2000;
var t;

//------------------------------------------//
//	ajax function for view search results
//-----------------------------------------//

function setDetails(){
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 	
		response_text=xmlHttp.responseText;
	}
}

//-----------------------
// First AJAX call
//-----------------------

function startSearch(){
	show("search_info");
	show("search_div"); 
	
	xmlHttp=GetXmlHttpObject(setSearchResults)
	xmlHttp.open("GET", url , true)
	xmlHttp.send(null)
} 

function setSearchResults() { 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 	
		url=ajax_script+"loop=y"  //all subsequent calls we need this url with loop=y
		response_text=xmlHttp.responseText;
		myregex=/[\n\r]+/;
		response_text=response_text.replace(myregex,""); //remove cr+lf


		// Get the search ID so we know which page to send user to
		myregex=/^.*SEARCH_ID:(.*)$/;
		if(response_text.match(myregex)){
			search_id = response_text.replace(myregex,"$1");
			search_id_position = url_search_results.indexOf('%s');
			url_search_results = url_search_results.substring(0,search_id_position) + search_id + url_search_results.substring(search_id_position+2);
		}


		// Handle message display from phpbl
		var phpbl_message
		myregex=/^.*PHPBL_MESSAGE:(.*)$/;
		if(response_text.match(myregex)){
		 	//alert('response_text='+response_text+' '+arr_response[0])
			phpbl_message=response_text.replace(myregex,"$1"); //gets the message string here
			document.getElementById("phpbl_message").innerHTML=phpbl_message;
	
			if(phpbl_message.length>0){
				show("phpbl_message");
				hide("search_div");
				show_search_button();
				//Stop counting
				time_elapsed=0;
				clearTimeout(t)	
				return;					
			}			
			
			// Strip PHPBL_MESSAGE from response text
			myregex=/PHPBL_MESSAGE:.*$/;
			response_text=response_text.replace(myregex,""); //Strips the message here
		}
	
	
		//Additional coding to handle message display from supplier classes
		var supplier_message
		myregex=/^.*SUPPLIER_MESSAGE:(.*)$/;
		if(response_text.match(myregex)){
			supplier_message=response_text.replace(myregex,"$1"); //gets the message string here

			// Strip SUPPLIER_MESSAGE from response text
			myregex=/SUPPLIER_MESSAGE:.*$/;
			response_text=response_text.replace(myregex,""); //Strips the message here
		}
		


		// Get the search ID so we know which page to send user to
		myregex=/^.*PERCENT:(.*)$/;
		if(response_text.match(myregex)){
			percent_complete = response_text.replace(myregex,"$1");

			if (percent_complete == 100) {
				document.getElementById("div_results_link").innerHTML="<a href='"+url_search_results+"'>VIEW RESULTS</a>";
				show_search_button();
				clearTimeout(t);
				window.location = url_search_results;
			}

			else if (percent_complete > 75 && time_elapsed > 25) {
				document.getElementById("div_results_link").innerHTML="<a href='"+url_search_results+"'>LOADING RESULTS</a>";
				show_search_button();
				clearTimeout(t);
				window.location = url_search_results;
			}

			else if(percent_complete > 50) {
				document.getElementById("div_results_link").innerHTML="<a href='"+url_search_results+"'>VIEW RESULTS SO FAR</a>";
			}

		}
		document.getElementById("percent").innerHTML = percent_complete + "% complete";




		
		// Split response text on ' ' 
		arr_response=response_text.split(" ");
		response_text=response_text.substring(response_text.indexOf(" ")); //removes the leading word

		myregex=/^\s+/;
		arr_response[0]=arr_response[0].replace(myregex,"");
		myregex=/\s+$/;
		arr_response[0]=arr_response[0].replace(myregex,"");

		if(arr_response[0]=="Done"){
			search_process_completed=true;
			show_search_button();

		}else if(arr_response[0]=="Looping"){ //Delay needed only here
			if(!timed_out()) startSearch();
			
		}
	
	} 
} 

function timed_out(){
	if(time_elapsed>time_out_client){
		return true;
	}else{
		return false
	}
}


function show_search_button(){
	//show ("search_button_div");
	document.getElementById("search_button_div").innerHTML="<input type=submit value='Get Hotel Prices' style='background-color:#cc0000; color:white; font-weight:bold; font-size:14px' onClick='validate()'>";
}


function time_out_control(){
	document.getElementById("search_time").innerHTML=time_elapsed+" seconds (max "+ (time_out_client-(ajax_window_refresh_delay/1000)) + ")";
	time_elapsed = time_elapsed + (ajax_window_refresh_delay / 1000);
	if(time_elapsed<(time_out_client)){
		t=window.setTimeout("time_out_control()", ajax_window_refresh_delay)
	}else{
		time_elapsed=time_out_client
		clearTimeout(t)
		window.location = url_search_results;
	}
}

function redirect(reason,details) {
	alert("To get automated search functionality please upgrade your browser!, click to proceed to manual seacrh page");
}

function GetXmlHttpObject(handler)
{ 

	var objXmlHttp=null
	if (navigator.userAgent.indexOf("Opera")>=0)
	{
		redirect('opera','AJAX will not work on Opera')	
		return 
	}
	if (navigator.userAgent.indexOf("MSIE")>=0)
	{ 
		var strName="Msxml2.XMLHTTP"
		if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
		{
			strName="Microsoft.XMLHTTP"
		} 
		try
		{ 
			objXmlHttp=new ActiveXObject(strName)
			objXmlHttp.onreadystatechange=handler 
			return objXmlHttp
		} 
		catch(e)
		{ 
			redirect('IE','Error. Scripting for ActiveX might be disabled')			
			return 
		} 
	} 
	if (navigator.userAgent.indexOf("Mozilla")>=0)
	{
		objXmlHttp=new XMLHttpRequest()
		objXmlHttp.onload=handler
		objXmlHttp.onerror=handler 
		return objXmlHttp
	}
} 


function select(id) {
	where_id = id;
	validate();
}



function validate(){
	affiliate_id=document.form_availability.affiliate_id.value;
	where_string=document.getElementById("where_string").value;
	hidden_id=document.form_availability.hidden_id.value;
	doa_dd=document.getElementById("doa_dd").value;
	doa_mm=document.getElementById("doa_mm").value;
	nights=document.getElementById("nights").value;
	radius_ui="";
	star_rating="";
	currency=document.getElementById("currency").value;

	total_rooms=document.getElementById("total_rooms").value;
	rooms_xml = "";
	for (i=1; i<=total_rooms; i++) {
		room_number = "r"+i;
		adults=document.getElementById(room_number + "adults").value;
		children=document.getElementById(room_number + "children").value;
		room_type_id=document.getElementById(room_number + "room_type_id").value;
		child_ages = "";
		if (children > 0) {
			child_ages=document.getElementById(room_number + "child_ages").value;
			if(children>0 && child_ages.length==0){
				alert("Please enter child ages separated with commas for room " + i);
				return false;
			}
		}
		
		rooms_xml = rooms_xml + "<room><room_number>" + i + "</room_number><adults>" + adults + "</adults><children>" + children + "</children><child_ages>" + child_ages + "</child_ages><room_type_id>" + room_type_id + "</room_type_id></room>";
	}

	var search_type;
	radio_obj=document.form_availability.where_mode;
	for(i=0;i<3;i++){
		if(radio_obj[i] && radio_obj[i].checked==true){
			search_type=radio_obj[i].value;
		}
	}
	if(search_type=="R"){
		radius_ui=document.getElementById("radius_ui").value;
		star_rating=document.getElementById("star_rating").value;
	}
	if(where_string.length==0){
		msg_caption=document.getElementById("where_label").innerHTML;
		alert("Please enter a " + msg_caption.toLowerCase());
		return false;
	}else{
		document.getElementById("phpbl_message").innerHTML="";
		hide("phpbl_message");
		hide("div_main_content");

		document.getElementById("search_button_div").innerHTML="Searching, please wait...";
		
		//Pass parameters
		url=ajax_script+"affiliate_id="+affiliate_id+"&where_string="+escape(where_string)+"&where_mode="+search_type+"&where_id="+where_id+"&hidden_id="+hidden_id+"&radius_ui="+radius_ui+"&star_rating="+star_rating+"&doa_dd="+doa_dd+"&doa_mm="+doa_mm+"&nights="+nights+"&currency="+currency+"&total_rooms="+total_rooms+"&rooms_xml="+escape(rooms_xml);

		search_type=search_type=="region"?where_string+" hotels":where_string;
 		search_info_msg="Checking availability from "+doa_dd+"/"+doa_mm+"/"+create_search_year(doa_dd, doa_mm)+" for "+nights+(nights==1?" night":" nights")+"...";
		document.getElementById("search_info").innerHTML=search_info_msg		
				
		//------------------------------
		// First AJAX that triggers
		// server threads
		//------------------------------
		
		time_out_control() //Initiate the AJAX polling		
		startSearch();
	}
	
}


function day_string(d){
	str="";
	day=parseInt(d);
	switch(day){
		case 1: 
		case 21:
		case 31: str=day.toString()+"st";
				 break;
		case 2:
		case 22: str=day.toString()+"nd";
				   break;
		case 3:
		case 23: str=day.toString()+"rd";
				 break;
		default: str=day.toString()+"th";
		
	}
	return str;
}


// Calculate year of arrival - if month and day are less than today's date, we must be looking at next year.
function create_search_year(doa_dd, doa_mm)
{
  var today = new Date();
  doa_yy = today.getFullYear();
  today_mon = today.getMonth() + 1;
  today_day = today.getDate();

  if ((doa_mm < today_mon) || (doa_mm == today_mon && doa_dd < today_day))
    doa_yy = doa_yy + 1;

  return doa_yy;
}

function get_children_age(){
	children_count=document.getElementById("children").value;
	
	if(children_count>0){
		show("children_age_div");
		str="<table class='style2' cellpadding='0' cellspacing='0'><tr>";
		for(i=1;i<=children_count;i++){
			str+="<td class='style2'>child"+i+" age</td><td  class='style2'><input class='style2' type='text' id='child"+i+"' size='1'></td>";
		}
		str+="</tr></table>";
		document.getElementById("children_age_div").innerHTML=str;
	}else{
		document.getElementById("children_age_div").innerHTML="";
		hide("children_age_div");
	}
}








/**************************************************************************
Visibility
**************************************************************************/

function show(obj)
{
	document.getElementById(obj).style.display = 'block';
}

function hide(obj)
{
	document.getElementById(obj).style.display = 'none';
}

function toggle_obj(obj)
{

  if( document.getElementById(obj).style.display == "block") {
  	hide(obj);
  }
  else {
  	show (obj);
  }
 	return;
}
    	

function network_direct(payment_method)
{
  switch (payment_method) {
    case "network":
    	show('payment_from_network');
    	hide('payment_from_sletoh');
    	break;
    	
    case "sletoh":
    default:
    	show('payment_from_sletoh');
    	hide('payment_from_network');
    	break;
	}
	
	return;
}
    
    
    
