// MediaMelon Namespace
var MediaMelon = {
	stopEvent: function(e){
		if(!e) { return };
		if(e.preventDefault){
      e.preventDefault();
      e.stopPropagation();
    }else{
      e.returnValue = false;
      e.cancelBubble = true;
    }
	},
	addEvent: function(e, n, o, c){
		if(e.addEventListener) {
    	e.addEventListener(n, o, (c || false));
		}else if(e.attachEvent){
			if(e==window && n=="mouseup") { e = document }
	  	e.attachEvent('on' + n, o);
    }
	},
	removeEvent: function(e, n, o, c){
		if(e.removeEventListener) {
    	e.removeEventListener(n, o, (c || false));
		}else if(e.attachEvent){
			if(e==window && n=="mouseup") { e = document }
	  	e.detachEvent('on' + n, o);
    }
	},
	toArray: function(item){
	  if(!item){
			return [];
		}else if(item.splice){
			return item;
		}else{
	    var results = [];
			if(item.length>0) {
	    	for (var i = 0; i < item.length; i++) results.push(item[i]);
			} else {
				results.push(item);
			}
	    return results;
	  }
	},
	getElementsByClassName: function(className, parentElement){
	  var children = (parentElement||document).getElementsByTagName('*'), elements = [];
		for(var i=0; i<children.length; i++){
			if(children[i].className.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))){
				elements.push(children[i]);
			}
		}
	  return elements;
	},
	addClassName: function(element, rule) {
    element.className = element.className + " " + rule;
  },
	removeClassName: function(element, rule) {
    element.className = element.className.replace(new RegExp("(^||( ))"+rule+"([\d\w]||$||( ))","g"),"$1"+"$2");
  },
	hasClassName: function(element,rule){
    return (element.className.search(new RegExp("(^|| )"+rule+"([\d\w]||$|| )","g"))>=0) ? true:false;
  }
};

MediaMelon.Popup = function(target){
	this.target = target;
	this.instances.members.push(this);
	this.open = function(){
		this.instances.active = this;
		this.target.style.visibility = "visible";
	}
	this.close = function(){
		this.target.style.visibility = "hidden";
		this.instances.active = null;
	}
	return this;
}

MediaMelon.Popup.prototype.instances = new function(){
	this.members = [];
	this.active = null;
	this.reset = function(){
		if(this.active){
			this.active.close();
		}
	}
}

MediaMelon.IframePopup = function(target){
	this.target = target;
	this.instances.members.push(this);
	this.open = function(){
		this.instances.active = this;
		this.target.style.zIndex = "1000";
		this.target.style.visibility = "visible";
	}
	this.close = function(){
		this.target.style.zIndex = "-1";
		this.target.style.visibility = "hidden";
		this.instances.active = null;
	}
	return this;
}

MediaMelon.IframePopup.prototype.instances = new function(){
	this.members = [];
	this.active = null;
	this.reset = function(){
		if(this.active){
			this.active.close();
		}
	}
}

var MM ={};
MM.Toggle = function(source,target,show,hide){
	this.source = source;
	this.target = target||source;
	this.show = show;
	this.hide = hide;
	if (Element.hasClassName(this.source,"sub-section-nav-toggle")) {
	var sectionItems = this.source.getElementsByClassName("section-nav-item");
		for(var i=0; i<sectionItems.length; i++){
			Event.observe(sectionItems[i], "click", function(e){
				Event.stop(e);
				if(Element.hasClassName(this.target, this.hide)){
					Element.removeClassName(this.target, this.hide)
					Element.addClassName(this.target, this.show)
				}else{
					Element.removeClassName(this.target, this.show)
					Element.addClassName(this.target, this.hide)
				}
			}.bind(this));
		}
	} else {
		Event.observe(this.source, "click", function(e){
		Event.stop(e);
			if(Element.hasClassName(this.target, this.hide)){
				Element.removeClassName(this.target, this.hide)
				Element.addClassName(this.target, this.show)
			}else{
				Element.removeClassName(this.target, this.show)
				Element.addClassName(this.target, this.hide)
			}
		}.bind(this));
	}
	return this;
}

MediaMelon.Toggle = function(source,target,show,hide){
	this.source = source;
	this.target = target||source;
	this.show = show;
	this.hide = hide;
	var scope = this;
	MediaMelon.addEvent(scope.source, "click", function(e){
		MediaMelon.stopEvent(e);
		if(MediaMelon.hasClassName(scope.target, scope.hide)){
			MediaMelon.removeClassName(scope.target, scope.hide)
			MediaMelon.addClassName(scope.target, scope.show)
		}else{
			MediaMelon.removeClassName(scope.target, scope.show)
			MediaMelon.addClassName(scope.target, scope.hide)
		}
	});
	return this;
}

