﻿
var CB = function(){
	return {
	    Tally: function(object, method, task, numthings){
	        var data = 'tallyObject=' + object + '&' +
				'tallyMethod=' + method + '&' +
				'tallyTask=' + task;
				
            if(numthings){
                data += '&tallyNumThings=' + numthings;
            }
        
            var page = 'tally.aspx';	
	        CB.AJAX.submitCallback(data,page,function(){});
        },
        
        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);
          
            CB.AJAX.submitCallback(paramValues, 'FormToEmail.aspx', callbackFunction);
        },
        
        IsValidEmail: function(emails, allowMultipleEmails, giveMsg, emailInputField){
	        var emailRegEx = new RegExp("^([-A-Za-z0-9._\'\&+])+@[-A-Za-z0-9._\'+]+[.][A-Za-z]{2,}$", "g" );
            var emailCSV = new RegExp(",|,,|;|\r|\n|,\r", "g" );
	        var emailToServer = "";
	        var standardizedEmailCSV, arEmails, email, i;

	        //this method relies on 2 crucial variables that should be set in the page. This is the regex code.
	        if (typeof emailRegEx == "undefined" || typeof emailCSV == "undefined" || emailRegEx === null || emailCSV === null){
		        alert('Error: Email validator is not available at the moment or is corrupted. Please contact technology');
		        return false;
	        }
    	    
	        if(allowMultipleEmails === null){
	            allowMultipleEmails = false;
	        }
    	        
	        if(giveMsg === null){
	            giveMsg = true; 
	        }   

	        if(emails.length > 0){
		        //see if the passed in string is a csv
		        //we'll also allow semi-colon seperated strings
		        if((emails.indexOf(",") > 0 || emails.indexOf(";") > 0) && allowMultipleEmails === true ){
			        //email seems to be comma/semi-comma seperated.
        			
			        //make sure we remove trails
			        emails = emails.emailtrim();
        			
			        //Do a string replacement to make sure CSV is in proper form
			        standardizedEmailCSV = emails.replace(emailCSV, ","); 
			        arEmails = standardizedEmailCSV.split(",");
                    email = "";
        			
			        for(i=0; i< arEmails.length ; i++){
				        email = arEmails[i];
        				
				        //make sure we remove trails
				        email = email.emailtrim();

				        if(email === "" || email === ' '){
					        //skip this round
					        continue;
				        }
				        if(email.match(emailRegEx) === null){
					        //invalid email, bail out
					        //if we have this to true, this will give us the wrong email for the user
        					
					        if(giveMsg === true){
							        alert('Please correct the following invalid email address, and try again.\n' + email);
							}
					        return false;
				        }
        				
				        //reconstruct emails
				        if (emailToServer !== ""){
					        emailToServer += ";";
					    }	
				        emailToServer += email;
			        }
        			
		        }else{
                    //Not CSV
                    //make sure we remove trails
			        emails = emails.emailtrim();
    					
                    bool = emails.match(emailRegEx); 	
			        if (bool === null){
				        if(giveMsg){
					        alert('Your email address is invalid. Please correct it and try again.');
					    }	
				        return false;
			        }else{
				        emailToServer = emails;
			        }
		        }	
	        }else{
		        //should be empty string here
		        emailToServer = emails;
	        }
        	
	        //if they get to this point, it should be TRUE
	        if (typeof emailInputField != "undefined"){
		        emailInputField.value = emailToServer;
	        }
        	
	        return true;
        },
    
        OtherFunction : function(){
            return '0';
        },
    
	    object: function (o) {
	        function F(){}
	        F.prototype = o;
	        return new F();
	    },
    	
	    // convenience function for grabbing an element
	    e: function (id){
		    return document.getElementById(id);
	    }
	};
}();

String.prototype.emailtrim = function(){
 // skip leading and trailing whitespace
 // and return everything in between
  var x=this;
  x=x.replace(/^\s*(.*)/, "$1");
  x=x.replace(/(.*?)\s*$/, "$1");
  x=x.replace(/(.*?),*$/, "$1");
  return x;
};

/*
    The CB.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.
*/
CB.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 (CB.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 (CB.Window.khtml){
		        return window.innerHeight;
		    }else if (window.opera){
		        return document.body.clientHeight;
		    }else if (CB.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(CB.Window.ie) {
		        return Math.max(Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth), document.body.scrollWidth);
		    }else if (CB.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 (CB.Window.ie) {
		        return Math.max(Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight), Math.max(document.body.offsetHeight, document.body.scrollHeight));
		    }else if (CB.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: CB.getWidth(), y: CB.getHeight()},
			    scrollSize: {x: CB.getScrollWidth(), y: CB.getScrollHeight()},
			    scroll: {x: CB.getScrollLeft(), y: CB.getScrollTop()}
		    };
        },
        scrollDown: function(distance, rate) {
            for (i = 0; i < distance; i += rate){
                setScrollTop(CB.Window.getScrollTop() + rate);
            }
	    }
    };
}();
// taken from Mootools to help sniff out the browser
// ie = ie; gecko = firefox/mozilla; khtml = ????
if (window.ActiveXObject){
    CB.Window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
    CB.Window.ie7 = (navigator.userAgent.indexOf('MSIE 7') > -1);
    CB.Window.ie6 = (navigator.userAgent.indexOf('MSIE 6') > -1);
} else if (document.childNodes && !document.all && !navigator.taintEnabled){
    CB.Window.khtml = true;
} else if (document.getBoxObjectFor !== null){
    CB.Window.gecko = true;
}

CB.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);
        }
    };
}();

CB.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);
            CB.EventUtils.addEventListener(textbox,'blur',function(evt,target){onBlur(textbox);});
            CB.EventUtils.addEventListener(textbox,'focus',function(evt,target){onFocus(textbox);});
            CB.EventUtils.addEventListener(submitButton,'click',function(evt,target){onSubmit(textbox);});
        }
    };
}();

CB.Textbox = function(){
    function handleKeyPress(evt, target){
        if ((evt.which && evt.which == 13) || (evt.keyCode && evt.keyCode == 13)){
		    if(target.cbEnterPressAction){
		        target.cbEnterPressAction();
		    }
	    }
    }
    
    return {
        setupTextbox:function(textbox,enterPressAction){
            textbox.cbEnterPressAction = enterPressAction;
            CB.EventUtils.addEventListener(textbox,'keydown', handleKeyPress);
        }
    };
}();
