$.extend(MarketWatch.Video, function() {

    var _getPlayerDomain = function(queryStr, defaultValue) {

        var quaryVal;
        var query = window.location.search.substring(1);
        var parms = query.split('&');

        for (var i = 0; i < parms.length; i++) {
            var pos = parms[i].indexOf('=');
            if (pos > 0) {
                var key = parms[i].substring(0, pos);
                if (queryStr.toLowerCase() == key.toLowerCase()) {
                    quaryVal = parms[i].substring(pos + 1);
                    break;
                }
            }
        }
        if (quaryVal == "undefined" || quaryVal == null || quaryVal == '') {
            quaryVal = (defaultValue) ? defaultValue : quaryVal;
        }
        return quaryVal;
    };
    return {
        getPlayerDomain: _getPlayerDomain
    }
} ()
)

_doEventDispatch = function(elId) {
    var evt, el = document.getElementById(elId);
    if (document.createEvent) {
        evt = document.createEvent("MouseEvents");
        if (evt.initMouseEvent) {
            evt.initMouseEvent("click", true, true, window,
      0, 0, 0, 0, 0, false, false, false, false, 0, null);
        } else {
            evt = false;
        }
    }
    (evt) ? el.dispatchEvent(evt) : (el.click && el.click());
}

var cdnDomain = "http://" + MarketWatch.Video.getPlayerDomain("playerdomain", "s.marketwatch.com");

Array.prototype.indexOf = function(value) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == value) {
            return i;
        }
    }
    return -1;
}

//var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();
/*jslint undef:true*/
/*global $,AT_VARS,alert,document,navigator,swfobject,unescape,window,screen*/
/* Global namespace setup */
if (typeof dj == "undefined") {
    var dj = {};
}
if (typeof dj.widget == "undefined") {
    dj.widget = {};
}
if (typeof dj.widget.video == "undefined") {
    dj.widget.video = {};
}

if (!window.console) {
    window.console = {};
    window.console.log = function() {
    }
}

var attic;

