/**************************************************************************  
 *  Shortcuts.com
 *  (c) 2004-2009 Patrick Flannery
 *
 *  Common and generic objects and utility function used throughout the site. 
 *
 ****************************************************************************/

// Global AJAX obj used
var myAjax;

// Character Sets
var CS_NUMERIC                  = "0123456789";
var CS_ALPHABETIC               = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var CS_ALPHANUMERIC             = CS_NUMERIC + CS_ALPHABETIC;
var CS_TEXTSEARCH               = CS_ALPHANUMERIC + " $./-,'";
var CS_NAME                     = CS_ALPHANUMERIC + "-' ,.";

//////////////////////////////////////////////////
// trim()
//
//  - Trims leading and trailing whitespace.
//
//  Input: string to trim
//  Output: string minus leading/trailing whitespace
/////////////////////////////////////////////////
function trim(var_string)
{
    var_string=var_string.replace(/^\s+/, "");  // takes care of leading spaces
    var_string=var_string.replace(/\s+$/, ""); // removes trailing spaces

    return var_string;
}

//////////////////////////////////////////////////
// check_len()
//
//  - Checks that variable length exceeded min limit.
//
//  Input: string to check, length minimum
//  Output: True/False
/////////////////////////////////////////////////
function check_len(var_string, minimum)
{
    return (var_string.length > minimum)
}

//////////////////////////////////////////////////
// check_exact_len()
//
//  - Checks if variable is exactly the size of
//    the limit.
//
//  Input: string to check, length limit
//  Output: True/False
/////////////////////////////////////////////////
function check_exact_len(var_string, limit)
{
    return (var_string.length == limit)
}

//////////////////////////////////////////////////
// trim_body()
//
//  - Removes any character existing in the passed
//    character set
//
//  Input: var_string, charset
//  Output: string with characters removed
/////////////////////////////////////////////////
function trim_body(var_string, charset)
{
    var new_string = "";
    for(i=0; i < var_string.length; i++)
    {
        var var_char = var_string.charAt(i);
        if (charset.indexOf(var_char) == -1)
        {
            new_string += var_char;
        }
    }
    return new_string;
}

//////////////////////////////////////////////////
// string_match()
//
//  - Checks two strings match (case sensitive)
//
//  Input: string1, string2
//  Output: True/False
/////////////////////////////////////////////////
function string_match(string1, string2)
{
    return (string1 == string2);
}

//////////////////////////////////////////////////
// getCookieVal()
//
//  - Retrieves the value of a cookie, given its name
//
//  Input: name of the desired cookie
//  Output: string value of the cookie or undefined
/////////////////////////////////////////////////
    function getCookieVal(cname) {
        var cval;
        var allCookies = document.cookie;
        var pos = allCookies.indexOf(cname);
        if (pos != -1) {
            if ((pos + cname.length == allCookies.length) || (allCookies.charAt(pos + cname.length) == ';')) {
                return true;
            } else {  // this cookie has an "=value"
                var start = pos + cname.length + 1;
                var end = allCookies.indexOf(";", start);
                if (end == -1) {end = allCookies.length;}
                cval = allCookies.substring(start, end);
            }
        }
        return cval;
    }
    
//////////////////////////////////////////////////
// setCookieVal()
//
//  - Sets a cookie with the name-value pair provided
//
//  Input: name of the desired cookie, value to store, expiration
/////////////////////////////////////////////////
function setCookieVal(name, value, expireDays) 
{
    var expDate=new Date();
    expDate.setDate(expDate.getDate() + expireDays);
    document.cookie = name + "=" + escape(value)+ "; expires=" + expDate.toGMTString() + "; path=/";
}

        
//////////////////////////////////////////////////
// setSessionCookie()
//
//  - Sets a cookie with the name-value pair provided
//
//  Input: name of the desired cookie, value to store, expiration
/////////////////////////////////////////////////
function setSessionCookie(name, value) 
{
    document.cookie = name + "=" + escape(value)+ "; path=/";
}

//////////////////////////////////////////////////
// removeCookieVal()
//
//  - Sets a cookie expiration date to yesterday
//
//  Input: Name of cookie to remove
/////////////////////////////////////////////////
function removeCookieVal(name) 
{
    var expDate=new Date();
    setCookieVal(name, "", -1);
}    

