﻿// 首页模块
Object.extend = function(destination, source) {
    for (var property in source) {
        destination[property] = source[property];
    }
    return destination;
}
var Class = {
    create: function() {
        return function() { this.ini.apply(this, arguments); }
    }
}
var def = Class.create();
Object.extend(def, {
    Init: function() {
        var len = $(".carousel a").size();
        $("#reviewSbm").click(function() {
            view.onCommentValid();
        });
        for(i=0; i<len; i++){
            view.href.push($(".carousel a").eq(i).attr("href"));
        }
    },
    pos: function(obj) {
        $(".hasMenu").removeClass("selected");
        obj.addClass("selected");
        p = obj.position();
        $(".submenu").hide();
        navId = obj.attr("id");
        $("#sub_" + navId).show();
    },
    globel_header: function(){
        $(".hasMenu").hover(function(){
		    def.pos($(this));
		    if ($(this).attr("id")!="menu5") {
		        $("#menu5").addClass("currMenu");
		    }else{
		        $("#menu5").removeClass("currMenu");
		    }
	    });
	    def.pos($("#menu5"));
    },
    interActive: function(obj) {
        isWhat = $(obj).attr("class");
        if (isWhat == "favo") {
            if (view.isFavo == false) {
                $(obj).addClass("favoed");
                view.isFavo = true;
            }
        } else if (isWhat == "top") {
            num = parseInt($(obj).children("label").text()) + 1;
            $(obj).children("label").text(num++);
        } else if (isWhat == "down") {
            num = parseInt($(obj).children("label").text()) + 1;
            $(obj).children("label").text(num++);
        }
    },
    get_share_url: function(type, link_id) {

        var tgt_full_url = '';

        var default_title = document.getElementById("h1title").innerHTML;

        var current_topic_title = (default_title == null) ? document.title : default_title;

        document.title = current_topic_title;

        // add target uri and self title information

        if (type == "renren") {

            tgt_full_url += "http://share.renren.com/share/buttonshare.do?link=";

            tgt_full_url += encodeURIComponent(location.href);

            tgt_full_url += "&title=";

            tgt_full_url += encodeURIComponent(document.title);



        } else if (type == "qq") {
            tgt_full_url += "http://v.t.qq.com/share/share.php?url=";
		    tgt_full_url += encodeURIComponent(location.href);
		    tgt_full_url += "&title=";
		    tgt_full_url += encodeURIComponent(document.title);
        } else if (type == "sina") {

            tgt_full_url += "http://v.t.sina.com.cn/share/share.php?url=";

            tgt_full_url += encodeURIComponent(location.href);

            tgt_full_url += "&title=";

            tgt_full_url += encodeURIComponent(document.title);



        } else if (type == "baidu") {

            tgt_full_url += "http://cang.baidu.com/do/add?it=";

            tgt_full_url += encodeURIComponent(document.title);

            tgt_full_url += "&iu=";

            tgt_full_url += encodeURIComponent(location.href);



        } else if (type == "google") {

            tgt_full_url += "http://google.com/bookmarks/mark?op=edit&bkmk=";

            tgt_full_url += encodeURIComponent(location.href);

            tgt_full_url += "&title=";

            tgt_full_url += encodeURIComponent(document.title);

        } else if (type == "kaixin001") {

            tgt_full_url += "http://www.kaixin001.com/repaste/share.php?rurl=";

            tgt_full_url += encodeURIComponent(location.href);

            tgt_full_url += "&rtitle=";

            tgt_full_url += encodeURIComponent(document.title);

            tgt_full_url += "&rcontent=" + encodeURIComponent("Ã¦Â´Â¾Ã¤Â»Â£Ã§Â½ÂÃ¥ÂÂÃ¤ÂºÂ«Ã¯Â¼Â"); ;



        } else if (type == "douban") {

            tgt_full_url += "http://www.douban.com/recommend/?url=";

            tgt_full_url += encodeURIComponent(location.href);

            tgt_full_url += "&title=";

            tgt_full_url += encodeURIComponent(document.title);


        } else if (type == "taobao") {

            tgt_full_url += "http://share.jianghu.taobao.com/share/addShare.htm?url=";

            tgt_full_url += encodeURIComponent(location.href);

            tgt_full_url += "&title=";

            tgt_full_url += encodeURIComponent(document.title);

        }



        var link_obj = document.getElementById(link_id);

        link_obj.target = "_blank";

        link_obj.href = tgt_full_url;

        return true;

    }

    
});

