// JavaScript Document
// Master Javascript file for the UI for HBO Share project
// �2009 exit5 LLC
// author: phil@roganstreet.com  Phil Rogan
// 09/11/2009




//a global variable for all database queries.

var dbGateWay = "view/getVideos_db_04.php";

var uploadSuccessMsg = "Thank you. We will review your video and notify you of acceptance..."
var uploadFailMsg = "We're sorry. There has been a problem with your upload."
var upload_TO; // used for timeouts 
 
//ratinggs messages on rollover
var exit5Ratings = {
	thisVideoID:curVideoID
	,
	ratingMSGs:["cold","warmer","warm","getting hot","it's more than you imagined"]
	,
	ratingInstructions:"Click on a star to rate this video"
	,
	postInstructions:"Your rating has been set. Thank You."
	,
	thankYouMSG:"Thank you for rating this video"
	,
	curRating:0
	,
	userRating:null
	,
	
	canRate: function(){
		if(this.userRating == null){
			return true;
		}else{
			return false;
		}
	}
	,
	
	setAllStars : function(p_rate, p_mode){
		var adjustedFloor = Math.max(p_rate, this.curRating);
		if(p_mode == 'over'){
			for(var nn = 0; nn < 5; nn++) {
				if(nn < adjustedFloor){
					$("#rating_" + nn).css('background-position','center top');
				}else if (nn > adjustedFloor) {
					$("#rating_" + nn).css('background-position','center bottom');
				}
			}
		}else {
			for(var nn = 0; nn < 5; nn++) {
				if(nn <= adjustedFloor){
					$("#rating_" + nn).css('background-position','center top');
				}else if (nn > adjustedFloor) {
					$("#rating_" + nn).css('background-position','center bottom');
				}
			}
		}
	},
	
	setCurrentRating : function(p_rating) {
		this.curRating = p_rating;
		this.showRating(this.curRating);
	}
	,
	
	showCurrentRating : function() {
		this.showRating(this.curRating);
	}
	,
	
	setUserRating : function(p_rating) {
		this.userRating = p_rating;
		this.showRating(p_rating);
	}
	,
	
	showRating : function(p_rating){
		for(var nn = 0; nn < 5; nn++) {
			if(nn <= p_rating){
				$("#rating_" + nn).css('background-position','center top');
			}else if (nn > p_rating) {
				$("#rating_" + nn).css('background-position','center bottom');
			}
		}
	}
	,
	setThankyou : function() {
		$("#starMSGs").html( exit5Ratings.thankYouMSG );
	}
	,
	resetRatings:function (){
		this.thisVideoID = curVideoID;
		//this.ratingInstructions="Click on a star to rate this video";
		//this.postInstructions="Your rating has been set. Thank You.";
		//this.thankYouMSG="Thank you for rating this video";
		this.curRating=0;
		this.userRating=null;
		this.showRating(this.curRating);
		
	}
	
}


// extendeing jQuery here for all UI activities.
// strategy for avoiding namespace conflicts


