var swfContainerType = "";
var videoQueue = Array();
var newPlaylist = null;
var currentItem = -1; 
var previousItem = -1; 

var videoSort = {
	dateView	: 'all',
	attribSort	: 'post_date',
	sortDir		: 'DESC',
	maxItem		: 4,
	urlTitle	: ''
}

var eCode = {
	eWidth : 425,
	eHeight : 259
}

function videoList() {
	this.vid = new Array();
	this.pid = new Array();
	this.title = new Array();
	this.category = new Array();
	this.rating = new Array();
	this.video_owner = new Array();
	this.profile_link = new Array();
	this.num_rated = new Array();
	this.current = -1;
	this.previous = -1;
	this.Id = -1;
	this.previousId = -1;
}


var thisPlayer = null; 
function playerReady(thePlayer) { 
	thisPlayer = window.document[thePlayer.id]; 
	
	if (typeof onLoadFunc != 'undefined') {
		for(var i in onLoadFunc) {
			thisPlayer.addViewListener('LOAD', onLoadFunc[i]);		
		}				
	}
	if (typeof onPlayFunc != 'undefined') {
		for(var i in onPlayFunc) {
			thisPlayer.addViewListener('PLAY', onPlayFunc[i]);		
		}				
	}
	addListeners();
}

function addListeners() {
	if (thisPlayer) { 
		thisPlayer.addControllerListener("ITEM", "itemListener");
	} else {
		setTimeout("addListeners()",100);
	}
}



function loadPopout() {
	var flvVideoDiv = document.createElement('div');
	flvVideoDiv.id = 'flashVideo';
	$('popOut').appendChild(flvVideoDiv);
	
	var playerWidth = (video.Width != undefined) ? video.Width : "640";
	var playerHeight = (video.Height != undefined) ? video.Height : "390";
	var displayHeight = playerHeight;
	
	var flvVars = {
	      
	        displayheight: '390',
	        enablejs: "true",
	        javascriptid: "bloggermovie",
	        stretching: "uniform",
      		repeat: "none",
	        autostart: "false",
	        bufferlength: "5",
	        config: '/flvConfig/'+ video.Pid +'.xml'

	        };
	var flvParams = {
	        allowscriptaccess: "always",
	        allowfullscreen: "true",
	        hideMenu: "true",
	        scale: "default",
	        wmode: "transparent"};
	var attrib = { id: "movie1", name: "movie1" };
	var vidObject = swfobject.embedSWF(video.SwfUrl, "flashVideo", "100%", "100%", "9.0.115", "/public/shared/swf/expressInstall.swf", flvVars, flvParams, attrib);
	
	
}


function loadPlayer() {
	
	// Create child for swfobject
	var flvVideoDiv = document.createElement('div');
	flvVideoDiv.id = 'flashVideo';
	$('player').appendChild(flvVideoDiv);
	
	var playerWidth = (video.Width != undefined) ? video.Width : "640";
	var playerHeight = (video.Height != undefined) ? video.Height : "390";
	var displayHeight = playerHeight;
		var flvVars = {
		      
		        
		        displayheight: displayHeight,
		        enablejs: "true",
		        javascriptid: "bloggermovie",
		        stretching: "uniform",
	      		repeat: "none",
		        autostart: "false",
		        playertype: 'original',
		        da: 'false',
		        config: '/flvConfig/'+ video.Pid +'.xml'
		       
		       // image: video.Thumbnail,
		       // file: video.Url,
		      //  title: video.Title,
	
		        };
 
	var flvParams = {
	        allowscriptaccess: "always",
	        allowfullscreen: "true",
	        hideMenu: "true",
	      
	        wmode: "transparent"};
	var attrib = { id: "movie1", name: "movie1" };
	var vidObject = swfobject.embedSWF(video.SwfUrl, "flashVideo", playerWidth, playerHeight, "9.0.115", "/public/shared/swf/expressInstall.swf", flvVars, flvParams, attrib);
}

function downloadTracker(dlUrl) {
	pageTracker1._trackEvent('Videos', 'Download', dlUrl);
	pageTracker2._trackEvent('Videos', 'Download', dlUrl);
}

