﻿window.General = window.General || new (function()
{
	var that = this;
	this.extend = function(to, from)
	{
		if (from == null || typeof from != "object") return from;
		if (from.constructor != Object && from.constructor != Array) return from;
		if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function ||
			from.constructor == String || from.constructor == Number || from.constructor == Boolean)
			return new from.constructor(from);

		to = to || new from.constructor();

		for (var name in from)
		{
			to[name] = typeof to[name] == "undefined" ? this.extend(null, from[name]) : to[name];
		}

		return to;
	}

	this.toJSON = function(o)
	{
		if (o == null) return null;
		if (typeof o == "string") return "'" + escape(o) + "'";
		if (typeof o != "object") return o;

		var array = [];
		var isArray = o instanceof Array;

		for (var key in o)
		{
			array.push(isArray ? this.toJSON(o[key]) : key + ":" + this.toJSON(o[key]));
		}

		return isArray ? "[" + array.toString() + "]" : "{" + array.toString() + "}";
	}

	this.fromJSON = function(text)
	{
		function Unescape(data)
		{
			if (data == null) return null;

			for (var key in data)
			{
				var item = data[key];

				if (!item) continue; //fix for bool false???
				if (item.constructor == String) data[key] = unescape(item);
				if (typeof data == "object") Unescape(item);
			}
		}

		var data = null;

		if (text && text.length > 0)
			eval("data = " + text);

		Unescape(data);

		return data;
	}

	this.scrollIntoView = function(item, scroller)
	{
		item = item.length ? item[0] : item;
		scroller = scroller && (scroller.length ? scroller[0] : scroller);

		// find parent scrollable element
		if (!scroller)
		{
			for (scroller = item.parentNode;
				scroller && scroller.offsetHeight >= scroller.scrollHeight;
					scroller = scroller.parentNode);
		}

		var ir = { top: item.offsetTop, bottom: item.offsetTop + item.offsetHeight };
		var sr = { top: scroller.scrollTop, bottom: scroller.scrollTop + scroller.clientHeight };

		// the item's top is obove the scroller's top
		if (ir.top <= sr.top)
			$(scroller).scrollTop(ir.top);

		// the item's bottom is below the scroller's bottom
		if (ir.bottom >= sr.bottom)
			$(scroller).scrollTop(ir.bottom - sr.bottom + sr.top);
	}

	this.StopEventBubbling = function(e)
	{
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	}

	this.scrollTop = function()
	{
	    //$(window.top).scrollTop(0);
	    try {
	        if (parent.window != null) { parent.window.scrollTo(0, 0); }
	    }
	    catch (ex) {
	        // Hosted in external iframe - no access to parent
	        window.scrollTo(0, 0)
	    }
	}

	this.currentCss = function(element)
	{
		element = element.jquery ? element[0] : element;

		if (element.nodeType != 1) return {};
		if (element.currentStyle) return element.currentStyle;
		if (window.getComputedStyle) return window.getComputedStyle(element, null);
	}

	this.isVisible = function(element)
	{
		for (element = element[0]; element = element.parentNode; )
		{
			if (General.currentCss(element).display == "none") return false;
		}

		return true;
	}

	this.format = function(text/*, params[]*/)
	{
		for (var n = 0, arg; (arg = arguments[n + 1]) != null; n++)
		{
			text = text.replace(new RegExp("\\{" + n + "\\}", "g"), arg);
		}

		return text;
	}

	this.find = function(array, func)
	{
		var value = func;
		var isFunc = func.constructor == Function;

		for (var n = 0, item; item = array[n]; n++)
		{
			if (isFunc ? func(item) : item == value)
				return { item: item, index: n, remove: function() { array.splice(n, 1); this.index = -1 } }
		}

		return { item: null, index: -1 };
	}

	this.indexOf = function(array, func)
	{
		var n = -1;
		var item = null;

		while ((item = array[++n]) && !func(item));

		return n;
	}

	this.accumulate = function(result, array, func)
	{
		if (arguments.length == 2) { func = array; array = result; result = null; }

		result = result || (array[0] && new array[0].constructor());

		for (var n = 0, item, value; item = array[n]; n++)
		{
			item && (value = func(result, item, n)) != null && (result = value);
		}

		return result;
	}

	this.take = function(array, func)
	{
		return this.accumulate([], array, function(result, item) { result.push(func(item)); });
	}

	this.wait = function(condFunc, readyFunc, delay)
	{
		if (!condFunc())
			setTimeout(function() { General.wait(condFunc, readyFunc, delay); }, delay || 50);
		else
			readyFunc();
	}
	
	this.needWaitAjax = function(onAfterWait)
	{
        if ($.active>0)
		{
	        General.wait(
                function(){return $.active==0;},
                function(){onAfterWait();}
            );
		    return true;
		}
		return false;
	}

	this.cloneCss = function(src, dest)
	{
		if (!(src = src.jquery ? src[0] : src) || !(dest = dest.jquery ? dest[0] : dest)) return;

		var css = General.currentCss(src);

		if ($.browser.msie)
		{
			for (var key in css) { dest.style[key] = css[key]; }
		}
		else
		{
			for (var n = 0, item; item = css.item(n++); )
			{
				dest.style.setProperty(item, css.getPropertyValue(item), css.getPropertyPriority(item));
			}
		}
	}

	function calculateBox(prefix, postfix, sides, element, isNumeric)
	{
		sides = sides || ["Top", "Right", "Bottom", "Left"];
		var css = General.currentCss(element);
		var top = css[prefix + sides[0] + postfix];
		var right = css[prefix + sides[1] + postfix];
		var bottom = css[prefix + sides[2] + postfix];
		var left = css[prefix + sides[3] + postfix];
		var result = { top: parseInt(top), right: parseInt(right), bottom: parseInt(bottom), left: parseInt(left) }

		if (isNaN(result.top)) result.top = isNumeric ? 0 : top;
		if (isNaN(result.right)) result.right = isNumeric ? 0 : right;
		if (isNaN(result.bottom)) result.bottom = isNumeric ? 0 : bottom;
		if (isNaN(result.left)) result.left = isNumeric ? 0 : left;

		return result;
	}

	function accumulate(result, func)
	{
		if (arguments.length == 1) { func = result; result = null; }

		return General.accumulate(result, this, func);
	}

	function take(func)
	{
		return General.take(this, func);
	}

	function getServerControl(id, type)
	{
		return $((type || "*") + "[id$=" + id + "]");
	}

	function visible()
	{
		return this.css("display") != "none";
	}

	function currentCss()
	{
		return General.currentCss(this);
	}

	this.ShowToolTip = function(e)
	{
		var tooltip = $('#divToolTip');
		if (!tooltip.length)
			tooltip = $("<div id='divToolTip' />").css("position", "absolute").appendTo("body");
		tooltip.empty().append($("#" + $(this).attr("tooltipCont")).clone()).css("top", e.pageY - 50).css("left", e.pageX + 30).show();
	}

	this.HideToolTip = function(e)
	{
		$("#divToolTip").hide();
	}
	
	//Returns a General DropDown with: ID, Name
    this.GetDdl = function(data, FirstOption, SelValue, name, className, id)
    {
	    if (data != null)
	    {
		    var curDdl = $("<select/>");
		    that.BuildDdlOptions(curDdl,data,FirstOption);
		    SelValue && curDdl.val(SelValue);
		    name && curDdl.attr("name", name);
		    id && curDdl.attr("id", id);
		    className && curDdl.addClass(className);
		    return curDdl;
	    }
	    else
		    return null;
    }
    
    this.BuildDdlOptions = function(ddl,data, FirstOption)
    {
        ddl.empty();
        FirstOption && ddl.append($("<option/>").attr("value", "-999").html(FirstOption));
	    for (var i = 0; i < data.length; i++)
	    {
		    var curOption = $("<option/>").attr("value", data[i].ID).html(data[i].Name);
		    ddl.append(curOption);
	    }
    }

	jQuery.format = this.format;
	jQuery.fn.visible = visible;
	jQuery.fn.take = take;
	jQuery.fn.accumulate = accumulate;
	jQuery.fn.currentCss = currentCss;
	jQuery.$ = getServerControl;
	jQuery.srcElem = function(e){return $(e.srcElement? e.srcElement : e.target)};
})(); //General

