// Global variables
var xMousePos = 0; // Horizontal position of the mouse on the screen
var yMousePos = 0; // Vertical position of the mouse on the screen
var xMousePosMax = 0; // Width of the page
var yMousePosMax = 0; // Height of the page
var windowsize = null;
var isIE = true;

// get mouse position
if (document.layers) { // Netscape
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
} else if (document.all) { // Internet Explorer
    document.onmousemove = captureMousePosition;
} else if (document.getElementById) { // Netcsape 6
    document.onmousemove = captureMousePosition;
}

function captureMousePosition(e) {

    if (!e) { e = window.event; } if (!e || (typeof (e.pageX) != 'number' && typeof (e.clientX) != 'number')) { xMousePos = 0; yMousePos = 0; }
    if (document.layers) {
        if (e) {
            xMousePos = e.pageX;
            yMousePos = e.pageY;
        }
        xMousePosMax = window.innerWidth + window.pageXOffset;
        yMousePosMax = window.innerHeight + window.pageYOffset;
    } else if (document.all && document.body) {
        xMousePos = e.clientX + document.documentElement.scrollLeft;
        yMousePos = e.clientY + document.documentElement.scrollTop;
        xMousePosMax = document.body.clientWidth + document.body.scrollLeft;
        yMousePosMax = document.body.clientHeight + document.body.scrollTop;
    } else if (document.getElementById) {
        if (e) {
            xMousePos = e.pageX + window.pageXOffset;
            yMousePos = e.pageY + window.pageYOffset;
        }
        xMousePosMax = window.innerWidth + window.pageXOffset;
        yMousePosMax = window.innerHeight + window.pageYOffset;
    }
    capturePageDimensions();
}

function capturePageDimensions() {
    if (document.body) {
        var xScroll, yScroll;

        if (window.innerHeight && window.scrollMaxY) {
            xScroll = document.body.scrollWidth;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }

        var wWidth, wHeight;
        if (self.innerHeight) {	// all except Explorer
            wWidth = self.innerWidth;
            wHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            wWidth = document.documentElement.clientWidth;
            wHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            wWidth = document.body.clientWidth;
            wHeight = document.body.clientHeight;
        }

        // for small pages with total height less then height of the viewport
        if (yScroll < wHeight) {
            pageHeight = wHeight;
        } else {
            pageHeight = yScroll + 50;
        }

        // for small pages with total width less then width of the viewport
        if (xScroll < wWidth) {
            pageWidth = wWidth;
        } else {
            pageWidth = xScroll;
        }

        var sLeft, sTop;
        if (window.pageXOffset) {
            sLeft = window.pageXOffset;
            sTop = window.pageYOffset;
        }
        else if (document.documentElement) {
            sLeft = document.documentElement.scrollLeft;
            sTop = document.documentElement.scrollTop;
        }
        else if (document.body) {
            sLeft = document.body.scrollLeft;
            sTop = document.body.scrollTop;
        }

        if (!windowsize) {
            windowsize = {
                width: pageWidth,
                height: pageHeight,
                windowWidth: wWidth,
                windowHeight: wHeight,
                scrollTop: sTop,
                scrollLeft: sLeft
            }
        } else {
            windowsize.width = pageWidth;
            windowsize.height = pageHeight;
            windowsize.windowWidth = wWidth;
            windowsize.windowHeight = wHeight;
            windowsize.scrollTop = sTop;
            windowsize.scrollLeft = sLeft;
        }
    }
}

function getStyle(element, style) {
    var value = element.style[style];
    if (!value) {
        if (document.defaultView && document.defaultView.getComputedStyle) {
            var css = document.defaultView.getComputedStyle(element, null);
            value = css ? css.getPropertyValue(style) : null;
        } else if (element.currentStyle) {
            value = element.currentStyle[style];
        }
    }

    return value;
}

function Hover(item, hover, cssclass) {
    if (hover) {
        if (!containsCssClass(item, cssclass)) {
            addCssClass(item, cssclass);
        }
    }
    else {
        if (containsCssClass(item, cssclass)) {
            removeCssClass(item, cssclass);
        }
    }
}

