var RecaptchaOptions = {theme : 'custom', lang: 'en', custom_theme_widget: 'recaptcha'}; 

$(document).ready(function()
{
	if ($("#recaptcha").length)
	{
		Recaptcha.create('6LeQBsYSAAAAAF8urqfJHrM2sZKxbfPxQEVHmQuM', 'recaptcha', RecaptchaOptions);
	}
});

function CaptureForm(Form, Element)
{
	if (typeof(Element) == "undefined")
	{
		Element = null;
	}

	var Objects = new Object();

	$("input, select, textarea", (Element != null) ? $(Element) : $(Form)).each(function()
	{
		var element_id = $(this).attr("id");

		if (typeof(element_id) != 'undefined')
		{
			if (!strcasecmp(this.tagName, "input"))
			{
				if (!strcasecmp($(this).attr("type"), "file"))
				{
					
				}

				else if (!strcasecmp($(this).attr("type"), "text") || !strcasecmp($(this).attr("type"), "password") || !strcasecmp($(this).attr("type"), "hidden"))
				{
					Objects[element_id] = $(this).val();
				}

				else if (!strcasecmp($(this).attr("type"), "checkbox") || !strcasecmp($(this).attr("type"), "radio"))
				{
					Objects[element_id] = $(this).is(":checked") ? true : false;
				}
			}

			else if (!strcasecmp(this.tagName, "select"))
			{
				Objects[element_id] = $(this).val();
			}

			else if (!strcasecmp(this.tagName, "textarea"))
			{
				if ($(this).hasClass("BBCode") || $(this).hasClass("editorBBCODE"))
				{
					doCheck();
				}

				Objects[element_id] = $(this).val();
			}
		}
	});

	return Objects;
}

function LoadCities(Province, City)
{
	if (typeof(City) == 'undefined')
	{
		City = -1;
	}

	$('#cities').show();

	$("#city").html("<option>Caricamento in corso...</option>");

	$.post(Link + "/utils/AjaxHandler.php", {req: 0, province: Province}, function(data)
	{
		$(".loading_status").html("");

		var Cities = JSON.parse(data);

		$("#city").html("");

		for (var i in Cities)
		{
			$("#city").append("<option value=\"" + Cities[i]["id_citta"] + "\"" + (((City >= 1) && (City == Cities[i]["id_citta"])) ? " selected=\"selected\"" : "") + ">" + Cities[i]["citta"] + "</option>");
		}
	});
}

function SubmitForm(Sect, Element)
{
	if (typeof(Element) == "undefined")
	{
		Element = null;
	}

	if (!Loading)
	{
		$(".loading_status", Element).html(Loading5);

		Loading++;

		var Fields = JSON.stringify(CaptureForm(".general_form", Element));

		$.post(Link + "/utils/AjaxHandler.php", {req: Sect, fields: Fields}, function(data)
		{
			$(".loading_status", Element).html("");

			data = JSON.parse(data);

			var Error = false;
			var Focused = false;
			var Checked = false;

			for (var i in data)
			{
				if (i == "entire_esit") continue;

				if (!$("#ans_del", $("#" + i).parent("td").next()).length)
				{
					//if (($("#" + i).parents("td").eq(0).next("td").html() == null) && $("#" + i).parents("td").eq(0).next("td").html().length && !Checked)
					{
						$("#" + i).parents("td").eq(0).next("td").html("");
					}
				}

				else
				{
					$("#" + i).parent("td").attr("title", "");
				}

				var el = null;

				if (Element != null)
				{
					el = $(Element).parents(".general_form").eq(0);

					if ($(".form_message", $(el)).length)
					{
						$(".form_message", $(el)).html("");
					}
				}

				el = $("#" + i);

				if ($(el).hasClass("BBCode") || $(el).hasClass("editorBBCODE"))
				{
					el = $(el).parents(".richeditor").eq(0);
				}

				if (!IE)
				{
					$(el).css("-moz-box-shadow", "");
					$(el).css("-webkit-box-shadow", "");
					$(el).css("box-shadow", "");
				}

				else
				{
					$(el).css("border-color", "");
				}

				if (!data[i]["isok"])
				{
					if (!IE)
					{
						$(el).css("-moz-box-shadow", "0px 0px 5px #EE0000");
						$(el).css("-webkit-box-shadow", "0px 0px 5px #EE0000");
						$(el).css("box-shadow", "0px 0px 5px #EE0000");
					}

					else
					{
						$(el).css("border-color", "#FF0000");
					}

					if (!Focused)
					{
						$("#" + i).focus();

						Focused = true;
					}

					if (!$("#ans_del", $("#" + i).parent("td").next()).length)
					{
						$("#" + i).parents("td").eq(0).next("td").html("<img src=\"img/error16.png\" alt=\"\" title=\"" + data[i]["message"] + "\"/>");
					}

					else
					{
						$("#" + i).parent("td").attr("title", data[i]["message"]);
					}

					Error = true;
				}

				Checked = true;
			}

			if (Error)
			{
				$(".general_form td img[title]").tooltip({position: "top center", effect: 'slide'});

				if (Sect == 1)
				{
					Recaptcha.reload();
				}
			}

			else
			{
				if (typeof(data["entire_esit"]) != "undefined")
				{
					el = null;

					if (Element != null)
					{
						el = $(Element).parents(".general_form").eq(0);

						if (!$(".form_message", $(el)).length)
						{
							el.prepend("<div class=\"form_message\"></div>");
						}

						$(".form_message", $(el)).html("<strong>" + data["entire_esit"]["message"] + "</strong><div class=\"spacer2\"></div>");
					}

					else
					{
						$(".general_form").html(data["entire_esit"]["message"]);
					}

					if (data["entire_esit"]["isok"])
					{
						if (typeof(data["id"]) != "undefined")
						{
							//GoToPage(data["id"]["page"] + "&id=" + data["id"]["message"]);
						}
					}
				}

				else
				{
					//$(".general_form").html("Per ora cos&igrave;...");
				}
			}

			Loading--;
		});
	}

	return false;
}

