﻿var iPropPageCounter = 0;
var area = 1;
var SearchCity = '';
var SearchState = '';
var SearchCityTag = 0;
var SearchTags = '';
var SearchCurrentRoute = '';
var aprops = null;
var afilteredprops = null;
var aselectedfilters = [];
var aSearchTags = [];
var resultcopy = [];
var aselectedgroups = [];
var alltheids = "";
var OnlineOnly = false;
var nopropertiesfoundtext = "";
var CoverFlowPlatform = "";
var CoverFlowLivePlatform = "";
var StateSearchURL = "";
var iOffset = 0;
var i10xPageSize = 10;
var proxy = new ServiceProxy("/Ajax.aspx/");
var iw;
var totalprops = 0;
var domain = location.host.replace("www.", "").replace("wwm.", "");
var pathname = window.location.pathname;
var userHasFlash = null;
var totalRecords = 0;
var i10XPullSize = 20;
var statemap;
var layer;
var us;
var mapcolor = '#bc4c00';
var mapmouse = '#6C757A';
var tableid;
var infoWindow;
var GotoAuctionAlerts = false;
var isPastResults = false;
var thepage = null;
var bupdateTags = true;
var microsite = false;
var ancarousellink = null;
var ancarousellivelink = null;
//FLOW PLAYER
var playerLocation = '/Resources/swf/flowplayer-3.2.6.swf';
var backgroundText = '';
var bufferingStopped = false;
var isMute = false;

var favs = [];
var calreminders = [];
var recents = [];
var mappoints = [];
var infoWindow;
var ddlsortvalue=null;
var first_load = true;

try {
    node.ontouchstart = function (evt) {
        alert(evt.touches.length);
    };
} catch (e) { }

//On Doc ready Start
$(document).ready(function () {
    $.extend({
        getUrlVars: function () {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        },
        getUrlVar: function (name) {
            return $.getUrlVars()[name];
        }
    });

    //var tempuri = "https://" + location.hostname + location.pathname.substr(0, location.pathname.lastIndexOf("/")) + "/ajax.aspx/";

    //if (location.protocol == "https:") {

    //    proxy = new ServiceProxy(tempuri);
    //}
    //else {
    //    proxy = new ServiceProxy(tempuri);
    //}

    //if ($.cookie("showlogin")) {
    //
    //    $('#Slider_Menu').slideDown();
    //    $.cookie("showlogin", null);

    //}

    //Drop down list for sorting handler
    $('.SortList').change(function () {
        ddlsortvalue = $(this).val();
        iOffset = 0;
        getProperties();
    });

    //AUCTION ALERTS
    var aa = $.getUrlVar('aaa');
    var as = $.getUrlVar('as');

    if (aa != null || as != null) {
        GotoAuctionAlerts = true;
    }

    if (GotoAuctionAlerts == true) {
        ScrollToDiv('auction-alerts-wrapper');
    }

    //SEARCH Type - left of search keyword
    $("#searchtypebox").click(function () {
        $("#searchtypebox div").toggle();

        var st = "";
        st = $("#searchtypebox .whitetext:visible").text();

        $("#butMySearch").attr("searchtype", st);

        var ajaxURL = "/ajax.aspx/setSearchType";
        var temp = st == "current" ? "1" : "2";

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: ajaxURL,
            data: "{ 'iType':'" + temp + "'}",
            processData: false,
            dataType: "json",
            async: true,
            success: function (res) {
                //alert('success');
                if (temp == 2) {
                    if (location.pathname == "/real-estate-auction" || location.pathname == "/residential-real-estate-home-auction") {
                        window.location.href = "/auction-results";
                    }
                }
                else {
                    if (location.pathname == "/auction-results") {
                        window.location.href = "/real-estate-auction";
                    }
                }
            },
            error: function (err) {
                //alert(err);
            }
        });
    });

    //CONTACT US - Login panel
    $('div .contactclicklink').bind({
        click: function (event) {
            var prefix = "Full";
            if ($('div .contactclicklink').hasClass('activecontact')) {
                $('div .contactclicklink').removeClass('activecontact');
            }

            $(this).addClass("activecontact");
            var divid = $(this).attr("id");

            $("#ContactUs li").hide();  //hide all
            $("#" + prefix + divid).show();  //show selected
        }
    });

    //LOGIN Menu
    $('.loginmenu').bind({
        click: function (event) {
            event.preventDefault();

            //if (location.protocol != 'https:') {
            //    $.cookie("showlogin", "true");
            //    window.location.href = location.href.replace(location.protocol, 'https:');
            //}
            //else {






            $(this).toggleClass('activelogintab');

            var clickedid = $(this)[0].id;

            $('#Slider_Menu').slideDown();

            if ($(this).hasClass('activelogintab')) {
                //remove active from all
                $('.activelogintab').removeClass();
                $(this).addClass('activelogintab');

                switch (clickedid) {
                    case "signin":
                        $('#contactuscontent').hide();
                        $('#accountcontent').hide();
                        $('#logincontent').show();
                        break;
                    case "spanaccountcontent":
                        if (mguid != null) {
                            GetAccountInfo('accountcontent');
                            $('#contactuscontent').hide();
                            $('#accountcontent').show();
                            $('#logincontent').hide();
                        }
                        else {
                            $('#contactuscontent').hide();
                            $('#accountcontent').hide();
                            $('#logincontent').show();
                        }
                        break;
                    case "spancontactuscontent":
                        $('#accountcontent').hide();
                        $('#logincontent').hide();
                        $('#contactuscontent').show();
                        $('#GeneralContactDetails').show();
                        break;
                    default:
                        break;
                }

                if (clickedid != "spancontactuscontent") {
                    $('#GeneralContactDetails').hide();
                }
                $('#btnclose').delay(300).fadeIn(700);
            }
            else {
                $('#Slider_Menu').slideUp();
                $('#accountcontent').hide();
                $('#logincontent').hide();
                $('#contactuscontent').hide();
                $('#btnclose').hide();
            }
        }
        //}
    });

    //MICROSITE
    if (!microsite) {
        $('body img').css('border', 'none');
    }

    //GENERAL
    if (FlashDetect.versionAtLeast(9)) {
        userHasFlash = true;
    } else {
        userHasFlash = false;
    }

    /*Catch enter key for logging in etc*/
    var event2key = { '13': 'enter' },
    e2key = function (e) { return event2key[(e.which || e.keyCode)] || ''; };

    pageKey = function (event) {
        switch (e2key(event)) {
            case 'enter':
                event.preventDefault();
                if ($("#Slider_Menu").css('display') == 'block') {
                    if ($("#logincontent").css('display') == 'block') {

                        var disablesub = false;
                        if ($('#email').val().length > 0) { //&& $('#password').val().length > 0) 
                            $('#login').trigger("click");
                            disablesub = true;
                        }
                        else if ($("#forgotemail").val().length > 0) {
                            $('#forgot').trigger("click");
                            disablesub = true;
                        }
                    }
                    if (disablesub) { event.preventDefault(); }
                } //catch enter key for search box
                else if ($(".searchtxtbox").is(":focus")) {
                    $("#butMySearch").trigger("click");
                    return false;
                }
                break;
        }
    };

    $(document)
    .focus()
    .bind('keydown', pageKey);
    /*End Catch enter Key*/

    //LOGIN - FORGOT PASSWORD CLICK EVENT
    $('#login').click(login);
    $('#forgot').click(forgot);

    $("#overlayx").overlay({
        mask: {
            color: '#000000',
            loadSpeed: 200,
            opacity: 0.8
        },
        closeOnClick: true,
        load: false
    });

    $('.mktabs').tabs();

    //region IMG Redirect
    $("img.LightboxImage").click(function () {
        return LoadLightbox(this, $("#" + this.id).attr("longdesc"), $("#" + this.id).attr("class").split(' ')[2]);
    });

    $("img.PopupImage").click(function () {
        return LoadPopup($("#" + this.id).attr("longdesc"), $("#" + this.id).attr("class").split(' ')[2]);
    });

    $("img.BlankLoadingImage").click(function () {
        return LoadBlankLoading($("#" + this.id).attr("longdesc"), $("#" + this.id).attr("alt"));
    });

    $("img.SelfLoadingImage").click(function () {
        return LoadSelfLoading($("#" + this.id).attr("longdesc"));
    });

    //region ANCHOR redirect
    $("a.LightboxAnchor").click(function () {
        return LoadLightbox($("#" + this.id).attr("href"), $("#" + this.id).attr("class").split(' ')[2]);
    });

    $("a.PopupAnchor").click(function () {
        return LoadPopup($("#" + this.id).attr("href"), $("#" + this.id).attr("class").split(' ')[2]);
    });

    $("a.BlankLoadingAnchor").click(function () {
        return LoadBlankLoading($("#" + this.id).attr("href"));
    });

    $("a.SelfLoadingAnchor").click(function () {
        return LoadSelfLoading($("#" + this.id).attr("href"));
    });


    //region DIV Redirect
    $("div.LightboxDiv").click(function () {
        return LoadLightbox(this, $("#" + this.id).attr("uri"), $("#" + this.id).attr("class").split(' ')[2]);
    });

    $("div.SelfLoadingDiv").click(function () {
        return LoadSelfLoading($("#" + this.id).attr("uri"));
    });

    $("div.BlankLoadingDiv").click(function () {
        return LoadBlankLoading($("#" + this.id).attr("uri"));
    });

    $("div.PopupDiv").click(function () {
        return LoadPopup($("#" + this.id).attr("uri"), $("#" + this.id).attr("class").split(' ')[2]);
    });

    $('.linklistitem').bind({
        mouseenter: function () { $(this).css({ 'cursor': 'pointer', 'background-image': 'url(/Resources/images/linklist/Dark1x.png)' }); },
        mouseleave: function () { $(this).css({ 'cursor': 'auto', 'background-image': 'url(/resources/images/linklist/linklistitem1x.png)' }); }
    });


    $('.contactcardmain').bind({
        click: function () {
            $.get('/Bio_Popup.aspx', { id: $(this).attr('cid') }, function (data) {
                loadBio(data);
            });
        }
    });

    $('.contactcardsmallmain').bind({
        click: function () {
            $.get('/Bio_Popup.aspx', { id: $(this).attr('cid') }, function (data) {
                loadBio(data);
            });
        }
    });

    //Property page ad
    $('#onsiteonlineonly, #bidonsiteonly').bind({
        click: function () {
            $.get('/resources/popup/bidonsite.aspx', { id: $(this).attr('cid') }, function (data) {
                loadPopupBox(data, '100px', '400px');
            });
        }
    });

    //PENCIL ADS
    $('.pencilad').css('visibility', 'visible').fadeIn("slow", function () {
        $(this).bind({
            mouseenter: function () {
                $(this)
                .stop(true, true)
                .delay(550)
                .animate({ "height": "150px" }, "slow");
            },
            mouseleave: function () {
                $(this)
                .clearQueue()
                .stop(true, true)
                .animate({ "height": "42px" }, "slow");
            }
        });
    });

    $('#dockAd1').css('visibility', 'visible').fadeIn("slow", function () {
        $(this).bind({
            mouseenter: function () {
                $(this)
                .stop(true, true)
                .delay(550)
                .animate({ "height": "150px" }, "slow");
            },
            mouseleave: function () {
                $(this)
                .clearQueue()
                .stop(true, true)
                .animate({ "height": "42px" }, "slow");
            }
        });
    });

    $('#dockAd2').css('visibility', 'visible').fadeIn("slow", function () {
        $(this).bind({
            mouseenter: function () {
                $(this)
                .stop(true, true)
                .delay(550)
                .animate({ "height": "150px" }, "slow");
            },
            mouseleave: function () {
                $(this)
                .clearQueue()
                .stop(true, true)
                .animate({ "height": "42px" }, "slow");
            }
        });
    });

    //DISPLAY NAME
    if ($("#DisplayName").text() == "") {
        $('#signout').hide();
        $('#signin').show();
    }
    else {
        $('#signin').hide();
        $('#signout').show();
    }

    $.ajaxSetup({ timeout: 40000 });

    $(".uni input, .uni textarea, .uni select, .uni button").uniform();

    $('#newsholder').bind('initialized slide_complete slide_init',
            function (e, slider) {
                $('#newscontrolstop').html('<a href="#"  id="newsleft"><img style="border:none" src="/Resources/images/10x/orange_arrow_left.gif"></a> Page ' + slider.currentPage + ' of ' + slider.pages + ' <a href="#" id="newsright"><img style="border:none" src="/Resources/images/10x/orange_arrow_right.gif"></a>');

                $('#newsleft').click(function (event) {
                    event.preventDefault();
                    $('#newsholder').data('AnythingSlider').goBack();      // go forward one slide
                });

                $('#newsright').click(function (event) {
                    event.preventDefault();
                    $('#newsholder').data('AnythingSlider').goForward();
                });

            });

    $('#holder').bind('slideshow_start slideshow_stop slideshow_paused slideshow_unpaused slide_init slide_begin slide_complete',
            function (e, slider) {
                if (slider.pages > 1) {
                    if (isPastResults) {

                        if (thepage == null) {
                            thepage = 1;
                            $('.pager').pagination(totalprops, { num_display_entries: 5, prev_text: '<<', next_text: '>>', num_edge_entries: 1, load_first_page: false, items_per_page: i10xPageSize, callback: handlePageClick, link_to: 'javascript:void(0);' });
                            //$('#controlsbottom').pagination(totalprops, { num_display_entries: 5, prev_text: '<<', next_text: '>>', num_edge_entries: 1, load_first_page: false, items_per_page: i10xPageSize, callback: handlePageClick, link_to: 'javascript:void(0);' });
                        }

                    } else {

                        if (thepage == null) {
                            thepage = 1;
                            $('.pager').pagination(totalprops, { num_display_entries: 5, prev_text: '<<', next_text: '>>', num_edge_entries: 1, load_first_page: false, items_per_page: i10xPageSize, callback: handlePageClick, link_to: 'javascript:void(0);' });
                           // $('#controlsbottom').pagination(totalprops, { num_display_entries: 5, prev_text: '<<', next_text: '>>', num_edge_entries: 1, load_first_page: false, items_per_page: i10xPageSize, callback: handlePageClick, link_to: 'javascript:void(0);' });
                        }
                    }
                }
                if (slider.pages == 1) {
                    $("#controlstop").html("");
                    $("#controlsbottom").html("");
                }
            });

    $("#holder").delegate('div.gradient', 'mouseenter mouseleave', function (event) {
        if (event.type == 'mouseenter') {
            var iheight = $(this).data("oheight") + 'px';
            $(this)
            .stop(true, true)
            .animate({ backgroundColor: "#FBFFEA" }, 250)
            .delay(250)
            .animate({ height: iheight }, 1000);
        } else {

            $(this)
            .clearQueue()
            .stop(true, true)
            .animate({ backgroundColor: "transparent", height: '110px' }, 1000);
        }
    });

    $('.spinner')
        .ajaxStart(function () { $(this).show(); })
        .ajaxStop(function () { $(this).fadeOut(); });

    $(".gradientarticle").live({
        mouseenter: function () {
            $(this)
            .stop(true, true)
            .animate({ backgroundColor: "#FBFFEA" }, 250);
        },
        mouseleave: function () {
            $(this)
            .clearQueue()
            .stop(true, true)
            .animate({ backgroundColor: "transparent" }, 1000);
        }
    });

    $("#statelist").delegate('#stateareafilter', 'change', function (event) {
        if ($(this).get(0).selectedIndex > 0) {
            SearchCity = '';
            SearchState = $('#stateareafilter option:selected').text();
            iOffset = 0;
            bupdateTags = false;
            thepage = 0;
            totalprops = 0;
            aprops = [];
            $('#citylist').show();
            getPastProperties();

        }
        else {
            SearchCity = '';
            SearchState = '';
            iOffset = 0;
            bupdateTags = false;
            thepage = 0;
            totalprops = 0;
            aprops = [];
            $('#citylist').hide();
            getPastProperties();
        }
    });

    $("#citylist").delegate('#cityareafilter', 'change', function (event) {
        if ($(this).get(0).selectedIndex > 0) {
            SearchCity = $('#cityareafilter option:selected').text();
            iOffset = 0;
            bupdateTags = false;
            thepage = 0;
            totalprops = 0;
            aprops = [];
            getPastProperties();
        }
        else {
            iOffset = 0;
            bupdateTags = false;
            thepage = 0;
            totalprops = 0;
            aprops = [];
            SearchCity = '';
            getPastProperties();

        }

    });

    $('#ajaxerrorconfirm').click(function () {
        $.unblockUI();
        return false;
    });
    $('#ajaxconfirm').click(function () {
        $.unblockUI();
        return false;
    });


    //MY ACCOUNT ----------------------------------------
    if (favs.length > 0) {
        loadFavs();
    }
    if (recents.length > 0) {
        loadRecents();
    }

    $('.myaccountpropertylink').live({
        mouseenter: function () {
            $(this).css("cursor", "hand");
        },
        mouseleave: function () {
            $(this).css("cursor", "pointer");
        },
        click: function () {
            window.location = $(this).attr('url');
            return false;
        }
    });

    //Map -----
    bRunFun = true;

    //SEARCH/MAP - mouse over search buttons image switch
    $(".searchbar_calendar")
        .mouseover(function () {
            var src = $(this).attr("src").replace("calendarsearch", "calsearchdk");
            $(this).attr("src", src);
        })
        .mouseout(function () {
            var src = $(this).attr("src").replace("calsearchdk", "calendarsearch");
            $(this).attr("src", src);
        });

    $(".searchbar_us")
        .mouseover(function () {
            var src = $(this).attr("src").replace("mapsearch", "mapsearchdk");
            $(this).attr("src", src);
        })
        .mouseout(function () {
            var src = $(this).attr("src").replace("mapsearchdk", "mapsearch");
            $(this).attr("src", src);
        });

    $(".live_now")
        .mouseover(function () {
            var src = $(this).attr("src").replace("liveaucnow", "liveaucnowdk");
            $(this).attr("src", src);
        })
        .mouseout(function () {
            var src = $(this).attr("src").replace("liveaucnowdk", "liveaucnow");
            $(this).attr("src", src);
        });

    //Calendar dropdown
    $(".searchbar_calendar").click(function () {
        var isHidden = $('#calendardrawer').is(':hidden');
        //hide map
        var isMapHidden = $('#imgmapdrawer').is(':hidden');
        if (!isMapHidden) {
            $('#imgmapdrawer').hide();
        }

        if (isHidden) {
            $('#calendardrawer').show();
        }
        else {
            $('#calendardrawer').hide();
        }

        $("#calsearchbtn")
        .mouseover(function () {
            var src = $(this).attr("src").replace("calsearch.png", "calsearchover.png");
            $(this).attr("src", src);
        })
        .mouseout(function () {
            var src = $(this).attr("src").replace("calsearchover.png", "calsearch.png");
            $(this).attr("src", src);
        });
    });

    $(".searchbar_us").click(function () {
        //hide cal
        var isCalHidden = $('#calendardrawer').is(':hidden');
        if (!isCalHidden) {
            $('#calendardrawer').hide();
        }
        var isHidden = $('#imgmapdrawer').is(':hidden');

        if (isHidden) {
            $('#imgmapdrawer').show();

            onMapReady();
        }
        else {
            $('#imgmapdrawer').hide();
        }
    });

    $("area[title]").tooltip({ effect: 'slide' }).dynamic({ bottom: { direction: 'down', bounce: true} });

    //SEARCH BAR ----------------------------------------
    $("#DisplayName").hide().animate({
        "left": "10px",
        "opacity": "toggle"
    }, 3000);

    //FAVS/REMINDERS/RECENTS   
    calreminder.prototype = new calreminder;
    recent.prototype = new recent;
    fav.prototype = new fav;

    /*wmg tabs*/
    var tabvalue = $.cookie("wmgtabs");

    if (tabvalue == "2") {
        $('.maintab1.ui-tabs-nav').tabs('select', 1);
        $('#container-1').css("background-image", "url(/app_themes/wmg/images/bodybling/sample1.png)");
        $('#fragment-2').removeClass('ui-tabs-hide');
        $('#fragment-1').addClass('ui-tabs-hide');
    }
    else {
        $('.maintab1.ui-tabs-nav').tabs('select', 0);
        $('#container-1').css("background-image", "url(/app_themes/wmg/images/bodybling/current.png)");
        $('#fragment-1').removeClass('ui-tabs-hide');
        $('#fragment-2').addClass('ui-tabs-hide');
    }

    $('.maintab1 .current').click(function () {
        $.cookie('wmgtabs', "1", { expires: -1, path: '/', domain: domain, secure: false });
        $.cookie('wmgtabs', "1", { expires: 1, path: '/', domain: domain, secure: false });

        $('#container-1').css("background-image", "url(/app_themes/wmg/images/bodybling/current.png)");
        $('#fragment-1').removeClass('ui-tabs-hide');
        $('#fragment-2').addClass('ui-tabs-hide');
    });

    $('.maintab1 .sample').click(function () {
        $.cookie('wmgtabs', "2", { expires: -1, path: '/', domain: domain, secure: false });
        $.cookie('wmgtabs', "2", { expires: 1, path: '/', domain: domain, secure: false });
        $('#container-1').css("background-image", "url(/app_themes/wmg/images/bodybling/sample1.png)");
        $('#fragment-2').removeClass('ui-tabs-hide');
        $('#fragment-1').addClass('ui-tabs-hide');
    });



    //Load DIALOGS
    var email = $("#txtFriendEmail"),
            username = $("#txtName"),
            commentText = $("#txtComment"),
            lnk = window.location,
            allFieldsSend = $([]).add(lnk).add(email).add(username).add(commentText),
                     tips = $(".validateSendTips");

    var usernameSI = $("#usernamepop"),
			passwordSI = $("#passwordpop"),
			allFieldsSI = $([]).add(usernameSI).add(passwordSI),
			tipsSignIn = $(".validateSignInTips");

    var sendType = '';

    var emailFP = $("#forgotemailpop"),
			allFieldsFP = $([]).add(emailFP),
			tipsFP = $(".validateForgotTips");

    $("#dialog-send").dialog({
        autoOpen: false,
        height: 465,
        width: 365,
        modal: true,
        resizable: false,
        hide: 'slide',
        buttons: {
            Cancel: function () {
                $(this).dialog('close');
                $('.ui-dialog :button').blur();
            },
            'Send': function () {
                var bValid = true;
                allFieldsSend.removeClass("ui-state-error");

                bValid = bValid && checkEmail(email, "email");
                bValid = bValid && checkName(username, "username");
                if (bValid) {
                    handleSendDialog(lnk, email, username, commentText);
                }
                $('.ui-dialog :button').blur();
            }
        },
        create: function (event, ui) {
            $('.ui-dialog').wrap('<div class="wwgrey" />');
        },
        open: function (event, ui) {
            $('.ui-widget-overlay').wrap('<div class="wwgrey" />');
        },
        close: function () {
            allFieldsSend.val("").removeClass("ui-state-error");
        }
    });

    $("#dialog-signin").dialog({
        autoOpen: false,
        height: 390,
        width: 500,
        modal: true,
        resizable: false,
        buttons: {
            Cancel: function () {
                $(this).dialog('close');
                $('.ui-dialog :button').blur();
            },
            'Forgot Login': function () {
                $(this).dialog('close');
                openForgotDialog();
                $('.ui-dialog :button').blur();
            },
            'Create Account': function () {
                //$.cookie("DestinationLOC");
                var urlprops = pathname.split('/');
                var propid = urlprops[urlprops.length - 1];

                window.location = "/profile?redir=" + propid;
                $(this).dialog('close');
                $('.ui-dialog :button').blur();
            },
            'Sign In': function () {
                var bValid = true;
                allFieldsSI.removeClass("ui-state-error");

                bValid = bValid && checkUsername(usernameSI, "username");
                bValid = bValid && checkPassword(passwordSI, "password");

                if (bValid) {
                    handleLoginDialog(usernameSI.val(), passwordSI.val());
                }
                $('.ui-dialog :button').blur();
            }
        },
        create: function (event, ui) {
            $(this).wrap('<div class="auctionnet" />');
        },
        open: function (event, ui) {
            $(this).wrap('<div class="auctionnet" />');
        },
        close: function () {
            allFieldsSI.val("").removeClass("ui-state-error");
        }
    });

    $("#dialog-signedin").dialog({
        autoOpen: false,
        height: 250,
        width: 365,
        modal: true,
        resizable: false,
        hide: 'slide',
        buttons: {
            Cancel: function () {
                $(this).dialog('close');
                $('.ui-dialog :button').blur();
            },
            'Continue': function () {
                //redirect to AN
                var destLoc = $.cookie("DestinationLOC");
                $.cookie('DestinationLOC', destLoc, { expires: -1, path: '/', domain: domain, secure: false });
                if (destLoc != null && destLoc != "")
                    window.location.href = destLoc;
            }
        },
        create: function (event, ui) {
            $('.ui-dialog').wrap('<div class="auctionnet" />');
        },
        open: function (event, ui) {
            $('.ui-widget-overlay').wrap('<div class="auctionnet" />');
        },
        close: function () {
            allFieldsSend.val("").removeClass("ui-state-error");
        }
    });

    $("#dialog-forgot").dialog({
        autoOpen: false,
        height: 335,
        width: 350,
        modal: true,
        resizable: false,
        buttons: {
            Cancel: function () {
                $(this).dialog('close');
                $('.ui-dialog :button').blur();
            },
            'Submit': function () {
                var bValid = true;
                allFieldsFP.removeClass("ui-state-error");

                bValid = bValid && checkEmailFP(emailFP, "email");

                if (bValid) {
                    handleForgotDialog(emailFP);
                }
                $('.ui-dialog :button').blur();
            }
        },
        create: function (event, ui) {
            $('.ui-dialog').wrap('<div class="auctionnet" />');
        },
        open: function (event, ui) {
            $('.ui-widget-overlay').wrap('<div class="auctionnet" />');
        },
        close: function () {
            allFieldsFP.val("").removeClass("ui-state-error");
        }
    });

    //MAIN MENU NAV
    $("#divSubNavItems > div").hide();
    $('#ulNavList li .menuinner').not('#home').bind({
        mouseover: function (event) {
            if ($('#ulNavList li').hasClass('activetab')) {
                $('#ulNavList li').removeClass('activetab');
            }

            $(this).closest("li").addClass("activetab");

            var link = $(this).parent().attr("href");

            if (link != null) {
                var linkto = $(this).closest("li").attr("id");
                linkto = linkto.replace("main", "");

                $('.tertiary').stop(true, true).delay(250).slideUp('slow', function () {
                });

                $("#divSubNavItems > div").hide();

                //skip items with no sub items
                if ($('#' + linkto + '').text().length > 0) {

                    $(".tertiary").stop(true, true).delay(250).slideDown('slow', function () {
                    });
                    $('#' + linkto + '').show();
                }
            }
        },
        mouseleave: function () {
            $(".tertiary").clearQueue();
        }
    });

    //Set Menu Items Cookie
    var menucookie = $.cookie('MainMenuItem');
    if (menucookie != null) {
        $('#main' + menucookie).addClass("activetab");
        menucookie = null;
    }
    else {  //set default
        if ($('#ulNavList li').hasClass('activetab')) {
            $('#ulNavList li').removeClass('activetab');
        }
        $('#mainBUY').addClass("activetab");
    }

    $('.mclass').bind({
        click: function (event) {
            var coo = $.cookie('MainMenuItem');
            $.cookie('MainMenuItem', coo, { expires: -1, path: '/', domain: domain, secure: false });
            $.cookie('MainMenuItem', $(this).attr('mitem'), { expires: 1, path: '/', domain: domain, secure: false });
        }
    });

    //Bind Tertiary
    $(".tertiary").bind({
        mouseenter: function () {
            $(".tertiary").stop(true, true).slideDown('slow', function () {
            });
        },
        mouseleave: function () {
            $('.tertiary').delay(900).slideUp(900);
        }
    });

    //If it is on the property detail page -> keep track of images selected
    if (pathname.toLowerCase().indexOf("property-auctions") >= 0) {
        $('#innerdiv img').bind("load", function (e) {
            //TrackImages(pathname, this.src, pathname.substring(pathname.length - 6, pathname.length));;
            fid = this.id;
            TrackImages(fid);
        })
    }

});                          //On Doc Ready END

