
//Basic Cookie Code should be in header not in this script

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function vplLoadScript(idList) {
 if(typeof vpl != "undefined") {
	 var scriptNode = '';
	 var head = document.getElementsByTagName("head")[0];
	 var scriptUrl = '/assets/videoListLoader?videoIds='+idList;
	 if (document.createElement) {
	  scriptNode = document.createElement('script');
	  scriptNode.id = "videoListData";
	  scriptNode.setAttribute('type', 'text/javascript');
	  scriptNode.setAttribute('src', scriptUrl);
	 } 
	 head.appendChild(scriptNode);
 }
}

function addToPlaylist(e, strId) {
	var videoTitle,videoUrl,videoDuration, videoType, videoChannel, videoThumb;	
	if (!e) var e = window.event;
	if (e.target) {
	  targ=e.target;
	} else if (e.srcElement) {
	  targ=e.srcElement;
	}
	if (targ.nodeType==3) { // defeat Safari bug	  
	  targ = targ.parentNode.parentNode;
	}
	var videoElem = targ.parentNode.parentNode.parentNode.parentNode;
	var divElems = videoElem.getElementsByTagName("div");
	var videoPlusIcon;
	for(var i = 0; i < divElems.length;i++) {
		switch(divElems[i].className) {
		case "videoThumb":
		  var videoThumbElem = divElems[i];
			videoThumbElem = videoThumbElem.getElementsByTagName("img")[0];
			videoThumb = videoThumbElem.src;
		  break;    
		case "videoText":
		  var videoTextElem = divElems[i];
		  videoUrl = videoTextElem.getElementsByTagName("a")[0].href;
		  videoChannel = videoUrl.split("videoChannel=")[1];
		  videoTitle = encodeURIComponent(videoTextElem.getElementsByTagName("a")[0].lastChild.nodeValue);
		  break;
		case "videoInfo":
		  var videoInfoElem = divElems[i];
		  videoDuration = videoInfoElem.innerHTML.split("(")[1].split(")")[0];
	  	  videoType = videoInfoElem.innerHTML.split(") ")[1];
		  break;
		case "videoPlaylister":
		  var videoPlaylisterElem = divElems[i];
		  videoPlusIcon = videoPlaylisterElem.getElementsByTagName("img")[0];
		  break;
		default:
		}
	}
	if(vpl.addIdToCookie(strId)){
		videoPlusIcon.setAttribute("src", "/resources/images/iconAddPlaylist_added.gif");
		vpl.addVideoToPL(strId,videoDuration,videoTitle,videoType,videoThumb,videoChannel,videoUrl);
	}
	return false;	
}

function removeFromPlaylist(strId) {
	vpl.removeVideoFromPL(strId);	
}

