var skava_platform_swfname = "website";
var skava_platform_showAlerts = (false || ((typeof(showAlerts) == "undefined") ? false : showAlerts));
var skava_platform_turnon_showHideScrollBar = (false || ((typeof(dynamicScrollBar) == "undefined") ? false : dynamicScrollBar));

var SKAVA_PLATFORM_SUCCESS = 0;
var SKAVA_PLATFORM_ADDR_NOT_FOUND_ERR = 1;
var SKAVA_PLATFORM_TIMEOUT_ERR = 2;

var SKAVA_PLATFORM_ALERT_TITLE = "Alert";
var SKAVA_PLATFORM_FAILED_TO_LAUNCH = "We were unable to launch the page. Be sure your pop-up blocker is turned off and try again.";
var SKAVA_PLATFORM_ADDR_NOT_FOUND_STR = "We're unable to locate the address you entered. Please verify the information and try again.";
var SKAVA_PLATFORM_TIMEOUT_STR = "Locating address operation timeout. Please try again.";
var SKAVA_PLATFORM_BROWSER_NOT_COMPATIBLE = "We're sorry, the Google Maps tool does not work with the browser you're using.";
var SKAVA_PLATFORM_GMAPS_EXCEPTION = "We encountered an unknown error while loading state information. Please try again later.";

var skava_platform_gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");

var skava_platform_flashTest = 
{
    onOpCompleted: function(op, successCode, result){ alert("op=" + op + "successCode=" + successCode + "result=\n" + result);},
    onOpCancelled: function() { alert("flash.onOpCancelled invoked");},
    PercentLoaded : function() {return 100;}
};

function platformOpenNewWindow(URLtoOpen, windowName, windowFeatures) 
{
    if(skava_platform_showAlerts)
    {
        alert("Function name: platformOpenNewWindow, Param URLtoOpen: "+URLtoOpen+", Param windowName: "+windowName+", Param windowFeatures: "+windowFeatures);
    }
    
    var newWindow = window.open(URLtoOpen, "_blank", windowFeatures);
    if(newWindow)
    {
        newWindow.focus(); // openInNewTab
    }
    else
    {
        platformShowAlertMessage(SKAVA_PLATFORM_ALERT_TITLE, SKAVA_PLATFORM_FAILED_TO_LAUNCH);
    }
}

/*Functions used for avoiding the flash reloading at the time of 'a href' calling */
function platformScrollToTop(divId)
{
    var divContainer = document.getElementById(divId);

    if(divContainer)
    {
        divContainer.scrollTop = 0;
    }
}

function platformAnchorJump(anchorId, divId)
{
    var divContainer = document.getElementById(divId);

    if(divContainer)
    {
        var topForAnchor = platformGetRealTop(document.getElementById(anchorId));
        var topForDivContainer = platformGetRealTop(document.getElementById(divId));
        divContainer.scrollTop = topForAnchor - topForDivContainer;
    }
    return false; 
}

function platformGetRealTop(el)
{
    var yPos = el.offsetTop;
    var tempEl = el.offsetParent;
    while (tempEl != null)
    {
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }
    return yPos;
}



// platformShowPopup(bodyHTML:String, width:int, height:int, showCloseBox:boolean, doAnimate: boolean, cancelFn:object)
function platformShowPopup(bodyHTML, width, height, showCloseBox, doAnimate, cancelFn, callBk, virtualheight)
{
    platformShowPopWin(bodyHTML, width, height, showCloseBox, doAnimate, cancelFn, callBk, virtualheight);
}

function platformDismissPopup(callReturnFn)
{
    platformHidePopWin(callReturnFn);
}

//platformShowAlertMessage(title: String, message: String)
function platformShowAlertMessage(title, message)
{
    if(skava_platform_showAlerts)
    {
        alert("Function name: platformShowAlertMessage, Param title: "+title+", Param message: "+message);
    }
    
    var alertw = 300;
    var alerth = 120;
    var html = '<table cellspacing="0" cellpadding="4" class="platformShowAlertMessageProp" width='+alertw+'px;">' + 
            '<tr>' + 
                '<td class="platformShowAlertMessage" align="center">' +
                    '<div class="platformShowAlertMessageTitle">'+
                    (title ? title : '')+                     
                    '</div>' +
                '</td>' +
            '</tr>' +
            '<tr>' + 
                '<td class="platformShowAlertMessage" align="center">' +
                    '<div class="platformShowAlertMessageContent">' +                
                    (message ? message : '')+                     
                    '</div>' +
                '</td>' +
            '</tr>' +
            '<tr>' + 
                '<td class="platformShowAlertMessage platformShowAlertMessageImgButtonArea" align="center">' +
                    '<div>' +
                        '<input type="button" class="platformShowAlertMessageImgButtonProp" onclick="platformHidePopWin();return false;"></input>' +
                    '</div>' + 
                '</td>' +
            '</tr>' +
        '</table>';
    platformShowPopup(html, alertw+5, alerth+5, true, false, createDelegate(platformOnCancelled, this, [1, "platformShowAlertMessage"]));     
}

