﻿//================================================================
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Search Bar Constructor - runs on page load
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//================================================================
$(document).ready(function() 
{ 
    //========|| Bind fields to cookies
    
    if ($.cookies.get('Term') != null && $.cookies.get('Term') != '')           $('#Term').val($.cookies.get('Term'));
    if ($.cookies.get('LocationSuggested') != null && $.cookies.get('LocationSuggested') != '')   $('#LocationSuggested').val($.cookies.get('LocationSuggested'));
    if ($.cookies.get('Channel') != null && $.cookies.get('Channel') != '')   $("input[name='Channel']").val($.cookies.get('Channel'));
});
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


function ResetSearch()
{
    $('#Term').val('');
    $.cookies.del('Term');
    $.cookies.del('LocationSuggested');
    $.cookies.del('Channel');
    SwapType(CacheObject.Channel);
}

//================================================================
//  ID Variables
//================================================================
var L1 = "#Location1";
var L2 = "#Location2";
var L3 = "#Location3";
var L4 = "#Location4";
var LS = "#LocationSelected";
var L1234 = "#Location1, #Location2, #Location3, #Location4";
var L123 =  "#Location1, #Location2, #Location3";
var L12 =   "#Location1, #Location2";
var L234 =  "#Location2, #Location3, #Location4";
var L34 =   "#Location3, #Location4";
var RegionSEO;       // reused for all Region SEO
var OtherCriteria = "#PriceMin, #PriceMax, #Bedrooms";
    

function SwapType(typ)
{
    CacheObject.Channel = typ;
    
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // reset Location Dropdowns
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    $(L1234).html("");
    $(L1234).get(0).selectedIndex = 0;
    $(LS).val("");
    $(L1234).unbind();
    
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // reset Other Dropdowns and Show Only with JSon
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    $(OtherCriteria).html("");
   
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Swap Selected Class
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    $('.search-options > label').removeClass('active');
    document.getElementById(typ).nextSibling.className='active';
    
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Trigger Tab
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //SwapTab('tri');
}






