var d=new Date();
var clientName;
var pageID;

//////////////////////////////////////////////////////////////////////////////////////////////////////
jQuery(function($) { 
	  getPageIDconsumerType();
	  addAdditionalCss();
	  getChannelInfo();
});


(function(){
	var html5elmeents = "address|article|aside|audio|canvas|command|datalist|details|dialog|figure|figcaption|footer|header|hgroup|keygen|mark|meter|menu|nav|progress|ruby|section|time|video".split('|');
	for(var i = 0; i < html5elmeents.length; i++){
		document.createElement(html5elmeents[i]);
  }
})();

//////////////////////////////////////////////////////////////////////////////////////////////////////
function getPageIDconsumerType(){	// get the current URL
	
	var url = window.location.toString();
	//get the parameters
	url.match(/\?(.+)$/);
	var params = RegExp.$1;
	// split up the query string and store in an
	// associative array
	var params = params.split("&");
	var queryStringList = {};
	
	for(var i=0;i<params.length;i++)
	{
	   var tmp = params[i].split("=");
	   queryStringList[tmp[0]] = unescape(tmp[1]);
	}
	
	
	var arr = new Array(2);
	var j = 0;
	for(var i in queryStringList){
	   arr[j] = queryStringList[i];
		j++;
	 }
	 clientName = arr[0];
	 pageID = arr[1];	
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
function addAdditionalCss(){
	$("#divLogo").append("<img id='logoImg'>");
	
	$("#logoImg").attr("src","/images/"+clientName+".png"); 
	$("#logoImg").attr("border","0"); 
	
	$('#greatphoto').attr('alt', 'Beijing Brush Seller');
	if (clientName == "cisco"){
		$("#divLogo").css({"background-color":"#005569"});
		$("#divLogo img").css({"position":"relative","left":"-440px"});
	}else if (clientName == "acnuk"){
		$("#divLogo img").css({"position":"relative","left":"-400px"});
	}else if (clientName == "marketing"){
		if  (customerName == "akamai"){
			$("#divLogo").css({"background-color":""});
			$("#divLogo").css({"background-image":"url(/images/akamai_logo_bg.gif)", "background-repeat":"repeat-x"});
			$("#divLogo img").css({"position":"relative","left":"-430px"});
		}
	}

}
//////////////////////////////////////////////////////////////////////////////////////////////////////

function getChannelInfo(){
	
	var channelNum, playlistNum, channelTitle, playlistID, playlistTitle

	$.ajax({
       type: "GET",
       url: "http://evssprodgateway.odaptor.com/channel/en-us/json/"+clientName+"/page/"+pageID, //add the time stamp and specified format to the end
       dataType: "jsonp",
       cache: true,
       //contentType: "application/json",
       success: function(data) {

	//$.getJSON("http://evssprodgateway.odaptor.com/channel/en-us/json/"+clientName+"/page/"+pageID+"?_="+d.getTime(), function(data) {
	//$.getJSON('http://'+document.location.host+'/evss/channel/en-us/json/cisco/page/'+pageID, function(data) {
		//$.getJSON("http://evssprodgateway.odaptor.com/channel/en-us/json/"+clientName+"page/"+pageID+"?callback=?", function(data) {
		$.each(data, function(i, item){ 
			if (item.channel.channels != undefined){
				channelNum = item.channel.channels.length;
				//alert(channelNum)
			}
			//for(var m=0; m<channelNum; m++){
				playlistNum = item.channel.positions.length;
				
				channelTitle =  item.channel.title;
				//alert(channelTitle)
				if (playlistNum > 0 ){
					for (var j=0; j<playlistNum; j++){
						playlistID = item.channel.positions[j].id;
						playlistTitle= channelTitle +" : " + item.channel.positions[j].title;
						GetPlaylistInfo(playlistID, playlistTitle, j)
					}
				}else{
					playlistID = item.channel.positions.id;
					playlistTitle= item.channel.positions.title;
					GetPlaylistInfo(playlistID, playlistTitle, 1)
				}
			//}
		});
	//});
	 }
	})
}

////////////////////////////////////////////////////////////////////////////////////////////////////
	  
function GetPlaylistInfo(playlistID, playlistTitle, boxNum){	
	
	
	$.ajax({
       type: "GET",
       url: "http://evssprodgateway.odaptor.com/playlist/en-us/json/"+clientName+"/position/"+playlistID, //add the time stamp and specified format to the end
       dataType: "jsonp",
       cache: true,
     //  contentType: "application/json",
       success: function(data) {
	
	//$.getJSON("http://evssprodgateway.odaptor.com/playlist/en-us/json/"+clientName+"/position/"+playlistID, function(data) {
		//$.getJSON('http://'+document.location.host+'/evss/playlist/en-us/json/cisco/position/'+playlistID, function(data) {		
		
		var str="";
		var itemNum;
		var videoProtocol;
		var videoRtmpAppName;
		var videoRtmpHostname;
		var videoStreamName;
		var videoHostApp;
		var videoBitrate
		var ipadURL="";
		
		$.each(data, function(i, item){
			
			var playlistNum = item.playlist; 
			
			if ((playlistNum!="" && (playlistNum.items.length> 0 || playlistNum.items.id==undefined)) || playlistNum.length == undefined){
				
				str = "<div class='playlistBox' id='playlistBox_"+boxNum+"'><ul title='"+playlistTitle+"'>";
				
				if (item.playlist.items.id==undefined){
					itemNum = item.playlist.items.length;
			    }else{
					itemNum 	= 1;
				}
				var dotNum = Math.ceil(itemNum/6);
				
				for (var m=0; m<dotNum; m++){ 
				
					str = str + "<li>";
					var n_s = m*6;
					var n_e = n_s + 6; 
					
					if (n_e >= itemNum){
						n_e = itemNum;
					}
					
					for (j=n_s; j<n_e;j++){
						var jsonData;
						var videoLength;
						videoStreamName = "";
						
						if (item.playlist.items.id!=undefined){
							jsonData = item.playlist.items;
						}else{
							jsonData = item.playlist.items[j];
						}
						
						if (jsonData.duration!=undefined ){
							videoLength	= jsonData.duration;
						}else{
							if (jsonData.mediaItems==undefined ){
									videoLength			= jsonData.scheduledEvent.duration;
									videoProtocol		= jsonData.scheduledEvent.protocol;
									videoRtmpAppName	= jsonData.scheduledEvent.rtmpAppName;
									videoRtmpHostname	= jsonData.scheduledEvent.rtmpHostName;
									videoBitrate		= jsonData.scheduledEvent.bitrate;
									
									videoStreamName		= jsonData.scheduledEvent.url;
									if(videoStreamName.match("http")){
										videoStreamName 	= videoStreamName.replace("http://" +videoRtmpHostname +"/","")	;
									}
									videoStreamName = videoStreamName + "|" + videoBitrate;
							}else{
								if (jsonData.mediaItems.duration!=undefined ){
									
									videoLength			= jsonData.mediaItems.duration;
									videoProtocol		= jsonData.mediaItems.protocol;
									videoRtmpAppName	= jsonData.mediaItems.rtmpAppName;
									videoRtmpHostname	= jsonData.mediaItems.rtmpHostName;
									videoBitrate		= jsonData.mediaItems.bitrate;
									
									videoStreamName		= jsonData.mediaItems.streamName;
									if(videoStreamName.match("http")){
										videoStreamName 	= videoStreamName.replace("http://" +videoRtmpHostname +"/","")	;
									}
									videoStreamName = videoStreamName + "|" + videoBitrate;
								}else{
									videoLength			= jsonData.mediaItems[0].duration;
									for(var n=0; n<jsonData.mediaItems.length; n++){
										videoProtocol		= jsonData.mediaItems[n].protocol;
										videoRtmpAppName	= jsonData.mediaItems[n].rtmpAppName;
										videoRtmpHostname	= jsonData.mediaItems[n].rtmpHostName;
										videoBitrate		= jsonData.mediaItems[n].bitrate;
										
										if ( (jsonData.mediaItems[n].streamName).match("http")!=null){
											ipadURL = jsonData.mediaItems[n].streamName;
											
										}else{
											if (videoStreamName == "") {
												videoStreamName = jsonData.mediaItems[n].streamName + "|" + videoBitrate;
											}else{
												videoStreamName	= videoStreamName + ", " + jsonData.mediaItems[n].streamName + "|" + videoBitrate;
											}
										}
									}
	
								}
							}
						}
						videoProtocol 	= jQuery.trim(videoProtocol);
						if (videoProtocol == "http") {
							videoProtocol 	= "HD";
							videoHostApp 	= videoRtmpHostname;
						}
						if (videoProtocol == "RTMP" || videoProtocol == "rtmp") {
							videoHostApp 	= videoRtmpHostname + "/" + videoRtmpAppName;
						}
						
						var videoTitle 			= jsonData.name;
						var videoThumbnail		= jsonData.thumbnailUrl;
						var videoDesc			= jsonData.description;
						var videoDateCreated	= jsonData.creationDate;
						
						var videoID				= jsonData.id;
						var videoLiveFlag		= jsonData.features.live;
						//var videoURL			= jsonData.mediaItems.streamName;
						//var videoRegRequired	= jsonData..duration;
						videoDateCreated		= videoDateCreated.substring(0,10);
						videoLength				= converToTimeHM(videoLength);
						
						var strA = '"'+videoProtocol+'", "'+videoHostApp+'", "'+videoStreamName+'", "'+ videoTitle+'", "'+ ipadURL + '"';
						
						var onclickFunction = 'showPlayer('+strA+');'
						
						str = str 	+ "<div id='videoThumb' class='videoThumb' title='" + videoDesc +"' onclick='"+onclickFunction+"'>"
											+ "<div class='videoThumbNail' onmouseover='this.style.opacity=0.5;'onmouseout='this.style.opacity=1.0;'>"
												+ "<img src='"+videoThumbnail+"' class='thumbNail'></div>"
											+ "<div class ='VideoTitle'>" + videoTitle + "</div>"
											+ "<div class='divVideoDate'>" + videoDateCreated + "</div>"
											+ "<div class='videoLength'><p>" + videoLength + "</p></div>"
										+ "</div>";
					}
					str = str + "</li>";
				}
				
			}
		
		});
		str = str + "</ul></div>"
		
		$("#divVideoThumbList").append(str);
		
		$("#playlistBox_"+boxNum).webwidget_slideshow_dot({
			slideshow_time_interval: '5000',
			slideshow_window_width: '958',
			slideshow_window_height: '200',
			slideshow_title_color: '#333333',
			slideshow_foreColor: '#e5e5e5',
			directory: '/images/'
		});
	//});
	 }
	})
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////
function showPlayer(videoProtocol,videoHostApp,videoStreamName,videoTitle, ipadURL){
	
	videoObj1 = {
					_protocol:videoProtocol,
					hostApp:videoHostApp,
					videoFeeds: videoStreamName,
					eventType : "vod",
					thumbnailURL : "",
					seekOffset : "0",
					clipTitle : videoTitle,
					clipList:"",
					volume : 1
				}
		
		
	// For use within iPad developer UIWebView		
	ua = navigator.userAgent;
	isiPad = /iPad/i.test(ua) || /iPhone OS 3_1_2/i.test(ua) || /iPhone OS 3_2_2/i.test(ua)
	
	if (isiPad && ipadURL.length > 0) {
		var str =  "<video src='"+ipadURL+"' width='780' height='505' controls='controls'>Your browser does not support the video tag.</video>";
		$("#playerLayer").html("");
		$("#playerLayer").append(str);
		
	}else{
		passObj(videoObj1);
	}
	
	$("#dialog").show();
	$("#curtain").show();
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
function createPlayer(){
	var str;	
	
	str = "<div id='playerLayer'><a href='http://www.adobe.com/go/EN_US-H-GET-FLASH'>You need to Get the Flash Player</a>\n"
                   + "<script type='text/javascript'>"
                   + "    var configURL='/embedPlayer/ServiceInit.xml';\n"
                   + "     var width = '780';\n"
                   + "     var height = '505';\n"
                   + "     var liveMode = true; // liveMode = false - enables VOD | true for LIVE \n"
                   + "     var smilPath = ''; \n"
                   + "     var bitRateMeter = false; // true will show bitRateMeter - false will hide bitRateMeter \n"
                                
                   + "     var flashvars = {};\n"
                   + "     flashvars.layer = 'playerLayer';\n"
                   + "     flashvars.configURL= configURL;\n"
                   + "     flashvars.height = height;\n"
                   + "     flashvars.width = width;\n"
                   + "     flashvars.liveMode = liveMode;\n"
                   + "     flashvars.smilPath = smilPath;\n"
                   + "     flashvars.bitRateMeter = bitRateMeter;\n"
                                                        
                   + "     var params = {};\n"
                   + "     params.menu = 'false';\n"
                   + "     params.quality = 'best';\n"
                   + "     params.scale = 'noscale';\n"
                   + "     params.salign = 'tl';\n"
                   + "     params.bgcolor = '#869ca7';\n"
                   + "     params.allowscriptaccess = 'always';\n"
                   + "     params.allowfullscreen = 'true';\n"
                   + "     params.wmode = 'transparent';\n"
                   + "     var attributes = {};"
                   + "     attributes.name = 'flexPlayer';"
                   + "     attributes.align = 'middle';"
                    + "    swfobject.embedSWF('/embedPlayer/main.swf?'+flashvars+ '&t=' + new Date().getTime(), 'playerLayer', width, height, '10.0.0',t=' + new Date().getTime() + '& '/common/flash/expressInstall.swf', 	flashvars, params, attributes );"
                    + "</script></div>";
					
	$("#dialog").append(str);				
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

function hideWindow(){
	
	$("#playerLayer").html("");
	
	createPlayer();
	$("#dialog").hide();
	$("#curtain").hide();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
function converToTimeHM(num){
	var Hours = Math.floor(num/60);
	var Minutes = num%60;
	Minutes	= Math.round(Minutes);
	
	if (Minutes < 10) {
		Minutes = "0" + Minutes;
	}
	if (Hours < 10){
		Hours = "0" + Hours;
	}
	var myTime = Hours + ":" + Minutes;
	return myTime;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////


	
	
