/**
* 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(){

/*	$("button.next").hover( function(){$(this).css("background-position","-329px -141px")}, function(){$(this).css("background-position","-329px -101px")});
	$("button.skip").hover( function(){$(this).css("background-position","-235px -141px")}, function(){$(this).css("background-position","-235px -101px")});
	$("#sendToFriend button").hover( function(){$(this).css("background-position","-329px -180px")}, function(){$(this).css("background-position","-235px -180px")});*/

/*	$('input:text').focus().css('border-color','#fff');
	$('input:text').blur().css('border-color','#7E9CC1');
*/

	if($.browser.msie) {
            $("input:text").focus( function(){$(this).addClass("focus")});
            $("input:text").blur( function(){$(this).removeClass("focus")});
			DD_roundies.addRule('.modal, .modal form, .modal input', '4px');
			DD_roundies.addRule('#editor_wrap', '11px');
            if($.browser.version>6)
                $("ul.column li").css("width","300px");
            if($.browser.version<7)
					DD_roundies.addRule('h1, a#tslogo, div#wrap-player, div#buttons, div#buttons a.mashup, #data_cols h2, div.rating, div.rating div, body#remix a#back, a.close, #view div.buttons a, div.modal button, div.details, .paging a');
	}

	if ($('body#remix').size() > 0) {	
		$('#screen2_loading, #screen3_loading, #screen2_error, #screen3_error').hide(); //, .error
		
		$('#screen2_next').click(screen2_onNextClick);
//		$('#screen2_cancel').click(screen2_onCancelClick);
		$('a.close').click(function(){
			$('#screen2').hide();
			$('#alien').css({'top':'9px','right':'133px'});;
			$('#screen1').show();
			return false;
		});
//		$('#screen3_next').click(screen3_onNextClick);
//		$('#screen3_cancel').click(screen3_onCancelClick);
	}
	
	if ($('body#view').size() > 0) {
		KalturaHelper.loadRanking();
		window.$sendToFriend=$("#sendToFriend");
		$("#contest").click(function(){toggleAgeChallenge('contest')});
		$("#tell").click(function(){toggleAgeChallenge('tell')});
	}
	
	if ($('body#contest').size() > 0) {
		$('#email').focus();
		$('#enter_contest').click(enter_contestClick);
		$('#back').click(contestBackClick);
	}
});

function toggleAgeChallenge(goto) {
	window.$dob_btn=$('#dob_btn');
	if (document.cookie.indexOf('not_13') != -1) 
	{
		showNot13Box();
	}
	else
	{
		$sendToFriend.show('250');
		$dob_btn.unbind().click(function(){checkAge(goto)});
	}
	return false
}

function checkAge(goto) {
	var doGoTo = false;
	var day = $("#day").val();
	var month = $("#month").val();
	var year = $("#year").val();
	var age = 13;
	var mydate = new Date();
	mydate.setFullYear(year, month-1, day);
	if (isNaN(mydate.getTime()))
	{
		alert("Please enter a valid date");
		return false;
	}
	var currdate = new Date();
	currdate.setFullYear(currdate.getFullYear() - age);
	if ((currdate - mydate) < 0) {
		document.cookie='not_13=true; expires=Tue, 31 Dec 2099 23:59:59 UTC; path=/'	//  set cookie
		showNot13Box();
	}
	else {
		doGoTo = true;
	}
	
	if (doGoTo) {
		switch(goto) {
			case "contest":
				var topWin = KalturaHelper.getTopWindow();
				topWin.location.href = KalturaHelper.contestUrl + "?kid=" + $("#kshowId").val() + "&kshowIdEncoded=" + $('#kshowIdEncoded').val();
				break;
			case "tell":
				var kplayer = $("#kplayer").get(0);
				kplayer.dispatchKdpEvent("gigyaPopup");
				$sendToFriend.hide('250');
				break;
		}
	}
}

function showNot13Box() {
	var callback = function(){
		$sendToFriend.find('div').hide();
		$sendToFriend.find("h1").css('background-position','50px -310px');
		$sendToFriend.find('h2').html('THIS IS ONLY AVAILABLE FOR USERS AGE 13+');
		$sendToFriend.show('250');
		$dob_btn.html('OK');
		$dob_btn.unbind().click(function(){
			$sendToFriend.hide('250');
			$('#contest').hide();
			$('#rules').hide();
			return false;
		});
	};
	if ($sendToFriend.is(":visible"))
		$sendToFriend.hide('250', callback);
	else
		callback();
}

function onSimpleEditorSaveClick() {
	setTimeout(onSimpleEditorSaveClickTimeout, 0);
}

