﻿var WIR = function(){
	return {
	      Tally: function(object, method, task, numthings){
	        var data = 'tallyObject=' + object + '&' +
				'tallyMethod=' + method + '&' +
				'tallyTask=' + task;
		    		
            if(numthings){
                data += '&tallyNumThings=' + numthings;
            }
        
            var page = 'http://www.workinretail.com/AJAX/ClientTally.aspx'; //this probably doesnt work on dev boxes, only production	
	        WIR.AJAX.submitCallback(data,page,function(){});
        },
        
        CheckManyMaxControlLength : function(arrObj)
        {
            for(var i=0; i<arrObj.length; i++)
            { 
                if(WIR.CheckMaxControlLength(arrObj[i].objId, arrObj[i].fieldName, arrObj[i].length, arrObj[i].showMsg) == false)
                {
                    return false;
                }
            }
            
            return true;
        },
        
        CheckMaxControlLength : function(objId, fieldName, length, showMsg)
        {
            var curlength = $get(objId).value.length;
                        
            if(curlength > length)
            {
                if(showMsg == true)
                    alert('You have exceeded max length for this field: ' + fieldName + ' (' + length + ')\nYour current character count is ' + curlength + '\nPlease shorten your text and try again.' );
                    
                return false;
            }
            
            return true;
        },
        
        CheckMaxLength : function(e, showAlert)
        {
            var domEvent = new Sys.UI.DomEvent(e);
            // Hack to accomodate Firefox inconsistencies with the keyCode
            if (Sys.Browser.agent == Sys.Browser.Firefox && e.keyCode && (e.keyCode === 46))
            {
                domEvent.keyCode = 127;
            }else{
                domEvent.keyCode = e.keyCode;
            }

            var textarea = domEvent.target;
            var charCode = domEvent.charCode;
            var textareaValue = textarea.value;
            
            // Hack to accomodate IE inconsistencies with whitespace
            textareaValue = textareaValue.replace(/\r\n/g, '\n');
            
            var actualLength = textareaValue.length;
            if (actualLength >= textarea.maxlength)
            {
            switch(domEvent.keyCode) {
                case Sys.UI.Key.backspace:
                case Sys.UI.Key.tab:
                case Sys.UI.Key.esc:
                case Sys.UI.Key.pageUp:
                case Sys.UI.Key.pageDown:
                case Sys.UI.Key.end:
                case Sys.UI.Key.home:
                case Sys.UI.Key.left:
                case Sys.UI.Key.up:
                case Sys.UI.Key.right:
                case Sys.UI.Key.down:
                case Sys.UI.Key.del:
                return true;
                case Sys.UI.Key.enter:
                case Sys.UI.Key.space:
                if(showAlert){alert('You have reached the maximum length for this field.');}
                return false;
                default: {
                    // Handle highlight/replace operations
                    if (document.selection) {
                        var range = document.selection.createRange();
                        var rangeElement = range.parentElement();
                        if (rangeElement == textarea) {
                            if (range.text.length > 0) {
                                return true;
                            }
                        }
                    } 
                    else if (textarea.selectionStart < textarea.selectionEnd) {
                        return true;
                    }
                }
            }
            
            // Hack to accomodate Safari inconsistencies with the keyCode
            if (domEvent.keyCode == 0 && domEvent.charCode == 0) 
            {
                return true;
            }

            if(showAlert)
            {
                alert('You have reached the maximum length for this field.');
            }
            
            return false;            
            
            }        
            
            return true;
        },

        FormToEmail: function(formObj, emailPrefix, emailSubject, callbackFunction)
        {
            //object that takes in POST forms (like surveys) and emails them to
            //the provided emailPrefix (the part before the AT part at our company)
            //Handy for collecting surveys and get the results emailed to you!
            var objValue = '';
            var objName = '';
            //lets first dissasamble the form object - take all values out of the formobjects
            //and send it down
            var radioGroupName = '';
            var paramValues = '';
            for(i=0; i<formObj.elements.length; i++)
            {   
                 //if the objects are of type radiobuttons, we only pick out the one that
                 //has been selected! (If none selected, we make value as blank string)
                 if(formObj.elements[i].type == 'radio')
                 {
                    if(radioGroupName != '' && radioGroupName != formObj.elements[i].name && paramValues.indexOf(radioGroupName) == -1)
                    {
                        //new radio coming in, the previous one was left unchecked!
                        if(paramValues != '')
                            paramValues += '&'; 
                               
                        paramValues += radioGroupName + '=';   //its unchecked
                    }
                    
                    radioGroupName = formObj.elements[i].name;    
                    if (formObj.elements[i].checked == true)
                    {
                        objValue = formObj.elements[i].value;
                        objName = formObj.elements[i].name;

                        if(paramValues != '')
                            paramValues += '&'; 
                               
                        paramValues += objName + '=' + escape(objValue);
                        uncheckedName = '';    
                    }
                 }
                 else
                 {
                    objName = formObj.elements[i].name;
                    objValue = formObj.elements[i].value;
                    if(paramValues != '')
                      paramValues += '&';
                      
                    paramValues += objName + '=' + escape(objValue);
                 }
                      
            } //end of for loop
            
            if(paramValues != '')
                paramValues += '&'
            
            paramValues += "FORMTOEMAIL_EmailPrefix=" + escape(emailPrefix);
            paramValues += "&FORMTOEMAIL_EmailSubject=" + escape(emailSubject);
          
            WIR.AJAX.submitCallback(paramValues, 'FormToEmail.aspx', callbackFunction);
        },
        
        object: function (o) 
        {
	        function F(){}
	        F.prototype = o;
	        return new F();
	    }
    	
	};
}();


