var Mcool = new Object();

Mcool.EventMonitor = function(){
	this.listeners = new Object();
}
Mcool.EventMonitor.prototype.broadcast=function(widgetObj, msg, data){
	var lst = this.listeners[msg];
	if(lst != null){
		for(var o in lst){
			lst[o](widgetObj, data);
		}
	}
}
Mcool.EventMonitor.prototype.subscribe=function(msg, callback){
	var lst = this.listeners[msg];
	if (lst) {
		lst.push(callback);
	} else {
		this.listeners[msg] = [callback];
	}
}
Mcool.EventMonitor.prototype.unsubscribe=function(msg, callback){
	var lst = this.listener[msg];
	if (lst != null){
		lst = lst.filter(function(ele, index, arr){return ele!=callback;});
	}
}

// Page scope event-monitor obj.
var event_monitor = new Mcool.EventMonitor();

function load_event_monitor(root) {
    var re = /a_(\w+)/;
    var fns = {};
    $(".j", root).each(function(i) {
        var m = re.exec(this.className);
        if (m) {
            var f = fns[m[1]];
            if (!f) {
                f = eval("Mcool.init_"+m[1]);
                fns[m[1]] = f;
            }
            f && f(this);
        }
    });
}

$(function() {
	load_event_monitor(document);
});

var get_form_fields = function(form) {
	var param = {};
	$(':input', form).each(function(i){
		var name = this.name;
		if (this.type == 'radio') {
			if (this.checked) param[name] = this.value;
        } else if (this.type == 'checkbox') {
			if (this.checked) param[name] = this.value;
		} else if (this.type == 'submit'){
			if (/selected/.test(this.className)) param[name] = this.value;
		} else {
			if (name) param[name] = this.value;
		}
		if(/notnull/.test(this.className) && this.value == ''){
			$(this).prev().addClass('errnotnull');
			param['err'] = 'notnull';
		}
	});

	if(!param['wish'] && !param['do'] && !param['collect'] && !param['save'] && /interest$/.test(form.action)){
		param['collect'] = 'do';
	}
	return param;
}

$.viewport_size = function(){
	var size = [0, 0];
	if (typeof window.innerWidth != 'undefined'){
		size = [window.innerWidth, window.innerHeight];
	}else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
		size = [document.documentElement.clientWidth, document.documentElement.clientHeight];
	}else{
		size = [document.body.clientWidth, document.body.clientHeight];
	}
	return size;
}

var refine_dialog = function(){
	var agent = navigator.userAgent.toLowerCase();
	var size = [0, 0];
	if (typeof window.innerWidth != 'undefined'){
		size = [window.innerWidth, window.innerHeight];
	}else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
		size = [document.documentElement.clientWidth, document.documentElement.clientHeight];
	}else{
		size = [document.body.clientWidth, document.body.clientHeight];
	}
	var top = 0.5 * (size[1] - $('#dialog')[0].offsetHeight) + 140;
	$('#dialog,#overlay').css('top', top);
    set_overlay();
}

var set_overlay = function(){
    var oheight = ($.browser.msie?11:26);
    $('#overlay').css('height',$('#dialog')[0].offsetHeight+oheight);
}

var show_dialog = function(div) {
    if($('#dialog').length) return;
    $('body').append('<div id="overlay"></div><div id="dialog"></div>');
    if(div != null){
        $('#dialog').html(div);
    }else{
        $('#dialog').html("<div class='loadpop pl'>正在载入，请稍候...</div>");
    }
    set_overlay();
}

var close_dialog = function() {
    $('#overlay').unbind('click');
    $('#dialog,#overlay,.bgi').remove();
    if (typeof document.body.style.maxHeight == "undefined") {//if IE6
        $('body','html').css({height: 'auto', width: 'auto'});
        $('html').css('overflow', '');
    }
    document.onkeydown = '';
    return false;
}


