/**
 * Controller JS Writen by Serymoon http://www.serymoon.com
 * lastupdate: 2010-10-27-1925
 *  Use Mootols for http://www.mootools.net
 */

/*érkező data tömb lehetséges felépítése
 * 
 * top_data = array(where, type, position, inject, data)
 * inner data = array(tag, params, data, inject)
 *
 */



// érkező adatok renderelése

var Sjs = {
    
    autoloader: [],
    addLoader: function(func) {
        //alert(func.toString())
        this.autoloader.push(func)
    },

    autoLoad: function() {
        //alert('SSSS');
        if (this.autoloader.length) {
            this.autoloader.each(function(value) {
                value();
            });
            this.autoloader = [];
        }
    },

    refressClick: function(classname, callobj, callfn) { //callobj,
        
        $$(classname).each(function(value, key) {
            
            value.removeEvents('click');
            value.addEvent('click', function(event){
                event.stop();
                callobj[callfn](this); //callobj[callfn]
            });
        })
    },

    requestJson: function(a,callobj, callfn) {
        var jsonRequest = new Request.JSON({
            method: 'post',
            url: a,
            onSuccess: function(txt, response){
                //callfn(response);
            },
            onComplete: function(request){

                callobj[callfn](request);
            },
            onFailure: function(error){
                alert('Plese contact site Administrator! Error No.:' + error);
            }
        }).post({
            'json': 'request'
        });
    },

    requestHtml: function(a, callobj, callfn) {
        var htmlRequest = new Request.HTML({
            
            method: 'post',
            url: a,
            onSuccess: function(txt, response){
                
                //callfn(txt);
            },
            onComplete: function(a,b,c,d){
                
                callobj[callfn](c);
            },
            onFailure: function(error){
                alert('Plese contact site Administrator! Error No.:' + error);
            }
        }).post({
            'html': 'request'
        });
    },

    defaultReplacer: function(cssclass){
        //alert('SDF')
        $$(cssclass).each(function(e){
            //alert('AS')
            e.basevalue = e.get('value');
            e.addEvents({
                focus: function(){
                    if (this.basevalue == this.get('value')) this.set('value', '');
                },
                blur: function(){
                    if (this.get('value') == '') this.set('value', this.basevalue)
                }
        
            })

        })
    },

    questionRefress: function(cssclass, question, advanced){
        $$(cssclass).each(function(e){
            e.question = question;
            if (advanced) {
                e.addEvent('click', function(event){
                    alert('HAHA');
                    event.stop();
                })
            }else {
                e.addEvent('click', function(event){
                    if(!confirm(this.question)) event.stop();
                })
            }
            
        })
        
    }
};



/**
 * Animate buttons
 */

SjsImgButton = new Class({
    cssbase: null,//'.animbase',
    cssover: null,//'.animover',
    initialize:function(classname, classover){
        //if (classname) this.cssbase = classname;
        this.cssbase = classname || '.animbase';
        this.cssover = classover || '.animover';
        //alert('SD')
    },
    refress: function(){
        //alert('--' + this.cssbase);




        $$(this.cssbase).each(function(item){
            //alert()
            item.over = item.getElement(this.cssover);
            if (item.over) {
                item.over.setStyles({'visibility': 'hidden', 'opacity': 0.01});
                //item.over.setStyles({'width': 300});
                //item.over.fade(0.01);//*/
                item.addEvents({
                    'mouseover': function(){
                        //alert(this.over)
                        this.over.fade('in');
                    },
                    'mouseout': function(){
                        this.over.fade(0.01);
                    }
                })
            }
        }, this)
    }
})

