var ie7 = (navigator.userAgent.search('MSIE 7.0') != -1);

var _isIE = $.browser.msie;
var _isMozilla = $.browser.mozilla;
var _isSafari = $.browser.safari; 

function GetViewPort(wnd) {    
    var w = wnd ? wnd : window;
    var d = w.document;
    var b = (!_isIE || d.compatMode == "CSS1Compat") ? d.documentElement : d.body;
    return {
        x: 0,
        y: 0,
        w: w.innerWidth || b.clientWidth,
        h: w.innerHeight || b.clientHeight
    };
}

function pop_up(page, width, height, scrollable) {
    close_pop_up();

    var vp = GetViewPort();
    var left = Math.round(Math.max(vp.x, vp.x + (vp.w / 2.0) - (width / 2.0)));

    var _top;
    if (!scrollable) { 
        _top = Math.round(Math.max(vp.y, vp.y + (vp.h / 2.0) - (height / 2.0)));
    } else {    
        if (!_isSafari) {
            _top = window.document.documentElement.scrollTop + 50;
        } else {
            _top = window.document.body.scrollTop + 50;
        }
    }    
    
    var style = 'position: ' + (scrollable ? 'absolute' : 'fixed') + '; width: {0}px; top: {1}px; left: {2}px;';

    style = style.replace(/\{0\}/ig, width).replace(/\{1\}/ig, _top).replace(/\{2\}/ig, left);    

    $("body").prepend('<div class="alphawindow" rel="popupown" style="position: fixed; width: 100%; height: 100%"></div>');
    $("body").prepend('<div class="alphablock" rel="popupown" style="' + style + '"></div>');    

    var data =
        '<div id="popup_container" class="shadowpopup">' +
        '   <div id="pop_up" class="withbg">' +
        '       <a class="pop_up_close" href="javascript:void(0);"></a>' +
        '       <div class="autoheight" id="pop_up_body" style="height: ' + height + 'px; background-color: #FFFFFF; ' + (_isIE ? "filter: alpha(opacity = 99);" : "") + '">' +
        '           <img id="progress_image" style="display: none" class="popup_progress_img" src="' + GetProgressImageURL(false) + '" height="32" width="32" alt="">' +
        '       </div>' +
        '       <iframe id="popup_iframe" frameborder="0" scrolling="no" style="background: #FFFFFF; overflow: hidden; display: none; border: 0pt none; width: 100%; height: auto;"></iframe>' +
        '   </div>' +
        '</div>';        

    $(".alphablock").append(data);

    _top = (parseInt($("#pop_up_body").height(), 10) - 32) / 2;
    left = (parseInt($("#pop_up_body").width(), 10) - 32) / 2;

    $("#progress_image")
        .css("position", "relative")
        .css("top", _top)
        .css("left", left)
        .css("display", "block");

    var popup_frame = $("#popup_iframe")[0];
    var doc = popup_frame.contentWindow.document;

    function OnLoad() {        
        try {
            $(popup_frame).unbind("load", OnLoad);

            var wnd = popup_frame.contentWindow;
            var doc = wnd.document;

            if (wnd.borderClass) {
                $("#pop_up").attr("class", wnd.borderClass);
            }

            $("#pop_up_body").remove();
            $(popup_frame).css("display", "block");

            if (_isIE) {
                $("#pop_up_body", doc)
                .css("background-color", "#FFFFFF")
                .attr("style", $("#pop_up_body", doc).attr("style") + "; filter: alpha(opacity = 99);");
            }            
            
            var pop_up_body_el = $("#pop_up_body", doc)[0];

            var cssheight = parseInt(pop_up_body_el.style.height, 10);
            if (isNaN(cssheight)) cssheight = 0;

            var actualheight = pop_up_body_el.offsetHeight;            

            $(popup_frame).height(actualheight);             

            if (!scrollable && cssheight != height) {
                var _top = Math.round(Math.max(vp.y, vp.y + (vp.h / 2.0) - (height / 2.0)));
                if (Math.abs(newtop - _top) > 50) {
                    $("div.alphablock").css("top", newtop);
                }
            }

        } catch (ex) { }        
    }

    function OnReady() {
        try {
            $(doc).unbind("ready", OnReady);

            $(popup_frame).load(OnLoad);
            popup_frame.src = page;
        } catch (ex) { }
    }

    $(doc).ready(OnReady);
}

function pop_up_updatebounds() {
    var popup_frame = $("#popup_iframe")[0];
    if (!popup_frame) {
        popup_frame = $("#popup_iframe", parent.document)[0];
    }
    setTimeout(function() {
        if (popup_frame && popup_frame.contentWindow) {
            var height = $("#pop_up_body", popup_frame.contentWindow.document)[0].offsetHeight;
            var update = false;
            if (height != $(popup_frame).height()) {
                $(popup_frame).height(height);
                update = true;
            }            
            if (update) {
                setTimeout(function() {
                    pop_up_updatebounds();
                }, 100);
            }
        }
    }, 0);
}

function admin_preview_pop_up_updatebounds() {
    var popup_conteiner = $("#ex_popup_preview")[0];
    if (!popup_conteiner) {
        popup_conteiner = $("#ex_popup_preview", parent.document)[0];
    }
    setTimeout(function() {
        var height = $("#popup_iframe", popup_conteiner).height() + 28;
        if (height != $(popup_conteiner).height()) {
            $(popup_conteiner).height(height);

            setTimeout(function() {
                admin_preview_pop_up_updatebounds();
            }, 100);
        }
    }, 0);
} 