/*
    The WIR.Window object holds properties that deliver useful information about the window.
    The methods are, for the most part, cross-browser compatible and return accurate information
    with or without the presence of the documentElement.
    
    These concepts in these properties came from Mootools.js and then were to be independent of the
    existence of the document element.
*/
WIR.Window = function (){
    // sets the number of pixels the window has scrolled down the page
    function setScrollTop(scrollTop){
        document.documentElement.scrollTop = scrollTop;
        document.body.scrollTop = scrollTop;
    }
    
    return {
        // returns an integer representing the width of the browser window (without the scrollbar)
        getWidth: function() {
    		if (WIR.Window.khtml) {
    		    return window.innerWidth;
    		}else if (window.opera) {
    		    return document.body.clientWidth;
    		}else {
    		    if (document.documentElement.clientWidth !== 0){
		            return document.documentElement.clientWidth;
    		    }
	    	    else {
		            return document.body.clientWidth;
		        }
		    }
        },
        // returns an integer representing the height of the browser window (without the scrollbar)
        getHeight: function() {
		    if (WIR.Window.khtml){
		        return window.innerHeight;
		    }else if (window.opera){
		        return document.body.clientHeight;
		    }else if (WIR.Window.gecko){
		        // firefox hack
		        return Math.min(document.documentElement.clientHeight, document.body.clientHeight);
		    } else {
		    	if(document.documentElement.clientHeight !== 0){
	                return document.documentElement.clientHeight;
	            }
	            else {
	                return document.body.clientHeight;
	            }
	        }
        },
        // returns an integer representing the scrollwidth of the window, which is >= getWidth
        getScrollWidth: function(){
		    if(WIR.Window.ie) {
		        return Math.max(Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth), document.body.scrollWidth);
		    }else if (WIR.Window.khtml) {
		        return document.body.scrollWidth;
		    }else {
		        return document.documentElement.scrollWidth;
		    }
        },
        // returns an integer representing the scrollHeight of the window, which is >= getHeight
        getScrollHeight: function(){
            if (WIR.Window.ie) {
		        return Math.max(Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight), Math.max(document.body.offsetHeight, document.body.scrollHeight));
		    }else if (WIR.Window.khtml) {
		        return document.body.scrollHeight;
		    }else {
	            return document.documentElement.scrollHeight;
	        }
        },
        // returns an integer representing the scrollLeft of the window (the num of pixels the window has scrolled from the left)
        getScrollLeft: function (){
            return window.pageXOffset || document.documentElement.scrollLeft;
        },
        // returns an integer representing the number of pixels the window has scrolled down the page
        getScrollTop: function(){
            return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
        },
        getSize: function(){
    		return {
			    size: {x: WIR.getWidth(), y: WIR.getHeight()},
			    scrollSize: {x: WIR.getScrollWidth(), y: WIR.getScrollHeight()},
			    scroll: {x: WIR.getScrollLeft(), y: WIR.getScrollTop()}
		    };
        },
        scrollDown: function(distance, rate) {
            for (i = 0; i < distance; i += rate){
                setScrollTop(WIR.Window.getScrollTop() + rate);
            }
	    }
    };
}();

