
/* Override ASP.NET ValidationSummaryOnSubmit */
function ValidationSummaryOnSubmit(validationGroup) {
    if (typeof (Page_ValidationSummaries) == "undefined") {
        return;
    }
    var summary, sums, s;
    for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
        summary = Page_ValidationSummaries[sums];
        summary.style.display = "none";
        if (!Page_IsValid && IsValidationGroupMatch(summary, validationGroup)) {
            var i;
            if (summary.showsummary != "False") {
                summary.style.display = "";
                if (typeof (summary.displaymode) != "string") {
                    summary.displaymode = "BulletList";
                }
                switch (summary.displaymode) {
                    case "List":
                        {
                            headerSep = "<br>";
                            first = "";
                            pre = "";
                            post = "<br>";
                            end = "";
                            break;
                        }
                    case "BulletList":
                    default:
                        {
                            headerSep = "";
                            first = "<ul>";
                            pre = "<li>";
                            post = "</li>";
                            end = "</ul>";
                            break;
                        }
                    case "SingleParagraph":
                        {
                            headerSep = " ";
                            first = "";
                            pre = "";
                            post = " ";
                            end = "<br>";
                            break;
                        }
                }

                s = "";
                if (typeof (summary.headertext) == "string") {
                    s += summary.headertext + headerSep;
                }
                s += first;
                for (i = 0; i < Page_Validators.length; i++) {
                    if (!Page_Validators[i].isvalid && typeof (Page_Validators[i].errormessage) == "string") {
                        s += pre + Page_Validators[i].errormessage + post;
                    }
                }
                s += end;
                summary.innerHTML = s;
                window.scrollTo(0, 0);
            }

            if (summary.showmessagebox == "True") {
                s = "";
                if (typeof (summary.headertext) == "string") {
                    s += summary.headertext + "<br>";
                }
                var ctrId;
                var lastValIndex = Page_Validators.length - 1;
                for (i = 0; i <= lastValIndex; i++) {
                    if (!Page_Validators[i].isvalid && typeof (Page_Validators[i].errormessage) == "string") {
                        switch (summary.displaymode) {
                            case "List":
                                {
                                    s += "<p>" + Page_Validators[i].errormessage + "</p>";

                                    break;
                                }
                            case "BulletList":
                            default:
                                {

                                    s += "<p> - " + Page_Validators[i].errormessage + "</p>";
                                    if (!ctrId) {
                                        ctrId = Page_Validators[i].controltovalidate;
                                    }

                                    break;
                                }
                            case "SingleParagraph":
                                {
                                    s += Page_Validators[i].errormessage + " ";
                                    break;
                                }
                        }
                    }
                }
                showAlert(s, ctrId, "error");

            }

        }

    }

}


