/* SEARCH FORM VALIDATION DIALOG */
function omniDialog(){
	var omniPos = $('.ShowLoc').position();
        $( "#omniError" ).dialog({ 
				//height: 200,
				modal: true,
				resizable: false,
				width:250,
				position:[omniPos.left+50,omniPos.top-80],
				dialogClass: 'omniDialog'
				});
		$('.omniError_list li').each(function(){
				$(this).hide();
        });
}

/* OMNIBOX */
if (typeof document.activeElement === 'undefined') {
	$(document)
		.focusin(function(e){ document.activeElement = e.target; })
		.focusout(function(){ document.activeElement = null; });
}
jQuery.expr[':'].focus = function(a){ return a === document.activeElement; }






$.widget( "custom.catcomplete", $.ui.autocomplete, {
            
		_renderMenu: function( ul, items ) {
			var self = this,
			
				currentCategory = "";
			$.each( items, function( index, item ) {
				if ( item.cat != currentCategory ) { 
					ul.append( '<li class="line"></li><li class="ui-autocomplete-category" cn="'+item.cat+'"><img src="/img/ui/' +item.cat + '.gif"></li>' );
					currentCategory = item.cat;
				}
				self._renderItem( ul, item );
			});
			ul.append('<li class="ui-menu-msg">'+$.typeTxt+'</li>');
		},
		
		_renderItem: function( ul, item) {
			
			var tie = item.tie; //marks loc header and depend. locs
			var v = item.v; //unique id
			
			var ll = (v == "")? $.listTxt : ''; //opener for list based on class "list"
			var map = (item.lat)? $.mapTxt : '';//suppress MAP if no geo-code
			
			var lh = (v != "" && tie != "")? 'refine_hide dep_loc' : ''; //hide all the dependent loc
			var ld = (v == "")? '"<a class="fui-span" v="'+v+'"></a>"' : '"<a  v="'+v+'"></a>"'; //set html for li items, either opener, depend., multi
			//var ld = (v == "")? '"<span class="ui-span" v="'+v+'"></span>"' : '"<a  v="'+v+'"></a>"'; //set html for li items, either opener, depend., multi
			var lat = item.lat;
			var lng = item.lng;
			var ad1 = item.ad1_label +' '+ item.ad2+', '+item.country; //change: if tie && f -> + country
			var f = (item.f == 0)? 'first' : '';
			
			return $( '<li class="'+item.cat+' '+lh+'" t="'+tie+'" f="'+f+'" ></li>' )
			.data( "item.autocomplete", item )
			.append( $( ld ).text(ad1)) //fill li item
			.append('<div class="ui-refine '+ll+'">'+ll+'</div><div class="ui-refine '+map+'" lat="'+lat+'" lng="'+lng+'">'+map+'</div>' )
			.appendTo( ul );
			
			}
	});
	


var cache = {};

$(function(){
	var fst;
	var list; 
	var iniLoc = $('#city').val();
		$( ".city" ).catcomplete({
			delay: 0,
			source: function( request, response) {
			var st = request.q.slice(0, 3);
			st = st.toLowerCase();
			var fst = request.q.toLowerCase();
		
			if (st in cache) {
				$('.locCh').val('');
			    response($.map(cache[st], function(item) {
					    if( item.ad1.toLowerCase().indexOf( fst ) != -1 ){
					    	
				return {
					    city: item.ad1,
					    cityH: item.city, 
					    country: item.country,
					    countryIso: item.countryIso,
					    value: item.ad1 +' ' + item.ad2 +', ' + item.country,
					    cat: item.cat,
					    v: item.v,
					    tie: item.tie,
					    ad1: item.ad1,
					    ad2: item.ad2,
					    lat: item.lat,
					    lng: item.lng,
					    ad1_label: item.ad1_label,
						f: item.f
				};
					    }
			    }))
					}else{
					
					$.ajax({
						url: "/CARLOCTXT/" + st + "_.txt",  
						dataType: "json",
						//scriptCharset: "utf-8",
						contentType:"text/html; charset=utf-8",
						error: function(){
							$("*:focus").val(iniLoc).addClass('omniError');
							omniDialog();
							$('.locErr').show();
						},
						success: function( data, status, xhr ) {	
							$('.locCh').val('');
							cache[st] = data;
							
							response( $.map( data, function( item ) { 
										
								if( item.ad1.toLowerCase().indexOf( fst ) != -1 ){	
									
								return {
									
									city: item.ad1,
									cityH: item.city, 
									country: item.country,
									countryIso: item.countryIso,
									value: item.ad1 +' ' + item.ad2 +', ' + item.country,
									cat: item.cat,
									v: item.v,
									tie: item.tie,
									ad1: item.ad1,
									ad2: item.ad2,
									lat: item.lat,
									lng: item.lng,
									ad1_label: item.ad1_label,
									f: item.f
									    
								}
								}
								
							}));	
						}
										
					});
					}
		},
		
		select: function( event, ui ) {
			//fill hidden fields       
			selected = true;
			if(ui.item.f == 0){
				event.preventDefault();
			};
			var omi = $(this).attr('id')+'U';
			$('#pulocList.'+omi+'').val(ui.item.v);
			$('#pulocCountry.'+omi+'').val(ui.item.countryIso);
			$('#dolocList.'+omi+'').val(ui.item.v);
			$('#dolocCountry.'+omi+'').val(ui.item.countryIso);
			$('#pucity.'+omi+'').val(ui.item.cityH);
			$('#docity.'+omi+'').val(ui.item.cityH);
			$(this).blur();
		},
		focus: function(event, ui){
			
			if(ui.item.f == 0){
				event.preventDefault();
			var dia = ui.item.tie;
				$('.dep_loc[t='+dia+']').show();
				adjCatHeight('City');
			}
		},
		close: function(event,ui){
			var omi = $(this).attr('id')+'U';
			//not to happen when clicked on map
			var locCh = $('.locCh').val();
			
			/*if($('#pulocList.'+omi+'').val()=='' && locCh != '1'){
				$(this).val(iniLoc).addClass('omniError');
				omniDialog();
				$('.locErrAb').show();
			};
			*/
		},
		minLength: 3,
		html: true,
		open: function() {
			adjCatHeight('City,Rail,Airport');
		$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
	}
		
	});

});	