var Upping = 0;

function UploadElement(Type, Section, Action, Upfile)
{
	var File = $("#" + Upfile).val();

	if (!File.length)
	{
		return false;
	}

	Upping++;

	if (typeof(Section) == 'undefined')
	{
		Section = "users";
	}

	if (typeof(Action) == 'undefined')
	{
		Action = "avatar";
	}

	$(".loading_status").html(Loading5 + " Caricamento in corso...");

	$.ajaxFileUpload(
	{
		url: 'utils/AjaxHandler.php?req=9&type=' + Type + '&upfile=' + Upfile + '&section=' + Section + '&action=' + Action,
		secureuri: false,
		fileElementId: Upfile,
		dataType: 'json',
		success: function (data, status)
		{
			if (typeof(data.error) != 'undefined')
			{
				if (data.error != '')
				{
					$(".loading_status").html(data.error);
				}

				else
				{
					$(".loading_status").html("Caricamento eseguito con successo!");

					if (Action == "avatar")
					{
						$("#avatar_img img").attr("src", "public/users/medres/" + data.id);
					}
				}
			}

			$("#" + Upfile).val("");

			Upping--;
		},
		error: function (data, status, e)
		{
			if (!e.length)
			{
				e = "Si &egrave; verificato un errore grave. Riprova il caricamento.";
			}

			$(".loading_status").html(e);

			$("#" + Upfile).val("");

			Upping--;
		}
	});

	return false;
}

function UploadAvatar(Section, Upfile)
{
	return UploadElement("photo", Section, "avatar", Upfile);
}

function UploadFile(Section, Upfile)
{
	return UploadElement("file", Section, "file", Upfile);
}

function Register()
{
	return SubmitForm(1);
}

function Recupera(Email)
{
	if (!Loading)
	{
		$(".loading_status").html(Loading5);

		Loading++;

		$.post(Link + "/utils/AjaxHandler.php", {req: 2, email: Email}, function(data)
		{
			$(".loading_status").html("");

			data = JSON.parse(data);

			var Return = parseInt(data["isok"]);
			var Message = data["message"];

			var Type = Return ? Good : Wrong;

			alert(Message);

			Loading--;
		});
	}
}

function Create()
{
	return SubmitForm(3);
}

function UpdateBase(Element)
{
	return SubmitForm(6, Element);
}

function UpdatePassword(Element)
{
	return SubmitForm(7, Element);
}

function UpdateAbout(Element)
{
	return SubmitForm(8, Element);
}

var AnsLimit = 9;

function DuplicateAnswer()
{
	var elements = $(".general_form .form_answer");
	var element = $(elements).eq(-1);
	var obj = $(element).clone();

	var len = $(elements).length;
	var len2 = $("label", $("td", $(element)).eq(0)).attr("for").split("wer");
	len2 = parseInt(len2[1]) + 1;

	if (len <= AnsLimit)
	{
		//Clean & Fix
		//$("td", $(obj)).eq(0).html("Risposta " + len2);
		$("input", $("td", $(obj)).eq(1)).val("");
		//$("td", $(obj)).eq(2).html("");

		$("label", $("td", $(obj)).eq(0)).attr("for", "answer" + len2);
		$("input", $("td", $(obj)).eq(1)).attr("name", "answer" + len2);
		$("input", $("td", $(obj)).eq(1)).attr("id", "answer" + len2);

		$(obj).insertAfter($(elements).eq(len - 1));
	}

	else
	{
		$("<img id=\"ans_limit\" class=\"floated_dx\" src=\"img/error16.png\" alt=\"\" title=\"Raggiunto limite di domande inseribili!\"/>").insertAfter($("#ans_add"));

		$("#ans_add").hide();

		$(".general_form td img[title]").tooltip({position: "top center", effect: 'slide'});
	}

	return false;
}

function DeleteAnswer(element)
{
	var elements = $(".general_form .form_answer");

	var len = $(elements).length;

	$("#ans_limit").remove();
	$("#ans_add").show();

	if (len <= 1)
	{
		DuplicateAnswer();
	}

	$(element).parents("tr").remove();

	return false;
}
