﻿// Preloaded images array
/// <reference path="droplet-grid.js" />

var _images = new Array();
_images["checkbox"] = new Image(9,9);
_images["checkbox"].src = "/assets/droplets/checkbox.gif";
_images["checkbox-off"] = new Image(9,9);
_images["checkbox-off"].src = "/assets/droplets/checkbox-off.gif";
_images["plus"] = new Image(9,9);
_images["plus"].src = "/assets/droplets/plus.gif";
_images["minus"] = new Image(9,9);
_images["minus"].src = "/assets/droplets/minus.gif";
_images["up"] = new Image(18,12);
_images["up"].src = "/assets/droplets/opt-up.gif";
_images["down"] = new Image(18,12);
_images["down"].src = "/assets/droplets/opt-down.gif";
_images["blank"] = new Image(18,12);
_images["blank"].src = "/assets/blank.gif";
_images["check"] = new Image(17,13);
_images["check"].src = "/assets/droplets/opt-check.gif";

function returnFalse()
{
    return false;
}

function emptySelection()
{
    if(window.getSelection && window.getSelection() != "")
    {   
        var sel = window.getSelection();
        sel.removeAllRanges();
    }
    else if(document.selection)
        document.selection.empty();
}


function getCookie(Name) 
{
    var search = Name + "="
    if (document.cookie.length > 0) { 
        // if there are any cookies
        offset = document.cookie.indexOf(search)
        if (offset != -1) { 
            // if cookie exists
            offset += search.length

            // set index of beginning of value
            end = document.cookie.indexOf(";", offset)

            // set index of end of cookie value
            if (end == -1)
                end = document.cookie.length
			
            return unescape(document.cookie.substring(offset, end))
        }
    }
}


function returnTrue()
{
    return true;
}

function addEvent(element, type, handler) {
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else {
		// assign each event handler a unique ID
		if (!handler.$$guid) handler.$$guid = addEvent.guid++;
		// create a hash table of event types for the element
		if (!element.events) element.events = {};
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = handleEvent;
	}
};
// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} else {
		// delete the event handler from the hash table
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
};

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) == false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};


// IE Compatibility
var isIE = (typeof document.all != "undefined");
var isIE6 = false;

function setIE6()
{
    isIE6 = isIE && (typeof document.body.style.maxHeight == "undefined");
}


function showPropsOf(obj)
{
    var props = "";
    for(prop in obj)
    {
        props += prop + "=" + obj[prop] + "\n";
    }
    alert(props);
}

function makeElement(name, attr, txt, cmt, data)
{
    var el = document.createElement(name);

    var u = "undefined";
    if(typeof attr != u && attr != null)
    {
        //Add attributes
        for(prop in attr)
        {
            if(prop.toString() == "cn")
            {
                el.className = attr[prop];
            }
            else if(prop.toString() == "style") 
            {
                for(style in attr[prop])
                {
                    if(style.toString() == "float")
                    {
                        if(isIE) // IE is a POS
                            el.style.styleFloat = attr[prop][style];
                        else
                            el.style.cssFloat = attr[prop][style];
                    }
                    else
                    {
                        el.style[style.toString()] = attr[prop][style];
                    }
                }
            }
            else if (prop.toString() == "frameborder")
            {
                el.frameBorder = attr[prop];
            }
            else
            {
                el.setAttribute(prop.toString(), attr[prop]);
            }
        }
    }

    if(typeof txt != u && txt != null)
        el.appendChild(document.createTextNode(txt));
    
    if(typeof cmt != u && cmt != null)
        el.appendChild(document.createComment(cmt));

    if(typeof data != u && data != null)
    {
        if(name == "img")
            el.src = data;
        else
            el.innerHTML = data;
    }

    return el;
}

function getQueryVariable(name) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == name)
			return pair[1];
	}
	
	return null;
}

function hasQueryVariable(name) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == name)
			return true;
	}
	
	return false;
}

var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};

var selectsHidden = false;

function toggleSelects(enforce, within)
{
    if(isIE6)
    {
        if(typeof enforce == "undefined")
            enforce = "toggle";

        if(enforce == "hide")
            selectsHidden = false;
        else if(enforce == "show")
            selectsHidden = true;
            
        if(typeof within == "undefined")
            within = document;

        var boxes = within.getElementsByTagName("select");
        for(var s = 0; s < boxes.length; s++) 
            boxes[s].style.visibility = (selectsHidden) ? "" : "hidden";
        
        selectsHidden = !selectsHidden;
    }
}