Mcool.init_collect_btn = function(o) {
    $(o).click(function(){
    	var session_userid = document.getElementById('session_userid').value;
    	if(typeof(session_userid) == 'undefined' || session_userid == '')
    	{
    		show_dialog('<span class="m" style="center">请您先登录...</span>');
            setTimeout(function(){
                $('#dialog, #overlay').fadeOut(close_dialog);

            },400);
			return false;
    	}    	
        if($('#hiddendialog').length){
            show_dialog($('#hiddendialog').html());
            load_event_monitor($('#dialog'));
        }else{
            show_dialog(null);
            var _ = $(this).attr('name').split('-');
            var btn_type = _[0],book_id = _[1], rating = _[2];
            if (typeof(rating)=='undefined') {rating = '';}
            var url = 'ebook_info.php?actionit=data&book_id='+book_id;
            $.get(url, {rating:rating}, function(ret) {
                if($('#dialog').length){
                    var r = eval('('+ret+')');
                    var html = $('<div></div>').html(r['html']);
                    var tags = r['tags'];
                    var content = tags.join(' ');
                    $('input[@name=tags]', html).val((content.length > 1)? content + ' ' : content)
                    var hash = {};
                    $.each(tags, function(i,tag){hash[tag.toLowerCase()]=true;});
                    populate_tag_btns('我的标签:', $('#mytags', html), r['my_tags'], hash);
                    populate_tag_btns("常用标签:", $('#populartags', html), r['popular_tags'], hash);
                    if (btn_type == 'pbtn') $('form', html).append('<div id="src_pbtn"></div>');
                    $('#dialog').html(html);
                    refine_dialog();
                    load_event_monitor(html);
                }
            });
        }
        return false;
    });	
};

Mcool.init_interest_form = function(form) {
	$(":submit",form).click(function(){
		$(this).addClass('selected');
	});
	var btns = {}, selected = {};
	var select = function(tl) {
		if (btns[tl]) {
			selected[tl] = true;
			$.each(btns[tl], function(i, btn) {
				$(btn).removeClass('gract').addClass('rdact');
			});
		}
	}
	var deselect = function(tl) {
		if (btns[tl]) {
			delete selected[tl];
			$.each(btns[tl], function(i, btn) {
				$(btn).removeClass('rdact').addClass('gract');
			});
		}
	}
	var update = function() {
		var tags = $.trim(form.tags.value.toLowerCase()).split(' '), hash = {};
		$.each(tags, function(i, t){
			if (t != '') { select(t); hash[t] = true; }
		});
		for (t in selected) { if (!hash[t]) deselect(t) }
	};

	update();
	form.tags.focus();

	$(form).submit(function() {
		remote_submit_json(this, function(data){
			if ($('#src_pbtn', form).length) {
				window.location.reload();
			}else{
				close_dialog();
			}
		});
		$('input', '#submits').hide();
		$('td', '#submits').append('<span class="m">正在保存...</span>');
		return false;
	});
	$(form.cancel).click(function(){
	    var sid = $(form).attr('action').split('/')[3];
		$("#collect_form_"+sid).html('');
	});

	$('.tagbtn', form).each(function(i){
		var tl = $(this).text().toLowerCase();
		if (btns[tl]) btns[tl].push(this);
		else btns[tl] = [this];
	}).click(function(){
		var tag = $(this).text();
		var tags = $.trim(form.tags.value).split(' '), present=false, tl=tag.toLowerCase(), i;
		tags = $.grep(tags, function(t, i){
			if (t.toLowerCase() == tl) {
				deselect(tl); present=true; return false;
			} else return true;
		});
		if (!present) { tags.push(tag); select(tl); }
		var content = tags.join(' ');
		form.tags.value = (content.length > 1) ? content+' ' : content;
		form.tags.focus();
	});

	$(form.tags).keyup(update);
}

var populate_tag_btns = function(title, div, tags, hash){
	if (tags.length) {
		var p = $('<p style="line-height:120%" class="pl">'+title+'<br/></p>');
		$.each(tags, function(i,tag) {
			var btn = $('<span class="tagbtn"/>').addClass(hash[tag.toLowerCase()]?'rdact':'gract').text(tag);
			p.append(btn).append(' &nbsp; ');
		});
		div.append(p);
	}
}