function playVideo(platformId) {
	previousItem = currentItem;
	currentItem = -1;
	thisPlayer.sendEvent('STOP');
	video.SwfUrl = '/bnqtPlayer/vid_'+ platformId;
	$('player').innerHTML = "";
	thisPlayer = null;
	loadPlayer();
	waitForPlay();
	
	
	var url = '/ajax/getVideoFromPid';
	var pars = 'pid='+ platformId;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
			var json = obj.responseText.evalJSON(true);
			if (json.success == "true") {	
				$('videoTitleSm').innerHTML = json.video.title;
				$('videoTitle').innerHTML = json.video.title;
				$('videoBody').innerHTML = json.video.body;
				var downloadIpod = $('downloadIpod');
				var downloadHD = $('downloadHD');
				removeChildNodes('downloadIpod');
				removeChildNodes('downloadHD');
				if (json.video.download_url == '') {
					var IpodLink = document.createElement('img')
					IpodLink.src = '/public/frontend/styles/nimbus/images/iconDownload_None.gif';
					IpodLink.alt = 'No download available';
				} else {
					var IpodLink = document.createElement('a');
					IpodLink.href = json.video.download_url;
					IpodLink.target = '_blank';
					IpodLink.onclick = function() {
						downloadTracker(json.video.url_title + ' - Ipod Version');
					};
				}
				downloadIpod.appendChild(IpodLink);
				if (json.video.hd_url == '') {
					var HDLink = document.createElement('img')
					HDLink.src = '/public/frontend/styles/nimbus/images/iconDownload_None.gif';
					HDLink.alt = 'No download available';
				} else {
					var HDLink = document.createElement('a');
					HDLink.href = json.video.hd_url;
					HDLink.target = '_blank';
					HDLink.onclick = function() {
						downloadTracker(json.video.url_title + ' - HD Version');
					};
				}
				downloadHD.appendChild(HDLink);
				comment.TypeId = json.video.video_id;
				comment.TypeTitle = json.video.title;
				refreshComments();

			}
		}
	});
}

function waitForPlay() {
	if (thisPlayer) {
		thisPlayer.sendEvent('PLAY');
	} else {
		setTimeout('waitForPlay()', 500);
	}
}


function itemListener(obj) { 

	if (obj.index != currentItem) {
 		previousItem = currentItem;
		currentItem = obj.index;
		var tmpTags = thisPlayer.getPlaylist()[currentItem].tags.replace(/<[//]{0,1}[^><]*>/ig,"");
		var tmpInfo = tmpTags.split(':');
		videoList.previous = videoList.current;
		videoList.previousId = videoList.Id;
		videoList.Id = tmpInfo[1];
		videoList.current = tmpInfo[0];
		if (videoList.previous != -1) {
			$('vid_'+ videoList.previous).removeClassName('videoSelected');
		}
		$('vid_'+ videoList.current).addClassName('videoSelected');
	}
}

function printItemData(theIndex) {
	var plst = null;

	plst = thisPlayer.getPlaylist();

	if (plst) {

        for(var i in plst[theIndex]) {
                txt += i +": "+plst[theIndex][i]+"<br>";
        }

		var tmp = document.getElementById("videoBody");
		
		var ptag = plst[theIndex].tags;
		
		var crap = HTMLtoDOM(ptag);
		tmp.innerHTML = crap;
	} 	
}

function clipPagination(currPage, sortCol, sortDir, webisodeId) {
	var url = '/ajax/clipPagination';
	var pars = 'webisodeId='+ webisodeId +'&currPage='+ currPage +'&sortCol='+ sortCol +'&sortDir='+ sortDir;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
			var json = obj.responseText.evalJSON(true);
			$('pageLink_'+ webisodeId).innerHTML = json.pagination_links;
			$('clipWebisode_'+ webisodeId).innerHTML = json.videos;
		}
	});
}

function videoPagination(currPage, catId) {
	var url = '/ajax/videoPagination';
	var pars = 'categoryId='+ catId +'&currPage='+ currPage +'&sortCol='+ videoSort.attribSort +'&sortDir=DESC&dateView='+ videoSort.dateView +'&maxItem='+ videoSort.maxItem;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
			var json = obj.responseText.evalJSON(true);
			//$('pageLink').innerHTML = json.pagination_links;
			
			$('videoContents').innerHTML = json.videos;
			$$('.videos .indicatorsContainer .indicator')[0].innerHTML = json.pagination_links;
		}
	});
}

function sortVideo(ele, val) {
	if (ele == 'videoSort') {
		videoSort.attribSort = val;
	}
	if (ele == 'videoSortTime') {
		videoSort.dateView = val;
	}
	videoPagination(0,null);
}

function sortVideoFull(ele, val) {
	if (ele == 'videoSort') {
		videoSort.attribSort = val;
	}
	if (ele == 'videoSortTime') {
		videoSort.dateView = val;
	}
	window.location = '/videos/index/'+ videoSort.attribSort +'/'+ videoSort.dateView;
}