var counterMap = {
	map: null,
	bounds: null
}

counterMap.init = function(selector, latLng, zoom) {
	var myOptions = {
	zoom:zoom,
	center: latLng,
	mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  this.map = new google.maps.Map($(selector)[0], myOptions);
	this.bounds = new google.maps.LatLngBounds();
}

	function selMarker(item){
							
							var name = item.ad1_label;
							var address = (item.ad2)? item.ad2+'<br>' : '';
							var address2 = item.city+'<br>'+item.country;
							var lat = (item.lat)? item.lat : "";
							var lng = (item.lng)? item.lng : "";
							var countryIso= item.countryIso;
							var country= item.country;
							var city= item.city;
							var v= item.v;
							var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng)); 
							
							counterMap.bounds.extend(point);
							
							var marker = new google.maps.Marker({
								position: point,
								map: counterMap.map
							});
							
							var infoWindow = new google.maps.InfoWindow();
							//var html='<div class="map_window"><div class="map_name">'+name+'</div><div class="iw" loc="'+v+'" co ="'+countryIso+'">'+$.selectLocTxt+'</div></div>';
								var html='<div class="map_window"><div class="map_name">'+name+'</div><div class="map_address"> '+address+''+address2+'</div><div class="iw" loc="'+v+'" co="'+countryIso+'" dp="'+city+ ' - '+name+ ' ' + item.ad2+', '+country+'" city ="'+city+'">'+$.selectLocTxt+'</div></div>';
							google.maps.event.addListener(marker, 'click', function() {
								infoWindow.setContent(html);
								infoWindow.open(counterMap.map, marker);
							});
								
	};

counterMap.placeMarkers = function(loc, tie, v) {
	var result = cache[loc]; //use cache from location ajax

		$.map( result, function( item ) { 
							if(v == '' && item.tie == tie && item.lat !=''){ //multi
								selMarker(item);
								counterMap.map.fitBounds(counterMap.bounds);
							}else if(v != '' && item.v == v && item.lat !=''){ //single or single depend
								selMarker(item);
							}
					
					});
	}


/*ADJUST HEIGHT OF CATEGORY LI TO HEIGHT OF ALL LOCATIONS IN THAT CATEGORY*/
function adjCatHeight(cat){
	var cma = cat.split(',');
	jQuery.each(cma, function(index, item) {
			var locHeight = $('.ui-menu li.'+item +':visible').length * 28 + 15; //- $('.refine_hide:visible').length * 1 + 10; //* 3 - 5;
			locH = (locHeight < 50)? 50 : locHeight;
    $('[cn='+item +']').height(locH);
   
});
};


/* CLEAR LOCATION INPUT */
function clearFld(fld){
$(fld).click(function(){
	$(this).find('input').val('').removeClass('omniError');	
	var hidFldsClass = $(this).find('input').attr('id');
	$('.'+hidFldsClass+'U').each(function(){
		$(this).val('');	
	});
	$(this).find('input').catcomplete('close');
	//close loc list
});
}


/* HIDE/SHOW MULTIPLE DIVS WITH THEIR OWN TOGGLERS
tab: class of "tab",cont: id of div to show/hide begins with cont,cont-tab: div to be shown,act: tab can be clicked,inact: current tab */
function toggleMulti(tab,cont,act,inact){
		
		$('.'+tab+'').click(function() {
			$('.'+tab+'').removeClass(''+act+'').addClass(''+inact+'');
			$('[id^='+cont+']').hide();
			var $this = $(this);
			var x = $this.attr("id");
			$('#'+cont+'-' + x).show();
			$this.toggleClass(''+act+' '+ inact+'');
		});
	}


/*HIDE/SHOW ONE DEPENDENT DIV WITH ONE TOGGLER*/
function toggleOne(tab,cont){
	$('.'+tab+'').click(function() {
			$('#'+cont+'').toggle();
	});
}

function toggleCheckbox(chbox,cont){
	$('#'+chbox+'').click(function() {
			$(this).is(':checked')? $('#'+cont+'').show() : $('#'+cont+'').hide();
			});
}

/* RADIO BTN REPLACEMENT */
function chRd(){
	 if ($('.rdRepl input').length) {
            $('.rdRepl').each(function(){ 
                $(this).removeClass('r_on');
            });
            $('.rdRepl input:checked').each(function(){ 
                $(this).parent('label').addClass('r_on');
            });
        };
}

function replRdBtn() {
       chRd();
       $('.rdRepl').click(function(){
       		   chRd()
       });
    };