jQuery.extend({
			  
			  
	// dynamically create the list of videos based on the current XML
	exit5_renderVideoList: function(theXML) {
		$('#videos').html(""); // resetthe html
		
		// set up the pagination data...
		exit5VideoListManager.setPrevCount ( eval( $('video_prev_rows',theXML).text() ) ) ;
		exit5VideoListManager.setNextCount ( eval( $('video_next_rows',theXML).text() ) ) ;									  
		
		
		var makeRoom = exit5VideoListManager.showPrevBtn();
		
		
		var videoRows = $('video_chip',theXML);
		
		//$('video_chip',theXML).each(function(i){
		videoRows.each(function(i){
			var video_chip = $('<div> </div>').addClass('video_chips').attr('id', 'video_chip_' + $(this).find("video_chips_id").text());
			
			// it there is a prev records butt9on showing, we gotta push it down a bit
			
			var image = $( '<img src="' +  $(this).find("video_chips_image").text() + '" />').addClass('video_chips_image');
			
			//var image = $( '<img src="/thumbs/sampleVideo.jpg" />').addClass('video_chips_image');
			var title = $( '<div>' + $(this).find("video_chips_title").text() + '</div>').addClass('video_chips_title').attr('id', 'video_thumb_title_'+ i);
			var subtitle = $( '<div>' + $(this).find("video_chips_subtitle").text() + '</div>').addClass('video_chips_subtitle').attr('id', 'video_thumb_subtitle_'+ i);
			var rating = $.exit5_renderStarRating( $(this).find("video_chips_rating").text() ).addClass('video_chips_rating').attr('id', 'video_thumb_rating_'+ i);
			var crlf = $('<div> </div>').addClass('clear_line') ;
			video_chip.append(image);
			video_chip.append(title);
			video_chip.append(subtitle);
			video_chip.append(rating);
			video_chip.append(crlf);
			
			video_chip.click(function(e){ 
				// set the current video to this item
				var myID = this.id.split("video_chip_");
				//alert( this.id + ":" + myID[0] + ":" + myID[1]);
				$.get(exit5_baseURL + dbGateWay + "?mode=info&id=" + myID[1] ,
					function(theXML){
						$.exit5_renderVideoInfo(theXML);
					});					  
			
			
			});
			$('#videos').append(video_chip);
		});
		
		exit5VideoListManager.showNextBtn();
	}
	// render the video info pane with an XML representing the current video.
	,
	exit5_renderVideoInfo: function(theXML){
		
		if(  $("#video_id").html( $("video_id", theXML).text()) == curVideoID){
			return;  // aleady on this video
		}
		curVideoID =  $("video_id", theXML).text(); // set the curVideo
		
		exit5VideoLoader.videoXML =theXML; // set up the view wit the curent xml
		var spacer = function(p_num){var tmpSP = ""; for(var nn = 0; nn < p_num; nn++){ tmpSP +='&nbsp;'} return tmpSP; } ;
		
		$("#video_title").html( $("video_title", theXML).text());
		$("#video_rating_title").html( $("video_title", theXML).text());
		exit5Ratings.resetRatings();
		exit5Ratings.setCurrentRating( parseInt($("video_rating", theXML).text()) - 1);  // adjust for index.
		
		
		$("#video_stats").html( "from:" + spacer(2)  + $("video_user", theXML).text() + spacer(4) + 
								"views:" + spacer(2) + $("video_views", theXML).text() + spacer(4) + 
								"uploaded:" + spacer(2) + $("video_date", theXML).text()); 
		$("#video_description").html( $("video_description", theXML).text());
		$("#video_rating").html(" ");
		
		$("#video_rating").append($.exit5_renderStarRating( $("video_rating", theXML).text() )) 
		
		$("#share_url").val( $("video_share", theXML).text() );
		$("#embed_url").val( $("video_embed", theXML).text() );
		location.href =  $("video_share", theXML).text() ;
		
		exit5VideoLoader.videoID = $("video_id", theXML).text();
		exit5VideoLoader.loadVideoInit($("video_swf", theXML).text());
	},
	
	// Section of methods that show/hide the current sections based on tab presses etc.
	
	
	// show the current video info (default)
	exit5_showInfoUI: function(){
		$("#video_info").css("display", "block");
		$("#video_rating_ui").css("display", "none");
		$("#video_upload_ui").css("display", "none");
		$("#video_sharing_ui").css("display", "none");
		toggleMoreOrLess('more_info');
		//$.exit5_renderVideoInfo(exit5VideoLoader.videoXML);
	},
	
	// show the panel for uploading your own video here
	exit5_showUploadUI: function(){
		$("#video_info").css("display", "none");
		$("#video_rating_ui").css("display", "none");
		$("#video_upload_ui").css("display", "block");
		$("#video_sharing_ui").css("display", "none");
		exit5VideoLoader.HBOplayer.sendEvent("PLAY","false");

	},
	
	// show the panel for sharing embeds and links of the current video
	exit5_showShareUI: function(){
		$("#video_info").css("display", "none");
		$("#video_rating_ui").css("display", "none");
		$("#video_upload_ui").css("display", "none");
		$("#video_sharing_ui").css("display", "block");
	},
	
	// show the panel for rating the current video
	exit5_showRatingUI: function(){
		$("#video_info").css("display", "none");
		$("#video_rating_ui").css("display", "block");
		$("#video_upload_ui").css("display", "none");
		$("#video_sharing_ui").css("display", "none");
		$.exit5_renderRatingUI();
	},
	
	
	
	
	// renders the internal dymnamic contents of hte ratings UI panel
	exit5_renderRatingUI: function(){
		$("#video_rating_title").html( $("video_title", exit5VideoLoader.videoXML).text()); 
	}
	,
	exit5_renderStarRating: function(p_stars){
		var tmpRatingBar = $('<div> </div>').attr('id','video_info_star_rating_bar');
		for (var nn = 0; nn < p_stars; nn++){
			var tmpStar =  $('<img src="/images/home/starRating.png" />').addClass('starRatingImg');
			tmpRatingBar.append(tmpStar);
		}
		return tmpRatingBar;	
	}
	
	
});


