var $j = jQuery.noConflict();

var val = 100;
var selTab = 0;
var frmShowing = '';
var tabShowing = '';

var showForm = '';
var homeCity = null;

var firstTimeFlight = true;
var firstTimeHotel = true;
var firstTimeCar = true;
var firstTimeCruise = true;
var firstTimeVacation = true;

var firstLoad = true;
var firstPageLoad = false;

var getckeval = readCookieVal("swapvalue");

/* added for main page report this popup */
function showReportThisPopup(URL){
 	window.open(URL,"reportPopup","toolbar=0,location=0,directories=0,menubar=0,scrollbars=1,resizable=0,height=500,width=580");	
}

/* Function to find the X-Position of a object in the page*/
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

/* Function to find the Y-Position of a object in the page*/
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

/* Function to create cookie */
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 = "";
	var ck = name+"="+value+expires+"; path=/";
	document.cookie = ck;
}

/* Function to read the set cookie */
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');

	for(var i=0;i<ca.length;i++)
	{
		var c = 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 to erase cookie */
function eraseCookie(name)
{
	createCookie(name,"",-1);
}

/* Function to remove the spaces on both the sides(left & right) */
function trimValue(str){
   return str.replace(/^\s*|\s*$/g,"");
}

/* Function to show the Div element using display property */
function divOn(id)
{
		if(document.getElementById(id) != null)
		{
				document.getElementById(id).style.display = 'block';
		}
}

/* Function to hide the Div element using display property */
function divOff(id)
{
		if(document.getElementById(id) != null)
		{
				document.getElementById(id).style.display = 'none';
		}
}

/* Function to show the Div element using visiblity property */
function divShow(id){
	if(document.getElementById(id) != null) {
		document.getElementById(id).style.visibility = 'visible';
	}
}

/* Function to hide the Div element using visiblity property */
function divHide(id){
	if(document.getElementById(id) != null) {
		document.getElementById(id).style.visibility = 'hidden';
	}
}

/* Function to append HTML inside a block level element*/
function appendHtmlInside(container, htmlString)
{
	document.getElementById(container).innerHTML = document.getElementById(container).innerHTML  + htmlString;
}

/* Function to replace HTML inside a block level element*/
function replaceHtmlInside(container, htmlString)
{
	document.getElementById(container).innerHTML = htmlString;
}

/* Function to find whether the field is empty or not */
function isEmpty(inputFieldVal) 
{
		if (trimValue(inputFieldVal) == "")
		{
			return true;
		}
		else 
		{
			return false;
		}
}

/* Function to find whether the field contains only alpha numeric characters or not */
function isAlphaNumeric(inputFieldVal) {
	var isinputValOk = trimValue(inputFieldVal).match(/^[a-zA-Z0-9]+$/);
	if (isinputValOk) {
		return true;
	} else {
		return false;
	}
}

/* Function to show the error messages */
function showError(){
    if (errors.length > 0){ alert(errors.join('\n')); errors.length=0; return false; }
    else{ return true; }
}


/* Function to find the browser */
function Browser()
{
	var browserName;

	is_mozilla   = (navigator.userAgent.toLowerCase().indexOf("firefox")!=-1)?1:0;
	is_ie5       = (navigator.appVersion.indexOf('MSIE 5')!=-1)?1:0;
	is_ie6       = (navigator.appVersion.indexOf('MSIE 6')!=-1)?1:0;
	is_ie7       = (navigator.appVersion.indexOf('MSIE 7')!=-1)?1:0;
	is_safari    = (navigator.userAgent.toLowerCase().indexOf("safari") != -1)?1:0;
	is_aol       = (navigator.userAgent.toLowerCase().indexOf("aol") != -1)?1:0;
	is_netscape  = (navigator.userAgent.toLowerCase().indexOf("netscape")!=-1)?1:0;

	if(is_mozilla) {
		browserName = "Mozilla";
	} else if(is_ie5) {
		browserName = "IE5";
	} else if(is_ie6) {
		browserName = "IE6";
	} else if(is_ie7) {
		browserName = "IE7";
	} else if(is_safari) {
		browserName = "Safari";
	} else if(is_aol) {
		browserName = "AOLExplorer";
	} else if(is_netscape) {
		browserName = "Netscape";
	}

	return browserName;
}

/* Function to disable a element or control in the form*/
function disableControl(id)
{
	if(document.getElementById(id))
		document.getElementById(id).disabled = true;
}

/* Function to enable a element or control in the form*/
function enableControl(id)
{
	if(document.getElementById(id))
	document.getElementById(id).disabled = false;
}

function compareDates(dateone, datetwo) {
    oneA = dateone.split('/');
    twoA = datetwo.split('/');
    date1 = oneA[2]*10000 + oneA[0]*100 + oneA[1];
    date2 = twoA[2]*10000 + twoA[0]*100 + twoA[1];
    if (date1 > date2) {
        return 1;
    }
    else if (date1 < date2) {
        return -1;
    }
    return 0;
}

function updateCookieVal(theForm, cookieName){
	els = theForm.elements;
	cookieVal = "";
	for(var ijk=0; ijk < els.length; ijk++){ 
			switch(els[ijk].type){
			case "select-one":
				cookieVal += els[ijk].id + '=' + els[ijk].selectedIndex + ":";
				break;
			case "text":
			case "hidden":
				cookieVal += els[ijk].id + '=' + els[ijk].value + ":";
				break;
			case "radio":
				if(els[ijk].checked == true)
					cookieVal += els[ijk].id + '=' + els[ijk].value + ":";
				break;
			case "checkbox":
				cookieVal += els[ijk].id + '=' + els[ijk].checked + ":";
				break;
			case "select-multiple":
				var MultiSelectedValues='';
				for(formMultiSelectIndex=0;formMultiSelectIndex<els[ijk].length;formMultiSelectIndex++)
				{
					if(els[ijk][formMultiSelectIndex].selected && els[ijk][formMultiSelectIndex].value != '')
					{
						MultiSelectedValues += els[ijk][formMultiSelectIndex].value + '|';
					}
}
				cookieVal += els[ijk].id + '=' + MultiSelectedValues + ":";
			default:
				break;
		}	
	}
	createCookie(cookieName, cookieVal, 1); //Changed cookie expire days from 365 days to 1 day.
};

function updateFormDetails(formName, cookieName,pg){
	var cookieVal = readCookie(cookieName);
	if(cookieVal != null & cookieVal != ''){ var valIndex = cookieVal.split(":"); }else{ return false;};
	for(var jkl=0; jkl < valIndex.length; jkl++){ 
		var elmNameValue = null;
		var elmId        = null;
		var elmValue     = null;
		var elmRef       = null;
		var elmType      = null;
		
		elmNameValue = valIndex[jkl].split('=');
		elmId        = elmNameValue[0];
		elmValue     = elmNameValue[1];
		elmRef       = (elmId != null) ? document.getElementById(elmId) : null;
		elmType      = (elmRef != null) ? elmRef.type : null;
		
		if(pg && (cookieName == 'flightLob' || cookieName == 'flightMain' || cookieName == 'vacationMain' || cookieName == 'vacationLob') && (elmId == 'flightType' || elmId == 'maxConnections' || elmId == 'children' || elmId == 'vachild1' || elmId == 'vanumOfRooms')){
			continue;
		}

		switch(elmType){
			case "select-one":
				elmValue = (elmValue != '' & elmValue != null & typeof elmValue != 'undefined') ? elmValue : 0;
				try{
					if(typeof elmRef[elmValue].selected != 'undefined')
						elmRef[elmValue].selected = true;
						elmRef.onchange();
				}catch(er){
					//alert(er)
					elmRef.onchange = function(){};
				}
				break;
			case "text":
			case "hidden":
				elmRef.value = (elmValue != '' & elmValue != null & typeof elmValue != 'undefined') ? elmValue : '';
				break;
			case "checkbox":
				elmRef.checked = (elmValue == 'true'  & elmValue != '' & elmValue != null & typeof elmValue != 'undefined') ? true : false;
				break;
			case "radio":
				elmRef.checked = true;
				break;
			case "select-multiple":
				elmValue     = (elmValue != '' & elmValue != null & typeof elmValue != 'undefined') ? elmValue : 0;
				if(elmValue) {
					elmValueArr  = elmValue.split("|");
					elmValLength = elmValueArr.length - 1;

					for(var j = 0; j < elmRef.length; j++) {
						elmRef[j].selected = false;

						for(var multiSelectIndex = 0; multiSelectIndex < elmValLength; multiSelectIndex++ ) {
							if( elmRef[j].value == elmValueArr[multiSelectIndex]) {
								elmRef[j].selected = true;
							}
						}

					}
				}
				try {
					elmRef.onblur();
				} catch (e) { 
					elmRef.onblur = function(){};
				}

				break;

			default:
				break;
		}
		
		if(cookieName == 'flightLob' && elmId == 'tripType' && elmValue == 'true' && document.getElementById('flthtl')){
			document.getElementById('flthtl').checked = true;
		}
		else if(cookieName == 'flightMain' && elmId == 'flthtl' && document.getElementById('flthtl')){
			document.getElementById('flthtl').checked = true;
		}
		if(cookieName == 'flightMainKayak' && elmId == 'ft' && elmValue == 'ow' && document.getElementById('ow')){
			document.getElementById('ow').checked = true;
		}
		
	}
}

function lbtnClick(obj){
	window.location = obj.childNodes[0].href;
	}


/*

Function that will return the date which is number of days(numOfDays) advance from the given specific date(dtVal)

for ex, passing dtVal as - 10/26/2007 and numOfDays - 30, the function will return the date(11/26/2007) which is 30 days advance from the given specific date

*/

function getSpecificDate(dtVal, numOfDays) {

	var dtObj             = new Date(dtVal);
	var advDtTimeStampVal = dtObj.setDate(dtObj.getDate() + numOfDays);
	var advDtObj          = new Date(advDtTimeStampVal);
	var advanceDate       = prefixZero(parseInt(advDtObj.getMonth()+1))+"/"+prefixZero(advDtObj.getDate())+"/"+advDtObj.getFullYear();

	return advanceDate;
}

//PREFIXES ZERO TO A SINGLE CHAR STRING
function prefixZero(num){
	if(num.toString().length<2)
		return '0'+num;
	else
		return num;
}


/* Function to switch the className for an object - used in validation functions */
function cssSwitch()
{
  var fnArguments = cssSwitch.arguments;
  for(var i=0;i < fnArguments.length;i++)
  {
    param = fnArguments[i].split("&");
    elemId = param[0];
    cssClass = param[1];
   	elemRef = document.getElementById(elemId);
    elemRef.className = cssClass;
  }
}
function checkforAolClient(){
	var is_aol = navigator.userAgent.toLowerCase().indexOf("aol") != -1;
	if(is_aol){
		document.getElementById('logoutBtn').style.display = "none";
	}
}

// Trims all spaces to the right of a specific string
function RTrim(str)
{
        var whitespace = new String(" \t\n\r ");
        var s = new String(str);
        if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
            var i = s.length - 1;       
            while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                i--;
            s = s.substring(0, i+1);
        }
        return s;
}