/* RD BTN REPLACEMENT - special rd btn, AM/PM*/
    function rdChecked(rdg,rdsel){
    	$('input:radio[name='+rdg+']').click( function() {
			var rdGroup = $('input[name="'+$(this).attr("name")+'"]');
			for (var i=0; i < rdGroup.length; i++) {
			if ( $(rdGroup[i]).is(':checked') ) $(rdGroup[i]).parents('label').addClass(''+rdsel+'');
			else $(rdGroup[i]).parents('label').removeClass(''+rdsel+'');
			}
});
}
 
/* CHECKBOX REPLACEMENT */
function checkChecked(){
			$('input:checkbox').each(function(){ 
					$(this).is(':checked')? $(this).parent('label').removeClass('chBox_Off').addClass('chBox_On') : $(this).parent('label').removeClass('chBox_On').addClass('chBox_Off');
            }); 
            $('input:checkbox').bind('click', function(){ 
					$(this).is(':checked')? $(this).parent('label').removeClass('chBox_Off').addClass('chBox_On') : $(this).parent('label').removeClass('chBox_On').addClass('chBox_Off');
            });
}



function loadedGo(){
//console.log('google maps loaded');	
}

/*window.loadedGo = function(){
       console.log('google maps loaded');
   };*/
   
 function loadScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    //script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=loadedGo"; 
    script.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'maps.google.com/maps/api/js?sensor=false&callback=loadedGo';
    document.body.appendChild(script);
  }
  
 
/* hover for IE */
sfHover = function() {
	var sfEls = document.getElementById("mainNav").getElementsByTagName("li");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" hover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" hover\\b"), "");
			}
		}
	}
	if (window.attachEvent) window.attachEvent("onload", sfHover);

	
// :focus for IE7




/* ALL PAGES */
function pageSetup(){
	    var tabindex = 1;
    $(':input').each(function() {
            var $input = $(this);
            $input.attr("tabindex", tabindex);
            tabindex++;
    });
   
    loadScript();

/* SELECT MENUS */	
$('.book_steps .sel_timeD').dropkick({theme: 'time'}); //see time sel. for theme
$('.sel_timeD').dropkick({theme: 'time'}); //see time sel. for theme
$('.book_steps .sel_carD').dropkick({theme: 'car'}); //see car sel. for size
$('.source').dropkick({theme: 'standard',change: function (value){initDDErrorHandling(this);}});


/* CAR INFO DIALOGS */
  $( "#dialog" ).dialog({ 
		autoOpen: false,
		height: 400,
		modal: true,
		resizable: false,
		width: 550,
		draggable: false
	});
	
/* T&C DIALOG */
  $( "#tandcdialog" ).dialog({ 
		autoOpen: false,
		height: 400,
		modal: true,
		resizable: false,
		width: 550,
		draggable: false,
		close: function(event, ui){
			$('#tandcAjax').html('');		
		}
	});
	
	$('a.tandc').click(function() { 
			$('#tandcdialog').dialog('open');
			$('.tandcLoad').show();
			
	$.get( this.href,
		function(data) {
			$('.tandcLoad').hide();
			$('#tandcAjax').html(data);
		});
	return false;
	});
	
	$('a.sippnotelink').click(function() { 
			$('#tandcdialog').dialog('open');
			$('.tandcLoad').show();
	$.get( this.href,
		function(data) {
			$('.tandcLoad').hide();
			$('#tandcAjax').html(data);
		});
	return false;
	});
	
	
	 $( "#lxTandcDialog" ).dialog({ 
		autoOpen: false,
		height: 400,
		modal: true,
		resizable: false,
		width: 550,
		draggable: false
	});

	 $('.lx_tandc').click(function(){
	 	$('#lxTandcDialog').dialog('open');	 
	 });
	 
/* CAR ZOOM DIALOG */
  $( "#dialogZoom" ).dialog({ 
		autoOpen: false,
		/*height: 550, */
		modal: true,
		resizable: false,
		width: 315,
		draggable: false
	});
	
	$('a.zoom').click(function() { 
	$.get( this.href,
		function(data) {
			$('#dialogZoom').html(data);
			$('#dialogZoom').dialog('open');
		});
	return false;
	});

 $('.load,.loadResults').dialog({ 
		autoOpen: false,
		height: 100,
		modal: true,
		resizable: false,
		width: 400,
		draggable: false,
		dialogClass: 'patience'
	});
	
$('.cd_book').click(function(){
			$('.loadResults').dialog('open');							
});	

$('.close_btn').live('click',function(){
		var whichDialog = $(this).attr('dia');
		$('#'+whichDialog+'').dialog('close');
});
	
/* RADIO BTN, CHCK BX, SELECTS */
	replRdBtn();
	checkChecked();
	//$('.source').each(function(){useDD(this);});
	
	/* AM/PM RD BTN */
	rdChecked('ampmpu_rdBtn','ui_rdBtnChecked');
	rdChecked('ampmdo_rdBtn','ui_rdBtnChecked');
	
/* COUNTRY MENU */	
	$('.header_originTrigger').hover(function(){
		$('.cor').css({"display":"block"});
		$(this).mousemove(function(e){
			$('.cor').css('top', e.clientY + 10).css('left', e.clientX + 10);
		});
	},function(){
		$('.cor').css("display","none");
	});

	$('.header_originTrigger').click(function(){
		$('.cor').css("display","none");
		$('.origin_list').slideToggle('slow');
	});
	
	
	
	$('.origin_list').delegate('li', 'click', function(e){
		$('.header_originTrigger').html($(this).find('a').html());
		$('.origin_list').slideToggle('slow');
		$('input[name="site"]').val($(this).attr('class'));	
		$('#countryForm').submit();
		e.preventDefault();
	});
	
	$('.origin_list').delegate('.closeCountry', 'click', function(){
			$('.origin_list').slideToggle('slow');
	});
	
	
/* MAIN NAV */
		$('#mainNav > li').not('.aehome').hover(function(){	
			$(this).find('a').toggleClass('mainNav_hover');
		});

		$('.mainNav_subMenu').hover(function(){
			$(this+' a').toggleClass('mainNav_hover');
		});
	
/* ******************************************************************** */
/* ******* BEGIN : HEADER LOGIN CONTROLS SECTION : BrianR - 01Sept2011  */
/* ******************************************************************** */

if (jsloginStatus == "false"){
	
	//Check if error exists on LOGIN only!!!!!!
	if($('.loginContainer .errorText').length){
		$(".loginContainer").css("height","269px");
		$(".login_list").css("height","257px");
		$(".login_list").animate({"top": "0"}, "slow");
	}
	
	$('.loginHit').toggle(function(){
		if($(this+':animated').length == 0 && $('.loginContainer .errorText').length == 0){
			$(".loginContainer").css("height","222px");
			$(".login_list").css("height","203px");
			$(".login_list").animate({"top": "0"}, "slow");
		} else if($(this+':animated').length == 0 && $('.loginContainer .errorText').length){
			$(".loginContainer").css("height","269px");
			$(".login_list").css("height","257px");
			$(".login_list").animate({"top": "0"}, "slow");
		}
	},function(){
		if($(this+':animated').length == 0 && $('.loginContainer .errorText').length == 0){
			$(".login_list").animate({"top": "-269"}, "slow","linear",function(){
				$(".loginContainer").css("height","1px");
			});
		} else if($(this+':animated').length == 0 && $('.loginContainer .errorText').length){
			$(".login_list").animate({"top": "-269"}, "slow","linear",function(){
				$(".loginContainer").css("height","1px");
			});
		}
	});
} else {
	$('.loginHit').toggle(function(){
		if($(this+':animated').length == 0){
			$(".loginContainer").css("height","222px");
			$(".logout_list").animate({"top": "0"}, "slow");
		}
	},function(){
		if($(this+':animated').length == 0){
			$(".logout_list").animate({"top": "-222"}, "slow","linear",function(){
				$(".loginContainer").css("height","1px");
			});
		}
	});
}
	
	// Change label colors when focused
	$("input[name='username'], input[name='password']").focus(function(){
		$(this).prev("label").css("color","#81CCEA");
	}).blur(function(){
		$(this).prev("label").css("color","#5A8BA1	");
	});
	
	// Close submenu on focus out
	/*$('.header_log').focusout(function(){
			console.log("cat");
			var checkLoginSub = $(".loginContainer").css("height");
			if (checkLoginSub != "1px"){
				$(".login_list").animate({"top": "-188"}, "slow","linear",function(){
					$(".loginContainer").css("height","1px");
				});
			}
	});*/
	
	// Login : Cancel Header Logout
	$('.headerLogout').click(function(){
			$('.loginHit').click();
	});

/* ******************************************************************** */
/* ******** END : HEADER LOGIN CONTROLS SECTION  ********************** */
/* ******************************************************************** */	


}


