var defaultDialogOptions = {
	closeOnEscape: false,
	bgiframe: true,
	autoOpen: false,
	height: 422,
	width: 670,
	resizable: false,
	modal: true,
	dialogClass: 'my-dialog',
	open: function(){
		redesignDialogTitle($(this));
	},
	buttons: {
		"Uložit": function() {
//			$(this).dialog("close");
		}
	},
	close: function() {
		
	}
};

function redesignDialogTitle($dialog, interval) {
	var $dialog_wrapper = $dialog.parent();
	
	if ($dialog_wrapper.find('.button-for-delete').length > 1) { //regiony, mapa
		$dialog_wrapper.find('.button-for-delete').remove();
		$dialog_wrapper.find("form").unbind('submit');
		$dialog_wrapper.find("form").bind('submit', function(event) { event.preventDefault(); });
		
		$(".ui-dialog-buttonpane button").click(function() {
			if ($('#tabs-idx').tabs('option', 'selected') == 0) {
				$.get("/admin/firma/regiony-pusobnosti-mapa?regions[]=", {'regions[]': regions}, function(data) {
					showAlertDialog($dialog, $dialog_wrapper.find("form"), data);
				});
			} else {
				$.post($("#map-form").attr("action"), $("#map-form").serialize(), function(data) {
					showAlertDialog($dialog, $dialog_wrapper.find("form"), data);
				});
			}
		});
	} else if ($dialog_wrapper.find('.button-for-delete').length) {
		$dialog_wrapper
			.find('.button-for-delete')
			.remove()
		;
		$dialog_wrapper.find("form").unbind('submit');
		$dialog_wrapper.find("form").bind('submit', function(event) { 
			var $thisForm = $(this);
		//$dialog_wrapper.find("form").submit(function(event) {
			$.post($(this).attr("action"), $(this).serialize(), function(data) {
				showAlertDialog($dialog, $thisForm, data);
			})
			event.preventDefault();
		});
		
		$(".ui-dialog-buttonpane button").unbind('click').bind('click', function() {
			$dialog_wrapper.find("form").submit();
		});
	}
	
	if ($dialog_wrapper.find('.button-for-relocate').length) {
		var $tempButton = $dialog_wrapper.find('.button-for-relocate').clone(true);
		$tempButton.css('margin', '12px 0 0 10px');
		$dialog_wrapper.find('.button-for-relocate').remove();
		$dialog_wrapper.find('.ui-dialog-buttonpane').prepend($tempButton);
	}
	
	if ($dialog_wrapper.find('.dialog-titlebar-left').length)
		return false;
	$dialog_wrapper
		.find('.ui-dialog-titlebar')
		.append($('<span />').addClass('dialog-titlebar-left'))
		.append($('<span />').addClass('dialog-titlebar-right'))
		.find('.ui-dialog-titlebar-close').prepend('zavřít')
			.unbind('click')
			.bind('click', function(event){
				dialogImpressiveClose($dialog, function(){
					if (closeTimeout) {
						clearTimeout(closeTimeout);
						closeTimeout = false;
						$dialog.dialog('close').remove();
					}
					$dialog.dialog('close');
				});
				event.preventDefault();
			})
	;
	$dialog_wrapper
		.css('overflow', 'visible')
		.append($('<div />').addClass('dialog-content-bottom'))
	;
	$dialog_wrapper
		.find('.dialog-content-bottom')
		.append($('<div />').addClass('filler'))
		.append($('<div />').addClass('corner rb'))
		.append($('<div />').addClass('corner lb'))
	;
	$dialog_wrapper
		.find('.ui-dialog-buttonpane button')
		.removeClass('ui-corner-all')
	;
}

var closeTimeout = false;