//////////////////////////////////////////////////
// filterString()
// - HTML encodes potantially malicious characters
//
//  Input: input string from user
//  Output: string value with characters HTML-encoded
/////////////////////////////////////////////////
function filterString(input)
{   
    var strInput = new String(input);
    strInput = replaceAll(strInput, "&", "&amp;");
    strInput = replaceAll(strInput,"<", "&lt;");
    strInput = replaceAll(strInput,">", "&gt;");
    strInput = replaceAll(strInput,"'", "&#39;");
    strInput = replaceAll(strInput,"\"", "&quot;");
    strInput = replaceAll(strInput,"%", "&#137;");
    return strInput;
}

//////////////////////////////////////////////////
// replaceAll()
// - Replace all occurrences
/////////////////////////////////////////////////
function replaceAll(stringToEdit, oldStr, newStr)
{
    var newstr1 = "";
    var suffix = "";
    while(stringToEdit.indexOf(oldStr) != -1)
    {
        var prefix = stringToEdit.substring(0, stringToEdit.indexOf(oldStr));
        suffix = stringToEdit.substring((stringToEdit.indexOf(oldStr) + oldStr.length), stringToEdit.length);
        stringToEdit = suffix;
        newstr1=  newstr1 + prefix + newStr;
    }
    newstr1 = newstr1 + suffix;
    if(newstr1 == "")
    {
        newstr1 = stringToEdit;
    }
    return newstr1;
}


//////////////////////////////////////////////////
// setFocus()
// - Takes the object passed in and sets focus on it.
//   This is mostly used for screenreaders to indicate
//   content has updated.
//
//  NOTE: Focus can only be set on a, area, button, 
//  input, object, select, and textarea elements. If
//  it is not one of these, we can set the tab index
//  to -1, and it will be able to receive focus in
//  Internet Explorer and Mozilla.  This may not work
//  in Safari.
//
//  Input: object upon which to set focus
/////////////////////////////////////////////////
function setFocus(obj)
{
    //Determine tag type
    var tagType = obj.nodeName;
    
    //if not any of the "focusable" tags, set tabIndex
    if (tagType != "A" &&
        tagType != "AREA" &&
        tagType != "BUTTON" &&
        tagType != "INPUT" &&
        tagType != "OBJECT" &&
        tagType != "SELECT" &&
        tagType != "TEXTAREA")
    {
        obj.tabIndex = -1;
    }
    
    obj.focus();        
}

//////////////////////////////////////////////////
// string_charset_check()
//
//  - Check that all characters of the passed
//    variable are limited to specific charset.
//
//  Input: string to check, predefined charset,
//         any additional/special characters as a string
//  Output: True/False
/////////////////////////////////////////////////
function string_charset_check(var_string, charset, special)
{
    charset += special;
    var_string = var_string.toLowerCase();
    for (i=0; i < var_string.length; i++)
    {
        if (!char_charset_check(var_string.charAt(i),charset))
            return false;
    }
    return true;
}

//////////////////////////////////////////////////
// char_charset_check()
//
//  - Check character against a string of characters
//    to see if the character exists in the string.
//
//  Input: char to check, character set
//  Output: True/False
/////////////////////////////////////////////////
function char_charset_check(var_char, charset)
{
    if(charset.indexOf(var_char) == -1)
        return false;
    else
        return true;
}    

/// METHODS TO FIND X AND Y COORDINATES OF AN OBJECT ///
/// * NOT HOME-GROWN *                               ///
function getXCoordinate(object)
{
    var left = 0;
    if(object.offsetParent)
    {
        while(true) 
        {
          left += object.offsetLeft;
          if(!object.offsetParent)
            break;
          object = object.offsetParent;
        }
    }
    else if(object.x)
        left += object.x;
        
    return left;
}

function getYCoordinate(object)
{
    var top = 0;
    if(object.offsetParent)
        while(true)
        {
          top += object.offsetTop;
          if(!object.offsetParent)
            break;
          object = object.offsetParent;
        }
    else if(object.y)
        top += object.y;
        
    return top;
}


