﻿// JScript File
var vVEMap = null;
var vReWriteURL = null;
var vSearchDataRang = null;
var vQueryString = "";

//***********************************************************************************************
//  Method used by the jquery date pickers to restrict invalid dates from previous selection
//***********************************************************************************************
function PerformSearch()
{
    if (!isLoadMapComplete()) return;
    
    vReWriteURL = "";    
    var vErrorMessage = "";
    var isValid = 1;
    var isLocationGeocodeSearch = 0;   
    
    var vbDestinationTypeId = $(":asp('zd_ddlDestinationTypes') :selected").val();
    //vQueryString += "&vcsc_id=" + vbDestinationTypeId;
    vQueryString = "vcsc_id=" + vbDestinationTypeId;
    
    var vSubDestinationType = $(":asp('zd_ddlSubDestinationTypes') :selected").val();
    vQueryString += "&vcsuc_id=" + vSubDestinationType;
    
    var vbDestinationType = GetDestinationTypes(vbDestinationTypeId, 'VCSC_URL_BROWSE_ALIAS');    
    vbDestinationType = vbDestinationType + "/" + vSubDestinationType;
    
    var vViewType = null;
    //Step  -   Get the desired results display View
    $("input.SearchResultsDisplayType").filter(':checked').eq(0).each(function()
    {
        vQueryString += "&vserdt_id=" + $(this).val();      
        switch ($(this).val())
        {
            case "1":                
                vViewType = "-results-list/";
                break;
            case "2":
                vViewType = "-results-grid/";
                break;
            case "3":
                vViewType = "-results-map/";
                break;
        }
    });
    
    //Step  -   If id="zd_dSearchAvailability" is visible, then pass Date parameters to SearchResults page
    vSearchDataRang = null;
    $("div#zd_dSearchAvailability").filter(":visible").eq(0).each(function()
    {        
        // Site Type
        vSearchDataRang = "";
        var vSiteType = $(":asp('zd_ddlSiteTypes') :selected").text();
        vSearchDataRang +=  replaceURLBlank(vSiteType) + "/"
       
        // from-03/25/2009-to-03/26/2009/
        var vFromDate = $(":asp('zd_tbSearchStartDate')").val();
        var vToDate = $(":asp('zd_tbSearchEndDate')").val();
        if (vFromDate == '') vFromDate = "empty/empty/empty";
        if (vToDate == '') vToDate = "empty/empty/empty/";
        vSearchDataRang += "from-" + vFromDate + "-to-" + vToDate + "/"
        
         //Step  - Get Search Camp Type
        vQueryString += "&vdest_id=" + $(":asp('zd_ddlSiteTypes') :selected").val();
        vQueryString += "&SearchStartDate=" + $(":asp('zd_tbSearchStartDate')").val();
        vQueryString += "&SearchEndDate=" + $(":asp('zd_tbSearchEndDate')").val();
    });
    
    //NOTE  -   Make sure that this section is the last step as its building the zm_sQueryString that will be used for the search
    //          and if the user is using the Location/Geocode search (Distance From Destination or Address) it will be using
    //          this pre-populated string
    
    //Step  -   If id="zd_dSearchBy" is visible, then 
    $("div#zd_dSearchBy").filter(":visible").eq(0).each(function()
    {   
        var vState = null;
        var vStateRegion = null;
        //Step  -   If State was chosen Search By filter
        $("input#zd_rState").filter(":checked").eq(0).each(function()
        {
            //Step  -   Check to see if selected value == "select" or selected value is the first element in the options list
            if(($(":asp('zd_ddlStates') :selected").val() == "select") || ($(":asp('zd_ddlStates') :selected").val() == $(":asp('zd_ddlStates') option").eq(0).val()))
            {
                isValid = 0;
                vErrorMessage += "Searching by State requires that you first select a State.";
            } else {
                // Add the result type
                vReWriteURL = "find-state" + vViewType;              
                // Add distination type
                vReWriteURL += vbDestinationType + "/";                
                // Add states
                var vState = $(":asp('zd_ddlStates') :selected").text();
                vReWriteURL += replaceURLBlank(vState) + "/"                
                // Add the region
                var vRegions = $(":asp('zd_ddlRegions') :selected").text();
                vReWriteURL += replaceURLBlank(vRegions) + "/"   
                
                vQueryString += "&State=" + $(":asp('zd_ddlStates') :selected").val();   
                vQueryString += "&vre_id=" + $(":asp('zd_ddlRegions') :selected").val();    
            } 
        });

        var vDestinationName = null;
        //Step  -   If DestinationName was chosen Search By filter
        $("input#zd_rDestinationName").filter(":checked").eq(0).each(function()
        {
            // zm_sQueryString += "&name=" + $(":asp('zd_tbDestinationName')").val();
            vDestinationName = $(":asp('zd_tbDestinationName')").val();
            vDestinationName = TrimString(vDestinationName);
            
            //Step  -   Take note that this isn't a valid search as there is not Destination Name
            if(vDestinationName == vConstDestinationNamePrompt)
            {
                isValid = 0;
                vErrorMessage += "Searching by Name requires that you first supply a Name.";
            } else             
            //Step  -   Take note that this isn't a valid search as the Destination Name being searched is less than 3 chars
            if(vDestinationName.length < 3)
            {
                isValid = 0;
                vErrorMessage += "Searching by Name requires a Name with a length of at least 3.";
            } else {
                // Add the result type
                vReWriteURL = "find-name" + vViewType;
                // Add distination type
                vReWriteURL += vbDestinationType + "/"; 
                // Add Destination Name
                vReWriteURL += vDestinationName + "/";
                
                vQueryString += "&name=" + $(":asp('zd_tbDestinationName')").val();
            }
        });        
        
        var vDistances = null;
        var vDestinationAddress = null;
        //Step  -   If DestinationAddress was chosen Search By filter
        $("input#zd_rDestinationAddress").filter(":checked").eq(0).each(function()
        {
            // zm_sQueryString += "&distance=" + $(":asp('zd_ddlDistances')").val();
            vDistances = $(":asp('zd_ddlDistances')").val();
            vDestinationAddress = $(":asp('zd_tbDestinationAddress')").val(); // ?????????
            
            //Step  -   Take note that this isn't a valid search as there is not Destination Address
            if(vDestinationAddress == vConstAddressPrompt)
            {
                isValid = 0;
                vErrorMessage += "Searching by Distance from Destination requires that you first supply a value.";
            } else            
            //Step  -   Take note that this isn't a valid search as the Destination Address being searched is less than 3 chars
            if(vDestinationAddress.length < 3)
            {
                isValid = 0;
                vErrorMessage += "Searching by Distance from Destination requires a value with a length of at least 3.";
            } else {
                 // Add the result type
                vReWriteURL = "find-distance" + vViewType;
                // Add distination type
                vReWriteURL += vbDestinationType + "/"; 
                // Add Distances
                vReWriteURL += vDistances + "/";
                
                vQueryString += "&distance=" + $(":asp('zd_ddlDistances')").val();
            }
            
            //Step  -   Set this variable so that we know to perform the Location Geocode lookup
            isLocationGeocodeSearch = 1;
        });
    });
    
    if(isValid == 1)
    {
        if(isLocationGeocodeSearch == 1)
        {
            try {
                var vObj = window.frames["mapIFrame"];
                var vMapIFrame = vObj.frameElement;
                if (vMapIFrame != null)
                {
                    var vAddress = $(":asp('zd_tbDestinationAddress')").val();
                    vMapIFrame.contentWindow.searchLocatioin(vAddress);
                }
            } catch (ex) {
                alert('Map Exception:' + ex.message);
            }
        }
        else
        {
            if (vSearchDataRang != null) vReWriteURL += vSearchDataRang;
                 
            var vAmenitiesObj = GetSelectedAmenities(); 
            var vAmenities = SelectedAmenitiesParameters(vAmenitiesObj);            
            if (vAmenities != null) vReWriteURL += vAmenities
            
            //window.location = LinkPath(vReWriteURL);
            SearchResults(vReWriteURL, vQueryString, vAmenitiesObj);
        }
    }
    else
    {
        DisplayErrorMessage(vErrorMessage, 400, 200);
        return false;
    }
}

