$(document).ready(function() {
    $.getScript(VM_SearchConfig.SiteRoot + "/scripts/jquery.cookie.js");
    checkCookies();
    
    setupAutoComplete();
    setupWebMetrics();
    setupResults(); // is called from results control subsequently
    setupSearchForm();
    jQuery.fn.outerHtml = function() { return $("<div>").append(this).html(); };

    if (window.location.toString().toLowerCase().indexOf("search.aspx") > -1) {
        setTimeout("primeCache()", 2000);
    }
});

var cookieCheckAttempts = 0;
function checkCookies() {
    if ($.cookie) {
        setupRecentSearches();
        setupFontSizing();
    } else if (cookieCheckAttempts < 15) {
        cookieCheckAttempts++;
        setTimeout(checkCookies, 100);
    }
}


// prime the results page cache by loading the MapResults.js early
function primeCache() {
    $.getScript(VM_SearchConfig.SiteRoot + "/scripts/MapResults.js");
}

function reloadWebTrends() {
    $.getScript("http://www.farmers.com/WTdcsCollect.js");
}

// ----- Auto Complete ----- //
function setupAutoComplete(){
    AutoComplete = function(inputClass, contentID, serviceMethod) {
        this.ready = false;
        this._phrases;
        this._phrase = "";
        this._index = -1;
        this._shown = false;
        this._inputClass = inputClass;
        this._contentID = contentID;
        this._serviceMethod = serviceMethod;
        var scope = this;

        this.load = function(phrase) {
            if (phrase != this._phrase) {
                this._phrase = phrase;
                this._index = -1;
                var url = VM_SearchConfig.SiteRoot + "/services/LocatorProxy.asmx/" + this._serviceMethod + "?phrase=" + phrase + "&locator=" + VM_SearchConfig.LocatorType;
                $.ajax({
                    type: "GET",
                    url: url,
                    dataType: "xml",
                    async: true,
                    success: function(xml) {
                        scope.parse(xml);
                        scope.getHTML();
                    },
                    error: function() { }
                });
            }
        }
        this.parse = function(xml) {
            var phrases = new Array();
            $(xml).children().children().each(function() {
                if ($(this).text() != $(this._inputClass).val()) {
                    phrases.push($(this).text());
                }
            });
            this._phrases = new Array();
            this._phrases = phrases;
        }
        this.getHTML = function() {
            if (this._phrases.length > 0) {
                var html = "";
                var len = (this._phrases.length > 10) ? 10 : this._phrases.length;
                for (var x = 0; x < len; x++) {
                    html += "<a href='javascript:;' class='link' index='" + x + "'>" + this._phrases[x] + "</a>";
                }
                $(this._contentID).html(html);
                $(this._contentID + ' .link').hover(function() {
                    scope.setSelection(parseInt($(this).attr('index')));
                }, function() { });
                $(this._contentID + ' .link').click(function() {
                    $(scope._inputClass).val($(this).text());
                });
                this.ready = true;
                this.addSelection();
                this.show();
            } else {
                this.hide();
            }
        }
        this.hide = function() {
            if (this._shown) {
                this._shown = false;
                $(this._contentID).fadeOut();
                $(this._inputClass).unbind('keypress');
            }
        }
        this.show = function() {
            this._shown = true;
            $(this._contentID).show();
            $(this._inputClass).bind('keypress', function(e) {
                if (scope._index > -1 && e.keyCode == 13) {
                    $(this).val($(scope._contentID + ' .selected').text());
                    scope.hide();
                    return false;
                } else if (scope._index > -1 && e.keyCode == 0) {
                    $(this).val($(scope._contentID + ' .selected').text() + " ");
                    scope.hide();
                    return false;
                }
            });
        }
        this.moveSelection = function(increment) {
            this.removeSelection();
            this._index += increment;
            this._index = (this._index < 0) ? 0 : this._index;
            this._index = (this._index > this._phrases.length - 1) ? this._phrases.length - 1 : this._index;
            this.addSelection();
        }
        this.setSelection = function(index) {
            this.removeSelection();
            this._index = index;
            this.addSelection();
        }
        this.addSelection = function() {
            var selector = this._contentID + ' .link:eq(' + this._index + ')';
            $(selector).addClass('selected');
        }
        this.removeSelection = function() {
            var selector = this._contentID + ' .link:eq(' + this._index + ')';
            $(selector).removeClass('selected');
        }
        $(this._inputClass).keyup(function() {
            if ($(this).val().length > 2) {
                scope.load($(this).val());
            } else {
                scope.hide();
            }
        });
        $(this._inputClass).bind("keydown", function(e) {
            if (scope.ready) {
                if (e.keyCode == 38) {
                    scope.moveSelection(-1);
                    return false;
                } else if (e.keyCode == 40) {
                    scope.moveSelection(1);
                    return false;
                }
            }
        });
        $(this._inputClass).blur(function() {
            scope.hide();
        });
        $(this._inputClass).attr("autocomplete", "off");
    }
    var autoComplete = new AutoComplete(".searchFormInput", "#autoComplete", "GetAutoComplete");
    var autoCompleteByName = new AutoComplete(".searchForm_agentName", "#autoCompleteByName", "GetAutoCompleteByName");
}

