/* Javascript for repstars.tv */

var pl = new Array(); // array to store video playlist
var plbrowse = 5; // default number of thumbs to load
var firstplbrowse = 10; // number of thumbs to load playlist on first call
var plcurrentpage = 1; // current page of playlist
var plnextpage = 1; // next page number of playlist
var plsort = "ra"; // deafult sort for playlist (mv = most viewed, mp = most popular, ra = recently added, al = alphabetical)
var pltotal;
var plcount = 0;
var plwidth = 605; // visible playlist width
var scrollswitch = false; //switch to enable/disable playlist navigation
var currentvideo = 0;
var plopp = "";
var plcat = "";
var plvideo = "";
var plsearch = "";
var plnetwork = "";
var pluser = "";
var videoplaying = "";
var autoclick = false;

var orgswitch = false;
var contactfocus = false;

var idleTime    	= 600000; // 10 minutes
var promptIdleTime 	= 500; // 1/2 second
var idleTimeOut 	= "";
var promptTimeOut 	= "";
var tvPaused = false;

$(document).ready(function()
{

$("#media_player").each(function() { 
	idleInit(); // Inactivity Timer Init 
});

	
	
$('#homefeature1 a').tooltip({
    track: true,
    showURL: false,
    extraClass: "video",
    showBody: " - "
});
$('#videothumbs a').tooltip({
    track: true,
    showURL: false,
    extraClass: "video",
    showBody: " - "
});
$('#homefeature2 a').tooltip({
    track: true,
    showURL: false,
    extraClass: "video",
    showBody: " - "
});
$('#homefeature3 a').tooltip({
    track: true,
    showURL: true,
    showBody: " - ",
    left: -200
});


$('#morevideolist a').tooltip({
    track: true,
    showURL: false,
    extraClass: "video",
    showBody: " - "
});

$('#morereplist a').tooltip({
    track: true,
    showURL: false,
    extraClass: "video",
    showBody: " - "
});

$('#moreweblist a').tooltip({
    track: true,
    showURL: true,
    showBody: " - ",
    left: -200
});


/************** Browse Scripts ***************/
setBrowseEvents();

// ******************* Org and Lang Selection Scripts Start Here ************************
	$("#myorg").click(function() {
		$("#langlist").hide();
		$("#orglist").load("/orglist", function() { 
			$(this).show(); 
			$("#orglist a.listclose").click(function() { $(this).parent().hide(); }); 
		});
	});
	
	$("#mylang").click(function() {
		$("#orglist").hide();
		$("#langlist").load("/langlist", function() {	
			$(this).show(); 
			$("#langlist a.listclose").click(function() { $(this).parent().hide(); }); 
		});
	});
	
	
	/*$("#mylang").mouseover(function() {
		$("#media_details select").hide();
		$("#langlist").show().mouseover(function() {
			orgswitch = true;
			$("#media_details select").hide();
			$(this).show();
		}).mouseout(function () {
			$(this).hide();
			$("#media_details select").show();
			orgswitch = false;
		});
	}).mouseout(function() {
		setTimeout("if (!orgswitch) { $('#langlist').hide(); $('#media_details select').show(); }",200);
		//$("#langlist").hide();
	});*/
	// ******************* Org and Lang Selection Scripts End Here ************************
	

// *********************Media Playlist Scripts Start Here ******************

	$("#media_playlist #videothumbs").each(function () {
		var querystring = document.location.search;
		querystring = querystring.substring(1);
		searchparams = querystring.split("&");
		for (i=0; i<searchparams.length;i++) {
			var searchname = searchparams[i].substring(0,1);
			searchname = searchname.toUpperCase();
			if (searchname == "O") {
				plopp = searchparams[i].substring(2);
				//alert("opp="+plopp);
			} else if (searchname == "C") {
				plcat = searchparams[i].substring(2);
				//alert("cat="+plcat);
			} else if (searchname == "V") {
				plvideo = searchparams[i].substring(2);
				//alert("video="+plvideo);
			} else if (searchname == "S") {
				plsort = searchparams[i].substring(2);
				//alert("sort="+plsort);
			} else if (searchname == "N") {
				plnetwork = searchparams[i].substring(2);
				//alert("network="+plnetwork);
			} else if (searchname == "U") {
				pluser = searchparams[i].substring(2);
				//alert("user="+pluser);
			}
				
		}
		getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser, true);
		scrollswitch = true;
	});
	$("#media_playlist #nextvideo a").click(function () {
		// alert(plcurrentpage + " --> " + plnextpage); 
		if (scrollswitch) {
			if (plcurrentpage < plnextpage) {
				scrollswitch = false;
				var newleft = $("#media_playlist #videothumbs ul").css("margin-left");
				newleft = newleft.replace(/px/, "");
				newleft -= plwidth; 
				//alert(newleft);
				$("#media_playlist #videothumbs ul").animate({
  					marginLeft: newleft
					}, 1000, function () { scrollswitch = true; });
				plcurrentpage++;
				getVideoThumbs(plcurrentpage + 1, plbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser);
			}
		}
		return false;
	});
	
	$("#media_playlist #prevvideo a").click(function () {
		if (scrollswitch) {
			if (plcurrentpage > 1) {
				scrollswitch = false;
				var newleft = $("#media_playlist #videothumbs ul").css("margin-left");
				newleft = newleft.replace(/px/, "");
				newleft = (newleft* 1) + plwidth;
				//alert(newleft);
				$("#media_playlist #videothumbs ul").animate({
  					marginLeft: newleft
					}, 1000, function () { scrollswitch = true; });
				plcurrentpage--;
			}
		}
		return false;
	});
	
	$("#sortlist a").click(function () {
		if (scrollswitch) {
			var selsort = this.href;
			var hashindex = selsort.indexOf("#");
			selsort = selsort.substring(hashindex+1);
		
			if (plsort != selsort) {
				plsort = selsort;
				pl.length = 0; // clear array
				plcurrentpage = 1; // reset current page back
				plnextpage = 1; // reset next page
				plcount = 0; // reset playlist count
				var currheight = $("#media_playlist #videothumbs ul").height() + "px";
				$("#media_playlist #videothumbs ul").width(plwidth*2).css("margin-left", 0).empty();
				getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser);	
			}
		}		
		return false;
	});
	
	
	$("#videosearch #videotags").keypress(function(e) {
		if (e.which == "13") {
			$("#videosearch a.button").click();
		}
	});
	$("#videosearch a.button").click(function() {
		if (scrollswitch) {
			plsearch = $("#videosearch #videotags").val();		
			if (plsearch != "") {
				pl.length = 0; // clear array
				plcurrentpage = 1; // reset current page back
				plnextpage = 1; // reset next page
				plcount = 0; // reset playlist count
				plopp = ""; // reset browse by opportunity
				plcat = ""; //reset browse by category
				plvideo = ""; //reset video loaded
				plnetwork = ""; //reeset network group
				pluser = ""; //reset user
				$("#media_playlist #videothumbs ul").width(plwidth*2).css("margin-left", 0).empty();
				getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser);	
			}
		}		
		return false;						
	});
	
	/*$("#media_details .searchtag").click(function() {
			var searchtag = $(this).text();
			$("#videosearch #videotags").val(searchtag);
			$("#videosearch button").click();
			return false;
		});*/
	
	$("#media_details .searchtag").click(function() {
		if (scrollswitch) {
			plsearch = $(this).text();			
			$("#all_playlists h1#current span").text(label_pl_current_1 + " '" + plsearch + "'");
			pl.length = 0; // clear array
			plcurrentpage = 1; // reset current page back
			plnextpage = 1; // reset next page
			plcount = 0; // reset playlist count
			plopp = ""; // reset browse by opportunity
			plcat = ""; //reset browse by category
			plvideo = videoplaying; //video currently loaded
			plnetwork = ""; //reeset network group
			pluser = ""; //reser user
			currentvideo = 0;
			//alert("video id="+plvideo);
			$("#media_playlist #videothumbs ul").width(plwidth*2).css("margin-left", 0).empty();
			getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser, true);	
		}		
		return false;						
	});
	
	$("#media_by a").click(function() {
		if (scrollswitch) {
			pluser = $(this).text();	
			$("#all_playlists h1#current span").text(label_pl_current_2 + " '" + pluser + "'");
			pl.length = 0; // clear array
			plcurrentpage = 1; // reset current page back
			plnextpage = 1; // reset next page
			plcount = 0; // reset playlist count
			plopp = ""; // reset browse by opportunity
			plcat = ""; //reset browse by category
			plvideo = ""; //reset video loaded
			plnetwork = ""; //reeset network group
			plsearch = ""; //reser search keywords
			$("#media_playlist #videothumbs ul").width(plwidth*2).css("margin-left", 0).empty();
			getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser, true);	
		}		
		return false;						
	});
	// *********************Media Playlist Scripts End Here ******************
		
	$("#icon_details, #icon_share, #icon_contact, #icon_flag").hover(function(){ bob = $(this).children("img");
																			  newRel = bob.attr("src"); bob.attr("src", bob.attr("rel")); bob.attr("rel",newRel);
																																											
	},function(){	bob = $(this).children("img");
																			  newRel = bob.attr("src"); bob.attr("src", bob.attr("rel")); bob.attr("rel",newRel);
	});
	$("#icon_details").click(function() { $("#media_details input").blur(); $("#media_contact").hide(); $("#media_share").hide(); $("#media_flag").hide(); $("#form_response").hide(); return false; });
	
	$("#icon_share").click(function() { $("#media_details input").blur(); $("#media_contact").hide(); $("#media_share").show(); $("#media_flag").hide(); $("#form_response").hide(); return false; });
	
	$("#icon_contact").click(function() { $("#media_details input").blur(); $("#media_contact").load('/contact?fv_username='+escape(pl[currentvideo][5])+'&fv_video_id='+pl[currentvideo][0]).show(); $("#media_share").hide(); $("#media_flag").hide(); $("#form_response").hide(); return false; });
	
	$("#icon_flag").click(function() { $("#media_details input").blur(); $("#media_contact").hide(); $("#media_share").hide(); $("#media_flag").show();$("#form_response").hide();  return false; });
	
	$("#media_share input, #media_share textarea").focus(function() { this.select(); });
	
	
	
	$("#media_flag form").submit(function() {
		var formaction = $(this).attr("action");
		//alert();
		var contactreason = this.fv_reason.value;
		var contactfcomment = this.fv_comment.value;
		var contactvideo = this.fv_video_id.value;
		
		$.post(formaction,{
  		fv_reason: contactreason,
		fv_comment: contactfcomment,
		fv_video_id: contactvideo
		},function(data){
			$("#media_contact").hide(); $("#media_share").hide(); $("#media_flag").hide();
			$("#form_response").text(data).show();
		 //alert(data);
		 });
		
		contactfocus = false;
		return false;										 
	});
	
});