function onSimpleEditorSaveClickTimeout() {
	$('#alien').css({'top':'141px','left':'393px'});
	$('#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');
	
	$("#screen2_form fieldset div.item span").hide(); //errors?
	
	if (!submitForm)
		return false;
	
	var params = {
		kshowId: kshowId,
		kshowIdEncoded: $('#kshowIdEncoded').val(),
		title: title.val(),
		name: name.val()
	};
	
	$('#screen2_loading').show();
	$.ajax({
		type: "POST",
		url: "ajax_finish_remix.php?"+(new Date()).getTime(),
		data: params,
		success: function(msg) {
//			$('#screen2_loading, #screen2').hide();
			KalturaHelper.goToKShowPage($("#kshowId").val(), $('#kshowIdEncoded').val());
		},
		error: function() {
			$('#screen2_loading').hide();
			$('#screen2_error').show();
		}
	});
	
	return false;
};

function screen2_onCancelClick() {
	KalturaHelper.goToIndex();
	return false;
}

function enter_contestClick() {
	var regx = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(regx.test($('#email').val()) == false) {
		$('#email_error').show();
		$('#email').addClass('error');
		$('#email').focus();
		return false;
	}
	else {
		var params = {
			kshowId: $('#kshowId').val(),
			kshowIdEncoded: $('#kshowIdEncoded').val(),
			email: $('#email').val()
		};
		$.ajax({
			type: "POST",
			url: "ajax_enter_contest.php?"+(new Date()).getTime(),
			data: params,
			success: function(msg) {
				$("#save_mashup").hide();
				$("#save_thx").show();
			},
			error: function() {
				
			}
		});
		return false;
	}
}

function contestBackClick() {
	var topWin = KalturaHelper.getTopWindow();
	var url = KalturaHelper.viewUrl + '?kid=' + $("#kshowId").val();
	
	topWin.location.href = url;
	return false;
}

KalturaHelper = {
	indexUrl: "",
	viewUrl: "",
	mixUrl: "",
	contestUrl: "",
	
	
	getTopWindow : function () {
		return (window.top) ? window.top : window;
	},
	
	goToIndex : function () {
		var topWin = KalturaHelper.getTopWindow();
		topWin.location.href = this.indexUrl;		
	},
	
	goToKShowPage : function (kshowId, kshowIdEncoded) {
		var topWin = KalturaHelper.getTopWindow();
		var url = this.viewUrl + '?kid=' + kshowId + '&remixed=true';
		
		if (kshowIdEncoded)
			url += ("&kshowIdEncoded=" + kshowIdEncoded);
			
		topWin.location.href = url;
	},
	
	showRemix: function (id) {
		jQuery.get(
			'ajax_get_mix_details.php?'+(new Date()).getTime(),
			{
				kshowId: id
			},
			function(xml) {
				$("#wrap div.details strong:first").html(jQuery('item name', xml).text())
				.siblings("span").html(jQuery('item user', xml).text())
				.siblings("div").find("div").width(Math.round(Number(jQuery('item rank', xml).text()) / 50) + "%");
				KalturaHelper.loadRanking();
			},
			'xml'
		);
		playerController.insertKShow(id, true);
		$('div.buttons .remix').attr('href', this.mixUrl + '&kid=' + id);
		$("#kshowId").val(id);
		
		$('a#contest').hide();
		$('a#rules').hide();
		KalturaHelper.loadRanking();
	},
	
	loadRanking: function() {
		KalturaHelper.rating_el = $("#info div.rating");
		KalturaHelper.rating_el.find("div")[0].rating = KalturaHelper.rating_el.find("div").css("width");
				
		$("#info div.rating b")
			.mouseover(function(){			
				var index = KalturaHelper.rating_el.find("b").index(this) + 1;
				KalturaHelper.rating_el.find("div").width((index*20)+"%");
			})
			.mouseout(function(){
				KalturaHelper.rating_el.find("div").width(KalturaHelper.rating_el.find("div")[0].rating);
			})
			.click(function() {
				// remove the events
				$(this).siblings().andSelf().unbind("mouseover").unbind("mouseout").unbind("click");
				var rank = KalturaHelper.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
							KalturaHelper.rating_el.find("div").width(KalturaHelper.rating_el.find("div")[0].rating);
							KalturaHelper.loadRanking();
						}
						else {
							setTimeout('KalturaHelper.rating_el.find("div").width("0%")', 0);
							setTimeout('KalturaHelper.rating_el.find("div").width("'+rank*20+'%")', 500);
							setTimeout('KalturaHelper.rating_el.find("div").width("0%")', 1000);
							setTimeout('KalturaHelper.rating_el.find("div").width("'+rank*20+'%")', 1500);
							setTimeout('KalturaHelper.rating_el.find("div").width("0%")', 2000);
							setTimeout('KalturaHelper.rating_el.find("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);
	}
};