var Showbox = Class.create();
Object.extend(Showbox, {
    GVar: {
        t: null,
        maxH: null, //缩略图总高度
        thVisiH: null, //缩略图可见区域高度
        thubsPos:[],  //存每个缩略图的位置
        thubsCurrTop:null, //目前显示的第一个缩略图的位置
        imgOrigW:null,  //图片原始宽
        imgOrigH:null,   //图片原始高
        stageW:null,  //图片显示区宽
        stageH:null, //图片显示区高 
        showingImg:null, //当前显示的图片对象
        isOrig: false,
		currIdx:0
    },
    
    Init: function () {
        Showbox.fixWindow();
        Showbox.fixEvent();
        //Showbox.loadLImg(".ex_stage", "http://jdi.baozang.com/201012/2014/666262w.jpg");
		Showbox.nEvent();
		var hash = window.location.hash,
		    GVar = Showbox.GVar,
		    tbns = $(".ex_thumbnail"),
		    len = tbns.length,
		    tbnl = $(".ex_thumbs_list");
		if(hash)GVar.currIdx = hash.slice(1);
		tbns.eq(parseInt(GVar.currIdx)).trigger("click");
        
        for(var i=0; i< len; i++){
            GVar.thubsPos[i] = -59*i ; //59是缩略图一格的高度
        }
        GVar.maxH = tbnl.outerHeight();
        GVar.thubsCurrTop = parseInt(tbnl.css("top"));
    },
    
    fixWindow: function () {
        var p = Showbox.getViewport();
        var thub = $(".ex_thumbs");
        var thub_w = $(".ex_thumbs_windows");
        var thub_lst = $(".ex_thumbs_list");
        var btn_p = $(".ex_btn_left");
        var btn_n = $(".ex_btn_right");
        var exInfo = $(".ex_tool_info");
        var Gvar = Showbox.GVar;
        
        thub.css({"top":p[3],"right":-p[2], "height":p[1]});
        exInfo.css({"bottom":-p[3], "right":-(p[2]-59)});
        // $(".ex_stage").html(thub_lst.outerHeight()); //结果
        
        if(thub_lst.outerHeight()<p[1]){
            Gvar.thVisiH = p[1];
            thub_w.height(p[1]);
            thub_lst.css("top","0px");
            btn_p.hide();
            btn_n.hide();
        }else{
            Gvar.thVisiH = p[1]-72;
            thub_w.height(p[1]-72); //72是上下按钮高度和
            btn_p.show();
            btn_n.show();
        }
        $(".ex_stage").width(p[0]).height(p[1]);
        Gvar.stageW = p[0];
        Gvar.stageH = p[1];
    },
    
    nEvent: function(){
        var Gvar = Showbox.GVar;
        $(".ex_btn_right").mouseover(function(){
            $(this).addClass("ex_btn_right_hover");
        }).mouseout(function(){
            $(this).removeClass("ex_btn_right_hover");
        }).click(function () {
            if(Gvar.thubsCurrTop<=0 && Gvar.maxH+Gvar.thubsCurrTop>Gvar.thVisiH){
                Showbox.jCarousel(parseInt((-Gvar.thubsCurrTop)/59+Gvar.thVisiH/59));//取余是为了半个格不算
            }
            //$(".ex_stage").html(Showbox.GVar.thubsCurrTop+"  "+Showbox.GVar.thVisiH);  //结果
        });
        
        $(".ex_btn_left").mouseover(function(){
            $(this).addClass("ex_btn_left_hover");
        }).mouseout(function(){
            $(this).removeClass("ex_btn_left_hover");
        }).click(function () {
            if(Gvar.thubsCurrTop<=0 && Gvar.thubsCurrTop+Gvar.thVisiH<0){
                Showbox.jCarousel(parseInt((-Gvar.thubsCurrTop)/59-Gvar.thVisiH/59)+1); //+1是为了将半个格算一个格
            }else{
                Showbox.jCarousel(0);
            }
            //$(".ex_stage").html(Showbox.GVar.thubsCurrTop+"  "+Showbox.GVar.thVisiH); //结果
        });
        
        $(".ex_thumbnail").click(function(){
            Showbox.loadLImg(".ex_stage", $(this).find("a").attr("href"));
			//Showbox.GVar.currIdx = $(this).attr("idx");
			$("#ex_picinfo").html($(this).find("img").attr("alt"));
			$(".ex_tool_info").animate({ 
                width: $("#ex_picinfo").width()+100
              }, 300 );
            return false;
        });
		
		$("#ex_orig").click(function(){
		    if(Gvar.isOrig){
		        alert("已是原图模式");
		        return false;
		    }
		    $(window).unbind("resize");
			Showbox.origImg();
			$(window).bind("resize",function () {
		        Showbox.onResize();
		    });
		});
		$("#ex_best").click(function(){
		    if(!Gvar.isOrig){
		        alert("已是最佳模式");
		        return false;
		    }
		    $(window).unbind("resize");
			Showbox.optImg();
			$(window).bind("resize",function () {
		        Showbox.onResize();
		    });
		});
		$("#ex_next").click(function(){
		    if(parseInt(Showbox.GVar.currIdx)+1>=$(".ex_thumbnail").length){
		        alert("已到最后一张");
		        return false;
		    }
			$(".ex_thumbnail").eq(parseInt(Showbox.GVar.currIdx)+1).trigger("click");	
		});
		$("#ex_prev").click(function(){
		    if(parseInt(Showbox.GVar.currIdx)-1<0){
		        alert("已到第一张");
		        return false;
		    }
			$(".ex_thumbnail").eq(parseInt(Showbox.GVar.currIdx)-1).trigger("click");	
		});
		$(window).bind("resize",function () {
		    Showbox.onResize();
		});
        $(window).scroll(function(){
            Showbox.fixWindow();   
        });
    },
    onResize : function () {
        var img = document.getElementById("ex_stage").getElementsByTagName("img")[0];
            if(!Showbox.GVar.isOrig){
                Showbox.fixWindow();
                Showbox.fixEvent();
                Showbox.fixImg();
               // alert("onResize fixImg");
                Showbox.centerImg($(".ex_stage"), Showbox.GVar.showingImg);
            }else{
                Showbox.fixWindow();
                Showbox.fixEvent();
                Showbox.centerImg($(".ex_stage"), Showbox.GVar.showingImg);
            }
    },
    fixEvent: function(){   //需要改成链接过来通过hash来判断显示第几个，及键盘和“上一件”“下一件”按钮来判断显示第几个
        var Gvar = Showbox.GVar;
        $(".ex_thumbnail").click(function(){
            $(".ex_thumbnail").removeClass("select");
            $(this).addClass("select");
            
            //点击的缩略图小格只有一半露在外面时则让其显示全部
            var idx = $(this).attr("idx");
            var thViFstIdx = parseInt((-Gvar.thubsCurrTop)/59);
            var thViLstIdx;
            if((-Gvar.thVisiH%59)!=0 && Gvar.maxH+Gvar.thubsCurrTop>Gvar.thVisiH){
                thViLstIdx = thViFstIdx+parseInt((Gvar.thVisiH/59));
            }
            if(idx==thViLstIdx){
                Showbox.jCarousel(thViFstIdx+1); 
            }
			if(idx<thViFstIdx){
				Showbox.jCarousel(idx);	
			}
			Gvar.currIdx = idx;
		    window.location.hash = idx;
            // $(".ex_stage").html(idx+"  "+thViLstIdx); //结果
           
            //加载大图
            return false;
        }); 
    },
    
    loadLImg: function(wrap, href){
        var imgWrap = $(wrap);
        imgWrap.empty();
        var newImg = new Image();
        $(newImg).load(function(){
            Showbox.GVar.imgOrigW = newImg.width;
            Showbox.GVar.imgOrigH = newImg.height;
            imgWrap.append($(this));
            Showbox.fixImg();
            //alert("loadLImg fixImg");
            Showbox.centerImg($(".ex_stage"), $(this));
            
        }).attr("src",href);
        Showbox.GVar.showingImg = $(newImg);
        Showbox.GVar.isOrig = false;
    },
    
    fixImg: function(){
        //alert("fixImg");
        if(!$(".ex_stage").find("img")) return;
        var img = $(".ex_stage").find("img");
        var ww = $(".ex_stage").width();
        var wh = $(".ex_stage").height();
        var iw = Showbox.GVar.imgOrigW;
        var ih = Showbox.GVar.imgOrigH;
 
        if(iw>0 && ih>0){
            if(iw/ih>= ww/wh){  
                if(iw>ww){  
                    img.width(ww);  
                    img.height((ih*ww)/iw);  
                }else{  
                    img.width(iw);  
                    img.height(ih);  
                }  
            } else{  
                if(ih>=wh){  
                    //$("#ex_picinfo").html(wh+" "+(iw*wh)/ih+" "+ww+" "+wh); 
                    img.height(wh);  
                    img.width((iw*wh)/ih);  
                }else{ 
                   // $("#ex_picinfo").html(iw/ih+" "+ww/wh+" "+ww+" "+wh); 
                    img.height(ih);   
                    img.width(iw);  
                }  
            }  
        }  
    },
    
    centerImg: function(wrap, img){
        //$("#ex_picinfo").html(wrap.width()+" "+wrap.height());  结果
        css = { "left": (wrap.width() - img.width()) / 2, "top": (wrap.height() - img.height()) / 2 };
        img.css(css);
    },
    
    origImg: function () {
       
       var Gvar = Showbox.GVar;
       var p = Showbox.getViewport();
       var /*img */$img = $("#ex_stage>img");//document.getElementById("ex_stage").getElementsByTagName("img")[0];
       /*var $img = $(img);*/
       var iw = Gvar.imgOrigW;
       var ih = Gvar.imgOrigH;
       
       //img.hide();
       $img.css({"height":"auto","width":"auto"});
       if(iw>p[0]){
           Showbox.centerImg($(".ex_stage"), $img);
           $img.css({"left":"0px"}); 
       }
       if(ih>p[1]){
           Showbox.centerImg($(".ex_stage"), $img);
           $img.css({"top":"0px"}); 
       }
       if(iw<=p[0]&&ih<=p[1]){
           Showbox.centerImg($(".ex_stage"), $img);
       }
       setTimeout('$(".ex_stage").find("img").show()',50);
       Gvar.isOrig = true;
    },
    
    optImg: function(){
        var Gvar = Showbox.GVar;
        var img = Gvar.showingImg;
        //img.hide();
        //alert("optImg fixImg");
        Showbox.fixImg();
        Showbox.centerImg($(".ex_stage"), img);
        window.scroll(0,0);
        //setTimeout('$(".ex_stage").find("img").show()',50);
        Gvar.isOrig = false;
    },
    
    jCarousel: function (to) {
        //alert(Showbox.GVar.thubsPos[to]);
        $(".ex_thumbs_list").animate({ 
            top: Showbox.GVar.thubsPos[to]+"px"
        }, 500 );
        Showbox.GVar.thubsCurrTop = -59*to;
    },
    
    getViewport: function() {
		return [$(window).width(), $(window).height(), $(document).scrollLeft(), $(document).scrollTop() ];
	}
	
});

