var WinDom = new Class({
    Implements: Options,
    newHeight: false,
    options: {
        /*
         * Sirka okna
         */
        width: 802,
        /*
         * Vyska okna
         */
        height: 400,
        /*
         * Popis okna v title, pokud bude v odkazu title, prepise se na tuto hodnotu
         */
        title: 'Nazev okna',
        /*
         * Url pro contentload
         */
        url: null,
        /*
         * Ma-li se vygenerovat kryci pozadi pro nemoznost kliku
         */
        background: true,
        /*
         * Rychlost animace nahoru/dolu
         */
        animation_duration: 600,
        /*
         * Na jakou pozici Y se ma okno animovat
         */
        openOffsetX: 100,
        /*
         * O kolik se ma okno posunout nahoru vyska okna + tento offset
         */
        closeOffsetX: 50,
        /*
         * Zda je mozny automaticky resize, tzn. pokud mi to dovoli okno prohlizece, jeli obsah contentu vetsi nez navolena vyska, bude hodnota height prepsana
         */
        automaticResizeY: false,
        /*
         * Zda-li ma byt vyska kryciho pozadi dle getScrollSize, pokud false, bere se getSize
         */
        fullbg: true,
        /*
         * Zda-li se maji pri otevreni okna vypnout scrollbary document.body
         */
        scrollbarOff: true,
        /*
         * Zda-li je mozne pokud kliknu na pozadi, zavrit cele okno
         */
        bgClose: true,
        /*
         * Nastaveni pruhlednosti kryciho pozadi
         */
        bgOpacity: 0.3
    },
    /*
     * Zakladni initializacni funkce, preda se option a spusti se vytvoreni okna
     * @param options HASH
     */
    initialize: function(options){
        this.setOptions(options);
        this.build();
    },

    /*
     * Vytvoreni okna, nacteni obsahu
     */
    build: function(){
        if (this.options.scrollbarOff){
            $(document.body).setStyle('overflow','hidden');
        }
        if (this.options.background == true){
            this.bg = new Element('div').inject($('addon')).setStyles({
                position: 'absolute',
                left: 0,
                top: 0,
                'z-index':1998,
                background: '#000000',
                height: (this.options.fullbg === true)?window.getScrollSize().y:window.getSize().y,
                width: window.getSize().x,
                opacity:0
            })
            this.bg.tween('opacity',this.options.bgOpacity);
            if (this.options.bgClose === true){
                this.bg.addEvent('click',this.close.bind(this));
            }
        }
        
        this.main = new Element('div',{'class':'DomWin'}).inject($('addon')).setStyles({width:this.options.width, height: this.options.height+20, top:-(this.options.height+this.options.closeOffsetX)});
        var title = new Element('div',{'class':'DomWin_title',html:this.options.title}).inject(this.main), content = new Element('div',{'class':'DomWin_content'}).inject(this.main).setStyles({width:this.options.width-22, height:this.options.height - 30, overflow:'auto'}), bg = new Element('div').inject(this.main,'before');
        new Element('div',{'class':'DomWin_title_close'}).inject(title).addEvent('click',this.close.bind(this));
        
        new Request.HTML({
            url: this.options.url,
            update: content,
            onComplete: this.loaded.bind(this)
        }).send();
    },

    loaded: function(){
        if (this.options.automaticResizeY === true){
            this.newHeight = window.getSize().y - this.options.openOffsetX - 20;
            content = this.main.getElement('.DomWin_content');
            frstTag = content.getChildren()[0];
            if (frstTag.getSize().y < this.newHeight - 30){
                this.newHeight = frstTag.getSize().y + 60;
            }

            this.main.setStyles({
                height: this.newHeight,
                top:-(this.newHeight+this.options.closeOffsetX)
            });

            content.setStyles({
                height:this.newHeight - 30
            })
        }

        window.FastestFormObj = new FastestForm(this.main.getElement('form'));
        this.set_to_center();
        this.main.set('tween',{duration:this.options.animation_duration,transition: Fx.Transitions.Sine.easeOut});
        this.main.tween('top',this.options.openOffsetX);
        
    },
    close: function(){
        this.main.set('tween', {duration:this.options.animation_duration, onComplete:function(el){el.dispose()}});
        this.main.tween('top', -((this.newHeight !== false)?this.newHeight:this.options.height + this.options.closeOffsetX));

        if (this.options.background == true){
            this.bg.set('tween', {onComplete:function(el){el.dispose()}});
            this.bg.tween('opacity', 0);
        }

        if (this.options.scrollbarOff){
            document.body.setStyle('overflow','auto');
        }
    },
    set_to_center: function(){
        var w = window.getSize().x;
        this.main.setStyle('left',w/2 - this.main.getSize().x/2);
    }


});

