/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

function isValidDate(dateStr) {
// Date validation function courtesty of 
// Sandeep V. Tamhankar (stamhankar@hotmail.com) 
// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; // requires 4 digit year

var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert(dateStr + " Date is not in a valid format.")
return false;
}
month = matchArray[3]; // parse date into variables
day = matchArray[1];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
alert("Month must be between 1 and 12.");
return false;
}
if (day < 1 || day > 31) {
alert("Day must be between 1 and 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("Month "+month+" doesn't have 31 days!")
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)) {
alert("February " + year + " doesn't have " + day + " days!");
return false;
   }
}
return true;
}

function isValidTime(timeStr) {
// Time validation function courtesty of 
// Sandeep V. Tamhankar (stamhankar@hotmail.com) -->

// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

var matchArray = timeStr.match(timePat);
if (matchArray == null) {
alert("Time is not in a valid format.");
return false;
}
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];

if (second=="") { second = null; }
if (ampm=="") { ampm = null }

if (hour < 0  || hour > 23) {
alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
return false;
}
if (hour <= 12 && ampm == null) {
if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
alert("You must specify AM or PM.");
return false;
   }
}
if  (hour > 12 && ampm != null) {
alert("You can't specify AM or PM for military time.");
return false;
}
if (minute < 0 || minute > 59) {
alert ("Minute must be between 0 and 59.");
return false;
}
if (second != null && (second < 0 || second > 59)) {
alert ("Second must be between 0 and 59.");
return false;
}
return true;
}

function dateDiff( firstdate, seconddate ) {
var temp   = firstdate.split( "/" );
var a      = new Date(temp[2],temp[1],temp[0]);
    temp   = seconddate.split("/");
var b      = new Date(temp[2],temp[1],temp[0]);
var oneday = 86400000;
var days   = Math.ceil( ( b - a ) / ( oneday ) );
return days;
}
/******************
/* When the page is fully loaded  */
jQuery(document).ready(function() {


	  var qs = new Querystring();
/*	  	  
	  $('a[href*=#]').click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
		&& location.hostname == this.hostname) {
		  var $target = $(this.hash);
		  $target = $target.length && $target
		  || $('[name=' + this.hash.slice(1) +']');
		  if ($target.length) {
			var targetOffset = $target.offset().top;
			$('html,body')
			.animate({scrollTop: targetOffset}, 1000);
		   return false;
		  }
		}
	  });
*/
 var myTextExtraction = function( node )
 {
 var $n = $( node );
 // extract data from markup and return it
 var $r = $n.find( ".sortbyPrice" );
 if ( $r.length > 0 ) { return $r.html( ); } else { return $n.html( ); }
 };

 if( $('#so_Cyprus').length && $('#so_Cyprus:has(tbody tr td.tabledata)').length){
	{$('#so_Cyprus:has(tbody tr)').tablesorter({ debug: false, sortList: [ [ 0, 0 ] ], textExtraction: myTextExtraction});}
 }else { 
 	$("table[id^=so_Cyprus]").remove();
 }
 if( $('#so_Egypt').length  && $('#so_Egypt:has(tbody tr td.tabledata)').length){	 
	$('#so_Egypt:has(tbody tr)').tablesorter({ debug: false, sortList: [ [ 0, 0 ] ], textExtraction: myTextExtraction});
 }else{
	$("table[id^=so_Egypt]").remove();
}
 if( $('#so_Greece').length && $('#so_Greece:has(tbody tr td.tabledata)')){
	 $('#so_Greece:has(tbody tr)').tablesorter({ debug: false, sortList: [ [ 0, 0 ] ], textExtraction: myTextExtraction});
 }else{
   	 $("table[id^=so_Greece]").remove();
 }
	
	if( $( "div.loading-results" ).length ){ $( "div.loading-results" ).each(function(){ $(this).remove(); }); }
	initBookingDates();

	/* get value from query string */
	
	
/*		
	var dfrom = new Date();
	var dto   = new Date();
		
	var dfromstr = dfrom.format("%DD") + "/" + dfrom.format("%MM") + "/" + dfrom.format("%YYYY");
	var dtostr = dto.format("%DD") + "/" + dto.format("%MM") + "/" + dto.format("%YYYY");
	
	if( (document.getElementById("search_checkin_date") != null) && (document.getElementById("search_checkin_date") == "") ) { 

		if( document.getElementById("search_checkin_date") != null) { document.getElementById("search_checkin_date").value = dfromstr; }
		
		if( document.getElementById("search_checkout_date") != null) { 
			document.getElementById("search_checkout_date").value = dtostr; 
			
			changecheckout_date();
			
		}
	}
*/
		var srchcntry = document.getElementById( 'search_country' );
		if( ( srchcntry != null ) && ( document.getElementById( 'search_searchby' ) != null ) ) {
			loadCountryList();
			loadDestinationList();		
			$( '#search_hotel' ).ajaxStop( function(){ loadHotelList(); });																 
			/*
			  var qs = new Querystring();
			  if(qs.contains("search_country")){
				var Value = qs.get("search_country","CYP");
				var index;
				for(index = 0; index < sc.length; index++) {
					if(sc[index].value == Value){
						sc.selectedIndex = index;
						alert(index);
					}
				}						
			} */
		}
	
//	checkSearchBy();

	offersSearchDates();
	
});