function right_pop_up(page, width, height) {
    close_pop_up();

    var vp = GetViewPort();
    
    var left = ((($("body").width() - $(".pageformat").width()) / 2) + $(".pageformat").width() - width - 20);
    var _top = 85;
    var style = 'position: fixed; width: {0}px; top: {1}px; left: {2}px;';    

    style = style.replace(/\{0\}/ig, width).replace(/\{1\}/ig, _top).replace(/\{2\}/ig, left);

    $("body").prepend('<div class="alphawindow" rel="popupown" style="position: fixed; width: 100%; height: 100%"></div>');
    $("body").prepend('<div class="alphablock" rel="popupown" style="' + style + '"></div>');

    var data =
        '<div id="popup_container" class="shadowpopup">' +
        '   <div id="pop_up" class="smallborders">' +
        '       <a class="pop_up_close" href="javascript:void(0);"></a>' +
        '       <div class="autoheight" id="pop_up_body" style="height: ' + height + 'px; background-color: #FFFFFF; ' + (_isIE ? "filter: alpha(opacity = 99);" : "") + '">' +        
        '           <img id="progress_image" style="display: none" class="popup_progress_img" src="' + GetProgressImageURL(false) + '" height="32" width="32" alt="">' +        
        '       </div>' +
        '       <iframe id="popup_iframe"  scrolling="no" frameborder="0" style="overflow: hidden; display: none; border: 0pt none; width: 100%; height: auto;"></iframe>' +         
        '   </div>' +
        '</div>';

    $(".alphablock").append(data);    

    _top = (parseInt($("#pop_up_body").height(), 10) - 32) / 2;
    left = (parseInt($("#pop_up_body").width(), 10) - 32) / 2;

    $("#progress_image")
        .css("position", "relative")
        .css("top", _top)
        .css("left", left)
        .css("display", "block");

    var popup_frame = $("#popup_iframe")[0];
    var doc = popup_frame.contentWindow.document;

    function OnLoad() {
        $(popup_frame).unbind("load", OnLoad);

        var wnd = popup_frame.contentWindow;
        var doc = wnd.document;

        if (wnd.borderClass) {
            $("#pop_up").attr("class", wnd.borderClass);
        }

        $("#pop_up_body").remove();
        $(popup_frame).css("display", "block");

        var actualheight = $("body", doc).height();        
        
        var actualtop = parseInt($("div.alphablock").css("top"), 10);
        if ((actualtop + actualheight + 30) > vp.h) {
            var newtop = vp.h - actualheight - 30;
            var diff = 0;
            if (newtop > 0) {
                var newtop = Math.round(Math.max(vp.y, vp.y + (vp.h / 2.0) - (actualheight / 2.0)));
                if (newtop < 30) newtop = 30;
                $("div.alphablock").css("top", newtop);
                $(popup_frame).height(actualheight);
            } else {
                var newheight = vp.h - 60;
                var newtop = Math.round(Math.max(vp.y, vp.y + (vp.h / 2.0) - (newheight / 2.0)));
                if (newtop < 30) newtop = 30;

                var innerheight = $("div.scroll", doc).height();
                newinnerheight = newheight - (actualheight - innerheight);

                $("div.alphablock").css("top", newtop);
                $("div.scroll", doc)
                    .removeAttr("style")
                    .css("height", newinnerheight);

                $(popup_frame).height(newheight);    
            }
        } else {                        
            $(popup_frame).height(actualheight);
        }        
    }

    function OnReady() {
        $(doc).unbind("ready", OnReady);

        $(popup_frame).load(OnLoad);
        popup_frame.src = page;
    }

    $(doc).ready(OnReady);
}

var seadragonPopupData = null;