// taken from Mootools to help sniff out the browser
// ie = ie; gecko = firefox/mozilla; khtml = ????
if (window.ActiveXObject){
    WIR.Window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
    WIR.Window.ie7 = (navigator.userAgent.indexOf('MSIE 7') > -1);
    WIR.Window.ie6 = (navigator.userAgent.indexOf('MSIE 6') > -1);
} else if (document.childNodes && !document.all && !navigator.taintEnabled){
    WIR.Window.khtml = true;
} else if (document.getBoxObjectFor !== null){
    WIR.Window.gecko = true;
}

WIR.EventUtils = function(){
    /**
	    Written by Peter Wilkinson of http://dynamic-tools.net
	    Feel free to use or modify this script for any purpose.  I'd appreciate you leaving
	    this header in though.
    */
    /**
        Minor modifications made by Matt McNair.  
        I changed the calling of the event handler so that the element originating the event is passed as a param.
    */
    function handleEvent(e){
	    var returnValue = true;
	    if (!e){ e = fixEvent(event);}
	    var handlers = this.eventHandlers[e.type];
	    for(var i = 0; i < handlers.length; i++){
	        if (handlers[i] && typeof handlers[i] == 'function'){
	            if (e.target){ // EOMB (every other modern browser)
		            returnValue = !((returnValue && handlers[i](e,e.target)) === false);
		        }else if(e.srcElement){ // IE
		            returnValue = !((returnValue && handlers[i](e,e.srcElement)) === false);
		        }else{
		            returnValue = !((returnValue && handlers[i](e)) === false);
		        }
		    }
	    }
	    return returnValue;
    }

    function fixEvent(e){
	    // add W3C standard event methods	    
	    e.preventDefault = fixEvent.preventDefault;
	    e.stopPropagation = fixEvent.stopPropagation;
	    return e;
    }

    fixEvent.preventDefault = function() {
	    this.returnValue = false;
    };

    fixEvent.stopPropagation = function() {
	    this.cancelBubble = true;
    };	
    
    return {
        addEventListener:function(elem, eventType, handler){
	        if (!elem.eventHandlers){elem.eventHandlers = [];}
	        if (!elem.eventHandlers[eventType])
	        {
		        elem.eventHandlers[eventType] = [];
		        if (elem['on' + eventType]){elem.eventHandlers[eventType].push(elem['on' + eventType]);}
		        elem['on' + eventType] = handleEvent; 
	        }
	        elem.eventHandlers[eventType].push(handler);
        },
        removeEventListener:function(elem, eventType, handler){
	        var handlers = elem.eventHandlers[eventType];
	        for(var i in handlers){
	            if (handlers[i] == handler){delete handlers[i];}
	        }
        },
        addLoadEvent:function(handler){
            this.addEventListener(window,'load',handler);
        },
        addResizeEvent:function(handler)
        {
            this.addEventListener(window, 'resize', handler);
        }
    };
}();