function SwapContent(id) {
    var contentholder = $get("contentdiv");
    var contentinnerholder = $get("contentinnerdiv");

    var itema = $get("theme_large_" + id);

    //var itemb = contentinnerholder.childNodes[0];

    var items = contentinnerholder.getElementsByTagName('div');

    var itemb = items[0];

    if (itema.id != itemb.id) {
        itema.style.display = "block";
        itemb.style.display = "none";

        contentholder.appendChild(itemb);
        contentinnerholder.appendChild(itema);
    }
}

function Swap(itemid, container, css) {
    if ($("#" + container).children("." + css).length == 0) { return; }
    if ($("#" + container).children("." + css)[0].id == itemid) { return; }
    $("#" + container).children("." + css).removeClass(css);
    $("#" + itemid).addClass(css);
}

function Colapse(ctrl, id, style) {
    var div = $get(id);
    if (div.style.display == "none") {
        div.style.display = "block";
        Hover(ctrl, false, style);
    }
    else {
        div.style.display = "none";
        Hover(ctrl, true, style);
    }
}

// watermark focus
function waterMark_Validate(obj) {
    if (obj.value == obj.getAttribute("ovalue")) {
        obj.value = '';
    }
}

function waterMark_focus(obj) {
    if (obj.value == obj.getAttribute("ovalue")) {
        obj.value = '';
    }
}

function waterMark_BlurChild(childObj, obj) {
    if (childObj.value == childObj.getAttribute("ovalue")) {
        childObj.value = '';
    }
}

function waterMark_Blur(obj, parentObj) {
    if (parentObj) {
        if (parentObj.value == parentObj.getAttribute("ovalue") && obj.value != obj.getAttribute("ovalue")) {
            if (obj.value == '') {
                obj.value = obj.getAttribute("ovalue");
            }
        }
    }
    else {
        if (obj.value != obj.getAttribute("ovalue")) {
            if (obj.value == '') {
                obj.value = obj.getAttribute("ovalue");
            }
        }
    }
}

function maxLimitLength(obj) {
    var maxlength = obj.getAttribute("maxLength")
    if (obj.value.length >= maxlength) {
        obj.value = obj.value.substring(0, maxlength);
    }
}

