/* handle of a popup window, only one popup is allowed even if page has n melonizing pieces */
var mywin;
var device = 0;
/* shows a particular video of a slideshow */
function showLayer(video, lastvideo){
window.document.getElementById("video"+lastvideo).style.visibility = "hidden";
window.document.getElementById("video"+video).style.visibility = "visible";
window.document.getElementById("video"+video).style.width = 200;
}

/* loads a channel or a video image depending on visibility flag status */
function loadImage(img_url, img_visible){
	 if(img_url!=null && img_visible!=null && img_visible == "true"){
	 //window.resizeTo(200,225);
	 img = new Image();
	 img.src = img_url;
	try{
	 this.frameElement.height = img.height+40;
	 if(img.width > 200){
		 this.frameElement.width = img.width;
	 }
	}catch(err){
		// alert(err);
	}
     document.getElementById("mm_image").innerHTML = "<img align='center' src='" +img_url+"'>";
     }
}

/* views a slideshow in a popup */
function view(){

/* create a popup with a div tag named 'popup_win' , relevant response from the opener page is extracted and is writted inside the popup*/
mywin = window.open("","Videos",'width=300,height=175,resizeable=0,menubar=0,toolbar=0');
mywin.document.write("<head><title>MediaMelon</title></head><div id='popup_win' name='popup_win'> " +" Initialize "+ "</div>  <script type='text/javascript' src='scripts/mediamelon_util.js'> </script> <link href='css/styles/page.css' type='text/css' rel='stylesheet'>");
mywin.document.close();

/* if opener page contains a div tag with video0 - implying first video */
if(document.getElementById("video0") != null){
/* write all the videos enclosed in channel_media div tag in the popup and make only the video0 div tag visible , making first video visible */
mywin.document.getElementById("popup_win").innerHTML =document.getElementById("channel_media").innerHTML;
mywin.document.getElementById("video0").style.visibility = "visible";
mywin.document.getElementById("video0").style.width = "200";

}else if(document.getElementById("channel_subscribe") != null){
/* if opener page contains a requst for subscribing a channel/video or a private channel response*/
mywin.document.getElementById("popup_win").innerHTML = "<img align='center' src='images/logo-hollow-small.gif'> <BR/><BR/>" + document.getElementById("channel_subscribe").innerHTML;

}else{
/* no videos available */
mywin.document.getElementById("popup_win").innerHTML = "<img align='center' src='images/logo-hollow-small.gif'> <BR/><BR/> No videos available for this subscription";
}
mywin.focus();
}

/* function shows a cached login page */
function Login() {
	var url = "activelogin.jsp";
	window.open(url,'login','width=300,height=300,resizeable=0,menubar=0,toolbar=0');
}
/* reloads all mm_frame containing melonizing javascript code , during login/logout*/
function reloadFrames() {

		//alert("reload frames")
		var frames = window.parent.frames;
		//alert(frames.length);
		for (var i=0; i<frames.length; i++)
		{
			try	{
				if (frames[i].name == "mm_frame")
				{
					//alert("reload frame");
					frames[i].location.reload();
				}
			}
			catch (E) {
		//alert(E);
			}
		}
		try {
		//alert("reload frame via parent");
		window.parent.location.reload(true);
	} catch (E) {
		//alert(E);

		}
}

/* reloads all mm_frame containing melonizing javascript code , during any action in the popup window
e,g deleting a video, saving a video etc., Need to get parent's handle in this case*/
function reloadParentFrames() {

		//alert("reload frames in reloadparentframes")
		var frames = opener.parent.frames;
		for (var i=0; i<frames.length; i++)
		{
			try {
				if (frames[i].name == "mm_frame") {
					//alert("reload frame");
					frames[i].location.reload();
				}
			} catch (E) {
			//alert("Exception " + E);
			}
		}

	try
	{
		//alert("reload frame via parent");
		opener.parent.location.reload(true);
	} catch (E) {
		//alert("Exception "+E);

		}
}

function Register() {
	var url = "Register.jsp?mediaId="+mediaId;
	window.open(url, fullscreen=1);
}