function showAlert(innerMsg, controlId, msgType, caption, userAction) {

    this.resize = function(form) {
        var mH = $(".page-alert .m-box").height();
        var mW = $(".page-alert .m-box").width();
        var maskHeight = $(document).height();
        var maskWidth = $(document).width();
        var winH = $(window).height();
        var winW = $(window).width();
        $(".m-pop-up-background").width(maskWidth);
        $(".m-pop-up-background").height(maskHeight);
        form.css('top', winH / 2 - mH / 2 + 'px');
        form.css('left', winW / 2 - mW / 2 + 'px');
    }

    var msg = innerMsg;
    if (typeof (innerMsg) == "object") {
        msg = "";
        for (var i = 0; i < innerMsg.length; i++) {
            msg += "<p>-" + innerMsg[i].Message + "</p>";

        }

    }
    if (typeof (msgType) != "string") {
        msgType = "error";
    }
    if (typeof (caption) != "string" || caption == "") {
        if (msgType == "info") {
            caption = Bernco_AlertBoxInformationCaption;
        }
        else
            if (msgType == "confirm") {
            caption = Bernco_AlertBoxQuestionCaption;
        }
        else {
            caption = Bernco_AlertBoxErrorCaption;
        }
    }

    //e.preventDefault();

    var pageAlert = $(".page-alert");
    pageAlert.show();

    pageAlert.attr("class", "page-alert " + msgType);
    pageAlert.find(".msg").html(msg);
    pageAlert.find("span.title").text(caption);
    //Get the screen height and width  
    var maskHeight = $(document).height();
    var maskWidth = $(document).width();

    var winH = $(window).height();
    var winW = $(window).width();

    var mH = $(".page-alert .m-box").height();
    var mW = $(".page-alert .m-box").width();

    $(".m-pop-up-background").height(maskHeight);
    $(".m-pop-up-background").width(maskWidth);
    $(".m-pop-up-background").fadeTo("slow", 0.2);


    pageAlert.css('top', winH / 2 - mH / 2 + 'px');
    pageAlert.css('left', winW / 2 - mW / 2 + 'px');
    pageAlert.find(".close-button").focus();
    $(window).bind("resize", function() {
        this.resize(pageAlert);
    });

    $(window).bind("scroll", function() {
        this.resize(pageAlert);
    });

    $(".close-button").click(function() {
        pageAlert.hide();
        $(window).unbind("scroll");
        $(window).unbind("resize");
        $(".m-pop-up-background").fadeOut("slow");
        if (controlId) {
            var ctr = $find(controlId);
            if (ctr && typeof (ctr.get_inputDomElement) == 'function') {
                ctr = $find(controlId).get_inputDomElement();
            }
            else
                if (ctr && typeof (ctr.focus) == 'function') {

            }
            else {
                ctr = document.getElementById(controlId);
            }
            ctr.focus();

        }
        messageAcction({ "MsgType": msgType, "Button": "ok", "Action": userAction });
        userAction = "";
        $(this).unbind("click");
    });

    $(".submit-button.yes").click(function() {
        messageAcction({ "MsgType": msgType, "Button": "yes", "Action": userAction });
        userAction = "";
        pageAlert.hide();
        $(".m-pop-up-background").fadeOut("slow");
        if (controlId) {
            document.getElementById(controlId).focus();
        }
        $(this).unbind("click");
    });

}

function messageAcction(arg) {

}

/*******************************Most Requested Action******************************************************/

function MostRequestedAction(link, e) {
    //e.preventDefault(); 
    var popUp = $(".most-requested");

    //Get the screen height and width  
    var maskHeight = $(document).height();
    var maskWidth = $(document).width();

    var winH = $(window).height();
    var winW = $(window).width();

    $(".m-pop-up-background").height(maskHeight);
    $(".m-pop-up-background").width(maskWidth);
    $(".m-pop-up-background").fadeTo("slow", 0.2);

    popUp.show();
    popUp.css('top', winH / 2 - popUp.height() / 2 + 'px');
    popUp.css('left', winW / 2 - popUp.width() / 2 + 'px');

    $(window).resize(function() {
        winH = $(window).height();
        winW = $(window).width();
        $(".m-pop-up-background").width(winW);
        $(".leaving-pop-up").css('top', winH / 2 - popUp.height() / 2 + 'px');
        $(".leaving-pop-up").css('left', winW / 2 - popUp.width() / 2 + 'px');
    });
    $("a.close-link").click(function() {
        popUp.hide();
        $(".m-pop-up-background").fadeOut("slow");
    });

}