function setBrowseEvents() {
	$("#catnav ul a, .sortnav a, .pagenav a").click(function() {
		//$("#main").load(this.href,function() { setBrowseEvents(); alert($("#main").html()); });
		$.get(this.href,
  			function(data){
    			//alert("Data Loaded: " + data);
				var mycontentdiv = document.getElementById("content");
				//var mychanneldiv = document.getElementById("channels");
				//alert(mychanneldiv);
				mycontentdiv.innerHTML = data;
				/*if (mycatdiv != null) {
					mycatdiv.innerHTML = data;
				} else if (mychanneldiv != null) {
					mychanneldiv.innerHTML = data;
				}	*/			
				//$("#browse").html(data);
				//alert($("#browse").html());
				setBrowseEvents();
  			}
		);
		return false;
	});	
}


function getVideoThumbs(page, browse, listsort, tags, opp, cat, firstvideo, network, user, firstplay) {
	page = (page == undefined) ? "" : page;
	browse = (browse == undefined) ? "" : browse;
	listsort = (listsort == undefined) ? "" : listsort;
	tags = (tags == undefined) ? "" : tags;
	opp = (opp == undefined) ? "" : opp;
	cat = (cat == undefined) ? "" : cat;
	firstvideo = (firstvideo == undefined) ? "" : firstvideo;
	network = (network == undefined) ? "" : network;
	user = (user == undefined) ? "" : user;
	firstplay = (firstplay == undefined) ? false : firstplay;
	
	$.ajax({
  		type: "POST",
  		url: "/xml_media",
  		dataType: "xml",
  		data: {
  			p: page,
			b: browse,
			s: listsort,
			t: tags,
			o: opp,
			c: cat,
			v: firstvideo,
			n: network,
			u: user
		},
		beforeSend: function(xhr) {
    		xhr.setRequestHeader( "Connection", "close" );
		},
  		success: function(xml) {
    		pltotal = $("allmedia > total",xml).text();
			if (pltotal > plcount) {
				$("allmedia > media",xml).each(function() {						
					tempmediaid = $("id", this).text();
					tempfilename = $("filename", this).text();
					temptype = $("type", this).text();
					temptitle = $("title", this).text();
					tempdescription = $("description", this).text();
					tempuser = $("user", this).text();
					templength = $("length", this).text();
					tempviews = $("views", this).text();
					tempthumb = $("thumbnailimage", this).text();
					tempkeywords = $("keywords", this).text();
					tempwebimage = $("websiteimage", this).text();
					tempweburl = $("websiteurl", this).text();
					tempnetwork = $("networkid", this).text();
					pl.push([tempmediaid, tempfilename, temptype, temptitle, tempdescription, tempuser, templength, tempviews, tempthumb, tempkeywords, tempwebimage, tempweburl, tempnetwork]);
				});
				createThumbs(firstplay);
			}
  		}
	});

}

