/**
 * www.lalettreagricole.com
 *
 * @copyright Copyright(C) FinanceAgri, 2011
 * @author Mathieu Le Quer <mlequer@financeagri.com>
 * @package lalettreagricole
 *
 * File: /script/main.js
 */

/**
 * Return the value of the specified parameter in URI
 * or null if the parameter not found
 * @param parameterName (string)
 * @return (mixed)
 * @see js/edition.js
 * @see js/chart.js
 */
function getURLParameter(parameterName)
{
	return decodeURI((RegExp(parameterName + "=" + "(.+?)(&|$)").exec(location.search) || [,null])[1]);
}

/**
 * Convert a Date object to a string in SQL Date Format yyyy-mm-dd
 * return a empty string if there is error
 * @param date (Date) the date object
 * @return (string)
 */
function convertDateToStringInSQLFormat(date)
{
	try
	{
		var month = (date.getMonth() + 1).toString();
		if (month.length < 2)
			month = "0" + month;

		var day = date.getDate().toString();
		if (day.length < 2)
			day = "0" + day;

		return date.getFullYear() + "-" + month + "-" + day;
	}
	catch (e)
	{
		return "";
	}
}

/**
 * Convert a string representing a date in SQL date format (YYYY-MM-DD) into
 * a javascript Date object.
 * @param str (string) the source string to convert
 * @return (Date) the corresponding javascript Date object. The returned value
 * is never null, if an error occured the returned date corresponds to the
 * epoch date (unix timestamp = 0)
 */
function convertStringInSQLDateFormatToDate(str)
{
	try
	{
		if (str.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/))
		{
			str = str.split("-");
			return new Date(str[0], str[1] - 1, str[2], 0, 0, 0, 0);
		}
	}
	catch (e)
	{
	}

	return new Date(0);
}

/**
 * Convert a string representing a date in SQL date format (YYYY-MM-DD) into
 * a localized date string according to g_jqueryDateFormat format pattern.
 * @param str (string) the source SQL date string to convert
 * @return (string) the corresponding localized date string or the source
 * string if an error occured
 */
function convertSQLDateToLocalizedDate(str)
{
	try
	{
		if (str.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/))
		{
			str = str.split("-");
			return $.datepicker.formatDate(g_jqueryDateFormat, new Date(str[0], str[1] - 1, str[2], 0, 0, 0, 0),
			{
				dayNamesMin: g_dayNamesMin,
				dayNamesShort: g_dayNamesMin,
				dayNames: g_dayNamesMin,
				monthNamesShort: g_monthNames,
				monthNames: g_monthNames
			});
		}
	}
	catch (e)
	{
	}

	return str;
}

/**
 * Verify if web browser version is compatible with the web site.
 * @returns (bool) true if the web browser is compatible, else returns false
 */
function isCompatibleBrowser()
{
	var userAgent = navigator.userAgent.toLowerCase();
	$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

	var minMozillaVersion = 4;
	var minIEVersion = 8;
	var minChromeVersion = 10;
	var minSafariVersion = 5;
	var minOperaVersion = 11;

	if ($.browser.msie)
	{
		userAgent = $.browser.version;
		userAgent = userAgent.substring(0, userAgent.indexOf("."));
		return (parseInt(userAgent) >= minIEVersion);
	}
	else if ($.browser.chrome)
	{
		userAgent = userAgent.substring(userAgent.indexOf("chrome/") + 7);
		userAgent = userAgent.substring(0, userAgent.indexOf("."));
		return (parseInt(userAgent) >= minChromeVersion);
	}
	else if ($.browser.safari)
	{
		userAgent = userAgent.substring(userAgent.indexOf("safari/") + 7);
		userAgent = userAgent.substring(0, userAgent.indexOf("."));
		return (parseInt(userAgent) >= minSafariVersion);
	}
	else if ($.browser.mozilla && (navigator.userAgent.toLowerCase().indexOf("firefox") != -1))
	{
		userAgent = userAgent.substring(userAgent.indexOf("firefox/") + 8);
		userAgent = userAgent.substring(0, userAgent.indexOf("."));
		return (parseInt(userAgent) >= minMozillaVersion);
	}
	else if ($.browser.opera)
	{
		userAgent = userAgent.substring(userAgent.indexOf("version/") + 8);
		userAgent = userAgent.substring(0, userAgent.indexOf("."));
		return (parseInt(userAgent) >= minOperaVersion);
	}

	return false;
}

/**
 * @param comp (object) JQuery component to fix
 * @param refObj (object) JQuery reference component for position
 * @param offset (int) fix position offset
 */
function fixComponentPosition(comp, refObj, autoHide, offset)
{
	var top = $(document).scrollTop();
	var pos = refObj.offset();

	if (autoHide)
	{
		pos.top += refObj.outerHeight(false);
		if (top > pos.top)
		{
			pos.top = top + offset;
			if (comp.is(":visible"))
				comp.stop(true).animate(pos, "slow");
			else
				comp.css(pos).show();
		}
		else
			comp.hide();
	}
	else
	{
		if (top > pos.top)
			pos.top = top + offset;
		else
			pos.top += offset;

		if (comp.is(":visible"))
			comp.stop(true).animate(pos, "slow");
		else
			comp.css(pos).show();
	}
}

/**
 * Opens and shows the top login form
 */
function showTopLoginForm()
{
	$("html, body").stop(true).animate({scrollTop: 0}, "slow");

	$("#authButton:visible").fadeOut("slow", function()
	{
		$("#auth").fadeIn("slow", function()
		{
			$("#frmAuth input[name='userName']").focus();
		});
	});

	$("#frmAuth input[name='userName']").focus();
}

