var USER_ID = -1;
var SUPPLIER_ID = -1;
var bCreateBooking = false;
var ajax_path = "library/ajax/";
var axConnection = false; 
/*
function toggle(obj, cnt)
{
	var selected = false;

	if(post_url && obj)
	{
		var box_class = 'box_off';
		var box_header_class = 'box_header_off';
		var src = post_url + 'images/arrow-right.gif';

		if(obj.className == 'box_header_off')
		{
			box_class = 'box_on';
			box_header_class = 'box_header_on';
			src = post_url + 'images/arrow-down.gif';
			selected = true;
		}

		setClassName(obj, box_header_class);
		setClassName(obj.parentNode, box_class);

		var aImg = obj.getElementsByTagName('img');
		if(aImg[0]){aImg[0].src = src;}

		jsSetPreference(cnt, selected);
	}
}
*/
function showPopUp(show, object)
{
	var pop_up = getObject('pop_up');

	if(pop_up)
	{
		setVisibility(pop_up, show);

		if(show)
		{
			var top = (object) ? getAbsoluteTop(object) - (pop_up.offsetHeight + 5) : 0;
			var left = (object)? getAbsoluteLeft(object) - ((pop_up.offsetWidth - object.offsetWidth) / 2) : 0;

			setScreenPosition(pop_up, top, left);
			setFilter(pop_up);
		}
	}
}

function selectItem(obj)
{
	if(obj)
	{
		var style = (obj.value > 0) ? 'bold' : '';
		var color = (obj.value > 0) ? '#238CC3' : '';

		obj = obj.parentNode.parentNode.parentNode;
		setFontWeight(obj, style);
		setColor(obj, color)
	}
}

function selectBooking(obj)
{
	var selected = false;

	if(post_url && obj)
	{
		selected = (obj.className == 'booking_off');
		var css = (selected) ? 'booking_on' : 'booking_off';

		setClassName(obj, css);
	}

	return selected;
}

function setOverlayPosition()
{
	var img = getObject('imgSupplierPicture');
	var img_ovl = getObject('imgSupplierPicture_Overlay');
	
	if(img && img_ovl)
	{
		setPosition(img_ovl, 'absolute');

//		var top = getAbsoluteTop(img) + ((img.offsetHeight - img_ovl.offsetHeight) / 2);
//		var left = getAbsoluteLeft(img) + ((img.offsetWidth - img_ovl.offsetWidth) / 2);
		var top = (getAbsoluteTop(img) + img.offsetHeight) - img_ovl.offsetHeight;
		var left = (getAbsoluteLeft(img) + img.offsetWidth) - img_ovl.offsetWidth;

		setScreenPosition(img_ovl, top, left);
	}
}

function enableSummary(enabled)
{
	var object = getObject('divSummary');
	setClassName(object, ((enabled) ? 'summary' : 'summary_off'));
	setDisable(object, !enabled);
}

function resizeInformationDiv()
{
	var height = 0;
	var minimum_height = 180;
	var object_ref = getObject('divAvailability');
	var obj_supplier = getObject('divSupplier');
	var elts = document.getElementsByName('information');

	var ref_height = (object_ref) ? object_ref.offsetHeight : 0;
	var sup_height = (obj_supplier) ? obj_supplier.offsetHeight : 0;
	var diff_height = (ref_height - sup_height);

	for(i=0; i<elts.length; i++)
	{
		var obj = elts[i];
		var display = obj.style.display;

		if(height == 0)
		{
			height = Math.abs(obj.offsetHeight + diff_height);
			height = (height > minimum_height) ? height : minimum_height;
		}

		obj.style.display = '';
		obj.style.height = height + 'px';
		obj.style.display = display;
	}
}

// Create the Ajax Engine

function jsAjaxEngine(id)
{
	this.id = id;
	this.object = getObject(id);
	this.response = false;

	var othis = this;

	this.stateChanged = function()
	{
	}
	
	this.stateCompleted = function()
	{
	}

	this.fire = function(url)
	{
		var requestDestination = ajax_path + url;

		jQuery.ajax({
		    url: requestDestination,
		    type: 'GET',
		    error: function(){
//		        alert('Error loading XML document');
		    },
		    success: function(response){
				othis.response = response; // || "error";
				othis.stateChanged();

				setHtml(othis.object, othis.response);
				othis.stateCompleted();
		        // do something with xml
		    }
		});

		/*
		new Ajax.Request(requestDestination,
		{
			method:'get',
			onSuccess: function(transport)
			{
				othis.response = transport.responseText; // || "error";
				othis.stateChanged();

				setHtml(othis.object, othis.response);
//				$(othis.id).innerHTML = othis.response;
			}
//			,
//			 onFailure: function(){alert('Something went wrong...');}
		});
		*/
	}
}

function jsSetAjax(id, url)
{
	if(id == '' || getObject(id))
	{
		var ajax = new jsAjaxEngine(id);
		ajax.fire(url);
	}
}

/***************************************************************************************************************************************************************/

function jsChangePeople(cnt, said, rid)
{
	//displayWaitingPicture('div_room_price_' + cnt);
	displayWaitingPicture('div_total_' + cnt);

	var objPeople = getObject("select_people_" + cnt);

	if(objPeople)
	{
		var people = objPeople.value;
		var ajax = new jsAjaxEngine('');

		ajax.stateChanged = function()
		{
			//getRoomRedisplay(said);
			selectItem(objPeople);
			getCheckDate(said);
			jsAfterMakingSelectionChange(cnt, said, rid);
		}
		ajax.fire('ajax_update_shoppingcart_item.php?said=' + said + '&rid=' + rid + '&p=' + people + '&fid=' + USER_ID);
	}
}

function getRoomRedisplay(said){
		var index = 0;
		var hotelhtmlIds=new Array();
			jQuery.ajax({
					url: '/library/ajax/ajax_get_room_redraw.php?said=' + said,
					type: 'GET',
					dataType: 'html',
					success: function(table){
					//jQuery("div > div[@class='daterow']").html("<span>Check in:</span>" + json.checkInStr);
					//alert(jQuery("div > div[@class='daterow']").html());
					jQuery("#divRooms:eq(0)").html(table);
					getRoomSelectUpdate();

					// (jQuery("div > div[@class='daterow']:eq(0)").html("<span>Check in:</span>"+ json.checkInStr));
					// (jQuery("div > div[@class='daterow']:eq(1)").html("<span>Check out:</span>"+ json.checkOutStr));
					// (jQuery("#checkInDate").val(json.bookingCheckIn));
					// (jQuery("#checkOutDate").val(json.bookingCheckOut));
					// (jQuery("#checkInDesc").html(json.checkInWeekday));
					// (jQuery("#checkOutDesc").html(json.checkOutWeekday));
					
	
					}
				});	
}


function getCheckDate(said){
		var index = 0;
		var hotelhtmlIds=new Array();
			jQuery.ajax({
					url: '/library/ajax/ajax_get_check_date.php?said=' + said,
					type: 'GET',
					dataType: 'json',
					success: function(json){
					//jQuery("div > div[@class='daterow']").html("<span>Check in:</span>" + json.checkInStr);
					//alert(jQuery("div > div[@class='daterow']").html());
					(jQuery("div > div[@class='daterow']:eq(0)").html("<span>Check in:</span>"+ json.checkInStr));
					(jQuery("div > div[@class='daterow']:eq(1)").html("<span>Check out:</span>"+ json.checkOutStr));
					(jQuery("#checkInDate").val(json.bookingCheckIn));
					(jQuery("#checkOutDate").val(json.bookingCheckOut));
					(jQuery("#checkInDesc").html(json.checkInWeekday));
					(jQuery("#checkOutDesc").html(json.checkOutWeekday));
					}
				});	
}

function getRoomSelectUpdate(){
	jQuery(".bg_dashed_bottom_border select option:selected" ).each(function (){
	
	var obj=(jQuery(this).parent().parent().parent().parent());
	if(jQuery(this).val()>0){
		obj.attr('style','color:#238CC3;font-weight:bold');
		//obj.css("font-weight",'bold');
	}else{
		obj.attr('style','');
	}
});
//jQuery("#selCurrencies [@value='" + json[room].currencyId +"']").attr("selected", true);	
}