jQuery.fn.load = function(url, data, callback)
{
	if (url.constructor != String) return this._load(url);
	if (data && data.constructor == Function) { callback = data; data = null; }

	var self = this;

	$.ajax({
		url: url,
		type: "GET",
		dataType: "html",
		cache: false,
		data: data,
		complete: function(response, status)
		{
			if (status != "error")
			{
				status = response.getResponseHeader("CustomStatus");
				status = (status == null || status == "") ? "success" : "error";
			}

			if (status != "error")
				self.html(response.responseText);

			callback && self.each(callback, [response.responseText, status, response]);
		}
	});
}

$().ajaxComplete(function(evt, request, ajaxOptions)
{
	try
	{
		var status = request.getResponseHeader("CustomStatus");

		if (status == null || status == "")
			return;

		switch (status)
		{
			case "SessionTimeout": window.location.href = "Login.aspx"; break;
			case "Exception": alert(request.responseText || "There was a server error!"); break;
		}

		request.abort();
	}
	catch (ex)
	{
		// for IE, this shit crush here, when redirecting to another page while there are open requests	
	}
});

//$("body")
//.ajaxStart(function() { $("*").css("cursor", "pointer"); });
//.ajaxStop(function() { $("body") = "default"; });

//Global Functions:
$().ajaxError(function(event, request, settings, thrownError)
{
	if (request.status != 200)
	{
		window.WaitPanel && WaitPanel.Clear();
		//var msgError = "Ajax Error: Status= " + request.status + "\nMessage= " + request.statusText + "\nUrl= " + settings.url;
		//alert(msgError);
	}

	request.abort();
});

