$(document).ready(function(){
	$('#filmContainer #film_0').addClass('filmActive');
	
	$('#jQueryUIAccordion').accordion({
		header: '.ui-accordion-link',
		autoheight: false
	});
	$('#jQueryUIAccordion2').accordion({
		header: '.ui-accordion-link',
		autoheight: false
	});
	
	// add bookmarks
	if ( $("#socialBookmarkURL").length > 0 ) thisURL = $("#socialBookmarkURL").val();
	else thisURL = window.location.href;
  if ( $("#socialBookmarkTitle").length > 0 ) thisTitle = $("#socialBookmarkTitle").val();
	else thisTitle = document.title;
	
	$('#ai_sbookmarks').bookmark({
		customURL: thisURL,
		customTitle: thisTitle,
    sites: ['google', 'facebook', 'myspace', 'delicious', 'digg', 'yahoo', 'reddit', 'slashdot'], 
		icons: '/ScriptLibrary/jquery/plugins/bookmarks/bookmarks.png', 
		iconSize: 16,  
		target: '_blank',  
		compact: false,   
		addFavorite: false, 
		favoriteText: 'Favorite', 
		favoriteIcon: 0, 
		addEmail: false, 
		emailText: 'E-mail', 
		emailIcon: 1, 
		emailSubject: 'Interesting page', 
		emailBody: 'I thought you might find this page interesting:\n{t} ({u})', 
		manualBookmark: 'Please close this dialog and\npress Ctrl-D to bookmark this page.'
	});
	
	// RATING EVENT BINDINGS
	$("#ratingwrapper_disabled").bind("mouseover", colorChangeOver);
	$("#ratingwrapper_disabled").bind("mouseout", colorChangeOut);
	$("#ratingwrapper_disabled").bind("mouseover", showLoginMsg);
	$("#ratingwrapper_disabled").bind("mouseout", hideLoginMsg);
	
	// CHECK FOR PREVIOUS RATING
	checkPreviousRating();
});


// FILM INFO/PLAYER PAGE MESSAGES
var MSG_LOADING_FILM_INFO 		= "Loading film information...";
var MSG_LOADING_FILM_PLAYER 	= "Loading film player...";
var MSG_LOADING_FILM_DETAILS 	= "Loading film player...";
var MSG_LOADING_FILM_COMMENTS 	= "Loading film player...";

// RATING BLOCK MESSAGES
var MSG_RATING_REMOVED 			= "Rating removed.";
var MSG_RATING_SAVED 			= "Rating saved!";
var MSG_RATING_ENABLED_IN 		= "Rating will be enabled in:";
var MSG_RATING_ENABLED 			= "Rating is now enabled!";
var MSG_RATING_VIEW_TO_RATE 	= "Please view film to allow rating.";
var MSG_RATING_SIGNIN_TO_RATE 	= "Please sign in to rate films.";
var MSG_RATING_MUST_WATCH 		= "You must view 80% of a film before rating it.";

// COMMENT BLOCK MESSAGES
var MSG_COMMENT_SAVING			= "Please wait, your comment is being saved.";
var MSG_COMMENT_SAVED 			= "Thank you, your comment has been successfully saved.";
var MSG_COMMENT_MUST_SIGNIN 	= "You must be signed in to post comments.";
var MSG_COMMENT_ERROR 			= "An error ocurred. Your comment could not be saved!";
var MSG_COMMENT_NONBLANK 		= "Please enter a comment.";

// APPLICATION ICONS
var ICON_TICK 					= "<img src=\"/media/images/tick.png\" alt=\"\" border=\"0\" height=\"16\" width=\"16\" align=\"absmiddle\" />";
var ICON_CLOCK 					= "<img src=\"/media/images/clock.png\" alt=\"\" border=\"0\" height=\"16\" width=\"16\" align=\"absmiddle\" />";

