/*
CSS Browser Selector v0.4.0 (Nov 02, 2010)
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector##contributors
*/
function css_browser_selector(u){var ua=u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1},g='gecko',w='webkit',s='safari',o='opera',m='mobile',h=document.documentElement,b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3.6')?g+' ff3 ff3_6':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('blackberry')?m+' blackberry':is('android')?m+' android':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?m+' j2me':is('iphone')?m+' iphone':is('ipod')?m+' ipod':is('ipad')?m+' ipad':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win'+(is('windows nt 6.0')?' vista':''):is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;};
css_browser_selector(navigator.userAgent);

//use .is(":focus")
/*jQuery.extend(jQuery.expr[':'], {
  focus: "a == document.activeElement"
});*/

/*PRELOADER*/
$.fn.preload = function() {
	this.each(function(){
		$('<img/>')[0].src = this;
	});
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = $.trim(ca[i]);
		//while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function eraseCookie(name) {
	createCookie(name,"",-1);
}



/* 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; }
*/

/* AUTOCOMPLETE SEARCHES BEGINNING OF STRING */
function firstCharsAutocomplete(){

    $.extend($.ui.autocomplete, {
        filter: function(array, term){
            var matcher = new RegExp("^" + term, "i");

            return $.grep(array, function(value){
                return matcher.test(value.label || value.value || value);
            });
        }
    });
}


firstCharsAutocomplete();

$.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 desk id
			var ll = (v == "")? $.listTxt : ''; //if this is header, "LIST" link
			var map = (item.lat)? $.mapTxt : '';//if geocode, "MAP" link
			var lh = (v != "" && tie != "")? 'refine_hide dep_loc' : ''; //hide all sublocations
			var lat = item.lat;
			var lng = item.lng;
			var city = item.cityH; //just city name
			var AR_city = item.AR_city; //to drop air/rail pins with header map
			var ad1 = item.LI_label; //display loc in autosuggest list
			var f = (item.f == 0)? 'first' : ''; //check to not close omnibox when header is clicked
			var ld = (v == "")? '"<span class="fui-span" v="'+v+'"></span>"' : '"<a  v="'+v+'"></a>"'; //set html for li items, either opener, depend., multi
			var lf =  item.ad1.slice(0, 3).toLowerCase()//3-letter loc code
			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+'" lf="'+lf+'" AR_city="'+AR_city+'">'+map+'</div>' )
			.appendTo( ul );
			
			}

        
	});
	


var cache = {};
var lsCh;
var selected;
var locs;