function initBookingDates(){
	var checkin_date_id;  
	var checkout_date_id; 
	
	if( $("#pageid").length > 0 ){
		checkin_date_id  = "checkin_date";
		checkout_date_id = "checkout_date";	
	}
	else{
		checkin_date_id  = "search_checkin_date";
		checkout_date_id = "search_checkout_date";			
	}
	var pickUpDate;
	$("#"+checkin_date_id).each( function(){ 
		if( $(this).is( ":not(:hidden)" ) ){ //alert("found"); 
		pickUpDate  = $(this); } 
	});
	if( pickUpDate ==  null ){ return; }
	
	var dropOffDate;
	$("#"+checkout_date_id).each( function(){ 
		if( $(this).is( ":not(:hidden)" ) ){ //alert("found1"); 
		dropOffDate = $(this); } 
	});
	if( dropOffDate ==  null ){ return; }

	if(!pickUpDate.length) {
		//alert('null');
		pickUpDate  = $(document.getElementById(checkin_date_id));
		alert(pickUpDate.value);
		if(pickUpDate){return;}
		//pickUpDate  = $(pickUpDate);
	}
	if(!dropOffDate.length){
		//alert('null1');
		dropOffDate = $(document.getElementById(checkout_date_id));
		alert(dropOffDate.value);
		if(dropOffDate){return;}
		//dropOffDate = $(dropOffDate);
	}
	if(pickUpDate.length || pickUpDate)
	{
		//dp_cal  = new Epoch('epoch_popup','popup',document.getElementById('search_checkin_date'));
		var todaysdate = new Date();
		pickUpDate.datepicker({
							 mandatory:  true,
							 minDate: 	 new Date( todaysdate.getFullYear(), todaysdate.getMonth(), todaysdate.getDate() ),
							 maxDate:    new Date( todaysdate.getFullYear() + 1, 11, 31 ),
							 yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,
							 dateFormat: 'dd/mm/yy',
							 speed: '',
							 onSelect: function(dateText){ 
											if ( dropOffDate.length ){  
												var new_date  = new Date();										 			
												var datearray = dateText.split("/");															
												new_date.setFullYear( datearray[ 2 ], datearray[ 1 ] - 1, datearray[ 0 ] );
												new_date.setDate( new_date.getDate() + 5 );
												//TODO find a better way to do the next line, since we already have reference to it through $ var.
												document.getElementById( checkout_date_id ).value = dateFormat( new_date, "%DD/%MM/%YYYY" );
												dropOffDate.datepicker( "disable" ); //hack to avoid showing the datepicker on setDate
												dropOffDate.datepicker( "setDate", new_date );
												dropOffDate.datepicker( "enable" ); //hack to avoid showing the datepicker on setDate							
											}
										}
							 });
	}
	if(dropOffDate.length || dropOffDate)
	{
		dropOffDate.datepicker({
							   mandatory:  true,
							   minDate:    new Date( todaysdate.getFullYear(),     todaysdate.getMonth(), todaysdate.getDate() ),
							   maxDate:    new Date( todaysdate.getFullYear() + 1, 11, 31 ),											
							   yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,
							   dateFormat: 'dd/mm/yy', 
							   speed: ''
							  });		
	}	
}
function initSpecialOfferBookingDates(pickUpDate,dropOffDate){
	//var pickUpDate  = $("#search_checkin_date");
//	var dropOffDate = $("#search_checkout_date");
	var checkin_date_id;  
	var checkout_date_id; 
	
	if( $("#pageid").length > 0 ){
		checkin_date_id  = "checkin_date";
		checkout_date_id = "checkout_date";	
	}
	else{
		checkin_date_id  = "search_checkin_date";
		checkout_date_id = "search_checkout_date";			
	}
	if(pickUpDate.length)
	{
		//dp_cal  = new Epoch('epoch_popup','popup',document.getElementById('search_checkin_date'));
		var todaysdate = new Date();
		pickUpDate.datepicker({
							 mandatory:  true,
							 minDate: 	 new Date( todaysdate.getFullYear(), todaysdate.getMonth(), todaysdate.getDate() ),
							 maxDate:    new Date( todaysdate.getFullYear() + 1, todaysdate.getMonth(), todaysdate.getDate() ),
							 yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,
							 dateFormat: 'dd/mm/yy',
							 speed: '',
							 onSelect: function(dateText){ 
											if ( dropOffDate.length ){  
												var new_date  = new Date();										 			
												var datearray = dateText.split("/");															
												new_date.setFullYear( datearray[ 2 ], datearray[ 1 ] - 1, datearray[ 0 ] );
												new_date.setDate( new_date.getDate() + 5 );
												//TODO find a better way to do the next line, since we already have reference to it through $ var.
												document.getElementById( checkout_date_id ).value = dateFormat( new_date, "%DD/%MM/%YYYY" );
												dropOffDate.datepicker( "disable" ); //hack to avoid showing the datepicker on setDate
												dropOffDate.datepicker( "setDate", new_date );
												dropOffDate.datepicker( "enable" ); //hack to avoid showing the datepicker on setDate							
											}
										}
							 });
	}
	if(dropOffDate.length)
	{
		dropOffDate.datepicker({
							   mandatory:  true,
							   minDate:    new Date( todaysdate.getFullYear(),     todaysdate.getMonth(), todaysdate.getDate() ),
							   maxDate:    new Date( todaysdate.getFullYear() + 1, todaysdate.getMonth(), todaysdate.getDate() ),											
							   yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,
							   dateFormat: 'dd/mm/yy', 
							   speed: ''
							  });		
	}	
}
function togglediv(szDivID, iState) // 1 visible, 0 hidden
{    
	if(document.layers)    //NN4+
    {
       document.layers[szDivID].visibility = iState ? "show" : "hide";
    }
    else if(document.getElementById)      //gecko(NN6) + IE 5+
    {
        var obj = document.getElementById(szDivID);
        obj.style.visibility = iState ? "visible" : "hidden";
    }
    else if(document.all)       // IE 4
    {
        document.all[szDivID].style.visibility = iState ? "visible" : "hidden";
    }
}

function loopSelected(myList)
{
  /* Count selected  */
  var selObj = document.getElementById(myList);
    
  var i;
  var count = 0;
  for (i=0; i<selObj.options.length; i++) {
    if ((selObj.options[i].selected) && (selObj.options[i].value != "")) {
      count++;
    }
  }
  return count;
}
function showselected(myList)
{
 
  var selObj = document.getElementById(myList);
    
  var i;
  for (i=0; i<selObj.options.length; i++) {
    if ((selObj.options[i].selected) && (selObj.options[i].value != "")) {      
	  return selObj.options[i].value;
    }
  }
  //return selObj.options[i].value;
}

/* Scripts For the OnChange */
function removeAllOptions(selectbox)
{
	var sbox = document.getElementById(selectbox);
	if(sbox!=null){ sbox.length=0;}
	var i;
	for(i=sbox.options.length-1;i>=0;i--)
	{
		sbox.remove(i);
	}	
}

