//任意div居中浮动
(function($){ 
    $.fn.center=function(settings){ 
        var style=$.extend({ 
                          position:'absolute',//absolute or fixed 
                          top:'50%',            //50%即居中，将应用负边距计算，溢出不予考虑了。 
                          left:'50%', 
                          zIndex:2009, 
                          relative:true        //相对于包含它的容器居中还是整个页面 
                          }, settings || {}); 
         
        return this.each(function(){ 
                  var $this=$(this); 
                   
                  if(style.top == '50%') style.marginTop=-$this.outerHeight()/2; 
                  if(style.left == '50%') style.marginLeft=-$this.outerWidth()/2; 
                  if(style.relative && !$this.parent().is('body') && $this.parent().css('position') == 'static') 
                      $this.parent().css('position','relative'); 
                  delete style.relative; 
                  //ie6 
                  if(style.position == 'fixed' && $.browser.version=='6.0'){ 
                      style.marginTop += $(window).scrollTop(); 
                      style.position = 'absolute'; 
                      $(window).scroll(function(){ 
                                                    $this.stop().animate({ 
                                                                      marginTop:$(window).scrollTop()-$this.outerHeight()/2 
                                                                      }); 
                                                    }); 
                  } 
                   
                  $this.css(style); 
                  }); 
    };	
	
})(jQuery);

// RSS 订阅
/*$(document).ready(function(){
	$('#RssLoad').bind('mouseover',function(){
			$('#rssFeed').show();
		}
	);
	$('#RssLoad').bind('mouseout', function(){
			$('#rssFeed').hide();
		}
	);
});*/


function rssShow(){
	document.getElementById('rssFeed').style.display = 'inline-block';
}

function rssHide(){
	document.getElementById('rssFeed').style.display = 'none';
}

var a= '';
var js_token='';
/**
 *计算字符串长度的函数
 *
 */
function JHshStrLen(sString)
{
        var sStr,iCount,i,strTemp ;

        iCount = 0 ;
        sStr = sString.split("");
        for (i = 0 ; i < sStr.length ; i ++)
        {
                strTemp = escape(sStr[i]);
                if (strTemp.indexOf("%u",0) == -1)
                {
                        iCount = iCount + 1 ;
                }
                else
                {
                        iCount = iCount + 2 ;
                }
        }

        return iCount ;
}



/**
 * checkbox选择控制
 *
 */
//按照类来选择
function selectAll(class_name) {
        //var checked = $("#selectall").attr("checked");

        $("."+class_name).each(function() {
                var subchecked = $(this).attr("checked");
                if (subchecked != 'checked')
                        $(this).click();
        });
}

function unSelectAll(class_name) {
        //var checked = $("#selectall").attr("checked");

        $("."+class_name).each(function() {
                var subchecked = $(this).attr("checked");
                if (subchecked == 'checked')
                        $(this).click();
        });
}

function getSelectValues() {
        id = [];
        $("input[type='checkbox']:checked").each(function(){
                id.push($(this).val());
        });
        return id.join(',');
}


//最常用的

$(function() {
        //showCss();

        js_token = $('#js_token').val();
        //setInterval( 'cleanName()',5000 );
        $("#checkAll").click(function(){
                if(this.checked){
                        $("input[type='checkbox']").each(function(i){
                                this.checked=true;
                        });
                }else{
                        $("input[type='checkbox']").each(function(i){
                                this.checked=false;
                        });
                }
        });
//shortcuts
    // if is showing infobox then move it to top of page
    $(window).scroll(function(){
        var new_top = $(window).scrollTop();
        $('#user_notice').css('top', new_top+'px');
    });

});
function cleanName(){
        a = '';
}

function checkLogin(){
        delCookie('log_refer');
        if(0 == MID){
                var url = location.href;
                setCookie('log_refer',url,'1000000' );
                window.location.href = APP+'/Index/login';
        }
}


function escapeHTML(s) {
        return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
};