$(document).ready(function() {

    /*********************Leaving Site************************************************************************/

    $("a").click(function(e) {

        var getFormatedDomain = function(domain) {
            var result = domain;
            var hostParts = domain.split(".");
            if (hostParts.length >= 2) {
                result = hostParts[hostParts.length - 2] + "." + hostParts[hostParts.length - 1];
            }
            return result;
        }
        var skip = function(domain) {
            var result = false;
            if (typeof (Logic_GlobalParams_SkipDomainListOnLeavingSiteAction) != "undefined") {

                var list = Logic_GlobalParams_SkipDomainListOnLeavingSiteAction;
                for (var i = 0; i < list.length; i++) {
                    if (this.hostname.indexOf(list[i]) != -1) {
                        result = true;
                        break;
                    }
                }
            }
            return result;
        }
        var currentDomain = getFormatedDomain($(document).context.domain)
        if (this.hostname && this.hostname.indexOf(currentDomain) == -1) {
            //Skip special hosts
            if (skip(this.hostname)) {
                return true;
            }
            LeavingSiteAction(this, e);
            return false;
        }
    });


    var leavingSiteDelay;
    var isBreak;
    var timeIntervalId;
    function LeavingSiteAction(link, e) {
        //e.preventDefault(); 
        leavingSiteDelay = Logic_GlobalParams_LeavingBerncoSiteDelay;
        isBreak = false;
        setGlassImg();
        $(".glass").attr("class", "glass p0");
        var popUp = $(".m-box");
        popUp.find(".seconds").text(leavingSiteDelay);

        //Get the screen height and width  
        var maskHeight = $(document).height();
        var maskWidth = $(document).width();

        var winH = $(window).height();
        var winW = $(window).width();



        $(".m-pop-up-background").height(maskHeight);
        $(".m-pop-up-background").width(maskWidth);
        $(".m-pop-up-background").fadeTo("slow", 0.2);

        $(".leaving-pop-up").show();

        var mH = $(".leaving-pop-up .m-box").height();
        var mW = $(".leaving-pop-up .m-box").width();

        $(".leaving-pop-up").css('top', winH / 2 - mH / 2 + 'px');
        $(".leaving-pop-up").css('left', winW / 2 - mW / 2 + 'px');
        timeIntervalId = window.setInterval(function() {
            updateTime(link, popUp);
        }, 1000);

        $(window).resize(function() {
            winH = $(window).height();
            winW = $(window).width();
            $(".m-pop-up-background").width(winW);
            $(".leaving-pop-up").css('top', winH / 2 - mH / 2 + 'px');
            $(".leaving-pop-up").css('left', winW / 2 - mW / 2 + 'px');
        });
        $("span.close-button").click(function() {
            $(".leaving-pop-up").hide();
            $(".m-pop-up-background").fadeOut("slow");
            isBreak = true;
            window.clearInterval(timeIntervalId);

        });

    }

    function setGlassImg() {

        var totalDelay = Logic_GlobalParams_LeavingBerncoSiteDelay;
        var prs = 100 - parseFloat(leavingSiteDelay / totalDelay) * 100;
        if (prs <= 0) {
            $(".glass").attr("class", "glass p0");
        }
        else
            if (prs <= 10) {
            $(".glass").attr("class", "glass p10");
        }
        else
            if (prs <= 20) {
            $(".glass").attr("class", "glass p20");
        }
        else
            if (prs <= 30) {
            $(".glass").attr("class", "glass p30");
        }
        else
            if (prs <= 50) {
            $(".glass").attr("class", "glass p50");
        }
        else
            if (prs <= 70) {
            $(".glass").attr("class", "glass p70");
        }
        else
            if (prs <= 80) {
            $(".glass").attr("class", "glass p80");
        }
        else
            if (prs <= 90) {
            $(".glass").attr("class", "glass p90");
        }
        else {
            $(".glass").attr("class", "glass p100");
        }
    }

    function updateTime(link, popUp) {
        if (isBreak) {
            return;
        }
        if (leavingSiteDelay <= 0) {
            window.location = link.href;
            isBreak = true;
        }
        else {
            leavingSiteDelay--;
        }
        setGlassImg();
        popUp.find(".seconds").text(leavingSiteDelay);

    }


    /****************************Search  Information*************************************/
    $(".most-requested-button").click(function(e) {
        MostRequestedAction(this, e);
    });


    $(".text.county-services").click(function() {
        window.location = county_services_page_utl;
    });
    $(".text.elected-officials").click(function() {
        window.location = elected_officials_page_utl
    });

    $("#elected_officials_arrow_link").click(function(e) {
        var menu = $find(elected_officials_menu_id);
        if (menu) {
            menu.show(e);
        }

    });



    /*********************Select*************************************/
    eld_select();

    function eld_select() {
        $(document).not('div.select').live("click", function(e) {
            e.preventDefault();
            $('.select ul').slideUp();
            $('.select').removeClass('active-block');
        });

        $('.select div a').live("click", function() {
            if ($(this).parent().parent().hasClass('active-block')) {
                $('.select ul').slideUp();
                $('.select').removeClass('active-block');
            }
            else {
                $('.select ul').slideUp();
                $(this).parent().parent().children('ul').slideDown();
                $(this).parent().parent().addClass('active-block');
                return false
            }
        });

        $('.select li a').live("click", function() {
            fs = $(this).text();
            $(this).parent().parent().parent().children().children('a').text(fs);
            $('.select ul li').removeClass('active');
            $(this).parent().addClass('active');

            if ($(this).parent().attr('value') != 'undefined' && $(this).parent().attr('value') != -1 && $(this).parent().attr('value') != 0) {
                $(this).parent().parent().next().attr('value', $(this).parent().attr('value'));
            }
            else {
                $(this).parent().parent().next().attr('value', $(this).parent().attr('name'));
            }

            $('.select ul').slideUp();
            $('.select').removeClass('active-block');
        });
    }

});
/********************************Print Functionality*********************************************************/
function printPage() {
    var prefex = "_" + Math.random() * 1000;
    prefex = prefex.replace(".", "");
    var styleLinks = $("<p>").append($("link[rel='stylesheet']").clone()).html();
    var scriptLinks = $("<p>").append($("script[src*='/upload/images/']").clone()).html();
    var printSections = $(".print-section");
    if (printSections.length > 0) {
        printSections = $(printSections[printSections.length - 1]).clone();
        if (w = window.open("about:blank", "Print" + prefex)) {
            var obj = buidPrintHtmlEvent(printSections);
            if (obj) {
                new_html = obj.html();
            }

            var html =
                    "<html>" +
                        "<head>" +
                            styleLinks +
                            "<link rel=\"stylesheet\" type=\"text/css\" href=" + upload_url + "/Themes/" + Logic_GlobalParams_SiteTheme + "/css/print.css>" +
                         "</head>" +
                        "<body onload=\"window.print();\">" +
                            new_html +
                        "</body>" +

                    "</html>";

            w.document.write(html);
            w.document.close();
        }
    }
    else {
        window.print();
    }
}
/**********************Video Preview****************************************/
function nodeCollapsing(sender, e) {
    //    e._cancel = true;
}
function nodeExpanding(sender, e) {
    //  var links = $(e._node._element).find("a");
    //  window.location = links[0].href;
    // e._cancel = true;
}
function nodeClicking(sender, e) {
    if (e._node._properties._data.cssClass.indexOf("video-item") != -1) {
        e._cancel = true;
    }
    if (e._node._properties._data.cssClass.indexOf("client-expand") != -1) {
        e._cancel = true;
        var isExpanded = e._node.get_expanded();
        if (isExpanded) {
            e._node.collapse();
        }
        else {
            e._node.expand();
        }
    }

}