function SeaDragonPopupData() {
    this.alphablock_style = null;
    this.alphablock_class = null;
    this.popup_container_style = null;
    this.popup_container_class = null;
    this.pop_up_style = null;
    this.pop_up_class = null;
    this.iframe_style = null;
    this.iframe_class = null;
    this._reset_style = "margin: 0; padding: 0; border: none 0; position: fixed; width: 100%; height: 100%; z-index: 100000;";
    this.contentScrollTop = 0;
    this.IsFullScreen = false;

    this._save = function(popup, pframe) {
        var alphablock = popup;
        var popup_container = $("#popup_container", popup);
        var pop_up = $("#pop_up", popup);    
    
        this.alphablock_style = $(alphablock).attr("style");
        this.popup_container_style = $(popup_container).attr("style");
        this.pop_up_style = $(pop_up).attr("style");
        this.iframe_style = $(pframe).attr("style");
        this.alphablock_class = $(alphablock).attr("class");
        this.popup_container_class = $(popup_container).attr("class");
        this.pop_up_class = $(pop_up).attr("class");
        this.iframe_class = $(pframe).attr("class");
    }
    this.SaveScroller = function() {
        if (!_isSafari) {
            this.contentScrollTop = window.document.documentElement.scrollTop;
        } else {
            this.contentScrollTop = window.document.body.scrollTop;
        }
    } 
    this.Expand = function(alpha, popup, pframe, sg) {
        if (this.IsFullScreen) return;

        if (!_isSafari) {
            this.contentScrollTop = window.document.documentElement.scrollTop;
        } else {
            this.contentScrollTop = window.document.body.scrollTop;
        }

        this._save(popup, pframe);

        var alphablock = popup;
        var popup_container = $("#popup_container", popup);
        var pop_up = $("#pop_up", popup);

        $(alpha).css("display", "none");

        $(alphablock).attr("style", this._reset_style);
        $(popup_container).attr("style", this._reset_style);
        $(pop_up).attr("style", this._reset_style);
        $(pframe).attr("style", this._reset_style);
        $(alphablock).removeAttr("class");
        $(popup_container).removeAttr("class");
        $(pop_up).removeAttr("class");
        $(pframe).removeAttr("class");

        $("#content").hide();

        this.IsFullScreen = true;
    }
    this.Restore = function(alpha, popup, pframe, sg) {
        if (!this.IsFullScreen) return;

        var alphablock = popup;
        var popup_container = $("#popup_container", popup);
        var pop_up = $("#pop_up", popup);

        $(alpha).css("display", "block");

        $(alphablock).removeAttr("style");
        $(popup_container).removeAttr("style");
        $(pop_up).removeAttr("style");
        $(pframe).removeAttr("style");
        $(alphablock).removeAttr("class");
        $(popup_container).removeAttr("class");
        $(pop_up).removeAttr("class");
        $(pframe).removeAttr("class");

        $(alphablock).attr("style", this.alphablock_style ? this.alphablock_style : "");
        $(popup_container).attr("style", this.popup_container_style ? this.popup_container_style : "");
        $(pop_up).attr("style", this.pop_up_style ? this.pop_up_style : "");
        $(pframe).attr("style", this.iframe_style ? this.iframe_style : "");
        $(alphablock).attr("class", this.alphablock_class ? this.alphablock_class : "");
        $(popup_container).attr("class", this.popup_container_class ? this.popup_container_class : "");
        $(pop_up).attr("class", this.pop_up_class ? this.pop_up_class : "");
        $(pframe).attr("class", this.iframe_class ? this.iframe_class : "");

        $("#content").show();
        
        if (!_isSafari) {
            window.document.documentElement.scrollTop = this.contentScrollTop;
        }

        this.IsFullScreen = false;
    }
}

function GetSeaDragonPopupData() {
    if (seadragonPopupData) return seadragonPopupData;
    seadragonPopupData = new SeaDragonPopupData();
    return seadragonPopupData;
}

function OnSeagragonResize(sg, wnd, container, isInitial) {
    if (!sg.isVisible()) return;

    var is_fullscreen = sg.isFullPage();  
    
    var alpha = $(".alphawindow");
    if (alpha.length == 0) return;
    alpha = alpha[0];
    var popup = $(".alphablock");
    if (popup.length == 0) {
        popup = $("#tmp_alphablock");
        if (popup.length == 0) return;
    } else {
        $(popup).attr("id", "tmp_alphablock");
    }    
    popup = popup[0];
    var pframe = $("#popup_iframe", popup);
    if (pframe.length == 0) return;
    pframe = pframe[0];

    var _data = GetSeaDragonPopupData();

    if (isInitial) {
        _data.SaveScroller();
        
        return;
    }
    
    if (is_fullscreen) {
        _data.Expand(alpha, popup, pframe, sg);
    } else {
        _data.Restore(alpha, popup, pframe, sg);
    }    

    if (_isSafari) {
        if (is_fullscreen) {
            $("canvas", wnd.document)
            .css("width", "100%")
            .css("height", "100%");
        } else {
            var w = parseInt($(container).css("width"), 10);
            var h = parseInt($(container).css("height"), 10);
            $("canvas", wnd.document)
                .css("width", w)
                .css("height", h);
        }
    }     
    
    var bounds = sg.viewport.getBounds(true);
    sg.viewport.fitBounds(bounds, true);
    sg.viewport.applyConstraints(true);    

    if (_isSafari && !is_fullscreen) {
        window.document.body.scrollTop = _data.contentScrollTop;
    }
}

function CheckForCloseSeaDragon() {
    try {
        var popup = $(".alphablock");
        if (popup.length == 0) return;
        var pframe = $("#popup_iframe", popup);
        if (pframe.length == 0) return;
        var wnd = pframe[0].contentWindow;
        var sg = wnd.seadragonViewer;
        if (sg) {
            if (sg.isOpen()) {
                sg.close();
            }
        }
        if (seadragonPopupData) {
            var sg = seadragonPopupData;
            seadragonPopupData = null;
            delete sg;
            sg = null;
        }
    } catch (ex) { }
}

function close_pop_up() {
    CheckForCloseSeaDragon();
    
	$(".alphawindow").remove();
	$(".alphablock").remove();
}

$(".alphawindow").live("click", function() {
	top.close_pop_up();
})

$("a.pop_up_close, a.pop_up_close_simple").live("click", function(){
    top.close_pop_up();
});

function htmldecode(str) {    
    var textarea = document.createElement('textarea');
    textarea.innerHTML = str;
    if (!$.browser.mozilla && !$.browser.safari) {
        var value = textarea.innerText;
    } else {
        var value = textarea.value;
    }
    delete textarea;
    return value;
}

var term_close_id;
function close_termbox() { term_close_id = setTimeout(function() { $(".termbox").remove(); }, 500); }