function jsSelectPricelineRoom(cnt, object, said, rid, ccyid)
{
	if(object)
	{
		var people = object.value;
//		var value = object.value;
//		var aRooms = (document.form_priceline_rooms && document.form_priceline_rooms.pl_room) ? document.form_priceline_rooms.pl_room : null;
		var aRooms = (document.form_priceline_rooms) ? document.form_priceline_rooms.getElementsByTagName('select') : null;
		if(aRooms){for(var i=0; i<aRooms.length; i++){aRooms[i].value = 0; selectItem(aRooms[i]);}}
//		object.checked = (value == 1 && object.checked) ? false : object.checked;
//		object.value = (object.checked) ? 1 : 0;
		object.value = people;

/*
		var tax = object.getAttribute('tax');
		var price = object.getAttribute('price');
		var avgprice = object.getAttribute('avg_price');
		var rcode = object.getAttribute('room_code');
		var rtcode = object.getAttribute('rate_code');
		var ccyid = object.getAttribute('currency_id');
		var rtcgy = object.getAttribute('rate_category');
		var rtdesc = object.getAttribute('rate_description');
		var rdesc = object.getAttribute('room_description');
*/
		var ajax = new jsAjaxEngine('');
		ajax.stateChanged = function()
		{
			getRoomRedisplay(said);
			selectItem(object);
			getCheckDate(said);
			getRoomSelectUpdate(said);
			jsAfterMakingSelectionChange(cnt, said, rid);
		}
/*	
		ajax.fire('ajax_select_priceline_room.php?sid=' + sid + '&rid=' + rid + '&p=' + people + '&price=' + price + 
																'&avgprice=' + avgprice + '&tax=' + tax + '&ccyid=' + ccyid + '&rtcode=' + rtcode + 
																'&rtdesc=' + rtdesc + '&rtcgy=' + rtcgy + '&rcode=' + rcode + '&rdesc=' + rdesc + 
																'&fid=' + USER_ID);
*/
		ajax.fire('ajax_update_shoppingcart_item.php?said=' + said + '&rid=' + rid + '&p=' + people + '&fid=' + USER_ID);
	}
}

function jsSelectHotelComRoom(cnt, object, said, rid, ccyid)
{
	if(object)
	{
		var people = object.value;
		var aRooms = (document.form_hotelcom_rooms) ? document.form_hotelcom_rooms.getElementsByTagName('select') : null;
		if(aRooms){for(var i=0; i<aRooms.length; i++){aRooms[i].value = 0; selectItem(aRooms[i]);}}

		object.value = people;
		
		var ajax = new jsAjaxEngine('');
		ajax.stateChanged = function()
		{
			//getRoomRedisplay(said);
			selectItem(object);
			getCheckDate(said);
			getRoomSelectUpdate(said);
			jsAfterMakingSelectionChange(cnt, said, rid);
		}
		//ajax.fire('ajax_update_shoppingcart_item.php?said=' + said + '&rid=' + rid + '&p=' + people + '&ccyid=' + ccyid + '&fid=' + USER_ID);
		ajax.fire('ajax_update_shoppingcart_item.php?said=' + said + '&rid=' + rid + '&p=' + people + '&fid=' + USER_ID);
	}
}

function jsAfterMakingSelectionChange(cnt, said, rid)
{
	//jsDisplayWarning(cnt, sid, rid);
	//jsDisplayRoomPrice(cnt, sid, rid);
	//jsDisplayNumberUnits(cnt, sid, rid);
	//jsDisplayTotalPrice(cnt, said, rid);
	jsDisplaySummaryPrices(said);
	jsDisplaySummaryPayment(said);
	//jsCheckForm();
}

function jsDisplayWarning(cnt, sid, rid)
{
	jsSetAjax('div_warning_' + cnt, 'ajax_display_warning.php?sid=' + sid + '&rid=' + rid);
}

/*
function jsDisplayRoomPrice(cnt, sid, rid)
{
	jsSetAjax('div_room_price_' + cnt, 'ajax_display_room_price.php?sid=' + sid + '&rid=' + rid);
}
*/

/*
function jsDisplayNumberUnits(cnt, sid, rid, date)
{
	jsSetAjax('div_units_' + cnt, 'ajax_display_number_units.php?sid=' + sid + '&rid=' + rid);
}
*/

/*
function jsDisplayTotalPrice(cnt, sid, rid)
{
	jsSetAjax('div_total_' + cnt, 'ajax_display_room_total.php?sid=' + sid + '&rid=' + rid);
}
*/
function jsDisplaySummaryPrices(said)
{
	var oid = 'divSummaryPrices';
	displayWaitingPicture(oid);
	jsSetAjax(oid, 'ajax_display_summary.php?said=' + said + '&p=1');
}

function jsDisplaySummaryPayment(said)
{
	var oid = 'divSummaryPayment';

	displayWaitingPicture(oid);
	jsSetAjax(oid, 'ajax_display_summary.php?said=' + said + '&p=0');
}
/*
function jsCheckForm()
{
	//if(!bCreateBooking)
	//{
		//jsSetAjax('panel', 'ajax_check_form.php?sid=' + SUPPLIER_ID);

		jQuery.ajax({
				type: "get",
				url: ajax_path+'ajax_check_form.php?sid=' + SUPPLIER_ID,
				success: function(response){
					var arrErrors = response.split(",");
					
					if(arrErrors.length==0){
						//jsCreateBooking(SUPPLIER_ID);
					}else{
						for(i = 0; i < arrErrors.length; i++){
							var result = arrErrors[i];
							result = result.replace(/(^\s*)|(\s*$)/g, ""); 
							if(result!=""){
								var arrValue = result.split("=");
								if(arrValue[1]=="F"){
									if(arrValue[0] == "Agreed terms and conditions"){
										jQuery("#errorMessage-chkTC").css({"display":"block"});
										jQuery("#errorMessage-chkTC").html("You must agree terms and conditions");
									}if(arrValue[0] == "Expiration"){
										jQuery("#errorMessage-expiration").css({"display":"block"});
										jQuery("#errorMessage-expiration").html("Expiration is invalid"); 
									}else{
										var func = function(){
											var errObj = jQuery("#errorMessage-"+jQuery(this).attr("id"));
											var label = jQuery(errObj.next().children(".billingtableleft > .bookinglabel").html()).filter(".bookinglabel").text();
											label = label.substring(0, label.indexOf(':'));
											if(label == arrValue[0]){
												errObj.css({"display":"block"});
												errObj.html( label + " is invalid" );
											}
										};
										jQuery("#fPaymentDetails input").each(func);
										jQuery("#fPaymentDetails select").each(func);
									}
								}
							}
						}
					}
				},
				error: function(transport){
					alert(transport.responseText);
				}
		});
}
*/

function jsChangeDate(date, nights, supplierAggregatorId)
{
	var oid = 'divAvailability';

	displayWaitingPicture(oid);
	/*var ajax = new jsAjaxEngine(oid);

	ajax.stateChanged = function()
	{
		//jsCheckForm();
		jQuery(document).ready(function(){
			setTimeout("loadimagecontrol();", 200);
		});
		
		var t = setTimeout("resizeInformationDiv();", 500);
	}
	ajax.fire('ajax_change_date.php?sid=' + SUPPLIER_ID + '&d=' + date + '&n=' + nights);
*/
	jQuery.ajax({
		url: '/library/ajax/ajax_change_date.php?said=' + supplierAggregatorId + '&d=' + date + '&n=' + nights,
		type: 'GET',
		dataType: 'json',
		//data: {c: cnt, type: property_type, d: checkinDateFormatted, n: nights, p: people, radius: radius},
		error: function(){
			hideWaitMsg(1);
		},
		success: function(json){	
			var t = setTimeout("resizeInformationDiv();", 500);
			jQuery("#divAvailability").html(json.roomAvailability);
			//alert(json.roomAvailability);
			//if(jQuery("#divPriceRange").length>0){
				//jQuery("#divPriceRange").html(json.priceRangeSlider);
			//}
		}
	});


}