/****************************Video Preview*********************/
function playVideo(params) {
    $('#move_player').html("");
    $('#move_player').flash({
        src: Logic_GlobalParams_VideoPlayerSWF,
        width: '320',
        height: '213',
        allowfullscreen: 'true',
        allowscriptaccess: 'always',
        wmode: 'opaque',
        flashvars: {
            backcolor: '0xFFFFFF',
            frontcolor: '0x666666',
            lightcolor: '0xFF6600',
            thumbsinplaylist: 'true',
            width: '320',
            height: '213',
            streamURL: params.streamURL,
            autoplay: params.autoplay,
            preview: params.preview,
            liveStream: params.liveStream
        }
    },
    { version: 8 });
}

function initFlashPlayerVideo(id, fileName, imageUrl, isAutoPlay) {
    var url = Logic_GlobalParams_VideoMediaServerURL + "/vod/" + fileName;
    playVideo({ streamURL: url, autoplay: isAutoPlay, preview: imageUrl });
    if (isAutoPlay) {
        $.get(video_ajax_action_page_utl, { p_v: id });
    }
    $(window).scrollTop(100);

}

function checkLiveStream(objectId, url) {
    var wrapper = $("<div></div>");
    wrapper.attr("id", objectId + "Fake");
    wrapper.addClass("live-stream-checker");
    wrapper.appendTo("body");


    wrapper.flash({
        src: "upload/videos/LiveStreamChecker.swf",
        width: '1',
        height: '1',
        allowfullscreen: 'true',
        allowscriptaccess: 'always',
        wmode: 'opaque',
        flashvars: {
            backcolor: 'transparent',
            width: '1',
            height: '1',
            streamURL: url,
            id: objectId,
            timeCheck: 15,
            callBack: "liveStreamConnectChanged"
        }
    },
    { version: 8 });
}