// ----- Recent Searches ----- //
var vm_recentSearches = null;
function setupRecentSearches(){
    RecentSearches = function(){  
        this._index = -1;
        this.Ready = false;
        var scope = this;
             
        this.getSearches = function(){
            if($.cookie){
                var searchTerms = $.cookie('loc_recentSearches');
                if(searchTerms){
                    this._searches = new Array();
                    if(searchTerms.indexOf('|') > -1){
                        this._searches = searchTerms.split('|');
                    }else{
                        this._searches = [searchTerms];
                    }
                }
            }
        }
        this.getHTML = function(){
        var html = "<div class='title'><em>" + VM_SearchConfig.RecentSearchesText + ":</em></div>";
            var tmpIndex = 0;
            for(var x=this._searches.length - 1; x>=0; x--){
                html += "<a href='javascript:;' class='link' index='" + tmpIndex + "'>" + this._searches[x] + "</a>";
                tmpIndex++;
            }
            return html + $('#recentSearches').html();
        }
        this.writeLocationHTML = function(location){
            var html = "<div class='title'><em>" + VM_SearchConfig.AgentNearYouText + ":</em></div>";
            html += "<a href='" + VM_SearchConfig.SiteRoot + "/Results.aspx?csz=" + location + "' class='link' >" + location + "</a>";
            $('#recentSearches').html(html + "<br/>" + $('#recentSearches').html());
            
            $('#recentSearches .link').click(function(){
                $(".searchFormInput").val($(this).text());
                return false;
            });
            $('#recentSearches .link').hover(function(){
                    $(this).addClass('selected');
                }, function(){
                    $(this).removeClass('selected');
                });
            $('#recentSearches').fadeIn("fast");
        }
        this.loadSearches = function(){
            $('#recentSearches').html('');
            this.getLocationByIP();
            // if there are cookied past searches use them
            if(this._searches && this._searches.length > 0){
                this._index = -1;
                $('#recentSearches').html(this.getHTML());
                $('#recentSearches .link').click(function(){
                    $(".searchFormInput").val($(this).text());
                });
                $('#recentSearches .link').hover(function(){
                        scope.setSelection(parseInt($(this).attr('index')));
                    }, function(){});
                $('#recentSearches').fadeIn("fast");
                this.Ready = true;
            }
        }
        this.getLocationByIP = function(){
            // other look for a location based on the users IP
            var url = VM_SearchConfig.SiteRoot + "/services/LocatorProxy.asmx/GetLocationByIP?ip=" + VM_SearchConfig.VisitorIP;
            $.ajax({
                type: "GET",
                url: url,
                dataType: "xml",
                async: true,
                success: function(xml){
                    if($(xml).find("location").text() != ""){
                        scope.writeLocationHTML($(xml).find("location").text());
                    }
                },
                error: function(){}
            });
        }
        this.addSearch = function(searchTerm){
            var exists = false;
            if(this._searches){
                for(var x=0; x<this._searches.length; x++){
                    if(this._searches[x] == searchTerm){
                        exists = true;
                    }
                }
                if(!exists){
                    this._searches.push(searchTerm);
                }
            }else{
                this._searches = new Array();
                this._searches.push(searchTerm);
            }
            if(this._searches.length > 2){
                this._searches = this._searches.slice(1);
            }
            $.cookie('loc_recentSearches', this._searches.join('|'), {path: '/', expires: 30});
        }
        this.hide = function(){
            $('#recentSearches').fadeOut("fast");
        }
        this.moveSelection = function(increment){
            this.removeSelection();
            this._index += increment;
            this._index = (this._index < 0) ? 0 : this._index;
            this._index = (this._index > this._searches.length - 1) ? this._searches.length - 1 : this._index;
            this.addSelection();
        }
        this.setSelection = function(index){
            this.removeSelection();
            this._index = index;
            this.addSelection();
        }
        this.addSelection = function(){
            var selector = '#recentSearches .link:eq(' + this._index + ')';
            $(selector).addClass('selected');
        }
        this.removeSelection = function(){
            var selector = '#recentSearches .link:eq(' + this._index + ')';
            $(selector).removeClass('selected');
        }
        // initialize
        this._searches;
        this.getSearches();
        // if the page has results (without errors) this was a valid search and the input should be added as a recent search
        try{
            if(vm_loc_hasResults && $(".searchFormInput").val() != "" && $('.errorMessage').html() == ""){
                this.addSearch($(".searchFormInput").val());
            }
        }catch(ex){ 
            //this.getLocationByIP(); 
        }
        // if there is a loc_recentSearches cookie, then load the recent searches
        if($.cookie && $.cookie('loc_recentSearches')){
            this.loadSearches();
        }
    }
    $(".searchFormInput").focus(function(){
        if(!vm_recentSearches){
            vm_recentSearches = new RecentSearches();
        }else{
            vm_recentSearches.loadSearches();
        }
    });
    $(".searchFormInput").blur(function(){
        if(vm_recentSearches){
            vm_recentSearches.hide();
        }
    })
    $(".searchFormInput").keydown(function(e){
        if(vm_recentSearches && vm_recentSearches.Ready){
            if(e.keyCode == 40){
                vm_recentSearches.moveSelection(1);
                return false;
            }else if(e.keyCode == 38){
                vm_recentSearches.moveSelection(-1);
                return false;
            }else{
                vm_recentSearches.hide();
            }
        }
    });
    $(".searchFormInput").keypress(function(e){
        if(vm_recentSearches && vm_recentSearches._index > -1 && e.keyCode == 13){
            vm_recentSearches._index = -1;
            $('.searchFormInput').val($('#recentSearches .selected').text());
            vm_recentSearches.hide();
            return false;
        }
    });
}