function trackVideo() {
	var url = '/ajax/trackVideo';
	var pars = 'video_id='+ video.Id;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
			var json = obj.responseText.evalJSON(true);
		}
	});
}

function thisMovie(swf) {
  if(navigator.appName.indexOf("Microsoft") != -1) {
    return window[swf];
  } else {
    return document[swf];
  }
};

function voteVideo() {

	var url = '/ajax/voteVideo';
	var pars = 'video_id='+ video.Id;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
			var json = obj.responseText.evalJSON(true);
			if (json.success == false) {		
				alert(json.message);
				return;
			} else {
				$('voteButton').innerHTML = json.html;
			}
		}
	});
}

function rateVideo(videoRating) {
	if (video.canRate == "true") {
		var url = '/ajax/rateVideo';
		var pars = 'video_id='+ video.Id + '&rating='+ videoRating;
		var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
				var json = obj.responseText.evalJSON(true);
				if (json.success == false) {		
					alert(json.message);
					return;
				} else {

					video.canRate = "false";
					video.numRatings = json.numRatings;
					video.totalRating = json.totalRating;
					$('videoRaterContainer').innerHTML = json.html;
					initVideoRating();
				}
			}
		});
	} else {
		alert('You must be logged in to rate this video.');
		return;
	}
}

function init() {

	loadPlayer();
	initVideoRating();
	initCommentEvents();
	
	if (video.customizeEmbed == true) {
		configureEmbed();
	}

}

function initCommentEvents() {
	Event.observe($('commentAction'), 'click', displayComments);
	Event.observe($('addComment'), 'click', displayComments);	
}

function loadVideoInfo() {
	return video;
}


function getFlashMovie(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  return (isIE) ? window[movieName] : document[movieName];
}
 
function initVideoRating() {
	var flvVars = {
			currRating: video.currentRating,
			numRatings: video.numRatings,
			currVideoId: video.Id,
			enableRating: video.canRate
	        };
	var flvParams = {
	        allowscriptaccess: "always",
	        wmode: "transparent"};
	var attrib = { id: 'videoRater' };
	var vidObject = swfobject.embedSWF('/public/shared/swf/videoRating.swf', "videoRater", "80", "25", "8", "/public/shared/swf/expressInstall.swf", flvVars, flvParams, attrib);
}

function checkVideoVotes() {
	var url = '/ajax/checkVideoVotes.html';
	var pars = 'video_id='+ video.Id;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
			var json = obj.responseText.evalJSON(true);
			$('voteButton').innerHTML = json.html;
		}
	});	
}


function initSwfUpload(uType) {
	
	Lightview.show({
	  href: '/ajax/pseudo_progress.html',
	  rel: 'ajax',
	  title: uType.substr(0,1).toUpperCase() + uType.substr(1) +" Upload Status",

	  options: {
	    width: 500,
	    height: 120,
	    topclose: true,
	    ajax: {
	      method: 'post',
		  onComplete: function() {
		  	var pseudoDiv = $('pseudo_progressDiv');
				  	
			pseudoDiv.style.width = "500px";
			pseudoDiv.style.height = "120px";
			pseudoDiv.style.lineHeight = "normal"
			pseudoDiv.style.padding = "5px"
			
					  
			//Effect.BlindDown(utypeContainer);
			var uProgress = document.createElement("div");
			uProgress.style.margin = "20px auto";
			uProgress.style.textAlign = "center";
			uProgress.id = "uploadProgressContainer";

			var uploadProcessDiv = document.createElement("div");
			uploadProcessDiv.style.height = "60px";
			uploadProcessDiv.style.textAlign = "left";
			uploadProcessDiv.style.margin = "5px";
			uploadProcessDiv.id = "uploadProcess";
			uProgress.appendChild(uploadProcessDiv);
			var thumbnailsDiv = document.createElement("div");
			thumbnailsDiv.style.textAlign = "center";
			thumbnailsDiv.id = "thumbnails";
			uProgress.appendChild(thumbnailsDiv);
			var divStatus = document.createElement("div");
			divStatus.style.textAlign = "center";
			divStatus.style.clear = "both";
			divStatus.id = "divStatus";
			uProgress.appendChild(divStatus);

			
			//utypeContainer.appendChild(uProgress);
			swfContainerType = uType;
		
			$('pseudo_progressDiv').innerHTML = uProgress.innerHTML;
			

			var post_params = swfU_Vid.settings.post_params;
			post_params.videoTitle = $('video_title').value;
			swfU_Vid.setPostParams(post_params);
			if (uType == "video") {
				setTimeout('swfU_Vid.selectFiles()', 1100);
			} else {
				setTimeout('swfU.selectFiles()', 1100);
			}
		
			iTime = "";			  
			  
			}		  	
		  } 
	    }
	  });
	

}

