
var tpGuests;
var tpKids;
var lastChoice;
var tpRooms;
var flightAdults;
var flightKids;
var totalAdult;
var totalKids;

var globalContent = {};
var showIdentifiedLocationFlag = true;
function toggleOnOffImage(img,parent){
    if(!parent){parent=1;}
    var div = img.parentNode;
    for(var x=1;x<parent;x++){
        div = div.parentNode;
    }
    var images = div.getElementsByTagName("img");
    for(var x=0;x<images.length;x++){
        images[x].src = images[x].src.replace(/(On|Off)\.(gif|jpe?g|png)$/,"Off.$2");
    }
    img.src = img.src.replace(/(On|Off)\.(gif|jpe?g|png)$/,"On.$2");
}
function toggleOnOff(obj,type,tagClass,parent){
    if(!parent){parent=1;}
    var parentObj = obj.parentNode;
    for(var x=1;x<parent;x++){
        parentObj = parentObj.parentNode;
    }
    var items;
    if(type=="tag"){
        items = parentObj.getElementsByTagName(tagClass);
    }else if(type=="class"){
        //console.debug(tagClass);
        items = document.getElementsByClassName(tagClass);
    }
    for(var x=0;x<items.length;x++){
        if(type=="tag" && tagClass=="img"){
            items[x].src = items[x].src.replace(/(On|Off)\.(gif|jpe?g|png)$/,"Off.$2");
        }else{
            items[x].src = items[x].style.display = "none";
        }
    }
    if(type=="tag" && tagClass=="img"){
        obj.src = obj.src.replace(/(On|Off)\.(gif|jpe?g|png)$/,"On.$2");
    }else{
        document.getElementById(obj).style.display = "block";
    }
}
function toggleSelected(obj,parent,tag,revert,invert,forceObjOn){
    if(!parent){parent=1;}
    if(!tag){tag=obj.tagName;}
    if(!revert){revert="true";}
    if(!invert){invert="false";}
    if(!forceObjOn){forceObjOn="false";}
    var parentItem = obj.parentNode;
    for(var x=1;x<parent;x++){
        parentItem = parentItem.parentNode;
    }
    if(revert!="false"){
        var siblings = parentItem.parentNode.getElementsByTagName(tag);
        for(var x=0;x<siblings.length;x++){
            var className = " "+siblings[x].className; // so the regex will work properly
            siblings[x].className = className.replace(/([^un|de])selected/,"unselected");
        }
    }
    if(invert=="false"){
        var className = " "+parentItem.className;
        parentItem.className = className.replace(/(un|de)selected/,"selected");
    }else{
        var className = " "+parentItem.className;
        parentItem.className = className.replace(/([^un|de])selected/,"unselected");
    }
    if(forceObjOn!="false"){
        obj.className = obj.className.replace(/(un|de)selected/,"selected");
    }
}
function formatDate(date){
    return date.replace(/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/,"$2/$3/$1");
}
function fromFinderNoSelected(action){
    var all_cookies = document.cookie.split(';');
    var result = false;
    for(var i=0;i< all_cookies.length;i++){
        var temp_cookie = all_cookies[i].split('=');
        var cookie_name = temp_cookie[0].replace(/^\s+|\s+$/g,'');
        if(cookie_name == "locations"){
            var cookie_value = unescape(temp_cookie[1].replace(/^\s+|\s+$/g,''));
            if(cookie_value != "[]" && cookie_value != ""){
                result = eval("("+cookie_value+")");
            }
        }
    }
    if(!result){
        jQuery.ajax({
            url : 'ajaxRedirect.php',
            type : 'get',
            data : ({
                action : 'server_fromFinderLogger.php',
                save : action
            }),
            error : function(XMLHttpRequest, textStatus, errorThrown){},
            complete : function() {},
            success : function(t) {}
        });
    }
}
function isLocation(city,state,id){
    var ids = id.split(",");
    var str = "\"city\":\""+city+"\",\"state\":\""+state+"\",\"locationId\":\"";
    var first = document.getElementById("FROMFinderSave");
    var select = first.getElementsByTagName("select");
    if(ids.length>0){
        select.locationSelectBox0.value = str+ids[0]+"\"";
    }
    if(ids.length>1){
        select.locationSelectBox1.value = str+ids[1]+"\"";
    }
    if(ids.length>2){
        select.locationSelectBox2.value = str+ids[2]+"\"";
    }
    //saveHomeAirports();
    showFromDiv();
    //getFromPricing();
}
function clearAirport(num){
    var first = document.getElementById("FROMFinderSave");
    var select = first.getElementsByTagName("select");
    for(var x=0;x<select.length;x++){
        if(select[x].name == "locationSelectBox"+(num-1)){
            select[x].value = "";
        }
    }
}
function showSiteShade(pod){

    var selects = document.getElementsByTagName('select');
    var siteShade = "site_shade1";
    var agt = navigator.userAgent.toLowerCase();
    var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    if(pod=='shadePodSearch'){
        jQuery("#site_shade1").css('display', "block");
        travelPlannerSiteShadeRemovePopUp("search");
        tpPopulateShadePod();
        setTimeout("submitSuccess()",1000);
    }
    else {
        if(document.getElementById(siteShade).style.display == "none"){
            for (i = 0; i < selects.length; i++) {
                selects[i].style.display = 'none';
            }
            jQuery("#site_shade1").css('display', "block");
            if(document.getElementById('shade_pod').style.display == "none"){
                jQuery("#shade_pod").css('display', "block");
            }
        } else{
            for (i = 0; i < selects.length; i++) {
                selects[i].style.display = 'block';
            }
            new Effect.Fade(siteShade,{duration:0.5});
            if(document.getElementById('shade_pod').style.display!="none"){
                new Effect.Fade('shade_pod',{duration:0.5});
            }
        }
    }
    resizeSiteShade();
}

// We can deprecate this, new siteshade plugin detects correctly. JP
function resizeSiteShade(){
    var agt = navigator.userAgent.toLowerCase();
    var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    var is_chrome = (agt.indexOf('chrome')  > -1)
    var siteShade = "site_shade1";
    if(is_ie || is_chrome){
        var shade = document.getElementById(siteShade);
        shade.style.position = "absolute";
        shade.style.height = (document.body.scrollHeight)+"px";
    }else{
        jQuery("#site_shade1").css('position', 'absolute');
        jQuery("#site_shade1").css('height', (window.innerHeight+window.scrollMaxY)+"px");
    }
}

// We can deprecate this, new siteshade plugin has it's own close option. JP
function hideSiteShade(trigger){
    var selects = document.getElementsByTagName('select');
    var agt = navigator.userAgent.toLowerCase();
    var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    document.getElementById('shade_pod_content').style.overflow = "hidden";
    var enhancedVideo = document.getElementById('EnhancedVideoGallery');
    if(enhancedVideo){
        try {
            //alert(document.getElementById('EnhancedVideoGallery').getElementsByTagName('embed')[0]);
            var emptyVideo = "";
            document.getElementById('EnhancedVideoGallery').innerHTML = '';
        }
        catch (e){}
    }
    if(trigger=='shadePodGallery'){
        var packageContent = globalContent.shadePodContent;
        document.getElementById('floatingTP').style.display = 'block';
        document.getElementById('shade_pod_container').style.width = '889px';
        document.getElementById('shade_pod_container').style.marginLeft = '80px';
        document.getElementById('shade_pod_content').innerHTML = packageContent;
        globalContent.shadePodContent = null;
    }else{
        travelPlannerSiteShadeRemovePopUp();
        handleSliderToDetailsShade(null,'close');
        if(document.getElementById('site_shade1').style.display!="none"){
            jQuery("#site_shade1").hide();
        }
        if(document.getElementById('shade_pod').style.display!="none"){
            jQuery("#shade_pod").hide();
        }
        if(window.location.toString().match("#")){
            location.replace("#");
        }
    }
    // Stop next page from loading
    try {
        window.stop();
        document.execCommand('Stop');
    }
    catch (e) {
    }
}
function setSkipFlag(){
    showIdentifiedLocationFlag = false;
}
function showFromDiv(type){
    if(!type){
        //if (window.XMLHttpRequest){
        //new Effect.BlindUp('FROMFinderContainer',{duration:2.0,scaleTo:1});
        //}else{
        document.getElementById('FROMFinderContainer').style.display = 'none';
        //}
        return;
    }
    if (type=='change') {
        var top = document.getElementById("fromTop");
        var bottom = document.getElementById("fromBottom");
        if 	(bottom.innerHTML!="") {
            top.innerHTML = bottom.innerHTML;
            bottom.innerHTML = "";
        }
    }
    var fSearch = document.getElementById('FROMFinderSearching');
    var fSearchBtn = document.getElementById('FROMFinderSearchingBtn');
    var fSelect = document.getElementById('FROMFinderSave');
    var fSelectBtn = document.getElementById('FROMFinderSaveBtn');
    var fFound  = document.getElementById('FROMFinderFound');
    var fFoundBtn  = document.getElementById('FROMFinderFoundBtn');
    fSelect.style.display = "none";
    fFound.style.display  = "none";
    fFoundBtn.style.display  = "none";
    var showDiv = false;
    switch(type){
        case 'edit':
                        if(document.getElementById('FROMFinderContainer').style.display == 'none') {
            document.getElementById('FROMFinderContainer').style.display = 'block';
            }
            fSearch.style.display = "block";
            document.getElementById('FROMFinderGetFlash').innerHTML='<embed allowscriptaccess="always" width="450px" height="150px" wmode="transparent" quality="high" name="FROMFinderFlash" id="FROMFinderFlash" src="//images.bookit.com/flash/FROMFinder.swf" type="application/x-shockwave-flash"/>';
            setTimeout("showIdentifiedLocation()",6000);
                        break;
        case 'change':
            if(document.getElementById('FROMFinderContainer').style.display == 'none')
            document.getElementById('FROMFinderContainer').style.display = 'block';
            document.getElementById("FROMFinderContentHeight").style.height = '210px';
            document.getElementById("FROMFinderMargins").style.marginTop = '0px';
            document.getElementById("FROMFinderLogo").style.marginTop = '0px';
            fSearch.style.display = "none";
            fSearchBtn.style.display = "none";
            fSelect.style.display = "block";
            fSelectBtn.style.display = "block";
            break;
        case 'remove':
            break;
    }
}