function liveStreamConnectChanged(arg) {
    if (arg.hasConnect) {
        $("#" + arg.id).removeClass("off");
        $("#" + arg.id).addClass("on");
    }
    else {
        $("#" + arg.id).removeClass("on");
        $("#" + arg.id).addClass("off");
    }
}


function initFlashPlayerLiveVideo(id, url, imageUrl, isAutoPlay) {

    playVideo({ streamURL: url, autoplay: isAutoPlay, preview: imageUrl, liveStream: true });
    $(window).scrollTop(100);
}


$(document).ready(function() {
    if (typeof (liveStreamData) != "undefined") {
        $(liveStreamData).each(function(index, item) {
            checkLiveStream(item.id, item.url);
        });
    }
});

/******************************Page System Messages************************************/
function SystemMsg() {
    try {
        this.SystemMsgList = system_msg_list;
    }
    catch (error) {
        this.SystemMsgList = [];
    }


    this.getMsg = function(id) {
        var result = null;
        $(this.SystemMsgList).each(function(index, item) {
            if (item.ID == id) {
                result = item;
                return;
            }
        });
        return result;
    };

    this.getMsgsByType = function(type) {
        var resutl = [];
        $(this.SystemMsgList).each(function(index, item) {
            if (item.Type == type) {
                resutl.push(item);
            }
        });
        return resutl;
    };

    this.show = function() {
        $('a.alert-close').click(function() {
            messages.close(this);
        });

        this.SystemMsgList.length > 0 ? $(".alert").show() : $(".alert").hide();
    };

    this.showOneMsg = function(type) {

        var lastMsg = this.getLastMsg(type);
        if (lastMsg) {
            $("input[value=" + lastMsg.ID + "]").parent().show();
        }

    }

    this.close = function(sender) {
        var msgList = this.SystemMsgList;
        $(".alert").fadeOut(Logic_GlobalParams_AlertMessageHideDuration, function() {
            $(msgList).each(function(index, msg) {
                if (msg.ShowOnce) {
                    $.cookie('displayed_' + msg.ID, msg.ID, { expires: msg.ExpireDays });
                }
            });

        });
    }


    this.getLastMsg = function(type) {
        var msgs = this.getMsgsByType(type);
        var result = null;
        $(msgs).each(function(index, item) {
            if (!item.Displayed) {
                result = item;
                return;
            }
        });
        return result;
    }

    this.getNextMsg = function(type) {
        var msgs = this.getMsgsByType(type);
        var result = null;
        var i = 0;
        $(msgs).each(function(index, item) {
            if (!item.Displayed) {
                i++;
                if (i == 2) {
                    result = item;
                    return;
                }
            }
        });
        return result;
    }
}

