ctv.ca.MasterController = function () {
    //InitFlash(Function.createDelegate(this, this.ready));
	//InitCTVFlashXMLHttpRequest("ctvMasterController.ready");
    this.url = ctvConfigController.videoUrl;
    this.clipPlayed = 0;
    this.playingAd = false;
    this.currentClip = null;
    
    this.bid = 0; //bin
    this.sid = 0; //pubset service
    this.id = 0;  //video
    this.vid = 0; //clip
    this.showid = 0;
    this.defaultbid = 0;
	
	this.kickStartTimer = null;
    
    ctv.ca.MasterController.createEvent("requestNextVideo");
    
    //hookup events
    ctvContentStack.add_initDataLoaded(Function.createDelegate(this, this.onInitDataLoaded));
    ctvVideoWindow.add_playstateChange(Function.createDelegate(this, this.onVideoWindowStateChange));
    ctvContentStack.add_playVideo(Function.createDelegate(this, this.onPlayVideo));
    
    //videoWindow
    
    //contentStack
    this.add_requestNextVideo(Function.createDelegate(ctvContentStack, ctvContentStack.onVideoRequest));
    
    //playerControl
    ctvVideoWindow.add_adPlaying(Function.createDelegate(ctvPlayerControl, ctvPlayerControl.onAdPlaying));
   
    //adcontroller
    ctvVideoWindow.add_playstateChange(Function.createDelegate(ctvAdController, ctvAdController.onVideoWindowStateChange));
     
    //tracking controller
    ctvVideoWindow.add_playstateChange(Function.createDelegate(ctvTrackingController, ctvTrackingController.onVideoWindowStateChange));
    ctvVideoWindow.add_positionChange(Function.createDelegate(ctvTrackingController, ctvTrackingController.onVideoWindowPositionChange));
    ctvVideoWindow.add_mediaLength(Function.createDelegate(ctvTrackingController, ctvTrackingController.onVideoWindowMediaLength));
    ctvVideoWindow.add_newMedia(Function.createDelegate(ctvTrackingController, ctvTrackingController.onNewMedia));

}