function ReplaceAll(str, sptr, sptr1)
{
        while (str.indexOf(sptr) >= 0)
        {
                str = str.replace(sptr, sptr1);
        }
        return str;
}


function handlerIframe(){
        // alert(ymPrompt.getPage().contentWindow.document.body.innerHTML);
        ymPrompt.close();
}




var keyStr = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789+/" +
"=";

function encode64(input)
{
        input = escape(input);
        var output = "";
        var chr1, chr2, chr3 = "";
        var enc1, enc2, enc3, enc4 = "";
        var i = 0;

        do
        {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);

                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;

                if (isNaN(chr2))
                {
                        enc3 = enc4 = 64;
                }
                else if (isNaN(chr3))
                {
                        enc4 = 64;
                }

                output = output +
                keyStr.charAt(enc1) +
                keyStr.charAt(enc2) +
                keyStr.charAt(enc3) +
                keyStr.charAt(enc4);
                chr1 = chr2 = chr3 = "";
                enc1 = enc2 = enc3 = enc4 = "";
        } while (i < input.length);

        return output;
}

function decode64(input)
{
        var output = "";
        var chr1, chr2, chr3 = "";
        var enc1, enc2, enc3, enc4 = "";
        var i = 0;

        // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
        var base64test = /[^A-Za-z0-9\+\/\=]/g;
        if (base64test.exec(input))
        {
                alert("There were invalid base64 characters in the input text.\n" +
                        "Valid base64 characters are A-Z, a-z, 0-9, '+', '/', and '='\n" +
                        "Expect errors in decoding.");
        }
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        do
        {
                enc1 = keyStr.indexOf(input.charAt(i++));
                enc2 = keyStr.indexOf(input.charAt(i++));
                enc3 = keyStr.indexOf(input.charAt(i++));
                enc4 = keyStr.indexOf(input.charAt(i++));

                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;

                output = output + String.fromCharCode(chr1);

                if (enc3 != 64)
                {
                        output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64)
                {
                        output = output + String.fromCharCode(chr3);
                }

                chr1 = chr2 = chr3 = "";
                enc1 = enc2 = enc3 = enc4 = "";
        } while (i < input.length);
        return unescape(output);
}
function setCookie(name,value,exp) {
        var LargeExpDate = new Date ();
        expires = exp?exp:1000000;
        LargeExpDate.setTime(LargeExpDate.getTime() + (3600*1000*24*30));
        path = '/';
        document.cookie = name + "="+ escape (value) + ";expires=" + LargeExpDate.toGMTString()+path;
}

function getCookie(name) {
        var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
        if(arr != null) return unescape(arr[2]);return null;
}

function delCookie(name){
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval=getCookie(name);
        path = '/';
        if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString()+path;
}
/**
 *      显示名片
 */
