var Utils = {};

Utils.Dlg = function() {
	return {
		show: function(name, url, title, w, h, modal, buttons, urlCnt) {
			var dialog = $('<div id="'+name+'" style="display:hidden"></div>').appendTo('body');
			
			var opts = {width: 'auto', height: 'auto', autoOpen: false, resizable: false};
			if (w) opts.width = w;
			if (h) opts.height = h;
			if (title) opts.title = title;
			if (modal) opts.modal = true;
			if (buttons) opts.buttons = buttons;
			opts.close = function(evt, ui) {$(document.body).css({overflow: 'auto'});Utils.Dlg.destroy(name);};

			$(dialog).dialog(opts);
			if (!Utils.Navigator.IE()) $(document.body).css({overflow: 'hidden'}); 

			if (!$('#ajax-load').get(0)) {
				$(document.body).append('<div class="ajax-load" id="ajax-load">&nbsp;</div>'); 
				$('#ajax-load').css({left: ($(window).width() - $('#ajax-load').width()) / 2 + 'px', top: ($(window).height() - $('#ajax-load').height()) / 2 + 'px'});
			}
			$('#ajax-load').show();

			if (!urlCnt) {
				$(dialog).load(url,
					function (response, status, xhr) {
						Init(name);

						$('#ajax-load').hide();
						$(dialog).dialog('open');
					}
				);
			}
			else {
				$(dialog).text(url);
				$(dialog).dialog('open');

				$('#ajax-load').hide();
			}
			
			return false;
		},
		showModal: function(title, url, w, h) {
			return Utils.Dlg.show('modal', url, title, w, h, true);
		},
		close: function(name) {
			name = name ? name : 'modal';
			if ($('#'+name)) {
				$('#'+name).dialog('close');
			}
			return false;
		},
		destroy: function(name) {
			name = name ? name : 'modal';
			if ($('#'+name)) {
				$('#'+name).dialog('destroy');
				$('#'+name).remove();
			}
			return false;
		},
		showMsg: function(title, msg, w, h) {
			var buttons = {"Ok": function() {Utils.Dlg.hide();}};
			return Utils.Dlg.show('modal', msg, title, w, h, true, buttons);
		},
		addButtons: function(name, buttons) {
			name = name ? name : 'modal';
			if ($('#'+name)) {
				$('#'+name).dialog('option', 'buttons', buttons);
			}
			return false;
		}
	}
}();

Utils.Parser = function() {
	return {
		parse2: function(object, template) {
			var result = template, field;
			for (var i in object) {
				field = eval('/\%'+i+'\%/ig');
				result = result.replace(field, object[i]);
			}
			
			return result;
		},
		parse: function(object, template) {
			var result = template, fields, m, str = '';
			
			m = template.match(/\%(.+?)\%/ig);
			if (m && m.length > 0) {
				for (i=0; i<m.length; i++) {
					str = object[m[i].replace(/%/g, '')];
					result = result.replace(m[i], str);
				}
			}	
			
			return result;
		}
	};
}();

Utils.A = function() {
	return {
	
		removeKey: function(A, key, preserveKey) {
			var B = [], index = 0;
			for (var i in A) {
				if (i != key) {
					index = preserveKey ? i : B.length;
					B[index] = A[i];
				}
			}
			
			return B;
		},
		
		removeValue: function(A, value, preserveKey) {
			var B = [], index = 0;
			for (var i in A) {
				if (A[i] != value) {
					index = preserveKey ? i : B.length;
					B[B.length] = A[i];
				}
			}
			
			return B;
		},
		
		hasValue: function(A, value) {
			for (var i in A) {
				if (A[i] == value) return true;
			}
			return false;
		},
		
		pushUnique: function(A, value) {
			if (!Utils.A.hasValue(A, value)) A.push(value);
			return A;
		}
	
	}
}();