function addOption(selectbox, value, text )
{
    /* Function to Add Options in a List */
	var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

function selectOption(mySelect,myOption)
{
  
  var selObj = document.getElementById(mySelect);
  if(selObj == null){return;}
  var i;
  for (i=0; i<selObj.options.length; i++) {
    if (selObj.options[i].value == myOption ) {      
	  selObj.options[i].selected = true;
	  return true;
    }
  }
}

function selectDestination(myList,Destination)
{
  
  var selObj = document.getElementById(myList);
  
  var i;
  for (i=0; i<selObj.options.length; i++) {
    if (selObj.options[i].value == Destination ) {      
	  selObj.options[i].selected = true;
	  return true;
    }
  }
}



function changecheckout_date() {
	var checkin_date_id;  
	var checkout_date_id; 

	if( $("#pageid").length > 0 ){
		checkin_date_id  = "checkin_date";
		checkout_date_id = "checkout_date";
	}
	else{
		checkin_date_id  = "search_checkin_date";
		checkout_date_id = "search_checkout_date";
	}
	if(document.getElementById(checkin_date_id).value == "") {
		return true;
	}
	//else{alert(document.getElementById("search_checkin_date").value); }
	var dfrom = new Date();
	var dto = new Date();

	var new_date = new Date();

	var dfromstr = document.getElementById(checkin_date_id).value;

	var datearray = dfromstr.split("/");

	new_date.setFullYear(datearray[2],datearray[1]-1,datearray[0]);
	new_date.setDate(new_date.getDate()+5);
	//new_date = new_date.addDays(5);

	document.getElementById(checkout_date_id).value = new_date.format("%DD/%MM/%YYYY");
	jQuery("#"+checkout_date_id).datepicker("setDate",new_date);
}

function loadCountryList() {
	/*clear*/
	var search_destination = document.getElementById('search_destination');	
	if(search_destination){search_destination.length = 0;}	
	var search_hotel = document.getElementById('search_hotel');	
	if(search_hotel){search_hotel.length = 0;}
	
	var search_searchby = document.getElementById('search_searchby').value;	
	var qs = new Querystring();
	if ( search_searchby == "" || search_searchby == null ){ 
		/* try get it from query string */
		if ( qs.contains("search_searchby") == true ){
			search_searchby = qs.get("search_searchby");
		}
		return; 
	}		
	
	if (search_searchby == "country") {
		var sc = document.getElementById('submitedcountry');
		var sc_value;
		if( sc == null ) { 
			/* try get it from query string */
			if ( qs.contains("submitedcountry") == true ){
				sc_value = qs.get("submitedcountry");
			}
			else if( qs.contains("search_country") == true ){
				sc_value = qs.get("search_country");
			}
			sc_value = ""; 
		}
		else{ sc_value = sc.value; }
		jQuery("#search_country_div").html("<div style='text-align:left; width:100%;'><img src='/images2/smallloading.gif' alt='' /></div>");
		jQuery.post("loadcountrylist.html", 
			{ 
				submitedcountry:sc_value
			}, 
			function(data){ 
				jQuery("#search_country_div").html(data);
			} 
		);
	}
}

function loadDestinationList() {
	/* clear */
	var search_destination = document.getElementById('search_destination');	
	if(search_destination){search_destination.length = 0;}
/*	var search_destination = document.getElementById('search_destination').value;	
	search_hotel*/
	
//$('#search_destination').ajaxStop(function(){	 		
	var search_searchby = document.getElementById('search_searchby').value;	
	var qs = new Querystring();
	if ( search_searchby == "" || search_searchby == null ){ 
		/* try get it from query string */
		if ( qs.contains("search_searchby") == true ){
			search_searchby = qs.get("search_searchby");
		}
		//return; 
	}		
	var search_country_value;	
	if (search_searchby == "country") {	
		var search_country = document.getElementById( 'search_country' );
		if( search_country == null ){
			search_country = document.getElementById( 'submitedcountry' );
			if( search_country == null || search_country.value == ""){ 
			/* try get it from query string */
				if ( qs.contains("submitedcountry") == true ){
					search_country_value = qs.get("submitedcountry");
				}
				else if( qs.contains("search_country") == true ){
					search_country_value = qs.get("search_country");
				}	
				//else{return;} 
			}
			else{ search_country_value = search_country.value;}
		}else if ( search_country.selectedIndex && search_country.options[ search_country.selectedIndex ].value == "" ){
			search_country = document.getElementById( 'submitedcountry' );				
			if( search_country == null || search_country.value == ""){ 			
			/* try get it from query string */
				if ( qs.contains("submitedcountry") == true ){
					search_country_value = qs.get("submitedcountry");
				}
				else if( qs.contains("search_country") == true ){
					search_country_value = qs.get("search_country");
				}	
				//else{return;}
			}
			else{search_country_value = search_country.value;}
		}
		else{ if(search_country.selectedIndex){search_country_value = search_country.options[search_country.selectedIndex].value;} }
		if (search_country_value != "") {			
			var sc = document.getElementById('submiteddestination');
			var sc_value;
			if( sc == null ) { sc_value = ""; }
			else{ sc_value = sc.value; }				
		}
		jQuery("#search_destination_div").html("<div style='text-align:left; width:100%;'><img src='/images2/smallloading.gif' alt='' /></div>");
		jQuery.post("loaddestinationlist.html", 
			{ search_country:search_country_value,
			  submiteddestination:sc_value	
			}, 
			function(data){ 
				jQuery("#search_destination_div").html(data);
			} 
		);	
	}
//});
}

function loadHotelList() {
	/*clear*/
	var search_hotel = document.getElementById('search_hotel');	
	if(search_hotel){search_hotel.length = 0;}
//	$('#search_hotel').ajaxStop(function(){	 	
		var search_destination = document.getElementById('search_destination');	
		var search_country     = document.getElementById('search_country');					
		if(search_country == "" || search_country == null){		
			if( document.getElementById('submitedcountry') != null){
				if(document.getElementById('submitedcountry').value != "" || document.getElementById('submitedcountry').value != null  ){
					if(search_country){search_country.value = document.getElementById('submitedcountry').value;}
				}
			}
		}		
		if(search_destination == "" || search_destination == null){		
			if( document.getElementById('submiteddestination') != null){
				if(document.getElementById('submiteddestination').value != "" || document.getElementById('submiteddestination').value != null  ){
					if(search_destination){search_destination.value = document.getElementById('submiteddestination').value;}
				}
			}
		}
		var sc = document.getElementById('submitedhotel');
		var sc_value;
		if( sc == null ) { sc_value = ""; }
		else{ sc_value = sc.value; }				
		var search_country_value     = "";
		var search_destination_value = "";
		if(search_country){search_country_value=search_country.value;}
		if(search_destination){search_destination_value=search_destination.value;}
		//alert(" sc " + search_country.value + " sd " + search_destination.value + " sh " + sc_value);
		jQuery("#search_hotel_div").html("<div style='text-align:left; width:100%;'><img src='/images2/smallloading.gif' alt='' /></div>");
		jQuery.post("loadhotellist.html", 
			{ search_country:search_country_value, search_destination:search_destination_value,submitedhotel:sc_value }, 
			function(data){ 
				jQuery("#search_hotel_div").html(data);
			} 
		);
//	});
}

function checkSearchBy() {

	if(document.getElementById('formname') == null) {
		
		return false;
	}
	//alert("asd");
	
	for  (var i=0; i < document.getElementById('formname').form.search_searchby.length; i++) {
		if(document.getElementById('formname').form.search_searchby[i].checked == true) {
			search_searchby = document.getElementById('formname').form.search_searchby[i].value;				
		}
	}
	
	if (search_searchby == "country") {
		jQuery("#search_country_div").html("<div style='text-align:left; width:100%;'><img src='/images2/smallloading.gif' alt='' /></div>");
		jQuery.post("loadcountrylist.html", 
			{ }, 
			function(data){ 
				var selectedcountry = document.getElementById('submitedcountry').value;
				jQuery("#search_country_div").html(data);
				selectvaluefromlist("search_country",selectedcountry)
				jQuery("#search_traveltype_div").html("");
			} 
		);
	}		
	
	
	
	if(search_searchby == "traveltype") {
		jQuery("#search_traveltype_div").html("<div style='text-align:left; width:100%;'><img src='/images2/smallloading.gif' alt='' /></div>");
		jQuery.post("loadtraveltypelist.html", 
			{ }, 
			function(data){ 
				var selectedtraveltype = document.getElementById('submitedtraveltype').value;
				jQuery("#search_country_div").html("");
				jQuery("#search_destination_div").html("");
				jQuery("#search_hotel_div").html("");
				jQuery("#search_traveltype_div").html(data);
				selectvaluefromlist("search_holiday_type",selectedtraveltype)
				
			} 
		);
	}		
	
}
function selectvaluefromlist(myList,valuetoselect)
{
  
  var selectedObject = jQuery("#" + myList);
  
  var i;
  if(selectedObject.options == null){ return;}
  for (i=0; i < selectedObject.options.length; i++) {
    if (selectedObject.options[i].value == valuetoselect ) {      
	  selectedObject.options[i].selected = true;
	  return true;
    }
  }
}

//fromCalendar
function doSearchInHome(isFromCalendar) {
	var vdisabled = jQuery( "#image" ).attr( "disabled" );
	if(!vdisabled){
		jQuery( "#image" ).attr({ src: "/images2/submit_button_disabled.GIF",
								  alt: "waiting search to finish",
								  title:"please wait before searching again",
								  disabled: "disabled"
								}) ;
	}
	
	var valarray = isFromCalendar.split(":");
	if(valarray[1] == 'True' ){ 
		var iscalendar   = document.getElementById('isfromcalendar');
		iscalendar.value = 'True';
		var calhtl = document.getElementById('calendar_hotel');
		calhtl.value = valarray[0];
		document.searchinhome.action = '/hotels.html?href=#results-box-' + valarray[0];				
	}
	document.searchinhome.submit();		
}

function addRowClone( obj, tblId, htlUrl, htlCode )
{	
    var todaysdate = new Date();
	var $table      = $("#"+tblId);
    var $tableBody  = $("tbody",$table);	
   	var $currentRow = $(obj)	//this is click obj
	
	/*clear each rows style*/
	$("tr[id!=blankRow]",$table).each(function(){	 	
		if( $(this).attr("style")){ $(this).removeAttr("style"); }
	});
	
	/*set cyrrents row color*/
	$currentRow.css("background-color","#28A2B7");
	
   	//clear previous row from all tables that may have it.
	var $tables      = $("table[id^=so]");
	var $tableBodies = 
	$tables.each(function(){
		$( "#removeRow", $(this) ).remove( );
	});
	//$("#removeRow",$tableBody).remove();
	
   	//insert new one
    newRow = $("#blankRow",$tableBody).clone().insertAfter($currentRow).removeAttr("id").removeClass("striped").attr("style","width:100%;height:100%").attr("id","removeRow").show().find("td div").slideDown(200);	
    newRow.find("#checkin_date").attr( "id","search_checkin_date");
	newRow.find("#checkout_date").attr("id","search_checkout_date");
	
    $( "#searchinspecials", newRow ).attr("action",window.location.protocol + "//" + window.location.host + "/" + htlUrl );
    $( "#calendar_hotel"  , newRow ).val( htlCode );
	var dropOffDate = $("input#search_checkout_date" , newRow)
    $(function() {
    $("input#search_checkin_date" , newRow).datepicker({
							 //mandatory:  true,
							 minDate: 	 new Date( todaysdate.getFullYear(), todaysdate.getMonth(), todaysdate.getDate() ),
							 maxDate:    new Date( todaysdate.getFullYear() + 1, todaysdate.getMonth(), todaysdate.getDate() ),
							 yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,
							 dateFormat: 'dd/mm/yy',
							 //speed: '',
							 onSelect: function(dateText){ 
							 				if(dropOffDate.length){
												var new_date  = new Date();										 			
												var datearray = dateText.split("/");															
												new_date.setFullYear( datearray[ 2 ], datearray[ 1 ] - 1, datearray[ 0 ] );
												new_date.setDate( new_date.getDate() + 5 );
												//TODO find a better way to do the next line, since we already have reference to it through $ var.
												document.getElementById( "search_checkout_date" ).value = dateFormat( new_date, "%DD/%MM/%YYYY" );
												dropOffDate.datepicker( "disable" ); //hack to avoid showing the datepicker on setDate
												dropOffDate.datepicker( "setDate", new_date );
												dropOffDate.datepicker( "enable" ); //hack to avoid showing the datepicker on setDate																		
											}
										}
							 });
	});
	
	$(function() {
	$("input#search_checkout_date" , newRow).datepicker({
							   //mandatory:  true,
							   minDate:    new Date( todaysdate.getFullYear(),     todaysdate.getMonth(), todaysdate.getDate() ),
							   maxDate:    new Date( todaysdate.getFullYear() + 1, todaysdate.getMonth(), todaysdate.getDate() ),											
							   yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,
							   dateFormat: 'dd/mm/yy'
							   //speed: ''
							  });	    
    });
  	return false;
}
 
function doSearchInSpecialOffers( obj, tblId, htlUrl, htlCode ) {	
	addRowClone( obj, tblId, htlUrl, htlCode);    	
}

function doSearchInHotel( isFromCalendar ) {
		
	jQuery("#search-results").html("<div style='text-align:center; width:100%;'><img src='/images2/loadinga.gif' alt='' /></div>");
	
	var search_checkin_date  = document.getElementById('checkin_date').value;
	var search_checkout_date = document.getElementById('checkout_date').value;
	
	var search_country 		 = document.getElementById('search_country').value;
	var search_destination   = document.getElementById('search_destination').value;
	var search_hotel 		 = document.getElementById('search_hotel').value;
	//var search_children_ages = document.getElementById('search_children_ages').value;
	var search_num_children  = document.getElementById('search_num_children').value;
    var search_num_infants   = document.getElementById('search_num_infants').value;
	var search_num_adults    = document.getElementById('search_num_adults').value;
	var ses_id				 = document.getElementById('ses_id').value;
	var vdisabled = jQuery( "#image" ).attr( "disabled" );
	if(!vdisabled){
		jQuery( "#image" ).attr({ src: "/images2/submit_button_disabled.GIF",
								  alt: "waiting search to finish",
								  title:"please wait before searching again",
								  disabled: "disabled"
								}) ;
	}
	
	var valarray;
	var iscalendar;
	var iscal;
	if( isFromCalendar != null ){
		valarray = isFromCalendar.split( ":" );
		if(valarray != null){
			if( valarray[ 1 ] == 'True' ){
				iscalendar       = document.getElementById( 'isfromcalendar' );
				iscalendar.value = 'True';
				iscal = iscalendar.value;
			}
		}
	}
 	if( iscal == null ){ iscal = 'False'; }
	var request = jQuery.post("search_results.html",
		{
		ses_id: ses_id,
		search_country: search_country,
		search_destination: search_destination,
		search_hotel: search_hotel,
		search_num_children:search_num_children,
		search_num_adults:search_num_adults,
		search_num_infants:search_num_infants,
		search_checkin_date:search_checkin_date,
		search_checkout_date:search_checkout_date,
		isfromcalendar:iscal,
		stop:true
		},
		function(data){
			jQuery("#search-results").hide();
			jQuery("#search-results").html(data);
			jQuery("#search-results").slideDown();
			vdisabled = jQuery( "#image" ).attr( "disabled" );
			if(vdisabled){
				jQuery( "#image" ).removeAttr("disabled");
				jQuery( "#image" ).attr({
										  src: "/images2/submit_button.gif",
										  alt: "Search",
										  title:"Search"
										});
			}
		}
	);
}

function doSearch() {	
	//togglediv("loading-results",1);
	jQuery("#loading-results").html("<img src='/images2/loadinga.gif' alt='' />");
	isLivesearch = document.getElementById('search_livedata');

	search_country = document.getElementById('search_country').value;
	search_destination = document.getElementById('search_destination').value;
	search_hotel = document.getElementById('search_hotel').value;

	if(isLivesearch.checked == true) {

		jQuery.post("search_results.html",
			{ search_country: search_country,
			search_destination: search_destination,
			search_hotel: search_hotel,
			search_checkin_date:search_checkin_date,
			search_checkout_date:search_checkout_date
			},
			function(data){
				jQuery("#search-results").html(data);
			} 
		);
		
	}
	jQuery("#loading-results").html("");
	
}

function view_calendar( search_country, search_destination, search_hotel ) {
	
	jQuery("#hotel-calendar-"+search_hotel).html("<div style='text-align:center; width:100%;'><img src='/images2/loadinga.gif' alt='' /></div>");
	
	var search_checkin_date = document.getElementById('search_checkin_date').value;
	var search_checkout_date = document.getElementById('search_checkout_date').value;
	
	//var search_children_ages = document.getElementById('search_children_ages').value;
	var search_num_children = document.getElementById('search_num_children').value;
	var search_num_adults = document.getElementById('search_num_adults').value;
	

	var disabledSearch   = jQuery( "#image" ).attr( "disabled" );
	if(!disabledSearch){
		jQuery( "#image" ).attr({ src: "/images2/submit_button_disabled.GIF",
								  alt: "waiting search to finish",
								  title:"please wait before searching again",
								  disabled: "disabled"
								}) ;		
	}
	jQuery("#view_calendar_" + search_hotel).css("display","none");
	
	jQuery.post("hotel_calendar.html", 
		{	search_country: search_country,
			search_destination: search_destination, 
			search_hotel: search_hotel,			
			search_num_children:search_num_children,
			search_num_adults:search_num_adults, 
			search_checkin_date:search_checkin_date,
			search_checkout_date:search_checkout_date
		}, 
		function(data){ 			
			jQuery("#hotel-calendar-"+search_hotel).hide();
			jQuery("#hotel-calendar-"+search_hotel).html(data);
			jQuery("#hotel-calendar-"+search_hotel).slideDown();			
			
			disabledSearch   = jQuery( "#image" ).attr( "disabled" );
			if( disabledSearch ){
				jQuery( "#image" ).removeAttr("disabled");
				jQuery( "#image" ).attr({
										  src: "/images2/submit_button.gif",
										  alt: "Search",
										  title:"Search"
										}) ;
			}

		} 
	);
			
}
function toggleCal(search_country,search_destination,search_hotel) {	
	jQuery("#hotel-calendar-"+search_hotel).slideUp();
    jQuery("#view_calendar_" + search_hotel).css("display","inline");
}
function toggleRates(search_country,search_destination,search_hotel) {
	//jQuery("#hotel-calendar-"+search_hotel).toggle();
	jQuery("#hotel-rates-"+search_hotel).slideUp();
}
function new_checkin_date(newdate,search_country,search_destination,search_hotel) {
	
	document.getElementById('search_checkin_date').value = newdate;
	jQuery("#new_from_date_"+search_hotel).html("<blink><font color='red'>"+newdate+"</font></blink>");
	
	if(document.getElementById('calendar_hotel') != null) {
		document.getElementById('calendar_hotel').value = search_hotel;
	}
	
	//doSearchInHotel();
	//view_calendar(search_country,search_destination,search_hotel);
	//view_rates(search_country,search_destination,search_hotel);
	
}
function new_checkout_date(newdate,search_country,search_destination,search_hotel) {
	
	document.getElementById('search_checkout_date').value = newdate;
	var searchinwhere = document.getElementById('searchinwhere').value;

	
	jQuery("#new_to_date_"+search_hotel).html("<blink><font color='red'>"+newdate+"</font></blink>");
	
	jQuery("#new_viewrates_btn"+search_hotel).html("<a href=\"javascript:" + searchinwhere + "('" + search_hotel +":True');\"><img border='0' src='/images2/view_rates_button.gif' /></a>");
	
	if(document.getElementById('calendar_hotel') != null) {
		document.getElementById('calendar_hotel').value = search_hotel;
	}
	
	//doSearchInHotel();
	//view_calendar(search_country,search_destination,search_hotel)
	//view_rates(search_country,search_destination,search_hotel)
}


function view_rates( search_country, search_destination, search_hotel, g_ses_id, search_checkin_date,search_checkout_date, search_num_adults, search_num_children, search_children_ages,search_num_infants					){
	var htl_name;
	var htlcd;
	htlcd = search_hotel.replace( '-', '_' );
	htl_name = document.getElementById(htlcd).value;
		  
	jQuery("#hotel-rates-"+search_hotel).html("<div style='text-align:center; width:100%;'><img src='/images2/loadinga.gif' alt='' /></div>");
	
/*	var checkin_date = document.getElementById('search_checkin_date').value;
	var checkout_date = document.getElementById('search_checkout_date').value;
	
	var children_ages = document.getElementById('search_children_ages').value;
	var num_children = document.getElementById('search_num_children').value;
	var num_adults = document.getElementById('search_num_adults').value;*/

	/*
    jQuery( "input:hidden" ).each( function(){
		htl_name = jQuery( this ).val();
	});*/

  
	jQuery("#roomRateBasis" + htlcd).hide();

	var disabledSearch   = jQuery( "#image" ).attr( "disabled" );
	if(!disabledSearch){
		jQuery( "#image" ).attr({ src: "/images2/submit_button_disabled.GIF",
								  alt: "waiting search to finish",
								  title:"please wait before searching again",
								  disabled: "disabled"
								}) ;		
	}
	jQuery("#view_rates_" + search_hotel).css("display","none");
/*
	jQuery.post( "hotel_rates.html"
															, 
		{ ses_id:              g_ses_id,
		  search_country:      search_country,
		  search_destination:  search_destination, 
   		  search_hotel: 	   search_hotel,
		  hotel_name:		   htl_name,
		  search_children_ages:search_children_ages,
		  search_num_children: search_num_children,
   		  search_num_adults:   search_num_adults, 
		  search_checkin_date: search_checkin_date,
		  search_checkout_date:search_checkout_date
		}, 
		function(data){ 
		
			jQuery("#hotel-rates-"+search_hotel).hide();
			jQuery("#hotel-rates-"+search_hotel).html(data);
			jQuery("#hotel-rates-"+search_hotel).slideDown();
			
			disabledSearch = jQuery( "#image" ).attr( "disabled" );
			if( disabledSearch ){
				jQuery( "#image" ).removeAttr("disabled");
				jQuery( "#image" ).attr({
										  src: "/images2/submit_button.gif",
										  alt: "Search",
										  title:"Search"
										}) ;
			}
			jQuery("#results-box-" + search_hotel).css("border","2px solid #BDBFAE");
			
			var ses_id;
			ses_id = jQuery("#hotel-rates-" + search_hotel + " > CONTEXT_SES-ID:hidden" ).attr( "value" );
			//jQuery.find("CONTEXT_SES-ID").attr( { value: ses_id } );
			
		} 
	);
	*/
	 $.ajax({
	   type: "POST",
	   url:  "hotel_rates.html",
	   data: {ses_id:              g_ses_id,
			  search_country:      search_country,
			  search_destination:  search_destination, 
	   		  search_hotel: 	   search_hotel,
			  hotel_name:		   htl_name,			  
			  search_num_children: search_num_children,
	   		  search_num_adults:   search_num_adults, 
			  search_num_infants:  search_num_infants,
			  search_checkin_date: search_checkin_date,
			  search_checkout_date:search_checkout_date
			  
		     },
	   success: function(data){ 		
			jQuery("#hotel-rates-"+search_hotel).hide();
			jQuery("#hotel-rates-"+search_hotel).html(data);
			jQuery("#hotel-rates-"+search_hotel).slideDown();
			
			disabledSearch = jQuery( "#image" ).attr( "disabled" );
			if( disabledSearch ){
				jQuery( "#image" ).removeAttr("disabled");
				jQuery( "#image" ).attr({
										  src: "/images2/submit_button.gif",
										  alt: "Search",
										  title:"Search"
										}) ;
			}
			jQuery("#results-box-" + search_hotel).css("border","2px solid #BDBFAE");
			
			var ses_id;
			ses_id = jQuery("#hotel-rates-" + search_hotel + " > CONTEXT_SES-ID:hidden" ).attr( "value" );
			//jQuery.find("CONTEXT_SES-ID").attr( { value: ses_id } );
			
		} 
	 });	
}

function loadcitymap(country_code,destination_code) {
	
	jQuery.post("loadcitymap.html", 
		{ country_code: country_code,city_code: destination_code  }, 
		function(data){ 
			jQuery("#city_map").html(data);
		} 
	);	
	
	loaddestination_details(country_code,destination_code);
	
}
function loaddestination_details(search_country,search_destination) {
	
	jQuery.post("destination_details.html", 
		{ search_country: search_country,search_destination: search_destination  }, 
		function(data){ 
			jQuery("#destination-details").html(data);
		} 
	);	
	loaddestination_results(search_country,search_destination);
}
function loaddestination_results(search_country,search_destination) {
	
	jQuery("#search-results").html("<img src='/images2/loading.gif' alt='' />");
	
	jQuery.post("search_results.html", 
		{ search_country: search_country,search_destination: search_destination  }, 
		function(data){ 
			
			jQuery("#search-results").html(data);
		} 
	);	

}
function popUp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=300,height=240,left = " + (screen.width-300)/2 + ",top = " + (screen.height-240)/2 + "');");
}