jQuery.fn.outerHTML = function(s)
{
	return s ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
}

jQuery.fn.htmlPersChange = function(html)
{
	this.html(html);
	this.replaceWith(this.clone(true));
	return this;
}

$.fn.check = function(mode)
{
	mode = mode || 'on'; // if mode is undefined, use 'on' as default
	return this.each(function()
	{
		switch (mode)
		{
			case 'on':
				this.checked = true;
				break;
			case 'off':
				this.checked = false;
				break;
			case 'toggle':
				this.checked = !this.checked;
				break;
		}
	});
};

//Global Functions END

//Generic AutoComplete:
window.GenericAutoComplete = window.GenericAutoComplete || new (function()
{
	// variables
	this.All = [];
	this.DefaultSettings =
	{
		url: null,
		data: null,
		minChars: 1,
		delay: 100,
		Events:
		{
			OnShowData: null
		}
	}
	// static function
	this.Create = function(control, settings)
	{
		return this.All[this.All.length] =
			(control[0].Controls = control[0].Controls || {}).GenericAutoComplete = new Instance(control, settings);
	}

	function Instance(control, settings)
	{
		// instance variables

		var that = this;
		var timer = null;

		this.Control = control;
		this.Settings = settings1 = General.extend(settings, GenericAutoComplete.DefaultSettings);

		// instance functions

		function Init()
		{
			control.keydown(OnKeyDown);
		}

		Init();

		function OnKeyDown(e)
		{
			switch (e.keyCode)
			{
				case 37: // left
				case 39: // right
					break;
				case 38: // up
					break;
				case 40: // down
					break;
				case 13: // return
					//control.blur();
					break;
				case 9:  // tab
					break;
				case 27:
					//HidePanel();
					break;
				default:
					timer && clearTimeout(timer);
					timer = setTimeout(function()
					{
						timer = null;

						if (control.val().length > settings.minChars)
						{
							if (settings.url)
								$.getJSON(settings.url + "?InputString=" + control.val(), DataToDom);
							//							else
							//								DataToDom(settings.data);
						}
						//						else
						//							HidePanel();
					}, settings.delay);
			} //switch
		} //OnKeyDown

		function DataToDom(data)
		{
			settings.data = data;
			settings.Events.OnShowData && settings.Events.OnShowData(settings.data);
		} //DataToDom

	} //Instance

	function Init()
	{
	}
	Init();

})(); //Generic AutoComplete


