var pageType;
function validateSearchFormURL(sURL, sActionAddOn) {
    var checkInField = document.getElementById('checkInDate');
    var checkOutField = document.getElementById('checkOutDate');
    var cityNameField = document.getElementById('cityName');
    var searchType="CITY";
	var skipDateValidation=false;
	if (document.getElementById('skipDateValidation')) {
		skipDateValidation = document.getElementById('skipDateValidation').value;
		document.getElementById('skipDateValidation').value = "false";
	}
	var searchTypeField;
    
	if(document.searchHotelsForm[0].searchType){
		searchTypeField = document.searchHotelsForm[0].searchType;
	}else if(document.searchHotelsForm.searchType){
		searchTypeField=document.searchHotelsForm.searchType;
	}

	if(searchTypeField.type == 'select-one'){//overview page search type is drop down
		searchType=searchTypeField.value;
	}
	else{//listings page(search type is option)
		for (var iT=0; iT<searchTypeField.length; iT++)
			if (searchTypeField[iT].checked) searchType = searchTypeField[iT].value;
	}

	cleanHiddenSearchValues(searchType);
	
    var bCheckIn = false;
    var bCheckOut = false;
    var errCount = 0;
    var sError = "";

    var arrErrors = new Array();

    sError ="";

	if (searchType == "POI") {
	    if (document.getElementById('poiName') != null) {
	        if(String(trimString(document.getElementById('poiName').value)) == "") {
	            arrErrors["poiName"] = "Please enter the landmark near where you'd like to stay.";
	            errCount++;
	        }
	    }
	} else if (searchType == "ADDR") {
	    if (document.getElementById('addrLine') != null) {
	        if(String(trimString(document.getElementById('addrLine').value)) == "") {
	            arrErrors["addrLine"] = "Please enter the address of the location where you would like to stay.";
	            errCount++;
	        }
	        if(String(trimString(document.getElementById('addrCity').value)) == "") {
	            arrErrors["addrCity"] = "Please enter the city of the location where you would like to stay.";
	            errCount++;
	        }
	        if(String(trimString(document.getElementById('addrState').value)) == "") {
	            arrErrors["addrState"] = "Please enter the state of the location where you would like to stay.";
	            errCount++;
	        }
	    }
	} else {
	    if (cityNameField != null) {
	        if(String(trimString(cityNameField.value)) == "") {
	            arrErrors["cityName"] = "Please enter the city in which you'd like to stay.";
	            errCount++;
	        }
	    }
   	}
  	if(skipDateValidation!="true"){
		sError = checkDateFormat(checkOutField);
		if (sError == "VALID_DATA") {
			bCheckOut = true;
		} else {
			arrErrors["checkOutDate"] = "Please select a valid Check-out date.";
			bCheckOut = false;
			errCount++;
		}

		sError = "";
		sError = checkDateFormat(checkInField);
		if (sError == "VALID_DATA") {
			bCheckIn = true;
		} else {

			if (sError=="TOO_EARLY") {
				arrErrors["checkInDate"] = "The earliest check-in date for " + cityNameField.value + " is " + getCurrentDateString() + ".";
				arrErrors["checkOutDate"] = ""; // remove the checkout date validations
			} else {
				arrErrors["checkInDate"] = "Please select a valid Check-in date.";
			}
			errCount++;
			bCheckIn = false;
		}   

		if (bCheckIn && bCheckOut) {
			sError = "";
			sError = dateCheck(checkInField.value,checkOutField.value);
			if (sError != "VALID_DATA") {
				arrErrors["checkInDate"] = "";
				arrErrors["checkOutDate"] = "";
				if (sError == "DURATION_TOO_LONG") {
					arrErrors["dateCheck"] = "The maximum length of stay is 21 days.";
				} else if (sError== "CHECK_OUT_LESS_THAN_CHECK_IN") {
					arrErrors["dateCheck"] = "The check-in date must come before the check-out date.";
				} else if (sError== "TOO_FAR_OUT") {
					arrErrors["dateCheck"] = "Reservations can only be made 330 days in advance.";
				} else {
					arrErrors["dateCheck"] = sError;
				}
				errCount++;
			}
		}
  	}//skip validation
	if (errCount>0) {

    	if(document.searchHotelsForm.length == 2 && (pageType == null ||pageType!='DETAIL')){//listings page
    		
    		document.getElementById('expand').style.display = "block";
			var errorDisplayStr = "Please verify the following information to continue with your request.";
			for (var v in arrErrors) {
				if (String(arrErrors[v]).length > 0) {
					errorDisplayStr += "<br>" + arrErrors[v];
				}
			}
			document.getElementById("validationErrors").innerHTML = errorDisplayStr;
			document.getElementById("newSearchValidationErrors").style.display = "";
			window.location.href = "#maincontent";	//this must be below the innerHTML set due to Safari bug
		} else {
			var sErrorDisplay = "<span style=\"{font-family: arial,helvetica,sans-serif;font-weight: bold; font-size:10pt; color:#BB0000}\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Please verify the following information to continue with your request.</span>";
			sErrorDisplay += "<ul>\n";
			for (var v in arrErrors) {
				
			    if (String(arrErrors[v]).length > 0) {
			        //sErrorDisplay += "<li style=\"{background-image: url(../graphics/bullet_off.gif);font-family: Geneva, Helvetica, sans-serif;font-weight:normal; font-size:10pt; color:red}\">" + arrErrors[v];
			        sErrorDisplay += "<li class=\"error_li\">" + arrErrors[v];
			    }
			}
			sErrorDisplay += "</ul>\n";
			document.getElementById("validationErrors").innerHTML = sErrorDisplay;
			document.getElementById("validationErrors").style.display = "";
			if (document.getElementById("newSearchValidationErrors")) document.getElementById("newSearchValidationErrors").style.display = "";
			if(searchType == "ADDR"){
				if(document.getElementById("NewHotelSearch")){
					
					if(errCount ==1){
						document.getElementById("NewHotelSearch").style.height='480px';
						document.getElementById("new_hotel_search_body").style.height='460px';
					}
					else if(errCount ==2){
						document.getElementById("NewHotelSearch").style.height='520px';
						document.getElementById("new_hotel_search_body").style.height='500px';
					}

					else{
						document.getElementById("NewHotelSearch").style.height='650px';
						document.getElementById("new_hotel_search_body").style.height='630px';
						
					}
				}
			}
			else{
				
				if(document.getElementById("NewHotelSearch")){
					if(errCount ==1){
						document.getElementById("NewHotelSearch").style.height='380px';
						document.getElementById("new_hotel_search_body").style.height='360px';
					}
					else if(errCount ==2){
						document.getElementById("NewHotelSearch").style.height='420px';
						document.getElementById("new_hotel_search_body").style.height='400px';
					}
	
					else{
						document.getElementById("NewHotelSearch").style.height='480px';
						document.getElementById("new_hotel_search_body").style.height='460px';
						
					}
				}
			}

				//if(document.getElementById("new_search_btm"))document.getElementById("new_search_btm").style.top='360px';
			
		}

		return false;
    } else {
		//clear out values not used for this search before submitting
		try {
			if (searchType == "POI") {
				cityNameField.value="";
				document.getElementById('cityID').value="";
				document.getElementById('cityID_Name').value="";
				document.getElementById('addrLine').value="";	
				document.getElementById('addrCity').value="";	
				document.getElementById('addrState').value="";	
				document.getElementById('addrZIP').value="";	
			} else if (searchType=="ADDR") {
				cityNameField.value="";
				document.getElementById('cityID').value="";
				document.getElementById('cityID_Name').value="";
				document.getElementById('poiName').value="";
				document.getElementById('poiID').value="";
			} else {
				document.getElementById('poiName').value="";
				document.getElementById('poiID').value="";
				document.getElementById('addrLine').value="";	
				document.getElementById('addrCity').value="";	
				document.getElementById('addrState').value="";	
				document.getElementById('addrZIP').value="";	
			}
		} catch (e) {}
         var searchAction = sURL;
         var numRooms = document.getElementById('numberOfRooms').value;
         if(numRooms == 5 || numRooms == 10){
            searchAction = searchAction + "&groupRoomCount=" + numRooms;
         }
		 if (sActionAddOn != null) searchAction += sActionAddOn;
         if(document.searchHotelsForm.length == 2){
           document.searchHotelsForm[0].action = searchAction + "&noWait=Y";
           document.searchHotelsForm[0].submit();
         }else{
           document.searchHotelsForm.action=searchAction + "&noWait=Y";
           document.searchHotelsForm.submit();                 
	     }
	     try {
	    	 //tgCloseHtmlLightBox();
	    	 tgCloseHtmlLightBoxWithoutBackFiller();
		     htlInitWaitMessage(C_WAIT_DELAY_SEARCH);
		 } catch (e) {}

	}
}