/*
function jsDisplaySupplierBrochure()
{
	var oid = 'divSupplierBrochure';

//	displayWaitingPicture(oid);
//	var ajax = new jsAjaxEngine(oid);
//
//	ajax.stateChanged = function()
//	{
//		setTimeout("setOverlayPosition();", 10);
//	}
//
//	ajax.fire('ajax_display_supplier_brochure.php?sid=' + SUPPLIER_ID);

	
	jQuery.ajax({
		url: '/library/ajax/ajax_display_supplier_brochure.php?sid=' + SUPPLIER_ID,
		type: 'GET',
		dataType: 'json',
		error: function(){
			//hideWaitMsg(1);
		},
		success: function(json){	
			setTimeout("setOverlayPosition();", 10);
			jQuery("#divSupplierBrochure").html(json.supplierDescription);
			
			jQuery(document).ready(function(){
				setTimeout("loadimagecontrol();", 200);
			});
		}
	});
}
*/
/*
function jsDisplaySupplierDirections()
{
	var oid = 'divSupplierDirections';

//	displayWaitingPicture(oid);
	var ajax = new jsAjaxEngine(oid);

	ajax.stateCompleted = function()
	{
		jQuery(document).ready(function(){
			var mapDiv = document.getElementById("map_canvas");
			if(mapDiv!=null){
				setTimeout(function (){
					jQuery(document).ready(function(){
						setTimeout("loadimagecontrol();", 200);
					});
					initializemap(); 
					setDirections(''+jQuery("#fromAddress").val(), jQuery("#toAddress1").val(), jQuery("#toAddress2").val(), jQuery("#toAddress3").val(), 'en');
				}, 200);
			}
		});
		setTimeout("setOverlayPosition();", 500);
	}

	ajax.fire('ajax_display_supplier_directions.php?sid=' + SUPPLIER_ID);
}
*/
function jsChangeCurrency(cid, supplierAggregatorId, search_page, nights)
{

	if(cid > 0)
	{
		if(search_page == 1)
		{
			showWaitMsg("Now Loading...");
		}else{
			var oid = 'divAvailability';
			displayWaitingPicture(oid);
		}
		
/*
		var ajax = new jsAjaxEngine('');
		ajax.stateChanged = function()
		{
			if(search_page != 1)
			{
				jsDisplayRooms(people);
			}
			else
			if(search_page == 1)
			{
				
			}
		}
		
		ajax.fire('ajax_change_currency.php?cid=' + cid + '&sid=' + SUPPLIER_ID);
*/


	jQuery.ajax({
		url: '/library/ajax/ajax_change_currency.php?cid='+cid+'&said='+supplierAggregatorId+'&isSearchPage='+search_page+'&n='+nights,
		type: 'GET',
		dataType: 'json',
		//data: {c: cnt, type: property_type, d: checkinDateFormatted, n: nights, p: people, radius: radius},
		error: function(){
			if(search_page == 1)
			{
				hideWaitMsg(1);
			}
		},
		success: function(json){			
			if(search_page != 1)
			{
				jQuery("#divAvailability").html(json.roomAvailability);
				if(jQuery("#divPriceRange").length>0){
					jQuery("#divPriceRange").html(json.priceRangeSlider);
				}
			}
			else
			if(search_page == 1)
			{
				hideWaitMsg(1);
				setTimeout(function (){
					jQuery("#divSearchResults").html(json.searchResult);
					if(jQuery("#divPriceRange").length>0){
						jQuery("#divPriceRange").html(json.priceRangeSlider);
					}
				}, 200);
			}
		}
	});

	/*
	new Ajax.Request('/library/ajax/ajax_change_currency.php', {
		method: 'get',
	  	parameters: {cid: cid, sid: SUPPLIER_ID, isSearchPage:search_page},
		onSuccess: function(transport) {
			if(search_page != 1)
			{
				jsDisplayRooms(people);
			}
			else
			if(search_page == 1)
			{
				hideWaitMsg(1);
				var json = eval('('+transport.responseText+')'); 
				setTimeout(function (){jQuery("#divSearchResults").html(json.searchResult);}, 200);
			}
		},
		onFailure: function(){
			// handle here
			if(search_page == 1)
			{
				hideWaitMsg(1);
			}
			alert(transport.responseText);

		}
	});
*/

	}
}


function jsDisplayRooms(people)
{
	var oid = 'divRooms';

	displayWaitingPicture(oid);
	/*var ajax = new jsAjaxEngine(oid);

	ajax.stateChanged = function()
	{
//		jsCheckForm();
	}
*/
	jQuery.ajax({
		url: '/library/ajax/ajax_display_rooms.php?sid=' + SUPPLIER_ID + '&p=' + people,
		type: 'GET',
		dataType: 'json',
		error: function(){
			//hideWaitMsg(1);
		},
		success: function(json){
			//hideWaitMsg(1);
			setTimeout(function (){jQuery("#divRooms").html(json.roomHtml);}, 200);
		}
	});

	//ajax.fire('ajax_display_rooms.php?sid=' + SUPPLIER_ID + '&p=' + people);
}

/*
function jsCreateBooking(sid)
{
	var oid = 'panel';

	bCreateBooking = true;
	displayBookingPicture(oid);

	var ajax = new jsAjaxEngine(oid);

	ajax.stateChanged = function()
	{
		if(this.response == 'BooKinG DonE')
		{
			// REDIRECT  TO THE CONFIRMATION PAGE...
			window.location = "confirmation";
		}
		else
		{
//			alert('test');
//			jsDisplayRooms(0);


			//jsCheckForm();
			hideWaitMsg();
		}

		bCreateBooking = false;
	}

	bCreateBooking = false;
	ajax.fire('ajax_create_booking.php?sid=' + sid);
}
*/

/* No longer used
function jsDisplayBookings(future, uid, sid, cnt, oid)
{
	displayWaitingPicture(oid+'Wait');
	jsSetAjax(oid, 'ajax_display_bookings.php?u=' + uid + '&i=' + sid + '&c=' + cnt + '&f=' + ((future) ? 'y' : 'n'));
}
*/
/*
function jsDisplayPastBookings(uid, sid)
{
	displayWaitingPicture('divPastBookings');
	jsSetAjax('divPastBookings', 'ajax_display_past_bookings.php?u=' + uid + '&i=' + sid);
}
*/
/*
function jsDisplayFutureBookings(uid, sid)
{
	displayWaitingPicture('divFutureBookings');
	jsSetAjax('divFutureBookings', 'ajax_display_future_bookings.php?u=' + uid + '&i=' + sid);
}
*/
/*
function jsDisplayShoppingCart()
{
	var oid = 'divShoppingCart';

	displayWaitingPicture(oid);
	jsSetAjax(oid, 'ajax_shopping_cart.php');
}
*/


/*
function jsSelectPeople(cnt, aid, wid, aggid, sid, rid1, rid2, date, objNightId, objPeopleId, objDivPeopleId, objRoomPriceId, objTotalId)
{
	var objNights = getObject(objNightId);
	var objPeople = getObject(objPeopleId);

	if(objNights && objPeople)
	{
		var nights = objNights.value;
		var people = objPeople.value;

		var ajax = new jsAjaxEngine(objDivPeopleId);
		ajax.stateChanged = function()
		{
			jsDisplayTotalPrice(cnt, aid, wid, aggid, sid, rid1, rid2, date, objNightId, objPeopleId, objRoomPriceId, objTotalId);
		}

		ajax.fire('ajax_display_select_people.php?aid=' + aid + '&wid=' + wid + '&aggid=' + aggid + '&sid=' + sid + '&r1=' + rid1 + '&r2=' + rid2 + '&d=' + date + '&n=' + nights + '&p=' + people + '&c=' + cnt);
	}
}

function jsDisplayTotalPrice(cnt, sid, rid)
{
	var objNights = getObject(objNightId);
	var objPeople = getObject(objPeopleId);

	if(objNights && objPeople)
	{
		var nights = objNights.value;
		var people = objPeople.value;
		var ajax = new jsAjaxEngine(objTotalId);

		ajax.stateChanged = function()
		{
			jsDisplayRoomPrice(cnt, aid, wid, aggid, sid, rid1, date, objNightId, objRoomPriceId);
			jsDisplayPrices(sid, date);
			jsDisplayPayment(sid, date);
			jsDisplayShoppingCartSummary();
			selectItem(objPeople);
			jsCheckForm();
displayShoppingCartWindow();
//displayTransactionWindow();
		}

		ajax.fire('ajax_display_room_total.php?aid=' + aid + '&wid=' + wid + '&aggid=' + aggid + '&sid=' + sid + '&r1=' + rid1 + '&r2=' + rid2 + '&d=' + date + '&n=' + nights + '&p=' + people + '&c=' + cnt);
	}
}

function jsDisplayRoomPrice(cnt, sid, rid, date, objNightId, objRoomPriceId)
{
	var objNights = getObject(objNightId);
	
	if(objNights)
	{
		var nights = objNights.value;
		jsSetAjax(objRoomPriceId, 'ajax_display_room_price.php?i=' + sid + '&r=' + rid + '&d=' + date + '&n=' + nights + '&c=' + cnt);
	}
}

function jsDisplayPrices(sid, date, rid, cnt)
{
	sid = (sid) ? sid : -1;
	rid = (rid) ? rid : -1;
	cnt = (cnt) ? cnt : '';
	date = (date) ? date : null;

	var oid = 'divSummaryPrices' + cnt;

	displayWaitingPicture(oid);
	jsSetAjax(oid, 'ajax_display_summary.php?i=' + sid + '&d=' + date + '&r=' + rid + '&p=1&c=' + cnt);
}

*/
/*No longer used
function jsDisplayConfirmation(oid)
{
	displayWaitingPicture(oid);
	jsSetAjax(oid, 'ajax_display_confirmation.php');
}
*/