function showpopup(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=650,height=550,left = " + (screen.width-650)/2 + ",top = " + (screen.height-550)/2 + "');");
}

function pop_up(URL)
{	
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=yes,width=850,height=380,left = " + (screen.width-850)/2 + ",top = " + (screen.height-380)/2 + "');");
	
}

function pop_up_full_screen(URL)
{	
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=yes,scrollbars=yes,location=0,statusbar=yes,menubar=yes,resizable=yes,width=" + screen.width +  ",height=" + screen.height + ",left = 0,top = 0');");
	
}

function expand(promo_cd){
  if ($("#" + promo_cd ).is(":hidden")) {
	$("#" + promo_cd).slideDown("slow");
  } else {
	$("#" + promo_cd ).slideUp();
  }
}



function radioBookValue(  ) {
	var res_url;
	/* base url */ /* The page in the res to redirect */  /* the session variables that res needs to proceeds from that point and onwards. */           
	res_url = "https://www.louishotels.com/cgi-bin/lcrs.sh/webinit.p?" + 
        	  "SCR=PN3&FCT=BOOK&" +                                      
              "numTotPrice=" + total + "&" +                  
              "cPCbox=" + codes[0] + "&" +
              "mPCbox=" + codes[1] + "&" +
			  "CONTEXT_SES-ID="  + sesid + "&" +
			  "CONTEXT_SYSTEM=PLAN&" +			  			  
			  "CONTEXT_PROFILE=PUB&" +
			  "CONTEXT_BKGNO=0&"  +
			  "CONTEXT_CURRENCY=EUR"  +
			  "CONTEXT_USE-DEC=YES"  +
			  "CONTEXT_COMP-ID=" + cmpid + "&" +
			  "CONTEXT_PAXBAR=A,A,:0,1,:,:" +
			  "CONTEXT_PRICE="   + price + "&" +			  
			  "CONTEXT_HEADER="  + procd + "&" +
			  "CONTEXT_EXTRA=CYP::CYP:2:0:15/10/2008:20/10/2008:::PFO-LIMB:0" ;			  
			  
    pop_up_full_screen(res_url);
    return false;
}