/* SEARCH FORM AND OTHER FORMS SET UP  */
function formSetup(){
	

$("#city").focus();	
$(".city").keypress(function (evt) {
var charCode = evt.charCode || evt.keyCode;
if (charCode  == 13) { 
return false;
}
});

	
/* OPEN FORM IN SIDEBAR */	
$('.refine_modifyTrigger').click(function(){
		$('.step2').slideToggle('fast');
		});		

/* OPEN RECENT SEARCHES */	
	$('.step2_refineRecent').click(function(){
		$('.step2_recentSearch').slideToggle('fast');
	});
	
/* OPEN DO LOC */		
	toggleCheckbox('book_doPrompt','doLoc');
	
	
/* SET INITIAL CALENDAR */
	$("#pu_date").datepicker('setDate', '+3d');
	$("#do_date").datepicker('setDate', '+6d');
	

/* CLEAR LOC INPUT */
clearFld('.form_clearFld');	

//travel east dialog handler
		$('#book_East').click(function(){
			if($('#book_East').is(':checked')){
		$( "#goEast" ).dialog({ 
				height: 420,
				modal: true,
				resizable: false,
				width: 550
				});
			};
	});

		/* OMNIBOX */		
		var currSt;
		var currIn;
		$('.city').blur(function(){
			currSt = $(this).val().slice(0,3);
			currIn = $(this).attr('id');
		});  
		
		
	 var map = null;
	 //loadScript();
	    
		$('.city').catcomplete();
		
		//add hidden flds val
		$(".iw").live("click", function(){ 
				var iwt = $(this).attr('dp');
				//var iwt = $(this).parent('.map_window').find('.map_name, .map_address').text();
				var co = $(this).attr('co');
				var country = $(this).attr('country');
				var loc = $(this).attr('loc');
				var city = $(this).attr('city');
				//$('#'+currIn+'').val(city + ' - ' + iwt+ ', '+country ); //puts val in pu or do fld
				$('#'+currIn+'').val(iwt);
				if(currIn == 'city'){
				$('#pulocList').val(loc);
				$('#pulocCountry').val(co);
				$('#pucity').val(city);
				}else{
				$('#dolocList').val(loc);
				$('#dolocCountry').val(co);	
				$('#docity').val(city);
				}
				$('.city').catcomplete( "close" );
				$( "#map" ).dialog("close")
		});
		
		$(".MAP").live("click", function(){  
				$('.locCh').val('1');
					var lat = $(this).attr('lat');
					var lng = $(this).attr('lng');
					var vc = $(this).parent('li').find('a').attr('v');
					var v = (vc)? vc : '';
					var tie = $(this).parent('li').attr('t');
					
		$( "#map" ).dialog({ width: 520 });
		
		//initialize map after dialog opens
			var myLatLng = new google.maps.LatLng(lat, lng);
			counterMap.init('#map_canvas', myLatLng, 15);
				
				counterMap.placeMarkers(currSt, tie, v);
				//counterMap.placeMarkers('par', '6617', '2773');
						});
	
		
			/*	$('a.fui-span').live('mouseenter', function(){
						//$('a.fui-span').live('focusin', function(){
				var dia = $(this).parent('li').attr('t');
				$('.dep_loc[t='+dia+']').toggle();
				adjCatHeight('City');
		});*/
		
		$(".LIST, .ui-span").live("click", function(){  
				var dia = $(this).parent('li').attr('t');
				$('.dep_loc[t='+dia+']').toggle();
				adjCatHeight('City');
		});
};

	
/* OMNIBOX VALIDATION */
$('.ui-widget-overlay').live('click', function(){ if($("#omniError").dialog('isOpen')) $("#omniError").dialog("close"); });