window.addEvent('domready',function(){
    new Element('div',{id:'addon'}).inject(document.body)

    $$('a[href=/login/]').addEvent('click', function(e){
        e.stop();
        var setting = {
            url: this.getProperty('href'),
            title: this.getProperty('title'),
            width: 460,
            height: 200
        };
        /*
         * nalezeni nastaveni dle informaci v atributu rel
         */
        var rel = this.getProperty('rel');
        if (rel){
            var serArr = JSON.decode(rel);
            if (serArr){
                Object.each(serArr,function(value, atr){
                    setting[atr] = value;
                })
            }
        }

        new WinDom(setting)
    })

    if($('open_form_for_add_new_file')){
        $('open_form_for_add_new_file').addEvent('click',function(e){
           e.stop();
            var setting = {
                url: this.getProperty('rel'),
                title: 'Přidání nového souboru',
                width: 460,
                height: 335
            };

            new WinDom(setting)
        });
    }


    if ($('Slider')){
        // The simple way
         mySlideShow = new SlideShow($('Slider'),{
        delay: 3000,
        autoplay: true
    });
    }

})


var Validation = new Class({
    //Implements: [Chain, Events, Options],
    options: {
        result: "Nejsou vyplněny následujicí údaje:\n\n",
        require_items : [],
        regexp_fnc : false,
        errors: [] // errors
    },
    initialize: function (ri_array) {
        this.init_require(ri_array);
    },
    init_require: function(ri_array){
        if(ri_array){
           ri_array = JSON.decode(ri_array);

           if(ri_array.length > 1){
              this.options.require_items.empty();
              this.options.require_items = this.options.require_items.concat(ri_array);
           }
       }
    },
    makeResultMsg: function (name){
        if(!name)
            return this.options.result + this.options.errors.join("\n");
        else
            return name + "\n" + this.options.result + this.options.errors.join("\n");
    },
    set_validation: function (val_array){
        this.options.regexp_fnc = true;
        this.validation_setting = JSON.decode(val_array);
    },
    result_condition: function (condition){
        switch(condition.type){
             case 'checked':
                if($(condition.id).checked){ return true;}
            break;
        }
        return false;
    },
    set_stars: function (id_box){
    //add red star to labels of required elements
        var el = $(id_box);
        Array.each(el.getElements('input[type=text],input[type=password],input[type=checkbox],select,textarea'),function(item){
            key = item.id.replace(/(Client|Address|ReferatyUser|ReferatyZakazky|CmsUser|Zprava|Booking|MenuLetter|RealItemWatchDog|RealItem|EquipmentReservation|HotelRoomBooking|PizzaOrder|PizzaClient|Cv|BzInsertion)|/g,"").underScore2();
            var label = '';
            if(item.getPrevious('label'))
                label = item.getPrevious('label').get('html').replace(":","");
            if(this.options.require_items.contains(key)){
                if(label != ''){
                    item.getPrevious('label').setProperty('html', item.getPrevious('label').getProperty('html') + ' <span class="require">*</span>');
                }
            }
        }, this);
    },
    validate: function(id_box,name){
        var el = $(id_box);
        var validate_next = true;
        this.options.errors.empty();

        Array.each(el.getElements('input[type=text],input[type=password],input[type=checkbox],select,textarea'),function(item){
            key = item.id.replace(/(Client|Address|ReferatyUser|ReferatyZakazky|CmsUser|Zprava|Booking|MenuLetter|RealItemWatchDog|RealItem|EquipmentReservation|HotelRoomBooking|PizzaOrder|PizzaClient|Cv|BzInsertion)|/g,"").underScore2();
            var label = '';
            //nastaveni label pro alert
            if(item.getPrevious('label')){
                  label = item.getPrevious('label').get('html').replace(":","");
                  label = label.stripTags() ;
            }
            if(this.options.require_items.contains(key) && (item.value == '' || item.value == 0)){
                if(label != ''){this.options.errors.push(' - '+label);}
            }
            else if(this.options.regexp_fnc === true && Object.keys(this.validation_setting).contains(key)){

                validate_data = this.validation_setting[key];
                if(typeOf(validate_data) == 'object'){validate_data = Array(validate_data);}

                Object.each(validate_data,function(obj){
                    /**
                     * Zapracovani condition, tzn validujeme pouze za nejake podminky
                     */
                    if(obj.condition){
                        if(this.result_condition(obj.condition) == false){ validate_next = false;}
                    }

                    if(validate_next == true){
                        switch(obj.type){
                           case 'require':
                                if(item.value == ''){
                                    this.options.errors.push(' - '+obj.error);
                                    validate_next = false;
                                }
                            break;
                            case 'checked':
                                if(item.checked == false){
                                    this.options.errors.push(' - '+obj.error);
                                    validate_next = false;
                                }
                            break;
                            case 'equals':
                                if(item.value != $(obj.value).value){
                                     label2 = $(obj.value).getPrevious('label').get('html').replace(":","");
                                     label2 = label2.stripTags();
                                     this.options.errors.push(' - '+label+' se neshoduje s '+label2);
                                     validate_next = false;
                                }
                            break;
                            case 'hour_greater_than':
                                //item.name bFrom
                                //obj.value bTo
                                regexp = /(\d{2}):(\d{2})/;
                                var aMathesHour2 = regexp.exec(item.value);
                                var aMathesHour1 = regexp.exec($(obj.value).value);
                                bIn = false;
                                if( (aMathesHour1[1] > aMathesHour2[1] )){
                                    bIn = true;
                                }else if((aMathesHour1[1] == aMathesHour2[1] )){
                                    if( (aMathesHour1[2] >= aMathesHour2[2]) ){
                                        bIn = true;
                                    }
                                }
                                if(bIn){
                                     label2 = $(obj.value).getPrevious('label').get('html').replace(":","");
                                     label2 = label2.stripTags();
                                     this.options.errors.push(' - '+label+' musí být větší než '+label2);
                                     validate_next = false;
                                }
                            break;
                            case 'hour_less_than':
                                //item.name bFrom
                                //obj.value bTo
                                regexp = /(\d{2}):(\d{2})/;
                                var aMathesHour1 = regexp.exec(item.value);
                                var aMathesHour2 = regexp.exec($(obj.value).value);
                                bIn = false;
                                if( (aMathesHour1[1] > aMathesHour2[1] )){
                                    bIn = true;
                                }else if((aMathesHour1[1] == aMathesHour2[1] )){
                                    if( (aMathesHour1[2] >= aMathesHour2[2]) ){
                                        bIn = true;
                                    }
                                }
                                if(bIn){
                                     label2 = $(obj.value).getPrevious('label').get('html').replace(":","");
                                     label2 = label2.stripTags();
                                     this.options.errors.push(' - '+label+' musí být menší než '+label2);
                                     validate_next = false;
                                }
                            break;
                            case 'validate':
                                if(item.value.test(obj.value) == false){
                                    this.options.errors.push(' - '+label+' je špatně vyplněno');
                                    validate_next = false;
                                }
                            break;
                        }
                    }
                },this)
                validate_next = true;
            }
        },this)


        if(this.options.errors.length < 1){
            return true;
        }
        else
            return this.makeResultMsg(name);
    }
});

