var _borderRed = "#f22";
var _backgroundRed = "#fee";
//------------------------

$(function(){
    textarea_limiters();
    isMaxSelected();
    $(".fajkakat").click(isMaxSelected);
    inputs_check();
    forms_check();
    multiupload();
    $("#projekt").change(projekt); //zmena projektu v novej sukromnej sprave
    $("a[id^='clickMe']").click(clickme);
    $("a[id^='commentMe']").click(commentMe);
    $("a[id^='deleteMe']").click(deleteMe);
    $("a[id^='deleteIn']").click(deleteIn);
    $("a[id^='deleteOut']").click(deleteOut);
    $("a[id^='clickSS']").click(clickSS);
    $("a[id^='clickOUT']").click(clickOUT);
    $("a[id^='deleteKOS']").click(deleteKOS);
    $("span[id^='show_msg_']").click(show_msg);
    $("span[id^='show_outmsg_']").click(show_outmsg);    
    
    $.spin.imageBasePath = 'http://nakoduj.to/images/spin2/';
    $("#cena1").spin({
        min: 10,
        max:999999,
        timeInterval: 120,
        interval:10
    });
	
    $("#sadzba,#prax,#zamestnancov").spin({
        min: 0,
        max:999999,
        timeInterval: 120,
        interval:1
    });
	
	$("#deposit").spin({
        min: 20, 
        max:9999,
        timeInterval: 120,
        interval:10
    });
	
    $("#sadzba_dec").spin({
        min: 0,
        max:9999,
        timeInterval: 120,
        interval:0.1,
		decimal: '.',
    });	
	
	
    //plynuly scroll pri #
    $('a[href*=#]').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
            && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({
                    scrollTop: [targetOffset-140, 'easeOutQuart']
                }, 1500);
                return false;
            }
        }
    });
});

function otvor_dialog_vymaz(bid) {
	
	 $('#dialog-delete').data("bid", bid);
    $('#dialog-delete').dialog('open');

}

//upozornenie
function upozorni(theMessage)
{
    $('#dialog3').html(theMessage);
    $("#dialog3").dialog('open');
}

//plynuly scroller, da sa vlozit v tvare #idecko a element v premennej
function scroller(el){
    if(!$('html').is(":animated")){
        var targetOffset = $(el).offset().top
        $('html:not(animated),body:not(animated)').animate({
            scrollTop: [targetOffset-140, 'easeout']
        }, 1500);
        
    }
    return false;
}

function highlight(el){
    //vyznaci tie vstupne polia, ktore treba doplnit
    if(!$(el).is(":animated")){        
        $(el).data("borderLeftColor", $(el).css("border-left-color"));
        $(el).data("borderRightColor", $(el).css("border-right-color"));
        $(el).data("borderTopColor", $(el).css("border-top-color"));
        $(el).data("borderBottomColor", $(el).css("border-bottom-color"));
        $(el).data("backgroundColor", $(el).css("background-color"));
        $(el).prev().data("color", $(el).css("color"));

        $(el).animate({
            borderTopColor: _borderRed,
            borderBottomColor: _borderRed,
            borderLeftColor: _borderRed,
            borderRightColor: _borderRed,
            backgroundColor: _backgroundRed
        }, 2000);

        $(el).click(function(){
            $(this).delay(3000).animate({
                borderTopColor: $(el).data("borderTopColor"),
                borderBottomColor: $(el).data("borderBottomColor"),
                borderLeftColor: $(el).data("borderLeftColor"),
                borderRightColor: $(el).data("borderRightColor"),
                backgroundColor:$(el).data("backgroundColor")
            }, 2000);
        })

        $(el).prev().animate({
            color:_borderRed
        }, 2000);
        $(el).focus(function(){
            $(this).prev().delay(3000).animate({
                color:$(el).prev().data("color")
            }, 2000)
        })
    }
}

function CheckEmptyField(theField) {
    if(( theField.value=="" )||( theField.value=="@" )||( theField.value=="+421" )) {
        scroller(theField);
        highlight(theField);
        return false;
    } else {
        return true;
    }
}
function CheckNicknameField(theField) {    
    if(( theField.value.length < 5 )||( $(".no_nick").length > 0 )) {
        scroller(theField);
        highlight(theField);
        return false;
    } else {
        return true;
    }
}
function CheckPassField() {
    pw1 = $("#pwd");
    pw2 = $("#pwd2");
    if(pw1.val()!=pw2.val() || pw1.val().length < 6) {
        scroller(pw1);
        highlight(pw1);
        highlight(pw2);
        return false;
    } else {
        return true;
    }    
}
function CheckEmailField(theField) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    if(!pattern.test(theField.value)){
        scroller(theField);
        highlight(theField);
        return false;
    }else{
        return true;
    }
}