function toggleWebisode(webisodeId) {
	var webState = $('webisodeState_'+ webisodeId).innerHTML;
	if (webState == 1) {
		Effect.BlindUp($('webisodeContainer_'+ webisodeId), {duration: 0.3});
		$('webisodeState_'+ webisodeId).innerHTML = 0;
	} else {
		Effect.BlindDown($('webisodeContainer_'+ webisodeId), {duration: 0.3});
		$('webisodeState_'+ webisodeId).innerHTML = 1;
	}
}


function showHelpInfo(hType) {
	 Effect.BlindDown(hType, { duration : 2.0 });
	 eval("$(hType + '_link').onclick = function () {};");
}

function hideHelpInfo(hType) {
	 Effect.BlindUp(hType, { duration : 2.0 });
	 eval("$(hType + '_link').onclick = function () { showHelpInfo('"+ hType +"'); };");
}

function hideProgress() {
	Lightview.hide();
	new Effect.Fade($('overlay'), { duration: 0.3 });	
}

function converTmpFile2Input(fn) {
	$('submit_continue').disabled = 'disabled';
	createHiddenInput("videoFile[fileSession]", tmpFile.fileSession, fn);
	createHiddenInput("videoFile[fileName]", tmpFile.fileName, fn);
	createHiddenInput("videoFile[fileDuration]", tmpFile.fileDuration, fn);
	createHiddenInput("videoFile[fileFromCodec]", tmpFile.fileFromCodec, fn);
	createHiddenInput("videoFile[thumbNail]", tmpFile.thumbNail, fn);
	createHiddenInput("videoFile[thumbNailSmall]", tmpFile.thumbNailSmall, fn);
	window.onbeforeunload = "";	
	
	fn.submit();
	
}

function encodingProgressChecker() {
	var url = '/ajax/encodingProgressChecker.html';

	var myPeriodicalAjax = new Ajax.PassivePeriodicalUpdater(url, {method: 'post',  decay : 1,
			onSuccess : function (obj) {
							var json = obj.responseText.evalJSON(true);
							var queues = json.queues;
							for (i=0; i<queues.length; i++) {
								var queue = queues[i];
								var videoId = queue.videoId;
								
								$('vQueue_' + videoId).className = "progressContainer blue";
								//$('vQueue_' + videoId).style.height = "45px";
								$('vQueueProgress_' + videoId).className = "progressBarInProgress";
								$('vQueueProgress_' + videoId).style.width = queue.encodingPercent + "%";
							//	$('vQueueProgress_' + videoId).style.height = '45px';
							//	$('vQueueProgress_' + videoId).style.bottom = '15px';
								$('vQueueProgress_' + videoId).innerHTML = "&nbsp;";
								
								$('vQueueUploadTime_' + videoId).innerHTML = queue.videoUploadDate;
								$('vQueueTitle_' + videoId).innerHTML = queue.videoTitle;
								$('vQueueProgressTimeRemaining_'+ videoId).innerHTML = queue.encodingTimeLeft;
								$('vQueueProgressTimeElapsed_'+ videoId).innerHTML = queue.encodingTimeElapsed;
							
								$('vQueueStatus_' + videoId).innerHTML = queue.sessionStatus;
							}
						}
					});
								
}

function updateVideoThumbnail(videoId, thumbId) {
	var url='/ajax/updateVideoThumbnail.html';
	var pars = 'video_id='+ videoId +'&thumbnail_id='+ thumbId;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
			var json = obj.responseText.evalJSON(true);
			$('videoThumbnail_'+ videoId).src = json.thumbnailUrl;
		}
	});	
}

function displayCompanionBanners(banners) {
	tmDisplayBanner(banners, "OAS_Middle1", 300, 250);
}


function configureEmbed() {
	var pars = 'contType=videos&contId='+ video.Id;
	Lightview.show({
	  href: '/ajax/getEmbedCodeForm.html',
	  rel: 'ajax',
	  title: 'Embed This Video',
	  options: {

	    topclose: true,
	    ajax: {
	      method: 'post',
	      parameters: pars,
		  onComplete: function() {
					$('theCode').value = generateEmbedCode(video.embedWidth, video.embedHeight);		
			  		$('embedWidth').value = video.embedWidth;
			  		$('embedHeight').value = video.embedHeight;
			  		$('videoLink').value = window.location;
				}
			}
		}
	});			
}