var overflowsHidden = false;

function toggleOverflowsOnClass(cn, under, enforce)
{
    var nav = navigator.userAgent.toLowerCase();
    if((nav.match("mozilla/5.0") && nav.match("macintosh") && nav.match("gecko") && nav.match("firefox/2")) != null)
    {
        if(typeof enforce == "undefined")
            enforce = "toggle";

        if(enforce == "hide")
            overflowsHidden = false;
        else if(enforce == "show")
            overflowsHidden = true;

        var boxes = getElementsByClassName(cn, "div", under);
        for(var s = 0; s < boxes.length; s++) 
            boxes[s].style.overflow = (overflowsHidden) ? "auto" : "hidden";
        
        overflowsHidden = !overflowsHidden;
    }
}

function clearTree(node)
{
    if(node != null)
    {
        if(node.childNodes != null && node.childNodes.length > 0)
        {
            for(var x = node.childNodes.length - 1; x > -1; x--)
            {
                if(!isIE && node.childNodes[x].childNodes != null && node.childNodes[x].childNodes.length > 0)
                {
                    this.clearTree(node.childNodes[x]);
                }
                
                node.removeChild(node.childNodes[x]);
            }
        }
    }
}

function clearMeOf(element, whatToClear)
{
    if(!element.readOnly && element.value.match(whatToClear))
    {
        element.style.color = "black";
        regexp = new RegExp(whatToClear,"g");
        element.value = element.value.replace(regexp, "");
    }
}

function replenishWith(element, whatToInsert, color)
{
    if(typeof color == "undefined")
        color = "#d4d0c8";
        
    if(!element.readOnly && element.value == "")
    {
        element.style.color = color;
        element.value = whatToInsert;
    }        
}

function toggle(btn, elementClass){
    var _element = null;
	if(typeof elementClass == "undefined")
	{
		_element = btn.parentNode.getElementsByTagName("div")[0];
	}
	else
	{
	    _element = getElementsByClassName(elementClass, "div", btn.parentNode)[0];
	}

	var _cn = _element.className.toString();
	_element.className = (_cn.match("hide")) ? _cn.replace(/\shide\b|\bhide\b/g,"") : _cn + " hide";

	var _imgs = btn.getElementsByTagName("img");
	if(_imgs.length > 0)
	{
	    _imgs[0].src = (_cn.match("hide")) ? _images["minus"].src : _images["plus"].src;
	}

	zIndexMgr.setzIndexOf(_element);
	return false;
}

function toggleOver(e, element)
{
    if(typeof element  == "undefined")
        element = this;
        
    var cn = element.className.toString();        
    element.className = cn.replace(/\sovr\b|\bovr\b/g,"") + " ovr";
    return true;
}

function toggleOut(e, element)
{
    if(typeof element  == "undefined")
        element = this;
        
    var cn = element.className.toString();        
    element.className = cn.replace(/\sovr\b|\bovr\b/g,"");
    return true;
}



function toggleButtons(e, element, forceHide)
{
	if(typeof element  == "undefined")
        element = this;
        
	childLinks = element.getElementsByTagName("a");
	
	for(var i = 0; i < childLinks.length; i++)
	{
		var cn = childLinks[i].className;
		if((forceHide && !cn.match("hide")) || !forceHide)
			childLinks[i].className = (cn.match("hide")) ? cn.replace(/\shide\b|\bhide\b/g,"") : cn + " hide";
	}
    
    /*   
    var cn = element.getElementsByTagName("td")[1].getElementsByTagName("a")[0].className;
    if((forceHide && !cn.match("hide")) || !forceHide)
        element.getElementsByTagName("td")[1].getElementsByTagName("a")[0].className = (cn.match("hide")) ? cn.replace(/\shide\b|\bhide\b/g,"") : cn + " hide";
    
    cn = element.getElementsByTagName("td")[2].getElementsByTagName("a")[0].className;
    if((forceHide && !cn.match("hide")) || !forceHide)
        element.getElementsByTagName("td")[2].getElementsByTagName("a")[0].className = (cn.match("hide")) ? cn.replace(/\shide\b|\bhide\b/g,"") : cn + " hide";
	*/
}
function getKeyCode(e)
{
    return window.event ? e.keyCode : e.which;
}

