$().ready(function(){


	//------------------------------------------
    // Zalozky diskusi
    //------------------------------------------
	$("#forumLastTabs").tabs();


	//------------------------------------------
    // Kontrola po submitu
    //------------------------------------------
	$('#validateForm').validate({
		rules: {
			pasword: {
				equalTo: "#password_control"
			},
			password_control: {
				equalTo: "#password"
			},
			email: {
				required: true,
				email: true
			}
		},
		messages: {
			password: {
				equalTo: "Vyplněná hesla musí souhlasit"
			},
			password_control: {
				equalTo: "Vyplněná hesla musí souhlasit"
			},
			email: {
				required: "Toto pole je vyžadováno",
				email: "Zadaný e-mail nemá správný tvar."
			}
		}
	});


	//------------------------------------------
    // Kopirovani hodnot poli
    //------------------------------------------
	$("input[rel^='copyfrom_']").each(function() {


		//------------------------------------------
	    // Nastaveni provadime jen u novych zaznamu
	    //------------------------------------------
		if (!$(this).val()) {
			$("input[rel='copyfrom_" + $(this).attr('id') + "']").val($(this).val());
		}
	});

	//------------------------------------------
    // Tvorba uri do input boxu
    //------------------------------------------
	_initUriFrom();


	//------------------------------------------
    // Skupina checkboxu
    //------------------------------------------
	$("input:checkbox[rel^='group_']").click(function() {
		var name = $(this).attr('name');
		$("input:checkbox[rel^='group_']").each(function(i, element){
			if ($(element).attr('name') == name) {
				return true;
			} else {
				$(this).attr('checked', false);
			}
		});

		return true;
	});


	//------------------------------------------
    // Kontrola maximalni hodnoty inputu
    //------------------------------------------
	$("input:text[rel^='maxinput_']").change(function() {
		var maxVal = parseInt($(this).attr('rel').replace('maxinput_', ''));
		var curVal = parseInt($(this).val());
		if (curVal > maxVal) {

			$(this).val(maxVal);
			alert('Maximální povolená hodnota je ' + maxVal);

		} else {
			return true;
		}
	});


	//------------------------------------------
    // Chainselect - ajax
    //------------------------------------------
	_initDatafrom();


	//---------------------------------------
	//Vytvoreni nahledu souboru z pole
	//---------------------------------------
	$('input:file[rel="thumb"]').each(function(){
		$(this).uploadify({
			'queueID': 'fileQueue',
			'auto': true,
			'folder': '/public/data/thumb',
			'wmode': 'transparent',
			onComplete: function(event, queueID, fileObj, response, data){
				$('#thumbFile').css('display', 'block');
				alert(fileObj.filePath);
				$('#thumbFileField').attr('val', fileObj.filePath);
				$('#thumbFile a.tooltip').attr('href', 'javascript:;');
				$('#thumbFile a.tooltip').attr('title', '<img src="'+fileObj.filePath+'" title="Náhled" alt="Náhled" style="width: 150px; height: 150px;" />');
			}
		});
		$(this).change(function(){
			$(this).uploadifyUpload();
		});
	});


	//---------------------------------------
	//Lightbox
	//---------------------------------------
	$('a.lightbox').lightBox();


	//---------------------------------------
	//Tooltip
	//---------------------------------------
	$('.help_img').each(function(){
		$(this).easyTooltip({
			useElement: $(this).attr('id')+"_txt"
		});
	});


	//---------------------------------------
	//Form checker
	//---------------------------------------
	$('.form_checker').each(function(){
		var check1 = $(this).children("input[rel='check1']").val();
		var check2 = $(this).children("input[rel='check2']").val();
		$(this).children("input[rel='check3']").val(parseInt(check1) + parseInt(check2));
		$(this).hide();
	});


	//---------------------------------------
	//Elements visibility
	//---------------------------------------
	$("a[rel^='show_']").each(function(){
		$(this).click(function(){
			var elementId = $(this).attr('rel').replace('show_', '');
			$('#'+elementId).toggle();
		});
	});


	//---------------------------------------
	//Elements visibility
	//---------------------------------------
	$("input[rel^='show_']").each(function(){
		$(this).change(function(){
			var elementId = $(this).attr('rel').replace('show_', '');
			$('#'+elementId).toggle();
		});
	});
});