//FUNCTIONS START

function TrackImages(fid) {
    //alert('LinkName:' + pathname + "\n Image:" + imgpath + "\n PropertyID:" + pathname.substring(pathname.length - 6, pathname.length));
    // alert(fid);
    /*proxy.invoke("TrackImages", {'sURL':url, 'iPath':imgpath, 'pID':pid },
    function (result) {
                    
    },
    function (error) {
    //alert(error);
    });*/
}

function LoadLightbox(obj, url, hw) {
    var hwsplit = hw.split('X');
    hs.src = url;
    hs.graphicsDir = '/Admin/CMS/Scripts/highslide-4.1.12/highslide/graphics/';
    hs.htmlExpand(obj, { objectType: 'iframe', height: hwsplit[0], width: hwsplit[1] });
    return false;
}

function LoadPopup(url, hw) {
    var hwsplit = hw.split('X');
    hs.src = url;
    window.open(url, 'mywindow', 'width=' + hwsplit[1] + ',height=' + hwsplit[1]);
    return false;
}

function LoadSelfLoading(url) {
    window.location = url;
    return false;
}

function LoadBlankLoading(url) {
    window.open(url, 'mywindow', 'toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
    return false;
}

function ScrollToDiv(divname) {
    if ($("#" + divname) == undefined) {
    } else {
        $('html,body').animate({
            scrollTop: $("#" + divname).offset().top
        }, 0);
    }
}

function ShowGeneralPopup(i) {

    var msg;
    switch (i) {
        case 1:
            msg = "<p style=\"text-align:left;font-size:12px;\"><b style=\"color: #ef6d22; font-size: 14px;\">Certified Funds Required</b><br />" +
            "<br />Each high bidder must make a 5% non-refundable deposit per property ($2,500 MINIMUM - whichever is greater) immediately following auction. <b>Buyer will be required to" +
            "tender a minimum of $2500 down payment in cash, certified funds or corporate check. Certified funds should be made payable to the order of the buyer.</b> The remainder" +
            " of the 5% deposit may be made with cash, cashier's checks, personal checks and business checks (electronically processed).<br />" +
            "<br />If you are a resident / citizen of a country outside of the US, certified funds (bank check, wire transfer, certified checks) are required for the down payment " +
            " and closing. The balance of the purchase price and all closing costs are due at closing. Closing costs generally total approximately $1,500 and include title exam," +
            "title policy, closing fee, filing costs and any other fees noted. If for any reason Seller does not perform or accept the terms of the Contract, the sole remedy shall" +
            "be the return of Buyer's deposit.</p>";
            break;

    }
    $.blockUI({ message: "<div style='font-size:15px;margin-top:25px;'>" + msg + "<br><br><br><br><div id='closeprofilecomplete' onclick='$.unblockUI();return false;'>Close</div></div>", css: { cursor: 'pointer', left: '25%', top: '15%', padding: '15px' }, overlayCSS: { cursor: 'pointer', backgroundColor: '#fff', opacity: 0.8} });
    return false;
}
function ShowMissingFieldsPopup() {
    $.blockUI({ message: "<div style='font-size:15px;margin-top:25px;'>We need a few additional pieces of information to update your registration.<br/><br/>Please complete the following form and your registration will be complete!<br/><br/><br/><br/><div id='closeprofilecomplete' onclick='$.unblockUI();return false;'>Close</div></div>", css: { cursor: 'pointer', left: '25%', top: '15%', width: '500px', height: '200px', padding: '15px' }, overlayCSS: { cursor: 'pointer', backgroundColor: '#fff', opacity: 0.8} });
}

function loadBio(item) {
    $.blockUI({ message: item, css: { cursor: 'pointer', left: '25%', top: '15%', width: '760px', height: '400px', padding: '15px' }, overlayCSS: { cursor: 'pointer', backgroundColor: '#fff', opacity: 0.8} });
    $('.blockOverlay').click($.unblockUI);
}

function loadPopupBox(item, h, w) {
    $.blockUI({ message: item, css: { cursor: 'pointer',  width: w, height: h, padding: '15px' }, overlayCSS: { cursor: 'pointer', backgroundColor: '#fff', opacity: 0.8} });
    $('.blockOverlay').click($.unblockUI);
}

function loadFavs() {
    $('#favs').html('');

    for (var i = 0; i < (favs.length > 3 ? 3 : favs.length); i++) {
        $('#favs').append(formatItem(favs[i]));
    }
}

function loadRecents() {
    $('#recents').html('');

    for (var i = 0; i < (recents.length > 3 ? 3 : recents.length); i++) {
        $('#recents').append(formatItem(recents[i]));
    }
}

function resetAuctionStatus() {
    $("#searchtypebox div").toggle();
    var st = "current";

    $("#butMySearch").attr("searchtype", st);

    var ajaxURL = "/ajax.aspx/setSearchType";

    var temp = st == "current" ? "1" : "2";

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: ajaxURL,
        data: "{ 'iType':'" + temp + "'}",
        processData: false,
        dataType: "json",
        async: true,
        success: function (res) {
            //alert('success');
            if (temp == 2) {
                if (location.pathname == "/real-estate-auction" || location.pathname == "/residential-real-estate-home-auction") {
                    window.location.href = "/auction-results";
                }
            }
            else {
                if (location.pathname == "/auction-results") {

                    window.location.href = "/real-estate-auction";
                }
            }
        },
        error: function (err) {
            //alert(err);
        }
    });
}

