﻿/*****************************************************************************************/

/****   Splat Core Common Cross Browser Functions   *****/

/*****************************************************************************************/

/**************  Helper Functions*************************************/

function $(id) { return document.getElementById(id); }


/*********************************************************************/



/**************  Event Functions*************************************/

function $button(ev) { return ev.button || ev.which; }
function $target(ev) { return ev.target || ev.srcElement; }
function $event(ev) { return ev = ev || window.event; }

function $create(tag, id, cls, htm)
{
    var elem = document.createElement(tag);
    if (id) elem.id = id;
    if (cls) elem.className = cls;
    if (htm) elem.innerHTML = htm;
    return elem;
}


// checks for the enterKey press and calls the function when Enter key is pressed
function $checkEnterKey(ev, functionToCall)
{
    if ($getCharCode(ev) == 13)
    {
        eval(functionToCall);
        return false;
    }
}


// returns the keyCode of key pressed
function $getCharCode(e)
{
    var characterCode;   //literal character code will be stored in this variable

    if (window.event)
        characterCode = window.event.keyCode;     //IE
    else
        characterCode = e.which;    //firefox

    return characterCode;
}

// cancel event bubbling
function $cancelBubble(ev) 
{ 
    if (ev.stopPropagation)
        ev.stopPropagation();
    else    
        ev.cancelBubble = true;
}    

// multi utility function : to be used for textboxes where we want to detect enter/escape key and call funtions accordingly
function $keyAction(ev, onEnter, onEscape)
{
    var keyCode = $getCharCode(ev);
    switch (keyCode)
    {
        case 13:            // Enter Key
            eval(onEnter);
            break;
        case 27:            // Escape Key
            eval(onEscape);
            break;
    }
}

/*********************************************************************/


/**************  Mouse Event Functions********************************/

function $getMouseXY(eventObject)
{
    if (eventObject.pageX || eventObject.pageY)
    {
        return { x: eventObject.pageX, y: eventObject.pageY };
    }
    else
    {
        return { x: eventObject.clientX + document.body.scrollLeft - document.body.clientLeft,
            y: eventObject.clientY + document.body.scrollTop - document.body.clientTop
        };
    }
}

/*********************************************************************/

/**************  Windows Functions ******************************/

function $clearInterval(intervalId)
{
    window.clearInterval(carStepIntervalID);
    intervalId = null;
}

function $setInterval(intervalId, functionToCall, intervalTime)
{
    intervalId = window.setInterval(functionToCall, intervalTime);
}

function $getWindowDim()
{
    var width = height = 0;


    if (typeof (window.innerWidth) == 'number')
    {
        //Non-IE
        width = window.innerWidth;
        height = window.innerHeight;
    }

    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    {
        //IE 6+ in 'standards compliant mode'
        width = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight;
    }

    else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    {
        //IE 4 compatible
        width = document.body.clientWidth;
        height = document.body.clientHeight;
    }

    return { width: width, height: height };

}


function $navigateTo(location, postData)
{
    if (postData)
        location += "?" + postData;

    window.location = location;

}


/*********************************************************************/


/**************  String Functions ******************************/

// Used to set text into a span/div
function $setText(target, text)
{

    if (target.innerText != null)
        target.innerText = text;
    else
        target.textContent = text;
}

// Used to get text from a span/div
function $getText(target)
{
    if (target.innerText != null)
        return target.innerText;
    else
        return target.textContent;
}

// remove whiteText from head and tail
function $trim(string)
{
    if (string)
        return string.replace(/^\s+|\s+$/g, "");
    else
        return string;
}

