var mod;
var noEsc = 0;

fixOffset = function(){
	if(!$('#modalContainer').length) return;
	if($.browser.msie){
		$('#modalContainer').css('top', (document.documentElement.scrollTop || document.body.scrollTop)+($(window).height()-$('#modalContainer').height())/2+'px');
		$('#modalContainer').css('left', (document.documentElement.scrollLeft || document.body.scrollLeft)+($(window).width()-$('#modalContainer').width())/2+'px');
	} else {
		$('#modalContainer').css('top', ($(window).height()-$('#modalContainer').height())/2+'px');
		$('#modalContainer').css('left', ($(window).width()-$('#modalContainer').width())/2+'px');
	}
};

function getFlashMovieObject(movieName) {
	if (window.document[movieName]) return window.document[movieName];
	if (navigator.appName.indexOf("Microsoft Internet")==-1)if (document.embeds && document.embeds[movieName])return document.embeds[movieName];
		else return document.getElementById(movieName);
}

function showModal(hash, width, height) {
	height = height || 0; 
	var h = $('#modal').innerHeight();
	if(h > height) height = h;
	// clearing forms in the window
//	$('#modal form').clearForm();
	mod = $('#modal').modal({containerCss:{width:width+'px'/*,height:height+'px'*/},close:false});
	$('#modalContainer input[type=text]:first').focus();
}

function setModalMessage(typ, msg) {
	if($('#modal div.msg').length > 0) {
		$('#modal div.msg').removeClass('error, info').addClass(typ).html(msg);
	} else {
		$('#modal form').before('<div class="msg '+typ+'">'+msg+'</div>');
	}
	/*
	var h = $('#modal').innerHeight();
	if(parseInt($('#modalContainer').css('height')) < h) {
		$('#modalContainer').css('height', h+'px')
	}
	*/
}

function initModals(path) {
	path = path || 'a.lmodal';
	// initialising loading of modal window for all a.lmodal
	$(path).click(function(e){
		if($(this).attr('rel').length > 1) {
			e.preventDefault();
			loadModal($(this).attr('rel'), this);
		}
	});
}

function fixBoxes() {
	// fixing heights of boxes
	$('div.box:not(.nofix) div.c2').each(function(i){
		var par = $(this).parent().parent();
		var box = $(this).parent();
		var is_btext = box.hasClass('btext');
		var is_blist = box.hasClass('blist');
		var is_notop = box.hasClass('notop');
		$(this).css({height:(par.height()-55-(is_blist?2:0)-(is_btext?14:0)-(is_notop?0:13))+'px'});
	});
}

$(document).ready(function(){
	$(window).scroll(fixOffset).resize(fixOffset);
	
	initModals();
	
	$(window).keydown(function(e){
		if(noEsc) return;
		if(e.keyCode == 27) {
			if(mod) mod.close();
		}
	});
	$.datepicker.setDefaults({showOn: 'button', buttonImageOnly: true, buttonImage: '/img/calendar.gif'});
	$('input.idate').datepicker({beforeShow: customRange});

	function customRange(input) {
		var tmp = input.name;
		tmp = tmp.substr(0,tmp.indexOf('['));
	    return {minDate: (input.name.indexOf('[to]') >= 0 ? $("input.idate[name='"+tmp+"[from]']").datepicker('getDate') : null), 
	        maxDate: (input.name.indexOf('[from]') >= 0 ? $("input.idate[name='"+tmp+"[to]']").datepicker('getDate') : null)}; 
	}
	
	fixBoxes();  
	
	// checking if message present
	if($('.msgmain:not(.nothide)').length > 0) {
		// if yes - then after few seconds deleting it
		$.timer(2000, function(timer){
			$('.msgmain:not(.nothide)').hide('slow', function(){
				$(this).remove();
			});
			timer.stop();
		});		
	}

});