function  platformGetLatitudeLongitudeForAddress(address)
{
    if(skava_platform_showAlerts)
    {
        alert("Function name: platformGetLatitudeLongitudeForAddress, Param address: "+address);
    }
    
    var afterLocationSearch = function(result)
    {
        if(result)
        {
            //alert(result+", lang "+result.lng()+", lat "+result.lat());
            var toRetXML = "<coords>\n"+
                    "\t<latitude>"+result.lat()+"</latitude>\n"+
                    "\t<longitude>"+result.lng()+"</longitude>\n"+
                    "<coords>";

            //alert(toRetXML);
            platformOnCompleted(1, "platformGetLatitudeLongitudeForAddress", SKAVA_PLATFORM_SUCCESS, toRetXML);
        }
        else
        {
            platformOnCompleted(1, "platformGetLatitudeLongitudeForAddress", SKAVA_PLATFORM_ADDR_NOT_FOUND_ERR, SKAVA_PLATFORM_ADDR_NOT_FOUND_STR);
        }
    }

    if (GBrowserIsCompatible()) 
    {
        var clientGeocoder = new GClientGeocoder();
        clientGeocoder.getLatLng(address, afterLocationSearch); //From API docs: If the address was successfully located, the user-specified callback function is invoked with a GLatLng  point. Otherwise, the callback function is given a null point. 
    }
}

function platformGetState(zip, cbk)
{
    var isTimeOver = false;
    var afterLocationSearch = function(result)
    {
        if(result)
        {
           if(result == true)
           {
                isTimeOver = true;
                cbk('', SKAVA_PLATFORM_TIMEOUT_ERR, SKAVA_PLATFORM_TIMEOUT_STR);
                //platformOnCompleted(1, "getStateForZip", 0, null);
           }
           else if(result.Placemark && result.Placemark[0] && !isTimeOver)
           {
                var placeMark = result.Placemark[0];
                var state = null;
                var addrNode = null;
                if(placeMark)
                {
                    addrNode = placeMark.AddressDetails;
                    if(addrNode)
                    {
                        addrNode = addrNode.Country;
                        if(addrNode && addrNode.AdministrativeArea)
                        {
                            state = addrNode.AdministrativeArea.AdministrativeAreaName;
                        }
                    }
                }
                if(!isTimeOver)
                {
                    isTimeOver = true;
                    //platformOnCompleted(1, "getStateForZip", 0, state);
                    cbk(state, SKAVA_PLATFORM_SUCCESS, "");
                }
            }
            else
            {
                cbk('', SKAVA_PLATFORM_ADDR_NOT_FOUND_ERR, SKAVA_PLATFORM_ADDR_NOT_FOUND_STR);
            }
        }
        else if(!isTimeOver)
        {
            cbk('', SKAVA_PLATFORM_ADDR_NOT_FOUND_ERR, SKAVA_PLATFORM_ADDR_NOT_FOUND_STR);
 //        platformOnCompleted(1, "getStateForZip", "Address not Found", "Couldn't find the specified address");
        }
    }

    try
    {
        if(GBrowserIsCompatible()) 
        {
            var clientGeocoder = new GClientGeocoder();
            clientGeocoder.getLocations(zip, afterLocationSearch); //From API docs: If the address was successfully located, the user-specified callback function is invoked with a GLatLng  point. Otherwise, the callback function is given a null point. 
            //setTimeout(afterLocationSearch, 30000, true);
        }    
        else
        {
            cbk('', SKAVA_PLATFORM_ADDR_NOT_FOUND_ERR, SKAVA_PLATFORM_BROWSER_NOT_COMPATIBLE);;
        }
    }
    catch(err)
    {
        //alert("err: "+err);
        cbk('', SKAVA_PLATFORM_ADDR_NOT_FOUND_ERR, SKAVA_PLATFORM_GMAPS_EXCEPTION);
        //cbk('', 0, '');
    }
}

function platformRegisterPageView(pageid, categoryid, isPdn)
{
    if(skava_platform_showAlerts)
    {
        alert("Function name: platformRegisterPageView, Param pageid: "+pageid+", Param categoryid: "+categoryid+", Param isPdn: "+isPdn);
    }
    
    try
    {
        if(skava_platform_showAlerts)
        {
            alert("platformRegisterPageView: " + pageid + " category:" + categoryid);
        }

        if(isProduction || isPdn)
        {
            cmSetProduction();
        }
        cmCreatePageviewTag(pageid, categoryid, null, null);
    }
    catch(error)
    {
        if(skava_platform_showAlerts)
        {
            alert("platformRegisterPageView error: " + error);
        }
    }
}

function platformRegisterElementView(elementid, elementcategory)
{
    if(skava_platform_showAlerts)
    {
        alert("Function name: platformRegisterElementView, Param elementid: "+elementid+", Param elementcategory: "+elementcategory);
    }
    
    try
    {
        var category = elementcategory;
        if(skava_platform_showAlerts)
        {
            alert("platformRegisterElementView: " + elementid + " category:" + elementcategory);
        }

        // this will be done as part of page view
        //if(isProduction)
        //{
            //cmSetProduction();
        //}
        cmCreatePageElementTag(elementid, elementcategory);
    }
    catch(error)
    {
        if(skava_platform_showAlerts)
        {
            alert("platformRegisterElementView error: " + error);
        }
    }
}

function platformGetGaJsTracker()
{
    var pageTracker = null;
            
    try
    {
        var qs = new platformQuerystring();
        var ga = qs.get('ga'); 
        pageTracker = _gat._getTracker(googleAnalyticsId);
    } 
    catch(err) 
    {
    }
    
    return pageTracker;
}

function platformOnCompleted(attempt, op, successCode, result)
{
    if(op)
    {
        var tracker = platformGetGaJsTracker(); 
        //alert("tracker=" + tracker);
        if(tracker)
        {
            tracker._trackPageview("/socialactions/" + op); 
        }
    }
    var flashObj = platformGetCallBack(skava_platform_swfname);

    if (flashObj && attempt > 0 && flashObj.PercentLoaded() == 100)
    {
        try
        {
            // if it is test, we will show the error right there.
            platformDismissPopup();
            if(skava_platform_showAlerts)
            {
                alert("Calling op completed: op=" + op + " successCode=" + successCode + " result=" + result);
            }
            flashObj.onOpCompleted(op, successCode, result);
        }
        catch(e)
        {
            // we have dismissed the popup
            platformShowAlertMessage("Error", "Invalid Flash object. Please contact support. " + e);
        }
    }        
    else if(attempt > 20) // dialup and slow connections...
    {
        platformShowAlertMessage("Error", "Invalid Flash object. Unable to load it.");
    }
    else
    {
        //alert("call again");
        var fn = function()
        {
            platformOnCompleted(attempt + 1, op, successCode, result);
        }
        setTimeout(createDelegate(platformOnCompleted, this, [attempt + 1, op, successCode, result]), 500);
    }    
}