$(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, //just city name
									country: item.country,
									countryIso: item.countryIso,
									tie: item.tie,
									value: item.FLD_label,
									cat: item.cat,
									v: item.v,
									ad1: item.ad1,
									ad2: item.ad2,
									lat: item.lat,
									lng: item.lng,
									LI_label: item.LI_label,
									FLD_label: item.FLD_label,
									AR_city: item.AR_city,
									f: item.f
				};
					    }
			    }))
					}else{
					
					$.ajax({
						url: "/CARLOCTXT/" + $.siteCode + "/" + st + "_.txt",  
					//	url:'http://ae-us-new.aemaine.com/car_location_NOFILE.cfm?c_part='+st+'&carloc_country='+ $.siteCode +'',
						dataType: "json",
						error: function(){
							$("*:focus").val(iniLoc).addClass('omniError');
							omniDialog();
							$('.locErr').show();
							var pudoDiff = $(this).attr('id');
							$('#dataDiv'+pudoDiff+'').removeData('lsInput');
						},
						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,
									tie: item.tie,
									value: item.FLD_label,
									cat: item.cat,
									v: item.v,
									ad1: item.ad1,
									ad2: item.ad2,
									lat: item.lat,
									lng: item.lng,
									LI_label: item.LI_label,
									FLD_label: item.FLD_label,
									AR_city: item.AR_city,
									f: item.f
									    
								}
								}
								
							}));	
						}
										
					});
					}
		},
		
		select: function( event, ui ) {
			//fill hidden fields       
			selected = true; //true when li loc selected (but not map loc)
			if(ui.item.f == 0){ //don't close when header is clicked
				event.preventDefault();
			};
			var omi = $(this).attr('id')+'U';
			var pudoDiff = $(this).attr('id');
			$('#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);
			
			$('#dataDiv'+pudoDiff+'').data({'lsSelect':ui.item.value,'lsCity':ui.item.cityH});
			if(ui.item.f != 0 && ui.item.tie !=''){
				$('#dataDiv'+pudoDiff+'').data({'lsSub':ui.item.cityH});
			}else{
				$('#dataDiv'+pudoDiff+'').removeData('lsSub');
			}
					lsCh = '2'; //li loc selected (but not map loc)
					
			$('#dataDiv'+pudoDiff+'').removeData('lsInput');		
			
			var mySearch = encodeURIComponent(ui.item.cityH+'||'+ui.item.value+'||'+ui.item.v+'||'+ui.item.countryIso);
			createCookie('ltSearch'+pudoDiff+'', mySearch );
			
		},
		focus: function(event, ui){
			if(ui.item.v != ''){
				//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();
			locs = false;
		},
		change: function(event, ui) { 
			//select and blur
		},
		
		minLength: 3,
		html: true,
		open: function() {
			$( "#omniError" ).dialog('close');
			var omi = $(this).attr('id');
			$('.ui-menu-msg').removeClass('cityrmsg');
			$('.ui-menu-msg').removeClass('citymsg');
			$('.ui-menu-msg:visible').addClass(omi+'msg'); //adds class to only visible autosuggest list
			adjCatHeight('City,Rail,Airport');
		$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
		
		//error msg if ajax success but run out of results
		//ended up in the open event because error msg got triggered when typing faster than autosuggest could open list
$(".city").keyup(function(evt){ 
		var omi = $(this).attr('id');
		var charCode = evt.charCode || evt.keyCode; //need that to not trigger error msg when map link is clicked
if (charCode  != 13) { 
		if($(this).val().length >3 && $('.'+omi+'msg').is(':hidden')){ //checks if autosuggest list has closed
			omniDialog();
				$('.locErr').show();
				$(this).val("");
				$('.'+omi+'U').val(''); //clears all hidden input fld for either PU or DO
		}
}
});
	
	}
		
	});

});	


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="map_address"> '+address+''+address2+'</div><div class="iw" loc="'+v+'" co="'+countryIso+'" dp="'+item.FLD_label+'" 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, stadt, f) {
	var result = cache[loc]; //use cache from location ajax
		$.map( result, function( item ) { 
				if(stadt !="" && tie !="" && f=='first'){ //multi, single: add air/rail pins
								if(item.AR_city == stadt && item.lat !="" && item.f != "0.0"){
									
									selMarker(item);
								}
								counterMap.map.fitBounds(counterMap.bounds);
				}else if(item.v == v){ //sub, air, rail: pin only this loc stadt =="" && 
								
								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; 
			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').not('.chbxS').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').not('.chbxS').bind('click', function(){ 
					$(this).is(':checked')? $(this).parent('label').removeClass('chBox_Off').addClass('chBox_On') : $(this).parent('label').removeClass('chBox_On').addClass('chBox_Off');
            });
}


/* CHECKBOX REPLACEMENT for CHBX THAT CAN BE SET TO STANDARD/DK*/
function chBxDKS(){
			$('input:checkbox.chbxS').each(function(){ 
					$(this).is(':checked')? $(this).parent('label').removeClass('chBx_Off').addClass('chBx_On') : $(this).parent('label').removeClass('chBx_On').addClass('chBx_Off');
            }); 
            $('input:checkbox.chbxS').bind('click', function(){ 
					$(this).is(':checked')? $(this).parent('label').removeClass('chBx_Off').addClass('chBx_On') : $(this).parent('label').removeClass('chBx_On').addClass('chBx_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"))? 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($('#mainNav')){	
	if (window.attachEvent) window.attachEvent("onload", sfHover);
}

	
// :focus for IE7




/* ALL PAGES */
function pageSetup(){
	
	/* 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();
		}
	});
	
	    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);}});
$('.date').dropkick({theme: 'halfStandard',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");
			});
		}
	});
}
	
	
	// Login : Cancel Header Logout
	$('.headerLogout').click(function(){
			$('.loginHit').click();
	});

/* ******************************************************************** */
/* ******** END : HEADER LOGIN CONTROLS SECTION  ********************** */
/* ******************************************************************** */	

	$('#HasTravelDetails').change(function(){
		var tdl = $('#HasTravelDetails:checked').length;
		$('input[name=tdv]').attr("value", tdl);
		$('#travelDetailsTA').toggle(this.checked);
	}).change();

}


/* SEARCH FORM AND OTHER FORMS SET UP  */
function formSetup(){
	
	
	
	
	if( readCookie('ltSearchcityr') != null ) { 
		$('#book_doPrompt').attr('checked','checked');
		$('input[name=insuranceFilter]').attr('checked', true);
		chBxDKS();
		$('#doLoc').show();
	};
	
var sipplist = window.location.href.indexOf('sipplist');
	
	
/* SET INITIAL FORM */
if( readCookie('ltTimePU') != null ) { 
	var pudate = readCookie('ltTimePU');
	var dodate = readCookie('ltTimeDO');
	var pu_date = decodeURIComponent(pudate).split('||');
	var do_date = decodeURIComponent(dodate).split('||');
	$("#pu_date").datepicker('setDate', pu_date[0]);
	$("#do_date").datepicker('setDate', do_date[0]);
	$('select[name="selDDdo_hours"]').val(do_date[2]).change();
	$('select[name="selDDdo_min"]').val(do_date[3]).change();
	$('select[name="selDDpu_hours"]').val(pu_date[2]).change();
	$('select[name="selDDpu_min"]').val(pu_date[3]).change();
	
	
	if(sipplist < 0){
		$('#carType').val(do_date[4]).change();	
	}
	
	
	
	if($.display24Hour=='false'){
		if(pu_date[1] == '12'){
		$('#pu_pm').attr('checked', true);
		$('.ui_rdBtnLblRight[for="pu_pm"]').addClass('ui_rdBtnChecked');
		$('.ui_rdBtnLblLeft[for="pu_am"]').removeClass('ui_rdBtnChecked');
		}
		if(do_date[1] == '12'){
		$('#do_pm').attr('checked', true);
		$('.ui_rdBtnLblRight[for="do_pm"]').addClass('ui_rdBtnChecked');
		$('.ui_rdBtnLblLeft[for="do_am"]').removeClass('ui_rdBtnChecked');
		}
	}
}else{
	$("#pu_date").datepicker('setDate', '+3d');
	$("#do_date").datepicker('setDate', '+6d');
	
}	


rdChecked('ampmpu_rdBtn','ui_rdBtnChecked');
rdChecked('ampmdo_rdBtn','ui_rdBtnChecked');	
	
	
		
function repeatSearch(r, pd){
	
var ltSKekse = readCookie('ltSearch'+r+'');
	if(ltSKekse){
		var ltSKrummel = decodeURIComponent(ltSKekse).split('||');
		$('#'+pd+'locList').val(ltSKrummel[2]);
		$('#'+pd+'city').val(ltSKrummel[0]);
		$('#'+pd+'locCountry').val(ltSKrummel[3]);
		
	}
	
	
		$('#'+r+'').click(function(){
			lsCh = '1'; //omnibox closed w/o selection from list (map selections get lsCh=1 as well) set lsCh to 2 for map loc but to 1 for map link?
			
			var ltSInput = $('#dataDiv'+r+'').data("lsInput");
			var ltSSelect = $('#dataDiv'+r+'').data("lsSelect");
			var ltSCity = $('#dataDiv'+r+'').data("lsCity");
			var ltSSub = $('#dataDiv'+r+'').data("lsSub");
			
			
			$(this).val('');
			
			if(ltSInput){
				$(this).catcomplete( "search" , ltSInput );
			}else{
				$(this).catcomplete( "search" , ltSCity );
			}
			if(!ltSInput && !ltSSelect && ltSKekse){
				$(this).catcomplete( "search" , ltSKrummel[0] );
			}
			
			
	});
		
/*	$('#'+r+'').blur(function(){
			var ltSKekse = readCookie('ltSearch'+r+'');
			
			if(lsCh!='2'){
				var ltS = $(this).val();
			}
			
			
			var ltSSelect = $('#dataDiv'+r+'').data("lsSelect");
			$('#dataDiv'+r+'').data({'lsInput':ltS});
			if(ltSSelect)
					{
						if(lsCh!='1'){
						console.log('did you mean last search');
						$(this).val(ltSSelect); //if successful search but no selection made, display that search again, comes from datadiv
						}
			}else if(ltSKekse){ //no search yet, use cookie
				if(lsCh!='1'){
				console.log('did you mean cookie');
				$(this).val(ltSKrummel[1]);
				$('#pulocList.'+r+'').val(ltSKrummel[2]);
				}
			}else{ //no search yet, no cookie, leave blank
				$(this).val('');
				$('#pulocList.'+r+'').val('');
			}
	});
	*/
	
	$('#'+r+'').blur(function(){
			var ltSKekse = readCookie('ltSearch'+r+'');
			
			if(lsCh!='2'){
				var ltS = $(this).val();
			}
			var ltSSelect = $('#dataDiv'+r+'').data("lsSelect");
			$('#dataDiv'+r+'').data({'lsInput':ltS});
			if(ltSSelect)
					{$(this).val(ltSSelect);
			}else if(ltSKekse){
				$(this).val(ltSKrummel[1]);
				$('#pulocList.'+r+'').val(ltSKrummel[2]);
			}else{
				$(this).val('');
			}
	});
	
	if(ltSKekse){
		$('#'+r+'').val(ltSKrummel[1]);
	}else{
		$('#'+r+'').focus();
		
	}
	
	}
	
	//repeatSearch();
	repeatSearch('city','pu');
	repeatSearch('cityr','do');
	
	

//$("#city").focus();	
$(".city").keypress(function (evt) {
var charCode = evt.charCode || evt.keyCode;
if (charCode  == 13) { 
return false;
}
});

//successful ajax but run out of results typing
/*$(".city").keyup(function(evt){
		var omi = $(this).attr('id');
		console.log(omi);
		var charCode = evt.charCode || evt.keyCode; //need that to not trigger error msg when map link is clicked
if (charCode  != 13) { 
		if($(this).val().length >3 && $('.'+omi+'msg').is(':hidden')){ //checks if autosuggest list has closed
			omniDialog();
				$('.locErr').show();
				$(this).val("");
				$('.'+omi+'U').val(''); //clears all hidden input fld for either PU or DO
		}
}
});
*/

//applies cityrmsg/citymsg to both omni li, whether open or not, so script errors because there is always one hidden cityrmsg/citymsg
/*$("#city").keyup(function(evt){
		var charCode = evt.charCode || evt.keyCode; //need that to not trigger error msg when map link is clicked
if (charCode  != 13) { 
		if($("#city").val().length >3 && $('.citymsg').is(':hidden')){ //checks if autosuggest list has closed
			omniDialog();
				$('.locErr').show();
				$("#city").val("");
				$('.cityU').val(''); //clears all hidden input fld for either PU or DO
		}
}
});

$("#cityr").keyup(function(evt){
		var charCode = evt.charCode || evt.keyCode; //need that to not trigger error msg when map link is clicked
if (charCode  != 13) { 
			if($("#cityr").val().length >3 && $('.cityrmsg').is(':hidden')){
			omniDialog();
				$('.locErr').show();
				$("#cityr").val("");
				$('.cityrU').val(''); //clears all hidden input fld for either PU or DO
		}
}
});*/

	
/* 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');
	
	

//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(){
			currIn = $(this).attr('id');
			
		
		});  
		
		
	 var map = null;
	 //loadScript();
	    
		$('.city').catcomplete();
		
		//add hidden flds val
		$(".iw").live("click", function(){ 
				lsCh='2';
				selected = true;
				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);
				var mySearch = encodeURIComponent(city+'||'+iwt+'||'+loc+'||'+co);
				createCookie('ltSearch'+currIn+'', mySearch );
				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');
				lsCh = '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');
					currSt = $(this).attr('lf');
					var stadt = $(this).attr('AR_city');
					var f = $(this).parent('li').attr('f');
					
		$( "#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, stadt, f);
						});
	
		
		
		
		$(".LIST, .fui-span").live("click", function(){  
				var dia = $(this).parent('li').attr('t');
				$('.dep_loc[t='+dia+']').toggle();
				adjCatHeight('City');
		});
		
		$(".fui-span").live("mouseenter ", function(){  
				var dia = $(this).parent('li').attr('t');
				$('.dep_loc[t='+dia+']').show();
				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 = ($('input[name="ampmpu_rdBtn"]:checked').val() == 'AM')? '0' : '12';
		var doPm = ($('input[name="ampmdo_rdBtn"]:checked').val() == 'AM')? '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{
			if(!$('#book_doPrompt').is(':checked')){
			eraseCookie('ltSearchcityr');
			
		}
		//set search cookies except for omnibox cookie
		var sipp = $('#carType').val();
		var doHH = $('select[name="selDDdo_hours"]').val();
		var doMM = $('select[name="selDDdo_min"]').val();
		var puHH = $('select[name="selDDpu_hours"]').val();
		var puMM = $('select[name="selDDpu_min"]').val();
		var myTimeDO = encodeURIComponent(doDate+'||'+doPm+'||'+doHH+'||'+doMM+'||'+sipp);
		var myTimePU = encodeURIComponent(puDate+'||'+puPm+'||'+puHH+'||'+puMM);
		createCookie('ltTimeDO', myTimeDO );
		createCookie('ltTimePU', myTimePU );
		
		$('.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) {
			//$('[name='+stateInputName+']').val('DOG');
	});
}

function showCorrectStateDD(formName,countrySelectValue,stateContainerClass,stateInputName){
	gStateInputValue = stateInputName;
	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();
			//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("");
			//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>');
		$(formName+' .btn_container .basic_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+' .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");
		};
	});
	
	//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');
		});
		
		/*function doitnow(param){
			clearInterval(dID);
			$('.fold').unbind('mouseover');
			var activeFold = $(param);
			$('.expand').switchClass('expand','fold',500,'easeOutBounce', function(){
					$(activeFold).switchClass('fold','expand',500,'easeOutBounce',function(){
						instantiateMouseoverHandler();	
					});
			});	
		}
		
		function instantiateMouseoverHandler(){
			$('.fold').mouseover(function(){
					var activeFold = $(this);
					dID = setTimeout(function(){doitnow(activeFold)},500);
					//doitnow(this);
			});
		}
		
		instantiateMouseoverHandler();*/
		

	

	
	
}

//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';
}




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;
	}	
}



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");
			}*/
			$('.'+stateContainerClass).css("display","block").addClass("required");;
			
			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");
}