// Deprecate this, using prototype effect. not sure what this does. JP
function showIdentifiedLocation(){
    if(showIdentifiedLocationFlag == false)
        return;
    var toggleSearching = [document.getElementById('FROMFinderSearching'),document.getElementById('FROMFinderSearchingBtn')];
    for(var x=0;x<toggleSearching.length;x++){
        toggleSearching[x].style.display = "none";
    }
    Effect.Appear('FROMFinderFound',{duration:1.0,delay:1.0});
    Effect.Appear('FROMFinderFoundBtn',{duration:1.0,delay:1.0});
}
function showSelectLocation(fadeAwayElement,trigger){
    if(trigger=='noAirportFound'){
    }else{
        var initSelectFrom 	= document.getElementById('locationSelectBoxInit').value;
        var selectFrom0 	= document.getElementById('locationSelectBox0').value;
        var initLocationObj = eval("({"+initSelectFrom+"})");
        var fromSelect0		= eval("({"+selectFrom0+"})");
        if(initLocationObj.locationId != fromSelect0.locationId){
            document.getElementById('metroSelect0Container').removeChild(document.getElementById('locationSelectBox0'));
            document.getElementById('metroSelect0Container').appendChild(document.getElementById('locationSelectBoxInit'));
            document.getElementById('locationSelectBoxInit').setAttribute('id','locationSelectBox0');
            saveHomeAirports();
        }
    }
    var toggleFound = [document.getElementById('FROMFinderFound'),document.getElementById('FROMFinderFoundBtn')];
    for(var x=0;x<toggleFound.length;x++){
	toggleFound[x].style.display = "none";
    }
    Effect.Appear('FROMFinderSave',{duration:1.0,delay:1.0});
    Effect.Appear('FROMFinderSaveBtn',{duration:1.0,delay:1.0});
}
function showFromPackageDetailsDiv(){
    if(document.getElementById('site_shade').style.display == 'none'){
        document.getElementById('site_shade').style.display = 'block';
    } else if(document.getElementById('site_shade').style.display == 'block'){
        document.getElementById('site_shade').style.display = 'none';
    }
}
function saveHomeAirports(locations,trigger){
    var FROM_top_locations = "";
    var json = "[";
    var removeLast = false;
    var noneSelected = true;
    var airports = [];
    var airportTracker = Array();
    if(json == "["){
        var undefinedAPT = "{\"city\":\"All Major Airports\",\"state\":\"N/A\",\"locationId\":\"ZZZ\"}";
        json += undefinedAPT;
        var location = eval("("+undefinedAPT+")");
        airports.push(location);
    }
    var weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
    var month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
    var today = new Date();

    if(removeLast)
        json = json.substring(0,json.length-1);
    json+="]";
    // Set from cookie if we don't have any locations
    /*if(!locations)
       setCookie("locations",json,'365');
    var input = getCookie('locations');
    var result = "";
    var locationCode = "";
    if(input["locationId"]!=null){
	result = input["city"]+", "+input["state"]+" ("+input["locationId"]+")";
	locationCode = input["locationId"];
    }*/
    // Update availability calendars
    if(jQuery().availabilitycalendar)
        jQuery.fn.availabilitycalendar.updateFrom();
    /*
    if(document.forms["tpForm"]){
        if(document.forms["tpForm"].fromLocation){
            document.forms["tpForm"].fromLocation.value = result;
        }
        if(document.forms["tpForm"].fl){
            document.forms["tpForm"].fl.value = locationCode;
        }
    }*/
    try{
        // not sure if this is deprecated ~ JP
        var fromAdLocation = jQuery('#fromAdLocation');
        if(fromAdlocation.length > 0){
            var locations = getLocations();
            // suppress error when cookies don't save or are disabled
            if(locations.length > 0)
            fromAdLocation.html(locations[0].city + " (" + locations[0].locationId + ")");
        }
    }catch(e){} // cookies disabled
    try{
        if(trigger!='bypassFrom'){
            getFrom();
        }
    }catch(e){} // some pages don't include from pricing displays
}
function setCookie(cookieName,cookieValue,expireDays){
    var today = new Date();
    var expire = new Date();
    expireDays = parseInt(expireDays);
    if(expireDays==null||expireDays<=0){expireDays=1;}
    expire.setTime(today.getTime()+3600000*24*expireDays);
    document.cookie = cookieName+"="+escape(cookieValue)+";path=/;expires="+expire.toGMTString()+";domain=.bookit.com;"; // change to bookit.com later, beginning . required
}
function showAltMemberSignin(){
    var container 			= document.getElementById('TP_Member_Sign_In');
    var containerHeight		= container.offsetHeight;
    container.style.height = containerHeight + "px";
    hideErrorDiv('membersigninError',0);
    new Effect.Fade('memberLogin1',{duration:1.0,afterFinish:function(){Effect.Appear('memberLogin2',{duration:1.0})}});
    new Effect.Fade('signinButton1',{duration:1.0,afterFinish:function(){Effect.Appear('signinButton2',{duration:1.0}); }});
}
function showMemberSignInDiv(){
    if(document.getElementById('TP_Member_Sign_In').style.display == 'none'){
        new Effect.BlindDown('TP_Member_Sign_In',{duration:1.0,scaleFrom:1,scaleTo:100});
    }
    else{
        new Effect.BlindUp('TP_Member_Sign_In',{duration:1.0,scaleFrom:100,scaleTo:1,afterFinish:function (){resetMemberSignin();hideErrorDiv('membersigninError',1.0);}});
    }
}
function toggleSlide(id,mixedSubject,mixedSearch,mixedReplace){
    var element = jQuery('#'+id);
    element.toggle();
    if(mixedSubject){
        if(mixedSubject.tagName == "IMG"){
            var newString = mixedSubject.src.replace(mixedReplace,mixedSearch); // we reverse the order for when obj goes back to original state
            mixedSubject.src = newString;
        }
    }
}
function trim(str){
    return str.replace(/^\s+|\s+$/, '');
}
function toggleAddonsSlide(id,className,parentlvl){
    if(!document.getElementById(id))
        return;
    if(!parentlvl){parentlvl = 1;}
    var parent = document.getElementById(id);
    for(var x=0;x<parentlvl;x++){
        parent = parent.parentNode;
    }
    var divs = parent.getElementsByTagName("div");
    for(var x=0;x<divs.length;x++){
        divs[x].className = trim(divs[x].className);
        if(divs[x].className == className && divs[x].style.display != "none" && divs[x].id != id){
            //divs[x].style.display = "none";
            toggleSlide(divs[x].id);
        }
    }
    if(document.getElementById(id).style.display == "none"){
        toggleSlide(id);
    }
}
function submitMemberSignin(hasBookingId){
    if(hasBookingId == 'yes'){
        var bookingId = jQuery('#bookingId').val();
        var email = jQuery('#email').val();
        var agentId = jQuery('#agentId').val();
    } else
        var email = jQuery('#sendEmail').val();

	jQuery.ajax({
		url: 'ajaxRedirect.php',
		type: 'POST',
		data: 'action=server_membersignin.php&BookingId='+bookingId+'&Email='+ encodeURIComponent(email)+'&agentId='+ agentId+'&hasBookingId=' + hasBookingId,
		dataType: 'xml',
		success: function(t) {
			var xmlDoc = t;
            var errmsg = document.getElementById('membersigninError');
            var hasError = false;
            errmsg.innerHTML = "";
            if(hasBookingId == 'yes'){
                // Only when you have booking Id
                var login1 					= xmlDoc.getElementsByTagName('login1');
                if(login1[0].getElementsByTagName('value')[0].firstChild.nodeValue == 'false'){
                    errmsg.innerHTML +=  login1[0].getElementsByTagName('message')[0].firstChild.nodeValue;
                    hasError		 =  true;
                }
            } else{
                // Only when you have booking Id sent to email
                var login2 					= xmlDoc.getElementsByTagName('login2');
                if(login2[0].getElementsByTagName('value')[0].firstChild.nodeValue == 'false'){
                    errmsg.innerHTML +=  login2[0].getElementsByTagName('message')[0].firstChild.nodeValue;
                    hasError		 =  true;
                }
            }
            if(hasError == true){
                //errmsg.style.display = "block";
                jQuery('#' + errmsg.id).show();
            } else{
                if(hasBookingId == 'yes'){
                    // submit member sign in
                    document.membersiginForm.submit();
                } else{
                    // Display sent email Message
                    jQuery('#emailSent').show();
                }
            }
		}
	});
}
function resetMemberSignin(){
    document.getElementById('memberLogin2').style.display 	= "none";
    document.getElementById('signinButton2').style.display 	= "none";
    document.getElementById('emailSent').style.display 		= "none";
    document.getElementById('TP_Member_Sign_In').style.height = "";
    Effect.Appear('memberLogin1',{duration:1.0,delay:1.0});
    Effect.Appear('signinButton1',{duration:1.0,delay:1.0});
}
function hideErrorDiv(divId,delayOpt){
    if(document.getElementById(divId).style.display != "none")
	Effect.Fade(divId,{duration:1.0,delay:delayOpt});
}
var onTab 						= 'tpPackage';
var toId						= new Array();
var lastToId					= new Array();
var tpInputId		 			= new Array();
var dates						= new Array();
var MAX_ROOMS		    		= 3;
var MAX_CHILDREN 				= 6;

