/**
 * ITBrix.js
 * 
 * Bootstraps and extensions needed for the system.
 *
 * @author 	Zhekov, Ivan (ITBrix) <http://wordframe.net>
 */
(function (window, document, $) {


	// jQuery is a must!
	if (!$) return;


	/**
	* Creates namespace from the specified identifier
	* Derived from namespacedotjs <http://code.google.com/p/namespacedotjs/>
	*
	* @param {String} identifier The namespace string
	*/
	function Namespace(identifier) {
		var cursor = window;

		if (identifier) {
			var spaces = identifier.split(".");
			for (var i = 0; i < spaces.length; i++) {
				if (!cursor[spaces[i]]) cursor[spaces[i]] = {};
				cursor = cursor[spaces[i]];
			}
		}
	}
	window.Namespace = Namespace;


	/**
	*/
	var Prototype = Prototype || {};
	Prototype.create = function () { }




	/*----------------------------------------------------------------------------*/




	/**
	* Resource manager
	*/
	var ResourceManager = {

		registerStyle: function (href, media) {

			if (!href) return;

			var link = document.createElement("link");
			link.type = "text/css";
			link.rel = "stylesheet";
			link.href = href;
			link.media = media || "screen, projection";

			document.getElementsByTagName("head")[0].appendChild(link);

		},

		registerStyleBlock: function (content) {

			if (!content) return;

			var style = document.createElement("style");
			style.type = "text/css";
			style.innerHTML = content;

			document.getElementsByTagName("head")[0].appendChild(style);
		},

		registerScript: function (src) {

			if (!src) return;

			var script = document.createElement("script");
			script.type = "text/javascript";
			script.src = src;

			document.getElementsByTagName("head")[0].appendChild(script);

		},

		registerScriptBlock: function (content) {

			if (!content) return;

			var script = document.createElement("script");
			script.type = "text/javascript";
			script.innerHTML = content;

			document.getElementsByTagName("head")[0].appendChild(style);
		}

	}



	Namespace("ITBrix");
	ITBrix.ResourceManager = ResourceManager;




	/*----------------------------------------------------------------------------*/




	/**
	* simulateClick
	*/
	function simulateClick(link) {

		if (!link) return;

		$(link).click();

		if (link.href && link.href.indexOf("javascript:") == 0) {

			var script = link.href.substring(11);

			// Case 1: <a href="javascript:...">...</a>
			//console.log("simulateClick: Case 1");
			if (script.indexOf("WebForm") == 0) {
				eval(unescape(script));
			} else {
				eval(script);
			}

		} else if (link.onclick) {

			// Case 2: <a onclick="...">...</a>
			//console.log("simulateClick: Case 2");
			eval(link.onclick);

		}
	}




	/*----------------------------------------------------------------------------*/




	/**
	* onImageIconLinkKeyPress
	*/
	function onImageIconLinkKeyPress(event) {

		if (event.which == 32)
			simulateClick(this);

	}


	$(document).delegate("a.image-icon", "keypress", onImageIconLinkKeyPress);




	/*----------------------------------------------------------------------------*/




	/**
	* xThrobberClick
	*/
	function xThrobberClick(event) {

		var classNames = [];

		//console.log("xThrobberClick");

		//event.preventDefault();

		if (!($(this).children(".image-icon")[0])) {

			// Case 1: .x-throbber < :not(.image-icon)
			//console.log("case 1");
			classNames = $.grep(this.className.split(" "), function (n, i) {
				//console.log(n.indexOf("icon"));
				return n.indexOf("icon") != 0;
			});
			//console.log(classNames.join(" "));
			this.className = classNames.join(" ") + " image-icon icon-throbber";

		} else {

			// Case 2: .x-throbber .image-icon
			//console.log("case 2");
			$(this).children(".image-icon").each(function () {
				classNames = $.grep(this.className.split(" "), function (n, i) {
					//console.log(n.indexOf("icon"));
					return n.indexOf("icon") != 0;
				});
				//console.log(classNames.join(" "));
				this.className = classNames.join(" ") + " icon-throbber";
			});

		}
	}


	$(document).delegate(".x-throbber", "click", xThrobberClick);




	/*----------------------------------------------------------------------------*/




	/**
	* xTogglerClick
	*/
	function xTogglerClick(event) {

		var 
		xToggler = this,
		xDetails, parent;

		if (xToggler.__xDetails) {
			xDetails = xToggler.__xDetails;
		}

		if (!xDetails && xToggler.href && xToggler.href.indexOf("#") > -1) {

			// Case 1: xDetails is the target of the HREF attribute
			//console.log("case 1");
			xDetails = document.getElementById(xToggler.href.substring(xToggler.href.indexOf("#") + 1));

		}

		if (!xDetails) {
			parent = $(xToggler).closest(".x-has-details")[0];

			if (!parent) {

				// Case 2: xDetails is the first sibling
				//console.log("case 2");
				xDetails = $(xToggler).siblings(".x-details")[0];

			} else {

				// Case 3: xDetails is the first descendendant / niece
				//console.log("case 3");
				xDetails = $(parent).find(".x-details")[0];

			}
		}

		if (xDetails) {
			this.__xDetails = xDetails;
			$(xDetails).toggle();
		}

		event.preventDefault();
	}


	$(document).delegate(".x-toggler", "click", xTogglerClick);




	/*----------------------------------------------------------------------------*/
	/**
	* findAndSubmitDefaultButton
	*/
	function onFormFieldKeyPress(event) {

		var elem = $(this).get(0);
		if (elem == null)
			return;

		if (elem.tagName.toLowerCase() == "textarea")
			return;

		//console.log("onFormFieldKeyPress");
		//console.log(event.which);

		if (event.keyCode == 13) {
			findAndSubmitDefaultButton(event, elem);
		}
	}


	function findAndSubmitDefaultButton(event, origin) {
		if (!origin)
			return;

		var parent = $(origin).parents(".x-has-default-button")[0], target, defaultButtons;

		if (parent) {

			// Case 1: origin and target reside in the same parent;
			//console.log("findAndSubmitDefaultButton: case 1");
			target = $.grep($(parent).find(".x-default-button"), function (button) {
				return $(button).parents(".x-has-default-button")[0] == parent;
			})[0];

		}

		if (!target) {
			parent = $(origin).parents("[onkeypress*='WebForm_FireDefaultButton']")[0];

			if (parent) {

				target = parent.onkeypress.toString();
				target = target.replace("&#39;", "'", "g").replace('"', "'", "g");
				target = target.substring(target.indexOf("(event, '") + 9);
				target = target.substring(0, target.indexOf("'"));

				//re.test(string)
				if (/[^A-Za-z0-9_\-]/.test(target)) {
					target = null;
				} else {
					target = document.getElementById(target);
				}
			}
		}

		// The the origin and target must eventually reside in the same parent
		// If not, resolve to .net in built functionallity
		/*if (!target) {

		// Case 2: origin and target do not reside in the same parent;
		//console.log("findAndSubmitDefaultButton: case 2");
		target = $(document.body).find(".x-default-button:not(.x-has-default-button .x-default-button)")[0];

		}*/

		if (target) {
			event.preventDefault();
			 setTimeout(function() {
			 	simulateClick(target);
			   }, 0);

			
		}

	}


	$(document).delegate(".text", "keydown", onFormFieldKeyPress);

	/*----------------------------------------------------------------------------*/




	/**
	* Autofocus fallback
	*/
	if (!("autofocus" in document.createElement("input"))) {

		$(document).ready(function () {

			var autofocusField = $("input[autofocus], textarea[autofocus], select[autofocus]")[0];

			if (autofocusField && autofocusField.focus) {
				window.setTimeout(function () { autofocusField.focus() }, 100);
			}

		});

	}




	/*----------------------------------------------------------------------------*/




	/**
	* Placeholder text fallback
	*/
	if (!("placeholder" in document.createElement("input"))) {

		$(document).ready(function () {

			$("input[placeholder]").each(function () {

				if (this.value == "") {

					this.value = $(this).attr("placeholder");

				}

			});

		});

		function placeHoderFieldFocus(event) {

			if (this.value && this.value == $(this).attr("placeholder")) {
				this.value = "";
			}

		}
		function placeHoderFieldBlur(event) {
			if (this.value == "") {
				this.value = $(this).attr("placeholder");
			}
		}


		$(document).delegate("input[placeholder]", "focus", placeHoderFieldFocus);
		$(document).delegate("input[placeholder]", "blur", placeHoderFieldBlur);

	}




	/*----------------------------------------------------------------------------*/




	/**/




})(window, document, jQuery, undefined)
