var I4App = {};

if (jQuery === undefined)
{
	jQuery = $ = {};
}

if (!window.console || !console.firebug)
{
	!function(w) { var fn, i = 0;
		if (!w.console) w.console = {};
		fn = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'getFirebugElement', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'notifyFirebug', 'profile', 'profileEnd', 'time', 'timeEnd', 'trace', 'warn'];
		for (i = 0; i < fn.length; ++i) if (!w.console[fn[i]]) w.console[fn[i]] = function() {};
	}(window);
}

(function($, window, document, _undefined)
{
	/**
	 * Extends jQuery core
	 */
	jQuery.extend(true,
	{
		context: function(fn, context)
		{
			if (typeof context == 'string')
			{
				var _context = fn;
				fn = fn[context];
				context = _context;
			}
			return function() { return fn.apply(context, arguments); };
		},

		setCookie: function(name, value, expires)
		{
			console.log('Set cookie %s=%s', name, value);

			document.cookie = I4App._cookieConfig.prefix + name + '=' + encodeURIComponent(value)
				+ (expires === undefined ? '' : ';expires=' + expires.toGMTString())
				+ (I4App._cookieConfig.path  ? ';path=' + I4App._cookieConfig.path : '')
				+ (I4App._cookieConfig.domain ? ';domain=' + I4App._cookieConfig.domain : '');

			return value;
		},
		getCookie: function(name)
		{
			var expr, cookie;

			expr = new RegExp('(^| )' + I4App._cookieConfig.prefix + name + '=([^;]+)(;|$)');
			cookie = expr.exec(document.cookie);

			if (cookie)
			{
				return decodeURIComponent(cookie[2]);
			}
			else
			{
				return null;
			}
		},
		deleteCookie: function(name)
		{
			console.info('Delete cookie %s', name);

			document.cookie = I4App._cookieConfig.prefix + name + '='
				+ (I4App._cookieConfig.path  ? '; path=' + I4App._cookieConfig.path : '')
				+ (I4App._cookieConfig.domain ? '; domain=' + I4App._cookieConfig.domain : '')
				+ '; expires=Thu, 01-Jan-70 00:00:01 GMT';

			return null;
		}
	});

	$.extend(I4App,
	{
		_cookieConfig: { path: '/', domain: '', 'prefix': 'i4_'},
		_swfConfig: {
			version: '9.0.0', expressInstall: '/_swf/expressInstall.swf',
			params: {
				menu: "false",
				allowfullscreen: "false",
				wmode: "transparent",
				scale: "showall"
			}
		},
		_ajaxProgress: false,
		_ajaxActive: 0,
		overlayWindow: {},
		form:{},
		phrases: {},

		init: function()
		{
			var dStart = new Date();
			I4App.activate(document);
			I4App.AjaxProgress();
			console.info('I4App.init() time: %d ms', new Date() - dStart);
		},

		register: function(selector, fn, event)
		{
			if (typeof fn == 'string')
			{
				var className = fn;
				fn = function(i)
				{
					I4App.create(className, this);
				};
			}

			$(document).bind(event || 'I4AppActivateHtml', function(e)
			{
				$(e.element).find(selector).each(fn);
			});
		},

		create: function(className, element)
		{
			var $element = $(element),
				i4Obj = window,
				parts = className.split('.'), i;

			for (i = 0; i < parts.length; i++) { i4Obj = i4Obj[parts[i]]; }

			if (typeof i4Obj != 'function')
			{
				return console.error('%s is not a function.', className);
			}

			if (!$element.data(className))
			{
				$element.data(className, new i4Obj($element));
			}

			return $element.data(className);
		},

		activate: function(element)
		{
			console.group('I4App.activate(%o)', element);
			$(element).trigger('I4AppActivate').removeClass('__I4AppActivator');
			$(element).find('noscript').empty().remove();
			$(document).trigger({ element: element, type: 'I4AppActivateHtml' });
			console.groupEnd();
			return element;
		},

		embedSWF: function(url, replaceId, width, height, flashvars, params, attributes, callback, version, exInstUrl)
		{
			if (swfobject === undefined)
			{
				console.error('swfobject not defined');
				return;
			}

			if (flashvars === undefined) flashvars = {};
			params =  (params === undefined) ? I4App._swfConfig.params : $.extend(I4App._swfConfig.params, params);
			if (attributes === undefined) attributes = {};
			if (version === undefined || version == '') version = I4App._swfConfig.version;
			if (exInstUrl === undefined || exInstUrl == '') exInstUrl = I4App._swfConfig.expressInstall;

			swfobject.embedSWF(url, replaceId, width, height, version, exInstUrl, flashvars, params, attributes, callback);
		},

		openExternalLink: function(url)
		{
			var newWin = window.open(url,'blank'); newWin.focus(); return false;
		},

		loadAndShow: function(url)
		{
			$.get(url, I4App.showOverlay);
		},

		showOverlay: function(data)
		{
			I4App.overlayWindow.showWindow('info', data);
		}
	});
	
	$.extend(I4App.overlayWindow,
	{
		showWindow : function(type, content)
		{
			var overlay = $('#I4AppInfoWindow'),
				top = 60 + $(window).scrollTop(),
				left = $(window).width() / 2 - overlay.width()/2,
				mask = $('#I4AppMask');
			overlay.css({top: top, left: left});
			overlay.children('.content').html(content).find('h1').hide();
			mask.css({
				opacity:0.7,
				width:$(document).width(),
				height:$(document).height()
			});

			I4App.activate(overlay);

			mask.show();
			overlay.show();


		},
		closeWindow : function()
		{
			$('#I4AppInfoWindow').hide().children('.content').html('');
			$('#I4AppMask').hide();
//			$('#I4AppInfoWindow a.windowCloser').hide();
		},

		onBrowserResize : function()
		{
			var overlay = $('#I4AppInfoWindow'),
				mask = $('#I4AppMask');

			overlay.css({
				top: 60 + $(window).scrollTop(),
				left: $(window).width() / 2 - overlay.width()/2
			});

			mask.css({
				width:$(document).width(),
				height:$(document).height()
			});
		}
	});

	$.extend(I4App.form,
	{
		validateEmail: function(value)
		{
			var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
 			return value.match(re)
		},

		getValue: function($form, selector)
		{
			var element = $form.find(selector);
			if (element !== undefined)
			{
				return jQuery.trim(element.val());
			}
			return undefined;
		},

		confirmForm: function($form)
		{
			$form.submit(function(e){
				e.preventDefault();
				var valid = true;
				$form.find('.required').each(function(){
					// todo: add support for checkboxes and selectboxes
					var elm = $(this),
						errLabel = elm.parent().find('label.error');

					if (errLabel.length > 0)
					{
						errLabel.remove();
					}

					if (jQuery.trim(elm.val()) == '')
					{
						valid = false;
						elm.parent().append('<label class="error">Položka nesmí být prázdná.</label>')
					}
				});

				if (!valid)
				{
					return;
				}

				$.post(
					$form.attr('action'),
					$form.serialize(),
					function(data){
						$form.parent().html(data);
						I4App.activate('#I4AppInfoWindow .content');
						$('#I4AppInfoWindow a.windowCloser').show();
					}
				);
			});
		}
	});

	I4App.AjaxProgress = function()
	{
		var indicator = null,

		showIndicator = function()
		{
			$('.progressIndicator').addClass('inProgress');
			if (!indicator)
			{
				indicator = $('<div id="ajaxProgress" class="i4Overlay"><div class="content"><span class="close" /></div></div>').appendTo('body');
				indicator.css('top', $(window).scrollTop());
			}
			indicator.show();
		},
		
		hideIndicator = function()
		{
			$('.progressIndicator').removeClass('inProgress');
			if (indicator)
			{
				indicator.hide();
			}
		};

		$(document).bind(
		{
			ajaxStart: function(e)
			{
				I4App._ajaxProgress = true; I4App._ajaxActive++;
				showIndicator();
			},

			ajaxStop: function(e)
			{
				I4App._ajaxProgress = false; (I4App._ajaxActive > 0) ? I4App._ajaxActive--: 0;
				hideIndicator();
			}
		});

		$(document).bind('scroll', function(e)
		{
			if (indicator)
			{
				indicator.css('top', indicator.top + $(window).scrollTop());
			}
		});
	};
	
	

	I4App.ExternalLinkOpener = function($link)
	{
		$link.click(function(e)
		{
			e.preventDefault();
			I4App.openExternalLink($(this).attr('href'));
		});
	};

	I4App.OverlayOpener = function($link)
	{
		$link.click(function(e)
		{
			e.preventDefault();
			I4App.loadAndShow($(this).attr('href'));
		});
	};

	I4App.WindowCloser = function($obj)
	{
		$obj.click(function(e){
			e.preventDefault();
			I4App.overlayWindow.closeWindow();
		});
	};

	/**
	 * Init listeners
	 * Example I4App.register('jquery selector', 'I4App.Object');
 	 */

	I4App.register('a.externalLink', 'I4App.ExternalLinkOpener');
	I4App.register('a.overlayOpener', 'I4App.OverlayOpener');
	I4App.register('.windowCloser', 'I4App.WindowCloser');
	I4App.register('.overlayFormConfirm', 'I4App.form.confirmForm');

	/**
	 * I4App bootstrap
	 */
	$(function()
	{
		I4App.init();
	});

}(jQuery, this, document));
