//if(g_isNS){console.profile();}
/*** globals: settings used for modules in the js code ***/
/* autocomplete */
var g_data 			 = [ ]; /* actuall data to be used for autocomplete display*/
var g_datacloned 	 = [ ]; /* same as data but with more info for filtering purposes and reloading */
var g_dataclonedInit = [ ];
var g_ac;

/* paging settings*/
var g_pagingGroupSize = 9;
var g_group   		  = 'span';
var g_groupId 		  = 'pageSeparator';
var g_groupClass      = 'pageSeparator';
var g_nextText		  = '>>';
var g_prevText        = '<<';
var g_isNS = navigator.appName == "Netscape";
var g_isIE = !g_isNS;

/* dropdowns/listboxes/combos HARD CODED VALUES */
var htlRating = [ { name: 'All', value: ''   }, 
				  { name: '2*' , value: '2*' }, 
				  { name: '3*' , value: '3*' },
				  { name: '4*' , value: '4*' },
				  { name: '5*' , value: '5*' } ];

var aptRating = [ { name: 'All'       , value: ''     },
				  { name: 'Category A', value: 'APT A' },
				  { name: 'Category B', value: 'APT B' },
				  { name: 'Category C', value: 'APT C' } ];

var $htlFilter;
var g_ses_id = '';

/*** End globals ***/
/*
	function customRange( input ) {  
  		var new_date  = new Date( $("#search_checkin_date").datepicker("getDate") );
	    new_date.setDate( new_date.getDate() + 1 );
		return {minDate: (input.id == "search_checkout_date" ? new_date : null ) };  
	}
*/

/* on document ready */
$( document ).ready( function() {
	var todaysdate = new Date();								   
	// caching for speedup
	//$.uiTableFilter.last_phrase = ""
    // Setup the sorting for the table with the first column initially sorted ascending
    // and the rows striped using the zebra widget
	// $( "#results" ).tablesorter( { textExtraction: myTextExtraction } ).tablesorterPager( { container: $("#pager") } );
	var results = $( "#results" );;
	var num_results = $( "#results_num:hidden" );
	if( results.length ){
		var myTextExtraction = function( node )
		{
			var $n = $( node );
			// extract data from markup and return it
			var $r = $n.find( ".sortHotelName" );
			if ( $r.length > 0 ) { return $r.html( ); }	else { return $n.html( ); }
		};

		if( num_results.length ){
			if(num_results.val() > 0){
				results.tablesorter(       { debug: false, dateFormat: 'dd/mm/yyyy', sortList: [ [ 0, 0 ] ], textExtraction: myTextExtraction } )
					   .tablesorterPager(  { container:$( "#pager" ), positionFixed: false } );
			}
			else if( num_results.val() <= 0 ){
				results.tablesorter( { debug: false, dateFormat: 'dd/mm/yyyy', sortList: [ [ 0, 0 ] ], textExtraction: myTextExtraction } );
			}
		}
	}
	else{
		results = $( "#htl_results" );;		
		var myTextExtraction = function( node )
		{
			var $n = $( node );
			// extract data from markup and return it
			var $r = $n.find( ".sortHotelName" );
			if ( $r.length > 0 ) { return $r.html( ); }	else { return $n.html( ); }
		};

		if( num_results.length ){
			if(num_results.val() > 0){
				results.tablesorter(       { debug: false, dateFormat: 'dd/mm/yyyy', sortList: [ [ 0, 0 ] ], textExtraction: myTextExtraction } )
					   .tablesorterPager(  { container:$( "#pager" ), positionFixed: false } );
			}
			else if( num_results.val() <= 0 ){
				results.tablesorter( { debug: false, dateFormat: 'dd/mm/yyyy', sortList: [ [ 0, 0 ] ], textExtraction: myTextExtraction } );
			}
		}		
	}
	/*travel selection:car hire item*/
	var pickUpDate  = $("#pickupdt");
	var dropOffDate = $("#dropoffdt");
	

	if( pickUpDate.length ){
		pickUpDate.datepicker({	
			mandatory:  true,
			minDate: 	new Date( todaysdate.getFullYear(), todaysdate.getMonth(), todaysdate.getDate() ),
			maxDate:    new Date( todaysdate.getFullYear() + 1, 11, 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( "dropoffdt" ).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,11, todaysdate.getDate() ),
			yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,
			dateFormat: 'dd/mm/yy', 
			speed:      ''
		});			
	}
	
	var ac_results = $("#ac_results");
	/* for hotels page: when the results are loaded:autocomplete feature */
	if( document.getElementById( 'results' ) != null || ( num_results.length && num_results.val() == "0" ) ){ 
		//create_pagination( 'results'); 		
		ac_results.attr("disabled","disabled");
		loadAllHotelNames();		 
		ac_results.removeAttr("disabled");
	}
	/* for hotel page when results are lodaed:autocomplete feature*/
	if( document.getElementById( 'hotelInfoFrm' ) != null ){ 
		//create_pagination( 'results'); 		
		ac_results.attr("disabled","disabled");
		loadAllHotelNames();		 
		ac_results.removeAttr("disabled");
	}	
	/* for hotels page when coming from home page*/
	if( document.getElementById( 'htl_results' ) != null || ( num_results.length && num_results.val() == "0" ) ){ 
		//alert('htl_results');
		//create_pagination( 'htl_results' ); 		
		ac_results.attr("disabled","disabled");
		loadAllHotelNames();		 
		ac_results.removeAttr("disabled");
	}
	/* for pax info page*/
	var paxInfoFrm = $("#paxInfoFrm");
	if($("#paxInfoFrm").length){
        $("#paxInfoFrm").validate({
			errorClass: "errmsg",
            rules:  { 
				/* pax info page MAY have up to 8 adults + children */				
				// simple rule, converted to {required:true}
				txtLast1: "required",
				txtFirst1:"required",
				txtLast2: "required",
				txtFirst2:"required",
				txtLast3: "required",
				txtFirst3:"required",
				txtLast4: "required",
				txtFirst4:"required",
				txtLast5: "required",
				txtFirst5:"required",
				txtLast6: "required",
				txtFirst6:"required",
				txtLast7: "required",
				txtFirst7:"required",
				txtLast8: "required",
				txtFirst8:"required",
				txtDriverLast:"required",
				txtDriverFirst:"required",
				txtTrfLast:"required",
				txtTrfFirst:"required",
				chkTerms:"required",
				radNews:"required",
				txtDriverAge:{required:true,
						      digits:true},
			//	txtEmail:{required:true,
			//	          email:true},
			//	txtPhone:{required:true,
			//		      digits:true},
			//	txtCity:"required",
				txtCountry:"required"				
            },        
            message:{ 
				txtLast1: "*",
				txtFirst1:"*",
				txtLast2: "*",
				txtFirst2:"*",
				txtLast3: "*",
				txtFirst3:"*",
				txtLast4: "*",
				txtFirst4:"*",
				txtLast5: "*",
				txtFirst5:"*",
				txtLast6: "*",
				txtFirst6:"*",
				txtLast7: "*",
				txtFirst7:"*",
				txtLast8: "*",
				txtFirst8:"*",
				txtDriverLast:"*",
				txtDriverFirst:"*",
				txtTrfLast:"*",
				txtTrfFirst:"*",
				chkTerms:"*",
				radNews:"*",
				txtDriverAge:{required:"*",
						      digits:"only digits"},
				txtEmail:{required:"*",
				          email:"must be in the format of name@domain.com"},
				txtPhone:{required:"*",
					      digits:"only digits."},
				txtCity:"*",
				txtCountry:"*"
            }
	    });
	}

	/* for transfers page: autocomplete feature */
	if( document.getElementById( 'transfers_results' ) != null ){ 				
		ac_results.attr("disabled","disabled");
		loadAllHotelNames();		 
		ac_results.removeAttr("disabled");
		/* init datepickers */
		var trfArrivalDate   = $("#search_trf_arrival_date");
		var trfDepartureDate = $("#search_trf_departure_date");
		trfArrivalDate.datepicker({	
			mandatory:  true,
			minDate: 	new Date( todaysdate.getFullYear(), todaysdate.getMonth(), todaysdate.getDate() ),
			maxDate:    new Date( todaysdate.getFullYear() + 1, 11, todaysdate.getDate() ),
			yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,											 
			dateFormat: 'dd/mm/yy', 
			speed:      '',
			onSelect:   function(dateText){ 
			            if ($("#search_trf_choice").val() != "A") {
							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 );
							document.getElementById( "search_trf_departure_date" ).value = dateFormat( new_date, "%DD/%MM/%YYYY" );
							trfDepartureDate.datepicker( "disable" ); //hack to avoid showing the datepicker on setDate
							trfDepartureDate.datepicker( "setDate", new_date );
							trfDepartureDate.datepicker( "enable" ); //hack to avoid showing the datepicker on setDate
							$("#numdays").text("5");
						}
					}
		});	
		trfDepartureDate.datepicker({
			mandatory:  true,
			minDate:    new Date( todaysdate.getFullYear(),     todaysdate.getMonth(), todaysdate.getDate() ),
			maxDate:    new Date( todaysdate.getFullYear() + 1, 11, todaysdate.getDate() ),											
			yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,
			dateFormat: 'dd/mm/yy', 
			speed:      ''		
		});	 
		trfDates();  
		loadTrfHotels($("#search_trf_location").val());
		otherHotel();		
	}	
	/* if this page is the HOME page*/
	if( document.getElementById( 'travel_to_cyprus' ) != null ){
		ac_results.attr("disabled","disabled");
		loadAllHotelNames();		 
		ac_results.removeAttr("disabled");		
	}
	var htlCheckinDate  = $("#search_checkin_date");
	var htlCheckoutDate = $("#search_checkout_date");
	htlCheckinDate.datepicker({	
		mandatory:  true,
		minDate: 	new Date( todaysdate.getFullYear(), todaysdate.getMonth(), todaysdate.getDate() ),
		maxDate:    new Date( todaysdate.getFullYear() + 1, 11, todaysdate.getDate() ),
		yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,											 
		dateFormat: 'dd/mm/yy', 
		speed:      '',
		onSelect:   function(dateText){ 
					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 );
					document.getElementById( "search_checkout_date" ).value = dateFormat( new_date, "%DD/%MM/%YYYY");
					htlCheckoutDate.datepicker( "disable" ); //hack to avoid showing the datepicker on setDate
					htlCheckoutDate.datepicker( "setDate", new_date );
					htlCheckoutDate.datepicker( "enable" ); //hack to avoid showing the datepicker on setDate
				}
	});	
	htlCheckoutDate.datepicker({
		mandatory:  true,
		minDate:    new Date( todaysdate.getFullYear(),     todaysdate.getMonth(), todaysdate.getDate() ),
		maxDate:    new Date( todaysdate.getFullYear() + 1, 11, todaysdate.getDate() ),		
		yearRange:  todaysdate.getFullYear() + ':' + todaysdate.getFullYear() + 1,
		dateFormat: 'dd/mm/yy', 
		speed:      ''
	});	


	/* for hotel info and holiday guide page */
    if( $("#htltabs").length ){ 
    $.jtabber({
			mainLinkTag: "#htltabs a", // much like a css selector, you must have a 'title' attribute that links to the div id name
			activeLinkClass: "flora", // class that is applied to the tab once it's clicked
			hiddenContentClass: "locinfo", // the class of the content you are hiding until the tab is clicked
			showDefaultTab: 1, // 1 will open the first tab, 2 will open the second etc.  null will open nothing by default
			showErrors: true, // true/false - if you want errors to be alerted to you
			effect: 'slide', // null, 'slide' or 'fade' - do you want your content to fade in or slide in?
			effectSpeed: 'fast' // 'slow', 'medium' or 'fast' - the speed of the effect
	});
	};
	/* for holiday guide page */	