Utils.Common = function() {
  return {
		waitWindow: null,
		mainContentID: 'mainContent',
		mainContent: null,
		waitForLoad: false,

		tryJSON: function(string) {
			var json;
			try {
				json = jQuery.parseJSON(string);
			} catch(e) {
				json = { result: 'ERR',  errors: string };
			}
			return json;
		},

    extend: function() {
  		var object = {};
  		for (var i=0; i<arguments.length; i++) {
  			for (var j in arguments[i]) {
  				object[j] = arguments[i][j];
  			}
  		}
  		return object;
  	},
  	
  	trim: function(str) { 
  		var	str = str.replace(/^\s\s*/, ''),
			ws = /\s/, i = str.length;
			while (ws.test(str.charAt(--i)));
			return str.slice(0, i + 1);
    },

		radioValue: function(name) {
    	var list = document.getElementsByName(name);

    	for (var i=0; i<list.length; i++)
    		if (list[i].tagName == 'INPUT' && list[i].type == 'radio' && list[i].checked) return list[i].value;
    },

		stretchImg: function() {
  		$('img.stretch').each(function() {
				value = !this.getAttribute('maxWidth') ? '100%' : this.getAttribute('maxHeight');
				this.width > this.height ? this.style.width = value : this.style.height = value;
			});
    },

		ajaxWait: function(show) {
			Utils.Common.waitWindow = $('div.modal-wait').get(0);
			if (show && !Utils.Common.waitWindow) {
				 $(document.body).append('<div id="modal-wait" class="modal-wait">&nbsp;</div>');
				 Utils.Common.waitWindow = $('div.modal-wait').get(0);
			}

			$(Utils.Common.waitWindow).css('left', (($(window).width() - $(Utils.Common.waitWindow).width()) / 2) + 'px');
			$(Utils.Common.waitWindow).css('top', $(document.body).scrollTop() + (($(window).height() - $(Utils.Common.waitWindow).height()) / 2) + 'px');
			show ? $(Utils.Common.waitWindow).show() : $(Utils.Common.waitWindow).hide();
		},

		ajaxLoad: function(url, hash, el) {
			if (Utils.Common.waitForLoad) return false;

			Utils.Common.ajaxWait(true);
			Utils.Common.mainContent = el ? $(el) : $('#'+Utils.Common.mainContentID);

			//$(Utils.Common.mainContent).css('visibility', 'hidden');

			if (!url.match(/ajaxload/i)) url += (url.match(/\?/i) ? '&ajaxload' : '?ajaxload');
			Utils.Common.waitForLoad = true;
			$.get(url, null, function(response) {
				// Perhaps we got JSON
				var response = jQuery.parseJSON(response);

				//if (hash) location.hash = hash;
				$(Utils.Common.mainContent).html(response.html);
				Init(Utils.Common.mainContentID);

				if (response.title) document.title = response.title;
				if (response.header) $('#header').text(response.header);
				if (response.crumbs) {
					$('#crumbs').html(response.crumbs);
					Init('crumbs');
				}
				
				Utils.Common.ajaxWait(false);
				$(Utils.Common.mainContent).fadeIn();
				Utils.Common.waitForLoad = false;
			});

			return false;
		}
  };
}();

Utils.Navigator = function() {
  return {
		_ie: null,
		_opera: null,
		_ff: null,

    IE:     function() {Utils.Navigator._ie = Utils.Navigator._ie !== null ? Utils.Navigator._ie : navigator.userAgent.indexOf("MSIE") != -1;return Utils.Navigator._ie;},
    Opera:  function() {Utils.Navigator._opera = Utils.Navigator._opera !== null ? Utils.Navigator._opera : navigator.userAgent.indexOf("Opera") != -1;return Utils.Navigator._opera;},
    FF:     function() {Utils.Navigator._ff = Utils.Navigator._ff !== null ? Utils.Navigator._ff : navigator.userAgent.indexOf("Chrome") != -1 || navigator.userAgent.indexOf("Firefox") != -1;return Utils.Navigator._ff;}
  }
}();