function showWaiting(elem) {
	return;
	//elem = $('body a:first');
	var tmp = $('#all').prev();//$('body a:first');//elem.children();
	if(!tmp.is('.waiting')) {
		tmp = $(elem).offset();
		$('#all').before('<img class="waiting" src="/img/waiting.gif" style="left:'+(tmp.left+$(elem).innerWidth()/2-10)+'px;top:'+tmp.top+'px;" />');
	}
}

function hideWaiting(elem) {
	return;
	var tmp = $('#all').prev();
	if(tmp.is('.waiting')) {
		tmp.remove();
	}
}


(function ($) {
	$.loadWait = function(options) {
		return $.loadWait.init(null, options);
	}
	$.fn.loadWait = function(options) {
		return $.loadWait.init(this, options);
	}
	
	$.loadWait.defaults = {
		onDone: null,
		url: '',
		params: {},
		elem: null
	}
	
	$.loadWait.init = function(elem, options) {
		var opts = null;
		elem = elem || null;
		opts = $.extend({}, $.loadWait.defaults, options);
		
		if(!opts.url) return;
		
		showWaiting(opts.elem);
		jQuery.ajax({
			url: base_url+opts.url,
			type: 'POST',
			data: opts.params,
			dataType: 'json',
			success: function(data) {
				hideWaiting(opts.elem);
				if(data.status == 'ok'){
					if(elem != null) {
						fixBoxes();  
						$(elem).html(data.content);
					}
					if(opts.onDone != undefined)opts.onDone.apply(this, [data] );
				} else {
					if(data.content != '' && data.content != undefined) {
						alert(data.content);
					} else {
						alert('An error has occurred. Please try again.');
					}
				}
			},
			error: function(data) {
				hideWaiting(opts.elem);
			}
		});
		
		return this;
	}
	
})(jQuery);

function loadModal(url, elem) {
	elem = elem || null;
	noEsc = $(elem).hasClass('noesc');  
	
	$.loadWait({
		url: '/ajax'+url,
		elem: elem,
		onDone: function(data) {
			$('#modal').html(data.content);
			showModal(url, data.width?data.width:400);
		}
	});
}

function initSuggest(nm, aurl) {
	$("#i"+nm).suggest(aurl, {
		minChars: 1,
		isReplace: false,
		onSelect: function(id, value, input, html){
			if(id > 0) {
				$("#i"+nm).val('');
				//$(input).parent().css({display: 'none'});
				$('.e'+nm).prev().css({display: 'none'});
				$('.e'+nm).prev().prev().css({display: 'none'});
				$('.e'+nm).css({display: ''});
				$('.e'+nm+' input[name='+nm+']').val(id);
				$('.e'+nm+' div').html(html);
			}
		}
	});
	$(".e"+nm+" a.bdelete").click(function(e){
		e.preventDefault();
		$('.e'+nm).prev().css({display: ''});
		$('.e'+nm).prev().prev().css({display: ''});
		$('.e'+nm).css({display: 'none'});
		$('.e'+nm+' input[name='+nm+']').val(0);
		$('.e'+nm+' div').html('');
		$(".i"+nm).val('');
	});
}

function showPopup(url, width) {
	window.open(url, 'popup', "width="+width+", toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, directories=no, status=no");
	return false;
}


(function($){
	$.fn.defaultValue = function(value) {
		var params = {};
		params.value = value;
		
		return this.each(function(){
			var $$ = $(this);
		
		    var putDefault = function() {
		        if (!$$.val() || $$.val().length == 0) {
		            $$.attr('value', params.value);
		        }
		    };
		    var removeDefault = function() {
		        if ($$.val() == params.value) {
		            $$.attr('value', '');
		        }
		    }
		
		    putDefault();
		    
		    $$.blur(putDefault);
		    $$.focus(removeDefault);
		
			if (!$$.parents('form')) return;
		    $$.parents('form').submit(removeDefault);
		});
	};
})(jQuery);