function CheckEmailValue(value) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    if(!pattern.test(value)){
        return false;
    }else{
        return true;
    }
}

function RemindValidate() {
	var login = $("#login").val();
	var posta = $("#posta").val();    
	if (!login && !posta) {
		$("#txtHint, #txtHint2").attr('style','color:#f22');    
		//alert(login + ' ' + posta);		
		return false;
	} else {
		if((posta && CheckEmailValue(posta)) || (login && !posta)) {
			return true; 
		} else {
			$("#txtHint").attr('style','');
			$("#txtHint2").attr('style','color:#f22');
			$("#txtHint2").html(NAKODUJTO_JS_6);
			return false;
		}
	}
	
}

function CheckCinnostiField() {
    r1 = $("#role1").is(":checked");
    r2 = $("#role2").is(":checked");
    output = $("#role1").parent();

    if(!(r1 || r2)){
        output.addClass("radius4w");
        scroller(output);
        highlight(output);
        return false;
    }else{
        return true;
    }
}

function isMaxSelected()
{
    max = 5;
    if($(".kategorie_limit .fajkakat:checked").length >= max){
        $(".kategorie_limit .fajkakat:not(:checked)").attr("disabled", "disabled");
    }
    else{
        $(".kategorie_limit .fajkakat:not(checked)").removeAttr("disabled", "disabled");
    }
}

//maximalna dlzka retazcov v textareas
function textarea_limiters(){
    $("#elm_comm").keyup(function(){
        limiter(this,500)
    });
    limiter($("#elm_comm").get(0),500);
    $("#elm_znalosti").keyup(function(){
        limiter(this,1000)
    });
    limiter($("#elm_znalosti").get(0),1000);
    $("#elm_oprj").keyup(function(){
        limiter(this,2000);
    });
    limiter($("#elm_oprj").get(0),2000);
    $("#elm_err").keyup(function(){
        limiter(this,1000);
    });
    limiter($("#elm_err").get(0),1000);
    $("#kontaktuj_text").keyup(function(){
        limiter(this,2000);
    });
    limiter($("#kontaktuj_text").get(0),2000);
}
function limiter(el,max){
    if(el != undefined){
        if($(el).val().length > max){
            $(el).val($(el).val().substr(0, max));
        }
        $(el).next().val(max - $(el).val().length);
    }
}

function ismaxlength(obj, kolko){
    var mlength=kolko;
    if (obj.getAttribute && obj.value.length>mlength)
        obj.value=obj.value.substring(0,mlength)
}

function inputs_check(){
    //checkovanie elementov pre vstup iba s cislami
    $("#cena1,#sadzba,#prax,#zamestnancov").keyup(function(event){
        this.value = this.value.replace(/[^0-9]/g,'');
    })
    // -@-> zakázanie nulovej hodnodty pre cena1
    $("#cena1").keyup(function(event)  { if(this.value == 0) {this.value = ''}; })
    //checkovanie tel cisla
    $("#tel_c,#fax").keyup(function(event){
        this.value = this.value.replace(/[^0-9 +/]/g,'');
    })
    //ico a psc
    $("#ico,#psc,#psc2").keyup(function(event){
        this.value = this.value.replace(/[^0-9 /]/g,'');
    })

    //dic
    $("#dic").keyup(function(event){
        this.value = this.value.replace(/[^0-9 A-Z/]/g,'');
    })
    
    $("#icq").keyup(function(event){
        this.value = this.value.replace(/[^0-9-/]/g,'');
    })

    //banka
    $("#banka").keyup(function(event){
        this.value = this.value.replace(/[^0-9/]/g,'');
    })
    
    //checkovanie elementov pre vstup iba s cislami a pismenami
    $("#cena11").keyup(function(){
        this.value = this.value.replace(/[^a-zA-Z0-9\-]/g,'');
    })

    //checkovanie zadavaneho loginu pri registracii
    in_ajax = 0;
    $("#login_registracia").keyup(function(){
        //this.value = this.value.replace(/[^a-zA-Z0-9\-.]/g,'');
        this.value = this.value.replace(/[^a-zA-Z0-9\-]/g,'');
        nick = this.value;
        output = $(this).prev();        

        if(!in_ajax){
            in_ajax = 1;
            setTimeout(function(){
            
                $.ajax({
                    type: "POST",
                    url: "../inc/ajax-nickcheck.php",
                    data: "str=" + nick,
                    success: function(msg){
                        if(msg!=""){
                            output.html(msg);
                        };
                        in_ajax = 0;
                    }
                });
            },500);
        }
    });
    //checkovanie hesla
    $("#pwd").keyup(function(){
        output = $(this).prev();
        if(this.value.length < 6){
            output.html(NAKODUJTO_JS_21);
        }else{
            output.html(NAKODUJTO_JS_22);
        }
        
    });
    $("#pwd2").keyup(function(){
        if($("#pwd").val().length > 5){
            output = $(this).prev();
            if($("#pwd").val() == $("#pwd2").val()){
                output.html(NAKODUJTO_JS_23);
            }else{
                output.html(NAKODUJTO_JS_24);
            }
        }
    });

    //checkovanie 2 fakturacnych adries
    $("#chsuhlas").click(function(){
        if($(this).is(":checked")){
            $("#fakadresa").slideDown("slow");
        }else{
            $("#fakadresa").slideUp("slow");
        }
    });
        
    $("#role2").click(function(){
        if($(this).is(":checked")){
            $("#suhlasil").slideDown("slow");
        }else{
            $("#suhlasil").slideUp("slow");
        }
    });

}