function keyIsCommon(e) // e = Keydown event
{
    // common keys are (tab) (delete) (up) (down) (left) (right) (home) (end) (backspace) (shift)
    if((getKeyCode(e) == 0) || (getKeyCode(e) >= 8 && getKeyCode(e) <= 9) || (getKeyCode(e) >= 35 && getKeyCode(e) <= 40) || getKeyCode(e) == 46 || getKeyCode(e) == 16)
        return true;
    else
        return false;    
}

function keyIsArrow(e)
{
    if(getKeyCode(e) >= 35 && getKeyCode(e) <= 40)
        return true;
    else
        return false;
}

function keyIsNum(e) // e = Keydown event
{
    if ((getKeyCode(e) >= 48 && getKeyCode(e) <= 57) || (getKeyCode(e) >= 93 && getKeyCode(e) <= 105))
        return true;
    else     
        return false;
}

function keyIsAlpha(e) // e = Keydown event
{
    if(getKeyCode(e) >= 65 && getKeyCode(e) <= 90)
        return true;
    else
        return false;
}

function keyIsAlphaNum(e) // e = Keydown event
{
    if(keyIsNum(e) || keyIsAlpha(e))
        return true;
    else
        return false;
}

function onHitKey(e, keyCode, elementOrId)
{
    if(getKeyCode(e) == keyCode)
    {        
        var type = typeof elementOrId;
        
        var element = (type.toLowerCase() == "object") ? elementOrId : document.getElementById(elementOrId);
        
        if(element.click != null)
        {
            element.click();
        }
        else if (element.onclick != null)
        {
            element.onclick();
        }
        else if (element.href != null && element.href.match('javascript:'))
        {
            eval(unescape(element.href.replace('javascript:','')));
        }        

        return false;
    }
    else
    {
        return true;
    }
}

function getOffsetTop(node)
{
    var t = 0;
    while (node)
    {
        if (typeof node.offsetTop != "undefined")
        {
             t += node.offsetTop;
        }
             
        node = (typeof node.offsetParent != "undefined") ? node.offsetParent : null;
    }

    return parseInt(t);
}

function getOffsetLeft(node)
{
    var l = 0;
    while (node)
    {
        if (typeof node.offsetLeft != "undefined")
        {
             l += node.offsetLeft;
        }
             
        node = (typeof node.offsetParent != "undefined") ? node.offsetParent : null;
    }
    return parseInt(l);
}

function getWindowHeight()
{
    return (typeof window.innerHeight == "undefined") ? parseInt(document.body.clientHeight) : parseInt(window.innerHeight);
}



function zIndexMgrObj()
{   
    var _this = this;
    this.zIndex = 100;
    this.setzIndexOf = function(element)
    {
        if(element.style.zIndex < _this.zIndex || element.style.zIndex > 9000)
        {
            _this.zIndex++;
            element.style.zIndex = _this.zIndex;
        }
    };
}

var zIndexMgr = new zIndexMgrObj();

function dialogMgrObj()
{
    var _this = this;
    this.dialog = null;
    this.button = null;
    this.isDropBtn = false;
    this.closeTimeout = null;
    this.closeEvent = returnFalse;
    
    this.close = function(e)
    {
        clearTimeout(_this.closeTimeout);
        
        _this.dialog.className = "hide";
        
        removeEvent(_this.dialog, "mouseover", dialogMgr.noclose);
        removeEvent(_this.dialog, "mouseout", dialogMgr.toclose);        
        removeEvent(_this.button, "mouseout", dialogMgr.toclose);
        
        if(_this.isDropBtn)
            _this.button.className = "drop";

        _this.button = null;
        _this.isDropBtn = false;
        
        toggleSelects("show");
        toggleOverflowsOnClass("dropContent", document.body, "show");        
        
        _this.closeEvent();
    };
    
    this.toclose = function(e)
    {
        if(_this.closeTimeout != null)
            _this.noclose();
        
        if(this == _this.button)
            _this.closeTimeout = setTimeout(_this.close, 900);
        else
            _this.closeTimeout = setTimeout(_this.close, 600);
    };
    
    this.noclose = function(e)
    {
        clearTimeout(_this.closeTimeout);
    };
    
    this.init = function()
    {
        this.dialog = makeElement("div", {cn:'hide'});
        document.body.appendChild(this.dialog);
    };
    
    this.updatePosition = function(top, left)
    {
        if(top != null)
        {
            _this.dialog.style.top = top + "px";
        }
        
        if(left != null)
        {
            left = (left == "usebtn") ? getOffsetLeft(_this.button) : left;
            _this.dialog.style.left = left + "px";
        }
    };
    
    this.open = function(list, btn, offsetTop, offsetLeft, isDropBtn, closeEvent)
    {
        if(_this.dialog == null)
        {
            _this.init();
            _this.dialog.appendChild(list);
        }
        else
        {
            _this.dialog.replaceChild(list, _this.dialog.childNodes[0]);
        }
        
        _this.dialog.style.left = offsetLeft + "px";
        _this.dialog.style.top = offsetTop + "px";
        _this.dialog.className = "contextMenu";        
        
        _this.button = btn;
        _this.isDropBtn = isDropBtn;
        
        if(_this.isDropBtn)
            _this.button.className = "dropon";

        addEvent(_this.dialog, "mouseover", dialogMgr.noclose);
        addEvent(_this.dialog, "mouseout", dialogMgr.toclose);
        addEvent(_this.button, "mouseout", dialogMgr.toclose);
        
        _this.closeEvent = closeEvent;
        
        toggleSelects("hide");
        toggleOverflowsOnClass("dropContent", document.body, "hide");
    };
}