function showAlertDialog($dialog, $form, data, onAlertDialogClose) {
	$('#alertDialog').dialog('close').remove();
	var messageOk = $(data).find(".status-ok").html();
	var messageError = $(data).find(".status-error").html();
	$('<div />')
		.attr({'id': 'alertDialog', 'title': 'Zpráva'})
		.dialog($.extend({}, defaultDialogOptions, {
			width: 350,
			height: 250,
			buttons: {
				'Zavřít': function() {
					clearTimeout(closeTimeout);
					closeTimeout = false;
					dialogImpressiveClose($('#alertDialog'), function(){
						$('#alertDialog').dialog('close').remove();
						if (onAlertDialogClose) onAlertDialogClose();
						if (messageOk && $dialog) {
							dialogImpressiveClose($dialog, function(){
								$dialog.dialog("close");
							});
						}
					});
				}
			}
		}));
	var message = (messageOk) ? messageOk : messageError;
	$('#alertDialog').html(message).dialog('open');
	
	$('#alertDialog').parent().find('.ui-dialog-titlebar-close')
		.unbind('click')
		.bind('click', function(event){
			event.preventDefault();
			dialogImpressiveClose($('#alertDialog'), function(){
				if (closeTimeout) {
					clearTimeout(closeTimeout);
					closeTimeout = false;
					$('#alertDialog').dialog('close').remove();
				}
				if (onAlertDialogClose) onAlertDialogClose();
				if ($dialog) {
					dialogImpressiveClose($dialog, function(){
						$dialog.dialog("close");
					});
				}
				$('#alertDialog').dialog('close');
			});
		});

	if ($form.find("[name=form-id]").val() == "fotogalerie-update") {
		gallerySaved = true;
	}
	if (messageOk) {
		closeTimeout = setTimeout(function() {
			dialogImpressiveClose($('#alertDialog'), function(){
				$('#alertDialog').dialog('close').remove();
				clearTimeout(closeTimeout);
				closeTimeout = false;
				if (onAlertDialogClose) onAlertDialogClose();
				if ($dialog) {
					dialogImpressiveClose($dialog, function(){
						$dialog.dialog("close");
					});
				}
			});
		}, 4000);
		
		$('#alertDialog').parent().find('button').text('Zavřít (4)').css('font-weight', 'bold');
		setTimeout(function() { $('#alertDialog').parent().find('button').text('Zavřít (3)'); }, 1000);
		setTimeout(function() { $('#alertDialog').parent().find('button').text('Zavřít (2)'); }, 2000);
		setTimeout(function() { $('#alertDialog').parent().find('button').text('Zavřít (1)'); }, 3000);
	}
}

function dialogImpressiveClose($dialog, callback) {
	if ($.browser.msie) {
		$dialog.parents('.ui-dialog').hide();
		//$dialog.dialog('close');
		setTimeout(function(){
			$(".ui-widget-overlay:last").hide().remove();
			if (callback) callback();
		}, 300);
		
	} else {
		$dialog.parents('.ui-dialog').fadeOut(function() {
			$(".ui-widget-overlay:last").fadeOut(callback);
		});
	}
}

$(function(){
	$('.b-header-bright-clickable').each(function(){
		$(this).addClass('bhbc');
		$(this).parent().find('.b-content').hide();
	});
	$('.bhbc').hover(
		function() {
			$(this).removeClass('b-header-bright-clickable');
			$(this).css('cursor', 'pointer');
		},
		function(){
			if (!$(this).parent().find('.b-content').is(':visible')) {
				$(this).addClass('b-header-bright-clickable');
			}
		}
	);
	$('.bhbc').click(function(){
		$(this).parent().find('.b-content').slideToggle('normal', function() {
			$('.bhbc').hover();
			ieBodyHeightFixer();
		});
		$(this).blur();
	});
	
	// TMAVEJ
	$('.b-header-clickable').each(function(){
		$(this).addClass('bhc');
		if (!$(this).hasClass('unwrapped')) {
			$(this).parent().find('.b-content-container').hide();
		}
	});
	$('.bhc').hover(
		function() {
			$(this).removeClass('b-header-clickable');
			$(this).css('cursor', 'pointer');
		},
		function(){
			$(this).addClass('b-header-clickable');
		}
	);
	$('.bhc').click(function() {
		var objToSave =  new Object();
		switch($(this).attr('id')) {
			case 'search-header':
				objToSave = {catalogSearchOpen: (!$(this).hasClass("unwrapped")) ? "true" : ""};
				break;
			case 'map-header':
				objToSave = {sortDialogOpen: (!$(this).hasClass("unwrapped")) ? "true" : ""};
				break;
			default:
				objToSave = {};
		}
		$(this).parent().find('.b-content-container').slideToggle('normal', function() {
			$.get("/SessionSave.php", objToSave);
			$(this).hover();
			ieBodyHeightFixer();
		});
		$(this).toggleClass("unwrapped");
		$(this).blur();
	});
//	$('.b-header-clickable').each(function() {
//		if ($(this).hasClass('unwrapped')) $(this).removeClass('b-header-clickable');
//	});
	
	// empirickej fix zobrazovani mapky pro operu
	if ($.browser.opera) {
		setTimeout(function() {
			$("object").after('<div style="background: transparent; position: absolute; left: 0; top: 0; width: 10px; height: 10px;">&nbsp;</div>').next().each(function() {
				var $postup = $(this);
				setTimeout(function() {
					$postup.remove();
				}, 1000);
			});
		}, 1000);
	}
	
	$('#report').click(function(){
		$(this).toggleClass('hover');
	});
});