/*No longer used
function jsDeleteBooking(sid, rid, date)
{
	var ajax = new jsAjaxEngine('');
	ajax.stateChanged = function()
	{
		jsDisplayShoppingCart();
	}

	ajax.fire('ajax_delete_booking.php?i=' + sid+ '&r=' + rid + '&d=' + date);
}
*/
/*
function jsSelectBooking(oid, sid, rid, date)
{
	var selected = selectBooking(getObject(oid));

	var ajax = new jsAjaxEngine('');

	ajax.stateChanged = function()
	{
		jsDisplayPrices();
		jsDisplayPayment();
	}

	ajax.fire('ajax_select_booking.php?i=' + sid+ '&r=' + rid + '&d=' + date + '&s=' + ((selected) ? 'y' : 'n'));
}
*/
/*
function jsUpdateDeposit(sid, rid, date, percent, cnt)
{
	var ajax = new jsAjaxEngine('');

	ajax.stateChanged = function()
	{
		jsDisplayPayment(sid, date, rid, cnt);
		jsDisplayPayment();
	}

	ajax.fire('ajax_update_deposit_percentage.php?i=' + sid+ '&r=' + rid + '&d=' + date + '&p=' + percent);
}
*/
/*
function jsOpenTermsAndConditions(object)
{
	var ajax = new jsAjaxEngine('pop_up');

	ajax.stateChanged = function()
	{
		setSize(getObject('pop_up'), 560, 538);
		showPopUp(true, object);
	}

	ajax.fire('ajax_open_tc.php');
}
*/
/*
function jsOpenFacebookHelp(object)
{
	var ajax = new jsAjaxEngine('pop_up');

	ajax.stateChanged = function()
	{
		setSize(getObject('pop_up'), 560, 538);
		showPopUp(true, object);
	}

	ajax.fire('ajax_open_facebook_help.php');
}
*/
/*
function jsUpdateCustomer()
{
	showPopUp(false);

	var txtFirstName = encodeURI( getObjectValue('txtFirstName') );
	var txtLastName = encodeURI( getObjectValue('txtLastName') );
	//var txtGender = encodeURI( getObjectValue('selGender') );
	var txtGender = encodeURI( getObjectValue('hidCender') );
	var txtArrivalTime = encodeURI( getObjectValue('selArrivalTime') );
	var txtContactEmail = encodeURI( getObjectValue('txtContactEmail') );
	var txtConfirmEmail = encodeURI( getObjectValue('txtConfirmEmail') );

	var checkbox = getObject('chkTC');
	var v1 = (checkbox && checkbox.checked) ? '1' : '0';
	checkbox = getObject('chkFacebook');
	var v2 = (checkbox && checkbox.checked) ? '1' : '0';


	
	var txtAddress1 = encodeURI( getObjectValue('txtAddress1') );
	var txtAddress2 = encodeURI( getObjectValue('txtAddress2') );
	var txtCity = encodeURI( getObjectValue('txtCity') );
	var txtZip = encodeURI( getObjectValue('txtZip') );
	var txtPhone = encodeURI( getObjectValue('txtPhone') );
	var txtCountry = encodeURI( getObjectValue('selCountry') );
	var txtReason = encodeURI( getObjectValue('selReason') );
	
	var ajax = new jsAjaxEngine('');

	ajax.stateChanged = function()
	{
		jsCheckForm();
	}

	ajax.fire('ajax_update_customer.php?fn=' + txtFirstName + '&ln=' + txtLastName + '&g=' + txtGender + '&at=' + txtArrivalTime + '&e1=' + txtContactEmail + '&e2=' + txtConfirmEmail + '&tc=' + v1 + '&f=' + v2
		+ '&ad1=' + txtAddress1 + '&ad2=' + txtAddress2 + '&cti=' + txtCity + '&zc=' + txtZip + '&cty=' + txtCountry + '&tp=' + txtPhone + '&rf=' + txtReason
	);
}
*/
/*
function jsUpdateCreditCard()
{
	showPopUp(false);

	var txtHolderName = encodeURI( getObjectValue('txtCCHolderName') );
	var txtNumber = encodeURI( getObjectValue('txtCCNumber') );
	var selType = encodeURI( getObjectValue('selCCType') );
	var selMonth = encodeURI( getObjectValue('selCCMonth') );
	var selYear = encodeURI( getObjectValue('selCCYear') );
	var txtCvv = encodeURI( getObjectValue('txtCCCvv') );

	var ajax = new jsAjaxEngine('');

	ajax.stateChanged = function()
	{
//		setDisable('btnPaySave', false);
//		jsChangePayButton();
		jsCheckForm();
	}

	ajax.fire('ajax_update_credit_card.php?h=' + txtHolderName + '&n=' + txtNumber + '&t=' + selType + '&m=' + selMonth + '&y=' + selYear + '&c=' + txtCvv);
}
*/
/*
function jsChangePayButton()
{
	jsSetAjax('btnPaySave', 'ajax_change_pay_button.php');
}
*/
/*
function jsSetPreference(cnt, value)
{
	jsSetAjax('', 'ajax_set_preference.php?c=' + cnt + '&v=' + value);
}
*/
/*
function jsUpdateBookingStatus(uid, sid, bid, status)
{
	var ajax = new jsAjaxEngine('');
	ajax.stateChanged = function()
	{
		jsDisplayFutureBookings(uid, sid);
	}

	ajax.fire('ajax_update_booking_status.php?i=' + bid+ '&s=' + status);
}
*/
/*
function jsUpdateCurrency(cid, aid, wid, aggid, sid, date, nights, people)
{
	displayWaitingPicture('divRooms');

	var ajax = new jsAjaxEngine('');
	var ajax = new jsAjaxEngine('');
	ajax.stateChanged = function()
	{
		if(sid > 0)
		{
			jsDisplayRooms(people);
		}
		else
		{
			jsDisplayResults();
		}
	}

	ajax.fire('ajax_update_currency.php?c=' + cid);
}
*/
function jsChangePage(pid)
{
	showWaitMsg("Now Loading...");
	jQuery.ajax({
		url: '/library/ajax/ajax_change_page.php?p=' + pid,
		type: 'GET',
		dataType: 'json',
		error: function(){
			hideWaitMsg(1);
		},
		success: function(json){
			hideWaitMsg(1);
			setTimeout(function (){
				jQuery("#divSearchResults").html(json.searchResult); 
				window.scrollTo(0, 0);}
			, 200);
		}
	});

	/*
	new Ajax.Request('/library/ajax/ajax_change_page.php?p=' + pid, {
		method: 'get',
	  	parameters: {},
		onSuccess: function(transport) {
			hideWaitMsg(1);
			var json = eval('('+transport.responseText+')'); 
			setTimeout(function (){jQuery("#divSearchResults").html(json.searchResult);}, 200);
		},
		onFailure: function(){
			hideWaitMsg(1);
		}
	});
	*/
/*
	displayWaitingPicture('divSupplierResults');

	jsSetAjax('divSearchResults', 'ajax_change_page.php?p=' + pid);
	*/
}
/*
function jsDisplayShoppingCartSummary()
{
	jsSetAjax('divShoppingCartSummary', 'ajax_display_shopping_cart_summary.php');
}
*/

var nTimeout;

function search(obj, evt)
{
	var evt = (evt) ? evt : ((window.event) ? event : null);

	if(obj && evt)
	{
		window.clearTimeout(nTimeout);

		if(evt.keyCode == 13)
		{
			jsSearchSuppliers(-1);
		}
		else
		{
			nTimeout = window.setTimeout("jsSearchSuggestion('" + obj.id + "')", 350);
		}
	}
}