// vpl is a global object to contain video objects, methods, variables for video playlist functionality
var vpl = {         
	nextVideo: "",
	origNextVideo: "",
	videos: [],
	getVideos: function (  ) {
		return this.videos;
	},
	getCookie: function () {
		try {
			var currentCookie = readCookie('videoPlayList');
			if (currentCookie != null) {
				return currentCookie.split(':');			 
			} else {return false;}
		} 
		catch (e) {return false;}
	},
	getCookieIndex: function (strId) {
		if(this.getCookie()) {
			var cookie = this.getCookie()
			var len = cookie.length;
			for(var i = 0;i < len;i++) {
				if(cookie[i] == strId) {
					return i;
				}
			}
			return -1; //fails because id does not exist in cookie
		} else {return -1} //fails bacause no cookie
	},
	setCookie: function (arrIds) {
		 try {eraseCookie('videoPlayList');}
		 catch (e) {}
		 var len = arrIds.length;
		 var strCookie = '';
		 for (var i = 0; i < len; i++) {
				if (i == len-1) {
					strCookie += arrIds[i]; //dont add trailing ":"
				} else {
					strCookie += arrIds[i] + ":";
				}
		 }
		 createCookie('videoPlayList',strCookie,90);
	},
	checkMaxCookieLen: function (strCookie, strId) {
		var maxCookieLen = 1024;
		if((strCookie.length+strId.length)< maxCookieLen) {
			return true;
		} else { return false;}
	},
	addIdToCookie: function (strId) {
		var cookie = this.getCookie();		
		if (cookie !== false) {
			var len = cookie.length;
			var cookieIndex = this.getCookieIndex(strId);
			if (cookieIndex == -1) { // id not in cookie, so continue
				var strCookie = readCookie('videoPlayList');
				if (this.checkMaxCookieLen(strCookie, strId)) { //detect cookie filesize. large cookie filesize can cause browser errors
					cookie.push(strId);
					this.setCookie(cookie);
					return true;
				} else {return false;} //reached predefined cookie limit
			} else {return false;} //id already in cookie
		} else { //set first id in cookie
			this.setCookie([''+strId]);
			return true;
		}			
	},
	getVideo: function (strId) {
		var len = this.videos.length;
		for(var i = 0;i<len;i++) {
			if(this.videos[i].id == strId) {
				return this.videos[i];
			}
			//should there be an else that returns false?
		}
	},
	getVideoIndex: function (strId) {
		var len = this.videos.length;
		if(len > 0){
			for(var i = 0;i<len;i++) {
				if(this.videos[i].id == strId) {
					return i;
				}
			}
			return -1; //fails because id does not exist in array
		} else {return -1} //fails bacause no videos in array
	},
	getNextVideo: function (strId) {
		var len = this.videos.length-1; //-1 from length for boundary detection
		for(var i = 0;i<len;i++) {
			if(this.videos[i].id == strId) {
				return this.nextVideo = this.videos[i+1];
			}
		}
		return false;
	},	
	updateNextVideoMod: function () {
		this.nextVideo = this.getNextVideo(currentVideo.id);
		if (this.nextVideo != false) {			
			try {
				nextVideo = this.nextVideo;
				//nextVideo.videoUrl = "";
				nextVideo.source = "playlist";
				loadComingNext();
			} 
			catch (e) {}
		} else {
				nextVideo = this.origNextVideo;
				if(nextVideo == false && this.origNextVideo == false) {
					//there is no next video so try to grab first video in the browser
				}
				loadComingNext();
		}
	},
	startPlaylist: function (strURL) {
		document.location.href = strURL+'&pl=true&refresh=true';
	},
	continuePlaylist: function () {
		var currentVidIndex = this.getVideoIndex(currentVideo.id);
		var currentPLcookie = this.getCookie();
		if(currentVidIndex != -1) {
			if(checkPlaylistMode()) {				
				if(currentVidIndex < currentPLcookie.length) {
					this.updateNextVideoMod();
				}			
			}
		}		
	},
	ImgError : function (source){
		source.src = "/resources/images/default_video_thumb.jpg";
		source.onerror = "";
		return true;
	},
	videoPlaylist_createContainer: function (o) {
		if (o.id == currentVideo.id && checkPlaylistMode()) {
			var vidHTML = '<div class="vplVideo activePlv" id="plv_'+o.id+'">';
		} else {
			var vidHTML = '<div class="vplVideo" id="plv_'+o.id+'">';
		}
	    vidHTML += '<div class="videoPlaylister"><a href="javascript:removeFromPlaylist(' + o.id + ');">';
	    vidHTML += '<img src="/resources/images/iconRemovePlaylist.gif" border="0" alt="Remove From Playlist" title="Remove From Playlist" /></a></div>';
	    vidHTML += '<div class="videoThumb"><a href="'+o.videoUrl+'" onclick="vpl.startPlaylist(\''+o.videoUrl+'\');return false;">';
	    vidHTML += '<img src="'+o.thumbnail+'" onerror="javascript:vpl.ImgError(this);" width="64" height="47" border="0" alt="0" /></a></div>';
	    vidHTML += '<div class="videoText">';
	    vidHTML += '<img src="/resources/images/iconVideo.gif" border="0" alt="Video" class="inlineLinkIcon" /><a href="'+o.videoUrl+'" onclick="vpl.startPlaylist(\''+o.videoUrl+'\');return false;">'+decodeURIComponent(o.title)+'</a>';
	    vidHTML += '<div class="videoInfo">('+o.duration+') '+o.type+'</div>';
	    vidHTML += '</div>';
	    vidHTML += '</div>';
		return vidHTML;
	},
	updatePlaylistBrowser: function () {
		var vidHTML = '';
		var numVideos = this.videos.length;
		for(var i=0;i<numVideos;i++) {
			vidHTML = vidHTML+this.videoPlaylist_createContainer(this.videos[i]);
		}
		document.getElementById("videoPlaylist").innerHTML = vidHTML;
	},
	
	updatePlaylistCount: function () {
		document.getElementById("playlistCount").innerHTML = " ("+this.videos.length+")";
	},
	
	addVideoToPL: function (strId, strDuration, strTitle, strType, strThumb, strChannel, strVidUrl) {
		if (this.getVideoIndex(strId) == -1) {
			this.videos.push({"id": strId, "duration": strDuration, "title": strTitle, "type": strType, "thumbnail": strThumb, "channel": strChannel, "videoUrl": strVidUrl});
			this.updatePlaylistCount();
			this.updatePlaylistBrowser();
		}
	},
	removeVideoFromPL: function (strId) {
		var cookie = this.getCookie();
		if(cookie !== false) { //make sure cookie exists
			var cookieIndex = this.getCookieIndex(strId);
			if(cookieIndex != -1) {//found id in cookie
				cookie.splice(cookieIndex,1); //remove id from cookie
				var vidIndex = this.getVideoIndex(strId);
				if (vidIndex != -1) { //found id in playlist
						this.videos.splice(vidIndex,1);//remove id from playlist
				}
			}
			this.setCookie(cookie);
			this.updatePlaylistCount();
			this.updatePlaylistBrowser();			
			//should the next video be updated as well?
			//return true;				
		} else {//return false;
		}
	},
	clearPL: function () {		
		if (this.getCookie() != false) {
			if (confirm(strClearPlaylist)) {
				this.videos = [];
				this.updatePlaylistCount();
				document.getElementById("videoPlaylist").innerHTML = "";
				eraseCookie('videoPlayList');
				//should the next video be updated as well?
			}
		}		
	},
	reversePL: function () {
		var vplCookieArray = this.getCookie();
		if(vplCookieArray != false) {
			len = vplCookieArray.length;
			this.videos.reverse();
			vplCookieArray.reverse();
			this.setCookie(vplCookieArray);
			this.updatePlaylistBrowser();
			this.updateNextVideoMod();
		}
	},
	init: function(videosArray) {		
		this.updatePlaylistCount();
		this.origNextVideo = nextVideo;
		this.updatePlaylistBrowser();		
		this.continuePlaylist();
	}
};