//---------------------------------------
//Ajax loader - vytvoreni obrazku
//---------------------------------------
var ajaxLoader = new Image();
ajaxLoader.src = '/application/layouts/css/images/ajax-loader.gif';


//---------------------------------------
//Center
//---------------------------------------
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}


//---------------------------------------
//Random identifer
//---------------------------------------
jQuery.fn.randomIdentifer = function(element_id) {
    var max = 1001;
	var rand = Math.floor(Math.random()*max);
    while ($('#'+element_id+rand).length) {
    	rand = Math.floor(Math.random()*max);
    }

    return element_id+rand;
}


//---------------------------------------
//Vytvoreni preloaderu + 
// vlozeni do elementu
//@param	element_id	HTML element
//---------------------------------------
jQuery.fn.createPreloader = function(element_id) {
    return $('<div id="'+$().randomIdentifer(element_id+'_preloader_')+'" class="center"><img src="'+ajaxLoader.src+'" title="Načítám" alt="Načítám" /></div>');
}


/**
 * Potvrzeni odstraneni zaznamu
 * 
 * @return	boolean
 */
function ConfirmDelete(name)
{
	if (name == null || typeof name == "undefined" || name == '') {
		var str = 'Opravdu chcete odstranit tento záznam?';
	} else {
		var str = 'Opravdu chcete odstranit záznam "' + name + '" ?';
	}

	if (confirm(str)) {
		return true;
	} else {
		return false;
	}
}


//---------------------------------------
//Inicializace chainselect
//---------------------------------------
function _initDatafrom()
{
	$("select[rel^='datafrom_']").each(function() {
		var source_element = this;
		var source_id = $(this).attr('rel').replace('datafrom_', '');
		$('#' + source_id).change(function(){
			chainRequest(source_id, source_element);
		});
		if ($(this).attr('rel2') != 'default') {
			chainRequest(source_id, source_element);
		}
	});
}


//------------------------------------------
// Tvorba uri do input boxu
//------------------------------------------
function _initUriFrom()
{
	$("input[rel^='urifrom_']").each(function() {


		//------------------------------------------
	    // Upravime vzhled elementu
	    //------------------------------------------
		$(this).css({
			'background-color': '#e5e5e5',
			'color': '#a5a5a5',
			'padding': '1px',
			'border': '1px solid'
        });


		//------------------------------------------
	    // Zmenu URL provadime jen u novych zaznamu
	    //------------------------------------------
		if (!$(this).val()) {
			$('#' + $(this).attr('rel').replace('urifrom_', '')).keyup(function(key, id){
				$("input[rel='urifrom_" + $(this).attr('id') + "']").val(str2url($(this).val(), 'UTF-8'));
			});
	        $('#' + $(this).attr('rel').replace('urifrom_', '')).keypress(function(key, id){
				$("input[rel='urifrom_" + $(this).attr('id') + "']").val(str2url($(this).val(), 'UTF-8'));
			});
			$('#' + $(this).attr('rel').replace('urifrom_', '')).change(function(){
				$("input[rel='urifrom_" + $(this).attr('id') + "']").val(str2url($(this).val(), 'UTF-8'));
	        });
		}
	});
}


//---------------------------------------
//Ajax request pro selectbox
//---------------------------------------
function chainRequest(source_id, source_element)
{
	
	$.ajax({
		type: 'POST',
		dataType: 'json',
		url: urlObject.url+'/'+(urlObject.module == 'admin' ? urlObject.module+'/'+urlObject.controller.replace('admin', '') : urlObject.module+(urlObject.controller=='admin' ? '' : '/'+urlObject.controller))+'/chainselect/' + ($('#' + source_id).attr('param') != undefined ? '?param='+$('#' + source_id).attr('param') : ''),
		//url: urlObject.url+'/'+(urlObject.module == 'admin' ? urlObject.module+'/'+urlObject.controller.replace('admin', '') : urlObject.module)+'/chainselect/',
		//url: urlObject.url+'/'+urlObject.module+'/'+urlObject.controller.replace('admin', '')+'/chainselect/',
		data: ({
			parent: $('#' + source_id + ' :selected').val()
		}),
		success: function(data){
			$(source_element).empty();
			for (var i = 0; i < data.length; i++ ) {
				$(source_element).append('<option value="' + data[i]['id'] + '">' + data[i]['name'] + '</option>');
			}

			if ($("select[rel^='datafrom_"+$(source_element).attr('id')+"']").length > 0) {
				$("select[rel^='datafrom_"+$(source_element).attr('id')+"']").each(function(){
					if ($(this).attr('rel2') != 'default') {
						chainRequest($(source_element).attr('id'), this);
					}
                });
			}
		}
	});
}