MediaMelon.addEvent(window, "load", function(){
	// Initiate sub section navigation toggle
	var section_navs = MediaMelon.toArray(MediaMelon.getElementsByClassName("sub-section-nav-toggle"));
	for(var i=0; i<section_navs.length; i++){
		new MM.Toggle(section_navs[i],null,"sub-section-nav-open","sub-section-nav-closed");
	}
	// Initate thumbnail popups
	var popups = MediaMelon.toArray(MediaMelon.getElementsByClassName("media-popup"));
	for(var i=0; i<popups.length; i++){
		(function(popup){
			MediaMelon.addEvent(popups[i], "mouseover", function(e){
				MediaMelon.stopEvent(e);
				popup.instances.reset();
				popup.open();
			});
			MediaMelon.addEvent(document, "mouseover", function(e){
				popup.instances.reset();
			});
		}(new MediaMelon.Popup(MediaMelon.getElementsByClassName("media-popup-content",popups[i])[0])));
	}
	// Initiate thumbnail load area toggle
	var toggle_source_show = document.getElementById("media_load_toggle_source_show");
	var toggle_source_hide = document.getElementById("media_load_toggle_source_hide");
	var toggle_target = document.getElementById("media_load_toggle_target");
	if(toggle_source_show && toggle_source_hide && toggle_target){
		new MediaMelon.Toggle(toggle_source_show,toggle_target,"media-load-toggle-open","media-load-toggle-closed")
		new MediaMelon.Toggle(toggle_source_hide,toggle_target,"media-load-toggle-open","media-load-toggle-closed")
	}
	// Initiate register popup
	MediaMelon.RegisterPopup = new MediaMelon.Popup(document.getElementById("register_popup"));
	MediaMelon.RegisterInvitedPopup = new MediaMelon.Popup(document.getElementById("register_invited_popup"));

	// Onclick class change for subsec items:
	var subsecs = (MediaMelon.getElementsByClassName("sub-section-nav-item"));
	for(var i=0; i<subsecs.length; i++){
		new MM.ActivateSubSection(subsecs[i],"sub-section-nav-active");

	}

	// Onclick class change for section items:
	var sections = (MediaMelon.getElementsByClassName("section-nav-item"));
	for(var i=0; i<sections.length; i++){
		new MM.ActivateSection(sections[i],"section-nav-active");
	}

	//Initiate Install popup
	MediaMelon.InstallPopup = new MediaMelon.Popup(document.getElementById("install_popup"));
	//Initiate Forgot password popup
	MediaMelon.FpPopup = new MediaMelon.Popup(document.getElementById("forgot_password_popup"));
	//Initiate reset password popup
	MediaMelon.RpPopup = new MediaMelon.Popup(document.getElementById("reset_password_popup"));
	// Initiate Feedback popup
	MediaMelon.FeedbackPopup = new MediaMelon.IframePopup(document.getElementById("feedback_popup"));

});

MM.ActivateSubSection = function(target, activeClassName){
	this.target = target;
	this.activeClassName = activeClassName;
	var subsecs = (document.getElementsByClassName("sub-section-nav-item"));
	Event.observe(target, "click", function(e){
		Event.stop(e);
		for(var i=0; i<subsecs.length; i++){
			if(Element.hasClassName(subsecs[i], this.activeClassName)){
				Element.removeClassName(subsecs[i], this.activeClassName);
			}
		}
		Element.addClassName(this.target, this.activeClassName);
		var sections = (document.getElementsByClassName("section-nav-item"));
		for(var i=0; i<sections.length; i++){
			if(Element.hasClassName(sections[i], "section-nav-active")){
				Element.removeClassName(sections[i], "section-nav-active");
			}
		}
		Element.addClassName(this.target.parentNode.parentNode.firstChild,"section-nav-active");
	}.bind(this));
	return this;
}


MM.ActivateSection = function(target, activeClassName){
	this.target = target;
	this.activeClassName = activeClassName;
	var sections = (document.getElementsByClassName("section-nav-item"));
	Event.observe(target, "click", function(e){
		Event.stop(e);
		for(var i=0; i<sections.length; i++){
			if(Element.hasClassName(sections[i], this.activeClassName)){
				Element.removeClassName(sections[i], this.activeClassName);
			}
		}
		Element.addClassName(this.target, this.activeClassName);
	}.bind(this));
	return this;
}

function showShareDiv(id){
	document.getElementById("nonShareDiv"+id).style.display="none";
	document.getElementById("shareDiv"+id).style.display="";
}

function submitShareForm(id){
new Ajax.Request("shareProgram.do", {
	   parameters : Form.serialize(document.getElementById("shareForm"+id))
	 });
	document.getElementById("shareDiv"+id).style.display="none";
	document.getElementById("nonShareDiv"+id).style.display="";
}

function showShareChannelDiv(id){
	document.getElementById("nonShareChannelDiv"+id).style.display="none";
	document.getElementById("shareChannelDiv"+id).style.display="";
}

function submitShareChannelForm(id){
new Ajax.Request("shareChannel.do", {
	   parameters : Form.serialize(document.getElementById("shareChannelForm"+id))
	 });
	document.getElementById("shareChannelDiv"+id).style.display="none";
	document.getElementById("nonShareChannelDiv"+id).style.display="";
}


function ajaxUpdater(id,url) {
	new Ajax.Updater(id,url,{asynchronous:true,onComplete:updatePopups});
}

function updateChannelObjs(id){
	showLoading();
 	var url =  'MyMedia.do?action=showSub&channelId=' + id;
	ajaxUpdater('contentarea',url);
}

function showRecommendedObjects(){
	showLoading();
 	var url =  'MyMedia.do?action=showRecommended';
	ajaxUpdater('contentarea',url);
}

function acceptRecoInvite(inviteid){
	showLoading();
 	var url =  'MyMedia.do?acceptInvite='+inviteid;
	ajaxUpdater('contentarea',url);
}

function deleteRecoInvite(inviteid){
	showLoading();
 	var url =  'MyMedia.do?deleteInvite='+inviteid;
	ajaxUpdater('contentarea',url);
}

function sortMyMediaAllVideos(criteria, view){
	showLoading();
	var url =  'MyMedia.do?action=' + criteria + "&view=" + view;
	ajaxUpdater('videoIconList',url);
}

function updatePopups(){
	var channelIcons = document.getElementById('videoIconList');
	var popups = (document.getElementsByClassName("media-popup"));
	for(var i=0; i<popups.length; i++){
		(function(popup){
			MediaMelon.addEvent(popups[i], "mouseover", function(e){
				MediaMelon.stopEvent(e);
				popup.instances.reset();
				popup.open();
			});
			MediaMelon.addEvent(document, "mouseover", function(e){
				popup.instances.reset();
			});
		}(new MediaMelon.Popup(MediaMelon.getElementsByClassName("media-popup-content",popups[i])[0])));
	}
	// check if user is on right device.
	checkforalert();

	document.getElementById('loading').innerHTML="";
}

function showLoading(){
	document.getElementById('loading').innerHTML="<img src='images/ajaxloading.gif'/>";
}