function onPlay(avatarid, player)
{
	var url;
	if (player == 0) {
		url = "MediaGuide.do?showVideoDetailsFor="+avatarid;
		window.location=url;
	} else {
		var url = 'Play.do?q='+avatarid;
		if (device > 0) {
			url = url+'&device='+device;
		}	
		var param = 'height='+screen.availHeight+',width='+screen.availWidth + ',scrollbars=1';
		var w =	window.open(url, 'PlayerWindow', param);
		w.focus();
	}
}


var req;

function realtime()
{
	retrieveURL('DownloadShell?deviceId='+deviceId);
	setTimeout("sendRequest()",20000)
}


function sendRequest()
{
	var dat = new Date();
	setTimeout("sendRequest()",20000)
	retrieveURL('DownloadShell?deviceId='+deviceId+'&time='+Date.parse(dat));
}

function retrieveURL(url,nameOfFormToPost)
{
	//get the (form based) params to push up as part of the get request
	//url=url+getFormAsString(nameOfFormToPost);
	//Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
		req = new XMLHttpRequest();
		req.onreadystatechange = processStateChange;
		try {
			req.open("GET", url, true); //was get
		} catch (e) {
			alert("Problem Communicating with Server\n"+e);
		}
		req.send(null);
	} else if (window.ActiveXObject) { // IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processStateChange;
			req.open("GET", url, true);
			req.send();
		}
	}
}

/*
   * Set as the callback method for when XmlHttpRequest State Changes
   * used by retrieveUrl
  */
function processStateChange() {
	if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response
			if(req.responseText.length>0)
			{
				var responseArray=req.responseText.substring(1,req.responseText.length-1);
		  		var arr= new Array(1000);
		  		arr=responseArray.split(",");

				for(var n in arr)
				{
					var objArray = new Array(2);
					s=new String(arr[n]);
					objArray=s.split("=");
					try {
						var db=document.getElementById("mediamelon"+objArray[0].replace(/^\s+|\s+$/, ''));

						if(db) {

							if(objArray[1].replace(/^\s+|\s+$/, '')<100) {
								document.getElementById("mediamelon"+objArray[0].replace(/^\s+|\s+$/, '')).innerHTML = getDiv(objArray[1].replace(/^\s+|\s+$/, ''));
							}
							else {
								document.getElementById("mediamelon"+objArray[0].replace(/^\s+|\s+$/, '')).innerHTML = "&nbsp;";
								enableButton(objArray[0].replace(/^\s+|\s+$/, ''));
							}
						}
					}
					catch(E) {}
				}
			}
		}
	}
}

function getDiv(percentage)
{
	return "<div class='smallroundedmodule mediumquota1' style='height:12px' id='quotameter'><span id='quotausagebar'><span class='first' style='width:"+percentage+"%;'><font class='mmX-itemValue'></font></span><span class='last'><font class='mmX-itemValue'>"+percentage+"% Complete</font></span></span></div>";
}

function enableButton(obj)
{
	if(isPrimaryDevice(deviceId)) {
	try
		{
			var play = document.getElementsByName("play"+mediaId);
			play.disabled = false;
		}
		catch(e){}
	}
}

function requestMedia(mediaId)
{
	var dat = new Date();
//	var url = "FindProgramInfo.do?submit=true&id="+mediaId+"&time="+Date.parse(dat);
		var url = "ActiveLink?RequestButton=Request&mediaId="+mediaId+"&time="+Date.parse(dat);

	//get the (form based) params to push up as part of the get request
	//url=url+getFormAsString(nameOfFormToPost);
	//Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
		req = new XMLHttpRequest();
		req.onreadystatechange = processSubRequest;
		try {
			req.open("GET", url, true); //was get
		} catch (e) {
			alert("Problem Communicating with Server\n"+e);
		}
		req.send(null);
	} else if (window.ActiveXObject) { // IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processSubRequest;
			req.open("GET", url, true);
			req.send();
		}
	}
}


function processRequest()
{
	if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response
			if(req.responseText.length>0)
			{
				self.location.reload(true);
			}
		}
	}
}