function createThumbs(firstplay) {
	var listHTML = "";
	for (i=plcount;i<pl.length;i++) {
		if ((firstplay) && (plcount == 0)) { 
			videoplaying = pl[i][0]; 
			$("#media_share #fv_embed").val('<embed src="http://' + document.location.host + '/swf" width="400" height="245" allowfullscreen="true" wmode="opaque" flashvars="&displayheight=225&file=http://media.repstars.com/enc/flv/' + pl[i][1] + '&height=245&image=http://media.repstars.com/enc/lg/' + pl[i][8] + '&width=400&screencolor=0x000000"></embed>');
			$("#media_share #fv_link").val("http://" + document.location.host + "/home?V=" + pl[i][0] + "&N=" + pl[i][12]);
			if ((pl[i][10] != "") && (pl[i][11] != "")) {
				$("#media_website").html('<a href="http://' + pl[i][11] + '" target="_blank"><img src="' + pl[i][10] + '" border="0" /></a>' + label_moreinfo_1);
			} else {
				$("#media_website").html(label_moreinfo_2);
			}
		}
		listHTML += ((firstplay) && (plcount == 0)) ? "<li class='nowplaying'>" : "<li>";
		listHTML += "<a href='http://media.repstars.com/enc/flv/" + pl[i][1] + "' id='vid" + plcount + "'>";
		listHTML += "<img src='http://media.repstars.com/enc/sm/" + pl[i][8] + "' />";
		listHTML += "<strong>";
		if (pl[i][3].length > 24) { listHTML +=  pl[i][3].substr(0,24) + "..."; } else { listHTML +=  pl[i][3]; }
		listHTML += "</strong></a><br>By: "
		if (pl[i][5].length > 11) { listHTML +=  pl[i][5].substr(0,11) + "..."; } else { listHTML +=  pl[i][5]; }
		//listHTML += "Views: " + pl[i][7]  + "<br>";
		listHTML += "<br><span class='quiet' rel='" + pl[i][6] + "'>";
		listHTML += ((firstplay) && (plcount == 0)) ? label_now_playing : "(" + pl[i][6]  + ")";
		listHTML += "</span></li>";
		plcount++;
	}
	
	if (plcount > (plcurrentpage * plbrowse)) { plnextpage++;}
		
	$("#media_playlist #videothumbs ul").width(plwidth*plnextpage).append(listHTML);
	$("#media_playlist #videothumbs li a").unbind("click");
	$("#media_playlist #videothumbs li a").click(function () {
		//alert("Vido File is: " + this.href);
		currentvideo = $(this).attr("id");
		currentvideo = currentvideo.substring(3);
		currentvideo = currentvideo*1;
		
		$("#icon_details").click();
		
		var thumb = "http://media.repstars.com/enc/lg/" + pl[currentvideo][8];
		$("#media_details h2").text(pl[currentvideo][3]);
		$("#media_details #media_by a").text(pl[currentvideo][5]);
		$("#media_details #media_views span").text(pl[currentvideo][7]);
		var videosummary =  (pl[currentvideo][4] != "") ? pl[currentvideo][4] : "<span class='quiet'>" + label_nosummary + "</span>";
		$("#media_details #media_summary").html(videosummary);
		$("#media_flag input[@name='fv_video_id']").val(pl[currentvideo][0]);
		$("#media_contact input[@name='fv_video_id']").val(pl[currentvideo][0]);
		$("#media_contact input[@name='fv_username']").val(pl[currentvideo][5]);
		
		$("#media_share #fv_link").val("http://" + document.location.host + "/home?V=" + pl[currentvideo][0] + "&N=" + pl[currentvideo][12]);
		$("#media_share #fv_embed").val('<embed src="http://' + document.location.host + '/jw_media_player/mediaplayer.swf" width="400" height="245" allowfullscreen="true" wmode="opaque" flashvars="&displayheight=225&file=' + this.href + '&height=245&image=' + thumb + '&width=400&screencolor=0x000000"></embed>');
		
		if ((pl[currentvideo][10] != "") && (pl[currentvideo][11] != "")) {
			$("#media_website").html('<a href="http://' + pl[currentvideo][11] + '" target="_blank"><img src="' + pl[currentvideo][10] + '" border="0" /></a>' + label_moreinfo_1);
		} else {
			$("#media_website").html(label_moreinfo_2);
		}
		
		videoplaying = pl[currentvideo][0];
		var keywords = pl[currentvideo][9]; 
		keywords = keywords.replace(/,/g, " ");
		var tags = keywords.split(" ");
		var taghtml = "";
		for(i = 0; i < tags.length; i++){
			taghtml += "<a href='#' class='searchtag'>" + tags[i] + "</a> ";
		}
		$("#media_details #media_tags span").html(taghtml);
		
		/*$("#media_details .searchtag").click(function() {
			var searchtag = $(this).text();
			$("#videosearch #videotags").val(searchtag);
			$("#videosearch button").click();
			return false;
		});*/
		
		$("#media_details .searchtag").click(function() {
		if (scrollswitch) {
			plsearch = $(this).text();	
			$("#all_playlists h1#current span").text(label_pl_current_1 + " '" + plsearch + "'");
			pl.length = 0; // clear array
			plcurrentpage = 1; // reset current page back
			plnextpage = 1; // reset next page
			plcount = 0; // reset playlist count
			plopp = ""; // reset browse by opportunity
			plcat = ""; //reset browse by category
			plvideo = videoplaying; //video currently loaded
			plnetwork = ""; //reeset network group
			pluser = ""; //reser user
			currentvideo = 0;
			//alert("video id="+plvideo);
			$("#media_playlist #videothumbs ul").width(plwidth*2).css("margin-left", 0).empty();
			getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser, true);	
		}		
		return false;						
	});
		
		if (tvPaused) { $("body").unbind("mousemove"); $("body").unbind("keydown"); tvPaused = false; $("#timerAlert").hide(); resetIdle(); $("body").mousemove(function() { resetIdle(); }); $("body").keydown(function() { resetIdle(); });  }
		
		loadFile('jstest',{file:this.href, image:thumb});
		if (autoclick) { setTimeout("sendEvent('jstest','playpause')", 500); }
		autoclick = false;
		
		$("#media_playlist #videothumbs li").each(function () { 
			$(this).removeClass("nowplaying");
			var playlength = $(this).find("span.quiet").attr("rel");
			$(this).find("span.quiet").text("(" + playlength + ")");
		});
		$(this).parent().addClass("nowplaying").find("span.quiet").text(label_now_playing);
		return false;
	});
	
	//if (firstplay) { playNextVideo(); }
}