function updatSaveVideoStatus(form, objid, saveVideoStatus) {
  window.location.replace(form+"?objid=" + objid+"&autoDelete="+saveVideoStatus);
}
function updatSaveVideoStatusListView(form, objid, saveVideoStatus) {
  window.location.replace(form+"?view=list&objid=" + objid+"&autoDelete="+saveVideoStatus);
}
function deleteVideo(form, objid) {
  window.location.replace(form+"?deleteObjId=" + objid);
}
function deleteVideoListView(form, objid) {
  window.location.replace(form+"?view=list&deleteObjId=" + objid);
}
function addAdditionalEmail(email){
var path='myAccount.do?addEmail=' + email;;
var myAjax = new Ajax.Request(
		path,
		{
			method: 'get',
			onComplete: showaddAdditionalEmailResponse
		});
}
function saveVideoStatusFromPlayer(deviceid,objid){
var path='Play.do?objid=' + objid +'&deviceid=' + deviceid + "&saveVideo=true";
var myAjax = new Ajax.Request(
		path,
		{
			method: 'get',
			onComplete: showSaveVideoStatus
		});
}
function showSaveVideoStatus () {
document.getElementById('save').innerHTML="<font color=green>Saved</font>"
}
function showaddAdditionalEmailResponse(originalRequest)	{
	var response=originalRequest.responseText;
		if (response=="success"){
			document.getElementById('addtionalEmail').value ="";
			reloadPage();
			document.getElementById("errormsg").innerHTML='Email Successfully added';

		}
		if (response=="failed"){
			reloadPage();
			document.getElementById("errormsg").innerHTML='Failed adding email';
		}
	setTimeout("getIsUserLoggedIn()",10000);
}

function changeEmailSettings(channelid, emailondownload){
 		var path='myAccount.do?tab=emailSettings&subid=' + channelid + '&emailondownload=' + emailondownload;
		var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: function(){changeCdsDivHtml(channelid, emailondownload);}
		});
}

function changeCdsDivHtml(channelid, emailondownload){
	if (emailondownload==1) {
		if(document.getElementById('cds' + channelid))
		document.getElementById('cds' + channelid).innerHTML="<span style='color:green'>Send Email On </span> (<a href='javascript:void(0)' onclick='changeEmailSettings(" + channelid + ",0)'><span style='color:red'> Off </span></a>)";
	} else if (emailondownload==0) {
		if(document.getElementById('cds' + channelid))
		document.getElementById('cds' + channelid).innerHTML="<span style='color:red'>Send Email Off </span> (<a href='javascript:void(0)' onclick='changeEmailSettings(" + channelid + ",1)'><span style='color:green'> On </span></a>)";
	}
}
function deletePublishChannel(channelid){
 var answer = confirm("Are you sure want to delete channel");
	 if(answer) {
		var path='PublishChannel.do?deletechannel=' + channelid;
		var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: reloadPageAfterPublishChannelDelete
		});
	}
}

function reloadPageAfterPublishChannelDelete() {
	window.location.replace("PublishChannel.do?action=allchannels");
}

function deletePublishVideo(channelid, videoid){
 var answer = confirm("Are you sure want to delete this video");
	 if(answer) {
		var path='PublishChannel.do?deletevideo=' + videoid + '&channelid=' + channelid;
		var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: function(){reloadPageAfterPublishVideoDelete(channelid);}
		});
	}
}

function reloadPageAfterPublishVideoDelete(channelid) {
	if (channelid==0){
		window.location.replace("PublishChannel.do?action=showIndVideos");
	} else {
		window.location.replace("PublishChannel.do?action=showPublishChannel&channelid=" + channelid);
	}
}
function showInnerFrame(avatarId){
	document.getElementById("invisibleFrame").innerHTML="<iframe src='addVideoFromFlash.jsp?objid=" + avatarId + "'></iframe>";
}
function addVideoViaFaceBook(avatarId){
	// this ajax request is to just to post to template nothing else.
	var path='FaceBook.do?action=addvideo&mediaid=' + avatarId + "&deviceid=" + device;
	var myAjax = new Ajax.Request(
		path,
		{
			method: 'post'
		});
		
	// now adding video to device as we do on, mediaguide
	if (device == 0) {
		downloadPlugIn('downloadLink-v'+avatarId);
		setTimeout("showInnerFrame(" + avatarId + ")", 10000);
	} else {
		var path='scheduleVideo.jsp?addVideo='+avatarId+'&deviceId='+device;
		var myAjax = new Ajax.Request(path,{method: 'post', onComplete: reloadPage()});
	}
}

function updateVideoStatusOnFacebook(device) {
	var url = 'DownloadShell?deviceId='+device;
	var myAjax = new Ajax.Request(url, {method: 'get', onComplete: updateVideoStatusResponseFacebook});
}

function updateVideoStatusResponseFacebook(response) {
	var arraytext=response.responseText.substring(1,response.responseText.length-1);
	var arr=arraytext.split(",");
	for(var n in arr) {
		var objArray = new Array(2);
		s=new String(arr[n]);
		objArray=s.split("=");
		try {
			var id = objArray[0].replace(/^\s+|\s+$/, '');
			var FBLoadImg=document.getElementsByName("FBLoadImg"+id);
			if(FBLoadImg.length > 0) {
				for(var i=0;i<FBLoadImg.length;i++) { 
					if (objArray[1].replace(/^\s+|\s+$/, '')<100) {
						FBLoadImg[i].innerHTML = "<img src='stylesheets/images/facebook_loading_icon.gif' border='0' style='margin-top:5px;width:16px;height:16px;'/>"
					} else if (objArray[1].replace(/^\s+|\s+$/, '')==100) {
						FBLoadImg[i].innerHTML = "<a class='fb_share_button' href='javascript:void(0)' onclick='onPlayViaFaceBook("+id+")'><img src='stylesheets/images/facebook_play_icon.gif' border='0' style='margin-top:5px;width:16px;height:16px;'/> Play HD</a>"
					}
				}
			}
		}
		catch(E) {}
	}
	updateVideoPercent(device);
}


function getDeviceVideosOnFB(deviceid, sessionKey){
	var path='FaceBook.do?action=showDeviceVideos&deviceid=' + deviceid + "&sessionKey=" + sessionKey;
	var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: showDeviceVideosOnFB
		});
	
}