function navigatetopage(pagevalue) {
    var pageurl = pagevalue;
    alert("function navigatetopage " + pageurl + "");
}

function overlayiframe(value) {
    var newurl = value;
    alert("function overlayiframe " + newurl + "");
    $("#overlayx").data("overlay").load();
}

function StartupCarousel() {
    var flashvars = {};
    flashvars.crossdomainxmlurl = "http://naveenve.cachefly.net/crossdomain.xml";
    flashvars.crossdomainurl = "http://naveenve.cachefly.net";

    flashvars.playlistxmlurl = ancarousellink + CoverFlowPlatform + "-";
    flashvars.livexmlurl = ancarousellivelink + CoverFlowPlatform + "-";

    var params = { AllowScriptAccess: "always", wmode: "transparent", menu: "false" };

    swfobject.embedSWF("/coverflow/CoverFlow_FlexControls5.swf", "myContent", "100%", "315", "9.0.0", "expressInstall.swf", flashvars, params);
}

function RemoveFavorite(fid, o) {
    if (mguid != null) {
        if (confirm('Are you sure you want to delete this favorite?')) {
            proxy.invoke("RemoveFavorite", { 'pID': fid, 'sAddress': null, 'sURL': null },
                function (result) {
                    if (result) {
                        $(o).remove();
                    }
                },
                function (error) {
                    // alert("RemoveFavoriteError:" + error.message);
                });
        }
    } else {
        $('html, body').animate({ scrollTop: 0 }, 'slow');
        show('logincontent');
    }
}

function RemoveSavedSearch(sid, o) {
    if (mguid != null) {
        if (confirm('Are you sure you want to delete this saved search?')) {
            proxy.invoke("deleteSearch", { 'sID': sid },
                function (result) {

                    if (result) {
                        $(o).remove();
                    }
                },
                function (error) {
                    //alert("GetRecentsError:" + error.message);
                }
            );
        }
    } else {
        $('html, body').animate({ scrollTop: 0 }, 'slow');
        show('logincontent');
    }
}

function SendEmailCall() {
    proxy.invoke("SendEmailForm", { 'formVars': $("#form1").serializeArray(), 'format': 'test' },
            function (result) {
                if (result) {
                    alert("Your message was sent. Thank you.");
                }
            }, function (error) {
                alert("There was an error sending your message. Support has been notifed.");
            });
}

function saveSearch() {
    if (mguid != null) {
        proxy.invoke("saveSearch", { 'sURI': BuildSaveSearchURL(), 'smid': mguid, 'sName': $('#searchname').val() },
            function (result) {
                if (result) {
                    $('#ajaxstatement').html("Search has been saved. You can view your saved searches by clicking 'My Account' from the menu at the top of the screen.");
                    $('#ajaxdialog').toggleClass('ajaxdialogsuccess', true);
                    $('#ajaxconfirm').css('display', 'block');
                    $.blockUI({
                        overlayCSS: { backgroundColor: '#fff' },
                        message: $('#ajaxdialog'),
                        css: {
                            border: '1px solid #c0c0c0',
                            opacity: .8
                        }
                    });
                }
            },
            function (error) {
                //alert("GetRecentsError:" + error.message);
            });
    } else {
        $('html, body').animate({ scrollTop: 0 }, 'slow');
        show('logincontent');
    }
}

function resize() {
    var width = $(window.viewport).width();
    if (width < 880) { width = 880; }
    $('#dockAd1').animate({ 'left': Math.floor((width - ($('#dockAd1').outerWidth())) / 2)
    }, "slow");
    $('#dockAd2').animate({ 'left': Math.floor((width - ($('#dockAd2').outerWidth())) / 2)
    }, "slow");
}

//HEADER Slide down sign/in Menu ----------------------------------------
function isLoggedIn() {
    return mguid != null ? true : false;
}


function mappointsholder(state, points) {
    this.state = state;
    this.points = points;
}

function prop(pid, addr, imgurl, linkurl, lat, lon) {
    this.pid = pid;
    this.addr = addr;
    this.imgurl = imgurl;
    this.linkurl = linkurl;
    this.lat = lat;
    this.lon = lon;
}


function recent(pid, addr, imgurl, linkurl) {
    this.pid = pid;
    this.addr = addr;
    this.imgurl = imgurl;
    this.linkurl = linkurl;
}

function fav(pid, addr, imgurl, linkurl) {
    this.pid = pid;
    this.addr = addr;
    this.imgurl = imgurl;
    this.linkurl = linkurl;
}

function calreminder(pid, startdate, enddate, addr, img, linkurl) {
    this.pid = pid;
    this.startdate = startdate;
    this.enddate = enddate;
    this.addr = addr;
    this.img = img;
    this.linkurl = linkurl;
}

function checkifexists(pid, type) {
    switch (type) {
        case "fav":
            for (var i = 0; i < favs.length; i++) {
                if (pid == favs[i].pid) {
                    //alert("found a match " + pid + "=" + properties[i].pid);
                    return true;
                }
            }
            return false;
            break;
        case "reminder":
            for (var i = 0; i < calreminders.length; i++) {
                if (pid == calreminders[i].pid) {
                    //alert("found a match " + pid + "=" + properties[i].pid);
                    return true;
                }
            }
            return false;
            break;
        case "recent":
            for (var i = 0; i < recents.length; i++) {
                if (pid == recents[i].pid) {
                    //alert("found a match " + pid + "=" + properties[i].pid);
                    return true;
                }
            }
            return false;
            break;
    }
}

function SlideLoginOpen() {
    hs.close();  //close any popups
    $('body').animate({ scrollTop: 0 });
    $('#Slider_Menu').slideDown('slow', function () {
    });
    $('#btnclose').show();
}

function SlideLoginClose() {
    $('#Slider_Menu').slideToggle('slow', function () {
    });
    $('#btnclose').hide();
}

function GetAccountInfo(panel) {
    proxy.invoke("GetFavorites", { 'sFavURL': sfavurl },
            function (result) {
                if (result.length > 0) {
                    $('#favs').empty();
                    $.tmpl(favsTemplate, result).appendTo("#favs");
                    $('#' + panel).show();
                    //alert($('#favs').html());
                } else {
                    $('#favs').empty();
                    $('#favs').html('<b>You do not have any properties added to your favorites at this time</b>');
                    $('#viewallfavscontainer').hide();
                }
            },
            function (error) {
            });

    proxy.invoke("GetSavedSearches", { 'iLim': 5, 'smid': mguid },
            function (result) {
                if (result.length > 0) {
                    $('#savedsearches').empty();
                    $("#savedSearchesTemplate").tmpl(
                        result, {
                            dataArrayIndex: function (item) {
                                return $.inArray(item, result);
                            }
                        }).appendTo("#savedsearches");

                    $('#' + panel).show();
                }
                else {
                    $('#savedsearches').empty();
                    $('#savedsearches').html('<b>You do not have any searches saved at this time.</b>');
                    $('#viewallsavedsearchescontainer').hide();
                }
            },
            function (error) {
            });

    proxy.invoke("getAuctionAlerts", { 'iLimit': 5 },
            function (result) {
                if (result.length > 0) {
                    $('#auctionalerts').empty();

                    $("#auctionAlertsTemplate").tmpl(
                        result, {
                            dataArrayIndex: function (item) {
                                return $.inArray(item, result);
                            }
                        }).appendTo("#auctionalerts");

                    $('#' + panel).show();
                }
                else {
                    $('#auctionalerts').empty();
                    $('#auctionalerts').html('<b>You do not have any alerts set at this time.<br><br><a href="/manage-auction-alerts">create a new alert</a></b>');
                    $('#viewallauctionalertscontainer').hide();
                }
            },
            function (error) {
                //alert("GetRecentsError:" + error.message);
            });
    return false;
}

function SlideLoginClose() {
    $('#Slider_Menu').slideToggle('slow', function () {
    });
    $('#btnclose').hide();
    $('.activelogintab').removeClass();
}

function show(panel) {
    $('#Slider_Menu').slideDown();
    $('#btnclose').show();
    $('.headerpane').hide();

    if (panel == "accountcontent" && mguid != null) {
        GetAccountInfo(panel);
    }
    else if (panel == "accountcontent" && mguid == null) {
        $('#logincontent').show();
    }
    else if (panel == "contactuscontent") {
        $('#contactuscontent').show();
        $('#GeneralContactDetails').show();
    }
    else {
        $('#GeneralContactDetails').hide();
        $('#' + panel).show();
    }
}

function show(panel, destloc) {
    $('#Slider_Menu').slideDown();
    $('#btnclose').show();
    $('.headerpane').hide();

    if (panel == "accountcontent" && mguid != null) {
        GetAccountInfo(panel);
    }
    else if (panel == "accountcontent" && mguid == null) {
        $('#logincontent').show();
    }
    else if (panel == "contactuscontent") {
        $('#contactuscontent').show();
        $('#GeneralContactDetails').show();
    }
    else {
        $('#GeneralContactDetails').hide();
        $('#' + panel).show();
    }
    //Set destination url cookie 
    if (destloc != "" && destloc != null) {
        $.cookie('DestinationLOC', destloc, { expires: -1, path: '/', domain: domain, secure: false });
        $.cookie('DestinationLOC', destloc, { expires: 1, path: '/', domain: domain, secure: false });
    }
}

// FLEX OBJECT ----------------------------------------
function navigatetopage(pagevalue) {
    var pageurl = pagevalue;
    window.location.href = pagevalue;
    return false;
}

function overlayiframe(value) {
    var newurl = value;

    $("#standaloneoverlay").overlay({
        expose: '#789',
        load: true,
        onBeforeLoad: function () {
            var wrap = this.getOverlay().find(".contentWrap");

            wrap.attr({ src: newurl });
            $('#standaloneoverlaycontent').toggle();
            $('#videoPlayer_player_api').attr({ left: '600px' });
        },
        onClose: function () {
            $('#standaloneoverlaycontent').toggle();
            unloadPlayer();
        }
    });
};

function unloadPlayer() {
    var overlayFrame = window.frames['videooverlaycontent'];
    if (!overlayFrame) {
        return;
    }

    if (typeof (overlayFrame['unloadPlayer']) == 'undefined') {
        return;
    }
    overlayFrame['unloadPlayer']();
}

// LOGIN PAGE ------------------------------------------
function LoginComplete(result, userContext, methodName) {
    $("#DisplayName").text("Welcome, " + result).fadeIn('slow');
}
function LoginError(error, userContext, methodName) {
    if (error != null) {
        alert("LoginError:" + error.get_message());
    }
}

function logout() {
    proxy.invoke("Logout", {},
                function (result) {
                    $('#signout').hide();
                    $('#signin').show();
                    $("#DisplayName").text("");


                    //if (location.protocol != 'http:') {

                    //    window.location.href = location.href.replace(location.protocol, 'http:');
                    //}

                    if (pathname.toLowerCase().indexOf("profile") >= 0) {
                        window.location = "/default.aspx";
                    }
                    else if (pathname.toLowerCase().indexOf("property-auctions") >= 0) {
                        window.location.reload();
                    }



                },
                function (error) {
                    //alert(error);
                    $('#ajaxerrorstatement').html(error);
                });
}

function login() {
    $('#signin').hide();
    $('#signout').show();

    $('#ajaxstatement').html("Logging in...");
    $('#ajaxdialog').toggleClass('ajaxerrordialog', false);
    $('#ajaxconfirm').css('display', 'none');
    $.blockUI({
        overlayCSS: { backgroundColor: '#fff' },
        message: $('#ajaxdialog'),
        css: {
            border: '1px solid #c0c0c0',
            opacity: .8
        }
    });

    //Check if going to another page
    var destLoc = $.cookie("DestinationLOC");

    $.cookie('DestinationLOC', destLoc, { expires: -1, path: '/', domain: domain, secure: false });

    if ($('#email').val().length > 0 && $('#password').val().length > 0) {


        proxy.invoke("Login", { 'sUser': $().crypt({ method: "b64enc", source: $('#email').val() }), 'sPassword': $().crypt({ method: "b64enc", source: $('#password').val() }), 'sDestLoc': destLoc },
                function (result) {
                    if (result.authenticated) {
                        $.unblockUI();
                        mguid = result.guid;
                        $("#Slider_Menu").slideUp("slow", function () {
                            $("#DisplayName").text("Welcome, " + result.fullname).css({ "left": "-600px" }).hide().animate({
                                "left": "20px",
                                "opacity": "toggle"
                            }, 3000);
                            for (i = 0; i <= result.roles.length - 1; i++) {
                            }
                        });
                        $('#btnclose').hide();

                        var pid = window.parent.location.href.substr(window.parent.location.href.length - 6);
                        if (result.missingFields == true) {
                            window.location.href = "/profile?missingfields=true&redir=" + pid;
                        } else
                        //redirect to destination page if set
                            if (result.desturl != "" && result.desturl != null) {
                                window.location.href = result.desturl;
                            }
                            else if (pathname.toLowerCase().indexOf("property-auctions") >= 0) {
                                window.location.reload();
                            }
                    }
                    else {
                        $('#ajaxdialog').toggleClass('ajaxerrordialog', true);
                        $('#ajaxstatement').html(result.msg);
                        $('#ajaxconfirm').css('display', 'block');
                    }
                    //Refresh the page for property detail to get auction network passthrough link updated with username
                    if (pathname.toLowerCase().indexOf("profile") >= 0) {
                        window.location.href = pathname;
                    }
                    else if (pathname.toLowerCase().indexOf("bulk-real-estate-debt-loan") >= 0) {
                        window.location.href = pathname;
                    }
                },
                function (error) {
                    //alert("LoginInvoke:" + error.message);
                    $('#ajaxerrorstatement').html(error);
                    $('#ajaxerrorconfirm').css('display', 'block');
                });
    } else {
                $('#ajaxdialog').toggleClass('ajaxerrordialog', true);
                $('#ajaxstatement').html("Please provide a valid username and password");
                $('#ajaxconfirm').css('display', 'block');
    }

    return false;
}

function showfriendpopup() {
    var dialog = $('#dialog-send');
    $('#dialog-send').dialog('open');
}

function showsigninpopup(destloc) {
    //Set destination url cookie
    if (destloc != "" && destloc != null) {
        $.cookie('DestinationLOC', destloc, { expires: -1, path: '/', domain: domain, secure: false });
        $.cookie('DestinationLOC', destloc, { expires: 1, path: '/', domain: domain, secure: false });
    }
    var dialog = $('#dialog-signin');
    $('#dialog-signin').dialog('open');
}