/*var initiall =function(){
    var x =new SjsImgButton()
    x.refress();
}
Sjs.addLoader(initiall)//*/

        /**/

        SjsGallery = new Class({
            initialize:function(classname, bodyid, tclose, tnext, tprev) {
                this.cname = classname;
                this.bodyid = bodyid || 'docbody';
                this.close_str = tclose || 'Bezár';
                this.next_str = tnext || 'Következő';
                this.prev_str = tprev || 'Előző';
                this.prepared = false;
                this.pics = [];
                this.title = [];
            },

    

            prepareStage:function() {
                if (!this.prepared) {
                    var hidebg = new Element('div', {
                        id: 'gallery_bg'
                    });
                    var container = new Element('div', {
                        id: 'gallery_fg'
                    });
                    var img = new Element('img', {
                        id: 'gallery_image'
                    });
                    var imgtitle = new Element('div', {
                        id: 'gallery_image_title'
                    });

                    // tool prepare
                    var tool_cont = new Element('div', {
                        id: 'gallery_tool'
                    });
                    var tclose = new Element('div', {
                        id: 'gallery_close',
                        html: this.close_str
                    });
                    var tnext = new Element('div', {
                        id: 'gallery_next',
                        html: this.next_str
                    });
                    var tprev = new Element('div', {
                        id: 'gallery_prev',
                        html: this.prev_str
                    });

            
                    hidebg.inject($(this.bodyid), 'bottom');
                    container.inject($(this.bodyid), 'bottom');

                    img.inject($('gallery_fg'), 'top');
                    imgtitle.inject($('gallery_fg'), 'top');
                    tool_cont.inject($('gallery_fg'), 'top');
                    tclose.inject(tool_cont, 'top');
                    tprev.inject(tool_cont, 'top');
                    tnext.inject(tool_cont, 'top');

            
                    $('gallery_bg').setStyle('display', 'none')
                    $('gallery_fg').setStyle('display', 'none')

                    $('gallery_image').addEvent('click', function() {
                        $('gallery_bg').setStyle('display', 'none');
                        $('gallery_fg').setStyle('display', 'none');
                    });

                    $('gallery_close').addEvent('click', function() {
                        $('gallery_bg').setStyle('display', 'none');
                        $('gallery_fg').setStyle('display', 'none');
                    });

                    $('gallery_next').obj = this;
                    $('gallery_next').addEvent('click', function() {
                        var l = this.obj.pics.length;
                        var cimg = $('gallery_image').getProperty('src');
                        for(var i = 0; i < l; i++ ) {
                            if (this.obj.pics[i] == cimg && (i+1) < l) {
                                //$('gallery_image').setProperty('src', this.obj.pics[i+1])
                                this.obj.changeImg(this.obj, this.obj.pics[i+1], this.obj.title[i+1]);
                            }
                        }
                    })

                    $('gallery_prev').obj = this;
                    $('gallery_prev').addEvent('click', function() {
                        var l = this.obj.pics.length;
                        var cimg = $('gallery_image').getProperty('src');
                        for(var i = 0; i < l; i++ ) {
                            if (this.obj.pics[i] == cimg && (i) > 0) {
                                //$('gallery_image').setProperty('src', this.obj.pics[i-1])
                                this.obj.changeImg(this.obj, this.obj.pics[i-1], this.obj.title[i-1]);
                            }
                        }
                    })

                    this.prepared = true;
                }
            },

            changeImg: function(obj, src, title){





                new Asset.image(src, {
                    id: 'gallery_image',
                    onload:function(){

                        obj.loadedImg(src, title);



                    }
                })






                /*   $('gallery_image').setProperty('src', src);
        
        coord = $(obj.bodyid).getScrollSize();
        $('gallery_bg').setStyles({'display': 'block', 'height': coord.y, 'width': coord.x});
        $('gallery_fg').setStyles({'display': 'block', 'width': coord.x, 'top': $(obj.bodyid).getScroll().y+10});
        $('gallery_tool').setStyles({'width': $('gallery_image').getSize().x-($('gallery_tool').getStyle('padding-left').toInt()*2)});
//*/

            },

            loadedImg: function(src, title){
                $('gallery_image').setProperties({
                    'src': src,
                    'title': title
                });
                $('gallery_image_title').setProperty('text', title);
                coord = $(this.bodyid).getScrollSize();
        
                $('gallery_bg').setStyles({
                    'display': 'block',
                    'height': coord.y,
                    'width': coord.x
                });
                $('gallery_fg').setStyles({
                    'display': 'block',
                    'width': coord.x,
                    'top': $(this.bodyid).getScroll().y+10
                });
                $('gallery_tool').setStyles({
                    'width': $('gallery_image').getSize().x-($('gallery_tool').getStyle('padding-left').toInt()*2)
                });
        
                imgcoord = $('gallery_tool').getCoordinates();
                $('gallery_image_title').setStyles({
                    'top': imgcoord.height+$('gallery_tool').getStyle('margin-bottom').toInt(),
                    'left': imgcoord.left
                });
            },

            refress:function() {
                this.prepareStage();
                var imgs = $$(this.cname);
                var length = imgs.length;
                this.pics = [];
                this.title = [];
                for (var i=0; i < length; i++) {
                    this.pics.push(imgs[i].getProperty('alt'));
                    this.title.push(imgs[i].getProperty('title'));
                    imgs[i].obj = this
                    imgs[i].addEvent('click', function() {
                        ii = this.getProperties('alt', 'title');
                        this.obj.changeImg(this.obj, ii.alt, ii.title);
                        /*coord = $(this.obj.bodyid).getScrollSize();
                $('gallery_bg').setStyles({'display': 'block', 'height': coord.y, 'width': coord.x});
                $('gallery_fg').setStyles({'display': 'block', 'width': coord.x, 'top': $(this.obj.bodyid).getScroll().y+10});
                $('gallery_image').setProperty('src', this.getProperty('alt'));//*/
                    });
                }

            }
        })

        SjsImageborder = new Class({
            initialize:function(classname, borderimg, overimg) {
                this.cn = classname;
                this.img = borderimg;
                this.over = overimg;
                this.replace();
            },

            replace: function() {

                var imgs = $$(this.cn)
                var len = imgs.length;
                //var overimg = this.overimg;

                for (var i = 0; i < len; i++) {

                    //alert(e)
                    //alert(e.replaced)
                    if (!imgs[i].replaced) {
                
                        img = imgs[i].getProperty('src');

                        imgs[i].setStyle('background', 'transparent url(' + img + ')');
                        imgs[i].replaced = true;
                        imgs[i].setProperty('src', this.img);
//alert(this.overimg)
                        if (this.over) {
                            eventer = imgs[i].getParent('div');
                            eventer.obj = this;
                            eventer.addEvents({
                                mouseover:function(){
                                    //alert(this.getElement('img'))
                                    this.getElement('img').set('src', this.obj.over);
                                },
                                mouseout:function(){
                                    this.getElement('img').set('src', this.obj.img);
                                }
                            })
                        }

                    }

                }
            }
        })

        SjsMessage = new Class({
            initialize: function(classname, vertical, posto, postopos) {
                
                this.msgbox = $$('div.' + classname);

                //alert('HE?');
                //alert(msgbox)
                this.msgbox.each(function(el, key) {

                    el.setStyle('position', 'absolute');
                    el.addClass('Sfw-message-popup');

                    var coord = el.getCoordinates();
                    
                    var full = $('docbody').getCoordinates();
                    //alert($('docbody').getScroll().y)
                    
                    if ($(posto)) {
                        //alert('sda')
                        verticalpos = $(posto).getCoordinates().top + postopos;
                    }
                    else {
                        verticalpos = vertical || $('docbody').getScroll().y + (full.height - coord.height)/2;
                    }

                    el.setStyles({
                        'left': (full.width - coord.width)/2 +'px',
                        'top': verticalpos + 'px'
                    })

                    el.addEvent('click', function() {
                        this.destroy();
                    })
                })
            }
        })

        SjsAccordion = new Class({
            initialize: function(contener_id, parameters) { //element, height, toggler, hiddentoggler
                this.htmlid = contener_id;
                this.cssclass = parameters.element || 'element';
                this.closedheight = parameters.closedheight || '50';
                this.csstoggler = parameters.toggler || '.toggler';
                this.csshtoggler = parameters.hiddentoggler || '.htoggler';
                this.instant = parameters.instant || false;
                this.opened = (parameters.opened !== undefined) ? parameters.opened : 0;
                this.load();
            },

            open: function(e, a, b) {
                //alert(this.obj)
                var curr = (a) ? e : this.getParent();
                //alert(b)
                b = b !== undefined ? b : true;
                //alert(b)
        
                var hide = null;
        
                for (var i = 0; i < curr.obj.len; i++) {

                    hide = curr.obj.alle[i].getChildren(curr.obj.csshtoggler);
                    var duration = 'long';//'normal';
                    if (curr.obj.alle[i].opened) {
                        curr.obj.alle[i].opened = false;

                        //curr.obj.alle[i].morph({height: curr.obj.closedheight});//curr.obj.closedheight
                        //hide.morph({top: -(curr.obj.alle[i].fullcoord.height - curr.obj.closedheight) + 'px'})
                        //alert('closed')
                        if (a !== undefined && curr.obj.instant) {
                            //alert('S')
                            duration = 1;
                        }
                        //else {
                        curr.obj.alle[i].set('morph', {
                            duration: duration
                        })
                        hide.set('morph', {
                            duration: duration
                        });
                        hide[0].set('tween', {
                            duration: duration
                        });
                        curr.obj.alle[i].morph({
                            height: curr.obj.closedheight
                        });//curr.obj.closedheight
                        hide.morph({
                            top: -(curr.obj.alle[i].fullcoord.height - curr.obj.closedheight) + 'px'
                        })
                        if (curr.obj.alle[i].fullcoord.height > curr.obj.closedheight) {
                            hide[0].fade('in');
                        }
                        else {
                            hide[0].fade('out');
                        }
                        //}
                    }
                    if (b && curr == curr.obj.alle[i]) {
                        //alert('OPEN')
                        curr.opened = true;

                        curr.set('morph', {
                            duration: duration
                        })
                        hide.set('morph', {
                            duration: duration
                        })
                        hide[0].set('tween', {
                            duration: duration
                        });

                        curr.morph({
                            height: curr.fullcoord.height,
                            duration: duration
                        })
                        hide.morph({
                            top: '0px',
                            duration: duration
                        })
                        hide[0].fade('out');
                    }
                }
            },

            load: function() {
                this.alle = $(this.htmlid).getChildren(this.cssclass);
                this.len = this.alle.length;
                this.alle.obj = this;
        
                var c = null;
                for (var i = 0; i < this.len; i++) {
                    c = this.alle[i];
                    c.obj = this;
                    c.opened = true;
                    c.fullcoord = c.getCoordinates();//height
                    c.setStyle('overflow', 'hidden');
                    //alert(this.csstoggler);
                    var x = c.getChildren(this.csstoggler);
                    var xlen = x.length;
                    for (var j = 0; j < xlen; j++) {
                        x[j].addEvent('click', this.open);
                    }
                    var y = c.getChildren(this.csshtoggler);
                    var ylen = y.length;
                    for (var k = 0; k < ylen; k++) {
                        y[k].addEvent('click', this.open);
                        //y[k].setPosition({y: -(c.fullcoord.height-this.closedheight)});
                    }
            
                }
        
                // open selected
        
                this.open_id = (this.opened !== false && this.len > this.opened) ? this.opened : 0;
                this.open(this.alle[this.open_id], 1, (this.opened !== false));
            }
        })


        var SjsAutoCompleter = new Class({
            initialize: function(element, jsonurl) {
                this.el = $(element);
                this.url = jsonurl;
                this.make();

            },

            make: function() {
                var basename = this.el.get('name');
                this.el.set('name', basename + '_SAC');
                this.el.addClass('SAC-popup');
                this.el.set('autocomplete', 'off');
                this.replacer = new Element('input', {
                    type: 'hidden',
                    name: basename,
                    id: this.el.get('id') + '_SAC'
                });
                this.popup = new Element('div', {
                    id: this.el.get('id') + '_Spop',
                    'class': 'SAC-box',
                    'style': 'display:none;'
                });
                this.popup.inject(this.el, 'after');
                this.replacer.inject(this.el, 'before');
                this.replacer.set('value', this.el.get('value'));

                /*$$('form').each(function(value) {
            value.addEvent('submit', function(e) {
                //alert(e.code );
                 e.stop();//if (e.key == 'enter')
            })
        })

        $$('input.').each(function(value) {
            alert(value.get('name'));
            if (value.get('type') == 'submit') {
                
                value.addEvenet('click', function(e) {
                    alert('SSS'); //e.getParent('form')
                })
            }
        })//*/

                //this.el.url = this.url;
                this.el.obj = this
                this.el.addEvents({
                    'keydown': function(e) {
                        //clear fuckin submit for autocompleter

                        if (e.key == 'enter') {
                            e.stopPropagation();
                            e.preventDefault();
                        }

                    },
                    'keyup': function(e) {

                
                        if (e.key != 'up' && e.key != 'down' && e.key != 'enter') {
                            Sjs.requestJson(this.obj.url + '/search:' + e.target.get('value'), this.obj, 'replace');
                        }
                        else {
                            this.obj.navigate(e.key);

                        }

                
                
                    },

                    'focus': function() {
                        Sjs.requestJson(this.obj.url + '/search:' + this.get('value'), this.obj, 'replace');
                    },
                    'blur': function() {

                        // clear data hidden object if cell is empty, or hidden empty and input not empty insert input text to hidden input
                        var visible = this.get('value');
                        var hidden = this.getPrevious().get('value');

                        if (!visible) this.getPrevious().set('value', '');
                        if (visible && !hidden) this.getPrevious().set('value', visible);


                        this.obj.hide.delay(1000, this.obj);
                    }
                });
            },

            replace: function(a) {
                //alert();
                //this.addItem('A', 'Y')
                this.hide()
                this.popup.set('html', '');
                var l = a.key.length;
                for(var i = 0; i < l; i++) {
                    this.addItem(a.key[i], a.value[i]); //, a.value[i]
                }
                if (l) this.show();
            },

            show: function() {
                this.popup.setStyle('display', 'block')
            },

            hide: function() {
                this.popup.setStyle('display', 'none')
            },

            navigate: function(key) {
                var c = this.selected()
                this.deselect();
                //alert(c)
                var a
                switch(key) {
                    case 'up':
                
                        a = (c === false) ? (this.popup.getChildren().length - 1) : (c-1);
                        this.select(a)
                        break;
                    case 'down':
                        a = (c === false) ? 0 : (c+1);
                        this.select(a)
                        break;
                    case 'enter':

                        var ch = this.popup.getChildren()[c].getChildren();
                        this.replacer.set('value', ch[1].get('text'));
                        this.el.set('value', ch[0].get('text'));
                        this.hide();
                        break;
                    default:
                }
            },

            selected: function() {
                var all = this.popup.getChildren();
                var s = false;

                all.each(function(value, key) {
                    if (value.hasClass('SAC-selected')) s = key;
                })
                return s;

            },

            deselect: function() {
                var all = this.popup.getChildren();
                all.each(function(value, key) {
                    value.removeClass('SAC-selected');
                })
            },

            select: function(a) {
                //alert(a);
                var all = this.popup.getChildren();
        
                if (all[a]) all[a].addClass('SAC-selected');
            
            },

            addItem: function(k, v) {
        
                var a = new Element('div');
        
                a.inject(this.popup, 'bottom');
                a.set('html', '<span>' + v + '</span><span style="display:none;">' + k + '</span>')
                a.obj = this
                a.addEvents({
                    'mouseover': function() {
                        this.obj.deselect();
                        this.addClass('SAC-selected');
                    },

                    'click': function() {
                        var ch = this.getChildren();
                        this.obj.replacer.set('value', ch[1].get('text'));
                        this.obj.el.set('value', ch[0].get('text'));
                        this.obj.hide();
                    }
                })
            }
        })





        /**
         * sprintf() for JavaScript v.0.4
         *
         * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
         * Thanks to David Baird (unit test and patch).
         *
         * This program is free software; you can redistribute it and/or modify it under
         * the terms of the GNU General Public License as published by the Free Software
         * Foundation; either version 2 of the License, or (at your option) any later
         * version.
         *
         * This program is distributed in the hope that it will be useful, but WITHOUT
         * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
         * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
         * details.
         *
         * You should have received a copy of the GNU General Public License along with
         * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
         * Place, Suite 330, Boston, MA 02111-1307 USA
         */

        function str_repeat(i, m) {
            for (var o = []; m > 0; o[--m] = i);
            return(o.join(''));
        }

        function sprintf () {
            var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
            while (f) {
                if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
                else if (m = /^\x25{2}/.exec(f)) o.push('%');
                else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
                    if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
                    if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
                        throw("Expecting number but found " + typeof(a));
                    switch (m[7]) {
                        case 'b':
                            a = a.toString(2);
                            break;
                        case 'c':
                            a = String.fromCharCode(a);
                            break;
                        case 'd':
                            a = parseInt(a);
                            break;
                        case 'e':
                            a = m[6] ? a.toExponential(m[6]) : a.toExponential();
                            break;
                        case 'f':
                            a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a);
                            break;
                        case 'o':
                            a = a.toString(8);
                            break;
                        case 's':
                            a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a);
                            break;
                        case 'u':
                            a = Math.abs(a);
                            break;
                        case 'x':
                            a = a.toString(16);
                            break;
                        case 'X':
                            a = a.toString(16).toUpperCase();
                            break;
                    }
                    a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
                    c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
                    x = m[5] - String(a).length;
                    p = m[5] ? str_repeat(c, x) : '';
                    o.push(m[4] ? a + p : p + a);
                }
                else throw ("Huh ?!");
                f = f.substring(m[0].length);
            }
            return o.join('');
        };