function platformOnCancelled(attempt, op)
{
    var flashObj = platformGetCallBack(skava_platform_swfname);
    if (flashObj && attempt > 0 && flashObj.PercentLoaded() == 100)
    {
        try
        {
            // if it is test, we will show the error right there.
            platformDismissPopup();
            if(skava_platform_showAlerts)
            {
                alert("calling op cancelled");
            }
            if(typeof(flashObjDoCancel) != "undefined" && flashObjDoCancel)
            {
                flashObj.onOpCancelled();
            }
            else
            {
                flashObj.onOpCompleted(op, -1, null);
            }
        }
        catch(e)
        {
            // we have dismissed the popup
            platformShowAlertMessage("Error", "Invalid Flash object. Please contact support. " + e);
        }
    }        
    else if(attempt > 20) // dialup and slow connections...
    {
        platformShowAlertMessage("Error", "Invalid Flash object. Unable to load it.");
    }
    else
    {
        setTimeout(createDelegate(platformOnCancelled, this, [attempt + 1, skava_platform_swfname]), 500);
    }    
}


function platformGetCallBack(movieName)
{
    //alert('gcb:' + movieName);
    return (movieName && movieName.onOpCompleted ? /*this is a json*/movieName : platformGetFlashObj(movieName));
}

function platformGetFlashObj(movieName)
{
    //alert('gfo:' + movieName + " isTestMode=" + isTestMode);
    var flashObj = null;
    if(isTestMode)
    {
        flashObj = skava_platform_flashTest;
        flashObj.skava_platform_swfname = movieName;
    }
    else
    {
        if (window.document[movieName]) 
        {
            flashObj = window.document[movieName];
        }
        else if (navigator.appName.indexOf("Microsoft Internet")==-1)
        {
            if (document.embeds && document.embeds[movieName])
                flashObj = document.embeds[movieName]; 
        }
        else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
        {
            flashObj = document.getElementById(movieName);
        }
    }
    return flashObj;
}

function platformGetFacebookProfilePhoto(callbck, focusId)
{
    var gotName = false;
    FB_RequireFeatures(["XFBML"], function()
    { 
        FB.init(SKAVA_PLATFORM_FBAPIKEY, "/cometogether/xd_receiver.html");
        FB.Connect.requireSession(function()
        {
            FB.Connect.ifUserConnected(function(uid)
            {
                if(!gotName)
                {
                    gotName = true;
                    var user = ((FB.Facebook.apiClient.get_session())?FB.Facebook.apiClient.get_session().uid:null);
                    var sql = "SELECT pic FROM user WHERE uid ="+FB.Facebook.apiClient.get_session().uid;
                    FB.Facebook.apiClient.fql_query(sql, 
                    function(result, ex) 
                    {
                        var pic = result[0]['pic'];
                        pic = ((pic && pic.length > 0)?pic:'http://static.ak.connect.facebook.com/pics/s_silhouette.jpg');
                        var facebookPhotoUrl = document.getElementById("facebookPhotoUrl");
                        if(facebookPhotoUrl)
                        {
                            facebookPhotoUrl.src = pic;
                            facebookPhotoUrl.style.visibility = "visible";
                            if(focusId)
                            {
                                var toFocus = document.getElementById(focusId);
                                if(toFocus)
                                {
                                    toFocus.focus();
                                }
                            }
                        }
                     });
                }
            }, 
            function()
            {
                return false;
            });
        });
    });
}

// SUBMODAL functions from prasad

/**
 * This derivative version of subModal can be downloaded from http://gabrito.com/files/subModal/
 * Original By Seth Banks (webmaster at subimage dot com)  http://www.subimage.com/
 * Contributions by Eric Angel (tab index code), Scott (hiding/showing selects for IE users), Todd Huss (submodal class on hrefs, moving div containers into javascript, phark method for putting close.gif into CSS), Thomas Risberg (safari fixes for scroll amount), Dave Campbell (improved parsing of submodal-width-height class)
 */

// Popup code
var skava_platform_gPopupMask = null;
var skava_platform_gPopupContainer = null;
var skava_platform_gPopFrame = null;
var skava_platform_gReturnFunc;
var skava_platform_gPopupIsShown = false;
var skava_platform_gHideSelects = false;
var skava_platform_gLoading = "Loading......";
var skava_platform_origTop = 0;
var skava_platform_origStart = 0;
var skava_platform_gTabIndexes = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
var skava_platform_gTabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME", "DIV");    

//4 removing this tab-key trap for FF. tabbing should work in Firefox too
// If using Mozilla or Firefox, use Tab-key trap.
if (!document.all && !document.getElementById) 
{
    document.onkeypress = platformKeyDownHandler;
}

/**
 * Override the loading page from loading.html to something else
 */
function platformSetPopUpLoadingPage(loading) 
{
    skava_platform_gLoading = loading;
}

/**
 * Initializes popup code on load.  
 */
