/* *
 * Combo design for:
 alert, dialog, prompt, tooltip, hint, notice
 history:
    2010-1-17 + options.stay 让dialog实例可以延续使用
 */
;
(function($){
    var __timer = null;

    var __default__options = {
        width: 360,
        height: 200,
        title: '标题',
        button: '确定',
        mask: false,
        timeout: null,
        selector: null,
        oncomplete: null,
        onabort: null,
        ondone: null,
        onerror: null,
        ontimeout: null,
        animate: 'show',
        type: 'box',
        stay: null,
        bare: false
    };

    var __box = function(options){
        __remove(options.type);
        var $box = $('<div></div>').attr('id', 'interactive-' + options.type + (options.stay ? '-' + options.stay.substr(1) : '')).appendTo('body');
        $box.attr('class', 'dialog').show().css({
            'minWidth': options.width,
            'zIndex': 99999
        }).html('<div class="top"><div class="corner"></div></div><div class="body"><div class="titlebar"' + (options.bare ? 'style="display:none"' : '')+ '><h1>' + options.title + '</h1><a class="close" href="javascript:void(0);">关闭</a></div><div class="client">&nbsp;</div><div class="error">&nbsp;</div><div class="buttons"><button class="default"><span><span>' + options.button + '</span></span></button> <button class="normal"><span><span>取消</span></span></button></div></div><div class="bottom"><div class="corner"></div></div></div>');
        if ($.browser.msie)
            $box.width(options.width);
        __handleButtons($box, options);
        __setPos($box, options);
        if (options.mask)
            $.mask();
        if ($.browser.version == '6.0' && $.browser.msie) {
            $box.wrapInner('<div style="position:relative;"></div>');
            var _h = $box.outerHeight();
            $('<iframe id="interactive-iframe"></iframe>').prependTo($box).height(_h).attr('src', 'about:blank').css({
                'left': -7,
                'opacity': 0,
                'position': 'absolute',
                'top': -7,
                'width': '100%',
                'zIndex': '-1'
            });
        }
        return $box;
    };

    var __remove = function(type){
        if (!type){
            $('#interactive-box, #interactive-alert, #interactive-dialog').remove();
            $('.dialog').hide();
        } else {
           $('#interactive-' + type).remove();
        }
        if($('.dialog:visible').length == 0) $('#interactive-mask').remove();
        $(window).unbind('resize.mask');
        if (__timer) {
            clearTimeout(__timer);
            __timer = null;
        }
    }

    var __handleButtons = function($box, options){
        $box.find('a.close').click(function(){
            if(options.onabort) options.onabort.call($box[0]);
            if(options.stay){
                $box.hide();
                if($('.dialog:visible').length == 0) $('#interactive-mask').remove();
            }else{
                $box.remove();
                if($('.dialog:visible').length == 0)  $('#interactive-mask').remove();
            }
            return false;
        });
        if ($('button.default, button.big-default', $box).length > 1) {
            $('.buttons:last', $box).remove();
        }
        if($box.find('.dialog-content').length && $box.find('.dialog-content').css('background-color') != 'transparent') {
            $('.client', $box).css('background-color', $box.find('.dialog-content').css('background-color'));
        }
        $box.find('.buttons button.default, .buttons button.normal').unbind('click').click(function(){
            if ($(this).hasClass('default')) {
                if (options.oncomplete) {
                    if (options.oncomplete.call($box[0]) != false) {
                        $box.hide();
                        __remove(options.stay ? 'box-' + options.stay : '');
                        return false;
                    } else {

                    }
                }
                return false;
            }
            if($(this).hasClass('normal') && options.onabort) options.onabort.call($box[0]);
            $box.hide();
            __remove('box-' + options.stay);
            return false;
        });
    }; //__handleButtons

    var __setPos = function($box, options){
        var $box = $box || $('#interactive-box');
        x = (($(window).width() - $box.outerWidth()) / 2 + $(document).scrollLeft()) >> 0;
        y = (($(window).height() - $box.outerHeight()) / 2 + $(document).scrollTop()) >> 0;
        if(y < 0) y = 0;
        $box.css({
            left: options.left || x,
            top: options.top || y
        });
    }

    var __resetPos = function($box, options){
        var $box = $box || $('#interactive-box');
        $('#interactive-iframe', $box).height($box.outerHeight()).width($box.outerWidth());
        __setPos($box, options);
    }

    function __disableSubmit($box){
        $box.find('button.default').attr('disabled', true).addClass('disabled');
    }

    function __enableSubmit($box){
        $box.find('button.default').attr('disabled', false).removeClass('disabled');
    }

    function __error($box, msg){
        $box.find('div.error').html(msg).show();
    }

    $.extend({
        alert: function(message, options){
            var __local__options = {
                title: '提示',
                type: 'alert'
            };
            options = $.extend({}, __default__options, __local__options, options);
            var $box = __box(options);
            $box.find('.client').html('<p>' + message + '</p>');
            $('.buttons button.normal', $box).remove();
            __resetPos($box, options);
            return $box;
        },

        confirm: function(message, options){ //$.
            var message = message || '确定要进行该操作吗？';
            options = $.extend({}, __default__options,  {title: '确认'}, options);
            var $box = __box(options);
            $box.find('.client').html(message);
            __resetPos($box, options);
            return $box;
        },

        sprite: function(url, options){ //$.
            options = $.extend({}, __default__options, {title: '对话框'}, options);
            var $box = __box(options);
            $('div.submit', $box).remove();
            __resetPos($box, options);
            var requestMethod = 'ajax';
            var rhost = (/^(\w+:)?\/\/([^\/?#]+)/.exec(url));
            if (rhost) {
                rhost = rhost[0];
                var shost = location.protocol + '//' + location.host;
                if (rhost !== shost)
                    requestMethod = 'swfajax';
            }
            $('.client', $box).addClass('throbber');
            $[requestMethod]({
                url: url,
                type: 'get',
                success: function(r){
                    if (r.substr(0, 1) == 1 || r.substr(0, 1) == 2) {
                        __remove();
                        $.notice(r.substr(2), 'error');
                        return;
                    }
                    $('.client', $box).removeClass('throbber').html(r);
                    $box.find('.warning').insertBefore($box.find('.client'));
                    if ($('.client', $box).width() > 330) {
                        var _w = $.browser.msie ? ($('.client', $box).width() + 30) : 'auto';
                        $box.width(_w);
                    }
                    __handleButtons($box, options);
                    if (options.ondisplay) options.ondisplay.call(options.link, $box);
                    __resetPos($box, options);
                    var $form = $('form', $box);
                    if(!$form.length){
                        $('.buttons button.default', $box).unbind('click').click(function(){
                            if(options.ondone) options.ondone.call(options.link, $box[0]);
                            __remove();
                        });
                        return false;
                    }
                    if ($form.attr('action') == '')
                        $form.attr('action', url);
                    $('.buttons button.default', $box).unbind('click').click(function(){
                       $('form:visible', $box).ajaxForm({
                            type: 'POST',
                            beforeSubmit: function(){
                                var failed = false;
                                $form.find(':input').each(function(){
                                    if ($(this).data('failed')) {
                                        failed = true;
                                        return false;
                                    }
                                });
                                if(failed) return false;
                                if (options.onrequirevalidate) {
                                    var result = options.onrequirevalidate.call(options.link, $box[0]);
                                    if (!result)
                                        return false;
                                }
                                __disableSubmit($box);
                                $('.buttons', $box).addClass('throbber');
                            },
                            success: function(r){
                                $('.buttons', $box).removeClass('throbber');
                                if (r.substr(0, 1) != '1') {
                                    if(options.oncomplete) options.oncomplete.call(options.link, $box[0], r);
                                    if (options.onunload) options.onunload.call(options.link);
                                    __remove(options.stay ? 'box-' + options.stay : undefined);
                                } else {
                                    __error($box, r.substring(2));
                                    __enableSubmit($box);
                                }
                            },
                            error: function(){
                                ('.buttons', $box).removeClass('throbber');
                                __error($box, '与服务器通讯时出错, 请重试');
                                __enableSubmit($box);
                            },
                            timeout: function(){
                                __error($box, '与服务器的通讯超时, 请重试');
                                __enableSubmit($box);
                            }
                        }).submit(); // ajaxForm
                    });
                } // ajax(1) : success
            });
            return false;
        },

        dialog: function(sel, options){ // $
            if (sel.substr(0,1) != '#') { // a url
                options = $.extend({}, __default__options, {title: '对话框', stay: 'remote', bare: false}, options);
                var $box = __box(options);
                var $client = $('div.client', $box);
                $box.repos = __resetPos();
                $('button.default', $box).hide();
                var url = sel;
                $.ajax({
                    url: url,
                    success: function(r){
                        $client.html(r);
                        if(options.ondisplay) options.ondisplay.call($box[0]);
                        $('button.default', $box).show();
                        __handleButtons($box, options);
                    },
                    error: function(){
                        __error($box, '出现了错误, 请重试');
                    }
                });
            }else{
                options = $.extend({}, __default__options, {title: '对话框', stay: sel, mercy: true}, options);
                $box =$('#interactive-box-' + sel.substr(1));
                if($box.get(0)) {
                    if(options.mask) $.mask();
                    __resetPos($box, options);
                    $box.show();
                }else{
                    $box = __box(options);
                    if(options.local) {
                        $box.insertAfter($(sel));
                    } else {
                        $box.appendTo(document.body);
                    }
                    if(options.mercy){
                        $box.find('.client').html('').append($(sel).children().clone());
                    }else{
                        $box.find('.client').html('').append($(sel).children());
                    }
                    __handleButtons($box, options);
                    __resetPos($box, options);
                }
                if (options.ondisplay)
                    options.ondisplay.call($box[0]);
            }
            return $box;
        },

        prompt: function(){ },

        hint: function(){ },

        notice: function(message, type, options){
            var options;
            var message = message || '';
            var _type = 'info';
            if (typeof(arguments[1]) == 'string')
                _type = arguments[1];
            if (typeof(arguments[1]) == 'object')
                options = arguments[1];

            options = $.extend({}, __default__options, options);
            var p = ['#systemnotice', '#maincolumn', '#content'];
            var location = null;
            for (var i = 0; i < p.length; i++) {
                if ($(p[i]).length) {
                    location = $(p[i]);
                    break;
                }
            }
            __remove('notice');
            var $box = $('<div id="interactive-notice"><a href="javascript:void(0);" class="x">关闭</a><p></p></div>').prependTo(location).addClass('notice-' + _type);
            $('p', $box).html(message);
            $box.hide()[options.animate]();

            $('a.x', $box).click(function(){
                __remove('notice');
                return false;
            });

            if (options.timeout) {
                __timer = setTimeout(function(){
                    $('#interactive-notice').fadeOut(function(){
                        $(this).remove();
                        if (options.ontimeout)
                            options.ontimeout.call();
                    });
                }, options.timeout);
            }
        },

        throbber : function(message){
            if(!message) message = '正在执行, 请稍候';
            var $box = $('<div id="interactive-throbber"></div>').appendTo(document.body);
            $box.css({
                width: 400
            }).append('<a class="cancelme remove" href="javascript:void(0);">取消</a>').append('<p>' + message + '</p>');
            __setPos($box, {});
            $box.find('a.cancelme').click(function(){
                $box.remove();
                $('#interactive-mask').remove(); $('#interactive-mask').remove();
            });
            $box.overlay();
            $.mask();
        },

        mask: function(options){
            var options = $.extend({
                opacity: .5,
                animate: 'show',
                color: '#000000'
            }, options);
            __remove('mask');
            $(window).unbind('resize.mask');
            var $box = $('<div id="interactive-mask"></div>').appendTo(document.body);
            $box.addClass('masking')[options.animate]();
            $box.css({
                width: $(window).width(),
                height: $(document).height(),
                opacity: options.opacity,
                backgroundColor: options.color,
                zIndex: 99990
            });
            if ($.browser.version == '6.0' && $.browser.msie) {
                $box.overlay();
            }
            $(window).bind('resize.mask', function(){
                $('#interactive-mask').width($(window).width());
            });
        }, // mask

        xlst: function(source, xslturl, dom){
            try {
                if ($.browser.mozilla) {
                    xsltdoc = document.implementation.createDocument("", "", null);
                    xsltdoc.async = false;
                    xsltdoc.load('/ajax/peoplepicker-groups.xlst');
                    xslt = new XSLTProcessor();
                    xslt.importStylesheet(xsltdoc);
                    resultdoc = xslt.transformToFragment(source, document);
                    $.each(resultdoc.childNodes, function(i, o){
                        $(dom).append(o);
                    });
                }
                else {
                    xsltdoc = new ActiveXObject("Microsoft.XMLDOM");
                    xsltdoc.async = false; // important
                    xsltdoc.load(xslturl);
                    resultdoc = source.transformNode(xsltdoc);
                    $(dom).append(resultdoc);
                }
            }
            catch (e) {
                alert('与服务器交换数据时出错, 请重试, ' + e.message);
            }
        } // xslt
    });

    $.fn.extend({
        confirm: function(message, options){
            var options = options || {};
            options.mask = false;
            $(this).each(function(){
                $(this).click(function(e){
                    var $link = $(this);
                    var $box = $.confirm(message, options);
                    $box.addClass('confirmbox');
                    var position = $link.offset();
                    var css = {
                        x: 'l',
                        y: 'b'
                    };
                    var base = {
                        x: position.left - $box.outerWidth() + 10,
                        y: position.top + $link.outerHeight() + 20
                    };
                    if (base.x < 2) {
                        base.x = position.left - 10 + $link.outerWidth();
                        css.x = 'r';
                    }

                    if ($(document).scrollTop() + $(window).height() - base.y < $box.outerHeight()) {
                        base.y = base.y - $box.outerHeight() - 40;
                        css.y = 't';
                    }
                    $box.css('left', base.x).css('top', base.y);
                    $box.addClass(css.x + css.y).append('<div class="tip"></div>');
                    if(options.ondisplay) options.ondisplay.call($link[0], $box[0]);
                    if (this.tagName.toUpperCase() == 'A') {
                        $('button.default', $box).unbind('click').click(function(){
                            __disableSubmit($box, options);
                            $.ajax({
                                url: $link[0].href,
                                success: function(data){
                                    if (data.substr(0, 1) == 0 && options.oncomplete) {
                                        __remove();
                                        options.oncomplete.call($link[0]);
                                    } else {
                                        __remove();
                                        $.notice(data.substring(2), 'error');
                                    }
                                    __enableSubmit($box, options);
                                },
                                error: function(xml, error){
                                    __error($box, error);
                                    __enableSubmit();
                                }
                            });
                        });
                    }
                    return false;
                });
            });
        },

        blurHint: function(message, options){
            options = $.extend({
                mode: ''
            }, options);
            var $me = this;
            var selector = $me.selector;
            $me.each(function(){
                if($(this).val() == '') $(this).addClass('g9').val(message);
            })
            $(selector).live('focusout', function(){
                if (this.blured && options.mode == 'once')
                    return true;
                if (this.value == message || this.value == '') {
                    $(this).addClass('g9');
                    this.value = message;
                    this.blured = true;
                    if (options && options.onrelease)
                        options.onrelease.call(this, false);
                }
            });
            $(selector).live('focusin', function(){
                if (this.value == message)
                    this.value = '';
                $(this).removeClass('g9');
                if (options && options.onengage)
                    options.onengage.call(this);
            });
            $me.parents('form').submit(function(){
                $(selector).each(function(){
                    if ($(this).hasClass('g9'))
                        $(this).removeClass('g9').val('');
                });
            });
            return $me;
        },

        spring: function(options){
            var result = this.each(function(){
                var id = this.id.substr(7);
                var link = this;

                var __dismiss = function(){
                    $('.spring').remove();
                    if (options && options.ondismiss)
                        options.ondismiss.call(link);
                }

                link.dismiss = function(){
                    __dismiss();
                }

                $(this).mouseover(function(){
                    var __dismissTimer = null;
                    __dismiss();
                    var p = $(link).position();
                    var $pane = $('<div id="' + link.id + '-spring" class="spring"><div class="tap"><h1></h1></div><div class="body"><div class="room"></div></div></div>').appendTo($(this).parent()).css({
                        left: p.left - 6,
                        top: p.top + 16
                    });
                    $pane.find('h1').text($(link).text());
                    if ($('#' + link.id + '-spring-content').length)
                        $pane.find('.room').html($('#' + link.id + '-spring-content').html());
                    if (options && options.onrequirecontent)
                        options.onrequirecontent.call(link, $pane.find('.room')[0]);
                    if (options && options.onactive)
                        options.onactive.call($pane.find('.room'), link);
                    $pane.click(function(e){
                        e.stopPropagation();
                        return false;
                    }).mouseout(function(){
                        __dismissTimer = window.setTimeout(__dismiss, 500);
                    }).mouseover(function(){
                        window.clearTimeout(__dismissTimer);
                    });
                    /*
                     $(document).click(function(){
                     $pane.fadeOut(function(){
                     __dismiss();
                     });
                     });
                     */
                    $(window).resize(function(){
                        $pane.fadeOut(function(){
                            __dismiss();
                        });
                    });
                }); // $(this).click
            }); // this.each
            return result;
        },// spring

        sprite: function(options){
            return $(this.selector).live('click', function(){
                var $this = $(this);
                var url = $this.attr('href');
                if ($this.attr('title')) {
                    options = $.extend({}, options, {title: $this.attr('title')});
                }
                options.link = $this;
                $.sprite(url, options);
                return false;
            }); // live
        },

        dialog: function(options){ //$.fn
            options = $.extend({}, __default__options, options);
            return $(this).each(function(){
                if (this.tagName.toUpperCase() == 'A') {
                    $(this).click(function(){
                        $.dialog(this.href, options);
                        return false;
                    });
                }else{
                    $.dialog('#' + this.id, options);
                }
            });
        },

        hook: function(options){
            var hideIntervalId;
            return $(this).each(function(){
                var baseElement = $(this);
                var coverElement = $(options.cover);
                baseElement.data('cover', coverElement);
                baseElement.mouseover(function(){
                    clearInterval(hideIntervalId);
                    if (options.beforeShow) {
                        options.beforeShow(baseElement, coverElement);
                    }
                    coverElement.show();
                }).mouseout(hideCover);
                coverElement.unbind().mouseover(function(){
                    clearInterval(hideIntervalId);
                }).mouseout(hideCover);

                function hideCover(){
                    hideIntervalId = setTimeout(function(){
                        baseElement.data('cover').hide();
                        if (options.afterHide) {
                            options.afterHide(baseElement, coverElement);
                        }
                        clearInterval(hideIntervalId);
                    }, 100);
                }
            });
        },

        protect: function(){
            if ($(this).length > 1) {
                alert('选择器' + this.selector + '一次配置Form超过1个');
                return;
            }
            var $submit = $('input:submit, button.default', this);
            var $form = $(this);

            function disable(){
                $form.bind('keydown.protect', function(){
                    return false;
                });
                $submit.attr('disabled', true).addClass('disabled');
            }

            // Note: IE6下即使submit被disable了，表单回车同样是可以触发提交的，因此在disable的时候需要把回车禁用, 使用setTimetout同样是解决ie6出现的bug
            function enable(){
                $form.unbind('keydown.protect');
                $submit.attr('disabled', false).removeClass('disabled');
            }

            $form.submit(function(){
                disable();
            });
            return {
                disable: function(w){
                    setTimeout(function(){
                        disable();
                    }, 0);
                },
                enable: function(){
                    setTimeout(function(){
                        enable();
                    }, 0);
                }
            }
        }, // frotect

        overlay: function(){
            return this.each(function(){
                var $div = $(this);
                if ($div.find('iframe.overlay').length)
                    $div.find('iframe.overlay').remove();
                var $iframe = $('<iframe class="overlay" src="about:blank" frameborder="0"></iframe>');
                $iframe.css({
                    position: 'absolute',
                    width: $div.outerWidth(),
                    height: $div.outerHeight(),
                    opacity: 0,
                    border: 0,
                    left: -1,
                    top: -1,
                    zIndex: -1
                });
                $div.prepend($iframe);
            }); // each
        },// overlay

        notice: function(message, options){
            var baseOption = {
                className: 'notice-tips',
                timeout: 1500,
                top: 0,
                left: 0
            };
            var options = $.extend(baseOption, options);
            return this.each(function(){
                var $this = $(this);
                var pos = $this.offset();
                var height = $this.height() + 2;
                var paddingTop = parseInt($this.css('padding-top'), 10);
                var paddingLeft = parseInt($this.css('padding-left'), 10);
                pos = {
                    left: (pos.left >> 0) + parseInt(options.left, 10),
                    top: (pos.top >> 0) + parseInt(options.top, 10)
                }
                var $notice = $('<div>' + message + '</div>').appendTo('body').css({
                    left: pos.left + paddingLeft,
                    top: pos.top + paddingTop + height
                });
                $notice.addClass(options.className);
                setTimeout(function(){
                    $notice.fadeOut(300, function(){
                        $(this).remove();
                    });
                }, options.timeout);
            });
        }
    });

    $['UI'] = {};
    $['UI']['hide'] = __remove;
    $['UI']['destory'] = function(stay){
        if(!stay) {
            $('.dialog').remove();
            return;
        }
        $('#interactive-box-' + stay.substr(1)).remove();
    }

})(jQuery);