function getStateList(formName,selectedCountryValue,selectCountryID,selectStateID){
	switch (selectedCountryValue){
		case "BR": // brazilian states
			var stateArray =  [{label:"Please select",abbr:""},{label:"Acre",abbr:"AC"},{label:"Alagoas",abbr:"AL"},{label:"Amap&aacute;",abbr:"AP"},{label:"Amazonas",abbr:"AM"},{label:"Bahia",abbr:"BA"},{label:"Cear&aacute;",abbr:"CE"},{label:"Distrito Federal",abbr:"DF"},{label:"Esp&iacute;rito Santo",abbr:"ES"},{label:"Goi&aacute;s",abbr:"GO"},{label:"Maranh&atilde;o",abbr:"MA"},{label:"Mato Grosso",abbr:"MT"},{label:"Mato Grosso do Sul",abbr:"MS"},{label:"Minas Gerais",abbr:"MG"},{label:"Par&aacute;",abbr:"PA"},{label:"Para&iacute;ba",abbr:"PB"},{label:"Paran&aacute;",abbr:"PR"},{label:"Pernambuco",abbr:"PE"},{label:"Piau&iacute;",abbr:"PI"},{label:"Rio de Janeiro",abbr:"RJ"},{label:"Rio Grande do Norte",abbr:"RN"},{label:"Rio Grande do Sul",abbr:"RS"},{label:"Rond&ocirc;nia",abbr:"RO"},{label:"Roraima",abbr:"RR"},{label:"Santa Catarina",abbr:"SC"},{label:"S&atilde;o Paulo",abbr:"SP"},{label:"Sergipe",abbr:"SE"},{label:"Tocantins",abbr:"TO"}];
			break;		
		case "CA": // canadian provinces
			var stateArray = [{label:"Please select",abbr:""},{label:"Alberta",abbr:"AB"},{label:"British Columbia",abbr:"BC"},{label:"Manitoba",abbr:"MB"},{label:"New Brunswick",abbr:"NB"},{label:"Newfoundland and Labrador",abbr:"NL"},{label:"Nova Scotia",abbr:"NS"},{label:"Northwest Territories",abbr:"NT"},{label:"Nunavut",abbr:"NU"},{label:"Ontario",abbr:"ON"},{label:"Prince Edward Island",abbr:"PE"},{label:"Qu&eacute;bec",abbr:"QC"},{label:"Saskatchewan",abbr:"SK"},{label:"Yukon",abbr:"YT"}];
			break;	
		case "AU": // Aussie States
			var stateArray = [{label:"Please select",abbr:""},{label:"New South Wales",abbr:"NSW"},{label:"Northern Territory",abbr:"NT"},{label:"Queensland",abbr:"QLD"},{label:"South Australia",abbr:"SA"},{label:"Tasmania",abbr:"TAS"},{label:"Victoria",abbr:"VIC"},{label:"Western Australia",abbr:"WA"},{label:"Australian Capital Territory",abbr:"ACT"}];
			break;
		case "ZA": //south africa
			var stateArray = [{label:"Please select",abbr:""},{label:"Eastern Cape",abbr:"EC"},{label:"Free State",abbr:"FS"},{label:"Gauteng",abbr:"GP"},{label:"KwaZulu-Natal",abbr:"KZ"},{label:"Limpopo",abbr:"LP"},{label:"Mpumalanga",abbr:"MP"},{label:"North West",abbr:"NW"},{label:"Northern Cape",abbr:"NC"},{label:"Western Cape",abbr:"WC"}];
			break;	
		case "US": // united States
			var stateArray = [{label:"Please select",abbr:""},{label:"Alabama",abbr:"AL"},{label:"Alaska",abbr:"AK"},{label:"Arizona",abbr:"AZ"},{label:"Arkansas",abbr:"AR"},{label:"California",abbr:"CA"},{label:"Colorado",abbr:"CO"},{label:"Connecticut",abbr:"CT"},{label:"Delaware",abbr:"DE"},{label:"District of Columbia",abbr:"DC"},{label:"Florida",abbr:"FL"},{label:"Georgia",abbr:"GA"},{label:"Hawaii",abbr:"HI"},{label:"Idaho",abbr:"ID"},{label:"Illinois",abbr:"IL"},{label:"Indiana",abbr:"IN"},{label:"Iowa",abbr:"IA"},{label:"Kansas",abbr:"KS"},{label:"Kentucky",abbr:"KY"},{label:"Louisiana",abbr:"LA"},{label:"Maine",abbr:"ME"},{label:"Maryland",abbr:"MD"},{label:"Massachusetts",abbr:"MA"},{label:"Michigan",abbr:"MI"},{label:"Minnesota",abbr:"MN"},{label:"Mississippi",abbr:"MS"},{label:"Missouri",abbr:"MO"},{label:"Montana",abbr:"MT"},{label:"Nebraska",abbr:"NE"},{label:"Nevada",abbr:"NV"},{label:"New Hampshire",abbr:"NH"},{label:"New Jersey",abbr:"NJ"},{label:"New Mexico",abbr:"NM"},{label:"New York",abbr:"NY"},{label:"North Carolina",abbr:"NC"},{label:"North Dakota",abbr:"ND"},{label:"Ohio",abbr:"OH"},{label:"Oklahoma",abbr:"OK"},{label:"Oregon",abbr:"OR"},{label:"Palau",abbr:"PW"},{label:"Pennsylvania",abbr:"PA"},{label:"Puerto Rico",abbr:"PR"},{label:"Rhode Island",abbr:"RI"},{label:"South Carolina",abbr:"SC"},{label:"South Dakota",abbr:"SD"},{label:"Tennessee",abbr:"TN"},{label:"Texas",abbr:"TX"},{label:"Utah",abbr:"UT"},{label:"Vermont",abbr:"VT"},{label:"Virginia",abbr:"VA"},{label:"Washington",abbr:"WA"},{label:"West Virginia",abbr:"WV"},{label:"Wisconsin",abbr:"WI"},{label:"Wyoming",abbr:"WY"},{label:"-------",abbr:"-"},{label:"Armed Forces Africa",abbr:"AE"},{label:"Armed Forces Americas",abbr:"AA"},{label:"Armed Forces Canada",abbr:"AE"},{label:"Armed Forces Europe",abbr:"AE"},{label:"Armed Forces Middle East",abbr:"AE"},{label:"Armed Forces Pacific",abbr:"AP"},{label:"American Samoa",abbr:"AS"},{label:"Federated States of Micronesia",abbr:"FM"},{label:"Guam",abbr:"GU"},{label:"Marshall Islands",abbr:"MH"},{label:"Northern Mariana Islands",abbr:"MP"},{label:"Virgin Islands",abbr:"VI"}];
			break;		
		default: // no states
			var stateArray = "";
			break;
	}
	
	if (stateArray.length > 0){
		$('.formStateDD').css("display","block");
		if (formName == "bookform" || formName == "ccform"){
			$('<select id="'+selectStateID+'" name="'+selectStateID+'" class="sourceS2 '+$.formEle+'"> </select>').appendTo('.newsstate');
		} else {
			$('<select id="'+selectStateID+'" name="'+selectStateID+'" class="sourceS2 source2"> </select>').appendTo('.newsstate');
		}
		for (i=0; i<stateArray.length; i++){
			$('#'+selectStateID).append("<option value='" + stateArray[i].abbr+ "'>" + stateArray[i].label + "</option>");
		}
		$('.source2').dropkick({theme: 'standard'});
		$('.formStateDD').find('.dk_label').html(stateArray[0].label);
	} else {
		$('.formStateDD').css("display","none");
	}
	
	$('#'+selectCountryID).change(function(value){
		var cLabel = $('#'+selectCountryID+' option:selected').text();
		var cText = $('#'+selectCountryID+' option:selected').val();
		$('#'+selectStateID+',#dk_container_'+selectStateID).remove();
		getStateList(formName,cText,selectCountryID,selectStateID);
	});
	
	$('.source2Country').dropkick({
		theme: 'standard',
		change: function (value){
					var cLabel = $('#'+selectCountryID+' option:selected').text();
					var cText = $('#'+selectCountryID+' option:selected').val();
					$('#'+selectStateID+',#dk_container_'+selectStateID).remove();
					getStateList(formName,cText,selectCountryID,selectStateID);
				}
	});
}