function cleanHiddenSearchValues(searchType) {
	var nameField = "";
	if (searchType == "CITY")
		nameField = "cityName";
	else if (searchType == "POI")
		nameField = "poiName";
		
	if (nameField != "") {
		var name=document.getElementById(nameField);
		var idName = document.getElementById(nameField.replace(/Name/,"ID_Name"));
		var elt = document.getElementById(nameField.replace(/Name/,"ID"));
		if ((name != null) && (String(name.value) != "undefined") && 
				(idName != null) && (String(idName.value) != "undefined") &&
				(elt != null) && (String(elt.value) != "undefined") && 
				(name.value != idName.value)) {
			idName.value="";
			elt.value = "";
		}
	}
}

function trimString (str) {
  while (str.charAt(0) == ' ')
	str = str.substring(1);
  while (str.charAt(str.length - 1) == ' ')
	str = str.substring(0, str.length - 1);
  return str;
}

function checkDateFormat(dateField) {

	var str = replaceSeparater(dateField.value);
	if(str!="none") {
        var date = str.split("/");
        if (date.length!=3 || date[0].length<=0 ||
            date[1].length<=0 || date[2].length<=0 ||
            date[0].length>2 || date[1].length>2 || date[2].length>4)
        {
            return "INVALID";
        }

        var today = new Date();
        var thisyear = today.getFullYear().toString().charAt(0);

        if(date[2].length==1){
            thisyear = thisyear+today.getFullYear().toString().charAt(1);
            thisyear = thisyear+today.getFullYear().toString().charAt(2);
            var year = thisyear+date[2];
        }
        else if(date[2].length==2){
            thisyear = thisyear+today.getFullYear().toString().charAt(1);
            var year = thisyear+date[2];
        }
        else if(date[2].length==3){
            var year = thisyear+date[2];
        }else{
			var year = date[2];
		}

		if(date[1].length==3) {
			var month = replace3digitMonth(date[1]);
			if(month=="none") {
                return "INVALID";
			}

			if((date[0].length>2)|(date[0].length<=0)|(!isNumber(date[0]))) {
                return "INVALID";
			} else {
				if(date[0].length==1) {
					var day = "0"+date[0];
				}else{
					var day=date[0];
				}
			}
		} else {
            if((date[0].length>3)|(date[0].length<=0)|(!isNumber(date[0]))) {
                return "INVALID";
			} else {
				if(date[0].length==1) {
					var month = "0"+date[0];
				}else{
					var month=date[0];
				}
			}
            if((date[1].length>2)|(date[1].length<=0)|(!isNumber(date[1]))) {
                return "INVALID";
            } else {
				if(date[1].length==1) {
					var day = "0"+date[1];
				} else {
					var day=date[1];
				}
			}
		}

        if (month < 1 || month > 12) {
            return "INVALID";
        }

        if (day < 1 || day > 31) {
            return "INVALID";
        }

        if ((month == 4 || month == 6 || month == 9 || month == 11) && (day == 31)) {
            return "INVALID";
        }

        if (month == 2) {
            var leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
            if (day>29 || (day == 29 && !leap)) {
                return "INVALID";
            }
        }

        var todaysDate = new Date();
        var currentYear = today.getFullYear().toString();
        var currentMonth = today.getMonth() + 1;
        var currentDate = today.getDate();

        if (year < currentYear)
        {
            return "TOO_EARLY";
        }
        else if (year == currentYear)
        {
            if (month < currentMonth)
            {
                return "TOO_EARLY";
            }
            else if (month == currentMonth)
            {
                if (day < currentDate)
                {
                    return "TOO_EARLY";
                }
            }
        }

		if((parseInt(onedigit(day))<32)&&(parseInt(onedigit(month))<13)){
			dateField.value = month+"/"+day+"/"+year;
			return "VALID_DATA";
		} else {
		    return "INVALID";
		}
	} else {
        return "INVALID";
	}
}
function replace3digitMonth(str) {
	if(str.toUpperCase()=="JAN"){return "01";}
	else if(str.toUpperCase()=="FEB"){return "02";}
	else if(str.toUpperCase()=="MAR"){return "03";}
	else if(str.toUpperCase()=="APR"){return "04";}
	else if(str.toUpperCase()=="MAY"){return "05";}
	else if(str.toUpperCase()=="JUN"){return "06";}
	else if(str.toUpperCase()=="JUL"){return "07";}
	else if(str.toUpperCase()=="AUG"){return "08";}
	else if(str.toUpperCase()=="SEP"){return "09";}
	else if(str.toUpperCase()=="OCT"){return "10";}
	else if(str.toUpperCase()=="NOV"){return "11";}
	else if(str.toUpperCase()=="DEC"){return "12";}
	else{return "none"}
}