Utils.Init = function() {
  return {
  	
    extractScripts: function(content) {
			var jsCode = '';
			
			var gmatch = content.match(/<script[^>]*>([\u0001-\uFFFF]*?)<\/script>/ig);
			if (gmatch) {
				var match = null;
				var value = '';
				for (var i=0; i<gmatch.length; i++) {
					value = gmatch[i];
					match = value.match(/<script[^>]*>([\u0001-\uFFFF]*?)<\/script>/i);
					if (match) jsCode += match[1];
				}
			}
			return jsCode;
		},
		
		loadScript: function(src) {
			var script = document.createElement('script');
			script.setAttribute('type', 'text/javascript');
			script.setAttribute('src', src);
			// InsertBefore for IE.
			// IE crashes on using appendChild before the head tag has been closed.
			$('head').get(0).insertBefore(script, head.firstChild);
		},

		loadScript: function(src) {
			var script = document.createElement('script');
			script.setAttribute('type', 'text/javascript');
			script.setAttribute('src', src);
			// InsertBefore for IE.
			// IE crashes on using appendChild before the head tag has been closed.
			$('head').get(0).insertBefore(script, head.firstChild);
		},
		
		loadStyle: function(src) {
      var ref = document.createElement("link");
      ref.setAttribute("rel", "stylesheet");
      ref.setAttribute("type", "text/css");
      ref.setAttribute("href", src);
      
      if (typeof ref != "undefined") $('head').get(0).appendChild(ref);
    },
		
		injectScript: function(jsCode) {
			if (!jsCode) return false;
			
			if (Utils.Navigator.IE()) {
				window.execScript(jsCode);
			} 
			else {
				var script = document.createElement('script');
				if (script.innerText == '') script.innerText = jsCode;
				else script.innerHTML = jsCode;
				$('head').appendChild(script);
			}
		},
    
    initValues: function(container) {
    	Utils.Init.hints(container);
    	Utils.Init.selects(container);
    	Utils.Init.checkboxes(container);
    },
    
    hints: function(container) {
    	var selector = (container ? '#'+container+' ' : '') + 'input[type=text]';
    	$(selector).each(function() {
    		if ($(this).attr('default') == 'true' || $(this).attr('default') == true) this.focus();
    		if ($(this).attr('hint')) {
    			$(this).val(!this.value ? $(this).attr('hint') : this.value);
    			
    			$(this).bind('focus', function() {
    				if (!this.value || this.value == $(this).attr('hint')) $(this).val('');
    			});
    			$(this).bind('blur', function() {
    				if (!this.value) $(this).val($(this).attr('hint'));
    			});
    		}
    	});
    },
  
    selects: function(container) {
    	var selector = (container ? '#'+container+' ' : '') + 'select';
    	$(selector).each(function() {
    		var metavalue = $(this).attr('metavalue');
    		
    		if (metavalue) {
    			$(this.options).each(function() {
    				if (this.value == metavalue) {this.selected = true;return false;}
    			});
    		}
    	});
    },
    
    checkboxes: function(container) { 
    	var selector = (container ? '#'+container+' ' : '') + 'input[type=checkbox], '
    		+ (container ? '#'+container+' ' : '') + 'input[type=radio]';
    	$(selector).each(function() {
    		var metavalue = $(this).attr('metavalue');
    		if (metavalue == this.value) this.checked = true;
    	});
    }
    
  };
}();

Utils.Info = function() {
	return {
		showErrors: function(text, show, block) {
			if (!block) block = 'errors';

			$('#'+block).html(text);
			show ? $('#'+block+'Holder').slideDown(400) : $('#'+block+'Holder').slideUp(400);
		},

		showInfo: function(text, show, hideBlock, block) {
			if (!block) block = 'info';
			if (hideBlock) Utils.Info.showErrors('', false, hideBlock);

			$('#'+block).html(text);
			show ? $('#'+block+'Holder').slideDown(400) : $('#'+block+'Holder').slideUp(400);
		}
	};
}();

var $A = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0, length = iterable.length; i < length; i++)
      results.push(iterable[i]);
    return results;
  }
};

Function.prototype.ctx = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
};

function Init(container) {
	Utils.Init.initValues(container);

	// UI Buttons
	var selector = container ? '#' + container + ' .btn' : '.btn';
	$(selector).each(function() {
		var icon = {};
		if ($(this).attr('icon')) icon.primary = 'ui-icon-' + $(this).attr('icon');
		$(this).button({icons: icon});
	});

	// Ajax link
	selector = container ? '#' + container + ' a.ajax' : 'a.ajax';
	$(selector).each(function() {
		var url = this.href;
		var el = $(this).attr('cnt') ? $('#' + $(this).attr('cnt')) : null;
		$(this).click(function() {return Utils.Common.ajaxLoad(url, this.href.replace('http://'+location.hostname, ''), $(el).get(0));});
	});

	// Errors
	if ($('#errors').text()) {$('#errorsHolder').fadeIn();}
}

$(document).ready(function() {
	Init();
});
