/*
 * $Id$
 *
 * Copyright (C) 2008 Allurent, Inc.  All Rights Reserved.  No use,
 * copying or distribution of this work may be made except in
 * accordance with a valid license agreement from Allurent.  This
 * notice must be included on all copies, modifications and
 * derivatives of this work.
 * 
 * Allurent makes no representations or warranties about the
 * suitability of the software, either express or implied, including
 * but not limited to the implied warranties of merchantability,
 * fitness for a particular purpose, or non-infringement. Allurent
 * shall not be liable for any damages suffered by licensee as a
 * result of using, modifying or distributing this software or its
 * derivatives.
 */
 
var alltelSelector = {
    // Configuration variables
    applicationSwfWidth: 770,
    applicationSwfHeight: 648,
    applicationSwfLocation: "/ShoppingFiles/NDV/AppSelector",
    applicationSwfId: "AppSelector",
    configLocation: "/ShoppingFiles/NDV/config.xml",
    redirectParamName: "rd",
    planRedirURL: "/wps/portal/AlltelPublic/Content?WCM_GLOBAL_CONTEXT=/wps/wcm/connect/Personal/home/p/wirelessplans/dwirelessplans",
    defaultRedirURL: "/wps/portal/AlltelPublic/Content?WCM_GLOBAL_CONTEXT=/wps/wcm/connect/Personal/home/p/phonesandaccessories/showphonesby/view+all",
    qualificationCookie: "ARCQUAL",
    qualificationFailValue: "fail",
    fallbackRetryInterval: 1000,

    debuggingStatsEnabled: false,

    // The list of "milestones" that the application must hit within
    // certain time limits as it is starting up.
    loadApplicationSwfMilestones: [
        {milestone: "preloaderStart", timeout: 20000},
        {milestone: "preloaderDownload-25%", timeout: 20000},
        {milestone: "preloaderDownload-50%", timeout: 20000},
        {milestone: "preloaderDownload-75%", timeout: 20000},
        {milestone: "preloaderDownloadComplete", timeout: 20000},
        {milestone: "applicationStart", timeout: 5000},
        {milestone: "preloaderFlexInitComplete", timeout: 45000},
        {milestone: "dataLoaded", timeout: 45000}
    ],

    // The index of the next milestone that the application has to
    // hit.
    loadApplicationSwfNextMilestoneIndex: 0,

    // The start time for waiting for the next milestone.
    loadApplicationSwfMilestoneStartTime: 0,
    
    // The start time when runApplication was called
    scriptStartTime: 0,
    
    // The time when page started to load, if specified
    initStartTime: null,
    
    // Allowable amount of time, in millis, between page load and 'runApplication'
    initTimeout: 6000,
    
    // The reason why user is disqualified, if they are
    disqualReason: null,

    // The main method which runs the application
    runApplication: function()
    {
        this.scriptStartTime = new Date().getTime();
        
        // Show debugging times if requested
        if (this.isEmitDebug()) this.emitDebuggingStats();
        
        // Check to see if the SWF should run
        if (this.shouldRunApplicationSwf()) {
        
            // Start the application running, forcing it into a 1x1
            // enclosing div.  When the application is ready to be
            // shown, it will expand back to its desired size.
            this.startApplicationSwf();

            // Set the timer running that makes sure we hit the next
            // startup milestone in a timely manner
            this.waitForNextMilestone();
        }
        else {
            // If we have immediately decided not to show the SWF,
            // then fall back to an HTML presentation
            this.fallbackToHtml();
        }
    },

    // Returns true if, as far as we know at this point, we should
    // attempt to run the SWF.  This will check, for example, the
    // flash version, as well as the cookie which indicates that we
    // have already failed previously.
    shouldRunApplicationSwf: function()
    {
        // Check for query arg override
        if (this.isForceAllurent())
        {
            arc.util.setCookie("ARCFORCE", "true");
            return true;
        }
        if (this.isForceHtml())
        {
            arc.util.setCookie("ARCFORCE", "false");
            return false;
        }
        
        // Check to see whether allowed embed time was exceeded
        if (this.initStartTime != null)
        {
            initElapse = (new Date().getTime()) - this.initStartTime;
            if (this.debuggingStatsEnabled) {
                document.getElementById("initStart").innerHTML = "" + initElapse + " msec";
            }            
            if (initElapse > this.initTimeout) 
            {
                this.disqualReason = "initializationStart:" + this.initTimeout;
                this.fallbackToHtml();
            }
        }
        
        // Check to see if there is a cookie indicating that we
        // previously failed to run the SWF
        cookieval = arc.util.getCookie(this.qualificationCookie);
        if (cookieval != null && (cookieval.indexOf(this.qualificationFailValue) > -1)) 
        {
            return false;
        }

        // Check the flash version
        if (!DetectFlashVer(9, 0, 0)) {
            this.disqualReason = "flashPlayer";
            return false;
        }

        return true;
    },

    // This is called if it has been decided that the SWF will not
    // run, and we should fall back to an HTML version
    fallbackToHtml: function()
    {
        // skip fallback if user opted to force Allurent application
        if (this.isForceAllurent()) return;

        // setup callback for backup attempt in case this call fails
        var sthis = this;
        // setTimeout(function () { sthis.fallbackToHtml(); }, this.fallbackRetryInterval);        
                    
        // only set failure cookie if not already set
        failval = arc.util.getCookie(this.qualificationCookie);
        if (failval == null)
        {
            // get identifier of missed milestone
            ttf = new Date().getTime() - this.scriptStartTime;
            failmsg = this.qualificationFailValue + "|" + 
                      this.disqualReason + "|" +
                      GetSwfVer() + "|" +
                      ttf + "|" +
                      navigator.userAgent;

            // Use a cookie to record the fact that we had to fallback
            arc.util.setCookie(this.qualificationCookie, failmsg);
            
            //Log Webtrends event recording failure and cause.
            dcsMultiTrack("DCSext.ApplicationLoadedIndicator", "FAIL",
                          "DCSext.FlashVersion", GetSwfVer(),
                          "DCSext.BrowserUserAgent", navigator.userAgent,
                          "DCSext.FailureReason", this.disqualReason, 
                          "DCSext.LoadTime", ttf,
                          "DCS.dcsuri", "",
                          "WT.ti", "",
                          "WT.si_n", "",
                          "WT.si_x", "",
                          "WT.mc_id", "",
                          "WT.pn_sku", "",
                          "WT.tx_u", "",
                          "WT.tx_e", "",
                          "DCSext.CompareQuantity", "");
              
        }

        document.location.href = this.getFallbackUrl();
    },

    // Returns the fallback URL that should be used if it is decided
    // that the SWF should not run.  Looks first for a query arg specifying the redirect
    // location.  If not found, determines redir location based on app launch mode.
    getFallbackUrl: function()
    {
        var redir = this.getArg(this.redirectParamName);
        if (redir == undefined)
        {
            if (this.isPlanMode()) return this.planRedirURL;
            else return this.defaultRedirURL;
        }
        return redir;
    },

    // Run the code from AC_OETags.js that starts the SWF
    startApplicationSwf: function()
    {
        //alert("RD: " + this.getFallbackUrl());
        // Extract the "#..." portion of the URL and use that as the flashVars
        urlArgs = this.getNavArgs();
	        
	    urlArgs = urlArgs.replace(";", "&");
        zip = arc.util.getCookie("wcmZipCodeCookie");
        AC_FL_RunContent(
            "src", this.applicationSwfLocation,
            "width", "" + this.applicationSwfWidth,
            "height", "" + this.applicationSwfHeight,
            "align", "middle",
            "id", this.applicationSwfId,
            "quality", "high",
            "bgcolor", "white",
            "name", this.applicationSwfId,
            "allowScriptAccess","sameDomain",
            "type", "application/x-shockwave-flash",
            "pluginspage", "http://www.adobe.com/go/getflashplayer",
            "flashVars", urlArgs + "&zip=" + zip + "&configUrl=" + this.configLocation
        );
        return document.getElementById(this.applicationSwfId);
    },

    // Called from the SWF application to indicate that it has hit one
    // of the startup milestones
    notifyApplicationSwfPreloaderProgress: function(bytesLoaded, bytesTotal)
    {
        var pct =
            Math.floor ((((bytesTotal) > 0.0 ? (bytesLoaded / bytesTotal) : 0.0) * 100.0) + .5);
        if (pct >= 75.0) {
            this.notifyApplicationSwfMilestoneHit("preloaderDownload-75%");
        }
        else if (pct >= 50.0) {
            this.notifyApplicationSwfMilestoneHit("preloaderDownload-50%");
        }
        else if (pct >= 25.0) {
            this.notifyApplicationSwfMilestoneHit("preloaderDownload-25%");
        }
        if (this.debuggingStatsEnabled) {
            var elem = document.getElementById("downloadProgress");
            elem.innerHTML = "" + bytesLoaded + " / " + bytesTotal + " (" + pct + "%)";
        }
    },

    // Called from the SWF application to indicate that it has hit one
    // of the startup milestones
    notifyApplicationSwfMilestoneHit: function(milestone)
    {
        // Find the index of this milestone
        var ix = -1;
        for (var i = 0; i < this.loadApplicationSwfMilestones.length; i++) {
            if (this.loadApplicationSwfMilestones[i].milestone == milestone) {
                ix = i;
            }
        }
        if (ix < 0) {
            // FIXME - what should happen here
            // alert ("Unknown milestone " + milestone);
        }
        else {
            // Make sure we have not gone backwards in milestones
            elapsed = new Date().getTime() - this.loadApplicationSwfMilestoneStartTime;
            if (ix >= this.loadApplicationSwfNextMilestoneIndex) {
                if (this.debuggingStatsEnabled) {
                    document.getElementById("milestoneElapsed-" + ix).innerHTML =
                        "" + elapsed + " msec";
                }
                this.loadApplicationSwfNextMilestoneIndex = ix + 1;
                this.waitForNextMilestone();
            }
        }
    },

    // Starts a timer running to wait for the next milestone to be hit
    waitForNextMilestone: function()
    {
        var ix = this.loadApplicationSwfNextMilestoneIndex;
        // See if we've finished all the milestones
        if (ix >= this.loadApplicationSwfMilestones.length) {
            this.notifyStartupComplete();
        }
        else {
            // Find the next milestone, see how much time is allocated
            // for it, and start the timer going.
            var milestone = this.loadApplicationSwfMilestones[ix];
            var stimeout = milestone.timeout;
            var sthis = this;
            setTimeout(function () { sthis.notifyApplicationSwfMilestoneTimeout(ix); },
                       stimeout);
            this.loadApplicationSwfMilestoneStartTime = new Date().getTime();
        }
    },

    // This is called when the timer for a milestone expires.  This
    // will check to see if the application has hit the specified
    // milestone - if not, it will fall back to the HTML application.
    notifyApplicationSwfMilestoneTimeout: function(milestoneIndex)
    {
        // See if the application has not yet reported hitting this milestone
        if (this.loadApplicationSwfNextMilestoneIndex <= milestoneIndex) {
            this.disqualReason = this.loadApplicationSwfMilestones[milestoneIndex].milestone + ":" +
                                 this.loadApplicationSwfMilestones[milestoneIndex].timeout;
            this.fallbackToHtml();
        }
    },

    // This is called when the application has completed all of its
    // startup milestones and is ready to be shown to the user.
    notifyStartupComplete: function()
    {
        // FIXME - do we want to record this success in a cookie, so
        // that we continue to use the SWF even if SWF conditions
        // become unfavorable in the future?

        totalelapsed = new Date().getTime() - this.scriptStartTime;
        
        // Log Webtrends event recording successful startup
        dcsMultiTrack("DCSext.ApplicationLoadedIndicator", "SUCCESS",
                      "DCSext.FlashVersion", GetSwfVer(),
                      "DCSext.BrowserUserAgent", navigator.userAgent,
                      "DCSext.FailureReason", "SUCCESS", 
                      "DCSext.LoadTime", totalelapsed,
                      "DCS.dcsuri", "",
                      "WT.ti", "",
                      "WT.si_n", "",
                      "WT.si_x", "",
                      "WT.mc_id", "",
                      "WT.pn_sku", "",
                      "WT.tx_u", "",
                      "WT.tx_e", "",
                      "DCSext.CompareQuantity", "");
    },

    // This is used for debugging - it emits the status area of HTML
    // that is used to display the downloading stats.
    emitDebuggingStats: function()
    {
        var str = "";
        str += "<li>Download Progress: <span id='downloadProgress'></span></li>";
        str += "<li><table border='border'>";
        str += "<tr><td></td><th>Milestone</th><th>Timeout</th><th>Completed In</th></tr>";
        str += "<tr><td></td><td>initStart</td><td>"+this.initTimeout+"</td><td id='initStart'></td></tr>";
        for (i = 0; i < this.loadApplicationSwfMilestones.length; i++) {
            str += "<tr><td>" +
                (i + 1) +
                "</td><td>" +
                this.loadApplicationSwfMilestones[i].milestone +
                "</td><td>" +
                this.loadApplicationSwfMilestones[i].timeout +
                " msec</td><td id='milestoneElapsed-" + i + "'></td></tr>";
        }
        str += "</table></li>";
        document.write(str);
        this.debuggingStatsEnabled = true;
    },
    
    // Retrieve the specified query arg or null if not found
    getArg: function(arg)
    {
        var querypairs = location.search.substring(1).split("&");
        for (var i=0; i<querypairs.length; i++)
        {
            var eq = querypairs[i].indexOf('=');
            if (eq == -1) continue;
            if (querypairs[i].substring(0,eq) == arg) return unescape(querypairs[i].substring(eq+1));
        }
    },
    
    // Return true if page is in "plan" mode; otherwise false
    isPlanMode: function()
    {
        return (this.getNavArgs().indexOf("mode=plan") != -1);
    },
    
    // Returns the navigation args if any, otherwise empty string
    getNavArgs: function()
    {
        urlParts = document.location.href.split("#", 2);
        return (urlParts.length >= 2) ? urlParts[1] : "";
    },
    
    // Returns true if user should be forced to HTML
    isForceHtml: function()
    {
        if (document.location.href.indexOf('arcForce=true') >= 0) return false;
        arcForce = arc.util.getCookie("ARCFORCE");
        return (document.location.href.indexOf('arcForce=false') >= 0 
                || (arcForce != null  && arcForce == "false") );
    },
    
    // Returns true if user should be forced to Allurent app
    isForceAllurent: function()
    {
        if (document.location.href.indexOf('arcForce=false') >= 0) return false;
        arcForce = arc.util.getCookie("ARCFORCE");
        return (document.location.href.indexOf('arcForce=true') >= 0 
                || (arcForce != null  && arcForce == "true") );
    },
    
    // Returns true if user has request to see debug info
    isEmitDebug: function()
    {
        return (document.location.href.indexOf('emitStats=true') >= 0);
    }

};