function platformInitPopUp() 
{
    //console.log("calling platformInitPopUp");
   var isFF2Mac = (navigator.userAgent && navigator.userAgent.indexOf("Macintosh") >=0 && navigator.userAgent.indexOf("Firefox/2") >= 0) ? true : false;    
    // Add the HTML to the body
    var body = document.getElementsByTagName('body')[0];
    var popmask = document.createElement('div');

    if(isFF2Mac)
    {
        popmask.id = 'platformPopupMaskNoCss'; // the bgnd is not transluscent, but opaque in FF2 on Mac - so avoid the bgnd altogether
    }
    else
    {
        popmask.id = 'platformPopupMask';
    }

    var popcont = document.createElement('div');
    popcont.id = 'platformPopupContainer';
    popcont.innerHTML = '' +
        '<div id="platformPopupInner">' +
            '<div id="platformPopupTitleBar">' +
                '<div id="platformPopupTitle"></div>' +
                '<div id="platformPopupControls">' +
                    //'<a onclick="platformHidePopWin(false);"><span>Close</span></a>' +
                '</div>' +
            '</div>' +
            '<div class="platformPropPopup" scrolling="auto" frameborder="0" allowtransparency="true" id="platformPopupFrame" name="platformPopupFrame" width="100%" height="100%"></div>' +
            //'<iframe src="'+skava_platform_gLoading+'" style="width:100%;height:100%;background-color:transparent;" scrolling="auto" frameborder="0" allowtransparency="true" id="platformPopupFrame" name="platformPopupFrame" width="100%" height="100%"></iframe>' +
        '</div>';
    body.appendChild(popmask);
    body.appendChild(popcont);
    
    skava_platform_gPopupMask = document.getElementById(isFF2Mac ? "platformPopupMaskNoCss" : "platformPopupMask");
    skava_platform_gPopupContainer = document.getElementById("platformPopupContainer");
    skava_platform_gPopFrame = document.getElementById("platformPopupFrame");  
    
    // check to see if this is IE version 6 or lower. hide select boxes if so
    // maybe they'll fix this in version 7?
    var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
    if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) 
    {
        skava_platform_gHideSelects = true;
    }
    
    // Add onclick handlers to 'a' elements of class submodal or submodal-width-height
    var elms = document.getElementsByTagName('a');
    for (i = 0; i < elms.length; i++) 
    {
        if (elms[i].className.indexOf("submodal") >= 0) 
        { 
            elms[i].onclick = function()
            {
                // default width and height
                var width = 400;
                var height = 200;
                // Parse out optional width and height from className
                var startIndex = this.className.indexOf("submodal");
                var endIndex = this.className.indexOf(" ", startIndex);
                if (endIndex < 0) 
                {
                    endIndex = this.className.length;
                }
                var clazz = this.className.substring(startIndex, endIndex);
                params = clazz.split('-');
                if (params.length == 3) 
                {
                    width = parseInt(params[1]);
                    height = parseInt(params[2]);
                }
                platformShowPopWin(this.href, width, height, null, null, 0); return false;
            }
        }
    }
}
//platformAddEvent(window, "load", platformInitPopUp);

 /**
    * @argument width - int in pixels
    * @argument height - int in pixels
    * @argument url - url to display
    * @argument returnFunc - function to call when returning true from the window.
    */

function platformShowPopWin(content, width, height, showCloseBox, doAnimate, returnFunc, callBk, virtualheight) 
{
    //console.log("calling platformShowPopWin");
    skava_platform_gPopupIsShown = true;
    platformDisableTabIndexes();
    if(!skava_platform_gPopupMask)
    {
        platformInitPopUp();
    }
    skava_platform_gPopupMask.style.display = "block";
    skava_platform_gPopupContainer.style.display = "block";
    platformPopupChangeSizeLocation(width, (virtualheight ? virtualheight : height), doAnimate);
    var titleBarHeight = parseInt(document.getElementById("platformPopupTitleBar").offsetHeight, 10);
    var popupControls = document.getElementById("platformPopupControls");
    
    if(showCloseBox == true)
    {
        popupControls.innerHTML = '<a onclick="platformHidePopWin(true);"><span>Close</span></a>';
    }
    else
    {
        popupControls.innerHTML = '';        
    }
    
    skava_platform_gPopupContainer.style.width = width + "px";
    skava_platform_gPopupContainer.style.height = (height+titleBarHeight) + "px";
    skava_platform_gPopFrame.style.width = parseInt(document.getElementById("platformPopupTitleBar").offsetWidth, 10) + "px";
    skava_platform_gPopFrame.style.height = (height) + "px";
    skava_platform_gPopFrame.innerHTML = content;
    //skava_platform_gPopFrame.src = url;
    skava_platform_gReturnFunc = returnFunc;
    // for IE
    if (skava_platform_gHideSelects == true) 
    {
        platformHideSelectBoxes();
    }
    window.setTimeout("platformSetPopTitleAndRewriteTargets();", 100);
    if(callBk)
    {
        callBk();
    }
}