function showsignedinpopup(destloc) {
    //Set-reset destination url cookie 
    if (destloc != "" && destloc != null) {
        $.cookie('DestinationLOC', destloc, { expires: -1, path: '/', domain: domain, secure: false });
        $.cookie('DestinationLOC', destloc, { expires: 1, path: '/', domain: domain, secure: false });
    }
    var dialog = $('#dialog-signedin');
    $('#dialog-signedin').dialog('open');
}

function handleLoginDialog(un, pword) {
    $('#signin').hide();
    $('#signout').show();

    $('#ajaxstatement').html("Logging in...");
    $('#ajaxdialog').toggleClass('ajaxerrordialog', false);
    $('#ajaxconfirm').css('display', 'none');
    $.blockUI({
        overlayCSS: { backgroundColor: '#fff' },
        message: $('#ajaxdialog'),
        css: {
            border: '1px solid #c0c0c0',
            opacity: .8
        }
    });

    //Check if going to another page
    var destLoc = $.cookie("DestinationLOC");

    $.cookie('DestinationLOC', destLoc, { expires: -1, path: '/', domain: domain, secure: false });

    proxy.invoke("Login", { 'sUser': $().crypt({ method: "b64enc", source: un }), 'sPassword': $().crypt({ method: "b64enc", source: pword }), 'sDestLoc': destLoc },
                function (result) {
                    if (result.authenticated) {
                        $.unblockUI();
                        mguid = result.guid;
                        $("#DisplayName").text("Welcome, " + result.fullname).css({ "left": "-600px" }).hide().animate({
                            "left": "20px",
                            "opacity": "toggle"
                        }, 3000);

                        //for (i = 0; i <= result.roles.length - 1; i++) {
                        // }
                        var pid = window.parent.location.href.substr(window.parent.location.href.length - 6);
                        if (result.missingFields == true) {
                            window.location.href = "/profile?missingfields=true&redir=" + pid;
                        }
                        else
                        //redirect to destination page if set
                            if (result.desturl != "" && result.desturl != null) {
                                window.location.href = result.desturl;
                            }
                            else if (pathname.toLowerCase().indexOf("property-auctions") >= 0) {
                                window.location.reload();
                            }
                    }
                    else {
                        $('#ajaxdialog').toggleClass('ajaxerrordialog', true);
                        $('#ajaxstatement').html(result.msg);
                        $('#ajaxconfirm').css('display', 'block');
                    }

                    //Refresh the page for property detail to get auction network passthrough link updated with username
                    if (pathname.toLowerCase().indexOf("profile") >= 0) {
                        window.location.href = pathname;
                    }
                },
                function (error) {
                    $('#ajaxerrorstatement').html(error);
                    $('#ajaxerrorconfirm').css('display', 'block');
                });
}

function forgot() {
    $('#ajaxdialog').toggleClass('ajaxerrordialog', false);

    $('#ajaxstatement').html("Looking up your account");
    $('#ajaxconfirm').css('display', 'none');
    $.blockUI({
        overlayCSS: { backgroundColor: '#fff' },
        message: $('#ajaxdialog'),
        css: {
            border: '1px solid #c0c0c0',
            opacity: .8
        }
    });

    proxy.invoke("GetPassword", { 'sUser': $('#forgotemail').val() },
                function (result) {
                    if (!result.authenticated) {
                        $('#ajaxdialog').toggleClass('ajaxerrordialog', true);
                        $('#ajaxstatement').html(result.msg);
                        $('#ajaxconfirm').css('display', 'block');
                    }
                    else {
                        $('#ajaxdialog').toggleClass('ajaxdialogsuccess', true);
                        $('#ajaxstatement').html(result.msg);
                        $('#ajaxconfirm').css('display', 'block');
                    }
                },
                function (error) {
                    $('#ajaxdialog').toggleClass('ajaxerrordialog');
                    $('#ajaxstatement').html(error.msg);
                    $('#ajaxconfirm').css('display', 'block');
                }
          );
    return false;
}

function handleForgotDialog(e) {
    $('#ajaxdialog').toggleClass('ajaxerrordialog', false);

    $('#ajaxstatement').html("Looking up your account");
    $('#ajaxconfirm').css('display', 'none');
    $.blockUI({
        overlayCSS: { backgroundColor: '#fff' },
        message: $('#ajaxdialog'),
        css: {
            border: '1px solid #c0c0c0',
            opacity: .8
        }
    });

    proxy.invoke("GetPassword", { 'sUser': e.val() },
        function (result) {
            if (!result.authenticated) {
                $('#ajaxdialog').toggleClass('ajaxerrordialog', true);
                $('#ajaxstatement').html(result.msg);
                $('#ajaxconfirm').css('display', 'block');
            }
            else {
                $('#ajaxdialog').toggleClass('ajaxdialogsuccess', true);
                $('#ajaxstatement').html(result.msg);
                $('#ajaxconfirm').css('display', 'block');
            }
        },
        function (error) {
            $('#ajaxdialog').toggleClass('ajaxerrordialog');
            $('#ajaxstatement').html(error.msg);
            $('#ajaxconfirm').css('display', 'block');
        });
}

function formatItem(o) {
    return "<div class='myaccountpropertylink' url='" + o.linkurl + "' style='border-bottom:1px solid #c0c0c0;position:relative;margin:10px;float:left;clear:both;width:100%;vertical-align:middle;text-align:center;'><div style='float:left'><image width=\"50px\" src=\"" + o.imgurl + "\" /></div><div style='width:125px;float:right;text-align:left;margin-left:5px'>" + o.addr + "</div></div>";
}

//PROPERTIES -----------------------------------------
function addSliderItems() {
    $('#holder').anythingSlider(); // update the slider
}

function update10xitems() {
    $(".gradient").each(function () {
        if ($(this).data("oheight") == null) {
            $(this).data("oheight", $(this).height());
            $(this).height(110);
        }
    });
    $(".open_property").click(function () {
        $(this)
        .toggleClass('open_property_expanded')
        .parent().animate({ height: $(this).parent().height() > 100 ? '100px' : '100%' }, 1000, function () { });
    });
}
function makenewsslider() {
    $('#newsholder').anythingSlider({
        autoPlay: false,
        resizeContents: false,
        width: '772px',
        height: '600px',
        buildArrows: false,
        buildNavigation: false
    });
}

function updatePropSlider() {
    $('#holder').anythingSlider({
        width: '762px',
        height: '1425px',
        buildArrows: false,
        buildNavigation: false,
        autoPlay: false,
        infiniteSlides: true,
        resizeContents: true,
        animationTime: 1000,
        buildStartStop: false
    });
    if ($('#holder').data('AnythingSlider').pages == 1) {
        $("#controlstop").html("");
        $("#controlsbottom").html("");
    }
    update10xitems();
}

function tagClicked(e) {
    aselectedfilters = [];
    aselectedgroups = [];
    $("#availablefilters input:checked").each(function () {

        aselectedfilters.push($(this).attr('id'));
        var bFound = false;
        var ed = $(this).closest('div.groupheader').attr('id');

        for (var i = 0; i < aselectedgroups.length; i++) {
            if (aselectedgroups[i] == ed) {
                bFound = true;
            }
        }
        if (!bFound) {
            aselectedgroups.push(ed);
        }
    });
}

function moveAnimate(element, newParent) {
    var oldOffset = element.data("parent").offset();
    element.appendTo(newParent);
    var newOffset = element.offset();
    var temp = element.clone(true).appendTo('body');
    temp.css('position', 'absolute')
                .css('left', oldOffset.left)
                .css('top', oldOffset.top)
                .css('zIndex', 1000);
    element.hide();
    temp.animate({ 'top': newOffset.top, 'left': newOffset.left }, 'slow', function () {

        element.show();

        aselectedfilters = [];

        $("#selectedfilters input:checked").each(function () {
            aselectedfilters.push($(this).attr('id'));
        });
        temp.remove();
    });

    $(temp).promise().done(function () {
        applyFilters();
    });
}

function applyFilters() {
    var tagorama = [];
    var common = $.grep(aprops.PropertyWrappers, function (itm, idx) {
        try {
            if (filterProps(itm.Tags)) {
                return true;
            }
            else {
                return false;
            }
        } catch (e) {
            return false;
        }
    });

    $(".box").promise().done(function () {
        loadFilterGrid(common);
    });
}

function loadFilterGrid(common) {
    remove10xpages();

    $('.propertycount').html(common.length);

    if (common.length == 0) {
        $('#controlstop').html(nopropertiesfoundtext);
        $('.propertycount').html('0');
        $('#statelist').hide();
        $('#citylist').hide();
        $('#Apply').hide();
    }
    else {
        var i = 10;
        totalprops = common.length;
        var top = Math.ceil(totalprops / i10xPageSize) * i10xPageSize;
        do {
            $('<li id="' + i + '">').appendTo("#holder");
            i += i10xPageSize;
        } while (i <= top);

        i = 0;
        do {
            $("#Template10x").tmpl(common.slice(i, i + i10xPageSize)).appendTo("#" + (i + i10xPageSize));

            i += i10xPageSize;
        } while (i < common.length);

        if (common.length <= 10) {
            $('#controlstop').html('Page 1 of 1');
            $('#controlsbottom').html('Page 1 of 1');
        }
        else {
            $('.pager').pagination(common.length, { num_display_entries: 5, prev_text: '<<', next_text: '>>', num_edge_entries: 1, load_first_page: false, items_per_page: i10xPageSize, callback: handlePageClick, link_to: 'javascript:void(0);' });
            //$('#controlsbottom').pagination(common.length, { num_display_entries: 5, prev_text: '<<', next_text: '>>', num_edge_entries: 1, load_first_page: false, items_per_page: i10xPageSize, callback: handlePageClick, link_to: 'javascript:void(0);' });
        }

        $('#holder').anythingSlider({ startPanel: 1, height:'auto', width: '762px', buildStartStop: false, buildArrows: false, buildNavigation: false, autoPlay: false, infiniteSlides: true, resizeContents: true, animationTime: 1000, expand:true });
        update10xitems();

        $('#holder').css('left', '0px');
    }
}

function tagExists(sTag) {
    $("#selectedfilters :input:checked").each(function () {
        if ($(this).get(0).id == sTag) {
            //alert('found');
            return true;
        }
    });
    return false;
}

function filterProps(stags) {
    var icount = 0;

    for (i = 0; i <= aselectedfilters.length; i++) {
        if ($.inArray(parseInt(aselectedfilters[i]), stags) > -1) {
            icount++;
        }
    }

    var stateCount = $.inArray(parseInt($('#stateareafilter').val()), stags) <= -1 ? 0 : 1;
    var cityCount = $.inArray(parseInt($('#cityareafilter').val()), stags) <= -1 ? 0 : 1;

    icount += stateCount;
    icount += cityCount;

    stateCount = cityCount = 0;
    if (parseInt($("#stateareafilter option:selected").attr("value")) < 0) {
        stateCount = 1;
        if (parseInt($("#cityareafilter option:selected").attr("value")) < 0) {
            cityCount = 1;
        }
    }

    if (aselectedgroups.length + cityCount + stateCount == 0 || icount == aselectedgroups.length + cityCount + stateCount) {
        return true;
    }
    return false;
}

function remove10xpages() {
    $('#holder li').remove();
}

function updateTags() {
    resultcopy = aprops;
    bonlyonestate = false;

    $("#availablefilters").empty();
    $("#areafilterstate").empty();

    if (aprops.TagHierarchy.length == 0)
        return;

    if (SearchTags.length != 0) {
        aSearchTags = SearchTags.split("~");
    }

    $.each(aprops.TagHierarchy[0].Groups, function (z, Group) {
        if (Group.GroupName == "State") {
            buildStateList(Group);

            if (Group.Tags.length == 1) {
                bonlyonestate = true;
            }
            if (SearchTags && SearchTags.length > 0) {
                for (var i = 0; i < aSearchTags.length; i++) {
                    if (aSearchTags[i] > -3000 && aSearchTags[i] < -2000) {
                        var b = '#stateareafilter option[value="' + aSearchTags[i] + '"]';
                        if ($(b) && $(b)[0]) {
                            $(b)[0].selected = true;
                            showCity();
                            if (SearchCity && SearchCity.length > 0) {
                                $("#cityareafilter option:contains(" + replaceAll(SearchCity, "-", " ") + ")").attr("selected", true);
                            }
                        }
                    }
                }
            }
            else {
                var b = '#stateareafilter option:contains("' + sargs + '")';
                if ($(b) && $(b)[0]) {
                    $(b)[0].selected = true;
                    showCity();
                    if (SearchCity && SearchCity.length > 0) {
                        $("#cityareafilter option:contains(" + replaceAll(SearchCity, "-", " ") + ")").attr("selected", true);
                    }
                }
            }
        }
        if (Group.GroupName == "City") { buildCityList(Group); }

        if (Group.GroupName != "City" && Group.GroupName != "State" && Group.GroupName != "Property Types") {
            $.each(Group.Tags, function (x, Tag) {
                $.each(aselectedfilters, function (t) {
                    if (aselectedfilters[t] == Group.Tags[x].TagID) {
                        resultcopy.push(Group.Tags.slice(x, 1));
                    }
                });
            });
        }
    });
    $("#taggrouptemplate").tmpl(resultcopy.TagHierarchy[0].Groups).appendTo("#availablefilters").promise().done(function () {
        if (bonlyonestate) {
            $('#cityareafilter').parent().show('slow');
        }
        $("input.mf").uniform();
    });
}

function buildStateList(result) {
    var selector = '<select id="stateareafilter" class="selectbox uni state" style="width:100%">';
    selector += '<option value="">Please select...</option>';
    $(selector)
                .append($("#statelisttemplate")
                .tmpl(result))
                .append('</select>')
                .appendTo("#statelist")
                .promise()
                .done(function () {
                    //$("#stateareafilter").uniform();
                });
}

function buildCityList(result) {
    $('#cityareafilter').remove();
    $('<select id="cityareafilter" class="selectbox uni state" style="width:100%"><option value="">Please select...</option>')
                .append($("#citylisttemplate")
                .tmpl(result))
                .append('</select>')
                .appendTo("#citylist")
                .promise()
                .done(function () {
                    //$("#cityareafilter").uniform();
                });
}

function getMoreProps() {
    proxy.invoke("getProperties", { 'sType': stype, 'sArgs': sargs, 'area': area, 'city': SearchCity, 'state': SearchState, 'iPageSize': i10XPullSize, 'iOffset': iOffset, 'iSort' : ddlsortvalue },
        function (result) {
            var moreprops = eval('(' + result + ')');
            if (moreprops.PropertyWrappers.length > 0) {
                iOffset += i10XPullSize;

                aprops.PropertyWrappers.push(moreprops.PropertyWrappers);

                var i = 0;
                do {
                    $('<li>').append($("#Template10x").tmpl(moreprops.PropertyWrappers.slice(i, i + i10xPageSize))).append('</li>').appendTo("#holder");
                    i += i10xPageSize;
                } while (i < moreprops.PropertyWrappers.length);

                var currpage = $('#holder').data('AnythingSlider').currentPage;
                updatePropSlider();
                $('#holder').anythingSlider(currpage);

                if (iOffset < totalprops) {
                    getMoreProps();
                }
            }
            else {
            }
        },
        function (error) {
        });
}

function blockIsFilled(block) {
    if ($('#' + (block + 1) * i10xPageSize + ' .gradient').length == 0) {
        return false;
    }
    return true;
}

function getNextEmptyBlock() {
    var totalblocks = Math.ceil(totalprops / i10xPageSize);
    for (t = 0; t < totalblocks; t++) {
        if (!blockIsFilled(t)) return t;
    }
    return -1;
}