jQuery.fn.loadthumb = function(options) {
    options = $.extend({
         src : "",
         imgId : "myImgs",
         parent : "CRviewer"
    },options);
    var _self = this;
    _self.hide();
    var img = new Image();
    $(img).load(function(){
        imgDem = {};
        imgDem.w  = img.width;
        imgDem.h  = img.height;
        imgDem = $.imgResize({"w": $(options.parent).width() ,"h": $(options.parent).height()},{"w":imgDem.w,"h":imgDem.h});
        var imgMargins = $.imgCenter({"w": $(options.parent).width() ,"h": $(options.parent).height()},{"w":imgDem.w,"h":imgDem.h});
        _self.css({width:imgDem.w,height:imgDem.h,marginLeft:imgMargins.l,marginTop:imgMargins.t});
        _self.attr("src", options.src);
        _self.fadeIn("slow");
    }).attr("src", options.src);  //.atte("src",options.src)要放在load后面，
    return _self;
}

//重置图片宽度，高度插件 ( parentDem是父元素，imgDem是图片 )
jQuery.imgResize = function(parentDem,imgDem){
    if(imgDem.w>0 && imgDem.h>0){
        var rate = (parentDem.w/imgDem.w < parentDem.h/imgDem.h)?parentDem.w/imgDem.w:parentDem.h/imgDem.h;
        //如果 指定高度/图片高度  小于  指定宽度/图片宽度 ，  那么，我们的比例数 取 指定高度/图片高度。
        //如果 指定高度/图片高度  大于  指定宽度/图片宽度 ，  那么，我们的比例数 取 指定宽度/图片宽度。
        if(rate <= 1){   
            imgDem.w = imgDem.w*rate; //图片新的宽度 = 宽度 * 比例数
            imgDem.h = imgDem.h*rate;
        }else{//  如果比例数大于1，则新的宽度等于以前的宽度。
            imgDem.w = imgDem.w;
            imgDem.h = imgDem.h;
        }
    }
    return imgDem;
}
//使图片在父元素内水平，垂直居中，( parentDem是父元素，imgDem是图片 )
jQuery.imgCenter = function(parentDem,imgDem){
    var left = (parentDem.w - imgDem.w)*0.5;
    var top = (parentDem.h - imgDem.h)*0.5;
    return { "l": left , "t": top};
}