function getSelectedRadioBtn(){
//Finds all inputs with name 'newsletter' and changes the text of the span next to it.
	$("input[id='newsletter']").next().text(" is newsletter");
}

var codes = new Array(2);
var total;
var cmpid;
var sesid;
var procd;

var promo_free_cd;
var promo_free_desc;
var promos_related = [];

function setRadioBookValue( theForm, obj, comp_id, sessionid, promocd, promocddesc, catgcd, catgcddesc, mplncd, mplncddesc ){
	var i;
	var j;		
	for( i = 0; i < document.forms.length; i++){
		if( document.forms[ i ].name == theForm ){
			for( j=0; j < document.forms[i].elements.length; j++ ){
/*				 if( 	   document.forms[i].elements[j].name == 'promo_code' ){		
				 	if( promocd != "" || promocd != null || promo_related != promocd ){
   					 	   document.forms[i].elements[j].value =  promocd;				 
					}
				 }else if( document.forms[i].elements[j].name == 'promo_code_desc' ){
				 	if( promocddesc != "" || promocddesc != null || promo_related != promocd ){					 
   					 	   document.forms[i].elements[j].value =  promocddesc;								 
					}
*/
     		     if( 	   document.forms[i].elements[j].name == 'promo_code' ){  /*11/05/2010 - Elena*/
				 	  document.forms[i].elements[j].value =  promocd;	
				 }
				 else  if( 	   document.forms[i].elements[j].name == 'promo_code_desc' ) {
					 document.forms[i].elements[j].value =  promocddesc;	
			     }
				 else
				 if( 	   document.forms[i].elements[j].name == 'mpln_code' ){
				           document.forms[i].elements[j].value =  mplncd; 		
				 }else if( document.forms[i].elements[j].name == 'mpln_code_desc' ){
				           document.forms[i].elements[j].value =  mplncddesc; 						 
				 }else if( document.forms[i].elements[j].name == 'catg_code' ){
				           document.forms[i].elements[j].value =  catgcd; 		
				 }else if( document.forms[i].elements[j].name == 'catg_code_desc' ){
				           document.forms[i].elements[j].value =  catgcddesc; 								  
				 }else if( document.forms[i].elements[j].name == 'total_price' ){
			    		   document.forms[i].elements[j].value = obj.value;
				 }
			}			
		}
	}	
	
	for( i = 0; i < document.forms.length; i++){
		if( document.forms[ i ].name == theForm ){
			for( j = 0; j < document.forms[ i ].elements.length; j++ ){
				 if( document.forms[ i ].elements[ j ].name == 'promo_code' ){						 
		 		 	for( k = 0; k < promos_related.length; k++ ){
						if( document.forms[ i ].elements[ j ].value != promos_related[ k ] || promocd == '' ){
	   						document.forms[ i ].elements[ j ].value =  promocd;				 					
							/*separate for is needed because of the arbitrary order of the controls in the form */
							for( i = 0; i < document.forms.length; i++ ){
								if( document.forms[ i ].name == theForm ){
									for(j=0; j < document.forms[ i ].elements.length; j++ ){
										 if( document.forms[ i ].elements[ j ].name == 'promo_code_desc' || promocddesc == ''){					 
									     	 document.forms[ i ].elements[ j ].value =  promocddesc;								 						
											return;
										 }									 
									}			
								}
							}
						}
					}
				 }
			}			
		}
	}	
}