function getMorePastProps(startingBlock, blocksToFill, switchPages) {
    var func;
    var args;

    if (startingBlock == null) startingBlock = getNextEmptyBlock();
    if (startingBlock == -1) return;
    if (blocksToFill == null) blocksToFill = 1;

    switch (isPastResults) {
        case true:
            func = "getProperties";
            args = { 'sType': stype, 'sArgs': sargs, 'area': area, 'city': SearchCity, 'state': SearchState, 'iPageSize': i10xPageSize * blocksToFill, 'iOffset': i10xPageSize * startingBlock, 'sFilters': aselectedfilters.join(',') == '' ? '' : aselectedfilters.join(','), 'iStatus': isPastResults == true ? 2 : 1, 'iSort': ddlsortvalue };
            break;
        case false:
            func = "getProperties";
            args = { 'sType': stype, 'sArgs': sargs, 'area': area, 'city': SearchCity, 'state': SearchState, 'iPageSize': i10xPageSize * blocksToFill, 'iOffset': i10xPageSize * startingBlock, 'sFilters': aselectedfilters.join(',') == '' ? '' : aselectedfilters.join(','), 'iStatus': isPastResults == true ? 2 : 1, 'iSort': ddlsortvalue };
            break;
        default:
            func = "getProperties";
            args = { 'sType': stype, 'sArgs': sargs, 'area': area, 'city': SearchCity, 'state': SearchState, 'iPageSize': i10xPageSize * blocksToFill, 'iOffset': i10xPageSize * startingBlock, 'sFilters': aselectedfilters.join(',') == '' ? '' : aselectedfilters.join(','), 'iStatus': isPastResults == true ? 2 : 1, 'iSort': ddlsortvalue };
    }

    proxy.invoke(func, args,
            function (result) {
                var moreprops = eval('(' + result + ')');
                if (moreprops.PropertyWrappers.length > 0) {
                    aprops.PropertyWrappers.push(moreprops.PropertyWrappers);
                    var i = 0;

                    do {
                        $("#Template10x").tmpl(moreprops.PropertyWrappers.slice(i, i + i10xPageSize)).appendTo("#" + (i + (i10xPageSize * (startingBlock + 1))));
                        i += i10xPageSize;
                    } while (i < moreprops.PropertyWrappers.length);

                    iOffset += i10xPageSize;

                    $('#holder').anythingSlider().promise().done(function () {
                        update10xitems();

                        $('#main').unblock().promise().done(function () {
                            $('#holder').anythingSlider((thepage));
                        });
                    });


                    //DO NOT ERASE**************
                    //$("#holder .gradient").highlight(sargs.split("||"));
                    //$(".highlight").css({ backgroundColor: "#FFFF88", border: "1px solid orange" });
                    //**************************

                    if (iOffset < totalprops) {
                        // getMorePastProps();
                    }
                }
                else {
                    $('#main').unblock().promise().done(function () {

                    });
                }
            },
            function (error) {
            });
    //return false;
}

function handlePageClick(new_page_index, pagination_container) {
    thepage = new_page_index == 0 ? 1 : new_page_index + 1;
    iOffset = thepage * i10xPageSize;

    if ($('#' + iOffset + ' .gradient').length == 0) {
        $('#main').block({ message: $('.spinner').html(), centerY: 0, css: { top: 0, left: 0, right: '10px', border: 'none', padding: '5px' }, overlayCSS: { backgroundColor: '#fff', opacity: 0.8} });
        getMorePastProps(new_page_index);
    }
    else {
        // alert('getting in the stickers');
        $('#holder').anythingSlider(thepage);
    }

    $('body').animate({ scrollTop: 0 });


}

function bindTags() {
    $("#availablefilters").delegate('.mf', 'click', function (event) {
        if (this.id == -1 || this.id == -2 || this.id == -3 || this.id == -4) {
            var sLoadDivision = this.id;

            if (!$(this).attr("checked")) {
                sLoadDivision = "0";
            }
            for (var myID = -1; myID > -5; myID--) {
                $("#" + myID).attr("checked", false);
                $.uniform.update("#" + myID);
            }

            $("#" + sLoadDivision).attr("checked", "checked");
            $.uniform.update("#" + sLoadDivision);

            LoadDivision(sLoadDivision);
            bupdateTags = true;
        }
        else {
            bupdateTags = false;
        }

        tagClicked($(this));
        //alert('getting props');
        iOffset = 0;
        thepage = 0;
        totalprops = 0;
        aprops = [];
        getPastProperties();

        $('#main').stop().block({ message: $('.spinner').html(), centerY: 0, css: { top: $(document).scrollTop() + 10, left: '', right: '10px', border: 'none', padding: '5px' }, overlayCSS: { backgroundColor: '#fff', opacity: 0.8} }).promise().done(function () {

            $('#main').unblock();
            $('html, body').stop().animate({ scrollTop: 0 }, 'slow');
        });
        return;
    });
}

function unbindTags() {
    $("#availablefilters").undelegate();
}


function getPastProperties() {

    switch (area) {
        case 0:
            nopropertiesfoundtext = "There are currently no properties that match your criteria.<br> Click <a href='/real-estate-auction'>here</a> to view all the properties in all listings.";
            break;
        case 1:
            nopropertiesfoundtext = "There are currently no properties that match your criteria.<br> Click <a href='/residential-real-estate-home-auction'>here</a> to view all our residential listings.";
            break;
        case 2:
            nopropertiesfoundtext = "There are currently no properties that match your criteria.<br> Click <a href='/commercial-real-estate-auction'>here</a> to view all our commercial listings.";
            break;
        case 3:
            nopropertiesfoundtext = "There are currently no properties that match your criteria.<br> Click <a href='/farm-ranch-land-auction'>here</a> to view all our farm and ranch listings.";
            break;
        case 4:
            nopropertiesfoundtext = "There are currently no properties that match your criteria.<br> Click <a href='/distinctive-luxury-auction'>here</a> to view all our distinctive listings.";
            break;

        default:
            nopropertiesfoundtext = "There are currently no properties that match your criteria.<br> Click <a href='/real-estate-auction'>here</a> to view all the properties in all listings.";
    }

    var func;
    var args;
    if (stype.toLowerCase() == "targeted") {
        aselectedfilters = SearchTags.split('~');
    }

    switch (isPastResults) {
        case true:
            func = "getProperties";
            args = { 'sType': stype, 'sArgs': sargs, 'area': area, 'city': SearchCity, 'state': SearchState, 'iPageSize': i10XPullSize, 'iOffset': iOffset, 'sFilters': aselectedfilters.join(',') == '' ? '' : aselectedfilters.join(','), 'iStatus': isPastResults == true ? 2 : 1, 'iSort': ddlsortvalue };

            break;
        case false:
            func = "getProperties";
            args = { 'sType': stype, 'sArgs': sargs, 'area': area, 'city': SearchCity, 'state': SearchState, 'iPageSize': i10XPullSize, 'iOffset': iOffset, 'sFilters': aselectedfilters.join(',') == '' ? '' : aselectedfilters.join(','), 'iStatus': isPastResults == true ? 2 : 1, 'iSort': ddlsortvalue };

            break;
        default:
            func = "getProperties";
            args = { 'sType': stype, 'sArgs': sargs, 'area': area, 'city': SearchCity, 'state': SearchState, 'iPageSize': i10XPullSize, 'iOffset': iOffset, 'sFilters': aselectedfilters.join(',') == '' ? '' : aselectedfilters.join(','), 'iStatus': isPastResults == true ? 2 : 1, 'iSort': ddlsortvalue };
    }

    proxy.invoke(func, args,
            function (result) {
                remove10xpages();

                aprops = eval('(' + result + ')');
                var i = 10;

                totalprops = aprops.iTotalCount;

                var top = Math.ceil(totalprops / i10xPageSize) * i10xPageSize;
                do {
                    $('<li id="' + i + '">').appendTo("#holder");
                    i += i10xPageSize;
                } while (i <= top);

                i = 0;

                if (aprops.PropertyWrappers.length != 0) {
                    do {
                        $("#Template10x").tmpl(aprops.PropertyWrappers.slice(i, i + i10xPageSize)).appendTo("#" + (i + i10xPageSize));

                        i += i10xPageSize;

                    } while (i < aprops.PropertyWrappers.length);

                    iOffset = i;

                    $('.propertycount').html(totalprops);

                    $('#statelist').show();
                    filterCities();

                    if (bupdateTags) {
                        $("#availablefilters").empty();
                        $("#stateareafilter").remove();
                        $("#cityareafilter").empty();
                        updateTags();

                        aselectedfilters = [];
                    }
                    $('#Apply').show();

                    if (aprops.PropertyWrappers.length == 1) {
                        $("#controlstop").html("");
                        $("#controlsbottom").html("");
                    }

                    unbindTags();

                    $("input.mf").each(function () {
                        var myID = $(this).attr("id");
                        if (parseInt(myID) > -5 && parseInt(myID) < 0) {
                            if (parseInt(myID) == -area) {
                                $("#" + myID).attr("checked", "checked");
                                $.uniform.update("#" + myID);
                            }
                        }
                        else if (aSearchTags.length != 0 && aSearchTags.indexOf(myID) > -1) {
                            $("#" + myID).click();
                            $.uniform.update("#" + myID);
                        }
                    });
                    bindTags();
                }
                else {
                    $('.propertycount').html('0');
                    $('#statelist').hide();
                    $('#citylist').hide();
                    $("#controlstop").html(nopropertiesfoundtext);
                    $("#controlsbottom").html("");
                    $('#Apply').hide();
                }
                if (aprops.iTotalCount == 0) {
                    //do nada
                } else if (aprops.iTotalCount <= 10) {
                    $('#holder').css('left', '0px');

                    $('#controlstop').empty();
                    $('#controlsbottom').empty();
                }
                else {
                    $('#holder').anythingSlider({ startPanel: 1, height: 'auto', width: '762px', buildStartStop: false, buildArrows: false, buildNavigation: false, autoPlay: false, infiniteSlides: true, resizeContents: true, animationTime: 1000, expand: true });
                    $('.pager').pagination(totalprops, { num_display_entries: 5, prev_text: '<<', next_text: '>>', num_edge_entries: 1, load_first_page: false, items_per_page: i10xPageSize, callback: handlePageClick, link_to: 'javascript:void(0);' });
                    //$('.panel .gradient:last-child').removeClass('gradient').pagination(totalprops, { num_display_entries: 5, prev_text: '<<', next_text: '>>', num_edge_entries: 1, load_first_page: false, items_per_page: i10xPageSize, callback: handlePageClick, link_to: 'javascript:void(0);' });
                    
                    $('#holder').anythingSlider(1);
                }
                update10xitems();

                //                aselectedfilters = [];
                //                aselectedgroups = [];
                //                $("#availablefilters input:checked").each(function () {

                //                    aselectedfilters.push($(this).attr('id'));
                //                    var bFound = false;
                //                    var ed = $(this).closest('div.groupheader').attr('id');

                //                    for (var i = 0; i < aselectedgroups.length; i++) {
                //                        if (aselectedgroups[i] == ed) {
                //                            bFound = true;
                //                        }
                //                    }
                //                    if (!bFound) {
                //                        aselectedgroups.push(ed);
                //                    }
                //                });


                //applyFilters();
            },
            function (error) {
            });
    return false;
}

function getProperties() {
    getPastProperties();
}

function getPastResultsByState(category) {
    proxy.invoke("getPastResultsByState", { 'categoryID': category, 'OnlineOnly': OnlineOnly, 'url': StateSearchURL, 'keywords': sargs },
            function (result) {

                $("#TemplatePastResultsStateList").tmpl(result).appendTo("#statesholder");
            },
            function (error) {
                // alert("GetPropertiesByStateError:" + error.text);
            });
    return false;
}

function getPropertiesByState(category) {
    proxy.invoke("getPropertiesByState", { 'categoryID': category, 'OnlineOnly': OnlineOnly, 'url': StateSearchURL, 'keywords': sargs },
            function (result) {
                $.each(result, function (key, value) {
                });
                $("#TemplateStateList").tmpl(result).appendTo("#statesholder");
            },
            function (error) {
                // alert("GetPropertiesByStateError:" + error.text);
            });
    return false;
}

function getTargetedPropertiesByState(sargs) {
    proxy.invoke("getTargetedPropertiesByState", { 'sFilters': sargs },
            function (result) {
                $.each(result, function (key, value) {
                });
                $("#TargetedTemplate").tmpl(result).appendTo("#holder");
            },
            function (error) {
                // alert("GetPropertiesByStateError:" + error.text);
            });
    return false;
}

function getPropertiesByStateForMap(category) {
    proxy.invoke("getPropertiesByState", { 'categoryID': category, 'OnlineOnly': OnlineOnly, 'url': '', 'keywords': '' },
            function (result) {
                $("#statelistmaptemplate").tmpl(result).appendTo("#stateholder");
            },
            function (error) {
                //alert("GetPropertiesByStateMapError:" + error.text);
            });
    return;
}

function LoadProperty(propertyID, address) {
    var url = "/property-auctions/" + replaceAll(address.replace(new RegExp('[^a-zA-Z0-9 -]'), "-"), ' ', '-') + "/" + propertyID;
    window.navigatetopage(url);
}

function updatefavs(pid, address, imgurl) {
    favs.push(new fav(pid, address, imgurl));
}

function updatecalreminders(pid, startdate, enddate, imgurl, addr) {
    calreminders.push(new calreminder(pid, startdate, enddate, addr, imgurl));
}

function addPropDetailFav(item, id, addr, imgurl) {
    if (mguid != null) {
        if (!checkifexists(id, 'fav')) {
            favs.push(new fav(id, addr, imgurl));
            propdetailclone(item);

            proxy.invoke("AddFavorite", { 'pID': id, 'sAddress': addr, 'sURL': imgurl },
                function (result) {
                    proxy.invoke("GetFavorites", { 'sFavURL': sfavurl },
                    function (result) {
                        $('#favs').empty();
                        $.tmpl(favsTemplate, result).appendTo("#favs");
                        //$('#' + panel).show();
                        //alert($('#favs').html());
                    },
                function (error) {
                    //alert("AddFavoritesError:" + error.message);
                });
                },
                function (error) {
                    //alert("AddFavError:" + error.message);
                });
        }
        else {
            //alert('fav exists');
            $(item).enabled = false;
        }
    }
    else {
        $('html, body').animate({ scrollTop: 0 }, 'slow');
        show('logincontent');
    }
}

function addFav(item, id, addr, imgurl) {
    if (mguid != null) {
        if (!checkifexists(id, 'fav')) {
            favs.push(new fav(id, addr, imgurl));
            clone(item);

            proxy.invoke("AddFavorite", { 'pID': id, 'sAddress': addr, 'sURL': imgurl },
                function (result) {
                    proxy.invoke("GetFavorites", { 'sFavURL': sfavurl },
                    function (result) {
                        $('#favs').empty();
                        $.tmpl(favsTemplate, result).appendTo("#favs");
                        //alert($('#favs').html());
                    },
                function (error) {
                    //alert("AddFavoritesError:" + error.message);
                });
                },
                function (error) {
                    //alert("AddFavError:" + error.message);
                });
        }
        else {
            //alert('fav exists');
            $(item).enabled = false;
        }
    }
    else {
        $('html, body').animate({ scrollTop: 0 }, 'slow');
        show('logincontent');
    }
}

function addCalReminder(item, id, startdate, enddate, addr, imgurl) {
    if (!checkifexists(id, 'reminder')) {
        calreminders.push(new calreminder(id, startdate, enddate, addr, imgurl));
        clone(item);
    }
    else {
        alert('reminder exists');
        $(item).enabled = false;
    }
}

/*DATE RANGE-------------------------------------*/
function InitializeDateRangePicker() {
    if ($(window.parent.document).find('iframe').size()) {
        var inframe = true;
    }

    $('#dateRange').daterangepicker({
        presetRanges: [
          { text: 'The previous Month',
              dateStart: function () { return Date.parse('1 month ago').moveToFirstDayOfMonth(); },
              dateEnd: function () { return Date.parse('1 month ago').moveToLastDayOfMonth(); }
          },
          { text: 'Current Month',
              dateStart: function () { return Date.parse('today').moveToFirstDayOfMonth(); },
              dateEnd: function () { return Date.parse('today').moveToLastDayOfMonth(); }
          }
          ],
        presets: {},
        appendTo: '#datepicker',
        posX: null,
        posY: null,
        arrows: true,
        dateFormat: 'm/d/yy',
        rangeSplitter: 'to',
        datepickerOptions: {
            changeMonth: true,
            changeYear: true
        },
        onOpen: function () { if (inframe) { $(window.parent.document).find('iframe:eq(1)').width(700).height('35em'); } },
        onClose: function () {
            GetStartEndDate();
        }
    });
};