function GetJson(SearchType, Term, ResponseHandler)
{
    var UrlPath = String.Format("{0}Service.aspx?Channel={1}&SearchType={2}&Term={3}&ReturnType=json", CacheObject.SearchServiceRoot, CacheObject.Channel, SearchType, Term);
    
    // Docs: http://docs.jquery.com/Ajax/jQuery.ajax
    $(document).ready(function() {
        $.ajax({
            type: "GET", // IE8 bug? does not like POST....
            url: UrlPath,
            cache: false,
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
            timeout: 3000,
            success: function(json) 
            {
                ResponseHandler(json);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            {
                $.log("Json Error Message: error(" + errorThrown + ") \"" + textStatus + "\""); 
                ResponseHandler(null);
            }
        })
    });
}

function ValidateJsonResponse(JsonResponse)
{
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // due diligence
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    if (JsonResponse==null) return false; 
    if (JsonResponse.group == null) return false;
    if (JsonResponse.group.length < 1) return false;
    if (JsonResponse.group[0].option == null) return false;
    if (JsonResponse.group[0].option.length < 1) return false;
    return true;
}

function Fader()
{
    if (arguments.length == 0) return;
    
    for(var x=0;x<arguments.length;x++)
    {
        eval(String.Format("$('{0}').fadeTo(10, 0.25, function(){{ $('{1}').fadeTo(400, 1.0); }});", arguments[x], arguments[x]));
    }
}

function LoadSelect(JsonResponse, SelectId, GroupIndex, CallbackMethod)
{
    var Count = 0;
    if (JsonResponse.group != undefined && JsonResponse.group.length > GroupIndex)
    {
        if (JsonResponse.group[GroupIndex] != undefined)
        {
            if (JsonResponse.group[GroupIndex].option != undefined)
            {
                if (JsonResponse.group[GroupIndex].option.length > 0)
                {
                    Count = JsonResponse.group[GroupIndex].option.length;
                    for(var g=0;g<JsonResponse.group[GroupIndex].option.length;g++)
                    {
                        var val = (JsonResponse.group[GroupIndex].option[g].value == undefined) ? JsonResponse.group[GroupIndex].option[g].valueseo : JsonResponse.group[GroupIndex].option[g].value;
                        
                        $(SelectId).append(NewOpt(val, JsonResponse.group[GroupIndex].option[g].title));
                    
                    }
                }
            }
        }
    }
    if (CallbackMethod != undefined)
    {
        CallbackMethod(Count);
    }
}


function NewOpt(val, text)
{
    return "<option value=\"" + val + "\">" + text + "</option>";
}

function MinQuery() //TODO: for debugging only
{
    //$("#bottomframe").attr("src", $("#QueryUrl").val() + "&Indent=true");
}

function Search()
{
    
    var Criteria = new Array();
    var LocationSuggested = jQuery.trim($("#LocationSuggested").val());
    var LocationSelected = ""; //jQuery.trim($("#LocationSelected").val());
    var Term = jQuery.trim($("#Term").val());

    var SmartQueryStringArray = new Array();
		SmartQueryStringArray.push("ss=true");
        SmartQueryStringArray.push("channel=" + CacheObject.Channel);

    if (LocationSuggested == "" && LocationSelected == "" && Term == "")
    {
        window.alert("Please select a location, or enter a location, zip or web ID");
        return;
    }

    var RequiresSmartSearch = false;
    var SearchLocation = "";
    var JSonTargetUrl = "";
    
    //================================================================
    //  Important concept: selecting a location and criteria does not
    //  guarantee listings.
    //================================================================
    if (LocationSuggested != "")
    {
        SearchLocation = LocationSuggested;
    }
    
    //================================================================
    //========|| 5. User enters Keyword Search only
    //================================================================
    else 
    if (LocationSelected == "" && LocationSuggested == "" && Term != "")
    {
        RequiresSmartSearch = true;
        SmartQueryStringArray.push("keyword=" + escape(trim(Term)));
    }
    //================================================================
    //========|| 6. Unknown Condition
    //================================================================
    else
    {
        window.alert("Please select a location, or enter a location, zip or web ID.");
        return;
    }
    
    //================================================================
    //========|| Add Search Type options
    //================================================================
    if ($("#search_bar_type").attr("selectedIndex") > 0)
    {
        Criteria.push($("#search_bar_type").val());
    }
    
    //================================================================
    //========|| Add Criteria
    //================================================================
    if (Criteria.length > 0)
    {
        SmartQueryStringArray.push("Criteria=" + Criteria.join("/"));
    }

    //================================================================
    //========|| Add Return Type
    //================================================================
    //SmartQueryStringArray.push("return_type=json"); // default
    
    var SmartQueryString = SmartQueryStringArray.join("&");

    var cri = Criteria.join('/');
    if (cri.length > 0) cri = "/" + cri;
    var RawUrl = String.Format("/{0}/{1}{2}", CacheObject.Channel.toLowerCase(), SearchLocation.toLowerCase(), cri);
    
   
    //================================================================
    //========|| Cookies
    //================================================================
    var opts = { hoursToLive: (24*7) };
    if ($('#Term').val() != null && $('#Term').val() != '')         $.cookies.set('Term', $('#Term').val(), opts);
    if ($('#LocationSuggested').val() != null && $('#LocationSuggested').val() != '') $.cookies.set('LocationSuggested', $('#LocationSuggested').val(), opts);

    if (RequiresSmartSearch)
    {
        JSonTargetUrl = "/Reno/Search/SmartSearch.aspx?" + SmartQueryString;
		
		//window.location.href = JSonTargetUrl;
		//return;
		
		//alert(JSonTargetUrl);
		//return;

		$.getJSON(JSonTargetUrl,
        function(JsonResponse, textStatus)
        {
            if (JsonResponse != null &&
                JsonResponse.matchgroup != null &&
                JsonResponse.matchgroup.length > 0 &&
                JsonResponse.matchgroup[0].match != null &&
                JsonResponse.matchgroup[0].match.length > 0)
            {
                window.setTimeout(function() // timeout required to set history, since this is an asynch call
                {
                    var RedirectUrl = JsonResponse.matchgroup[0].match[0].seopath;

                    //window.location.href = JSonTargetUrl;
                    //return;
                    if (JsonResponse.matchgroup.length > 1 || JsonResponse.matchgroup[0].match.length > 1)
                    {
						RedirectUrl = RedirectUrl + "?" + SmartQueryString;
                    } 
                    // reset search cookie values
                    $.cookies.del('Term');
					$.cookies.del('LocationSuggested');
					$.cookies.del('Channel');
					var Opts = { hoursToLive: 1 };
					$.cookies.set("Term", $("#Term").val(), Opts);
                    window.location.href = RedirectUrl;
                    
                },10);
            }
            else
            {
				alert("Your search for '" + Term + "' returned zero results. Please try another term.");
				$.cookies.del('Term');
				$.cookies.del('LocationSuggested');
				$.cookies.del('Channel');
            }
        });
    }
    else
    {
        window.location.href = RawUrl;
    }
    
}

function setBcolH()
{
    $('#col-b').height($('#col-a').height());
}
