LBP.Media = new Hash({
    presets: {
        container: 'container',
        pagebody: 'pagebody-wrapper',
        btnCss: 'button-state',
        aBtnCss: 'button-3-state',
        wBtnCss: 'button-2-state'
    },
    initialize: function(options) {
        this.presets = $merge(this.presets,options || {});
    },
    distributeHTML: function(responseString){
        var responseArr = JSON.decode(responseString);
        $each(  responseArr, function(elementData, elementID, arr){
            if($(elementID)){
                var injectMode = elementData['inject'];
                switch(injectMode) {
                    case 'overwrite':
                        $(elementID).set('html', elementData['html']);
                        LBP.processScripts( elementData['html'] );
                        $(elementID).fireEvent('onReLoad');
                        break;
                    case 'destroy':
                        $(elementID).destroy();                        
                        break;
                    default:
                        var temp = new Element('div', { 'class': 'dwrapper'});
                        dwrapper.set('html', elementData['html']);
                        dwrapper.inject($(elementID), injectMode);
                        LBP.processScripts( elementData['html'] );
                        break;
                }
            }
        });
    },
    setGlobal: function(){
        LBP.Tip.assign($$('a.tip-item'), {position: 'vCenter', tipCss: 'tip-content', margin: 2, opacity: 0.86});
        LBP.Tip.assign($$('.ltip-item'));
        $$('a[class^=returnback]').each(function(currentLink){
            currentLink.removeEvents('click');
            var setLocationFnc = function(event){
                if(LBP.Links.isAttached(currentLink)){
                    event.preventDefault();
                    LBP.setReturnURL(window.location.href);
                    LBP.Links.forceSubmitLink(currentLink);
                } else {
                    window.location.href = currentLink.href;
                }
            };
            currentLink.addEvent('click', setLocationFnc);
        });
        
        $$('input.'+this.presets.btnCss).each(function(btnObj){
            if(!btnObj.retrieve('assignedState')) {
                btnObj.addEvents({
                    'mouseenter': function(event){
                        event.stopPropagation();
                        if(btnObj.hasClass('button-down')) btnObj.removeClass('button-down');
                        btnObj.addClass('button-hover');
                    },
                    'mouseleave': function(event){
                        event.stopPropagation();
                        btnObj.className = 'button';
                    },
                    'mousedown': function(event){
                        event.stopPropagation();
                        if(btnObj.hasClass('button-hover')) btnObj.removeClass('button-hover');
                        btnObj.addClass('button-down');
                    },
                    'mouseup': function(event){
                        event.stopPropagation();
                        btnObj.className = 'button';
                    }
                });
                btnObj.store('assignedState', true);
            }
        });
        $$('.'+this.presets.wBtnCss).each(function(btnObj){
            if(!btnObj.retrieve('assignedState')) {
                btnObj.removeClass(this.presets.wBtnCss);
                btnObj.addEvents({
                    'mouseenter': function(event){
                        if(!btnObj.hasClass('hover')) btnObj.addClass('hover');
                    },
                    'mouseleave': function(event){
                        if(btnObj.hasClass('hover')) btnObj.removeClass('hover');
                    }
                });
                btnObj.store('assignedState', true);
            }
        }.bind( this ));
        
        $$('a.'+this.presets.aBtnCss).each(function(btnObj){
            if(!btnObj.retrieve('assignedState')) {
                btnObj.removeClass(this.presets.aBtnCss);
                btnObj.addEvents({
                    'mouseenter': function(event){
                        event.stopPropagation();
                        if(!btnObj.hasClass('active')) btnObj.addClass('hover');
                    },
                    'mouseleave': function(event){
                        event.stopPropagation();
                        if(btnObj.hasClass('hover')) btnObj.removeClass('hover');
                    },
                    'mousedown': function(event){
                        event.stopPropagation();
                        if(btnObj.hasClass('hover')) btnObj.removeClass('hover');
                        btnObj.addClass('active');
                    },
                    'mouseup': function(event){
                        event.stopPropagation();
                        if(btnObj.hasClass('active')) btnObj.removeClass('active');
                    }
                });
                btnObj.store('assignedState', true);
            }
        }.bind( this ));
        //modal assignment
        LBP.Modal.assign($$('a[rel=modal-image]'),{ type: 'image', header: false});
        LBP.Modal.assign($$('a[rel=modal-confirm]'),{ type: 'confirm', header: false, content: 'element', callerMarker: 'modalcaller', 
            button:[ 
                { id: 'button_ok', action: 'selfajax', caller: '', label: 'Thực hiện', fn: function(){ LBP.Modal.close(); } },
                { id: 'button_cancel', action: 'cancel', label: 'Trở về'}]
        });
        LBP.Modal.assign($$('a[rel=modal-ajax]'),{ type: 'ajax', header: true, ajaxMarker:'modalcaller'});
        //attached ajax urls & form
        $$('[a[rev!=]').each(function(linkObj) {
            if(!LBP.Links.isAttached(linkObj)) {
                LBP.Links.attachLink(linkObj);
            }
        });
        $$('form.ajaxform').each(function(formObj){
            LBP.Media.Forms.assign(formObj);
        });
        $$('form.lbp').each(function(formObj){
            if(!LBP.Forms.isAttached(formObj)) { LBP.Forms.attachForm(formObj); }
        });
        $$('a[scroll!=]') .each(function(linkObj){
            if(!linkObj.retrieve('scrollto')) {
                var scrollTo = linkObj.get('scroll');
                if(scrollTo) {
                    linkObj.store('scrollto', scrollTo);
                    linkObj.removeProperty('scroll');
                    linkObj.addEvent('click',function(event){
                        event.stop();
                        if($(linkObj.retrieve('scrollto'))) {
                            var position = $(linkObj.retrieve('scrollto')).getPosition();
                            window.scrollTo(position.x, position.y);
                        }
                    });
                }
            }
        });
        //onchange submit for select dropdown list
        $$('select[rel=submit]').each(function(selObj){
            if(!selObj.retrieve('processed')) {
                selObj.store('processed', true);
                selObj.addEvent('change', function(event){
                    var formObj = selObj.getParent('form');
                    LBP.Media.Forms.submitForm(formObj);
                });
            }
        });
        
        //select
        var myselect = new LBP.Dropdownlists({  wrapperName: 'ed-dropdown', selectListWidthDiff: -9, injectTo: 'wrapper'});
        var myselect2 = new LBP.Dropdownlists({  wrapperName: 'ed-dropdown2', selectListWidthDiff: -9, selectListClassName: 'editor-select-list'});        
        var portselect = new LBP.Dropdownlists({  wrapperName: 'toolbar-dropdown', selectListWidthDiff: -2, injectTo: 'wrapper'});
        var portselect2 = new LBP.Dropdownlists({  wrapperName: 'toolbar-dropdown2', selectListWidthDiff: -10, selectListClassName: 'editor-select-list', injectTo: 'wrapper', modal: true });
        var plselect = new LBP.Dropdownlists({  wrapperName: 'pl-dropdown', selectListWidthDiff: 0, injectTo: 'wrapper' });
                
        $$('div.scrollslider').each(function(obj){
            var options = {};
            ['container', 'wrapper', 'total', 'perSlide', 'startPage', 'mode', 'prefix', 'dump'].each(function(item){
                options[item] = obj.get(item);
                obj.removeProperty(item);
            }.bind(this));
            var seriesPL = new LBP.ScrollSlider(options.container, options.wrapper, options);
        }.bind(this));
    },
    setPageName: function(pagename) {
        $(this.presets.pagebody).className = '';
        $(this.presets.pagebody).addClass(pagename);
    },
    setPageTitle: function(title) {
        document.title = title.replace(/RAQUO/g,'\273');
    },
    setUpError: function() {
        window.store('accLeftBox', $pick(window.retrieve('accLeftBox'), new LBP.Alertx({ duration: 5000, position: 'upperLeft', type: 'errorbx'})));
        window.addEvent('onError', function(msg, alertType, title, cusFunc, arguments, bindObj){
            var error = window.retrieve('accLeftBox');
            var options = (title && title !='')? { txtTitle: title} : {};
            error.generateAlert(msg, options);
            if(cusFunc) { cusFunc.run(arguments, bindObj); }
        });
    }
});