/**
 * Kontrola registracniho formulare
 * 
 * @return	boolean
 */
function checkRegistration()
{
	var error = 0;
	if ($('#clubman').attr('checked')) {
		$('#clubman_name').parent().find('span').remove();
		$('#clubman_name').parent().find('br').remove();
		if ($('#clubman_name').val() == '') {
			$('#clubman_name').parent().append('<br /><span class="redInfo smallest">Vyplňte prosím tento údaj</span>');
			error = 1;
		}
		$('#clubman_birth').parent().find('span').remove();
		$('#clubman_birth').parent().find('br').remove();
		if ($('#clubman_birth').val() == '') {
			$('#clubman_birth').parent().append('<br /><span class="redInfo smallest">Vyplňte prosím tento údaj</span>');
			error = 1;
		}
		$('#clubman_place').parent().find('span').remove();
		$('#clubman_place').parent().find('br').remove();
		if ($('#clubman_place').val() == '') {
			$('#clubman_place').parent().append('<br /><span class="redInfo smallest">Vyplňte prosím tento údaj</span>');
			error = 1;
		}
	}

	if (!error) {
		return true;
	} else {
		return false;
	}
}


//---------------------------------------
//Zavreni popup okna
//---------------------------------------
function closePopup(fn_before, fn_after)
{
	if (typeof(fn_before) == "function") fn_before();
    $('#popup').empty().remove();
    $('#popup_bck').fadeOut('slow', function(){
        $('#popup_bck').empty().remove();
        if (typeof(fn_after) == "function") fn_after();
    });
}


//---------------------------------------
//Vytvoreni popup okna
//---------------------------------------
function createPopup(content, fn_before)
{
	if (!$('#popup_bck').length) {
		$('<div id="popup_bck"></div>').css({ 'backgroundColor': '#000', 'width': window.document.width+'px', 'height': window.document.height+'px', 'position': 'absolute', 'top': '0px', 'left': '0px' }).appendTo('body').fadeTo('slow', 0.5);
	    $('<div id="popup"></div>').appendTo('body');
	    $('<div id="popup_header"></div>').appendTo('#popup');
	    $('<div id="popup_content"></div>').appendTo('#popup').html(content);

	    if (typeof(fn_before) == "function") {
	    	fn_before();
	    }

	    var top = ($(window).scrollTop() + 20);
	    if (top < 0) {
	    	top = 10;
	    }
	    $('#popup').css({
	    	'position'	:	'absolute',
	    	'top'		:	top + "px",
	    	'left'		:	(($(window).width() - $('#popup').width()) / 2+$(window).scrollLeft()) + "px"
	    });
	    $('<a href="javascript:;" title="" onclick="return closePopup();" class="fr" id="popup_close"><img src="/application/layouts/css/icons/cross.png" title="Zavřít" alt="Zavřít" class="fl" />&nbsp;Zavřít</a>').appendTo('#popup_header');
	}
}


//---------------------------------------
//Ajax - odstraneni
//---------------------------------------
function deleteItem(itemId, info_element, url, element_to_remove)
{
	if (deleteConfirmWindow()) {
		$.ajax({
			url: url,
			success: function(data){
				if (data == '1') {
					$(element_to_remove).hide('slow', function(){
						$(this).empty();
						$(this).remove();
					});
				} else {
					showInfo(info_element, data);
				}
			},
			data: ({
				item:itemId
			}),
			dataType: "html",
			type: 'POST'
		});
	} else {
		return false;
	}
}


