var divJS = [];
var _searchParams = [];

function setupSearch()
{
    try
    {
        _searchParams["MRU"] = { SearchType:"MRU", MRU: "" };
	    _searchParams["Fuzzy"] = { SearchType:"FUZZY", SOID:"", CountryList:"", ResortID:"", WeekID:"", SOCategory:"", Rating:"" };
	    _searchParams["Chalet"] = { SearchType:"FUZZY", ShowSortBy:"", SO_ID:"", WeekID:"", ResortID:"", CountryList:"", FacilityFilter:"" };

        $('#tab-offers').parent().hide();
        $('#tab-result').parent().hide();
	    checkSearchOnLoad();
	}
	catch(ex)
	{
	    raiseError("Error in setupSearch:"+ex);
	}
}

function gotoPage(pageNo)
{
    try
    {
        $('#results').html('<p class="loading"><img class="loading-img" src="/i/images/loaders/ajax-loader.gif" alt="Please Wait..." /> Loading chalets</p>');
        $('#txtPageNumber').val(pageNo);
        _searchParams["Chalet"].PageNumber = pageNo;
        InitSearch("Chalet",$('#chalets'));
    }
    catch(ex)
    {
        alert('An error occured attempting to perform your search.\nPlease try again or contact us by phone for further assistance.');
        raiseError("Error in gotoPage:"+ex.description);
    }
}

function FuzzySearch()
{
    try
    {
        $('#tab-offers').html('Special Offers');
        $('#tab-offers').parent().show();
        $('#results').html('<p class="loading"><img class="loading-img" src="/i/images/loaders/ajax-loader.gif" alt="Please Wait..." /> Loading offers</p>');
        navtabs.tabs('select',1);
        var countries = "";
        $('#display-by-countries:visible ul li input[@name="chkcountry"]:checked').each(function(){countries+=$(this).val()+',';});
        countries = (countries != "" ? countries+"-1" : countries);
        _searchParams["Fuzzy"] = { SearchType:"FUZZY", PageNumber:"1", ShowSortBy:"", SOID:$('#txtSOID').val(), CountryList:countries, 
                                    ResortID:$('#ddlResort:visible').val(), WeekID:$('#ddlWeek').val(),
                                    SOCategory:$('#ddlOfferType').val(), Rating:($('#ratingLuxury:checked').val()=="Y"?"3":"") };
        $('#txtSOID').val("");
        $('#ddlOfferType').val("")
        InitSearch("Fuzzy",$('#results'));
    }
    catch(ex)
    {
        alert('An error occured attempting to perform your search.\nPlease try again or contact us by phone for further assistance.');
        raiseError("Error in Fuzzy search:"+ex.description);
    }
}

function searchSO(resortID,SO_ID_C)
{
    try
    {
        ChaletSearch(SO_ID_C,-1,resortID,"");
    }
    catch(ex)
    {
        alert('An error occured attempting to perform your search.\nPlease try again or contact us by phone for further assistance.');
        raiseError("Error in searchSO:"+ex.description);
    }
}

//populates third tab
function ChaletSearch(pSO_ID_C,pWeekID,pResortID,pCountryList)
{
    try
    {
        $('#tab-result').html('Chalets');
        $('#tab-result').parent().show();
        $('#chalets').html('<p class="loading"><img class="loading-img" src="/i/images/loaders/ajax-loader.gif" alt="Please Wait..." /> Loading chalets</p>');
        navtabs.tabs('select',2);
        var countries = "";
        $('#display-by-countries:visible ul li input[@name="chkcountry"]:checked').each(function(){countries+=$(this).val()+',';});
        countries = (countries != "" ? countries+"-1" : countries);
        _searchParams["Chalet"] = { SearchType:"FUZZY", PageNumber:"1", ShowSortBy:"",
                                    SO_ID:pSO_ID_C, WeekID:pWeekID, ResortID:pResortID, CountryList:pCountryList };
        InitSearch("Chalet",$('#chalets'));
    }
    catch(ex)
    {
        alert('An error occured attempting to perform your search.\nPlease try again or contact us by phone for further assistance.');
        raiseError("Error in Fuzzy search:"+ex.description);
    }
}

function InitSearch(searchType, displaydiv)
{
    try
    {
        _searchParams["Chalet"].ShowSortBy = sortByVisible;
        if (searchType=="Fuzzy")
            $.post("/SOSearch.aspx", _searchParams[searchType], function(data){PopulateSidebar(searchType, displaydiv,data);});
        else if (searchType=="Chalet")
            $.post("/ChaletSearch.aspx", _searchParams[searchType], function(data){PopulateSidebar(searchType, displaydiv,data);});
    }
    catch(ex)
    {
        alert('An error occured attempting to perform your search.\nPlease try again or contact us by phone for further assistance.');
        raiseError("Error in Init search:"+ex.description);
    }    
}

function PopulateSidebar(searchtype, div, data)
{
    try
    {
        var output = "", JS = "";
        var codearray = data.split("<div class='sectionbreaker' />");
        if (codearray.length == 3)
        {
            if (codearray[0].replace(/^\s+|\s+$/g, '') != "")
            {
                output = "Error retrieving search results. Please try again or contact us by phone for further assistance.";
                raiseError("Ajax call returned error:"+codearray[0]);
            }
            else
            {
                output = codearray[1];
                JS = codearray[2];
            }
        }
        else
        {
            output = "Error retrieving search results. Please try again or contact us by phone for further assistance.";
            raiseError("Ajax call failed, result:"+data);
        }
        div.html(output);
        divJS[div.attr('id')] = JS;
        setTimeout(JS,100);
        setTimeout(function () {$('p.trunc-me').truncate(100,{chars: /\\s/, trail: [ " ... <a href='#' class='truncate_show'> Read more</a>",""]}).removeClass('trunc-me');},250);
        if (searchtype=="Chalet")
            applyResultsFilterJS();
    }
    catch(ex)
    {
        alert('An error occured attempting to show your search results.\nPlease try again or contact us by phone for further assistance.');
        raiseError("Error in Sidebar populate:"+ex.description);
    }
}