dj.widget.video.video = $.klass({
    initialize: function(args, objName) {
        this.usrActnHash = {
            '': this.handleResponse,
            'toBrowse': this.handleBrowsingResults,
            'toSearch': this.handleSearchResults,
            'current': this.handleCurrent,
            'next': this.handleNext
        };

        attic = this;

        this.domainName = 'marketwatch'; //wsj,barrons,marketwatch
        //swfobject.addParam("allowScriptAccess","always");
        this.embedConfigURL = "http://wsj.vo.llnwd.net/o28/players/";
        this.microPlayers = [];
        this.microPlayersObjects = {};
        this.videoIdMicroPlayerIdMap = {};
        this.popUpWindow = ''; //Name of the pop up window to set focus
        //File paths
        this.flashPlayerPath = cdnDomain + "/media/swf/";
        this.collectionsXMLPath = "content/video/";
        this.videoCenterPageUrl = "/video";

        this.popUpPageUrl = videoSiteRoot + 'video/popup/index';
        //this.popUpPageUrl = '0_0_Neeki_PopUp.html'; //For testing popup at local system
        this.objName = objName;
        this.videoPlayerDivId = '#video_player';
        this.sideNavUlId = '#video_sidenav';
        this.nextVideoDivId = '#next_video';
        this.videoResultsDivId = '#video_results';
        this.searchDivId = 'video_search';
        this.advertisementDivId = 'advertisement';
        this.collectionsSelectId = 'collectionsSelectId';
        this.videoSummaryDivId = '#video_headline';
        this.registeredVideosDivId = 'registered_videos';
        //DIV ids
        if (this.isNotBlankOrNull(args)) {
            this.videoPlayerDivId = args.videoPlayerDivId ? args.videoPlayerDivId : 'video_player';
            this.sideNavUlId = args.sideNavUlId ? args.sideNavUlId : '#video_sidenav';
            this.nextVideoDivId = args.nextVideoDivId ? args.nextVideoDivId : '#next_video';
            this.videoResultsDivId = args.videoResultsDivId ? args.videoResultsDivId : '#video_results';
            this.searchDivId = args.searchDivId ? args.searchDivId : 'video_search';
            this.advertisementDivId = args.advertisementDivId ? args.advertisementDivId : 'advertisement';
            this.videoSummaryDivId = args.videoSummaryDivId ? args.videoSummaryDivId : '#video_headline';
            this.registeredVideosDivId = args.registeredVideosDivId ? args.registeredVideosDivId : '';
        }

        this.xmlDoc = '';
        this.defaultCollectionName = 'markets'; //'investing';

        //Objects from xml parsing
        this.collectionNamesArray = [];
        this.subcollectionsObject = {};

        this.collectionObjects = {};

        //Current and next video id
        this.currentlyPlayingVideoId = '';
        this.currentlyPlayingVideoIds = [];
        this.currentlyPlayingCollection = '';
        this.currentlyPlayingSubCollection = '';
        this.nextVideoId = '';

        // visible collection & subcollection id
        this.visibleCollectionId = '';
        this.visibleSubCollectionId = '';

        //Search variable
        this.sortOrder = 'relevancy'; //Default is kept as relevancy
        this.currentSearchText = '';
        this.isVideoResultsInSideNav = false;

        //JSON objects - 
        this.currentPlayingJsonObject = {};
        this.currentBrowsingJsonObject = {};
        this.currentSearchJsonObject = {};
        this.currentVideoDetailsJsonObject = {};
        this.nextVideoDetailsJsonObject = {};

        //Registered videos on article page
        this.registeredVideos = [];
        this.registeredVideosIds = [];
        this.playFromRegisteredVideos = false;
        this.relatedVideosCollection = ''; //collection of the 1st video in the article page.
        //pagination
        //this.lastPageNumber = 1;
        //this.currentPageNumber = 1;
        //this.browsingPageNumber = 1;
        this.pageSize = 12;
        // Default - toPlay - blank, toSearch, toBrowse
        this.userAction = '';

        //source application
        this.sourceApplicationName = '';

        // Auto play - 
        this.browsingGroup = "collection";
        this.playingGroup = "collection";
        this.skipCollection = true;

        //Article page bookmark
        this.bookMarkedId = '';
        this.bookMarkedLocation = '';

        // hacky sponsored stuff
        this.sponsoredBannerMarkup = '<div style="border-bottom:solid #cccccc 1px; position:relative; height:25px"><div style="position:absolute; left:5px; top:5px; font-size:0.8em; font-weight:bold;"><a href="/video">&#171; Back to MarketWatch Video</a></div><div style="position:absolute; left:45%; top:5px; font-size:0.8em">Special Advertiser Feature</div></div><div><a href="http://ad.doubleclick.net/click;h=v2|3BA3|0|0|%2a|w;218975212;0-0;0;42162463;31-1|1;32417616|32435492|1;;%3fhttps://us.etrade.com/e/t/home?SC=NPNM7SW&ch_id=D&s_id=MRKWTCH&c_id=LGSTDBT&o_id=100" target="_blank"><img alt="etrade-logo" style="float: right;" src="http://i.marketwatch.com/_newsimages/misc/etrade-140x31.png"/></a></div>';
        this.sponsoredAdMarkup = '<a target="_blank" href="http://ad.doubleclick.net/click;h=v2|3BCE|0|0|%2a|s;220115019;0-0;0;43733456;31-1|1;34527735|34545613|1;;%3fhttps:/us.etrade.com/e/t/investingandtrading/newtoinvesting?SC=NPNM7SW&ch_id=D&s_id=MRKWTCH&c_id=HURT&o_id=100"><div style="cursor: pointer; height: 280px; width: 363px; margin: 10px; background: #000 no-repeat center center url(http://i.marketwatch.com/_newsimages/misc/eTrade-StopNewLook-300x250.gif)"></div></a>';
    },

    loadVideo: function(id, sourceApplicationName, domainName, section, subsection) {
        if (this.isNotBlankOrNull(domainName)) {
            this.domainName = domainName;
        }
        this.sourceApplicationName = sourceApplicationName;
        if (this.isNotBlankOrNull(id)) {
            if (id.indexOf('{') == -1) {
                this.currentlyPlayingVideoId = '{' + id + '}';
            }
            else {
                this.currentlyPlayingVideoId = id;
            }
        }

        if (section) {
            this.visibleCollectionId = section;
        }

        if (subsection) {
            this.visibleSubCollectionId = subsection;
        }
        if (this.IsLatestFlashPlayer()) {
            this.createFlashPlayer();
        }
        else {//html 5
            this.continueLoadVideo(); // do this on page load
        }


    },
    IsLatestFlashPlayer: function() {
        //check if html5 is forced
        var query = window.location.search.substring(1);
        var parms = query.split('&');
        for (var i = 0; i < parms.length; i++) {
            var pos = parms[i].indexOf('=');
            if (pos > 0) {
                var key = parms[i].substring(0, pos);
                if ("html5" == key.toLowerCase()) {
                    if (parms[i].substring(pos + 1) == 'true');
                    return false;
                }
            }
        }

        if (swfobject.getFlashPlayerVersion().major < 9) {
            this.nonSupportingFlashPlayer(this.videoPlayerDivId);
            return false;
        }
        return true;

    },

    continueLoadVideo: function() {

        this.loadCollectionsDoc(videoSiteRoot + attic.collectionsXMLPath);

        this.parseInformationFromXmlDoc();

        if (this.sourceApplicationName == 'articlePage') {
            var vObj = '';
            if (this.isNotBlankOrNull(this.currentlyPlayingVideoId)) {
                vObj = this.registeredVideos[this.registeredVideosIds.indexOf(this.currentlyPlayingVideoId)];
                this.playVideoByParam(vObj);
            }
            else
                if (this.isNotBlankOrNull(this.bookMarkedId)) {
                this.currentlyPlayingVideoId = this.bookMarkedId;
                vObj = this.registeredVideos[this.registeredVideosIds.indexOf(this.currentlyPlayingVideoId)];
                vObj.seekTime = this.bookMarkedLocation;
                this.playVideoByParam(vObj);
            }
            else {
                vObj = this.registeredVideos[0];
                this.currentlyPlayingVideoId = vObj.id;
                this.playVideoByParam(vObj);
            }

            this.relatedVideosCollection = this.isNotBlankOrNull(this.registeredVideos[0]['wsj-section']) ? this.registeredVideos[0]['wsj-section'] : this.defaultCollectionName;
            this.currentlyPlayingCollection = this.registeredVideos[0]['wsj-section'];
            this.getVideos(this.validateContentUrl(this.collectionObjects[this.currentlyPlayingCollection].contentUrl) + '&count=60', '', false); //to-do
        }
        else {

            if (typeof AT_VARS != 'undefined' && AT_VARS.baseDocId) {
                this.currentlyPlayingVideoId = '{' + AT_VARS.baseDocId + '}';
            }
            //Logic for Initial play in Video center STARTS
            if (this.isNotBlankOrNull(this.currentlyPlayingVideoId)) {
                this.playVideoByVideoId(this.currentlyPlayingVideoId);
                //currentVideoDetailsJsonObject - param set in playVideoByVideoId
                var channelName = this.currentVideoDetailsJsonObject['mw-channel'];
                var subchannelName = this.currentVideoDetailsJsonObject['mw-subchannel'];
                var channelObject = this.channelObjectByName(channelName);
                var subchannelObject = this.channelObjectByName(subchannelName);

                this.currentlyPlayingCollection = channelObject.urlkey;

                var isSponsored = this.isVideoSponsored();
                // So ISHY.  It's okay though, this is only for the promotion.
                if (isSponsored) {
                    this.currentlyPlayingCollection = "etrade";
                }

                if (channelName !== subchannelName && subchannelObject !== void 0) {
                    this.currentlyPlayingSubCollection = subchannelObject.urlkey;
                }

                //Then make a call to getVideos with the content url of collection name or subcollection name
                if (this.isNotBlankOrNull(this.currentlyPlayingSubCollection)) {
                    this.visibleCollectionId = this.collectionNameForSubcollection(this.currentlyPlayingSubCollection);
                    this.currentlyPlayingCollection = this.visibleCollectionId;
                    this.getVideos(this.validateContentUrl(this.collectionObjects[this.currentlyPlayingSubCollection].contentUrl) + '&count=60', '', false);
                    //this.updateSideNavAppearance('subcollection',this.currentlyPlayingSubCollection);
                }
                else {
                    if (!this.isNotBlankOrNull(this.currentlyPlayingCollection)) {
                        this.currentlyPlayingCollection = this.defaultCollectionName;
                    }
                    this.getVideos(this.validateContentUrl(this.collectionObjects[this.currentlyPlayingCollection].contentUrl) + '&count=60', '', false);
                }
            }
            else {
                this.currentlyPlayingCollection = this.defaultCollectionName;

                if (this.visibleCollectionId != '' && (this.collectionObjects[this.visibleCollectionId]) !== (void 0)) {
                    this.currentlyPlayingCollection = this.collectionObjects[this.visibleCollectionId].urlkey;
                }

                if (this.visibleSubCollectionId != '' && (this.collectionObjects[this.visibleSubCollectionId]) !== (void 0)) {
                    this.currentlyPlayingSubCollection = this.collectionObjects[this.visibleSubCollectionId].urlkey;
                    this.visibleCollectionId = this.collectionObjects[this.currentlyPlayingSubCollection].parent.urlkey;
                    this.currentlyPlayingCollection = this.visibleCollectionId;
                }

                if (this.isNotBlankOrNull(this.currentlyPlayingSubCollection)) {
                    this.getVideos(this.validateContentUrl(this.collectionObjects[this.currentlyPlayingSubCollection].contentUrl) + '&count=60', '', false);
                }
                else {
                    this.getVideos(this.validateContentUrl(this.collectionObjects[this.currentlyPlayingCollection].contentUrl) + '&count=60', '', false);
                }

                if (this.currentPlayingJsonObject.items && this.currentPlayingJsonObject.items.length > 0) {
                    this.currentlyPlayingVideoId = this.currentPlayingJsonObject.items[0].id;
                    this.playVideoByVideoId(this.currentlyPlayingVideoId);
                }
            }
        }
        //Logic for Initial play in Video center ENDS

        //alert(this.collectionObjects[this.currentlyPlayingCollection]);

        this.populateSideNav();
        //In the begining Playing variables are set as browsing variables
        if (this.isNotBlankOrNull(this.currentlyPlayingSubCollection)) {
            //this.getVideos(this.contentUrlsObject[this.currentlyPlayingSubCollection]);
            this.updateSideNavAppearance('subcollection', this.currentlyPlayingSubCollection, false, true);
            this.visibleSubCollectionId = this.currentlyPlayingSubCollection;
            this.browsingGroup = "subcollection";
            this.playingGroup = "subcollection";
        }
        else {
            //this.getVideos(this.contentUrlsObject[this.currentlyPlayingCollection]);
            this.updateSideNavAppearance('collection', this.currentlyPlayingCollection, false, true);
            this.visibleCollectionId = this.currentlyPlayingCollection;
        }
        this.currentBrowsingJsonObject = this.currentPlayingJsonObject;

        if (this.sourceApplicationName == 'articlePage' && this.registeredVideosIds.length > 0) {
            this.createRegisteredVideosThumbnails();
            this.updateVideoThumbnailVisual('', 'reg' + this.currentlyPlayingVideoId);
        }
        this.createNextVideo();
        this.createSearch();
        this.createAdvertisementFramework();
        //this.createAdvertisement('', '');
        this.populateMoreVideos(1);
        this.loadPagination(1);
        this.updateRssFeed((this.visibleSubCollectionId !== '') ? this.visibleSubCollectionId : this.visibleCollectionId);

        this.updateSponsoredDisplayItemStates();
    },
    validateContentUrl: function(contentUrl) {
        if (this.isNotBlankOrNull(contentUrl)) {
            return contentUrl;
        }
        else {
            this.visibleCollectionId = this.defaultCollectionName;
            this.currentlyPlayingCollection = this.defaultCollectionName;
            return this.collectionObjects[this.defaultCollectionName].contentUrl;
        }
    },
    channelObjectByName: function(channelName) {
        for (var o in this.collectionObjects) {
            if (this.collectionObjects[o].name === channelName) {
                return this.collectionObjects[o];
            }
        }
    },
    createAdvertisementFramework: function() {
        if (this.advertisementDivId) {
            if (swfobject.getFlashPlayerVersion().major >= 9) {
                var dim = { w: "363", h: "280" };
                swfobject.embedSWF(this.flashPlayerPath + "adPlayer.swf", this.advertisementDivId, dim.w, dim.h, "9.0.0", "", {
                    'objName': this.getName(),
                    'movieWidth': dim.w,
                    'movieHeight': dim.h,
                    'host': location.host
                }, {
                    allowscriptaccess: "always",
                    wmode: "transparent"
                }, {});
            }
            else {
                this.nonSupportingFlashPlayer(this.advertisementDivId);
            }
        }
    },
    nonSupportingFlashPlayer: function(divId) {
        var str = '';
        str += '<table width="75%" cellspacing="1" cellpadding="2" bordercolor="#336699" border="2">';
        str += '<tbody>';
        str += '<tr>';
        str += '</tr>';
        str += '<tr>';
        str += '<td align="left">';
        str += '<span style="font-size: 12px;">';
        str += 'The version of Adobe Flash Player required to view this interactive has not been found.';
        str += '<br/>';
        str += 'To enjoy our complete interactive experience, please download a free copy of the latest version of Adobe Flash Player ';
        str += '<b>';
        str += '<a target="_blank" href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash">here.</a>';
        str += '</b>';
        str += '</span>';
        str += '</td>';
        str += '</tr>';
        str += '</tbody>';
        str += '</table>';


        $("#" + divId).html(str);
        $('.loadingPlaceholder').hide();

    },
    collectionNameForSubcollection: function(subCol) {
        return this.collectionObjects[subCol].parent.urlkey;
    },
    pauseMicroPlayers: function() {
        try {
            for (var index = 0, len = this.microPlayers.length; index < len; ++index) {
                swfobject.getObjectById(this.microPlayers[index]).pauseVideo();
            }
        }
        catch (e) {
            console.error("Error while pausing microPlayers. " + e.message);
        }
    },
    setBookMark: function() {
        try {
            this.bookMarkedId = this.currentlyPlayingVideoId; // current playing video id
            this.bookMarkedLocation = Math.floor(swfobject.getObjectById("flashPlayer").getSeek()); // current playing video location
            swfobject.getObjectById("flashPlayer").pauseVideo();
        }
        catch (e) {
            console.error("Error while setting the bookmark. " + e.message);
        }
    },
    getUrlParam: function(srcUrl, name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(srcUrl);
        if (results === null) {
            return "";
        }
        else {
            return results[1];
        }
    },
    updateVideoThumbnailVisual: function(cleanId, applyId) {
        $(document.getElementById("np_" + cleanId)).removeClass("nowPlaying").addClass("playOverlay");
        $(document.getElementById("np_" + applyId)).removeClass("playOverlay").addClass("nowPlaying");
    },

    isNotBlankOrNull: function(strVar) {
        return (strVar !== '' && strVar !== null && typeof strVar != 'undefined');
    },

    //Will have to have different maps for url key for section and sub section        
    parseInformationFromXmlDoc: function() {
        var collectionArray = this.xmlDoc.documentElement.getElementsByTagName("collection");

        for (var index = 0; index < collectionArray.length; ++index) {
            var item = collectionArray[index];
            if (item) {
                //alert(item.getAttribute("urlkey"));
                if (item.getAttribute("urlkey")) {
                    this.collectionNamesArray[index] = item.getAttribute("name")

                    this.collectionObjects[item.getAttribute("urlkey")] = {
                        contentUrl: item.getAttribute("contenturl"),
                        name: item.getAttribute("name"),
                        rssUrl: item.getAttribute("rssurl"),
                        urlkey: item.getAttribute("urlkey"),
                        internalUrl: item.getAttribute("internalurl"),
                        sponsored: item.getAttribute("sponsored"),
                        parent: null
                    };

                    var subCollectionArray = item.getElementsByTagName("subcollection");
                    var subCollectionArrayLength = subCollectionArray.length;

                    for (var sindex = 0; sindex < subCollectionArray.length; ++sindex) {
                        var sitem = subCollectionArray[sindex];
                        if (sitem && sitem.getAttribute("urlkey")) {
                            this.collectionObjects[sitem.getAttribute("urlkey")] = {
                                contentUrl: sitem.getAttribute("contenturl"),
                                name: sitem.getAttribute("name"),
                                rssUrl: sitem.getAttribute("rssurl"),
                                urlkey: sitem.getAttribute("urlkey"),
                                internalUrl: item.getAttribute("internalurl"),
                                sponsored: item.getAttribute("sponsored"),
                                parent: this.collectionObjects[item.getAttribute("urlkey")]
                            };
                        }
                    }
                }
            }
        }

        this.collectionObjects[""] = {
            contentUrl: "",
            name: "",
            rssUrl: "",
            urlkey: "",
            internalUrl: "",
            parent: null
        };

    },
    createFlashPlayer: function() {
        try {
            var divId = $(this.videoPlayerDivId).selector;
            var dim = { w: "512", h: "363" };
            swfobject.embedSWF(this.flashPlayerPath + "main.swf", divId, dim.w, dim.h, "9.0.0", "", {
                'objName': this.getName(),
                'allowPlayerPopup': '1',
                'plyMediaEnabled': '1',
                'movieWidth': dim.w,
                'movieHeight': dim.h,
                'host': location.host
            }, {
                allowscriptaccess: "always",
                wmode: "transparent"
            }, {
                id: "flashPlayer"
            });
        }
        catch (e) {
            //console.error("Error occured createFlashPlayer.." + e.message);
            $(this.videoPlayerDivId).html('Couldn\'t load the flash player. \n Error message is: ' + e.message);
        }

    },
    convertCurrentPlayingJsonToIdsArray: function() {
        this.currentlyPlayingVideoIds = [];
        if (this.currentPlayingJsonObject.items.length > 0) {
            for (var index = 0, len = this.currentPlayingJsonObject.items.length; index < len; ++index) {
                this.currentlyPlayingVideoIds[index] = this.currentPlayingJsonObject.items[index].id;
            }
        }
    },

    formatAPDisplayDate: function(unformattedDate) {
        var retstr = '';
        switch (unformattedDate.split('/')[0])   // the month
        {
            case '1':
                retstr = 'Jan.';
                break;
            case '2':
                retstr = 'Feb.';
                break;
            case '3':
                retstr = 'March';
                break;
            case '4':
                retstr = 'April';
                break;
            case '5':
                retstr = 'May';
                break;
            case '6':
                retstr = 'June';
                break;
            case '7':
                retstr = 'July';
                break;
            case '8':
                retstr = 'Aug.';
                break;
            case '9':
                retstr = 'Sept.';
                break;
            case '10':
                retstr = 'Oct.';
                break;
            case '11':
                retstr = 'Nov.';
                break;
            case '12':
                retstr = 'Dec.';
                break;
        }
        retstr += ' ' + unformattedDate.split('/')[1] + ', ' + unformattedDate.split('/')[2]

        return retstr;
    },

    populateVideoSummary: function(name, description, formattedCreationDate, relatedText, relatedHref) {
        if ($(this.videoSummaryDivId)) {
            var str = '';
            try {
                str += '<br/><div class="videoHeadline">' + name;
                str += '</div>';
                str += '<div class="videoTimestamp">' + this.formatAPDisplayDate(formattedCreationDate.split(' ')[0]);
                if (this.isVideoSponsored()) {
                    str += ' (E*Trade Securities LLC)';
                }
                str += '</div>';
                str += '<div class="videoCaption">' + description + '</div>';

                if (relatedText !== (void 0) && relatedText != '') {
                    if (relatedHref.indexOf("www.marketwatch.com") > -1) {
                        str += '<div class="relatedLink">Related: <a href="' + relatedHref + '">' + relatedText + '</a></div>';
                    } else {
                        str += '<div class="relatedLink">Related: <a href="' + relatedHref + '" target="_blank">' + relatedText + '</a></div>';
                    }
                }
            }
            catch (e) {
                console.error("Error occured in populateVideoSummary." + e.message);
                str += 'Couldn\'t get video summary.';
            }
            $(this.videoSummaryDivId).html(str);
        }
    },

    createAdvertisement: function(imgUrl, link) {
        try {
            swfobject.getObjectById("advertisement").loadAd(imgUrl, link);
        }
        catch (e) {
            console.error("Error while loading ad in createAdvertisement : " + e);
        }
    },

    createNextVideo: function() {
        var str = 'Loading...';
        try {
            this.nextVideoId = this.getNextVideoId();
            if (this.nextVideoId !== '') {
                var url = '/api-video/get_video_info.asp?site=mw&guid=' + this.nextVideoId + '&fields=all';
                this.getVideos(url, 'next', true);
            }
            else {
                str = 'No more videos.';
            }
        }
        catch (e) {
            console.error("Error occured while executing createNextVideo() - " + e.message);
            str += 'Couldn\'t determine next video details.';
        }
        if ($(this.nextVideoDivId)) {
            $(this.nextVideoDivId).html(str);
        }
    },
    populateNextVideo: function() {

        var str = '';
        try {
            var nameToDisplay = this.isNotBlankOrNull(this.currentlyPlayingSubCollection) ? this.currentlyPlayingSubCollection : this.currentlyPlayingCollection;

            if (this.currentlyPlayingCollection == 'Search Results') {
                str += '<div class="videoFeatureTitleBar">Next in Video ' + this.collectionObjects[this.currentlyPlayingCollection].name + '</div>';
            }
            else {
                str += '<div class="videoFeatureTitleBar">Next in ' + this.collectionObjects[nameToDisplay].name + ' Video</div>';
            }

            str += '<div class="videoThumbnail"><a href="javascript:' + this.getName() + '.nextVideoThumbnailClicked(\'' + this.nextVideoDetailsJsonObject.id + '\')" class="preview"><img src="' + this.nextVideoDetailsJsonObject.thumbnailURL + '" width="115" height="65" valign="center"/></a></div>';
            str += '<span style="font-size:14px;"><a href="javascript:' + this.getName() + '.nextVideoThumbnailClicked(\'' + this.nextVideoDetailsJsonObject.id + '\')">' + this.nextVideoDetailsJsonObject.name + '</a></span><br/>';
            var minutes = Math.floor(this.nextVideoDetailsJsonObject.duration / 60);
            var seconds = this.nextVideoDetailsJsonObject.duration % 60;
            if (seconds < 10) {
                seconds = '0' + seconds;
            }
            str += '<span style="font-size:10px;color:#666666">' + minutes + ':' + seconds + '</span><br/>';
            str += '<span>' + this.nextVideoDetailsJsonObject.description + '</span>';

        }
        catch (e) {
            console.error("Error occured while executing populateNextVideo() - " + e.message);
            str += 'Couldn\'t populate next video details.';
        }
        if ($(this.nextVideoDivId)) {
            $(this.nextVideoDivId).html(str);
        }
    },
    //need to work - to-do
    nextVideoThumbnailClicked: function(videoId) {
        this.userAction = '';
        this.populateMoreVideos(1);
        this.loadPagination(1);
        this.updateVideoThumbnailVisual(this.currentlyPlayingVideoId, videoId);
        this.currentlyPlayingVideoId = videoId;
        this.playVideoByVideoId(videoId);
        this.createNextVideo();
        if (this.isNotBlankOrNull(this.currentlyPlayingSubCollection)) {
            this.updateSideNavAppearance('subcollection', this.currentlyPlayingSubCollection);
        }
        else {
            this.updateSideNavAppearance('collection', this.currentlyPlayingCollection);
        }
        $("#video_error_message").html("");
    },

    createSearch: function() {
        //        var str = '';
        //        str += '<form id="searchForm" onSubmit="javascript:' + this.getName() + '.searchButtonClicked();return false;" class="" method="post" accept-charset="utf-8">';
        //        str += '<fieldset>';
        //        str += '<legend>Search Videos</legend>';
        //        str += '<div class="ctl">';
        //        str += '<label for="frmSearchSectCtl01">Search Videos</label>';
        //        str += '<input type="text" name="frmSearchSectCtl01" value="Search Videos" id="frmSearchSectCtl01" class="text" onFocus="' + this.getName() + '.searchInputBoxFocused();"/>';
        //        str += '</div>';
        //        str += '<div class="ctl">';
        //        str += '<label for="frmSearchSectSub">Search</label>';
        //        str += '<button id="searchButton" type="submit">Search</button>';
        //        str += '</div>';
        //        str += '</fieldset>';
        //        str += '</form>';
        //        if ($(this.searchDivId)) {
        //            $(this.searchDivId).html(str);
        //        }
    },
    searchInputBoxFocused: function() {
        //$("frmSearchSectCtl01").value = "";
        //$("searchForm").className = "";
    },
    searchButtonClicked: function() {
        var videoSearchInput = document.getElementById("videoSearch");
        var searchTxt = videoSearchInput.value.replace(/^\s+|\s+$/, '');
        searchTxt = searchTxt.replace(/((\%3C)|<)((\%2F)|\/)*[a-z0-9\%]+((\%3E)|>)/i, "");

        videoSearchInput.value = searchTxt;

        if (searchTxt === '') {
            $("#searchForm").addClass("search_error");
            $("#videoSearch").value = "Please enter search terms";
            //$("#searchButton").focus();
            return false;
        }
        this.currentSearchText = searchTxt;
        this.sortOrder = 'relevancy';
        if (!this.isVideoResultsInSideNav) {
            this.insertVideoResultsInSideNav();
            this.isVideoResultsInSideNav = true;
        }
        this.updateVideoResultsInSideNav(this.currentSearchText);
        this.updateSideNavAppearance('collection', 'Search Results');
        var searchUrl = '/api-video/find_all_videos.asp?type=wsj-fulltext&query=' + searchTxt;
        this.performSearch(searchUrl);
        //$("#searchButton").focus();
    },
    insertVideoResultsInSideNav: function() {
        var str = '';
        str += '<li id="SearchResults">';
        str += '</li>';
        if ($(this.sideNavUlId)[0]) {
            str += $(this.sideNavUlId)[0].innerHTML;
        }
        $(this.sideNavUlId).html(str);
    },
    updateVideoResultsInSideNav: function(srchText) {
        var fields = 'id,name,description,duration,thumbnailURL,videoURL,formattedCreationDate,wsj-section,wsj-subsection';
        var srchContentUrl = '/api-video/find_all_videos.asp?type=wsj-fulltext&query=' + srchText + '&fields=' + fields;
        this.collectionObjects['Search Results'] = { contentUrl: srchContentUrl };
        var str = '';
        str += '<div>&nbsp;&nbsp;<a id="a_SearchResults" class="" href="javascript:' + this.getName() + '.sideNavClicked(\'collection\',\'Search Results\');">';
        str += 'Search Results</a><div>';
        $("#SearchResults").html(str);
    },
    performSearch: function(searchUrl) {
        this.userAction = 'toSearch';
        var fields = 'id,name,description,duration,thumbnailURL,videoURL,formattedCreationDate,wsj-section,wsj-subsection';
        $(this.videoResultsDivId).html('<div class="loadingPlaceholder" style="height:100px; width:500px;">&nbsp;</div>');
        this.getVideos(searchUrl + '&fields=' + fields + '&count=60', this.userAction, true);
    },
    loadPagination: function(pageNumber) {
        var varToDisplay = '';
        // Change the variable to display on the basis of user action
        if (this.userAction == 'toBrowse') {
            if (typeof this.currentBrowsingJsonObject != "undefined") {
                varToDisplay = this.currentBrowsingJsonObject.items;
            }
        }
        else
            if (this.userAction == 'toSearch') {
            if (typeof this.currentSearchJsonObject != "undefined") {
                varToDisplay = this.currentSearchJsonObject.items;
            }
        }
        else {
            varToDisplay = this.currentPlayingJsonObject.items;
        }

        var currentPageNumber = Number(pageNumber);
        var flr = Math.floor(varToDisplay.length / this.pageSize);
        var cl = Math.ceil(varToDisplay.length / this.pageSize);
        /* variables for testing purpose
        currentPageNumber = 3;
        var flr = (Math.floor(60/this.pageSize));
        var cl = (Math.ceil(60/this.pageSize));
        */
        //var lastPageNumber = (flr == cl) ? Math.min(flr, cl) : Math.min(flr, cl) + 1;
        var lastPageNumber = Math.max(flr, cl);
        //this.lastPageNumber = lastPageNumber;
        //if currentpage number is = 1 - previous is disabled
        // if currentpagenumber = lastpage number - next is disabled
        var str = '';
        if (currentPageNumber == 1) {
            str += '<li id="previous" class="listFirst"><span>Prev</span></li>';
        }
        else {
            str += '<li id="previous" class="listFirst"><a href="javascript:' + this.getName() + '.paginationClicked(\'' + (currentPageNumber - 1) + '\')">Prev</a></li>';
        }
        for (var index = 1; index <= lastPageNumber; index++) {
            if (currentPageNumber == index) {
                str += '<li><span>' + index + '</span></li>';
            }
            else {
                str += '<li><a href="javascript:' + this.getName() + '.paginationClicked(\'' + index + '\')" >' + index + '</a></li>';
            }
        }
        if (currentPageNumber >= lastPageNumber) {
            str += '<li id="next"><span>Next</span></li>';
        }
        else {
            str += '<li id="next"><a href="javascript:' + this.getName() + '.paginationClicked(\'' + (currentPageNumber + 1) + '\')">Next</a></li>';
        }
        $("#pagination").html(str);
    },
    paginationClicked: function(pageNumber) {
        /*
        if ((((this.playingGroup == 'collection') && (this.visibleCollectionId != this.currentlyPlayingCollection)) || ((this.playingGroup == 'subcollection') && (this.visibleSubCollectionId != this.currentlyPlayingSubCollection))) || (pageNumber != this.currentPageNumber)) {
        this.browsingPageNumber = Number(pageNumber);
        }
        else {
        this.currentPageNumber = Number(pageNumber);
        }
        */
        this.populateMoreVideos(pageNumber);
        this.loadPagination(pageNumber);
        this.updateRssFeed((this.visibleSubCollectionId !== '') ? this.visibleSubCollectionId : this.visibleCollectionId);
    },
    getVideos: function(purl, userAction, async) {
        $.ajax({ url: this.proxyUrl(purl),
            type: "GET",
            async: async,
            success: this.usrActnHash[userAction],
            error: this.handleFailure,
            dataType: "json"
        });
    },
    handleFailure: function(obj, url, userAction, async) {
        setTimeout("" + attic.getName() + ".getVideos('" + url + "','" + userAction + "','" + async + "')", 10000);
    },
    handleResponse: function(json) {
        attic.currentPlayingJsonObject = json;
        attic.convertCurrentPlayingJsonToIdsArray();
        /*
        this.populateMoreVideos(1);
        this.loadPagination(1);
        this.updateRssFeed((this.visibleSubCollectionId != '') ? this.visibleSubCollectionId : this.visibleCollectionId);
        */
    },
    handleBrowsingResults: function(json) {
        attic.currentBrowsingJsonObject = json;
        attic.populateMoreVideos(1);
        attic.loadPagination(1);
        attic.updateRssFeed((attic.visibleSubCollectionId !== '') ? attic.visibleSubCollectionId : attic.visibleCollectionId);
    },
    handleSearchResults: function(json) {
        attic.currentSearchJsonObject = json;
        attic.populateMoreVideos(1);
        attic.loadPagination(1);
    },
    handleCurrent: function(json) {
        attic.currentVideoDetailsJsonObject = json;
        attic.playVideoByParam(attic.currentVideoDetailsJsonObject);
        attic.populateVideoSummary(attic.currentVideoDetailsJsonObject.name,
                attic.currentVideoDetailsJsonObject.description,
                attic.currentVideoDetailsJsonObject.formattedCreationDate,
                attic.currentVideoDetailsJsonObject.relatedLinkText,
                attic.currentVideoDetailsJsonObject.relatedLinkHref);
        //attic.fireTrackingPixelForVideo(json);
    },
    handleNext: function(json) {
        attic.nextVideoDetailsJsonObject = json;
        attic.populateNextVideo();
    },
    populateSideNav: function() {
        var src = '';
        var collectionArray = this.xmlDoc.getElementsByTagName("collection");

        for (var index = 0, len = collectionArray.length; index < len; ++index) {
            var item = collectionArray[index];
            var subCollectionArray = item.getElementsByTagName("subcollection");
            var subCollectionArrayLength = subCollectionArray.length;

            if (item.getAttribute("urlkey")) {
                src += '<li id="' + item.getAttribute("urlkey") + '" ';
                var sponsored = this.isNotBlankOrNull(item.getAttribute("sponsored")) ? "sponsored expanded" : "";
                if (sponsored != null) {
                    src += 'class="' + sponsored + '"';
                    sponsored = ' ' + sponsored; // hacky, yes.  this will be backed out after promo is over.
                }
                src += '>';

                if (subCollectionArrayLength > 0) {
                    var defChild = "";
                    src += '<a id="a_' + item.getAttribute("urlkey") + '"';
                    if (item.getAttribute("internalurl") != null) {
                        src += ' href="' + item.getAttribute("internalurl") + '" class="collapsed' + sponsored + '"';
                        src += ' onclick="' + this.getName() + '.sideNavClicked(\'' + item.nodeName + '\', \'' + item.getAttribute('urlkey') + '\'); return false;"';
                    } else {
                        defChild = "defChild";
                        src += ' href="' + subCollectionArray[0].getAttribute("internalurl") + '" class="empty ' + sponsored + (this.isNotBlankOrNull(item.getAttribute("sponsored")) ? '' : ' collapsed') + '"';
                        src += ' onclick="' + this.getName() + '.sideNavClicked(\'' + subCollectionArray[0].nodeName + '\', \'' + subCollectionArray[0].getAttribute('urlkey') + '\', true); return false;"';
                    }
                    src += '>' + item.getAttribute('name') + '</a>';
                    var display = this.isNotBlankOrNull(item.getAttribute("sponsored")) ? 'display: block;' : 'display: none;';
                    src += '<ul style="' + display + '" id="Sub' + item.getAttribute("name") + '">';
                    for (var sindex = 0, slen = subCollectionArray.length; sindex < slen; ++sindex) {
                        var sitem = subCollectionArray[sindex];
                        sponsored = this.isNotBlankOrNull(sitem.getAttribute("sponsored")) ? " sponsored" : "";
                        src += '<li id="' + sitem.getAttribute("urlkey") + '">';
                        src += '<a id="a_' + sitem.getAttribute("urlkey") + '" class="' + defChild + sponsored + '" href="';
                        src += sitem.getAttribute("internalurl") + '" onclick="' + this.getName() + '.sideNavClicked(\'';
                        src += sitem.nodeName + '\', \'' + sitem.getAttribute("urlkey") + '\'); return false;">';
                        src += sitem.getAttribute("name") + '</a></li>';
                    }
                    src += '</ul>';
                } else {
                    src += '<a id="a_' + item.getAttribute("urlkey") + '" ';
                    src += 'href="' + item.getAttribute("internalurl") + '" class="headeronly"';
                    src += ' onclick="' + this.getName() + '.sideNavClicked(\'' + item.nodeName + '\', \'' + item.getAttribute('urlkey') + '\'); return false;">';
                    src += item.getAttribute('name') + '</a>';
                }


                src += '</li>';
            }
        }

        $(this.sideNavUlId).html(src);

        // Expand only the active menu, which is determined by the class name
        $("#video_sidenav > li > a[class='expanded']").find("+ ul").slideToggle("medium");
    },
    sideNavClicked: function(strType, strName, expandParent) {
        this.userAction = '';
        var collectionClicked = this.collectionObjects[strName];
        $("#video_feed_link").html(''); // Hide the RSS link when a click occurs

        this.updateSideNavAppearance(strType, strName, expandParent);

        if (this.isNotBlankOrNull(collectionClicked.contentUrl)) {
            this.browsingGroup = strType;
            if (strName == 'Search Results') {
                this.userAction = 'toSearch';
                this.sortOrder = 'relevancy';
            }
            else
                if (((strType == 'subcollection') && (strName != this.currentlyPlayingSubCollection)) || ((strType == 'collection') && (strName != this.currentlyPlayingCollection))) {
                this.userAction = 'toBrowse';
            }
            $(this.videoResultsDivId).html('<div class="loadingPlaceholder" style="height:100px; width:500px;">&nbsp;</div>');
            if (this.isNotBlankOrNull(this.userAction)) {
                this.getVideos(collectionClicked.contentUrl + '&count=60', this.userAction, true);
            }
            else {
                this.populateMoreVideos(1);
                this.loadPagination(1);
            }

            $("div#sponsoredDisclaimer").css("display", (collectionClicked.sponsored == "true" ? "block" : "none"));
        }
    },
    updateSponsoredDisplayItemStates: function() {
        var show = this.isVideoSponsored();

        var banner = $("div#sponsoredBanner");
        if (show && !this.isNotBlankOrNull(banner.html())) {
            banner.html(this.sponsoredBannerMarkup);
            banner.after('<img src="http://ad.doubleclick.net/imp;v1;f;218975212;0-0;0;42162463;1|1;32417616|32435492|1;;cs=k%3fhttp://ad.doubleclick.net/dot.gif?' + this.cacheBust() + '"/>');
            $("div#sponsoredAd").html(this.sponsoredAdMarkup);
            $("div#sponsoredAd").after('<img src="http://ad.doubleclick.net/imp;v1;f;220115019;0-0;0;43733456;1|1;34527735|34545613|1;;cs=x%3fhttp:/ad.doubleclick.net/dot.gif?' + this.cacheBust() + '"/>');
        }

        banner.css("display", (show == true ? "block" : "none"));

        $("div#sponsoredAd").css("display", (show == true ? "block" : "none"));
        $("div#adContainer").css("display", (show == true ? "none" : "block"));
        $("div#next_video").css("display", (show == true ? "none" : "block"));

        var disc = (this.currentlyPlayingVideoId == '{343D5DD4-3AC9-4440-A86B-7EC5FE0033A1}' ||
                    this.currentlyPlayingVideoId == '{2503C475-D2FD-4984-8DC7-87BAEAED6B6D}');

        $("div#sponsoredNote").css("display", (disc == true ? "block" : "none"));
    },
    isVideoSponsored: function() {
        var ret = (this.currentlyPlayingVideoId == '{8E6281C9-BFA4-45D9-93BA-E65BF41FC970}' ||
                    this.currentlyPlayingVideoId == '{343D5DD4-3AC9-4440-A86B-7EC5FE0033A1}' ||
                    this.currentlyPlayingVideoId == '{2503C475-D2FD-4984-8DC7-87BAEAED6B6D}' ||
                    this.currentlyPlayingVideoId == '{214BC7C2-011D-4A66-A5FC-7764E0D97B37}' ||
                    this.currentlyPlayingVideoId == '{B3F5AABB-E6A0-45CD-9FC8-CC1D9BE1DC28}');
        return ret;
    },
    searchLinkClicked: function(searchUrl, sortParam) {
        this.sortOrder = sortParam;
        this.performSearch(searchUrl);
    },
    populateMoreVideos: function(pageNumber) {
        var varToDisplay = '';
        // Change the variable to display on the basis of user action
        if (this.userAction == 'toBrowse') {
            if (typeof this.currentBrowsingJsonObject != "undefined") {
                varToDisplay = this.currentBrowsingJsonObject.items;
            }
        }
        else
            if (this.userAction == 'toSearch') {
            if (typeof this.currentSearchJsonObject != "undefined") {
                varToDisplay = this.currentSearchJsonObject.items;
            }
        }
        else {
            varToDisplay = this.currentPlayingJsonObject.items;
        }
        var startIndex = (pageNumber - 1) * 12;
        var endIndex = Math.min(pageNumber * 12 - 1, varToDisplay.length - 1);
        var str = '';
        if (this.userAction == 'toSearch' && varToDisplay.length > 0) {
            str += '<table id="searchHeader"><tr>';
            str += '<td width="50%"><span class="resultsLabel">' + (startIndex + 1) + ' - ' + (endIndex + 1) + ' results out of ' + varToDisplay.length + ' for: <strong>' + this.currentSearchText + '</strong></span></td><td>';
            str += '<ul class="sort"><li class="listFirst">Sort by:</li>';
            var sUrl = '/api-video/find_all_videos.asp?type=wsj-fulltext&query=' + this.currentSearchText;
            if (this.sortOrder == 'relevancy') {
                str += '<li class="selected"><span>Relevance</span></li>';
                str += '<li class="listLast"><a href="javascript:' + this.getName() + '.searchLinkClicked(\'' + sUrl + '&sort=date+desc\',\'date\')">Date</a></li>';
            }
            else {
                str += '<li><a href="javascript:' + this.getName() + '.searchLinkClicked(\'' + sUrl + '&sort=relevancy\',\'relevancy\')">Relevance</a></li>';
                str += '<li class="listLast selected"><span>Date</span></li>';
            }
            str += '</ul></td>';
            str += '</tr></table>';
        }
        if (this.userAction == 'toSearch' && varToDisplay.length === 0) {
            str += '<br/><br/><p class="noResults"> No content matches your search terms. Please try again. </p>';
            $(this.videoResultsDivId).html(str);
            return false;
        }
        str += '<ul class="videoListMed">';
        for (var i = startIndex; i < endIndex + 1; i++) {
            var title = varToDisplay[i];

            if (((i + 1) % 4) === 0) {
                str += '<li id="li_' + title.id + '" class="rowEnd">';
            }
            else {
                str += '<li id="li_' + title.id + '" class="">';
            }

            str += '<a href="javascript:' + this.getName() + '.videoThumbnailClicked(\'' + title.id + '\')" id="' + title.id + '" style="background-image: url(' + unescape(title.thumbnailURL) + ');" class="video preview"><div id="np_' + title.id + '" class="playOverlay">&nbsp;</div></a>';
            str += '<div><a href="javascript:' + this.getName() + '.videoThumbnailClicked(\'' + title.id + '\')">' + title.name + '</a>&nbsp;&nbsp;';
            var minutes = Math.floor(title.duration / 60);
            var seconds = title.duration % 60;
            if (seconds < 10) {
                seconds = '0' + seconds;
            }
            str += '<small>' + minutes + ':' + seconds + '</small>';

            if (this.isNotBlankOrNull(title.formattedCreationDate)) {
                str += '<small> ' + title.formattedCreationDate.split(' ')[0] + '</small>';
            }
            str += '</div></li>';

        }
        str += '</ul>';

        //RSS feed starts
        if (this.userAction != 'toSearch') {
            var currentCollection = this.isNotBlankOrNull(this.visibleSubCollectionId) ? this.visibleSubCollectionId : this.visibleCollectionId;

            if (this.isNotBlankOrNull(this.collectionObjects[currentCollection].rssUrl)) {
                $("#video_feed_link").html('<img src="http://i.marketwatch.com/newsimages/tvradio/video/podcasticon.gif" height="16" width="16" valign="center"/>&nbsp;<a target="_blank" id="rssFeed" class="rss" href="' +
              this.collectionObjects[currentCollection].rssUrl +
              '">' + this.collectionObjects[currentCollection].name + ' Video Feed</a>');
            } else {
                $("#video_feed_link").html('');
            }
        }

        //RSS feed ends
        $(this.videoResultsDivId).html(str);

        if (!this.playFromRegisteredVideos) {
            this.updateVideoThumbnailVisual('', this.currentlyPlayingVideoId);
        }
    },
    updateRssFeed: function(str) {
        //        if ($("#video_feed_link")) {
        //            $("#video_feed_link").href = this.collectionObjects[str].rssUrl;
        //        }
    },
    videoThumbnailClicked: function(videoId) {
        //		this.currentPageNumber  = this.browsingPageNumber;
        var videoDetails = '';
        if (this.sourceApplicationName == 'articlePage') {
            this.playFromRegisteredVideos = false;
            this.updateVideoThumbnailVisual('reg' + this.currentlyPlayingVideoId, '');
            videoDetails = this.getVideoDetails({
                'id': videoId,
                'fields': 'linkRelativeURL,wsj-section'
            });
        }
        if (videoDetails !== '' && (this.relatedVideosCollection != videoDetails['wsj-section'] || this.visibleCollectionId == 'Search Results')) {
            window.location.href = videoDetails.linkRelativeURL;
        }
        else {
            this.playingGroup = this.browsingGroup;
            if (this.userAction == 'toSearch') {
                this.currentPlayingJsonObject = this.currentSearchJsonObject;
            }
            else
                if (this.userAction == 'toBrowse') {
                this.currentPlayingJsonObject = this.currentBrowsingJsonObject;
            }
            this.convertCurrentPlayingJsonToIdsArray();
            this.currentlyPlayingCollection = this.visibleCollectionId;
            this.currentlyPlayingSubCollection = this.visibleSubCollectionId;
            this.updateVideoThumbnailVisual(this.currentlyPlayingVideoId, videoId);
            this.currentlyPlayingVideoId = videoId;
            this.playVideoByVideoId(videoId);
            this.updateSponsoredDisplayItemStates();
            this.createNextVideo();

            // for testing auto play
            //this.playNextVideo();
        }

        $("#video_error_message").html("");
        $("#" + this.advertisementDivId).scroll();

        if (this.isVideoSponsored()) {
            $.scrollTo('#sponsoredBanner');
        } else {
            $.scrollTo('#videoPlayerSurround');
        }
    },
    //Called by flash player - upon finishing a video
    playNextVideo: function() {
        if (this.nextVideoId !== '') {
            this.updateVideoThumbnailVisual('reg' + this.currentlyPlayingVideoId, 'reg' + this.nextVideoDetailsJsonObject.id);
            this.updateVideoThumbnailVisual(this.currentlyPlayingVideoId, this.nextVideoDetailsJsonObject.id);
            this.currentlyPlayingVideoId = this.nextVideoDetailsJsonObject.id;
            this.playVideoByParam(this.nextVideoDetailsJsonObject);
            this.populateVideoSummary(this.nextVideoDetailsJsonObject.name,
                this.nextVideoDetailsJsonObject.description,
                this.nextVideoDetailsJsonObject.formattedCreationDate,
                this.nextVideoDetailsJsonObject.relatedLinkText,
                this.nextVideoDetailsJsonObject.relatedLinkHref);
            this.createNextVideo();

            /*
            if ((((this.playingGroup == 'collection') && (this.visibleCollectionId == this.currentlyPlayingCollection)) || ((this.playingGroup == 'subcollection') && (this.visibleSubCollectionId == this.currentlyPlayingSubCollection))) && (this.currentPageNumber == this.browsingPageNumber)) {
            this.currentPageNumber = Math.floor(this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) / this.pageSize) + 1;
            this.populateMoreVideos(this.currentPageNumber);
            this.loadPagination(Number(this.currentPageNumber));
            this.updateRssFeed((this.visibleSubCollectionId != '') ? this.visibleSubCollectionId : this.visibleCollectionId);
            }
            */
        }
    },
    getNextVideoId: function() {
        if (this.sourceApplicationName == 'articlePage') {
            //autoplay logic for article page
            if (this.playFromRegisteredVideos && this.registeredVideosIds.indexOf(this.currentlyPlayingVideoId) < this.registeredVideosIds.length - 1) {
                return this.registeredVideosIds[this.registeredVideosIds.indexOf(this.currentlyPlayingVideoId) + 1];
            }
            if (this.playFromRegisteredVideos && this.registeredVideosIds.indexOf(this.currentlyPlayingVideoId) == this.registeredVideosIds.length - 1) {
                this.playFromRegisteredVideos = false;
                return this.currentlyPlayingVideoIds[0];
            }

            if (this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) < (this.currentlyPlayingVideoIds.length - 1)) {
                return this.currentlyPlayingVideoIds[this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) + 1];
            }
            if (this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) == (this.currentlyPlayingVideoIds.length - 1)) {
                return '';
            }
        }
        else {
            //autoplay logic for video center
            if (this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) == -1) {
                return this.currentlyPlayingVideoIds[0];
            }
            if (this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) < (this.currentlyPlayingVideoIds.length - 1)) {
                return this.currentlyPlayingVideoIds[this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) + 1];
            }
            if (this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) == (this.currentlyPlayingVideoIds.length - 1)) {
                if (this.isVideoSponsored()) { // special case, start over with sponsored videos
                    return this.currentlyPlayingVideoIds[0];
                } else {
                    if (this.currentlyPlayingCollection == 'Search Results') {
                        return '';
                    }
                    if (this.playingGroup !== "" && this.playingGroup == 'collection') {
                        //get the videos for next collection
                        return this.getVideoIdFromNextCollection();
                    }
                    if (this.playingGroup !== "" && this.playingGroup == 'subcollection') {
                        //get the videos for next subcollection
                        return this.getVideoIdFromNextSubCollection();
                    }
                }
            }
        }
    },
    getVideoIdFromNextSubCollection: function() {
        var subColAr = this.subcollectionsObject[this.currentlyPlayingCollection];
        if (subColAr.indexOf(this.currentlyPlayingSubCollection) != subColAr.length - 1) {
            this.currentlyPlayingSubCollection = subColAr[subColAr.indexOf(this.currentlyPlayingSubCollection) + 1];
            this.getVideos(this.collectionObjects[this.currentlyPlayingSubCollection].contentUrl + '&count=60', '', false);
            if (this.currentPlayingJsonObject.items.length === 0) {
                return this.getVideoIdFromNextSubCollection();
            }
            else {
                return this.currentPlayingJsonObject.items[0].id;
            }
        }
        else {
            //to-do
            //this.playingGroup = 'collection';
            this.currentlyPlayingSubCollection = '';
            return this.getVideoIdFromNextCollection();
        }
    },
    getVideoIdFromNextCollection: function() {

        if (this.collectionNamesArray.indexOf(this.currentlyPlayingCollection) != this.collectionNamesArray.length - 1) {
            if (this.skipCollection) {
                this.currentlyPlayingCollection = this.collectionNamesArray[this.collectionNamesArray.indexOf(this.currentlyPlayingCollection) + 1];
            }
            this.skipCollection = true;
            this.getVideos(this.collectionObjects[this.currentlyPlayingCollection].contentUrls + '&count=60', '', false);
            if (this.currentPlayingJsonObject.items.length === 0) {
                return this.getVideoIdFromNextCollection();
            }
            else {
                return this.currentPlayingJsonObject.items[0].id;
            }
        }
        else {
            //return '';
            this.currentlyPlayingCollection = this.defaultCollectionName;
            this.skipCollection = false;
            return this.getVideoIdFromNextCollection();
            //this.getVideos(this.contentUrlsObject[this.currentlyPlayingCollection] + '&count=60', '', false);
            //return this.getNextVideoId();
        }
    },

    loadCollectionsDoc: function(xMLPath) {
        //console.error(videoSiteRoot);
        var localAjax = $.ajax({
            url: xMLPath + "video-collections.xml",
            type: "GET",
            async: false
        });
        //console.error(localAjax.responseXML);
        attic.xmlDoc = localAjax.responseXML;
        return attic.xmlDoc;
    },

    updateSideNavAppearance: function(strType, id, expandParent, force) {
        // alert('strType: ' + strType + ' id: ' + id + ' expandParent: ' + expandParent + ' force: ' + force);
        if ((strType == 'collection' && this.visibleCollectionId != id) ||
            (strType == 'collection' && this.visibleCollectionId == id && this.visibleSubCollectionId != '') ||
            expandParent == true || force == true) {
            var oldli = $("#videoBrowserNav li[class='expanded']");
            var newli = $("#" + id);
            if (expandParent) {
                newli = newli.parent().parent();
            }
            if (this.visibleCollectionId != id || this.visibleCollectionId == '' || force == true) {
                this.visibleCollectionId = id;
                this.visibleSubCollectionId = '';
                if (!newli.hasClass("sponsored")) {
                    newli.find("> ul").slideToggle("medium");
                    newli.find("> a").removeClass("collapsed").addClass("expanded");
                }

                if (oldli.length > 0 && !$(oldli).hasClass('sponsored')) {
                    oldli.find("> ul").slideToggle("medium");
                    oldli.find("> a").removeClass("expanded").addClass("collapsed");
                    oldli.removeClass("expanded");
                }

                if (!newli.hasClass("sponsored")) {
                    newli.removeClass("collapsed").addClass("expanded");
                }
            }

            oldli.find("> ul > li > a[class='noclick']").removeClass("noclick");
        }

        if (strType == 'subcollection' && this.visibleSubCollectionId != id) {
            this.visibleSubCollectionId = id;
            var newli = $("#" + id);
            newli.parent().find("> li > a[class='noclick']").removeClass("noclick");
            newli.find("> a").addClass("noclick");
            if (newli.find("> a").hasClass("sponsored")) {
                var oldli = $("#videoBrowserNav li[class='expanded']");
                oldli.find("> ul").slideToggle("medium");
                oldli.find("> a").removeClass("expanded").addClass("collapsed");
                oldli.removeClass("expanded");
            }
        }
    },
    getName: function() {
        return this.objName;
    },
    playVideoByVideoId: function(videoId) {
        var url = '/api-video/get_video_info.asp?guid=' + videoId + '&fields=all&site=mw';
        this.getVideos(url, 'current', false);
    },
    _createVideoObject: function(videoStillURL, videoUri) {
        this._video = $("<video></video>")
            .attr({ poster: videoStillURL })
            .attr({ src: videoUri })
            .attr({ controls: true })
            .attr({ width: 512 })
            .attr({ height: 363 });
    },
    callThroughDispatch: function(callback, context) {
        var link = $('<a id="dispatcherlink"></a>').attr({ is: "false" });
        $("#" + this.videoPlayerDivId).append(link);

        var linkId = "dispatcherlink";

        link[0].addEventListener("click", function(event) {
            event.returnValue = false;
            // preventing double dispatch
            if (link[0].getAttribute("is") === "true") { return; }
            else { link[0].setAttribute("is", "true"); }
            callback.call(context);
        }, true);

        setTimeout(function() {
            _doEventDispatch(linkId);
        }, 400);
    },

    _subscribeToVideoEvents: function() {
        var that = this;
        this._video[0].addEventListener("play", function(e) { }, true);
        this._video[0].addEventListener("canplay", function(e) { that._video[0].play(); }, true);
        this._video[0].addEventListener("pause", function(e) { }, true);
        this._video[0].addEventListener("ended", function(e) { that.playNextVideo(); }, true);
    },
    playHtml5: function(params) {
        this._createVideoObject(params.videoStillURL, params.video320kMP4Url);
        this._subscribeToVideoEvents();
        $("#" + this.videoPlayerDivId).empty();
        $("#" + this.videoPlayerDivId).append(this._video);
        dj.util.VideoTracking.fire(params);

        if (navigator.userAgent.indexOf('iPad') != -1) {
            this.callThroughDispatch(function() {
                this._video[0].play();
            }, this);
        }
        else {
            this._video[0].play();
        }



    },
    playVideoByParam: function(params) {
        //var adZone = ''//new dj.util.Ads().getRegisteredAdsZone(''); //adZone - new dj.util.Ads().getRegisteredAdsZone('')
        var lineup = this.isNotBlankOrNull(this.currentlyPlayingSubCollection) ? this.currentlyPlayingSubCollection : this.currentlyPlayingCollection; //lineup - collection / subcollection name
        //params.adZone = adZone;
        params.lineup = lineup;
        params.emailPartnerID = 110626;
        if (!this.isVideoSponsored()) { // this cancels the pre-roll ad
            params.site = "video.marketwatch.com";
        }
        params.playerName = (this.sourceApplicationName == 'articlePage') ? "video_articletab" : "video_videocenter";
        params.embedPlayerURL = this.flashPlayerPath + "main.swf";
        params.embedConfigURL = this.embedConfigURL;
        params.embedPlayerID = "2001";
        params.embedName = "flashPlayer"; //Name of the flash object
        params.embedBaseURL = this.flashPlayerPath;
        params.embedHeight = 363;
        params.embedWidth = 512;
        params.larsSourceID = 92;
        params.larsID = 92;
        params.larsAdTrackingID = 1260;
        params.adFrmt = "frmt=2;";

        params.prop5 = window.location.href.split('?')[0];
        params.prop6 = window.location.href;
        params.prop10 = this.getUrlParam(window.location.href, 'siteid');
        params.prop11 = document.referrer;
        params.prop19 = "video";
        params.prop25 = window.mwu2id;
        params.prop27 = (this.isNotBlankOrNull(params.prop25)) ? "MW_mem_yes" : "MW_mem_no";

        var subSecComponent = this.omnitureEncoding(this.collectionObjects[this.currentlyPlayingCollection].name, this.collectionObjects[this.currentlyPlayingSubCollection].name, 's');
        var secComponent = this.omnitureEncoding(this.collectionObjects[this.currentlyPlayingCollection].name, this.collectionObjects[this.currentlyPlayingSubCollection].name, 'c');
        params.prop2 = "MW_" + secComponent;
        params.prop3 = "MW_Multimedia_Video_" + secComponent;
        params.prop22 = "MW_Multimedia_Video_" + subSecComponent;
        params.prop26 = "MW_" + subSecComponent;

        var playedOn = subSecComponent;
        if (playedOn == 'Tech' && subSecComponent != secComponent)
            playedOn = 'techindustry';
        if (playedOn == null || playedOn == "")
            playedOnd = secComponent;
        if (playedOn != null)
            params.lineupID = unescape(playedOn).toLowerCase().replace(/[^a-zA-Z0-9]/g, "");


        params["wsj-section"] = params["mw-channel"];
        params["wsj-subsection"] = params["mw-subchannel"];

        //if its flash
        if (this.IsLatestFlashPlayer()) {
            swfobject.getObjectById("flashPlayer").playVideo(JSON.stringify(params));
        }
        else {
            //if its html5
            this.playHtml5(params);
        }

    },

    openPopUpPlayer: function() {
        var currentPlayingLocation = Math.floor(swfobject.getObjectById("flashPlayer").getSeek());
        var width = '512';
        var height = '680';
        var currentlyPlayingCollection = this.currentlyPlayingCollection;
        if ((currentlyPlayingCollection == 'Special Packages') || (currentlyPlayingCollection == 'Search Results')) {
            currentlyPlayingCollection = this.currentVideoDetailsJsonObject['mw-channel'];
        }
        //window.open(this.popUpPageUrl,'name','height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,status=yes');
        this.popUpWindow = window.open(this.popUpPageUrl + '?currentPlayingLocation=' + currentPlayingLocation + '&currentlyPlayingCollection=' + escape(currentlyPlayingCollection) + '&currentlyPlayingVideoId=' + this.currentlyPlayingVideoId, 'popUpPlayer', 'height=' + height + ',width=' + width + ',left=' + ((screen.width - Number(width)) / 2) + ',top=' + (screen.height - Number(height)) / 2 + ',resizable=yes,scrollbars=no,toolbar=no,status=no');
    },
    openMicroPopUpPlayer: function(id) {
        var currentPlayingLocation = Math.floor(swfobject.getObjectById(this.videoIdMicroPlayerIdMap[id]).getSeek());
        var currentlyPlayingCollection = this.microPlayersObjects[id]['wsj-section'];
        var currentlyPlayingVideoId = id;
        var width = '512';
        var height = '660';
        //window.open(this.popUpPageUrl,'name','height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,status=yes');
        this.popUpWindow = window.open(this.popUpPageUrl + '?currentPlayingLocation=' + currentPlayingLocation + '&currentlyPlayingCollection=' + escape(currentlyPlayingCollection) + '&currentlyPlayingVideoId=' + currentlyPlayingVideoId, 'popUpPlayer', 'height=' + height + ',width=' + width + ',left=' + ((screen.width - Number(width)) / 2) + ',top=' + (screen.height - Number(height)) / 2 + ',resizable=yes,scrollbars=no,toolbar=no,status=no');
    },

    focusPopUp: function() {
        if (this.popUpWindow) {
            this.popUpWindow.focus();
        }
    },

    //ARTICLE PAGE SPECIFIC
    createRegisteredVideosThumbnails: function() {
        if (this.registeredVideosIds.length > 0) {
            var str = '';
            for (var index = 0, len = this.registeredVideosIds.length; index < len; ++index) {
                var title = this.registeredVideos[index];
                str += '<li id="li_reg' + title.id + '" class="">';
                str += '<a href="javascript:' + this.getName() + '.regVideoThumbnailClicked(\'' + title.id + '\',\'' + unescape(title.videoURL) + '\')" id="' + title.id + '" style="background-image: url(' + unescape(title.thumbnailURL) + ');" class="preview"><span>&nbsp;</span></a>';
                str += '<h2><a href="javascript:' + this.getName() + '.regVideoThumbnailClicked(\'' + title.id + '\',\'' + unescape(title.videoURL) + '\')">' + title.name + '</a></h2>';

                var minutes = Math.floor(title.duration / 60);
                var seconds = title.duration % 60;
                if (seconds < 10) {
                    seconds = '0' + seconds;
                }
                str += '<small> ' + minutes + ':' + seconds + '</small>';
                str += '</li>';
            }
            $(this.registeredVideosDivId).html(str);
        }
    },

    regVideoThumbnailClicked: function(videoId) {
        this.playFromRegisteredVideos = true;
        this.updateVideoThumbnailVisual('reg' + this.currentlyPlayingVideoId, 'reg' + videoId);
        this.updateVideoThumbnailVisual(this.currentlyPlayingVideoId, '');
        this.currentlyPlayingVideoId = videoId;
        this.playVideoByVideoId(videoId);
        this.createNextVideo();
    },

    // ARTICLE PAGE WRAPPER CLASSES
    registerVideo: function(videoId) {
        this.playFromRegisteredVideos = true;
        if (videoId.indexOf('{') == -1) {
            videoId = '{' + videoId + '}';
        }
        this.registeredVideosIds[this.registeredVideosIds.length] = videoId;
        //Details of the videos will be used to create the thumbnails
        this.registeredVideos[this.registeredVideos.length] = this.getVideoDetails({
            'id': videoId,
            'fields': 'all'
        });
    },
    loadSoloVideo: function(videoId, divId) {
        if (videoId.indexOf('{') == -1) {
            videoId = '{' + videoId + '}';
        }
        var microPlayerId = "MicroPlayer_" + Math.floor(Math.random() * 1000000);
        this.microPlayers[this.microPlayers.length] = microPlayerId;
        this.videoIdMicroPlayerIdMap[videoId] = microPlayerId;
        if (!dj.context.video) {
            dj.context.video = {};
        }
        if (!dj.context.video.soloVideos) {
            dj.context.video.soloVideos = [];
        }
        dj.context.video.soloVideos[videoId] = this;


        if (swfobject.getFlashPlayerVersion().major >= 9) {
            var dim = { w: "272", h: "180" };
            swfobject.embedSWF(this.flashPlayerPath + "microPlayer.swf", divId, dim.w, dim.h, "9.0.0", "", {
                'objName': "dummy",
                'videoGUID': videoId,
                'allowPlayerPopup': '1',
                'movieWidth': dim.w,
                'movieHeight': dim.h,
                'host': location.host
            }, {
                allowscriptaccess: "always"
            }, {
                id: microPlayerId
            });
        }
        else {
            this.nonSupportingFlashPlayer(divId);
        }
    },

    //Methods for microplayer
    getJSON: function(id) {
        var url = '/api-video/get_video_info.asp?site=mw&guid=' + id;

        url += '&fields=all';

        this.ajax = new Ajax.Request(this.proxyUrl(url), {
            method: 'get',
            asynchronous: false,
            requestHeaders: {
                Accept: 'application/json'
            },
            onSuccess: this.handleGetJSON.bindAsEventListener(this),
            onFailure: function() {
                console.error("Failed while executing getJSON.");
            }
        });
        this.microPlayersObjects[id] = this.jsonData;
        return $H(this.jsonData).toJSON();
    },
    handleGetJSON: function(json) {
        this.jsonData = json;
        var adZone = new dj.util.Ads().getRegisteredAdsZone(''); //adZone - new dj.util.Ads().getRegisteredAdsZone('')
        //var lineup = this.currentlyPlayingCollection;//lineup - collection / subcollection name
        this.jsonData.adZone = adZone;
        //params.lineup = lineup;
        this.jsonData.emailPartnerID = 110626;
        this.jsonData.site = "video.marketwatch.com";
        this.jsonData.playerName = "video_articleembed";
        this.jsonData.videoCenterURL = "http://" + window.location.host + "/video";
        this.jsonData.embedPlayerURL = this.flashPlayerPath + "microPlayer.swf";
        this.jsonData.embedConfigURL = this.embedConfigURL;
        this.jsonData.embedPlayerID = "2001";
        //to - do
        this.jsonData.embedName = "microflashPlayer"; //Name of the flash object
        this.jsonData.embedBaseURL = this.flashPlayerPath;
        this.jsonData.embedHeight = 180;
        this.jsonData.embedWidth = 272;
        this.jsonData.larsSourceID = 92;
        this.jsonData.larsID = 92;
        this.jsonData.larsAdTrackingID = 1260;
        this.jsonData.adFrmt = "frmt=0;";
    },

    getVideoDetails: function(args) {
        if (!args.id) {
            return "No Id.";
        }
        var purl = '/api-video/get_video_info.asp?site=mw&guid=' + args.id;
        if (args.fields) {
            purl += '&fields=' + args.fields;
        }
        else {
            purl += '&fields=all';
        }

        $.ajax({ url: this.proxyUrl(purl),
            type: "GET",
            async: false,
            success: this.handleGetVideoDetails,
            error: function() {
                console.error("Failed while executing getVideoDetails.");
            },
            dataType: "json"
        });

        return this.jsonData;
    },
    handleGetVideoDetails: function(json) {
        attic.jsonData = json;
    },
    omnitureEncoding: function(col, subcol, type) {
        // if there is no subcollection, return collection name
        if (type == 's' && subcol == '') {
            return col;
        }
        if (type == 's') {
            return subcol;
        }
        if (type == 'c') {
            return col;
        }
    },
    proxyUrl: function(url) {
        return MarketWatch.getBaseUrl() + "/proxy/http/www.marketwatch.com" + url;
    },
    cacheBust: function() {
        var vdate = new Date();
        var timestamp;
        timestamp = Date.UTC(vdate.getFullYear(), vdate.getMonth(), vdate.getDate(), vdate.getHours(), vdate.getMinutes(), vdate.getSeconds(), vdate.getMilliseconds());
        return timestamp;
    }
});

