

function ajax(iUrl, iActionName, iData, iSuccessCallBack, iErrorCallBack, asyncParam)
{
    if(typeof asyncParam == "undefined" || asyncParam == null)
    {
        asyncParam = true;
    }

    var actionAndData       = new Object();
    actionAndData.action    = iActionName;
    actionAndData.data      = jsToJson(iData);

    $.ajax({
        type: "POST",
        dataType: "json",
        async: asyncParam,
        url: iUrl + "?ajax=true",
        data: actionAndData,
        success: function(msg)
        {
            var typeMsg = (typeof msg) + "";
            var typeIsSuccess = (typeof msg.isSuccess) + "";
            if(typeMsg != "object" || typeIsSuccess != "boolean" || !msg.isSuccess)
            {
                var errorMsg = "";
                var type = (typeof msg.errorMsg) + "";
                if(type == "string")
                {
                    errorMsg = msg.errorMsg;
                }
            
                iErrorCallBack(errorMsg);
                return;
            }
            
            var msgConfirm = "";
            var type = (typeof msg.confirmMsg) + "";
            if(type == "string" )
            {
                msgConfirm = msg.confirmMsg;
            }
        
            iSuccessCallBack(msgConfirm, msg.data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown)
        {
            iErrorCallBack("");
        } 
    });
}

/*
based on http://www.json.org/json.js
*/
function jsToJson(obj)
{
    var type = typeof obj ;
    if(type == 'string')
    {
        obj = obj.replace(/\\/g, '\\\\') ;
        obj = obj.replace(/\t/g, '\\t') ;
        obj = obj.replace(/\n/g, '\\n') ;
        obj = obj.replace(/\f/g, '\\f') ;
        obj = obj.replace(/\r/g, '\\r') ;
        obj = obj.replace(/"/g, '\\"') ;
        
        return '"'+ obj + '"' ;
    }
    else if(type == 'array' || (type == 'object' && obj.push))
    {
        var a = ['['], b, i, l = obj.length, v;

        function pp(s) 
        {
            if (b) 
            {
                a.push(',');
            }
            a.push(s);
            b = true;
        }

        for (i = 0; i < l; i += 1) 
        {
            v = obj[i];
            switch (typeof v) 
            {
            case 'undefined':
            case 'function':
            case 'unknown':
                break;
            case 'object':
                if (v) 
                {
                    pp(jsToJson(v));
                } 
                else 
                {
                    pp("null");
                }
                break;
            default:
                pp(jsToJson(v));
            }
        }
        a.push(']');
        return a.join('');
    
    }
    else if(type == 'object')
    {
        var a = ['{'], b, i, v;

        function p(s) 
        {
            if (b) 
            {
                a.push(',');
            }
            a.push(jsToJson(i), ':', s);
            b = true;
        }

        for (i in obj) {
            if (typeof obj[i] != "undefined") 
            {
                v = obj[i];
                switch (typeof v) 
                {
                case 'undefined':
                case 'function':
                case 'unknown':
                    break;
                case 'object':
                    if (v) 
                    {
                        p(jsToJson(v));
                    } 
                    else 
                    {
                        p("null");
                    }
                    break;
                default:
                    p(jsToJson(v));
                }
            }
        }
        a.push('}');
        return a.join('');       
    }
    else if(type == 'number')
    {
        return isFinite(obj) ? String(obj) : "null";
    }
    else
    {
        return String(obj);
    }
}


function setCookie(cookieName, cookieValue, nDays) 
{
    if(cookieValue === true)
    {
        cookieValue = '__bangtrue';
    }
    else if(cookieValue === false)
    {
        cookieValue = '__bangfalse';
    }

    var today = new Date();
    var expire = new Date();
    if (nDays==null || nDays==0) nDays=365;
    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie = cookieName + "=" + escape(cookieValue) + ";expires="+expire.toGMTString() + ";path=/;domain=.assurancevieguide.com";
}

function deleteCookie(name) 
{
    document.cookie = name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT;path=/;domain=.assurancevieguide.com";
}

function detectTimezoneChange(userCurrentOffset)
{
    var now     = new Date();
    var offset  = (now.getTimezoneOffset() * -1)/60;
    
    if(userCurrentOffset != offset)
    {
        var div = document.getElementById('tzChangedDiv');
        div.style.display = 'block';
    }
}

function disableTimezoneChangeDetection()
{
    ajax("http://assurancevieguide.com/user/account", 
         "disableTimezoneChangeDetection",
         "disabletzd=true", 
         
         function(data)
         {
            document.getElementById('tzChangedDiv').style.display = 'none';
            var check = document.getElementById("tzautodetect");
            if(check)
            {
                check.checked = false;
            }
         }, 
         
         function(msgError)
         {
            if(msgError == "")
            {
                msgError = "An error occured while saving";
            }
            alert(msgError);
         })
}

function saveTimezoneForAnonymousUser()
{
    var now     = new Date();
    var offset  = (now.getTimezoneOffset() * -1)/60;
    
    setCookie("timezoneoffset", offset, 360)
}

function addAnchorAndSubmit(form, anchor)
{
    if(!form)
    {
        return; 
    }
    
    form.action += "#" + anchor;
    form.submit(); 
}

function showMoreInfo()
{
    var el = document.getElementById("moreInfoLink");
    el.style.display = "none";    
    
    var el = document.getElementById("infoMore");
    el.style.display = "block";
}

function showLessInfo()
{
    var el = document.getElementById("infoMore");
    el.style.display = "none";
    
    var el = document.getElementById("moreInfoLink");
    el.style.display = "block";  
}

function trim(str, chars)
{
    if(typeof str == "undefined" || str == "")
    {
        return "";
    }
    
    return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars)
{
    if(typeof str == "undefined" || str == "")
    {
        return "";
    }
    
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars)
{
    if(typeof str == "undefined" || str == "")
    {
        return "";
    }
    
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


function createDivFromHtml(html, cacheName)
{
    // doesn't always work when things imbricated
    //var newDiv = $(html);
    //newDiv = newDiv[0];
    
    html = trim(html);
    
        var pos = html.indexOf("<");
    var pos2 = html.indexOf(">", pos) + 1;
    var divStartTag = html.substring(pos, pos2);
    html = html.substring(pos2);
    
        pos = html.lastIndexOf("<");
    html = html.substring(0, pos);
    
    var newDiv = document.createElement("div");
    newDiv.innerHTML = html;
    
        var pos = divStartTag.indexOf(" ");
    if(pos != -1)
    {
        divStartTag = divStartTag.substring(pos);
        divStartTag = trim(divStartTag, " >");
        
                var inQuoteChar     = false;
        var attAndValues    = new Array();
        var buffer          = "";
        for(var i = 0; i < divStartTag.length; i++)
        {
            buffer += divStartTag[i];
            
            if(i == (divStartTag.length - 1))
            {
                attAndValues.push(buffer);
                continue;
            }
            
            if(divStartTag[i] == '"')
            {
                if(!inQuoteChar)
                {
                    inQuoteChar = '"';
                }
                else if(inQuoteChar == '"')
                {
                    inQuoteChar = false;
                }
                continue;
            }
            else if(divStartTag[i] == "'")
            {
                if(!inQuoteChar)
                {
                    inQuoteChar = "'";
                }
                else if(inQuoteChar == "'")
                {
                    inQuoteChar = false;
                }  
                continue;
            }
            
            if(divStartTag[i] == " ")
            {
                if(inQuoteChar)
                {
                    continue;
                }
                else
                {
                    attAndValues.push(buffer);
                    buffer = "";
                }
            }  
        }
        
        for(var i = 0; i < attAndValues.length; i++)
        {
            var oneAttAndValue = attAndValues[i];
            
            var tokens = oneAttAndValue.split("=");
            
            var attName     = tokens[0];
            var attValue    = tokens[1];
            attValue        = trim(attValue, ' "');

            newDiv.setAttribute(attName, attValue);
        }
    }


    return newDiv;
}



function getElementNbr(obj)
{
    var l = 0;
    for (var k in obj) 
    {
        l++;
    }
    return l;
}

function getWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  
  return new Array(myHeight, myWidth);
}

function getWindowHeight()
{
    var size = getWindowSize();
    return size[0];
}

function getWindowWidth()
{
    var size = getWindowSize();
    return size[1];
}



//================================
// http://www.quirksmode.org/js/detect.html
//
// Browser name: BrowserDetect.browser
// Browser version: BrowserDetect.version
// OS name: BrowserDetect.OS
//
// Call BrowserDetect.init() to initialize
//================================
var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++)    {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        {
            string: navigator.userAgent,
            subString: "Chrome",
            identity: "Chrome"
        },
        {     string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari",
            versionSearch: "Version"
        },
        {
            prop: window.opera,
            identity: "Opera"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {        // for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        {         // for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
               string: navigator.userAgent,
               subString: "iPhone",
               identity: "iPhone/iPod"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};

function getMouseCoordinates(e) {
    var posx = 0;
    var posy = 0;
    if (!e) var e = window.event;
    if (e.pageX || e.pageY)     {
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY)     {
        posx = e.clientX + document.body.scrollLeft
            + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop
            + document.documentElement.scrollTop;
    }

    return new Array(posx, posy);
}



