﻿// generic methods

if (!Array.indexOf) {
    //fix for js version 1
    Array.prototype.indexOf = function(value) { for (var i = 0; i < this.length; i++) { if (this[i] == value) { return i; } } return -1; };
}

if (!Array.insert) {
    Array.prototype.insert = function(value, index) { var _l = this.length; for (var i = index; i < l; i++) { this[i + 1] = this[i]; } this[index] = value; };
}

if (!Array.remove) {
    Array.prototype.remove = function(value) { var i = this.indexOf(value); if (i > -1) { this.splice(i, 1); return true } return false; };
}

if (!Array.addItems) {
    Array.prototype.addItems = function(items) { for (var i = 0; i < items.length; i++) { this.push(items[i]); } };
}

function getElementsByClassName(classname, tag) {
    if (!tag) tag = "*";
    var anchs = document.getElementsByTagName(tag);
    var total_anchs = anchs.length;
    var regexp = new RegExp('\\b' + classname + '\\b');
    var class_items = new Array()

    for (var i = 0; i < total_anchs; i++) { //Go thru all the links seaching for the class name
        var this_item = anchs[i];
        if (regexp.test(this_item.className)) {
            class_items.push(this_item);
        }
    }
    return class_items;
}

function addListener(element, type, expression, bubbling) {
    bubbling = bubbling || false;
    if (element.addEventListener) { // Standard
        element.addEventListener(type, expression, bubbling);
        return true;
    } else if (element.attachEvent) { // IE
        element.attachEvent('on' + type, expression);
        return true;
    } else
        return false;
}

if (typeof HTMLElement != "undefined" && !HTMLElement.prototype.insertAdjacentElement) {
    HTMLElement.prototype.insertAdjacentElement = function
		(where, parsedNode) {
        switch (where) {
            case 'beforeBegin':
                this.parentNode.insertBefore(parsedNode, this)
                break;
            case 'afterBegin':
                this.insertBefore(parsedNode, this.firstChild);
                break;
            case 'beforeEnd':
                this.appendChild(parsedNode);
                break;
            case 'afterEnd':
                if (this.nextSibling)
                    this.parentNode.insertBefore(parsedNode, this.nextSibling);
                else this.parentNode.appendChild(parsedNode);
                break;
        }
    }

    HTMLElement.prototype.insertAdjacentHTML = function
		(where, htmlStr) {
        var r = this.ownerDocument.createRange();
        r.setStartBefore(this);
        var parsedHTML = r.createContextualFragment(htmlStr);
        this.insertAdjacentElement(where, parsedHTML)
    }


    HTMLElement.prototype.insertAdjacentText = function
		(where, txtStr) {
        var parsedText = document.createTextNode(txtStr)
        this.insertAdjacentElement(where, parsedText)
    }
}

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent)
        while (1) {
        curleft += obj.offsetLeft;
        if (!obj.offsetParent)
            break;
        obj = obj.offsetParent;
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent)
        while (1) {
        curtop += obj.offsetTop;
        if (!obj.offsetParent)
            break;
        obj = obj.offsetParent;

    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}


function hideOverlappingElements(elementId, overlayControl, excludedIdNames) {
    if (Browser.Name == 'IE') {
        for (i = 0; i < document.all.tags(elementId).length; i++) {
            obj = document.all.tags(elementId)[i];

            if (!obj || !obj.offsetParent) {
                continue;
            }

            // Find the element's offsetTop and offsetLeft relative to the BODY tag.
            objLeft = obj.offsetLeft;
            objTop = obj.offsetTop;
            objParent = obj.offsetParent;

            while ((objParent != null) && (objParent.tagName.toUpperCase() != "BODY")) {
                objLeft += objParent.offsetLeft;
                objTop += objParent.offsetTop;

                objParent = objParent.offsetParent;
            }

            objHeight = obj.offsetHeight;
            objWidth = obj.offsetWidth;

            if ((overlayControl.offsetLeft + overlayControl.offsetWidth) <= objLeft);
            else if ((overlayControl.offsetTop + overlayControl.offsetHeight) <= objTop);
            else if (overlayControl.offsetTop >= (objTop + objHeight));
            else if (overlayControl.offsetLeft >= (objLeft + objWidth));
            else {
                if (excludedIdNames != undefined) {
                    if (excludedIdNames.indexOf(obj.id) < 0)
                        obj.style.visibility = "hidden";
                }
                else {
                    obj.style.visibility = "hidden";
                }
            }
        }
    }
}