function replaceSlash(string,sep) {
	while(string.indexOf(sep)>=0){
		string = string.substring(0,string.indexOf(sep))+"/"+
		string.substring(string.indexOf(sep)+1,string.length);
	}
	return string;
}

function replaceSeparater(string) {

	string = trimString(string);

	if(string.indexOf("-")>=0){
		string = replaceSlash(string,"-");
	}
	if(string.indexOf(".")>=0){
		string = replaceSlash(string,".");
	}
	if(string.indexOf(",")>=0){
		string = replaceSlash(string,",");
	}
	if(string.indexOf(":")>=0){
		string = replaceSlash(string,":");
	}
	if(string.indexOf(" ")>=0){
		string = replaceSlash(string," ");
	}
	if(string.indexOf("/")>=0){
		return string;
	}
	else{
		return "none";
	}
}
function dateCheck(sCheckIn,sCheckOut) {

	var indate = sCheckIn.split("/");
	var outdate = sCheckOut.split("/");
	var cInDay = parseInt(onedigit(indate[1]));
	var cInMonth = parseInt(onedigit(indate[0]));
	var cOutDay = parseInt(onedigit(outdate[1]));
	var cOutMonth = parseInt(onedigit(outdate[0]));
	var Inyear = parseInt(indate[2]);
	var Outyear = parseInt(outdate[2]);
	var InDiff = calculateDayDiff(cInMonth,cInDay,Inyear);
	var OutDiff = calculateDayDiff(cOutMonth,cOutDay,Outyear);
    if(InDiff>=OutDiff) {
        return "CHECK_OUT_LESS_THAN_CHECK_IN";
    } else if(InDiff<0|OutDiff<1) {
        return "Please enter a valid check in and check out date";
	} else if((OutDiff-InDiff)>21) {
        return "DURATION_TOO_LONG";
	}  else if(OutDiff>=330) {
        return "TOO_FAR_OUT";
	} else {
        return "VALID_DATA";
    }
}