function showDeviceVideosOnFB(originalRequest){
	if(document.getElementById("myDeviceVideos")){
		document.getElementById("myDeviceVideos").innerHTML = originalRequest.responseText;
	}
	document.getElementById("showHideMyVideos").innerHTML=" ( <a href='javascript:hideMyVideosFacebook();'>hide</a> )"
	updateVideoStatusOnFacebook(device);
}

function addVideo(avatarId){
var path='MediaGuide.do?addVideo=' + avatarId;
var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: reloadPage
		});
}



function downloadPlugIn(id) {
	var downloadObj = document.getElementsByName(id)[0];
	if ((navigator.userAgent.indexOf("Macintosh")!=-1) && (navigator.userAgent.indexOf("Intel")!=-1)) {
		downloadObj.href="http://download.mediamelon.com/mediamelon.dmg";
	} else if ((navigator.userAgent.indexOf("Macintosh")!=-1) && (navigator.userAgent.indexOf("PPC")!=-1)) {
		downloadObj.href="http://download.mediamelon.com/mediamelon.dmg";
	} else if (navigator.userAgent.indexOf("Macintosh")!=-1) {
		downloadObj.href="http://download.mediamelon.com/mediamelon.dmg";
	} else if (navigator.userAgent.indexOf("Windows")!=-1) {
		downloadObj.href="http://download.mediamelon.com/mediamelon.exe";
	} else {
		downloadObj.href="http://download.mediamelon.com/mediamelon.exe";
	}
	downloadObj.onclicked;
	if(document.getElementById("floatingResponseDivInner")){
		document.getElementById("floatingResponseDivInner").innerHTML = "<b>&nbsp;Please Install MediaMelon PlugIn</b> &nbsp;&nbsp;&nbsp;&nbsp;" ;
		document.getElementById("floatingResponseDiv").style.display="";
		setTimeout("hideFloatingResponseDiv()",20000);
	}
	if(document.getElementById("invisibleFrame")){
		setTimeout("showInvisibleFrame()", 5000);
	}
}

function showInvisibleFrame(){
		document.getElementById("invisibleFrame").innerHTML="<iframe src='downloadInstallerInvisibleFrame.jsp' width=1 height=1></iframe>";
}
function addVideoToDevice(avatarId) {
	if (device == 0) {
		downloadPlugIn('downloadLink-v');
	} else {
		var path='scheduleVideo.jsp?addVideo='+avatarId+'&deviceId='+device;
		var myAjax = new Ajax.Request(path,{method: 'post', onComplete: reloadPage()});
	}
}

function showAddVideo(avatarId, size){
	var path='MediaGuide.do?addVideo=' + avatarId;
	var myAjax = new Ajax.Request(
			path,
			{
				method: 'post',
				onComplete: function(){modifyAddChanges(avatarId, size);}
			});
}

function showAddVideoToDevice(avatarId, size) {
	if (device == 0) {
		downloadPlugIn('downloadLink-v'+avatarId);
	} else {
		var path='scheduleVideo.jsp?addVideo='+avatarId+'&deviceId='+device;
		var myAjax = new Ajax.Request(path,{method: 'post', onComplete: scheduled(avatarId, size)});
		delete path;
	}
}

function scheduled(avatarId, size) {
	connectTransport(avatarId);
	var speed = 500;
	var timeLeft = Math.floor(size * 1024 / speed) ;
	var timeMin = Math.ceil(timeLeft/ 60);
	var timeSec = timeLeft % 60;
	
	var hoverPlay = document.getElementsByName("hoverPlay"+avatarId);
	for(var i=0;i<hoverPlay.length;i++) {
		hoverPlay[i].innerHTML ="<img src='images/videoloading.gif' />";
	}
	var timer = document.getElementsByName("timer"+avatarId);
	var l = timer.length;
	for(var j=0;j<l;j++) {
		timer[j].innerHTML ="<span id='av" + avatarId + "' name='av" + avatarId + "' style='display:none'>0</span><span id='timer" + avatarId + "' name='timer" + avatarId + "'>"+timeMin + ":" + timeSec+"</span>";
		
	}
	getTimerHtml(0,avatarId);
	document.getElementById("floatingResponseDivInner").innerHTML="<a href='MediaGuide.do?showVideoDetailsFor="+avatarId+"'>The video</a> has been scheduled to download, it will take appx. " + timeMin + " mins to download. &nbsp;&nbsp;&nbsp;&nbsp;" ;
	document.getElementById("floatingResponseDiv").style.display="";
	setTimeout("hideFloatingResponseDiv()",20000);
}

function deleteVideoUndo(objid){
	if (window.location.href.lastIndexOf("deleteObjId")==-1){
		if(window.location.href.substring(window.location.href.length-2,window.location.href.length) == "do") {
		window.location.replace(window.location.href+"?&deleteObjId=" + objid);
		} else {
			window.location.replace(window.location.href+"&deleteObjId=" + objid);
		}
	} else {
		window.location.replace(window.location.href.substring(0,window.location.href.lastIndexOf("deleteObjId")) + "deleteObjId=" + objid);
	}
} 

function modifyAddChanges(avatarId, size){
	connectTransport(avatarId);
	var speed = 500;
	var timeLeft = Math.floor(size * 1024 / speed) ;
	var timeMin = Math.ceil(timeLeft/ 60);
	var timeSec = timeLeft % 60;
	
	var hoverPlay = document.getElementsByName("hoverPlay"+avatarId);
	for(var i=0;i<hoverPlay.length;i++) {
		hoverPlay[i].innerHTML ="<img src='images/videoloading.gif' />";
	}
	var videoadded = document.getElementsByName("videoadded"+avatarId);
	for(var i=0;i<videoadded.length;i++) {
		videoadded[i].innerHTML ="<span id='av" + avatarId + "' name='av" + avatarId + "' style='display:none'>0</span><span id='timer" + avatarId + "' name='timer" + avatarId + "'>"+timeMin + ":" + timeSec+"</span>";
	}
	getTimerHtml(0,avatarId);
	document.getElementById("floatingResponseDivInner").innerHTML="<a href='MediaGuide.do?showVideoDetailsFor="+avatarId+"'>The video</a> has been scheduled to download, it will take appx. " + timeMin + " mins to download.&nbsp;&nbsp;<b><a href='#' onclick=\"deleteVideoUndo("+avatarId+");\"'>Remove it !</a></b> &nbsp;&nbsp;&nbsp;&nbsp;" ;
	document.getElementById("floatingResponseDiv").style.display="";
	setTimeout("hideFloatingResponseDiv()",20000);
}

