﻿var StorefrontInternalAPI, StorefrontScriptAPI, xmlHttp;

ContentDirect = {}
ContentDirect.UI = {}
ContentDirect.UI.Storefront = function () {
    this._TARGET_CONTAINER_ID = '__StorefrontContainer';
    this._TARGET_VERSION = '4.0.50524.0';
    this._MIN_VERSION = '1.0';
    this._INIT_XAP = '/ContentDirect.UI.StoreFront.Init.xap';
    this._RESOURCE_SL_SYNDICATED_ALT = 'Please click this image to go to the store.';
    this._RESOURCE_SL_INSTALL_ALT = 'Please install Silverlight Framework.';
    this._RESOURCE_SL_GET_ALT = 'Get Microsoft Silverlight';
    this._REQUEST_FORMAT = 'StorefrontHttpPostService.aspx?method=createInteraction&systemId={0}&interactionTypeCode={1}&country=USA&contextId=42&description={2}&contextData={3}';
    this._PARAM_FORMAT = '{0},NonSilverlightImageURL={1},WindowlessMode={2},Language={3},CustomResourcesXapLocation={4}';
    this._contentContainer = null;
    this._rawInitParams = null;
    this._initParams = null;
    this._browserType = null;
    this._apiStub = null;
    this._isInitialized = false;
}