// ----- Locator Metrics ----- //
function setupWebMetrics(){
    locatorMetrics();
    locatorCityStateMetrics();
    webMetricsCaptureSubmission();
}

function locatorMetrics() {
    $('.result').each(function() {
        var resultId = $(this).attr('id') + '_';
        $(this).find('a').click(function() {
            WebMetrics.Capture('click', resultId + $(this).attr('class'));
            return true;
        })
    })
}

// city state metrics
function locatorCityStateMetrics() {
    $('.citiesList li a').click(function() {
        var link = $(this).attr('href');
        link = link.substr(link.indexOf("csz=") + 4, link.length - link.indexOf("csz="));
        WebMetrics.Capture('click', 'CITYSTATE$' + link);
    })
}
// form submission data capturing and data mapping
function webMetricsCaptureSubmission(){
    if($('.searchFormInput').val() != ""){
        setTimeout("CaptureSubmission()", 5000);
    }
}
function CaptureSubmission(){
    var submissionData = '<object name="' + SubmissionMap.Name + '" type="' + VM_SearchConfig.Type + '">' + WebMetrics.RetrieveFormValuesById(SubmissionMap.Data) + '</object>';
    WebMetrics.Capture('submission', submissionData);
}
var SubmissionMap = {
    Name: 'Agent Search',
    Data: {
        agentCityStateZip: { id:'ctl00_searchForm_txt_csz', name:'ctl00$searchForm$txt_csz' },
        includeSurroundingArea: { id: 'ctl00_searchForm_chkSurroundingArea', name: 'ctl00$searchForm$chkSurroundingArea' },
        agentName: { id:'ctl00_searchForm_txt_name', name: 'ctl00$searchForm$txt_name'},
        limitToFinancialServices: { id: 'ctl00_searchForm_chkFinancialServices', name: 'ctl00$searchForm$chkFinancialServices' },
        limitLanguage: { id: 'ctl00_searchForm_ddLanguage', name: 'ctl00$searchForm$ddLanguage' },
        limitMILK: { id: 'ctl00_searchForm_chkMilk', name: 'ctl00$searchForm$chkMilk' }
    }
}

