/// <reference path="jQuery.js"/>

function formatNumber(num, dec, thou, pnt, curr1, curr2, n1, n2) {
	///<summary>Formats given number to a string</summary>
	///<param name="num" optional="false" type="Number">the number to format</param>
	///<param name="dec" optional="false" type="Number" integer="true">Number of decimal places</param>
	///<param name="thou" optional="false" type="String">Thousands separator</param>
	///<param name="pnt" optional="false" type="String">Decima point (period or comma is normal here)</param>
	///<param name="curr1" optional="false" type="String">Currency symbol put before number</param>
	///<param name="curr2" optional="false" type="String">Currency symbol put after number</param>
	///<param name="n1" optional="false" type="String">Symbol put before number when negative</param>
	///<param name="n2" optional="false" type="String">Symbol put after number when negative</param>
	///<returns type="String">Formatted number</returns>
	var x = Math.round(num * Math.pow(10, dec));
	if (x >= 0) n1 = n2 = '';
	var y = ('' + Math.abs(x)).split('');
	var z = y.length - dec;
	if (z < 0) z--;
	for (var i = z; i < 0; i++) y.unshift('0');
	if (z < 0) z = 1;
	y.splice(z, 0, pnt);
	if (y[0] == pnt) y.unshift('0');
	while (z > 3) {
		z -= 3;
		y.splice(z, 0, thou);
	}
	var r = curr1 + n1 + y.join('') + n2 + curr2;
	return r;
}

function parseFloat2(value) {
	return parseFloat(value.replace(' ', '').replace(',', '.'));
}