function setFreePromo(theForm,promocd,promocddesc,promosRelated){
	var i;
	var j;
	var k;
	promos_related  = promosRelated.split(",");
	promo_free_cd   = promocd;
	promo_free_desc = promocddesc; 
	for( i = 0; i < document.forms.length; i++){
		if( document.forms[ i ].name == theForm ){
			if(document.forms[ i ]!=null)
			for( j = 0; j < document.forms[ i ].elements.length; j++ ){
				 if( document.forms[ i ].elements[ j ].name == 'promo_code' ){						 
		 		 	for( k = 0; k < promos_related.length; k++ ){
						if( document.forms[ i ].elements[ j ].value == promos_related[ k ] || promocd == '' ){
	   						document.forms[ i ].elements[ j ].value =  promocd;				 					
							/*separate for is needed because of the arbitrary order of the controls in the form */
							for( i = 0; i < document.forms.length; i++ ){
								if( document.forms[ i ].name == theForm ){
									for(j=0; j < document.forms[i].elements.length; j++ ){
										 if( document.forms[i].elements[j].name == 'promo_code_desc' || promocddesc == ''){					 
									     	document.forms[ i ].elements[ j ].value =  promocddesc;								 						
											return;
										 }									 
									}			
								}
							}
							
						}
					}
				 }
			}			
		}
	}			
}