$(document).ready(function(){
	$('.whisperer').jWhisperer();
	
	$('#search-tabs ul li a').click(function(event) {
		$(this).parents('ul').find('li').removeClass('ui-tabs-selected ui-state-active');
		$(this).parent().addClass('ui-tabs-selected ui-state-active');
		$('#search-tabs .glass').focus();
		event.preventDefault();
	})
});

function contentLimiter(coverSelector, firstChildrenSelector, limitTo) {
	var linkHeight = 15;
	var animateSpeed = 1100;
	
	switch(firstChildrenSelector) {
		case 'tr':
			var items = $(coverSelector + ' > table > tbody > tr');
		break;
		default:
			var items = $(coverSelector + '>' + firstChildrenSelector);
			
	}
	
	if (items.length <= limitTo) {
		return false;
	}
	
	var visibleContentHeight = 0;
	var i = 1;
	items.each(function(){
		if (i <= limitTo) {
			visibleContentHeight += $(this).height();
		}
		i++;
	});
	
	var verticalPadding = parseInt($(coverSelector).css('padding-top')) + parseInt($(coverSelector).css('padding-bottom'));
	var contentHeight = visibleContentHeight - verticalPadding + linkHeight;
	var coverPaddingBottom = parseInt($(coverSelector).css('padding-bottom'));
	var litMore = '<span style="font-size: 14px">&raquo;</span> více &hellip;';
	var litLess = '<span style="font-size: 14px">&laquo;</span> méně &hellip;';
	
	$(coverSelector).css({
		overflow:'hidden',
		height: contentHeight + 'px',
		position: 'relative'
	});
	
	$link = $('<a />')
		.attr('href', '#')
		.addClass('more')
		.css({fontWeight: 'normal', textDecoration: 'none'})
		.click(function(event){
			$(this).blur();
			if ($(this).hasClass('more')) {
				$(coverSelector).css({
					overflow: 'visible',
					height: 'auto'
				});
				
				var ch = $(coverSelector).height();
				
				$(coverSelector).css({
					overflow: 'hidden',
					height: contentHeight + 'px'
				});
				
				$(coverSelector).css('overflow', 'visible');
				$(coverSelector).animate({
					height: (ch + verticalPadding + linkHeight) + 'px',
					'padding-bottom': (coverPaddingBottom + linkHeight) + 'px'
				}, animateSpeed);
				
				$(this).html(litLess);
			} else {
				$(coverSelector).css('overflow', 'hidden');
				$(coverSelector).animate({
					height: contentHeight + 'px',
					'padding-bottom': coverPaddingBottom + 'px'
				}, animateSpeed);
				$(this).html(litMore);
			}
			$(this).toggleClass('more')
			event.preventDefault();
		})
		.html(litMore)
	;
	
	$linkCover = $('<div />')
		.css({
			position: 'absolute',
			bottom: '0',
			right: '0',
			width: '100%',
			height: linkHeight + 'px',
			'background-color': '#fff',
			'text-align': 'right',
			'z-index': 2
		})
	;
	
	$link.appendTo($linkCover);
	$linkCover.appendTo($(coverSelector));
}

function showInfoDialog(message, title) {
	$("#info-popup-dialog").remove();
	
	var options = new Object();
	options.width = 600;
	options.height = 400;
	if (title) 
		options.title = title;
	else
		options.title = "Informace";		
	options.buttons = {
		"Zavřít": function() {
			dialogImpressiveClose($(this), function(){
				$("#info-popup-dialog").dialog("close");
			});
		}
	};
	$('<div id="info-popup-dialog" />').appendTo("body");
	$("#info-popup-dialog").html(message);
	
	$("#info-popup-dialog").dialog($.extend({}, defaultDialogOptions, options));	
	$("#info-popup-dialog").dialog('open');
}

$(function() {
	$(".podminky-serveru").click(function(event) {
		$.get('/smluvni-ujednani?free', function(data) {
			showInfoDialog('<div style="padding: 10px">' + data + '</div>', "Smluvní ujednání");
		});
		event.preventDefault();
	});
});

function clearForm(form) {
	$(':input', form).each(function() {
		var type = this.type;
		var tag = this.tagName.toLowerCase(); // normalize case
		if (type == 'text' || type == 'password' || tag == 'textarea')
			this.value = "";
		else if (type == 'checkbox' || type == 'radio')
		this.checked = false;
		else if (tag == 'select')
		this.selectedIndex = -1;
	});
};