function SearchResults(vReWriteURL, vQueryString, vAmenitiesObj)
{   
    try {        
        vQueryString += GetSelectAmenitiesTabIndex() 
        vQueryString += SelectSearchTabIndex();
        if (vAmenitiesObj != null)
        {
            if(vAmenitiesObj.VAM != "") vQueryString += "&vam_ids_string=" + vAmenitiesObj.VAM;
            if(vAmenitiesObj.VAF != "") vQueryString += "&vaf_ids_string=" + vAmenitiesObj.VAF;
        }
        vQueryString = LinkPath("Search/SearchOption.aspx?" + vQueryString);;
               
        $.ajax({
            type: "POST",
            cache: false,
            url: vQueryString,//data: paramData,            
            contentType: "application/json; charset=utf-8",
            dataType: "html",
            
            success: function(content) 
            {   
              // maskWindow(false);
              var vURL = BrowserLinkPath(vReWriteURL);
              window.location = vURL;  
            },
            beforeSend: function()
            {
                maskWindow(true);
            },
            complete: function()
            {
                //maskWindow(false);
            },
            error: function(msg)
            {
                // maskWindow(false);
                window.location = BrowserLinkPath(vReWriteURL);
            }
        });
    } catch (ex) {
        AlertMsg('search.methods_rewrite.js', 'SearchResults', ex.message);
    }
}