//cookie code
function createCookieObj(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 readCookieVal(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
                var c = 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 '';
}

function eraseCookieObj(name) {
        createCookie(name,"",-1);
}

function srchSub(ref,type){
  var queryval='';
  if(type)
	  queryval = document.ft_searchForm.query.value.trim();
  else
	  queryval = document.searchForm.query.value.trim();
  if(queryval == 'Search Here'){
    queryval = '';
  }
  queryval = queryval.replace( /\+/, " ");
  newurl = ref.href + queryval;
  window.location = newurl;
  return false;

}

String.prototype.trim = function () {
	return this.replace(/^\s*|\s*$/g,"");
}

 /* clear text input field onclick */
function search_form(){
 		var $jqr = jQuery.noConflict();
			jQuery.fn.hint = function() {
				var t = $jqr(this); 
				var defVal = t.attr('value'); 
					t.focus(function(){
						if (t.val() == defVal) {
						  t.val('');
						  t.removeClass('blur');
						}
					})
	
					t.blur(function(){
						if (t.val() == '') {
						  t.val(defVal);
						  t.addClass('blur');
						}
					})
			}
			$jqr(function(){ 
				$jqr('input.clearText').hint();
			})
}

function cityFocus(textbox, searchtype, idfield) {
	initSmartBox(textbox, idfield, searchtype, 20, 175);
}

function removeCityCode()
{	
	var fnArguments = removeCityCode.arguments;
	for(var i=0;i < fnArguments.length;i++)
	{
		var param = fnArguments[i];
		var elemId = param;
		var elemRef = document.getElementById(elemId);
	
	    //remove cityCode for ex: /12345
	    var cityCodePattern = new RegExp('\/.*','gi');
	    var elemValue = elemRef.value.replace(cityCodePattern,'');
		
		//remove if only city code is integer
		var cityIntCode = new RegExp('[0-9]','gi');
		var elemValueInt = elemValue.replace(cityIntCode, '');

	    elemRef.value = elemValueInt;
	}
}

/*
 * clear both airport code value 
 * if one of the airport code is null
 */
function checkValidCityCode(from, to){
	var fromElem = document.getElementById(from);
	var toElem = document.getElementById(to);
	
	if(fromElem.value == '' || toElem.value == ''){
		fromElem.value = '';
		toElem.value = '';
	}
}

function hideSeeMoreLink()
{
	var y = document.getElementsByTagName('a');
	for (i=0;i<y.length;i++)
	{
		if(y[i].href.indexOf('aolsearch.aol.com/aol/weboffers') > 0)
		{
			y[i].parentNode.style.display = 'none';
			break;
		}
	}	
	
}

 function done(sponsorData) {
 	//If there is at least one results then create some sponsored links
 	if(sponsorData.length!=0) {
 		//Build up a string of HTML to display the results
 		s="";
 		s+="<div><h5><a href='http://about-search.aol.com/index.html#sl' target='_blank' title='Sponsored Links'>Sponsored Links</a></h5></div>"
 		   +"<ul>";
 
 		//For each sponsored link in the results array, add a list item to the unordered list
 		for (i=0;i<sponsorData.length;i++) {
 			if(i < 4){
 				s+="<li>"
 				+"<a target='_blank' href='"
 				+sponsorData[i].redirect_url
 				+"' onmouseover=\"self.status='"
 				+sponsorData[i].url
 				+"'; return true\" onmouseout='self.status=\"\"; return true'><h2>"
 				+sponsorData[i].title
 				+"</h2>"
 				+"<h4>"+sponsorData[i].d1+" "+sponsorData[i].d2+"</h4>"
 				+"<h3>"+sponsorData[i].url+"</h3></a>"
 				+"</li>";
 			}
 			
 		}
 		s+="</ul>";
 		
 	} else {
 		//we got no results so do some default behavior or even nothing at all.
 		s="";
 	}
 	if(s != ""){
 		document.getElementById('travelSponsoredLinks').innerHTML = s;
 		document.getElementById('travelSponsoredLinks').style.display = "block";
 	}else{
 		document.getElementById('travelSponsoredLinks').style.display = "none";
 	}
 	//Stuff the string of HTML into the DIV we created for it
 }


    /********************************************************
                    Calendar Functions
    ********************************************************/

g_Calendar = new Object();
g_Calendar.showCal = function(){};
g_Calendar.hide = function(){};
var browserType = navigator.userAgent;
var justClicked = false;
var miniCalendar;
var m_Calendar;
if(typeof staticDomain == 'undefined')
	var staticDomain = '';

 
function MiniCalendar(){
                                  
        divOffCal                  = this.divOffCal                 
        divOnCal                   = this.divOnCal                  
        errorMessage            = this.errorMessage                   

        this.serverDate = serverDate;
        this.initCalendars = initCalendars;
        this.Calendar  = Calendar;
        this.handleDocumentClick = handleDocumentClick;




    var g_startDay = 0// 0=sunday, 1=monday
    
    var calHeight = 115;

    // sniffer
    function Browser(){
        this.moz = (!document.all)?1:0;
        this.ie5 = (document.all)?1:0;
        this.ie6strict = (document.documentElement && document.documentElement.clientHeight)?1:0;
        this.safari = (navigator.userAgent.toLowerCase().indexOf("safari") != -1)?1:0;
    }
    var browser = new Browser();


    var g_Calendar;
    var g_target;
	var g_cTarget;
	var g_box;

    function Calendar(){
        g_Calendar = this;
        var tmpLayer = document.getElementById('container');
        this.containerLayer = tmpLayer;
    }

    Calendar.prototype.showCal = function(event, target, cTarget, box){
        if (this.containerLayer!=null) {
        if (this.containerLayer.style.visibility=='visible'){
            document.getElementById('ifrm_cal').style.display = 'none'
            document.getElementById('bg_ifrm').style.display = 'none'
            this.containerLayer.style.visibility='hidden';
        }
          var obj = document.getElementById(target);
	if(browser.ie5){
		var event = window.event;
		var winBottom = (browser.ie6strict) ? (document.documentElement.clientHeight + document.documentElement.scrollTop) : (document.body.clientHeight + document.body.scrollTop);
		var obj = document.getElementById(target);
		x = 0;
		//WORKAROUND FOR GETTING THE RELATIVE X POSITION WRT BODY ELEMENT
	    while(obj.tagName != 'BODY'){
		x+=obj.offsetLeft;
		obj=obj.offsetParent;
	    }
		y = 0;
		var obj = document.getElementById(target);

		y = findPosY(obj) + obj.offsetHeight + 1;

		this.containerLayer.style.left = document.getElementById('bg_ifrm').style.left = x;

		var calBottom = y + calHeight;
		var overTop = y - calHeight - 15;

		this.containerLayer.style.top = document.getElementById('bg_ifrm').style.top = (calBottom < winBottom) ? y : overTop;
	}
	if(browser.moz){
		document.getElementById('bg_ifrm').style.left = (findPosX(obj))+'px';
     	   	this.containerLayer.style.left = (findPosX(obj))+'px';
        	document.getElementById('bg_ifrm').style.top = findPosY(obj)+20+'px';
        	this.containerLayer.style.top = findPosY(obj)+20+'px';
    	}	
        this.target = target;
        g_target = this.target;

		this.cTarget = cTarget;
		g_cTarget = this.cTarget;

		this.box = box;
		g_box = this.box;

        getCal();
        this.containerLayer.style.visibility='visible';
        document.getElementById('ifrm_cal').style.display = 'block'
        document.getElementById('bg_ifrm').style.display = 'block'
        justClicked = true;
        doTimeout('justClicked');
        }
    }

    function findPosX(obj){
        var curleft=0;
        while (obj.offsetParent){
            curleft+=obj.offsetLeft;
            obj=obj.offsetParent;
        }
        curleft+=obj.offsetLeft;
        return curleft;
    }

    function findPosY(obj){
        var curtop = 0;
        while(obj.offsetParent){
            curtop += obj.offsetTop;
            obj=obj.offsetParent;
        }
        curtop+=obj.offsetTop;
        return curtop;
    }

    function getTarget(){
        return g_Calendar.target;
    }

    Calendar.prototype.hide = function(){
        if (this.containerLayer!=null) {
            this.containerLayer.style.visibility='hidden';
            document.getElementById('ifrm_cal').style.display = 'none'
            document.getElementById('bg_ifrm').style.display = 'none'
     //       divOffCal('bb_bkeyword');
     //       divOnCal('bb_bkeyword');
        }
    }

    function initCalendars(calLists){
        for(c in calLists){
            for(var x=0;x<calLists[c].length;x++){
				if(document.getElementById(c))
					document.getElementById(c). setAttribute('autocomplete', 'off');
				if(calLists[c][x] == 'mdy' && document.getElementById(c))
						document.getElementById(c).value = 'mm/dd/yyyy';
				else
					buildDate(parseInt(calLists[c][x],10),c);
            }
        }
    }


    function buildDate(num,t){
        var adjDate = new Date(serverDate);
        adjDate.setDate(adjDate.getDate()+num);

        var d = ((adjDate.getMonth()+1)<10?'0'+(adjDate.getMonth()+1):(adjDate.getMonth()+1)) + '/' + (adjDate.getDate()<10?'0'+adjDate.getDate():adjDate.getDate()) + '/' + adjDate.getFullYear();
        if(document.getElementById(t))
            document.getElementById(t).value = d;
        
    }

            /****************************
                from calendat.html
             ****************************/

    var aDate=new Date();
    var aYear=aDate.getYear();
    if (aYear<1000) aYear+=1900;
    var aMonth=aDate.getMonth()+1;
    if (aMonth<10) aMonth="0"+aMonth;
    var aDay=aDate.getDate();
    if (aDay<10) aDay="0"+aDay;

    var serverDate = aMonth+"/"+aDay+"/"+aYear;
    var d = new Date(serverDate);

    if (navigator.userAgent.toLowerCase().indexOf("safari") != -1) { document.writeln("<style></style>"); }     


    function getCal(){
    this.showCal = showCal;
    this.pushDate = pushDate;
    //this.splitUserDate = splitUserDate;

            function getTarget() {
         //       query = '' + window.location;
          //      query = query.substring((query.indexOf('=')) + 1);
                return g_target;
            }

			function getcTarget(){
				return g_cTarget;
			}

			function getBox(){
				return g_box;
			}

            function Calendar(m) {
                this.date = new Date(serverDate);
                this.date.setDate(1);
                /* worx Safari fix */
                if(m<0) {
                    var subYears = m/12;
                    if(m%12==0)--subYears;
                    m = m%12+12;
                    this.date.setFullYear(this.date.getFullYear()+subYears);
                }
                else if(m>11) {
                    var addYears = m/12;
                    m = m%12;
                    this.date.setFullYear(this.date.getFullYear()+addYears);
                }
                /* worx Safari fix end */
                this.date.setMonth(m);
                if(arguments.length == 2) {
                    this.date.setYear(arguments[1])
                    inc = this.date.getMonth();
                }
                this.month = m%12;
                this.months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
                if(this.date.getYear()%400==0 || (this.date.getYear()%4==0 && this.date.getYear()%100!=0))
                    this.daysInMonth = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
                else
                    this.daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
            }

            Calendar.prototype.getFirstDay = function() {
                this.date.setDate(1);
                return this.date.getDay();
            }

            Calendar.prototype.fillCalendar = function() {
                var extraWeek = 7;
				var selDate = null;
				var selcDate = null;
				var badSel = false;
				var styDate ="";

				var tg = document.getElementById(target).value;
				var ctg = document.getElementById(cTarget).value;

				if(tg != 'mm/dd/yyyy' && tg != "" && checkUserDate(splitUserDate(target)))
					selDate = new Date(tg);
				if(ctg != 'mm/dd/yyyy' && ctg != "" && checkUserDate(splitUserDate(cTarget)))
					selcDate = new Date(ctg);

				if(box == 2){
					var temp = selDate;
					selDate = selcDate;
					selcDate = temp;
				}
				if(selDate > selcDate){
					badSel = true;
					var temp = selDate;
					selDate = selcDate;
					selcDate = temp;
				}
				if(selDate == null){
					selDate = selcDate;
				}

				if(selcDate != null && selcDate.getMonth() != this.month){
					styDate = "";
				}
				if(selcDate != null && selDate.getMonth() != selcDate.getMonth() && selcDate.getMonth() == this.month){
					styDate = "style='background:#184A7B;color:#FFF'";
				}

                var code = '<div class="calendar"><div class="cal_top"><a href="javascript:;" onclick="showCal(100);event.cancelBubble = true;return false;"><img src="'+staticDomain+'/img/cal-larrow.gif" width="5" height="6" alt="Previous Month" title="Previous Month" /></a><a href="javascript:;" onclick="showCal(200);event.cancelBubble = true;return false;"><img src="'+staticDomain+'/img/cal-rarrow.gif" width="5" height="6" alt="Next Month" title="Next Month" /></a><p>'+this.months[this.date.getMonth()]+' '+this.date.getFullYear()+'</p></div>';
                code += '<div class="header"><p class="wend">Su</p><p>Mo</p><p>Tu</p><p>We</p><p>Th</p><p>Fr</p><p class="wend">Sa</p></div><div class="cal_body">';
                for(var i=0; i < (35+extraWeek); ++i) {
                    if(i < this.getFirstDay() || i >= this.daysInMonth[this.month]+this.getFirstDay()){
                        if(i==0 || i==7 || i==14 || i==21 || i==28 || i==35 || i==42 || i==6 || i==13 || i==20 || i==27 || i==34 || i==41){
                            code += '<p class="wend">&nbsp;</p>';
                        } else{
                            code += '<p>&nbsp;</p>';
                        }
                    }
                    else{
                        var d = ((this.date.getMonth()+1)<10?'0'+(this.date.getMonth()+1):(this.date.getMonth()+1))+'/'+((i-this.getFirstDay()+1)<10?'0'+(i-this.getFirstDay()+1):(i-this.getFirstDay()+1))+'/'+this.date.getFullYear();
                        var compare = new Date(serverDate);
                        compare.setMonth( d.split('/')[0]-1);
                        compare.setDate( d.split('/')[1]);
                        compare.setFullYear( d.split('/')[2]);
                        if(typeof pastDates == 'undefined'){
                            if(i==0 || i==7 || i==14 || i==21 || i==28 || i==35 || i==42 || i==6 || i==13 || i==20 || i==27 || i==34 || i==41){
                                if((compare < startDate) || (compare >= endDate)){
                                    code += '<p class="wend out">'+(i-this.getFirstDay()+1)+'</p>';
                                }else{
									if(selDate != null && selDate.toString() == compare.toString() || selcDate != null && selcDate.toString() == compare.toString()){
										styDate = "style='background:#184A7B;color:#FFF'";
									}else if(badSel){
										styDate = styDate.replace("#184A7B","#FF5D59");
									}else{
										styDate = styDate.replace("#184A7B","#4B84BD");
									}
                                    code += '<p><a href="#" onclick="pushDate(\''+d+'\');return false;" class="wend" '+styDate+'>'+(i-this.getFirstDay()+1)+'</a></p>';
									if(selcDate == null || selcDate.toString() == compare.toString()){
										styDate = "";
									}
								}
                            } else{
                                if((compare < startDate) || (compare >= endDate)){
                                    code += '<p class="out">'+(i-this.getFirstDay()+1)+'</p>';
                                } else{
									if(selDate != null && selDate.toString() == compare.toString() || selcDate != null && selcDate.toString() == compare.toString()){
										styDate = "style='background:#184A7B;color:#FFF'";
									}else if(badSel){
										styDate = styDate.replace("#184A7B","#FF5D59");
									}else{
										styDate = styDate.replace("#184A7B","#4B84BD");
									}
                                    code += '<p><a href="#" onclick="pushDate(\''+d+'\');return false;" '+styDate+'>'+(i-this.getFirstDay()+1)+'</a></p>';
									if(selcDate == null || selcDate.toString() == compare.toString()){
										styDate = "";
									}
                                }
                            }
                        } else{
                            if(i==0 || i==7 || i==14 || i==21 || i==28 || i==35 || i==42 || i==6 || i==13 || i==20 || i==27 || i==34 || i==41){
                                if((compare < startDate)){
                                    code += '<p><a href="#" onclick="pushDate(\''+d+'\');return false;" class="wend" style="color:blue">'+(i-this.getFirstDay()+1)+'</a></p>';
                                } else{
                                    code += '<p class="wend out">'+(i-this.getFirstDay()+1)+'</p>';
                                }
                            } else{
                                if((compare < startDate)){
                                    code += '<p><a href="#" onclick="pushDate(\''+d+'\');return false;">'+(i-this.getFirstDay()+1)+'</a></p>';                                
                                } else{
                                    code += '<p class="out">'+(i-this.getFirstDay()+1)+'</p>';
                                }
                            }
                        }
                    }
                }
                code += '</div></div>';
                return code;
            }
            

            Calendar.prototype.createCalendar = function() {
         //       var c_area = document.getElementById('containers');
         //       c_area.innerHTML = this.fillCalendar();
                  document.getElementById('container').innerHTML = "";
                  document.getElementById('container').innerHTML = this.fillCalendar();
            }

            function pushDate(dateStr){
                var topFrame = document;
                var form = topFrame.forms['frm'];
                target = getTarget();
			
                topFrame.getElementById(target).value=dateStr;
                //topFrame.getElementById(target).onclick();
                document.getElementById('ifrm_cal').style.display = 'none'
                document.getElementById('bg_ifrm').style.display = 'none'
                $j("#"+target).trigger('pushed');
            }

            function splitUserDate(incomingElement, rplc){
				
                var usersDate = document.getElementById(incomingElement);
				var userDateRtn = usersDate.value;
				if(typeof rplc != 'undefined' && !checkUserDate(splitUserDate(incomingElement))){
					var crDate = new Date(serverDate);
					userDateRtn = (crDate.getMonth()+1)+"/"+crDate.getDate()+"/"+crDate.getYear();
				}
                var dateArray = (userDateRtn).split("/");
                return dateArray;
            }

            function showCal(m){
				if(browserType.indexOf("Firefox/3") != -1){
					justClicked = true;
				}
				
            	if(m == 100)
                    m = --inc;
                else if(m == 200)
                    m = ++inc;

				var byear = splitUserDate(g_target);

				if(!isNaN(byear[2]) && byear[2].length == 4){
					m = (byear[2]*1-new Date(serverDate).getFullYear())*12+m;
				}else{
					byear = splitUserDate(g_cTarget);	
					if(!isNaN(byear[2]) && byear[2].length == 4){
						m = (byear[2]*1-new Date(serverDate).getFullYear())*12+m;
					}
				}

				
                if(arguments.length == 2){
                    var cal = new Calendar(arguments[0],arguments[1]);
                }else{
					var cal = new Calendar(m); 
				}
                cal.createCalendar();
            }
           
            function checkUserDate(incomingDate){
                var month = parseInt(incomingDate[0], 10);
                var day = parseInt(incomingDate[1], 10);
                var year = parseInt(incomingDate[2], 10);

				if(isNaN(month) || isNaN(day) || isNaN(year)){
					return 0;
				}
                var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
                if(year%400==0 || (year%4==0 && year%100!=0))
                    var daysInMonth = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
                else
                    var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
                if(month < 1 || month > 12){
                   // alert('Please enter a valid month.');
					//Commented to stop alert looping
                    //showCal(inc, date.getFullYear());   //Defaults to serverDate
                    return 0;
                }
                if(day < 1 || day > daysInMonth[month-1]){
                   // alert('That is not a valid number of days.');
					//Commented to stop alert looping
                    //showCal(inc, date.getFullYear());   //Defaults to serverDate
                    return 0;
                }
                return 1;
            }

            function isLeap(y) {
                return ( (y.getYear()%400 == 0 || y.getYear()%4 == 0 && y.getYear()%100 != 0)?1:0);
            }
            function daysInMonth(mydate) {
                if (isLeap(mydate)) days = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
                else days = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
                return days[mydate.getMonth()];	
            }

            var date = new Date(serverDate);
            var inc = date.getMonth();
            var target = getTarget();
			var cTarget = getcTarget();
			var box = getBox();
            var target2;

            //NOT ALWAYS SETTING CORRECTLY!!
            var startDate = new Date(serverDate);
            var endDate = new Date(serverDate);

            var i = 331 - (daysInMonth(startDate) - startDate.getDate());

            while ( i > daysInMonth(endDate) ) {
                i-=daysInMonth(endDate);
                if(endDate.getMonth() < 11) { endDate.setMonth(endDate.getMonth()+1); }
                else {
                    endDate.setMonth(1);
                    endDate.setFullYear(endDate.getFullYear()+1);
                }
            }

            endDate.setDate(i);

            //Code for autopagination of months for the calendar
			// Calendar will open based on user selected date.
			if(box == 2 && checkUserDate(splitUserDate(cTarget)) && !checkUserDate(splitUserDate(target)) || splitUserDate(cTarget)[0] == splitUserDate(target)[0]){
				var usersDateArray = splitUserDate(cTarget, true);
			}else {
				var usersDateArray = splitUserDate(target, true);
			}
			
			//if(splitUserDate(cTarget)[0] == splitUserDate(target)[0])
			
            if ( (usersDateArray.length > 1) && (usersDateArray[0].length<=2 && usersDateArray[1].length<=2 && usersDateArray[2].length==4) && !isNaN(usersDateArray[2])){
				if(checkUserDate(usersDateArray)){
                    showCal(usersDateArray[0]-1,usersDateArray[2]);	
                }
            }
            else{
				//alert('Please enter date in mm/dd/yyyy format.');
                showCal(inc, date.getFullYear());   //Defaults to serverDate
            }
    }

    function handleDocumentClick(e){
    
 		doTimeout('justClicked');     
        if(justClicked == false){
            if (document.all) e = window.event;

            if(e != null && g_Calendar && g_Calendar.containerLayer){
                var bTest = (e.pageX > parseInt(g_Calendar.containerLayer.style.left,10) && e.pageX <  (parseInt(g_Calendar.containerLayer.style.left,10)+125) && e.pageY < (parseInt(g_Calendar.containerLayer.style.top,10)+125) && e.pageY > parseInt(g_Calendar.containerLayer.style.top,10));
                if(!bTest)
                    g_Calendar.hide();
            }

        }
    }

    function doTimeout(name){
        window.setTimeout(name + '= false',100);
        return;
    }
}
function divOffCal(id)
{
if(document.getElementById(id) != null)
{
document.getElementById(id).style.display = 'none';
}
}

function divOnCal(id)
{
if(document.getElementById(id) != null)
{
document.getElementById(id).style.display = 'inline';
}
}

var aDate=new Date();
var aYear=aDate.getYear();
if (aYear<1000) aYear+=1900;
var aMonth=aDate.getMonth()+1;
if (aMonth<10) aMonth="0"+aMonth;
var aDay=aDate.getDate();
if (aDay<10) aDay="0"+aDay;

var serverDate = aMonth+"/"+aDay+"/"+aYear;


function validateBooking(){
	if(!validDate(document.bookingForm.checkIn,'cin')){
		errorMsg();
        errors = new Array();
		return false;
	}
	var chkIn = document.bookingForm.checkIn.value;

	if(!validDate(document.bookingForm.checkOut,'cout')){
		errorMsg();
        errors = new Array();
		return false;
	}
	var chkOut = document.bookingForm.checkOut.value;

	if(convertDate(chkIn,'us','js') > convertDate(chkOut,'us','js')){ 
		errors = errors.concat('Check-out date can not be earlier than check-in date.');
		errorMsg();
        errors = new Array();
		return false;
	}else if(chkIn == chkOut){
        errors = errors.concat('Check-out date must be different from the Check-in date');
		errorMsg();
        errors = new Array();
		return false;
	}

	document.bookingForm.dateLeavingMonth.value = chkIn.split("/")[0];
	document.bookingForm.dateLeavingDay.value = chkIn.split("/")[1];
	document.bookingForm.dateReturningMonth.value = chkOut.split("/")[0];
	document.bookingForm.dateReturningDay.value = chkOut.split("/")[1];
	return true;
}


//ACTUAL DATE VALIDATION
function validDate(d,which)
{
	var val = d.value;
	var valid = 0;
	var wdate = '';
    if(which == "depart"){wdate='depart';}
	else if(which == "return"){wdate='return';}
	else if(which == "cin"){wdate='check-in';}
	else if(which == "cout"){wdate='check-out';}
	else if(which == "pickup"){wdate='pick-up';}
	else if(which == "dropoff"){wdate='drop-off';}
	if(val == '')
	{
		if(wdate != '')
			errors = errors.concat('Please enter your '+wdate+' date.');
		else
			errors = errors.concat('Enter your date information.');		
		return false;
	}
	else
	{
		if(val.split('/').length == 3)
		{
	//THIS WILL MAKE DATES LIKE '5/6/06' VALID. AND IT WILL BE CHANGED TO '05/06/2006'
		var valsp = val.split('/');
		var month = valsp[0];

		if (month.length == 1)
		{
			month = "0" + month;
		}
		var day = valsp[1];
		if (day.length == 1)
		{
			day = "0" + day;
		}
		var year = valsp[2];
		if (year.length == 2)
		{
			year = "20" + year;
		}
		val =  month + '/' + day + '/' + year;
		d.value = val;
		}
		if(val.search(/^\d{2}\/\d{2}\/\d{4}$/) != -1)
		{
			var vFmt = null;
			vFmt = val.search(/^\d{2}\/\d{2}\/\d{4}$/);

			val = val.substr(vFmt,10);
			if( ((val.split('/')[0]<=12) && (val.split('/')[0]>=1)) && ((val.split('/')[1]<=31) && (val.split('/')[1]>=1)) )
			{
				if(!sensibleDate(val))
				{
					return false;
				}
				if(!validRange(val,which))
				{
					return false;
				}
			}
			else
			{
				if(wdate != '')
					errors = errors.concat('You have entered a non-existent date for '+wdate+'.\nPlease re-enter the date.');
				else
					errors = errors.concat('You have entered a non-existent date.\nPlease re-enter the date.');			
				return false;
			}
		}
		else
		{
			if(wdate != '')
				errors = errors.concat('Invalid Date Format\nPlease enter the '+wdate+' date in the format:\nmm/dd/yyyy');
			else
				errors = errors.concat('Invalid Date Format\nPlease enter the date in the format:\nmm/dd/yyyy');
			return false;
		}
	}
	return true;
}

//CHECKS IF THE INDATE AND OUTDATE ARE WITH IN THE VALID RANGE
var errors = new Array();

function validRange(d,which)
{
	// TODAY (00:00:00)
	var t = new Date(serverDate);
	today = zeroTime(t);

	// MAX: TODAY + 365 Days (00:00:00)
	var m = new Date(serverDate);
	m = zeroTime(m);

	if (navigator.userAgent.toLowerCase().indexOf("safari") == -1)
	{ //WORKAROUND FOR APPARENT SAFARI JS DATES BUG
		m.setDate(m.getDate()+365);
	}
	else
	{
		for(var i = 0; i<365; i+=5)
		{
			m.setDate(m.getDate()+5);
		}
	}

	// SUBMAX: MAX - 1 Day (00:00:00)
	var s = new Date(serverDate);
	s.setTime(m.getTime());
	s.setDate(s.getDate()-1);


	var cin = m;
	var cout = new Date(serverDate);
	cout.setTime(m.getTime());
	cout.setDate(cout.getDate()+1);

	d = convertDate(d,'us','js');

    switch(which){
        case 'cin':
            if(d > s){
                errors = errors.concat('Check-in date you entered is too far in advance to show availability.');
                return false;
            } else if (d < t){
                errors = errors.concat('Check-in date you entered has already passed.');
                return false;
            }
            break;
        case 'pickup':
            if(d > s){
        
                errors = errors.concat('Pick-up date you entered is too far in advance to show availability.');
                return false;
            } else if (d < t){
                errors = errors.concat('Pick-up date you entered has already passed.');
                return false;
            }
            break;
        case 'dropoff':
            if(d > m){
                errors = errors.concat('Drop-off date you entered is too far in advance to show availability.');
                return false;
            } else if (d < t){
                errors = errors.concat('Drop-off date you entered has already passed.');
                return false;
            }
            break;
        case 'depart':
            if(d > s){
            errors = errors.concat('Departure date you entered is too far in advance to show availability.');
                return false;
            } else if (d < t){
                errors = errors.concat('Departure date you entered has already passed.');
                return false;
            }
            break;
        case 'return':
            if(d > m){
                errors = errors.concat('Return date you entered is too far in advance to show availability.');
                return false;
            } else if (d < t){
                errors = errors.concat('Return date you entered has already passed.');
                return false;
            }
            break;
        default:
            if(d > m){
                errors = errors.concat('Check-out date you entered is too far in advance to show availability.');
                return false;
            } else if (d < t){
                errors = errors.concat('Check-out date you entered has already passed.');
                return false;
            }
            break;
    }
    	return true;
}

function sensibleDate(d)
{
	var newD = new Date(d);
	if(newD.getMonth()+1 != parseInt(d.split('/')[0],10))
	{
		errors = errors.concat('You have entered a non-existent date.\nPlease re-enter the date.');
		return false;
	}
	return true;
}

function errorMsg()
{
	if (errors.length > 0)
	{
		alert(errors.join('\n')); errors.length=0;
		return false;
	}
	else
	{
		return true;
	}
}

function zeroTime(d){
    d.setHours(0);
    d.setMinutes(0);
    d.setSeconds(0);
    d.setMilliseconds(0);
    return d;
}

function convertDate(d,from,to) {
    var date1 = null;
    var date2 = null;
    switch(from){
        case 'int':
            d = d.toString();
            date1 = new Date(serverDate);
            date1.setFullYear(parseInt(d.substr(0,4)));
            date1.setMonth(parseInt(d.substr(4,2),10)-1);
            date1.setDate(parseInt(d.substr(6,2),10));
            date1 = zeroTime(date1);
            break;
        case 'us':
            d = d.toString();
        date1 = new Date(d);
            break;
        case 'js':
            date1 = d;
            break;
        default:
            date1 = d;
            break;
    }
    switch(to){
        case 'js':
            return date1;
            break;
        case 'int':
            date2 = date1.getFullYear()+''+( (date1.getMonth()+1 < 10) ? '0'+(date1.getMonth()+1):(date1.getMonth()+1))+''+(date1.getDate()<10?'0'+date1.getDate():date1.getDate());
            return date2;
            break;
        case 'us':
            date2 = ( (date1.getMonth()+1 < 10) ? '0'+(date1.getMonth()+1):(date1.getMonth()+1))+'/'+(date1.getDate()<10?'0'+date1.getDate():date1.getDate())+'/'+date1.getFullYear();
            return date2;
            break;
        default:
            date2 = date1;
            return date2;
            break;
    }
}

if (getckeval != null && getckeval != 'null' && getckeval != '')
{
	var swapcheckvalue = 'Travelocity';
}
/*else if (_sns_isLoggedIn == 0)
{
	var swapcheckvalue = 'Travelocity';
}*/
else
{
	var swapcheckvalue = 'Travelocity';
}
						
if(tabToSel == 'Hotel'){
	selTab = 'hotelsTab';
	showForm = 'hotelsForm';
	}
else if(tabToSel == 'Car'){
	selTab = 'carsTab';
	showForm = 'carsForm';
}
else if(tabToSel == 'Cruise'){
	selTab = 'cruisesTab';
	showForm = 'cruisesForm';
}
else if(tabToSel == 'Vacation'){
	selTab = 'vacationsTab';
	showForm = 'vacationsForm';
}
else{
	selTab = 'flightsTab';
	showForm = 'flightsForm';
	
}

if(!readCookieVal('pers') || !readCookieVal('sesn')){
	var date = new Date();
	date.setTime(date.getTime()+(30*60*1000));
	var expires = "; expires="+date.toGMTString();

	document.cookie =  "pers=1"+expires+"path=/";
	document.cookie = "sesn=1;path=/";
	firstPageLoad = true;
}

window.onload = function(){

	document.getElementById('vachild1').selectedIndex = 0;
	document.getElementById('vanumOfRooms').selectedIndex = 0;
}

function refAdd(){
	try {
		if (tabToSel == 'Hotel') {
			reloadAdIfNotEmpty(addOneHO);
		} else if (tabToSel == 'Flight') {
			reloadAdIfNotEmpty(addOneFL);
		} else if (tabToSel == 'Car') {
			reloadAdIfNotEmpty(addOneCA);
		} else if (tabToSel == 'Cruise') {
			reloadAdIfNotEmpty(addOneCR);
		} else if (tabToSel == 'Vacation') {
			reloadAdIfNotEmpty(addOneVA);
		} else if (tabToSel == 'FLHO') {
			reloadAdIfNotEmpty(addOneFLHO);
		}
	}catch(e){
	}
}

function reloadAdIfNotEmpty(mn) {
	if (mn != '') {
		adsReloadAd('squareAd1', mn)
	} else {
		$j('#squareAd1').html('');
	}
}

function radioClick(obj,radio){
	if(radio == 'flho'){
		tabToSel = 'FLHO';
	}
	refAdd();
}

function initBodyEvent(){
	if(typeof miniCalendar != 'undefined'){
		miniCalendar.handleDocumentClick(this);
	}
}


function initTab(){
	$j('.mainTabs div').bind('click', function() {
		return false;		
	});
	$j('#flightsTab div').bind('click', function() {
			formToShow('flightsForm');
  	});
  	$j('#hotelsTab div').bind('click', function() {
			formToShow('hotelsForm');
  	});
  	$j('#carsTab div').bind('click', function() {
			formToShow('carsForm');
  	});
  	$j('#cruisesTab div').bind('click', function() {
			formToShow('cruisesForm');
  	});
	$j('#vacationsTab div').bind('click', function() {
			formToShow('vacationsForm');
  	});
}

function formToShow(frmShow)
{
	initBodyEvent();
	closePricePop();

	$j('.mainForms').removeClass('showForm');
	$j('.mainForms').addClass('hideForm');
	$j('.mainTabs div').removeClass('onTab');
	$j('.mainTabs div').addClass('offTab');

	if(frmShow == 'flightsForm'){
		$j('#flightsForm').removeClass('hideForm');
		$j('#flightsForm').addClass('showForm swapImgFlights');
		$j('#flightsTab div').removeClass('offTab');
  		$j('#flightsTab div').addClass('onTab');	
		refreshAds('flightForm');
		loadShermansDeals('flightForm');
	}
	else if(frmShow == 'hotelsForm'){
		$j('#hotelsForm').removeClass('hideForm');
		$j('#hotelsForm').addClass('showForm swapImgHotels');
		$j('#hotelsTab div').removeClass('offTab');
  		$j('#hotelsTab div').addClass('onTab');	
		refreshAds('hotelForm');
		loadShermansDeals('hotelForm');
	}
	else if(frmShow == 'carsForm'){
		$j('#carsForm').removeClass('hideForm');
		$j('#carsForm').addClass('showForm swapImgCars');
		$j('#carsTab div').removeClass('offTab');
  		$j('#carsTab div').addClass('onTab');	
		refreshAds('carForm');
		loadShermansDeals('carForm');
	}
	else if(frmShow == 'cruisesForm'){
		$j('#cruisesForm').removeClass('hideForm');
		$j('#cruisesForm').addClass('showForm swapImgCruises');
		$j('#cruisesTab div').removeClass('offTab');
  		$j('#cruisesTab div').addClass('onTab');	
		refreshAds('cruiseForm');
		loadShermansDeals('cruiseForm');
	}
	else if(frmShow == 'vacationsForm'){
		$j('#vacationsForm').removeClass('hideForm');
		$j('#vacationsForm').addClass('showForm swapImgVacations');
		$j('#vacationsTab div').removeClass('offTab');
  		$j('#vacationsTab div').addClass('onTab');	
		refreshAds('vacationForm');
		loadShermansDeals('vacationForm');
	}
}

function refreshAds(frmShowing)
{
	var omniTabSel = '';
	switch(frmShowing){
		case 'flightForm':
			if(firstTimeFlight){
				if(!readCookieVal('flightMain') && firstTimeFlight){
					updateFormDetails('AirSearchForm','flightLob','main');
					smartBoxSelInput('AirSearchForm', "leavingFrom", ""); 
					smartBoxSelInput('AirSearchForm', "goingTo", ""); 
				}else{
					updateFormDetails('AirSearchForm','flightMain','main');
				}
				firstTimeFlight = false;
			}
			omniTabSel = tabToSel = 'Flight';
			document.getElementById('leavingFromFL').focus();
			break;
		case 'hotelForm':
			omniTabSel = tabToSel = 'Hotel';
			document.getElementById('trvCity').focus();
			break;
		case 'carForm':
			if(firstTimeCar){
				if(!readCookieVal('carMain')){
					updateFormDetails('formCATrv','carLob','main');
					smartBoxSelInput('formCATrv', "pickupCity", ""); 
					smartBoxSelInput('formCATrv', "dropoffCity", "");
				}else{
					updateFormDetails('formCATrv','carMain','main');
				}
				firstTimeCar = false;
			}
			omniTabSel = tabToSel = 'Car';
			document.getElementById('pickupCity').focus();
			break;
		case 'cruiseForm':
			if(firstTimeCruise){
				initCruise();
				firstTimeCruise = false;
			}
			omniTabSel = tabToSel = 'Cruise';
			document.getElementById('destination').focus();
			break;
		case 'vacationForm':
			if(firstTimeVacation){
				if(!readCookieVal('vacationMain'))
					updateFormDetails('VacationSearchForm','vacationLob','main');
				else
					updateFormDetails('VacationSearchForm','vacationMain','main');
				firstTimeVacation = false;
			}
			omniTabSel = tabToSel = 'Vacation';
			document.getElementById('valeavingFrom').focus();
			break;
	}
	if(firstLoad){
		firstLoad = false;
	}
	else{
		window.setTimeout('refAdd()',100);
	}
	
}


function loadShermansDeals(tabValue) {
	var time = Math.round(new Date().getTime()/1000);
	if (tabValue == 'hotelForm') {
		$j("#mainDealsResults").load("/travel-deals/inc/shermansMainHotelDeals.jsp?preview="+preview+"&amp;ts="+time); 
	}
	else if (tabValue == 'carForm') {
		$j('#mainDealsResults').load("/travel-deals/inc/shermansMainCarDeals.jsp?preview="+preview+"&amp;ts="+time);
	}
	else if (tabValue == 'cruiseForm') {
		$j('#mainDealsResults').load("/travel-deals/inc/shermansMainCruiseDeals.jsp?preview="+preview+"&amp;ts="+time);
	}
	else if (tabValue == 'vacationForm') {
		$j('#mainDealsResults').load("/travel-deals/inc/shermansMainVacationDeals.jsp?preview="+preview+"&amp;ts="+time); 
	}
	else {
		$j('#mainDealsResults').load("/travel-deals/inc/shermansMainFlightDeals.jsp?preview="+preview+"&amp;ts="+time); 
	}
}


var tabColor = '';
function highlightTab(obj){
	tabColor = obj.style.color;
	obj.style.color = '#C65A18';
}

function restoreTab(obj){
	obj.style.color = tabColor;
}

function showLinks(obj){
	obj.className = "smallImgDiv showImgList";
	obj.getElementsByTagName('IMG')[0].className = "smallImg hideBtmMrg";
}

function hideLinks(obj){
	obj.className = "smallImgDiv imgList";
	obj.getElementsByTagName('IMG')[0].className = "smallImg btmMrg";
}

function initCruise(){
	dhtmlLoadScript(staticDomain+"/js/travelocityCruiseAPI.js");
	afterAPILoad();
}

function afterAPILoad(){
	if(typeof destSelectList == 'undefined'){
		window.setTimeout('afterAPILoad()', 1);
	}
	else{
		doVendorSel('cruiseVendor', 'All Cruise Lines');
		afterCruiseLoad();
	}
}

function afterCruiseLoad(){
	if ( typeof( window[ 'destSelectList' ] ) != "undefined" ) {
	//	document.getElementById('destination').innerHTML = document.getElementById('destination').innerHTML+destSelectList; 
		var splitOpt = destSelectList.replace(/  <option value=\"/g,'');
		splitOpt = splitOpt.replace(/<\/option>/g,'">');
		splitOpt = splitOpt.replace(/&nbsp;/g,' ');
		splitOpt = splitOpt.replace(/&#187;/g,String.fromCharCode(187));
		splitOpt = splitOpt.split(/\">/g);

		var splitOptLength = splitOpt.length;
		var x=1;
		for(var i=0;i<splitOptLength;i++){
			if(typeof splitOpt[i+1] != "undefined"){
				document.getElementById('destination').options[x] = new Option(splitOpt[i+1],splitOpt[i]);
				i++;x++;
			}
		}
	} else {
		document.getElementById('geoDest').text = "Currently Unavailiable";
	}

	if ( typeof( window[ 'monthSelectList' ] ) != "undefined" ) {
	//	document.getElementById('fromMonthYear').innerHTML = document.getElementById('fromMonthYear').innerHTML+monthSelectList;
		var splitOpt = monthSelectList.replace(/<option value=\"/g,'');
		splitOpt = splitOpt.replace(/<\/option>/g,'">');
		splitOpt = splitOpt.split(/\">/g);

		var splitOptLength = splitOpt.length;
		var x=1;
		for(var i=0;i<splitOptLength;i++){
			if(typeof splitOpt[i+1] != "undefined"){
				document.getElementById('fromMonthYear').options[x] = new Option(splitOpt[i+1],splitOpt[i]);
				i++;x++;
			}
		}
		
	} else {
		document.getElementById('dateMonth').text = "Currently Unavailiable";
	}

	if(!readCookieVal('cruiseMain'))
		updateFormDetails('formCR','cruiseLob');
	else
		updateFormDetails('formCR','cruiseMain');
	
	var frmMonthIdx = readCookie_forFromMonthField();
	if(frmMonthIdx != null)
		getCruise_fromDay(document.getElementById('fromMonthYear')[frmMonthIdx].value);

	if(!readCookieVal('cruiseMain'))
		updateFormDetails('formCR','cruiseLob');
	else
		updateFormDetails('formCR','cruiseMain');
	
}

function readCookie_forFromMonthField() {
	var cookieVal;
	if(!readCookieVal('cruiseMain'))	
		cookieVal = readCookieVal('cruiseLob');
	else
		cookieVal = readCookieVal('cruiseMain');

	if(cookieVal != null) {
		var cookieValSplit = cookieVal.split(":");
		for(var colonCnt=0; colonCnt < cookieValSplit.length; colonCnt++) {
			var cookieEquValSplit = cookieValSplit[colonCnt].split("=");
			if (cookieEquValSplit[0] == "fromMonthYear") {
				return cookieEquValSplit[1];
			}
			
		}
	} else {
		return null;
	}
}

function dhtmlLoadScript(url)
{
	var e = document.createElement("script");
	e.src = url;
	e.type="text/javascript";
	document.getElementsByTagName("head")[0].appendChild(e);
}

var monthList = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var monthDays = {'Jan':'31','Feb':'28','Mar':'31','Apr':'30','May':'31','Jun':'30','Jul':'31','Aug':'31','Sep':'30','Oct':'31','Nov':'30','Dec':'31'};

function getCruise_fromDay(yrMonVal){
	yrMonValArr = yrMonVal.split("-");
	yrVal    = yrMonValArr[0];
	monVal   = yrMonValArr[1];

	if(monVal=="02")
	{
		var yrValCal=parseInt(yrVal,10)-1900;
		if(yrValCal%400==0 || (yrValCal%4==0 && yrValCal%100!=0))
			monthDays = {'Jan':'31','Feb':'29','Mar':'31','Apr':'30','May':'31','Jun':'30','Jul':'31','Aug':'31','Sep':'30','Oct':'31','Nov':'30','Dec':'31'};
		else
			monthDays = {'Jan':'31','Feb':'28','Mar':'31','Apr':'30','May':'31','Jun':'30','Jul':'31','Aug':'31','Sep':'30','Oct':'31','Nov':'30','Dec':'31'};
	}
	else
	{
		monthDays = {'Jan':'31','Feb':'28','Mar':'31','Apr':'30','May':'31','Jun':'30','Jul':'31','Aug':'31','Sep':'30','Oct':'31','Nov':'30','Dec':'31'};
	}
	var noOfDays = monthDays[monthList[parseInt(monVal,10)-1]];

	var startDay = 1;
	var serverDt = new Date(serverDate);

	var tdMonIdx = '' + serverDt.getFullYear() + '-' + ((serverDt.getMonth()+1 < 10)?'0':'') + (serverDt.getMonth()+1);
	var tdDtIdx  =  serverDt.getDate();

	if(yrMonVal == tdMonIdx) {
		startDay += parseInt(tdDtIdx,10);
	} 
	
	var daysSelectObj = document.getElementById("fromDay");
	var selectedVal   = daysSelectObj.value;

	while(daysSelectObj.firstChild)
	{
		daysSelectObj.removeChild(daysSelectObj.firstChild);
	}
	var optionElement = document.createElement('option');
	optionElement.setAttribute('value','');
	optionElement.setAttribute('selected','selected');
	optionElement.appendChild(document.createTextNode('Any Day'));
	daysSelectObj.appendChild(optionElement);

	for(i=startDay; i<=noOfDays; i++) {
		var optionElement = document.createElement('option');
		optionElement.setAttribute('value','-'+i);
		optionElement.appendChild(document.createTextNode(i));
		daysSelectObj.appendChild(optionElement);		
	}	

	if(yrMonVal != "") {
		if( ((parseInt(selectedVal,10)*-1) > noOfDays) || ((yrMonVal == tdMonIdx) && ((parseInt(selectedVal,10)*-1) < tdDtIdx)) ) {
			daysSelectObj.value = "";
		} else {
			daysSelectObj.value = selectedVal;
		}
	}
}

function flightValidate(frm,vac){
	
	if(!vac)
		vac ='';

	var fromObj = frm.elements['leavingFrom'];
	var toObj = frm.elements['goingTo'];

	fromObj.value = trimValue(fromObj.value);
	toObj.value = trimValue(toObj.value);

	var flagTxt = true;

	if(fromObj.value.length < 3 ){
		showInvalid(fromObj,vac);
		errors = errors.concat('Please enter a departure city or airport code of 3 to 40 characters.');
		flagTxt = false;
	}
	else{
		showValid(fromObj,vac);
	}
	if(toObj.value.length < 3){
		showInvalid(toObj,vac);
		errors = errors.concat('Please enter an arrival city or airport code of 3 to 40 characters.');
		flagTxt = false;
	}
	else{
		showValid(toObj,vac);
	}
	if(flagTxt){
		if((fromObj.value.toLowerCase() == toObj.value.toLowerCase()) && toObj.value != ''){
			showInvalid(fromObj,vac);
			showInvalid(toObj,vac);
			errors = errors.concat('Starting airport and destination airport cannot be the same.');
		}
		else{
			showValid(fromObj,vac);
			showValid(toObj,vac);
		}
	}


	var ldate = validDate(frm.elements['leavingDate'],'depart');
	var rdate = validDate(frm.elements['returningDate'],'return');
	if((ldate != true) && (rdate != true))
	{
		showInvalid(frm.elements['leavingDate'],vac);
		showInvalid(frm.elements['returningDate'],vac);
	}
	else if((ldate != true) && (rdate == true)){
		showInvalid(frm.elements['leavingDate'],vac);
		showValid(frm.elements['returningDate'],vac);
	}
	else if((ldate == true) && (rdate != true)){
		showValid(frm.elements['leavingDate'],vac);
		showInvalid(frm.elements['returningDate'],vac);
	}
	else 
	{
		if(convertDate(frm.elements['leavingDate'].value,'us','js') > convertDate(frm.elements['returningDate'].value,'us','js')){ 
			errors = errors.concat('Return date cannot be earlier than departure date.');
			showInvalid(frm.elements['leavingDate'],vac);
			showInvalid(frm.elements['returningDate'],vac);
		}
		else if(frm.elements['leavingDate'].value == frm.elements['returningDate'].value){
            var startTime = getTimeValue(trimValue(frm.elements['dateLeavingTime'].value), true);
            var endTime = getTimeValue(trimValue(frm.elements['dateReturningTime'].value), false);
            if(startTime >= endTime)
            {
                errors = errors.concat('Return time cannot be earlier than or same as departure time.');
                showInvalid(frm.elements['leavingDate'],vac);
                showInvalid(frm.elements['returningDate'],vac);
            }
            else
            {
                showValid(frm.elements['leavingDate'],vac);
                showValid(frm.elements['returningDate'],vac);
            }
        }
		/*else if((trimValue(frm.elements['leavingDate'].value) == trimValue(frm.elements['returningDate'].value)) && (trimValue(frm.elements['dateLeavingTime'].value) == trimValue(frm.elements['dateReturningTime'].value))){
			errors = errors.concat('Return date&time must be different from the departure date&time.');
			showInvalid(frm.elements['leavingDate'],vac);
			showInvalid(frm.elements['returningDate'],vac);
		}*/	
		else
		{
			showValid(frm.elements['leavingDate'],vac);
			showValid(frm.elements['returningDate'],vac);
		}
	}
	
		
	

	if(vac == ''){
		if(frm.elements['adults'].value == 0 && frm.elements['seniors'].value == 0){
			showInvalid(frm.elements['adults']);
			showInvalid(frm.elements['seniors']);
			errors = errors.concat('Please select at least 1 traveler.');
		}
		else if(((1*frm.elements['adults'].value) + (1*frm.elements['seniors'].value) + (1*frm.elements['children'].value)) > 6){
			showInvalid(frm.elements['adults']);
			showInvalid(frm.elements['seniors']);
			showInvalid(frm.elements['children']);
			errors = errors.concat('There is a maximum of 6 travelers per reservation.');
		}
		else{
			showValid(frm.elements['adults']);
			showValid(frm.elements['seniors']);
			showValid(frm.elements['children']);
		}
	}
	else{
		if(frm.elements['adult1'].value == 0 && frm.elements['senior1'].value == 0){
			showInvalid(frm.elements['adult1'],vac);
			showInvalid(frm.elements['senior1'],vac);
			errors = errors.concat('Please select at least 1 traveler.');
		}
		else if(((1*frm.elements['adult1'].value) + (frm.elements['senior1'].value*1) + (frm.elements['child1'].value*1)) > 6){
			showInvalid(frm.elements['adult1'],vac);
			showInvalid(frm.elements['senior1'],vac);
			showInvalid(frm.elements['child1'],vac);
			errors = errors.concat('There is a maximum of 6 travelers per reservation.');
		}
		else{
			showValid(frm.elements['adult1'],vac);
			showValid(frm.elements['senior1'],vac);
			showValid(frm.elements['child1'],vac);
		}
	}
	if(errors != ''){
		errorMsg();
        errors = new Array();
		return false;
	}
	else{
		if(vac == ''){
			updateCookieVal(frm,'flightMain');
			popAd(frm,'flight');
                        openPopupWindow('flight', frm, false);
		}
		else{
			updateCookieVal(frm,'vacationMain');
                        openPopupWindow('vacation', frm, false);
		}
		smartBoxSelInput(frm, "leavingFrom", "submit");    
		smartBoxSelInput(frm, "goingTo", "submit");     
		frm.submit();
	}
}

function showInvalid(obj,lbl){
	if(!lbl || lbl == ''){
		lbl = obj.name+'lbl';}
	else if(lbl == '1'){
		lbl = 'va'+obj.name+'lbl';}

	obj.className = obj.className+" invalid";
	document.getElementById(lbl).className = document.getElementById(lbl).className+" invalidLbl";
}

function showValid(obj,lbl){
	if(!lbl || lbl == '')
		lbl = obj.name+'lbl';
	else if(lbl == '1')
		lbl = 'va'+obj.name+'lbl';

	
	var str = obj.className;
	var lblStr = document.getElementById(lbl).className;
	obj.className = str.replace(/ invalid/g,'');
	document.getElementById(lbl).className = "label";
}

function popAd(frm,type){
	if(!readCookieVal('popAd')){
		var browserName = Browser();
		if(navigator.userAgent.toLowerCase().indexOf("aol") == -1){
			var widthWin = (browserName == 'Mozilla') ? 725 : 720;
			var heightWin = (browserName == 'Mozilla') ? 305: 300;

			adWindow = open('','viewAd','width='+widthWin+',height='+heightWin+',resizable=no,scrollbars=no');


			var popHtml = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
			popHtml += '<html><head><style>body{overflow:hidden;} #adText img{position:absolute; left=0px; top=0px; border:0px;}</style>';
			popHtml += '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>Travel Deals</title></head>';
			popHtml += '<body bgcolor="#FFFFFF" marginheight="0" marginwidth="0" topmargin="0" rightmargin="0" leftmargin="0" bottommargin="0"><div id="adText" align="center">';
			if(type == 'flight'){
				popHtml +='<iframe src="http://dm.travelocity.com/html.ng/site=aol&amp;cobrand=AOLSVC&amp;area=air&amp;section=pop&amp;adsize=720x300&amp;orig='+(frm.leavingFrom.value.replace(/ /g,'_')).toUpperCase()+'&amp;dest='+(frm.goingTo.value.replace(/ /g,'_')).toUpperCase()+'&amp;startDay='+(frm.leavingDate.value).split('/')[1]+'&amp;startMonth='+(frm.leavingDate.value).split('/')[0]+'&amp;startYear='+(frm.leavingDate.value).split('/')[2]+'&amp;endDay='+(frm.returningDate.value).split('/')[1]+'&amp;endMonth='+(frm.returningDate.value).split('/')[0]+'&amp;endYear='+(frm.returningDate.value).split('/')[2]+'&amp;noOfAdults='+frm.adults.value+'&amp;random='+Math.random()+'?" noresize scrolling=no hspace=0 vspace=0 frameborder=0 marginheight=0 marginwidth=0 width=720 height=300></iframe>';
			}
			else if(type == 'hotel')
				popHtml +='<iframe src="http://dm.travelocity.com/html.ng/site=aol&amp;cobrand=AOLSVC&amp;area=hotel&amp;section=pop&amp;adsize=720x300&amp;dest='+(frm.city.value.replace(/ /g,'_')).toUpperCase()+'&amp;startDay='+(frm.leavingDate.value).split('/')[1]+'&amp;startMonth='+(frm.leavingDate.value).split('/')[0]+'&amp;startYear='+(frm.leavingDate.value).split('/')[2]+'&amp;endDay='+(frm.returningDate.value).split('/')[1]+'&amp;endMonth='+(frm.returningDate.value).split('/')[0]+'&amp;endYear='+(frm.returningDate.value).split('/')[2]+'&amp;noOfAdults='+frm.adult1.value+'&amp;noOfRooms=1&amp;random='+Math.random()+'?" noresize scrolling=no hspace=0 vspace=0 frameborder=0 marginheight=0 marginwidth=0 width=720 height=300></iframe>';
			else if(type == 'car')
				popHtml +='<iframe src="http://dm.travelocity.com/html.ng/site=aol&amp;cobrand=AOLSVC&amp;area=car&amp;section=pop&amp;adsize=720x300&amp;dest='+(frm.pickupCity.value.replace(/ /g,'_')).toUpperCase()+'&amp;startDay='+(frm.pickupDate.value).split('/')[1]+'&amp;startMonth='+(frm.pickupDate.value).split('/')[0]+'&amp;startYear='+(frm.pickupDate.value).split('/')[2]+'&amp;startTime='+frm.pickupTime.value+'&amp;endDay='+(frm.dropoffDate.value).split('/')[1]+'&amp;endMonth='+(frm.dropoffDate.value).split('/')[0]+'&amp;endYear='+(frm.dropoffDate.value).split('/')[2]+'&amp;endTime='+frm.dropoffTime.value+'&amp;random='+Math.random()+'?" noresize scrolling=no hspace=0 vspace=0 frameborder=0 marginheight=0 marginwidth=0 width=720 height=300></iframe>';
			popHtml += '</div></body></html>';
			adWindow.document.write(popHtml);
			adWindow.blur();
			adWindow.screenX = 150;
			adWindow.screenY = 200;
			window.focus();

		} else if(navigator.userAgent.toLowerCase().indexOf("aol 9") != -1 && navigator.userAgent.toLowerCase().indexOf("AOL 9.5") == -1 && _sns_isLoggedIn == 1 && switchOffRateFinderInClient != "true") {
			window.open('aol://1391:48-35664','', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=725,height=305');
		}
		var date = new Date();
		date.setTime(date.getTime()+(24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		document.cookie =  "popAd=1"+expires+"path=/";
	}
}

/* Validate Function for hotel booking module starts (travelocity & kayak) */

/* Validation for Travelocity Form starts */
function trvHotelValidate(frm){
	
	var cityVal = trimValue(frm.elements['city'].value);
	
	if(cityVal == "") {
		errors = errors.concat('Please enter a city.');
		cssSwitch("trvCity&inputInvalid", "trvCityLbl&inputInvalidLbl");
		
	} else if ((cityVal != '') && ((cityVal.length < 3) || (cityVal.length > 40))) {
		errors = errors.concat('Please enter a city or airport code of 3 to 40 characters.');
		cssSwitch("trvCity&inputInvalid", "trvCityLbl&inputInvalidLbl");
		
	} else {
		cssSwitch("trvCity&textField", "trvCityLbl&labels");
	}
	
	var trvCheckInFlag  = false;
	var trvCheckOutFlag = false;
	
	if(frm.elements['leavingDate'].value != "") {
		if (!validDate(frm.elements['leavingDate'],'cin')) {
			trvCheckInFlag = true;
			cssSwitch("trvHotelIn&inputInvalid", "hotelInLbl&inputInvalidLbl");
		} else {
			cssSwitch("trvHotelIn&textField date", "hotelInLbl&labels");
		}
 	}

	if(frm.elements['returningDate'].value != "") { 	
		if (!validDate(frm.elements['returningDate'],'cout')) {
			trvCheckOutFlag = true;
			cssSwitch("trvHotelOut&inputInvalid", "hotelOutLbl&inputInvalidLbl");
		} else {
			cssSwitch("trvHotelOut&textField date", "hotelOutLbl&labels");
		}
	}	

	var trvCheckInDt  = frm.elements['leavingDate'].value;	
	var trvCheckOutDt = frm.elements['returningDate'].value;

	if(trvCheckInDt != "" && trvCheckOutDt == "" ) {
		errors = errors.concat('Please enter a check out date.');
		cssSwitch("trvHotelOut&inputInvalid", "hotelOutLbl&inputInvalidLbl");
	
	} else if(trvCheckInDt == "" && trvCheckOutDt != "" ) {
		errors = errors.concat('Please enter a check in date.');
		cssSwitch("trvHotelIn&inputInvalid", "hotelInLbl&inputInvalidLbl");

	} else if(trvCheckInDt != "" && trvCheckOutDt != "") {
		if(convertDate(trvCheckInDt,'us','js') > convertDate(trvCheckOutDt,'us','js')){ 
			errors = errors.concat('Check-out date can not be earlier than check-in date.');
			cssSwitch("trvHotelOut&inputInvalid", "hotelOutLbl&inputInvalidLbl", "trvHotelIn&inputInvalid", "hotelInLbl&inputInvalidLbl");
			
		} else if(trvCheckInDt == trvCheckOutDt) {
	        errors = errors.concat('Check-out date must be different from the Check-in date');
			cssSwitch("trvHotelOut&inputInvalid", "hotelOutLbl&inputInvalidLbl", "trvHotelIn&inputInvalid", "hotelInLbl&inputInvalidLbl");
			
		} else {
			if(trvCheckInFlag && !trvCheckOutFlag) {
				cssSwitch("trvHotelIn&inputInvalid", "hotelInLbl&inputInvalidLbl");
				
			} else if(!trvCheckInFlag && trvCheckOutFlag) {
				cssSwitch("trvHotelOut&inputInvalid", "hotelOutLbl&inputInvalidLbl");
				
			} else if(!trvCheckInFlag && !trvCheckOutFlag){
				cssSwitch("trvHotelIn&textField date", "hotelInLbl&labels", "trvHotelOut&textField date", "hotelOutLbl&labels");
				
			} else if(trvCheckInFlag && trvCheckOutFlag){
				cssSwitch("trvHotelOut&inputInvalid", "hotelOutLbl&inputInvalidLbl", "trvHotelIn&inputInvalid", "hotelInLbl&inputInvalidLbl");
			}
		}
	} else if(trvCheckInDt == "" && trvCheckOutDt == "") {
		errors = errors.concat('Please enter a check in date.');
		errors = errors.concat('Please enter a check out date.');
		cssSwitch("trvHotelOut&inputInvalid", "hotelOutLbl&inputInvalidLbl", "trvHotelIn&inputInvalid", "hotelInLbl&inputInvalidLbl");
		
	}

    var ret = showError();
    if (ret == true){
        openPopupWindow('hotel', frm, false);
    }
	return (ret);
}
/* Validation for Travelocity Form ends */

/* Validates, Sets Cookies and then Submits the form starts */

function validate_setCookie_submit(cookieName, validateFnName ,formObj) {
	var validatedForm = false;

	if(validateFnName == 'trvHotelValidate') {
		validatedForm = trvHotelValidate(formObj);		
	} 
	
	if(validatedForm) {
		if(document.getElementById("rooms")){
			changeGuestValue(document.getElementById("rooms").value);
		}
		updateCookieVal(formObj, cookieName);
		popAd(formObj,'hotel');
		formObj.submit();
	}	
	return validatedForm;
}
/* Validates, Sets Cookies and then Submits the form Ends */


function hotelMainBmOnLoad(){
//Need to modify once Hotel LOB is completed.
	updateFormDetails ("mainFrmTrv", "trvHotelBmCookie");
	updateFormDetails ("kykHotelFrm", "kykHotelBmCookie");

	updateFormDetails("mainFrmTrv","trvHotelMain");
	updateFormDetails("kykHotelFrm","kykHotelMain");

}
/* Validate Function for hotel booking module ends (travelocity & kayak) */


function carValidate(frm){
	frm.elements['pickupCity'].value = trimValue(frm.elements['pickupCity'].value);	
	if(frm.elements['pickupCity'].value.length < 3){
		showInvalid(frm.elements['pickupCity']);
		errors = errors.concat('Please let us know where you want to pick-up your car.');
	}
	else{
		showValid(frm.elements['pickupCity']);
	}
	if(frm.elements['dropoffCity'].value.length < 3 && frm.elements['dropoffCity'].value.length != 0){
		showInvalid(frm.elements['dropoffCity']);
		errors = errors.concat('Please enter dropoff city or airport code of 3 to 40 characters.');
	}
	else{
		showValid(frm.elements['dropoffCity']);
	}

	var ispickup = validDate(frm.elements['pickupDate'],'pickup');
	var isdropoff = validDate(frm.elements['dropoffDate'],'dropoff');
	var chkIn = frm.elements['pickupDate'].value;	
	var chkOut = frm.elements['dropoffDate'].value;

	if((ispickup != true) && (isdropoff != true))
	{
		showInvalid(frm.elements['pickupDate'],'CAdepartlbl');
		showInvalid(frm.elements['dropoffDate'],'CAreturnlbl');
	}
	else if((ispickup != true) && (isdropoff == true)){
		showInvalid(frm.elements['pickupDate'],'CAdepartlbl');
		showValid(frm.elements['dropoffDate'],'CAreturnlbl');
	}
	else if((ispickup == true) && (isdropoff != true)){
		showInvalid(frm.elements['dropoffDate'],'CAreturnlbl');
		showValid(frm.elements['pickupDate'],'CAdepartlbl');
	}
	else
	{
		if(convertDate(chkIn,'us','js') > convertDate(chkOut,'us','js')){ 
			errors = errors.concat('Drop-off date can not be earlier than Pick-up date.');
			showInvalid(frm.elements['pickupDate'],'CAdepartlbl');
			showInvalid(frm.elements['dropoffDate'],'CAreturnlbl');
		}else if(chkIn == chkOut && frm.elements['pickupTime'].value*1 >= frm.elements['dropoffTime'].value*1){
			errors = errors.concat('Drop-off time must be later than pick-up time on the same date.');
			showInvalid(frm.elements['pickupDate'],'CAdepartlbl');
			showInvalid(frm.elements['dropoffDate'],'CAreturnlbl');
		}
		else{
			showValid(frm.elements['pickupDate'],'CAdepartlbl');
			showValid(frm.elements['dropoffDate'],'CAreturnlbl');
		}
	}
	if(errors != ''){
		errorMsg();
        errors = new Array();
		return false;
	}
	else{
		var pd = frm.elements['pickupDate'].value;
		var dd = frm.elements['dropoffDate'].value;
		frm.elements['pickupMonth'].value = pd.split("/")[0];
		frm.elements['pickupDayOfMonth'].value = pd.split("/")[1];
		frm.elements['dropoffMonth'].value = dd.split("/")[0];
		frm.elements['dropoffDayOfMonth'].value = dd.split("/")[1];
		updateCookieVal(frm,'carMain');
		if(frm.elements['dropoffCity'].value == 'Same as pick-up')
			frm.elements['dropoffCity'].value = frm.elements['pickupCity'].value;

                openPopupWindow('car', frm, false);
                smartBoxSelInput(frm, "pickupCity", "submit"); 
        		smartBoxSelInput(frm, "dropoffCity", "submit");
		frm.submit();
	}
}



function cruiseValidate(frm){
        openPopupWindow('cruise', frm, false);
	updateCookieVal(frm,'cruiseMain');
	frm.submit();
}

function childAges(I,q,R){o_div=document.getElementById(q);if(I.selectedIndex!=0){if(I.selectedIndex>1){cssDisplay("minorsText!1","minorText!0");}else{cssDisplay("minorsText!0","minorText!1");}a_children=o_div.getElementsByTagName("span");o_div.style.display="block";for(i=0;i<a_children.length;i++){a_children[i].style.visibility="hidden";}for(i=0;i<a_children.length;i++){a_children[i].style.visibility=(i<I.selectedIndex)?"visible":"hidden";}}else{o_div.style.display="none";}}



function changeCountry(val){
	if(val != 'us')
		document.getElementById('state').disabled = true;
	else
		document.getElementById('state').disabled = false;
}

function setFlightType(obj,val,frmName,cookieName,loc){
	document.getElementById(obj).value = val;
	updateCookieVal(document.getElementById(frmName),cookieName);
	window.location = loc;
}


function setFlightTypeChk(obj,val,frmName,cookieName,loc){
	document.getElementById(obj).checked = val;
	updateCookieVal(document.getElementById(frmName),cookieName);
	window.location = loc;
}


function cssDisplay()
{
  var s_navigator = navigator.userAgent.toLowerCase();
  var isIE = (s_navigator.indexOf("msie")>-1&&s_navigator.indexOf("opera")==-1);
  var fnArguments = cssDisplay.arguments;
  for(var i=0;i < fnArguments.length;i++)
  {
    param = fnArguments[i].split("!");
    elemId = param[0];
    displayVal = param[1];
    elemRef = document.getElementById(elemId)
	  if(elemRef != null)
      elemRef.style.display = (displayVal==0) ? "none" : (displayVal==1) ? "block" : (displayVal==2) ? "inline" : (displayVal==3) ? (isIE) ? "block" : "table-row" : (displayVal==4) ? (isIE) ? "block" : "table-cell" : "block";
  }
}

function closePricePop(){
    cssDisplay('pricePopup!0');
}


function showPassengers(event,city,airport,price,left){
    var div = _showPassengers(document.mybpFrom,city,airport,price,left);
    if(!event) event = window.event;
    if(event.target) var t = event.target;
    else var t = event.srcElement;
    justClickedPrice = true;
    if(document.getElementById('frBtn')){setTimeout('try {document.getElementById(\'frBtn\').focus();}catch(err){}',20);}
}

function _showPassengers(dep_airport,dest_city,dest_airport,price,left){
    homeCity = (homeCity == null) ? document.getElementById('leavingFromMB').value : homeCity;
    dep_airport = homeCity;
    if(!left) {left=375;}
    cssDisplay('pricePopup!1');
    var openBlank = "";
    var mbpPopUp = location.search.indexOf('_mbp');
    if(mbpPopUp != -1) {openBlank = "target='_blank'";}
    var div = document.getElementById('pricePopup');
    div.innerHTML = '<form ' + openBlank  + ' action="http://aolsvc.res.travelocity.aol.com/flights/InitialSearch.do" method="post" id="mybpForm" onsubmit="return validateBpFlight(this);"><input type="hidden" name="Service" value="AOLSVC"><input type="hidden" name="flightType" value="roundtrip"><input type="hidden" name="entryPoint" value="CB"><input type="hidden" name="tripType" value="aironly"><input type="hidden" name="dateTypeSelect" id="mybptype" value="flexibleDates"><input type="hidden" name="goingTo" value="'+dest_airport+'"><input type="hidden" name="leavingFrom" value="'+dep_airport+'"><div class="header"><span id="pp-city">' + dest_city + '</span><span id="pp-price">' + price + '</span><span class="right"><a href="#" onclick="closePricePop();return false;">&gt; Return to Price List</a></span></div><div class="content"><p><strong>Who</strong> will be traveling?</p><div class="fieldset"><div class="f"><div class="label"><label for="MB-adults" id="MB-adultsLabel">Adults (18-64)</label></div></div><select id="MB-adults" name="adults"><option value="0">0</option><option value="1" selected>1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option></select></div><div class="fieldset"><div class="f"><div class="label"><label for="MB-seniors" id="MB-seniorsLabel">Seniors (65+)</label></div></div><select id="MB-seniors" name="seniors"><option value="0" selected>0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option></select></div><div class="fieldset"><div class="f"><div class="label"><label for="MB-minors" id="MB-minorsLabel">Minors (2-17)</label></div></div><select id="MB-minors" name="children" onchange="childAges(this,\'MB-paxChildAges\', this.parentNode)\;"><option value="0" selected>0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></select></div><div class="minors" id="MB-min"><div id="MB-minorPref"><div class="selectedBGPad" id="MB-paxChildAges" ><label id="MB-minorAgeLabel">Specify the ages of children at time of travel</label><div class="ages"><span style="visibility: visible;"><label for="MB-minorsAge0" ID="minorsAge0Label">Child 1</label><br/><select class="" name="minorsAge0" ID="MB-minorsAge0"><option value="0">?</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option></select></span></div><div class="ages"><span style="visibility: visible;"><label for="MB-minorsAge1" ID="minorsAge1Label">Child 2</label><br/> <select class="" name="minorsAge1" ID="MB-minorsAge1"><option value="0">?</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option></select></span></div><div class="ages"><span style="visibility: visible;"><label for="MB-minorsAge2" ID="minorsAge2Label">Child 3</label><br/> <select class="" name="minorsAge2" ID="MB-minorsAge2"><option value="0">?</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option></select></span></div><div class="ages"><span style="visibility: visible;"><label for="MB-minorsAge3" ID="minorsAge3Label">Child 4</label><br/> <select class="" name="minorsAge3" ID="MB-minorsAge3"><option value="0">?</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option></select></span></div><div class="ages"><span style="visibility: visible;"><label for="MB-minorsAge4" ID="minorsAge4Label">Child 5</label><br/> <select class="" name="minorsAge4" ID="MB-minorsAge4"><option value="0">?</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option></select></span></div></div></div></div></div><div class="btnbar"><button type="submit" id="searchBtnMB" class="searchBtn">Search Flights</button></div></form>';
    return div;
}


/*copy value from smarty fld to l1 input field*/
function copyFromValueFlight(value){
	document.AOLFlightSearchForm.l1.value = value;
}

/*copy value from smarty fld to l2 input field */
function copyToValueFlight(value){
	document.AOLFlightSearchForm.l2.value = value;
}

/*
 * uncheck flight + hotel radio button 
 */
	function uncheckFLHO(){
		document.AOLFlightSearchForm.flhoKayak.checked = false;
	}
	
/* deals search module*/
function removeGhostTxt(txtFldObjId, txtFldObjValue){
	if($j.trim(txtFldObjValue) != "" && txtFldObjValue == "e.g. Paris, France or New York, NY"){
		$j("#"+txtFldObjId).val('');
	}
}
function showGhostTxt(txtFldObjId, txtFldObjValue){
	if($j.trim(txtFldObjValue) == ""){
		$j("#"+txtFldObjId).val("e.g. Paris, France or New York, NY");
	}
}

$j(document).ready(function(){
	initTravelMainTopDest()
	
	/*$j('.ad300x250, #ad300x250').each(function(i){
		if($j(this).find('iframe').size() == 0)
			$j(this).css('display','none');
	});*/

	$j("#VacationSearchForm").submit(function(){		
		var isItValid = flightValidate(this,'1');
		if(isItValid != false){
			popUnder('inc/shermansDealsPopunder.jsp?dealsCat=vacation&city='+escape($j('#vagoingTo').attr('value')));
		}
		else{
			return false;
		}
	});
	$j("#formCATrv").submit(function(){
		var isItValid = carValidate(this);
		if(isItValid != false){
			popUnder('inc/shermansDealsPopunder.jsp?dealsCat=car&city='+escape($j('#dropoffCity').attr('value')));
		}
		else{
			return false;
		}
	});
	$j("#formCR").submit(function(){
		var isItValid = cruiseValidate(this);
		if(isItValid != false){
			popUnder('inc/shermansDealsPopunder.jsp?dealsCat=cruise');
		}
		else{
			return false;
		}
	});

	$j("#srchBox").attr({autocomplete:"off"});
	$j("#srchBox").val(readCookieVal("searchTerm"));
	var fromAirport = document.getElementById("leavingFromFL").value.replace(/ /g,'_').toUpperCase();
 	var toAirport = document.getElementById("goingToFL").value.replace(/ /g,'_').toUpperCase();
 	var startDay = document.getElementById("leavingDate").value.split('/')[1];
 	var startMonth = document.getElementById("leavingDate").value.split('/')[0];
 	var startYear = document.getElementById("leavingDate").value.split('/')[2];
 	var endDay = document.getElementById("returningDate").value.split('/')[1];
 	var endMonth = document.getElementById("returningDate").value.split('/')[0];
 	var endYear = document.getElementById("returningDate").value.split('/')[2];	
 	var noOfAdults = document.getElementById("adults").value;
 	
	$j("#AirSearchForm").submit(function(){
		flightValidate(this);
		//setPUCookie(this);
		setCookie('rateFinderPopUnder', 'http://dm.travelocity.com/html.ng/site=aol&amp;cobrand=AOLSVC&amp;area=air&amp;section=pop&amp;adsize=720x300&amp;orig='+fromAirport+'&amp;dest='+toAirport+'&amp;startDay='+startDay+'&amp;startMonth='+startMonth+'&amp;startYear='+startYear+'&amp;endDay='+endDay+'&amp;endMonth='+endMonth+'&amp;endYear='+endYear+'&amp;noOfAdults='+noOfAdults+'&amp;random='+Math.random()+'?', 7);
		return false;
	});
	
 	function setCookie(cookieName,cookieValue,nDays) {
		 var today = new Date();
		 var expire = new Date();
		 if (nDays==null || nDays==0) nDays=1;
		 expire.setTime(today.getTime() + 3600000*24*nDays);
		 document.cookie = cookieName+"="+escape(cookieValue)+ ";expires="+expire.toGMTString();
	}

	var fromCity = document.getElementById("trvCity").value.replace(/ /g,'_').toUpperCase();
 	var startDayHotel = document.getElementById("trvHotelIn").value.split('/')[1];
 	var startMonthHotel = document.getElementById("trvHotelIn").value.split('/')[0];
 	var startYearHotel = document.getElementById("trvHotelIn").value.split('/')[2];
 	
 	var endDayHotel = document.getElementById("trvHotelOut").value.split('/')[1];
 	var endMonthHotel = document.getElementById("trvHotelOut").value.split('/')[0];
 	var endYearHotel = document.getElementById("trvHotelOut").value.split('/')[2];	
 	var noOfAdultsHotel = document.getElementById("adult1").value; 
	function setCookie(cookieName,cookieValue,nDays) {
		var today = new Date();
		var expire = new Date();
		if (nDays==null || nDays==0) nDays=1;
		expire.setTime(today.getTime() + 3600000*24*nDays);
		document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
	}
	$j("#mainFrmTrv").submit(function(){
		validate_setCookie_submit('trvHotelMain', 'trvHotelValidate', this);
		setCookie('rateFinderPopUnder', 'http://dm.travelocity.com/html.ng/site=aol&amp;cobrand=AOLSVC&amp;area=hotel&amp;section=pop&amp;adsize=720x300&amp;dest='+fromCity+'&amp;startDay='+startDayHotel+'&amp;startMonth='+startMonthHotel+'&amp;startYear='+startYearHotel+'&amp;endDay='+endDayHotel+'&amp;endMonth='+endMonthHotel+'&amp;endYear='+endYearHotel+'&amp;noOfAdults='+noOfAdultsHotel+'&amp;noOfRooms=1&random='+Math.random()+'?' , 7);
		return false;
	});

	miniCalendar = new MiniCalendar();
	m_Calendar = new miniCalendar.Calendar();
	var calLists={'leavingDate':['mdy'],'returningDate':['mdy'],'aolTravel_d1':['mdy'],'aolTravel_d2':['mdy'],'trvHotelIn':['mdy'],'trvHotelOut':['mdy'],'CAdepart':['mdy'],'CAreturn':['mdy'],'CAdepartKyk':['mdy'],'CAreturnKyk':['mdy'],'valeavingDate':['mdy'],'vareturningDate':['mdy']};
	miniCalendar.initCalendars(calLists);		

	formToShow(showForm);
	initTab();
	hotelMainBmOnLoad();
	search_form();
});

//=== TravelMainTopDest stuff ==
var mostPopImages = [];
var editPickImages = [];
var topDestImages = [];
var cmsOverImages = [];

function initTravelMainTopDest() {
	$j("#dest_interest").focus(function(){
		removeGhostTxt(this.id, this.value);
	}).blur(function(){
		showGhostTxt(this.id, this.value);
	});
	
	$j('#mainDealsResults .dealList:last, #toolsModule li:last').addClass('last');
	
	paginationCount(firstCount, lastCount, mostPopLen);
	//var exploreGuidesByDiv = $j('#exploreGuidesBy')
	$j('#prevBtn').bind('click', function() {
		changeGuide('left');
	});
	$j('#nextBtn').bind('click', function() {
		changeGuide('right');
	});
	//exploreGuidesByDiv.bind('change', function() {showSelect()});
}

var firstCount = 1;
var lastCount = 2;
var count = 2;

function changeGuide(direction)
{
	var divName = '#mostPop';
	var slideLength = 0;
	var arr = mostPopImages;
	
	//if(selName =='Most_Popular'){
		slideLength = mostPopLen;
		divName = '#mostPop';
		arr = mostPopImages;
	//} else if(selName =='From_Our_Editors_Pick'){
	//	slideLength = editPickLen;
	//	divName = '#editPick';
	//	arr = editPickImages;
	//} else if (selName == 'Top_Destinations') {
	//	slideLength = topDestLen;
	//	divName = '#topDest';
	//	arr = topDestImages;
	//} else if(selName =='Cms_Overrides'){
	//	slideLength = cmsOverLen;
	//	divName = '#cmsOver';
	//	arr = cmsOverImages;
	//} 
	if (slideLength == 2) return;
	
	var objID3 = divName + firstCount;
	var objID4 = divName + lastCount;
	if(direction == "right"){
		if((firstCount == slideLength-1) && (lastCount == slideLength)){
			firstCount = 1;
			lastCount = 2;
		}
		else{
			firstCount = firstCount + count;
			lastCount = lastCount + count;
		}
	}
	if(direction == "left"){
		if(firstCount == 1 && lastCount == 2){
			firstCount = slideLength-1;
			lastCount = slideLength;
		}
		else{
			firstCount = firstCount - count;
			lastCount = lastCount - count;
		}
	}
	var objID1 = divName + firstCount;
	var objID2 = divName + lastCount;
	$j(objID1).addClass('show').removeClass('hide');
	$j(objID2).addClass('show').removeClass('hide');
	$j(objID3).addClass('hide').removeClass('show');
	$j(objID4).addClass('hide').removeClass('show');
	$j(objID1+'> a > img').attr('src', arr[firstCount])
	$j(objID2+'> a > img').attr('src', arr[lastCount])
	paginationCount(firstCount, lastCount, slideLength);
	if(typeof custumComscore != 'undefined'){
		s_265.mmxcustom=custumComscore;
    	}
	comscore();
	omni();
}

function showSelect() {
	firstCount = 1;
	lastCount = 2;
	count = 2;
	var selVal = $j('#exploreGuidesBy').val();
	var slideLength = 0;
	
	if(selVal=='Most_Popular'){
		slideLength = mostPopLen;
		showHideSlide('#mostPop', mostPopImages);	
		showHideBlock('#mostPopular');
	}
	else if (selVal=='From_Our_Editors_Pick'){
		slideLength = editPickLen;
		showHideSlide('#editPick', editPickImages);
		showHideBlock('#editorsPick');
	}
	else if (selVal=='Top_Destinations'){
		slideLength = topDestLen;
		showHideSlide('#topDest', topDestImages);
		showHideBlock('#topDestinations');
	}
	else if (selVal=='Cms_Overrides'){
		slideLength = cmsOverLen;
		showHideSlide('#cmsOver', cmsOverImages);
		showHideBlock('#cmsOverrides');
	}
	paginationCount(firstCount, lastCount, slideLength);
	if(typeof custumComscore != 'undefined'){
		s_265.mmxcustom=custumComscore;
    	}
	comscore();
	omni();
}

function showHideBlock(idVal) {
	$j('.guideContainer').removeClass('show').addClass('hide');
	$j(idVal).removeClass('hide').addClass('show');
}

function showHideSlide(idName, arr) {
	$j('.guideCont').addClass('hide');
	$j(idName+'1 > a > img').attr('src', arr[firstCount])
	$j(idName+'2 > a > img').attr('src', arr[lastCount])

	$j(idName + "1").removeClass('hide').addClass('show');
	$j(idName + "2").removeClass('hide').addClass('show');
}
function paginationCount(first, last, total) {
	$j('#sCounter').html('<span>' + firstCount + ' - ' + lastCount + '</span> of ' + total);
}
function comscore() {
	var comURL = "/mm_track?cId=" + new Date().getTime();
	$j.ajax({url: comURL, async: true});
}
function omni() {
	var s_265=s_gi(s_account);
	s_265.eVar5='';
	s_265.prop11 = '';
	s_265.t();
}
function fireBeaconOnTopDestModuleDealClick(partnerName) {
	var s_265=s_gi(s_account);
	s_265.linkTrackVars='eVar5';
	s_265.eVar5='CPC | ' + partnerName + ' - ' + pageTitle;
	s_265.tl(this,'o','CPC | ' + partnerName + ' - ' + pageTitle);
}

function getTimeValue(strTime, isStartTime)
{
    var returntime = 0;
    if(strTime == "Anytime")
    {
        if(isStartTime)
            returntime = -0.99;
        else
            returntime = 23.01;
    }
    else if(strTime == "Morning")
    {
        if(isStartTime)
            returntime = -0.99;
        else
            returntime = 11.01;
    }
    else if(strTime == "Afternoon")
    {
        if(isStartTime)
            returntime = 11.99;
        else
            returntime = 15.01;
    }
    else if(strTime == "Evening")
    {
        if(isStartTime)
            returntime = 15.99;
        else
            returntime = 23.01;
    }
    else
    {
        var postFix = strTime.substring(strTime.length - 2);
        var indexOfColon = strTime.indexOf(':');
        var intTime = parseInt(strTime.substring(0, indexOfColon));
       
        if(postFix == "am")
        {
            if(intTime == 12)
                returntime = 0;
            else
                returntime = intTime;
        }
        else
        {
            if(intTime == 12)
                returntime = intTime;
            else
                returntime = intTime + 12;
        }
    }
    return returntime;
}
function smartBoxSelInput(frmObj, inputboxId, which){
	if(which == 'submit'){
	  var str = frmObj.elements[inputboxId].value;
	  var ary = str.match(/\(([^\(\)]*)\)/);
	  if(ary)
		ary = ary[1];
	  else
		  ary = str;
	  
	  	  
		frmObj.elements["new"+inputboxId].value = str;
		frmObj.elements[inputboxId].value = ary;
	}
}