function jsSearchSuppliers(cnt)
{
	if(prepareSubmit() == false)
	{
		return;
	}
	
	if(jQuery("#checkInDate").val().length <= 0)
	{
		alert("Please enter a valid checkin date");
		return;
	}
	
	if(jQuery("#checkOutDate").val().length <= 0)
	{
		alert("Please enter a valid checkout date");
		return;
	}

	var pageUrl = window.location.href;
	var mySplitUrl = pageUrl.split("?");
	
	// FIX ME: check number of nights!

	
	var people = 1;
	var checkIn	= jQuery("#checkInDate").val();
	var checkOut= jQuery("#checkOutDate").val();
	
	var checkInFiledValue  = checkIn.split("/");

	var nCheckInYear = checkInFiledValue[2];
	
	if(nCheckInYear.length <= 2)
	{
		nCheckInYear = '20' + nCheckInYear;
	}	
	
	var checkInDate = new Date(nCheckInYear, parseInt(checkInFiledValue[0] - 1)  , checkInFiledValue[1] ); //Month is 0-11 in JavaScript
	
	var checkinDateFormatted = checkInDate.getFullYear() + '' 
									+ formatnumfordate(checkInDate.getMonth() + 1)
									+ formatnumfordate(checkInDate.getDate());
	
	var nights = 1;
	if (checkOut == "")
	{
		//alert("empty");
		// CANCEL SEARCH HERE!
	}
	else
	{
		var checkOutFiledValue = checkOut.split("/");
		
		var nCheckOutYear = checkOutFiledValue[2];
	
		if(nCheckOutYear.length <= 2)
		{
			nCheckOutYear = '20' + nCheckOutYear;
		}	
		
		var checkOutDate  = new Date(nCheckOutYear, parseInt(checkOutFiledValue[0] - 1)  , checkOutFiledValue[1] ); //Month is 0-11 in JavaScript

		
		var checkoutDateFormatted = checkOutDate.getFullYear() + '' 
									+ formatnumfordate(checkOutDate.getMonth() + 1)
									+ formatnumfordate(checkOutDate.getDate());
		/*alert(Math.floor(( checkOutDate - checkInDate ) / (1000*60*60*24)));
		alert(Math.floor(( checkOutDate.getTime() - checkInDate.getTime() ) / (1000*60*60*24)));
		alert(Math.round(( checkOutDate - checkInDate ) / (1000*60*60*24)));
		alert(Math.round(( checkOutDate.getTime() - checkInDate.getTime() ) / (1000*60*60*24)));
		return ;*/
		nights = Math.round(( checkOutDate.getTime() - checkInDate.getTime() ) / (1000*60*60*24));
	}
	
	if(nights < 1 || nights > 30)
	{
		alert("Number of nights can not be more than 30");

		return;
		// CANCEL SEARCH HERE!
	}

	var checkInParam = checkIn.replace(/-/g, "");
	checkinDateFormatted = checkinDateFormatted.replace(/-/g, "");
	
	/*start changes*/
	var radius = 10;
	
	
	var property_type = "";
	
	if (jQuery('#Hotel:checked').is(':checked')) 
	{
		property_type = property_type + 'hotel';
	}
	
	if (jQuery('#Hostel:checked').is(':checked')) 
	{
		property_type = property_type + ' hostel';
	}
	
	if (jQuery('#Motel:checked').is(':checked')) 
	{
		property_type = property_type + ' motels';
	} 
	
	if (jQuery('#GuesthouseAndBedAndBreakfast:checked').is(':checked')) 
	{
		property_type = property_type + ' guesthouseandbnb';
	} 
	
	if (jQuery('#Campsite:checked').is(':checked')) 
	{
		property_type = property_type + ' campsite';
	} 
	
	if (jQuery('#ApartmentAndVilla:checked').is(':checked')) 
	{
		property_type = property_type + ' apartmentandvilla';
	} 
	
	if (jQuery('#Resort:checked').is(':checked')) 
	{
		property_type = property_type + ' resort';
	} 

	//property_type = property_type.replace(/ /g, "%2C");
	property_type 	= property_type.replace(/ /g, ",");
	/*end changes */
	
	//alert(property_type + '-' + checkinDateFormatted);
	
	
	showWaitMsg("Now Loading...");
	
	jQuery.ajax({
		url: '/library/ajax/ajax_search_suppliers.php?c='+cnt+'&type='+property_type+'&d='+checkinDateFormatted+'&n='+nights+'&p='+people+'&radius'+radius,
		type: 'GET',
		//dataType: 'json',
		//data: "[{c: "+cnt+", type: "+property_type+", d: +"checkinDateFormatted"+, n: +"nights+", p: people, radius: radius}]",
		error: function(){
			hideWaitMsg(1);
		},
		success: function(){	
			hideWaitMsg(1);
			//jsDisplayResults();
		}
	});

/*
	new Ajax.Request('/library/ajax/ajax_search_suppliers.php', {
		method: 'get',
	  	parameters: {c: cnt, type: property_type, d: checkinDateFormatted, n: nights, p: people, radius: radius},
		onSuccess: function(transport) {
			hideWaitMsg(1);
				//alert(mySplitUrl[0].toString());
				//window.location.reload();
				//window.location.replace ( 'http://securebookingsphp.travelonomy.local.doloforge.com/search');
				
				jsDisplayResults();
				//document.getElementById('divCompareseparator').style.display="block";
				//document.getElementById('divCompareBox').style.display="block"; 
		},
		onFailure: function(){
			hideWaitMsg(1);
			// handle here
		}
	});
*/
	//jsSetAjax('divSearchResults', 'ajax_search_suppliers.php?c=' + cnt + '&type='+ property_type + '&d=' + checkInParam + '&n=' + nights + '&p=' + people + '&radius=' + radius );
}

/*
function jsRefineSearch(p, r)
{
	displayWaitingPicture('divSupplierResults');

	var ajax = new jsAjaxEngine('');
	ajax.stateChanged = function()
	{
		jsDisplayResults();
	}

	ajax.fire('ajax_change_search_criterias.php?p=' + p + '&r=' + r);
}
*/
function jsDisplayResults()
{
	setVisibility(getObject('divSuggestions'), false);
	displayWaitingPicture('divSupplierResults', 10);

	showWaitMsg("Now Loading...");
	
	jQuery.ajax({
		url: '/library/ajax/ajax_display_results.php',
		type: 'GET',
		dataType: 'json',
		//data: {c: cnt, type: property_type, d: checkinDateFormatted, n: nights, p: people, radius: radius},
		error: function(){
			hideWaitMsg(1);
		},
		success: function(json){			
			hideWaitMsg(1);
			var othis = getObject('divSearchResults');
			othis.innerHTML = json.searchResult;
			document.getElementById("city").value=json.city;
			document.getElementById("checkin").value=json.checkin;
			document.getElementById("checkout").value=json.checkout;

			if(jQuery("#divPriceRange").length>0 && json.priceRangeSlider != null ){
				jQuery("#divPriceRange").html(json.priceRangeSlider);
			}
		}
	});
	
	/*
	new Ajax.Request('/library/ajax/ajax_display_results.php', {
		method: 'get',
		requestHeaders: {Accept: 'application/json'},
	  	//parameters: {c: cnt, type: property_type, d: checkInParam, n: nights, p: people, radius: radius},
		onSuccess: function(transport) {
				var json = transport.responseText.evalJSON(true);
				var othis = getObject('divSearchResults');
				othis.innerHTML = json.searchResult;
				document.getElementById("city").value=json.city;
				document.getElementById("checkin").value=json.checkin;
				document.getElementById("checkout").value=json.checkout;
				
				//document.getElementById('divCompareseparator').style.display="block";
				//document.getElementById('divCompareBox').style.display="block"; 
		},
		onFailure: function(){ 
			// handle here
		}
	});
	*/
	//jsSetAjax('divSearchResults', 'c.php');
}

function jsSearchSuggestion(id)
{
	var ajax = new jsAjaxEngine('divSuggestions');
	ajax.stateChanged = function()
	{
		var object = getObject('txtSearch');
		var top = (object) ? getAbsoluteTop(object) + object.clientHeight + 5 : 0;
		var left = (object)? getAbsoluteLeft(object) : 0;

		var div = getObject('divSuggestions');
		setScreenPosition(div, top, left);
		setVisibility(div, (this.value != ''));
	}

	ajax.fire('ajax_search_suggestions.php?t=' + getObjectValue(id));
}

function SEPARATOR(){}

//-Animated Picture ---------------------------------------------------------------------------//

function displayAnimatedPicture(object, src, margin)
{
	if(object)
	{
		var height = object.offsetHeight;
		setHtml(object, '');

		var div = document.createElement('div');

		setAlign(div, 'center');
		setSize(div, null, height);
		setVisibility(div, 'hidden');

		var img = document.createElement('img');
		img.src = src;

		div.appendChild(img);
		object.appendChild(div);

		var img_height = (height >= 100) ? 100 : 16;							// img.offsetHeight
		var tb_margin = (typeof(margin) == 'number') ? margin : ((height - img_height) / 2);
		setMargin(img, tb_margin);

		setVisibility(div, 'visible');
	}
}

function displayWaitingPicture(oid, margin)
{
	var object = getObject(oid);

	if(object)
	{
		var h_pict = (object.offsetHeight >= 100) ? 100 : 16;
		var src = 'images/waiting/wait' + h_pict + '.gif';

		displayAnimatedPicture(object, src, margin);
	}
}