//	var defaultTab = 1;
    $("div[id^=loctabs]").each(function(){
		//if (defaultTab != 1 ){defaultTab = null;}
		$.jtabber({
				mainLinkTag: "#" + $(this).attr("id") + " a", // much like a css selector, you must have a 'title' attribute that links to the div id name
				activeLinkClass: "flora", // class that is applied to the tab once it's clicked
				hiddenContentClass: "locinfodetails", // the class of the content you are hiding until the tab is clicked
				showDefaultTab: 1, // 1 will open the first tab, 2 will open the second etc.  null will open nothing by default
				showErrors: true, // true/false - if you want errors to be alerted to you
				effect: 'slide', // null, 'slide' or 'fade' - do you want your content to fade in or slide in?
				effectSpeed: 'fast' // 'slow', 'medium' or 'fast' - the speed of the effect
		});
	//	defaultTab++;
	});

	/* for cars page */
    if( $("#cartabs").length ){ 
    $.jtabber({
			mainLinkTag: "#cartabs a", // much like a css selector, you must have a 'title' attribute that links to the div id name
			activeLinkClass: "floracars", // class that is applied to the tab once it's clicked
			hiddenContentClass: "hiddencontent", // the class of the content you are hiding until the tab is clicked
			showDefaultTab: null, // 1 will open the first tab, 2 will open the second etc.  null will open nothing by default
			showErrors: true, // true/false - if you want errors to be alerted to you
			effect: 'slide', // null, 'slide' or 'fade' - do you want your content to fade in or slide in?
			effectSpeed: 'fast' // 'slow', 'medium' or 'fast' - the speed of the effect
	})
	};
	/* when coming to hotels page through the home page
	var qs = new Querystring();
	var travelToCyprus;		
    if( qs.contains( "travelToCyprus" ) == true ){		
		travelToCyprus = qs.get( "travelToCyprus" );			
		alert(travelToCyprus);
   	    $("#search_submit").click();	
	}*/

});

function setStarRating( obj ){
    $( "#search_stars" ).removeAttr( "disabled" );
    if(      obj.value == 'HTL' ){ populateSelect( $("#search_stars").get( 0 ), htlRating );	}
	else if( obj.value == 'APT' ){ populateSelect( $("#search_stars").get( 0 ), aptRating );	}
	else                         { populateSelect( $("#search_stars").get( 0 ), [ ] ); $( "#search_stars" ).attr( "disabled", "disabled" ); } 
}

function populateSelect( el, items ) {
    el.options.length = 0;
    //if (items.length > 0) el.options[0] = new Option('select', '');
    $.each( items, function ( ) {
        el.options[ el.options.length ] = new Option( this.name, this.value );
    });
}