function showTips() {
        if(TPIS =='1'){
        $('a.tips').cluetip({
                width: 350,
                cluetipClass: 'jtip',
                showTitle: false,
                clickThrough:true,
                arrows: false,
                dropShadow: false,
                hoverIntent: false,
                tracking: false,
                sticky: true,
                mouseOutClose: true,
                leftOffset:6,
                topOffset:5,
                cluezIndex:30,
                closePosition: 'title'
        });
        }
}
function getMsgCount(){
        var num = 0;
        var href = '';
        $.getJSON(TS+'/Index/getMsgCount/uid/'+'&jsoncallback=?', function(result){
            $.each(result, function(key, value){
                if(value){
                    //value = parseInt(value);
                    if(value != 0 && key){
                        num = num + value;
                        //$('#'+key+MID).html('('+value+'条'+')');
                        switch(key){
                        /*
                            case 'friend':
                                href = TS+'/Notify/index/t/fri';
                            break;
                            case 'notification':
                                href = TS+'/Notify/index';
                                $("#lbInfoLaftNavNotify").html("New!");
                            break;
                            case 'wall':
                                href = TS+'/Space/#wall';
                            break;
                            case 'message':
                                href = TS+'/Notify/inbox';
                                $("#lbInfoLaftNavMsg").html("New!");
                            break;
                            default:
                                href = TS+'/Notify/index/t/sys/';
                            break;
                            */
                            case 'notification':
                                $("#lbInfoLaftNavNotify").html("New!");
                            break;
                            case 'message':
                                $("#lbInfoLaftNavMsg").html("New!");
                            break;
                        }
                        href = TS+'/Notify/newMsg';
                    }
                }
            });
            if(num == 0){
                $('#msg_top').remove();
                $('#newMsg').empty();
                // 在短消息中隐藏新消息栏目
                if ($("#tagNotifyNewMsg").length>0) {
                    $("#tagNotifyNewMsg").hide();
                }
                if ($("#tagNotifyNewMsg2").length>0) {
                    $("#tagNotifyNewMsg2").hide();
                }
            }else{
                $('#msg_top_href').attr('href',href).text("短消息" + num);
                $('#msg_top').css('display','inline-block');
                $('#newMsg').append("New!");
                // 在短消息中显示新消息栏目
                if ($("#tagNotifyNewMsg").length>0) {
                    $("#tagNotifyNewMsg").show();
                }
                if ($("#tagNotifyNewMsg2").length>0) {
                    $("#tagNotifyNewMsg2").show();
                }
            }
        });
}
function showCss(){
//$(document).not('input').bind('keydown', 'ctrl+shift+c',function (evt){	loadScript('http://westciv.com/xray/thexray.js'); return false; });
//showKey();
}

function showKey(){
        $(document+':not(input)').bind('keydown', 'right',function (evt){
                nextPage();return true;
        });
        $(document+':not(input)').bind('keydown', 'left',function (evt){
                prePage();return true;
        });
}
function nextPage(){
        var page = $('#Pagination').html();
        if(page){
                location.href = $('#Pagination').children('a:last').attr('href');
        }
}
function prePage(){
        var page = $('#Pagination').html();
        if(page){
                location.href = $('#Pagination').children('a:first').attr('href');
        }
}
function loadScript(scriptURL){
        var scriptElem = document.createElement('SCRIPT');
        scriptElem.setAttribute('language', 'JavaScript');
        scriptElem.setAttribute('src', scriptURL);
        document.body.appendChild(scriptElem);
}
function alertAuthor(){
        var re = /[^\d]/g;   //判断字符串是否为数字     //判断正整数 /^[1-9]+[0-9]*]*$/
        var mid = a;
        var test = re.test(mid);
        if(!test){
                a ='';
                location.href = TS+'/space/'+mid;
        }
        switch(a){
                case 'sam':
                        alert('Sam');
                        break;
                case 'nonant':
                        alert('冷浩然');
                        break;
                case 'sst':
                        alert('水上铁');
                        break;
                case 'haixia':
                        alert('海虾');
                        break;
                case 'shoutaimu':
                        alert('兽汰姆');
                        break;
                default:
                        a = '';
        }
        a = '';

}
function gotoHome(){
        if(MID!=0) location.href = TS+'/Home/index';
}
function gotoMySpace(){
        if(MID!=0) location.href = TS+'/space/'+MID;
}

function checkJsToken(txt) {
        if(txt == 'error'){
                Alert('请不要频繁提交');
                $( '.btn_big').removeAttr('disabled');
                return false;
        }
        if(txt == 'fail'){
                Alert('说得太快了。休息会吧');
                $( '.btn_big').removeAttr('disabled');
                return false;
        }
        return true
}

function displayNotice(info) {
    if (info) {
        var viewHeight = $(window).height();
        var scrollHeight = $(document).scrollTop();
        var top = scrollHeight;
        $('#user_notice').css("top", top + "px");
        $('#user_notice').css("left", "0px");
        $('#user_notice').html(info).fadeIn(500);
        setInterval('hideNotice()', 5000);
    }
}