WIR.UpdatePanel = function(){

 return {

    dynamicAnchor: '',
    
    SetDynamicAnchor: function(anchorid)
    {
        dynamicAnchor = anchorid;
    },
    
    SetupProgressMessage: function(popupid, anchor, offsetX, offsetY, WaitingMessage, bShowErrorMessage)
    {
        var prm = Sys.WebForms.PageRequestManager.getInstance(); 
        prm.add_initializeRequest(InitializeRequest);
        prm.add_endRequest(EndRequest);
        var postBackElement;
        function InitializeRequest(sender, e)
        { 
          if (prm.get_isInAsyncPostBack())
            e.set_cancel(true);
            
            postBackElement = e.get_postBackElement(); 
            //if (postBackElement.id == 'Button1')
            //$get('CenterPopup').style.display = 'block';
            
            if(anchor != '')
                showWIRPopup(popupid, anchor, offsetX, offsetY, WaitingMessage);
            else if(dynamicAnchor != '')
                showWIRPopup(popupid, dynamicAnchor, offsetX, offsetY, WaitingMessage);
        }
        function EndRequest(sender, e)
        { 
          //if (postBackElement.id == 'Button1')
          //$get('CenterPopup').style.display = 'none'; 
           hideWIRPopup();
           if( e.get_error() != undefined )
           {
                   var errMsg = '';
                   errMsg += 'Unfortunately an error occured. Please try again later.';
                   if(bShowErrorMessage)
                    errMsg += '<br/>Message: ' + e.get_error().message.split(':')[1];
                    
                   errMsg += '<br/><br/><input type="button" class="SmallActionButton btnback_gray" value="Close" onclick="javascript:hideWIRPopup();" />'; 
                   
                   if(anchor != '')
                        showWIRPopup(popupid, anchor, offsetX, offsetY, errMsg);
                   else if(dynamicAnchor != '')
                        showWIRPopup(popupid, dynamicAnchor, offsetX, offsetY, errMsg);
                   
                   e.set_errorHandled( true );    
                  
           }
           
        }
    }
    
  };
}();

WIR.SuggestionTextbox = function(){
    function onBlur(textbox){
        if (textbox.value.length === 0 || textbox.value == textbox.suggestionText) {
            textbox.style.color = "gray";
            textbox.value = textbox.suggestionText;
        } 
        else {textbox.style.color = "";}
    }
    
    function onFocus(textbox){
        if (textbox.value == textbox.suggestionText) {
            textbox.value = "";
        }
        textbox.style.color = "";
    }
    
    function onSubmit(textbox){
        onFocus(textbox);
    }
    return{
        setupTextbox:function(textbox,suggestionText,submitButton){
            textbox.suggestionText = suggestionText;
            onBlur(textbox);
            WIR.EventUtils.addEventListener(textbox,'blur',function(evt,target){onBlur(textbox);});
            WIR.EventUtils.addEventListener(textbox,'focus',function(evt,target){onFocus(textbox);});
            WIR.EventUtils.addEventListener(submitButton,'click',function(evt,target){onSubmit(textbox);});
        }
    };
}();


//***
//* Check out the Javascript Documentation Wiki for details
//***

//XMLHttpRequest(JK)
if( window.XMLHttpRequest || window.ActiveXObject ){
  	if( window.ActiveXObject ){
		var lib = /MSIE 5/.test(navigator.userAgent) ? "Microsoft" : "Msxml2";
  		window.XMLHttpRequest = function(){	return new ActiveXObject(lib + ".XMLHTTP"); };
  	};
}

//String trim(JK)
String.prototype.trim = function () { return this.replace(/^\s*/, "").replace(/\s*$/, ""); }

//*** Custom Javascripts *** (JK)
/*
Function: $
	Returns the element(s)
	Shortcut for document.ElementById

Arguments:
	obj - the object to inspect.

Example:
	>$('myElement').style.display='none';  //same as document.getElementById('myElement).style.dispplay ='none';
	>$('myElement1','myElement2',myElement3').style.display='none'; //same as above for all elements
*/
function $() {
   var es = new Array();
   for (var i = 0; i < arguments.length; i++) {
      var e = arguments[i];
      if (typeof(e) == 'string') { e = document.getElementById(e); }
      if (arguments.length == 1) { return e; }
      es.push(e);
   }
   return es;
}