function combo_onchange( obj ){	
//	if( obj.options[obj.selectedIndex] = "" )
	if( obj != null && obj.id == 'search_trf_location'){
		var $destination	   = $( "#search_trf_location option:selected"  );
	 	var results_found = 0;
		/* reset the hotel names to full list if all combos have ANY */
		g_datacloned = g_dataclonedInit.slice();	
		if( $destination.val() 		 != '' && $destination.val() 	   != null ) { results_found = filterHotelNames( '4', $destination.val()       ); }
    }
	else if( obj != null ){
		var $stars 			   = $( "#search_stars:not(:disabled)" );
		var $accomodation_type = $( "#search_holiday_type" );
		var $travel_type	   = $( "#search_searchby"     );
		var $destination	   = $( "#search_destination option:selected"  );
	 	var results_found = 0;
		/* reset the hotel names to full list if all combos have ANY */
		g_datacloned = g_dataclonedInit.slice();
		//alert("'"+$destination.val()+"'");
		if( $destination.val() == '' ){ loadAllHotelNames(); return; }
		if( $stars.val() == '' && $accomodation_type.val() == ''  && $travel_type.val() == '' && $destination.val() == '' ){ loadAllHotelNames(); return; }		
		
		/* stars have a value and is not disabled*/
		if( $stars.val() 			 != null && $stars.val() 			 != '' ) { results_found = filterHotelNames( '1', $stars.val() 			 ); }
		if( $accomodation_type.val() != null && $accomodation_type.val() != '' ) { results_found = filterHotelNames( '2', $accomodation_type.val() ); }
		if( $travel_type.val() 	  	 != null && $accomodation_type.val() != '' ) { results_found = filterHotelNames( '3', $travel_type.val() 		 ); }
		if( $destination.val() 	   	 != null && $destination.val() 	   	 != '' ) { results_found = filterHotelNames( '4', $destination.val()       ); }

		if(results_found == 0){ 
			//$( "#ac_results" ).val('No hotels found!'); 
			$( "#ac_results" ).attr( { disabled: 'disabled' } ); 
		}
		else{ 
			$( "#ac_results" ).val(''); 
			$( "#ac_results" ).removeAttr("disabled"); 
		}
	}
}







function filterHotelNames( compareIndex, compareValue ){
	var tstr;
	var new_data_index = 0;	
	var new_data       = [ ];
	var new_datacloned = [ ] ;
	var starating;
	if( g_datacloned != null ) {
		for( var i = 0; i < g_datacloned.length; i++ ) {	
			tstr = g_datacloned[ i ].split("||");
			/*			
			if 	    ( tstr[ 1 ] == "APT A"    ){ starating = "Category A"; }
			else if ( tstr[ 1 ] == "APT B"    ){ starating = "Category B"; }
			else if ( tstr[ 1 ] == "APT C"    ){ starating = "Category C"; }
			else if ( tstr[ 1 ] == "TOURVILL" ){ starating = "Holiday Village"; }
			else if ( tstr[ 1 ] == "TRAD" )    { starating = "Traditional House"; }
			else 							   { starating = tstr[ 1 ]; } 
			*/
		
			if( compareIndex == 3 && compareValue != ''){
				var ttemp;
				ttemp = tstr[ compareIndex ].split(",");
				for(var j = 0; j < ttemp.length; j++ ){
					if( ttemp[ j ] == compareValue ) {
						new_data[ new_data_index ]       = tstr[ 0 ] + ", " + tstr[ 5 ]; /* hotelname and hotel star rating */
						new_datacloned[ new_data_index ] = tstr[ 0 ] + "||" + tstr[ 1 ] + "||" + tstr[ 2 ] + "||" + tstr[ 3 ] + "||" + tstr[ 4 ] + "||" + tstr[ 5 ];
						new_data_index++; 						
						break;
					}
				}
			}
			else if( compareValue == '' ){
					new_data[ new_data_index ]       = tstr[ 0 ] + ", " + tstr[ 5 ]; /* hotelname and hotel star rating */
					new_datacloned[ new_data_index ] = tstr[ 0 ] + "||" + tstr[ 1 ] + "||" + tstr[ 2 ] + "||" + tstr[ 3 ] + "||" + tstr[ 4 ] + "||" + tstr[ 5 ];
					new_data_index++; 					
		    }
			else if( tstr[ compareIndex ] == compareValue ) {				
				new_data[ new_data_index ]       = tstr[ 0 ] + ", " + tstr[ 5 ]; /* hotelname and hotel star rating */
				new_datacloned[ new_data_index ] = tstr[ 0 ] + "||" + tstr[ 1 ] + "||" + tstr[ 2 ] + "||" + tstr[ 3 ] + "||" + tstr[ 4 ] + "||" + tstr[ 5 ];
				new_data_index++; 
			}
		}
	}
	g_datacloned = new_datacloned.slice( );
	g_ac[ 0 ].autocompleter.flushCache( ); 
	g_ac = $( "#ac_results" ).autocompleteArray( new_data );
	return new_data_index;
}

function loadAllHotelNames(){
	var temp;	
	g_data = [];
	g_datacloned = [];
	var starating;
	for( var i = 0; i < hotelresults.length; i++ ) {		
		temp              = hotelresults[ i ].split("||", 9 );				
		
/*		if 	    ( temp[ 1 ] == "APT A"    ){ starating = "Category A"; }
		else if ( temp[ 1 ] == "APT B"    ){ starating = "Category B"; }
		else if ( temp[ 1 ] == "APT C"    ){ starating = "Category C"; }
		else if ( temp[ 1 ] == "TOURVILL" ){ starating = "Holiday Village"; }
		else if ( temp[ 1 ] == "TRAD" )    { starating = "Traditional House"; }
		else 							   { starating = temp[ 1 ]; }	*/
		
		g_data[ i ]       = temp[ 0 ] + ", " + temp[ 8 ];
		g_datacloned[ i ] = temp[ 0 ] + "||" + temp[ 1 ] + "||" + temp[ 2 ] + "||" + temp[ 3 ] + "||" + temp[ 4 ] + "||" + temp[ 8 ];
	} 
	g_dataclonedInit = g_datacloned.slice();
	g_ac = $("#ac_results").autocompleteArray( g_data );	
}


//window.dhtmlHistory.create();

//var yourListener = function(newLocation, historyData) {
        //do something;
//}
    
/*
function sortby( elementId, childId, sortbyId, direction, by ){
	var options;
	if( direction = "" || direction != "asc" || direction != "desc" ){ direction = "asc"; }
	elementId = "#" + elementId;
	childId   = "#" + childId;
	sortbyId  = sortbyId;
	var selso = function(){
		var count=0;
		$( 'div.aresult' ).selso( options );
		};
	var orderByNum=function(){
		options = {type:'num',     orderBy:sortbyId, direction:direction };
		selso();
		};
	var orderByAlpha=function(){
		options = {type:'alpha',   orderBy:sortbyId, direction:direction };
		selso();
		};
	var orderByAccents=function(){
		options = {type:'accents', orderBy:sortbyId, direction:direction };
		selso();
		};
	var orderById = function(){
		options = {
			type:'alpha',
			direction:direction,
			extract:function(o){return $(o).attr('id');}
		};
		selso();
		};
	var orderByLength = function(){
		options = {
			type:'num',
			direction:direction,
			extract:function( o ){return $( sortbyId, o ).text( ).length; }
		};
		selso();
		};	
		*/
		/*main*/	
/*		switch(by.toLowerCase()){
			case "num":     orderByNum();		break;
			case "alpha":   orderByAlpha();		break;		
			case "accents": orderByAccents();   break;		
			case "id":      orderById();		break;				
			case "length":  orderByLength();    break;
			default:		*//*HANDLE ERROR?*//*	break;}
}
*/
function sortby_onclick( elementClass, childClass, sortbyId, direction, by ){
//    alert(elementId + ',' + childId + ',' + sortbyId + ',' + direction + ',' + by);
/*	sortby( elementId, childId, "span.sortHotelName", direction, by ); */	
	$("span.sortingmessage").show();	
	var options;
	options = { 
		type:       by,   
		orderBy:    sortbyId, 
		direction:  direction,
		extract:    'function( o ){ return $( o ).find(' + sortbyId + ').text( ); }',
		group:      g_group,
		groupId:	g_groupId,
		groupClass: g_groupClass,
		groupSize:  g_pagingGroupSize,
		makePaging: 'true'
	};
//	$('span.pageSeparator').remove();
	var cnt;
	$(elementClass).each(function(){
		cnt = $(this).contents();
		$(this).replaceWith(cnt);												  
	});
	/* implementation specific*/
    $("#nav1").remove();
	$("div.locationname").remove();	
	/*end of implementation specific*/	
	$('.' + childClass).selso( options );	

}