ctv.ca.MasterController.prototype = {
    ready : function () {
		//this.doGeoChecking();
        ctvAdController.setupAdTracker();
        //ctvContentStack.loadInitData();
        ctvPlayerControl.createUI();
    },
	
	/*
	doGeoChecking : function()
	{
        var xhr = new CTVFlashXMLHttpRequest();
		var url = "http://esi.ctv.ca/esitoken/countrycode/default.aspx";
		xhr.HttpCall("GET", url,"ctvMasterController.processResponse", null);        
    },
    
    processGeoResponse : function(response)
    {
     	var country = XMLParser.parseCountryCode(response[0]);
		
		if (country == 'US')
			window.location = "http://www.comedycentral.com";
		
    },
	*/
	
    loadInitData : function()
    {
//		if (this.bid != 0)
//            ctvContentStack.loadInitData("bid", this.bid);
//        else if (this.sid != 0)
//            ctvContentStack.loadInitData("sid", this.sid);
//        else if (this.id != 0)
//            ctvContentStack.loadInitData("id", this.id);
//        else if (this.vid != 0)
//            ctvContentStack.loadInitData("vid", this.vid);
//        else if (this.showid != 0 && this.defaultbid != 0)
//            ctvContentStack.loadInitShowData(this.showid, this.defaultbid);      

			//wj will load everything from file
		//ctvContentStack.loadXmlFile("xml/tabs.xml");
		
		var xhr = new CTVFlashXMLHttpRequest();        
		xhr.HttpCall("GET", ctvConfigController.tabUrl, "ctvMasterController.processTabResponse");
		
		
    },
	
	loadAndPlayId : function(idType, id)
	{
		ctvContentStack.playLoadedList = true;
		ctvContentStack.loadInitData(idType, id);
	},
    
    playVideo : function (clip) {
		/*
		if (this.playingAd)
		{
			ctvClipQueue.pop();
			ctvClipQueue.push(clip);
			ctvPlayerControl.onSetCurrentTitle(clip.clipTitle);
			return;
		}
		*/
        this.currentClip = clip;
		
		if (clip.clipUrl == "deprecated")
		{
	        //use clip id to get the mms
			var xhr = new CTVFlashXMLHttpRequest();
			
	        var url = this.url + clip.clipId;
			var params = new Array();
			params.push(clip);
			xhr.HttpCall("GET", url,"ctvMasterController.processResponse", params);
		}
		else if (clip.clipUrl.indexOf("http://") == 0)
		{
			//an http returns asx
	        var xhr = new CTVFlashXMLHttpRequest();
			
	        var url = clip.clipUrl;
			var params = new Array();
			params.push(clip);
			xhr.HttpCall("GET", url,"ctvMasterController.processResponse", params);			
		}
		else
		{
			//directly play the url
			var urlArr = new Array();
			urlArr.push(new ctv.ca.MediaUrl(clip.clipUrl, "wmv", "", "", "", clip.clipId, clip.clipTitle, clip.showTypeId, clip.showTypeName, clip.season, clip.episode, clip.clipCat, false));
			ctvPlayerHead = new ctv.ca.PlayerHead(urlArr);
        
			ctvPlayerControl.onSetCurrentTitle(clip.clipTitle);
		
			if (!this.playingAd)
				this.playNextClip();
		}
    },
    
    processTabResponse : function (response)
    {
        var xmlStr = response[0];
        var tabArr = XMLParser.parseTabs(xmlStr);
       
        ctvContentStack.setTabs(tabArr);
        //ctvContentStack.loadXmlFile(tabArr[0].xmlUrl);  
	    ctvContentStack.createUI();
         
    },
    
    processResponse : function(response)
    {
     	var clip = response[0];
		var xmlStr = response[1];
		var urlArr = XMLParser.parseMediaUrls(xmlStr, clip);
        ctvPlayerHead = new ctv.ca.PlayerHead(urlArr);
        
        ctvPlayerControl.onSetCurrentTitle(clip.clipTitle);
		
		if (!this.playingAd)
            this.playNextClip();
		
    },
    
    playNextClip : function() {
		//always play an ad, if the ad slot is not empty
        if (ctvAdPlayerHead.slots.length != 0) {
                var adUrl = ctvAdPlayerHead.slots.shift();
                ctvAdController.currentAdObj = adUrl;
                ctvVideoWindow.PlayVideo(adUrl, adUrl.mediaType);
                this.playingAd = true;
                ctvVideoWindow.onAdPlaying(true);
        } else {
			if (ctvPlayerHead.slots.length != 0)
            {
    			//serve the preroll ad, if needed
                if (ctvConfigController.serveLeadingAd && this.clipPlayed == 0) {
                    ctvConfigController.serveLeadingAd = false;
                    ctvAdController.serveAd(this.currentClip);	
                }
                else if (this.clipPlayed >= ctvConfigController.maxAdGap) {
                    this.clipPlayed = 0;
                    ctvAdController.serveAd(this.currentClip);
                }
                else {
                    ctvAdController.currentAdObj = null;
                    var mediaUrl = ctvPlayerHead.slots.shift();
                    ctvVideoWindow.PlayVideo(mediaUrl, mediaUrl.mediaType);
                    if (mediaUrl.vid > 0)
                        this.clipPlayed++;
						
					//kick start next video if no playstate 3 in 30 s
					clearTimeout(this.kickStartTimer);
					var thisObj = this;
					this.kickStartTimer = setTimeout(function() { thisObj.playNextClip() },1000*20);				 
                }
    		}
    		else
    		{
    			this.requestVideoToPlay();
    		}
        }
        
        /*
        if (ctvConfigController.serveLeadingAd && this.clipPlayed == 0) {
			ctvConfigController.serveLeadingAd = false;
            ctvAdController.serveAd();	
		}
		else if (this.clipPlayed >= ctvConfigController.maxAdGap) {
			this.clipPlayed = 0;
            ctvAdController.serveAd();
		}
		else
		{	
			if (ctvAdPlayerHead.slots.length != 0) {
                var adUrl = ctvAdPlayerHead.slots.shift();
                ctvAdController.currentAdObj = adUrl;
                ctvVideoWindow.PlayVideo(adUrl.url, adUrl.mediaType);
                this.playingAd = true;
                ctvVideoWindow.onAdPlaying(true);
            } else {
                if (ctvPlayerHead.slots.length != 0)
    			{
    				ctvAdController.currentAdObj = null;
                    var mediaUrl = ctvPlayerHead.slots.shift();
    				ctvVideoWindow.PlayVideo(mediaUrl.url, mediaUrl.mediaType);
                    this.clipPlayed++;
                    this.playingAd = false;
                    ctvVideoWindow.onAdPlaying(false);
    			}
    			else
    			{
    				this.requestVideoToPlay();
    			}
            }
		}
    */
    },
    
    endVideo: function () {
        //overwrite
		
	},
    
    requestVideoToPlay : function () {
        this._raiseEvent("requestNextVideo");
    },
    
    onVideoWindowStateChange : function (sender, s) {
        switch (s) {
			case 3:
			case 6:
				//current clip is connected
				clearTimeout(this.kickStartTimer);
				break;
            case 8:
            case 10000:
				clearTimeout(this.kickStartTimer);
				//delay a bit, 
                if (this.playingAd)
                {
                    this.playingAd = false;
                    ctvVideoWindow.onAdPlaying(false);
                }
                var thisObj = this;
                setTimeout(function() { thisObj.playNextClip() },500);
                //this.playNextClip();
				break;
        }
    },
    
    onInitDataLoaded : function (sender, s) {
        this.requestVideoToPlay();
    },
    
    onPlayVideo : function(sender, clip) {
        this.playVideo(clip);
    }
} 

ctv.ca.MasterController.registerClass('ctv.ca.MasterController', Sys.Component);

var ctvMasterController = new ctv.ca.MasterController();
InitCTVFlashXMLHttpRequest("ctvMasterController.ready");

function init()
{
    setTimeout("ctvMasterController.loadInitData()", 500);
}

function finish()
{
    ctvVideoWindow.cleanUp();
}

window.onload = init;

//flash external interface causes ie to fire unload
{
    if (window.addEventListener)
    {    
        window.addEventListener("unload",finish,false);
    }
    else
    {   
        window.attachEvent("onunload",finish)
    }
}