toId['hotel_input']				= 'toAreaLocation';
toId['hotel_main']				= 'toAreaLocation'
toId['hotel_to_title']			= 'Destination';
toId['flight_input']			= 'toAirportLocation';
toId['flight_main']				= 'toAirportLocationCode';
toId['flight_to_title']			= 'To';
toId['package_input'] 			= 'toPackageLocation';
toId['package_main']			= 'toPackageLocationCode';
toId['package_to_title']		= 'To';
toId['package_main_alt']		= 'toPackageAreaId';
toId['car_input']				= 'fromCarLocation';
toId['car_main']				= 'fromCarLocationCode';
toId['car_to_title']			= 'Pick up / Drop off Location';
lastToId['input']				= 'toPackageLocation';
lastToId['main']				= 'toPackageLocationCode';
tpInputId['room_input']			= 'rm';
tpInputId['room_container']		= 'TP_Rooms';
tpInputId['room_number']		= 'TP_RoomCount';
tpInputId['adult_container']	= 'TP_Adults';
tpInputId['child_container']	= 'TP_Children';
tpInputId['package_type']		= 'TP_PackageType_Row';
tpInputId['more_type']          = 'TP_MoreType_Row';
tpInputId['car_time_container'] = 'carTimeContainer';
tpInputId['from_input']			= 'fromLocation';
tpInputId['from_main']			= 'fromLocationCode';
dates['hotel_fd_title']			= 'Check In';
dates['hotel_fd_title_cal']		= ' ';
dates['flight_fd_title']		= 'Depart';
dates['flight_fd_title_cal']	= 'Please Select Your Departure Date';
dates['package_fd_title']		= 'Depart';
dates['package_fd_title_cal']	= 'Please Select Your Departure Date';
dates['car_fd_title']			= 'Pick Up Date';
dates['car_fd_title_cal']		= 'Please Select Your Pick Up Date';
dates['hotel_td_title']			= 'Check Out';
dates['hotel_td_title_cal']		= ' ';
dates['flight_td_title']		= 'Return';
dates['flight_td_title_cal']	= 'Please Select Your Return Date';
dates['package_td_title']		= 'Return';
dates['package_td_title_cal']	= 'Please Select Your Return Date';
dates['car_td_title']			= 'Drop Off Date';
dates['car_td_title_cal']		= 'Please Select Your Drop Off Date';

