/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

$(document).ready(function(){
	/*					   
		$("#data_cols div.column ul > li div.rating b").hover(
		  function () {
			 
		  }, 
		  function () {
			
		  }
		);
	*/
	
	if( $('div#wrap').hasClass('remix') ){	
		$('#screen2_loading, #screen3_loading, #screen2_error, #screen3_error, .error').hide();
		
		$('#screen2_next').click(screen2_onNextClick);
		$('#screen2_cancel').click(screen2_onCancelClick);
		
		$('#screen3_next').click(screen3_onNextClick);
		$('#screen3_cancel').click(screen3_onCancelClick);
	}
	
	if ($("#wrap").hasClass("view")) {
		KalturaHelper.loadRanking();
		
		$("#sendToFreind").find("button").click(function () {
			var params = {
				kshowId: $("#kshowId").val(),
				email1: $("#shareFriend1").val(),
				email2: $("#shareFriend2").val(),
				email3: $("#shareFriend3").val()
			}
			$.ajax({
				type: "POST",
				url: "ajax_send_to_friend2.php?"+(new Date()).getTime(),
				data: params,
				success: function(msg) {
					$('#sendToFreind').fadeOut('fast', function() {
						$("#shareFriend1").val("");
						$("#shareFriend2").val("");
						$("#shareFriend3").val("");
					});
				},
				error: function() {

				}
			});
			return false;
		})
	}	
	
});

function onSimpleEditorSaveClick()
{
	setTimeout(onSimpleEditorSaveClickTimeout, 0);
}

function onSimpleEditorSaveClickTimeout()
{
	$('#screen1').hide();
	$('#screen2').show();
}
	
function onSimpleEditorBackClick(modified)
{
	KalturaHelper.goToIndex();
}

function screen2_onNextClick () {
	var submitForm = true;
	$('.error').css('visibility', 'hidden'); 
	
	var kshowId = $('#kshowId').val();
	var title = $('#screen2_title');
	var name = $('#screen2_name');
	var email = $('#screen2_email');
	
	$("#screen2_form fieldset div.item span").hide();
	
	var emailRegxp = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
	
	if ( email.val().replace(/ /g, '' ).length > 0 && !emailRegxp.test(email.val()) ){
		submitForm = false;
		email.next("span").css('visibility', 'visible');
	}
	
	if (!submitForm)
		return false;
	
	var params = {
		kshowId: kshowId,
		kshowIdEncoded: $('#kshowIdEncoded').val(),
		title: title.val(),
		name: name.val(),
		email: email.val()
	}
	
	$('#screen2_loading').show();
	$.ajax({
		type: "POST",
		url: "ajax_finish_remix.php?"+(new Date()).getTime(),
		data: params,
		success: function(msg) {
			$('#screen2_loading, #screen2').hide();
			$('#screen3').show();
		},
		error: function() {
			$('#screen2_loading').hide();
			$('#screen2_error').show();
		}
	});
};

function screen2_onCancelClick() {
	KalturaHelper.goToIndex();
}

function screen3_onNextClick() {
	var submitStatus = 3;
	
	var kshowId = $('#kshowId').val();
	var email1 = $('#screen3_email1').val();
	var email2 = $('#screen3_email2').val();
	var email3 = $('#screen3_email3').val();
	
	$("#screen3_form fieldset div.item input").each(function(){
		$(this).next("span").hide();
		if (this.value == '') {
			submitStatus -= 1;
		}
	})
	
	switch(submitStatus) {
		default:
			return false;
			break;
		case 1:
		case 2:
		case 3:
			var params ={ kshowId: kshowId, email1: email1, email2: email2, email3: email3 };
			
		 	$('#screen3_loading').show();
			$.ajax({
				type: "POST",
				url: "ajax_send_to_friend.php?"+(new Date()).getTime(),
				data: params,
				success: function(msg) {
					$('#screen3_loading').hide();
					KalturaHelper.goToKShowPage($("#kshowId").val());
				},
				error: function() {
					$('#screen3_loading').hide();
					$('#screen3_error').show();
				}
			});
			break;	
		case 0:
			KalturaHelper.goToKShowPage($("#kshowId").val());
			break;	
	}
}

function screen3_onCancelClick() {
	screen3_onNextClick();
}