function checkDevice()
{
	if(!isPrimaryDevice(deviceId)) {
		try
		{
			var play = document.getElementById("mediamelon_play"+mediaId);
			play.disabled = true;
		}
		catch(e){}
	}
}

function isPrimaryDevice(priId) {
    var curId = -1;

    //If pri device is not yet established, no need for this check ??
    if(priId == -1)
    	return false;

    //check if client script is loaded
    if(window.getLocalDeviceId)
		curId = getLocalDeviceId();

    if(curId == priId)
		return true;

    return false;
}


/* makes a request subscribing a channel or a video*/
function subscribeChannel(subid)
{
	//alert("Subscribe "+subid);
	var dat = new Date();
	var url = "ActiveChannel?SubscribeButton=Subscribe&sid="+subid+"&time="+Date.parse(dat);

	//get the (form based) params to push up as part of the get request
	//url=url+getFormAsString(nameOfFormToPost);
	//Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
		req = new XMLHttpRequest();
		req.onreadystatechange = processSubRequest;
		try {
			req.open("GET", url, true); //was get
		} catch (e) {
			alert("Problem Communicating with Server\n"+e);
		}
		req.send(null);
	} else if (window.ActiveXObject) { // IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processSubRequest;
			req.open("GET", url, true);
			req.send();
		}
	}
}

/* response for the subscription request */
function processSubRequest()
{
	if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response
			if(req.responseText.length>0)
			{
				/* if subscription response recieved , extract data and update the popup*/
				var data = req.responseText;
				//alert("data in subreq is "+data);


				var sIndex = data.indexOf("<mesg>");
				var eIndex = data.indexOf("</mesg>");
				//alert(sIndex+"  "+eIndex);
				if(sIndex > 0){
					// data contains videos
				var data1 = data.substring(sIndex, eIndex);
				// alert(data1);
				mywin = window.open("","Videos",'width=300,height=300,resizeable=0,menubar=0,toolbar=0');
				mywin.document.write("<head><title>MediaMelon</title></head><div id='popup_win' name='popup_win'> <img align='center' src='images/logo-hollow-small.gif'> <BR/><BR/>" +data1 +"</mesg>"+ "</div>  <script type='text/javascript' src='scripts/mediamelon_util.js'> </script> <link href='css/styles/page.css' type='text/css' rel='stylesheet'>");
				mywin.document.close();

				//document.getElementById("popup_win").innerHTML =  data1 + "</mesg>";

				//document.getElementById("video0").style.visibility = "visible";
				//document.getElementById("video0").style.width = 200;
				//alert(data);
				//self.location.reload(true);
				}else{
					// data contains a private video/channel message
				reloadFrames();
					/* alert("error "+req.responseText);
					document.getElementById("popup_win").innerHTML = "<img align='center' src='images/logo-hollow-small.gif'>  <BR/>" + req.responseText;
					*/
				}

			}
		}
	}
}


function processSubscribe()
{
	if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response
			if(req.responseText.length>0)
			{
				self.location.reload(true);
			}
		}
	}
}

function shareChannel(id) { window.open("shareChannel.do?id=" + id,'Share Channel','height=450,width=700'); }
function shareProgram(id) { window.open('shareProgram.do?id='+id,'MediaMelon','height=450,width=700'); }


function deleteSubMedia(channelid, objid) {
// alert("delete video status");
// alert("channel  id "+ channelid +  "objid "+ objid);
// customRequest("New-WatchSubscribed.do?id=" + objid+"&ChannelId="+channelid,"deleteSubMediaResponse");
customRequest("ActiveChannel?id=" + objid+"&sid="+channelid+"&status=delete");
}

function saveMedia(channelid, objid,saveVideoStatus) {
//alert("save video status");
// alert("channel  id "+ channelid +  "objid "+ objid);
customRequest("ActiveLink?mediaId=" + objid+"&sid="+channelid+"&autoDelete="+saveVideoStatus+"&status=save");
// reloadParentFrames();
// window.close();
}