var dialogMgr = new dialogMgrObj();



function themeMgrObj()
{
    var _this = this;
    this.list = null;
    this.closeTimeout = null;
    this.currentTheme = "";
    this.changeWithSeason = true;
    this.themes = new Array();
    this.themes[0] = null;
    this.themes[1] = new Array("Spring", "spring");
    this.themes[2] = new Array("Summer", "summer");
    this.themes[3] = new Array("Autumn", "autumn");
    this.themes[4] = new Array("Winter", "winter");
    this.themes[5] = new Array("Starry Night", "starry");
    this.themes[6] = new Array("Citrus Summer", "citrus");
    this.stylesheets = new Array();
    this.ieStyleSheet = null;

    this.setTheme = function(to, save)
    {        
        if(typeof to == "object")
        {         
            to = parseInt(this.getAttribute("id").replace(/theme-/, ""));
            save = true;
        }

        for(var s = 0; s < _this.stylesheets.length; s++)
        {
            if(_this.stylesheets[s].getAttribute("title"))
            {
                if(isIE && _this.stylesheets[s].getAttribute("title") == "css-" + to)
                {                    
                    document.getElementsByTagName("head")[0].replaceChild(_this.stylesheets[s], _this.ieStyleSheet);                    
                    _this.ieStyleSheet = _this.stylesheets[s];
                    _this.ieStyleSheet.setAttribute("rel", "stylesheet");
                    break;
                }
                else if(!isIE)
                {
                    _this.stylesheets[s].disabled = true;
                    _this.stylesheets[s].disabled = (_this.stylesheets[s].getAttribute("title") != "css-" + to);
                }
            }
        }

        if(save)
        {
            _this.setAsSelected(to);
            _this.currentTheme = _this.themes[to][0];
            _this.save();
        }
    };
    
    this.setAsSelected = function(themeIdx)
    {
        for(var t = 0; t < _this.list.childNodes.length; t++)
        {
            _this.list.childNodes[t].style.fontWeight = (themeIdx == t) ? "bold" : "normal";
        }
    };
    
    this.save = function()
    {
        if(typeof Sys != "undefined")
            Ratchet.WeatherClub.Web.services.Theme.setSelectedTheme(_this.currentTheme);
    };
    
    this.setBySeason = function(e, save)
    {
        var today = new Date();
        var month = (today.getMonth() + 1).toString();
        var day = today.getDate().toString();
        day = (day.length == 1) ? "0" + day : day;

        var now = parseInt(month + day);
        
        if(now > 320 && now < 621) _this.setTheme(1, false);
        if(now > 620 && now < 923) _this.setTheme(2, false);
        if(now > 922 && now < 1221) _this.setTheme(3, false);
        if(now > 1220 || now < 321) _this.setTheme(4, false);
        
        _this.setAsSelected(0);
        _this.currentTheme = "";
        
        if(typeof save != "undefined")
            _this.save();
    };
    
    this.load = function(theme)
    {
        _this.currentTheme = theme;
        
        
        if(theme == "")
        {
            theme = getCookie('wc-theme');
        }
        
        if (typeof(theme) != "undefined")
        {
            for(var t = 1; t < _this.themes.length; t++)
            {
                if(_this.themes[t][0] == theme)
                {
                    _this.setTheme(t, false);
                    _this.setAsSelected(t);
                }
            }
        } 
        else
        {
            _this.setTheme(5,false);
        }
    };
    
    this.init = function(theme)
    {
        for(var t = 1; t < this.themes.length; t++)
        {
            var stylesheet = makeElement("link", {href:'/library/css/themes/' + this.themes[t][1] + '.css',rel:'alternate stylesheet',type:'text/css',title:'css-' + t,media:'screen'});
            
            if(!isIE)
                document.getElementsByTagName("head")[0].appendChild(stylesheet);
                
            this.stylesheets[this.stylesheets.length] = stylesheet;
        }
    
        this.list = makeElement("ul");
        
        this.list.appendChild(makeElement("li", {id:'theme-0',cn:'hand'}, "Change with Season"));
        
        addEvent(_this.list.childNodes[0], "click", this.setBySeason);
        
        for(var t = 1; t < this.themes.length; t++)
        {
            this.list.appendChild(makeElement("li", {id:'theme-' + t,cn:'hand'}, this.themes[t][0]));
            addEvent(this.list.childNodes[this.list.childNodes.length - 1], "click", this.setTheme);
        }
        
        this.load(theme);
    };
    
    this.open = function(btn)
    {
        dialogMgr.open(_this.list, btn, (getOffsetTop(document.getElementById("wc-header")) + 35), (getOffsetLeft(document.getElementById("wc-header")) + 755), false, returnFalse);
    };
}