KalturaHelper = {
	metacafeBaseUrl : "http://www.metacafe.com",
	
	getTopWindow : function () {
		return (window.top) ? window.top : window;
	},
	
	goToIndex : function () {
		var topWin = KalturaHelper.getTopWindow();
		topWin.location.href = this.metacafeBaseUrl + '/ghosthouse/';		
	},
	
	goToKShowPage : function (kshowId) {
		var topWin = KalturaHelper.getTopWindow();
		topWin.location.href = this.metacafeBaseUrl + '/ghosthouse/mashup/?id=' + kshowId + '&remixed=true';		
	},
	
	showRemix: function (id) {
		jQuery.get(
			'ajax_get_mix_details.php?'+(new Date()).getTime(),
			{
				kshowId: id
			},
			function(xml) {
				$("#wrap>div>div.col2 h1").html(jQuery('item name', xml).text())
				.next("strong").html("By: " + jQuery('item user', xml).text())
				.next("strong").html(jQuery('item date', xml).text())
				.siblings("div").find("div").width(Math.round(Number(jQuery('item rank', xml).text()) / 50) + "%");
				KalturaHelper.loadRanking();
			},	           
			'xml'
		);
		playerController.insertKShow(id, true);
		$('#remixThisButton').attr('href', this.metacafeBaseUrl + '/ghosthouse/mixer/?id=' + id);
		$("#kshowId").val(id);	
		
		KalturaHelper.loadRanking();
	},
	
	loadRanking: function() {
		var rating_el = $("#player_row div.rating");
		rating_el.find("div")[0].rating = rating_el.find("div").css("width");
				
		$("#player_row div.rating b")
			.mouseover(function(){			
				var index = rating_el.find("b").index(this) + 1;
				rating_el.find("div").width((index*20)+"%");
			})
			.mouseout(function(){
				rating_el.find("div").width(rating_el.find("div")[0].rating);
			})
			.click(function() {
				// remove the events
				$(this).siblings().andSelf().unbind("mouseover").unbind("mouseout").unbind("click");
				var rank = rating_el.find("b").index(this) + 1;
				var params = { 
					rank: rank, 
					kshowId: $("#kshowId").val() 
				};
				
				$.ajax({
					type: "POST",
					url: "ajax_rank_remix.php?"+(new Date()).getTime(),
					data: params,
					success: function(msg) {
						// blink and then show the new rank
						var newRank = Number(msg);
						if (newRank==0) { 
							// if user ranked the mix just show the original rank
							var rating_el = $("#player_row div.rating");
							rating_el.find("div").width(rating_el.find("div")[0].rating);
							KalturaHelper.loadRanking();
						}
						else {
							setTimeout('$("#player_row div.rating div").width("0%")', 0);
							setTimeout('$("#player_row div.rating div").width("'+rank*20+'%")', 500);
							setTimeout('$("#player_row div.rating div").width("0%")', 1000);
							setTimeout('$("#player_row div.rating div").width("'+rank*20+'%")', 1500);
							setTimeout('$("#player_row div.rating div").width("0%")', 2000);
							setTimeout('$("#player_row div.rating div").width("'+Math.round(newRank/50)+'%")', 2500);
						}
					},
					error: function() {
						
					}
				});
			});
	}
}


/*
 * Kaltura Player Controller
 */
Delegate = function () {
};

Delegate.create = function (/*Object*/ scope, /*Function*/ method ) {
	var f = function () {
		return method.apply (scope, arguments);
	}
	return f;
};


KalturaPlayerController = function (playerId) {
	this.playerId = playerId;
	this.currentKshowId = -1;
	this.currentEntryId = -1;
	this.args = null;
};

KalturaPlayerController.prototype = {
	insertMedia: function (kshowId, entryId, autoStart) {
		this.invoke("insertMedia", kshowId, entryId, autoStart);
		this.currentKshowId = kshowId;
		this.currentEntryId = entryId;
	},
	
	insertEntry: function (entryId, autoStart) {
		this.insertMedia(-1, entryId, autoStart);
	},
	
	insertKShow: function (kshowId, autoStart) {
		this.insertMedia(kshowId, -1, autoStart);
	},
	
	pause: function () {
		this.invoke("pauseMedia");
	},
	
	stop: function () {
		this.invoke("stopMedia");
	},
	
	play: function () {
		this.invoke("playMedia");
	},
	
	seek: function (time) {
		this.invoke("seekMedia", time);
	}, 
	
	invoke: function () {
		this.playerElement = document.getElementById(this.playerId);

		// store the arguments so we can use them if the player is not ready yet 
		if (!this.args)
			this.args = arguments;
			
		// no arguments means that this function was called after the local args were set to null
		if (!this.args || this.args.length == 0)
			return;
	
		var method = this.args[0];
		
		if (this.playerElement && this.playerElement[method]) {
			// shift to remove the method name from the array
			var args = Array.prototype.slice.call(this.args, [1]);
			
			switch (args.length) {
				case 1:
					this.playerElement[method](args[0]);
					break;
				case 2:
					this.playerElement[method](args[0], args[1]);
					break;
				case 3:
					this.playerElement[method](args[0], args[1], args[2]);
					break;
				default:
					this.playerElement[method]();
					break; 	
			}
			
			this.args = null; // clean the arguments container
		}
		else {
			var f = Delegate.create(this, this.invoke);
			setTimeout(f, 200);
		}
	},
	
	reload: function () {
		this.insertMedia(this.currentKshowId, this.currentEntryId, true);
	}
};