//收藏
var Fav= Class.create();
Object.extend(Fav,{
    //收藏操作
    favor:function (userid) {
        var title=  $("title").html();
        title=escape(title);
         var sign = document.getElementById("sign");  
         if(document.getElementById("client"))  
            $("#client").remove();

         var javascript= document.createElement("script");
         javascript.setAttribute("type","text/javascript");
         javascript.setAttribute("id","client");
         javascript.setAttribute("ic_client","");
         sign.appendChild(javascript);    
    
         document.getElementById("client").src=("http://my.baozang.com/common/ashx/favorite/favorite.ashx?pa="+userid+"&title="+title); 
    },

    //判断状态
    stat:function () {  

         if($("#sign").html().indexOf("注销")>=0)//已登录
         {
         //欢迎 XXXXXXX, 进入我的用户中心 
            var userid=$("#sign").html().substring( $("#sign").html().indexOf("欢迎"), $("#sign").html().indexOf(", 进入")).replace("欢迎","");
            Fav.favor(userid);            
         }
         else    
         {
             User.OnPopLog();//弹出登录窗口
              //调整登录窗口的位置
             var scrlT = $(document).scrollTop();
             var pos=$("#popLogin").css("top");
             pos=pos.replace("px","");
             pos=parseInt(pos)+parseInt(scrlT);
             
             $("#popLogin").css("top",pos+"px");
         }        
            
    }    
    
});