ContentDirect.UI.Storefront.prototype = {
    get_isInitialized: function () {
        return this._isInitialized;
    },
    initialize: function () {
        if (!this.checkRequirements()) {
            alert('Not all the requirements have been met');
            return;
        }
        this.updateEmbedTag();
        this.startSilverlight();
        this._isInitialized = true;
    },
    end: function () {
        this._contentContainer.innerHTML = "";
        this._contentContainer = null;
        this._isInitialized = false;
    },
    updateEmbedTag: function () {
        try {
            if (null != window.parent && window.parent.window['BuildEmbedMode'] !== undefined) {
                var parentPath = window.parent.location.href.split('Preview.aspx')[0];
                var functionToRun = 'window.parent.BuildEmbedMode("' + this._rawInitParams + ',DelayLoadPlayer=' + this.getQuerystring('DelayLoadPlayer', '0') + ',DelayLoadPlayerImageUrl=' + this.getQuerystring('DelayLoadPlayerImageUrl', '') + ',XapLocation=' + parentPath + 'ClientBin","' + parentPath + '", true)';
                eval(functionToRun);
            };
        }
        catch (e) {
        }
    },
    checkRequirements: function () {
        //check if container exist with id '__StorefrontContainer'
        result = false;
        this._contentContainer = document.getElementById(this._TARGET_CONTAINER_ID);
        containerExist = (null != this._contentContainer);
        if (containerExist) {
            paramAttribute = this._contentContainer.attributes['initParams'];
            paramsExist = (null != paramAttribute);
            var rawParams = '';
            if (!paramsExist)
                rawParams = this.createParams();
            else
                rawParams = paramAttribute.value;

            this._rawInitParams = this.overrideSystemParams(rawParams);
            this._initParams = this.stripParams(this._rawInitParams, ',');
            result = true;
        }
        else
            result = false;

        return result;
    },
    createParams: function () {
        var systemParams = this.getSystemParams();

        formattedParams = String(this._PARAM_FORMAT).replace('{0}', systemParams);
        formattedParams = String(formattedParams).replace('{1}', null == document.getElementById('NonSilverlightImageURL') ? '' : document.getElementById('NonSilverlightImageURL').value);
        formattedParams = String(formattedParams).replace('{2}', null == document.getElementById('WindowlessMode') ? '' : document.getElementById('WindowlessMode').value);
        formattedParams = String(formattedParams).replace('{3}', null == document.getElementById('Language') ? '' : document.getElementById('Language').value);
        formattedParams = String(formattedParams).replace('{4}', null == document.getElementById('CustomResourcesXapLocation') ? '' : document.getElementById('CustomResourcesXapLocation').value);
        return formattedParams;
    },
    getParam: function (key) {
        return this._initParams[key];
    },
    stripParams: function (params, separator) {
        strippedParams = String(params).split(separator);
        paramList = new Array();
        for (var i = 0; i < strippedParams.length; i++) {
            param = strippedParams[i];
            paramList[String(param).split('=')[0]] = String(param).split('=')[1];
        }

        return paramList;
    },
    getSystemParams: function () {
        var systemParams = '';
        if (null != this._rawInitParams)
            systemParams = this._rawInitParams;
        else
            systemParams = document.getElementById('SystemParams').value;

        return systemParams;
    },
    overrideSystemParams: function (initParams) {
        params = initParams;
        try {
            var targetWindow = null;
            try {
                targetWindow = window.parent;
            }
            catch (e) {
                targetWindow = window;
            }

            if (null != targetWindow && null != targetWindow.document.location.href) {
                var queryString = targetWindow.document.location.href.split('?')[1];
                if (queryString) {
                    var qsList = String(queryString).split('&');
                    var counter = 0;
                    while (counter < qsList.length) {
                        var p = qsList[counter];
                        if (p) {
                            var pId = p.split('=')[0];
                            var pValue = p.split('=')[1];
                            var pIdPosition = String(params.toLowerCase()).search(pId.toLowerCase());
                            if (pIdPosition == 0
                                || String(params).substring(pIdPosition - 1, pIdPosition) == ',') {
                                var searchString = String(params).substring(pIdPosition, params.length);
                                var seachEnd = searchString.search(',');

                                sourceString = String(searchString.substring(0, seachEnd));

                                valueString = sourceString.split('=')[1];
                                targetString = String(sourceString).replace(valueString, pValue);
                                params = String(params).replace(sourceString, targetString);
                            }
                            else {
                                params = params + ',' + p;
                            }
                        }
                        counter++;
                    }
                }
            }
        }
        catch (e) {
            params = initParams;
        }
        return params;
    },
    getQuerystring: function (key, default_) {
        if (default_ == null) default_ = "";
        key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
        var qs = regex.exec(window.location.href);
        if (qs == null)
            return default_;
        else
            return qs[1];
    },
    includeSilverlight: function () {
        var e = window.document.createElement('script');
        e.setAttribute('type', 'text/javascript');
        e.setAttribute('src', 'Scripts\Silverlight.debug.js');
        window.document.body.appendChild(e);
    },
    startSilverlight: function () {
        var isSyndicateMode = this.getQuerystring('DelayLoadPlayer', '0') == '1' || this.getParam('DelayLoadPlayer') == '1';
        var isSyndicateNoClickMode = this.getQuerystring('DelayLoadPlayer', '0') == '2' || this.getParam('DelayLoadPlayer') == '2';
        this._contentContainer.style.position = "relative";
        this._contentContainer.style.width = this.getWidth();
        this._contentContainer.style.height = this.getHeight();
        
        if (!isSyndicateMode) {
            if (!isSyndicateNoClickMode) {
                this.loadStorefront();
            }
            else
                this.startSyndicateNoClickMode();
        }
        else
            this.startSyndicateMode();
    },
    startSyndicateNoClickMode: function () {
        var syndicatedImage = this.getParam('DelayLoadPlayerImageUrl') == undefined ? this.getQuerystring('DelayLoadPlayerImageUrl', null) : this.getParam('DelayLoadPlayerImageUrl');
        var baseImage = new Image();
        baseImage.src = syndicatedImage;

        baseImage.style.cursor = 'default';

        var baseE = window.document.createElement('div');
        if (String(this.getBrowserType()).toLowerCase().search('firefox') == -1) {
            baseE.style.width = "100%";
            baseE.style.height = "100%";
        }
        baseE.style.position = "absolute";
        baseE.style.width = "100%";
        baseE.style.textAlign = "center";
        baseE.style.left = "0px";
        baseE.style.top = "0px";
        baseE.style.zIndex = "0";
        baseE.appendChild(baseImage);
        StorefrontInternalAPI._contentContainer.appendChild(baseE);
    },
    startSyndicateMode: function () {
        var syndicatedImage = this.getParam('DelayLoadPlayerImageUrl') == undefined ? this.getQuerystring('DelayLoadPlayerImageUrl', null) : this.getParam('DelayLoadPlayerImageUrl');
        var baseImage = new Image();
        baseImage.src = syndicatedImage;
        baseImage.onclick = StorefrontInternalAPI.loadStorefront();
        baseImage.style.cursor = 'hand';
        baseImage.style.cursor = 'pointer';

        var baseE = window.document.createElement('div');
        if (String(this.getBrowserType()).toLowerCase().search('firefox') == -1) {
            baseE.style.width = "100%";
            baseE.style.height = "100%";
        }
        baseE.style.width = "100%";
        baseE.style.textAlign = "center";
        baseE.style.position = "absolute";
        baseE.style.left = "0px";
        baseE.style.top = "0px";
        baseE.style.zIndex = "0";
        baseE.appendChild(baseImage);
        StorefrontInternalAPI._contentContainer.appendChild(baseE);
    },
    loadStorefront: function () {
        this.loadStorefront();
    },
    getXAPLocation: function () {
        xapLocation = '';
        if (null != document.getElementById('XapLocation'))
            xapLocation = document.getElementById('XapLocation').value;
        else
            xapLocation = this._initParams['XapLocation'];

        return xapLocation;
    },
    loadStorefront: function () {
        if (null != Silverlight && Silverlight.isInstalled(this._MIN_VERSION)) {
            xapfile = StorefrontInternalAPI.getXAPLocation() + StorefrontInternalAPI._INIT_XAP;
            getSilverlightMethodCall = 'Silverlight.getSilverlight("' + StorefrontInternalAPI._TARGET_VERSION + '");';
            useWindowless = StorefrontInternalAPI.getParam('WindowlessMode');
            language = StorefrontInternalAPI.getParam('Language');
            parameters = StorefrontInternalAPI.getSystemParams();

            Silverlight.createObjectEx({
                source: xapfile,
                parentElement: StorefrontInternalAPI._contentContainer,
                id: 'silverlightMain',
                properties: params = {
                    height: StorefrontInternalAPI.getHeight(),
                    width: StorefrontInternalAPI.getWidth(),
                    background: 'Black',
                    alt: 'PluginImage',
                    autoUpgrade: 'true',
                    minRuntimeVersion: StorefrontInternalAPI._TARGET_VERSION,
                    windowless: useWindowless,
                    version: StorefrontInternalAPI._MIN_VERSION,
                    enableGPUAcceleration: 'true',
                    enableHTMLAccess: 'true'
                },
                events: {},
                initParams: parameters,
                context: "Being loaded"
            });
        }
        else
            this.loadSilverlightInstallation();
    },
    getHeight: function () {
        var result = StorefrontInternalAPI.getParam('Height');
        if (result == '0')
            result = '100%';
        else
            result = result + 'px';

        return result;
    },
    getWidth: function () {
        var result = StorefrontInternalAPI.getParam('Width');
        if (result == '0')
            result = '100%';
        else
            result = result + 'px';
        return result;
    },
    loadSilverlightInstallation: function () {
        var baseImage = new Image();
        baseImage.alt = StorefrontInternalAPI._RESOURCE_SL_INSTALL_ALT;

        var source = null;
        //Fullplayer = 3, SurfacePlayer = 4
        if (StorefrontInternalAPI.getParam('NonSilverlightImageURL'))
            source = StorefrontInternalAPI.getParam('NonSilverlightImageURL');
        else {
            source = '3' == StorefrontInternalAPI.getParam('PlayerLayoutTypeCode') || '4' == StorefrontInternalAPI.getParam('PlayerLayoutTypeCode')
				    ? 'http://hwcdn.net/n8v4q7r8/cds/Player/LargePlayerNonSilverlight.jpg'
				    : 'http://hwcdn.net/n8v4q7r8/cds/Player/NonSilverlight.jpg';
        }
        baseImage.src = source;

        var baseE = window.document.createElement('div');
        if (String(this.getBrowserType()).toLowerCase().search('firefox') == -1) {
            baseE.style.width = "100%";
            baseE.style.height = "100%";
        }
        baseE.style.position = "absolute";
        baseE.style.left = "0px";
        baseE.style.top = "0px";
        baseE.style.zIndex = "0";
        baseE.style.maxHeight = "428px";
        baseE.appendChild(baseImage);
        StorefrontInternalAPI._contentContainer.innerHTML = "";
        StorefrontInternalAPI._contentContainer.appendChild(baseE);

        //Create plugin image
        var pluginImage = new Image();
        pluginImage.alt = StorefrontInternalAPI._RESOURCE_SL_GET_ALT;
        pluginImage.src = 'http://go.microsoft.com/fwlink/?LinkId=108181';
        pluginImage.style.marginTop = '30px';
        pluginImage.style.marginRight = '30px';
        pluginImage.style.cursor = 'pointer';
        pluginImage.onload = StorefrontInternalAPI.plugin_load;
        pluginImage.onclick = StorefrontInternalAPI.plugin_click;

        var e = window.document.createElement('div');
        e.style.styleFloat = 'right';
        e.style.cssFloat = 'right';
        e.style.position = 'relative';
        e.style.zIndex = '1';

        e.appendChild(pluginImage);
        StorefrontInternalAPI._contentContainer.appendChild(e);
    },
    getRequestURL: function (code, description) {

        var domain = StorefrontInternalAPI.getXAPLocation();
        var url = domain.replace('ClientBin', '');

        requestFormat = String(this._REQUEST_FORMAT).replace('{0}', this.getParam('SystemId'));
        requestFormat = String(requestFormat).replace('{1}', code);
        requestFormat = String(requestFormat).replace('{2}', description);
        requestFormat = String(requestFormat).replace('{3}', this.getBrowserType());

        return url + requestFormat;
    },
    plugin_click: function (e) {
        StorefrontInternalAPI.loadUrl(StorefrontInternalAPI.getRequestURL('502', 'Silverlight+Installed'));
        Silverlight.getSilverlight();
    },
    plugin_load: function (e) {
        if (!Silverlight.isInstalled(StorefrontInternalAPI._TARGET_VERSION)) {
            StorefrontInternalAPI.loadUrl(StorefrontInternalAPI.getRequestURL('501', 'Install+SL+Prompt'));
        }
    },
    loadXMLDoc: function (url) {
        xmlHttp = null;
        StorefrontInternalAPI.createXMLHttp();
        if (xmlHttp != null) {
            xmlHttp.open('GET', url, true);
            xmlHttp.send(null);
        }
    },
    loadUrl: function (url) {
        window.document.getElementById('__CDHTTPPOST__').setAttribute('src', url);
    },
    createXMLHttp: function () {
        if (window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            try {
                xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
            }
            catch (e) {
                try {
                    xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
                }
                catch (e) {
                    xmlHttp = null;
                }
            }
        }

        if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
            xmlHttp = new XMLHttpRequest();
        }
    },
    getBrowserType: function () {
        if (null != this.browserType) return this._browserType;

        var browser = "";
        if (navigator.userAgent.indexOf("MSIE ") > -1) {
            browser = this.getBrowserTypeEx(navigator.userAgent.indexOf("MSIE "), 5);
            browser = browser.replace(";", "");
        }
        else if (navigator.userAgent.indexOf("Firefox") > -1) {
            browser = this.getBrowserTypeEx(navigator.userAgent.indexOf("Firefox"), 0);
        }
        else if (navigator.userAgent.indexOf("Safari") > -1) {
            browser = this.getBrowserTypeEx(navigator.userAgent.indexOf("Safari"), 0);
        }
        else if (navigator.userAgent.indexOf("Opera") > -1) {
            browser = this.getBrowserTypeEx(navigator.userAgent.indexOf("Opera"), 0);
        }
        else if (navigator.userAgent.indexOf("Chrome") > -1) {
            browser = this.getBrowserTypeEx(navigator.userAgent.indexOf("Chrome"), 0);
        }
        else {
            browser = navigator.userAgent;
        }
        if (browser != null) {
            browser = browser.replace("/", " ");
        }

        this._browserType = browser;

        return browser;
    },
    getBrowserTypeEx: function (startIdx, offset) {
        if (navigator.userAgent.indexOf(" ", startIdx + offset) > -1) {
            return navigator.userAgent.substr(startIdx, navigator.userAgent.indexOf(" ", startIdx + offset) - startIdx);
        }
        else {
            return navigator.userAgent.substr(startIdx);
        }
    },
    getDRMChallenge: function () {
        try {
            var netobj = new ActiveXObject('DRM.GetLicense.1');
            var challenge = netobj.GetSystemInfo();
            return (challenge);
        }
        catch (e) {
            return e;
        }
    },
    installDRMLicense: function (license) {
        try {
            var netobj = new ActiveXObject('DRM.GetLicense.1');
            netobj.StoreLicense(license);
            return true;
        }
        catch (e) {
            return e;
        }
    },
    setSessionID: function (s) {
        this._initParams['SessionID'] = s;
    },
    logoutSubscriber: function (e, sessionId) {
        if (null == sessionId) {
            sessionId = StorefrontInternalAPI._initParams['SessionID'];
        }
        var domain = StorefrontInternalAPI.getXAPLocation();
        var url = '';
        if (domain == 'ClientBin')
            url = 'StorefrontHttpPostService.aspx?method=logoutSubscriber&sessionId=' + sessionId;
        else
            url = domain.replace('ClientBin', '') + 'StorefrontHttpPostService.aspx?method=logoutSubscriber&sessionId=' + sessionId;

        StorefrontInternalAPI.loadUrl(url);
    },
    loadXMLDoc_stateChange: function () {
    },
    setPlayerReady: function (isReady) {
        if (isReady && StorefrontScriptAPI) {
            try {
                //this call has caused error in IE in certain environments, 
                //we need to figure out why the Content is not always available.
                //For now I am trapping this exception so that the player loads w/o the JS bridge functionality.
                this._apiStub = document.getElementById('silverlightMain').Content.Page.GetScriptStub();
                StorefrontScriptAPI.initialize(this._apiStub);
            }
            catch (e)
            { }
        }
    },
    raiseClientEvent: function (type, target, keyword) {
        if (null != this.Tools)
            StorefrontScriptAPI.EventOccured(type, target, keyword);
    }
};

    ContentDirect.UI.Storefront.Tools = function() { }
    ContentDirect.UI.Storefront.Tools.prototype = {
        copyToClipboard: function(s) {
            if (window.clipboardData && clipboardData.setData) {
                clipboardData.setData("Text", s);
            }
            else {
                // You have to sign the code to enable this or allow the action in about:config by changing
                //user_pref("signed.applets.codebase_principal_support", true);
                try {
                    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                } catch (e) {
                    alert("Permission to read file was denied.");
                }

                var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
                if (!clip) return;

                // create a transferable
                var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
                if (!trans) return;

                // specify the data we wish to handle. Plaintext in this case.
                trans.addDataFlavor('text/unicode');

                // To get the data from the transferable we need two new objects
                var str = new Object();
                var len = new Object();

                str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);

                var copytext = meintext;

                str.data = copytext;

                trans.setTransferData("text/unicode", str, copytext.length * [[[[2]]]]);

                var clipid = Components.interfaces.nsIClipboard;

                if (!clip) return false;

                clip.setData(trans, null, clipid.kGlobalClipboard);
            }
        }
    }

    ActionType = function() {
        this.Popup = 0;
    };

    //Client API
    ContentDirect.UI.Storefront.ClientAPI = function() {
        this._isReady = false;
        this._pointer = null;
        this._actionCallBack = this._actionCallBack;
    };
    ContentDirect.UI.Storefront.ClientAPI.prototype = {
        get_IsReady: function () {
            return this._isReady;
        },
        initialize: function (pointer) {
            this._isReady = true;
            this._pointer = pointer;
        },
        popupProduct: function (id) {
            this.Popup('product', id);
        },
        popupPerson: function (name) {
            this.Popup('person', name);
        },
        popupCategoryBrowse: function (category) {
            this.Popup('category', category);
        },
        Play: function (target, keyword) {
            try {
                if (this._isReady)
                    this._pointer.Trigger('play', target, keyword)
                else
                    alert('Player is not ready to process your action');
            }
            catch (e) {
                alert('Cannot process your request');
            }
        },
        Popup: function (target, keyword) {
            try {
                if (this._isReady)
                    this._pointer.Trigger('popup', target, keyword)
                else
                    alert('Player is not ready to process your action');
            }
            catch (e) {
                alert('Cannot process your request');
            }
        },
        Search: function (keyword) {
            try {
                if (this._isReady)
                    this._pointer.Trigger('search', 'all', keyword)
                else
                    alert('Player is not ready to process your action');
            }
            catch (e) {
                alert('Cannot process your request');
            }
        },
        RegisterEventCallback: function (func) {
            try {
                if (null != func)
                    this._actionCallBack = func;
            }
            catch (e) {
            }
        },
        EventOccured: function (type, target, keyword) {
            try {
                if (null == this._actionCallBack && window['StorefrontEventListner'] != undefined)
                    this.RegisterEventCallback("StorefrontEventListner");

                if (null != this._actionCallBack) {
                    eval(this._actionCallBack + "('" + type + "','" + target + "','" + keyword + "')");
                }
            }
            catch (e) {
            }
        },
        LoadStorefront: function () {
            try {
                if (this._isReady)
                    this._pointer.Trigger('loadStorefront');
                else
                    alert('Player is not ready to process your action');
            }
            catch (e) {
            }
        }


    };

    function AddLoadEvent(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                if (oldonload) {
                    oldonload();
                }
                func();
            }
        }
    }

    function InitializeStorefrontAPI() {
        StorefrontInternalAPI = new ContentDirect.UI.Storefront();
        StorefrontInternalAPI.Tools = new ContentDirect.UI.Storefront.Tools();
        StorefrontInternalAPI.initialize();

        if (ContentDirect.UI.Storefront.ClientAPI) {
            StorefrontScriptAPI = new ContentDirect.UI.Storefront.ClientAPI();            
            StorefrontScriptAPI.Tools = StorefrontInternalAPI.Tools;
        }

        //This is a workaround for Safari being crashed during logout subscriber;        
        if (null != navigator.vendor) {
            var oldonUnload = window.logoutSubscriber;
            var exitFunc = StorefrontInternalAPI.logoutSubscriber;
            if (typeof window.onbeforeunload != 'function') {
                window.onbeforeunload = exitFunc;
            } else {
                window.onbeforeunload = function() {
                    if (oldonUnload) {
                        oldonUnload();
                    }
                    exitFunc();
                }
            }
        }
        else
            window.onbeforeunload = StorefrontInternalAPI.logoutSubscriber;

        //Use this iframe to make all the http service calls (no response needed)
        var e = window.document.createElement('iframe');
        e.setAttribute('width', '0px');
        e.setAttribute('height', '0px');
        e.setAttribute('id', '__CDHTTPPOST__');
        window.document.body.appendChild(e);
    }

    //Start here when window loads
    AddLoadEvent(InitializeStorefrontAPI);

    function TrackPage(account, url) {
        var pageTracker = _gat._getTracker(account);
        pageTracker._trackPageview(url);
    }
