/// <reference path="jquery-1.3.2-vsdoc2.js" />
//应用扩展
Meimi.common = {
    confirm: function(msg, url) {
        if (arguments.length == 1) {
            url = msg;
            msg = '真的要删除吗？';
        }
        Meimi.dialog.confirm(msg, {
            yes: function() {
                if (url.constructor == String) {
                    location.href = url;
                } else if (url.constructor == Function) {
                    url();
                }
            }
        });
        return false;
    },
    photo:{
        get: function(options, callback){
            callback = callback || $.noop;
            Meimi.api.get("moretopics",$.extend({
                pagesize: 8,
                tags: "",
                gender:""
            }, options || {}),callback);
        },
        list:function(options, callback){
            callback = callback || $.noop;
            var opt = $.extend({
                el:document.body,
                pagesize: 8,
                tags:"",
                page:1,
                listtype:"recommend",
                gender:""
            }, options || {});
            var loading;
            var loading = $('<li class="photo_loading">下页图片加载中…</li>').appendTo(opt.el);
            this.get({
                pagesize: opt.pagesize,
                listtype: opt.listtype,
                tags: opt.tags,
                page: opt.page,
                gender: opt.gender
            },function(json){
                loading.remove();
                if(json.code == 1 && json.result.length > 0){
                    this.page = opt.page + 1;
                    $(opt.el).append(Meimi.template("PHOTO_LIST",json));
                    Meimi.common.anchor.list();
                    callback();
                }
            }.bind(this));
        },
        clip: function(){
            var imgw,imgh;
            this.preview = function(img, selection) { 
                if(selection){
                    if(selection.x2 - selection.x1 > 0){
                        $("#x").val(selection.x1);
                        $("#y").val(selection.y1);
                        $("#width").val(selection.x2 - selection.x1);
                        $("#height").val(selection.y2 - selection.y1);
                    }else{
                        $("#x,#y,#width,#height").val(0);
                    }
                }
            }
            imgw = $('#bigimg').width();
            imgh = $('#bigimg').height();
            $('#bigimg').imgAreaSelect({
                onSelectChange : this.preview
            });
        }
    },
    write: function(id, fn) {
        if (!id) return;
        if (!$(document).data("write" + id)) {
            Meimi.api.get("write", {
                id: id
            }, function(json) {
                if (json.code == 1) {
                    $(document).data("write" + id, json.result);
                    fn(json.result);
                }
            });
        } else {
            fn($(document).data("write" + id));
        }
    },
    posturl: function(topicid,markid){
        if(!Meimi.common.user.checklogin())return;
        Meimi.dialog.layer(null,{
            content:"#posturlDialog",
            mask:true,
            blur:true,
            open:{
                callback:function(){
                    $("h3.title",this.pannel).html($("#thingTitle" + markid).html()).contents().not("kbd,span.icon").remove();
                    var obj = $("input[name=content]",this.pannel).focus();
                    $("span.submit",this.pannel).unbind("click").bind("click",function(){
                        var v = obj.val().trim();
                        if(v == ""){
                            alert("网址不能为空，请确认");
                            obj.focus();
                            return false;
                        }
                        if(!new RegExp("^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([!#\\w-./?%&=:\\+]*)?$").test(v)){
                            alert("填写的网址格式不正确，请确认");
                            obj.focus();
                            return false;
                        }
                        $("button",this).attr("disabled", true).css("color","#888");
                        Meimi.api.get("posturl",{
                            topicid:topicid, 
                            markid:markid,
                            content:obj.val().trim()
                        },function(json){
                            this.close();
                            $("button",this).attr("disabled", false).css("color","");
                            if(json.code == 1){
                                location.reload();
                            }else{
                                Meimi.dialog.notice(json.result, {
                                    className:"dialog_error"
                                });
                            }
                        }.bind(this));
                        return false;
                    }.bind(this));
                    $("span.cancel",this.pannel).unbind("click").bind("click",this.close.bind(this));
                }
            }
        });
    },
    url:{
        preview: function(url){
            var num_iid = '';
            var list = {};
            $.each(url.match(/(?:[\?|\&])[^\=]+=[^\&|#|$]*/gi) || [], function(n, item) {
                var _item = item.substring(1);
                var _key = _item.split("=", 1)[0];
                var _value = _item.replace(eval("/" + _key + "=/i"), "");
                list[_key.toLowerCase()] = _value;
            });
            num_iid = list["id"] || list["item_num_id"];
            if(num_iid){
                Meimi.dialog.ajax("商品预览",{
                    action:"write",
                    params:{
                        name:2,
                        num_iid:num_iid
                    },
                    result:"result",
                    width: 550,
                    blur:true,
                    open:{
                        callback: function(){
                            var _dialog = this;
                            var obj = $("#previewContent",this.pannel);
                            Meimi.api.get("taobao_item_get",{
                                num_iid: num_iid
                            },function(json){
                                if(json.result.item_get_response){
                                    Meimi.init("core.template",function(){
                                        var item = json.result.item_get_response.item;
                                        Meimi.api.get("taobao_items_get",{
                                            q:item.title, 
                                            nicks:item.nick
                                            }, function(json2){
                                            if(json2.result.items_get_response.items){
                                                var item2 = json2.result.items_get_response.items.item[0];
                                                $("a.rank",obj).addClass("seller-rank-" + item2.score);
                                                $(".url_ext",obj).html(Meimi.template("URL_PREVIEW_EXT",item2));
                                            }
                                        });
                                        Meimi.api.get("taobao_shop_get",{
                                            nick:item.nick
                                            }, function(json2){
                                            if(json2.result.shop_get_response.shop){
                                                var item2 = json2.result.shop_get_response.shop;
                                                $("a.nick_link,a.nick_rank",obj).attr("href","http://shop" + item2.sid + ".taobao.com/");
                                            }
                                        });
                                        obj.html(Meimi.template("URL_PREVIEW",item));
                                        _dialog.setPos();
                                    });
                                }else{
                                    obj.html("无法获取该商品的信息，可能商品信息已过期！");
                                }
                            },false,true,{
                                error:function(){
                                    obj.html("无法获取该商品的信息，可能商品信息已过期！");
                                }
                            });
                        }
                    }
                });
            }else{
                Meimi.dialog.alert("没有预览信息，请直接点击完整网址进行查看！");
            }
        },
        buy: function(topicid,postid){
            if(!Meimi.common.user.checklogin())return;
            var self = this;
            Meimi.dialog.layer("我买过 - 提供购买反馈",{
                content:"#buyDialog",
                mask:true,
                blur:true,
                className:"dialog_like",
                width: 440,
                open:{
                    callback:function(){
                        var dialog = this;
                        $(".buy_detail",this.pannel).empty().append($("#urlItem" + postid).clone().contents().not(".button"));
                        $("span.submit_small a",this.pannel).unbind("click").bind("click",function(){
                            Meimi.api.get("buy",{
                                topicid:topicid, 
                                postid:postid,
                                rate:this.rel
                            },function(json){
                                dialog.close();
                                if(json.code == 1){
                                    if(this.rel == 1)
                                        var i = 1;
                                    else if(this.rel == -1)
                                        var i = 2;
                                    $(".meta em","#urlItem" + postid).eq(0).html(function(html){
                                        return parseInt(html)+1;
                                    }).end().eq(i).html(function(html){
                                        return parseInt(html)+1;
                                    });
                                    $(self).closest(".button").replaceWith('<span class="btn_buy">已评分</span>');
                                    Meimi.dialog.suggest("提交成功，谢谢参与");
                                }else{
                                    Meimi.dialog.suggest(json.result);
                                }
                            }.bind(this));
                            return false;
                        });
                    //$("span.cancel",this.pannel).unbind("click").bind("click",this.close.bind(this));
                    }
                }
            });
        },
        del: function(topicid,postid){
            var self = this;
            Meimi.common.confirm("确认要删除这个购买地址吗？",function(){
                //location.replace(self.href);
                Meimi.api.get("deleteurl",{
                    topicid:topicid,
                    postid:postid
                },function(json){
                    if(json.code == 1){
                        $("#urlItem"+postid).slideUp(1000,function(){
                            $(this).remove();
                        });
                        Meimi.dialog.suggest(json.result);
                    }else{
                        Meimi.dialog.notice(json.result);
                    }
                }.bind(this));
                return false;
            });
            return false;
        }
    },
    errorAnimation: function(obj) {
        obj.stop(false, true).focus();
        var _o_bgcolor = obj.css("backgroundColor");
        obj.css({
            backgroundColor: "#FFC8C8"
        }).animate({
            backgroundColor: _o_bgcolor
        }, 1000);
        return false;
    },
    anchor:{
        _init: function(options){
            this.opt = $.extend({
                el: document.body,
                container: document.body,
                target: document.body,
                count: 0,
                max: Meimi.MAXANCHORCOUNT,
                maxdesc: 30
            }, options || {});
            this.opt.container = $(this.opt.el).parent();
        },
        init:function(options){
            this._init(options);
            var self = this;
            $.each(self.opt.data.result,function(i,item){
                $('<a href="javascript:void(0)" class="anchor" rel="' + item.id + '" title="' + item.title + '"><span class="icon i_num18">' + (i+1) + '</span></a>').appendTo(self.opt.container).css({
                    top: item.anchor.y,
                    left: item.anchor.x
                }).hover(function(){
                    $("#thingItem" + this.rel).toggleClass("hover");
                });
            });
            $(self.opt.target).children("li").bind("mouseenter mouseleave",function(e){
                //$(this).toggleClass("hover");
                //if(e.type == "mouseenter")$(this).siblings().removeClass("hover");
                self.opt.container.find(".anchor[rel=" + $(this).attr("rel") + "]").andSelf().toggleClass("hover",e.type == "mouseenter");
            });
        },
        list:function(){
            $("li.normal[bind!='ok']").each(function(i){
                var item = eval("(" + $(this).attr("anchor_init") + ")");
                $('<a href="javascript:void(0)" class="anchor" rel="' + item.id + '" title="' + item.title + '"><span class="icon i_num18">' + item.sortrank + '</span></a>').appendTo($("#photoface"+$(this).attr("topic_id"))).css({
                    top: item.anchor.y,
                    left: item.anchor.x
                }).hover(function(){
                    $("#thingItem" + $(this).attr("rel")).toggleClass("hover");
                });
                $(this).bind("mouseenter mouseleave",function(e){
                    $("#photoface"+$(this).attr("topic_id")).find(".anchor[rel=" + $(this).attr("rel") + "]").andSelf().toggleClass("hover",e.type == "mouseenter");
                });
                $(this).attr("bind","ok");
            });
        },
        bind: function(options){
            this._init(options);
            var self = this;
            self.opt.templete = '<div><div class="d_content">' + 
            '<div class="wedge"></div>' + 
            '<form>' + 
            '<input class="text default" type="text" name="content" value="物品描述（如：品牌、亮点）..." autocomplete="off"" />' + 
            '<span class="button submit"><span><button type="submit">保存锚点</button></span></span> ' + 
            '<a href="javascript:;" class="del_anchor">移除</a>' + 
            '</form>' + 
            '</div>';
            if(self.anchorDialog == undefined) {
                self.anchorDialog = Meimi.dialog.layer(null,{
                    content: self.opt.templete,
                    className:"tooltip anchor_form",
                    width: 340,
                    open:{
                        callback:function(){
                            var initValue = $("li",self.opt.target).eq(this.pannel.data("index") - 1).children("kbd").text().trim();
                            if(initValue.length > 0){
                                self.anchorDialog.pannel.find("input[name=content]").focus().val(initValue)[0].select();
                            }else if(self.opt.a_count >= 1){
                                self.anchorDialog.pannel.find("input[name=content]").focus();
                            }
                        }
                    }
                }).hide();
                self.anchorDialog.pannel.find("form").bind("submit.anchor",function(){
                    var desc = this.pannel.find("input[name=content]");
                    var position = $(".anchor:eq(" + (this.pannel.data("index") - 1) + ")",self.opt.container).position();
                    if(Meimi.form.isInputNull(desc)){
                        alert("请填写物品描述！");
                        return false;
                    }
                    if(Meimi.tools.string.length(desc.val()) > self.opt.maxdesc){
                        alert("物品描述最多只允许" + self.opt.maxdesc + "个字符（" +  self.opt.maxdesc / 2 + "个中文）哦。");
                        desc.focus();
                        return false;
                    }
                    self.save(0,this.pannel.data("index"),desc.val().trim(),parseInt(position.left,10),parseInt(position.top,10));
                    return false;
                }.bind(self.anchorDialog));
                self.anchorDialog.pannel.find("a.del_anchor").bind("click.anchor",function(){
                    self.delTmp(this.pannel.data("index"));
                    return false;
                }.bind(self.anchorDialog));
            }
            $(self.opt.el).bind("click",self.mark.bind(this)).out("click",function(e){
                if(e.target.tagName == "INPUT" || e.target.tagName == "TEXTAREA") return;
                var a = $(".anchor",self.opt.container);
                if(a.has(e.target).length == 0 && self.anchorDialog.pannel.has(e.target).length == 0){
                    var desc = self.anchorDialog.pannel.find("input[name=content]");
                    if(Meimi.form.isInputNull(desc)){
                        self.anchorDialog.hide();
                        self.opt.count = $("li",self.opt.target).length;
                        a.slice(self.opt.count).remove();
                    }else{
                        self.anchorDialog.pannel.find("form").triggerHandler("submit.anchor");
                    }
                }
                return false;
            },true);
        },
        _initDialog: function(){
            if(this.anchorDialog){
                this.anchorDialog.hide();
            }
        },
        mark: function(e,defaultX,defaultY){
            var self = this;
            self.opt.count = $("li",self.opt.target).length;
            if(self.opt.count >= self.opt.max){
                Meimi.dialog.notice("最多只允许标记" + self.opt.max + "个锚点！",{
                    className:"dialog_error"
                });
                return false;
            }
            self.delTmp(self.opt.count + 1);
            self.bindMark.call(self,defaultX || ((e.layerX||e.offsetX) - 9),defaultY || ((e.layerY||e.offsetY) - 9), true).triggerHandler("click");
        },
        bindMark: function(x,y,issave,userid,postcount){
            if(postcount == undefined) postcount = 0;
            if(userid == undefined) userid = 0;
            var self = this;
            self.opt.a_count = $(".anchor",self.opt.container).length;
            var obj = $('<a href="javascript:void(0)" class="anchor preview" title="' + (issave ? "标记可拖动进行位置调整" : "已保存标记不允许移动") + '"><span class="icon i_num18">' + (self.opt.a_count + 1) + '</span></a>').appendTo(self.opt.container).css({
                top: y,
                left: x
            }).bind("mouseenter mouseleave",function(){
                var index = $(this).index() - 1;
                $("li:eq(" + index + ")",self.opt.target).toggleClass("hover");
            }).bind("mousedown",function(){
                self.anchorDialog.hide();
                if(issave) $(this).css("opacity",0.5);
            }).bind("mouseup",function(){
                $(this).css("opacity",1);
            });
            if(Meimi.common.user.info.groupid == 1 || userid == 0 || (Meimi.common.user.info.userid == userid && postcount == 0)){
                obj.bind("click",function(e){
                    self._initDialog();
                    self.anchorDialog.setPos({
                        top: $(this).offset().top - 10,
                        left: $(this).offset().left + 30
                    }).pannel.data("index",$(this).index());
                    self.anchorDialog.show();
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                });
                if(issave)
                    obj.drag(self.opt.container);
            }
            return obj;
        },
        delTmp: function(i){
            var self = this;
            self.anchorDialog.hide();
            $("li",self.opt.target).eq(i-1).remove();
            $(".anchor",self.opt.container).eq(i-1).remove();
            var _count = $("li",self.opt.target).length;
            if(self.opt.count > _count){
                self.opt.count = _count;
                self.opt.a_count = $(".anchor",self.opt.container).length;
                $(".anchor",self.opt.container).each(function(i){
                    $(".i_num18",this).html(i+1);
                    $("li:eq(" + i + ") .i_num23",self.opt.target).html(i+1);
                });
            }
        },
        save: function(id,i,value,x,y,userid,postcount){
            var self = this;
            if(postcount == undefined) postcount = 0;
            if(userid == undefined) userid = 0;
            if($("li",self.opt.target).eq(i - 1).length == 0){
                var _html = [];
                _html.push('<li><span class="icon i_num23">' +  i + '</span><kbd>' + value + '</kbd>');
                if(Meimi.common.user.info.groupid == 1 || Meimi.common.user.info.userid == userid || userid == 0){
                    if(Meimi.common.user.info.groupid == 1 || postcount == 0)
                        _html.push('<a href="javascript:void(0)" class="remove" title="删除" unselectable="on"></a>');
                    else
                        _html.push('<em class="note" title="出于对购买信息提供者的权益保护，我们希望不删除任何一个已有相应购买地址的标记，如需删除，请联系美蜜客服。">锁</em>');
                }else{
                    _html.push(' <em class="date">（他人标记）</em>');
                }
                _html.push('<input type="hidden" name="anchorid[]" value="' + (id || 0) + '" />');
                _html.push('<input type="hidden" name="anchors[]" value="' + value + '" />');
                _html.push('<input type="hidden" name="signs[]" value="' + x + ',' + y + '" />');
                _html.push('<input type="hidden" name="postcount[]" value="' + postcount + '" />');
                _html.push('</li>');
                $(_html.join('')).appendTo(self.opt.target)
                .bind("mouseenter mouseleave",function(){
                    var index = $(this).index();
                    $("a.anchor:eq(" + index + ")",self.opt.container).toggleClass("hover");
                }).click(function(e){
                    var index = $(this).index();
                    $(".anchor:eq(" + index + ")",self.opt.container).triggerHandler("click");
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }).find(".remove").click(function(e){
                    //Meimi.common.confirm("确认要删除吗？",function(){
                    self.delTmp($(this).closest("li").index() + 1);
                    //}.bind(this));
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                });
                self.opt.count = $("li",self.opt.target).length;
            }else{
                $("li",self.opt.target).eq(i - 1).find("kbd").text(value).end()
                .find("input[name='anchors[]']").val(value).end()
                .find("input[name='signs[]']").val(x + ',' + y);
            }
            this.anchorDialog.pannel.find("input.text").val("").trigger("blur");
            this._initDialog();
        },
        edit: function(topicid, anchorid){
            Meimi.dialog.layer("修改物品标记",{
                content: "#anchorEditDialog",
                mask:true,
                open:{
                    callback:function(){
                        var dialog = this;
                        $("input[name=title]",this.pannel).val($("kbd","#thingTitle" + anchorid).html());
                        $("span.submit_small a",this.pannel).unbind("click").eq(0).bind("click",function(){
                            $("form",dialog.pannel).trigger("submit");
                            return false;
                        });
                        $("form",this.pannel).submit(function(){
                            var self = this;
                            var titleValue = $("input[name=title]",dialog.pannel).val();
                            if(titleValue.trim() == ""){
                                alert("描述不能为空！");
                                return false;
                            }
                            dialog.close();
                            var loading = Meimi.dialog.loading();
                            Meimi.api.post("updateanchor",{
                                title: titleValue,
                                anchorid: anchorid
                            }, function(json){
                                if(json.code == 1){
                                    location.reload();
                                }else{
                                    Meimi.dialog.alert(json.result);
                                }
                            });
                            return false;
                        }).find("a.del_anchor").bind("click",function(){
                            if(confirm("确认要移除吗？")){
                                dialog.close();
                                var loading = Meimi.dialog.loading();
                                Meimi.api.get("deleteanchor",{
                                    anchorid: anchorid
                                }, function(json){
                                    if(json.code == 1){
                                        location.reload();
                                    }else{
                                        loading.close();
                                        Meimi.dialog.alert(json.result);
                                    }
                                });
                            }
                            return false;
                        });
                    //$("span.cancel",this.pannel).unbind("click").bind("click",this.close.bind(this));
                    }
                }
            });
        }
    },
    comment:{
        init: function(obj,topicid){
            obj = $(obj);
            //评论
            $("span.comment_reply_btn a",obj).click(function(){
                $("form.thread_form input[name=parentid]",obj).val(this.rel);
				$("form.thread_form input[name=classid]",obj).val(this.rel);
                $("form.thread_form textarea[name=content]",obj).focus().val(this.title);
                return false;
            });
            $("a.comment_del_btn",obj).live("click",function(){
                Meimi.common.comment.del(this.rel,topicid);
                return false;
            });
            $("form.thread_form textarea[name=content]",obj).focus(function(){
                if(this.timer) return;
                this.timer = setInterval(function(){
                    if(!/^@[^\ ]+\ .*/.test($(this).val())){
                        $("form.thread_form input[name=parentid]",obj).val(0);
						//$("form.thread_form input[name=classid]",obj).val(0);
                    }
                }.bind(this),200);
            }).blur(function(){
                clearInterval(this.timer);
            });
            Meimi.common.comment.bindEmot($("form.thread_form .i_insertemot",obj),$("form.thread_form textarea[name=content]",obj));
            $("form.thread_form",obj).submit(function(){
                var obj = $("textarea[name=content]",this);
                var parent = $("input[name=parentid]",this);
				var class_id = $("input[name=classid]",this);
                if (Meimi.form.isInputNull(obj)) {
                    Meimi.common.errorAnimation(obj);
                    return false;
                }
                Meimi.common.comment.save({
                    target: parent,
                    topicid: topicid,
					classid: class_id.val(),
                    parentid: parent.val(),
                    content: obj.val()
                },function(json){
                    if(!json.code > 0) return;
                    obj.val("");
                    if(parent.val() == 0){
                        var template = '<li class="item" style="display:none" id="comment'+json.code+'">\
											<a href="javascript:void(0)" class="comment_del_btn" rel="' + json.code + '" title="删除">X</a>\
											<div class="list_image">\
												<a href="/user/' + Meimi.common.user.info.userid + '/" title="' + Meimi.common.user.info.nickname + '"><img alt="' + Meimi.common.user.info.nickname + '" onerror="this.src=\'' + Meimi.RESOURCEURL + '/images/common/face50.gif\'" class="icon i_user i_user50" src="' + Meimi.RESOURCEURL + '/uploads/face/' + Meimi.common.user.info.userid + '/50.jpg"></a>\
												<a class="title" href="/user/' + Meimi.common.user.info.userid + '/">' + Meimi.common.user.info.nickname + '</a>\
												<em class="date">刚刚</em>\
											</div>\
											<div class="list_info"><p>' + json.result + '</p></div>\
										</li>';
                        $("li.nodata","#comment").remove();
                        $(template).appendTo("#comment .list_comment").fadeIn(1000);
                    }else{
                        var template = '<li style="display:none" id="comment'+json.code+'">\
											<a href="javascript:void(0)" class="comment_del_btn" rel="' + json.code + '" title="删除">X</a>\
											<div class="lite_image">\
												<a href="/user/' + Meimi.common.user.info.userid + '/" title="' + Meimi.common.user.info.nickname + '"><img alt="' + Meimi.common.user.info.nickname + '" onerror="this.src=\'' + Meimi.RESOURCEURL + '/images/common/face30.gif\'" class="icon i_user i_user30" src="' + Meimi.RESOURCEURL + '/uploads/face/' + Meimi.common.user.info.userid + '/30.jpg"></a>\
												<a class="title" href="/user/' + Meimi.common.user.info.userid + '/">' + Meimi.common.user.info.nickname + '</a>\
												<em class="date">刚刚</em>\
											</div>\
											<div class="lite_info"><p>' + json.result + '</p></div>\
										</li>';
                        $(template).appendTo($(".lite_small_comment","#comment" + parent.val()).show()).fadeIn(1000);
                        location.href = "#comment" + parent.val();
                    }
                    Meimi.dialog.suggest("评论成功！");
                    parent.val(0);
                });
                return false;
            });
        },
        del:function(commentid,topicid){
            Meimi.common.confirm("你确认要删除这条评论吗？",function(){
                Meimi.api.get("deletecomment",{
                    id: commentid,
                    topicid: topicid
                },function(json){
                    if(json.code == 1){
                        $("#comment" + commentid).slideUp(1000,function(){
                            $(this).remove();
                        });
                        Meimi.dialog.suggest("删除评论成功！");
                    }else{
                        Meimi.dialog.notice(json.result);
                    }
                });
            });
            return false;
        },
        bindEmot: function(el,target){
            var $div = $('<div class="d_emot d_content"></div>');
            el = $(el);
            target = $(target);
            el.click(function(){
                if(el.emot){
                    el.emot.toggle();
                }else{
                    for(var i = 1; i <= 60; i++){
                        $('<a rel="' + i + '" class="emot e-base-' + i + '" href="javascript:;"><img alt="" src="' + Meimi.RESOURCEURL + '/images/common/emot/' + i + '.gif"></a>').appendTo($div).click(function(){
                            Meimi.tools.insertSelection(target[0], '[em' + this.rel + ']');
                            el.emot.hide();
                            target.focus().css("color", "#000");
                            return false;
                        });
                    }
                    el.emot = Meimi.dialog.tooltip("layer", "", {
                        width: 430,
                        content: $("<div/>").append($div),
                        pos: {
                            "top": el.offset().top + el.outerHeight() + 2,
                            "left": el.offset().left - 1
                        }
                    })
                }
                return false;
            });
        },
        save: function(options, callback){
            var opt = $.extend({
                topicid: 0,
                parentid: 0,
				classid: 1,
                content: ""
            }, options || {});
            callback = callback || $.noop;
            Meimi.api.post("postcomment",{
                topicid: opt.topicid,
                parentid: opt.parentid,
				classid: opt.classid,
                content: opt.content
            },function(json){
                if(json.code > 0){
                    callback(json);
                }else{
                    Meimi.dialog.notice(json.result,{
                        className:"dialog_error"
                    });
                }
            });
        }
    },
    like: {
        save:function(topicid,tags, callback){
            Meimi.api.post("like",{
                topicid: topicid,
                tags: tags || []
            }, function(json){
                if(json.code == 1){
                    $("var","#likeinfo" + topicid).html(json.result);
                    if($.isFunction(callback))callback(json.result);
                }else{
                    Meimi.dialog.notice(json.result,{
                        className:"dialog_error"
                    });
                }
            });
            return false;
        },
        show: function(topicid,authorid, reload){
            var self = this;
            if(authorid == Meimi.common.user.info.userid){
                Meimi.dialog.notice("不能给自己发表的图片投票哦！",{
                    className:"dialog_error"
                });
                return false;
            }
            var obj = $("#likeinfo" + topicid);
            self.save(topicid, []);
            if(!obj.data("isshow")){
                var dialog = Meimi.dialog.tooltip("ajax",null,{
                    action:"postlike",
                    params:{
                        name: 1,
                        topicid: topicid
                    },
                    width: 580,
                    className:"tooltip like_dialog",
                    drag: false,
                    pos:{
                        top: obj.offset().top + obj.height() + 2,
                        left: obj.offset().left
                    },
                    mask: false,
                    open:{
                        callback:function(){
                            obj.data("isshow",true);
                            var _dialog = this;
                            var isedit = false;
                            $("ul.tag_label li>a",this.pannel).bind("click.tag",function(){
                                isedit = true;
                                if(!$("input[name=tag]",this).is(":checked") && $("input[name='tag[]']:checked",_dialog.pannel).length >= Meimi.MAXTAGCOUNT){
                                    alert("最多只能选择 " + Meimi.MAXTAGCOUNT + " 个风格印象标签哦！");
                                    return false;
                                }
                                $(this).toggleClass("curr").find("input:checkbox").attr("checked",$(this).hasClass("curr"));
                                return false;
                            });
                            $("span.submit a",this.pannel).click(function(){
                                var _tags = $("input[name='tag[]']",this.pannel).serializeArray();
                                var tags = [];
                                $.each(_tags, function(i,item){
                                    tags.push(item.value);
                                });
                                tags = ""+tags+"";
                                self.save(topicid, tags ,function(){
                                    //if(reload && isedit) location.reload();
                                    _dialog.close();
                                });
                                return false;
                            }.bind(this));
                            $("span.cancel a",this.pannel).click(this.close.bind(this));
                        }
                    },
                    close:{
                        callback:function(){
                            obj.removeData("isshow");
                        }
                    }
                });
            }
            return false;
        }
    },
    votetag:function(tagid,topicid,rate){
		
    },
    user: {	
        checklogin: function(){
            if(!Meimi.common.user.info.userid){
                Meimi.dialog.layer("请先登录",{
                    content:'<div><div class="d_content">对不起，您还没有登录呢！</div></div>',
                    className: "dialog_error",
                    mask:true,
                    buttons: [{
                        title: '马上登录',
                        type: 'main',
                        close: true,
                        func: function(){
                            location.href = $("#loginLink").attr("href");
                        }
                    },
                    {
                        title: '注册新帐号',
                        type: 'button_blue',
                        close: true,
                        func: function(){
                            location.href = $("#regLink").attr("href");
                        }
                    }
                    ]
                });
                return false;
            }
            return true;
        },
        //好友
        follow: function(uid, options) {
            var options = $.extend({
                el: null,
                displayname: ""
            }, options);
            var _loading = Meimi.dialog.loading();
            Meimi.api.get("addfollow", {
                uid: uid
            }, function(json) {
                Meimi.dialog.notice(json.result, {
                    className:"dialog_succes"
                });
                switch (json.code) {
                    case 1:
                        if (options.el) $(options.el).attr("onclick", "").removeClass().addClass("disabled").html('已成功关注');
                        break;
                }
                _loading.close();
            });
        },
        unfollow: function(uid, options) {
            var options = $.extend({
                el: null,
                displayname: ""
            }, options);
            var _loading = Meimi.dialog.loading();
            Meimi.api.get("removefollow", {
                uid: uid
            }, function(json) {
                Meimi.dialog.notice(json.result, {
                    className:"dialog_succes"
                });
                switch (json.code) {
                    case 1:
                        if (options.el) $(options.el).attr("onclick", "").removeClass().addClass("disabled").html('已取消关注');
                        break;
                }
                _loading.close();
            });
        },
        editIcon: function(){
            var imgw,imgh;
            this.preview = function(img, selection) { 
                var scale50X = 50 / selection.width; 
                var scale50Y = 50 / selection.height; 
                var scale30X = 30 / selection.width; 
                var scale30Y = 30 / selection.height; 
                $('#preimg50').css({ 
                    width: Math.round(scale50X * imgw) + 'px', 
                    height: Math.round(scale50Y * imgh) + 'px', 
                    marginLeft: '-' + Math.round(scale50X * selection.x1) + 'px',
                    marginTop: '-' + Math.round(scale50Y * selection.y1) + 'px'
                });
                $('#preimg30').css({ 
                    width: Math.round(scale30X * imgw) + 'px', 
                    height: Math.round(scale30Y * imgh) + 'px', 
                    marginLeft: '-' + Math.round(scale30X * selection.x1) + 'px',
                    marginTop: '-' + Math.round(scale30Y * selection.y1) + 'px'
                });
                if($('#imgpos').length && selection) $('#imgpos').attr('value',selection.x1 + '_' + selection.y1 + '_' + (selection.x2 - selection.x1)).attr('name', 'imgpos');
            }
            if($('#imgpos').length){
                imgw = $('#bigimg').width();
                imgh = $('#bigimg').height();
                var _ = $('#imgpos').val().split('_');
                var pos = (_[2] && (_[2] != '0') && (parseInt(_[0]) + parseInt(_[2])) <= imgw && (parseInt(_[1]) + parseInt(_[2])) <= imgh)?  { 
                    x1: parseInt(_[0]), 
                    y1: parseInt(_[1]), 
                    x2: parseInt(_[0]) + parseInt(_[2]), 
                    y2: parseInt(_[1]) + parseInt(_[2]) 
                } : {
                    x1: imgw > imgh ? (imgw-imgh)/2+3 : (imgw == imgh ? 0 : 3), 
                    x2: imgw > imgh ? (imgw+imgh)/2-3 : (imgw == imgh ? imgw : imgw-3), 
                    y1: imgw > imgh ? 3 : (imgw == imgh ? (imgh-imgw)/2 : (imgh-imgw)/2 + 3), 
                    y2: imgw > imgh ? imgh-3 : (imgw == imgh ? (imgh+imgw)/2 : (imgh+imgw)/2-3) 
                };
                $('#bigimg').imgAreaSelect($.extend(pos,{
                    aspectRatio : '1:1' ,
                    onSelectChange : this.preview,
                    onInit : this.preview,
                    persistent : true
                }));
            }
        }
    },
    message: {
        filter: function(id){
            Meimi.api.get("readnotice",{
                id: id,
                status: 2
            },function(json){
                if(json.code == 1){
                    $(this).closest("tbody").fadeOut(function(){
                        if($(this).siblings().length == 0) 
                            $(".index_notice2").remove();
                        else
                            $(this).remove();
                    });
                }else{
                    Meimi.dialog.notice(json.result);
                }
            }.bind(this));
        },
        post: function(touid, touname) {
            Meimi.dialog.ajax("给" + touname + "发送悄悄话", {
                action: "write",
                params: {
                    id: 1
                },
                result: "result",
                open: {
                    callback: function() {
                        this.pannel.find("textarea[name=content]").focus();
                    }
                },
                buttons: [{
                    title: '提交',
                    type: 'main',
                    close: false,
                    func: function() {
                        var obj = this.pannel.find("textarea[name=content]");
                        if (Meimi.form.isInputNull(obj)) {
                            Meimi.SNS.common.errorAnimation(obj);
                            return false;
                        }
                        this.close();
                        Meimi.api.post("postmessage", {
                            touid: touid,
                            messagebody: obj.val()
                        }, function(json) {
                            if (json.code > 0) {
                                Meimi.dialog.notice(json.result, {
                                    className:"dialog_succes"
                                });
                            }
                        });
                    }
                },
                {
                    title: '取消',
                    type: 'cancel',
                    close: true
                }
                ]
            });
        },
        check: function() {
            var _this = this;
            _this.originalTitle = _this.originalTitle || document.title;
            var mainObj = $("#container");
            var noteTips = $("#noteTips");
            $(window).bind("resize.checkmsg",function(){
                noteTips.css("right",mainObj.offset().left);
            }).triggerHandler("resize.checkmsg");
            Meimi.api.get("checknote", {}, function(json) {
                if (json.code > 0) {
                    if (json.result.length > 0) {
                        noteTips.show().find("em").html(json.result.length);
                        clearInterval(_this.timer);
                        _this.timer = setInterval(function() {
                            if (!this.tipSwitch) {
                                this.tipSwitch = true;
                                //document.title = "【新消息】" + this.originalTitle;
                                $("a>span",noteTips).css("visibility","visible");
                            } else {
                                this.tipSwitch = false;
                                $("a>span",noteTips).css("visibility","hidden");
                            //document.title = "【　　　】" + this.originalTitle;
                            }
                        } .bind(_this), 700);
                    } else {
                        clearInterval(_this.timer);
                        noteTips.hide().find("em").html(0);
                        document.title = _this.originalTitle;
                        _this.originalTitle = "";
                    }
                }
            }, false, true, {
                global: false
            });
            setTimeout(arguments.callee.bind(this), Meimi.NOTEFREQUENCY);
        }
    }
};

/*
 * jQuery Color Animations
 */
(function(jQuery){
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
        jQuery.fx.step[attr] = function(fx){
            if ( fx.state == 0 ) {
                fx.start = getColor( fx.elem, attr );
                fx.end = getRGB( fx.end );
            }
            fx.elem.style[attr] = "rgb(" + [
            Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
            Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
            Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
            ].join(",") + ")";
        }
    });
    function getRGB(color) {
        var result;
        if ( color && color.constructor == Array && color.length == 3 )
            return color;
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
            return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
            return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
            return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
            return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
        return "";
    }
    function getColor(elem, attr) {
        var color;
        do {
            color = jQuery.curCSS(elem, attr);
            if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
                break; 
            attr = "backgroundColor";
        } while ( elem = elem.parentNode );
        return getRGB(color);
    };
})(jQuery);

$(function(){
    $(".open").click(function(){
        open_wind($(this).attr("href"),$(this).attr("width"),$(this).attr("height"));
        return false;
    });
});
function open_wind(url, width, height){
    var top=($(window).height()-height)/2;
    var left=($(window).width()-width)/2;
    window.open(url,'kaixinwindow', 'height='+height+', width='+width+', toolbar =no, menubar=no, scrollbars=yes, resizable=no,top='+top+',left='+left+', location=no, status=no');
}