var skava_platform_gi = 0;
function platformCenterPopWin(width, height, doAnimate)
{
    //console.log("calling platformCenterPopWin");
    if (skava_platform_gPopupIsShown == true) 
    {
        if (width == null || isNaN(width))
        {
            width = skava_platform_gPopupContainer.offsetWidth;
        }
        if (height == null || isNaN(height))
        {
            height = skava_platform_gPopupContainer.offsetHeight;
        }
        var fullHeight = platformGetViewportHeight();
        var fullWidth = platformGetViewportWidth();
        var bodyTag = document.getElementsByTagName("body")[0];
        
        // scLeft and scTop changes by Thomas Risberg
        var scLeft,scTop;
        if (self.pageYOffset)
        {
            scLeft = self.pageXOffset;
            scTop = self.pageYOffset;
        }
        else if (document.documentElement && document.documentElement.scrollTop)
        {
            scLeft = document.documentElement.scrollLeft;
            scTop = document.documentElement.scrollTop;
        }
        else if (document.body)
        {
            scLeft = document.body.scrollLeft;
            scTop = document.body.scrollTop;
        } 
        var bodyClientHeight =  bodyTag.clientHeight;
        var bodyClientWidth = bodyTag.clientWidth;        
        var bodyOffsetHeight =  bodyTag.offsetHeight;
        var bodyOffsetWidth = bodyTag.offsetWidth;
        
        skava_platform_gPopupMask.style.height = (bodyClientHeight > bodyOffsetHeight ? bodyClientHeight : bodyOffsetHeight) + "px";        
        skava_platform_gPopupMask.style.width = (bodyClientWidth > bodyOffsetWidth ? bodyClientWidth : bodyOffsetWidth) + "px";
        skava_platform_gPopupMask.style.top = bodyTag.clientTop + "px";
        skava_platform_gPopupMask.style.left = bodyTag.clientLeft + "px";
        //4 removing the update shown in status bar 
        //window.status = skava_platform_gPopupMask.style.top + " " + skava_platform_gPopupMask.style.left + " " + skava_platform_gi++;
        var titleBarHeight = parseInt(document.getElementById("platformPopupTitleBar").offsetHeight, 10);
        var topMargin = scTop + ((fullHeight - (height+titleBarHeight)) / 2);
        if (topMargin < 0) { topMargin = 0; }
        if (scLeft < 0) { scLeft = 0; }
        
        //skava_platform_gPopupContainer.style.top = topMargin + "px";
        skava_platform_origTop = topMargin;
        skava_platform_origStart = fullWidth-width;

        if(doAnimate == true)
        {
            skava_platform_gPopupContainer.style.top = fullHeight + "px";
            platformStartAnim(skava_platform_gPopupContainer, skava_platform_origStart, skava_platform_origTop);     
        }
        else
        {
            skava_platform_gPopupContainer.style.top = topMargin + "px";
            //skava_platform_gPopupMask.style.opacity = 0.30;
            //skava_platform_gPopupMask.style.filter = alpha(opacity=30);
        }
        var popupContLeft = (scLeft + ((fullWidth - width) / 2));
        if(popupContLeft < 0) { popupContLeft = 0; }
        skava_platform_gPopupContainer.style.left = popupContLeft + "px";
    }
}
//platformAddEvent(window, "resize", platformCenterPopWin);
//platformAddEvent(window, "scroll", platformCenterPopWin);
//window.onscroll = platformCenterPopWin;
var platformOpacity = 0;

/**
 * @argument callReturnFunc - bool - determines if we call the return function specified
 * @argument returnVal - anything - return value 
 */
function platformHidePopWin(callReturnFunc)
{
    skava_platform_gPopupIsShown = false;
    platformRestoreTabIndexes();
    if (skava_platform_gPopupMask == null) 
    {
        return;
    }
    skava_platform_gPopupMask.style.display = "none";
    skava_platform_gPopupContainer.style.display = "none";
    skava_platform_gPopFrame.innerHTML = skava_platform_gLoading;
    
    if (callReturnFunc == true && skava_platform_gReturnFunc != null)
    {
       skava_platform_gReturnFunc.call();
    }
    //skava_platform_gPopFrame.src = skava_platform_gLoading;
    
    // display all select boxes
    if (skava_platform_gHideSelects == true)
    {
        platformDisplaySelectBoxes();
    }
}

/**
 * Sets the popup title based on the title of the html document it contains.
 * Also adds a base attribute so links and forms will jump out out of the iframe
 * unless a base or target is already explicitly set.
 * Uses a timeout to keep checking until the title is valid.
 */
function platformSetPopTitleAndRewriteTargets()
{
    /*if (window.frames["platformPopupFrame"].document.title == null) {*/
        window.setTimeout("platformSetPopTitleAndRewriteTargets();", 10);
    /*} else {
        var popupDocument = window.frames["platformPopupFrame"].document;
        document.getElementById("platformPopupTitle").innerHTML = popupDocument.title;
        if (popupDocument.getElementsByTagName('base').length < 1) {
            var aList  = window.frames["platformPopupFrame"].document.getElementsByTagName('a');
            for (var i = 0; i < aList.length; i++) {
                if (aList.target == null) aList[i].target='_parent';
            }
            var fList  = window.frames["platformPopupFrame"].document.getElementsByTagName('form');
            for (i = 0; i < fList.length; i++) {
                if (fList.target == null) fList[i].target='_parent';
            }
        }
    }*/
}

// Tab key trap. iff popup is shown and key was [TAB], suppress it.
// @argument e - event - keyboard event that caused this function to be called.
function platformKeyDownHandler(e)
{
    if (skava_platform_gPopupIsShown && e.keyCode == 9)  return false;
}

// For IE.  Go through predefined tags and disable tabbing into them.
function platformDisableTabIndexes() 
{
    //4 adding document.getElementById to disable the tabbing in the background fields in FF and safari.
    if ((document.all) || (document.getElementById)) 
    {
        var i = 0;
        for (var j = 0; j < skava_platform_gTabbableTags.length; j++)
        {
            var tagElements = document.getElementsByTagName(skava_platform_gTabbableTags[j]);
            for (var k = 0 ; k < tagElements.length; k++)
            {
                skava_platform_gTabIndexes[i] = tagElements[k].tabIndex;
                tagElements[k].tabIndex="-1";
                i++;
            }
        }
    }
}

// For IE. Restore tab-indexes.
function platformRestoreTabIndexes()
{
    //4 adding document.getElementById to disable the tabbing in the background fields in FF and safari.
    if ((document.all) || (document.getElementById))
    {
        var i = 0;
        for (var j = 0; j < skava_platform_gTabbableTags.length; j++)
        {
            var tagElements = document.getElementsByTagName(skava_platform_gTabbableTags[j]);
            for (var k = 0 ; k < tagElements.length; k++)
            {
                tagElements[k].tabIndex = skava_platform_gTabIndexes[i];
                tagElements[k].tabEnabled = true;
                i++;
            }
        }
    }
}