//////////////////////////////////////////////////
// BrowserObj
//
//  A browser object class, which tries to determine the
//  client, version, and O/S types supported by Shortcuts.com
//
//  e.g.:   var browser = new BrowserObj();
//          browser.client ("IE","Firefox","Safari","unknown")
//          browser.version (For IE, major version number.  For FF and Safari, first two digits of version)
//          browser.os ("Windows","Mac")
/////////////////////////////////////////////////
function BrowserObj()
{
     var browserString = new String(navigator.userAgent);   
     
     // Internet Explorer versions
     if (browserString.indexOf("MSIE") != -1)
     {
        this.client = "IE";
        if (browserString.indexOf("MSIE 6") != -1)   
            this.version = 6;
        else  if (browserString.indexOf("MSIE 7") != -1)
            this.version = 7;
        else  if (browserString.indexOf("MSIE 8") != -1)
            this.version = 8;
        
     }
     
     // Firefox versions
     else if (browserString.indexOf("Firefox") != -1)
     {
        this.client = "Firefox";
        //get rest of string beginning with version number
        var tmp = browserString.substring(browserString.indexOf("Firefox/")+8,browserString.length);
        var pattern = /[\d+\.*]*/;
        tmp = new String(pattern.exec(tmp));
        var versionArray = tmp.split(".");
        //Now get first two elements of version
        if (versionArray.length > 1)
            this.version = versionArray[0] + "." + versionArray[1];
        else
            this.version = versionArray[0] + ".0";
     }
     
     // Safari versions
     else if (browserString.indexOf("Safari") != -1)
     {
        this.client = "Safari";
        //get rest of string beginning with version number
        var tmp = browserString.substring(browserString.indexOf("Version/")+8,browserString.length);
        //Now trim from whitespace back
        tmp = tmp.substring(0,tmp.indexOf(" "));
        var versionArray = tmp.split(".");
        //Now get first two elements of version
        if (versionArray.length > 1)
            this.version = versionArray[0] + "." + versionArray[1];
        else
            this.version = versionArray[0] + ".0";
     }
     
     //Else, not tracked
     else
     {
        this.client = "unknown";
        this.version = "unknown";    
     }
     
     
     //OS
     if (browserString.indexOf("Windows") != -1)
         this.os = "Windows";
     else if (browserString.indexOf("Macintosh") != -1)
         this.os = "Mac";
     else
        this.os = "unknown";
}

//////////////////////////////////////////////////////
//  showOrHideAllDropDowns()
//
//  In IE6, <select> items are window controls, and
//  consequently, have an infinite z-index value.  As such,
//  whenever we "disable" the background and pop something
//  over it (e.g. coupon icons, buzzworthy), the <select>
//  object still appears over it.  So, for IE6 users, 
//  whenever we do the background "disable", we will hide the
//  <select> elements, too.  Then, un-hide them when done.
//////////////////////////////////////////////////////
function showOrHideAllDropDowns(newState) 
{
        var elements = document.documentElement.getElementsByTagName('select');
     
        for (var i=0; i<elements.length; i++) {
            elements[i].style.visibility = newState;
        }
} 

//////////////////////////////////////////////////////
//  capLock()
//
//  A function which can determine if CAPS LOCK is on while
//  a user is typing.  If so, it displays "capWarning" div.
//////////////////////////////////////////////////////
function capLock(event,element)
{
     var kc = event.keyCode ? event.keyCode : event.which;
     var sk = event.shiftKey ? event.shiftKey: ((kc == 16) ? true : false);
     
     if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))
     {
        document.getElementById('capWarning').style.left = (getXCoordinate(element) + 10) + "px";
        document.getElementById('capWarning').style.top = (getYCoordinate(element) + 20) + "px";
        document.getElementById('capWarning').style.zIndex = 10;
        document.getElementById('capWarning').style.display = 'block';
     }
     else
        document.getElementById('capWarning').style.display = 'none';
}

//////////////////////////////////////////////////////
//  toggleCapLock()
//
//  CapsLock is not supported on the keypress, and we cant test the
//  shift key with onkeydown, so we have to have the two methods.  This
//  one simply tests if the user hits caps lock while in the field
//////////////////////////////////////////////////////
function toggleCapLock(event,element)
{
    var kc = event.keyCode ? event.keyCode : event.which;
    if (kc == 20)
    {
        if(document.getElementById('capWarning').style.display == 'none')
        {
            document.getElementById('capWarning').style.left = (getXCoordinate(element) + 10) + "px";
            document.getElementById('capWarning').style.top = (getYCoordinate(element) + 20) + "px";
            document.getElementById('capWarning').style.zIndex = 10;
            document.getElementById('capWarning').style.display = 'block';
        }
        else
            document.getElementById('capWarning').style.display = 'none'
    }
}

///////////////////////////////////////////////////////
//  setFocusSelectField()
//
//  This uses setTimeout() to add the focus and select
//  events to the end of the event handler queue.  Not all
//  browsers (FF currently) wait to set focus on a field until 
//  the last event.
///////////////////////////////////////////////////////
function setFocusSelectField(input)
{
	setTimeout(function(){input.focus();input.select();},1);
}