function connectTransport(avatarId) {
	var path = "http://localhost:11111/requestAvatar?id=" + avatarId ;
	var myAjax = new Ajax.Request(path,{method: 'post'});
	delete path;
}

function hideFloatingResponseDiv(){
	document.getElementById("floatingResponseDiv").style.display="none";
}

function cancelAddVideo(avatarId) {
	document.getElementById("firstLayer"+avatarId).style.display = "";
	document.getElementById("secondLayer"+avatarId).style.display = "none";
}

function subscribeDevice(channelid){
	if (device == 0) {
		downloadPlugIn('downloadLink-c'+channelid);
	} else {
		var path='subscribeChannel.jsp?channelId='+channelid+'&deviceId='+device+'&action=sub';
		var myAjax = new Ajax.Request(path,{method: 'post', onComplete: subscribed("sub",channelid)});
	}
}

function unsubscribeDevice(channelid){
	var path='subscribeChannel.jsp?channelId='+channelid+'&deviceId='+device+'&action=unsub';
	var myAjax = new Ajax.Request(path,{method: 'post', onComplete: subscribed("unsub",channelid)});
}

function subscribed(action, channelid){
	if(action == "sub") {
		if(document.getElementById("subscribe"+channelid))
			document.getElementById("subscribe"+channelid).innerHTML ="<a href='#' class='thumbnail-view-unsubscribe-black on-channel-icon' onclick='unsubscribeDevice("+channelid+")'>Unsubscribe</a>";
		if(document.getElementById("floatingResponseDivInner"))
			document.getElementById("floatingResponseDivInner").innerHTML="<b>You have been subscribed to <a href='MediaGuide.do?showChannelDetailsFor="+channelid+"'>this Channel</a>.<br/><br/>&nbsp;&nbsp;To Unsubscribe <a href='#' onclick=\"unsubscribeChannel("+channelid+");\"'>click here!</a></b> &nbsp;&nbsp;&nbsp;&nbsp;" ;
		if(document.getElementById("floatingResponseDiv")) {
			document.getElementById("floatingResponseDiv").style.display="";
			setTimeout("hideFloatingResponseDiv()",20000);
		}
	} else {
		if (document.getElementById("subscribe"+channelid))
			document.getElementById("subscribe"+channelid).innerHTML ="<a href='#' class='thumbnail-view-subscribe-black on-channel-icon' onclick='subscribeDevice("+channelid+")'>Subscribe</a>";
		if (document.getElementById("floatingResponseDivInner"))
			document.getElementById("floatingResponseDivInner").innerHTML="<b>You have been unsubscribed from <a href='MediaGuide.do?showChannelDetailsFor="+channelid+"'>this Channel</a>.<br/>To subscribe again <a href='#' onclick=\"showSubscribeChannel("+channelid+");\"'>click here!</a></b> &nbsp;&nbsp;&nbsp;&nbsp;" ;
		if (document.getElementById("floatingResponseDiv"))	{
			document.getElementById("floatingResponseDiv").style.display="";
			setTimeout("hideFloatingResponseDiv()",20000); 
		}
	}
}

function subscribeChannel(channelid){
	var path='MediaGuide.do?subscribeChannel=' + channelid;
	var myAjax = new Ajax.Request(
		path, {
			method: 'post',
			onComplete: reloadPage
		});
}

function modifyChannelChanges(action,channelid){
	if(action == "subscribe") {
		document.getElementById("subscribe"+channelid).innerHTML ="<a href='#' class='thumbnail-view-unsubscribe-black on-channel-icon' onclick='unsubscribeChannel("+channelid+")'>Unsubscribe</a>";
		changeEmailSettings(channelid,1);
		document.getElementById("floatingResponseDivInner").innerHTML="<b>You have been subscribed to <a href='MediaGuide.do?showChannelDetailsFor="+channelid+"'>this Channel</a>.<br/><input type='checkbox' id='chk"+channelid+"' name='channelEmailNotification' checked onclick=\"changeChannelNotification('" + channelid + "');\"/> Notify me when videos for this channel are downloaded <br/>&nbsp;&nbsp;To Unsubscribe <a href='#' onclick=\"unsubscribeChannel("+channelid+");\"'>click here!</a></b> &nbsp;&nbsp;&nbsp;&nbsp;" ;
		document.getElementById("floatingResponseDiv").style.display="";
		setTimeout("hideFloatingResponseDiv()",20000);
	} else {
		document.getElementById("subscribe"+channelid).innerHTML ="<a href='#' class='thumbnail-view-subscribe-black on-channel-icon' onclick='showSubscribeChannel("+channelid+")'>Subscribe</a>";
		document.getElementById("floatingResponseDivInner").innerHTML="<b>You have been unsubscribed from <a href='MediaGuide.do?showChannelDetailsFor="+channelid+"'>this Channel</a>.<br/>To subscribe again <a href='#' onclick=\"showSubscribeChannel("+channelid+");\"'>click here!</a></b> &nbsp;&nbsp;&nbsp;&nbsp;" ;
		document.getElementById("floatingResponseDiv").style.display="";
		setTimeout("hideFloatingResponseDiv()",20000); 
	}
}

function showSubscribeChannel(channelid){
	var path='MediaGuide.do?subscribeChannel=' + channelid;
	var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: function(){modifyChannelChanges("subscribe",channelid);}
		});
}

function showSubscribeChannelFromDetails(channelid) {
	var path='MediaGuide.do?subscribeChannel=' + channelid;
	var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: function(){modifyChannelChangesFromDetails("subscribe",channelid);}
		});
}