var cityIni = $('#city').val();
$('#form1').live('submit', function(e){
		
		var form = true;
		
		/* check DO checkbox, wipe flds if unchecked */
		if(!$('#book_doPrompt').is(':checked')){
			$('.cityrU').each(function(){
				$(this).val('');
			});
			$('#cityr').val(cityIni);
		}
		
		if($('#book_doPrompt').is(':checked')){
			var locDOErr = $('#dolocList').val()==''? false : true;
		}
		
		/* check PU loc empty */
		var locErr = $('#pulocList').val()==''? false : true;
		
		/* check date combo */
		var puPm = $('#do_pm').is(':checked')? '0' : '12';
		var doPm = $('#pu_pm').is(':checked')? '0' : '12';
		var puTime = parseInt($('select[name="selDDpu_hours"]').val()) + parseInt(puPm);
		 puTime += $('select[name="selDDpu_min"]').val();
		var doTime = parseInt($('select[name="selDDdo_hours"]').val()) + parseInt(doPm);
		 doTime += $('select[name="selDDdo_min"]').val();
		
		var time = (doTime > puTime)? 'good' : 'bad';
		var puDate = $('#pu_date').val();
		var doDate = $('#do_date').val();
		if(doDate == puDate){
			var dateErr = (time == 'bad')? false : true;
		}else{
			var dateErr = true;
		}
		
		/* check East */
		var eastErr = $('#book_East').is(':checked')? false : true;
		
		if(locErr == false) form = false;
		if(locDOErr == false) form = false;
		if(dateErr == false) form = false;
		if(eastErr == false) form = false;
	
		
		if(form == false){
			omniDialog();
			if(locErr == false) $('.locErrEmpty').show();
			if(locDOErr == false) $('.locErrDOEmpty').show();
			if(dateErr == false) $('.dateErr').show();
			if(eastErr == false) $('.eastErr').show();
				
		e.preventDefault();
		}else{
		$('.load').dialog('open');
		}
});

		



function isTextNode(){
	// If this is a text node, return true.
	return( this.nodeType === 3 );
}

var gStateInputValue = "";
var prevSelectedCountryValue = "";
var cValue = "";

// Instantiate State dropdown for new SELECT GUI
function initStateDDCheck(formName,countrySelectName,countrySelectValue,formName,stateContainerClass,stateInputName){
	//change event of the dropkick
	showCorrectStateDD(formName,countrySelectValue,stateContainerClass,stateInputName);
	//Create detect for country dropdown change
	
	//change event of the dropkick
	$('.'+countrySelectName+' dd a').click(function(e) {
			 var text = $('#'+countrySelectName).find(":selected").val();
			 countrySelectValue = text;
			 //Hide all state DD
			 $(".stateDDShow").addClass("stateDDHide").removeClass("stateDDShow");
			 //Show correct OPTION and DL
			 $(".state_"+countrySelectValue).addClass("stateDDShow").removeClass("stateDDHide");
			 //Hide all DL for all countries
			 $("dl."+stateInputName).attr("style","display:none");
			 showCorrectStateDD(formName,countrySelectValue,stateContainerClass,stateInputName);
			 
	});
	$('.'+stateContainerClass+' dd a').click(function(e) {
			//console.log("state val0 : "+$('[name='+stateInputName+']').val());
			//$('[name='+stateInputName+']').val('DOG');
	});
}