$(document).ready(function() {
    $(".term").bind("mouseover", function() {
        clearTimeout(term_close_id);
        $(".termbox").remove();
        var offset = $(this).offset();
        $("body").prepend("<div class='termbox'><div class='shadowterm'><div class='viewterm'>" + htmldecode($(this).attr("caption")) + "</div></div><div class='termarrow'></div></div>");
        $(".termbox").css({ top: (offset.top - parseInt($(".shadowterm").height()) - 10) + "px", left: offset.left + "px" });
        $(".termbox").bind("mouseout", function() { close_termbox(); });
        $(".termbox").bind("mouseover", function() { clearTimeout(term_close_id); });
    });
    $(".term").bind("mouseout", function() { close_termbox(); });
});

var __where_is_this_link = null;
var __where_is_this_first_run = true;

$("a.wherethis").live("mouseover", function() {
    if (!$(this).hasClass("active")) {
        $("a.wherethis").removeClass("active");
        $(".shadowviewer").remove();
        $(this).addClass("active");
        if ($(this).attr("path")) {
            var offset = $("#" + $(this).attr("rel")).offset();
            $("body").prepend("<div class='shadowviewer' rel='popupown'><img class='mapviewer' src='" + $(this).attr("path") + "'></div>");
            $(".shadowviewer").css({ top: (offset.top + parseInt($("#" + $(this).attr("rel")).height()) - parseInt($(".shadowviewer").height()) + 10) + "px", left: offset.left + "px" });
        }
        __where_is_this_link = this;
    }
    return false;
})

function HideWhereIsThisPopup() {
    var a = __where_is_this_link;
    if (!a) return;    
    if ($(a).hasClass("active")) {
        $(a).removeClass("active");
        $(".shadowviewer").remove();
    }
    __where_is_this_link = null;
    __where_is_this_first_run = false;
}

$("a.wherethis").live("mouseout", function() {
    var delay = 200;
    if (__where_is_this_first_run) delay = 1;
    setTimeout('HideWhereIsThisPopup();', delay);
    return false;
})

$(".noalphawindow").live("click", function(){
	var rel = $(this).attr("rel");
	$("[rel='"+rel+"']").remove();
	$("a.wherethis").removeClass("active");
})

function init_mediatitles(){
    $(".mediaimg").each(function(i) {
        if (!$(this).hasClass("mediaset")) {
            var offset = $(this).offset();
            var objleft = $(this).css("padding-left");
            var parentoffset = $(this).parent().offset();
            var parentpadding = $(this).parent().css("padding-left");
            var offset = $(this).offset();
            var objleft = $(this).css("padding-left");
            var objtop = $(this).css("padding-top");
            if ($(this).attr("borderside")) {
                var borderside = parseInt($(this).attr("borderside"));
            } else {
                var borderside = 0;
            }
            if ($(this).attr("bordertop")) {
                var bordertop = parseInt($(this).attr("bordertop"));
            } else {
                var bordertop = 0;
            }

            var parentoffset = $(this).parent().offset();
            var parentoffset = $(this).parent().offset();
            var additionleft;
            if (ie7) {
                additionleft = parseInt(objleft) + borderside + parseInt(parentpadding);
            } else {
                additionleft = parseInt(objleft) + borderside + parseInt(parentpadding);
            }

            var additiontop = parseInt(objtop) + bordertop;

            $(this).before("<div class='mediaicon' style='margin-bottom:-" + (additiontop + 14) + "px;margin-top:" + (additiontop) + "px;margin-left:" + additionleft + "px'>" + $(this).attr("rel") + "</div>");
            $(this).addClass("mediaset");
        }
    })
}

function init_autoblock(){
	$(".autoblock").each(function(i){
		$(this).parent().css({"width":$(this).width()+"px"});
	});
}

$(".dropdown").live("click", function(){
	if(!$(this).attr("opened")){
		$("body").prepend("<div class='noalphawindow spec' rel='popupown' style=' width: "+$("body").width()+"px; height: "+document.documentElement.scrollHeight+"px;'></div>");
		var offset = $(this).offset();
		var width = $(this).width();
		$(".dropdownlist[rel='"+$(this).attr("id")+"']").css({
			left: offset.left + $(this).width()-$(".dropdownlist[rel='"+$(this).attr("id")+"']").width(), 
      		top: offset.top+$(this).height()-2
		}).fadeIn(500);
		$(this).attr("opened", "true");
	}else{
		$(".noalphawindow").remove();
		$(".dropdownlist[rel='"+$(this).attr("id")+"']").fadeOut(500);
		$(this).removeAttr("opened");
	}
})

$(".dropdownlist").live("click", function(){
	$(this).fadeOut(500);
	$("#"+$(this).attr("rel")+".dropdown").removeAttr("opened");
})

$(".noalphawindow.spec").live("click", function(){
		$(".noalphawindow").remove();
		$(".dropdownlist").fadeOut(500);
		$(".dropdown").removeAttr("opened");
})

var _BrowsePopup = null;