function getElementsByClassName(oElm, strTagName, strClassName) {
    var arrElements = (strTagName == "*" && oElm.all) ? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for (var i = 0; i < arrElements.length; i++) {
        oElement = arrElements[i];
        if (oRegExp.test(oElement.className)) {
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}

function DisableExpressButton(btn, redirect) {
    if (redirect == null) {
        redirect = true;
    }
    var href = btn.getAttribute("href");
    btn.setAttribute("xhref", href);
    btn.setAttribute("xonclick", btn.getAttribute("onclick"));

    btn.removeAttribute("href");
    btn.removeAttribute("onclick");
    Hover(btn, true, 'btndisabled');

    if (href && redirect)
        window.location = href;
}

function EnableExpressButton(btn) {
    var xhref = btn.getAttribute("xhref");
    var xonclick = btn.getAttribute("xonclick");

    if (xhref) {
        btn.setAttribute("href", xhref);
        btn.removeAttribute("xhref");
    }
    if (xonclick) {
        btn.setAttribute("onclick", xonclick);
        btn.removeAttribute("xonclick");
    }

    Hover(btn, false, 'btndisabled');
}

function EditContent(url) {
    window.open(url, 'contenteditor', 'width=1024,height=768,scrollbars=yes,toolbar=no,location=no,resizable=yes');
}

function DisplayContentButtons(show) {
    var items = getElementsByClassName(document, "cite", "admincmseditbutton");

    if (show) {
        for (var i = 0; i < items.length; i++) {
            removeCssClass(items[i], "cmsedithide");
        }
        $get("cmshidebutton").style.display = "block";
        $get("cmsshowbutton").style.display = "none";
    }
    else {
        for (var i = 0; i < items.length; i++) {
            if (!containsCssClass(items[i], "cmsedithide")) {
                addCssClass(items[i], "cmsedithide");
            }
        }
        $get("cmsshowbutton").style.display = "block";
        $get("cmshidebutton").style.display = "none";
    }

    document.cookie = "cmsiseb=" + show + "; path=/"
}

function ForceJavaUpload() {
    var url = window.location.toString();

    if (url.indexOf('?') > 0) {
        window.location = url + "&java=true";
    }
    else {
        window.location = url + "?java=true";
    }
}

// Trick to show validation callout when validation is invalid (bug in Ajax toolkit)
function TriggerValidationCallout(validationGroup) {
    try {
        if ((typeof (Page_Validators) != "undefined") && (Page_Validators != null)) {
            var i;
            for (i = 0; i < Page_Validators.length; i++) {
                if ((!Page_Validators[i].isvalid) && (Page_Validators[i].validationGroup == validationGroup)) {
                    var x = Page_Validators[i].controltovalidate;
                    if ((x != null) && x != 'undefined') {
                        $get(x).focus();
                        return 0;
                    }
                }
            }
        }
        return 1;
    }
    catch (error) { }
}

//----------------------------------------------------------------------
//  modified methods and functions copied from microsoft ajax library
//----------------------------------------------------------------------
function addCssClass(element, className) {
    if (!containsCssClass(element, className)) {
        if (element.className === '') {
            element.className = className;
        }
        else {
            element.className += ' ' + className;
        }
    }
}

function containsCssClass(element, className) {
    return Array.contains(element.className.split(' '), className);
}

function removeCssClass(element, className) {
    var currentClassName = ' ' + element.className + ' ';
    var index = currentClassName.indexOf(' ' + className + ' ');
    if (index >= 0) {
        element.className = (currentClassName.substr(0, index) + ' ' +
            currentClassName.substring(index + className.length + 1, currentClassName.length)).trim();
    }
}

var $get = function(id, element) {

    if (!element) return document.getElementById(id);
    if (element.getElementById) return element.getElementById(id);

    var nodeQueue = [];
    var childNodes = element.childNodes;
    for (var i = 0; i < childNodes.length; i++) {
        var node = childNodes[i];
        if (node.nodeType == 1) {
            nodeQueue[nodeQueue.length] = node;
        }
    }

    while (nodeQueue.length) {
        node = nodeQueue.shift();
        if (node.id == id) {
            return node;
        }
        childNodes = node.childNodes;
        for (i = 0; i < childNodes.length; i++) {
            node = childNodes[i];
            if (node.nodeType == 1) {
                nodeQueue[nodeQueue.length] = node;
            }
        }
    }

    return null;
}

Array.__typeName = 'Array';
Array.__class = true;

Array.add = Array.enqueue = function Array$enqueue(array, item) {
    array[array.length] = item;
}

Array.addRange = function Array$addRange(array, items) {
    array.push.apply(array, items);
}

Array.clear = function Array$clear(array) {
    array.length = 0;
}

Array.clone = function Array$clone(array) {
    if (array.length === 1) {
        return [array[0]];
    }
    else {
        return Array.apply(null, array);
    }
}

Array.contains = function Array$contains(array, item) {
    return (Array.indexOf(array, item) >= 0);
}

Array.dequeue = function Array$dequeue(array) {
    return array.shift();
}

Array.forEach = function Array$forEach(array, method, instance) {
    for (var i = 0, l = array.length; i < l; i++) {
        var elt = array[i];
        if (typeof (elt) !== 'undefined') method.call(instance, elt, i, array);
    }
}

Array.indexOf = function Array$indexOf(array, item, start) {
    if (typeof (item) === "undefined") return -1;
    var length = array.length;
    if (length !== 0) {
        start = start - 0;
        if (isNaN(start)) {
            start = 0;
        }
        else {
            if (isFinite(start)) {
                start = start - (start % 1);
            }
            if (start < 0) {
                start = Math.max(0, length + start);
            }
        }

        for (var i = start; i < length; i++) {
            if ((typeof (array[i]) !== "undefined") && (array[i] === item)) {
                return i;
            }
        }
    }
    return -1;
}

Array.insert = function Array$insert(array, index, item) {
    array.splice(index, 0, item);
}

Array.parse = function Array$parse(value) {
    if (!value) return [];
    var v = eval(value);
    if (!Array.isInstanceOfType(v)) throw Error.argument('value', Sys.Res.arrayParseBadFormat);
    return v;
}

Array.remove = function Array$remove(array, item) {
    var index = Array.indexOf(array, item);
    if (index >= 0) {
        array.splice(index, 1);
    }
    return (index >= 0);
}

Array.removeAt = function Array$removeAt(array, index) {
    array.splice(index, 1);
}

// String

String.__typeName = 'String';
String.__class = true;

String.prototype.endsWith = function String$endsWith(suffix) {
    return (this.substr(this.length - suffix.length) === suffix);
}

String.prototype.startsWith = function String$startsWith(prefix) {
    return (this.substr(0, prefix.length) === prefix);
}

String.prototype.trim = function String$trim() {
    return this.replace(/^\s+|\s+$/g, '');
}

String.prototype.trimEnd = function String$trimEnd() {
    return this.replace(/\s+$/, '');
}

String.prototype.trimStart = function String$trimStart() {
    return this.replace(/^\s+/, '');
}

String.format = function String$format(format, args) {
    return String._toFormattedString(false, arguments);
}

String.localeFormat = function String$localeFormat(format, args) {
    return String._toFormattedString(true, arguments);
}

String._toFormattedString = function String$_toFormattedString(useLocale, args) {
    var result = '';
    var format = args[0];

    for (var i = 0; ; ) {
        var open = format.indexOf('{', i);
        var close = format.indexOf('}', i);
        if ((open < 0) && (close < 0)) {
            result += format.slice(i);
            break;
        }
        if ((close > 0) && ((close < open) || (open < 0))) {
            if (format.charAt(close + 1) !== '}') {
                throw Error.argument('format', Sys.Res.stringFormatBraceMismatch);
            }
            result += format.slice(i, close + 1);
            i = close + 2;
            continue;
        }

        result += format.slice(i, open);
        i = open + 1;

        if (format.charAt(i) === '{') {
            result += '{';
            i++;
            continue;
        }

        if (close < 0) throw Error.argument('format', Sys.Res.stringFormatBraceMismatch);


        var brace = format.substring(i, close);
        var colonIndex = brace.indexOf(':');
        var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex)) + 1;
        if (isNaN(argNumber)) throw Error.argument('format', Sys.Res.stringFormatInvalid);
        var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1);

        var arg = args[argNumber];
        if (typeof (arg) === "undefined" || arg === null) {
            arg = '';
        }

        if (arg.toFormattedString) {
            result += arg.toFormattedString(argFormat);
        }
        else if (useLocale && arg.localeFormat) {
            result += arg.localeFormat(argFormat);
        }
        else if (arg.format) {
            result += arg.format(argFormat);
        }
        else
            result += arg.toString();

        i = close + 1;
    }

    return result;
}