function hideNotice() {
    $('#user_notice').fadeOut(500);
}

//全局分享
function ts_sharePop(id,url,type){
	var classId = '#BtnShare_'+id;
	//$(classId).attr('disabled','true');
	
	$.post(url+"/addShare_check/", {aimId:id}, function(txt){
			if(txt==1){
					ymPrompt.win(url+'/addShare/aimId/'+id+'/type/'+type,500,'315','分享',null,null,null,{id:'a'});
			}else if(txt==-1){
					ymPrompt.errorInfo('请不要分享自己发布的东西!');
			}else if(txt==-2){
					ymPrompt.errorInfo('您已经分享过,请不要重复分享!');
			}else if(txt==-3){
					ymPrompt.errorInfo('您没有权限分享!');
			}else{
					ymPrompt.errorInfo('参数出错,请重试!');
			}
			
			//$(classId).attr('disabled','');
	});
}

//打入黑名单
function moveToBlock(navName, id, username) {
    $.post("/index.php?s=Favorite/addBlock", {uid:id,name:username}, function(txt){
        if (txt=="1") {
            $('#'+navName).html("<b><a href=\"#\" onclick=\"return moveBackFromBlock('" + navName + "'," + id + ",'" + username + "');\"><span>拉出黑名单</span></a></b>");
            displayNotice("<p><a href=\"/index.php?s=/space/" + id + "\">"+ username + "</a>已被您打入黑名单!</p>");
        } else {
            displayNotice("<p>抱歉，打入此用户至黑名单时出错，暂时未能完成，请稍后再式。</p>");
        }
    });
    return false;
}
//拉出黑名单
function moveBackFromBlock(navName, id, username) {
    $.post("/index.php?s=Favorite/delBlock", {uid:id}, function(txt){
        if (txt=="1") {
            $('#'+navName).html("<a href=\"#\" onclick=\"return moveToBlock('" + navName + "'," + id + ",'" + username + "');\"><span>打入黑名单</span></a>");
            displayNotice("<p><a href=\"/index.php?s=/space/" + id + "\">"+ username + "</a>已被您拉出黑名单!</p>");
        } else {
            displayNotice("<p>抱歉，拉出此用户至黑名单时出错，暂时未能完成，请稍后再式。</p>");
        }
    });
    return false;
}

function postWink(navName, id, username) {
    if (id) {
        $.post("/apps/poster/index.php?s=/Index/create", {
            uid:id,
            key:'sdf3Sfs&@df3oqK8BeW',
            isWink:1
        }, function(txt){
            if (txt=="1") {
                $('#'+navName).fadeOut(300);
                displayNotice("<p>抛向"+ username + "的飞吻已送达!</p>");
            } else {
                displayNotice("<p>抱歉，可能网络问题，暂时未能发送成功，请稍后再式。</p>");
            }
        });
    }
    return false;
}

function sendMesg(stateId,uid,chenHu) {
    if (stateId == 1 || stateId == 3) {
        location = "/index.php?s=/Notify/write/uid/" + uid;
    } else {
        displayNotice("<p>抱歉, 你们双方需谈定价格后才能联系，先向" + chenHu + "开个价吧！</p>");
    }
    return false;
}

function addFav(navName, id, username) {
    if (id) {
        $.post("/index.php?s=Favorite/addFav", {
            uid:id,
            key:'sdf3Sfs&@dft3oqK8BeW',
            isAjax:1
        }, function(txt){
            if (txt=="1") {
                $('#'+navName).html("<a href=\"#\" onclick=\"return delFromFav('"+ navName + "'," + id + ",'" + username + "');\"><span>移出搜藏夹</span></a>");
                displayNotice("<p>已将<a href=\"/index.php?s=/space/" + id + "\">"+ username + "</a>添加到了您的搜藏夹.</p>");
            } else {
                displayNotice("<p>抱歉，可能网络问题，暂时未能添加成功，请稍后再式。</p>");
            }
        });
    }
    return false;
}