function toggleTpTab(id,forced){
    var aClass;
    var targetAClass;

	if (jQuery('#' + id + 'Tab').hasClass('tpTabActive')) {
		return;
	}

	jQuery('#TP_Tabs li').removeClass('tpTabActive');

    // Exception for car, we will remove, then below if toggle car we switch more tab carrot
    jQuery('.moreTitle').removeClass('moreTitleOn');
    if(jQuery('#'+onTab+'Tab').length > 0){
        var lastElement	    = jQuery('#'+onTab+'Tab');
        var theTabs 		= jQuery('#'+id+'Tab');
        if(theTabs.length > 0){
            aClass 			= theTabs.attr('class').split(' ')[1]; // Get second class name since theres two ~JP
            targetAClass	= aClass.replace('Off','On');
        }
    }
    if(aClass != targetAClass || forced){
        //this means that a string replace was successful since replace returns haystack if needle is not found
        theTabs.addClass(targetAClass).removeClass(aClass);
        onTab			    = id;
        offAClass		    = lastElement.attr('class').split(' ')[1]; // Get second class name sincer theres two ~JP
        offTargetAClass	    = offAClass.replace('On','Off');
        if(offAClass != offTargetAClass && !forced)
            lastElement.addClass(offTargetAClass).removeClass(offAClass);

        jQuery('#tpError').hide();
        var needIdeasVisibility;
        var toggleSwitchNeedIdeas   = jQuery('#toggleSwitchNeedIdeas');
        var allLocationsListToImage = jQuery('#allLocationsListToImage');

        jQuery('.tp_pack_radio').css('font-weight','normal');
        jQuery('.TP_moreList').hide();

        if(jQuery('.roomSelect').val() == 1)
            jQuery("#TP_MoreRooms").show();
        //else
            //jQuery('#TP_RoomCount').show();
    }
    switch(id){
        case 'tpHotels':
			flightAdults=jQuery('#TP_Adults_1').children('div').children('.selected_display').text();
			flightKids=jQuery('#TP_Children_1').children('div').children('.selected_display').text();

			if(lastChoice!='tpPackage'){
			jQuery('#ap1').val(tpGuests);
			jQuery('#TP_Adults_1').children('div').children('.selected_display').html(tpGuests);
			jQuery('#mp1').val(tpKids);
			jQuery('#TP_Children_1').children('div').children('.selected_display').html(tpKids);
			}
			if(onTab!=lastChoice)
			{
				tpGuests = jQuery('#TP_Adults_1').children('div').children('.selected_display').text();
				tpKids = jQuery('#TP_Children_1').children('div').children('.selected_display').text();
			}
			else
			{
				tpGuests=jQuery('#ap1').val();
				tpKids=jQuery('#mp1').val();
			}
			tpRooms=parseInt(jQuery('#TP_Rooms').children('div').children('.selected_display').text());
			//tpRooms=parseInt(jQuery('#rm').val());

			totalAdult=0;
			totalKids=0;
			for(i=1;i<=tpRooms;i++){
						totalAdult+=parseInt(jQuery('#TP_Adults_'+i).children('div').children('.selected_display').text());
						totalKids+=parseInt(jQuery('#TP_Children_'+i).children('div').children('.selected_display').text());
			}
			jQuery('#rm').val(tpRooms);
            showTravelPlannerHotel();
			if((totalAdult!=flightAdults || totalKids != flightKids) && lastChoice== 'tpFlights'){
				tpRooms=1;
				jQuery('#rm').val(tpRooms);
				jQuery('#TP_Rooms').children('div').children('.selected_display').html(tpRooms);

				jQuery('#ap1').val(flightAdults);
				jQuery('#TP_Adults_1').children('div').children('.selected_display').html(flightAdults);

				jQuery('#mp1').val(flightKids);
				jQuery('#TP_Children_1').children('div').children('.selected_display').html(flightKids);
				hideOtherRooms();
			}
			//if(lastChoice=='tpFlights'){
				if(tpRooms==1){
					jQuery('#TP_RoomCount').hide();
				}
				else{
					jQuery('#TP_MoreRooms').hide();
				}
			//}
            loadEventListeners();
			//when tabs change set the guests (need this because flights tab sets it to 1
            //toggleSwitchNeedIdeas.show();
            //allLocationsListToImage.hide();
            jQuery('#tp_radio_hotel').attr('checked','checked').parent().css('font-weight','bold');
			lastChoice=onTab;
            break;
        case 'tpFlights':
			//set what guests were selected before change to tab
			if(onTab!=lastChoice)
			{
				tpGuests = jQuery('#TP_Adults_1').children('div').children('.selected_display').text();
				tpKids = jQuery('#TP_Children_1').children('div').children('.selected_display').text();
				tpRooms = jQuery('#TP_Rooms').children('div').children('.selected_display').text();
				totalAdult=0;
				totalKids=0;
			}
			else
			{
				tpRooms=0;
			}
			for(i=1;i<=tpRooms;i++){
				for(j=1;j<=tpKids;j++){
					jQuery('#ar' + i + 'm' + j).val('select');
			}
						totalAdult+=parseInt(jQuery('#TP_Adults_'+i).children('div').children('.selected_display').text());
						totalKids+=parseInt(jQuery('#TP_Children_'+i).children('div').children('.selected_display').text());
			}
			//flight tab defaults to 1 guest but if they have already changed it from another tab don't force it back to one
				if(totalKids>6)
				{
					totalKids=6;
				}
				if(totalAdult>12)
				{
					totalAdult=12;
				}

				jQuery('#rm').val(1);
				jQuery('#ap1').val(totalAdult);
				jQuery('#TP_Adults_1').children('div').children('.selected_display').html(totalAdult);

				jQuery('#mp1').val(totalKids);
				jQuery('#TP_Children_1').children('div').children('.selected_display').html(totalKids);

            showTravelPlannerFlight();

				jQuery('#rm').val(1);
				jQuery('#ap1').val(totalAdult);
				jQuery('#TP_Adults_1').children('div').children('.selected_display').html(totalAdult);

				jQuery('#mp1').val(totalKids);
				jQuery('#TP_Children_1').children('div').children('.selected_display').html(totalKids);


            loadEventListeners();
            jQuery("#TP_MoreRooms").hide();
            jQuery('#tp_radio_flight').attr('checked','checked').parent().css('font-weight','bold');
			lastChoice=onTab;
            break;
        case 'tpPackage':

			flightAdults=jQuery('#TP_Adults_1').children('div').children('.selected_display').text();
			flightKids=jQuery('#TP_Children_1').children('div').children('.selected_display').text();

			if(lastChoice!='tpHotels'){
			jQuery('#ap1').val(tpGuests);
			jQuery('#TP_Adults_1').children('div').children('.selected_display').html(tpGuests);
			jQuery('#mp1').val(tpKids);
			jQuery('#TP_Children_1').children('div').children('.selected_display').html(tpKids);
			}
			if(onTab!=lastChoice)
			{
				tpGuests = jQuery('#TP_Adults_1').children('div').children('.selected_display').text();
				tpKids = jQuery('#TP_Children_1').children('div').children('.selected_display').text();
			}
			tpRooms=parseInt(jQuery('#TP_Rooms').children('div').children('.selected_display').text());

			totalAdult=0;
			totalKids=0;
			for(i=1;i<=tpRooms;i++){
						totalAdult+=parseInt(jQuery('#TP_Adults_'+i).children('div').children('.selected_display').text());
						totalKids+=parseInt(jQuery('#TP_Children_'+i).children('div').children('.selected_display').text());
			}

			jQuery('#rm').val(tpRooms);
            showTravelPlannerPackage();

			if((totalAdult!=flightAdults || totalKids != flightKids) && lastChoice== 'tpFlights'){
				tpRooms=1;
				jQuery('#rm').val(tpRooms);
				jQuery('#TP_Rooms').children('div').children('.selected_display').html(tpRooms);

				jQuery('#ap1').val(flightAdults);
				jQuery('#TP_Adults_1').children('div').children('.selected_display').html(flightAdults);

				jQuery('#mp1').val(flightKids);
				jQuery('#TP_Children_1').children('div').children('.selected_display').html(flightKids);
				hideOtherRooms();
			}
			//if(lastChoice== 'tpFlights'){
				if(tpRooms==1){
					jQuery('#TP_RoomCount').hide();
				}
				else{
					jQuery('#TP_MoreRooms').hide();
				}

			//}

            loadEventListeners();
			//when tabs change set the guests (need this because flights tab sets it to 1
            //toggleSwitchNeedIdeas.show();
            //allLocationsListToImage.hide();
            if( jQuery('#tp_radio_flight').is(':checked') || jQuery('#tp_radio_hotel').is(':checked') || jQuery('#hotelFlightPackageOpt').is(':checked') )
                jQuery('#hotelFlightPackageOpt').attr('checked','checked').parent().css('font-weight','bold');
            else
                jQuery('#tp_radio_f_h_c').attr('checked','checked').parent().css('font-weight','bold');
			lastChoice=onTab;
            break;
        case 'tpCarTab':
            showTravelPlannerCar();
            loadEventListeners();
            //toggleSwitchNeedIdeas.hide();
            //allLocationsListToImage.hide();
            jQuery('#tp_radio_car').attr('checked','checked').parent().css('font-weight','bold');
            jQuery('.moreTitle').addClass('moreTitleOn');
			lastChoice=onTab;
            break;
            }
	jQuery('#' + id + 'Tab').addClass('tpTabActive');

    changeTitles();
}
function submitTravelPlanner(){
    /* Send Travel Planner Form to ajax script to validate - ajax scrip located in ajax/server/server_travelplanner.php*/
    // The reason we have to do validation here on triptype as opposed to just "trusting" the variable is because
    // when browsers cache the page and a user presses 'back', it goes back to the last known contents of certain
    // form variables instead of being properly set.  However, the tabs are always the trip type we want to run,
    // so based on the tab, we then set the trip type.
    var tripType 		= "";
    switch (onTab) {
        case 'tpHotels': 		tripType = "hotel"; break;
        case 'tpPackage': 		tripType = "package"; break;
        case 'tpCarTab': 			tripType = "car"; break;
        case 'tpFlights': 		tripType = "flight"; break;
        default: 					tripType = document.getElementById('tripType').value; break;
    }
    jQuery('#tripType').val(tripType);
    var departDate		= jQuery('#fd').val();
    var returnDate		= jQuery('#td').val();
    var rooms;
    var fromLocation;
    var toLocation;
    var toLocationAreaId; // for package ONLY
    var toLocationInput;
    var formAction;
    var roomChildAges = new Array();
    jQuery('#rm option').each(function(roomNum,roomElem){
	if(jQuery(this).val() <= jQuery('#rm option:selected').val()){
	    var ages = new Array();
	    jQuery('#mp'+(roomNum+1)+' option').each(function(childNum,childElem){
            if(jQuery(this).val()>0 && jQuery(this).val() <= jQuery('#mp'+(roomNum+1)+' option:selected').val()){
                var room = roomNum+1;
                var selector = '#ar'+room+'m'+childNum+' option:selected';
                ages.push(jQuery(selector).val());
            }
	    });
	    roomChildAges.push(ages);
	}
    });
    var roomChildAges = new Array();
    jQuery('#rm option').each(function(roomNum,roomElem){
        if(jQuery(this).val() <= jQuery('#rm option:selected').val()){
            var ages = new Array();
            jQuery('#mp'+(roomNum+1)+' option').each(function(childNum,childElem){
                if(jQuery(this).val()>0 && jQuery(this).val() <= jQuery('#mp'+(roomNum+1)+' option:selected').val()){
                    var room = roomNum+1;
                    var selector = '#ar'+room+'m'+childNum+' option:selected';
                    ages.push(jQuery(selector).val());
                }
            });
            roomChildAges.push(ages);
        }
    });
    switch(tripType){
	case 'hotel' :
        formAction = "hotel_results.php";
        if(document.getElementById('is_property_page') && document.getElementById('is_property_page').value == "true"){
            // Default
            toLocation 			= document.getElementById('toAreaLocation_property').value;
            // If they want to change where they search
            if (document.forms["tpForm"].toAreaLocation != null && document.forms["tpForm"].toAreaLocation.type == "text") {
                toLocation = document.forms["tpForm"].toAreaLocation.value;
                // Remove the hotel ID and hotel vendor ID
                if (document.forms["tpForm"].elements["hotelId"])
                    document.forms["tpForm"].elements["hotelId"].parentNode.removeChild(document.forms["tpForm"].elements["hotelId"]);
                if (document.forms["tpForm"].elements["hotelVendorId"])
                    document.forms["tpForm"].elements["hotelVendorId"].parentNode.removeChild(document.forms["tpForm"].elements["hotelVendorId"]);
            }
	    } else {
            toLocation = document.getElementById('toAreaLocation').value;
            formAction = "hotel_results.php"; // remember to change this because Jete wants to be different
        }
	    break;
	case 'flight' :
        toLocation = document.getElementById('toAirportLocationCode').value;
	    fromLocation = document.getElementById('fromLocationCode').value;
	    formAction = "flight_results.php";
	    break;
	case 'package'	:
        if(document.getElementById('is_property_page') && document.getElementById('is_property_page').value == "true" && document.getElementById('toPackageLocationCode_property')){
            toLocation = document.getElementById('toPackageLocationCode_property').value;
            // If they want to change where they search
            if (document.forms["tpForm"].toPackageLocation != null && document.forms["tpForm"].toPackageLocation != "undefined" && document.forms["tpForm"].toPackageLocation.type == "text") {
                toLocation = document.forms["tpForm"].toPackageLocation.value;
                // Remove the hotel ID and hotel vendor ID
                if (document.forms["tpForm"].elements["hotelId"])
                    document.forms["tpForm"].elements["hotelId"].parentNode.removeChild(document.forms["tpForm"].elements["hotelId"]);
                if (document.forms["tpForm"].elements["hotelVendorId"])
                    document.forms["tpForm"].elements["hotelVendorId"].parentNode.removeChild(document.forms["tpForm"].elements["hotelVendorId"]);
            }
	    }
	    else if(document.getElementById('is_property_page') && document.getElementById('is_property_page').value == "true"){
            // Remove the hotel ID and hotel vendor ID
            if (document.forms["tpForm"].elements["hotelId"])
                document.forms["tpForm"].elements["hotelId"].parentNode.removeChild(document.forms["tpForm"].elements["hotelId"]);
            if (document.forms["tpForm"].elements["hotelVendorId"])
                document.forms["tpForm"].elements["hotelVendorId"].parentNode.removeChild(document.forms["tpForm"].elements["hotelVendorId"]);
            toLocation = document.getElementById('toPackageLocationCode').value;
	    }
	    else
            toLocation 			= document.getElementById('toPackageLocationCode').value;

        toLocationAreaId = '';
	    if (document.getElementById('toPackageAreaId'))
            toLocationAreaId 	= document.getElementById('toPackageAreaId').value;
	    // See if the area alternate dropdown exists
	    if (document.forms['tpForm'].elements['ptl'] && document.getElementById('alternateDropDown')) {
            var foundId = jQuery('#alternateDropDown').val();
            var m = foundId.match(/\((.*)\)$/);
            if (m)
                document.forms['tpForm'].elements['ptl'].value = m[1];
	    }
	    // Make sure there's a ptl set... this is a hack, but not sure why it's occuring, however this is too critical to wait
	    if (document.forms['tpForm'].elements['ptl'] && !document.forms['tpForm'].elements['ptl'].value) {
            document.forms['tpForm'].elements['ptl'].value = jQuery('#toPackageLocationCode').val().substr(0,3);
	    }
	    // Fix package to
	    if (document.forms['tpForm'].elements['packageTo'] && !document.forms['tpForm'].elements['packageTo'].value.length) {
            jQuery('#toPackageLocationCode:eq(0)').children().each(function(s) {
                if (s.selected)
                    jQuery('#toPackageLocation').val(s.innerHTML);
            });
	    }
	    if (document.getElementById('toPackageLocation')) {
            toLocationInput		= document.getElementById('toPackageLocation').value;
            if (toLocationInput && !toLocationInput.length && jQuery('#toAreaLocation')[0].tagName.toLowerCase() == 'select') {
                jQuery('#toAreaLocation:eq(0)').children().each(function(s) {
                if (s.selected)
                    toLocationInput = s.innerHTML;
                });
            }
            else if (toLocationInput && !toLocationInput.length && jQuery('#toAreaLocation')[0].tagName.toLowerCase() == 'input') {
                toLocationInput = jQuery('#toAreaLocation').val();
            }
	    }
	    fromLocation = document.getElementById('fromLocationCode').value;
	    formAction = "package_results.php";
	    break;
	case 'car' : toLocation = document.getElementById('fromCarLocationCode').value;
	    formAction = "car_results.php";
	    break;
    }
    jQuery.ajax({
        url : 'ajaxRedirect.php',
        type : 'get',
        dataType : 'xml',
        data : ({
            action : 'server_travelplanner.php',
            tripType : tripType,
            toLocation : toLocation,
            toLocationAreaId : toLocationAreaId,
            depart : departDate,
            'return' : returnDate,
            fromLocation : fromLocation,
            toLocationInput : toLocationInput,
            childAges : JSON.stringify(roomChildAges)
        }),
        error : function(XMLHttpRequest, textStatus, errorThrown){
            //alert(XMLHttpRequest +' '+ textStatus +' '+ errorThrown);
        },
        complete : function() {
        },
        success : function(t) {
            var xmlDoc = t;
            var tripTypeResponse 		= xmlDoc.getElementsByTagName('tripType');
            var toLocationResponse		= xmlDoc.getElementsByTagName('toLocation');
            var datesResponse			= xmlDoc.getElementsByTagName('dates');
            var fromLocationResponse	= xmlDoc.getElementsByTagName('fromLocation');
            var children				= xmlDoc.getElementsByTagName('tripAges');
            var errmsg					= jQuery('#tpError');
            var alternateContainer		= jQuery('#alternateNameContainer');

            var hasAlternate			= null;
            var alternateSelect			= null;
            var errorText               = '';
            errmsg.html('');

            if(tripTypeResponse[0].getElementsByTagName('status')[0].firstChild.nodeValue == 'false'){
                errorText +=  tripTypeResponse[0].getElementsByTagName('message')[0].firstChild.nodeValue;
            }

            jQuery('.ageOfChildContainer .selected_display').parent().css('border','1px solid #999');
            if(children[0].getElementsByTagName('status')[0].firstChild.nodeValue == 'false'){
                errorText +=  children[0].getElementsByTagName('message')[0].firstChild.nodeValue;
                jQuery('.ageOfChildContainer .selected_display:contains(Select)').parent().css('border','1px solid #ff5a00');
            }

            jQuery('#TpToPackageContainer, #TpToHotelContainer, #TpToFlightContainer, #TpToCarContainer').find('.clearInputWrapper').css('border','1px solid #999');
            if(toLocationResponse[0].getElementsByTagName('status')[0].firstChild.nodeValue == 'false'){
                errorText +=  toLocationResponse[0].getElementsByTagName('message')[0].firstChild.nodeValue;
                jQuery('#TpToPackageContainer, #TpToHotelContainer, #TpToFlightContainer, #TpToCarContainer').find('.clearInputWrapper').css('border','1px solid #ff5a00');
            }
            else if(toLocationResponse[0].getElementsByTagName('status')[0].firstChild.nodeValue == 'check'){
                hasAlternate 	= true;
                alternateSelect = toLocationResponse[0].getElementsByTagName('message')[0].firstChild.nodeValue;
            }

            jQuery('#fd, #td').css('border','1px solid #999');
            if(datesResponse[0].getElementsByTagName('status')[0].firstChild.nodeValue == 'false'){
                errorText +=  datesResponse[0].getElementsByTagName('message')[0].firstChild.nodeValue;
                jQuery('#fd, #td').css('border','1px solid #ff5a00');
            }

            if(tripType == 'flight' || tripType == 'package'){
                jQuery('.fromInputContainer').find('.clearInputWrapper').css('border','1px solid #999');
                if(fromLocationResponse[0].getElementsByTagName('status')[0].firstChild.nodeValue == 'false'){
                    errorText +=  fromLocationResponse[0].getElementsByTagName('message')[0].firstChild.nodeValue;
                    jQuery('.fromInputContainer').find('.clearInputWrapper').css('border','1px solid #ff5a00');
                }
            }

            if(errorText.length > 0){
                errmsg.html('Oops! Please Fill in the Missing Information<br />Highlighted Above, Then Click SEARCH Again').show();
                //errmsg.html(errorText).show();
            }
            else if(hasAlternate == true){
                alternateContainer.html(alternateSelect).show();
                errmsg.html("Multiple destinations found.<br />Please narrow your search above.").show();
            }
            else{
                errmsg.hide();
                if(formAction=="hotel_results.php")
                    jQuery('#tpForm').attr('action','http://from.bookit.com/' + formAction); // Jete's thing
                else
                    jQuery('#tpForm').attr('action','http://from.bookit.com/' + formAction);

                // Set the traveller's new from location
                jQuery.ajax({
                    url : 'ajaxRedirect.php',
                    type : 'post',
                    dataType : 'json',
                    data : ({
                        action : 'server_setfromlocation.php',
                        fromLocation : fromLocation
                    }),
                    error : function(XMLHttpRequest, textStatus, errorThrown){
                        //alert(XMLHttpRequest +' '+ textStatus +' '+ errorThrown);
                    },
                    success : function(res) {
                        var resJson = res;
                        if (resJson != null && resJson != 'undefined' && resJson.state && resJson.state.length) {
                            // Get the locations and save the new one
                            var locations = getLocations();
                            locations[0].state = resJson.state;
                            locations[0].city = resJson.city;
                            locations[0].locationId = resJson.locationId;

                            setCookie("locations", JSON.stringify(locations), '365');
                        }
                    }
                });

                // If it's a hotel, only get relevant hotel data
                if (tripType == 'hotel') {
                    var formElements = document.getElementById('tpForm').elements;
                    var toDelete = new Array();

                    // Go through the form and remove non-essential elements
                    for (var i = 0; i < formElements.length; ++i) {
                        // Go through each element and remove elements we aren't using
                        var curElement = formElements[i].name;
                        switch(curElement) {
                            // Allowed/expected elements
                            case 'fd':
                            case 'td':
                            case 'rm':
                            case 'tripType':
                            case 'hotelTo':
                            case 'super':
                            case 'hotelId':
                            case 'hotelVendorId':
							case 'st':
                                continue;
                        }

                        // Test allowed patterns
                        if ((/^(?:a|m)p\d$/).test(curElement)) {
                            // Adults / minors in each room
                            continue;
                        }
                        else if ((/^ar\dm\d$/).test(curElement)) {
                            // Children ages in each room
                            continue;
                        }

                        // Everything else needs to be deleted
                        toDelete[toDelete.length] = formElements[i]
                    }

                    // Delete all elements set to be deleted
                    for (var i = 0; i < toDelete.length; ++i) {
                        //toDelete[i].parentNode.removeChild(toDelete[i]);
                        toDelete[i].value = "";
                    }
                }

                var floatingTP = document.getElementById('floatingTP');
                if(floatingTP && jQuery('#shade_pod').css('display') != 'none'){
                    //showSiteShade('shadePodSearch');
                }else{
                    tpPopulateShadePod();
                    //showSiteShade();
                    setTimeout("submitSuccess()",1000);
                }
            }
        }
    });
}
function submitAction(){
    var json = "";
    setCookie("travelPlanner",json,'365');
    submitTravelPlanner();
}
function timeoutHideLocationList(type){
    if(type = 'hotelTo')
        setTimeout("saveAndhideLocationList(\'hotelTo\')",1000);
    else
    	setTimeout("saveAndhideLocationList(\'to\')",1000);
}
function tpReplaceSelectInputs(){
    var tripType = jQuery('#tripType').val();
    var container;
    var replacementInputs = new Array();
    var replacementInput;
    var inputId;
    var hiddenId;
    var newElem = '';
    switch(tripType){
        case "package": container = "TpToPackageContainer";
            newElem = '<input type="text" name="packageTo" '+
                      'id="toPackageLocation" class="text" onkeyup="updateToLocation();" '+
                      'onblur="timeoutHideLocationList();" autocomplete="off" style="width: 216px;" />';
            if (jQuery('#toPackageLocationCode_property'))
                jQuery('#toPackageLocationCode_property').remove();
            newElem+= '<input type="hidden" name="ptl" id="toPackageLocationCode" />';
            newElem+= '<input type="hidden" name="toPackageAreaId" id="pta" />';
            inputId = 'toPackageLocation';
            hiddenId = 'toPackageLocationCode';
        break;
        case "hotel": container = "TpToHotelContainer";
            newElem = '<input type="text" name="hotelTo" '+
                      'id="toAreaLocation" class="text" onkeyup="updateHotelToLocation();" '+
                      'onblur="timeoutHideLocationList(\'hotelTo\');" autocomplete="off" style="width: 216px;" />';
            inputId = 'toAreaLocation';
            hiddenId = 'toAreaLocation';
        break;
        case "flight": container = "TpToFlightContainer";
            newElem = '<input type="text" name="flightTo" '+
                      'id="toAirportLocation" class="text" onkeyup="updateToLocation();" '+
                      'onblur="timeoutHideLocationList();" autocomplete="off" style="width: 216px;" />';
            newElem+= '<input type="hidden" name="tl" '+
                      'id="toAirportLocationCode" />';
            inputId = 'toAirportLocation';
            hiddenId = 'toAirportLocationCode';
        break;
        case "car":     container = "TpToCarContainer";
            newElem = '<input type="text" name="carFrom" '+
                      'id="fromCarLocation" class="text" onkeyup="updateToLocation();" '+
                      'onblur="timeoutHideLocationList();" autocomplete="off" style="width: 216px;" />';
            newElem+= '<input type="hidd" name="carFromLocation" '+
                      'id="fromCarLocationCode" />';
            inputId = 'fromCarLocation';
            hiddenId = 'fromCarLocationCode';
        break;
    }
    jQuery('#'+container).html(newElem);
    jQuery('#'+inputId).clearinput({style : {'display':'block'}, altHiddenField : '#'+hiddenId});
}
function tpPopulateShadePod(){
    var doy = new Array("Sun","Mon","Tues","Wed","Thur","Fri","Sat");
    var month = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
    /*var content = '<embed type="application/x-shockwave-flash" '+
		  'src="//images.bookit.com/flash/rotation.swf" '+
		  'style="margin-left: -50px;" id="loader" name="loader" '+
		  'quality="high" wmode="transparent" allowscriptaccess="always" height="230" width="480" />'+
		  '<p class="textSmallBold" style="padding:0;margin:0;">searching</p>'+
		  '<p class="textMediumGrey" style="margin:0;position:relative;z-index:1000;padding:0;">';*/
    var content = "";
    var agt = navigator.userAgent.toLowerCase();
    var is_ie = (agt.indexOf("msie 6") != -1);
    if(!is_ie){
        document.getElementById('shade_pod_content').style.overflow = "visible";
    }
    var form = document.forms["tpForm"];
    var fd = new Date();
    var td = new Date();
    fd.setTime(Date.parse(form.fd.value));
    td.setTime(Date.parse(form.td.value));
    fd = doy[fd.getDay()]+", "+month[fd.getMonth()]+" "+fd.getDate()+", "+fd.getFullYear();
    td = doy[td.getDay()]+", "+month[td.getMonth()]+" "+td.getDate()+", "+td.getFullYear();

    switch(form.tripType.value){
	case "flight":
	    var toLocation = "";
	    if(document.getElementById("toAirportLocationCode").type != "hidden"){
            var optiontags = document.getElementById("toAirportLocationCode").getElementsByTagName("option");
            for(var x=0;x<optiontags.length;x++){
                if(optiontags[x].value == document.getElementById("toAirportLocationCode").value){
                    toLocation = optiontags[x].innerHTML ;//
                }
            }
	    }else{
            toLocation = document.getElementById("toAirportLocation").value;
	    }
	    content += "<b>BookIt.com</b><sup>&reg;</sup> is searching for <b>Round Trip</b> Tickets<br>From <b>"+form.fromLocation.value+"</b> to <b>"+toLocation+"</b><br>Departing <b>"+fd+"</b> & Returning <b>"+td+"</b>";
	    break;
	case "hotel":
        var toAreaLocation = "";
	    if(document.getElementById("toAreaLocation")){
            if(document.getElementById("toAreaLocation").tagName.toLowerCase() == "select"){
                var selectbox;
                for(var x=0;x<form.elements.length;x++){
                    if(form.elements[x].name=="super"){
                        selectbox = form.elements[x];
                    }
                }
                var optiontags = selectbox.getElementsByTagName("option");
                for(var x=0;x<optiontags.length;x++){
                    if(optiontags[x].value == selectbox.value){
                        toAreaLocation = optiontags[x].innerHTML ;//
                    }
                }
            }else{
                // See if we're using the default location or if the user changed it
                if(document.getElementById("toAreaLocation").nodeName == 'INPUT')
                    toAreaLocation = document.getElementById("toAreaLocation").value;

                if(document.getElementById("toAreaLocation").nodeName == 'DIV')
                    toAreaLocation = document.getElementById("toAreaLocation").innerHTML ;
            }
	    }else{
            toAreaLocation = form.toAreaLocation_property.value;
	    }
        var roomsTxt = (form.rm.value == 1) ? 'Room' : 'Rooms';
        content += '<b>BookIt.com</b><sup>&reg;</sup> is searching for <b>'+form.rm.value+' '+roomsTxt+'</b> in <b>'+toAreaLocation+
                   '</b><br>Checking In <b>'+fd+'</b><br>Checking Out <b>'+td+'</b>'+
                   '<img src="//bookit.advertserve.com/servlet/view/banner/image/zone?zid=6&pid=0&keywords=&random='+Math.floor(89999999*Math.random()+10000000)+'"'+
                        'height="80" width="375" hspace="0" vspace="0" border="0" alt="" '+
                        'id="AdLocationHotelLoader" style="margin-top: 7px;">';
        break;
	case "package":
        var packageTo = jQuery('#toPackageLocation');
        if(packageTo) {
            toAreaLocation = packageTo.val();
        } else {
            var packageToSel = jQuery('#toPackageLocationCode');
            if(packageToSel) {
                toAreaLocation = packageToSel.val();
            }
        }
        var roomsTxt = (form.rm.value == 1) ? 'Room' : 'Rooms';
	    content += '<b>BookIt.com</b><sup>&reg;</sup> is searching for <b>'+form.rm.value+' '+roomsTxt+'</b> in <b>'+toAreaLocation+
                   '</b><br>Checking In <b>'+fd+'</b><br>Checking Out <b>'+td+'</b>'+
                   '<img src="//bookit.advertserve.com/servlet/view/banner/image/zone?zid=6&pid=0&keywords=&random='+Math.floor(89999999*Math.random()+10000000)+'"'+
                        'height="80" width="375" hspace="0" vspace="0" border="0" alt="" '+
                        'id="AdLocationHotelLoader" style="margin-top: 7px;">';
        break;
	    /*var toPackageLocation = "";
	    if(document.getElementById("toPackageLocationCode") && document.getElementById("toPackageLocationCode").tagName == "SELECT"){
            var optiontags = document.getElementById("toPackageLocationCode").getElementsByTagName("option");
            for(var x=0;x<optiontags.length;x++){
                if(optiontags[x].value == document.getElementById("toPackageLocationCode").value){
                    toPackageLocation = optiontags[x].innerHTML;
                }
            }
	    }else{
            var element = document.getElementById('toPackageLocation');
            if(element.nodeName == 'INPUT') {
                toPackageLocation = jQuery("#toPackageLocation").val();
            }
            else if(element.nodeName == 'DIV') {
                toPackageLocation = jQuery("#toPackageLocation").html();
            }
	    }
	    /*showPackageDetailsTPSlide(0, {
		arrivalDate: fd,
		endingDate: td,
		fromLocationCityName: form.fromLocation.value,
		toLocationCityName: toPackageLocation
	    }, false);
	    return;*/
	    break;
	case "car":
	    var fromCarLocation = "";
	    if(form.carFromLocation.type!="hidden"){
            var optiontags = form.carFromLocation.getElementsByTagName("option");
            for(var x=0;x<optiontags.length;x++){
                if(optiontags[x].value == form.carFromLocation.value){
                    fromCarLocation = optiontags[x].innerHTML ;//
                }
            }
	    }else{
            fromCarLocation = form.fromCarLocation.value;
	    }
	    content += "<b>BookIt.com</b><sup>&reg;</sup> is searching <b>Rental Cars</b><br>Pick Up in <b>"+fromCarLocation+"</b> on <b>"+fd+"</b><br>Drop Off in <b>"+fromCarLocation+"</b> on <b>"+td+"</b>";
	    break;
	case "tpCruiseTab":
	    content += "<b>BookIt.com</b><sup>&reg;</sup> is searching <b>Cruises</b>";
	    break;
	default:
	    content += "<b>Your page is being loaded.</b>";
	    break;
    }
    content += "</p>";
    jQuery('<div></div>').siteshade({
        theme : 'search',
        model : true,
        modalClose : false,
        autoOpen : true,
        html : content,
        dialogScroll : true
    });
    //populateShadePod(content);
}
function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [ scrOfX, scrOfY ];
}
function submitSuccess(){
    document.tpForm.submit();
}
function loadEventListeners(){
    if(!jQuery('#tripType'))
        return;
    var tripType = jQuery('#tripType').val();
    var toInputObj;
    var fromInputObj;
    var inputIdtoListenId;
    // This will be event listener for input text box for the to location. before we create listener, we want to check to see
    // that input is indeed a select and not pre-selected destination as in specific sites such as orlando.bookit.com
    if(jQuery('#'+toId[tripType+'_main']) || jQuery('#'+toId[tripType+'_main'] + '_property')){
        if(jQuery('#'+toId[tripType+'_main'])){
            if(!jQuery('#'+toId[tripType+'_main']).is('select')){
                //Event Listener for To Input
                switch(tripType){
                    case 'hotel' : inputIdtoListenId = toId[tripType+'_input'];
                    jQuery('#'+inputIdtoListenId).live('keyup',function(){updateHotelToLocation();});
                    break;
                    case 'flight' :
                    case 'package' :
                    case 'car' : inputIdtoListenId = toId[tripType+'_input'];
                    jQuery('#'+inputIdtoListenId).live('keyup',function(){updateToLocation();});
                    break;
                }
            }
        }
        switch(tripType){
            case 'flight' :
            case 'package':	inputIdtoListenId = tpInputId['from_input'];
            jQuery('#'+inputIdtoListenId).live('keyup', function(e){ keyboardFromLocation(e); updateFromLocation(); });
            break;
        }
    }
}
// Deprecate this
function addEvent(obj,type,fn){
    if(obj.addEventListener)
        obj.addEventListener(type,fn,false);
    else if(obj.attachEvent){
        obj["e"+type+fn]=fn;
        obj[type+fn]=function(){obj["e"+type+fn](window.event);};
        obj.attachEvent("on"+type,obj[type+fn]);
    }
}
// This function is pointless ~ JP
function keyboardFromLocation(e){
    switch(e.keyCode){
	case 40: // down
	    break;
	case 38: // up
	    break;
	case 13: // enter
	    break;
	default:
	    break;
    }
}
function keyboardToLocation(e){
}
function updateFromLocation(e){
    fromInputObj = jQuery('#'+tpInputId['from_input']);
    var inputValue  = fromInputObj.val();
    //if less than 3 characters have been typed in we dont want to run the location lookup
    if(inputValue.length < 3)
        return;
    locationLookup('from', inputValue);
}
function updateHotelToLocation(e){
    var tripType 		= document.getElementById('tripType').value;
    toInputObj			= document.getElementById(toId[tripType + '_input']);
    toTargetObj			= document.getElementById(toId[tripType + '_main']);
    var inputLength		= toInputObj.value;
    if(inputLength.length < 3) //if less than 3 characters have been typed in we dont want to run the location lookup
        return;
    locationLookup('hotelTo',toInputObj.value,tripType);
}
function updateToLocation(e){
    var tripType 		= document.getElementById('tripType').value;
    toInputObj			= document.getElementById(toId[tripType + '_input']);
    toTargetObj			= document.getElementById(toId[tripType + '_main']);
    var inputLength		= toInputObj.value;
    if(inputLength.length < 3) //if less than 3 characters have been typed in we dont want to run the location lookup
        return;
    locationLookup('to',toInputObj.value,tripType);
}
var dropdownLocationListRequest = null;
function locationLookup(type,objValue,tripType){
    var targetId;
	
    //for hotels we look for cities
	if(type == 'hotelTo'){
        targetId 		= "hotelLocationList";
        onClickFunction = "setHotelToLocation";
        action			= "server_findHotelToLocation.php";
    }
	//for all from locations, flight only to location, and package or flight to location where string length is <=3 we are looking for airports
    else if(type == 'from' || tripType == 'flight' ||(type == 'to' && objValue.length <= 3)){ 
		if(type == 'from'){
			targetId 		= "fromLocationList";
			onClickFunction = "hideLocationList('"+type+"'); setFromLocation";
		}	
	    else {
			targetId 		= "toLocationList";
			onClickFunction = "setToLocation";
		}
		
        action			= "server_findcitylistFrom.php";
    }
	//for package to location we look for cities and airports when the string length is > 3
    else if(type == 'to'){
        targetId 		= "toLocationList";
        onClickFunction = "setToLocation";
        action			= "server_findcitylistTo.php";
    }	
    var opt = {
        url : 'ajaxRedirect.php',
        type : 'get',
        dataType : 'xml',
		cache: false,
        data : ({
            action : action,
            city : objValue,
            length : 15
        }),
        error : function(XMLHttpRequest, textStatus, errorThrown){
            //alert(XMLHttpRequest +' '+ textStatus +' '+ errorThrown);
        },
        success : function(t) {
            // Response was empty; no results
            if (!t) {
                // Close list
                target = jQuery('#'+targetId);
                target.html('').hide();
                // Set our object back to 'null'
                dropdownLocationListRequest = null;
            }
            var xmlDoc   = t;
            var response = xmlDoc.getElementsByTagName("location");
            var iterate = 0;
            var locationIdResponse;
            var locationTextResponse;
            var areaIdResponse;
            var locationId;
            var areaId;
            var locationText;
            var locationList = "";
            var locationListFns = [];
            var cityResponse;
            var stateResponse;
            var city = "";
            var state = "";
            var target;
            var container;
            var listClass;
            while(iterate < response.length){
				locationIdResponse = response[iterate].getElementsByTagName('locationId');
                locationTextResponse = response[iterate].getElementsByTagName('locationText');
                cityResponse = response[iterate].getElementsByTagName('city');
                stateResponse = response[iterate].getElementsByTagName('state');
                locationId = locationIdResponse[0].firstChild.nodeValue;
                locationText = locationTextResponse[0].firstChild.nodeValue;
                city = location
                areaIdResponse = response[iterate].getElementsByTagName('areaId');
                if(areaIdResponse.length > 0){
                    if(areaIdResponse[0].firstChild != null)
                        areaId = areaIdResponse[0].firstChild.nodeValue;
                    else
                        areaId = '';
                } else
                    areaId = '';

                if((iterate%2) == 0)
                    listClass = "bg0";
                else
                    listClass = "bg1";

                var onClickString;
                if(type == 'to' || type == 'hotelTo'){
                    onClickString = onClickFunction + "('"+ locationId +"','"+ locationText +"' , '"+ tripType +"',null,'"+ areaId +"')";
                } else { //when setting from location getFrom needs to be passed so it fires after we save the from cookie
                    onClickString = onClickFunction + "('"+ locationId +"','"+ locationText +"' , '"+ tripType +"',true,'',true)";
                }

                locationList += '<li class="'+listClass+'" ';
                locationList += 'onmousedown="'+ onClickString +'">';
                locationList += '<input type="hidden" id="listLocationAreaId'+iterate+'" value="'+areaId+'">';
                locationList += '<input type="hidden" id="listLocationId'+iterate+'" value="'+locationId+'">';
                locationList += '<input type="hidden" id="listLocationText'+iterate+'" value="'+locationText+'">';
                locationList += '<input type="hidden" id="listLocationCity'+iterate+'" value="'+city+'">';
                locationList += '<input type="hidden" id="listLocationState'+iterate+'" value="'+state+'">';
                locationList += '<a href="javascript:void(0);" style="width:100%;">'+locationText+'</a></li>';

                locationListFns[iterate] = onClickString;
                iterate++;
            }
            target = jQuery('#'+targetId);
            target.html(locationList).show();
            var listItems = target.find("li");
            listItems.each(function(){
                jQuery(this).click(function(){
                    eval(jQuery(this).attr('onclick'));
                });
            });
            // Set our object back to 'null'
            dropdownLocationListRequest = null;
        }
    }
    // Cancel any existing request that's going on!
    if (dropdownLocationListRequest != null)
        dropdownLocationListRequest.abort();

    // Make new request
    dropdownLocationListRequest = jQuery.ajax(opt);
}