$(function()
{
	$(".fieldError").live("focus", function()
	{
		$(this).removeClass("fieldError");
	});

	$("#errorDiv:visible").delay(5000).slideUp(500);

	//Verify web browser version
	if (($("#linksBrowser").length == 1) && !isCompatibleBrowser())
	{
		$("#linksBrowser").dialog(
		{
			title: $("#dialogTitle", $(this)).text(),
			width: 800,
			modal: true,
			hide: "explode",
			resizable: false,
			open: function()
			{
				$("#dialogTitle", $(this)).remove();
			},
			close: function()
			{
				$(this).remove();
			}
		});
	}

	//Authentication div
	if ($("#auth").length == 1)
	{
		try
		{
			if (parseInt(getURLParameter("publication")) > 0)
				showTopLoginForm();
		}
		catch (e)
		{
		}

		$(".linkGoToLogin").click(function()
		{
			showTopLoginForm();
			return false;
		});

		$("#closeAuth").click(function()
		{
			$("#auth:visible").fadeOut("slow", function()
			{
				$("#authButton").fadeIn("slow");
				$("#frmForgottenPassword, #linkShowAuth").hide();
				$("#frmAuth, #linkLostPass").show();
				$(".fieldError").removeClass("fieldError");

				var email = $("#forgottenEmail");
				if (email.data("defaultDesc"))
				{
					email.val(email.data("defaultDesc"));
					email.removeData("defaultDesc");
				}

				$("input[name='userName'], input[name='password']", "#frmAuth").val("");
			});
			return false;
		});

		$("#linkLostPass").click(function()
		{
			$("#frmAuth").slideUp("slow", function()
			{
				var email = $("#forgottenEmail");
				if (email.data("defaultDesc"))
				{
					email.val(email.data("defaultDesc"));
					email.removeData("defaultDesc");
				}

				$(".fieldError").removeClass("fieldError");
				$("#frmForgottenPassword").slideDown("slow");
			});

			$("#linkLostPass").fadeOut("slow", function()
			{
				$("#linkShowAuth").fadeIn("slow");
			});
			return false;
		});

		$("#linkShowAuth").click(function()
		{
			$("#frmForgottenPassword").slideUp("slow", function()
			{
				$(".fieldError").removeClass("fieldError");
				$("input[name='userName'], input[name='password']", "#frmAuth").val("");
				$("#frmAuth").slideDown("slow", function()
				{
					$("#frmAuth input[name='userName']").focus();
				});
			});

			$("#linkShowAuth").fadeOut("slow", function()
			{
				$("#linkLostPass").fadeIn("slow");
			});
			return false;
		});

		$("#forgottenEmail").focus(function()
		{
			if (!$(this).data("defaultDesc"))
			{
				$(this).data("defaultDesc", $(this).val());
				$(this).val("");
			}
		});
	}

	$("#postLogout").click(function()
	{
		$("#frmLogout").submit();
		return false;
	});

	$(".letterHide").click(function()
	{
		$(this).parents(".box").find(".contentBox:first").stop(true, true).slideUp("slow");
		$(this).hide().siblings(".letterShow:first").show();
	});

	$(".letterShow").click(function()
	{
		$(this).parents(".box").find(".contentBox:first").stop(true, true).slideDown("slow");
		$(this).hide().siblings(".letterHide:first").show();
	});

	$(".linkQuoteContract").click(function()
	{
		var printImg = $("<img src=\"img/print.png\" border=\"0\" width=\"38\" height=\"38\" style=\"position: absolute; right: 50px; top: 0;\">");
		var label = $("<div></div>").append($("<span class=\"white textshadow\">" + $(this).html() + "</span>"))
									.append($("<a id=\"printContract\"></a>").append(printImg));

		var contract = $("#contract-" + $(this).attr("id").split("-")[1]).find("table").clone().addClass("tableContract size12");
		var dialogBox = $("<div></div>").append(contract);

		dialogBox.dialog(
		{
			title: label,
			width: 640,
			autoOpen: true,
			modal: true,
			show: "blind",
			hide: "explode",
			resizable: false,
			open: function()
			{
				var html = $(this).html();
				$("#printContract").click(function()
				{
					var windowContent = "<!DOCTYPE html>";
					windowContent += "<html>";
					windowContent += "<head>";
					windowContent += "<link rel=\"stylesheet\" type=\"text/css\" href=\"../style/main.css\" media=\"print\">";
					windowContent += "<link rel=\"stylesheet\" type=\"text/css\" href=\"../style/main.css\" media=\"screen\">";
					windowContent += "<title>www.lalettreagricole.com</title>";
					windowContent += "</head>";
					windowContent += "<body>";
					windowContent += "<div style=\"font-weight: bold; margin: 10px 0 20px 0\">" + label.find("span").html() + "</div>";
					windowContent += html;
					windowContent += "<div style=\"font-weight: bold; margin: 10px 0 20px 0\">&copy;lalettreagricole</div>";
					windowContent += "</body>";
					windowContent += "</html>";

					var printWin = window.open("", "", "width=800, height=600");
					printWin.document.open();
					printWin.document.write(windowContent);
					printWin.document.close();

					printWin.focus();
					printWin.print();

					return false;
				});
			},
			close: function()
			{
				$(this).remove();
			}
		});

		return false;
	});

	//Center the main topic if no other Topic
	if ($(".mainTopic").length == 1)
	{
		if ($(".topic", "#rightTopics").length == 0)
			$(".mainTopic").removeClass("floatL");
	}

	$(".linkpageLoader").live("click", function()
	{
		$(".pageLoading").show();
	});
});