//called by Resort IW to search for accom - don't confuse with *Chalet*Search
function chaletSearch()
{
    try
    {
        if ($('#ddlIWWeek').val()=="" || $('#ddlIWGroupSize').val()=="")
        {
            alert('Please select at least a week and a group size before submitting your search.');
            return;
        }

        window.location.href='/ChaletExplorer.aspx?SBQS=Y&WeekID='+$('#ddlIWWeek').val()+"&GroupSize="+$('#ddlIWGroupSize').val();
    }
    catch(ex)
    {
        alert('An error occured attempting to perform your search.\nPlease try again or contact us by phone for further assistance.');
        raiseError("Error in chaletSearch:"+ex.description);
    }
}

function showSearch()
{
    try
    {
        $('#sidebar').animate({scrollTop:0}); 
    }
    catch(ex)
    {
        raiseError("Error in showSearch:"+ex.description);
    }
}

function showSOResults()
{
    try
    {
        $('#sidebar').animate({scrollTop:0}); 
        if (divJS["results"]!="")
                eval(divJS["results"]);
    }
    catch(ex)
    {
        raiseError("Error in showResults:"+ex.description);
    }
}

function showChaletResults()
{
    try
    {
        $('#sidebar').animate({scrollTop:0}); 
        if (divJS["chalets"]!="")
                eval(divJS["chalets"]);
    }
    catch(ex)
    {
        raiseError("Error in showChalets:"+ex.description);
    }
}

function toggleSortBy(href,sortby)
{
    try
    {
        var $href = $(href);
        var hasAsc = $href.hasClass('ascending');
        _searchParams["Chalet"].SortBy = ($href.hasClass('ascending') ? '2' : '1') + sortby;
        gotoPage(1);
    }
    catch(ex)
    {
         raiseError("Error in toggleSortBy:"+ex.description);
    }
}


var filterstrings = [], filtercounts = [];
function clearFilterStrings()
{
    filterstrings = [];
    filtercounts = [];
}

function addFilterString(filter,count)
{
    filterstrings[filterstrings.length]=filter;
    filtercounts[filtercounts.length]=count;
}

function toggleFacilityFilter(chkbox)
{
    try
    {
        var count = 0;
        if (filterstrings.length > 0)
        {
            var filter="";
            $('.facility-filter:checked').each(function(){filter+=$(this).val();});
            for(var i = 0; i < filterstrings.length; i++)
            {
                var allfound = true;
                if (filter.length > 0)
                {
                    for(var j = 0; j < filter.length; j++)
                    {
                        if (filterstrings[i].indexOf(filter.charAt(j))==-1)
                        {
                            allfound=false;
                            break;
                        }
                    }
                }
                if (allfound)
                    count += filtercounts[i];
            }
        }
        $('#filtercount').html("<span class='total'>" + count + "</span> chalet" + (count == 1 ? "" : "s") + " found");
        (count==0?$('#btnFilter').attr("disabled","disabled"):$('#btnFilter').removeAttr("disabled"));
        $('div.show-matches').removeClass("matches-found no-matches");
        (count==0?$('div.show-matches').addClass("no-matches"):$('div.show-matches').addClass("matches-found"));
    }
    catch(ex)
    {
         raiseError("Error in toggleFacilityFilter:"+ex.description);
    }  
}

function facilityFilter()
{
    try
    {
        var facilityfilter="";
        $('.facility-filter:checked').each(function(){facilityfilter+=$(this).val();});
        _searchParams["Chalet"].FacilityFilter = facilityfilter;     
        gotoPage(1);
    }
    catch(ex)
    {
         raiseError("Error in facilityFilter:"+ex.description);
    }  
}

function addRecentlyViewed(dummy)
{

}

/* search on load */
function checkSearchOnLoad()
{
    try
    {
        var qs = getArgs();
        if (qs.SBQS || $('#txtForceSOL').val()=='Y') //search by query string is true
        {
            //load search params
            try { if (qs.WeekID) $('#ddlWeek').val(qs.WeekID); } catch(ex) {}
            try { if (qs.ResortID) $('#ddlResort').val(qs.ResortID); } catch(ex) {}
            try { if (qs.OfferType) $('#ddlOfferType').val(qs.OfferType); } catch(ex) {}
            try { if (qs.Luxury) $('#ratingLuxury').attr("checked","checked"); } catch(ex) {}
            try { if (qs.SOID) $('#txtSOID').val(qs.SOID); } catch(ex) {}
            try
            {
                if (qs.CountryList)
                {
                    var countries = qs.CountryList.split(",");
                    if (countries.length > 0)
                    {   
                        $('#allCountries').attr("checked","");
                        $('input[@name="chkcountry"]').attr("checked","");
                        for(var i = 0; i < countries.length; i++)
                            $('input[@name="chkcountry"][@value="'+countries[i]+'"]').attr("checked","checked");
                    }
                }
                
            }
            catch(ex)
            {}
            //execute search
            if (qs.SOID && qs.WeekID && (qs.ResortID || qs.CountryList))
                ChaletSearch(qs.SOID,qs.WeekID,qs.ResortID,qs.CountryList);
            else
                FuzzySearch();
        }
    }
    catch(ex)
    {
        raiseError("Error in checkSearchOnLoad:"+ex.description);
    }
}