/**
* Hides all drop down form select boxes on the screen so they do not appear above the mask layer.
* IE has a problem with wanted select form tags to always be the topmost z-index or layer
* Thanks for the code Scott!
*/
function platformHideSelectBoxes()
{
    for(var i = 0; i < document.forms.length; i++)
    {
        for(var e = 0; e < document.forms[i].length; e++)
        {
            if(document.forms[i].elements[e].tagName == "SELECT")
            {
                document.forms[i].elements[e].style.visibility="hidden";
            }
        }
    }
}

/**
* Makes all drop down form select boxes on the screen visible so they do not reappear after the dialog is closed.
* IE has a problem with wanted select form tags to always be the topmost z-index or layer
*/
function platformDisplaySelectBoxes()
{
    for(var i = 0; i < document.forms.length; i++)
    {
        for(var e = 0; e < document.forms[i].length; e++)
        {
            if(document.forms[i].elements[e].tagName == "SELECT")
            {
                document.forms[i].elements[e].style.visibility="visible";
            }
        }
    }
}

/**
 * X-browser event handler attachment and detachment
 * @argument obj - the object to attach event to
 * @argument evType - name of the event - DONT ADD "on", pass only "mouseover", etc
 * @argument fn - function to call
 */
function platformAddEvent(obj, evType, fn)
{
    if (obj.addEventListener)
    {
        obj.addEventListener(evType, fn, false);
        return true;
    }
    else if (obj.attachEvent)
    {
        var r = obj.attachEvent("on"+evType, fn);
        return r;
    }
    else
    {
        return false;
    }
}

/**
 * Code below taken from - http://www.evolt.org/article/document_body_doctype_switching_and_more/17/30655/ *
 * Modified 4/22/04 to work with Opera/Moz (by webmaster at subimage dot com)
 * Gets the full width/height because it's different for most browsers.
 */
function platformGetViewportHeight()
{
    if (window.innerHeight!=window.undefined)
    {
        return window.innerHeight;
    }
    if (document.compatMode=='CSS1Compat')
    {
        return document.documentElement.clientHeight;
    }
    if (document.body) 
    {
        return document.body.clientHeight; 
    }
    return window.undefined; 
}

function platformGetViewportWidth()
{
    if (window.innerWidth!=window.undefined)
    {
        return window.innerWidth; 
    }
    if (document.compatMode=='CSS1Compat')
    {
        return document.documentElement.clientWidth; 
    }
    if (document.body)
    {
        return document.body.clientWidth; 
    }
    return window.undefined; 
}

// this are all my code
function platformStartAnim(skava_platform_gPopupContainer, from , to)
{
    if(skava_platform_gPopupContainer)
    {
        platformOpacity = 0;            
        platformDoWidthChangeMem(skava_platform_gPopupContainer, from, to, 40, 15);
        platformFadeBackground(skava_platform_gPopupMask, 15, 10, 30);
    }
    return false;
}

var skava_platform_animid;

function platformDoWidthChangeMem(elem,startWidth,endWidth,steps,intervals) 
{ 
    if(skava_platform_animid)
    {
        window.clearInterval(skava_platform_animid);
    }
    var actStep = 0;
    skava_platform_animid = window.setInterval(function() 
    { 
        actStep++;
        var delta;
        delta = platformBackout(actStep, 0, (endWidth-startWidth), steps);
        elem.style.top = (startWidth+delta) + "px"; 
        if (actStep > steps)
        {       
            window.clearInterval(skava_platform_animid);
        }
    }, intervals);
}


var skava_platform_animid1;
function platformFadeBackground(element, steps, intervals, maxopacity)
{
    if(skava_platform_animid1)
    {
        window.clearInterval(skava_platform_animid1);
    }

    var actStep = 0;

    skava_platform_animid1 = window.setInterval(function() 
    { 
      platformOpacity = platformOpacity + (maxopacity/steps);
      var tempopacity = (platformOpacity/100);
      element.style.opacity = tempopacity;
      element.style.filter = 'alpha(opacity=' + platformOpacity + ')';
      actStep++;
      if (actStep > steps)
      {     
          window.clearInterval(skava_platform_animid1);
      }
    }, intervals);
}

//t = current time b = start value c = end value d = duration
function platformBackout(t, b, c, d)
{
    var s=2.70158;
    return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
}

//utils

function platformUrldecode(msg)
{
    // unescape does not unescape a string this : hello+world
    return (msg ? unescape(msg.replace(/\+/g, "%20")) : msg);
}

function platformTrim(s)
{
     //4 since \n is not dected as \n in IE6 etc, we are setting a hack to find it by escaping the string and searching for form feed and carriage return
     var temp = escape(s);
     temp = temp.replace(/%0D%0A/g, '%20');
     temp = temp.replace(/%0D/g, '%20');
     temp = temp.replace(/%0A/g, '%20');    
     s = unescape(temp);
    return platformRtrim(platformLtrim(s));
}

function platformLtrim(s)
{
    var l=0;
    while(l < s.length && (s[l] == ' ' || s.charAt(l)==' ' || s.charAt(l)=='\n'))
    {
        l++; 
    }
    
    return s.substring(l, s.length);
}

function platformRtrim(s)
{
    var r=s.length -1;
    
    while(r > 0 && (s[r] == ' ' || s.charAt(r)==' ' || s.charAt(r)=='\n'))
    {
        r-=1;
    }
    
    return s.substring(0, r+1);
}