/*
Function: $type
	Returns the type of object that matches the element passed in.

Arguments:
	obj - the object to inspect.

Example:
	>var myString = 'hello';
	>$type(myString); //returns "string"

Returns:
	'element' - if obj is a DOM element node
	'textnode' - if obj is a DOM text node
	'whitespace' - if obj is a DOM whitespace node
	'arguments' - if obj is an arguments object
	'object' - if obj is an object
	'string' - if obj is a string
	'number' - if obj is a number
	'boolean' - if obj is a boolean
	'function' - if obj is a function
	'regexp' - if obj is a regular expression
	'class' - if obj is a Class. (created with new Class, or the extend of another class).
	'collection' - if obj is a native htmlelements collection, such as childNodes, getElementsByTagName .. etc.
	false - (boolean) if the object is not defined or none of the above.
*/
function $type(obj){
	if (!$defined(obj)) return false;
	if (obj.htmlElement) return 'element';
	var type = typeof obj;
	if (type == 'object' && obj.nodeName){
		switch(obj.nodeType){
			case 1: return 'element';
			case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
		}
	}
	if (type == 'object' || type == 'function'){
		switch(obj.constructor){
			case Array: return 'array';
			case RegExp: return 'regexp';
			case Class: return 'class';
		}
		if (typeof obj.length == 'number'){
			if (obj.item) return 'collection';
			if (obj.callee) return 'arguments';
		}
	}
	return type;
};

/*
Function: $random
	Returns a random number between two integers passed by arguments 

Arguments:
	min - (integer) minimum range of a random number
	max - (integer) maximum range of a random number

Example:
	>var num = $random(0,100); //returns a random number between 0-100
*/
function $random(min, max){
	return Math.floor(Math.random() * (max - min + 1) + min);
};

/*
Function: $time
	Returns a current time in milliseconds

Arguments:
	nothing

Example:
	>var time = $time(); //returns a time ex)1204311506409 
*/
function $time(){
	return new Date().getTime();
};

/*
Function: $clear
	clears timeout & interval of of the timer id that is passed by an argument 

Arguments:
	id - (pointer) id of the timer 

Example:
    >var myTimer = setTimer(SomeFunction,2000); //sets a timer to excute 'SomeFunction' in 2 sec
	>$clear(myTimer); //clears the 'myTimer' timer
*/
function $clear(timer){
	clearTimeout(timer);
	clearInterval(timer);
	return null;
};


//******(JK)
//Ajax
WIR.Ajax = function (url,option) {
	if($_RedirectUrl && $_RedirectUrl != "") {url = $_RedirectUrl + encodeURIComponent(url);}
	if (!url) return;
	var _method = option.method || 'post';	
	var _data = option.data || null;
	var _evalResponse = option.evalResponse || false;
	var _onComplete = option.onComplete || new Function();
	var _onFailure = option.onFailure || new Function();
	var _async = option.async || true;
     
	if (_method.toLowerCase() == 'get') {
		url = url + "?" +_data;	
		_data = null;	
	}
	var _request = 	new window.XMLHttpRequest;
	_request.onreadystatechange = _CheckStateChange;
	_request.open(_method, url, _async);
			
	function _CheckStateChange() {
		if (_request.readyState == 4) {
           if (_request.status == 200) {
			   var text = _request.responseText;
			   var xml = _request.responseXML;
			   if (_evalResponse) { eval('(' + text + ')'); }
			   _onComplete(text,xml);
           } else {
			   _onFailure(_request.status );
           }
       	} 
	}
	return {
		send: function() {
			_request.send(_data);
		}
	};	
}

//toQueryString
WIR.ToQueryString = function (source) {
	var qs = new Array();
	for(var property in source) {
		var value = source[property];
		var pqs = function(val) { qs.push([encodeURIComponent(property), encodeURIComponent(val)].join('=')); }
		if (typeof(value) == 'array') { value.each(pqs) }
		else { pqs(value) }
	}
	return qs.join('&');
}
//******