//Generic AutoComplete END


/****************** Dialog********************/
window.GenericDialog = window.GenericDialog || new (function()
{
	var divDialog = null;
	var m_OnYes = null;
	var m_OnNo = null;
	var m_OnOk = null;
	var m_objPrm = null;
	var m_widthDefault = 400;
	var m_heightDefault = 120;
	var m_width = m_widthDefault;
	var m_height = m_heightDefault;

	this.divDialog = function(val)
	{
		if (val != null) divDialog = val;

		return divDialog;
	}

	this.ConfirmDialog = function(text, OnYes, OnNo, objPrm, width, height, ShowOkCancel)
	{
		m_OnYes = OnYes;
		m_OnNo = OnNo;
		m_objPrm = objPrm;
		SetOptions(width, height);
		divDialog = $("#divConfirm");
		$("div[id$=divDialogConfirm]").show();
		$("div[id$=divWait]").hide();
		$("div[id$=divDialogOk]").hide();
		if (text) divDialog.find("*[id$=spnConfirmText]").html(text);
		divDialog.find("*[id$=lnkConfirmYes]").click(this.CloseDialog).click(_OnYes);
		divDialog.find("*[id$=lnkConfirmNo]").click(this.CloseDialog).click(_OnNo);
		if (ShowOkCancel)
		{
			divDialog.find("*[id$=lnkConfirmYes]").html(txtOk);
			divDialog.find("*[id$=lnkConfirmNo]").html(txtCancel);
		}
		this.OpenDialog();
	}
	this.OkDialog = function(text, OnOk, objPrm, width, height)
	{
		m_OnOk = OnOk;
		m_objPrm = objPrm;
		divDialog = $("#divConfirm");
		$("div[id$=divDialogConfirm]").hide();
		$("div[id$=divWait]").hide();
		$("div[id$=divDialogOk]").show();
		if (text) divDialog.find("*[id$=spnConfirmText]").html(text);
		divDialog.find("*[id$=lnkDialogOk]").click(this.CloseDialog).click(m_OnOk);
		SetOptions(width, height);
		this.OpenDialog();
	}


	this.WaitDialog = function(text)
	{
		divDialog = $("#divConfirm");
		$("div[id$=divDialogConfirm]").hide();
		$("div[id$=divDialogOk]").hide();
		$("div[id$=divWait]").show()
		SetOptions();
		if (text) divDialog.find("*[id$=spnConfirmText]").html(text);
		divDialog.dialog({ open: function() { $(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove(); } });
		this.OpenDialog();
	}

	function _OnYes()
	{
		if (m_OnYes == null)
			return;
		m_OnYes(m_objPrm);
	}
	function _OnNo()
	{
		if (m_OnNo == null)
			return;
		m_OnNo(m_objPrm);
	}
	this.OpenDialog = function()
	{
		if (divDialog == null) return;

		divDialog.dialog({
			position: ["center", top == window ? "center" : "top"],
			width: m_width > 0 ? m_width : "auto",
			height: m_height > 0 ? m_height : "auto"
		});
		divDialog.dialog("open");
	}

	this.CloseDialog = function()
	{
		if (divDialog == null) return;
		divDialog.dialog("close");
		divDialog.dialog('destroy');
	}

	function SetOptions(width, height)
	{
		if (width)
			m_width = width;
		else
			m_width = m_widthDefault
		if (height)
			m_height = height;
		else
			m_height = m_heightDefault
	}

})();            //GenericDialog
/****************** Dialog END ********************/


/****************** JCookies **********************/
jQuery.cookie = function(name, value, options)
{
	if (typeof value != 'undefined')
	{
		options = options || {};
		if (value === null)
		{
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString))
		{
			var date;
			if (typeof options.expires == 'number')
			{
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else
			{
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else
	{
		var cookieValue = null;
		if (document.cookie && document.cookie != '')
		{
			var cookies = document.cookie.split(';');
			for (var i = 0, length = cookies.length; i < length; i++)
			{
				var cookie = jQuery.trim(cookies[i]);
				if (cookie.substring(0, name.length + 1) == (name + '='))
				{
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};
/****************** JCookies **********************/