var User = Class.create();
Object.extend(User,{
    PostDir : "/common/ashx/",
    ajaxPost: null,
    /// <summary>
    /// 登陆栏
    /// </summary>
    topbar:{
        notin : '<a onclick="User.OnPopLog()">登录</a> | <a href="http://my.baozang.com/signup/">注册</a>',
        hasin : '<span><a href="http://my.baozang.com/" title="进入我的用户中心">欢迎 {userid}, 进入我的用户中心 </a> <a onclick="User.SingOut();">注销</a></span>',
        loading:'loading...'
    },
    /// <summary>
    /// 检查是否已经登陆
    /// </summary>
    isSingIn : function () {
        $("#sign").html(User.topbar.loading);
        $.ajax({
            url: User.PostDir+ "checkSign.ashx?n=" + Math.random(),
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //alert(XMLHttpRequest.responseText);
                $("#sign").html(User.topbar.notin);
            },
            success: function(JsonData) {
                var json = $.evalJSON(JsonData)
                if (json.success == 1) {
                    $("#sign").html(User.topbar.hasin.replace("{userid}",json.BzUID));
                }
                else
                {
                    $("#sign").html(User.topbar.notin);
                }
            }
        });
    },
    /// <summary>
    /// 登陆
    /// </summary>
    /// <param name="options">Post的用户登陆数据{uin,upwd}</param>
    SingIn : function () {
       //alert(User.OnValid());
        if(User.OnValid()){
            $(".loading").show();
            User.ajaxPost =$.ajax({
                url:  User.PostDir+ "signin.ashx?n=" + Math.random(),
                async: true,
                type: "POST",
                data: { username: $("#unpop").val(), password: $("#pswpop").val() },
                complete: function() {
                    $(".loading").hide();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $("#sign").html(User.topbar.notin);
                    alert(XMLHttpRequest.responseText);
                },
                success: function(resTxt) {
                    var json = $.evalJSON(resTxt);
                    if (resTxt == "" || resTxt.length == 0 || resTxt == null) {
                        alert("登录请求已取消");
                        return;
                    }
                    if (json.success == 1) {
                        $("#sign").html(User.topbar.hasin.replace("{userid}",json.BzUID));
                        $("#popLogin").find(".text").val("");
                        $("#cover2, #popLogin, .loading").hide();
                        $.cookie('uin', json.BzUID, { expires: 7, path: '/', domain: 'baozang.com', secure: false });
                    }
                    else {
                        alert(json.err);
                        $("#sign").html(User.topbar.notin);
                    }
                }
            });
        }

    },
    /// <summary>
    /// 退出
    /// </summary>
    SingOut : function (options) {
        $("#sign").html(User.topbar.loading);
        $.ajax({
            url: User.PostDir+"signout.ashx?n=" + Math.random(),
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.responseText);
            },
            success: function(rssTxt) {
                if (rssTxt == "1") {
                    setTimeout(function(){
                        $("#sign").html(User.topbar.notin);
                    },50);
                }
                else {
                    alert("注销失败,请重试");
                }
            }
        });
    },
    
    OnPopLog: function(){
        var pageW = document.body.clientWidth;
        var pageH = document.body.clientHeight;
        var winW = $(window).width();
        var winH = $(window).height();
        var scrlL = $(document).scrollLeft();
        var scrlT = $(document).scrollTop();
        
        $("#cover2").css({
            "width":pageW,
            "height":pageH,
            "opacity": "0.5"
        }).show();
        
        $("#popLogin").css({
            "top":"150px",
            "left":parseInt((winW-$("#popLogin").width())/2)
        }).show();
        
        $(window).bind("resize scroll", function(){
            pageW = document.body.clientWidth;
            pageH = document.body.clientHeight;
            winW = $(window).width();
            winH = $(window).height();
            scrlL = $(document).scrollLeft();
            scrlT = $(document).scrollTop();
            
            $("#cover2").css({
                "width":pageW+scrlL,
                "height":pageH,
                "opacity": "0.5"
            });
            
            if(winH>($("#popLogin").height()+150)){
                $("#popLogin").css({
                    "top":parseInt(scrlT)+150,
                    "left":parseInt((winW-$("#popLogin").width())/2)
                });
            }else if(winH>($("#popLogin").height())){
                $("#popLogin").css({
                    "top":parseInt(scrlT)+(winH-parseInt($("#popLogin").height()))/2,
                    "left":parseInt((winW-$("#popLogin").width())/2)
                });
            }else{
                $("#popLogin").css({
                    "top":parseInt(scrlT),
                    "left":parseInt((winW-$("#popLogin").width())/2)
                });
            }
        });
        
        $(".cls, #cover2").click(function(){
            if(User.ajaxPost){
                User.ajaxPost.abort();
            }
            $("#popLogin").find(".text").val("");
            $("#cover2, #popLogin, .loading").hide();
        });
        
        return false;
        
    },
    checkEnter:function(e){
        var keycode;
        if (window.event) {
            keycode = e.keyCode;
        } else if (e.which) {
            keycode = e.which;
        }
        if(keycode!=13)return;
        $("#submit").trigger("click");
    },
    OnValid: function () {
        var usn = $("#unpop").val().trim();
        var psw = $("#pswpop").val().trim();
        if (usn == "" || psw == "") {
            alert("用户名或密码不能为空!");
            return false;
        }
        return true;
    }
});