function showCorrectStateDD(formName,countrySelectValue,stateContainerClass,stateInputName){
	gStateInputValue = stateInputName;
	//console.log("state val1 : "+$('[name='+stateInputName+']').val());
	//console.log("SELECTED : "+$('[name=state] :selected').val());
	switch (countrySelectValue){
		case "BR": // brazilian states		
		case "CA": // canadian provinces
		case "AU": // Aussie States
		case "ZA": //south africa
		case "US": // united States
			var cValue = $("dl."+countrySelectValue+" dt a").text();
			//console.log("countrySelectValue : "+countrySelectValue);
			//console.log("cValue :"+$("dl."+countrySelectValue+" dt a").contents().text());
			//Clear out all state DT text
			$("dl."+stateInputName+" dt a").text("").find("span.value").text("");
			//Clear form state val
			$('[name='+stateInputName+']').val("");
			//Set correct country DT
			if (cValue){
				$("dl."+countrySelectValue+" dt a").text(cValue)
			}
			
			//Clear out selected value
			$('#'+stateInputName).val("");
			//Show state container
			//Check if "required"
			if ($("#paymentrequiredclient").val == "required"){
				$('.'+stateContainerClass).attr("style","display:block").addClass("required");
			} else {
				$('.'+stateContainerClass).attr("style","display:block");
			}
			if ($("#"+formName+" .invalid").length > 0){
				$('.'+stateContainerClass).addClass("invalid");
			}
			//Show correct dropdown
			$("dl."+countrySelectValue).attr("style","display:block");
			break;		
		default: // no states
			//Hide everything
			$('[name='+stateInputName+']').val("");
			$(".formStateDD dl dt a").text("").find("span.value").text("");
			$('.'+stateContainerClass).attr("style","display:none").removeClass("required");
			$("dl."+stateInputName).attr("style","display:none");
			//Clear out all state DT text
			//$("dl."+stateInputName+" dt a").text("").find("span.value").text("");
			//console.log("state form : "+$('#'+stateInputName).attr("value"));
			//Clear form state value
			//$('#'+stateInputName).attr("value","");
			break;
	}	
}

//Check for browser vertical scrollbar
function checkScrollBar() {
	var hContent = $("body").height(); // get the height of your content
	var hWindow = $(window).height(); // get the height of the visitor's browser window
	if(hContent>hWindow) { // if the height of your content is bigger than the height of the browser window, we have a scroll bar
		return true;    
	} else {
        return false;
    }
}

function showErrorNextToButton(formName,errorMsgNearBtn){
	//Show error msg next to button
	if ($(formName+' .invalid').length > 0 && $(formName+' .errorTextBottom').length == 0){
		$(formName+' .btn_container .book_btn').after('<div class="resForm_tooltip errorTextBottom">'+errorMsgNearBtn+'</div>');
	}
}

function removeErrorNextToButton(formName){
	$(formName+' div').remove('.errorTextBottom');
}

//Handles error display from serverside errors
function runErrorCheck(thisForm,errorListName,errorListDesc,errorMsgNearBtn){
	if (errorListName != "" || errorListDesc != ""){
		var erFld = errorListName.split('|');
		jQuery.each(erFld, function(index) {
				// Need exception for Checkboxes due to different HTML structure
				if ($(thisForm+" li .required :input[type='checkbox']").length > 0){
					$(thisForm+' :input[name='+this+']').parent("li").addClass("invalid");
					$(thisForm+' :input[name='+this+']').parent().parent("li").addClass("invalid");
				} else {
					$(thisForm+' :input[name='+this+']').parent("li").addClass("invalid");
				}
		});
		var erItem = errorListDesc.split('|');
		jQuery.each(erItem, function(index) {
			$('.sserror_List').append('<li class="errorText">'+this+'</li>');		 
		});
		
		//Reposition a long page to error section
		if (checkScrollBar()){
			window.scrollTo(0, $('.errorText').position().top);
		}
		
		//Show error msg next to button
		if ($(thisForm+' .errorTextBottom').length == 0){
			$(thisForm+' .btn_container .book_btn').after('<div class="resForm_tooltip errorTextBottom">'+errorMsgNearBtn+'</div>');
		}
	}
}

	
//Handles clientside error handling
function subformVal(thisForm,errorMsgNearBtn){
	$(thisForm).removeClass("invalid");
	//Clear * in "notrequired" LI
	$(thisForm+' .notrequired').not('.required').find('label span').text("");
	//Set * in "required" spans that are empty
	if ($(thisForm+' .required span').text() == ""){
		$(thisForm+' .required span').text("*")
	}
	$(thisForm).bind("submit", function(e) {
		var isValid = true;
		$(thisForm+' li .required').each(function(){
			$(this).removeClass("invalid");
			var stateCheck = $(this).hasClass("formStateDD");
			// Check value for input fields except for State
			if (stateCheck == false && ($(this).find("input").val() == "" || $(this).find(":selected").val() == "")){
				isValid = false;
				$(this).addClass("invalid");
			} else if (stateCheck == true && ($(this).find("input").val() == "" || $(this).find(":selected").val() == "")){
				//Check only active OPTION is checked not all of them since some are hidden
				var formStateVal = $('[name='+gStateInputValue+']').val();
				if (formStateVal == ""){
					isValid = false;
					$(this).addClass("invalid");
				}
			}
			if (thisForm == "#ccform" && $("#tc").attr("checked") == false ){
					isValid = false;
					$(".tcCheck").parent().parent("li").addClass("invalid");	 
			}
			//Prevent form action to trigger until true
			if(isValid == false){	         	 		         	 	
				e.preventDefault();
        	}
		});    
		
		if(isValid == false){	         	 		         	 	
			e.preventDefault();
        } else {
        	$('.loadResults').dialog('open');
        }
		showErrorNextToButton(thisForm,errorMsgNearBtn);
	});
	
	//CHECK INPUTS
	//$(thisForm+' .required input').unbind("focus");
	$(thisForm+' .required input').live("focus", function(){
		$(this).parent().removeClass("invalid");
		removeErrorNextToButton(thisForm);
	}).blur(function(){
		if ($(this).val() == "" && $(this).parent("li").hasClass("required") ){
			$(this).parent("li").addClass("invalid");
		};
	});	
	
	//CHECK DROPDOWNS
	//$(thisForm+' .required .dropdown').unbind("click");
	$(thisForm+' .required .dropdown').live("click", function(){  
		$(this).parent().parent().removeClass("invalid");
		removeErrorNextToButton(thisForm);
	}).blur(function(){
		if ($(this).find(":selected").val() == "" && $(this).parent().parent("li").hasClass("required")){
			$(this).parent().parent("li").addClass("invalid");
		};
	});
	
	//CHECK CHECKBOXES
	//$(thisForm+' .required input[type=checkbox]').unbind("change");
	$(thisForm+' .required input[type=checkbox]').live("change", function(){
			if ($(this).is(':checked')){
				$(this).attr("value","Y");
			} else {
				$(this).attr("value","");
			}
			//checkChecked();
		$(this).parent().parent().removeClass("invalid");
		removeErrorNextToButton(thisForm);
	}).blur(function(){
		if ($(this).find(":checked").val() == "" && $(this).parent().parent("li").hasClass("required")){
			$(this).parent().parent("li").addClass("invalid");
		};
	});

/* END FORM VALIDATION */
}

