﻿var _PortalID;
var _SitePageURL;

$(document).ready(function() {

    _PortalID = dnn.getVar('PortalID');
    _SitePageURL = dnn.getVar('SitePageURL');

    if (querySt("msg") != '' && querySt("msgtype") != '') {
        RaiseMessage(querySt("msgtype"), querySt("msg").replace(/\+/g, ' '), "msgcontainer");
    }
    
    // Initialize Location AutoComplete
    $('#txtSite').autocomplete('../../../../desktopmodules/sitebuilder/js/LookUp.ashx/ProcessRequest',
        {
            delay: 10,
            minChars: 4,
            matchSubset: 1,
            matchContains: 1,
            cacheLength: 10,
            maxItemsToShow: 10,
            onItemSelect: selectItem,
            onFindValue: findValue,
            formatItem: formatItem,
            autoFill: false,
            extraParams: { portalid: _PortalID }
        }
    );
    if (dnn.getVar('UserID') > 0) {
        $('#lnkmysite').show();
        $('#lnkmysite').attr("href", _SitePageURL);
    }
});

function selectItem() {
    lookupAjax();
}

function lookupAjax() {
    var oSuggest = $("#txtSite")[0].autocompleter;
    oSuggest.findValue();
    return false;
}

function findValue(li) {
    if (li == null) return RaiseMessage("info", "Sorry, but we're unable to find '" + $("#txtLocation").attr("value") + "'.", "msgcontainer");

    // get LocationID from AutoComplete
    if (!!li.extra) _SiteID = li.extra[0];
    $('#lnkSearch').attr("href", _SitePageURL + '#site.' + li.extra[0]);  //location.hash = 'site.' + li.extra[0];  // FetchSite(li.extra[0]);
}

function formatItem(row) {
    return row[0]
}

function querySt(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
    return ''
}

function RaiseMessage(msgtype, msg, placeholder) {
    // add message div to placeholder
    $('#' + placeholder).empty();
    $("<div id='" + placeholder + "_pnlmsg' class='" + msgtype + "'><div class='leftcol'>" + unescape(msg) + "</div><div class='rightcol'><a id='" + placeholder + "_close' href=''><img alt='x' src='/desktopmodules/sitebuilder/images/close.png' /></a></div></div>").fadeIn("slow").appendTo('#' + placeholder);
    $('#' + placeholder + '_close').click(function() {
        $(this).unbind("click");
        $(this).fadeOut("slow", function() { $('#' + placeholder).empty(); });
        return false;
    });
}