(function($) {
	$.pageMethod = function(method, paramList, onSuccess, onError) {
		///<summary>calls $.ajax in a simplified to use form</summary>
		///<param name="method" optional="false" type="String">Page and WebMethod name ex, Page.aspx/Method</param>
		///<param name="paramList" optional="false" type="String">enclosed in {} list of method's parameters in json format</param>
		///<param name="onSuccess" optional="false" type="Function">Callback fired when ajax call completes successfully</param>
		///<param name="onError" optional="true" type="Function">Callback fired wher ajax call fails ex. Exception thrown, wrong method or parameter (value)</param>
		$.ajax({
			type: "POST",
			url: method,
			contentType: "application/json; charset=utf-8",
			data: paramList,
			dataType: "json",
			success: onSuccess,
			error: onError ? onError : function(r, status, errorThrown) {
				var args = "{'status':'" + status + "','error':'" + errorThrown + "','method':'" + method + "','args':'" + paramList + "','href':'" + window.location + "','response':'" + escape(r.responseText) + "'}";
				$.pageMethod("Default.aspx/LogError", args, function() { }, function() { });
				alert("Wystąpił błąd w trakcie przetwarzania zapytania");
			}
		});
	};

	$.cookieBoolGet = function(name, defaultValue) {
		///<summary>Gets boolean cookie value. if key not found returns defaultValue</summary>
		///<param name="name" optional="false" type="String">cookie Key</param>
		///<param name="defaultValue" optional="false" type="String">default value returned if key not found</param>
		var val = $.cookie(name);
		if (val == null) val = defaultValue;
		else val = val == 1 ? true : false;
		return val;
	};
	$.cookieBoolSet = function(name, value) {
		///<summary>Sets boolean value in cookie.</summary>
		///<param name="name" optional="false" type="String">cookie Key</param>
		///<param name="value" optional="false" type="String">value to set</param>
		$.cookie(name, value ? 1 : 0);
	};
	$.cookieIntGet = function(name, defaultValue) {
		///<summary>Gets integer cookie value. if key not found returns defaultValue</summary>
		///<param name="name" optional="false" type="String">cookie Key</param>
		///<param name="defaultValue" optional="false" type="Number">default value returned if key not found</param>
		var val = $.cookie(name);
		if (val == null) val = defaultValue;
		return val;
	};

	$.fn.isInt = function(onTrue, onFalse) {
		///<summary>Checks if val() or text() is an integer value.</summary>
		///<param name="onTrue" optional="true" type="Function">Callback fired for each item that returns true</param>
		///<param name="onFalse" optional="true" type="Function">Callback fired for each item that returns false</param>
		///<returns type="Boolean">logical product of all items results</returns>
		var ok = true;
		this.each(function() {
			var $t = $(this);
			var x = $t.val();
			if (!x)
				x = $t.text();

			var y = parseInt(x);

			if (!isNaN(y) && y >= 0 && x == y && x.toString() == y.toString())
				if (onTrue) onTrue.call($t);
			else {
				if (onFalse) onFalse.call($t);
				ok = false;
			}
		});
		return ok;
	};

	$.fn.matches = function(regex, onTrue, onFalse, message) {
		///<summary>Checks if val() or text() matches given regex pattern</summary>
		///<param name="regex" optional="true" type="Regex">Regex exression used to test items' values.</param>
		///<param name="onTrue" optional="true" type="Function">Callback fired for each item that returns true</param>
		///<param name="onFalse" optional="true" type="Function">Callback fired for each item that returns false</param>
		///<param name="message" optional="true" type="String">Message passed to onFalse callback as a parameter</param>
		///<returns type="Boolean">logical product of all items results</returns>
		var ok = true;
		this.each(function() {
			var $t = $(this);
			var x = $t.val();
			if (x == "")
				x = $t.text();

			if (x != "" && regex.test(x)) {
				if (onTrue) onTrue.call($t);
			}
			else {
				if (onFalse) onFalse.call($t, message);
				ok = false;
			}
		});
		return ok;
	};

	$.fn.tooltip = function(remove) {
		///<summary>Adds an onHover tooltip to each element. Attribure 'rel' is used for tooltips message.</summary>
		///<param name="remove" optional="true" type="Boolean">if true the tooltip is removed.</param>
		///<returns type="jQuery"/>

		var xOffset = -10;
		var yOffset = 10;

		return this.each(function() {
			$(this).unbind('mouseenter.tooltip').unbind('mouseleave.tooltip').unbind('mousemove.tooltip');

			if (remove)
				return;

			$(this).bind('mouseenter.tooltip', onMouseEnter).bind('mouseleave.tooltip', onMouseLeave).bind('mousemove.tooltip', onMouseMove);
		});

		function onMouseEnter(e) {
			var t = $(this);

			this.top = (e.pageY + yOffset);
			this.left = (e.pageX + xOffset);
			var p = t.after('<p class="ui-tooltip ui-state-default ui-corner-all">' + t.attr('rel') + '</p>').next('p');
			p.css({ top: this.top + "px", left: this.left + "px" }).show();
			setTimeout(function() { p.hide().remove(); }, 3000);
		};
		function onMouseLeave(e) {
			$(this).next('p').hide().remove();
		};
		function onMouseMove(e) {
			this.top = (e.pageY + yOffset);
			this.left = (e.pageX + xOffset);
			$(this).next('p').css({ top: this.top + "px", left: this.left + "px" });
		};
	};

	$.fn.onSubmit = function(button) {
		///<summary>Binds [Enter] key press in element (textbox preferably) with button's click event</summary>
		///<param name="button" optional="false" type="jQuery">Element whose click event is fired when Enter is pressed while target has focus</param>
		///<returns type="jQuery"/>
		return this.each(function() {
			$(this).unbind('keypress.onSubmit').bind('keypress.onSubmit', function(e) {
				var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
				if (keyCode == 13) {
					$(button[0]).click();
					return false;
				} else
					return true;
			});
		});
	};

	$.fn.onCancel = function(button) {
		///<summary>Binds [Esc] key press in element (textbox preferably) with button's click event</summary>
		///<param name="button" optional="false" type="jQuery">Element whose click event is fired when Esc is pressed while target has focus</param>
		///<returns type="jQuery"/>
		return this.each(function() {
			$(this).unbind('keypress.onCancel').bind('keypress.onCancel', function(e) {
				var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
				if (keyCode == 27) {
					$(button[0]).click();
					return false;
				} else
					return true;
			});
		});
	};

	$.fn.enterAsTab = function() {
		///<summary>Binds [Enter] key press in element with passing focus in stead of submitting form</summary>
		///<returns type="jQuery"/>
		return this.keypress(function(e) {
			var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
			if (keyCode == 13) {
				$(this).next().focus();
				return false;
			}
			else
				return true;
		});
	};

	$.fn.checked = function(value) {
		///<summary>Returns whether element is checked/sets 'checked' value</summary>
		///<param name="value" optional="true" type="Boolean">value to set (true/false)</param>
		///<returns type="jQuery/Boolean"/>
		if (value === undefined) {
			var val = true;
			this.each(function() {
				val &= $(this).attr('checked');
			});
			return val;
		}
		else {
			return this.each(function() {
				if (value)
					$(this).attr('checked', 'checked');
				else
					$(this).removeAttr('checked');
			});
		}
	};

	$.fn.enabled = function(value) {
		///<summary>Returns whether element is enabled/sets 'disabled' value</summary>
		///<param name="value" optional="true" type="Boolean">value to set (true/false)</param>
		///<returns type="jQuery/Boolean"/>
		if (value === undefined) {
			var val = false;
			this.each(function() {
				val |= $(this).attr('disabled');
			});
			return !val;
		}
		else {
			return this.each(function() {
				if (!value)
					$(this).attr('disabled', 'disabled');
				else
					$(this).removeAttr('disabled');
			});
		}
	};
})(jQuery);

String.prototype.trim = function() {
	///<summary>Removes extra spaces and non-written characters from string</summary>
	///<returns type="String"/>
	return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))
};
String.prototype.startsWith = function(str) {
	///<summary>Checks if string begins with given string</summary>
	///<returns type="Boolean"/>
	return (this.match("^" + str) == str)
};
String.prototype.endsWith = function(str) {
	///<summary>Checks if string ends with given string</summary>
	///<returns type="Boolean"/>
	return (this.match(str + "$") == str)
};