///////////////////////////
// FILM RATING
///////////////////////////
function initStarRatingControl() {
	$("#ratingwrapper").stars({
		cancelShow: false,
		captionEl: $('#ratingcap'),
		split: 2,
		disabled: true,

		callback: function(ui, type, value){
			// POST THE RATING
			$.get("/ajaxCall.php", { operation: "rateFilm", rating_id: $('#rating_id').val(), checkstr: $('#checkstr').val(), rating: value },
				function(data){
					//alert("Data Loaded: " + data);
					filmRated(value, $("#current_film_id").val());
				}
			);

			var instance = $("#ratingwrapper").data("stars");
			instance.disable();

			//alert($("ratingwrapper").attr("value"));

			$("#ratingResponse").addClass('alertBrBlue').html(value==ui.options.cancelValue ? MSG_RATING_REMOVED : MSG_RATING_SAVED).stop().css("opacity", 1).fadeIn(30);
			setTimeout(function(){ 
				$("#ratingResponse").fadeOut(1000);
				instance.enable();
			}, 3000);
		}

	});
}

function filmRated(rval, rid) {
	//alert("filmRated FIRED!");
	var baseUrl = '/media/images/';
	var baseImg = 'starstrip_';
	var baseExt = '.png';
	
	if (rval != "" && rid != "") {
		var imageSrc = baseUrl+baseImg+rval+baseExt;
		$('#fr_'+rid+' img').attr('src', imageSrc);
	}
	
}

function enableRating(enable) {
	//alert("enableRating FIRED! ("+enable+")");
	var instance = $("#ratingwrapper").data("stars");

	if (enable == 1) {
		instance.enable();
		$("#rating_is_enabled").val(1);

		$("#ratingTimer").css("display", "block");
		$("#ratingResponse").empty();
		
		$("#ratingwrapper").removeClass("block_hidden").addClass("block_visible");
		$("#ratingwrapper_disabled").removeClass("block_visible").addClass("block_hidden");
		
	} else {
		instance.disable();
		$("#rating_is_enabled").val(0);
		$("#ratingTimer").removeClass("block_hidden").addClass("block_hidden");
		$("#ratingResponse").removeClass().addClass("alertOrange").html(MSG_RATING_MUST_WATCH);
	}
}

function checkPreviousRating() {
	var instance = $("#ratingwrapper").data("stars");
	var previousRating = $("#rating_value").val();
	
	//alert("checkPreviousRating FIRED! ("+previousRating+")");
	
	if (previousRating > 0) {
		enableRating(1);
		$("#rating_"+previousRating).attr("checked", "checked");
		$('#ratingform').stars('select', $('#ratingform :radio:checked').val())
	} else {
		$("#rating_is_enabled").val(0);
	}
}

function colorChangeOver() {
	var isEnabled = $("#rating_is_enabled").val();
	//$("#ratingResponse").append("isEnabled:"+isEnabled);

	if (isEnabled == 0) {
		showMessage = $("#show_login_message").val();
		if (showMessage == 0) {
			$("#ratingResponse").addClass("alertOrange").html(MSG_RATING_MUST_WATCH);
		}
	}
}

function colorChangeOut() {
	var isEnabled = $("#rating_is_enabled").val();
	//$("#ratingResponse").append("isEnabled:"+isEnabled);

	if (isEnabled == 0) {
		var showMessage = $("#show_login_message").val();
		if (showMessage == 0) {
			$("#ratingTimer").removeClass("block_hidden").addClass("block_visible");
			$("#ratingResponse").empty().removeClass().fadeOut("slow");
		}
	}
}

function showLoginMsg() {
	
	var userID = $("#user_id").val();
	var isLoggedIn = $("#user_logged_in").val();
	var showMessage = $("#show_login_message").val();
	
	//alert("showLoginMsg FIRED! ("+showMessage+")");
	
	if (showMessage == 1) {
		if (isLoggedIn == 1) {
			$("#ratingResponse").empty().removeClass().addClass("alertBrGreen").html(MSG_RATING_VIEW_TO_RATE).fadeIn("slow");
		} else {
			$("#ratingResponse").empty().removeClass().addClass("alertBrGreen").html(MSG_RATING_SIGNIN_TO_RATE).fadeIn("slow");
		}
	}
}

function hideLoginMsg() {
	$("#ratingResponse").empty().removeClass().fadeOut("slow");
}