//***********************************************************************************************
//  Method used by liveMap.Find as the Callback function
//***********************************************************************************************
function LocationGeocodeCallback(arrPlace)
{
    var content = "";
    var vErrorMessage = "";

	if( arrPlace == null || arrPlace.length == 0 )
	{
	    vErrorMessage = "<div style=\"text-align:center;\"><br /><b>Landmark/Address could not be found.</b></div>";
	    DisplayErrorMessage(vErrorMessage);
		return false;
	}
	else if( arrPlace.length > 1 )
	{
	    content = "<br /><b>Select a Location</b><br /><br />";
	    for( var i = 0; i < arrPlace.length; i++ )
	    {
	        content += "<a onclick=\"javascript:PerformLocationGeocodeSelected('" + arrPlace[i].Name + "','" +  arrPlace[i].LatLong.Latitude + "','" + arrPlace[i].LatLong.Longitude + "');\" href=\"#\">" + arrPlace[i].Name + "</a><br />";
	    }
	    		
		//Step  -   Show the Modal Pop-up with the available Locations
        $.nyroModalManual({content: content});
	}
	else if ( arrPlace.length == 1 )
	{
	    PerformLocationGeocodeSelected(arrPlace[0].Name, arrPlace[0].LatLong.Latitude, arrPlace[0].LatLong.Longitude);
	}
}

//***********************************************************************************************
//  Method used after a Location Geocode has been selected
//***********************************************************************************************
function PerformLocationGeocodeSelected(location, latitude, longitude)
{
    try {
        var sRedirectUrl = "";
        
        $(":asp('zd_tbDestinationAddress')").attr("value", location);
	    $.nyroModalRemove();

        vReWriteURL += location + "/";
        vReWriteURL += "latitude=" +  latitude + "/";
        vReWriteURL += "longitude=" +  longitude + "/";
        if (vSearchDataRang != null) vReWriteURL += vSearchDataRang;
        
        vQueryString += "&location=" + location;
        vQueryString += "&latitude=" + latitude;
        vQueryString += "&longitude=" + longitude;
        
        var vAmenitiesObj = GetSelectedAmenities(); 
        var vAmenities = SelectedAmenitiesParameters(vAmenitiesObj);            
        if (vAmenities != null) vReWriteURL += vAmenities
        
	    //sRedirectUrl = zm_sStaticRedirectUrl + zm_sQueryString;
	    //sRedirectUrl = LinkPath(vReWriteURL);	
        // window.location = sRedirectUrl;
        SearchResults(vReWriteURL, vQueryString, vAmenities);
    } catch (ex) {
        AlertMsg('search.methods_rewrite.js', 'PerformLocationGeocodeSelected', ex.message);
    }
}