
/**
 * @author drewf
 */

if (!channelv) {
    var channelv = {};
}
channelv.Config = {};

channelv.Config.defaultURL = '/Explore';

channelv.Page = {};


if (window['loadFirebugConsole']) {
    window.loadFirebugConsole();
} else {
    if (!window['console']) {
        window.console = {};
        window.console.info = function(){
        };
        window.console.log = function(){
        };
        window.console.warn = function(){
        };
        window.console.error = window.alert;
    }
}

(function(o){

    o.sceneAliases = {
        "1": "ChannelV",
        "3": "Explore",
        "5": "Social",
        "7": "MyMusic"
    };
    
    o.LEFTCOLUMN_ID = 'left';
    o.CENTER_ID = 'centre'; // a centre? or the center column?
    o.RIGHT_ID = 'right';
    o.MODULE_SERVICE = "http://" + window.location.hostname + "/ContentModuleService.svc/GetContentState?";
    
    o.VideoPlayListController;
    o.VideoPlayListControllerObject;
    o.VideoUserPlayListControllerObject;
    
    o.currentURL = '';
    o.backURL = '';
	o.currentTitle = '';
    $this = o;
    
	o.customStylesIds = [];
	
    $.ajaxSetup({
        cache: false
    });
    
    o.changeScene = function(sceneData){
        var thisURL = this.currentURL;
        
        o.updateDblClickAd();
        
        //console.log(sceneData);
        
        drawColumn($this.LEFTCOLUMN_ID, sceneData);
        drawColumn($this.CENTER_ID, sceneData);
        drawColumn($this.RIGHT_ID, sceneData);
        
        document.title = sceneData.Title;
		this.currentTitle = sceneData.Title;
		var sceneID=sceneData.ID;
		
		$this.trackPage();

		
		if(sceneData.BackgroundImageUrl) {var sceneCustomBgrUrl = sceneData.BackgroundImageUrl;}
		else {var sceneCustomBgrUrl = '';}
		
		if(sceneData.BackgroundGradientUrl) {var sceneCustomGradientUrl = sceneData.BackgroundGradientUrl;}
		else {var sceneCustomGradientUrl = '';}
		
		if(sceneData.BackgroundGradientRepeatType) {var sceneCustomGradientRepeat = sceneData.BackgroundGradientRepeatType;}
		else {var sceneCustomGradientRepeat = '';}
		
		if(sceneData.BackgroundColor) {var sceneCustomBgrColor = sceneData.BackgroundColor;}
		else {var sceneCustomBgrColor = '';}
		

        // set background

		if (thisURL.indexOf("PresenterSearch") > 0)$("#dynamicContent").addClass("microsite_PS")
		else {$("#dynamicContent").removeClass("microsite_PS")}
		
        if (thisURL.indexOf("ChannelV") > 0) {
            $this.clearStageCss(sceneID);
            $("#stage").addClass("stage6");
        }
		if (thisURL.indexOf("Scene2") > 0) {
            $this.clearStageCss(sceneID);
            $("#stage").addClass("stage6");
        }
        if (thisURL.indexOf("Explore") > 0) {
            $this.clearStageCss(sceneID);
            $("#stage").addClass("stage4");
            // $("#stage").removeClass("stage6").addClass("stage4");
        }
		if (thisURL.indexOf("Scene4") > 0) {
            $this.clearStageCss(sceneID);
            $("#stage").addClass("stage4");
        }
        if (thisURL.indexOf("Social") > 0) {
            $this.clearStageCss(sceneID);
            $("#stage").addClass("stage2");
            //$("#stage").removeClass("stage6").addClass("stage2");
        }
		if (thisURL.indexOf("Scene6") > 0) {
            $this.clearStageCss(sceneID);
            $("#stage").addClass("stage2");
        }
        if (thisURL.indexOf("MyMusic") > 0) {
            $this.clearStageCss(sceneID);
			
            $("#stage").addClass("stage0");
            //$("#stage").removeClass("stage6").addClass("stage0");
        }
		if($("#stage[class*='stage']").length<1){	
			$this.clearStageCss(sceneID);
			$("#stage").addClass("stage6");	
		}
		
		if(sceneCustomBgrUrl!='' || sceneCustomGradientUrl!='' || sceneCustomBgrColor!=''){
			appendCustomStageStyleToHead(sceneID, sceneCustomBgrUrl, sceneCustomGradientUrl, sceneCustomGradientRepeat,sceneCustomBgrColor)
			
				$("#stage").addClass('customStage');
				$("#dynamicContent").addClass('customBgrDC');
			
		}
		
		//$("#stage").removeAttr("style");
        if (thisURL.indexOf("Video") > 0 && thisURL.indexOf("VideoSearch") < 1 && thisURL.indexOf("PresenterSearch") < 1) {
            //, sceneData.BuyLink 
            
            window.setTimeout(function(){
                var _BuyLink = "";
                if (sceneData.PlaylistEntry.BuyLink) _BuyLink = sceneData.PlaylistEntry.BuyLink;
                doPlayOneVideo(sceneData.PlaylistEntry.VideoId, sceneData.PlaylistEntry.ArtistName, sceneData.PlaylistEntry.SongTitle, _BuyLink)
            }, 2000);
        }
        
    };
    
    o.clearStageCss = function(Id){
		$("#stage").removeAttr("style");
        var stageClasses = $("#stage").attr("class");
        stageClassesArr = stageClasses.split(" ");
        for (i = 0; i < stageClassesArr.length; i++) {
            if (stageClassesArr[i].indexOf("microsite_") == 0 || stageClassesArr[i].indexOf("stage") == 0 || stageClassesArr[i].indexOf("customStage") == 0) {$("#stage").removeClass(stageClassesArr[i]);}
        };
		 
		var dynamicContentClasses = $("#dynamicContent").attr("class");
		var dynamicContentClassesArr = dynamicContentClasses.split(" ");
		
		for (j = 0; j < dynamicContentClassesArr.length; j++) {
			if (dynamicContentClassesArr[j].indexOf("customBgrDC") == 0) {
				$("#dynamicContent").removeClass(dynamicContentClassesArr[j]);
				$("head style[title*='customStageBackgrounds']").remove();
				}
		}
			
    };
    
    o.onSliderChange = function(e, i){
    
        var sceneId = String(i + 1);
        
        if ($this.sceneAliases[sceneId]) {
            sceneId = $this.sceneAliases[sceneId];
        } else {
            sceneId = 'Scene' + sceneId;
        }
        
        var url = '/' + sceneId;
        
        if (url == $this.currentURL) return;
        
        $.historyLoad(url);
    }
    
    o.init = function(){
        $.historyInit(channelv.Page.onHistoryChange);
        
        setupNavigationLinks();
        o.initPlaylist();
        channelv.Slider.bind("sliderchange", o.onSliderChange);
        
        if ($.historyCurrentHash == '#' || $.historyCurrentHash == '') {
            var url = channelv.Config.defaultURL;
            $.historyLoad(url);
        }
        
        $.addthis('publishername');
        
    }
    
    
    o.navigationRequest = function(url){
        if (url == $this.currentURL) return;
        $this.backURL = $this.currentURL;
        $.historyLoad(url);
    };
    
    o.onHistoryChange = function(hash){
    
        if (String(hash).indexOf('&') > 0) {
            hash = String(hash).split('&')[0];
        }
        
        $this.currentURL = hash;
        
        var section = String(hash).split("/")[1];
        var sceneNumber = /\d+/.exec(section);
        
        if (sceneNumber != null) {
            sceneNumber = Number(sceneNumber[0]);
        } else {
            $.each(o.sceneAliases, function(key, value){
                if (value == section) {
                    sceneNumber = Number(key);
                }
            });
        }
        
        //console.log(hash);
        
        channelv.Slider.gotoSegment(channelv.Slider.SEGMENTS - (sceneNumber - 1));
        
        $.ajax({
            url: $this.MODULE_SERVICE + 'urlParametersString=' + encodeURIComponent(hash),
            success: $this.onModuleService,
            cache: false
        });
        
    };
    
    o.onModuleService = function(data){
        var modules = $.evalJSON(data);
        $this.changeScene(modules);
    };
    
    o.trackPage = function(u, g){
		
		var url = $this.currentURL;
		if (u) {
			url += u;
		} 
		
		pageTracker._trackPageview(url);
		var Title = document.title;
		Title  = Title.replace(" ", "+")
		
		trac.pvar.page_url=escape(window.location.href.replace(window.location.hostname + '/#', window.location.hostname));
		
		if (g) {
			trac.slideEvent(g);
			//console.log(g+ '_' + url)
		} else {
			trac.pageEvent(Title);
			//console.log('page_'+Title+ '_' + url);
		}
		
    };
    
    o.updateDblClickAd = function(subURL){
    	//console.log(subURL)
        var scriptUrl = $this.currentURL;
        if (subURL) {
            scriptUrl += subURL;
        }
        
        var sizes = {
            "leaderboard": "728x90",
            "island": "300x250"
        };
        
		var ord =  new Date().getTime();
		 
        $('.doubleclickAd').each(function(i){
            var size = sizes[this.id].split('x');
           
            var url = 'http://ad.doubleclick.net/adi/mcn.channelv.com.au' + scriptUrl + ';sz=' + sizes[this.id] + ';ord=' + ord;
            
            url += (sizes[this.id] != '300x250') ? ';dcopt=ist;tile=1' : ';tile=2';
            
            $(this).html('<div id="adWrap"><iframe frameborder="0" scrolling="no" src="' + url + '" style="width:' + size[0] + 'px; height:' + size[1] + 'px;"></iframe><span class="adFoot">Advertisment</span></div>');
            
        });
        
    };
    
    o.initPlaylist = function(){
        $.getJSON('http://' + window.location.hostname + '/MediaPlayerService.svc/GetDefaultPlaylists', onGetPlaylist);
        // $.getJSON('http://' + window.location.hostname + '/fakeJson2.asp', onGetPlaylist);
    
    };
    
    
    function onGetPlaylist(data){
        $this.VideoPlayListController = new $.fn.ViderPlayListManager();
        $.get("Templates/Static/VideoPlatList.htm", function(playListHTML){
            var _html = $(playListHTML);
            var domStr = '';
            //data[data.length]={"Entries":[],"PlaylistId":"AdHoc"};
            $(data).each(function(i){
                domStr += $this.VideoPlayListController.CreatePlayListHTMLString(this, i);
            })
            
            $('div.PlayListHTMLTemplate', _html).append(domStr);
            $('.videoController').append(_html);
            $('.videoController [jsClass]').each(function(){
                $.getScript('js/' + $(this).attr('jsClass') + '.js');
            });
            
            $('#' + $this.VideoPlayListController.VarValue('VideoNavWrapperDOMID')).find($this.VideoPlayListController.VarValue('sortablePlayListClassName')).each(function(){
                if ($(this).find('li').length > 0) {
                    $this.VideoPlayListController.SetClientPlayList(this); //Create a playlist as whole
                    $this.VideoPlayListController.BindEvents(this);
                }
            });
            
            $this.VideoPlayListControllerObject = $this.VideoPlayListController.InstanciatePlayListController();
            //$this.VideoPlayListControllerObject.AdHocId = "";
            //$this.VideoPlayListControllerObject.TempAdHocId = "";
        
            var _initialPlaylist = ($this.VideoPlayListControllerObject.GetCurrentlyPlayedPlayListInFlash());
            var _initialSongid = ($("ul#" + _initialPlaylist).find('li').eq(0).attr('songid'));
        
            $this.VideoPlayListControllerObject.SetCurrentlySelectedVideoInHTML(_initialSongid);
        
        });
        
        
        
    }
    /** end okkey code */
    
    function drawColumn(columnId, sceneData){
    
    
        var oldModuleIds = [];
        var newModules = [];
        var removeModules = [];
        var column = $('#' + columnId);
        
        // get the old modules in this column
        $('.module', column).each(function(){
            oldModuleIds.push(this.id);
        });
        
        // get the new modules in this column
        $.each(sceneData.ScenePositions, function(i){
            if (columnId.toLowerCase() == sceneData.ScenePositions[i].PanelName.toLowerCase()) {
                newModules.push(sceneData.ScenePositions[i]);
            }
        });
        
        // find the old module id's that are not in the newmodules list
        $.each(oldModuleIds, function(i){
            var found = false;
            for (var x = 0; x < newModules.length; x++) {
                if (newModules[x].ModuleID == oldModuleIds[i]) {
                    found = true;
                    newModules[x].loaded = true;
                }
            }
            
            if (!found) {
                removeModules.push(oldModuleIds[i]);
            }
        });
        
        // remove modules in the column that are not in the new list
        $.each(removeModules, function(i){
            var t = $('#' + removeModules[i]);
            t.remove();
        });
        
        newModules.sort(function(a, b){
            return (b.Order - a.Order);
        })
        
        $.each(newModules, function(i){
            if (!newModules[i].loaded) {
                drawModule(newModules[i], newModules[i - 1]);
            }
        });
        
    }
    
    function setupNavigationLinks(){
        $('.navURL').live('click', function(){
            var url = $(this).attr('href');
            if ($.browser.msie) {
                var rx = /\b(https?|ftp):\/\/([\-A-Z0-9.]+)(\/[\-A-Z0-9+&@#\/%=~_|!:,.;]*)?(\?[A-Z0-9+&@#\/%=~_|!:,.;]*)?/i;
                var urlparts = rx.exec(url);
                if (urlparts != null) {
                    url = urlparts[3];
                }
            }
            $this.navigationRequest(url);
            return false;
        });
        
        $('.returnURL').live('click', function(){
            var re = /(returnURL=)(.*)&?/i;
            var match = re.exec(location.hash);
            if (match != null) {
                returnURL = match[2];
            } else {
                returnURL = "";
            }
            if (returnURL != "") {
                $this.navigationRequest(returnURL);
            }
            return false;
        });
        
        $('.regURL').live('click', function(){
            var url = $(this).attr('href');
            if ($.browser.msie) {
                var rx = /\b(https?|ftp):\/\/([\-A-Z0-9.]+)(\/[\-A-Z0-9+&@#\/%=~_|!:,.;]*)?(\?[A-Z0-9+&@#\/%=~_|!:,.;]*)?/i;
                var urlparts = rx.exec(url);
                if (urlparts != null) {
                    url = urlparts[3];
                }
            }
            
            $this.navigationRequest(url + '&returnURL=' + $this.currentURL);
            return false;
        });
		
		$('.gobackURL').live('click', function(){
            var url = $this.backURL;
            if ($.browser.msie) {
                var rx = /\b(https?|ftp):\/\/([\-A-Z0-9.]+)(\/[\-A-Z0-9+&@#\/%=~_|!:,.;]*)?(\?[A-Z0-9+&@#\/%=~_|!:,.;]*)?/i;
                var urlparts = rx.exec(url);
                if (urlparts != null) {
                    url = urlparts[3];
                }
            }
            
            $this.navigationRequest(url);
            return false;
        });
        
    }
    
    function drawModule(module, before){
        var html = '<div id="' + module.ModuleID + '" class="module container">' + module.ModuleHtml + '</div>';
        var ele = $(html).hide();
        
        if (before) {
            $('#' + before.ModuleID).before(ele);
        } else {
            $('#' + module.PanelName.toLowerCase()).append(ele);
        }
        
        $('[jsClass]', html).each(function(){
            //$.getScript('js/' + $(this).attr('jsClass') + '.js');
			$.ajax({
				url: 'js/' + $(this).attr('jsClass') + '.js',
				dataType: 'script',
				cache: true
			})
        });
        
        //ele.css({opacity:0,display:"block"}).animate({"opacity":1},1500)
        /*if ($.browser.version < 7) ele.show();
         else ele.css({
         opacity: 0,
         display: "block"
         }).animate({
         "opacity": 1
         }, 1500);
         */
		 
		 if (module.ModuleStyle!="") {
			 appendStyleToHead(module.ModuleID,module.ModuleStyle);
		 }
        ele.show();
    }
    
    
})(channelv.Page);

// add page initialization to document.ready que
$(channelv.Page.init);