var themeMgr = new themeMgrObj();

function wcMessageMgrObj()
{
    var _this = this;
    this.messageBox = null;
    this.opacity = 0;
    this.fadeTimer = null;
    this.step = 8;
    this.wcMessageArea = null;
    this.displayConfirmMsg = function() {
        document.getElementById("confirmOverlay").style.display = "inline";
    };
    this.showMessage = function(text)
    {
        if(text.toLowerCase() == "you are not logged in!")
            loginTools.showLogin(document.getElementById("ctl00_twcTopNav_ctlLoginStatus"));
        
        if(_this.fadeTimer != null)
            clearTimeout(_this.fadeTimer);
        
        if(_this.wcMessageArea == null)
            _this.wcMessageArea = document.getElementById("wc-message");
            
        _this.wcMessageArea.className = "";
            
        _this.messageBox = makeElement("div", {cn:"clr-theme",style:{margin:'0 auto',width:'90%',padding:"3px",fontSize:"80%",textAlign:"center"}}, text);
        _this.wcMessageArea.replaceChild(_this.messageBox, _this.wcMessageArea.childNodes[0]);        
        
        _this.opacity = 100;
        _this.fadeTimer = setTimeout(_this.fadeMessage, 5000);
    };
    this.fadeMessage = function()
    {
        clearTimeout(_this.fadeTimer);
        
        if(_this.opacity > 0)
        {
            _this.opacity = (_this.opacity - _this.step) < 0 ? 0 : (_this.opacity - _this.step);
            if(isIE)
                _this.messageBox.style.filter = "alpha(opacity=" + _this.opacity + ")";
            else
                _this.messageBox.style.opacity = (_this.opacity / 100);
        }
        
        if(_this.opacity > 0)
            _this.fadeTimer = setTimeout(_this.fadeMessage, 50);
        else
            _this.wcMessageArea.className = "hide";
    };
}


var wcMessageMgr = new wcMessageMgrObj();

function modalMgrObj()
{
    var _this = this;
    this.openOverlay = function(modalId) {
        document.getElementById(modalId).className = "";
        dropletMgr.dropletOverlay.className = "";
        zIndexMgr.setzIndexOf(dropletMgr.dropletOverlay);
        zIndexMgr.setzIndexOf(document.getElementById(modalId));
    };
    this.closeOverlay = function() {
    document.getElementById("introOverlay").className = 'hide';
    dropletMgr.dropletOverlay.className = "hide";
    
    };
}

var modalMgr = new modalMgrObj();

