// (c) stefan.barasso@loki.sk

// default namespace for scripts
Trafo = (typeof Trafo == "undefined") ? {} : Trafo;

// variables
Trafo.oldContent = "";
Trafo.FBAK = "";
Trafo.IncludeToFeed = "";
Trafo.submitPerformed = false;

// simple universal form validation
Trafo.ValidateForm = function(formName){
	var result = true;
	var requiredFields = new Array();
	
	switch(formName)
	{
		case "video" :
			requiredFields = new Array("qt", "idc", "tg");
			if ($("#vupload_visible").val()=="" && $("#img2").val()=="")
			{
				result = false;
			}
		break;
	}
	
	for (var i=0;i<requiredFields.length;i++)
	{
		if ($("#" + requiredFields[i]).val()=="")
		{
			result = false;
			$("#" + requiredFields[i]).focus();
			break;
		}
	}
	
	if (!result)
	{
		alert("Please fill out all required fields!");
	}
	
	return result;
}




// youtube handler
Trafo.SendVideo = function(button){
	var result = false;
	button.disabled = true;
	
	if ($("#vupload_visible").val()!="")
	{
		var r = {
			video_name : $("#qt").val(),
			video_description : $("#idc").val(),
			video_tags : $("#tg").val()
		}
		
		$("body").prepend($("#modalDialog"));
		
		$("#modalDialog").jqm({
			modal: true
		}).jqmShow();		
		
	    $.get("../../ajax/YoutubeConnector.php", r, function(data) {
    		try
    		{
				eval(data);
			}
			catch(err)
			{
			}
    		if (typeof VideoResponse != "undefined")
    		{
    			$("#videoform").attr("action", VideoResponse.postUrl + "?nexturl=" + VideoResponse.nextUrl + "?guid=" + VideoResponse.guid);
    			$("#token").val(VideoResponse.tokenValue);
    			$("#videoform").submit();
    		}
    		else
    		{
    			Trafo.oldContent = $("#modalDialogInner").html(); 
    			$("#modalDialogInner").html("<h1>A connection error occured. Please try again later.</h1><p onclick='Trafo.HideDialog()' class='jqmClose'>Close</p>");
    			button.disabled = false;
    		}
    	}, "text")
		
	}
	else if ($("#img2").val()!="")
	{
		button.disabled = false;
		if (!Trafo.submitPerformed)
		{
			Trafo.submitPerformed = true;
			result = true;
		}
	}
	
	return result;
}


Trafo.HideDialog = function(button){
	$("#modalDialog").jqmHide();
	$("#modalDialogInner").html(Trafo.oldContent);
}

Trafo.ReplaceUploadValues = function(el){
	// remove fakepath string (ie fix)
	$(el).parent().find(".fakefile input").val($(el).val().replace("C:\\fakepath\\", ""));
}


Trafo.CharCounter = function(t){
	var el = $(t).parent();
	if (el[0].parentNode.className=="row")
	{
		el = el[0].parentNode;
	} 
	if ($(el).hasClass("row"))
	{
		el = $(el).find("span.ch_counter");
	}
	else if($(el).parent().parent().parent().hasClass("row"))
	{
		el = $($(el).parent().parent().parent()).find("span.ch_counter");
	}
	$(el).text($(el).attr("max") - t.value.length);
	
	var maxLength = $(el).attr("max");
	if (t.nodeName.toLowerCase() == "textarea" && t.value.length>maxLength-1)
	{
		t.value = t.value.substring(0, maxLength-1);
	}
}