///////////////////////////
// FILM CONTROL
///////////////////////////
function changefilm (cid,fid,ind) {
	// KILL ACCORDIONS
	$('#jQueryUIAccordion').accordion('destroy');
	$('#jQueryUIAccordion2').accordion('destroy');
	// KILL BOOKMARKS
	$('#ai_sbookmarks').bookmark('destroy');
	
	url = "/module.php?name="+framework_module_path+"film_info.php&params=channel|"+cid+"|film|"+fid+"&template="+framework_module_path+"";
	$('#film_info').html('<div class=\"preloadMsg\">'+MSG_LOADING_FILM_INFO+'</div>');
	$('#screen').html('<div class=\"preloadMsg\">'+MSG_LOADING_FILM_PLAYER+'</div>');
	$('#ad_sp_1').html('');
	$('#film_details').html('<div class=\"preloadMsg\">'+MSG_LOADING_FILM_DETAILS+'</div>');
	$('#rating').html('');
	$('#film_comments').html('<div class=\"preloadMsg\">'+MSG_LOADING_FILM_COMMENTS+'</div>');
	
	$('#film_info').load(url+'filmHeader.tpl');
	$('#screen').load(url+'flvPlayer.tpl', "", $('#rating').load(url+'filmRating.tpl'));
	$('#ad_sp_1').load(url+'adSpace1.tpl');
	
	$('#film_details').load(url+'filmDetails.tpl', "", function() {
			$('#jQueryUIAccordion').accordion({
				header: '.ui-accordion-link',
				autoheight: false
			});
			$('#jQueryUIAccordion2').accordion({
				header: '.ui-accordion-link',
				autoheight: false
			});
			
			// REBIND RATING CONTROLS
			$("#star").bind("mouseover", colorChangeOver);
			$("#star").bind("mouseout", colorChangeOut);
			
			$("#ratingwrapper_disabled").bind("mouseover", showLoginMsg);
			$("#ratingwrapper_disabled").bind("mouseout", hideLoginMsg);
			
			// ADD BOOKMARKS
			
			if ( $("#socialBookmarkURL").length > 0 ) thisURL = $("#socialBookmarkURL").val();
    	else thisURL = window.location.href;
      if ( $("#socialBookmarkTitle").length > 0 ) thisTitle = $("#socialBookmarkTitle").val();
    	else thisTitle = document.title;
			
			$('#ai_sbookmarks').bookmark({
			  customURL: thisURL,
		    customTitle: thisTitle,
				sites: ['google', 'facebook', 'myspace', 'delicious', 'digg', 'yahoo', 'reddit', 'slashdot'], 
				icons: '/ScriptLibrary/jquery/plugins/bookmarks/bookmarks.png', 
				iconSize: 16,  
				target: '_blank',  
				compact: false,   
				addFavorite: false, 
				favoriteText: 'Favorite', 
				favoriteIcon: 0, 
				addEmail: false, 
				emailText: 'E-mail', 
				emailIcon: 1, 
				emailSubject: 'Interesting page', 
				emailBody: 'I thought you might find this page interesting:\n{t} ({u})', 
				manualBookmark: 'Please close this dialog and\npress Ctrl-D to bookmark this page.'
			});
			
			// CHECK FOR PREVIOUS RATING
			checkPreviousRating();
			
		}
	);
	
	$('#'+ind).addClass('filmActive');
	$('#film_comments').load(url+'filmComments.tpl');
	// SCROLL PAGE TO FILM DISPLAY
	$.scrollTo( '#pageContent', 500 );
	
	return;
}

function filmPlay() {
	startCountdown();
	$.get("/ajaxCall.php", { context: "filmPlay", rating_id: $('#rating_id').val(), checkstr: $('#checkstr').val() },
		function(data){
			//alert("Data Loaded: " + data);
		}
	);
}

function filmPause() {
	pauseCountdown();
}

function filmEnd() {

}