function modifyChannelChangesFromDetails(action,channelid){
	if(action == "subscribe") {
		document.getElementById("subscribe"+channelid).innerHTML ="<a href='#' class='thumbnail-view-unsubscribe' onclick='unsubscribeChannelFromDetails("+channelid+")'>Unsubscribe</a>";
		changeEmailSettings(channelid,1);
		document.getElementById("floatingResponseDivInner").innerHTML="<b>You have been subscribed to <a href='MediaGuide.do?showChannelDetailsFor="+channelid+"'>this Channel</a>.<br/><input type='checkbox' id='chk"+channelid+"' name='channelEmailNotification' checked onclick=\"changeChannelNotification('" + channelid + "');\"/> Notify me when videos for this channel are downloaded <br/>&nbsp;&nbsp;To Unsubscribe <a href='#' onclick=\"unsubscribeChannelFromDetails("+channelid+");\"'>click here!</a></b> &nbsp;&nbsp;&nbsp;&nbsp;" ;
		document.getElementById("floatingResponseDiv").style.display="";
		setTimeout("hideFloatingResponseDiv()",20000);
	} else {
		document.getElementById("subscribe"+channelid).innerHTML ="<a href='#' class='thumbnail-view-subscribe' onclick='showSubscribeChannelFromDetails("+channelid+")'>Subscribe</a>";
		document.getElementById("floatingResponseDivInner").innerHTML="<b>You have been unsubscribed from <a href='MediaGuide.do?showChannelDetailsFor="+channelid+"'>this Channel</a>.<br/>To subscribe again <a href='#' onclick=\"showSubscribeChannelFromDetails("+channelid+");\"'>click here!</a></b> &nbsp;&nbsp;&nbsp;&nbsp;" ;
		document.getElementById("floatingResponseDiv").style.display="";
		setTimeout("hideFloatingResponseDiv()",20000); 
	}
}

function changeChannelNotification(channelid){
	checkbox = document.getElementById("chk" + channelid);
	if(checkbox.checked){
		changeEmailSettings(channelid,1);
	} else {
		changeEmailSettings(channelid,0)
	}
}

function cancelSubscribeChannel(channelid){
	document.getElementById("firstLayerChannel"+channelid).style.display = "";
}

function unsubscribeChannel(channelid){
	var path='MediaGuide.do?unsubscribeChannel=' + channelid;
	var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: function(){modifyChannelChanges("unsubscribe",channelid);}
		});
}

function unsubscribeChannelFromDetails(channelid){
	var path='MediaGuide.do?unsubscribeChannel=' + channelid;
	var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: function(){modifyChannelChangesFromDetails("unsubscribe",channelid);}
		});
}

function reloadPage(){
	window.location.reload();
}

function updateVideoPercent(deviceId)
{
	updateVideoPercentRetrieveURL('DownloadShell?deviceId='+deviceId);
	setTimeout("updateVideoPercentSendRequest("+deviceId+")",10000)
}

function updateVideoPercentSendRequest(deviceId)
{
	var dat = new Date();
	setTimeout("updateVideoPercentSendRequest("+deviceId+")",60000)
	updateVideoPercentRetrieveURL('DownloadShell?deviceId='+deviceId+'&time='+Date.parse(dat));
}

function updateVideoPercentRetrieveURL(url)
{
	var myAjax = new Ajax.Request(
		url,
		{
			method: 'get',
			onComplete: showResponse
		});
}

function updateCdnDetails(cdnId) {
	var name = document.getElementById("cdnName" + cdnId).value;
	var ftpUrl = document.getElementById("ftpUrl" + cdnId).value;
	var userName = document.getElementById("userName" + cdnId).value;
	var password = document.getElementById("password" + cdnId).value;
	var prefix = document.getElementById("prefix" + cdnId).value;
	var priority = document.getElementById("priority" + cdnId).value;
	var cost = document.getElementById("cost" + cdnId).value;
	var status = document.getElementById("status" + cdnId).value;
	
	var path='prodashboard.do?action=saveCdnDetails&cdnId='+cdnId+'&ftpUrl='+ftpUrl+'&userName=' + userName + '&password=' + password + '&prefix=' + prefix + '&priority=' + priority + '&cost=' + cost + '&status=' + status + '&name=' + name;
	var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: function(){alert("Update Successful");}
		});
}
function updateOriginCdnDetails(cdnId) {
	var name = document.getElementById("cdnName" + cdnId).value;
	var ftpUrl = document.getElementById("ftpUrl" + cdnId).value;
	var userName = document.getElementById("userName" + cdnId).value;
	var password = document.getElementById("password" + cdnId).value;
	var prefix = document.getElementById("prefix" + cdnId).value;
	var limitingDataRate = document.getElementById("limitingDataRate" + cdnId).value;
	var status = document.getElementById("status" + cdnId).value;
	var cost = document.getElementById("cost" + cdnId).value;
	var priority = document.getElementById("priority" + cdnId).value;
	
	var path='prodashboard.do?action=saveCdnDetails&cdnId='+cdnId+'&ftpUrl='+ftpUrl+'&userName=' + userName + '&password=' + password + '&prefix=' + prefix + '&priority=' + priority + '&cost=' + cost + '&limitingDataRate=' + limitingDataRate + '&status=' + status + '&name=' + name;
	var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: function(){alert("Update Successful");}
		});
}