/* DOCUMENT INIT - READY */
$(document).ready(function(){

	
	exit5VideoUpLoader.createForm();
	exit5VideoLoader.createPlayer();
	curVideoID = (curVideoID != -1) ? ("&id=" + curVideoID) : "" ;
	
	// set the new list
	exit5VideoListManager.set_curList('latest_videos');
		
		// now reset the hilited sttes of the list
	exit5VideoListManager.resetHilites();
		
		//  now we go get the data...
	exit5VideoListManager.set_videoList();
	
	
	$("#referring_url_link").click(
		function(e) {
			window.location.href = "http://hboimagine.com";
	});
	
	$("#less_info").click(
		function(e) {
			toggleMoreOrLess(e.target.name);
	});
	
	$("#more_info").click(
		function(e) {
			toggleMoreOrLess(e.target.name);
	});
	
	
	//  RATINGS EVENT CONTROLLER  //
	// init...
	$("#starMSGs").html( exit5Ratings.ratingInstructions );
	exit5Ratings.showCurrentRating();
	$("#rating_UI_Bar > a").mouseover(
		function(e) {
			if(!exit5Ratings.canRate()){ return; };
			var rate = Number(e.target.id.charAt(7));
			exit5Ratings.setAllStars(rate,'over');
			$("#" + e.target.id).css('background-position','center center');
			$("#starMSGs").html( exit5Ratings.ratingMSGs[rate] );
			//reset stars around the highlighted...
			
			
		});
	$("#rating_UI_Bar > a").mouseleave(
		function(e) {
			if(!exit5Ratings.canRate()){ return; };
			var rate = Number(e.target.id.charAt(7));
			//reset stars around the highlighted...
			exit5Ratings.setAllStars(rate,'leave');
		});
	
	$("#rating_UI_Bar").mouseleave(
			function(e) {
			if(!exit5Ratings.canRate()){ return; };
			var rate = Number(e.target.id.charAt(7));
			//reset stars around the highlighted...
			exit5Ratings.setAllStars(-1,'leave');
			$("#starMSGs").html( exit5Ratings.ratingInstructions );
		});
	
	$("#rating_UI_Bar > a").click(
		function(e) {
		if(!exit5Ratings.canRate()){ return; };
			// submit rating and close set render to info.
		var rate = Number(e.target.id.charAt(7));
		exit5Ratings.setUserRating(rate);
		rate ++;  // adjust for the 1 base records
		$.get(exit5_baseURL + dbGateWay + "?mode=rate&id=" + exit5VideoLoader.videoID + "&rating="+ rate,
   			function(theXML){ 
				// rset the rating bsed on the return value TBD
				exit5Ratings.setThankyou();
  			});
		});
	
	// END RATINGS CONTROLLER  //
	
	
	 $("#info_menu > a").click(
		function(e) {
				// kill any classes that are active now...sloppy... but I'm in a hurry. [_pr_]
			$("#rate_this_video").removeClass("showingInfo");
			$("#upload_your_video").removeClass("showingInfo");
			$("#share_this_video").removeClass("showingInfo");
			$("#info_this_video").removeClass("showingInfo");
			$("#" + e.target.id).addClass("showingInfo");
			
			
			switch (e.target.id) {
				case "rate_this_video":
					$.exit5_showRatingUI();
					break;
				case "upload_your_video":
					$.exit5_showUploadUI();
					break;
				case "share_this_video":
					$.exit5_showShareUI();
					break;
				default:
					$.exit5_showInfoUI();
					break;	
			}
		});
	
     $("#video_list_tabs > a").click(
	 	function(e){
		// because this is called from a tab, it assumes a change in list...
		// set the new list
		exit5VideoListManager.set_curList(e.target.id);
		
		// now reset the hilited sttes of the list
		exit5VideoListManager.resetHilites();
		
		//  now we go get the data...
		exit5VideoListManager.set_videoList();
		
	});
});