LBP.Media.Search = new Class ({
    Implements: [Events, Options],
    options: {
        formId: 'search_form',
        fieldId: 'search-string',
        searchBtn: 'search-btn',
        wrapper: 'search-bar-wrapper',
        dfltStr: ''
    },
    initialize: function(options){
        this.setOptions(options);
        if(!$(this.options.formId) || $(this.options.formId).retrieve('wasAttached')) return;
        this.formObj = $(this.options.formId);
        this.formObj.store('wasAttached', true);
        this.fieldObj = $(this.options.fieldId);
        this.fieldObj.value = this.options.dfltStr;
        this.wrapper = $(this.options.wrapper);
        this.fieldObj.addEvents({
            'focus' : function(event){
                event.stop();
                if(this.fieldObj.value == this.options.dfltStr) this.fieldObj.value = '';
                this.wrapper.className = 'active';
            }.bind( this ),
            'blur' : function(event) {
                event.stop();
                if(this.fieldObj.value == '') this.fieldObj.value = this.options.dfltStr;
                this.wrapper.className = '';
            }.bind( this )
        });
        this.formObj.addEvent(
            'submit', function(event) {
                event.stop();
                var value = this.fieldObj.value.clean();
                if(value.length < 3) {
                    window.fireEvent('onError', ['Chuỗi tìm kiếm quá ngắn, xin bạn vui lòng nhập từ 3 ký tự trở lên.', 'errorbx','Có lỗi']);
                } else if(value == this.options.dfltStr) {
                    window.fireEvent('onError', ['Bạn chưa nhập chuỗi tìm kiếm', 'errorbx', 'Có lỗi']);
                } else {
                    var searchstring = this.fieldObj.value.clean();
                    searchstring = searchstring.replace(/ /g,'+');
                    if($('search-query')) {
                        $('search-query').value = searchstring;
                    } else {
                        this.formObj.adopt( new Element( 'input', { type: 'hidden', name: 'q', id: 'search-query', value: searchstring }));
                    }
                    ourHM.setValues('url', ["http://fansub.acc.vn/tim-kiem.htmx?q="+searchstring, 'globalsearchbar']);
                    LBP.Forms.forceSubmitForm(this.formObj);
                }
            }.bind(this)
        );
    }
});
LBP.Media.Links = new Hash({
    options: new Hash({
        caller: 'caller',
        caption: 'caption',
        target: 'captarget',
        overlay: 'section'
    }),
    initialize: function(options) {
        options = options || {};
        this.options = $merge(this.options, options);
    },
    bound: $empty,
    toggleLoading: function(state, request){
        if(!LBP.Media.Links.overlay) { LBP.Media.Links.overlay = new Element("div",{ id:'media-overlay' });
        if(state) {
            if(!LBP.Media.Links.container) return;
            $(document.body).adopt(LBP.Media.Links.overlay);
            LBP.Media.Links.overlay.addEvent('click', function(event){
                event.stopPropagation();
                if(confirm('Bạn có chắc muốn cancel request?')) {
                    request.cancel();
                    LBP.Media.Links.overlay.set('styles', { display: 'none'});
                }
            });
        
            }
            var size = LBP.Media.Links.container.getSize(), scroll = LBP.Media.Links.container.getPosition();
            LBP.Media.Links.overlay.set('styles',{ display: '', width: size.x+'px', height: size.y+'px', top: scroll.y+'px', left: scroll.x+'px', opacity: 0.8 });
        } else {
            LBP.Media.Links.overlay.set('styles',{ display: 'none' });
        }
    },
    assign: function(obj) {
        if(!obj.retrieve('managedByMedia')) {
            this.options.each(function(item, key){
                var temp = obj.get(item);
                if(temp && temp !='') {
                    obj.store(key, temp);
                    obj.removeProperty(item);
                }
            });
            this.bound = function(event){
                LBP.Media.Links.submitLink(event, obj);
            };
            obj.addEvent('click', this.bound.bind(this));
            obj.store('managedByMedia', true);
        }
    },
    submitLink: function(event, obj) {
        event.stop();
        var objUrl = $pick(obj.get('href'), obj.retrieve('href'), false);
        if(objUrl && objUrl !='') {
            var caption = obj.retrieve('caption');
            var caller = obj.retrieve('caller');
            if(caption && caption !='') {
                $(obj.retrieve('target')).set('html', caption);
            }
            this.container = $(obj.retrieve('overlay'));
            var mediarequest = new Request({ 
                'url': objUrl,
                'caller': caller,
                async: false,
                autoCancel: true,
                onRequest: function() {
                    LBP.Media.Links.toggleLoading(true, this);
                    window.fireEvent('onRequest');
                    if (this.options.caller){
                        ourHM.setValues('url', [this.options.url, this.options.caller]);
                    }
                },
                onSuccess: function(response){
                    try {
                        LBP.Media.distributeHTML(response);
                        LBP.runProcesses();
                        LBP.Media.Links.toggleLoading.delay(100,false);
                    } catch(e) {
                        window.fireEvent('onError', [ response || 'Chưa có nội dung', 'errorbx', 'Có lỗi xảy ra' ]);
                        LBP.Media.Links.toggleLoading.delay(10,false);
                    }
                }.bind(this),
                onFailure: function(instance) {
                    LBP.Media.Links.toggleLoading.delay(100,false);
                    window.fireEvent('onError', [instance.statusText, 'errorbx', 'Có lỗi - '+instance.status]);
                }
            }).send('sendby=' + caller + '&dmode=html_ajax');
        } else {
            obj.removeEvent('click', this.bound.bind(this));
        }
    }
});
LBP.Media.Forms = new Hash({
    options: new Hash({
        caption: 'caption',
        target: 'captarget',
        overlay: 'section'
    }),
    initialize: function(options) {
        options = options || {};
        this.options = $merge(this.options, options);
    },
    bound: $empty,
    assign: function(obj) {
        if(!obj.retrieve('managedByMedia')) {
            this.options.each(function(item, key){
                var temp = obj.get(item);
                if(temp && temp !='') {
                    obj.store(key, temp);
                    obj.removeProperty(item);
                }
            });
            this.bound = function(event){
                try{ event.stop(); } catch(err){};
                LBP.Media.Forms.submitForm(obj);
            };
            obj.addEvent('submit', this.bound.bind(this));
            obj.store('managedByMedia', true);
        }
    },
    submitForm: function(obj) {
        if (!obj.getElement('input[name=sendby]')){
            new Element( "input", { 'type': 'hidden', 'name': 'sendby', 'value': 'lbp' }).inject(obj,'top');
            var requestCaller = 'lbp';
        }
        else {
            var requestCaller = obj.getElement('input[name=sendby]').value;
        }

        if (!obj.getElement('input[name=dmode]')){
            obj.adopt(new Element( "input", { 'type': 'hidden', 'name': 'dmode', 'value': 'html_ajax' }));
        }
        var caption = obj.retrieve('caption');
        if(caption && caption !='') {
            $(obj.retrieve('target')).set('html', caption);
        }
        LBP.Media.Links.container = $(obj.retrieve('overlay'));
        var mediarequest = new Request({ 
            'url': obj.get('action'),
            'data': obj,
            'method': 'post',
            'caller': requestCaller,
            async: false,
            autoCancel: true,
            onRequest: function() {
                LBP.Media.Links.toggleLoading(true, this);
                ourHM.setValues('url', [this.options.url, this.options.caller]);
                if (this.options.caller){
                    ourHM.setValues('url', [this.options.url, this.options.caller]);
                }
            },
            onSuccess: function(response){  
                try {
                    LBP.Media.distributeHTML(response);
                    LBP.runProcesses();
                    LBP.Media.Links.toggleLoading.delay(100,false);
                } catch(e) {
                    window.fireEvent('onError', [ response, 'errorbx', 'Có lỗi xảy ra' ]);
                    LBP.Media.Links.toggleLoading(false);                    
                } 
            },
            onFailure: function(instance) {
                LBP.Media.Links.toggleLoading.delay(100,false);
                window.fireEvent('onError', [instance.statusText, 'errorbx', 'Có lỗi - '+instance.status]);
            }
        }).send();
    }
});
LBP.Media.Tab = new Class({
    Implements: [Events, Options],
    options : {
        mode: 'static', // static || dynamic || auto
        headerCss: '',
        contentCss: '',
        contentInner: '',
        overlayCss: '',
        currentCss:'',
        markers: { url: 'href', caller: ''},
        dfltIdx: -1,
        collapse: '',
        onHover: $empty,
        onOut: $empty,
        onShow: $empty,
        onHide: $empty
    },
    initialize: function(container, options) {
        if(!container || $type(container) != 'element') return;
        this.container = $(container);
        this.setOptions(options);
        this.build();
        if(this.current){ this.current.fireEvent('click');};
        var onreload = this.build.bind(this);
        this.container.addEvent('onReload', onreload);        
    },
    build: function() {
        this.items = [];
        this.container.getElements('.'+this.options.contentCss).each(function(content){
            if(!content.retrieve('tabProcessed')) {
                content.set('styles',{ display: 'none'});
                if(this.options.mode =='auto'){
                    var cntHtml = content.get('html');
                    cntHtml = cntHtml.trim();
                    content.store('hasContent', (cntHtml != ''));
                }
                this.items.push(content);
            }
            content.store('tabProcessed', true);
        }.bind(this));
        var i = 0;
        this.container.getElements('.'+this.options.headerCss).each(function(item){
            //try{
            if(!item.retrieve('tabProcessed')) {
                item.store('tabContent', this.items[i]);
                if(this.options.dfltIdx == i+1 || item.hasClass(this.options.currentCss)){ this.current = item; }
                i++;
                item.addEvents({
                    'click': function(event){ 
                        if(event) { event.stop();}                        
                        this[this.options.mode+'Click'](item, item.retrieve('tabContent'));
                    }.bind(this),
                    'mouseenter': function(event){ event.stop(); var myfn = this.options.onHover || this.onHover; myfn.run([item, this]); }.bind(this),
                    'mouseleave': function(event){ event.stop(); var myfn = this.options.onOut || this.onOut; myfn.run([item, this]); }.bind(this),
                    'onHide': function(item, tab){ if(this.options.onHide) this.options.onHide.run([item, tab]); }.bind(this),
                    'onShow': function(item, tab){ if(this.options.onShow) this.options.onShow.run([item, tab]); }.bind(this)
                });
                item.store('tabProcessed', true);
                if(this.options.mode != 'static'){
                    $each(this.options.markers, function(mrk, key){
                        var temp = item.get(mrk) || '';                        
                        if(temp && temp !='') {
                            item.store(key, temp);
                            item.removeProperty(key);
                        };
                    }.bind(this));
                }
            }
            //} catch(err){ window.fireEvent('tab error'); };
            this.session = LBP.getCookie('acc_session_code');
        }.bind(this));
        this.items.empty();
        if(this.options.collapse) {
            this.container.getElements('.'+this.options.collapse).each(function(closeBtn){
                closeBtn.addEvent('click', function(){ this.collapse(); }.bind(this));
            }.bind(this));
        }
    },
    collapse: function(){
        if(this.current) {
            this.hide(this.current, this.current.retrieve('tabContent'));
        }
        this.current = null;
        window.scrollTo(this.container.offsetLeft, this.container.offsetTop);
    },
    onHover: function(item){
        if(!item.hasClass('hover')) { item.addClass('hover'); }
    },
    onOut: function(item){
        if(item.hasClass('hover')) { item.removeClass('hover'); }
    },
    show: function(item, content) {
        content.style.display = 'block';
        item.addClass(this.options.currentCss);
        item.fireEvent('onShow',[item, this]);
    },
    hide: function(item, content) {
        if(item.hasClass(this.options.currentCss)) item.removeClass(this.options.currentCss);
        content.style.display = 'none';
        item.fireEvent('onHide',[item, this]);
    },
    autoClick: function(item, content) {        
        var newSession = LBP.getCookie('acc_session_code');
        if(!content.retrieve('hasContent') || this.session!= newSession){
            this.dynamicClick(item, content);
        } else {            
            this.staticClick(item, content);
        }
    },
    staticClick: function(item, content) {        
        if(this.current == item && content.style.display != 'none') return;
        if(this.current) this.hide(this.current, this.current.retrieve('tabContent'));
        this.show(item,content);
        this.current = item;
    },
    dynamicClick: function(item, content) {
        var newSession = LBP.getCookie('acc_session_code');
        if(this.current == item && newSession == this.session) return;        
        this.session = newSession;
        var statefn = { onSuccess: this.onSuccess.bind(this), onFailure: this.onFailure.bind(this), onRequest: this.onRequest.bind(this) };
        var itemUrl = item.retrieve('url') || '';
        var itemCaller = item.retrieve('caller');        
        if(itemUrl != '') {
            this.clicked = item;
            LBP.Media.Links.container = content;
            var dyanmicrequest = new Request($merge({ url: itemUrl, caller: itemCaller, async: false, autoCancel: true}, statefn)).send('sendby=' + itemCaller + '&dmode=html_ajax');
        }
    },
    onSuccess: function(response) {        
        LBP.toggleLoading(false);
        var item = this.clicked;
        var content = item.retrieve('tabContent');
        if(this.current) this.hide(this.current, this.current.retrieve('tabContent'));
        this.show(item,content);
        this.current = item;
        content.store('hasContent', true);
        LBP.Media.distributeHTML(response);
        LBP.runProcesses();
    },
    onFailure: function() {
        //if(this.current.hasClass(this.options.overlayCss)) this.current.removeClass(this.options.overlayCss);
        LBP.toggleLoading(false);
    },
    onRequest: function() {
        //this.current.addClass(this.options.overlayCss);
        LBP.toggleLoading(true);
    }    
});