$(document).ready(function() {
    messages = new SystemMsg();
    messages.show();
});
/********************Home Page******************************/
function newsObject() {
    var timer;
    var newsCurrentId = 0;

    this.startSlide = function() {
        var that = this;
        that.stopSlide();
        timer = setInterval(function() {
            var news = that.getNext(that.newsCurrentId);
            that.showSldie(news);
        }, 10000);
    }




    this.stopSlide = function() {
        clearInterval(timer);
    }

    this.showSldie = function(news) {
        if (typeof (news) == "undefined") {
            return;
        }
        var image = $(".home-news-image");
        if (this.newsCurrentId != news.ID) {

            this.newsCurrentId = news.ID;
            $(".home-news-image").fadeOut("slow", function() {
                $(this).attr("src", "");
                $(this).attr("src", news.ImageUrl);
               // $(this).delay(200);
                $(this).fadeIn("slow", function() {
                    $(".home-news-title").text(news.Title);
                    $(".home .sub-string").text(news.Title);
                    $(".home-new-short-text").html(news.ShortText);
                    $(".home-news-continue").attr("href", news.NewsUrl);
                });
            });
        }
    }


    try {
        this.NewsData = home_news_data;
    }
    catch (error) {
        this.NewsData = [];
    }

    this.getNext = function(id) {
        var item = this.getNews(id);
        var curIndex = $(this.NewsData).index(item);
        return curIndex + 1 > this.NewsData.length - 1 ? this.NewsData[0] : this.NewsData[curIndex + 1];
    }

    this.getNews = function(id) {
        var result = null;
        $(this.NewsData).each(function(index, item) {
            if (item.ID == id) {
                result = item;
                return;
            }
        });
        return result;
    };
}

$(document).ready(function() {
    newsHelper = new newsObject();
    newsHelper.newsCurrentId = $("[id$=_currentSlide]").val();
    newsHelper.startSlide();
    $("img.rotator-item").click(function(e) {
        var id = $(this).parent().find("[id$=_itemId]").val();
        var news = newsHelper.getNews(id);
        newsHelper.showSldie(news);
        newsHelper.stopSlide();
    });

    $("div.slider, div.right.dynamic-font-size").mouseenter(function() {
        newsHelper.stopSlide();
    });

    $("div.slider, div.right.dynamic-font-size").mouseleave(function() {
        newsHelper.startSlide();
    });

    $("div.divider").height($("div.page-body-bottom").height() - 10);

    $(".events-calendar.link").click(function() {
        window.location = events_calendar_page_utl;
    });

    $(".polls.banner .images").cycle({
        fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
        random: 1,
        height: 255,
        delay: 1000,
        cleartypeNoBg:true,
        timeout: Logic_GlobalParams_HomeBannersDelayToShow
    });
});

/**********************Alphabetical Index Page*****************************/
$(document).ready(function() {
    var totalHeight = $(".abc-links").height();
    var columnIndex = 1;
    var currentHeight = 0;
    $(".abc-group").each(function(index, item) {
        $(".column-" + columnIndex).append(item);
        currentHeight += $(item).height();
        if (currentHeight > totalHeight / 3 && columnIndex < 3) {
            columnIndex++;
            if (currentHeight - totalHeight / 3 > 100) {
                currentHeight = 0;
                $(".column-" + columnIndex).append(item);
                currentHeight += $(item).height();
            }
            else {
                currentHeight = 0;
            }

        }
    });
});