// Code for albumselection grayed-out existing and new
//**************************************************
function RadioButtonAlbum_click(clientIdPrefix) {
    var RadioNew = $get(clientIdPrefix + "RadioButtonNew");
    var dropdown = $get(clientIdPrefix + "DropDownListAlbums");
    var textbox = $get(clientIdPrefix + "InputNewAlbum");

    if ((RadioNew != null) && (RadioNew.checked)) {
        if (textbox) { textbox.disabled = false; }
        if (dropdown) { dropdown.disabled = true; }
    }
    else {
        if (textbox) { textbox.disabled = true; }
        if (dropdown) { dropdown.disabled = false; }
    }
}

function CheckRadioButtonNewAlbum(clientIdPrefix) {
    var RadioNew = $get(clientIdPrefix + "RadioButtonNew");

    if (RadioNew != null) {
        RadioNew.checked = true
    }
}

function CheckRadioButtonExistingAlbum(clientIdPrefix) {
    var RadioExisting = $get(clientIdPrefix + "RadioButtonExisting");

    if (RadioExisting != null) {
        RadioExisting.checked = true
    }
}

/* Onmouseover and onmouseout for rcHover */
function RCIn(item, prefix) {
    var el = $(item);
    if (typeof (prefix) == "undefined") { prefix = "boxRc"; }
    el.find("." + prefix + "Topleft").css({ 'background-position': '0 -437px' });
    el.find("." + prefix + "Topright").css({ 'background-position': 'right -437px' });
    el.find("." + prefix + "Bottomleft").css("background-position", "0 -852px");
    el.find("." + prefix + "Bottomright").css("background-position", "right -852px");
}
function RCOut(item, prefix) {
    if (containsCssClass(item, "selected")) { return; }
    var el = $(item);
    if (typeof (prefix) == "undefined") { prefix = "boxRc"; }
    el.find("." + prefix + "Topleft").css("background-position", "0 0");
    el.find("." + prefix + "Topright").css("background-position", "right 0");
    el.find("." + prefix + "Bottomleft").css("background-position", "0 -421px");
    el.find("." + prefix + "Bottomright").css("background-position", "right -421px");
}