function new_sortby_onclick( elementClass, childClass, sortbyId, direction, by ){
	// alert(elementId + ',' + childId + ',' + sortbyId + ',' + direction + ',' + by);
	/* 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 == "span.sortHotelStars" )				 { sorting = [ [ 1 , 0 ] ]; } 
	else if( sortbyId == "span.sortHotelName"  ) 				 { sorting = [ [ 0 , 0 ] ]; }
	else if( sortbyId == "span.sortPrice" && direction == "asc" ){ sorting = [ [ 3 , 0 ] ]; }
	else if( sortbyId == "span.sortPrice" && direction == "dsc" ){ sorting = [ [ 3 , 1 ] ]; }	
	// sort on the first column 
	if( $("#hotel_list table").length )      { 
		$("#hotel_list table" ).trigger("sorton",[sorting]); 
	}	
	else if( $( "#hotel_results table").length ){ 
		$( "#hotel_results table").each(function(){
			/*$( this ).attr( "id" )*/
			if( $( this ).attr( "id" ) == "htl_results" ){ $( this ).trigger( "sorton", [sorting] ); }
		});
	}	
	// return false to stop default link action 	
	return false; 	
}

function create_pagination( tableId ){
	/*** PAGER ***/
	// First Parameter: the name of the element that separates each page content.
	// Second Parameter: options object	
	$('#' + tableId ).pager('span', { 
		navId:          'nav1',
		navClass:       'navClass',
		highlightClass: 'navHighlight', 
		navAttach: 	    'before',
		prevText:  	    g_prevText,
		nextText:       g_nextText,
		height:         '50em',
		ignoreId:       'hotelName,hotelStars'
	});
}

/*	if(sortby == 'StarRating')
	else if(sortby == 'AlphabeticalOrder')*/	
	/*<element> 
	  <child>Text1</child> 
	  <child>Text2</child> 
	</element> */
/*	var sortItems=[];
	$( elementId ).find( childId ).each(function(){ 	  
	   sortItems.push( $(this).find( sortbyId ).text() + '|' + $(this).html() );			
	}); 
	sortItems
	idsToSortBy = idsToSortBy.sort(); 
    $(elementId).html("");
	for(i=0;i<idsToSortBy.length;i++){ 
	   $(elementId).append( ids[i] );
	   if(i<tmp.length-1) 
			$("#div_id").append(", "); 
	}*/ 
	/* The result is: <div id="div_id"> Text1, Text2 </div> */