function isPhone(strfield1) {
    var re = /[\(\+\)\.-]*\d[\(\+\)\.-]*\d[\(\+\)\.-]*\d[\(\+\)\.-]*\d[\(\+\)\.-]*\d[\(\+\)\.-]*\d[\(\+\)\.-]*\d[\(\+\)\.-]*\d[\(\+\)\.-]*\d[\(\+\)\.-]*\d{1,}[\(\+\)\.-]*/;
    return re.test(strfield1);
}

function isValidEmail(strEmail){
	validRegExp = /^[a-zA-Z0-9_.\-]{1,}@\w{1,}\.\w{2,3}$/i;
   	return validRegExp.test(strEmail);
}

function showIfTicket() {
	if(typeof(flag) == 'undefined') {
   		flag=0;
	}
	if(document.getElementById('feedbackIssueType').value=='Help_Desk_Ticket' && flag==0) {
		jQuery('.showTicketContainer').slideToggle("slow");
		flag=1;
	}
	else if(!(document.getElementById('feedbackIssueType').value=='Help_Desk_Ticket') && flag==1) {
		jQuery('.showTicketContainer').slideToggle("slow");
   		flag=0;
	}
}

function isEmpty(val) {
	return (val && !val.length);
}

function sendPageFeedback(){
	if(isEmpty(document.getElementById('PageFeedbackPhone').value) && isEmpty(document.getElementById('PageFeedbackEmail').value)) {
		document.getElementById('emailphoneerror').style.display='block';
		return;
	} else {
	    if( (!isEmpty(document.getElementById('PageFeedbackEmail').value) && isValidEmail(document.getElementById('PageFeedbackEmail').value)) || (!isEmpty(document.getElementById('PageFeedbackPhone').value)  && isPhone(document.getElementById('PageFeedbackPhone').value)))
	    {
            //alert(1);
            document.getElementById('emailphoneerror').style.display='none';
	    } else {
            //alert(2);
            document.getElementById('emailphoneerror').style.display='block';
            return;
	    }
	}

	if((isEmpty(document.getElementById('PageFeedbackEmail').value) || !isValidEmail(document.getElementById('PageFeedbackEmail').value)) && (!isEmpty(document.getElementById('PageFeedbackPhone').value) && !isPhone(document.getElementById('PageFeedbackPhone').value)))
	{
		//alert(4);
		document.getElementById('phonenumbererror').style.display='block';
		return;
	} else {
	    //alert(5);
	    document.getElementById('phonenumbererror').style.display='none';
	}

	var agentId = '';//email will be required if its from an agent so we can follow up
	var email = escape(document.getElementById("PageFeedbackEmail").value);
	var comments = escape(document.getElementById("PageFeedbackComments").value);
	var req = escape(jQuery('#PageFeedbackRequest').val());
	var businessUnit = escape(document.getElementById("businessUnit").value);
	var summaryText = escape(document.getElementById("summaryText").value);
	var feedbackIssueType = escape(document.getElementById("feedbackIssueType").value);
	var phoneNumber = escape(document.getElementById("PageFeedbackPhone").value);
	var hideOrNot = escape(document.getElementById("hideDrop").value);
	var page = escape(document.URL);

    if(hideOrNot=='999')
		feedbackIssueType='site_functionality';

	var commentsDesctirption=comments;
	//alert(feedbackIssueType);

	if(comments == ''){
		errorMessage="Please Provide Your Comments";
		document.getElementById("CommentsError").innerHTML = errorMessage;
		document.getElementById("CommentsError").style.display = "block";
		hasError = true;
		return hasError;
	} else
	    jQuery("#feedbackSendingMsg").fadeIn();

	if(document.getElementById('feedbackIssueType').value=='Help_Desk_Ticket')
	    var actionText='CCSoapFeedback.php';
	else
	    var actionText='server_pageFeedback.php';

	jQuery.ajax({
		url: 'ajaxRedirect.php',
		type: 'POST',
		data: 'phoneNumber='+phoneNumber + '&email='+email + '&PageFeedbackComments=' + commentsDesctirption + '&msg=' + comments + '&page=' + page + '&action='+ actionText + '&feedbackIssueType=' + feedbackIssueType + '&businessUnit=' + businessUnit + '&summaryText=' + summaryText + '&req=' + req,
		success: function(t) {
			jQuery("#CommentsError").hide();
			jQuery("#feedbackSendingMsg").fadeOut('slow', function() {
				jQuery("#feedbackSuccessMsg").fadeIn('slow', function() {
					setTimeout('jQuery("#feedbackSuccessMsg").fadeOut()', 3000);
					setTimeout("jQuery('#toggleSwitchFeedBackTop').click()", 4000);
				});
			});
		}
	});
}