function ResetRCAddIn(resetelement, prefix) {
    $("." + resetelement + " div").each(function() {
        RCOut(this, prefix);
    });
}

function RCAddIn(item, prefix, resetelement) {
    if (resetelement) {
        ResetRCAddIn(resetelement, prefix);
    }
    var el = $(item);
    if (typeof (prefix) == "undefined") { prefix = "boxRc"; }
    if (typeof (el.find("." + prefix + "Topleft")[0]) == "undefined") {
        var offset = 14;
        var varHeight = el.height();
        var varWidth = el.width();
        el.append("<span class='" + prefix + "Topleft'></span>");
        el.append("<span class='" + prefix + "Topright'></span>");
        el.append("<span class='" + prefix + "Bottomleft'></span>");
        el.append("<span class='" + prefix + "Bottomright'></span>");
        el.find("." + prefix + "Topleft").css({ 'height': varHeight - offset });
        el.find("." + prefix + "Topright").css({ 'height': varHeight - offset });
        el.find("." + prefix + "Topleft").css({ 'width': varWidth - offset });
        el.find("." + prefix + "Bottomleft").css({ 'width': varWidth - offset });
    }
    RCIn(item);
}

function jHover(item, hover, cssclass) {
    if (hover) {
        item.addClass(cssclass);
    }
    else {
        item.removeClass(cssclass);
    }
}

function SetState(visualid, clicked, labelid) {

    var css = "selected";
    if (typeof (clicked) == "undefined" || clicked == null) { clicked = true; }
    if (typeof (labelid) == "undefined") { labelid = visualid; }

    // get input id from label
    var inputid = $("#" + labelid).attr("for");

    // get target input control
    var input = $("#" + inputid)[0];

    // if the input is a radio button
    if (input.type == "radio") {

        // loop all input controls and deselect other radiobuttons.
        $("input").each(function() {

            // if the input control is in the same group
            if (input.name == this.name) {

                // loop all labels to deselect the related radio buttons
                $("label").each(function() {

                    // get for attribute from label to get the input id
                    var labelfor = $(this).attr("for");

                    // if there is a for attribute ->  check the input name
                    if (labelfor != null && $("#" + labelfor)[0].name == input.name) {

                        // if the id is not the id we need to keep selected
                        if (labelfor != input.id) {

                            // check if the onclick event is triggered from another dom element
                            var obj = $("#" + labelfor);

                            // if there is a rel attribute
                            if (obj.attr("rel")) {
                                jHover($("#" + obj.attr("rel")), false, css);
                            }
                            else {
                                jHover($("#" + this.id), false, css);
                            }
                            // remove hover effect
                            RCOut(this);
                        }
                        else {
                            // set related checkbox selected
                            SelectParentCheckbox(input.name);
                        }
                    }
                });
            }
        });

        jHover($("#" + visualid), true, css);
    }
    else {
        // set selected
        if (input.checked && clicked) {
            jHover($("#" + visualid), false, css);
            DeselectRadioButtons(input.name);
        }
        else {
            jHover($("#" + visualid), true, css);
        }
    }
}

function SelectParentCheckbox(groupname) {
    var parent = groupname.toString().replace("sub", "");
    $("input").each(function() {
        if (this.name == parent) {
            this.checked = true;
            SelectVisual($(this), true);
        }
    });
}

function DeselectRadioButtons(groupname) {
    $("input").each(function() {
        // if the input control is in the same group
        if (this.name == "sub" + groupname) {
            if (this.checked) {
                // uncheck
                this.checked = false;
                SelectVisual($(this), false);
            }
        }
    });
}

function SelectVisual(obj, checked) {
    var css = "selected";
    // if there is a rel attribute
    if (obj.attr("rel")) {
        jHover($("#" + obj.attr("rel")), checked, css);
    }
    else {
        jHover(obj, checked, css);
    }
}

function CheckOptions(dialogdataid, messageid) {

    var item = $("#" + messageid);

    jHover(item, false, "txtRed");

    var selection = false;
    $("input", $("#" + dialogdataid)).each(function() {
        if (this.checked) { selection = true; }
    });

    if (!selection) {
        jHover(item, true, "txtRed");
        return false;
    }

    // TODO: redirect
    return true;
}

function PopupRequired() {
    // TODO: checks querystring
}