// designed to be used as a singleton object, so you probably shouldn't inherit from this guy
WIR.AJAX = function (){
    return {
        currentVisiblePopup: null,
        isPopupLocked: false,
        
        // Cross browser compatible creation of XmlHttpRequest object
        createRequest: function(){
            var request;

            // IE
            try{
	            request = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e){
	            try{
		            request = new ActiveXObject("Microsoft.XMLHTTP");
	            } 
	            catch(oc){
		            request = null;
	            }
            }
        	
            // Mozilla
            if(!request && typeof XMLHttpRequest != "undefined") {
	            request = new XMLHttpRequest();
            }
        	
            return request;
        },
        
        // Fires a callback, sending data to page, with the response handled by handler
        submitCallback: function(data, page, handler, lockPopups){
            var request = this.createRequest();
            if(request){
	            //if(typeof ajaxRelativePrefix != 'undefined'){
		            // prefix page with relative path prefix var that was inserted by MatrixPage
		            //page = ajaxRelativePrefix + page;

		            // prepare request
		            request.open('POST', page, true);
		            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		            // when the request is answered, relayResponse() will be called
		            request.onreadystatechange = function(){ WIR.AJAX.relayResponse(request, handler); };

                    WIR.AJAX.isPopupLocked = lockPopups;
		            // fire off the request
		            request.send(data);
	            //}
	            //else{
		            // relative path var not found, cannot correctly set path to AJAX page
		            //handler(false, 'Relative prefix not found (be sure to use Page.HasAjax).');
	            //}	
            }
            else{
	            // request object wasn't instantiated
	            handler(false, 'Unable to create request object.');
            }
        },
        
        // Passes response data from a callback to the handler function
        relayResponse: function (request, handler){
            var responseText;
            var index;
            if(request.readyState == 4){
                try{
	                if(request.status == 200){
		                responseText = request.responseText;
            			
		                // ugly hack for international pages adding extra HTML
		                index = responseText.indexOf("<!DOCTYPE");
		                if(index != -1){
			                responseText = responseText.substring(0, index);
		                }
            			
		                // success, give response text to handler function
		                WIR.AJAX.isPopupLocked = false;
		                handler(true, responseText);
	                }
	                else{
		                // page returned error code (such as 404)
		                WIR.AJAX.isPopupLocked = false;
		                handler(false, 'Ajax page returned error code ' + request.status + '.');
	                }
	            }
	            catch(e){
	                // i hate this, but for now we need to eat the error.  we don't have a sure way of tracking errors
	            }
            }
        },
        hidePopups: function () {
            if (WIR.AJAX.currentVisiblePopup && !WIR.AJAX.isPopupLocked) {
	            WIR.AJAX.currentVisiblePopup.hide();
	        }
	        if (window.hideCurrentPopup) {   // this will close windows in the other popup management system
                hideCurrentPopup();
            }
	    }
    };
} ();