//---------------------------------------
//Okno potvrzeni textu
//---------------------------------------
function deleteConfirmWindow(sMsg) {
	if(sMsg == '' || typeof(sMsg) == "undefined") sMsg = 'Opravdu chcete položu smazat?';
	var act;
	act = confirm(sMsg);
	return act;
}


//---------------------------------------
//Opakujici se fading obsahu
//---------------------------------------
function fading(item, sliderDelay)
{
	if (typeof sliderDelay == "undefined") {
		sliderDelay = 4000;
	}
	if ($('#slide-'+item).size() > 0) {
		$('#slide-'+item).fadeIn('slow').delay(sliderDelay).fadeOut('slow', function(){
			fading((item+1), sliderDelay);
		});
	} else {
		fading(1, sliderDelay);
	}
}


//---------------------------------------
//Skryti konkretniho bloku
//---------------------------------------
function fadingHide(item)
{
	if ($('#slide-'+item).size() > 0) {
		$('#slide-'+item).hide();
		fadingHide((item+1));
	}

	return true;
}


//---------------------------------------
//Fading konkretniho obsahu
//---------------------------------------
function fadingItem(item, sliderDelay)
{
	if (typeof sliderDelay == "undefined") {
		sliderDelay = 4000;
	}
	if (fadingStop(1)) {
		if (fadingHide(1)) {
			fading(item, sliderDelay);
		}
	}
}


//---------------------------------------
//Zastaveni fadingu
//---------------------------------------
function fadingStop(item)
{
	if ($('#slide-'+item).size() > 0) {
		$('#slide-'+item).stop(true);
		fadingStop((item+1));
	}

	return true;
}


//---------------------------------------
//Presun elementu
//---------------------------------------
function moveElements(elements_ids, destination) {
    $('#'+destination).empty();
    $('#popup_form input').each(function(){
        if ($('#'+destination+' input[id="'+$(this).attr('id')+'"]').size() == 0) {
            $('<input type="hidden" name="'+$(this).attr('name')+'" value="'+($(this).attr('checked')==true || $(this).val()==1 ? 1 : 0)+'" id="'+$(this).attr('id')+'" />').appendTo('#'+destination);
        }
    });
}


//---------------------------------------
//Otevreni Popup okna s fotogalerii
//---------------------------------------
function myPopWindow(windowURL, windowName, windowFeatures) {
	var defaultFeatures = {"status": 0, "toolbar": 0, "location": 0, "menubar": 0,
                           "directories": 0, "resizeable": 1, "scrollbars": 1,
                           "width": 640, "height": 480};
	var features = '';

	for (i in windowFeatures) { defaultFeatures[i] = windowFeatures[i]; }
	for (i in defaultFeatures) { features += i + '=' + defaultFeatures[i] + ','; }

	window.open(windowURL, '', features);
	//window.location = windowURL;
	return false;
}


//---------------------------------------
//Volani popup okna dle elementu
//---------------------------------------
function popupData(element, action, params, fn_before, fn_after)
{
	var url_action = (typeof(action) != "undefined" ? action : 'ajax');
	var data = new Object();
	if (typeof(params) == "object" && params != null) {
		params.element = (typeof(element) != "undefined" && $(element).attr('id') != '') ? $(element).attr('id') : urlObject.action;
		data = params;
	} else {
		data.element = (typeof(element) != "undefined" && $(element).attr('id') != '') ? $(element).attr('id') : urlObject.action;
	}

	$.ajax({
		url: urlObject.url+'/'+(urlObject.module == 'admin' ? urlObject.module+'/'+urlObject.controller.replace('admin', '') : (urlObject.controller == 'admin' ? '' : urlObject.controller+'/')+urlObject.module)+'/'+url_action+'/' + ($(element).attr('rel2') != '' && $(element).attr('rel2') != undefined ? $(element).attr('rel2') + '/' : '') + (typeof(params) == "string" ? '?' + params : ''),
		success: function(data){
			createPopup(data, fn_before, fn_after);
		},
		data: (data),
		dataType: "html",
		type: 'POST'
	});

	return false;
}


function popupImagesList(itemIdentifer)
{
	$.ajax({
		url: '/admin/gallery/adminimages/popuplist/',
		success: function(data){
			createPopup(data);
		},
		data:({
			itemCount: itemIdentifer,
			hiddenInput: true
		}),
		dataType: "html",
		type: 'POST'
	});
}