function generateEmbedCode(newWidth, newHeight) {
  	var embdCode = '<object width="'+ newWidth +'" height="'+ newHeight +'"><param name="movie" value="'+ video.SwfUrl +'" /><param name="allowfullscreen" value="true" ';
		embdCode += '/><param name="allowscriptaccess" value="always" /><param name="wmode" value="opaque" /><param name="bgcolor" value="#000000" /><param name="flashvars" ';
		embdCode += 'value="config='+ escape(video.websiteUrl +'/flvConfig/'+ video.Pid +'.xml') +'" /><embed src="'+ video.SwfUrl +'" width="'+ newWidth +'" height="'+ newHeight +'" ';
		embdCode += 'allowfullscreen="true" allowscriptaccess="always" wmode="opaque" bgcolor="#000000" type="application/x-shockwave-flash" ';
		embdCode += 'pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="config='+ escape(video.websiteUrl +'/flvConfig/'+ video.Pid +'.xml') +'" ';
		embdCode += 'scale="noscale"></embed></object>';
	
	return (embdCode);
}

function updateEmbed() {
	var currWidth = parseInt($('embedWidth').value);
	var currHeight = parseInt($('embedHeight').value);
	if (currWidth != eCode.eWidth) {
		var oRatio = parseInt(currWidth) / parseInt(video.embedWidth);
		eCode.eWidth = currWidth;
		eCode.eHeight = Math.ceil(video.embedHeight * oRatio);
		$('theCode').value = generateEmbedCode(currWidth, eCode.eHeight);
		$('embedHeight').value = eCode.eHeight;
	} else if (currHeight != eCode.eHeight) {
		var oRatio = parseInt(currHeight) / parseInt(video.embedHeight);
		eCode.eHeight = currHeight;
		eCode.eWidth = Math.ceil(video.embedWidth * oRatio);
		$('theCode').value = generateEmbedCode(eCode.eWidth, currHeight);
		$('embedWidth').value = eCode.eWidth;
	}
}

function doClear(searchBox, default_string) {
	if (searchBox.value == default_string) { searchBox.value = ''; }       
	}

function noClear(searchBox, default_string) {
	if (searchBox.value == '') { searchBox.value = default_string; }       
	}

function displayEmailFriend(videoId) {
	/*
	var url = '/ajax/displayEmailFriendVideo.html';
	var pars = 'video_id='+ videoId;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
			var json = obj.responseText.evalJSON(true);
	*/
			Effect.BlindDown('emailFriendBox', { duration : 0.4 });
			//eval("$('addToPlaylist').onclick = function () {};");
			eval("$('emailFriendVideo').onclick = function () {};");
			
			//$('emailFriendBoxMessage').innerHTML = json.content;
	/*		
		}
	});
	*/
	
	
}

function emailFriendVideo() {
	var isValid = emailFriendValid.validate();
	if (!isValid) {
		return false;
	} else {
		var url = '/ajax/emailFriendVideo.html';
		var pars = Form.serialize($('friendVideo'));
		var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: function(obj,json) {
				var json = obj.responseText.evalJSON(true);
				if (json.success == false) {
					alert(json.message);
					
					
				}
				$('fullName').value = "";
				$('friendName').value = "";
				$('friendEmail').value = "";
				$('emailComment').value = "";
				emailFriendValid.reset();
			}			
		});
	}
}

function episodeAutoFill(selectObj) {
	var idx = selectObj.selectedIndex; 
	var webisodeId = selectObj.options[idx].value;
	var preEpisode = $('previousEpisode').value;
	var preWebisode = $('previousWebisode').value;
	if (webisodeId != 0) {

		var url = '/ajax/getLatestEpisode.html';
		var pars = 'webisodeId='+ webisodeId;
		var myAjax = new Ajax.Request(url, { method: 'post', parameters: pars, onComplete: function(obj, json) {
				var json = obj.responseText.evalJSON(true);
				var lastEpisode = parseInt(json.lastEpisode);
				$('episodeInput').show();
				if (preWebisode != "" && preEpisode != "") {
					if (preWebisode == webisodeId) {
						$('video_episode').value = lastEpisode;
					} else {
						$('video_episode').value = lastEpisode + 1;
					}
				} else {
					$('video_episode').value = lastEpisode + 1;
				}
		}});
	} else {
		$('video_episode').value = "";
		$('episodeInput').hide();
	}
}

function closeEmailFriend() {
	Effect.BlindUp('emailFriendBox', { duration : 0.4});
	eval("$('emailFriendVideo').onclick = function () { displayEmailFriend('"+ video.Id +"'); };");
	//eval("$('addToPlaylist').onclick = function () { addToPlaylist('"+ video.Id +"'); };");
}

