/**
 * @fileOverview    Behavioral logic for video on iDevices .
 *                  Copyright (C) Discovery.com 2011. All Rights Reserved.
 * @author          <a href="mailto:owais_malik@discovery.com">owais malik</a>
 */

var isIOS=false;
var iOSdevices="iPod,iPad,iPhone,iPhone Simulator,iPad Simulator"; //MacIntel only for testing
if (iOSdevices.indexOf(navigator.platform)>-1) {isIOS=true}  
iVideo = {
      servEnv:'',
	  currentEnv:'',
	  postRollExist:false,
	  currentClip:'',
	  lowerEnv:false,
	  videoPlayerExists:false,
	  fwInitialized:false,
	  testingDomainAlias : {"dev":true,"test":true,"stg":true,"newprod":true,"uat":true},
	
      init:function() {
		var testEnv=(location.hostname).split('.')[1]; 
		this.hostContainsTestSub=this.testingDomainAlias[testEnv];
		console.debug(this.hostContainsTestSub);
		 //this.addCSS('/shared/stylesheets/ivideo.css');
         if(playerApplication!="snag") { 
			 videoContainer=document.getElementById('video-per-page-player');
		 } else {
			 videoContainer=document.getElementById('video-snag-player');
		 }
	     videoContainer.innerHTML='';
		if(this.hostContainsTestSub) {
			this.servEnv=".uat";
			this.lowerEnv=true;
			this.currentEnv="."+(location.hostname).split('.')[1];
		}
		switch(playerApplication) {
			
			case "vap-player" : iVideo.initVAP(); break;
			
			case "hub" : iVideo.initVAP(); break;
			
			case "playlist-player" : iVideo.initPlaylistPlayer(); break;
			
			case "mini-playlist-player" : iVideo.initPlaylistPlayer(); break;
			
			case "snag" : 
				videoContainer.style.width=iframewidth+'px';
				videoContainer.style.height=iframeheight+'px';
				//testLoc="static.discoverymedia.com"; //for testing
				var h=location.hostname.split('.');
				//h=testLoc.split('.'); //for testing
				var l=h.length;
				iframeLoc=h[l-2]+'.'+h[l-1];
				parentLoc=parent.location.hostname;
				iVideo.initVAP();
				break;
		}

     },
	initVAP:function(){
		this.currentClip=clipJSON;
		if(clipJSON.m3u8!="") {
			this.getLocale();
		} else {
			this.createErrorScreen("iOS");
		}
	},
	initPlaylistPlayer:function(){
		var l=playlistClipsJSON.clips.length;
		m3u8Playlist = new Array();
		for (var i=0;i<l;i++) {
			if (playlistClipsJSON.clips[i].m3u8!='') {
				m3u8Playlist.push(i);
			}
		}
		if(m3u8Playlist.length>0) {
			m3u8PlaylistClipNumber=0;
			this.playlistClipPlay(0);
			setTimeout("iVideo.updatePlaylistHTML()",2000);
		} else {
			this.createErrorScreen("iOS");
		}
	
	},
	updatePlaylistHTML:function() {
		console.info("[iV] " + " updatePlaylistHTML");
		if (playerApplication=="playlist-player") {
			var playlistContainer=document.getElementById('playlist-container');
			var lis=playlistContainer.getElementsByTagName('li');
			var l=lis.length;
			for (var i=0;i<l;i++) {
				if(m3u8Playlist.indexOf(i)<0){
					//tables[i].childNodes[1].childNodes[0].childNodes[1].innerHTML='not available';
					lis[i].style.display='none';
				}
			}
		}
	
	},
	playlistClipPlay:function(numb) {
		console.debug("[iV] "+"playlistClipPlay");
		this.currentClip=playlistClipsJSON.clips[m3u8Playlist[numb]];
		this.getLocale();
		if (numb<m3u8Playlist.length) {
			numb++;
			m3u8PlaylistClipNumber=numb;
		}
		/*
		var clipObj = {
			"playlistName":playlistClipsJSON.name,
			"showName":this.currentClip.programTitle,
			"clipLength":this.currentClip.duration,
			"clipName":this.currentClip.episodeTitle,
			"clipId":this.currentClip.clipId,
			"clipRefId":this.currentClip.clipRefId,
			"playerName":playerApplication,
			"syndicationDomain":'',
			"adName":''
		};
		clipNowPlaying(clipObj);
	 */
	},
     initFreeWheel:function(){
       console.debug("[iV] "+"initFreeWheel");
       fw5 = {
			"caid":this.currentClip.clipRefId,
			"ssid":(playerApplication!="snag")?omnitureLookupObject.asset.uuid:this.currentClip.siteSectionId,
			"dur":this.currentClip.duration/1000
		};
		if(iVideo.lowerEnv) {
			fw5.server="http://165a4.v.fwmrm.net";
			fw5.nwid="91556";
			fw5.prof="91556:discovery_Test_HTML5";
		} else {
			fw5.server="http://165a7.v.fwmrm.net";
			fw5.nwid="91559";
			fw5.prof="91559:discovery_live";
		}
	
       this.addScript("http://adm.fwmrm.net/p/release/latest-JS/adm/prd/AdManager.js",iVideo.initAds,true);
	   this.fwInitialized=true;
     },
     initAds:function(){
       console.debug("[iV] "+"initAds");
        freewheelAdManager = new tv.freewheel.SDK.AdManager();
        freewheelAdManager.registerVideoDisplayBase("video-per-page-player");  
        freewheelAdManager.setVideoAsset(fw5.caid, fw5.dur);
        freewheelAdManager.setSiteSection(fw5.ssid);
        freewheelAdManager.setServer(fw5.server+'/ad/g/1?nw='+fw5.nwid+'&prof='+fw5.prof+'&flag=+sltp+exvt+slcb+unka+unks;' );
        freewheelAdManager.submitRequest( iVideo.requestComplete, 2000 );
     },
	moreAds:function() {
		console.debug("[iV] "+"moreAds");
		fw5.caid=this.currentClip.clipRefId;
		fw5.ssid=this.currentClip.siteSection;
		fw5.dur=this.currentClip.duration/1000;
		freewheelAdManager = new tv.freewheel.SDK.AdManager();
        freewheelAdManager.registerVideoDisplayBase("video-per-page-player");
		freewheelAdManager.setVideoAsset(fw5.caid, fw5.dur);
        freewheelAdManager.setSiteSection(fw5.ssid);
		freewheelAdManager.setServer(fw5.server+'/ad/g/1?nw='+fw5.nwid+'&prof='+fw5.prof+'&flag=+sltp+exvt+slcb+unka+unks;' );
		freewheelAdManager.submitRequest( iVideo.requestComplete, 2000 );
	},
     requestComplete:function(e) { 
          console.debug("[iV] "+"requestComplete");
          video.addEventListener("play",iVideo.playFWad);
		  //video.play();
     },
     playFWad:function(){
       iVideo.omniTrackLink("Ad Started");
	   iVideo.fireComscore("Ad Started");
       freewheelAdManager.playSlots( tv.freewheel.SDK.TIME_POSITION_CLASS_PREROLL, iVideo.prerollComplete );
       video.removeEventListener("play",iVideo.playFWad);
	   video.removeEventListener('ended',iVideo.videoComplete,false);
     },
     prerollComplete:function(e){
       console.debug("[iV] "+"prerollComplete");
       iVideo.playMain();
       iVideo.omniTrackLink("Ad Completed");
     },
     createPlayer:function(){
	   
       console.debug("[iV] "+"createPlayer");
	
	   if (!this.videoPlayerExists) {
	  	   video=document.createElement('video');
		   video.setAttribute("controls","controls");
	       video.setAttribute("autoplay","false");
	       if (playerApplication=="mini-playlist-player") {
			   video.setAttribute("width","512px");
		       video.setAttribute("height","288px");
		   } else if (playerApplication=="hub"){
		  	   video.setAttribute("width","384px");
		       video.setAttribute("height","216px");
		   } else {
		 	   video.setAttribute("width","662px");
		       video.setAttribute("height","390px");
		   }
		   switch (playerApplication) {
				case "mini-playlist-player":
					var pWidth="512px";
				    var pHeight="288px";
					break;
				case "hub":
		 		 	var pWidth="384px";
				    var pHeight="216px";
					break;
				case "snag":
					var pWidth=iframewidth+'px';
			    	var pHeight=iframeheight+'px';
					break;
				default:
		     		var pWidth="662px";
			        var pHeight="390px";	
		   }
		   video.setAttribute("width",pWidth);
		   video.setAttribute("height",pHeight);
		   videoContainer.appendChild(video);
		   video.setAttribute("x-webkit-airplay","allow");
		   this.videoPlayerExists=true;
	 }
      if((this.currentClip.videoStill==null) || (this.currentClip.videoStill=='')) {
		video.setAttribute("poster","http://static"+this.currentEnv+".discoverymedia.com/shared/images/browser-cache/indefinite/"+this.currentClip.networkId.toLowerCase()+"-default-scrn-001.png");
	  } else {
		video.setAttribute("poster",this.currentClip.videoStill);
	  } 
      video.setAttribute("src",this.currentClip.m3u8);
	
     },
     play:function(){
       video.play();
     },
     getLocale:function(){
       console.debug("[iV] "+"getLocale");
       var localeServiceURL="http://static"+this.servEnv+".discoverymedia.com/shared/swf/video-players/monetized/geo-locale.html";
       this.xhr(localeServiceURL,"locale");
     },
     getPolicy:function (locale){
       console.debug("[iV] "+"getPolicy for "+locale);
       var policyURL="http://static"+this.servEnv+".discoverymedia.com/videos/components/"+this.currentClip.networkId.toLowerCase()+"/"+this.currentClip.clipRefId+"/json-policies-service.html?application=short-form&iframe=discovery.com&parent=dsc.dev.discovery.com&locale="+locale;
       this.xhr(policyURL,"policy");
     },
     policyCheck:function(responseText) {
       var policyObj=eval('(' + responseText + ')');
       if(policyObj.geoFilter) {
         if (policyObj.geoFilter=="true") {
           console.debug ("this guy is blocked");
           this.createErrorScreen("geoBlocked");
         }
       } else {
         console.debug("[iV] "+ "policycheck is a go!");
		
		if(playerApplication=='snag') { //remove when snag ads work
			console.debug("[iV] " + "snag rule:" +policyObj.snag);
			if (policyObj.blacklisted==="true") {
				this.createErrorScreen("blacklisted");
			} else {
				switch (policyObj.snag) {
					case "off":
						this.createErrorScreen("snagOff");
						break;
					case "owner":
						console.debug("owner");
						break;
					case "local":
						console.debug("local");
						break;
					default :
						this.createPlayer();
						this.playMain();
				}	
			}
			
		} else {
			this.createPlayer();
			if(this.fwInitialized) {
				this.moreAds();
			} else {
		        this.initFreeWheel();
			}
			
		}
		
         
	  	 //this.playMain(); //remove when serving ads via freewheel
         //this.createShareBar();
       }
     },
      playMain:function() {
        console.debug("[iV] "+"playMain: "+ video.src);
		video.addEventListener('ended',this.videoComplete,false);
		video.style.display="inline";
		video.play();
        iVideo.omniTrackLink("Video Clip Start");
		iVideo.fireComscore("Video Clip Start");
		iVideo.firePlayCountService();
        
		
      },
      videoComplete:function(){
		console.debug("video completeted")
        iVideo.omniTrackLink("Clip Completed"); 
		if((playerApplication=="playlist-player") || (playerApplication=="mini-playlist-player")) {
			iVideo.playlistClipPlay(m3u8PlaylistClipNumber);
		}
		if ((playerApplication=="vap-player") || (playerApplication=="hub") || (playerApplication=="snag")) {
			if (this.postRollExists) {
				iVideo.showPostRoll();
			} else {
				iVideo.createPostRoll();
			}	
		}
 		
      },
      createShareBar:function() {
        console.debug("[iV] "+"createShareBar"); 
        shareBar=document.createElement('div');
        shareBar.className="videoShare hide";
        var txt=document.createTextNode("shareBar");
        shareBar.appendChild(txt);
        videoContainer.appendChild(shareBar);
        videoContainer.addEventListener('mouseover',this.showHideShare);
        videoContainer.addEventListener('mouseout',this.showHideShare);

      },
     showHideShare:function() {
		shareBar.className = (shareBar.className == 'videoShare hide') ? 'videoShare show' : 'videoShare hide';
	  },
	replayVideo:function(){
		iVideo.hidePostRoll();
		video.setAttribute("src",iVideo.currentClip.m3u8);
		iVideo.playMain();
		
	},
	createRelatedClips:function(){
		console.debug ("createRelatedClips");
		var l=relatedClipsJSON.clips.length;
		var relatedClipsWrapper=document.createElement('div');
		relatedClipsWrapper.className="relatedClipsWrapper";	
		var relatedClipsContainer=document.createElement('div');
		relatedClipsContainer.className="relatedClipsContainer";
	
		m3u8Clips = new Array();
	  for (i=0;i<l;i++){
		if (relatedClipsJSON.clips[i].m3u8!="") {
	    	var clip=document.createElement("div");
		    clip.className="relatedClip";
		    var anchor=document.createElement('a');
		    anchor.href=relatedClipsJSON.clips[i].fullyQualifiedURL;
			if (playerApplication=='snag') {
				anchor.setAttribute('target','_top');
			}
		    var img=document.createElement('img');
		    img.src=relatedClipsJSON.clips[i].thumbnailURL;
		    anchor.appendChild(img);
		    var clipInfo=document.createElement("div");
		    clipInfo.className="clipInfo";
		    var caption=document.createElement('p');
		    var captionTxt=document.createTextNode(relatedClipsJSON.clips[i].episodeTitle);
		    caption.appendChild(captionTxt);
		    clipInfo.appendChild(caption);
	    	anchor.appendChild(clipInfo);
		    clip.appendChild(anchor);
		    relatedClipsContainer.appendChild(clip);
			m3u8Clips.push(relatedClipsJSON.clips[i]);
		}
	  }
	  if (m3u8Clips.length>0) {
		relatedClipsLabel=document.createElement('div');
		relatedClipsLabel.setAttribute('class','relatedClipsLabel');
		relatedClipsLabel.innerHTML="Related Clips";
		relatedClipsWrapper.appendChild(relatedClipsLabel);
	  }
	  relatedClipsWrapper.appendChild(relatedClipsContainer);
	  relatedClipsContainer.style.left="0px";
	  relatedClipsWidth=m3u8Clips.length*180;
	  this.addSwipeListener(relatedClipsContainer,function(e){});
	return relatedClipsWrapper;
	
	},
	createPostRoll:function(){
	  console.debug("[iV] "+"createPostRollScreen");
	 
	  /* create post roll container*/
	  var postRollContainer=document.createElement('div');
	  postRollContainer.className="video-postRoll hide";
	  postRollContainer.setAttribute("id","postRollContainer");
	
	 /* create post roll nav container*/
	  var postRollNav=document.createElement('div');
	  postRollNav.className="postRollNav";
	  if (playerApplication!="hub") postRollContainer.appendChild(postRollNav);
	
	  var replay=document.createElement('div');
	  replay.className='replayIcon'
	  var replayText=document.createTextNode('Replay Video');
	  replay.addEventListener('click',iVideo.replayVideo)
	  replay.appendChild(replayText);
	
	  postRollNav.appendChild(replay);
	  

	  var relatedClipsWrapper=iVideo.createRelatedClips();
	  postRollContainer.appendChild(relatedClipsWrapper);
	  videoContainer.appendChild(postRollContainer);
	 
	  /*postRollWidth=l*clip.offsetWidth;
	  console.info("postRollWidth : " + postRollWidth);
	*/
	  //this.addSwipeListener(postRollClipsContainer,function(e){});
	  console.debug(video.poster);
	  postRollContainer.style.background="url("+video.poster+") no-repeat";
	  this.postRollExists=true;
	  
/*
	if (playerApplication==="vap-player") {
		postRollContinuousDiv=document.createElement('div');
		postRollContinuousDiv.setAttribute('id','postRollContinuosDiv');
		postRollContinuousText=document.createElement('span');
		postRollContinuousText.setAttribute('class','postRollContText');
		postRollContinuousText.innerHTML="Up Next: ";
		postRollContinuousDiv.appendChild(postRollContinuousText);
		postRollContinuousCountdown=document.createElement('span');
		postRollContinuousCountdown.setAttribute("class","postRollCntDwn");
		postRollContinuousCountdown.innerHTML="10";
		postRollContinuousDiv.appendChild(postRollContinuousCountdown);
		postRollContainer.appendChild(postRollContinuousDiv);
		upNext=0;
	}
*/
	var showPostRoll=setTimeout('iVideo.showPostRoll()',50);
	},
	showPostRoll:function(){
		console.debug("[iV] "+'showPostRoll');
		video.style.display="none";
		document.getElementById("postRollContainer").className="video-postRoll show";
		/*
		postRollContinuousText.innerHTML='Up Next: '+m3u8Clips[upNext].episodeTitle;
		postRollTimer=setInterval('iVideo.continuousPlay()',1000);
		*/	
	},
	continuousPlay:function() {
		var currTime=parseInt(postRollContinuousCountdown.innerHTML);
		var newTime=currTime--;
		postRollContinuousCountdown.innerHTML=newTime;
	},
	hidePostRoll:function(){
		document.getElementById("postRollContainer").className="video-postRoll hide";
		//clearInterval(postRollTimer);
	},
	flipClip:function(obj) {
	    console.debug("[iV] "+"flip out");
	  	obj.className = (obj.className == 'postRollClip') ? 'postRollClip flipped' : 'postRollClip';
	},
	createErrorScreen:function(err){
	  errorScreen=document.createElement('div');
	  errorScreen.className="videoError";
	  switch(err) {
	    case "geoBlocked" : 
	      var errTxt="This video is not available in your area.";
	      break;
	    case "notAvailable" : 
	      var errTxt="This Video is not available.";
	      break;
	    case "iOS" : 
	      var errTxt="We're working on making this video available on your device.";
	      break;
		case "blacklisted" :
			var errTxt="This video is not viewable on this site.";
			break;
		case "snagOff" :
			var errTxt='Embedding disabled. View: ';
			break;
	    default :
	      var errTxt="An Error has occurred.";
	  }
	 
	  var txtNode=document.createTextNode(errTxt);
	  errorScreen.appendChild(txtNode);
	  var anchor=document.createElement('a');
	  anchor.setAttribute('href',this.currentClip.fullyQualifiedURL);
	  anchor.setAttribute('target','_top');
	  anchor.appendChild(document.createTextNode(this.currentClip.episodeTitle));
	  if (err==="snagOff") errorScreen.appendChild(anchor);
	  if (err!="blacklisted") {
		var relatedClipsWrapper=iVideo.createRelatedClips();
		errorScreen.appendChild(relatedClipsWrapper);
		}
	  videoContainer.appendChild(errorScreen);
	},
	xhr:function(url,t) {
	  console.debug("[iV] "+"xhr "+url);
  		req = new XMLHttpRequest();
  		f=function(){if(req.readyState>3)iVideo.parseData(req,t);}
  		req.onreadystatechange = f;
  		req.open("GET", url, true);
  		req.send(null);
  	},
    parseData:function(r,t){
      console.debug("[iV] "+"parseData "+ t);
      if(r.status==200){
  			console.debug("[iV] "+r.responseText + "  " + t);
			switch (t) {
				case "policy":
					this.policyCheck(r.responseText);
					break;
				case "locale":
					this.getPolicy(r.responseText);
					break;
				case "playcountservice":
					console.debug("[iV] "+"PCS Success");
			}
  		}
    },
    addScript:function(js_file,f,doload) {
      console.debug("[iV] "+"addScript")
  		var newScript=document.createElement('script');
  		newScript.type="text/javascript";
  		newScript.src=js_file;
  		document.getElementsByTagName('head')[0].appendChild(newScript);
  		
  		if(doload) {
  			newScript.onreadystatechange = function () {
  		        if (newScript.readyState == 'complete') {
  		          console.debug("[iV] "+"script loaded 1");
  		            f();
  		        }
  		    }
  		    newScript.onload = function () {
  		        console.debug("[iV] "+"script loaded 2");
  		        f();
  		    }
  		}		
  	},
   	omniTrackLink:function(type){
   	  switch(type) {
   	    
   	    case "Ad Started" :
   	      var events="event22";
   	      break;
   	      
   	    case "Video Clip Start" : 
 	        var events="event21,event24";
   	      break;
   	      
   	    case "Clip Completed" :
   	      var events="event25";
   	      break;
   	  }
   	  console.debug ("omniTrackLink: " + type + "events: "+events);
   	  s.linkTrackEvents=events;
   	  s.events=events;
	  s.prop29="iOS HTML5 Player - " + playerApplication;
	  s.eVar25="iOS HTML5 Player - " + playerApplication;
   	  s.tl(true,'o',type);
   	  
   	  
   	},
	fireComscore:function(type){
		switch(type) {
	   	    case "Ad Started" :
	   	      var cs5="010000";
	   	      break;
	   	    case "Video Clip Start" : 
	 	         var cs5="020000";
	   	      break;
	   	  }
		console.debug("[iV] "+"comscore firing  "+cs5);
		COMSCORE.beacon({c1:1,c2:3000036,c3:3000036,c4:"",c5:cs5,c6:document.title});
	},
	firePlayCountService:function(){
		var pcsServiceURL="http://static"+this.servEnv+".discoverymedia.com/videos/components/pcs/"+this.currentClip.clipRefId+"/play-count-service.html";
		this.xhr(pcsServiceURL,"playcountservice");
	},
	addCSS:function(css_file) {
		var css = document.createElement('link');
	    css.setAttribute('rel', 'stylesheet');
	    css.setAttribute('type', 'text/css');
	    css.setAttribute('href', css_file);
	    document.getElementsByTagName("head")[0].appendChild(css);
	},
	
	debug:function(msg){
		console.debug(msg);
	},
	
	addSwipeListener:function(el, listener) {
	console.debug("[iV] "+"[DIT] addSwipeListener");
     var startX;
     var dx=0;
     var direction;
     function cancelTouch() {
      el.removeEventListener('touchmove', onTouchMove);
      el.removeEventListener('touchend', onTouchEnd);
      startX = null;
      startY = null;
      direction = null;
     }

     function onTouchMove(e){
	//console.debug("[iV] "+"el is at :" + el.style.left);
      if (e.touches.length > 1) {
       cancelTouch();
      } else {
        touch=e.touches[0];
       if (direction == null) {
         curX=touch.pageX;
         diffX = curX-prevX;
         newX=diffX+parseInt(el.style.left);
         // el.style.webkitTransform = 'translateX(' + newX + 'px)'; 
		//console.debug("[iV] "+"[DIT] touchmoving newX: "+newX+ "  curX: "+curX+ " diffX: "+ diffX+ "  el.style.left: "+el.style.left);
        //if (newX > 500) {newX=500;diffX=0}
	   // if (newX < -1*(relatedClipsWidth+160)) {newX=-1*relatedClipsWidth+160;diffX=0}
 		el.style.left=newX+"px";
        prevX=curX;
        e.preventDefault();
       } else if ((direction < 0 && dx > 0) || (direction > 0 && dx < 0) || Math.abs(dy) > 15) {
        cancelTouch();
       }
      }
     }


     function onTouchEnd(e) {
      cancelTouch();
      this.style.webkitTransition = 'all 1s ease-out';
      this.addEventListener( 'webkitTransitionEnd', function( event ) { this.style.webkitTransition = 'none'; }, false );
		var currTrans=this.style.webkitTransform;
		//console.debug(currTrans);
		var currTX=(currTrans.split('('))[1].split(',')[0];
	  var targX=parseInt(this.style.left)+diffX*3;
	console.debug("[iV] "+"targX "+ targX);
	  if (targX > 500) {targX=500;}
	
	  if (targX < (-1*relatedClipsWidth+160)) {targX=-1*relatedClipsWidth+160;}
	  
      //this.style.left=targX +"px";
   this.style.webkitTransform='translate3d('+dx+'px,0px, 0)';
     }

     function onTouchStart(e){
		console.debug("[iV] "+"[DIT] touchstarted")
      if (e.touches.length === 1) {
       prevX=e.touches[0].pageX;
       el.addEventListener('touchmove', onTouchMove, false);
       el.addEventListener('touchend', onTouchEnd, false);
      }
     }
     el.addEventListener('touchstart', onTouchStart, false);
    }     
}
   
   
   
   