// ---- Results animation/highlighting ----- //
var initTop = 190;
function setupResults(){
    $('.result').each(function() {
        var link = "MapResults.aspx?" + window.location.toString().split("?")[1] + "&partyIdentifier=" + $(this).attr("id");
        var viewOnMapHTML = "<div class='viewOnMap' style='display: none;'><a title='" + vm_loc_trans_ClickToViewOnMap + "' href='" + link + "'>" + vm_loc_trans_ViewOnMap + "</a></div>";
        $(this).prepend(viewOnMapHTML);
        $('.viewOnMap').parent().css("position", "relative");

        $(this).hover(
            function() {
                $(this).addClass("over");
                LocMap_lightMarker($(this).attr("id"));
                $("#" + $(this).attr("id") + ' .viewOnMap').show();
            },
            function() {
                $(this).removeClass("over");
                LocMap_unlightMarker($(this).attr("id"));
                $("#" + $(this).attr("id") + ' .viewOnMap').hide();
            }
        );
    });
    $(window).scroll(function(){
        var offsetTop = $(window).scrollTop();
        if(offsetTop > initTop){
            offsetTop -= initTop;
            $("#sideBarMapWidget").animate({top: offsetTop + "px"}, { duration: 200, queue: false });
        }else{
            $("#sideBarMapWidget").animate({top: "0px"}, { duration: 200, queue: false });
        }
    });
}


function setupSearchForm(){
    $('.searchForm_submitButton').attr("disabled", false);
    $('.searchForm_submitButton').click(function() {
        if ($('.searchForm_agentName').val() != ""
                && $('.searchFormInput').val() == ""
                && !$('.chkbox_milk input').is(':checked')
                && !$('.chkbox_fs input').is(':checked')
                ) {
            var url = VM_SearchConfig.SiteRoot + "/services/LocatorProxy.asmx/GetNameCountsByRegion?locator=" + VM_SearchConfig.LocatorType + "&name=" + $('.searchForm_agentName').val();
            var valid = true;
            $('.searchForm_loadingImg').show();
            $.ajax({
                type: "GET",
                url: url,
                dataType: "xml",
                async: false,
                success: function(xml) {
                    if ($(xml).find("results").attr("numResults") > 20) {
                        valid = false;
                        showManyNamesAlert(xml);
                    } else if ($(xml).find("results").attr("numResults") == 0) {
                        valid = false;
                        showNoNamesAlert(xml);
                    }
                    $('.searchForm_loadingImg').hide();
                },
                error: function() { alert("error") }
            });
            if (!valid) {
                return false;
            }
        }
    });
}


function showManyNamesAlert(xml) {    
    var message = FormatString(VM_SearchConfig.NameModalResultsText, [$('.searchForm_agentName').val(), $(xml).find("results").attr("numResults")]);
    var links = "<div class='regions'>";
    $(xml).find("region").each(function(){
        var link = VM_SearchConfig.SiteRoot + "/Results.aspx?state=" + $(this).attr('code') + "&name=" + $('.searchForm_agentName').val();
        links += "<div class='region'><a href='" + link + "'>" + $(this).attr('name') + " <span class='count'>(" + $(this).attr('count') + ")</span></a></div>";
    });
    links += "</div><div class='clearBoth'></div>";
    var footerHTML = "<div class='footer'><a href='" + VM_SearchConfig.SiteRoot + "/Results.aspx?name=" + $('.searchForm_agentName').val() + "'>" + VM_SearchConfig.ViewFullResults + "</a></div>";
    popWin(message + links + footerHTML, "search_popWin");
}

function showNoNamesAlert(xml){            
    popWin(FormatString(VM_SearchConfig.NameModalNoResultsText, [$('.searchForm_agentName').val(), "0"]), "search_popWin");
}

// worker method to replace portions of a formatted string
// looks for ^ as positioning and replaces it with snippets in order of precedence
var FormatString = function(string, snippets) {
    var str = string.toString();
    for (var x = 0; x < snippets.length; x++) {
        var index = str.indexOf("^");
        var first = str.substr(0, index);
        var last = str.substr(index + 1, str.length);
        str = first + snippets[x] + last;
    }
    return str;
}

function setupFontSizing() {
    var fontSize = $.cookie('vm_fontSize');

    if (fontSize && fontSize != "") {
        $("#txtResize a").removeClass("selected");
        $("#txtResize ." + fontSize).addClass("selected");

        if (fontSize == 'small') {
            $("#template_contentBody").css("font-size", "80%");
        }
        else if (fontSize == 'large') {
            $("#template_contentBody").css("font-size", "140%");
        }
    }
    
    $("#txtResize a").click(function() {
        $("#txtResize a").removeClass("selected");
        $(this).addClass("selected");
        return false;
    });

    $("#txtResize .small").click(function() {
        $("#template_contentBody").css("font-size", "80%");
        $.cookie('vm_fontSize', 'small');
    });
    $("#txtResize .normal").click(function() {
        $("#template_contentBody").css("font-size", "100%");
        $.cookie('vm_fontSize', 'normal');
    });
    $("#txtResize .large").click(function() {
        $("#template_contentBody").css("font-size", "140%");
        $.cookie('vm_fontSize', 'large');
    });
}