function tisk(){
    print();
}

var ContactForm = new Class({
    Implements: Options,
    options: {
        url: '/ajax_panel/ContactForm/send/',
        inside: false,
        classes: '.input_text, .input_textarea',
        buttonClass: '.button',
        comunicationErr: 'Opakujte svuj pozadavek pozdeji.',
        comunicationEnd: 'Dekujeme, Vas pozadavek byl odeslan.',
        errors: [],
        validate_el: [], //Array of elements wich we validate
        result: "Nejsou vyplněny následujicí údaje:\n\n"
    },

    initialize: function(form, options,validate_el){
        this.setOptions(options);
        this.options.validate_el = validate_el;

        this.form = form;

        if (!this.form)
            return;



        this.form.getElements(this.options.classes).each(function(element){
            element.store('orig_name', element.value);
            element.addEvents({
                'focus' : function(){
                    if (this.value === this.retrieve('orig_name')){
                        this.value = '';
                    }
                },
                'blur' : function(){
                    if (this.value === ''){
                        this.value = this.retrieve('orig_name');
                    }
                }
            });
        });
        var btn = this.form.getElement(this.options.buttonClass);
        if (btn){
            btn.addEvent('click', (function(e){
                e.stop();
                var validate_result = this.validate();
//                console.log(validate_result);return false;

                if(validate_result === true){
                    new Request.JSON({
                        url: this.options.url,
                        onComplete: (function(json){
                            if (json){
                                if (json.result === true){
                                    if(json.data){
                                        alert(json.data);
                                    } else {
                                        alert(this.options.comunicationEnd);
                                    }
                                } else {
                                    alert(json.message);
                                }
                            } else {
                                alert(this.options.comunicationErr);
                            }
                            this.form.getElements().value = '';
                            location.reload(true);
                        }).bind(this)
                    }).send(this.form);
                }
                else {
                    alert(validate_result);
                }

            }).bind(this));
        }
    },
    makeResultMsg: function (){
        return this.options.result + this.options.errors.join("\n");
    },
    makeErrorMsg: function (el,item,type){
        switch(type){
            case 'required':
                if(!item.required_text ||  item.required_text === ''){
                    //return 'Nevyplnily jste pole '+(this.options.inside == true ? el.retrieve('orig_name') : el.getPrevious('label').get('html')).replace(":","").toLowerCase();
                    return 'Nevyplnily jste pole '+item.name;
                }
                else {
                    return item.required_text;
                }
            break;
            case 'validate':
                if(!item.validate_text ||  item.validate_text === ''){
                    //return 'Špatně vyplněno pole '+(this.options.inside == true ? el.retrieve('orig_name') : el.getPrevious('label').get('html')).replace(":","").toLowerCase();
                    return 'Špatně vyplněno pole '+item.name;
                }
                else {
                    return item.validate_text;
                }
            break;
            default:alert('Nespecifikovany typ');break;
        }
        return true;
    },
    validate: function(){

        var prefix = 'ContactFormInstance';
        this.options.errors.empty();
        Object.each(this.options.validate_el,function(item){
            var el, html_id = prefix+item.contact_form_id.camelCase2()+item.id.camelCase2();
            el = $(html_id);
            if(item.required == true){
                switch(item.type){
                    case 'text':
                    case 'textarea':
                        if(el.value === '' || (this.options.inside === true && el.value === el.retrieve('orig_name'))){
                            this.options.errors.push(' - '+this.makeErrorMsg(el,item,'required'));
                        }
                        else if(item.validate !== '' && el.value.test(item.validate) === false){
                            this.options.errors.push(' - '+this.makeErrorMsg(el,item,'validate'));
                        }
                    break;
                    case 'enum':
                        if(el.value === ''){this.options.errors.push(' - '+this.makeErrorMsg(el,item,'required'));}
                    break;
                    case 'checkbox':
                        if(!el.checked){this.options.errors.push(' - '+this.makeErrorMsg(el,item,'required'));}
                    break;
                }
            }
        },this);

        if(this.options.errors.length < 1){
            return true;
        }
        else {
            return this.makeResultMsg();
        }
    }

});