function loadFile(swf,obj) { 
  thisMovie(swf).loadFile(obj); 
};

function sendEvent(swf,typ,prm) { 
//alert("next video is: " + currentvideo);
  thisMovie(swf).sendEvent(typ,prm); 
};

function getUpdate(typ,pr1,pr2,swf) { 
//$("body").append("type="+typ+"; pr1="+pr1+"; pr2=" +pr2+"<br>"); //if(typ == "remaining") { alert('remaining: '+pr1); } 
	if((typ == "state")&&(pr1 != undefined)) { 
		currentState = pr1; 
		if(currentState=="3") { playNextVideo(); }
		if(currentState=="0") { tvPaused = true; }
		if(currentState=="2") { tvPaused = false; }
	}
}

function playNextVideo() {
	if (!contactfocus) {
		autoclick = true;
		currentvideo++;
		var videocount = 0;
		$("#media_playlist #videothumbs li a").each(function() {
			if (videocount == currentvideo) { 
				$(this).click(); 
				if (videocount > (plcurrentpage * plbrowse - 1)) { $("#media_playlist #nextvideo a").click(); }
				//alert ("videocount= "+videocount+"; plcurrentpage= "+plcurrentpage+"; plbrowse= "+plbrowse+"; last thumb= "+(plcurrentpage * plbrowse));

			}		
			videocount++;
		});
	}
}