function showResponse(originalRequest)	{
	var arraytext=originalRequest.responseText.substring(1,originalRequest.responseText.length-1);
	var arr=arraytext.split(",");
	for(var n in arr) {
		var objArray = new Array(2);
		s=new String(arr[n]);
		objArray=s.split("=");
		try {
			var db=document.getElementsByName("av"+objArray[0].replace(/^\s+|\s+$/, ''));
			if(db.length>0) {
				for(var i=0;i<db.length;i++) { 
					if(objArray[1].replace(/^\s+|\s+$/, '')<0) {
						var timer = document.getElementsByName("timer"+objArray[0].replace(/^\s+|\s+$/, ''));
						for (var j=0;j<timer.length;j++) {
							timer[j].innerHTML = "queued";
						}
					} else if(objArray[1].replace(/^\s+|\s+$/, '')<100) {
						getTimerHtml(objArray[1].replace(/^\s+|\s+$/, ''),objArray[0].replace(/^\s+|\s+$/, '') );
					}
					if (!(db[i].innerHTML == 0) && (objArray[1].replace(/^\s+|\s+$/, '')==100)) {
						//reloadPage();
					}
				}
			}

			var vd=document.getElementsByName("vd"+objArray[0].replace(/^\s+|\s+$/, ''));

			if(vd.length>0) {
				for(var i=0;i<vd.length;i++) { 
					if(objArray[1].replace(/^\s+|\s+$/, '')<0) {
						var timer = document.getElementById("timerVd"+objArray[0].replace(/^\s+|\s+$/, ''));
						for (var j=0;j<timer.length;j++) {
							timer[j].innerHTML = "queued";
						}
					} else if(objArray[1].replace(/^\s+|\s+$/, '')<100) {
						getTimerHtml(objArray[1].replace(/^\s+|\s+$/, ''),objArray[0].replace(/^\s+|\s+$/, '') );
					}
					if(objArray[1].replace(/^\s+|\s+$/, '')==100) {
						//reloadPage();
					}
				}
			}
		}
		catch(E) {}
	}
}

function getTimerHtml(percentage, objid)
{
	var sizeInMb = document.getElementById("sizeOf" + objid).innerHTML;
	var speed = 500;
	var timeLeft = Math.floor(sizeInMb * 1024 * (100 - percentage) / (100*speed)) ;
	var av = document.getElementsByName("av"+ objid);
	if (av.length>0) {
		if (av[0].innerHTML == 0) {
				UpdateTimer(objid, timeLeft);
		}
		for (var i=0;i<av.length;i++) {
			av[i].innerHTML = timeLeft;
		}
	}
}

function UpdateTimer(objid, timeLeft) {
	var av = document.getElementsByName("av"+ objid);
	if (av.length>0) {
		for (var i=0;i<av.length;i++) {
			if (timeLeft) {
				av[i].innerHTML = timeLeft;
			}
			av[i].innerHTML = av[i].innerHTML - 1;
			var timer = document.getElementsByName("timer"+ objid);
			if (timer.length>0) {
				for (var j=0;j<timer.length;j++) {
					if (Math.floor(av[i].innerHTML / 60) < 60) {
						timer[j].innerHTML = Math.floor(av[i].innerHTML / 60) + ":" + av[i].innerHTML % 60;
					} else {
						timer[j].innerHTML = Math.floor(Math.floor(av[i].innerHTML / 60)/60) + ":" + Math.floor(av[i].innerHTML / 60) % 60 + ":" + av[i].innerHTML % 60;
					}
					if (av[i].innerHTML <= 120 ) {
						timer[j].innerHTML = "< 02:00"
					}
				}
			}
			var timerVd=document.getElementById("timerVd"+ objid);
			if (timerVd) {
				if (timerVd.length>0) {
					for (var j=0;j<timerVd.length;j++) {
						timerVd[j].innerHTML = Math.floor(av[i].innerHTML / 60) + ":" + av[i].innerHTML % 60;
						if (av[i].innerHTML <= 120 ) {
							timerVd[j].innerHTML = "< 02:00"
						}
					}
				}
			}
		}
		if (av[0].innerHTML > 120 ) {
				setTimeout("UpdateTimer(" + objid + ")", 1000);
		}
	}
}

function getSpanPercentHtml(percentage) {
	return percentage + "%";
}

function OpenUrl(url) {
	window.open(url, 'mediaWindow', 'height=600,width=670' );
	return false;
}

function updateOnclick(obj, replaceWith) {
	var onclickVal = obj.getAttribute("onclick").toString();
	if(onclickVal.match(/\{\s*(.*\s*)\s*\}/)) {
		// IE will match this regexp
		onclickVal = onclickVal.match(/\{\s*(.*\s*)\s*\}/)[1];
		onclickVal = replaceWith; // or whatever you need here
		obj.onclick = new Function(onclickVal);
	}
	else {
		// Works with all non-IE browsers tested so far
		obj.setAttribute("onclick", replaceWith); // or whatever you need here
	}
}

function updateOnclick(obj, replaceWith) {
	var onclickVal = obj.getAttribute("onclick").toString();
	if(onclickVal.match(/\{\s*(.*\s*)\s*\}/)) {
		// IE will match this regexp
		onclickVal = onclickVal.match(/\{\s*(.*\s*)\s*\}/)[1];
		onclickVal = replaceWith; // or whatever you need here
		obj.onclick = new Function(onclickVal);
	}
	else {
		// Works with all non-IE browsers tested so far
		obj.setAttribute("onclick", replaceWith); // or whatever you need here
	}
}

function moveVideoToChannel(videoid, channelid) {
	var answer = confirm("Are you sure want to move this video");
	if(answer) {
		document.getElementById('errormsgMoveVideo').innerHTML="<img src='images/ajaxloading.gif'/>";
		if (channelid==0) {
			window.location.replace("PublishChannel.do?action=showIndVideoDetail&videoid="+videoid+"&movevideo=true");
		} else {
			window.location.replace("PublishChannel.do?action=showVideoDetail&videoid=" + videoid+ "&channelid=" + channelid+"&movevideo=true");
		}
	}
}

function sendValidationEmailInput() {
	var vemail = document.getElementById("valEmailAddress").value;
	var path='Logout.do?sendValidationEmail=' + vemail;
	var myAjax = new Ajax.Request(
		path,
		{
			method: 'post',
			onComplete: showResposneAfterSendingValidationEmail
		});
}

function showResposneAfterSendingValidationEmail(originalRequest){
	var response=originalRequest.responseText;
	if (response=="success"){
		document.getElementById("loginFormDiv").innerHTML = "<font color=red>A validation email is sent to your address : " + document.getElementById("valEmailAddress").value + ". Please check your email and validate. Click <a href='MyMedia.do'>here</a> to continue. </font>";
	} else {
		document.getElementById("loginFormDiv").innerHTML = "<font color=red>Error sending email, please try again with a registerd email id. Click <a href='MyMedia.do'>here</a> to continue.</font>";
	}
}