function do_search( fromWhere, showIn, ses_id ){
	if( ses_id == '' && g_ses_id != '') {ses_id = g_ses_id;}
	if( $( "#ses_id" ).length && ses_id == ''){ ses_id = $( "#ses_id" ).val(); }

	var htlname = [];
	var temp;
	var htlcd;	

	if( $("#errormsg").length ){
		$("#errormsg").html("");
	}

	if( $( "#ac_results" ).val() != null && $( "#ac_results" ).val() != ''){
		htlname = $( "#ac_results" ).val().split(",");
		/* find hotel code */
		for( var i = 0; i < hotelresults.length; i++ ) {
			temp           = hotelresults[ i ].split( "||", 6 );
			if( temp[ 0 ] == htlname[ 0 ] ){ htlcd = temp[ 5 ]; break;}
		}
	}
	else{ htlname[0]= ''; htlcd='';}

	if( fromWhere == 'searchinhome'   ){
		if( $("#search_destination option:selected").val() == '' && $("#ac_results").val() == '' ){
			$("#errormsg").html("One of Location or Hotel name is required.");
			return false;
	    }			
		if($("#search_checkin_date").val() == "" || $("#search_checkout_date").val() == ""){
			$("#errormsg").html("Checkin and Checkout dates are required");
			return false;
		}
		if ($("#search_num_adults").val() == "0" && $("#search_num_children").val() == "0" && $("#search_num_infants").val() == "0"){
			$("#errormsg").html("You must enter at least 1 person");
			return false;
		}		
	    $("#search_hotel_name:hidden").val( htlname[ 0 ] );
		$("#search_hotel:hidden").val( htlcd );
    }
	else if( fromWhere == 'searchinhotels' ){
		if( $("#search_destination option:selected").val() == '' && $("#ac_results").val() == '' ){
			$("#errormsg").html("One of Location or Hotel name is required.");
			return false;
	    }			

		if($("#search_checkin_date").val() == "" || $("#search_checkout_date").val() == ""){
			$("#errormsg").html("Checkin and Checkout dates are required");
			return false;
		}

		if ($("#search_num_adults").val() == "0" && $("#search_num_children").val() == "0" && $("#search_num_infants").val() == "0"){
			$("#errormsg").html("You must enter at least 1 person");
			return false;
		}
		if( $("#hotelInfo").length ){/*we are in hotel info page no need to ajax search since redirect to hotels page */ 
			return true;
		}
		
		if( $("#search_num_adults").val() == "1" &&  $("#search_num_children").val() == "1" && $("#search_num_infants").val() == "0"){
			$("#errormsg").html("Please select 2 adults instead.");			
			return false;
		}
			if($( "#hotel_list" ).length){$( "#hotel_list" ).remove( );}			
			$( "div.mainframe" ).prepend( "<span id='temp'><img src='/images2/loadinga.gif' alt='' />Please wait.</span>" );
			$("#search_submit").attr( "disabled", "disabled" );
			/* ajax post */
			if( htlname[ 0 ] == 'No hotels found!') { htlname[ 0 ] = ''; }
			var search_stars;
			
			if( $( "#search_stars" ).length ){ search_stars = $( "#search_stars" ).val( ); }
			else{ search_stars = ""; }
			var destination = $("#search_destination").val();
			if(  destination == "PIS" ) { destination = "LIM";}
			if( $( "#results_num:hidden", "#hotel_results").length ) { $( "#results_num:hidden", "#hotel_results").remove();}
			
			var search_num_adults = $("#search_num_adults").val();
			$("select[rel=adults]").each(function(){
				search_num_adults = search_num_adults + "," + $(this).val();
			});
			var search_num_children = $("#search_num_children").val();
			$("select[rel=children]").each(function(){
				search_num_children = search_num_children + "," + $(this).val();
			});
			var search_num_infants = $("#search_num_infants").val();
			$("select[rel=infants]").each(function(){
				search_num_infants = search_num_infants + "," + $(this).val();
			});			
			var search_num_rooms = $("#search_num_rooms").val();
			if(search_num_rooms==null){search_num_rooms=1;}
			
			$.post( "hotel_results.html", 
				{ search_num_rooms:		search_num_rooms,
				  search_destination:   destination, 
				  search_checkin_date:  $("#search_checkin_date").val(),
				  search_checkout_date: $("#search_checkout_date").val(),  
				  search_num_adults:	search_num_adults, 
				  search_num_children:	search_num_children,
				  search_num_infants:	search_num_infants, 
				  search_holiday_type:	$("#search_holiday_type").val(), 
				  search_stars:			search_stars, 
				  search_searchby:		$("#search_searchby").val(), 
				  search_hotel_name:	htlname[ 0 ], 
				  search_hotel:         htlcd, 
				  ses_id:				ses_id },
				function( data ){ 
					$( "#" + showIn ).html( data ); 
					$( "#temp" ).remove( );			
					$( "#search_submit" ).removeAttr("disabled");					
					g_ses_id = $( "#ses_id", data ).val();
					if( $( "#htl_results" ).length ){
						var myTextExtraction1 = function( node )
						{  
							var $n = $( node );
							// extract data from markup and return it
							var $r = $n.find( ".sortHotelName" );
							if ( $r.length > 0 ) { return $r.html( ); }	else {  return $n.html( ); }
						}		
						if( $( "#results_num:hidden", "#hotel_results").length && $( "#results_num:hidden" ).val() > 0 ){		
							$( "#htl_results" ).tablesorter(      { debug: false, dateFormat: 'dd/mm/yyyy', sortList: [ [ 0, 0 ] ], textExtraction: myTextExtraction1} )
								   		       .tablesorterPager(  { container:            $( "#pager" ), positionFixed: false } );
						}
						else if($( "#results_num:hidden" ).length && $( "#results_num:hidden" ).val() <= 0 ){
							$( "#htl_results" ).tablesorter( { debug: false, dateFormat: 'dd/mm/yyyy', sortList: [ [ 0, 0 ] ], textExtraction: myTextExtraction } );
						}					
					}					
				} 
			);
			/*
 			$.post("/cgi-bin/lta.sh/includes/destination_guide.html", 
				   {search_destination:destination}, 
				   function( data1 ){ $("#destinationCyprus").html(data1);},
				   "html"
			); */
			$.ajax({
			  url: "destination_guide.html",
			  cache: false,
			  data:{search_destination:destination},
			  success: function(html){
				$("#destinationCyprus").html(html);
			  }
			});
	}
	else if ( fromWhere == 'searchincars' ){
	    /* check required fields */
		if( $("#search_pickup_date").val() == '' && $("#search_dropoff_date").val() == '' ){
			$("#errormsg").html("Pickup/DropOff Dates are required.");
			return false;
	    }

		if ( $("#search_pickup_location").val() == 'HTL' && $("#search_pickuphotel").val() == '' &&  $("#search_other_pickuphotel").val() == ''){
			$("#errormsg").html("You must provide a pickup hotel.");
			return false;
		}

		if ( $("#search_dropoff_location").val() == 'HTL' && $("#search_dropoffhotel").val() == '' &&  $("#search_other_dropoffhotel").val() == ''){
			$("#errormsg").html("You must provide a dropoff hotel.");
			return false;
		}

		$( "div.mainframe" ).prepend( "<span id='temp'><img src='/images2/loadinga.gif' alt='' />Please wait.</span>" );

		$("#search_submit").attr("disabled","disabled");
		$.post( "car_results.html",
			{ search_pickup_date:   	 $("#search_pickup_date").val(),
  			  search_pickup_time:  		 $("#search_pickup_time_hours" ).val() + ":" + $("#search_pickup_time_mins" ).val(),
			  search_pickup_location:    $("#search_pickup_location").val(),
			  search_pickuphotel:		 $("#search_pickuphotel option:selected").text(),
			  search_other_pickuphotel:  $("#search_other_pickuphotel").val(),
			  search_dropoff_date:		 $("#search_dropoff_date").val(),
			  search_dropoff_time:		 $("#search_dropoff_time_hours" ).val() + ":" + $("#search_dropoff_time_mins" ).val(),
			  search_dropoff_location:	 $("#search_dropoff_location").val(),
			  search_dropoffhotel: 	     $("#search_dropoffhotel option:selected").text(),
			  search_other_dropoffhotel: $("#search_other_dropoffhotel").val(),
			  ses_id:					 ses_id},
			function( data ){
				$( "#" + showIn ).html( data );
				$( "#temp" ).remove( );
				$( "#search_submit" ).removeAttr("disabled");
			}
		);
	}
	else if( fromWhere == 'searchintransfers' ){
		if($("#search_trf_choice").val() == "R" && ($("#search_trf_arrival_date").val() == "" || $("#search_trf_departure_date").val() == "")){
			$("#errormsg").html("Arrival and Departure dates are required");
			return;
		}
		else if ($("#search_trf_choice").val() == "A" && $("#search_trf_arrival_date").val() == "" ){
			$("#errormsg").html("Arrival date is required");
			return;
		}
		else if ($("#search_trf_choice").val() == "D" && $("#search_trf_departure_date").val() == "" ){
			$("#errormsg").html("Departure date is required");
			return;
		}
		if ( $("#search_trf_hotel option:selected").val() == '' &&  $("#search_other_trf_hotel").val() == ''){
			$("#errormsg").html("You must provide a hotel.");
			return false;		
		}		
		
		var trfhtlcd;
		var trfhtlname;
		
		if( $( "#search_other_trf_hotel" ).val() != "" && $("#search_trf_hotel option:selected").val() == ""){ 		
		    trfhtlcd   = '';
			trfhtlname = $( "#search_other_trf_hotel" ).val(); 
		}
		else if( $( "#search_trf_hotel option:selected" ).val() != "" ){
			trfhtlcd   = $( "#search_trf_hotel option:selected" ).val(); 
			trfhtlname = $( "#search_trf_hotel option:selected" ).text(); 
		}
		
		$( "div.mainframe" ).prepend( "<span id='temp'><img src='/images2/loadinga.gif' alt='' />Please wait.</span>" );
        $( "#search_submit" ).attr( "disabled","disabled" );
		$.post( "transfer_results.html", 					
			{ 
			  ses_id:				     $( "#ses_id" ).val(),
			  search_trf_airport:   	 $( "#search_trf_airport" ).val(), 
  			  search_trf_location:  	 $( "#search_trf_location" ).val(),
			  search_trf_choice:		 $( "#search_trf_choice" ).val(), 
			  search_trf_arrival_date:	 $( "#search_trf_arrival_date" ).val(),
			  search_trf_arrival_time:   $( "#search_trf_arrival_time_hours" ).val() + ":" + $( "#search_trf_arrival_time_mins" ).val(), 
 			  search_trf_departure_date: $( "#search_trf_departure_date" ).val(),
			  search_trf_departure_time: $( "#search_trf_departure_time_hours" ).val() + ":" + $( "#search_trf_departure_time_mins" ).val(),
			  search_trf_persons:		 $( "#search_trf_persons" ).val(),
			  search_trf_htl:			 trfhtlcd + ":" + trfhtlname			  
   		    },			  
			function( data ){ 
				$( "#" + showIn ).html( data ); 
				$( "#temp" ).remove( );			
				$( "#search_submit" ).removeAttr( "disabled" );} 
		);		
	}
}

function add_htl_to_my_travel_selection(htlcd,htlname,htldesc){
		if( htlname != null && htldesc != null ){		
			var $obj = $( "input.radio:checked" );			
			setHotelRatesTotal( $obj, htlcd, $obj.val(), r1, r2, r3, htlname, htldesc );
		}
}