var moreORless ='less_info'; // set at default
	
var toggleMoreOrLess = function(p_mode){

	if(p_mode == moreORless){
		return ;  // skip it 
	}
	
	if (p_mode == 'more_info') {
		$("#video_description").css("display", "block");
		$("#video_stats").css("display", "block");
		$("#less_info").css("display", "block");
		$("#more_info").css("display", "none");
	} else {
		$("#video_description").css("display", "none");
		$("#video_stats").css("display", "none");
		$("#less_info").css("display", "none");
		$("#more_info").css("display", "block");
	}
	moreORless = p_mode;
};

var exit5VideoListManager = {
		// manage the lists and teir pages.
		listMaxPage:10
		,
		curList:'all_videos'
		,
		
		nextCount: false
		,
		
		prevCount : false
		,
		
		setPrevCount : function(p_count){
			this.prevCount = p_count;
		}
		,
		setNextCount : function(p_count){
			this.nextCount = p_count;
		}
		
		,
		showPrevBtn : function(){
			if(this.prevCount ) { 
				var tmpPrevBtn = $('<div> </div>').addClass('video_chips_prevPage').attr('id','video_list_get_prev') ;
				tmpPrevBtn.click(function(e){ 
						exit5VideoListManager.set_curPage(-1);
						
						exit5VideoListManager.set_videoList();
					
					});
				$('#videos').append(tmpPrevBtn);
				return true
	
			}
			return false;
		}
		,
		showNextBtn : function(){
				if(this.nextCount ) {
					var tmpNextBtn = $('<a> </a>').addClass('video_chips_nextPage').attr('id','video_list_getnext') ;
					tmpNextBtn.click(function(e){ 
						exit5VideoListManager.set_curPage(1);
						
						exit5VideoListManager.set_videoList();
					
					});
				$('#videos').append(tmpNextBtn);
			}
		}
		
		,
		
		videoLists: {
					all_videos: { curPage : 1 , id: 'all_videos', maxPage: 0 , SQLLabel:"alpha" , SQLCat:"all",  bgArrowPos:"-274px 23px"} ,
					latest_videos: { curPage : 1 , id: 'latest_videos', maxPage: 0  , SQLLabel:"latest", SQLCat:"latest", bgArrowPos:"-227px 23px"} ,
					toprated_videos: { curPage : 1 ,id: 'toprated_videos', maxPage: 0 , SQLLabel:"rating", SQLCat:"rating", bgArrowPos:"-162px 23px"} ,
					featured_videos: { curPage : 1 , id: 'featured_videos' , maxPage: 0  , SQLLabel:"featured", SQLCat:"featured", bgArrowPos: "-74px 23px"}
					}
		,
		
		set_curList:function(p_listref) {
			this.curList = p_listref;
		}
		,
		get_curPage : function(){
			// sniff the recent page and shoot back the current value
			return this.videoLists[this.curList].curPage;
		}
		,
		
		set_curPage : function(p_add){  // can -1 or 1
			// sniff the recent page and shoot back the current value
			var tmppage =  this.videoLists[this.curList].curPage + p_add;
			this.videoLists[this.curList].curPage = tmppage ;
		}
		
		,
		resetHilites : function(){
			for(var obj in this.videoLists){
				$("#" + this.videoLists[obj].id).removeClass("showing");
			}
		
			$("#" + this.curList).addClass("showing");
			var tmpBGPOS = "20px 23px";
			$("#video_list_tabs").css('background-position',this.videoLists[this.curList].bgArrowPos);
		}
		,
		set_videoList : function() {
			// kill the current list
			$('#videos').css("display", "none");
			$("#videos").scrollTop(0);

		// lay in some code to get the queries right here...
		// cat = latest, rating, alpha
			switch (this.videoLists[ this.curList ].SQLLabel){
				case "latest":
				case "featured":
					var SQL_order = "desc";
					break;
				case "alpha":
					var SQL_order = "asc";
					break;
				default:
					var SQL_order = "desc";
			}
			
			//we need to get the page number now
			// this was already set. so we just need to reference it.
			
			 $.get(exit5_baseURL + dbGateWay + "?mode=list&cat=" + this.videoLists[ this.curList ].SQLCat + "&order=" + SQL_order + "&page=" + this.videoLists[ this.curList ].curPage + "&maxrows=" + this.listMaxPage, function(theXML){
				$.exit5_renderVideoList(theXML);

				$('#videos').fadeIn();
			});
		}
	}
			
					
						