function dontBotherAlert(){
	var alertCheckBox = document.getElementById("alertCheckBox");
	if (alertCheckBox.checked == true) {
		document.cookie = "dont_bother=yes";
	}
}

function get_cookie ( cookie_name ){
	var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );
	if ( results )
		return ( unescape ( results[1] ) );
	else
		return null;
}

function onPlayViaFaceBook(mediaid) {
	var sessionKey = document.getElementById("fbSessionKey").value;
	var url = 'FaceBook.do?action=playvideo&mediaid='+mediaid+'&deviceid='+device+ '&sessionKey='+sessionKey;
	var param = 'height='+screen.height+',width='+screen.width + ',scrollbars=1';
	window.open(url, 'PlayerWindow', param);
}

function showRightPanelForVideo(avatarid){
	document.getElementById("rightPanelVideoImageHover" + avatarid).style.display="none";
	document.getElementById("rightPanelVideoImage" + avatarid).style.display="";
}

function showRightPanelHoverForVideo(avatarid){
	document.getElementById("rightPanelVideoImage" + avatarid).style.display="none";
	document.getElementById("rightPanelVideoImageHover" + avatarid).style.display="";
}

function updateVideoStatus(device) {
	var url = 'DownloadShell?deviceId='+device;
	var myAjax = new Ajax.Request(url, {method: 'get', onComplete: updateVideoStatusResponse});
}

function updateVideoStatusResponse(response) {
	var arraytext=response.responseText.substring(1,response.responseText.length-1);
	var arr=arraytext.split(",");
	for(var n in arr) {
		var objArray = new Array(2);
		s=new String(arr[n]);
		objArray=s.split("=");
		try {
			var id = objArray[0].replace(/^\s+|\s+$/, '');
			var timer=document.getElementById("timer"+id);
			var timerVd=document.getElementById("timerVd"+id);
			var hoverPlay=document.getElementById("hoverPlay"+id);
	
			if(hoverPlay) {
				if (objArray[1].replace(/^\s+|\s+$/, '')<100) {
					hoverPlay.innerHTML = "<img src='images/videoloading.gif'/>"
				} else if (objArray[1].replace(/^\s+|\s+$/, '')==100) {
					hoverPlay.innerHTML = "<a class='thumbnail-view-play' href='javascript:void(0)' onclick='onPlay("+id+")'>Play</a>"
					timer.innerHTML = "<a class='thumbnail-view-play' href='javascript:void(0)' onclick='onPlay("+id+")'>Play</a>"
				}
			}
			if (timerVd) {	
				if (objArray[1].replace(/^\s+|\s+$/, '')<100) {
					timerVd.innerHTML = "<img src='images/videoloading.gif'/>"
				} else if (objArray[1].replace(/^\s+|\s+$/, '')==100) {
					timerVd.innerHTML = "<a class='thumbnail-view-play' href='javascript:void(0)' onclick='onPlay("+id+")'>Play</a>"
				}
			}
		}
		catch(E) {}
	}
	updateVideoPercent(device);
}


function showUploadVideoPercent(mediaid){
	updateUploadVideoPercentRetrieveURL('PublishChannel.do?getUploadStatus='+mediaid);
	setTimeout("updateUploadVideoPercentSendRequest("+mediaid+")",10000)
}

function updateUploadVideoPercentSendRequest(mediaid) {
	var dat = new Date();
	setTimeout("updateUploadVideoPercentSendRequest("+mediaid+")",60000)
	updateUploadVideoPercentRetrieveURL('PublishChannel.do?getUploadStatus='+mediaid+'&time='+Date.parse(dat));
}

function updateUploadVideoPercentRetrieveURL(url) {
	var myAjax = new Ajax.Request(
		url,
		{
			method: 'get',
			onComplete: showUploadPercentResponse
		});
}

function showUploadPercentResponse(originalRequest)	{
	var arraytext=originalRequest.responseText;
	var arr=arraytext.split(",");
	var status = arr[0].substring(1,arr[0].length-1);
	var uploadPercent = arr[1].substring(1,arr[1].length-1);
	var db=document.getElementById("uploadStatus");
	if(db){
		if(status=="23"){
			db.innerHTML="Uploading.. "+uploadPercent+"%";
		} else if(status=="24"){
			db.innerHTML="Uploaded";
		} else if(status=="25"){
			db.innerHTML="Published";
		} 
	}
}

function checkAutoPublish() {
	
	var db = document.getElementsByName("checkautopublish");
	var checked=0;
    for(var i=0;i<db.length;i++) {
    	if(db[i].checked)
			checked++;
    }
    if (checked > 4) {
    	alert("Error : You can set maximum of only 4 Videos for auto-publish.");
	} else {
		document.forms[0].submit();
	}
}
function showInstaller(mediaid) {
        var installerDiv = document.getElementById("installerDiv"+mediaid);
        installerDiv.style.visibility = "visible";
}

HoverMenu = function (tab,hover) {
                                                var hoverMenu = this;
                                                this.tab = document.getElementById(tab);
                                                this.hover = document.getElementById(hover);
                                                this.isVisible = false;
                                                this.makeMenuInvisible = function() {
                                                        if(this.isVisible==false){
                                                                this.hover.style.display="none";
                                                        }
                                                }
                                                this.hoverVisible = function() {
                                                        hoverMenu.isVisible = true;
                                                        hoverMenu.hover.style.display="block";
                                                }
                                                this.hoverInvisible = function() {
                                                        hoverMenu.isVisible = false;
                                                        setTimeout(function() {
                                                                        if(hoverMenu.isVisible==false){
                                                                                hoverMenu.hover.style.display="none";
                                                                        }
                                                                },300);
                                                }

                                                this.tab.onmouseout = this.hoverInvisible;
                                                this.hover.onmouseover = this.hoverVisible;
                                                this.tab.onmouseover = this.hoverVisible;
                                                this.hover.onmouseout = this.hoverInvisible;

                                        }
                                        
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}
                                        
                                      