//---------------------------------------
//Volani funkce controlleru
// (defualtne: default)
//---------------------------------------
function call(action, params, fn)
{
	_call(action, params, fn);
}


//---------------------------------------
//Volani funkce controlleru
// (defualtne: default) + 
// pozadavek na konfirmaci provedeni + 
// volani dodatecne fce
//---------------------------------------
function callConfirm(action, params, fn)
{
    if (deleteConfirmWindow()) {
        _call(action, params, fn);
    }
}


//---------------------------------------
//Volani funkce
//---------------------------------------
function _call(action, params, fn)
{
	var data = new Object();
	if (typeof(params) == "object") {
		data = params;
	}
	if (typeof(action) == "undefined" || action == null) action = 'default';
	$.ajax({
		url: urlObject.url+'/'+(urlObject.module == 'admin' ? urlObject.module+'/'+urlObject.controller.replace('admin', '') : urlObject.module+'/'+(urlObject.controller == 'admin' ? '' : urlObject.controller+'/'))+action+'/',
		success: function(data) {
			if (data == 'true' || data == '1') window.location = window.location;
			if (typeof(fn) == 'function') fn(data);
		},
		data: data,
		dataType: "html",
		type: "POST"
	});
}


//--------------------------------------------
//Vlozeni dat do elementu
//  @param	htmlData			HTML obsah
//  @param	destinationElement	Cilovy element
//--------------------------------------------
function replaceContent(htmlData, destinationElement)
{
	$(destinationElement).hide("slow");
	$(destinationElement).empty();
	$(destinationElement).html(htmlData);
	$(destinationElement).show("slow");
}


//---------------------------------------
//Zmena viditelnosti prvku
//@param	element			Aktualni HTML prvek
//@param	string			ID prvku pro skryti
//@param	string			ID prvku pro skryti
//...
//---------------------------------------
function changeVisibility()
{
	$('#' + $(arguments[0]).attr('id') + '_item').show('slow');
	$(arguments[0]).show('slow');
	for (var i = 1; i <= arguments.length; i++) {
		$('#'+arguments[i]).hide('slow');
	}
}


//--------------------------------------------
//Vlozeni dat na konec elementu obsahu
//@param	htmlData			HTML obsah
//@param	destinationElement	Cilovy element
//--------------------------------------------
function insertContent(data, destinationElement)
{
	$(destinationElement).hide("slow");
	$(destinationElement).empty();
	$(data).appendTo(destinationElement);
	$(destinationElement).show("slow");
}


//---------------------------------------
//Zobrazeni informace - delay
//---------------------------------------
function showInfo(info_element, data)
{
    $(info_element).html(data);
    $(info_element).fadeIn(1000);
    $(info_element).fadeTo(2000, 1);
    $(info_element).fadeOut(1000);
}