function sgBrowsePopup() {
    this.is_loaded = false;
    this.content = null;
    this.frame = null;

    this._is_visible = function() {
        return $("#browser").length > 0;
    }
    this._update_bounds = function(is_expanded) {
        $(this.frame)
                .css("width", 650)
                .css("height", is_expanded ? 428 : 118);

        if (!is_expanded) return;
        
        var doc = this.frame.contentWindow.document;
        
        var _left = 13;
        var _top = 76;

        var navwidth = parseInt($(".alphabet", doc).width(), 10);

        $(".browse_progress", doc)
            .css("position", "absolute")
            .css("left", _left)
            .css("top", _top)
            .width(navwidth - 2);

        $(".browse_progress", doc).height(280);

        _left = (navwidth - 2 - 32) / 2;
        _top = (280 - 32) / 2;

        $(".popup_progress_img", doc)
            .css("position", "absolute")
            .css("left", _left)
            .css("top", _top);
    }
    this._is_expanded = function() {
        var doc = this.frame.contentWindow.document;
        var list = $("#panelList", doc);
        return !(list.length == 0 || $(list).css("display").toLowerCase() == "none");
    }
    this._show_inner_content = function() {
        $("#browser").css("height", "auto");
        $(".browse_progress_container").remove();

        $(this.frame).css("display", "block");

        var doc = this.frame.contentWindow.document;
        var img = $(".popup_progress_img", doc)[0];
        img.src = GetProgressImageURL(true, true);

        this._update_bounds(false);

        this.UpdateEvents();
    }    
    this._preload = function() {
        var self = this;

        $("body").prepend("<div id='browser' style='display: none'></div>");

        var html = '<iframe id="popup_iframe" scrolling="no" frameborder="0" style="overflow: hidden; display: none; border: 0pt none; width: 100%; height: 100%;"></iframe>';
        $("#browser").append(html);
        this.frame = $("#popup_iframe")[0];
        var doc = this.frame.contentWindow.document;

        function OnLoad() {
            $(self.frame).unbind("load", OnLoad);

            self.is_loaded = true;
            if (self._is_visible()) {
                self._show_inner_content();                
            }
        }

        function OnReady() {
            $(doc).unbind("ready", OnReady);

            $(self.frame).load(OnLoad);
            self.frame.src = "./popups/browse.aspx";
        }

        $(doc).ready(OnReady);
    }
    this.Initialize = function() {
        this._preload();
    }
    this.UpdateEvents = function() {
        var doc = this.frame.contentWindow.document;
        if (_isMozilla && $("#panelList", doc).length > 0) {
            $("#panelList", doc)[0].scrollTop = 0;
        }
        var self = this;
        $("div.alphabet a", doc).click(function() {
            $("div.alphabet a", doc).removeClass("active");
            $(this).addClass("active");

            if (!self._is_expanded()) {
                $("#progress_content", doc).css("display", "block");
                self._update_bounds(true);
            }
            return true;
        });
    }    
    this.Show = function(parent) {
        var browser = $("#browser");
        if (browser.length == 0) return;
        $("body").prepend("<div class='noalphawindow browse' rel='popupown' style='position: fixed; width: 100%; height: 100%'></div>");
        var offset = $(parent).offset();
        
        $(browser)
            .css("left", offset.left)
            .css("top", offset.top + $(parent).height())
            .css("display", "block");        

        $(parent).addClass("active");
        if (this.is_loaded) {
            this._show_inner_content();
        } else {
            var progress = '<div class="body browse_progress_container" style="height: 100%; padding: 0;"><img class="popup_progress_img" src="' + GetProgressImageURL(true, false) + '" height="32" width="32" alt="" style="display: none;"></div>';
            $(browser).css("height", 118);
            $(browser).prepend(progress);
            $(".popup_progress_img")
                .css("position", "relative")
                .css("left", (648 - 32) / 2)
                .css("top", (118 - 32) / 2)
                .css("display", "block");
        }
    }
    this.Hide = function() {
        $(".noalphawindow").remove();
        $("#browser").css("display", "none");
        var doc = this.frame.contentWindow.document;
        $("#panelList", doc).css("display", "none");
        $("div.alphabet a", doc).removeClass("active");
        $(".browseopener").removeClass("active");
    }
    this.Fade = function() {
        try {            
            $(".noalphawindow").remove();
            $("#browser").fadeOut(400, function() {
                try {                    
                    $("#browser").css("display", "none");
                    var doc = this.frame.contentWindow.document;
                    $("#panelList", doc).css("display", "none");
                    $("div.alphabet a", doc).removeClass("active");
                    $(".browseopener").removeClass("active");
                } catch (ex) { $("#browser").css("display", "none"); }
            });
        } catch (ex) { }
    }
}

function InitializeBrowsePopup() {
    if (_isIE) {
        PreloadProgressImages();
    }
    if (!_BrowsePopup) {
        _BrowsePopup = new sgBrowsePopup();
        _BrowsePopup.Initialize();
    }
}

$(".browseopener").live("click", function() {
    if (!_BrowsePopup) {
        _BrowsePopup = new sgBrowsePopup();
        _BrowsePopup.Initialize();
    }

    _BrowsePopup.Show(this);
})

if ($.browser.msie) {
    $("#content").live("click", function() {
        if (_BrowsePopup) {
            _BrowsePopup.Hide();
        } else {
            $(".noalphawindow").remove();
        }
    })
}

$(".noalphawindow.browse").live("click", function() {
    if (_BrowsePopup) {
        _BrowsePopup.Hide();
    } else {
        $(".noalphawindow").remove();
    }
})

function changeExpandCollapseState(link, container) {
    link = document.getElementById(link);
    container = document.getElementById(container);

    if ((!link) || (!container)) return false;

    var linkClass = link.className;

    if (linkClass == "closedlink") {
        container.style.display = "block";
        link.className = "openlink";
    }
    else {
        container.style.display = "none";
        link.className = "closedlink";
    }
}
            