// Key restricter

function getKeyCode(e) {
    if (window.event)
        return window.event.keyCode;
    else if (e)
        return e.which;
    else
        return null;
}

var validchars = '1234567890';

function keyRestrict(e) {
    var key = '', keychar = '';
    key = getKeyCode(e);
    if (key == null) return true;
    keychar = String.fromCharCode(key);
    keychar = keychar.toLowerCase();
    validchars = validchars.toLowerCase();
    if (validchars.indexOf(keychar) != -1)
        return true;
    if (key == null || key == 0 || key == 8 || key == 9 || key == 13 || key == 27)
        return true;
    return false;
}

if (typeof (Sys) !== "undefined") {
    Sys.Application.notifyScriptLoaded();
}


// Ajax Scripts

function GetXmlHttp() {
    var xmlhttp = false;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest()
    }
    else if (window.ActiveXObject)// code for IE
    {
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
            } catch (E) {
                xmlhttp = false
            }
        }
    }
    return xmlhttp;
}

function AjaxCall(url, callbackFunction, errorFunction, params) {
    var xmlhttp = new GetXmlHttp();
    if (xmlhttp) {
        xmlhttp.onreadystatechange =
            function() {
                if (xmlhttp && xmlhttp.readyState == 4) {
                    if (xmlhttp.status == 200) {
                        var response = xmlhttp.responseText;

                        if (response != "OK") {
                            if (!errorFunction)
                                errorFunction = 'alert';

                            eval(errorFunction + '(response)');
                        }
                        else {
                            var functionToCall = callbackFunction +
                                 '(response,' + params + ')';

                            if (!functionToCall)
                                eval(functionToCall);
                        }
                    }
                    else {
                        if (!errorFunction) {
                            alert(xmlhttp.responseText);
                        }
                    }
                }
            }
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    }
}

function SetHtmlFromAjax(url, obj_id, errorFunction) {
    var xmlhttp = new GetXmlHttp();
    if (xmlhttp) {
        xmlhttp.onreadystatechange =
            function() {
                if (xmlhttp && xmlhttp.readyState == 4) {//we got something back..
                    if (xmlhttp.status == 200) {
                        if (typeof obj_id == 'object') {
                            obj_id.innerHTML = xmlhttp.responseText;
                        } else {
                            document.getElementById(obj_id).innerHTML =
                                          xmlhttp.responseText;
                        }
                    } else {
                        if (!errorFunction) {
                            alert(xmlhttp.responseText);
                        }
                    }
                }
            }
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    }
}

// popup (WTF?)

//Unify events with mozilla
if (!window.addEventListener) {
    window.addEventListener = function(eventName, method, capture) { window.attachEvent('on' + eventName, method); };
    window.removeEventListener = function(eventName, method, capture) { window.detachEvent('on' + eventName, method); };
}

//simulates width:100% and height:100%
function ResizeToFull(node) {
    var p = document.body.parentNode;
    var h = (p.scrollHeight > p.clientHeight ? p.scrollHeight : p.clientHeight);
    var w = (p.scrollWidth > p.clientWidth ? p.scrollWidth : p.clientWidth);
    node.style.height = h + 'px';
    node.style.width = w + 'px';
}

//Finds DOM nodes in root node with given tag names and passes to foundDelegate(node).
function FindNodesByTag(root, tag, neglectNodes) {
    var items = new Array();
    items.addItems(root.getElementsByTagName(tag));
    for (var i = 0; i < neglectNodes.length; i++) {
        items.remove(neglectNodes[i]);
        var nitems = neglectNodes[i].getElementsByTagName(tag);
        for (var j = 0; j < nitems.length; j++) {
            items.remove(nitems[j]);
        }
    }
    return items;
}