function displayBookingPicture(oid)
{
	displayAnimatedPicture(getObject(oid), 'images/waiting/createbooking.gif');
}

function displaySupplier()
{
	var name = 'Supplier';
	var url = ajax_path + '_ajax_supplier.php';
	var features = 'height=1000,width=450,left=820,top=0';
	var win = window.open(url, name, features + ",scrollbars=yes,status=no,toolbar=no,menubar=no,location=no,resizable=yes,titlebar=no");
}
/*
function displayShoppingCartWindow()
{
	var name = 'ShoppingCart';
	var url = ajax_path + '_ajax_shopping_cart.php';
	var features = 'height=1000,width=450,left=820,top=0';
	var win = window.open(url, name, features + ",scrollbars=yes,status=no,toolbar=no,menubar=no,location=no,resizable=yes,titlebar=no");
}
*/
function displayTransactionWindow()
{
	var name = 'Transaction';
	var url = ajax_path + '_ajax_transaction.php';
	var features = 'height=1000,width=450,left=820,top=0';
	var win = window.open(url, name, features + ",scrollbars=yes,status=no,toolbar=no,menubar=no,location=no,resizable=yes,titlebar=no");
}

function displayHostelBookersWindow(url, fwUrl, fwName, startDate, nights, selectedLocation)
{
	var name = 'HostelBookers';
	var features = 'height=600,width=800,left=300,top=0';
//, name, features + ",scrollbars=yes,status=yes,toolbar=yes,menubar=no,location=no,resizable=yes,titlebar=no"

	var win = window.open(url+"?url="+escape(fwUrl)+"&toName="+escape(fwName)+"&startDate="+escape(startDate)+"&selectedNights="+escape(nights)+"&selectedLocation="+escape(selectedLocation));
}

function slider(attach, bar, handle, text, min, max, initial, unit, pos)
{
	this.slider	= $(attach);
	this.bar 	= $(bar);
	this.handle = $(handle);
	this.text 	= $(text);
	
	this.lastPos = 0;
	this.mousedown = 0;
	this.unit = (unit) ? unit : '';
	this.pos = (pos) ? pos : '';
	
// 	this.bar.style.position= "absolute";
// 	this.bar.style.display= "block";
// // 	this.bar.style.display= "block";
// 	alert(this.bar.offsetWidth);
// // 
// 	
// 	this.bar.style.position= "relative";
	
	initial = (initial && initial > 0) ? initial : max;
	this.maxmove = this.bar.offsetWidth - this.handle.offsetWidth;
	
	


	// FIX ME - HACK!!!
	this.move = 0;
	this.text.innerHTML = "10 mile";
	this.slider.value = 10;
	
	this.move = (initial) ? (((initial - min) * this.maxmove)/(max-min)) : 0;

	
	setMargin(this.handle, null, null, null, this.move, 'px');

	var othis = this;

	this.slider.onmouseup = function()
	{
		othis.mousedown = 0;
		othis.validate();

		if(document.documentElement)
		{
			document.documentElement.onmouseup = function(){}
			document.documentElement.onmousemove = function(){}
		}
	}

	this.bar.onmouseover = function()
	{
		othis.mouseover = 1;
	}

	this.bar.onmouseout = function()
	{
		othis.mouseover = 0;
	}

	this.handle.onmousedown = function(evt)
	{
		var evt = (evt) ? evt : ((window.event) ? event : null);

		othis.mousedown = 1;
		othis.lastPos = evt.clientX;
		othis.lastTop = evt.y;

		if(document.documentElement)
		{
			document.documentElement.onmouseup = function(){othis.slider.onmouseup();}
			document.documentElement.onmousemove = function(event){othis.mouseMove(event);}
		}

	}

	this.mouseMove = function(evt)
	{
		var evt = (evt) ? evt : ((window.event) ? event : null);

		if(this.mousedown > 0 && this.mouseover > 0)
		{
			this.move += (evt.clientX - this.lastPos);
			this.lastPos = evt.clientX;
//			evt.y = this.lastTop;

			this.setLimits();
			setMargin(this.handle, null, null, null, this.move, 'px');
			this.calculateValues();
//			evt.preventDefault();
		}
	}

	this.calculateValues = function()
	{
		this.maxmove = this.bar.offsetWidth - this.handle.offsetWidth;
		if(this.maxmove > 0)
		{
			this.slider.value = Math.round((((max-min) * this.move) / this.maxmove) + min);
			var text = (this.pos == 0) ? this.unit + ' ' + this.slider.value : this.slider.value + ' ' + this.unit;
			if(this.slider.value == max){this.slider.value = -1;}
			setHtml(this.text, text);
		}
	}

	this.setLimits = function()
	{
		if(this.move > this.maxmove){this.move = this.maxmove;}
		if(this.move < 0){this.move = 0;}
	}
	
	this.validate = function()
	{
	}

	this.calculateValues();
}


function jsHideAffiliateAd()
{
	var ajax = new jsAjaxEngine('');
	ajax.stateChanged = function()
	{
		$('widgetadvertclose').hide();
		$('widgetadvert').hide();
	}

	ajax.fire('ajax_hide_affiliate_ad.php');
}

function locationAfterUpdate(text, li) 
{
	if(li.id > -1)
	{
		jsSearchSuppliers(li.id);
	}
}

function jsSortResults(criteria, direction)
{
	
	showWaitMsg("Now Loading...");
	jQuery.ajax({
		url: '/library/ajax/ajax_sort_results.php?sort_criteria=' + criteria + '&sort_direction=' + direction,
		type: 'GET',
		dataType: 'json',
		error: function(){
			hideWaitMsg(1);
		},
		success: function(json){
			hideWaitMsg(1);

			setTimeout(function (){
				jQuery("#divSearchResults").html(json.searchResult);
			}, 200);
		}
	});

/*
	new Ajax.Request('/library/ajax/ajax_sort_results.php?sort_criteria=' + criteria + '&sort_direction=' + direction, {
		method: 'get',
	  	parameters: {},
		onSuccess: function(transport) {
			hideWaitMsg(1);
			var json = eval('('+transport.responseText+')'); 
			setTimeout(function (){jQuery("#divSearchResults").html(json.searchResult);}, 200);
		},
		onFailure: function(){
			hideWaitMsg(1);
		}
	});
	*/
	/*
	displayWaitingPicture('divSupplierResults', 10);

	jsSetAjax('divSearchResults', 'ajax_sort_results.php?sort_criteria=' + criteria + '&sort_direction=' + direction);
	*/
}

function jsLocationSearchOnFocus()
{
// 	alert('focus');
	if($('txtSearch').value == "e.g., 'new york, us'")
	{
		$('txtSearch').value = "";
		$('txtSearch').removeClassName('suggest_pretext');
	}
}

function jsLocationSearchOnBlur()
{
// 	alert('blur');
	if($('txtSearch').value ==  "")
	{
		$('txtSearch').value = "e.g., 'new york, us'";
		$('txtSearch').addClassName('suggest_pretext');
	}
}

/*
function jsOpenCVV(object)
{
	var ajax = new jsAjaxEngine('pop_up');

	ajax.stateChanged = function()
	{
		setSize(getObject('pop_up'), 300, 158);
		showPopUp(true, object);
	}

	ajax.fire('ajax_open_cvv.php');
}
*/

/*
function jsOpenTaxesFees(object)
{
	//TODO:Do not have Spec.
	if(true){
		return false;
	}
	var ajax = new jsAjaxEngine('pop_up');

	ajax.stateChanged = function()
	{
		setSize(getObject('pop_up'), 500, 480);
		showPopUp(true, object);
	}

	ajax.fire('ajax_open_taxes_fees.php');
}
*/
function jsGotoBookingDetailPage(url){
	var totalPrice = jQuery("#divsummarytotal").text();
	totalPrice = totalPrice.replace(/(^\s*)|(\s*$)/g, ""); 
	totalPrice = totalPrice.substring(1);
	if(parseInt(totalPrice) > 0){
		var selCurrencies = jQuery("#selCurrencies");
		var currencyHtml = '';
		if(selCurrencies.val()!=null){
			currencyHtml += '&selectCurrency='+selCurrencies.val();
		}
		window.location = url+currencyHtml;
	}else {
		alert("Please select room!");
	}
}

function jsSubmitCustomerInformation(){
	
	jQuery(".errorMessage").each(
		function(){
			jQuery(this).css({"display":"none"});;
		}
	);
	//jsUpdateCustomer();
	//jsUpdateCreditCard();
	jsUpdateAndCheckBookingInfo();
}