// handles the login process for facebook
Trafo.FacebookLogin = function(btn){
	btn.disabled = true;
	$("#a")[0].disabled = true;
	$("#b")[0].disabled = true;

	FB.Connect.requireSession(function(){

		var fbClient = new FB.ApiClient(Trafo.FBAK);
		var userId = FB.Connect.get_loggedInUser();

		$("body").prepend($("#modalLogin"));
		$("#modalLogin").jqm({
			modal: true
		}).jqmShow();		

		FB.Connect.forceSessionRefresh(function(){
			fbClient.users_hasAppPermission ("email", function(hasPermission){
				if (!hasPermission)
				{
					FB.Connect.showPermissionDialog("email", continueExecution, true, null);
				}
				else
				{
					continueExecution();
				}
			});
		});

			
		function continueExecution()
		{
			fbClient.users_hasAppPermission ("email", function(hasPermission){
				if (hasPermission)
				{
					fbClient.users_getInfo(userId, "first_name, last_name, pic_big_with_logo, proxied_email, sex, birthday_date, timezone", function(user){
							
						user[0]["session_key"] = fbClient.get_session().session_key;
						$.get("../../ajax/FacebookReceiver.php", user[0], function(data) {
							if (data!=null && data!="")
							{
								window.location.href = window.location.href;
							}
							else
							{
				    			Trafo.oldContent = $("#modalLoginInner").html(); 
				    			$("#modalLoginInner").html("<h1>A connection error occured. Please try again later.</h1><p onclick='Trafo.HideLoginDialog()' class='jqmClose'>Close</p>");
							}
						}, "text");
	
					})
	
				}
				else
				{
		    		Trafo.oldContent = $("#modalLoginInner").html(); 
		    		$("#modalLoginInner").html("<h1>You must grand the permission to send emails for this website to proceed.</h1><p onclick='Trafo.HideLoginDialog()' class='jqmClose'>Close</p>");
				}
			});
		}

	});
	
	btn.disabled = false;
	$("#a")[0].disabled = false;
	$("#b")[0].disabled = false;
	return false;
}


// hide modal box for login
Trafo.HideLoginDialog = function(button){
	$("#modalLogin").jqmHide();
	$("#modalLoginInner").html(Trafo.oldContent);
}


// publish feeds to facebook
Trafo.PublishFacebookFeed = function(mediaType){
	
	FB.Connect.requireSession(function(){
		switch(mediaType)
		{
			case "video" :
				var att = {'media': [{'type': 'video', 'video_src': 'http://www.youtube.com/v/' + Trafo.IncludeToFeed.video_id, 'preview_img': 'http://img.youtube.com/vi/' + Trafo.IncludeToFeed.video_id + '/1.jpg'}]};
				FB.Connect.streamPublish(window.location.href, att, null, null);
			break;
			
			case "article" :
				var att = {'href': window.location.href, 'name' : window.location.href};
				FB.Connect.streamPublish('', att, null, null);
			break;
			
			case "gallery" :
				var att = {'media': [{'type': 'image', 'src': Trafo.IncludeToFeed.image_url, 'href': window.location.href}]}
				FB.Connect.streamPublish(window.location.href, att, null, null);
			break;
		}
	});

	return false;
}



Trafo.email = "email";
Trafo.passw = "p-ssword";
	
Trafo.setemail = function(){
	var o = $("input#a"); 
	
	if ($(o).val() == Trafo.email)
	{
		$(o).val("");
	}
	else if ($(o).val() == "")
	{
		$(o).val(Trafo.email);
	}
}

Trafo.setpass = function(){
	var o = $("input#b"); 
	
	if ($(o).val() == Trafo.passw)
	{
		$(o).val("");
	}
	else if ($(o).val() == "")
	{
		$(o).val(Trafo.passw);
	}
}

Trafo.functions = new Array();

// dom load
$(document).ready(function() {
	$.each($(".ch_counter"), function(){
		$(this).attr("max", $(this).text());		
	});
	$(".row:has(input[type=text]):has(span.ch_counter) input, .row:has(textarea):has(span.ch_counter) textarea").keyup(function(){
		Trafo.CharCounter(this);
	}).focus(function(){
		Trafo.CharCounter(this);
	}).focus().blur();
	
	// fix bad styled inputs, quickest way
	$("div.leftrow input[type=text]").wrap("<div class='fakeInput'></div>").css("background-image", "none");
	$(".postbox .row input[type=text]").wrap("<div class='fakeInput2'></div>").css("background-image", "none");
	
	// fix safari upload form styling
	$.browser.safari ? $.each($("input[type=file]"), function(){
		$(this).css("background-image", "none").css("background", "none");
	}) : void(0);
	
	$("#uploadmyfoto, #imgupload, #imguploadd").click(function(){
		$("body").prepend($("#modalDialog"));
		$("#modalDialog").jqm({
			modal: true
		}).jqmShow();
	});
	
	// fix for file dialog not opening in some situations
	$("input[type=file]").css("height", "30px");
	$("div.profilbox .postbox .row div. input[type=file]").mouseover(function(){$("div.profilbox .postbox .row div.fakefile input").css("background-position", "-200px -20px");}).mouseout(function(){$("div.profilbox .postbox .row div.fakefile input").css("background-position", "-200px 0px");});

});