function PreloadProgressImages() {
    var el = document.createElement("img");
    el.src = "images/images/progress.gif";
    el = document.createElement("img");
    el.src = "images/images/progress0.gif";        
}            

function GetProgressImageURL(is_transparent, from_popups_dir) {
    if (_isIE) {
        var url = null;    
        if (is_transparent) {
            url = "images/images/progress.gif";
        } else {
            url = "images/images/progress0.gif";
        }
        if (from_popups_dir) {
            url = "../" + url;
        }
        return url;
    } else {
        return "data:image/gif;base64," +
            'R0lGODlhIAAgALMAAP///7Ozs/v7+9bW1uHh4fLy8rq6uoGBgTQ0NAEBARsbG8TExJeXl/39/VRUVAAAACH' +
            '/C05FVFNDQVBFMi4wAwEAAAAh+QQFBQAAACwAAAAAIAAgAAAE5xDISSlLrOrNp0pKNRCdFhxVolJLEJQUoS' +
            'gOpSYT4RowNSsvyW1icA16k8MMMRkCBjskBTFDAZyuAEkqCfxIQ2hgQRFvAQEEIjNxVDW6XNE4YagRjuBCw' +
            'e60smQUDnd4Rz1ZAQZnFAGDd0hihh12CEE9kjAEVlycXIg7BAsMB6SlnJ87paqbSKiKoqusnbMdmDC2tXQl' +
            'kUhziYtyWTxIfy6BE8WJt5YEvpJivxNaGmLHT0VnOgGYf0dZXS7APdpB309RnHOG5gDqXGLDaC457D1zZ/V' +
            '/nmOM82XiHQjYKhKP1oZmADdEAAAh+QQFBQAAACwAAAAAGAAXAAAEchDISasKNeuJFKoHs4mUYlJIkmjIV5' +
            '4Soypsa0wmLSnqoTEtBw52mG0AjhYpBxioEqRNy8V0qFzNw+GGwlJki4lBqx1IBgjMkRIghwjrzcDti2/Gh' +
            '7D9qN774wQGAYOEfwCChIV/gYmDho+QkZKTR3p7EQAh+QQFBQAAACwBAAAAHQAOAAAEchDISWdANesNHHJZ' +
            'wE2DUSEo5SjKKB2HOKGYFLD1CB/DnEoIlkti2PlyuKGEATMBaAACSyGbEDYD4zN1YIEmh0SCQQgYehNmTNN' +
            'aKsQJXmBuuEYPi9ECAU/UFnNzeUp9VBQEBoFOLmFxWHNoQw6RWEocEQAh+QQFBQAAACwHAAAAGQARAAAEaR' +
            'DICdZZNOvNDsvfBhBDdpwZgohBgE3nQaki0AYEjEqOGmqDlkEnAzBUjhrA0CoBYhLVSkm4SaAAWkahCFAWT' +
            'U0A4RxzFWJnzXFWJJWb9pTihRu5dvghl+/7NQmBggo/fYKHCX8AiAmEEQAh+QQFBQAAACwOAAAAEgAYAAAE' +
            'ZXCwAaq9ODAMDOUAI17McYDhWA3mCYpb1RooXBktmsbt944BU6zCQCBQiwPB4jAihiCK86irTB20qvWp7Xq' +
            '/FYV4TNWNz4oqWoEIgL0HX/eQSLi69boCikTkE2VVDAp5d1p0CW4RACH5BAUFAAAALA4AAAASAB4AAASAkB' +
            'gCqr3YBIMXvkEIMsxXhcFFpiZqBaTXisBClibgAnd+ijYGq2I4HAamwXBgNHJ8BEbzgPNNjz7LwpnFDLvgL' +
            'GJMdnw/5DRCrHaE3xbKm6FQwOt1xDnpwCvcJgcJMgEIeCYOCQlrF4YmBIoJVV2CCXZvCooHbwGRcAiKcmFU' +
            'JhEAIfkEBQUAAAAsDwABABEAHwAABHsQyAkGoRivELInnOFlBjeM1BCiFBdcbMUtKQdTN0CUJru5NJQrYMh' +
            '5VIFTTKJcOj2HqJQRhEqvqGuU+uw6AwgEwxkOO55lxIihoDjKY8pBoThPxmpAYi+hKzoeewkTdHkZghMIdC' +
            'OIhIuHfBMOjxiNLR4KCW1ODAlxSxEAIfkEBQUAAAAsCAAOABgAEgAABGwQyEkrCDgbYvvMoOF5ILaNaIoGK' +
            'roch9hacD3MFMHUBzMHiBtgwJMBFolDB4GoGGBCACKRcAAUWAmzOWJQExysQsJgWj0KqvKalTiYPhp1LBFT' +
            'tp10Is6mT5gdVFx1bRN8FTsVCAqDOB9+KhEAIfkEBQUAAAAsAgASAB0ADgAABHgQyEmrBePS4bQdQZBdR5I' +
            'cHmWEgUFQgWKaKbWwwSIhc4LonsXhBSCsQoOSScGQDJiWwOHQnAxWBIYJNXEoFCiEWDI9jCzESey7GwMM5d' +
            'oEwW4jJoypQQ743u1WcTV0CgFzbhJ5XClfHYd/EwZnHoYVDgiOfHKQNREAIfkEBQUAAAAsAAAPABkAEQAAB' +
            'GeQqUQruDjrW3vaYCZ5X2ie6EkcKaooTAsi7ytnTq046BBsNcTvItz4AotMwKZBIC6H6CVAJaCcT0CUBTga' +
            'Tg5nTCu9GKiDEMPJg5YBBOpwlnVzLwtqyKnZagZWahoMB2M3GgsHSRsRACH5BAUFAAAALAEACAARABgAAAR' +
            'cMKR0gL34npkUyyCAcAmyhBijkGi2UW02VHFt33iu7yiDIDaD4/erEYGDlu/nuBAOJ9Dvc2EcDgFAYIuaXS' +
            '3bbOh6MIC5IAP5Eh5fk2exC4tpgwZyiyFgvhEMBBEAIfkEBQUAAAAsAAACAA4AHQAABHMQyAnYoViSlFDGX' +
            'BJ808Ep5KRwV8qEg+pRCOeoioKMwJK0Ekcu54h9AoghKgXIMZgAApQZcCCu2Ax2O6NUud2pmJcyHA4L0uDM' +
            '/ljYDCnGfGakJQE5YH0wUBYBAUYfBIFkHwaBgxkDgX5lgXpHAXcpBIsRADs=';
    }
}