var isNS = navigator.appName == "Netscape";
var isIE = !isNS;

function labelMouseOver(lbl){ 

	if(isIE){		
		jQuery("#" + lbl).css("cursor","pointer");		
		jQuery("#" + lbl).css("color","orange");
	}else{
		jQuery("#" + lbl).css("cursor","pointer");		
		jQuery("#" + lbl).css("color","orange");		
	}
}
function labelMouseOut(lbl){ 
	if(isIE){		
		jQuery("#" + lbl).css("cursor","pointer");
		jQuery("#" + lbl).css("color","#3F6970");
	}else{
		jQuery("#" + lbl).css("cursor","pointer");		
		jQuery("#" + lbl).css("color","#3F6970");		
	}
}



function validatePersonalInfo(){
//	txtPhone
//	txtEmail
//	TxtLast
//	TxtFirst
//	TxtInit
//	txtTitle
//	TxtAge
//	TxtSex
//	TxtAddr1
//	TxtCity
//	TxtCountry
//	TxtZip
	return false;	
}

function search_criteria(){

	var qsparams = "?" + "search_checkin_date="   + jQuery( "#search_checkin_date" ).val( )  
					   + "&search_checkout_date=" + jQuery( "#search_checkout_date" ).val( ) 
					   + "&search_country="       + jQuery( "#search_country" ).val( ) 
					   + "&search_destination="   + jQuery( "#search_destination" ).val( ) 					   
					   + "&search_hotel="         + jQuery( "#search_hotel" ).val( ) 					   					   
					   + "&search_num_adults="    + jQuery( "#search_num_adults" ).val( ) 					   					   
					   + "&search_num_children="  + jQuery( "#search_num_children" ).val( )
					   + "&search_searchby="      + jQuery( "#search_searchby" ).val( )
					   + "&search_holiday_type="  + jQuery( "#search_searchby" ).val( )
  					   + "&ses_id="               + jQuery( "#ses_id" ).val( );
					   //+ "&search_children_ages=" + jQuery( "#search_children_ages" ).val( )
	var qs_new_url = "advanced_search.html" + qsparams;
	window.location.href = qs_new_url;
}