function delFromFav(navName, id, username) {
    if (id) {
        $.post("/index.php?s=Favorite/delFav", {
            uid:id,
            key:'sdf3Sfs&@dft3oqK8BeW',
            isAjax:1
        }, function(txt){
            if (txt=="1") {
                $('#'+navName).html("<a href=\"#\" onclick=\"return addFav('"+ navName + "'," + id + ",'" + username + "');\"><span>加入搜藏夹</span></a>");
                displayNotice("<p>已将<a href=\"/index.php?s=/space/" + id + "\">"+ username + "</a>从您的搜藏夹中移出.</p>");
            } else {
                displayNotice("<p>抱歉，可能网络问题，暂时未能添加成功，请稍后再式。</p>");
            }
        });
    }
    return false;
}

function ChkMail(o){
    var regm = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    if (!o.match(regm) && o!="")
    {
        return true;
    }
    return false;
}

function closeDialog() {
    $('#pagemasker').hide();
    $('#dialog').hide();
}

function showDialog() {
    $.colorbox({
        title:'&nbsp;',
        href:'/Payment/paymentDialog',
        width: 580,
        height: 300,
        overlayClose:false
    });
}

function checkVerify(url, objo, tx, checkObj) {
    $.post(url, {
        isAjax:1
    }, function(res){
        if (res == 'NO') {
            $('#'+objo).html(tx);
            $('#'+checkObj).val(0);
        } else if (res == 'OK') {
            $('#'+objo).html('');
            $('#'+checkObj).val(1);
        }
    });
}

function quote(target) {
    //alert($("#" + target).html());
    $('iframe').contents().find('.ke-content').text("[quote]" + $("#" + target).text() + "[/quote]");
}

function displayMsg(msg) {
    $("#msg").html(msg);
    $("#msg").show();
    setTimeout('$("#msg").hide()', 5000);
}

// 验证手机格式
function validateMobile(mobile) {
    if(mobile.length==0)
    {
       $("#sendTip").html("<p>请输入手机号码！</p>");
       return false;
    }    
    if(mobile.length!=11)
    {
        $("#sendTip").html("<p>请输入有效的手机号码！</p>");
        return false;
    }
    
    var myreg = /^((13|14|15|18)+\d{9})$/;
    if(!myreg.test(mobile))
    {
        $("#sendTip").html("<p>请输入有效的手机号码！</p>");
        return false;
    }
    return true;
}

// 验证邮件格式
function validateEmail(email) {
    var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    if (!reg.test(email)) {
        return false;
    } else {
        return true;
    }
}

function changeSecurityCode(obj, url) {
    $(obj).attr("src",url);
}

function checkSecurityCode(inputName, divName, url, async) {
    var securityCode = $("#" + inputName).val();
    var flag = true;
    if (!async) async = false;
    if (securityCode) {
        $.ajax({
            type: "POST",
            dataType: "json",
            async: async,
            url: url,
            data: "",
            success: function(msg) {
                if (msg && msg.info) {
                    $("#" + divName).html(msg.info);
                    $("#" + divName).show();
                    flag = false;
                } else {
                    $("#" + divName).hide();
                    $("#"+ divName).html("验证码不能为空");
                }
            }
        });
    } else {
        $("#"+ divName).html("验证码不能为空");
        $("#" + divName).show();
        flag = false;
    }
    return flag
 }

 function checkCodeForEject(inputName,url) {
    var securityCode = $("#" + inputName).val();
    var flag = false;
    if (securityCode) {
        $.ajax({
            type: "POST",
            dataType: "json",
            async: false,
            url: url,
            data: {yzm:securityCode},
            success: function(msg) {
                if (msg.err) flag = true;
            }
        });
    }
    return flag
 }