function rooms_onchange( obj ){
	var roomsHtml = "";
	var roomsnum;
	var row;
	var $table      = $("#rooming");
    var $tableBody  = $("tbody",$table);	
	
	roomsnum = obj.value;
	$( ".removeRow" ).remove( );
	if( roomsnum == 1){ roomsHtml = ""; }
	else if( roomsnum > 1 ){		
		$row = $("#rooming tr:nth-child(2)");				
		for( var i = 0; i < Number(roomsnum) - 1 ; i ++ ){			
		    newRow = $row.clone();
			newRow.find("#search_num_rooms").remove();
			newRow.find("#search_num_adults").attr("rel","adults");
		    newRow.find("#search_num_children").attr("rel","children");
			newRow.find("#search_num_infants").attr("rel","infants");
			newRow.find("td").attr( "style", "padding-top:3px" );
			newRow.insertAfter($row).attr("class","removeRow");
		}
	}	
}

/* hide only*/
function hideColumns( tableid, colIndex, value ){
	var filterPattern = new RegExp('^' + value + '', 'i');
	// TO DO:check to see if the column was found.
	if ( colIndex > -1 ){
		// loop through each table body row and evaulate the proper cell.
		var bodyRows = $( "#" + tableid + " tbody tr" );
		bodyRows.each( function( n ){	
			if( this.childNodes[ colIndex ] != null ){
				if( filterPattern.test( $.trim( this.childNodes[ colIndex ].innerHTML ) ) ){
					this.style.display = 'none';
				}
			}	
		});				
	}
}
/* show only */
function showColumns( tableid, colIndex, value ){
	var filterPattern = new RegExp('^' + value + '', 'i');
	// TO DO:check to see if the column was found.
	if ( colIndex > -1 ){
		// loop through each table body row and evaulate the proper cell.
		var bodyRows = $( "#" + tableid + " tbody tr" );
		bodyRows.each( function( n ){	
			if( this.childNodes[ colIndex ] != null ){
				if( filterPattern.test( $.trim( this.childNodes[ colIndex ].innerHTML ) ) ){
					this.style.display = '';
				}
			}	
		});				
	}
}
function new_showbyDest_onclick( obj ){
	var pageNum = 0;
	var trel;
	var colNum;	
	/*** hide results ***/
    if  ( g_isIE ) { colNum = 2; }
    else           { colNum = 5; }
	if( !obj.checked ){ hideColumns( "results", colNum, obj.value ); }
	else{               showColumns( "results", colNum, obj.value ); }
}

function showbyDest_onclick( obj ){
	var pageNum = 0;
	var trel;	
	/*** hide/show results ***/
	if(!obj.checked){
		if ( $(".aresult[rel='" + obj.value + "']").length )
		$(".aresult[rel='" + obj.value + "']").hide();
		$("div.results > span.pageSeparator").each(function(){									
			pageNum++;										   
			//if page is empty then disable						
			if( $(this).children(":visible").length == 0 ){				
				//alert(pageNum + ' is empty');
				$("a[rel='" + pageNum + "']").attr("style", "background-color:lightgrey");
				trel = $("a[rel='" + pageNum + "']").attr("rel");
				$( "a[rel='" + pageNum + "']" ).attr( "rel"  , "disabled" + trel );
			}
		});		
		/* after hiding results and disabling pages go to the first non disabled page */
		$( "a[rel]" ).each( function( ){
			if( $( this ).attr( "rel" ) 					   !=  'prev'  
			 && $( this ).attr( "rel" ).indexOf( 'disabled' ) == -1 
			 && $( this ).attr( "rel" ) 					   !=  'next' ){
				$( this ).trigger( 'click' );
				return false; //to break; the for loop(each() function)
			}
		});
	}
	else
	{
		//instead of just doing ==> $(".aresult[rel='" + obj.value + "']").show();
    	if ( $(".aresult[rel='" + obj.value + "']").length ){ //if $(".aresult[rel='" + obj.value + "']") exist? then
			var tempNum = 0;
			var tempStr;
			var tempPrevious = -1;
			//alert( 'pagesNUM:' + $( "div.results > span.pageSeparator" ).length );
			$( "div.results > span.pageSeparator" ).each( function( ){
				$( this ).children( ".aresult" ).each( function( ){
					tempNum++;
					if($(this).attr("rel") == obj.value ){
						$(this).show();
						tempStr = $(this).attr( "id" );
						tempStr = tempStr.replace( "aresult", "" );
						tempStr = Math.ceil( tempStr / g_pagingGroupSize );
						if( tempPrevious == -1 || tempPrevious != tempStr ){
							tempPrevious = tempStr;
							$( "a[rel='disabled" + tempStr + "']" ).attr( "rel"  , tempStr );
							$( "a[rel='" + tempStr + "']" ).attr("style", "");
						}
					}
				});
			});
		}
	}
}

/*
 * 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;
}

/* transfers */
function calcTotalVehiclesPrice( obj, count ){
	var numVechicles  = $( "#" + obj.id + " option:selected" ).val() ;
	var priceVechicle =	$( "#search_trf_mean_cd__" + count ).val() 
	var total         = numVechicles * priceVechicle;
	$( "#totprice" + count ).text( total );
	$( "#vtot" ).text( total );	
}
function setVehicleTotal(objVal,compid,meancd,trfcd){
	$( "#vtot" ).text(objVal);
	$( "#comp_id:hidden", "#trfSearchResultsFrm" ).val( compid  );
	$( "#search_trf_mean:hidden",  "#trfSearchResultsFrm" ).val( meancd  );	
    $( "#search_trf_total:hidden", "#trfSearchResultsFrm" ).val( objVal  );	
    $( "#search_trf_code:hidden",  "#trfSearchResultsFrm" ).val( trfcd  );		
	
}
function add_trf_to_my_travel_selection(){
	$("#trfSearchResultsFrm").submit(function(){ /*NOOP*/ });
}