function deleteMedia(channelid, objid) {
// alert("delete video status");
// alert("channel  id "+ channelid +  "objid "+ objid);
// customRequest("New-WatchSubscribed.do?id=" + objid+"&ChannelId="+channelid,"deleteSubMediaResponse");
customRequest("ActiveLink?mediaId=" + objid+"&sid="+channelid+"&status=delete");
}

/* response for logout request*/
function logoutRequest(){

if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response
			if(req.responseText.length>0)
			{
				reloadFrames();
				try{
				window.close();
				}catch(E){
					// alert(E);
				}

				try{
					self.close();
				}catch(E){
					// alert(E);
				}
			}
		}
	}

}

/* response for delete/save requests */
function processMultiRequest(){
if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response
			if(req.responseText.length>0)
			{

				// alert(req.responseText);

				reloadParentFrames();
				try{
				window.close();
				}catch(E){
					// alert(E);
				}

				try{
					self.close();
				}catch(E){
					// alert(E);
				}
				//close();

				// var data = req.responseText;

				//mywin.close();

				/*
				if(req.responseText.indexOf("video0") > 0){


					alert("video 0 is not null");

				var sIndex = data.indexOf("<ch_media>");
				var eIndex = data.indexOf("</ch_media>");

		*/

/* write all the videos enclosed in channel_media div tag in the popup and make only the video0 div tag visible , making first video visible */
// alert(sIndex +"  "+eIndex);


/*
mywin = window.open("","Videos",'width=260,height=300,resizeable=0,menubar=0,toolbar=0');
mywin.document.write("<head><title>MediaMelon</title></head><div id='popup_win' name='popup_win'> " +" Initialize "+ "</div>  <script type='text/javascript' src='scripts/mediamelon_util.js'> </script> <link href='css/styles/page.css' type='text/css' rel='stylesheet'>");
mywin.document.close();

mywin.document.getElementById("popup_win").innerHTML = data.substring(sIndex, eIndex) +"</ch_media>";
alert(data.substring(sIndex, eIndex));

mywin.document.getElementById("video0").style.visibility = "visible";
mywin.document.getElementById("video0").style.width = "200";
*/
//}
				/* reload all parent frames, open any opened popup,
				currently no support is there for changing the popup state so just closing the popup*/

			}
		}
	}

}



function logout(){
/* close any open popup */
if(mywin!=null){
	mywin.close();
}

	ajaxurl = "Logout.do?al=2";
	var dat = new Date();
	var url = ajaxurl + "&time="+Date.parse(dat);


	//get the (form based) params to push up as part of the get request
	//url=url+getFormAsString(nameOfFormToPost);
	//Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers

		req = new XMLHttpRequest();

		req.onreadystatechange = logoutRequest;

		try {
			req.open("GET", url, true); //was get
		} catch (e) {
			alert("Problem Communicating with Server\n"+e);
		}
		req.send(null);
	} else if (window.ActiveXObject) { // IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			try{
			req.onreadystatechange = logoutRequest;
		}catch(e){
		alert(e);
		}
			req.open("GET", url, true);
			req.send();

		}
	}

}

function customRequest(ajaxurl)
{
	var dat = new Date();
	var url = ajaxurl + "&time="+Date.parse(dat);


	//get the (form based) params to push up as part of the get request
	//url=url+getFormAsString(nameOfFormToPost);
	//Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers

		req = new XMLHttpRequest();

		req.onreadystatechange = processMultiRequest;

		try {
			req.open("GET", url, true); //was get
		} catch (e) {
			alert("Problem Communicating with Server\n"+e);
		}
		req.send(null);
	} else if (window.ActiveXObject) { // IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			try{
			req.onreadystatechange = processMultiRequest;
		}catch(e){
		alert(e);
		}
			req.open("GET", url, true);
			req.send();

		}
	}
}

function writeStatus(){
	if(deviceId == getLocalDeviceId()){
		document.write("<IMG src='images/melonize/green.gif' alt='Your device is online !' title='Your device is online !' />");
	}else{
		document.write("<IMG src='images/melonize/red.gif' alt='Your device is offline !' title='Your device is offline !'/>");
	}
}

function closePopup(){
	try{
	if(mywin!=null){
		mywin.close();
	}
	}catch(E){
	}
}