//用户登录账号验证
function getFocus(obj) {
    var txt = $(obj).val();
    txt = $.trim(txt);
    if(txt == "" || txt == "用户名或邮箱") $(obj).val("");
}
function loseFocus(obj) {
    var inputid = $(obj).attr("id");
    $("#" + inputid + "_div").hide();
    var txt = $(obj).val();
    txt = $.trim(txt);
    if(!txt || txt =='用户名或邮箱') {
        $("#" + inputid + "_div").show();
        $(obj).val("用户名或邮箱");
        return false;
    }
    return true;
}
//检测的input后面跟一个input id 加_div的元素，就可以实现隐藏显示这个元素
function checkInput(obj) {
    var inputid = $(obj).attr("id");
    var value = $("#" + inputid).val();
    if (!value){
        $("#" + inputid + "_div").show();
        return false;
    } else {
        $("#" + inputid + "_div").hide();
        return true;
    }
}
//返回上一步
function goToPrev(){
    if( document.referrer )
       window.location = document.referrer;
    else	 
       window.history.back(-1);
}

function ReImgSize(imgBox, width) {
    try {
        var imgall = $("#" + imgBox + " img");
        var reWidth = width;
        for (i = 0;i < imgall.length; i++) {
            if (imgall[i].width > reWidth) {                //如果图片的宽度大于规定宽度
                var oWidth = imgall[i].width;               //取得图片的实际宽度
                var oHeight = imgall[i].height;             //取得图片的实际高度
                imgall[i].width = reWidth;                  //重设图片的宽度为300
                imgall[i].height = oHeight*reWidth/oWidth;  //重设图片的高度
            }
        }
    } catch(e) {
        alert("异常发生:" + e);
    }
}
//头部用户状态加载
function topLoginState(){
  var spaceUrl = ROOT.replace("www","home");
       $.getJSON(TS+'/Index/getLoginState/&jsoncallback=?', function(result){
        if(result.myid){
            $("#topLogin").html('您好<a style="font-family: Microsoft 微软雅黑! importan;font-weight: bold" href="'+spaceUrl+'/space/">'+result.myname+'</a>，欢迎来到 <a href="'+ROOT+'">全球设计网</a>，<a href="'+ROOT+'/Index/logout">退出</a>');
            MID = result.myid;
            getMsgCount();
        }
     }); 
}
//首页用户登录状态显示，qq绑定
function indexLoginState(flag){
    if(!arguments[0]) flag=0;
     var spaceUrl = ROOT.replace("www","home");
     var userUrl  = ROOT.replace("www","user");
     $.getJSON(TS+'/Index/getLoginState/&jsoncallback=?', function(result){
        if(result.myid){
            if(!flag) {
                $("#topLogin").html('您好<a style="font-family: Microsoft 微软雅黑! importan;font-weight: bold" href="'+spaceUrl+'/space/">'+result.myname+'</a>，欢迎来到 <a href="'+ROOT+'">全球设计网</a>，<a href="'+ROOT+'/Index/logout">退出</a>');
            }else {
                $("#topLogin").html('您好<a style="font-family: Microsoft 微软雅黑! importan;font-weight: bold" href="'+spaceUrl+'/space/">'+result.myname+'</a>，欢迎来到 <a href="'+ROOT+'"><h1>全球设计网</h1></a>，<a href="'+ROOT+'/Index/logout">退出</a>');
            }
            $("#ctLoginState").addClass("indexLogined");
            $("#ctLoginState").html('<a title="'+result.myname+'" class="ellipsis" href="'+spaceUrl+'/space/">'+result.myname+'</a>您好，进入<a href="'+userUrl+'">会员中心</a>或<a href="'+ROOT+'/Index/logout">退出</a>');
            MID = result.myid;
            getMsgCount();
       }else{
          noBind = result.nonBindQQ;
          uName = result.myname;
          bindQQ(result.nonBindQQ,result.myname,dlg);
        }
     }); 
}
