$(document).ready(function(){
    $(".colorbox").colorbox({});
	$(".colorboxIframe").colorbox({iframe:true, innerWidth:425, innerHeight:344});
});

// adaptovano z http://jonraasch.com/blog/a-simple-jquery-slideshow
function homepageSlideshowSwitch() 
{
    var $active = $('#home_main_img img.active');
    if ($active.length == 0)
    	$active = $('#home_main_img img:last');

    var $next =  $active.next().length ? $active.next() : $('#home_main_img img:first');
    // uncomment the 3 lines below to pull the images in random order
    // var $sibs  = $active.siblings();
    // var rndNum = Math.floor(Math.random() * $sibs.length );
    // var $next  = $( $sibs[ rndNum ] );

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
    
    $active.css({opacity: 1.0})
	    .addClass('active')
	    .animate({opacity: 0.0}, 1000, function() {
	    });
}

function tinyMceHelper(jqobject)
{
	jqobject.tinymce({
		script_url : '/js/tiny_mce/tiny_mce.js',

		mode : "none",
		editor_selector : "mceEditor",
		theme : "advanced",
		entity_encoding : "raw",
		remove_linebreaks : false,
		apply_source_formatting : true,
		//plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",
		plugins : "style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras",
		theme_advanced_buttons1 : "bold,italic,underline,sub,sup,|,justifyleft,justifycenter,justifyright,justifyfull,|,hr,|,bullist,numlist,|,outdent,indent,forecolor,backcolor,formatselect,|,link,image,table,emotions,|,undo,redo,|,code",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		//theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
		//theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
		//theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
		//theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,|,visualchars,nonbreaking",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		extended_valid_elements : "a[name|href|target|title|onclick|rel],img[style|class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
		file_browser_callback : "ajaxfilemanager",
		auto_resize : true,
		relative_urls : false,
		remove_script_host : true,
		language: "cs",
		//document_base_url : "' . site()->url . '"

		content_css : "/css/main.css"
	});
}

$(document).ready(function(){
	tinyMceHelper($('textarea.tinymce'));
});

function ajaxfilemanager(field_name, url, type, win)
{
	tinyMCE.activeEditor.windowManager.open({
		url: "/php/ajaxfilemanager/ajaxfilemanager.php",
		width: 782,
		height: 440,
		inline : "yes",
		close_previous : "no"
	},{
		window : win,
		input : field_name
	});
}

function autocompleteSelected(li, v)
{
    if (v)
    {
        value = $('#q').val().replace(/[\w-]*\s*$/, '');
        if (value && !value.match(/"$/))
            value = value + ' ';
        if (value.match(/"/g) && ((value.match(/"/g).length % 2) == 1))
            value = value.substring(0, value.lastIndexOf('"'));
        if (v.match(/ /g))
            value = value + '"' + v + '"';
        else
            value = value + v;
        value = value.replace(/\s+/, ' ');
        $('#q').val(value);
        $('#q').focus();
    }
}

var okInfo = "Zadaná hesla jsou stejná.";
var nokInfo = "Zadaná hesla jsou rozdílná!";
var emptyInfo = "Hesla nejsou vyplněna!";
var shortInfo = "Minimální délka hesla jsou 4 znaky.";

var loginExist = "Toto uživatelské jméno si už vybral někdo před Vámi. Nebo není ve správném formátu!";
var loginOk = "Bezva, toto uživatelské jméno je ještě volné!";

//hidden pro informaci o dostupnosti jmeno
var doesLoginExist;

