$(document).ready(function(){
	/**
	 * Function contains template related initialization and called upon each template load
	 */
	var initialize = function () {
		// drop-down menu
		$('#menu > ul > li > ul').each(function() { 
			this.initHeight = $(this).height();
			$(this).height(0);
		});
		
		$('#menu > ul > li').bind('mouseover', function() {
			var $ul = $(this).find('> ul');
			if ($ul.length) {
				$ul.stop(true).animate({height: $ul.get(0).initHeight}, {
					duration: ($ul.get(0).initHeight - $ul.height()) * 5
				});
			}
		});
	 
		$('#menu > ul > li').bind('mouseout', function() {
			var $ul = $(this).find('> ul');
			if ($ul.length) {
				$ul.stop(true).animate({height: 0}, {
					duration: $ul.height() * 5,
					complete: function () {
						$ul.hide();
					}
				});
			}
		});
		
		// zebra-table effect
		//$('tr:nth-child(odd).not("#calendar")').addClass('odd');
		$('tr:nth-child(odd)').not('#calendar').addClass('odd');
		$('table#calendar tr:nth-child(odd)').removeClass('odd');
		
		// unique rules for removing form field value on focus, and return it on blur
		$('input[type=text]').bind('focus',function() {
			if ($(this).val() == $(this).attr('alt')) {
				$(this).val('');
			}
			$(this).addClass('selected');
		});
		
		$('input[type=text]').bind('blur',function() {
			if ($(this).val() == '') {
				$(this).val($(this).get(0).defaultValue);
			}
			$(this).removeClass('selected');
		});
		
		$('input[type=password]').bind('focus',function() {
			$(this).addClass('selected');
		});
		
		$('input[type=password]').bind('blur',function() {
			$(this).removeClass('selected');
		});
		
		if ($.fn.colorbox) {
			$('#gallery div.image a[rel="colorbox"]').colorbox();
		}
		
		// login form dynamic vertical position
		$('#login').css('margin-top','-'+$('#login').height()/2+'px');
		
	};

	/**
	 * Global frame initialization: executed only once
	 */
	
	$('#template-switcher').bind('change',function(){
		var t = $("#template-switcher").val();
		
		// Adding `Loading...` element
		var loading = $('<div class="loading">Loading...</div>');
		if ($('body>*').length) {
			$('body>*:first').before(loading);
		} else {
			$('body').append(loading);
		}
		
		// TODO: put loading image before data is loaded...

		$.ajax({
			type: "post",
			url: "/fetch.php",
			data: "t="+ escape(t),
			dataType: "text",
			success: function(data, textStatus) {
				if (data != "ERROR") {
					// append template to body
					$('#template-frame').html(data);
					initialize(); // WARNING: depending on what operations is planned inside `Display the error` code block this function might need to be placed after `IF` clause it currently resides
				} else {
					// Display the error
				};
				// remove `Loading...` element
				loading.remove();
			}
		});

	});

	initialize();
});
