/* personal nav show and hide */
function personalNav_show(){
    if(!$('personal_nav')) return false;
    $$('#personal_nav li').each(function(li){
        li.observe('mouseover',function(){
            var ul=this.select('ul').first();
            if(ul){
                ul.style.display='block';
            }
        }).observe('mouseout',function(){
            var ul=this.select('ul').first();
            if(ul){
                ul.style.display='';
            }
        })
    })
}
//== require <prototype>
Ajax.PeriodicalUpdaterWithMaxDecay = Class.create(Ajax.PeriodicalUpdater, {
    initialize: function($super, container, url, options) {
        $super(container, url, options);
        this.maxDecay = (this.options.maxDecay || 30);
    },
    updateComplete: function(response) {
        if (this.options.decay) {
            if( response.responseText == this.lastText ) {
                var newDecay = this.decay * this.options.decay;
                this.decay = newDecay > this.maxDecay ? this.maxDecay : newDecay;
            }
            this.lastText = response.responseText;
        }
        this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
    }
});

Element.addMethods({
    replaceSelection: function(element, content) {
        element = $(element);
        if((element.tagName.toLowerCase() == 'input' && element.type == 'text') || element.tagName.toLowerCase() == 'textarea' ) {
            element.focus();
            if( document.selection ) {
                document.selection.createRange().text = content;
            } else {
                var start = element.selectionStart;
                var end = element.selectionEnd;
                var value = element.value;
                element.value = value.substring(0, start) + content + value.substring(end, value.length);
                element.selectionStart = start + content.length;
                element.selectionEnd = element.selectionStart;
            }
        }
    },
    wrapSelection: function(element, prefix, postfix) {
        element = $(element);
        if((element.tagName.toLowerCase() == 'input' && element.type == 'text') || element.tagName.toLowerCase() == 'textarea' ) {
            element.focus();
            if( document.selection ) {
                var text = document.selection.createRange().text;
                document.selection.createRange().text = prefix + text + postfix;
            } else {
                var start = element.selectionStart;
                var end = element.selectionEnd;
                var value = element.value;
                var content = prefix + value.substring(start, end) + postfix;
                element.value = value.substring(0, start) + content + value.substring(end, value.length);
                element.selectStart = start + content.length;
                element.selectEnd = element.selectStart;
            }
        }
    }
});