function OnAutoCompletePopupShown(source, eventArgs) {
    $(".suggestionslist li").each(function(i) {
        var text = $(this).text();
        if (text.length > 25) {
            var value = text.substring(0, 25) + '...';
            $(this).text(value);            
        }
    });
}

function OnAutoCompleteItemSelected(source, eventArgs) {
    $(source._element).val(eventArgs._value);
}

function OnAutoCompletePopulating(source, eventArgs) {

}

function InitGrayedCheckBoxControl(cntrId) {
    $(document).ready(function() {
        var ctnr = $("#" + cntrId)[0];
        var chk = $("input[id$='checkboxMain']", ctnr)[0];
        var hf = $("input[id$='hiddenState']", ctnr)[0];
        var cb = $(chk).parent()[0];
        cb.__isGrayedCheckBox = true;
        chk.__isGrayedCheckBox = true;
        chk.__container = ctnr;
        chk.__stateField = hf;
        chk.__control = cb;
        cb.__checkbox = chk;

        chk.getState = function() {
            return $(chk.__stateField).val();
        }
        chk.setState = function(value) {
            $(chk.__stateField).val(value);
            chk.checked = value != "False";
            if (chk.__grayDiv) {
                if (value == "Grayed") {
                    $(chk.__grayDiv).show();
                } else {
                    $(chk.__grayDiv).hide();
                }
            }
        }

        if (chk.clientWidth > 0 && chk.clientHeight > 0) {
            var tl = tt = 0;
            var p = $(chk).parents();
            for (var i = 0; i < p.length; i++) {
                var el = p[i];
                var st = "";
                if (document.defaultView) {
                    st = document.defaultView.getComputedStyle(el, null).getPropertyValue('float');
                } else {
                    st = el.currentStyle.styleFloat;
                }
                if (st.toLowerCase() != "none") {
                    tl = $(el).offset().left;
                    tt = $(el).offset().top;
                    break;
                }
            }
            tl = $(chk).offset().left - tl;
            tt = $(chk).offset().top - tt;
            if ($.browser.msie) {
                tl += 4;
                tt += 4;
            } else {
                tl += 1;
                tt += 1;
            }
            var dsp = chk.getState() == "Grayed" ? "block" : "none";
            var div = document.createElement("div");

            var w1 = chk.clientWidth - 3;
            var h1 = chk.clientHeight - 3;

            if (_isIE && w1 == 17 && h1 == 17) {
                w1 = 13;
                h1 = 13;
            }

            $(div).attr("style", "background-color: #999999; opacity: 0.5; filter: alpha(opacity = 50); z-index: 10;")
                .css("width", w1)
                .css("height", h1)
                .css("position", "absolute")
                .css("left", tl)
                .css("top", tt)
                .css("display", dsp);
            $(cb).after(div);

            chk.__grayDiv = div;

            $(div).click(function() {
                chk.checked = !chk.checked;
                if (!$.browser.safari) chk.focus();
                $(chk.__grayDiv).hide();
                chk.setState(chk.checked ? "True" : "False");
                $(chk.__control).click();
            });

            $(cb).click(function() {
                $(chk.__grayDiv).hide();
                chk.setState(chk.checked ? "True" : "False");
            });
        } else {
            chk.__grayDiv = null;
        }
    });
}