function calculateDayDiff(month,day,year){
	var Today=new Date();
	//Month is 0-11 in JavaScript
	var input_date =new Date(year, (month-1), day);
	// 1 day in milliseconds
	var one_day=1000*60*60*24;
	//Calculate difference btw the two dates, and convert to days
	return Math.ceil((input_date.getTime()-Today.getTime())/(one_day));
}

function onedigit (str) {
  if(trimString(str).charAt(0) == "0"){
	str = str.substring(1);
  }
  return str;
}
function isNumber(string) {
	if (string.length == 0)
		return false;
	for (var i=0;i < string.length;i++)
		if ((string.substring(i,i+1) < '0') || (string.substring(i,i+1) > '9'))
			return false;

	return true;
}
function isValidDate(day, month, year) {
    if (month < 1 || month > 12) {
        return false;
    }
    if (day < 1 || day > 31) {
        return false;
    }
    if ((month == 4 || month == 6 || month == 9 || month == 11) &&  (day == 31)) {
        return false;
    }

    if (month == 2) {
        var leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day>29 || (day == 29 && !leap)) {
            return false;
        }
    }
    return true;
}

function getCurrentDateString() {
    var today = new Date();
    var thisYear = today.getYear();
    if (thisYear < 1000) {
        thisYear+=1900;
    }
    return (today.getMonth()+1)+"/"+(today.getDate())+"/"+(thisYear);
}
function validateDates(checkInField,checkOutField,errorOuterDiv,errorInnerDiv){
		var checkInField = checkInField;
    	var checkOutField = checkOutField;
		//var currentIdx=document.getElementById('tmpNumberOfRoomsLightBox').selectedIndex;
		//var numOfRooms=document.getElementById('tmpNumberOfRoomsLightBox').options[currentIdx].value
		var bCheckIn = false;
    	var bCheckOut = false;
   		var errCount = 0;
    	var sError = "";
    	var arrErrors = new Array();
    	sError ="";
		sError = checkDateFormat(checkOutField);
	
		if (sError == "VALID_DATA") {
			bCheckOut = true;
		} else {
			arrErrors["checkOutDate"] = "Please select a valid Check-out date.";
			bCheckOut = false;
			errCount++;
		}

		sError = "";
		sError = checkDateFormat(checkInField);
		if (sError == "VALID_DATA") {
			bCheckIn = true;
		} else {

			if (sError=="TOO_EARLY") {
				//arrErrors["checkInDate"] = "The earliest check-in date for " + cityNameField.value + " is " + getCurrentDateString() + ".";
				arrErrors["checkInDate"] = "The earliest check-in date " + " is " + getCurrentDateString() + ".";
				arrErrors["checkOutDate"] = ""; // remove the checkout date validations
			} else {
				arrErrors["checkInDate"] = "Please select a valid Check-in date.";
			}
			errCount++;
			bCheckIn = false;
		}   

		if (bCheckIn && bCheckOut) {
			sError = "";
			sError = dateCheck(checkInField.value,checkOutField.value);

			if (sError != "VALID_DATA") {
				arrErrors["checkInDate"] = "";
				arrErrors["checkOutDate"] = "";
				if (sError == "DURATION_TOO_LONG") {
					arrErrors["dateCheck"] = "The maximum length of stay is 21 days.";
				} else if (sError== "CHECK_OUT_LESS_THAN_CHECK_IN") {
					arrErrors["dateCheck"] = "The check-in date must come before the check-out date.";
				} else if (sError== "TOO_FAR_OUT") {
					arrErrors["dateCheck"] = "Reservations can only be made 330 days in advance.";
				} else {
					arrErrors["dateCheck"] = sError;
				}
				errCount++;
			}
		}

		if (errCount>0) {
			//var sErrorDisplay = "<span style=\"{font-family: Geneva, Helvetica, sans-serif;font-weight: bold; font-size:10pt; color:red}\">Please verify the following information to continue with your request.</span>";
			var sErrorDisplay = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Please verify the following information to continue with your request.";
			sErrorDisplay += "<ul>\n";
			//var sErrorDisplay ="";
			for (var v in arrErrors) {
				if (String(arrErrors[v]).length > 0) {
					//sErrorDisplay += "<li style=\"{font-family: Geneva, Helvetica, sans-serif;font-weight:normal; font-size:10pt; color:red}\">" + arrErrors[v];
					sErrorDisplay += "<li class=\"error_li\">" + arrErrors[v] + "</li>" ;
				}
			}
			sErrorDisplay += "</ul>\n";

			document.getElementById(errorInnerDiv).innerHTML = sErrorDisplay;
			document.getElementById(errorInnerDiv).style.display = "";
			if (document.getElementById(errorOuterDiv)) document.getElementById(errorOuterDiv).style.display = "";
		
			//document.getElementById("NewSearch").style.height='320px';
		}
		else{
			
			//var sURL = "http://<%=request.getServerName() + request.getContextPath() + CreateLink.appendSessionKey("/rateSelectionDirect.do",request)%>"+
				//"&checkInDate="+checkInField.value+"&checkOutDate="+checkOutField.value+"&propID="+lightBoxpropID+"&numberOfRooms="+numOfRooms;			
			//var params="&checkInDate="+checkInField.value+"&checkOutDate="+checkOutField.value+"&propID="+lightBoxpropID+"&numberOfRooms="+numOfRooms;
			//window.location.href=rateSelectionURL+params;
			return true;
		}
}