//Handles clientside error handling for Payment Form
function subformValCC(thisForm,errorMsgNearBtn){
	$(thisForm).removeClass("invalid");
	
	$(thisForm).bind("submit", function(e) {
		var isValid = true;
		$(thisForm+' li .required').each(function(){
			$(this).removeClass("invalid");
			
			if (thisForm == "#ccform" && $("#tc").attr("checked") == false ){
					isValid = false;
					$(".tcCheck").parent().parent("li").addClass("invalid");	 
			}
			
			//Prevent form action to trigger until true
			if(isValid == false){	         	 		         	 	
				e.preventDefault();
        	} else {
        		$('.loadResults').dialog('open');
        		
        	}
		});    
		
		showErrorNextToButton(thisForm,errorMsgNearBtn);
		
	});
	
	//CHECK INPUTS
	//$(thisForm+' .required input').unbind("focus");
	$(thisForm+' .notrequired input').live("focus", function(){
		$(this).parent().removeClass("invalid");
		removeErrorNextToButton(thisForm);
	}).blur(function(){
		if ($(this).val() == "" && $(this).parent("li").hasClass("notrequired") ){
			$(this).parent("li").addClass("invalid");
		};
	});	
	
	//CHECK DROPDOWNS
	//$(thisForm+' .required .dropdown').unbind("click");
	$(thisForm+' .notrequired .dropdown').live("click", function(){  
		$(this).parent().parent().removeClass("invalid");
		removeErrorNextToButton(thisForm);
	}).blur(function(){
		if ($(this).find(":selected").val() == "" && $(this).parent().parent("li").hasClass("notrequired")){
			$(this).parent().parent("li").addClass("invalid");
		};
	});
	
	
	//CHECK CHECKBOXES
	//$(thisForm+' .required input[type=checkbox]').unbind("change");
	$(thisForm+' .required input[type=checkbox]').live("change", function(){
			if ($(this).is(':checked')){
				$(this).attr("value","Y");
			} else {
				$(this).attr("value","");
			}
			//checkChecked();
		$(this).parent().parent().removeClass("invalid");
		removeErrorNextToButton(thisForm);
	}).blur(function(){
		if ($(this).find(":checked").val() == "" && $(this).parent().parent("li").hasClass("required")){
			$(this).parent().parent("li").addClass("invalid");
		};
	});
	
	//Check CC# only if paymentrequired == "notrequired"
	/*if ($('#paymentrequired').val() == "notrequired"){
		$(thisForm+' #cardNumber').live("focusout", function(){  
			if ($(this).val() != ""){
				makeFormRequired(thisForm);
			} else {
				makeFormNotRequired(thisForm);
			}
		});
	}*/

/* END FORM VALIDATION */
}

function makeFormRequired(formName){
	$(formName+' .notrequired').addClass("required");
	$(formName+' .required').not('.resForm_newsCB').find('label span').replaceWith('<span>*</span>');
	$('#paymentrequiredclient').val("required");
	//subformVal(formName);	
}
function makeFormNotRequired(formName){
	$(formName+' .notrequired').removeClass("required");
	$(formName+' .notrequired').removeClass("invalid")
	$(formName+' .notrequired span').replaceWith('<span></span>');
	$('#paymentrequiredclient').val("notrequired");
	//subformVal(formName);	
}


/* HP SETUP */
function hpSetup(){
/* TOGGLE NEW/EXISTING RES */
	toggleMulti('resTab','tabC','resTab_active','resTab_inactive');
	
	$('#newRes').click(function(){
			if($('#pulocList').val()==''){
				$("#city").focus();
			}
	});
	
/* RESOURCE SLIDER */
		$('.rl_wrap').click(function(){
			//$(this).parent('li').siblings('li').switchClass('expand','fold',500,'easeOutBounce');
			$(this).parent('li').siblings('.expand').switchClass('expand','fold',500,'easeOutBounce');
			$(this).parent('li').switchClass('fold','expand',500,'easeOutBounce');
		});

	
/* MANAGE RES - HAVE VOUCHER? */
	$('.voucherQ input:radio').click( function() {
		var rdGroup = $('input[name="'+$(this).attr("name")+'"]');
		$('.vYesV input, .vNoV input').val('');
		for (var i=0; i < rdGroup.length; i++) {
		if ( $(rdGroup[i]).is(':checked') ) $('.'+$(rdGroup[i]).val()+'').show()
		else $('.'+$(rdGroup[i]).val()+'').hide();
		}
	});
	
	
}

