﻿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);
			}
		}

		try
		{
			var data = null;

			if (text && text.length > 0)
				eval("data = " + text);

			Unescape(data);

			return data;
		}
		catch (ex)
		{
			return null;
		}
	}

	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[]*/)
	{
		var n = arguments.length;

		while (n-- > 1)
		{
			text = text.replace(new RegExp('\\{' + (n - 1) + '\\}', 'gm'), arguments[n]);
		}

		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)); });
	}

	// use this on yor own risk
	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);
		}
	}

	this.GetQSParam = function (name, hash)
	{
		if (!hash)
			return null;

		if (!(result = hash.match(new RegExp(name + "=([^&]+)"))) || result.length != 2)
			return null;

		return result[1];
	}

	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) };
})();

//$("body")
//.ajaxStart(function() { $("*").css("cursor", "pointer"); });
//.ajaxStop(function() { $("body") = "default"; });

//Global Functions:
$(window).ajaxError(function (event, response, settings, thrownError)
{
	if (response.status != 200)
	{
		window.WaitPanel && WaitPanel.Clear();
	}

	var status = response.getResponseHeader("CustomStatus");

	if (status == null || status == "")
		return;

	switch (status)
	{
		case "SessionTimeout": window.location.href = "Login.aspx"; break;
		case "ServiceTimeout": alert(httpRequest.responseText || "RealMatch Service is experiencing problems and is currently not available."); break;
		case "Exception": response.responseText.length > 1
				? alert(response.responseText)
				: alert("There was a server error."); break;
	}
});

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, positionX, positionY)
	{
		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(positionX, positionY);
	}

	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();
	}

	this.EmptyWindow = function (dialogElement, width, height, okId, notOkId, onOk, onNotOk, onAfterClose)
	{
		if (dialogElement.length == 0)
			return;

		function OnOk()
		{
			onOk && onOk();
			onOk = null;
			GenericDialog.KillTheDarkness();
			GenericDialog.CloseDialog();
		}

		function OnNotOk()
		{
			onNotOk && onNotOk();
			onNotOk = null;

			GenericDialog.KillTheDarkness();
			GenericDialog.CloseDialog();
			OnAfterClose();

		}
		function OnAfterClose()
		{
			onAfterClose && onAfterClose();

		}



		divDialog = dialogElement;

		SetOptions(width, height);

		divDialog.find("#" + okId).click(OnOk);
		divDialog.find("#" + notOkId).click(OnNotOk);

		GenericDialog.CreateTheDarkness();

		divDialog.dialog({
			width: width,
			height: height,
			dialogClass: "RealmatchDialog",
			closeOnEscape: false,
			open: function () { $(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove(); }
		});
	}


	this.SurveryWindow = function (dialogElement, width, height, onAfterClose)
	{
		if (dialogElement.length == 0)
			return;

		function OnAfterClose()
		{
			onAfterClose && onAfterClose();

		}
		divDialog = dialogElement;

		SetOptions(width, height);


		GenericDialog.CreateTheDarkness();

		divDialog.dialog({
			width: width,
			height: height,
			dialogClass: "RealmatchDialog",
			closeOnEscape: false,
			open: function () { },
			close: function () { GenericDialog.KillTheDarkness(); OnAfterClose(); }
		});
	}

	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 (positionX, positionY)
	{
		if (divDialog == null) return;

		if (positionX == null)
			positionX = "center";
		if (positionY == null)
			positionY = top == window ? "center" : "top";

		divDialog.dialog({
			position: [positionX, positionY],
			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.find("*[id$=lnkConfirmYes]").unbind('click');
		divDialog.find("*[id$=lnkConfirmNo]").unbind('click');
		//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;
	}

	this.CreateTheDarkness = function ()
	{
		var opacity = 0.7;

		$("<div></div>")
			.attr("id", "TheDarkness")
			.css({
				position: "fixed",
				left: 0,
				top: 0,
				width: "100%",
				height: "100%",
				backgroundColor: "Black",
				transparency: "alpha(opacity=" + opacity * 100 + ")",
				opacity: opacity
			})
		.appendTo($("body").css("overflow", "hidden"));
	}

	this.KillTheDarkness = function ()
	{
		$("body").css("overflow", "auto");
		$("#TheDarkness").remove();
	}
})();                                              //GenericDialog

//Using Dialog to fix bullhorn scroll in span
function IframeScrollTop()
{
	$("<div/>").dialog({
		position: ["right", "top"],
		width: 0,
		height: 0
	}).dialog("open").dialog("close");
}
/****************** 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 **********************/
    