/**********************FAQ Page*****************************/
$(document).ready(function() {

    $(".faq-question h4").click(function() {

        if ($(this).parent().hasClass("expanded")) {
            $(this).parent().removeClass("expanded");
            $(this).next().slideUp("slow");

        }
        else {

            $(this).parent().addClass("expanded");
            $(this).next().slideDown("slow");
        }

    });

    $(".expand-all").toggle(
        function() {
            $(this).text(Logic_theLibDict_FAQ_CollapseAllText);
            var items = $(this).parent().find(".faq-question h4");
            items.next().slideDown("slow");
            items.parent().addClass("expanded");

        },
        function() {
            $(this).text(Logic_theLibDict_FAQ_ExpandAllText);
            var items = $(this).parent().find(".faq-question h4");
            items.next().slideUp("slow");
            items.parent().removeClass("expanded");
        });

});
/******************************************************/
function OnClientResponseError(sender, args) {
    args.set_cancelErrorAlert(true);
}
/*****************Enable/Disable UI**********************/
function enableUI(enable) {
    this.resize = function() {
        var width = $(document).width();
        var height = $(document).height();
        var winW = $(window).width();
        var winH = $(window).height();
        $(".window-blur").width(width);
        $(".window-blur").height(height);
        var mW = $(".request-progress").width();
        var mH = $(".request-progress").height();
        $(".request-progress").css('top', winH / 2 - mH / 2 + 'px');
        $(".request-progress").css('left', winW / 2 - mW / 2 + 'px');
    }
    if (!enable) {
        $("body").append("<div class=\"window-blur\"></div>");
        $("body").append("<div class=\"request-progress\">&nbsp;</div>");
        this.resize();
        $(window).bind("resize", function() {
            this.resize();
        });
        $(window).bind("scroll", function() {
            this.resize();
        });
    }
    else {
        $(".window-blur").remove();
        $(".request-progress").remove();
        $(window).unbind("resize");
        $(window).unbind("scroll");
    }
}
/*************************Google address***************************/