///////////////////////////
// COUNTDOWN
///////////////////////////
function startCountdown() {
	//alert("startCountdown FIRED!");
	userLoggedIn = $("#user_logged_in").val();
	var previousRating = $("#rating_value").val();

	if (userLoggedIn > 0 && previousRating <= 0) {
		$("#show_login_message").val(0);
		$("#ratingTimer").countdown({until: '+' + $("#rating_enabled_in").val() + 's', format: 'ms', layout: '<strong>'+MSG_RATING_ENABLED_IN+'</strong> %M%n %l%M %S%n %l%S', onExpiry: removeCountdown});
		$("#ratingTimer").countdown('resume');
	}
}

function pauseCountdown() {
	$("#ratingTimer").countdown('pause');
}

function resumeCountdown() {
	$("#ratingTimer").countdown('resume');
}

function removeCountdown() {
	isEnabled = $("#rating_is_enabled").val();
	if (isEnabled == 0) {
		enableRating(1);
		$("#ratingTimer").countdown('destroy');
		$("#ratingTimer").removeClass().addClass('alertBrGreen').html(MSG_RATING_ENABLED).pulse({ textColors: ['#00FF00','black'] });
	}
  
	$.get("/ajaxCall.php", { operation: "markRatingAllowed", rating_id: $('#rating_id').val(), checkstr: $('#checkstr').val() },
		function(data){
			if (data == 1) { enableRating(1); }
		}
	);

	setTimeout(function(){ $("#ratingTimer").fadeOut(1000) }, 8000);
}

///////////////////////////
// COMMENTS
///////////////////////////
function reloadComments() {
	filmID = $("#filmID").val();
	channelID = $("#channelID").val();
	url = "/module.php?name="+framework_module_path+"film_info.php&params=action|comments|channel_id|"+channelID+"|film_id|"+filmID+"&template="+framework_module_path+"filmCommentList.tpl";

	$('#comment_list').fadeOut(300, function () {
		$('#comment_list').load(url);
		$("#comment_list").fadeIn(500);
		$.scrollTo("#comments", 500 );
		return false;
	});
}

function pageFilmComments(page, filmID) {
  filmID = $("#filmID").val();
	channelID = $("#channelID").val();
	url = "/module.php?name="+framework_module_path+"film_info.php&params=action|comments|channel_id|"+channelID+"|film_id|"+filmID+"|comment_page|"+page+"&template="+framework_module_path+"filmCommentList.tpl";
  $('#comment_list').fadeTo(500, 0.01, function(){
    $('#comment_list').load(url, {page: page}, function(){
      $("#comment_list").fadeTo(500, 100);
      $.scrollTo("#comments", 500 );
      return false;
    });
  });
}

function postComment(context, entity, group) {
	if ((context.length > 0) && (entity.length > 0)) {
		// disable submit button and alert user comment is being saved
		$("#comment_form #submit").attr("disabled", "disabled");
		$("#commentResponse").html('<div id="errorBlock" style="color:#FFFFCC;">'+ICON_CLOCK+' <strong>'+MSG_COMMENT_SAVING+'</strong></div><br />');

    	comment = $("#comment_text").val();
	    if (comment.length == 0) {
			alert(MSG_COMMENT_NONBLANK);
		} else {
      
			$.ajax({
				type: "POST",
				url: "/ajaxCall.php",
				data: "operation=postComment&context="+context+"&entity="+entity+"&group="+group+"&comment="+escape(comment),
				success: function(result){
			
					// RE-ENABLE THE SUBMIT BUTTON AND ALERT USER THE COMMENT HAS BEEN SAVED
					$("#comment_form #comment_text").val("");
					$("#comment_form #submit").removeAttr("disabled");
					$("#commentResponse").html("");
					$("#commentResponse").html('<div id="errorBlock" style="color:#FFFFCC;">'+ICON_TICK+' <strong>'+MSG_COMMENT_SAVED+'</strong></div><br />');
			 
					if (result == 2) {
						reloadComments();
					} else if (result == 1) {
						alert(MSG_COMMENT_MUST_SIGNIN); 
					} else {
						alert(MSG_COMMENT_ERROR);
					}
			
				}
			});
		}
	}
	return false;
}