function GetStartEndDate() {
    var stDate = $('#datepicker').find('.range-start').datepicker("getDate");
    var enDate = $('#datepicker').find('.range-end').datepicker("getDate");

    enDate = $.datepicker.formatDate('m-dd-yy', enDate);
    stDate = $.datepicker.formatDate('m-dd-yy', stDate);

    if (enDate != "" && stDate != "") {
        window.location = "/real-estate-auction/" + stDate + "/" + enDate;
    }
}

/* Property 10x*/
function clone(item) {
    var oLI = $(item).parents(".gradient").get(0);
    var copy = $(oLI).clone(false, false);

    var itemX = $(oLI).offset().left;
    var itemY = $(oLI).offset().top;

    var targetX = $('#spanaccountcontent').offset().left; //left;
    var targetY = $('#spanaccountcontent').offset().top; //top;

    var gotoX = targetX - itemX;
    var gotoY = targetY - itemY;

    var newWidth = $(oLI).width() / 20;
    var newHeight = $(oLI).height() / 20;

    $(copy).css({ 'position': 'absolute', 'width': '700px', 'height': '100px', 'top': itemY, 'left': itemX });

    $(copy)
        .appendTo($("body"))
        .stop()
           .animate({ opacity: 1.0 }, 100)
        .animate({ opacity: 0.0, height: newHeight, width: newWidth, left: targetX, top: targetY }, 3000, function () {
            $(copy).remove();
        });
}

function propdetailclone(item) {
    var copy = $(item).clone(false, false);

    var itemX = $(item).offset().left;
    var itemY = $(item).offset().top;

    var targetX = $('#spanaccountcontent').offset().left; //left;
    var targetY = $('#spanaccountcontent').offset().top; //top;

    var gotoX = targetX - itemX;
    var gotoY = targetY - itemY;

    var newWidth = $(item).width() / 20;
    var newHeight = $(item).height() / 20;

    $(copy).css({ 'position': 'absolute', 'width': '700px', 'height': '100px', 'top': itemY, 'left': itemX });

    $(copy)
        .appendTo($("body"))
        .stop()
           .animate({ opacity: 1.0 }, 100)
        .animate({ opacity: 0.0, height: newHeight, width: newWidth, left: targetX, top: targetY }, 3000, function () {
            $(copy).remove();
        });
}

function GetData(count) {
    var url = query
                + "&iPageNum=" + count
                + "&$callback=displayResults"
                + "&$format=json";
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp",
        async: true,
        url: url
    });
}

function loadSearchResultsForEvent(eventID) {
    // alert("Here");
}

function GetDateString(date) {
    var time = new Date(date);
    var days = time.getDate();
    var months = time.getMonth() + 1;
    var year = time.getFullYear();
    return months + "/" + days + "/" + year;
}

function getLiveEvents(MyClientID, IsLFTL, EffectiveDate) {
    var d = GetDateString(EffectiveDate);
    proxy.invoke("GetLiveEvents", { 'effectiveDate': d, 'IsLFTL': IsLFTL },
            function (result) {
                var selector = "#" + MyClientID + " ul";
                $(selector).empty();
                var i = 0;
                do {
                    $('<li class="EventListItem">').append($("#LiveEventTemplate").tmpl(result.slice(i, i + 1))).appendTo(selector);
                    i++;
                } while (i < result.length);
            },
            function (error) {
                //alert("GetLiveEventsError:" + error.message);
            });
    return false;
}

function NextEvent() {
    ChangeEffectiveDate(1);
    GetLiveEvents();
    PaintEventNav();
}

function ChangeEffectiveDate(amt) {
    var oneMinute = 60 * 1000;
    var oneHour = oneMinute * 60;
    var day = oneHour * 24;

    amt = amt * day;

    liveNowEffectiveDate = new Date(liveNowEffectiveDate.getTime() + amt);
}

function PreviousEvent() {
    ChangeEffectiveDate(-1);
    GetLiveEvents();
    PaintEventNav();
}

function GetLiveEvents() {
    getLiveEvents(OLOClientID, false, liveNowEffectiveDate);
    getLiveEvents(LFTLClientID, true, liveNowEffectiveDate);
}

function updateLiveEventSlider(MyClientID, IsLFTL) {
    $('#Dashboard_holder').anythingSlider({
        width: 1400,
        height: 800,
        buildArrows: false,
        buildNavigation: false,
        autoPlay: false,
        infiniteSlides: false,
        buildStartStop: false,

        onInitialized: function (e, slider) {
            GetLiveEvents()
            PaintEventNav();
        }
    });
}

function PaintEventNav() {
    var nav = '<a href="#" onclick="PreviousEvent();" >&laquo;</a> ' + (liveNowEffectiveDate).toString().substring(4, 15) + ' Auctions <a href="#"onclick="NextEvent();"  >&raquo</a>';
    $('#liveEventDashboardControlsTop').html(nav);
    $('#liveEventDashboardControlsBottom').html(nav);
}

function stopbuff() {
    if (!bufferingStopped) {
        $f().stopBuffering();
        $f().setVolume(100);
        bufferingStopped = true;
    }
}

function FlowPlayer() {
    $f("player", { src: '/Resources/swf/flowplayer-3.2.6.swf', wmode: 'transparent' }, {
        canvas: {
            backgroundColor: '#000000',
            backgroundGradient: 'none'
            //background: 'url(/app_themes/wmg/images/player/WWMvidPic.png) no-repeat'
        },
        clip: {
            autoPlay: false,
            autoBuffering: true,
            bufferLength: 3,
            accelerated: true,
            metaData: false,
            scaling: 'fit',
            onStart: function () {
                setTimeout(stopbuff, 600);
            }
        },
        plugins: { controls: null },
        onLoad: function () {
            this.setVolume(0);
        }
    });
    $f().play();
}

function unloadPlayer() {
    $f().unload();
}

function togglePlayback() {
    $f().toggle();
    var imgPlayback = document.getElementById("play-pause");
    if (imgPlayback.title == "Pause") {
        imgPlayback.src = '/app_themes/wmg/images/buttons/btn_home_play.png';
        imgPlayback.title = "Play";
    }
    else {
        imgPlayback.src = '/app_themes/wmg/images/buttons/btn_home_pause.png';
        imgPlayback.title = "Pause";
    }
}


function toggleSound() {
    if (isMute) {
        $f().unmute();
    }
    else {
        $f().mute();
    }
    var imgMute = document.getElementById("volume-onoff");
    if (imgMute.title == "Volume Off") {
        imgMute.src = '/app_themes/wmg/images/buttons/btn_home_volumeon.png';
        imgMute.title = "Volume On";
    }
    else {
        imgMute.src = '/app_themes/wmg/images/buttons/btn_home_volumeoff.png';
        imgMute.title = "Volume Off";
    }
}

function playVideo(mediaURL) {
    $f().play(mediaURL);
    return false;
}

function hslide() {
    hs.registerOverlay({
        html: '<div class="closebutton" onclick="return hs.close(this)" title="Close"></div>',
        position: 'top right',
        useOnHtml: true, fade: 2 // fading the semi-transparent overlay looks bad in IE
    });
    hs.graphicsDir = '/Resources/JS/highslide-4.1.12/highslide/graphics/';
    hs.expandCursor = null;
    hs.allowMultipleInstances = false;
    hs.align = 'center';
    hs.transitions = ['expand', 'crossfade'];
    hs.fadeInOut = true;
    hs.dimmingOpacity = .75;
    hs.wrapperClassName = 'borderless floating-caption premierborder no-footer';
}

function toggleSection(section, link) {
    control = document.getElementById(section);
    if (control.className == 'collapsedsection') {
        control.className = 'expandedsection';
        link.innerHTML = link.innerHTML.replace('Show', 'Hide');
    } else {
        control.className = 'collapsedsection';
        link.innerHTML = link.innerHTML.replace('Hide', 'Show');
    }
}

function getPoints() {
    $.ajax({
        type: "POST",
        url: "/Ajax.aspx/getMapPoints",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            alert("GetPoints Results:" + result);
        }
    });
}

function createMyInfoWindow(mymarker, mycontent, mymap) {
    google.maps.event.addListener(mymarker, 'click', function () { iw.setContent(mycontent); mymap.panTo(mymarker.position); iw.open(mymap, mymarker); });
}

function onMapReady() {
    usLatLng();
}

function parseXml(xml) {
    var stname;
    var lat;
    var lng;
    var myll;
    var st;

    $.ajax({
        type: "POST",
        url: "/Ajax.aspx/getPropertiesByState",
        //data: "{'categoryID': 0}",
        data: "{'categoryID': 0, 'OnlineOnly' : false, 'url' : '', 'keywords' : '' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (res) {
            //for each state
            for (inx = 0; inx < res.length; inx++) {
                var dataPhoto = res[inx];
                var la;
                var lo;

                $(xml).find("state").each(function () {
                    if ($(this).attr("name") == dataPhoto.StateName) {
                        la = $(this).attr("latitude");
                        lo = $(this).attr("longitude");
                    }
                });
                var bubbleContent = document.createElement('DIV');
                bubbleContent.innerHTML = '<div class="pcount">' + dataPhoto.PropertyCount + '</div>';

                var loc = new google.maps.LatLng(la, lo);
                var infoWindowContent = "<div>" + dataPhoto.StateName + "</div><br/><div>" + dataPhoto.PropertyCount + " Properties</div>";
                createMarker(statemap, dataPhoto.StateName, loc, inx, bubbleContent, infoWindowContent);
            }

            function createMarker(statemap, statename, location, number, bubbleContent, infoWindowContent) {
                var marker = new RichMarker({
                    map: statemap,
                    position: location,
                    draggable: true,
                    flat: true,
                    anchor: RichMarkerPosition.MIDDLE,
                    content: bubbleContent
                });

                google.maps.event.addListener(marker, "mouseover", function () {
                    var myHtml = '<strong>' + infoWindowContent + '</strong><br/>';
                    infoWindow.setOptions({ pixelOffset: new google.maps.Size(9, 9) });
                    infoWindow.setContent(myHtml);
                    infoWindow.open(statemap, marker);
                });

                //Link to Get specific state
                google.maps.event.addListener(marker, 'click', function () {
                    var redir = "/real-estate-auction/" + statename;
                    window.parent.location.href = redir;
                });
            }
        }
    });
}

function usLatLng() {
    tableid = '555623';
    if (us == null) {
        us = new google.maps.LatLng(38, -97);

        statemap = new google.maps.Map(document.getElementById('mapmain'), {
            center: us,
            zoom: 4,
            mapTypeId: google.maps.MapTypeId.ROADMAP

        });

        var style = [
         {
             featureType: "all",
             elementType: "all",
             stylers: [
              { visibility: "on" },
              { hue: "#0099ff" }
            ]
         }
        ];

        var styledMapType = new google.maps.StyledMapType(style, {
            map: statemap,
            name: 'Styled Map'
        });

        statemap.mapTypes.set('map-style', styledMapType);
        statemap.setMapTypeId('map-style');

        layer = new google.maps.FusionTablesLayer({
            suppressInfoWindows: true,
            query: {
                select: 'geometry',
                from: '555623'
            },
            styles: [{
                polygonOptions: {
                    fillColor: "#0863E8",
                    fillOpacity: .2
                }
            }]
        });

        infoWindow = new google.maps.InfoWindow({});
        google.maps.event.addListenerOnce(statemap, 'tilesloaded', addMarkers);
        layer.setMap(statemap);

        // Create the legend and display on the map
        var legendDiv = document.createElement('DIV');
        var legend = new Legend(legendDiv, statemap);
        legendDiv.index = 1;
        statemap.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legendDiv);
    }
}

function Legend(controlDiv, map) {
    controlDiv.style.padding = '5px';
    controlDiv.style.width = '250px';
    controlDiv.style.height = '150px';

    // Set CSS for the control border
    var controlUI = document.createElement('DIV');
    controlUI.style.backgroundColor = 'white';
    controlUI.style.borderStyle = 'solid';
    controlUI.style.borderWidth = '1px';
    controlUI.title = 'Legend';
    controlDiv.appendChild(controlUI);

    // Set CSS for the control text
    var controlText = document.createElement('DIV');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    controlText.style.paddingLeft = '4px';
    controlText.style.paddingRight = '4px';
    controlText.style.textAlign = 'left';

    // Add the text
    controlText.innerHTML = '<div style="font-size:20px;">Properties By State</div><br />' +
        '<div class="pcountlegend">#</div><span style="font-size:20px;">Property Count</span><br /><br />' +
            '<div>Hover over state for additional info.</div><br />' +
                '<div>Click on state to show property list for that state.</div><br />';
    controlUI.appendChild(controlText);
}

function addMarkers() {
    var bounds = statemap.getBounds();
    $.ajax({
        type: "GET",
        url: "/resources/js/usmap/StatesLatLng.xml",
        dataType: "xml",
        success: parseXml
    });
}

function changeMap(stName) {
    var redir = "/real-estate-auction/" + stName;
    window.parent.location.href = redir;
}

function InitMainMap() {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': 'US' }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var options = { zoom: 4, center: results[0].geometry.location, mapTypeId: google.maps.MapTypeId.ROADMAP }

            statemap = new google.maps.Map(document.getElementById('mapmain'), options);
        }
    });

    $.ajax({
        type: "POST",
        url: "/Ajax.aspx/getPropertiesByState",
        data: "{'categoryID': 0}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (res) {
            var arr = [];
        }
    });
}

function LoadDivision(divNumber) {
    var stateID = parseInt($("#stateareafilter option:selected").attr("value"));

    switch (divNumber) {
        case "0":
            area = 0;
            SearchCurrentRoute = "/real-estate-auction";
            if (stateID < -2000) {
                SearchCurrentRoute += "/" + -(2000 + stateID);
            }
            else {
                //window.location = SearchCurrentRoute;
                return;
            }
            break;
        case "-1":
            area = 1;
            SearchCurrentRoute = '/residential-real-estate-home-auction';
            if (stateID < -2000) {
                SearchCurrentRoute += "/" + -(2000 + stateID);
            }
            else {
                return;
            }
            break;
        case "-2":
            area = 2;
            SearchCurrentRoute = '/commercial-real-estate-auction';
            break;
        case "-3":
            area = 3;
            SearchCurrentRoute = '/farm-ranch-land-auction';
            break;
        case "-4":
            area = 4;
            SearchCurrentRoute = '/distinctive-luxury-auction';
            break;
    }

    var tags = new Array();

    var b = BuildSaveSearchURL(tags, null);

    if (area != 0 && area != 1) {
        //window.location = b;
    }
    return false;
}

function GetTagString(tags) {
    var rtn = '';

    if (tags.length == 0) {
        return '0';
    }
    for (var i = 0; i < tags.length; i++) {
        rtn += '~' + tags[i];
    }
    return rtn.substr(1, 1000);
}

function filterCities() {
    showCity();
}

function isOptionHidden(opt) {
    if ($(opt).parent().get(0).tagName == 'SPAN') return true;
    return false;
}

function hideOption(opt) {
    if (isOptionHidden(opt) == true) return;
    $(opt).css('display', 'none'); //for Firefox
    $(opt).wrap('<span>').parent().css('display', 'none');
}

function showOption(opt) {
    if (isOptionHidden(opt) == false) return;
    $(opt).css('display', 'block'); //for Firefox
    var content = $(opt).parent().html();
    $(opt).parent().replaceWith(content);
}