//Initialize car rate Status
var jsRatesStatus = true;

function checkCarsRateStatus(param){
	jsRatesStatus =	param;
	if (jsRatesStatus == false){
		$('.refine_modifyTrigger').click();			
	}
}

// support Share This button used on news articles
function showhidesharethis() {
	if (document.getElementById('sharebox').style.display == 'block') {
		document.getElementById('sharebox').style.display = 'none';
	}
	else {
		document.getElementById('sharebox').style.display = 'block';
	}
}
function autohide() {
	document.getElementById('sharebox').style.display = 'none';
}


//**************************************************************
//**************************************************************
//*******     Instantiate State dropdown Regular     ***********
//**************************************************************
//**************************************************************

function initStateDDCheckReg(formName,countrySelectName,selectedCountryValue,stateContainerClass,stateInputName){
	var cLabel = $('#'+countrySelectName+' option:selected').text();
	var text = $('#'+countrySelectName+' option:selected').val();
	showCorrectStateDDReg(formName,cLabel,selectedCountryValue,stateContainerClass,stateInputName);
	//Create detect for country dropdown change
	$('#'+countrySelectName).change(function(e) {
			cLabel = $('#'+countrySelectName+' option:selected').text();
			text = $('#'+countrySelectName+' option:selected').val();
			countrySelectValue = text;
			$('[name='+stateInputName+']').val("");
			$(".stateDDShow").addClass("stateDDHide").removeClass("stateDDShow");
			showCorrectStateDDReg(formName,cLabel,countrySelectValue,stateContainerClass,stateInputName);
			 
	});
}

function showCorrectStateDDReg(formName,cLabel,selectedCountryValue,stateContainerClass,stateInputName2){
	gStateInputValue = stateInputName2;
	switch (selectedCountryValue){
		case "BR": // brazilian states		
		case "CA": // canadian provinces
		case "AU": // Aussie States
		case "ZA": //south africa
		case "US": // united States
			$('.stateDDHide').removeAttr("id").removeAttr("name");
			$('.state_'+selectedCountryValue).removeClass("stateDDHide").addClass("stateDDShow").attr({id:stateInputName2, name:stateInputName2});
			if ($("#"+formName+" #paymentrequiredclient").val == "required"){
				$('.'+stateContainerClass).attr("style","display:block").addClass("required");
			} else if ($("#"+formName+" #paymentrequiredclient").val == "notrequired") {
				$('.'+stateContainerClass).attr("style","display:block");
			} else {
				$('.'+stateContainerClass).attr("style","display:block").addClass("required");
			}
			if ($("#"+formName+" .invalid").length > 0){
				$('.'+stateContainerClass).addClass("invalid");
			}
			break;		
		default: // no states
			$('.stateDDHide').removeAttr("id").removeAttr("name");
			$('[name='+stateInputName2+']').val("");
			$('.'+stateContainerClass).attr("style","display:none").removeClass("required");
			break;
	}	
}

//**************************************************************
//**************************************************************
//*******     Instantiate State dropdown DROPKICK     ***********
//**************************************************************
//**************************************************************

function showCorrectStateDDDropkick(formName,cLabel,selectedCountryValue,stateContainerClass,stateInputName2){
	prevSelectedCountryValue = cValue;
	cValue = selectedCountryValue;
	gStateInputValue = stateInputName2;
	switch (selectedCountryValue){
		case "BR": // brazilian states		
		case "CA": // canadian provinces
		case "AU": // Aussie States
		case "ZA": //south africa
		case "US": // united States
			//$('.stateDDHide').removeAttr("id").removeAttr("name");
			//$('.state_'+selectedCountryValue).removeClass("stateDDHide").addClass("stateDDShow").attr({id:stateInputName2, name:stateInputName2});
			$(".stateDDShow").addClass("stateDDHide").removeClass("stateDDShow");
			$('#dk_container_state_'+selectedCountryValue).addClass('stateDDShow').removeClass('stateDDHide');
			
			//Change old state SELECT ID and NAME
			if (prevSelectedCountryValue){
				$('#'+stateInputName2).removeAttr("name").attr({id:'state_'+prevSelectedCountryValue});
			}
			
			//Set ID and NAME attributes
			$('#state_'+selectedCountryValue).attr({id:stateInputName2, name:stateInputName2});
			
			if ($("#"+formName+" #paymentrequiredclient").val == "required"){
				$('.'+stateContainerClass).attr("style","display:block").addClass("required");
			} else if ($("#"+formName+" #paymentrequiredclient").val == "notrequired") {
				$('.'+stateContainerClass).attr("style","display:block");
			}
			if ($("#"+formName+" .invalid").length > 0){
				$('.'+stateContainerClass).addClass("invalid");
			}
			break;		
		default: // no states
			//$('.stateDDHide').removeAttr("id").removeAttr("name");
			if (prevSelectedCountryValue){
				$('#'+stateInputName2).removeAttr("name").attr({id:'state_'+prevSelectedCountryValue});
			}
			$('[name='+stateInputName2+']').val("");
			$('.'+stateContainerClass).attr("style","display:none").removeClass("required");
			break;
	}	

}




function initDDErrorHandling(param){
	$(param).parent().parent().removeClass("invalid");
}