function sendEmailPage(){
	var name = escape(document.getElementById("EmailPageName").value);
	var youremail = escape(document.getElementById("EmailPageYourEmail").value);
	var friendemail = escape(document.getElementById("EmailPageFriendEmail").value);
	var message = escape(document.getElementById("EmailPageMessage").value);
	var page = escape(document.URL);
	var hasError = false;

	if(name == ''){
		document.getElementById("NameErrorEPage").innerHTML = "Please Provide Your Name";
		document.getElementById("NameErrorEPage").style.display = "block";
		hasError = true;
	}
	if(youremail == ''){
		document.getElementById("EmailErrorEPage").innerHTML = "Please Provide Your Email";
		document.getElementById("EmailErrorEPage").style.display = "block";
		hasError = true;
	}
	if(friendemail == ''){
		document.getElementById("FriendEmailErrorEPage").innerHTML = "Please Provide Your Friends Email";
		document.getElementById("FriendEmailErrorEPage").style.display = "block";
		hasError = true;
	}

	if(hasError == true)
		return hasError;

	jQuery.ajax({
		url: 'ajaxRedirect.php',
		type: 'POST',
		data: 'fromEmail='+youremail + '&fromName='+name +'&msg=' + message + '&page=' + page + '&toEmail=' + friendemail + '&action=server_emailpage.php',
		success: function(t) {
			jQuery('#successMsgEmail').show();
			setTimeout("jQuery('#successMsgEmail').fadeOut()", 3000);
			setTimeout("jQuery('#toggleSwitchEmailPageTop').click()", 4000);
		}
	});
}

function storeTPGuests(guest){
	tpGuests = guest;
}