function $encodeText(text)
{
    if (text != null && text != "")
    {
        text = escape(text);
        text = text.replace(/\+/g, "%2B");
        text = text.replace(/ /g, "%20");
        text = text.replace(/\//g, "%2F");
        text = text.replace(/@/g, "%40");
    }

    return text;
}

function $decodeText(text)
{
    if (text != null && text != "")
    {
        text = text.replace(/%20/g, " ");
        text = text.replace(/\+/g, " ");
        text = text.replace(/%2B/g, "+");
        text = text.replace(/%2F/g, "/");
        text = text.replace(/%40/g, "@");
        text = unescape(text);
    }

    return text;
}

function $xmlDecode(text)
{
    if (text != null && text != "")
    {
        text = text.replace(/&amp;/g, "&");
        text = text.replace(/&gt;/g, ">");
        text = text.replace(/&lt;/g, "<");
        text = text.replace(/&quot;/g, "\"");
        text = text.replace(/&apos;/g, "'");
    }
    
    return text;
}

function xmlEncode(text)
{
    if (text != null && text != "")
    {
        text = text.replace(/&(?!(amp|lt|gt|quot|apos);)/g, "&amp;");
        text = text.replace(/>/g, "&gt;");
        text = text.replace(/</g, "&lt;");
        text = text.replace(/\"/g, "&quot;");
        text = text.replace(/'/g, "&apos;");
    }
    
    return text;
}

/*********************************************************************/


/**************  validation functions  ******************************/
function $validateEmail(email)
{
    if (email)
    {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        return reg.test(email);
    }

    return false;
}



// validates date in format dd\mm\yyyy
function $validateDate(strValue)
{

    var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/

    //check to see if in correct format
    if (!objRegExp.test(strValue))
        return false; //doesn't match pattern, bad date
    else
    {
        var strSeparator = strValue.substring(2, 3)
        var arrayDate = strValue.split(strSeparator);
        //create a lookup for months not equal to Feb.
        var arrayLookup = { '01': 31, '03': 31,
            '04': 30, '05': 31,
            '06': 30, '07': 31,
            '08': 31, '09': 30,
            '10': 31, '11': 30, '12': 31
        }
        var intDay = parseInt(arrayDate[0], 10);

        //check if month value and day value agree
        if (arrayLookup[arrayDate[1]] != null)
        {
            if (intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
                return true; //found in lookup table, good date
        }

        //check for February (bugfix 20050322)
        //bugfix  for parseInt kevin
        //bugfix  biss year  O.Jp Voutat
        var intMonth = parseInt(arrayDate[1], 10);
        if (intMonth == 2)
        {
            var intYear = parseInt(arrayDate[2]);
            if (intDay > 0 && intDay < 29)
            {
                return true;
            }
            else if (intDay == 29)
            {
                if ((intYear % 4 == 0) && (intYear % 100 != 0) ||
             (intYear % 400 == 0))
                {
                    // year div by 4 and ((not div by 100) or div by 400) ->ok
                    return true;
                }
            }
        }
    }
    return false; //any other values, bad date
}

/*********************************************************************/




/************** Display functions  ******************************/

function $toggleDisplay(obj)
{
    if (obj.style.display != "none")
        $display(obj, false)
    else
        $display(obj, true)
}

function $display(obj, flag)
{
    if (typeof (obj ) !== "object")
        var objStyle = document.getElementById(obj).style;
    else
        objStyle = obj.style;

    if (objStyle)
    {
        if (flag)
        {
            objStyle.display = "";
            objStyle.visibility = "visible";
        }
        else
        {
            objStyle.display = "none";
            objStyle.visibility = "hidden";
        }
    }
}


/*********************************************************************/


/************** HTML Element functions  ******************************/

// returns value of the selected radio option from group
function $getSelectedRadioValue(groupId)
{
    var radios = document.getElementsByName(groupId);
    var value = null;

    for (var i = 0; i < radios.length; i++)
    {
        if (radios[i].checked)
        {
            value = radios[i].value;
            break;
        }
    }

    return value;
}

// flips the radio checked property
function $toggleRadios(name, status)
{
    var radios = document.getElementsByName(name);

    for (var i = 0; i < radios.length; i++)
    {
        radios[i].disabled = !status;
    }
}

// selects all checkBoxes on the page
function $selectAllCheckboxes()
{
    var checkBoxes = document.getElementsByTagName("input");

    for (var i = 0; i < checkBoxes.length; i++)
    {
        checkBoxes[i].checked = "checked";
    }
}

// deselects all checkboxes
function $deselectAllCheckboxes()
{
    var checkBoxes = document.getElementsByTagName("input");

    for (var i = 0; i < checkBoxes.length; i++)
    {
        checkBoxes[i].checked = false;
    }

}

/*********************************************************************/



/******************** Debug functions  ******************************/

function $debugMsg(debugMSG)
{
    $insertDebugDiv();
    $setText($("debugSpan"), debugMSG);
}

function $debugMsgAppend(debugMsg)
{
 $insertDebugDiv();
 $setText($("debugSpan"), $getText($("debugSpan")) + "    " + debugMsg);
}

function $insertDebugDiv()
{
    var debugDiv = $("debugDiv");
    if (debugDiv)
        return;
    
    debugDiv = $create("div", "debugDiv","","");
    
    var debugSpan = $create("span", "debugSpan","","S4K Debug Info");
    debugDiv.appendChild(debugSpan);
    
    var debugStyle = debugDiv.style;
    
    debugStyle.cssText = "color:white;background-color:#d18034; position:fixed; top:0px; left:40%; padding:5px; border:solid 1px black;";

    document.body.appendChild(debugDiv);

}

/*********************************************************************/


/******************** Position functions  *******************************/

function $getAbsPos(elt, which)
{
    iPos = 0;
    while (elt != null)
    {
        iPos += elt["offset" + which];
        elt = elt.offsetParent;
    }
    return iPos;
}

function $getAbsX(elt) { return (elt.x) ? elt.x : $getAbsPos(elt, "Left"); }
function $getAbsY(elt) { return (elt.y) ? elt.y : $getAbsPos(elt, "Top"); }


/*********************************************************************/


/********************  Fade functions  *******************************/


// ASC: copied from http://www.sean.co.uk/a/webdesign/javascriptdelay.shtm
function $pauseComp(timeLag)
{
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }

    while (curDate - date < timeLag);
}

 
function $setOpacity(obj, opacity)
{
    var objStyle = obj.style;

        objStyle.opacity = (opacity / 100);
        objStyle.MozOpacity = (opacity / 100);
        objStyle.KhtmlOpacity = (opacity / 100);
        objStyle.filter = 'alpha(opacity=' + opacity + ')';
}

function $fadeOutObject(obj, speed, step)
{

    $continueFadeObj(obj, 100, speed, step);

}


function $continueFadeObj(obj, opacity, speed, step)
{
    opacity = opacity - step;

    if (opacity <= 0)
    {
        $setOpacity(obj, 0);
    }
        
    if (opacity > 0)
    {
        $setOpacity(obj, opacity);
        setTimeout(function() { $continueFadeObj(obj, opacity, speed, step) }, speed);
    }
    else
        return;
    

    
}


/*********************************************************************/


/******************** DateTime functions  *******************************/
/*
* Date Format 1.2.2
* (c) 2007-2008 Steven Levithan <stevenlevithan.com>
* MIT license
* Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/
var dateFormat = function()
{
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function(val, len)
		{
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function(date, mask, utc)
    {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date))
        {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date();
        if (isNaN(date)) throw new SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:")
        {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function($0)
        {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function(mask, utc)
{
    return dateFormat(this, mask, utc);
};


/*********************************************************************/


/******************** Misc functions  *******************************/
// from mooTools 1.2
function $random(min, max)
{
	return Math.floor(Math.random() * (max - min + 1) + min);
}

function $exec(text){
	if (!text) return text;
	if (window.execScript){
		window.execScript(text);
	} else {
		var script = document.createElement('script');
		script.setAttribute('type', 'text/javascript');
		script.text = text;
		document.head.appendChild(script);
		document.head.removeChild(script);
	}
	return text;
}

function $isBody(element)
{
	return (/^(?:body|html)$/i).test(element.tagName);
}


//-------------------XML Functions-----------------------------------//
function createXmlObject(xmlResponse)
{
    var doc = null;
    var result = false;
    var browserType = "";
    
    // code for IE
    if (window.ActiveXObject)
    {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async = "false";
        doc.loadXML(xmlResponse);
        
        var err = doc.parseError;

        if (err.errorCode == 0)
            result = true;
            
        browserType = "ie";
    }
    // code for Mozilla, Firefox, Opera, etc.
    else
    {
        var parser = new DOMParser();
        doc = parser.parseFromString(xmlResponse,"text/xml");
        
        if (doc.documentElement.nodeName != "parsererror")
            result = true;
            
        browserType = "other";
    }
    
    return { xmlDoc: doc, browser: browserType, validXml: result };
}

function xmlDecode(text)
{
    if (text != null && text != "")
    {
        text = text.replace(/&amp;/g, "&");
        text = text.replace(/&gt;/g, ">");
        text = text.replace(/&lt;/g, "<");
        text = text.replace(/&quot;/g, "\"");
        text = text.replace(/&apos;/g, "'");
    }
    
    return text;
}

function xmlEncode(text)
{
    if (text != null && text != "")
    {
        text = text.replace(/&/g, "&amp;");
        text = text.replace(/>/g, "&gt;");
        text = text.replace(/</g, "&lt;");
        text = text.replace(/\"/g, "&quot;");
        text = text.replace(/'/g, "&apos;");
    }
    
    return text;
}

// gets the node text
function getNodeText(node, browserType)
{
    var nodeText = "";
    if(node)
    {
        if (browserType == "ie")
            nodeText = node.text;
        else
            nodeText = node.textContent;
    }        
    return nodeText;
}

function getInnerXml(node, browserType)
{
    var xml = "";
    
    if (browserType == "ie")
       xml = node.xml;    
    else
        xml = new XMLSerializer().serializeToString(node);
        
    return xml;
}


/*********************************************************************/