//---------------------------------------
//Vraci url dle textu
//---------------------------------------
function str2url(str, encoding, ucfirst)
{
	str = str.toUpperCase();
	str = str.toLowerCase();

	str = str.replace(/[\u00E0\u00E1\u00E2\u00E3\u00E4\u00E5]/g,'a');
	str = str.replace(/[\u00E7\u010D\u010C]/g,'c');
	str = str.replace(/[\u010E\u010F]/g, 'd');
	str = str.replace(/[\u0161\u0160]/g,'s');
	str = str.replace(/[\u0164\u0165]/g, 't');
	str = str.replace(/[\u0159\u0158]/g,'r');
	str = str.replace(/[\u017E\u017D]/g,'z');
	str = str.replace(/[\u00E8\u00E9\u00EA\u00EB\u011B\u011A]/g,'e');
	str = str.replace(/[\u00EC\u00ED\u00EE\u00EF]/g,'i');
	str = str.replace(/[\u0147\u0148]/g, 'n');
	str = str.replace(/[\u00F2\u00F3\u00F4\u00F5\u00F6\u00F8]/g,'o');
	str = str.replace(/[\u00F9\u00FA\u00FB\u00FC\u016E\u016F]/g,'u');
	str = str.replace(/[\u00FD\u00FF]/g,'y');
	str = str.replace(/[\u00F1]/g,'n');
	str = str.replace(/[\u0153]/g,'oe');
	str = str.replace(/[\u00E6]/g,'ae');
	str = str.replace(/[\u00DF]/g,'ss');

	str = str.replace(/[^a-z0-9\s\'\:\/\[\]-]/g,'');
	str = str.replace(/[\s\'\:\/\[\]-]+/g,' ');
	str = str.replace(/[ ]/g,'-');

	if (ucfirst == 1) {
		c = str.charAt(0);
		str = c.toUpperCase()+str.slice(1);
    }

	return str;
}

function toggleMenu(element_id)
{
    $('#'+element_id).slideToggle("slow", function(){
        var value = ($('#'+element_id).css('display') == 'none') ? 0 : 1;
        //$.post(http_host + "/mainclasses/requests.php", {saveModulesMenu: element_id, settingValue: value, user_id: $('#sidebar_user').val()} );
    });
}


//---------------------------------------
//Zmena viditelnosti prvku
//@param 	id elementu		array()
//---------------------------------------
function toggleElements()
{
	for (var i = 0; i <= arguments.length; i++) {
		$('#'+arguments[i]).toggle('slow');
	}
}


//---------------------------------------
//Ulozeni dat
//---------------------------------------
function saveForm(form, info_element, close_btn, fnc) {
    var data = $(form).serialize();
    $.ajax({
        type:"POST",
        url:$(form).attr('action'),
        data:'&action=save_form&'+data,
        success:function(result){
            $(info_element).html(result);
            $(info_element).fadeIn(1000);
            $(info_element).fadeTo(2000, 1);
            $(info_element).fadeOut(1000);

            if (typeof(close_btn != "undefined")) {
                $(close_btn).click();
            }
        }
    });
}


//---------------------------------------
//Zaslani dat
//---------------------------------------
function sendMiniForm(element, info_element, url)
{
	var send_url = (typeof(url) != "undefined" ? url : $(element).attr('action'));
	$(info_element).html('<img src="/application/layouts/css/images/ajax-loader.gif" title="Nahrávám" alt="Nahrávám" />').show('slow');
    $.ajax({
        type:"POST",
        url:send_url,
        data:$(element).serialize(),
        success:function(result){
            $(info_element).html(result);
            $(info_element).fadeIn(1000);
            $(info_element).fadeTo(2000, 1);
            $(info_element).fadeOut(1000);
        }
    });
}


//---------------------------------------
//Vyber polozek modulu
//---------------------------------------
function getModuleItems(selected_item, selected_part, end_function)
{
	$.ajax({
        url : "/ajax/structure_info.php",
        dataType : "json",
        data : {
            "id" : $('#module_list :selected').val(),
            "action" : "module_items"
        },
        success : function(data) {
        	$('#module_items_td').html(data);
        	if (selected_item != 0) {
        		$("#module_items option[value='" + selected_item + "']").attr('selected', 'selected');
        		if (selected_part != 0) {
        			getModuleItemsPart(selected_part, end_function);
        		}
        	} else {
            	getModuleItemsPart(0, end_function);
            }
        }
    });
}


//---------------------------------------
//Vyber casti polozek modulu
//---------------------------------------
function getModuleItemsPart(selected_part, end_function)
{
    $.ajax({
        url : "/ajax/structure_info.php",
        dataType : "json",
        data : {
            "id" : selected_part,
            "id_module" : $('#module_list :selected').val(),
            "id_parent" : $('#module_items :selected').val(),
            "action" : "module_parts"
        },
        success : function(data) {

        	selectPageAddon();

            $('#module_parts_td').html(data);
            $('#module_parts_td_name').html(data.name);
            if (selected_part != 0) {
                $("#module_parts option[value='" + selected_part + "']").attr('selected', 'selected');
            }

            if (typeof(end_function) == "function") end_function();
        }
    });
}


//---------------------------------------
//Fce nastaveni vlastnosti stranky
//---------------------------------------
function selectPageAddon() { }


//---------------------------------------
//Fce zmeny module part
//---------------------------------------
function getModuleItemPart() { }