function platformValidateUserName(userName)
{   
    var isValid = true;
    if(userName)
    {
        var asciiVal = 0;
        for(var i = 0; i < userName.length; i++)
        {
            asciiVal = userName.charCodeAt(i);
            //space 32
            // '-' 45
            // '.' 46
            // '_' 95
            // 48 to 57 -> 0 to  9
            //65 to 90 -> A to z
            // 97 to 122 -> a to z
            //alert(asciiVal);
            if(asciiVal == 32 || asciiVal == 45 ||  asciiVal == 46 || asciiVal == 95 || 
                (asciiVal >= 48 && asciiVal <= 57) || (asciiVal >= 65 && asciiVal <= 90) ||
                (asciiVal >= 97 && asciiVal <= 122) )
            {
                continue;
            }
            else
            {
                isValid = false;
                break;
            }
        }
    }
    return isValid;
}
/*
function platformValidateEmailId(emailid)
{
    //The local-part of the e-mail address may use any of these ASCII characters:
    //* Uppercase and lowercase English letters (a-z, A-Z)
    //* Digits 0 through 9
    //* Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
    //* Character . (dot, period, full stop) provided that it is not the first or last character, and provided also that it does not appear two or more times consecutively.
    // the domain may be an IP address literal, surrounded by square braces, such as jsmith@[192.168.2.1] (this is rarely seen, except in spam).
                                     
    var filterForEMailId = new RegExp("^(([a-zA-Z0-9][a-zA-Z0-9!#\$^\'\=\?\%\/{|}~&`_\*\+\-]*(([\.][a-zA-Z0-9]+)*)[a-zA-Z0-9!#\$^\'\=\?\%\/{|}~&`_\*\+\-]*))@(([a-zA-Z0-9]+([\.][a-zA-Z0-9]{2,4})+)|([\[]((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]))\]))$");;

    if(emailid != '' && (filterForEMailId.test(platformTrim(emailid))))
    {   
        return true;
    }
    
    return false;
}
*/

function platformLoadCaptchaImage(elid)
{
    var serverprefix = "http://"+document.domain;
    var el = document.getElementById(elid);
    if(el)
    {
        var sessionid = platformReadCookie('JSESSIONID');
        var url = serverprefix + '/mc/captcha;jsessionid='+sessionid+'?timeforreload="' + (new Date()).getTime() + '"';
        el.src = url;        
    }
}