// the base object of all AJAX widgets.  These will most likely be comprised of DIVs
WIR.AJAX.Popup = function ()
{
    function onDocumentClick (evt,target){
        var shadowBox;
        if (!WIR.AJAX.currentVisiblePopup.isModal){
            if(target){//if i don't know the target then I can't determine anything
                shadowBox = $get('shadowAJAX');
                if(!shadowBox || !shadowBox.lastAnchor || shadowBox.lastAnchor.id != target.id){
                    WIR.AJAX.hidePopups();
                }
            }
        }
    }
	// find X coordinate of an element:  anchor - the element we are trying to position relative to, element - the element we are positioning
	function findX(anchor, element, halign)	{
	    // we need to be really intelligent about what we spit back out.
		var curleft = 0;
		var leftcenter = anchor.offsetWidth / 3;
		var rightcenter = anchor.offsetWidth - leftcenter;
		if(anchor.offsetParent){
			while(anchor.offsetParent){
				curleft += anchor.offsetLeft;
				anchor = anchor.offsetParent;
			}
		}
		else if(anchor.x){
			curleft += anchor.x;
		}
		
		if(halign && halign === 'flush'){
		    if (curleft > WIR.Window.getWidth() / 2) {
		        // we are on the right side of the window		    
		        return (curleft + (leftcenter * 3)) - element.scrollWidth;
		    } else {
		    	// we are on the left side of the window
		    	return curleft;
		    }
		}
		else {
		    if (curleft > WIR.Window.getWidth() / 2) {
		        // we are on the right side of the window
		        return (curleft + rightcenter) - (element.scrollWidth);
		    }
		    else {
		        // we are on the left side of the window
		        return curleft + leftcenter;
		    }
	    }
	}

	// find Y coordinate of an element
	function findY(anchor, element)	{
		var curtop = 0;
		if(anchor.offsetParent){
			while(anchor.offsetParent){
				curtop += anchor.offsetTop;
				anchor = anchor.offsetParent;
			}
		}
		else if(anchor.y){
			curtop += anchor.y;
		}
		
		// using a hard number feels like a hack, but it should serve us well
		// I used to use anchor.offsetHeight, but it counts padding and so is inconsistent
		if (!WIR.Window.ie) {
		    if (curtop + 20 + element.offsetHeight > WIR.Window.getScrollHeight()) {
		        return WIR.Window.getScrollHeight() - element.offsetHeight;
		    }
		    else {
		        return curtop + 20;
		    }
		}
		else {
		    if (curtop + 15 + element.offsetHeight > WIR.Window.getScrollHeight()) {
		        return WIR.Window.getScrollHeight() - element.offsetHeight;
		    }
		    else {
		        return curtop + 15;
		    }
		}
	}
	
    return {
        containerElm: null,
        parentContainer: null,
        isModal: false,
        halign: null,
    
        initialize: function(container, options){
            // do some initialization here
            this.containerElm = container;
            if (container) {
                this.parentContainer = container.parentNode;
            }
            if(options){
                this.isModal = options.isModal;
                this.halign = options.halign;
            }
        },
    
        // options is an optional variable where you can stuff any desired parameters for onShow
        show: function(anchor, options, anchorOffsetX, anchorOffsetY, message){
            // we have to get our shadow
            //alert('hellob');
            var shadowBox = $get('shadowAJAX');
            var diff,i;
            if (!shadowBox) {
                shadowBox = document.createElement("div");
                shadowBox.className = 'wirStyle shadowing';
                shadowBox.style.textAlign = 'left';
                shadowBox.id = 'shadowAJAX';
                WIR.EventUtils.addEventListener(shadowBox,'click',function(evt,target){evt.cancelBubble = true;});
                
                document.body.appendChild(shadowBox);
            }
            
            if(message != null)
            {
                if($get('pMessage') != null)
                {
                    $get('pMessage').innerHTML = message;
                }
            }
            
            if (this.containerElm  && !WIR.AJAX.isPopupLocked) {
                // now we need to hide all the other windows
                WIR.AJAX.hidePopups();
                if (this.isModal){
                    var modal = $get('modal_background');
                    if(!modal){
                        modal = document.createElement("div");
                        modal.id = 'modal_background';
                        document.body.appendChild(modal);
                    }
                    this.containerElm.style.left = '0px';
                    modal.style.width = WIR.Window.getScrollWidth() + 'px';
                    modal.style.height = WIR.Window.getScrollHeight() + 'px';
                    modal.style.left = '0px';
                    
                    // ugly, but, this is how we have to reposition it to be seen
                    shadowBox.x = ((WIR.Window.getWidth()/2) - (this.containerElm.scrollWidth/2));
                    shadowBox.y = ((WIR.Window.getHeight()/2) - (this.containerElm.scrollHeight/2));
      
                    shadowBox.style.left = shadowBox.x + 'px';
                    shadowBox.style.top = shadowBox.y + 'px';
                    if(WIR.Window.ie7 || WIR.Window.gecko || WIR.Window.khtml){
                        shadowBox.style.position = 'fixed';
                    }
                }else if (anchor) {
                    // if we have an anchor, then we can position based on it
                    //  otherwise, just use our current position
                    anchor.blur();
                    this.containerElm.style.left = '0px';
                    shadowBox.x = findX(anchor, this.containerElm, this.halign);
                    shadowBox.y = findY(anchor, this.containerElm);
                    
                    if(arguments.length >= 4 && anchorOffsetX != null && anchorOffsetY != null)
                    {
                        shadowBox.x += anchorOffsetX;
                        shadowBox.y += anchorOffsetY;
                    }
                    
                    shadowBox.style.left = shadowBox.x + 'px';
                    shadowBox.style.top = shadowBox.y + 'px';
                    shadowBox.lastAnchor = anchor;
                    shadowBox.style.position = 'absolute';
                }
                
                this.onShow(options);
                shadowBox.appendChild(this.containerElm);
                
                if (!WIR.Window.ie) {  // we are not in IE
                    shadowBox.style.height = (this.containerElm.scrollHeight + 1) + 'px';
                    shadowBox.style.width = (this.containerElm.scrollWidth + 4) + 'px';
                }
                else {  // we are in IE
                    shadowBox.style.height = (this.containerElm.scrollHeight + 6) + 'px';
                    shadowBox.style.width = (this.containerElm.scrollWidth + 6) + 'px';
                }
                //this.containerElm.style.display = 'block';
                this.containerElm.style.visibility = 'visible';
                //this.containerElm.style.zIndex = '100000';
                //this.containerElm.height = this.containerElm.style.height + 'px';
                //$get('ctl00_WirMaster_theMap1').style.height = '1px';
                
                
                shadowBox.style.visibility = 'visible';
                WIR.AJAX.currentVisiblePopup = this;
                WIR.Window.scrollDown((shadowBox.offsetHeight + shadowBox.y - WIR.Window.getScrollTop()) - WIR.Window.getHeight(), 8);
                WIR.EventUtils.addEventListener(document,'click',onDocumentClick);
            }
        },
        
        onShow: function(anchor, options) {
            // this function is designed to be overridden  (technically an onBeforeShow)
            // so if you have any special processing that happens when your div is opened, then
            // change onShow so that it points to a different/custom function
        },
        
        hide: function() {
            var shadowBox = $get('shadowAJAX');
            if (shadowBox) {
                shadowBox.style.visibility = 'hidden';
                shadowBox.height='1px';
 
                this.containerElm.style.visibility = 'hidden';
                this.containerElm.style.left = '-2000px';
                //this.containerElm.height = '1px';
                
                this.onHide();

            }
            
            if(this.isModal){
	            var modal = $get('modal_background');
	            if(modal){
	                modal.style.left = '-3000px';
	            }
	        }
            
        	if (!shadowBox && this.containerElm.style.visibility != 'hidden') 
        	{
	            this.containerElm.style.visibility = 'hidden';
	            this.onHide();
	            this.parentContainer.appendChild(this.containerElm);
	        }
	        
	        WIR.EventUtils.removeEventListener(document,'click',onDocumentClick);
        },
        
        onHide: function() {
            // this function is designed to be overridden  (technically an onAfterShow)
            // so if you have any special processing that happens when your div is closed, then
            // change onHide so that it points to a different/custom function
        }
        
        // TODO: have a max height and width variable to check against and use that to determine scrolling
        // TODO: if the window resizes, then reposition yourself (this may require us to hold onto the anchor's coordinates)
    };
} ();