/* Client-side access to querystring name=value pairs
	Version 1.3
	28 May 2008
	
	License (Simplified BSD):
	http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};
	
	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params[name] = value;
	}
}

Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}

function checkOffers( htlcode ){
	
	if( $( htlcode + "freeOfferId" ).val( ) == 'checked' ){
			
	}		
}

/* checks for up to 5 offers*/
function checkOffers( theForm, htlcode ){
	var is_standard_price;
	var offer_description = [];
	var temporary;
	
	is_standard_price = $( "input[id^='" + htlcode.replace( "-", "_" ) + "none']" ).is( ":checked" )
	
	if( is_standard_price ){		
		if( $( "#" + htlcode + "_freeOfferId" ).is( ":checked" ) ){
			temporary = $( "#" + htlcode + "_freeOfferId" ).attr("onclick");
			offer_description = temporary.toString().split(",");
			temporary = offer_description[ 2 ].replace("\\uFFFD","");
			temporary = temporary.substring(2);
			setOfferDetails( $( "#" + htlcode + "_freeOfferId" ).val( ), temporary  );
			
		}	
		else if( $( "#" + htlcode + "_freeOfferId1" ).is( ":checked" )){
			temporary = $( "#" + htlcode + "_freeOfferId1" ).attr("onclick");
			offer_description = temporary.toString().split(",");
			temporary = offer_description[ 2 ].replace("\\uFFFD","");
			temporary = temporary.substring(2);
			setOfferDetails( $( "#" + htlcode + "_freeOfferId1" ).val( ), temporary  );
		}	
		else if( $( "#" + htlcode + "_freeOfferId2" ).is( ":checked" )){
			temporary = $( "#" + htlcode + "_freeOfferId2" ).attr("onclick");
			offer_description = temporary.toString().split(",");
			temporary = offer_description[ 2 ].replace("\\uFFFD","");
			temporary = temporary.substring(2);
			setOfferDetails( $( "#" + htlcode + "_freeOfferId2" ).val( ), temporary  );
		}		
		else if( $( "#" + htlcode + "_freeOfferId3" ).is( ":checked" ) ){
			temporary = $( "#" + htlcode + "_freeOfferId3" ).attr("onclick");
			offer_description = temporary.toString().split(",");
			temporary = offer_description[ 2 ].replace("\\uFFFD","");
			temporary = temporary.substring(2);
			setOfferDetails( $( "#" + htlcode + "_freeOfferId3" ).val( ), temporary  );
		}		
		else if( $( "#" + htlcode + "_freeOfferId4" ).is( ":checked" )  ){
			temporary = $( "#" + htlcode + "_freeOfferId4" ).attr("onclick");
			offer_description = temporary.toString().split(",");
			temporary = offer_description[ 2 ].replace("\\uFFFD","");
			temporary = temporary.substring(2);
			setOfferDetails( $( "#" + htlcode + "_freeOfferId4" ).val( ), temporary  );
		}		
	}
}

function setOfferDetails(theForm,offerCode,offerDesc){
	for( i = 0; i < document.forms.length; i++){
		if( document.forms[ i ].name == theForm ){
			if(document.forms[ i ]!=null)
			for( j = 0; j < document.forms[ i ].elements.length; j++ ){
				 if( document.forms[ i ].elements[ j ].name == 'promo_code' ){
					 document.forms[ i ].elements[ j ].value = offerCode;
				 }
				 else if( document.forms[ i ].elements[ j ].name == 'promo_code_desc' ){
					 document.forms[ i ].elements[ j ].value = offerDesc;
				 }
			}
		}
	}						 
}

function sortby_onclick( sortbyId, direction ){
	/* sortby( elementId, childId, "span.sortHotelName", direction, by ); */	
	// set sorting column and direction, this will sort on the first and third column the column index starts at zero 
	var sorting;
	if( 	 sortbyId == "date" )				   	    { sorting = [ [ 5 , 0 ] ]; } 
	else if( sortbyId == "destination"  ) 				{ sorting = [ [ 0 , 0 ] ]; }
	else if( sortbyId == "price" && direction == "asc" ){ sorting = [ [ 6 , 1 ] ]; }
    else if( sortbyId == "price" && direction == "dsc" ){ sorting = [ [ 6 , 0 ] ]; }
	// sort on the first column 
	//var idt;
	$("table[id^='so_']").each(function(){
		//idt = "'#"+$(this).attr("id")+" table'";
		$( this ).trigger("sorton",[sorting]); 
	});		
	$("#removeRow").remove();
	$(function() { $("table[id^=so] tr").removeClass("striped"); });
	$(function() { $("table[id^=so] tr:nth-child(even)").addClass("striped"); });
	// return false to stop default link action 	
	return false; 	
}

function getMinRate(htlcd,promocd,id){
	$("#"+id).html('<img src="/images2/smallloading.gif" alt="" />');
	$.post("minrate.html", 
		   { HotelCode: htlcd, PromoCode: promocd  },
  		   function(data){
    			$("#"+id).html("&euro; " + data);
           });

} 

function offersSearchDates(){
	
	var todaysdate = new Date();
    $("#offerRangeFrom").datepicker({
							 mandatory:  true,
							 minDate: 	 new Date( todaysdate.getFullYear(), todaysdate.getMonth(), todaysdate.getDate() ),
							 maxDate:    new Date( todaysdate.getFullYear() + 1, 11, 31 ),
							 yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,
							 dateFormat: 'dd/mm/yy',
							 speed: '' });
	
    $("#offerRangeTo").datepicker({
							 mandatory:  true,
							 minDate: 	 new Date( todaysdate.getFullYear(), todaysdate.getMonth(), todaysdate.getDate() ),
							 maxDate:    new Date( todaysdate.getFullYear() + 1, 11, 31 ),
							 yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,
							 dateFormat: 'dd/mm/yy',
							 speed: '' });

	$("#offerRangeFrom").val("");
	$("#offerRangeTo").val("");
	$("#offerCountry").val("");
	$("#offerDestination").val("");
}

function loadOffers(){
	var offerFromDate     = $("#offerRangeFrom").val();
	var offerToDate       = $("#offerRangeTo").val();
	var offerCountry      = $("#offersCountry").val();
	var offerDestination  = $("#offersDestination").val();
	var offerValCountries =$("#validCountries").val();
	$("#offersBox").html("<div id='offersLoading' style='text-align:center; width:100%;'><img src='/images2/smallloading.gif' alt='' /></div>");
	$.post("findoffers.html",
		    {FromDate: offerFromDate, ToDate: offerToDate, Country: offerCountry, Destination: offerDestination, validCountries: offerValCountries},
			function(data){
				$("#offersBox").html(data);
			});
}