function showCity() {
    if ($('#stateareafilter option:selected').val.length == 0 || $('#stateareafilter option:selected').text().toLowerCase() == "please select...") {
        $('#cityareafilter').parent().hide('slow');
        return false;
    }

    var currentndx = 0;
    //IE wierdness: for some reason re-filtering options after they have already been filtered/displayed seems to not update in the IE DOM (even as late as 9), even though inspect element clearly shows that the html is as it should be.  
    //Destoying and recreating the dropdown seems to unlock this and lets us reset the filtering...
    var p = $("#cityareafilter").wrap('<span>').parent();
    $(p).replaceWith(p.html());

    $('#cityareafilter option').each(function () {
        if ($(this).text().indexOf($('#stateareafilter option:selected').text()) < 0) {
            if ($(this).val() != "") {
                hideOption($(this));
            };
        }
        else {
            showOption($(this));
            if ($(this).text() == SearchCity) currentndx = $(this).val();
        }
    }).promise().done(function () {
        $('#cityareafilter').val(currentndx);
        $('#cityareafilter').parent().show('slow');
    });
}

function updatePropCount() {
    aselectedfilters = [];
    $("#availablefilters input:checked").each(function () {
        aselectedfilters.push($(this).attr('id'));
    });

    var common = $.grep(aprops.PropertyWrappers, function (itm, idx) {
        try {
            if (filterProps(itm.Tags) == true) {
                return true;
            }
            else {
                return false;
            }
        } catch (e) {
            return false;
        }
    });

    $('.propertycount').toggle('drop', 250).promise().done(function () {
        $(this).html(common.length).toggle('drop', 350);
        $('#main').stop().block({ message: $('.spinner').html(), centerY: 0, css: { top: $(document).scrollTop() + 10, left: '', right: '10px', border: 'none', padding: '5px' }, overlayCSS: { backgroundColor: '#fff', opacity: 0.8} }).delay(1000).promise().done(function () {
            tagClicked($(this));
            $('#main').unblock();
        });
    });
}

function replaceAll(txt, replace, with_this) {
    return txt.replace(new RegExp(replace, 'g'), with_this);
}

function BuildSaveSearchURL() {
    tagClicked();
    var tags = [];
    var city = null;
    var sReturn = "";

    if ($('#cityareafilter').get(0).selectedIndex > 0) {
        city = $('#cityareafilter :selected').text();
        SearchCity = city;
    } else {
        SearchCity = null;
    }

    for (var i = 0; i < aselectedfilters.length; i++) {
        tags.push(aselectedfilters[i]);
    }

    if ($('#stateareafilter option:selected').val.length > 0) {
        tags.push($('#stateareafilter').val());
    }

    //Remove previous tags from url if they exist
    var tagIndex = SearchCurrentRoute.indexOf("/ts/");
    if (tagIndex != -1) {
        SearchCurrentRoute = SearchCurrentRoute.substring(0, tagIndex);
    }
    tagIndex = SearchCurrentRoute.indexOf("/cs/");
    if (tagIndex != -1) {
        SearchCurrentRoute = SearchCurrentRoute.substring(0, tagIndex);
    }

    var tagString = GetTagString(tags);
    if (city && city.length > 0) {
        sReturn = SearchCurrentRoute + '/cs-' + city.split(' ').join('-') + '/' + tagString;
        return sReturn.toLowerCase();
    }
    else {
        sReturn = SearchCurrentRoute + '/ts/' + tagString;
        return sReturn.toLowerCase();
    }
}

/* Profile */
function ProfileMaskFields() {
    jQuery(function ($) {
        $("#tbxPhone").mask("(999) 999-9999");
        $("#tbxCellPhone").mask("(999) 999-9999");
        $("#tbxFax").mask("(999) 999-9999");
    });
}

function toggleDiv(id, flagit) {
    if (flagit == "1") {
        if (document.layers) document.layers['' + id + ''].visibility = "show"
        else if (document.all) document.all['' + id + ''].style.visibility = "visible"
        else if (document.getElementById) document.getElementById('' + id + '').style.visibility = "visible"
    }
    else
        if (flagit == "0") {
            if (document.layers) document.layers['' + id + ''].visibility = "hide"
            else if (document.all) document.all['' + id + ''].style.visibility = "hidden"
            else if (document.getElementById) document.getElementById('' + id + '').style.visibility = "hidden"
        }
}

/* DIALOG SECTION */
function updateTipsFP(t) {
    tipsFP
		.text(t)
		.addClass("ui-state-highlight");
    setTimeout(function () {
        tipsFP.removeClass("ui-state-highlight", 1500);
    }, 500);
}

function updateTipsSignIn(msg) {
    tipsSignIn
        .text(msg)
        .addClass("ui-state-highlight");
    setTimeout(function () {
        tipsSignIn.removeClass("ui-state-highlight", 1500);
    }, 500);
}

function updateTips(msg) {
    tips
        .text(msg)
        .addClass("ui-state-highlight");
    setTimeout(function () {
        tips.removeClass("ui-state-highlight", 1500);
    }, 500);
}

function checkEmailFP(o, n) {
    var e = o.val();

    if (e == '') {
        updateTipsFP("Email is missing. Please re-enter and try again.");
        return false;
    }

    if (e.indexOf("@") == -1) {
        updateTipsFP("Invalid email. Please try again.");
        return false;
    }
    return true;
}

function openSendDialog(typeParams, initialMsg) {
    sendType = typeParams;
    $(".validateSendTips").text(initialMsg);
    var dialog = $('#dialog-send');
    $('#dialog-send').dialog('open');
    return false;
}

function openForgotDialog() {
    var dialogFP = $('#dialog-forgot');
    $('#dialog-forgot').dialog('open');
    return false;
}

function handleSendDialog(lnk, e, u, c) {
    var last = lnk.toString().substring(lnk.toString().lastIndexOf("/") + 1, lnk.toString().length);
    var pid = 0;

    if (isNaN(last) || last == "") {
        last = $('#hPropertyID').val();
        if (last != "") {
            pid = last;
        }
    }
    else {
        pid = last;
    }


    var emailEntered = e.val();
    var nameEntered = u.val();
    var commentEntered = c.val();
    var ajaxURL = "/ajax.aspx/SendToFriend";
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: ajaxURL,
        data: '{ "lnk":"' + lnk + '", "pid":"' + pid + '", "emailTo":"' + emailEntered + '", "userName":"' + nameEntered + '", "commentText":"' + commentEntered + '" }',
        processData: false,
        dataType: "json",
        async: false,
        success: handleSendSuccess
    });
}

function handleSendSuccess(data, textStatus, jqXHR) {
    if (data == "OK") {
        $('#dialog-send').dialog('close');
    }
    else {
        var responseArray = data.split('|');
        alert("Send Email Error: " + responseArray[1]);
        return false;
    }
}

function checkEmail(o, n) {
    var e = o.val();

    if (e == '') {
        updateTips("Email is missing. Please re-enter and try again.");
        return false;
    }

    if (e.indexOf("@") == -1) {
        updateTips("Invalid email. Please try again.");
        return false;
    }
    return true;
}

function checkName(o, n) {
    var u = o.val();

    if (u == '') {
        updateTips("Your name is missing. Please re-enter and try again.");
        return false;
    }
    return true;
}

function checkUsername(o, n) {
    var u = o.val();
    if (u == '') {
        jAlert("error", "E-mail is missing. Please re-enter and try again.", "Missing Email");
        return false;
    }
    if (u.indexOf("@") != -1) {
        var reEmail = new RegExp("^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$", "i");
        if (!reEmail.test(u)) {
            jAlert("error", "E-mail address entered appears to be invalid. Please check your e-mail and try again.", "Invalid E-mail Address");
            return false;
        }
    }
    else {
        re = /^\w+$/;
        if (!re.test(u)) {
            jAlert("error", "User ID entered contains invalid characters. Please try again.", "Invalid Characters");
            return false;
        }
    }
    return true;
}

function checkPassword(o, n) {
    var p = o.val();
    if (p == '') {
        updateTipsSignIn("Password is missing. Please re-enter and try again.");
        return false;
    }
    var isInvalid = false;
    InvalidCharacters = Array(";", "<", ">", ",");
    for (var i = 0; i < InvalidCharacters.length; ++i) {
        if (p.indexOf(InvalidCharacters[i]) != -1) {
            isInvalid = true;
        }
    }
    if (isInvalid) {
        updateTipsSignIn("Pasword entered contains invalid characters. Please try again.");
        return false;
    }
    return true;
}

function checkForgotEmail(ctlEmail) {
    var email = $(ctlEmail).val();

    if (email == '') {
        jAlert("error", "Please provide an e-mail address.", "E-mail address needed.");
        return false;
    }
    return true;
}

function WmgTerms(obj) {
    if ($('input[name=chkIAgree]').is(':checked')) {
        $('#btnCompleteForm').show();
    }
    else {
        $('#btnCompleteForm').hide();
    }
}

function HideSubmitButton() {
    $('#btnCompleteForm').hide();
}

//Auction Calendar Date selection
function CalSelectDate(obj, selectedDate) {
    var startonly = false;
    var startdateCurr = false;
    var startdatePrev = false;
    var enddateCurr = false;
    var enddatePrev = false;
    var swap = false;

    if ($("#AucCalPrev td").hasClass("selectedenddate")) {
        enddatePrev = true;
    }
    else if ($("#AucCalCurr td").hasClass("selectedenddate")) {
        enddateCurr = true;
    }

    //is there a start date
    if ($("#AucCalPrev td").hasClass("selectedstartdate")) {
        startdatePrev = true;
    }
    else if ($("#AucCalCurr td").hasClass("selectedstartdate")) {
        startdateCurr = true;
    }

    if ((startdateCurr || startdatePrev) && (!enddateCurr && !enddatePrev)) {
        //check if selected enddate is before startdate selected
        var pstart = Date.parse($('#hdrangefrom').val(), "MM-dd-yy");

        if (Date.parse(selectedDate, "MM-dd-yy") < pstart) {
            swap = true;
        }

        $(obj).addClass("selectedenddate");

        $('#drangeto').html(selectedDate);
        $('#hdrangeto').val(selectedDate);
    }
    else {
        //is there an end date?
        if (enddateCurr || enddatePrev) {  //reset
            $("#AucCalPrev td").removeClass("selectedstartdate");
            $("#AucCalPrev td").removeClass("selectedenddate");
            $("#AucCalPrev td").removeClass("selectedmid");
            $("#AucCalPrev td").removeClass("selectedmidmix");
            $("#AucCalPrev td").removeClass("mixd");
            $("#AucCalCurr td").removeClass("selectedstartdate");
            $("#AucCalCurr td").removeClass("selectedenddate");
            $("#AucCalCurr td").removeClass("selectedmid");
            $("#AucCalCurr td").removeClass("selectedmidmix");
            $("#AucCalCurr td").removeClass("mixd");
        }
        $(obj).addClass("selectedstartdate");

        $('#drangefrom').html(selectedDate);
        $('#hdrangefrom').val(selectedDate);

        startonly = true;
    }

    if ($(obj).hasClass("hasauction")) {
        $(obj).addClass("mixd");
    }

    if (!startonly) {
        var std = $(".selectedstartdate").text();
        var end = $(".selectedenddate").text();

        if ($("#AucCalPrev td").hasClass("selectedenddate")) {
            enddatePrev = true;
        }
        else if ($("#AucCalCurr td").hasClass("selectedenddate")) {
            enddateCurr = true;
        }

        //is there a start date
        if ($("#AucCalPrev td").hasClass("selectedstartdate")) {
            startdatePrev = true;
        }
        else if ($("#AucCalCurr td").hasClass("selectedstartdate")) {
            startdateCurr = true;
        }

        if (swap) {
            var tmp = std;
            std = end;
            end = tmp;

            var tmpf = $('#drangefrom').html();
            var tmpt = $('#drangeto').html();

            $('#drangefrom').html(tmpt);
            $('#hdrangefrom').val(tmpt);

            $('#drangeto').html(tmpf);
            $('#hdrangeto').val(tmpf);
        }

        if (startdatePrev && enddateCurr || startdateCurr && enddatePrev) {
            //highlight after start date
            $("#AucCalPrev .no_underline").each(function () {
                if (parseInt($(this).text()) != NaN && (parseInt($(this).text()) >= parseInt(std))) {
                    //If it is a date with auctions
                    if ($(this).hasClass("hasauction")) {
                        $(this).not(".selectedenddate").not(".selectedstartdate").addClass("selectedmidmix");
                    }
                    else {
                        $(this).not(".selectedenddate").not(".selectedstartdate").addClass("selectedmid");
                    }
                }
            });
            $("#AucCalCurr .no_underline").each(function () {
                if (parseInt($(this).text()) != NaN && (parseInt($(this).text()) <= parseInt(end))) {
                    if ($(this).hasClass("hasauction")) {
                        $(this).not(".selectedenddate").not(".selectedstartdate").addClass("selectedmidmix");
                    }
                    else {
                        $(this).not(".selectedenddate").not(".selectedstartdate").addClass("selectedmid");
                    }
                }
            });
        }
        else if (startdateCurr && enddateCurr) {
            $("#AucCalCurr .no_underline").each(function () {
                if (parseInt($(this).text()) != NaN && (parseInt($(this).text()) >= parseInt(std)) && (parseInt($(this).text()) <= parseInt(end))) {
                    if ($(this).hasClass("hasauction")) {
                        $(this).not(".selectedenddate").not(".selectedstartdate").addClass("selectedmidmix");
                    }
                    else {
                        $(this).not(".selectedenddate").not(".selectedstartdate").addClass("selectedmid");
                    }

                }
            });
        }
        else if (startdatePrev && enddatePrev) {
            $("#AucCalPrev .no_underline").each(function () {
                if (parseInt($(this).text()) != NaN && (parseInt($(this).text()) >= parseInt(std)) && (parseInt($(this).text()) <= parseInt(end))) {
                    if ($(this).hasClass("hasauction")) {
                        $(this).not(".selectedenddate").not(".selectedstartdate").addClass("selectedmidmix");
                    }
                    else {
                        $(this).not(".selectedenddate").not(".selectedstartdate").addClass("selectedmid");
                    }
                }
            });
        }
    }
    return obj;
}

function makeMapPoint(arr, pid, address, imgurl, linkurl, lat, lon) {
    if (lat != null && lon != null) {
        arr.push(new prop(pid, address, imgurl, linkurl, lat, lon));
    }

}
function renderStateArr(name, points) {

    mappoints.push({ statename: name, points: points });
}

var gmarkers = [];