var MixiEffect = {
    makeTabable: function(wrapper, invoker, handler, selectedClassName) {
        var wrapper = $(wrapper);
        if(!wrapper) return;
        wrapper.select(invoker).each(function(ele, index) {
            ele.observe('mouseover', function(event) {
                wrapper.select(invoker).invoke('removeClassName', selectedClassName);
                wrapper.select(handler).invoke('hide');
                this.addClassName(selectedClassName);
                wrapper.select(handler)[index].style.display = "block";
            });
        }); 
    },  
    makeSlidable: function(scrollcontent,mouseevent,showamount) {
        if(!$(scrollcontent)) return false;
        var textchanged='<a href="" id="slidepre" style="">前一页</a><a href="" id="slidenext">后一页</a>';
        Insertion.After($(scrollcontent).ancestors()[0],textchanged);
        var number = 0;
        $$('#' + scrollcontent + '>li').each(function(item) {
            distance=parseInt(item.getWidth())+parseInt(item.getStyle('margin-right'))+parseInt(item.getStyle('margin-left'));
            number += distance;
        })
        $(scrollcontent).setStyle({
            'width': number + 'px'
        });
        $('slidepre').hide();
        if( $$('#' + scrollcontent + '>li').length <= showamount )  {
            $('slidenext').hide();
        }
        
        function prescroll(){
            new Effect.Move($(scrollcontent), {
                beforeStart: function(){
                    $('slidepre').stopObserving(mouseevent, prescroll);
                },
                x: distance,
                afterFinish: function(){
                    $('slidepre').observe(mouseevent, prescroll);
                    if($('slidenext').style.display == 'none'){
                        $('slidenext').appear({
                            duration: 0.5
                        });
                        $('slidenext').observe(mouseevent, nextscroll);
                    }
                    if ($(scrollcontent).style.left == '0px') {
                        $('slidepre').stopObserving(mouseevent, prescroll);
                        $('slidepre').fade({
                            duration: 0.5
                        });
                        $('slidenext').observe(mouseevent, nextscroll);
                    }
                }
            });
        }

        function nextscroll(){
            new Effect.Move($(scrollcontent), {
                beforeStart: function(){
                    $('slidenext').stopObserving(mouseevent, nextscroll);
                },
                x: -distance,
                afterFinish: function(){
                    $('slidenext').observe(mouseevent, nextscroll);
                    if ($('slidepre').style.display == 'none') {
                        $('slidepre').appear({
                            duration: 0.5
                        });
                        $('slidepre').observe(mouseevent, prescroll);
                    }
                    if (parseFloat($(scrollcontent).style.left) <= (showamount*distance-number)) {
                        $('slidenext').stopObserving(mouseevent, nextscroll);
                        $('slidenext').fade({
                            duration: 0.5
                        });
                        $('slidepre').observe(mouseevent, prescroll);
                    }
                }
            });
        }
        $('slidenext').observe(mouseevent, function(event){
            event.stop();
        });
        $('slidepre').observe(mouseevent, function(event){
            event.stop();
        });
        
        $('slidenext').observe(mouseevent, nextscroll)
        $('slidepre').observe(mouseevent, prescroll)
    },
    showWarning: function(result) {
        var errorEle = $('error_panel');
        if(!errorEle) {
            var errorEle = new Element('div', {
                id: 'error_panel'
            }).setStyle({
                width: '400px'
            }).addClassName('pop');
            var html =  
                '<p class="pop_prompt"><strong>提示</strong><a href="javascript:void(MixiEffect.hide(\'error_panel\'))">关闭</a></p>' +
                '<div class="pop_content">' +
                    '<ul id="error_msg" class="error"></ul>' +
                '</div>';
            errorEle.innerHTML = html;
            document.body.appendChild(errorEle);
        }
        var error_msg = "";
        
        for( var key in result.warnings.messages ) {
            error_msg += '<li>' + result.warnings.messages[key] + '</li>';
        }
        $('error_msg').innerHTML = error_msg;
        MixiEffect.showOverlap();
        MixiEffect.makeCenter(errorEle).show();
    },
    alert: function(message) {
        this.showConfirm({
            'message': message,
            okOnly: 1,
            onOk: function() {}
        });
    },
    showConfirm: function(args) {
        var confirmEle = $('confirm_panel');
        if( confirmEle ) {
            document.body.removeChild(confirmEle);
        }
        var okLabel = args.okLabel || "确定";
        var cancelLabel = args.cancelLabel || "取消";
        confirmEle = new Element('div', {
            id: 'confirm_panel'
        }).setStyle({
            width: '400px'
        }).addClassName('pop');
        var html =  
            '<p class="pop_prompt"><strong>提示</strong><a href="javascript:void(0)" id="confirm_popup_close">关闭</a></p>' +
            '<div class="pop_content">' +
                '<span id="confirm_message"></span>' +
            '</div>' +
            '<p class="pop_btn">' + 
                '<input id="confirm_popup_ok" type="button" value="' + okLabel + '">' +
                (!args.okOnly ? '<input id="confirm_popup_cancel" type="button" value="' + cancelLabel + '">' : '') +
            '</p>';
        confirmEle.innerHTML = html;
        document.body.appendChild(confirmEle);
        if( args.escapeHTML == undefined ) {
            args.escapeHTML = 1;
        }
        $('confirm_message').replace(args.escapeHTML == 1 ? args.message.escapeHTML() : args.message);
        $('confirm_popup_ok').observe('click', function() {
            MixiEffect.hide('confirm_panel'); 
            args['onOk']();
        });
        if(!args.okOnly) {
            $('confirm_popup_cancel').observe('click', function(){
                MixiEffect.hide('confirm_panel');
                if( args['onCancel']){
                    args['onCancel']();
                }
            });
        }
        $('confirm_popup_close').observe('click', function() {
            MixiEffect.hide('confirm_panel'); 
            if( args['onClose'] ){
                args['onClose']();
            }
        });
        MixiEffect.showOverlap();
        MixiEffect.makeCenter(confirmEle).show();
    },
    showLoading : function() {
        var loadingEle = $('loading_panel');
        if (!loadingEle) {
            loadingEle = new Element('div', {
                id: 'loading_panel'
            }).setStyle({
                width: '400px'
            });
            var html = '<img src="/static/img/basic/common/ajax-loader.gif">';  
            loadingEle.innerHTML = html;
            document.body.appendChild(loadingEle);
        }
        MixiEffect.showOverlap();
        MixiEffect.makeCenter(loadingEle).show();
    },
    showLoginPanel: function() {
        var divEle = $('login_panel');
        if(!divEle) {
            var divEle = new Element('div', {
                id: 'login_panel'
            }).setStyle({
                width: '220px'
            }).addClassName('pop');
            var html =  
            '<p class="pop_prompt"><strong>请登陆</strong><a href="javascript:void(MixiEffect.hide(\'login_panel\'))">关闭</a></p>' +
            '<div class="pop_content">' +
            
                '<form action="/login.pl" method="POST" id="ajax_login">' +
                    '<div id="toplogin">' +
                        '<h2 title="登陆蜜秀">登陆蜜秀</h2>' +
                        '<fieldset>' +
                            '<legend>' +
                                '<label for="email">' +
                                    '登陆邮箱' +
                                '</label>' +
                            '</legend>' +
                            '<input id="email" type="text" name="email" />' +
                        '</fieldset>' +
                        '<fieldset>' +
                            '<legend>' +
                                '<label for="password">' +
                                    '密码' +
                                '</label>' +
                            '</legend>' +
                            '<input type="password" name="password" id="password" />' +
                        '</fieldset>' +
                        '<div id="ajax_login_error" style="display: none; color: red">登陆失败</div>' +
                        '<div id="login_req" style="display: none; color: red">请求中...</div>' +
                        '<ul>' +
                            '<li>' +
                               '<input class="sticky" name="sticky" value="1" type="checkbox" />下次自动登陆<br /><a href="/remind_password.pl">找回密码</a>' +
                            '</li>' +
                            '<li class="l">' +
                                '<input title="登陆" type="submit" value="登陆" />' +
                            '</li>' +
                            '<li>' +
                                   '<strong>还没有蜜秀账户？</strong>' +
                            '</li>' +
                            '<li class="i">' +
                                '<a href="/signup2.pl">立即注册</a>' +
                            '</li>' +
                        '</ul>' +
                    '</div>' +
                '</form>' +
            '</div>';
            divEle.innerHTML = html;
            document.body.appendChild(divEle);

            $('ajax_login').observe('submit', function(event) {
                Event.stop(event);
                $('ajax_login_error').hide();
                $('login_req').show();
                $('ajax_login').request({
                    onSuccess: function(transporter) {
                        var json = transporter.responseJSON;
                        $('login_req').hide();
                        if( json.result == 1 ) {
                            setCookie(json.cookie.name, json.cookie.value, null, json.cookie.path, json.cookie.domain, json.cookie.secure);
                            MixiEffect.hide('login_panel');
                        }
                        else {
                            $('ajax_login_error').show();
                        }
                    },
                    onFailed: function(transporter) {
                    },
                    onException: function(transporter, exception) {
                    }
                });
            });
        }
        MixiEffect.showOverlap();
        MixiEffect.makeCenter(divEle).show();
    },
    closePanel: function(id) {
        $(id).hide();
        MixiEffect.hideOverlap();
    },
    showOverlap: function(color, alpha) {
        if (!$('overlap')) {
            document.body.appendChild(new Element('div', {
                id: 'overlap'
            }).setStyle({
                position: 'absolute',
                left: 0,
                top: 0,
                display: 'none',
                backgroundColor: color || '#CCCCCC',
                zIndex: 9999,
                width: '100%'
            }));
        }
        $('overlap').setStyle({
            height: document.body.clientHeight + "px"
        }).setOpacity(alpha || 0.3).show();
    },
    hideOverlap: function() {
        if (!$('overlap')) {
            return;
        }
        $('overlap').hide();
    },
    makeCenter: function(id) {
        var dimension = document.viewport.getDimensions();
        var offset = document.viewport.getScrollOffsets();
        return $(id).setStyle({
            position: 'absolute',
            left: ((dimension.width - $(id).getWidth()) / 2) + "px",
            top: ((dimension.height - $(id).getHeight()) / 2 + offset.top) + "px",
            zIndex: 10000
        });
    },
    fall: function(id) {
        var dimension = document.viewport.getDimensions();
        var offset = document.viewport.getScrollOffsets();
        $(id).setStyle({
            position: 'absolute',
            left: ((dimension.width - $(id).getWidth()) / 2) + "px",
            top: -$(id).getHeight() + "px",
            zIndex: 100
        }).show();
        new Effect.Move(id, {
            y: $(id).getHeight() + ((dimension.height - $(id).getHeight()) / 2 + offset.top),
            duration: 2,
            transition: Effect.Transitions.spring
        });
    },
    flyUp: function(id) {
        if($('ajax_login_error')) {
            $('ajax_login_error').hide();
        }
        MixiEffect.hideOverlap();
        new Effect.Move(id, {
            y: -($(id).getHeight() + parseFloat($(id).getStyle('top'))),
            duration: 0.5,
            afterFinish: function() {
                $(id).hide();
            }
        });
    },
    hide: function(id) {
        if($('ajax_login_error')) {
            $('ajax_login_error').hide();
        }
        MixiEffect.hideOverlap();
        $(id).hide();
    }
}

document.observe('dom:loaded', function(){
    personalNav_show()
})


var Mixiu = Mixiu || {};
Mixiu.Refresher = function(container, targetLocation, optSec) {
    var second = optSec || 5;

    var secondContainer = new Element('span');
    secondContainer.innerHTML = second;
    var container = $(container);
    container.appendChild(document.createTextNode('页面将在'));
    container.appendChild(secondContainer);
    container.appendChild(document.createTextNode('秒后自动跳转'));

    function proc() {
        if( second-- > 0 ) {
            secondContainer.innerHTML = second;
            window.setTimeout(proc, 1000);
        }
        else {
            window.location.href = targetLocation; 
        }
    }
    window.setTimeout(proc, 1000);
}