function postalCodeObj() {
    var _this = this;
    this.currentPostalCode = null;
    this.linkObj = null;
    this.textObj = null;
    this.divObj = null;
    this.change = function(_link) {
        if (typeof _link.tagName != "undefined")
            _this.linkObj = _link;

        _this.divObj = _this.linkObj.previousSibling.cloneNode(true);
        _this.currentPostalCode = _this.linkObj.previousSibling.childNodes[0].nodeValue;
        _this.textObj = makeElement("input", { type: 'text', cn: 'postalCode', value: _this.currentPostalCode, style: { float: 'left', marginRight: "3px"} });

        _this.linkObj.parentNode.replaceChild(_this.textObj, _this.linkObj.previousSibling);
        _this.linkObj.childNodes[0].nodeValue = "(save)";
        _this.linkObj.onclick = _this.commit;

        if (isIE)
            addEvent(_this.textObj, "keypress", postalCode.update);
        else
            _this.textObj.setAttribute("onkeypress", "return postalCode.update(event)");

        _this.textObj.focus();
        _this.textObj.select();
    };
    this.update = function(e) {
        if (getKeyCode(e) == 13)
            _this.commit();

        return (getKeyCode(e) != 13);
    };
    this.reset = function() {
        _this.textObj.parentNode.replaceChild(_this.divObj, _this.textObj);
        _this.linkObj.childNodes[0].nodeValue = "(change location)";
        _this.linkObj.onclick = _this.change;
    };
    this.commit = function() {
        if (_this.textObj.value != _this.currentPostalCode) {
            var expDate = new Date();
            expDate.setDate(expDate.getDate() + 90);
            document.cookie = "wc_PostalCode=" + escape(_this.textObj.value) + ";expires=" + expDate.toGMTString();
            window.location.reload();
        }
        else {
            _this.reset();
        }
    };
}

var postalCode = new postalCodeObj();

// Color tools
function ConvertToHex(color)
{
    if(color.match("#"))
        return color;
        
    color = color.replace(/rgb\(|\)|\s/g,"").split(/,/);

    return "#" + toHex(color[0])+toHex(color[1])+toHex(color[2]);
}

function toHex(N) {
    if (N == null)
        return "00";

    N = parseInt(N);

    if (N == 0 || isNaN(N))
        return "00";

    N = Math.max(0,N);

    N = Math.min(N,255);

    N = Math.round(N);

    return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}

function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

function setForecolor(bgColor)
{
    bgColor = ConvertToHex(bgColor);
    
    // W3C formula for deriving the brightness of a color
    var sum = Math.floor(255 - ((.299 * HexToR(bgColor) ) + (.587 * HexToG(bgColor)) + (.114 * HexToB(bgColor))));

    return (sum < 105) ? "Black" : "White";
}

function roundNumIfIE(num)
{
    if(isIE)
        return parseFloat(num.toString().substr(0, 5));
    else
        return num;
}


var wcContent = null;
var wcFooter = null;

function adjustFooter(e)
{
    if(wcContent == null)
        wcContent = document.getElementById("wc-content");

    if(wcFooter == null)
        wcFooter = document.getElementById("wc-footer-bg");

    wcFooter.className = "hide";
    wcContent.style.height = "auto";

    var offset = 164;

    if (document.getElementById("wc-register-device-band") != null) {
        offset += 72;
    }

    var winHeight = getWindowHeight();

    if(parseInt(wcContent.offsetHeight - 10) < (winHeight - offset))
        wcContent.style.height = (winHeight - offset) + "px";

    wcFooter.className = "";
    wcFooter.style.height = "52px";
    
}

function moveModals()
{
    var modals = getElementsByClassName("modalDialog", "div", wcContent);
    var washouts = getElementsByClassName("washout", "div", wcContent);

    for(var w = 0; w < washouts.length; w++)
    {
        if(washouts[w].className.toString().indexOf("fixed") == -1)
        {
            wcContent.appendChild(washouts[w]);
            zIndexMgr.setzIndexOf(washouts[w]);
        }
    }
    
    for(var m = 0; m < modals.length; m++)
    {
        if(modals[m].className.toString().indexOf("fixed") == -1)
        {
            wcContent.appendChild(modals[m]);
            zIndexMgr.setzIndexOf(modals[m]);
        }
    }
}


function loadEvents(e)
{
    if(isIE)
        setIE6();

    if(getQueryVariable("msg") != null)
        wcMessageMgr.showMessage(unescape(getQueryVariable("msg")));
        
    if(typeof checkForLoginErr != "undefined")
    {
        assignLoginPanelReferences();
        checkForLoginErr();
    }
    
    if(typeof dropletMgr != "undefined")
    {
        addEvent(window, "resize", dropletMgr.redraw);
        dropletMgr.redraw();
    }
    else
    {
        adjustFooter();
        addEvent(window, "resize", adjustFooter);
        moveModals();
        
        if(typeof Sys != "undefined")        
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(adjustFooter);
    }
}

addEvent(window, "load", loadEvents);