var exit5VideoLoader = {
	videoXML:null
	,
	videoURL:null
	,
	videoID:null
	,
	HBOplayer:null
	,
	checkTO:null
	,
	rechecker:0
	,
	
	loadVideoInit : function(p_url){
		this.videoURL = p_url;
		this.loadVideo();
	}
	,
	loadVideo : function (){
		if(this.HBOplayer != null){
			this.HBOplayer.sendEvent('LOAD', this.videoURL);
			this.rechecker = 0;
			clearTimeout(this.checkTO);
		} else {
			//alert("attempting to load " + this.videoURL);
			this.checkTO = setTimeout('exit5VideoLoader.loadVideo', 500);
			this.rechecker ++;
			if(this.rechecker > 4){
				alert("Problem with Flash!");
				this.rechecker = 0;
				clearTimeout(this.checkTO);
			}
		}
	}
	,
	createPlayer: function() {
    	var flashvars = {
         	file:"", 
			autostart:"true",
			skin:"/flash/stylish_slim.swf"
		}
		var params = {
			allowfullscreen:"true", 
			allowscriptaccess:"always"
		}
		var attributes = {
			id:"video_screen",  
			name:"video_screen"
		}
    	swfobject.embedSWF("/flash/player.swf", "screen", "586", "362", "9.0.115", false, flashvars, params, attributes);

	}
}


var exit5VideoUpLoader = {
	
	createForm: function() {
			
    	var flashvars = {
         	file:""
		}
		var params = { 
			allowscriptaccess:"sameDomain",
			bgcolor:"#000000"
		}
		var attributes = {
			id:"formEntryColFlash_SWF",  
			name:"formEntryColFlash_SWF"
		}
    	swfobject.embedSWF("/flash/HBOUploader.swf", "formEntryColFlash", "280", "340", "9.0.115", false, flashvars, params, attributes);

	}
}


function resetUploadForm(){
	clearTimeout(upload_TO);
	$('#uploadInstructions').css('display', 'block');
	$('#formEntryCol').css('display', 'block');
}

function playerReady(obj) {
	exit5VideoLoader.HBOplayer = document.getElementById(obj['id']);
	$('#info_this_video').addClass("showingInfo");
	$.get(exit5_baseURL + dbGateWay + "?mode=info" + curVideoID ,
   	function(theXML){ 
		$.exit5_renderVideoInfo(theXML);
   	});
};