var popattic;

dj.widget.video.popupvideo = $.klass({
    initialize: function(objName) {
        this.objName = objName;
        this.currentlyPlayingVideoIds = [];
        this.videoResultsDivId = '#video_results';
        this.videoSummaryDivId = '#video_headline';
        //this.subcollectionsObject = {};
        this.defaultCollectionName = 'markets';
        this.currentPlayingJsonObject = {};
        this.currentBrowsingJsonObject = {};
        this.visibleCollectionId = '';
        this.currentlyPlayingCollection = '';
        this.videoPlayerDivId = 'video_player';
        this.currentPlayingLocation = '';
        this.currentlyPlayingCollection = '';
        this.currentlyPlayingVideoId = '';
        this.urlKeysCollectionMap = new Array();
        this.contentUrlsObject = {};
        this.rssUrlsObject = {};
        this.collectionNamesArray = [];
        this.xmlDoc = '';
        this.collectionObjects = {};
        this.currentVideoDetailsJsonObject = {};
        this.nextVideoId = '';
        this.collectionsXMLPath = "content/video/";

        //will use updateVideoThumbnailVisual,videoCenterPageUrl,getVideoDetails,loadCollectionsDoc,getUrlParam from util object
        this.utilVideoObj = new dj.widget.video.video('', 'utilVideoObj');
        this.nextVideoId = '';
        this.nextVideoDetailsJsonObject = {};
        this.skipCollection = true;
        popattic = this;
    },
    getName: function() {
        return this.objName;
    },
    loadVideo: function() {
        this.createFlashPlayer();
    },
    continueLoadVideo: function() {
        var srcUrl = window.location.href;
        this.currentPlayingLocation = this.utilVideoObj.getUrlParam(srcUrl, 'currentPlayingLocation');
        this.currentlyPlayingCollection = unescape(this.utilVideoObj.getUrlParam(srcUrl, 'currentlyPlayingCollection'));
        this.currentlyPlayingVideoId = this.utilVideoObj.getUrlParam(srcUrl, 'currentlyPlayingVideoId');

        this.xmlDoc = this.utilVideoObj.loadCollectionsDoc(videoSiteRoot + popattic.collectionsXMLPath);
        this.parseInformationFromXmlDoc();
        this.createPopUpFramework();
        this.popPopulateSelect();
        //For testing
        //this.currentlyPlayingVideoId = '{DE334C59-4C75-420A-855F-9F3DFC3C15A6}';
        //this.currentlyPlayingCollection = 'News';
        this.playVideoByVideoId(this.currentlyPlayingVideoId, this.currentPlayingLocation);
        //can be made async - to-do
        if (this.currentlyPlayingCollection === '') {
            this.currentlyPlayingCollection = this.defaultCollectionName;
            if (this.currentVideoDetailsJsonObject["mw-channel"] !== void 0) {
                for (var item in this.collectionObjects) {
                    if (this.collectionObjects[item].name === this.currentVideoDetailsJsonObject["mw-channel"]) {
                        this.currentlyPlayingCollection = this.collectionObjects[item].urlkey;
                        break;

                    }
                }
            }
        }
        this.popSelectSetDisplay(this.currentlyPlayingCollection);

        this.getVideos(this.collectionObjects[this.currentlyPlayingCollection].contentUrl + '&count=15', '', false);
        this.popPopulateVideos(1);
        this.popPopulatePagination(1);
        this.utilVideoObj.updateVideoThumbnailVisual('', this.currentlyPlayingVideoId);
        this.updateSelect(this.currentlyPlayingCollection);
        this.createNextVideoParams();
        this.currentBrowsingJsonObject = this.currentPlayingJsonObject;
        this.populateVideoSummary(this.currentVideoDetailsJsonObject.name,
                this.currentVideoDetailsJsonObject.description,
                this.currentVideoDetailsJsonObject.formattedCreationDate,
                this.currentVideoDetailsJsonObject.duration,
                this.currentVideoDetailsJsonObject.relatedLinkText,
                this.currentVideoDetailsJsonObject.relatedLinkHref);
        this.visibleCollectionId = this.currentlyPlayingCollection;
    },
    createNextVideoParams: function() {
        this.nextVideoId = this.getNextVideoId();
        var url = '/api-video/get_video_info.asp?site=mw&guid=' + this.nextVideoId + '&fields=all';
        this.getVideos(url, 'next', true);
    },
    popThumbnailClicked: function(videoId) {
        this.utilVideoObj.updateVideoThumbnailVisual(this.currentlyPlayingVideoId, videoId);
        this.currentPlayingJsonObject = this.currentBrowsingJsonObject;
        this.convertCurrentPlayingJsonToIdsArray();

        this.currentlyPlayingCollection = this.visibleCollectionId;
        this.currentlyPlayingVideoId = videoId;
        this.playVideoByVideoId(videoId);
        this.createNextVideoParams();
        this.populateVideoSummary(this.currentVideoDetailsJsonObject.name,
                this.currentVideoDetailsJsonObject.description,
                this.currentVideoDetailsJsonObject.formattedCreationDate,
                this.currentVideoDetailsJsonObject.duration,
                this.currentVideoDetailsJsonObject.relatedLinkText,
                this.currentVideoDetailsJsonObject.relatedLinkHref);
        //this.nextVideoId = this.getNextVideoId();
    },
    updateSelect: function(collName) {
        $(collName).selected = 'true';
    },
    createPopUpFramework: function() {
        if ($(this.videoResultsDivId)) {
            var str = '';
            str += '<ul id="popPagination" class="arrows">';
            str += '</ul>';
            //str += '<h3>More Video in</h3>';
            str += '<form id="selForm" action="" method="">';
            str += '</form>';
            str += '<ul id="popVideoList" class="video videoPlaylist">';
            str += '</ul>';
            $(this.videoResultsDivId).html(str);
        }
    },


    playVideoByParam: function(params) {
        var adZone = ""; //new dj.util.Ads().getRegisteredAdsZone(''); //adZone - new dj.util.Ads().getRegisteredAdsZone('')
        var lineup = this.currentlyPlayingCollection; //lineup - collection / subcollection name
        params.adZone = adZone;
        params.lineup = lineup;
        params.emailPartnerID = 110626;
        params.site = "video.marketwatch.com";
        params.playerName = "video_popup";
        params.embedPlayerURL = this.utilVideoObj.flashPlayerPath + "main.swf";
        params.embedConfigURL = this.utilVideoObj.embedConfigURL;
        params.embedPlayerID = "2001";
        params.embedName = "popupflashPlayer"; //Name of the flash object
        params.embedBaseURL = this.utilVideoObj.flashPlayerPath;
        params.embedHeight = 363;
        params.embedWidth = 512;
        params.larsSourceID = 92;
        params.larsID = 92;
        params.larsAdTrackingID = 1260;
        params.adFrmt = "frmt=0;";

        params.prop5 = window.location.href.split('?')[0];
        params.prop6 = window.location.href;
        params.prop10 = this.getUrlParam(window.location.href, 'siteid');
        params.prop11 = document.referrer;
        params.prop19 = "video_popup";
        params.prop25 = window.mwu2id;
        params.prop27 = (this.isNotBlankOrNull(params.prop25)) ? "MW_mem_yes" : "MW_mem_no";

        var subSecComponent = this.omnitureEncoding(this.getUrlParam(document.location.href, "currentlyPlayingCollection"), this.getUrlParam(document.location.href, "currentlyPlayingSubCollection"), 's');
        var secComponent = this.omnitureEncoding(this.getUrlParam(document.location.href, "currentlyPlayingCollection"), this.getUrlParam(document.location.href, "currentlyPlayingSubCollection"), 'c');
        params.prop2 = "MW_" + secComponent;
        params.prop3 = "MW_Multimedia_Video_" + secComponent;
        params.prop22 = "MW_Multimedia_Video_" + subSecComponent;
        params.prop26 = "MW_" + subSecComponent;

        params["wsj-section"] = params["mw-channel"];
        params["wsj-subsection"] = params["mw-subchannel"];

        swfobject.getObjectById("popupflashPlayer").playVideo(JSON.stringify(params));
    },

    getVideos: function(purl, userAction, async) {
        var fun = this.handleResponse;
        if (userAction == 'toBrowse') {
            fun = this.handleBrowsingResults;
        }
        if (userAction == 'next') {
            fun = this.handleNext;
        }

        $.ajax({ url: this.proxyUrl(purl),
            type: "GET",
            async: async,
            success: fun,
            error: this.handleFailure,
            dataType: "json"
        });
    },
    handleFailure: function(obj, url, userAction, async) {
        setTimeout("" + this.getName() + ".getVideos('" + url + "','" + userAction + "','" + async + "')", 10000);
    },
    handleResponse: function(json) {
        popattic.currentPlayingJsonObject = json;
        popattic.convertCurrentPlayingJsonToIdsArray();
    },
    handleBrowsingResults: function(json) {
        popattic.currentBrowsingJsonObject = json;
        popattic.popPopulateVideos(1);
        popattic.popPopulatePagination(1);
    },
    handleNext: function(json) {
        popattic.nextVideoDetailsJsonObject = json;
    },
    convertCurrentPlayingJsonToIdsArray: function() {
        if (this.currentPlayingJsonObject.items.length > 0) {
            for (var index = 0, len = this.currentPlayingJsonObject.items.length; index < len; ++index) {
                this.currentlyPlayingVideoIds[index] = this.currentPlayingJsonObject.items[index].id;
            }
        }
    },
    playVideoByVideoId: function(videoId, duration) {
        this.currentVideoDetailsJsonObject = this.utilVideoObj.getVideoDetails({
            'id': videoId,
            'fields': 'all'
        });
        this.currentVideoDetailsJsonObject.seekTime = duration;
        this.playVideoByParam(this.currentVideoDetailsJsonObject);
    },

    popPopulateVideos: function(pageNumber) {
        var varToDisplay = '';
        // Change the variable to display on the basis of user action
        if (this.userAction == 'toBrowse') {
            if (typeof this.currentBrowsingJsonObject != "undefined") {
                varToDisplay = this.currentBrowsingJsonObject.items;
            }
        }
        else {
            varToDisplay = this.currentPlayingJsonObject.items;
        }
        var startIndex = (pageNumber - 1);
        var endIndex = Math.min(startIndex + 3, varToDisplay.length - 1);
        var str = '';
        for (var i = startIndex; i < endIndex + 1; i++) {
            var title = varToDisplay[i];
            str += '<li class="" id="li_' + title.id + '">';
            str += '<a href="#" onClick="' + this.getName() + '.popThumbnailClicked(\'' + title.id + '\')" id="' + title.id + '" style="background-image: url(' + unescape(title.thumbnailURL) + ');" class="preview"><div id="np_' + title.id + '" class="playOverlay">&nbsp;</div></a>';
            str += '<a href="#" onClick="' + this.getName() + '.popThumbnailClicked(\'' + title.id + '\')">' + title.name + '</a>';
            var minutes = Math.floor(title.duration / 60);
            var seconds = title.duration % 60;
            if (seconds < 10) {
                seconds = '0' + seconds;
            }
            str += ' <small>' + minutes + ':' + seconds + '</small>';
            str += '</li>';
        }
        $("#popVideoList").html(str);
    },

    popPopulatePagination: function(pageNumber) {
        var varToDisplay = '';

        // Change the variable to display on the basis of user action
        if (this.userAction == 'toBrowse') {
            if (typeof this.currentBrowsingJsonObject != "undefined") {
                varToDisplay = this.currentBrowsingJsonObject.items;
            }
        }
        else {
            varToDisplay = this.currentPlayingJsonObject.items;
        }

        var lastPageNumber = Math.max(varToDisplay.length - 3, 1);
        var str = '';
        if (pageNumber == 1) {
            str += '<li class="prev"><a><span></span></a></li>';
        }
        else {
            str += '<li class="prev"><a href="javascript:' + this.getName() + '.popPaginationClicked(' + (Number(pageNumber) - 1) + ')"><span></span></a></li>';
        }
        if (pageNumber == lastPageNumber) {
            str += '<li class="next"><a><span></span></a></li>';
        }
        else {
            str += '<li class="next"><a href="javascript:' + this.getName() + '.popPaginationClicked(' + (Number(pageNumber) + 1) + ')"><span></span></a></li>';
        }
        $("#popPagination").html(str);
    },

    popPaginationClicked: function(pageNumber) {
        this.popPopulatePagination(pageNumber);
        this.popPopulateVideos(pageNumber);
        this.utilVideoObj.updateVideoThumbnailVisual('', this.currentlyPlayingVideoId);
    },
    popPopulateSelect: function() {
        var str = '';
        str += '<select id="popSelect" onChange="javascript:' + this.getName() + '.popSelectChanged(this.value)">';
        var collectionArray = this.xmlDoc.getElementsByTagName("collection");
        for (var index = 0, len = collectionArray.length; index < len; ++index) {
            var item = collectionArray[index];
            if (item.getAttribute("name") != "Special Packages") {
                str += '<option value="' + item.getAttribute("urlkey") + '" id="' + item.getAttribute("urlkey") + '">' + item.getAttribute("name") + '</option>';
            }
        }
        str += '<option value="See More Video" id="See More Video">See More Video</option>';
        str += '</select>';
        $("#selForm").html(str);
    },
    popSelectChanged: function(collectionName) {
        if (collectionName == 'See More Video') {
            window.open(this.utilVideoObj.videoCenterPageUrl);
            return;
        }
        if (collectionName != this.currentlyPlayingCollection) {
            this.userAction = 'toBrowse';
            $("#popVideoList").html('<p class="noResults"> Loading ... </p>');
            this.getVideos(this.collectionObjects[collectionName].contentUrl + '&count=15', this.userAction, true);
            this.popPopulateVideos(1);
            this.popPopulatePagination(1);
        }
        else {
            this.userAction = '';
            this.popPopulateVideos(1);
            this.popPopulatePagination(1);
            this.utilVideoObj.updateVideoThumbnailVisual('', this.currentlyPlayingVideoId);
        }
    },
    popSelectSetDisplay: function(collectionName) {
        var popSel = document.getElementById("popSelect");
        for (var i = 0; i < popSel.length; i++) {
            if (popSel[i].value === collectionName) {
                popSel[i].selected = true;
            }
            else {
                popSel[i].selected = false;
            }
        }



    },
    createFlashPlayer: function() {
        var dim = { w: "512", h: "363" };
        if ($(this.videoPlayerDivId)) {
            swfobject.embedSWF(this.utilVideoObj.flashPlayerPath + "main.swf", this.videoPlayerDivId, dim.w, dim.h, "9.0.0", "", {
                'objName': this.getName(),
                'movieWidth': dim.w,
                'movieHeight': dim.h,
                'host': location.host
            }, {
                allowscriptaccess: "always"
            }, {
                id: "popupflashPlayer"
            });

        }
    },

    getUrlParam: function(srcUrl, name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(srcUrl);
        if (results === null) {
            return "";
        }
        else {
            return results[1];
        }
    },
    updateVideoThumbnailVisual: function(cleanId, applyId) {
        $(document.getElementById("np_" + cleanId)).removeClass("nowPlaying").addClass("playOverlay");
        $(document.getElementById("np_" + applyId)).removeClass("playOverlay").addClass("nowPlaying");
    },

    isNotBlankOrNull: function(strVar) {
        return (strVar !== '' && strVar !== null && typeof strVar != 'undefined');
    },

    parseInformationFromXmlDoc: function() {
        var collectionArray = this.xmlDoc.documentElement.getElementsByTagName("collection");

        for (var index = 0; index < collectionArray.length; ++index) {
            var item = collectionArray[index];
            if (item) {
                //alert(item.getAttribute("urlkey"));
                if (item.getAttribute("urlkey")) {
                    this.collectionNamesArray[index] = item.getAttribute("name")

                    this.collectionObjects[item.getAttribute("urlkey")] = {
                        contentUrl: item.getAttribute("contenturl"),
                        name: item.getAttribute("name"),
                        rssUrl: item.getAttribute("rssurl"),
                        urlkey: item.getAttribute("urlkey"),
                        internalUrl: item.getAttribute("internalurl"),
                        sponsored: item.getAttribute("sponsored"),
                        parent: null
                    };

                    var subCollectionArray = item.getElementsByTagName("subcollection");
                    var subCollectionArrayLength = subCollectionArray.length;

                    for (var sindex = 0; sindex < subCollectionArray.length; ++sindex) {
                        var sitem = subCollectionArray[sindex];
                        if (sitem && sitem.getAttribute("urlkey")) {
                            this.collectionObjects[sitem.getAttribute("urlkey")] = {
                                contentUrl: sitem.getAttribute("contenturl"),
                                name: sitem.getAttribute("name"),
                                rssUrl: sitem.getAttribute("rssurl"),
                                urlkey: sitem.getAttribute("urlkey"),
                                internalUrl: item.getAttribute("internalurl"),
                                sponsored: item.getAttribute("sponsored"),
                                parent: this.collectionObjects[item.getAttribute("urlkey")]
                            };
                        }
                    }
                }
            }
        }

        this.collectionObjects[""] = {
            contentUrl: "",
            name: "",
            rssUrl: "",
            urlkey: "",
            internalUrl: "",
            parent: null
        };

    },
    //Called by flash player - upon finishing a video
    playNextVideo: function() {
        if (this.nextVideoId !== '') {
            //alert(this.currentlyPlayingVideoId + "  " + this.nextVideoDetailsJsonObject.id);
            this.utilVideoObj.updateVideoThumbnailVisual(this.currentlyPlayingVideoId, this.nextVideoDetailsJsonObject.id);
            this.currentlyPlayingVideoId = this.nextVideoDetailsJsonObject.id;
            this.playVideoByParam(this.nextVideoDetailsJsonObject);
            this.populateVideoSummary(this.nextVideoDetailsJsonObject.name,
                this.nextVideoDetailsJsonObject.description,
                this.nextVideoDetailsJsonObject.formattedCreationDate,
                this.nextVideoDetailsJsonObject.duration,
                this.nextVideoDetailsJsonObject.relatedLinkText,
                this.nextVideoDetailsJsonObject.relatedLinkHref);
            this.createNextVideoParams();
        }
    },
    populateVideoSummary: function(name, description, formattedCreationDate, videoDuration, relatedText, relatedHref) {
        if ($(this.videoSummaryDivId)) {
            var str = '';
            try {
                var minutes = Math.floor(videoDuration / 60);
                var seconds = videoDuration % 60;
                if (seconds < 10) {
                    seconds = '0' + seconds;
                }
                str += '<br/><div class="videoHeadline">' + name;
                str += '</div>';
                str += '<div class="videoTimestamp">' + minutes + ':' + seconds + '</div>';
                //                str += '<div class="videoCaption">' + description + '</div>';

                //                if (relatedText !== (void 0) && relatedText != '') {
                //                    if (relatedHref.indexOf("www.marketwatch.com") > -1) {
                //                        str += '<div class="relatedLink">Related: <a href="' + relatedHref + '">' + relatedText + '</a></div>';
                //                    } else {
                //                        str += '<div class="relatedLink">Related: <a href="' + relatedHref + '" target="_blank">' + relatedText + '</a></div>';
                //                    }
                //                }
            }
            catch (e) {
                console.error("Error occured in populateVideoSummary." + e.message);
                str += 'Couldn\'t get video summary.';
            }
            $(this.videoSummaryDivId).html(str);
        }
    },
    getNextVideoId: function() {
        if (this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) == -1) { //can happen only while testing
            return this.currentlyPlayingVideoIds[0];
        }
        if (this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) < (this.currentlyPlayingVideoIds.length - 1)) {
            return this.currentlyPlayingVideoIds[this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) + 1];
        }
        if (this.currentlyPlayingVideoIds.indexOf(this.currentlyPlayingVideoId) == (this.currentlyPlayingVideoIds.length - 1)) {
            return this.getVideoIdFromNextCollection();
        }
    },
    getVideoIdFromNextCollection: function() {
        if (this.collectionNamesArray.indexOf(this.currentlyPlayingCollection) != this.collectionNamesArray.length - 1) {
            if (this.skipCollection) {
                this.currentlyPlayingCollection = this.collectionNamesArray[this.collectionNamesArray.indexOf(this.currentlyPlayingCollection) + 1];
            }
            this.skipCollection = true;
            //this.currentlyPlayingCollection = nextCollection;
            this.getVideos(this.contentUrlsObject[this.currentlyPlayingCollection] + '&count=15', '', false);
            if (this.currentPlayingJsonObject.items.length === 0) {
                this.getVideoIdFromNextCollection();
            }
            else {
                return this.currentPlayingJsonObject.items[0].id;
            }
        }
        else {
            this.currentlyPlayingCollection = this.defaultCollectionName;
            this.skipCollection = false;
            return this.getVideoIdFromNextCollection();
        }
    },
    omnitureEncoding: function(col, subcol, type) {
        // if there is no subcollection, return collection name
        if (type == 's' && subcol == '') {
            return col;
        }
        if (type == 's') {
            return subcol;
        }
        if (type == 'c') {
            return col;
        }
    },
    proxyUrl: function(url) {
        return MarketWatch.getBaseUrl() + "/proxy/http/www.marketwatch.com" + url;
    }
});