function formx_change() {
    if($('#chsuhlas2').is(":checked") && $('#chsuhlas').is(":checked")){
        $("#suhlasil").slideDown("slow");
    }else{
        $("#suhlasil").slideUp("slow")
    }
}


// kontrola emailu
function echeck(str) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    if(pattern.test(str)){
        return true
    }else{
        upozorni("Neexistujúca e-mailová adresa! Vyplňte prosím pole email korektne!");
        return false;
    }
}

//kontrola ci je zadana hodnota cislo
function CheckValue( theField, theField2, theMessage ) {
    //if( eval(theField2.value) < eval(theField.value )) {
    if( eval(theField2.value) < eval(theField.value )) {
        theField.focus();
        upozorni(theMessage);
        return false;
    } else {
        return true;
    }

}

//kontrola pre zadavanie kategorii (min 5)
function CheckEmptyCats() {
    if ($(".kategorie_limit .fajkakat:checked").length>=1)
        return true
    else
    {       
        return false
    }
}
//---------------------------------------------//
//       Validovanie formularov
//---------------------------------------------//
//kontrola zadavania projektu
function Validate_kontrola_projekt(theForm) {

    CheckEmptyField(theForm.nadpis);
    CheckEmptyField(theForm.cena1);
    CheckEmptyField(theForm.elm_oprj);

    if(!(CheckEmptyField(theForm.nadpis) &&
        CheckEmptyField(theForm.cena1)&&
        CheckEmptyField(theForm.elm_oprj))) return false;

    if( CheckEmptyCats() || $("input[@name='kategorie']:checked").val()==0) {
        return true
    } else { 
        upozorni(NAKODUJTO_JS_20);
        return false
    }    
}

function Validate_kontrola_registraciaosoba (theForm) {
    CheckNicknameField(theForm.login_registracia);
    CheckPassField();
    CheckEmptyField(theForm.osoba);
    CheckEmailField(theForm.email);
    CheckCinnostiField();

    if(!(CheckNicknameField(theForm.login_registracia) &&
        CheckPassField() &&
        CheckEmptyField(theForm.osoba) &&
        CheckEmailField(theForm.email) &&
        CheckCinnostiField())) return false;
    return true;
}

function Validate_kontrola_registracia (theForm) {
    CheckNicknameField(theForm.login_registracia);
    CheckPassField();
    CheckEmptyField(theForm.nazov);
    CheckEmptyField(theForm.osoba);
    CheckEmailField(theForm.email);
    CheckEmptyField(theForm.sadzba);
    CheckCinnostiField();
    
    if(!(CheckNicknameField(theForm.login_registracia) &&
        CheckPassField() &&
        CheckEmptyField(theForm.nazov) &&
        CheckEmptyField(theForm.osoba) &&
        CheckEmailField(theForm.email) &&
        CheckEmptyField(theForm.sadzba) &&
        CheckCinnostiField())) return false;
    return true;
}

function Validate_kontrola_firma (theForm) {
    CheckEmptyField(theForm.nazov);
    CheckEmptyField(theForm.osoba);
    CheckEmailField(theForm.email);
    CheckEmptyField(theForm.sadzba);
    CheckCinnostiField();

    if(!(CheckEmptyField(theForm.nazov) &&
        CheckEmptyField(theForm.osoba) &&
        CheckEmailField(theForm.email) &&
        CheckEmptyField(theForm.sadzba) &&
        CheckCinnostiField())) return false;
    return true;
}