/* hotels */
function view_rates(search_country, 
					search_destination, 
					search_hotel, 
					search_hotel_name,
					g_ses_id, 
					compid,
					search_checkin_date, 
					search_checkout_date, 
					search_num_rooms,
					search_num_adults, 
					search_num_children, 
					search_children_ages,
					bmplncd,
					bmplndesc){		  
	$("#" + search_hotel + "loading").html("<img src='/images2/loadinga.gif' alt='' />");
	var disabledSearch   = $( "#search_submit" ).attr( "disabled" );
	if(!disabledSearch){
		$( "#search_submit" ).attr({ src: "/images2/find_button.gif",
										  alt: "waiting search to finish",
										  title: "please wait before searching again",
										  disabled: "disabled" });
	}
	$( "#moreinfo" + search_hotel ).css("display","none");
	$.post( "hotel_rates.html",
		{ ses_id:               g_ses_id,
		  comp_id:              compid,
		  search_num_rooms:		search_num_rooms,
		  search_country:       search_country,
		  search_destination:   search_destination,
   		  search_hotel: 	    search_hotel,
		  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,
		  mplncd:				bmplncd,
		  mplndesc:				bmplndesc
		},
		function(data){
		    $("#hotel-rates-"+search_hotel).hide();
			$("#hotel-rates-"+search_hotel).html(data);
			$("#hotel-rates-"+search_hotel).slideDown();
			disabledSearch = $( "#search_submit" ).attr( "disabled" );
			if( disabledSearch ){
				$( "#search_submit" ).removeAttr("disabled");
				$( "#search_submit" ).attr({ src: "/images2/find_button.gif",
												  alt: "Search",
												  title:"Search" });
				$("#" + search_hotel + "loading").hide();
				/* load selected radio choice to hidden values */
					var is_selected;
					is_selected = $("input.radioprice").is(":checked")
					if( is_selected ){	
						var htlInfo = $("input[class=radioprice][type=radio][checked]").attr( "id" ).split( "__" );		
						var htlprice = 0;
						if( search_num_rooms == "1"){ htlprice = $("input[class=radioprice][type=radio][checked]").val(); }
						else{  
							htlprice = $("#firstValue").text();
							/*$("input[class=radioprice][type=radio][checked]").nextAll('label').each( function( ){
								htlprice = Number( htlprice ) + Number( $(this).text() );
							});*/
						}
						var htlName;
						var htlDesc;
						var temp;
						if( $( "#ac_results" ).val() == "" ){
							for( var i = 0; i < hotelresults.length; i++ ) {
								temp           = hotelresults[ i ].split( "||", 7 );
								if( temp[ 5 ] == htlInfo[ 1 ] ){
									//htlName = temp[ 0 ];
									htlDesc = temp[ 6 ];
									break;
								}
							}	
						}
						$( "#search_hotel:hidden", 			"#htlSearchResultsFrm" ).val( htlInfo[ 1 ] );
						$( "#promo_code:hidden", 			"#htlSearchResultsFrm" ).val( htlInfo[ 2 ] );
						$( "#catg_code:hidden", 			"#htlSearchResultsFrm" ).val( htlInfo[ 3 ] );
						$( "#mpln_code:hidden", 			"#htlSearchResultsFrm" ).val( htlInfo[ 4 ] );		
						$( "#comp_id:hidden",   			"#htlSearchResultsFrm" ).val( htlInfo[ 5 ] );				
						$( "#search_destination:hidden",    "#htlSearchResultsFrm" ).val( $("#search_destination option:selected").val() );
						$( "#search_checkin_date:hidden",   "#htlSearchResultsFrm" ).val( $("#search_checkin_date").val() );
						$( "#search_checkout_date:hidden",  "#htlSearchResultsFrm" ).val( $("#search_checkout_date").val() );
						$( "#search_hotel_name:hidden",     "#htlSearchResultsFrm" ).val( search_hotel_name );
						$( "#search_hotel_desc:hidden",     "#htlSearchResultsFrm" ).val( htlDesc );
						$( "#total_price:hidden", 			"#htlSearchResultsFrm" ).val( htlprice );
					}
					else{
						alert('Hotel room/meal plan may not be available at the moment or you have not choose one.');
						return false;		
					}				
			}			
		} 
	);
}

function setHotelRatesTotal( $obj, htlcd, value, r1, r2, r3, htlname, htldesc ){
	var objid;
	if(typeof $obj.attr  == 'function'){objid = $obj.attr("id");}
	else{objid=$obj.id;}
	var htlInfo  = objid.split( "__" );		
	var htlprice;
	
	if(r2 != null && r3 != null){ htlprice = r1 + "," + r2 + "," + r3;	}
	else if( r2 != null ){ htlprice = r1 + "," + r2; }
	else{ htlprice = value; }
	var htlName;
	var htlDesc;
	var temp;
	if(htlname != null && htldesc != null){ htlName = htlname; htlDesc = htldesc; }
	else if( $( "#ac_results" ).val() == "" ){			
		for( var i = 0; i < hotelresults.length; i++ ) {
			temp           = hotelresults[ i ].split( "||", 7 );
			if( temp[ 5 ] == htlInfo[ 1 ] ){ 
				htlName = temp[ 0 ]; 
				htlDesc = temp[ 6 ]; 
				break;
			}
		} 							
	}																	/* 3915__26EBD__TWNSSV__HB__H265201 */								
	$( "#search_hotel:hidden", 		    "#htlSearchResultsFrm" ).val( htlInfo[ 1 ] );
	$( "#promo_code:hidden", 			"#htlSearchResultsFrm" ).val( htlInfo[ 2 ] );
	$( "#catg_code:hidden", 			"#htlSearchResultsFrm" ).val( htlInfo[ 3 ] );
	$( "#mpln_code:hidden", 			"#htlSearchResultsFrm" ).val( htlInfo[ 4 ] );
	$( "#comp_id:hidden",   			"#htlSearchResultsFrm" ).val( htlInfo[ 5 ] );
	$( "#search_destination:hidden",    "#htlSearchResultsFrm" ).val( $("#search_destination option:selected").val() );
	$( "#search_checkin_date:hidden", 	"#htlSearchResultsFrm" ).val( $("#search_checkin_date").val() );
	$( "#search_checkout_date:hidden",  "#htlSearchResultsFrm" ).val( $("#search_checkout_date").val() );	
	$( "#search_hotel_name:hidden",     "#htlSearchResultsFrm" ).val( htlName );
	$( "#search_hotel_desc:hidden",     "#htlSearchResultsFrm" ).val( htlDesc );		
	$( "#total_price:hidden", 			"#htlSearchResultsFrm" ).val( htlprice );	
	$(	"#id__" + htlcd + "__tot").html("Total Price &euro;&nbsp;" + value );
}

/* cars */
//         add_car_to_my_travel_selection('C734283','A1','81.15','A1 - DAIHATSU CUORE - A1','28/02/2009','10:00','ALC','','05/03/2009','10:00','ALC','')
function add_car_to_my_travel_selection( compid, carcd, price, cardesc, pud, put, puloc, puhtl, dod, dot, doloc, dohtl ){
		$( "#carSearchResultsFrm" ).submit( function( ){														  														  
			$( "#comp_id:hidden", 		           "#carSearchResultsFrm" ).val( compid  );
			$( "#search_car:hidden", 		       "#carSearchResultsFrm" ).val( carcd   );
			$( "#search_car_total:hidden", 	       "#carSearchResultsFrm" ).val( price   );
			$( "#search_car_desc:hidden", 		   "#carSearchResultsFrm" ).val( cardesc );
			
			$( "#search_pickup_date:hidden",	   "#carSearchResultsFrm" ).val( pud    );
			$( "#search_pickup_time:hidden",	   "#carSearchResultsFrm" ).val( put     );
			$( "#search_pickup_location:hidden",   "#carSearchResultsFrm" ).val( puloc   );
			$( "#search_pickuphotel:hidden",       "#carSearchResultsFrm" ).val( puhtl   );
			
			$( "#search_dropoff_date:hidden",	   "#carSearchResultsFrm" ).val( dod    );
			$( "#search_dropoff_time:hidden",	   "#carSearchResultsFrm" ).val( dot     );
			$( "#search_dropoff_location:hidden",  "#carSearchResultsFrm" ).val( doloc   );
			$( "#search_dropoffhotel:hidden",      "#carSearchResultsFrm" ).val( dohtl   );
		});
}

function add_car_misc( compid, search_destination, search_num_adults, search_children_ages, search_num_children, search_num_infants, search_pickup_date, search_pickup_time,search_dropoff_date, search_dropoff_time){
	$.post( "add_car_misc.html", 
		{ ses_id:               $( "#comp_id:hidden" ).val( ),
		  comp_id:              compid,
		  search_destination:   search_destination,    		  
		  search_children_ages: search_children_ages,
		  search_num_children:  search_num_children,
   		  search_num_adults:    search_num_adults, 
		  search_pickup_date:   search_pickup_date,
		  search_pickup_time:   search_pickup_time,
		  search_dropoff_date:  search_dropoff_date,
		  search_dropoff_time:	search_dropoff_time,
		  search_num_children_seats: $("chiseat").val(),
		  search_num_booster_seats:  $("bostseat").val()		  
		}, 
		function(data){ 
			alert(data);
		} 
	);		
/*	$( "#carAddMiscFrm" ).submit( function( ) {
		$( this ).ajaxSubmit({
	  		success: function(data) {
				alert(data);								
  			}
		});
	});*/
}