jQuery.gMap = function() {
    this.wSize = JSON.parse(Logic_GlobalParams_GoogleMapWindowSize);
    this.data = [];
    this.buid = function(selector, params) {
        var dataList = [];
        var elements = $(selector);
        var hasData = params ? true : false;
        $(elements).each(function() {
            var data = { title: "", address: "", position: null, dom: null };
            if (hasData) {
                data.title = params.title || "";
                //data.description = params.description || "";
                //data.phone = params.phone || "";
                data.address = params.address || "";
                if (params.position) {
                    data.position = new google.maps.LatLng(params.position.lat, params.position.lng) || null;
                }
                data.dom = this;
            }
            else {
                var position = $(this).find("span[class=g-position]").text().split(',');
                $(this).find("span[class=g-position]").remove();
                data.title = $(this).html();
                // data.description = "";
                // data.phone = "";

                data.address = $(this).text().replace(new RegExp("\n", "g"), "");
                data.address = jQuery.trim(data.address);
                data.position = position.length > 1 ? new google.maps.LatLng(position[0], position[1]) : null;
                data.dom = this;
            }
            dataList.push(data);

        });
        jQuery.merge(this.data, dataList);
        this.replace(dataList);
    }

    this.buidAll = function(selector) {
        this.buid(selector);
    };

    this.destroyPopups = function() {
        $("div[id^=g_popup_]").hide("slow");
        $("div[id^=g_popup_]").remove();
    }

    this.createPopUp = function(item) {
        var index = $(this.data).index(item);

        var html = "<div class=\"RadToolTip RadToolTip_Bernco rtVisibleCallout gmap-pop-up\">" +
	        "<table class=\"rtWrapper\">" +
		        "<tr>" +
			        "<td class=\"rtWrapperTopLeft\">&nbsp;</td>" +
			        "<td class=\"rtWrapperTopCenter\">" +
        /*"<a target=\"_break\" class=\"get-direction\">Get Direction</a>" +*/
			        "<a class=\"rtCloseButton\" href=\"javascript: void(0);\" title=\"Close\">" +
			        "<span>Close</span></a></td>" +
			        "<td class=\"rtWrapperTopRight\">&nbsp;</td>" +
		        "</tr>" +
		        "<tr>" +
			        "<td class=\"rtWrapperLeftMiddle\">&nbsp;</td>" +
			        "<td class=\"rtWrapperContent RadToolTip RadToolTip_Bernco RadToolTip RadToolTip_Bernco\" valign=\"top\">" +
                        "<div class=\"gmap-holder\">" +
                        "</div>" +
			        "</td>" +
			        "<td class=\"rtWrapperRightMiddle\">&nbsp;</td>" +
		        "</tr>" +
		        "<tr>" +
			        "<td class=\"rtWrapperBottomLeft\">&nbsp;</td>" +
			        "<td class=\"rtWrapperBottomCenter\">&nbsp;</td>" +
			        "<td class=\"rtWrapperBottomRight\">&nbsp;</td>" +
		        "</tr>" +
	        "</table>" +
        "</div>";

        var div = $(html);
        $(div).attr("id", "g_popup_" + index);
        $(div).find(".gmap-holder").css("width", gmap.wSize.width);
        $(div).find(".gmap-holder").css("height", gmap.wSize.height);
        item.window = div;
        var position = $(item.dom).offset();
        $(div).css("left", position.left);
        $(div).css("top", position.top - (gmap.wSize.height + 10));
        return div;

    };

    this.createMap = function(element, item) {

        var data = item;
        var zoom = parseInt(Logic_GlobalParams_GoogleMapZoomLevel);
        zoom = isNaN(zoom) ? 16 : zoom;
        var map = new google.maps.Map(element, {
            scaleControl: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            zoom: zoom,
            navigationControl: false,
            streetViewControl: false,
            mapTypeControl: false

        });

        var gc = new google.maps.Geocoder();
        var params = {};

        if (data.position) {
            params.location = data.position;
        }
        else {
            params.address = data.address;
        }

        /* var directionLink = $(element).parents(".gmap-pop-up").find(".get-direction");
        directionLink.hide();*/

        gc.geocode(params, function(results, status) {

            if (status == google.maps.GeocoderStatus.OK) {

                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });


                var sdirectionLink = $("<div><a target=\"_break\" class=\"get-sdirection\">From here</a></div>");
                sdirectionLink.find(".get-sdirection").attr("href", "http://maps.google.com/maps?saddr=" + results[0].geometry.location.toUrlValue() + "&z=" + zoom);

                var ddirectionLink = $("<div><a target=\"_break\" class=\"get-ddirection\">To here</a></div>");
                ddirectionLink.find(".get-ddirection").attr("href", "http://maps.google.com/maps?daddr=" + results[0].geometry.location.toUrlValue() + "&z=" + zoom);

                var infowindow = new google.maps.InfoWindow({
                    content: results[0].formatted_address + "<br><br>" + sdirectionLink.html() + " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; " + ddirectionLink.html()
                });

                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map, marker);

                });


                google.maps.event.trigger(map, 'resize');

            }
            else {
                var msg = $(Logic_theLibDict_Bernco_GoogleNotFoundAddressMessage);
                $(data.window).find(".gmap-holder").css("background-image", "none");
                $(data.window).find(".gmap-holder").html("");
                $(msg).appendTo($(data.window).find(".gmap-holder"));
            }
        });
    }

    this.show = function(item) {
        gmap.destroyPopups();
        var popUp = gmap.createPopUp(item);

        var id = "#" + $(popUp).attr("id");
        if ($(id).length == 0) {
            $(popUp).appendTo("form");
        }
        $(id).find("a.rtCloseButton").click(function() {
            gmap.destroyPopups();
        });


        $(id).show("slow", function() {

            var element = $(this).find(".gmap-holder");
            gmap.createMap(element[0], item);

        });
    };

    this.replace = function(data) {

        var dataList = this.data;
        show = this.show;
        $(data).each(function(index, item) {
            var index = $(dataList).index(item);
            var link = $("<a></a>");
            $(link).attr("href", "javascript:void(0)");
            $(link).html(item.title);
            $(item.dom).replaceWith($(link));
            item.dom = link;
            $(link).bind("click", function() {
                show(item);

            });
        });
    }
};

$(document).ready(function() {
    gmap = new $.gMap();
    gmap.buidAll("address");
});