function trim(src){
	return src == null ? "" : src.replace(/(^\s*)|(\s*$)/g, "");
}

function jsUpdateAndCheckBookingInfo()
{
	showPopUp(false);
	showWaitMsg("Check Booking Info");
	//----------------- customer info --------------------
	var txtFirstName = encodeURI( trim( getObjectValue('txtFirstName') ) );
	var txtLastName = encodeURI( trim( getObjectValue('txtLastName') ) );
	var txtGender = encodeURI( trim( getObjectValue('hidCender') ) );
	var txtArrivalTime = encodeURI( trim( getObjectValue('selArrivalTime') ) );
	var txtContactEmail = encodeURI( trim( getObjectValue('txtContactEmail') ) );
	var txtConfirmEmail = encodeURI( trim( getObjectValue('txtConfirmEmail') ) );

	var checkbox = getObject('chkTC');
	var v1 = (checkbox && checkbox.checked) ? '1' : '0';
	checkbox = getObject('chkFacebook');
	var v2 = (checkbox && checkbox.checked) ? '1' : '0';
	checkbox = getObject('chkPolicies');
	var v3 = (checkbox && checkbox.checked) ? '1' : '0';

	var txtAddress1 = encodeURI( trim( getObjectValue('txtAddress1') ) );
	var txtAddress2 = encodeURI( trim( getObjectValue('txtAddress2') ) );
	var txtCity = encodeURI( trim( getObjectValue('txtCity') ) );
	var txtZip = encodeURI( trim( getObjectValue('txtZip') ) );
	var txtPhone = encodeURI( trim( getObjectValue('txtPhone') ) );
	var txtCountry = encodeURI( trim( getObjectValue('selCountry') ) );
	var txtReason = encodeURI( trim( getObjectValue('selReason') ) );
	var txtState = encodeURI( trim( getObjectValue('txtState') ) );
	
	var countryId = txtCountry.split("-")[0];
	var countryCode = txtCountry.split("-")[1];
	
	if(countryCode == 'US'||countryCode == 'CA'||countryCode == 'AU'){
		txtState = jQuery("#selState"+countryCode).val(); 
	}
	//----------------- card info --------------------
	var txtHolderName = encodeURI( trim( getObjectValue('txtCCHolderName') ) );
	
	
	var txtNumber = encodeURI( trim( getObjectValue('txtCCNumber') ) );
	var selType = encodeURI( trim( getObjectValue('selCCType') ) );
	var selMonth = encodeURI( trim( getObjectValue('selCCMonth') ) );
	var selYear = encodeURI( trim( getObjectValue('selCCYear') ) );
	var txtCvv = encodeURI( trim( getObjectValue('txtCCCvv') ) );

	jQuery.ajax({
		url:  ajax_path + 'ajax_update_and_check_booking_info.php?sid=' + SUPPLIER_ID 
			+'&fn=' + txtFirstName + '&ln=' + txtLastName + '&g=' + txtGender + '&at=' + txtArrivalTime 
			+ '&e1=' + txtContactEmail + '&e2=' + txtConfirmEmail + '&tc=' + v1 + '&f=' + v2 + '&tps=' + v3
			+ '&ad1=' + txtAddress1 + '&ad2=' + txtAddress2 + '&cti=' + txtCity + '&zc=' + txtZip 
			+ '&cty=' + countryId + '&tp=' + txtPhone + '&rf=' + txtReason + '&st=' + txtState 
			+ '&h=' + txtHolderName 
			+ '&n=' + txtNumber + '&t=' + selType + '&m=' + selMonth + '&y=' + selYear + '&c=' + txtCvv ,
		type: 'GET',
		//dataType: 'json',
		error: function(){
			hideWaitMsg(1);
		},
		success: function(response){
			var arrErrors = response.split(",");
			if(arrErrors == null || arrErrors == "" || arrErrors.length==0){
				showWaitMsg("Create Booking");
				jsCreateBooking(supplierAggregatorId);
			}else{
				hideWaitMsg(1);
				var isAlert = false;
				for(i = 0; i < arrErrors.length; i++){
					var result = arrErrors[i];
					result = result.replace(/(^\s*)|(\s*$)/g, ""); 
					if(result!=""){
						var arrValue = result.split("=");
						arrValue[0] = arrValue[0].replace(/(^\s*)|(\s*$)/g, ""); 
						arrValue[1] = arrValue[1].replace(/(^\s*)|(\s*$)/g, ""); 
						if(arrValue[1]=="F"){
							if(arrValue[0] == "Select Rooms"){
								isAlert = true;
							} else if(arrValue[0] == "Agreed terms and conditions"){
								jQuery("#errorMessage-chkTC").css({"display":"block"});
								jQuery("#errorMessage-chkTC").html("You must agree terms and conditions");
							} else if(arrValue[0] == "Agreed Policies"){
								jQuery("#errorMessage-chkPolicies").css({"display":"block"});
								jQuery("#errorMessage-chkPolicies").html("You must agree policies");
							} else if(arrValue[0] == "Expiration"){
								jQuery("#errorMessage-expiration").css({"display":"block"});
								jQuery("#errorMessage-expiration").html("Expiration is invalid"); 
							} else if(arrValue[0] == "Gender"){
								jQuery("#errorMessage-hidCender").css({"display":"block"});
								jQuery("#errorMessage-hidCender").html("Please select Gender"); 
							} else if(arrValue[0] == "Contact Email"){
								jQuery("#errorMessage-txtContactEmail").css({"display":"block"});
								if(trim( getObjectValue('txtContactEmail') )!=""){
									jQuery("#errorMessage-txtContactEmail").html("Please enter a valid email"); 
								}else{
									jQuery("#errorMessage-txtContactEmail").html("Please enter contact email"); 
								}
							} else if(arrValue[0] == "Confirm Email"){
								jQuery("#errorMessage-txtConfirmEmail").css({"display":"block"});
								if(trim( getObjectValue('txtConfirmEmail') )!=""){
									jQuery("#errorMessage-txtConfirmEmail").html("Please enter a valid email"); 
								}else{
									jQuery("#errorMessage-txtConfirmEmail").html("Please enter confirm email"); 
								}
							} else if(arrValue[0] == "Same Email"){
								jQuery("#errorMessage-txtConfirmEmail").css({"display":"block"});
								jQuery("#errorMessage-txtConfirmEmail").html("Please enter the same email"); 
							} else if(arrValue[0] == "CardHolder Invalid"){
								jQuery("#errorMessage-txtCCHolderName").css({"display":"block"});
								jQuery("#errorMessage-txtCCHolderName").html("Please enter Name on card"); 
							} else if(arrValue[0] == "Card Type"){
								if(trim(jQuery("#txtCCNumber").val())!=''){
									jQuery("#errorMessage-selCCType").css({"display":"block"});
									jQuery("#errorMessage-selCCType").html("Please select correct credit card type"); 
								}
							}
							else {
								var errMessage = "Please enter ";
								var func = function(){
									var errObj = jQuery("#errorMessage-"+jQuery(this).attr("id"));
									var label = jQuery(errObj.next().children(".billingtableleft > .bookinglabel").html()).filter(".bookinglabel").text();
									label = label.substring(0, label.indexOf(':'));
									if(label == arrValue[0]){
										errObj.css({"display":"block"});
										errObj.html( errMessage + label);
									}
								};
								jQuery("#fPaymentDetails input").each(func);
								var errMessage = "Please select ";
								jQuery("#fPaymentDetails select").each(func);
							}
						}
					}
				}
				
				if(isAlert){
					alert("Please select room.");
				}
			}
		}
	});

/*
	new Ajax.Request( ajax_path + 'ajax_update_and_check_booking_info.php?sid=' + SUPPLIER_ID 
			+'&fn=' + txtFirstName + '&ln=' + txtLastName + '&g=' + txtGender + '&at=' + txtArrivalTime 
			+ '&e1=' + txtContactEmail + '&e2=' + txtConfirmEmail + '&tc=' + v1 + '&f=' + v2
			+ '&ad1=' + txtAddress1 + '&ad2=' + txtAddress2 + '&cti=' + txtCity + '&zc=' + txtZip 
			+ '&cty=' + txtCountry + '&tp=' + txtPhone + '&rf=' + txtReason + '&h=' + txtHolderName 
			+ '&n=' + txtNumber + '&t=' + selType + '&m=' + selMonth + '&y=' + selYear + '&c=' + txtCvv , {

			method: 'get',
			parameters: {},
			onSuccess: function(transport) {
				hideWaitMsg();
				var arrErrors = transport.responseText.split(",");
				if(arrErrors == null || arrErrors == "" || arrErrors.length==0){
					jsCreateBooking(SUPPLIER_ID);
				}else{
					for(i = 0; i < arrErrors.length; i++){
						var result = arrErrors[i];
						result = result.replace(/(^\s*)|(\s*$)/g, ""); 
						if(result!=""){
							var arrValue = result.split("=");
							if(arrValue[1]=="F"){
								if(arrValue[0] == "Agreed terms and conditions"){
									jQuery("#errorMessage-chkTC").css({"display":"block"});
									jQuery("#errorMessage-chkTC").html("You must agree terms and conditions");
								}if(arrValue[0] == "Expiration"){
									jQuery("#errorMessage-expiration").css({"display":"block"});
									jQuery("#errorMessage-expiration").html("Expiration is invalid"); 
								}if(arrValue[0] == "Gender"){
									jQuery("#errorMessage-hidCender").css({"display":"block"});
									jQuery("#errorMessage-hidCender").html("Please select Gender"); 
								}if(arrValue[0] == "Same Email"){
									jQuery("#errorMessage-txtContactEmail").css({"display":"block"});
									jQuery("#errorMessage-txtContactEmail").html("Please enter same emails."); 
								}else{
									var errMessage = "Please enter ";
									var func = function(){
										var errObj = jQuery("#errorMessage-"+jQuery(this).attr("id"));
										var label = jQuery(errObj.next().children(".billingtableleft > .bookinglabel").html()).filter(".bookinglabel").text();
										label = label.substring(0, label.indexOf(':'));
										if(label == arrValue[0]){
											errObj.css({"display":"block"});
											errObj.html( errMessage + label);
										}
									};
									jQuery("#fPaymentDetails input").each(func);
									var errMessage = "Please select ";
									jQuery("#fPaymentDetails select").each(func);
								}
							}
						}
					}
				}
			},
			onFailure: function(transport){
				hideWaitMsg();
				// handle here
				alert(transport.responseText);
			}
		});
		*/
}

