'use strict';
$.prompt = function (text, delay) {
    if (delay === undefined || +delay <= 0) {
        delay = 3000;
    }
    var prompt = $('#prompt'), timer = 0;
    if (prompt.length === 0) {
        prompt = $('<div>', {'class': 'prompt', id: 'prompt'}).append($('<span>')).appendTo($('body'));
    }
    prompt.find('span').html(text);
    timer = prompt.data('timer');
    timer && clearTimeout(timer);
    prompt.show();
    prompt.data("timer",setTimeout(function(){
        prompt.detach().data("timer",0);
    }, delay));
}

$.toast = function (text, delay) {
    if (delay === undefined || +delay <= 0) {
        delay = 3000;
    }
    var toast = $('#toast'), timer = 0;
    if (toast.length === 0) {
        toast = $('<div>', {'class': 'toast', id: 'toast'}).append($('<span>')).appendTo($('body'));
    }
    toast.find('span').html(text);
    timer = toast.data('timer');
    timer && clearTimeout(timer);
    toast.show();
    toast.data("timer",setTimeout(function(){
        toast.detach().data("timer",0);
    }, delay));
}

function Dialog(){
	var title = null,content = null,style={};
	if (arguments.length==1) {
        var arg0 = arguments[0];
        if (typeof arg0 == 'string') {
            content = arguments[0];
        }else if (typeof arg0 == 'object') {
            'title' in arg0 && (title = arg0.title);
            'content' in arg0 && (content = arg0.content);
            'style' in arg0 && (style = arg0.style);
            if ('html' in arg0) {
                content = arg0.html;
            }else if('content' in arg0){
                content = (function htmlEncode(str) {
                    var div = document.createElement("div");
                    div.appendChild(document.createTextNode(str));
                    return div.innerHTML;
                })(arg0.content);
            }
        }
	}else if(arguments.length>=2) {
		title = arguments[0];
		content = arguments[1];
	}
	this.context = $(['<div class="dialog">',
            '<div class="dialog-title"></div>',
            '<div class="dialog-wrapper">',
            '<div class="dialog-content">',
            '</div>',
            '<div class="dialog-button-container">',
            '</div>',
            '</div>',
            '</div>'].join(''));

    this.context.find(".dialog-title")[!!title?'html':'detach'](title);

	this.content = this.context.find(".dialog-content");
    if (!!content) {
	    this.content.append(content);
    }else{
        this.content.empty();
    }

    for(var key in style){
        key = key.replace(/([A-Z])/g,'-$1').toLowerCase();
        var ele = key == 'root'?this.context:this.context.find(".dialog-"+key);
        var css = style[key];
        if (typeof css == 'string') {
            ele.addClass(css);
        }else if(typeof css == 'object'){
            ele.css(css);
        }
    }
	this.loaded = false;
    this.alert = false;
}

function extendMethod(class_name, method_set) {
    for (var method_name in method_set) {
        class_name.prototype[method_name] = method_set[method_name];
    }
}

function EventListener() {
}

extendMethod(EventListener, {
    on: function (event, func) {
        if (typeof event === 'string' && typeof func === 'function') {
            var list = this['on' + event + 'list'];
            if (list instanceof Array) {
                for (var i = 0; i < list.length; i++) {
                    if (list[i] === func) {
                        return this;
                    }
                }
                list.push(func);
            } else {
                this['on' + event + 'list'] = [func];
            }
        }
        return this;
    },

    off: function (event, func) {
        var list = this['on' + event + 'list'];
        if (list instanceof Array) {
            if (!func) {
                list.length && list.splice(0, list.length);
            } else {
                for (var i = 0; i < list.length; i++) {
                    if (list[i] === func) {
                        list.splice(i, 1);
                        break;
                    }
                }
            }
        }
        return this;
    },

    trigger: function (event) {
        var result = false, list = this['on' + event + 'list'];
        if (list instanceof Array) {
            for (var i = 0; i < list.length; i++) {
                var func = list[i];
                if (typeof func != 'function') {
                    continue;
                }
                var args = Array.prototype.slice.call(arguments, 0);
                args.shift();
                result = result || func.apply(this, args);
            }

        }
        return result;
    }
});

Dialog.prototype = new EventListener();

extendMethod(Dialog,{
	dismiss:function(){
		var self = this;
		self.trigger('dimiss');
		this.context.removeClass("out");
		var overlay = $(".ui-overlay").removeClass("out");
		setTimeout(function(){
			overlay.removeClass('show');
			self.context.removeClass("show");
			self.trigger('hide');
            self.context.detach();
		}, 200);
	},
	addClass:function(className){
		this.context.addClass(className);
		return this;
	},
	attr:function(){
		return this.context.attr.apply(this.context,Array.prototype.slice.call(arguments,0));
	},
	find:function(selector){
		return this.content.find(selector);
	},
    $:function(selector){
        return this.find(selector);
    },
	model:function(){
		var self = this;
        this.alert = arguments.length>0?!!arguments[0]:false;
		this.loaded==false && this.trigger("load"),this.loaded=true;
		var overlay = $(".ui-overlay");
		overlay.length == 0 && (overlay = $("<div>",{'class':'ui-overlay'}).appendTo($('body')));
		overlay.off("click").on("click",function(){
            if(self.alert){
                return;
            }
			self.dismiss();
		});
		// overlay.addClass('show');
		this.trigger('present');
		this.context.appendTo($('body'));
		setTimeout(function(){
			// self.context.addClass("out");
			// overlay.addClass('out');
            self.trigger('show');
		}, 10);
	},
	wrap: function(title,className,func){
		return this.context.find('.dialog-button-container').empty(),this.add(title,className,func);
	},
	add:function(title,className,func){
		var self = this;
		var btns = self.context.find('.dialog-button');
		btns.removeClass('d-'+btns.length);
		return (btns = btns.add($('<button>',{'class':'dialog-button'+(className?' '+className:'')}).html(title).on('click',function(){
			var i = $(this).index();
			(typeof func == 'function' && func()) || self.trigger('click',i) || self.dismiss();
		}))),this.context.find('.dialog-button-container').empty().append(btns.addClass('d-'+btns.length)),this;
	}
});