function travel_selection(){/*NOOP*/}
function pax_info(){
	if($("#paxinfosubmitbtn").length){
		
		$("input[id^=txtLast]").each(function(){
			if( $(this).val() == "" ){
				if( !$("#"+$(this).attr("id")+"r").length ){
				$("<span id='"+$(this).attr("id")+"r' class='errmsg'>Last name is required.</span>").insertAfter( "#"+$(this).attr("id") );
				}
				return false;
			}
			else if( $("'"+$(this).attr("id")+"r'").length ){ $("'"+$(this).attr("id")+"r'").remove(); }
		});
		
		$("input[id^=txtFirst]").each(function(){
			if( $(this).val() == "" ){
				if( !$("#"+$(this).attr("id")+"r").length ){
				$("<span id='"+$(this).attr("id")+"r' class='errmsg'>First name is required.</span>").insertAfter( "#"+$(this).attr("id") );
				}
				return false;
			}
			else if( $("'"+$(this).attr("id")+"r'").length ){ $("'"+$(this).attr("id")+"r'").remove(); }
		});			
		
		if( $("#txtEmail").length && $("#txtEmail").val() == ""  ){
			if(!$("#emailr").length ){
			$("<span id='emailr' class='errmsg'>Email is required.</span>").insertAfter("#txtEmail");}
			return false;			
		}		
		else if( $("#emailr").length ){ $("#emailr").remove(); }
		
		if( $("#txtPhone").length && $("#txtPhone").val() == ""  ){
			if(!$("#phoner").length ){			
			$("<span id='phoner' class='errmsg'>Phone is required.</span>").insertAfter("#txtPhone");}
			return false;
		}
		else if( $("#phoner").length ){ $("#phoner").remove(); }
				
		if( $("#txtAddr").length && $("#txtAddr").val() == ""  ){
			if(!$("#addressr").length ){
			$("<span id='addressr' class='errmsg'>Address is required.</span>").insertAfter("#txtAddr");}
			return false;
		}
		else if( $("#addressr").length ){ $("#addressr").remove(); }
		
		if( $("#txtCity").length && $("#txtCity").val() == ""  ){
			if(!$("#cityr").length ){			
			$("<span id='cityr' class='errmsg'>City is required.</span>").insertAfter("#txtCity");}
			return false;
		}		
		else if( $("#cityr").length ){ $("#cityr").remove(); }
		
		if( $("#txtCountry").length && $("#txtCountry option:selected").val() == ""  ){
			if(!$("#countryr").length ){
			$("<span id='countryr' class='errmsg'>Country is required.</span>").insertAfter("#txtCountry");}
			return false;
		}
		else if( $("#countryr").length ){ $("#countryr").remove(); }		
		
		if( $("#txtDriverLast").length && $("#txtDriverLast").val() == ""  ){
			if(!$("#dlr").length ){			
			$("<span id='dlr' class='errmsg'>Driver last name is required.</span>").insertAfter("#txtDriverLast");}
			return false;
		}
		else if( $("#dlr").length ){ $("#dlr").remove(); }				
		
		if( $("#txtDriverFirst").length && $("#txtDriverFirst").val() == ""  ){
			if(!$("#dfr").length ){			
			$("<span id='dfr' class='errmsg'>Driver first name is required.</span>").insertAfter("#txtDriverFirst");}
			return false;
		}
		else if( $("#dfr").length ){ $("#dfr").remove(); }		
				
		if( $("#txtDriverAge").length && $("#txtDriverAge").val() == ""  ){
			if(!$("#dar").length ){						
			$("<span id='dar' class='errmsg'>Driver age is required.</span>").insertAfter("#txtDriverAge");}
			return false;
		}
		else if( $("#dar").length ){ $("#dar").remove(); }
		
		if( $("#chkTerms").length && !$("#chkTerms").is(":checked") ){
			if( $("#chkTermserr").html() == "" ){						
			$("#chkTermserr").html("This field is required.");}
			return false;
		}
		else if( $("#chkTermserr").length ){ $("#chkTermserr").html(""); }
		
		return true;
	}
}

function loadTrfHotels(location){
	$("#hotels_compo").html("<div style='text-align:left; width:100%;'><img src='/images2/smallloading.gif' alt='' /></div>");
	$.post("ldhotellist.html", 
		{ search_trf_location:location }, 
		function(data){ 
			$("#hotels_compo").html(data);
		} 
	);
}

function remove_travel_selection( obj, sesid, compid ){
	var compitem;
	var counthtls = 0;	
	$( "div.hotelname" ).each( function( ){
		counthtls++;											   
	});	
	$.post("remove_travel_selection.html", 
		{ ses_id:sesid, comp_id:compid }, 
		function( data ){ 			
			if(compid.substr(0,1) == 'H'){
				compitem = 'htl';
			}
			if(compid.substr(0,1) == 'C'){
				compitem = 'car';
			}
			if(compid.substr(0,1) == 'T'){
				compitem = 'trf';
			}			
			$( "#" + compitem + "__" + sesid + "__" + compid ).remove();			
			//$("#isRemoved").html( data );
		} 
	);	
	/* Remove total section if this was the last items from the basket */
	if( counthtls == 1 ){ $( "#totalContinue" ).remove(""); }	
}


//function resetFilters(){
	/*
	$("#locfilters input").each(function(){
		$( this ).attr( "checked", "checked");
	});		*/		
/*	var colNum;
    if  ( g_isIE ) { colNum = 2; }
    else           { colNum = 5; }	
	$( "input.showby_destination:not(:checked)" ).each( function( ){
	    alert( $(this).val() );
		hideColumns( "results", colNum, $(this).val() );
	});	*/
//}
function checkForFiltering(){
	$("#locfilters input").each(function(){
		if( $( this ).attr( "checked" ) == "" ){
			/* hide results*/
			if( g_isIE )     {filterColumn( "results", 2, $( this ).val() );}
			else if( g_isNS ){filterColumn( "results", 5, $( this ).val() );}				
		}
	});
}





/*helper functions*/
/* 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 validate_travel_selection(){
	var tempF;
	/*car validation*/
	if( $( "#pickupdt" ).length && $( "#pickupdt" ).val() == "" ){ 
		$("#carerrormsg").html("Car hire Pickup date is required.");	
		$("#travelerrormsg").html("Car hire Pickup date is required.");
		return false;	
	}
	
	if( $( "#dropoffdt" ).length && $( "#dropoffdt" ).val() == "" ){ 
		$("#carerrormsg").html("Car hire Dropoff date is required.");	
		$("#travelerrormsg").html("Car hire Dropoff date is required.");		
		return false;	
	}	
	
	$( "input.carflightdetails" ).each(function(){
		if( $( this ).val() == "" ){
			$("#carerrormsg").html("Car hire flight details are required.");	
			$("#travelerrormsg").html("Car hire flight details are required.");
			tempF = true;
			return false;
		}
	});
	if (tempF == true){return false;}
	/* trf validation*/
	$( "input.trflightdetails" ).each(function(){
		if( $( this ).val() == "" ){
			$("#trferrormsg").html("Transfer flight details are required.");			
			$("#travelerrormsg").html("Transfer flight details are required.");		
			tempF = true;
			return false;		
		}											   
	});
	if (tempF == true){return false;}
}
//if(g_isNS){console.profileEnd();}

var sessionId;
function agentLogin(){
	$.post( "agent-login.p", 
		{ txtAgent:      $("txtAgent").val(), 
   		  txtUserID:     $("txtUserID").val(), 
		  txtPassword:   $("txtPassword").val() },
		function( data ){ 		     
			$( "#submitButton" ).after( data );
		} 
	);
}