function smCheckBoxesTree() {
    this.__allCheckBoxes = new Array();
    this.__allCheckBoxesIsSorted = false;    

    this.AttachCheckBox = function(control) {
        var className = null;
        var classes = $(control).attr("class").split(" ");
        var group_id_a = new Array();
        for (var i = 0; i < classes.length; i++) {
            className = classes[i];
            if (className.match("^group_") == "group_") {
                var group_id = className.match(/([\d])+/)[0];
                if (className.match("_all$") != "_all") {
                    var input = $("input:checkbox", control)[0];
                    if (input) {
                        var chk = $(".group_" + group_id + "_all > input:checkbox")[0];
                        if (chk) {
                            if (!chk.__children) chk.__children = new Array();
                            chk.__children[chk.__children.length] = input;
                            if (!input.__parents) input.__parents = new Array();
                            input.__parents[input.__parents.length] = chk;
                            if (!this.IsExists(chk)) this.__allCheckBoxes[this.__allCheckBoxes.length] = chk;
                            if (!this.IsExists(input)) this.__allCheckBoxes[this.__allCheckBoxes.length] = input;
                        }
                    }
                }
            }
        }
    }
    this.Initialize = function(className, onClickHandler) {
        var self = this;
        $("." + className).each(function(i) {
            self.AttachCheckBox(this);
            $(this).click(function() {
                self.UpdateCheckBoxes(this, 0);
                if (onClickHandler) {
                    setTimeout(function() {
                        onClickHandler();                        
                    }, 0);
                }
            });
        });
    }
    this.IsExists = function(control) {
        for (var i = 0; i < this.__allCheckBoxes.length; i++) {
            if (this.__allCheckBoxes[i] == control) return true;
        }
        return false;
    }
    this.IsAllParents = function(control) {
        if (control.__parents) {
            var aParents = control.__parents;
            var ok = nok = 0;
            for (var i = 0; i < aParents.length; i++) {
                var item = aParents[i];
                if (item.checked) ok++; else nok++;
            }
            return (ok == aParents.length || nok == aParents.length);
        } else {
            return true;
        }
    }
    this.IsAllChilds = function(control) {
        var result = true;
        var all_ok = false;
        var all_nok = false;
        var anyGrayed = false;
        if (control.__children) {
            var aChilds = control.__children;
            var ok = nok = 0;
            for (var i = 0; i < aChilds.length; i++) {
                var item = aChilds[i];
                if (item.checked) ok++; else nok++;
                if (item.__isGrayedCheckBox) {
                    anyGrayed |= item.getState() == "Grayed";
                }
            }
            all_ok = ok == aChilds.length;
            all_nok = nok == aChilds.length;
            result = (all_ok || all_nok);
        }
        return {
            result: result,
            anyGrayed: anyGrayed,
            all_ok: all_ok,
            all_nok: all_nok
        }
    }
    this.UpdateCheckBoxes = function(control, mode) {
        if (control.nodeName.toLowerCase() != "input") {
            control = $("input", control)[0];
        }
        var checked = control.checked;
        if (control.__children && (mode == 0 || mode == 1)) {
            var aChilds = control.__children;
            for (var i = 0; i < aChilds.length; i++) {
                var item = aChilds[i];
                if (item.__isGrayedCheckBox) {
                    if (this.IsAllParents(item)) {
                        item.setState(checked ? "True" : "False");
                    } else {
                        if (checked) {
                            item.setState("Grayed");
                        } else {
                            item.setState(item.checked ? "Grayed" : "False");
                        }
                    }
                } else {
                    item.checked = checked;
                }
                this.UpdateCheckBoxes(item, 1);
            }
        }
        if (control.__parents && (mode == 0 || mode == 2)) {
            var aParents = control.__parents;
            for (var i = 0; i < aParents.length; i++) {
                var item = aParents[i];
                if (item.__isGrayedCheckBox) {
                    var result = this.IsAllChilds(item);
                    if (result.result && !result.anyGrayed) {
                        item.setState(checked ? "True" : "False");
                    } else {
                        if (!checked && !item.checked) {
                            item.setState("False");
                        } else {
                            item.setState("Grayed");
                        }
                    }
                } else {
                    item.checked = checked;
                }
                this.UpdateCheckBoxes(item, 2);
            }
        }
        if (mode == 0) {
            if (!this.__allCheckBoxesIsSorted) {
                for (var i = 0; i < this.__allCheckBoxes.length; i++) {
                    var rItem = this.__allCheckBoxes[i];
                    var l = 0;
                    var p = rItem;
                    while (p.__parents) {
                        l++;
                        p = p.__parents[0];
                    }
                    rItem.__level = l;
                }
                this.__allCheckBoxes.sort(function(a, b) { return b.__level - a.__level });
                this.__allCheckBoxesIsSorted = true;
            }
            for (var i = 0; i < this.__allCheckBoxes.length; i++) {
                this.UpdateCheckBoxes(this.__allCheckBoxes[i], 3);
            }
            for (var i = this.__allCheckBoxes.length - 1; i >= 0; i--) {
                this.UpdateCheckBoxes(this.__allCheckBoxes[i], 4);
            }
        }
        if (mode == 3 && control.__children) {
            var aChilds = control.__children;
            for (var i = 0; i < aChilds.length; i++) {
                var item = aChilds[i];
                if (item.__isGrayedCheckBox && item.__children) {
                    var result = this.IsAllChilds(item);
                    if (!result.result || (result.anyGrayed && item.level == 0)) {
                        item.setState(item.checked ? "Grayed" : "False");
                    } else if (result.all_ok && item.getState() != "False") {
                        item.setState("True");
                    }
                }
            }
        }
        if (mode == 4 && control.__parents && !control.__children && control.__isGrayedCheckBox) {
            if (control.checked) {
                control.setState(!this.IsAllParents(control) ? "Grayed" : "True");
            } else {
                control.setState("False");
            }
        }
    }
    this.IsChecked = function(id, precisely) {
        var check = $("#" + id)[0];
        if (!check) {
            check = $("#" + id + "_containerCheckBox")[0];
            if (check) {
                check = $("input:checkbox", check)[0];
            }
        }
        if (check) {
            if (check.__isGrayedCheckBox && precisely) {
                return check.getState() == "True";
            } else {
                return check.checked;
            }
        } else {
            return false;
        }
    }
}