function platformReadCookie(name) 
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    
    for(var i=0;i < ca.length;i++) 
    {
        var c = ca[i];
        
        while (c.charAt(0)==' ') 
        {
            c = c.substring(1,c.length);
        }
        
        if (c.indexOf(nameEQ) == 0) 
        {
            return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

function platformGetDisplayText(string, length, donotEncode)
{
    var toRet = "";

    if(string && string.length > length)
    {
        toRet = string.substr(0, length) + "...";
    }
    else
    {
        toRet = string;
    }

    if(!donotEncode)
    {
           toRet = htmlEncode(toRet);
    }
    
    return (toRet ? toRet : "");        
}

function platformCheckIsNumber(evt, control, limit, alowHyphen, afterChar, allowDot) 
{
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    var allowHyphenChar = false, allowDotChar = false;

/*    var str = new String;
    str = String.fromCharCode(charCode);
    var tmp = charCode;
    tmp ^= 0x0F;       // XOR 
    var encrypted = String.fromCharCode(tmp); */
    //alert("char code: "+charCode+", str: "+str+", encrypted: "+encrypted);
    
    if(alowHyphen && control.value.length > afterChar)
    {
        allowHyphenChar = true;
    }

    if(allowDot && control.value.length > afterChar)
    {
        allowDotChar = true;
    }

    //4 removing the <-, ->, del allow for FF2  issue, which assigns the same key code to % . '  
    if (charCode > 31 && (/*charCode != 37 && charCode != 39 && charCode != 46 &&*/ (charCode < 48 || charCode > 57)) && !(allowHyphenChar && (/*charCode == 189 || charCode == 109 || */ charCode == 45)) && !(allowHyphenChar && (/*charCode == 189 || charCode == 109 || */ charCode == 45)) && !(allowDot && charCode == 46))  // to allow hyphen in zip code
    {
        return false;
    }        
    else if(charCode > 31 && control != null && limit != null)
    {
        if (control.value.length >= limit) 
        {
            return false;
        } 
    }
    
    return true;
}

function platformLimiter(el, limit)
{
    var len = el.value.length;
    var toRet = true;
    //console.log("len: "+len+"limit: "+limit);
    if(len > limit)
    {
        var text = el.value.substring(0, limit);
        el.value = text;
        toRet = false;
    }
    return toRet;
}

function platformCheckLimit(evt, control, limit) 
{
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && charCode != 127) 
    {
        if(control.value.length >= limit)
        {
            return false;
        }
    }        
    return true;
}

function platformIncludeJavaScript(jsFile)
{
    document.write('<script type="text/javascript" src="'
                + jsFile + '"></scr' + 'ipt>'); 
}

PlatformQuerystring.prototype.get = function(key, defaultStr) 
{
    var value = this.params[key];
    return (value != null) ? value : defaultStr;
}

PlatformQuerystring.prototype.contains = function(key) 
{
    var value = this.params[key];
    return (value != null);
}

function PlatformQuerystring(qs) 
{ 
    // optionally pass a querystring to parse
    this.params = {};
    
    if (qs == null) 
    {
        qs = location.search.substring(1, location.search.length);
    }
    
    if (qs.length == 0) 
    {
        return;
    }

    // Turn <plus> back to <space>
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&'); // parse out name/value pairs separated via &
    
    // split out each name=value pair
    for (var i = 0; i < args.length; i++) 
    {
        var pair = args[i].split('=');
        var name = decodeURIComponent(pair[0]);           
        var value = (pair.length==2)? decodeURIComponent(pair[1]): name;           
        this.params[name] = value;
    }
}

function platformDoWhiteSpaceEncode(strToEncode, numChars, breakAt)
{
    var toRet = "";
    var tempStr = (numChars ? platformGetDisplayText(strToEncode, numChars, true) : strToEncode);
    var wordsArr = tempStr.split(' ');
    var tempArr = null;
    var wbrAt = (breakAt ? breakAt : 15);
  
    for(i=0; i<wordsArr.length; i++)
    {
        if(wordsArr[i].length > wbrAt)
        {
            tempArr = new Array();
            for(j=0; j+wbrAt < wordsArr[i].length; j+=wbrAt)
            {
                tempArr.push(htmlEncode(wordsArr[i].substr(j, wbrAt)));
            }
            
            if(wordsArr[i].substr(j))
            {
                tempArr.push(htmlEncode(wordsArr[i].substr(j)));
            }
            wordsArr[i] = tempArr.join('<font size="0"><wbr></font>');
        }
        else
        {
            wordsArr[i] = htmlEncode(wordsArr[i]);
        }
    }

    toRet = wordsArr.join(' ');
    return toRet;
}

function platformPopupChangeSizeLocation(width, height, doAnimate)
{
    if(skava_platform_gPopupIsShown == true)
    {
        var platformPopupContainer = document.getElementById("platformPopupContainer");
        if(platformPopupContainer)
        {
            platformCenterPopWin(width ? width : parseInt(platformPopupContainer.style.width), height ? height : parseInt(platformPopupContainer.style.height), doAnimate);
        }        
    }
}

function platformValidateNumber(strToValidate, limit, alowHyphen, atChar, allowDot, afterChar) 
{
    var alowHyphenChar = false, allowDotChar = false;
    var ch= null;
    var charCode = 0, i =0;
    var isValid = true;

    if(strToValidate)
    {
        for(i=0; i < strToValidate.length; i++)
        {    
            alowHyphenChar = (alowHyphen && i == atChar);

            if(allowDot && i > afterChar)
            {
                allowDotChar = true;
            }

            charCode = strToValidate.charCodeAt(i);

            if(alowHyphenChar)
            {
                if(charCode != 45 || strToValidate.length < limit)
                {
                    isValid = false;
                    break;
                }
            }
            else if(charCode > 31 && ((charCode < 48 || charCode > 57)) && !(allowDot && charCode == 46))  // to allow hyphen in zip code
            {
                isValid = false;
                break;
            }        
            else if(charCode > 31 && strToValidate != null && limit != null)
            {
                if(strToValidate.length > limit) 
                {
                    isValid = false;
                    break;
                } 
            }
        }
    }
    else
    {
        isValid = false;
    }
    
    return isValid;
}

function platformFacebookConnectLogin(facebookConnectApiKey, xdReciverPath, callbck)
{
    FB_RequireFeatures(["XFBML"], function() 
    {
        FB.Facebook.init(facebookConnectApiKey, xdReciverPath);
        FB.Connect.requireSession( 
            function()
            {
                FB.Connect.ifUserConnected(
                    function(uid)
                    {
                        callbck(uid);
                    },
                    function() 
                    {
                        return false;
                    });
            });
    });

}

function platformShowHideScrollBar(overlayHeight)
{
    if(skava_platform_turnon_showHideScrollBar)
    {
        var set = false;
        if(overlayHeight > window.innerHeight)
        {
            set = true;
        }

        var node = null;
        if(set == true)
        {
            node = document.getElementsByTagName("html");
            node[0].style.overflow = "scroll";
        }
        else
        {
            node = document.getElementsByTagName("html");
            node[0].style.overflow = "hidden";
        }
     }
}

function platformLoadJsCssfile(filename, isJs, callback)
{
    // to avoid browser caching, add a timestamp
    filename = filename + ((filename.indexOf("?") >= 0) ? "&" : "?") + "time=" + (new Date().getTime());
    
    if (isJs)
    { //if filename is a external JavaScript file
        var fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);        
    }
    else
    { //if filename is an external CSS file
        var fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);        
    }

    if (typeof fileref!="undefined")
    {
        if(callback)
        {
            fileref.onload = function() 
            { 
                fileref.onloadDone = true; 
                callback(); 
            };

            //for IE to call callback correctely we need onreadystatechange, IE is not calling onload
            fileref.onreadystatechange = function() 
            { 
                if ( "loaded" === fileref.readyState && ! fileref.onloadDone ) 
                {
                    fileref.onloadDone = true; 
                    callback();
                }
            }
        }    
    
        document.getElementsByTagName("head")[0].appendChild(fileref);
    }
}

function platformCheckForGmaps(gmapskey)
{
    //alert("calling gmaps check");
    try
    {
        if(GBrowserIsCompatible()) 
        {
            var clientGeocoder = new GClientGeocoder();
        }
    }
    catch(err)
    {
        //alert("gmaps api is not loaded. hence reloading it.");
        getDataFromServer("gmapsapi", "http://www.google.com/maps?file=api&v=2&sensor=false&key=" + gmapskey);
    }
}

function platformSortfunction(a, b)
{
    return (a - b); 
}

function platformGetUnique(a)
{
    var r = new Array();
    u:for(var i = 0, n = a.length; i < n; i++)
    {
        for(var x = 0, y = r.length; x < y; x++)
        {
             if(r[x]==a[i]) continue u;
        }
        r[r.length] = a[i];
    }
    return r;
}

platformIncludeJavaScript(skava_platform_gaJsHost + 'google-analytics.com/ga.js'); // google analytics api