// Provides base functions for using AJAX
// Cross browser compatible creation of XmlHttpRequest object
function createRequest()
{
	return request = new window.XMLHttpRequest();
}

// Fires a callback, sending data to page, with the response handled by handler
function submitCallback(data, page, handler, showMsg)
{
    if(showMsg){
        if(document.title && document.title.indexOf('WAT') > -1 && document.title.indexOf('RunDeveloper') > -1){
            alert('You are using the old submitCallback method.  Please update your AJAX call to use WIR.AJAX.submitCallback.  Callback sent to ' + page);
        }
    }
    
	var request = createRequest();
	if(request)
	{
		if(typeof ajaxRelativePrefix != 'undefined')
		{
			// prefix page with relative path prefix var that was inserted by MatrixPage
			page = ajaxRelativePrefix + page;

			// prepare request
			request.open('POST', page, true);
			request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

			// when the request is answered, relayResponse() will be called
			request.onreadystatechange = function(){ relayResponse(request, handler); };

			// fire off the request
			request.send(data);
		}
		else
		{
			// relative path var not found, cannot correctly set path to AJAX page
			handler(false, 'Relative prefix not found (be sure to use Page.HasAjax).');
		}	
	}
	else
	{
		// request object wasn't instantiated
		handler(false, 'Unable to create request object.');
	}
}

// Passes response data from a callback to the handler function
function relayResponse(request, handler)
{
    var responseText;
    var index;
	if(request.readyState == 4)
	{
		if(request.status == 200){
			responseText = request.responseText;
			
			// ugly hack for international pages adding extra HTML
			index = responseText.indexOf("<!DOCTYPE");
			if(index != -1)
			{
				responseText = responseText.substring(0, index);
			}
			
			// success, give response text to handler function
			handler(true, responseText);
		}
		else
		{
			// page returned error code (such as 404)
			handler(false, 'Ajax page returned error code ' + request.status + '.');
		}
	}
}


if (typeof(Sys) !== "undefined")
  Sys.Application.notifyScriptLoaded();	