function Validate_kontrola_osoba (theForm) {    
    CheckEmptyField(theForm.osoba);
    CheckEmailField(theForm.email);
    CheckCinnostiField();

    if(!(CheckEmptyField(theForm.osoba) &&
        CheckEmailField(theForm.email) &&
        CheckCinnostiField())) return false;
    return true;
}
function Validate_kontrola_novaSprava(theForm) {
    tinyMCE.triggerSave();
   
    CheckEmptyField(theForm.projekt);
    CheckEmptyField(theForm.prijemca);
    CheckEmptyField(theForm.subject);
    CheckEmptyField(theForm.elm2);
    
    if(!(CheckEmptyField(theForm.projekt) &&
        CheckEmptyField(theForm.prijemca) &&
        CheckEmptyField(theForm.subject) &&
        CheckEmptyField(theForm.elm2))) return false;
    return true;
}

function Validate_kontrola_hesla() {
    CheckPassField();
    if(!(CheckPassField()))return false;
    return true;
}

function Validate_kontrola_errpopis(theForm) {
    CheckEmptyField(theForm.elm_err);
    CheckEmptyField(theForm.err_predmet);
    if(!(CheckEmptyField(theForm.elm_err)&&
        CheckEmptyField(theForm.err_predmet))) return false;
    return true;
}

function Validate_kontrola_kontaktuj(theForm) {
    CheckEmptyField(theForm.kontaktuj_meno);
    CheckEmptyField(theForm.kontaktuj_email);
    CheckEmptyField(theForm.kontaktuj_predmet);
    CheckEmptyField(theForm.kontaktuj_text);

	//este podmienka navyse pre 
	//if ($("#b3e7146a7ca06d139a01dfdac6b64d42").val() == 1) {return false;}
    
	return true;
}



function Validate_comment() {
    CheckEmptyField($("#elm_comm").get(0));
    if(!(CheckEmptyField($("#elm_comm").get(0))))return false;
    return true;
}

function Validate_kontrola_dialog_fin(theForm) {
    if(!(CheckEmptyField(theForm.msg))) return false;
    return true;
}

function forms_check(){
    $("#projektnovy").submit(function(){
        if (Validate_kontrola_projekt(this)) preview_project();
        return false ;
    });

    $("#registracianovaosoba").submit(function(){
        if (!Validate_kontrola_registraciaosoba(this)) return false ;
    });

    $("#registraciaNovaFirma").submit(function(){
        if (!Validate_kontrola_registracia(this)) return false ;
    });

    $("#zmenaHesla").submit(function(){
        if (!Validate_kontrola_hesla(this)) return false ;
    });

    $("#editaciaRegistracie").submit(function(){
        if (!Validate_kontrola_firma(this)) return false ;
    });

    $("#editaciaRegistracieOsoba").submit(function(){
        if (!Validate_kontrola_osoba(this)) return false ;
    });

    $("#novaSprava").submit(function(){
        if (!Validate_kontrola_novaSprava(this)) return false ;
    });
    $("#form_fin").submit(function(){
        if (!Validate_kontrola_dialog_fin(this)) return false ;
        $("#dialog_fin").dialog("close");
    });
}
// -- koniec validovania formularov ---//
function clickme(){  
    $(this).parent().parent().parent().parent().next().slideToggle("slow");
    $(this).toggleClass('plus').toggleClass('minus');
}

function commentMe(){
    $(this).parent().parent().parent().parent().next().slideToggle("slow");
    $(this).toggleClass('comment').toggleClass('uncomment');
}

function deleteMe(){
    $('#dialog-delete').data("bid", this.id.replace(/\D/g,''));
    $('#dialog-delete').dialog('open');
}

function deleteIn(){
    $('#dialog_sure').data("bid", this.id.replace(/\D/g,''));
    $('#dialog_sure').dialog('open');
}
function deleteOut(){
    $('#dialog_sure2').data("bid", this.id.replace(/\D/g,''));
    $('#dialog_sure2').dialog('open');
}
function deleteKOS(){
    $('#dialog_realdel').data("id", this.id.replace(/\D/g,''));
    $("#dialog_realdel").dialog('open');
}