function createMarker(point, name, html, category, map) {


    /* map marker */
    var image = new google.maps.MarkerImage(
	  '/resources/images/map/housesmall.png'
    //new google.maps.Size(47, 50),
    //new google.maps.Point(0, 0),
    //new google.maps.Point(0, 35)
	);

    var shadow = new google.maps.MarkerImage(
	  '/app_themes/wwm/images/map/shadow.png',
		new google.maps.Size(62, 35),
		new google.maps.Point(0, 0),
		new google.maps.Point(0, 35)
	);

    var shape = {
        coord: [27, 0, 30, 1, 32, 2, 34, 3, 35, 4, 36, 5, 38, 6, 39, 7, 39, 8, 39, 9, 39, 10, 38, 11, 37, 12, 33, 13, 34, 14, 34, 15, 33, 16, 32, 17, 31, 18, 27, 19, 28, 20, 28, 21, 27, 22, 26, 23, 22, 25, 23, 26, 24, 27, 24, 28, 24, 29, 24, 30, 24, 31, 24, 32, 23, 33, 22, 34, 17, 34, 16, 33, 15, 32, 15, 31, 14, 30, 14, 29, 15, 28, 15, 27, 16, 26, 17, 25, 13, 23, 12, 22, 11, 21, 11, 20, 12, 19, 8, 18, 7, 17, 6, 16, 5, 15, 5, 14, 6, 13, 2, 12, 1, 11, 0, 10, 0, 9, 0, 8, 0, 7, 1, 6, 3, 5, 4, 4, 5, 3, 7, 2, 9, 1, 12, 0, 27, 0],
        type: 'poly'
    };

    var marker = new google.maps.Marker({
        draggable: false,
        raiseOnDrag: false,
        icon: image,
        //shadow: shadow,
        html: html,
        map: map,
        position: point,
        title: name

    });


    //var marker = new google.maps.Marker({ position: point, title: name, map:map });
    // === Store the category and name info as a marker properties ===
    marker.mycategory = category;
    marker.myname = name;


    //var infoWindow = new google.maps.InfoWindow({
    //    content: html
    //});


    ////

    //    map.panTo(marker.position);


    //    google.maps.event.addListener(marker, "mouseover", function (event) {
    //        infoWindow.open(map, marker);

    //        //google.maps.event.addListener(map, "idle", function (event) {
    //        map.setZoom(map.getZoom() + 1);

    //        google.maps.event.addListener(map, 'tilesloaded', function (event) {
    //            if (map.getZoom() < 12) {
    //                map.setZoom(map.getZoom() + 1);
    //            }
    //        });

    //        //});



    //        //alert(map.getZoom());



    //        //        smoothZoomIn(map, 13, map.getZoom()); //

    //        //map.setZoom(13);

    //    });


    ////


    google.maps.event.addListener(infoWindow, 'closeclick', function () {
        this.setMap(null); //removes the marker 
        map.setZoom(6);
        //map.setCenter(XMapOriginalXY);
        map.panTo(XMapOriginalXY);

    });



    google.maps.event.addListener(marker, 'click', function () {
        //var tempmark = this;
        //map.setCenter(this.position);
        map.setZoom(15);

        infoWindow.height = 100;
        infoWindow.width = 200;
        infoWindow.setContent(this.html);
        infoWindow.open(map, this);

        //alert(map.getZoom());
        // google.maps.event.addListener(map, 'tilesloaded', function (event) {
        //     if (map.getZoom() < 12) {
        //         map.setZoom(map.getZoom() + 1);
        //     }
        // });


        //        smoothZoomIn(map, 13, map.getZoom()); //



        map.panTo(this.position);
        map.panBy(60, -60); //first is horizontal, other is vert


    });

    //google.maps.event.addListener(marker, "mouseout", function () {
    //infoWindow.close();
    //map.setZoom(6);
    //map.setCenter(XMapOriginalXY);
    //smoothZoomOut(map, 6, map.getZoom()); //
    //});

    gmarkers.push(marker);
    marker.setMap(map);
}


$('#side_bar').delegate('div', 'click mouseover mouseout', function (event) {

    if (event.type == 'mouseover') {
        $(this)
        .css('background-color', 'red');
    } else {

        $(this)
        .css('background-color', 'white');

        //map.setZoom(map.getZoom() - 2);

        //  google.maps.event.addListener(map, 'tilesloaded', function (event) {
        //      if (map.getZoom() != 6) {
        //          map.setZoom(map.getZoom() - 1);
        //      }
        //   });


    }
});


var XMapOriginalXY;

// the smooth zoom function
function smoothZoomIn(map, max, cnt) {
    if (cnt >= max) {
        return;
    }
    else {
        z = google.maps.event.addListener(map, 'zoom_changed', function (event) {
            google.maps.event.removeListener(z);

            google.maps.event.addListener(map, 'tilesloaded', function (event) {
                self.smoothZoomIn(map, max, cnt + 1);
            });
        });
        setTimeout(function () { map.setZoom(cnt) }, 160);
    }
}
function smoothZoomOut(map, min, cnt) {
    if (cnt <= min) {
        return;
    }
    else {
        z = google.maps.event.addListener(map, 'zoom_changed', function (event) {
            google.maps.event.removeListener(z);

            google.maps.event.addListener(map, 'tilesloaded', function (event) {
                self.smoothZoomOut(map, min, cnt - 1);
            });

        });
        setTimeout(function () { map.setZoom(cnt) }, 160);
    }
}
function show10XStateMap(key, e) {
    var geocoder = new google.maps.Geocoder();
    $('#side_bar').empty();

    geocoder.geocode({ 'address': key + ', US' }
        , function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

                infoWindow = new google.maps.InfoWindow({
                    content: 'loading...'
                });

                var options = { zoom: 6, center: results[0].geometry.location, mapTypeId: google.maps.MapTypeId.ROADMAP, enableContinuousZoom: true };
                var Xmap = new google.maps.Map(document.getElementById('STATE_MAP'), options);
                XMapOriginalXY = results[0].geometry.location;
                //$('#side_bar').clear();


                var temp = [];

                $.each(mappoints, function (index, value) {
                    if (value.statename == key) {
                        temp = value;

                    }
                });

                for (var i = 0; i < temp.points.length; i++) {
                    // obtain the attribues of each marker
                    var lat = parseFloat(temp.points[i].lat);
                    var lng = parseFloat(temp.points[i].lon);




                    var point = new google.maps.LatLng(lat, lng);

                    var address = temp.points[i].addr;

                    var name = '';  //markers[i].getAttribute("name");
                    var html = "<br><img src='" + temp.points[i].imgurl + "' /><br><a href='" + temp.points[i].linkurl + "'><b>" + address + "<\/b></a>";

                    var category = ''; //markers[i].getAttribute("category");
                    // create the marker
                    createMarker(point, name, html, category, Xmap);

                    $('#Content_Address').html('<h3>Properties in ' + key + '</h3>');
                    $('#side_bar').append('<div class="stateName" style="clear:both;margin-top:5px;margin-bottom:5px;" onmouseover="google.maps.event.trigger(gmarkers[' + i + '],\'click\');" >' + address + '</div>');
                    //statemap.addOverlay(marker);



                }

            }
        });

    $('#statesholder')
        .block(
            { message: $('#STATE_MAP_HOLDER'),
                css: { cursor: 'pointer', width: '800px', height: '500px', padding: '15px', top: '0px', border: 'none' },
                overlayCSS: { cursor: 'pointer', backgroundColor: '#fff', opacity: 1 },
                centerX: true,
                centerY: false
            });
    gmarkers = [];
}

function emptyit() {
    $('body').unblock();

}

function goToByScroll(id) {
    $('html,body').animate({ scrollTop: $(id).offset().top }, 'slow');
}

function mapPropertiesFor10X(items) {

    
var test = $.map(items, 
    function(i) { 
        if(i.id !== "")
        {
            return i.id
        }
    }
).join(',');




$("#frameholder").empty();
 goToByScroll($(".searchbar"));

$("#frameholder").append("<iframe id='Mapframe' height='500' width='100%' style='border: none;overflow:hidden' src='/sellerportal/auctionnearyoumap.aspx?type=all&city=null&BigMap=1&Clickable=true&ZipCode=-1&props=" + test + "' />");

//window.frames["Mapframe"].location.reload();
// city = geoip_city();
$("#maploc").html("Location: Various");
//$('#divcontent')
$('html body')
                .block(
                    { message: $('#MAP_HOLDER'),
                        css: { cursor: 'pointer', width: '90%', height: '500px', padding: '0px', top: '200px', border: 'none', backgroundColor: 'transparent' },
                        overlayCSS: { cursor: 'pointer', backgroundColor: '#fff', opacity: .7 },
                        centerX: true,
                        centerY: false
                    });

}

function mapPropertiesForState(id,fullname) {

    $("#frameholder").empty();
    // goToByScroll("ulNavList");
    
    $("#frameholder").append("<iframe id='Mapframe' height='500' width='100%' style='border: none;overflow:hidden' src='/sellerportal/AuctionNearYouMap.aspx?type=all&city=null&Clickable=true&BigMap=1&MarketValue=0&ZipCode=-1&state=" + id + "' />");
    
    //window.frames["Mapframe"].location.reload();
    // city = geoip_city();
    $("#maploc").html("Location: " + fullname);
    //$('#divcontent')
    $('html body')
                .block(
                    { message: $('#MAP_HOLDER'),
                        css: { cursor: 'pointer', width: '90%', height: '500px', padding: '0px', top: '200px', border: 'none', backgroundColor: 'transparent' },
                        overlayCSS: { cursor: 'pointer', backgroundColor: '#fff', opacity: .7 },
                        centerX: true,
                        centerY: false
                    });

    //$('.closeit').click(emptyit());

                    goToByScroll($(".searchbar"));

}

function showAdvancedSearch() {
    $('#advancedsearchmain').slideToggle('slow', function () {
        // Animation complete.
    });

    $('#as_availablefilters').empty();
    area = 1;
    proxy.invoke("getTagGroupsByDivision", { 'iDiv': 1 },
        function (result) {
            $('#as_availableasdivs').empty();

            var taggroups = eval('(' + result + ')');
            $("#as_taggrouptemplate").tmpl(taggroups.pop()).appendTo("#as_availableasdivs").promise().done(function () {
                // Add onclick handlers for division template items

                $('#as_availablefilters').empty();



                $("#as_taggrouptemplate").tmpl(taggroups).appendTo("#as_availablefilters").promise().done(function () {

                    var i = 0;


                    $("#as_availablefilters select").each(function (e) {


                        var item = this;

                        $(this).selectToUISlider({
                            labels: 0,
                            //labelSrc: "text",
                            sliderOptions: {
                                change: function (e, ui) {
                                    //alert($(item).val());
                                    //alert(-$("#as_availableasdivs .as_division").val());
                                    item.selectedIndex = ui.value;
                                    aselectedfilters = [];
                                    $('#as_group_' + -$("#as_availableasdivs .as_division").val() + ' select').each(function () {
                                        aselectedfilters.push($(this).val());
                                    });

                                    
                                    //alert($(item).val());
                                    area = 0;
                                    stype = "Targeted";
                                    //aselectedfilters.push($(item).val());

                                    SearchTags = aselectedfilters.join("~");
                                    //alert(SearchTags);
                                    getAdvancedProperties();
                                    //alert('changed' + $(this).eq(ui.value).val());
                                }
                            }

                        });

                    }).hide();


                    //                        //alert($(this));
                    //                        var select = $(this);

                    //                        select
                    //                        var slider = $("<div id='slider_" + i + "'></div>").insertAfter(select).slider({
                    //                            min: select[0],
                    //                            max: select[select.length],
                    //                            range: "min",
                    //                            value: select[0].selectedIndex + 1,
                    //                            slide: function (event, ui) {
                    //                                select[0].selectedIndex = ui.value - 1;
                    //                            }
                    //                        });
                    //                        //                        $("#minbeds").change(function () {
                    //                        //                            slider.slider("value", this.selectedIndex + 1);
                    //                        //                        });
                    //                        i++;
                    //                    });







                    $("#as_availableasdivs .as_division").on('change', function () {
                        //alert($(this).val());
                        //alert($('as_' + -this.id));
                        //$('.as_group').hide().promise().done(
                        first_load = false;
                        //slider.slider("value", this.selectedIndex + 1);

                        var item = -$(this).val();

                        // alert('#as_' + -$(this).val());
                        $('.as_group').each(function (e) {
                            //alert($(this).attr('id'));
                            if ($(this).attr('id') == ('as_group_' + item)) {

                                $(this).show();
                            }
                            else {
                                $(this).hide();
                            }
                            //$(this).show();
                        }).promise().done(function () {
                            //alert('done');
                        });

                    });
                    //var detailTemplate = $("#as_taggrouptemplate").tmpl(taggroups).appendTo("#as_availablefilters");
                });


                $('.as_group').each(function (e) {
                    if (first_load && $(this).attr('id') == "as_group_" + 1) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }

                });

                //                $('.as_group').hide().promise().done(function () {
                //                    if (first_load) {
                //$('#as_group_1').show();

                //                    }
                //                });


                $("input.mf").uniform();

            });

        },
        function (error) {
        });



        

    }



    function getAdvancedProperties() {
        
        var func, args;
        aselectedfilters = [];
        aselectedfilters = SearchTags.split('~');

        switch (isPastResults) {
            case true:
                func = "getProperties";
                args = { 'sType': stype, 'sArgs': sargs, 'area': area, 'city': SearchCity, 'state': SearchState, 'iPageSize': i10XPullSize, 'iOffset': iOffset, 'sFilters': aselectedfilters.join(',') == '' ? '' : aselectedfilters.join(','), 'iStatus': isPastResults == true ? 2 : 1, 'iSort': ddlsortvalue };

                break;
            case false:
                func = "getProperties";
                args = { 'sType': stype, 'sArgs': sargs, 'area': area, 'city': SearchCity, 'state': SearchState, 'iPageSize': i10XPullSize, 'iOffset': iOffset, 'sFilters': aselectedfilters.join(',') == '' ? '' : aselectedfilters.join(','), 'iStatus': isPastResults == true ? 2 : 1, 'iSort': ddlsortvalue };

                break;
            default:
                func = "getProperties";
                args = { 'sType': stype, 'sArgs': sargs, 'area': area, 'city': SearchCity, 'state': SearchState, 'iPageSize': i10XPullSize, 'iOffset': iOffset, 'sFilters': aselectedfilters.join(',') == '' ? '' : aselectedfilters.join(','), 'iStatus': isPastResults == true ? 2 : 1, 'iSort': ddlsortvalue };
        }

        proxy.invoke(func, args,
            function (result) {

                var aprops = eval('(' + result + ')');


                totalprops = aprops.iTotalCount;

                //$('#as_totalcount').html(totalprops).effect('highlight', { color: totalprops > 0 ? "#ffff99" : "#ff0000" }, 500);
                $('#as_totalcount').html("0");

                //                var from = { property: 0 };
                //                var to = { property: totalprops };

                //                $(from).animate(to, {
                //                    duration: 1000,
                //                    step: function () {
                //                        alert(this.property);
                //                        $('#as_totalcount').html(this.property); //console.log('Currently @ ' + this.property);
                //                    }
                //                });

                //                $(function () {
                //                    //alert($('#as_totalcount').html());
                //                    var current = $('#as_totalcount').html() != '' ? parseInt($('#as_totalcount').html()) > totalprops ? totalprops : $('#as_totalcount').html() : 0;
                //                    var finish = totalprops;
                //                    var miliseconds = 1000;
                //                    var rate = 1;

                //                    var counter = setInterval(function () {
                //                        if (current >= finish) current = clearInterval(counter);
                //                        $('#as_totalcount').html(current);
                //                        current = parseInt(current) + parseInt(rate);
                //                    }, miliseconds / (finish / rate));
                //                });
                //alert(totalprops);
                // animateNumber($('#as_totalcount'), totalprops);
                //$('#as_totalcount').animateNumber(totalprops);
                slotmachine('as_totalcount', totalprops);
            },
            function (error) {
            });
        return false;
    }

    function animateNumber($input, num, duration, easing) {
        $input
        .data("start", parseInt($input.val()))
        .animate({ "val": parseInt(num) },
        {
            easing: easing == undefined ? "linear" : easing,
            duration: duration == undefined ? 500 : parseInt(duration),
            step: function (fin, obj) {
                var $this = jQuery(this);
                var start = parseInt($this.data("start"));
                alert(parseInt((fin - start) * obj.state) + start);
                $this.val(parseInt((fin - start) * obj.state) + start);
            }
        });
    }

    (function ($) {
        $.fn.animateNumber = function (to) {
            var $ele = $(this),
            num = parseInt($ele.html()),
            up = to > num,
            num_interval = Math.abs(num - to) / 90;

            var loop = function () {
                num = Math.floor(up ? num + num_interval : num - num_interval);
                if ((up && num > to) || (!up && num < to)) {
                    num = to;
                    clearInterval(animation)
                }
                $ele.html(num);
            }

            var animation = setInterval(loop, 5);
        }
    })(jQuery);


    function slotmachine(id, changeto) {
        var thisid = '#' + id;
        var $obj = $(thisid);
        $obj.css('opacity', '.3');
        var original = $obj.text();

        var spin = function () {
            return Math.floor(Math.random() * 10);
        };

        var spinning = setInterval(function () {
            $obj.text(function () {
                var result = '';
                for (var i = 0; i < original.length; i++) {
                    result += spin().toString();
                }
                return result;
            });
        }, 50);

        var done = setTimeout(function () {
            clearInterval(spinning);
            $obj.text(changeto).css('opacity', '1').effect('highlight', { color: changeto > 0 ? "#ffff99" : "#ff0000" }, 500);
   
        }, 1000);
    }