if (typeof(arc)=="undefined")
{
    var arc = Class.create({
        // version string
        version :"2.1.0"
    });
    
    Object.extend(arc,{
        version:"2.1.0",
        util:function(){}
        
    }); // end ARC object extend
    
    // UTILITIES
    Object.extend(arc.util, {
        cookiesAllowed:function() {
            setCookie('checkCookie', 'test', 1);
            if (arc.util.getCookie('checkCookie')) {
                arc.util.deleteCookie('checkCookie');
                return true;
            }
           return false;
        },
        setCookie:function(name,value,expires, options) {
            if (options===undefined) { options = {}; }
            if ( expires ) {
                var expires_date = new Date();
                expires_date.setDate(expires_date.getDate() + expires)
            }
            document.cookie = name+'='+escape( value ) +
                ( ( expires ) ? ';expires='+expires_date.toGMTString() : '')+
                ( ( options.path ) ? ';path=' + options.path : ';path=/' ) +
                ( ( options.domain ) ? ';domain=' + options.domain : '')+
                ( ( options.secure ) ? ';secure' : '');
        },
        getCookie:function( name ) {
            var start = document.cookie.indexOf( name + "=");
            var len = start + name.length + 1;
            if ( ( !start ) && ( name != document.cookie.substring( 0, name.length))){
                return null;
            }
            if ( start == -1 ) return null;
            var end = document.cookie.indexOf( ';', len );
            if ( end == -1 ) end = document.cookie.length;
            return unescape( document.cookie.substring( len, end ) );
        },
        deleteCookie:function( name, path, domain ) {
            if ( arc.util.getCookie( name ) ) document.cookie = name + '=' +
                ( ( path ) ? ';path=' + path : '') +
                ( ( domain ) ? ';domain=' + domain : '' ) +
                ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
        }
    });
} // end if arc == null 

function writeCartCookie(value)
{
    arc.util.setCookie("selectorCart", value);
}

function readCartCookie()
{
    return arc.util.getCookie("selectorCart");
}

function popWinSbs(url)
{
    if(url.indexOf("http://www.alltel.com/stepbystep/index.jsp") > -1)
    {
        popWin(url, 740, 510, 0);
    }
    else 
    {
        popWin(url, 838, 748, 0);
    }
}
