/*
 * Media Center Script for Ultra Video Gallery 4
 * By Pengcheng Rong (rongers@hotmail.com, service@bizmodules.net)
 * Copyright (c) 2010 Pengcheng Rong
 * All rights reserved, donot use this script library out of Ultra Video Gallery.
*/
String.prototype.endsWith = function(suffix) { 
    return this.indexOf(suffix, this.length - suffix.length) !== -1; 
}; 

function mediaCenter(pid,mid,baseurl,clientid, usehtml5, baselineonly, newperiod)
{
	var dest = "#uvg_dest" + mid + " ";

	jQuery(dest).css("display", "block");

	this.portalid = pid;
	this.mid = mid;
	this.baseurl = baseurl;
	this.clientid = clientid;
	this.usehtml5 = usehtml5;
	this.baselineonly = baselineonly;
	this.newperiod = newperiod;
	this.dest = dest;

	var _this=this;

	var currentItem = -1;
	var currentItemId = -1;
	var currentPage = 0;//the page index of comments

	var thumbslist = jQuery(dest + ".thumbslist");
	var thumbs = jQuery(dest + ".thumbs");
	var videoplayer = jQuery(dest + ".videoplayer");
	var xofy = jQuery(dest + ".xofy");
	var title = jQuery(dest + ".currentvideo .title");
	var description = jQuery(dest + ".description");
	var xcomment = jQuery(dest + ".comment");
	var addcomment = jQuery(dest + ".addcomment");
	var loading = jQuery(dest + ".loading");

	var currentvideo = jQuery(dest + ".currentvideo");
	var commentwindow = jQuery(dest + ".commentwindow");

	var scrollleft = jQuery(dest + ".thumbsscrollleft");
	var scrollright = jQuery(dest + ".thumbsscrollright");

	//cookie operation
	this.setCookie= function(name,value)
	{
		var Days = 180; 
		var exp  = new Date();    
		exp.setTime(exp.getTime() + Days*24*60*60*1000);
		document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
	};

	this.getCookie = function(name)
	{
		var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
		 if(arr != null) return unescape(arr[2]); return null;

	}

	var lastWatch = _this.getCookie("LastWatch");

	this.getThumbsWidth = function(){
		var items = thumbs.find("a");
		if (items.length == 0)
		{
			return 0;
		}
		var lastitem = jQuery(items[items.length-1]);
		var width = lastitem.position().left + lastitem.width();
		return width;			
	};

	this.getFirstThumbWidth = function(){
		var items = thumbs.find("a");
		var firstitem = jQuery(items[0]);
		var width = parseInt(firstitem.css("margin-right")) + firstitem.width();
		return width;			
	};

	scrollleft.click(function() {
		_this.doScroll(_this.getItemsPerScreen());
	});

	scrollright.click(function() {
		_this.doScroll(-1 * _this.getItemsPerScreen());
	});

	addcomment.click(function() {
		_this.showCommentWindow();
	});

	xcomment.click(function() {
		_this.showCommentWindow();
	});

	this.showCommentWindow = function()
	{
		var newLeft1 = currentvideo.position().left;
		var newLeft2 = commentwindow.position().left;
		//crt.fadeTo("fast", .1);
		commentwindow.animate({"left":newLeft1}, "slow");
		currentvideo.animate({"left":newLeft2}, "slow");

		_this.showComment();
	};

	jQuery(commentwindow.find("#btnClose")).click(function() {
		var newLeft1 = currentvideo.position().left;
		var newLeft2 = commentwindow.position().left;
		//crt.fadeTo("fast", .1);
		commentwindow.animate({"left":newLeft1}, "slow");
		currentvideo.animate({"left":newLeft2}, "slow");
	});

	jQuery(commentwindow.find("#btnPost")).click(function() {
		var ctlComment = jQuery(dest + "#txtComment");
		var txtComment = ctlComment.attr("value").trim();
		if (txtComment == '')
		{
			return false;
		}
		
	
		var eventArgs = 'comment|post|' + currentItemId + "|" + txtComment ;
		//enterLoadingState();
		jQuery(commentwindow.find("#btnPost")).attr("disabled", "disabled");
		dnn.xmlhttp.doCallBack('MediaCenter ' + _this.clientid,eventArgs,_this.postComment_CallBack,this,_this.gnl_CallBackError,null,null,null,0);
	});

	this.postComment_CallBack = function(result, ctx)
	{
		jQuery(commentwindow.find("#btnPost")).removeAttr("disabled");
		if (result != "")
		{ 
			alert(result);
			return;
		}  

		_this.showComment();
		jQuery(dest + "#txtComment").attr("value", "");
	}

	this.doScroll = function(distance)
	{
		var barWidth = this.getThumbsWidth();
		var itemWidth = this.getFirstThumbWidth();
		var currentPos = thumbs.position().left;
		var offset = distance * itemWidth;
		if (currentPos >= 0 && offset > 0)
		{
			return;
		}
		if (currentPos < -1 * barWidth + thumbslist.width() && offset < 0)
		{
			return;
		}

		var scrollTo = currentPos + offset;
		if (scrollTo > 0 )
		{
			scrollTo = 0;
		}
		else if (scrollTo + barWidth < thumbslist.width())
		{
			scrollTo = thumbslist.width() - barWidth;
			//alert("fixed scrollTo to " + scrollTo + ", " + thumbslist.width() + "/" + barWidth);
		}
		//if (scrollTo % itemWidth != 0 && distance > 0)//scroll to left
		//{
		//	scrollTo -= scrollTo % itemWidth;
		//}
		thumbs.animate({"left": scrollTo}, "fast", this.ensureScrollVisibility);

		//this.ensureScrollVisibility();
	}

	this.getItemsPerScreen = function()
	{
		var ttlWidth = thumbslist.width();
		var itemWidth = this.getFirstThumbWidth();
		return Math.floor(ttlWidth / itemWidth)
	}

	this.ensureScrollVisibility = function()
	{
		if (thumbs.position().left >= 0)
			scrollleft.hide();
		else
			scrollleft.show();

		if (thumbs.position().left + _this.getThumbsWidth() <= thumbslist.width())
		{
			scrollright.hide();
			//alert("hide scrollright, thumbs.position().left + _this.getThumbsWidth()=" + (thumbs.position().left + _this.getThumbsWidth()));
		}
		else
			scrollright.show();

		//alert("left="+thumbs.position().left+", right edge="+(thumbs.position().left + _this.getThumbsWidth()));
	}

	this.updateDefaultVideoList = function(){
		var source = "#uvg_src" + mid + " ";
		var videos = jQuery(source + "div[class='video']");

		for (var i=0;i<videos.length ;i++ )
		{
			var video = jQuery(videos[i]);
			var info = new Array();//id, title, thumbnail, createdbyuser, description, comments, tag, lowpath, highpath, embedcode
			info[0]= video.find(".videoid").attr("innerHTML");
			info[1]= video.find(".title").attr("innerHTML");
			info[2]= video.find(".image").attr("src");
			info[3]= video.find(".userid").attr("innerHTML");
			info[4]= video.find(".description").attr("innerHTML");
			info[5]= video.find(".comment").attr("innerHTML");
			info[6]= video.find(".tag").attr("innerHTML");
			info[7]= video.find(".createddate").attr("innerHTML");

			var embedcode = video.find(".embedcode");
			if (embedcode.length > 0)
			{
				//is embed code
				info[8]= 'embedcode';
				info[9]= video.find(".embedcode").attr("innerHTML");
			}
			else
			{
				info[8]= 'whatever';
				info[9]= video.find(".lowpath").attr("innerHTML");
				info[10]= video.find(".highpath").attr("innerHTML");
			}

			addVideoToList(info);
		}

		//Hide the source 
		jQuery(source).css("display", "none");

		this.ensureScrollVisibility();
	};

	if (thumbslist.mousewheel)
	{
		thumbslist.mousewheel(function(event, delta) {
			if (delta > 0)
				_this.doScroll(1);
			else if (delta < 0)
				_this.doScroll(-1);
			return false;
		});
	}

	this.navigateTo = function(index){
		var items = thumbs.find("a");
		if (index <0 || index > items.length - 1)
		{
			return;
		}
		var item = jQuery(items[index]);
		var tlt = item.find(".title");
		var desc = item.find(".description");
		var embedcode = item.find(".embedcode");
		var lowpath = item.find(".lowpath");
		var highpath = item.find(".highpath");
		var tag = item.find(".tag");
		var comment = item.find(".comment");
		var videoid = item.find(".videoid");
		var createdbyuser = item.find(".createdbyuser");

		var embedcodehtml = "";
		if (embedcode.length > 0)
		{
			embedcodehtml = embedcode.attr("value");
		}

		this.play(index,	videoid.attr("innerHTML"), tlt.attr("innerHTML"), createdbyuser.attr("innerHTML"), desc.attr("innerHTML"), comment.attr("innerHTML"), lowpath.attr("innerHTML"), highpath.attr("innerHTML"), embedcodehtml);

	};

	this.play = function(index,	id, tlt, createdbyuser, desc, comments, lowpath, highpath, embedcode)
	{
		//alert("params=\n" + id + "\n" +  tlt + "\n" +  createdbyuser + "\n" +  desc + "\n" +  comments + "\n" +  lowpath + "\n" +  highpath + "\n" + embedcode);
		if (embedcode != "")
		{
			videoplayer.attr("innerHTML", embedcode);
		}
		else
		{
			var uvgplayer = "";
			var playerwidth = videoplayer.width();
			var playerheight = videoplayer.height();

			if (this.usehtml5)
			{
				if (!lowpath.endsWith(".mp4"))
				{
					lowpath = "";
				}
				if (highpath!= "" && !highpath.endsWith(".mp4"))
				{
					highpath = "";
				}
				if (lowpath == "" && highpath !="")
				{
					lowpath = highpath;
				}

				if (lowpath == "")
				{
					uvgplayer = "This video is not supported by your browser.";
				}
				else
				{
					var extraMessage = "";
					if (this.baselineonly)
					{
						playerheight -= 40; // to place the extra message
						highpath = "";
						extraMessage = "<p class='Help Normal'>Our videos might not fully work on iPhone/iPad.</p>";
					}

					if (highpath != "")
					{
						playerheight -= 40; // to place the radio buttons
						var iden = this.mid;
						uvgplayer = "<div id='UVGL" + iden + "'>";
						uvgplayer += "<video src='" + lowpath + "' type='video/mp4' width='" + playerwidth + "px' height='" + playerheight + "px' controls='controls' />";
						uvgplayer += "</div><div id='UVGH" + iden + "' style='display:none;'>";
						uvgplayer += "<video src='" + highpath + "' type='video/mp4' width='" + playerwidth + "px' height='" + playerheight + "px' controls='controls' />";
						uvgplayer += "</div><p class='Normal'>";
						uvgplayer += "<input id='qualityLow' type='radio' name='quality' value='low' checked='checked' onclick=\"document.getElementById('UVGL" + iden + "').style.display='block';document.getElementById('UVGH" + iden + "').style.display='none';\" /><label for='qualityLow'>Low quality</label> <input id='qualityHigh' type='radio' name='quality' value='high' onclick=\"document.getElementById('UVGL" + iden + "').style.display='none';document.getElementById('UVGH" + iden + "').style.display='block';\" /><label for='qualityHigh'>High quality</label>";
						uvgplayer += "</p>";
					}
					else if (lowpath != "")
					{
						uvgplayer = "<div><video src='" + lowpath + "' type='video/mp4' width='" + playerwidth + "px' height='" + playerheight + "px' controls='controls' /></div>";
					}
					else
					{
						extraMessage = "<p class='Help Normal'>This video is not available on your browser.</p>";
					}

					uvgplayer += extraMessage;
				}
			}
			else
			{
				var flashvars = "vId="+id+"&portalId="+this.portalid+"&baseUrl="+this.baseurl+"&mid="+this.mid;
				uvgplayer = "<object allowFullScreen='True' allowScriptAccess='always' allowNetworking='all' width='"+playerwidth+"' height='"+playerheight+"' wmode='transparent'><param name='movie' value='"+this.baseurl+"mediacenter.swf' /><param name='allowFullScreen' value='true' /><param name='wmode' value='transparent' /><param name='flashvars' value='" + flashvars + "' /><embed src='"+this.baseurl+"mediacenter.swf' type='application/x-shockwave-flash' allowFullScreen='True' allowScriptAccess='always' allowNetworking='all' wmode='transparent' width='"+playerwidth+"' height='"+playerheight+"' flashvars='" + flashvars + "'></embed></object>";
			}
			videoplayer.attr("innerHTML", uvgplayer);
		}

		title.attr("innerHTML", tlt);
		description.attr("innerHTML", unescape(desc));
		xcomment.attr("innerHTML", "<div class='commentbg'>" + comments + "</div>Comments");
		//addcomment.attr("innerHTML", "Add a Comment");

		this.showAuthorInfo(createdbyuser, id);

		if (index >= 0)
		{
			var items = thumbs.find("a");
			var item = jQuery(items[index]);
			xofy.attr("innerHTML", "Now playing " + (index+1) + " of " + items.length);
			if (currentItem >= 0)
			{
				jQuery(items[currentItem]).removeClass("active");
			}

			//ensure this item in thumbslist is visible
			var itemLeft = item.position().left + thumbs.position().left;
			var itemRight = itemLeft + item.width();
			if (itemLeft < 0 || itemRight > thumbslist.width())
			{
				//left or right side not fully visible, or completely invisible
				var ttlWidth = thumbslist.width();
				var itemWidth = this.getFirstThumbWidth();
				var newLeft = Math.floor(ttlWidth / itemWidth / 2) * itemWidth - item.position().left;
				var barWidth = this.getThumbsWidth();
				if (newLeft > 0)
				{
					newLeft = 0
				}
				else if (newLeft + barWidth < thumbslist.width())
				{
					newLeft = thumbslist.width() - barWidth;
				}

				thumbs.animate({"left": newLeft}, "fast", this.ensureScrollVisibility);
			}
			//ok

			item.addClass("active");
			currentItem = index;
		}
		currentItemId = id;
		this.setCookie("LastWatch", new Date().getTime());
	}

	this.showAuthorInfo = function(userid,videoid){
		if(jQuery(dest + ".lowerbody").length == 0)
		{
			return;
		}

		if ("user|" + userid == jQuery(dest + ".criteria").attr("value"))
		{
			jQuery(dest + ".seeall").hide();
			return;
		}
		var eventArgs = 'user|' + userid + "|" + videoid;
		dnn.xmlhttp.doCallBack('MediaCenter ' + this.clientid,eventArgs,this.showAuthorInfo_CallBack,this,this.gnl_CallBackError,null,null,null,0);
	};

	this.showAuthorInfo_CallBack = function(result, ctx){
		var meta = result.split("|");
		var info = "<table width='100%' class='Normal'><tr><td align='center' rowspan='2'><img height='45' src='"+meta[2]+"' /></td><td class='regdate'>since " + meta[1] + "</td></tr><tr><td class='displayname'>" + meta[0] + "</td></tr><tr><td colspan='2'>"+meta[4]+"</td></tr></table>";
		jQuery(dest + ".lowerbody").attr("innerHTML", info);
		var seeall = jQuery(dest + ".seeall");
		if (meta[3] * 1 > 1)
		{
			seeall.attr("innerHTML",  "see all " + meta[3] + " videos");
			seeall.attr("title", meta[0]+"("+meta[3]+")");
			seeall.show();
		}
		else
		{
			seeall.hide();
		}
	}

	this.gnl_CallBackError = function(result, ctx)
	{
		alert(result);
	}

	jQuery(dest + ".seeall").click(function(){
		jQuery(dest + ".seeall").hide();

		var items = thumbs.find("a");
		var userid = jQuery(items[currentItem]).find(".createdbyuser").attr("innerHTML");

		var cbocriteria = jQuery(dest + ".criteria");
		var optns = cbocriteria.attr("options");
		var userIndex = -1;
		for (var i=0;i<optns.length ;i++ )
		{
			if (optns[i].value ==  "user|"+userid)
			{
				userIndex = i;
				break;
			}
		}

		var hassplitter = false;
		if (userIndex <= 0)
		{
			for (var i=0;i<optns.length ;i++ )
			{
				if (optns[i].value == "-2")
				{
					hassplitter = true;
					break;
				}
			}

			if (!hassplitter)
			{
				optns[optns.length] = new Option("********************", "-2");
			}

			optns[optns.length] = new Option(jQuery(dest + ".seeall").attr("title"), "user|"+userid);
			optns.selectedIndex = optns.length - 1;
		}
		else
		{
			optns.selectedIndex = userIndex;
		}

		//update video list;

		_this.updateVideoList();
	});

	jQuery(dest + ".criteria").change(function(){
		_this.updateVideoList();
	});

	this.updateDefaultVideoList();
	this.navigateTo(0);

	this.updateVideoList = function(){

		var cbocriteria = jQuery(dest + ".criteria").get(0);
		var cta = cbocriteria.options[cbocriteria.selectedIndex].value;
		if (cta == "-1" || cta == "-2")
		{
			//splitter
			return;
		}
		if (cta * 1 > 0)
		{
			if (cbocriteria.selectedIndex < cbocriteria.options.length - 1)
			{
				//not the last item
				if (cbocriteria.options[cbocriteria.selectedIndex].text.lastIndexOf('--') < cbocriteria.options[cbocriteria.selectedIndex+1].text.lastIndexOf('--'))
				{
					isParent = true;
					return;
				}
			}
		}
		var params = cta.split("|");
		thumbslist.animate({"margin-top":thumbslist.height()},"fast");
		loading.show();
		dnn.xmlhttp.doCallBack('MediaCenter ' + _this.clientid,"loadby|"+cta,this.updateVideoList_CallBack,this,this.gnl_CallBackError,null,null,null,0);
	};

	this.updateVideoList_CallBack = function(result, ctx)
	{
		var results = result.split("!");
		loading.hide();
		thumbs.css("left", 0);
		thumbs.children("a").remove();
		for (var i=0;i<results.length ;i++ )
		{
			//id, title, thumbnail, createdbyuser, description, comments, tag, createddate, sourcetype, lowpath, highpath, embedcode
			//or id, title, thumbnail, createdbyuser, description, comments, tag, createddate, sourcetype, embedcode
			var info = results[i].split("|");
			addVideoToList(info);
		}
		thumbslist.animate({"margin-top":0},"slow");

		_this.ensureScrollVisibility();

		//mark current item as active
		var items = thumbs.find("a");
		for (var i=0;i<items.length ;i++ )
		{
			if (jQuery(items[i]).find(".videoid").attr("innerHTML") == currentItemId)
			{
				jQuery(items[i]).addClass("active");
				return;
			}
		}

	}

	function addVideoToList(info)
	{
		var index = thumbs.find("a").length;
		var item = "";
		item += "<a href='javascript:uvg_MC"+mid+".navigateTo("+index+")'><img class='image' id='img"+index+"' index='"+index+"' src='"+info[2]+"' /> <br /> <div class='title'>" + info[1] +"</div>";
				
		item += "<div style='display:none'>";
		item += "	<div class='videoid'>" + info[0] + "</div>";
		item += "	<div class='createdbyuser'>" + info[3] + "</div>";
		item += "	<div class='description'>" + info[4] + "</div>";
		item += "	<div class='comment'>" + info[5] + "</div>";
		item += "	<div class='tag'>" + info[6] + "</div>";
		//item += "	<div class='createddate'>" + info[7] + "</div>";
		if (info[8]=="embedcode")
		{
			item += "	<textarea class='embedcode'>" + info[9] + "</textarea>";
		}
		else
		{
			item += "	<div class='lowpath'>" + info[9] + "</div>";
			item += "	<div class='highpath'>" + info[10] + "</div>";
		}
		item += "</div>";
			
		var days = Math.ceil((new Date().getTime() - info[7]) / (1000*60*60*24));
		if(days < _this.newperiod)
		{
			//this is a new video
			item += "<div class='newitem' />";
		}

		item += "</a>";

		thumbs.append(item);

	}

	//comments
	this.showComment = function(page)
	{
		if (!page)
		{
			page = 0;
		}
		currentPage = page;
		this.enterLoadingState();
		var eventArgs = 'comment|load|' + currentItemId + "|" + currentPage;
		dnn.xmlhttp.doCallBack('MediaCenter ' + this.clientid,eventArgs,this.showComment_CallBack,this,this.gnl_CallBackError,null,null,null,0);
	}

	this.enterLoadingState = function()
	{
		var ldg = "<div class='commentloading'></div>";
		jQuery(dest + ".allcomments").attr("innerHTML", ldg);
	}

	this.showComment_CallBack = function(result, ctx)
	{
		var comments = result;
		var commentsData = comments;
		jQuery(dest + ".allcomments").attr("innerHTML", commentsData);

		jQuery(dest + ".allcomments .deletecomment").click(function(){
			if (!window.confirm("Are you sure you wish to delete this item?"))
			{
				return;
			}
			var eventArgs = 'comment|delete|' + this.title;
			_this.enterLoadingState();
			dnn.xmlhttp.doCallBack('MediaCenter ' + _this.clientid,eventArgs,_this.deleteComment_CallBack,this,_this.gnl_CallBackError,null,null,null,0);
		});

		jQuery(dest + ".allcomments .quotecomment").click(function(){
			var src = jQuery(dest + ".allcomments #UVGComment_" + this.itemid);
			var author = this.author;
			var msg = src.attr("innerHTML");

			var html = "\n[QUOTE]" + author + " says:<br>" + msg + "[/QUOTE]";
			var txtComment = jQuery(dest + "#txtComment");
			txtComment.attr("value", html);
			txtComment.focus();
		});


	}

	_this.deleteComment_CallBack = function(result, ctx)
	{
		if (result != "")
		{ 
			alert(result);
			return;
		}  
		
		_this.showComment(currentPage);
	};

	this.loadVideoById = function(id)
	{
		dnn.xmlhttp.doCallBack('MediaCenter ' + _this.clientid,"loadbyid|"+id,this.loadVideoById_CallBack,this,this.gnl_CallBackError,null,null,null,0);
	}

	this.loadVideoById_CallBack = function(result, ctx)
	{
		//id, title, thumbnail, createdbyuser, description, comments, tag, createddate, sourcetype, lowpath, highpath, embedcode
		//or id, title, thumbnail, createdbyuser, description, comments, tag, createddate, sourcetype, embedcode
		var info = result.split("|");

		var index = -1;
		var items = thumbs.find("a");
		for (i=0;i<items.length ;i++ )
		{
			var idofi = jQuery(items[i]).find(".videoid").attr("innerHTML");
			if (idofi == info[0])
			{
				//that's it
				index =  i;
				break;
			}
		}

		//	this.play = funcction(index,	id, videotitle, createdbyuser, description, comments, lowpath, highpath, embedcode)

		var lowpath;
		var highpath;
		var embedcode="";
		if (info[8] == "embedcode")
		{
			embedcode = info[9];
		}
		else
		{
			lowpath = info[9];
			highpath = info[10];
		}
		_this.play(index, info[0], info[1], info[3], info[4], info[5], lowpath, highpath, embedcode);
	}

	//return this;
}