$(document).ready(function(){
    //zobrazeni napovedy, na submit overim jestli hesla souhlasi
    $("#form_registrace").each(function(){
       zobrazeniNapovedyUFormulare($(this));
       $(this).submit(function(){
           var pass = initPasswordCheck();
           var nameExist = initCheckLogin();
           return true;
           /*
           if(pass >= 1 && nameExist == 0)
               return true;
           else
               return false;*/
       });
    });

    doesLoginExist = $("#doesLoginExist");
    
    //overeni existence loginu
    var login = $(this).find("#registrace_login");
    function initCheckLogin(){checkLogin(login);return doesLoginExist.val();}
    login.bind("keyup", initCheckLogin);

    //overeni hesel
    var password1 = $("#registrace_heslo");
    var password2 = $("#registrace_heslo2");
    var passwordInfo = $("#password_info");
    function initPasswordCheck(){return handlePasswords(passwordInfo, password1, password2);}
    password1.bind("blur", initPasswordCheck);
    password2.bind("blur", initPasswordCheck);

    //skryti pole kontaktni adresa, kdyz je stejne
    var ch = $("#registrace_kontaktni_je_stejna_jako_fakturacni");
    var el = $("#register_contactData")
    ch.change(function(){onCheckHideElement(ch, el);});
    onCheckHideElement(ch, el);
});

function onCheckHideElement(check_el, element_el){
    if(check_el.attr("checked"))
        element_el.hide();
    else
        element_el.show();
}

function checkLogin(element){
    var val = element.val();

    var infoElement = $("#login_info");
    var infoElementParent = infoElement.parent();
    if(val == "") {
        nok();
        return;
    }
    
    $.getJSON('/ajax/uzivatelskeJmenoDostupne', {login: val}, function(data){
        if(data == 1){
            ok();
        }
        else{
            nok();
        }
    });

    function ok(){
        doesLoginExist.val(0);
        infoElementParent.removeClass("failure");
        infoElementParent.addClass("valid");
        infoElement.text(loginOk);
    }
    function nok(){
        doesLoginExist.val(1);
        infoElementParent.removeClass("valid");
        infoElementParent.addClass("failure");
        infoElement.text(loginExist);
    }
}

//kontroluje shodu hesel
//-1 - nejsou stejne, 0 - prazdne, 1 - ok
function handlePasswords(infoElement, password1Element, password2Element){
    infoElementParent = infoElement.parent();
    if(password2Element.val() == "") {
        handleErrorClassses();
        infoElement.text(emptyInfo);
        return 0;
    }
    if(password2Element.val().length < 4){
        handleErrorClassses();
        infoElement.text(shortInfo);
        return 0;
    }
    
    if(isValSame(password1Element, password2Element)){
        handleValidClassses();
        infoElement.text(okInfo);
        return 1;
    }
    else{
        handleErrorClassses();
        infoElement.text(nokInfo);
        return -1;
    }
    
    function handleValidClassses(){
        infoElementParent.removeClass("failure");
        infoElementParent.addClass("valid");
    }

    function handleErrorClassses(){
        infoElementParent.removeClass("valid");
        infoElementParent.addClass("failure");
    }
}

//vraci true, kdyz maji predavane elementy stejne hodnoty value
//jinak false
function isValSame(element1, element2){
    if(element1.val() != element2.val())
        return false;
    return true;
}

//zobrazi, skryje element, volitelne je mozne explicitne urcit skyti
function handleDisplay(element){
    if(arguments[1] == "hide"){
        element.hide();
        return;
    }
    if(element.css("display") == "none")
        element.show();
    else
        element.hide();
}


//zobrazi napovedu u formulare
function zobrazeniNapovedyUFormulare(form){
    form.find("span.hint").each(function(){
        handleDisplay($(this), "hide");
        var row = $(this).parent().parent().parent();
        row.find("td").each(function(){
            if($(this).attr("class") != "info"){
                var element = $(this).parent().find("span.hint");
                var input = $(this).find("input");
                input.focus(function(){handleDisplay(element);});
                input.blur(function(){handleDisplay(element);});
            }else{
                var hint = $(this).find("a");
                hint.mouseover(function(){handleDisplay($(this).find(".hint"));});
                hint.mouseout(function(){handleDisplay($(this).find(".hint"));});
            }
        });
   });
}

/* ZRUSENO function pridatDoOblibenych(produkt_id)
{
    var blokProduktu = $('#produkt_'+produkt_id);
    var zprava = blokProduktu.find('.pridatDoOblibenychZprava');
    $.get('ajax/pridatDoOblibenych', function(data) {
        console.log(data);
    });
}*/

function lang()
{
    return 'cs';
    //TODO lang()
}

function culture()
{
    return 'cs_CZ';
    //TODO culture()
}