var remote_submit_json = function(form, func, disable) {
    var fvalue = get_form_fields(form); 
    if(fvalue['err'] == undefined){
        if(disable != false){
            $(':submit',form).attr('disabled', 1);
            $('textarea',form).attr('disabled', 1);
        }

        $.post(form.action, 
           fvalue, 
           function(ret){
            var json = eval('('+ret+')'); 
			func(json);
        });
    }
}

jQuery.fn.extend({
    set_len_limit : function(limit){
        var s = this.find(':submit');
        var oldv = s.attr('value');
        var check = function(){
            if(this.value && this.value.length > limit){
                s.attr('disabled',1).attr('value','字数不能超过'+limit+'字');
            } else {
                s.attr('disabled',0).attr('value', oldv);
            }
        }
        $('textarea', this).focus(check).blur(check).keydown(check).keyup(check);
    },

    set_caret: function(){
        if(!$.browser.msie) return;
        var initSetCaret = function(){this.p = document.selection.createRange().duplicate()};
        this.click(initSetCaret).select(initSetCaret).keyup(initSetCaret);
    },

    insert_caret:function(t){
        var o = this[0];
        if(document.all && o.createTextRange && o.p){
            var p=o.p;
            p.text = p.text.charAt(p.text.length-1) == '' ? t+'' : t;
        } else if(o.setSelectionRange){
            var s=o.selectionStart;
            var e=o.selectionEnd;
            var t1=o.value.substring(0,s);
            var t2=o.value.substring(e);
            o.value=t1+t+t2;
            o.focus();
            var len=t.length;
            o.setSelectionRange(s+len,s+len);
            o.blur();
        } else {
            o.value+=t;
        }
    },
    
    get_sel:function(){
        var o = this[0];
        return document.all && o.createTextRange && o.p ? 
            o.p.text : o.setSelectionRange ? 
            o.value.substring(o.selectionStart,o.selectionEnd) : '';
    }
})
var check_form = function(form){
    var _re = true;
    $(':input',form).each(function(){
        if((/notnull/.test(this.className) && this.value == '')
            || (/most/.test(this.className) && this.value && this.value.length>/most(\d*)/.exec(this.className)[1]))
        {
            $(this).next().show();
            _re = false;
        }else{
            if(/attn/.test($(this).next().attr('className'))) $(this).next().hide();
        }
    })
    return _re;
}
var paras = function(s){
    var o = {};
    if(s.indexOf('?') == -1) return {};
    var vs = s.split('?')[1].split('&');
    for(var i=0;i<vs.length;i++){
        if(vs[i].indexOf('=') != -1){
            var k = vs[i].split('=');
            eval('o.'+k[0]+'="'+k[1]+'"');
        }
    }
    return o;
}

function copylink() 
{ 
  var therange = window.location.href; 
  copyToClipboard(therange); 
} 

function copyToClipboard(txt) {   
    if(window.clipboardData)   
    {   
        window.clipboardData.clearData();   
        window.clipboardData.setData("Text", txt);   
    }   
    else if(navigator.userAgent.indexOf("Opera") != -1)   
    {   
        window.location = txt;   
    }   
    else if (window.netscape)   
    {   
        try {   
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");   
        }   
        catch (e)   
        {   
            alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将[signed.applets.codebase_principal_support]设置为'true'");   
        }   
        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);   
        if (!clip)   
            return;   
        var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);   
        if (!trans)   
            return;   
        trans.addDataFlavor('text/unicode');   
        var str = new Object();   
        var len = new Object();   
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);   
        var copytext = txt;   
        str.data = copytext;   
        trans.setTransferData("text/unicode",str,copytext.length*2);   
        var clipid = Components.interfaces.nsIClipboard;   
        if (!clip)   
            return false;   
        clip.setData(trans,null,clipid.kGlobalClipboard);   
    } 
    alert('已成功复制');  
    return true;   
}