//Opens a dialog window and returns refrence.
function OpenDialog(url, width, height, resizable, scrollbars) {

    if (width == 0)
        width = screen.availWidth / 2;

    if (height == 0)
        height = screen.availHeight / 2;

    var left = Math.round((screen.availWidth - width) / 2);
    var top = Math.round((screen.availHeight - height) / 2);

    var popup = window.open(url, 'popup', 'left=' + left + ',top=' + top + ',width=' + width + ',height=' + height + ',modal=yes,resizable=' + (resizable ? 'yes' : 'no') + ',scrollbars=' + (scrollbars ? 'yes' : 'no'));
    
    return popup;
}

//Generates an overlay div with given color and opacity.
function GetOverlay(opacity, color) {
    var layer = document.createElement('div');
    ResizeToFull(layer);
    layer.style.filter = 'alpha(opacity=' + opacity + ')';
    layer.style.opacity = opacity / 100;
    layer.style.backgroundColor = color;

    if (Browser.Name == 'IE')
        layer.style.zIndex = 0;
    else
        layer.style.zIndex = 'auto';

    layer.style.position = 'absolute';
    layer.style.top = '0px';
    layer.style.left = '0px';
    layer.style.display = 'block';
    return layer;
}

function fixIeDropDown(select){

	var select = (typeof select == "string") ? document.getElementById(select) : select;

	// THIS FUNCTION IS ONLY CONCERNED WITH INTERNET EXPLORER NON-MULTIPLE SELECT NODES THAT HAVE A SPECIFIC WIDTH DEFINED
	if(!select.attachEvent || navigator.userAgent.indexOf("Opera") > -1 || select.multiple || select.currentStyle.width == "auto") { return; }

	var body = document.getElementsByTagName("body").item(0);

	var si = select.selectedIndex;

	var clone = select.cloneNode(true);
	clone.style.position = "absolute";
	clone.style.visibility = "hidden";
	clone.style.width = "auto";
	body.appendChild(clone);

	clone._initialOffsetWidth = select.offsetWidth;
	clone._initialOffsetHeight = select.offsetHeight;
	clone._autoWidth = clone.offsetWidth;

	clone = body.removeChild(clone);
	clone.style.visibility = "visible";
	clone.style.width = clone._initialOffsetWidth + "px";

	var span = document.createElement("span");
	span._isIeDropDownContainer = true;
	span.style.position = "relative";
	span.style.width = clone._initialOffsetWidth + "px";
	span.style.height = clone._initialOffsetHeight + "px";
	span.style.marginBottom = "-4"; //hmm...quirky...
	span.appendChild(clone);

	if (select.parentNode._isIeDropDownContainer){
		select.parentNode.parentNode.replaceChild(span, select.parentNode);
	}else{
		select.parentNode.replaceChild(span, select);
	}

	if (clone._autoWidth > clone._initialOffsetWidth){
		var expand = function(){
			event.srcElement.parentNode.style.zIndex = 1;
			event.srcElement.style.width = "auto";
			if (event.srcElement.offsetWidth > event.srcElement._initialOffsetWidth){
				event.srcElement.style.width = "auto";
			}else{
				event.srcElement.style.width = event.srcElement._initialOffsetWidth + "px";
			}
		};
		var contract = function(){
			event.srcElement.parentNode.style.zIndex = 0;
			event.srcElement.style.width = event.srcElement._initialOffsetWidth + "px";
		};
		clone.attachEvent("onactivate", expand);
		clone.attachEvent("ondeactivate", contract);
	}
	clone.selectedIndex = si;
}

function fixAllIeDropDowns(){
    var selects = document.getElementsByTagName("select");
    for (var i = 0; i < selects.length; i++) {
        fixIeDropDown( selects[i] );
    }
}

function _browser() {
    var index;
    var userAgent = window.navigator.userAgent;
    this.Name = (((index = (userAgent.indexOf('MSIE'))) != -1) ? 'IE' : (((index = (userAgent.indexOf('Netscape'))) != -1) ? 'Netscape' : (((index = (userAgent.indexOf('Firefox'))) != -1) ? 'Firefox' : 'Unknown')));
    this.Version = parseFloat(this.Name == 'MSIE' ? userAgent.substring(index + 4, userAgent.length) : (this.Name == 'Netscape' ? userAgent.substring(index + 9, userAgent.length) : (this.Name == 'Firefox' ? userAgent.substring(index + 8, userAgent.length) : 0)));
}

var Browser = new _browser();


if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();