function jsCreateBooking(said)
{
//	jQuery("#btnCompare a").unbind('click');
	jQuery.ajax({
		url:  ajax_path + 'ajax_create_booking.php?said=' + said ,
		type: 'GET',
		timeout: 60000,
		//dataType: 'json',
		error: function(response, error){
//			jQuery("#btnCompare a").bind('click', function (){
//				jsSubmitCustomerInformation();
//				return false;
//			});
			hideWaitMsg(1);
			if (error == "timeout") {
				alert("The request timed out, please resubmit");
			} else {
				alert("ERROR: " + error);
			}

		},
		success: function(response){
//			jQuery("#btnCompare a").bind('click', function (){
//				jsSubmitCustomerInformation();
//				return false;
//			});
			hideWaitMsg();
            var result = response.replace(/(^\s*)|(\s*$)/g, ""); 
            var json = eval('('+result+')')
            
			if(json.bookingResult == 'BooKinG DonE')
			{
				// REDIRECT  TO THE CONFIRMATION PAGE...
				window.location = "confirmation?"+"bookingIds="+json.bookingIds;
			} else if(json.bookingResult == 'Session Expired'){
				alert("Session expired, please re-select a hotel!");
				window.location = "search";
			} else if(json.bookingResult.indexOf("Booking Error:")>=0){
				if(json.lastErrorMessage != null && json.lastErrorMessage != ""){
					alert("Booking Error: "+json.lastErrorMessage);
				}else{
					alert("Booking error, please try again!");
				}
			} else {
				alert("Unknown exception: please try again!");
			}
		}
	});
	
	
/*
	new Ajax.Request( ajax_path + 'ajax_create_booking.php?sid=' + sid , {
			method: 'get',
			parameters: {},
			onSuccess: function(transport) {
				hideWaitMsg();
				var result = transport.responseText.replace(/(^\s*)|(\s*$)/g, ""); 
				if(result == 'BooKinG DonE')
				{
					// REDIRECT  TO THE CONFIRMATION PAGE...
					window.location = "confirmation";
				}
			},
			onFailure: function(transport){
				hideWaitMsg();
				// handle here
				alert(transport.responseText);
			}
	});
	*/
}

function jsChangeSearchPriceRange(minPrice, maxPrice)
{
	showWaitMsg("Now Loading...");
	jQuery.ajax({
		url: '/library/ajax/ajax_change_price_range.php?p=' + 1 + '&minPrice=' + minPrice + '&maxPrice=' + maxPrice + '&isSearchPage=1',
		type: 'GET',
		dataType: 'json',
		error: function(){
			hideWaitMsg(1);
		},
		success: function(json){
			hideWaitMsg(1);
			setTimeout(function (){jQuery("#divSearchResults").html(json.searchResult);}, 200);
		}
	});
}

function jsChangeRoomPriceRange(minPrice, maxPrice)
{

	
	var oid = 'divAvailability';

	displayWaitingPicture(oid);

	jQuery.ajax({
		url: '/library/ajax/ajax_change_price_range.php?sid=' + SUPPLIER_ID + '&minPrice=' + minPrice + '&maxPrice=' + maxPrice + '&isSearchPage=0',
		type: 'GET',
		dataType: 'json',
		//data: {c: cnt, type: property_type, d: checkinDateFormatted, n: nights, p: people, radius: radius},
		error: function(){
			//hideWaitMsg(1);
		},
		success: function(json){	
			var t = setTimeout("resizeInformationDiv();", 500);
			jQuery("#divAvailability").html(json.roomAvailability);
		}
	});

/*	
	jQuery(".roompricerow").each(
		function(){
			var displayPrice = jQuery(this).children().html();
			symbol = displayPrice.split(' ')[0];
			var price = displayPrice.split(' ')[1];
			var tempPrice = price.replace(/[,]/g,'');
			if(parseInt(minPrice) > parseInt(tempPrice) || parseInt(maxPrice) < parseInt(tempPrice)){
				jQuery(this).parent().css({"display":"none"});
			}else{
				jQuery(this).parent().css({"display":""});
			}
			//alert(displayPrice+' , '+price+' , '+ (parseInt(minPrice) > parseInt(price))+' , '+(parseInt(maxPrice) < parseInt(price))+' , '+ minPrice+' , '+maxPrice);
		}
	);
*/
}

function cancelCheckAll(){
	jQuery('#All').attr('checked', false);
}

function jsChangeSupplierInfo(tabIndex){
	if (tabIndex == 1)	{
		jQuery("#infoTab").attr({"class":"infoTab"});
		jQuery("#directionTab").attr({"class":"directionTabUnselected"});
		jQuery("#hotelPolicyTab").attr({"class":"hotelPolicyTabUnselected"});
		jQuery("#divInfoAndFacilities").css({"display":""});
		jQuery("#divDirections").css({"display":"none"});
		jQuery("#divHotelPolicy").css({"display":"none"});
	}else if(tabIndex == 2){
		jQuery("#infoTab").attr({"class":"infoTabUnselected"});
		jQuery("#directionTab").attr({"class":"directionTab"});
		jQuery("#hotelPolicyTab").attr({"class":"hotelPolicyTabUnselected"});
		jQuery("#divInfoAndFacilities").css({"display":"none"});
		jQuery("#divDirections").css({"display":""});
		jQuery("#divHotelPolicy").css({"display":"none"});
		if(trim(jQuery("#map_canvas").html())==''){
			initializemap(); 
			setDirections(''+jQuery("#fromAddress").val(), jQuery("#toAddress1").val(), jQuery("#toAddress2").val(), jQuery("#toAddress3").val(), 'en');
		}
	}else if (tabIndex == 3)	{
		jQuery("#infoTab").attr({"class":"infoTabUnselected"});
		jQuery("#directionTab").attr({"class":"directionTabUnselected"});
		jQuery("#hotelPolicyTab").attr({"class":"hotelPolicyTab"});
		jQuery("#divInfoAndFacilities").css({"display":"none"});
		jQuery("#divDirections").css({"display":"none"});
		jQuery("#divHotelPolicy").css({"display":""});
	}
}

function showStateSelect(value){
	
	var countryId = value.split("-")[0];
	var countryCode = value.split("-")[1];
	jQuery(".divStateSelect").each(
		function(){
			jQuery(this).css({"display":"none"});
		}
	);
	if(countryCode == 'US'||countryCode == 'CA'||countryCode == 'AU'){
		jQuery("#divselState"+countryCode).css({"display":""});
		jQuery("#txtState").css({"display":"none"});
	}else{
		jQuery("#txtState").css({"display":""});
	}
}

var selectStateValue = null;
function selectStateItem(value){
	selectStateValue = value;
}