function clickSS(){
    var id = this.id.replace(/\D/g,'');
    $(this).parent().parent().parent().parent().next().slideToggle("slow");
    $(this).toggleClass('plus').toggleClass('minus'); 

    if($('#newmsg' + id).hasClass('new')){
        showHint8(id);
        $('#newmsg'+id).removeClass('new').addClass('nonew');
    }
}
function clickOUT(){
    var id = this.id.replace(/\D/g,'');
    $(this).parent().parent().parent().parent().next().slideToggle("slow");
    $(this).toggleClass('plus').toggleClass('minus');
}

function show_msg(){
    var id = this.id.replace(/\D/g,'');
    $('#clickSS'+id).click();
}

function show_outmsg(){
    var id = this.id.replace(/\D/g,'');
    $('#clickOUT'+id).click();
}

function projekt(){
    showHint9($(this).val());
}
function vybrat(id,ssto,accbid,accbid_val,bidder){
    $('#projekt_id').val(id);
    $('#ssto').val(ssto);
    $('#accbid').val(accbid);
    $('#accbid_val').val(accbid_val);
    $('#bidder').val(bidder);
    $('#dialog_prijat').dialog('open');
}

function ukazpodmienky()
{
    $("#dialog_podmienky").dialog('open');
}
function ukazkontakt()
{
    $("#dialog_kontakt").dialog('open');
}

//---------hinty-----------//
function showHint12(bid,autor)
{
    $.ajax({
        type: "POST",
        url: "../inc/ajax-biddelete.php",
        data: "bid=" + bid + "&autor=" + autor,
        success: function(msg){
            if(msg==""){
                $('#bid_id_' + bid).slideUp("slow");
                $('#textBox' + bid).slideUp("slow");
                $("#dialog-deleted").dialog("open");
            };
        }
    });
}

function showHint11(str,str2)
{
    $.ajax({
        type: "POST",
        url: "../inc/ajax-projectdatumlong.php",
        data: "str=" + str + "&str2=" + str2,
        success: function(msg){
            if(msg==""){
                $('#txtHint11').text(msg);
                window.location.reload();
            };
        }
    });
}

function showHint6(str)
{
    $.ajax({
        type: "POST",
        url: "../inc/ajax-delforss.php",
        data: "str=" + str,
        success: function(msg){
            if(msg==""){
                $('#deleteIn'+str).parent().parent().parent().parent().slideUp("slow");
            };
        }
    });
}

function showHint7(str)
{
    $.ajax({
        type: "POST",
        url: "../inc/ajax-delfromss.php",
        data: "str=" + str,
        success: function(msg){
            if(msg==""){
                $('#deleteOut'+str).parent().parent().parent().parent().slideUp("slow");
            };
        }
    });
}

function showHint8(str)
{
    $.ajax({
        type: "POST",
        url: "../inc/ajax-citanass.php",
        data: "str=" + str,
        success: function(msg){
            $("#pocet_novych_sprav").text($("#pocet_novych_sprav").text()-1);
        }
    });
}

function showHint9(str)
{
    $.ajax({
        type: "POST",
        url: "../inc/ajax-getprijemcovia.php",
        data: "str=" + str,
        success: function(msg){
            if(msg!=""){
                $("#txtHint9").html(msg);
            }
        }
    });
}

function showHint10(str)
{
    $.ajax({
        type: "POST",
        url: "../inc/ajax-delssfin.php",
        data: "str=" + str,
        success: function(msg){
            if(msg==""){
                $('#deleteKOS'+str).parent().parent().parent().parent().slideUp("slow");
            }
        }
    });
} 
function fblike(){
    $(".fblike").html('<fb:like href="'+document.location.href+'" show_faces="false"  width="280"  font="arial"></fb:like>');
}

$(document).ready(function() {                           
var string1 = "&#105;&#110;&#102;&#111;";
var string2 = "&#64;";
var string3 = "nakoduj.to";
var string4 = string1 + string2 + string3;
$('#mailik').html("<a class='codem' href=" + "mai" + "lto:" + string1 + string2 + string3 + ">" + string4 + "</a>");
});

function multiupload(){
    $('#T7').MultiFile({
        list: '#T7-list',
        max:3,
        accept:"psd|xml|pptm|potx|potm|ppc|xlsx|xls|docx|doc|pdf|tar|gz|zip|rar|png|gif|jpg|pps|mp4|wma|tif|wav|wmv|ppt|avi|mp3|htm|html|txt|mpeg|flv|swf|rtf|iso|sql",
        STRING:{remove:'X',
        selected:'Vybrané: $file',
        denied:'Prípona $ext nie je povolená!',
        duplicate:'Duplokovaný upload: \n$file!'}
    });
 }