function thisMovie(swf) {
  if(navigator.appName.indexOf("Microsoft") != -1) {
    return window[swf];
  } else {
    return document[swf];
  }
};


/**************** Inactivity Timer Functions ******************/

function idleInit() {    
	$("body").mousemove(function() { resetIdle(); });
	$("body").keydown(function() { resetIdle(); });   
    setIdle();   
	
	var alertBox = '<div id="timerAlert" style="display: none;"><h2>You have been inactive for ' + (idleTime/1000/60) + 'minutes</h2><p>If you are still watching TV, then please click "I&#8217;m Here" to continue watching. If not, your TV will be paused until you return.</p><p><a href="#" class="button" onclick="resumePlay(); return false;">I&#8217;m Here<span></span></a></p></div>';
	
	$(".container").append(alertBox);
}

function onIdleFunction(){   
    //alert("Your browser has been idle for " + (idleTime/1000) +" seconds.");
	promptTimeOut = window.setTimeout( "onPromptIdleFunction()", promptIdleTime );
	$("#timerAlert").show();
	$("body").unbind("mousemove");
	$("body").unbind("keydown");   
	
	/*var continuePrompt = confirm("Your current viewing session has been inactive for " + (idleTime/1000/60) +" minutes. If you are still watching TV, then please click OK to continue watching. If not, your TV will be paused until you return.");
	if (continuePrompt) { 
		resetPromptIdle(); 
	}*/

	//alert("Your current session has been inactive for " + (idleTime/1000/60) +" minutes and you are being disconnected. If you would like continue, please login again.");
}

function onPromptIdleFunction(){   
		if (!tvPaused) {
        	sendEvent('jstest','playpause');
			tvPaused = true;
		}
}

function resetIdle(){   
    window.clearTimeout( idleTimeOut );	
    setIdle();
}

function resetPromptIdle(){   
    window.clearTimeout( promptTimeOut );
    setIdle();   
}

function setIdle(){   
    idleTimeOut = window.setTimeout( "onIdleFunction()", idleTime );   
}

function resumePlay() {
	$("#timerAlert").hide();
	
	if (tvPaused) {
		sendEvent('jstest','playpause');
		tvPaused = false;
	}
	
	$("body").mousemove(function() { resetIdle(); });
	$("body").keydown(function() { resetIdle(); });  
	
	resetIdle();
	
}
