global.js 33.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
if (typeof QGlobal == undefined || !QGlobal) {
    var QGlobal = {};
}
QGlobal.Common = {
    // 域
    QSITE_DOMAIN : '.yohobuy.com',
    
    CropTypes : {'thumbnail':1, 'paste':2, 'crop':3,'resize':4,'autoCrop':5},
		
    /**
	 * 获取验证码
	 */
    clickImgCode : function( nspace ,imgCodeId) {
        var dt = new Date();
        var group = '';
        if(nspace){
        	group = "&g="+nspace;
        }
        var imgcode = 'imgcode';
        if(imgCodeId){
        	imgcode = imgCodeId;
        }
        var src = "http://www.yohobuy.com/passport/images?t=" + dt.getTime() + group;
        $('#'+imgcode).attr('src', src);
        return false;
    },

    /**
	 * 获取图片地址
	 * QGetImages('/2010/08/19/23/014425e77c83612e86c6d76d453ccc5b97.jpg','50x50','album');
	 * QGetImages('/2010/08/19/23/014425e77c83612e86c6d76d453ccc5b97.jpg','source','album');
	 */
    QGetImages : function(imageUrl, type, project) {
        if (!imageUrl || !type) {
            return '';
        }
        var imgArr = imageUrl.split("/");
        if (imgArr.length < 5) {
            return '';
        }
        var newImages = 'http://img' + imgArr[imgArr.length - 1].substr(0, 2)
        + ".static" + this.QSITE_DOMAIN + "/";
        if (type == 'source') {
            newImages += project + imageUrl;
        } else {
            var typeArr = type.split("x");
            if (typeArr[0].length > 3 || typeArr[1].length > 3) {
                return '';
            }
            var newType = sprintf("%04d",typeArr[0]) + sprintf("%04d",typeArr[1]);
            try {
                var fileArr = imgArr[imgArr.length - 1].split('.');
                var newFile = fileArr[0] + newType + "." + fileArr[1];
                imgArr.splice(imgArr.length - 1, 1);
                newImages += "thumb" + imgArr.join("/") + "/" + newFile;
            } catch (err) {
                newImages = "";
            }
        }
        return newImages;
    },
    //  http://img04.static.yohobuy.com/thumb/2012/03/21/18/013ed6165a76585d4c95517486d7b35385-0180x0240-2-goodsimg.jpg
    //  QFSFImages('/2012/03/21/18/013ed6165a76585d4c95517486d7b35385.jpg','goodsimg','180x240',2);
    QFSFImages:function(imagesUrl, project, thumbSize, mode) {
        if ( !imagesUrl || !thumbSize || !project ) { return ''; }
        if(thumbSize == 'source')
        {
        	return this.QGetImages(imagesUrl, thumbSize, project);
        }
        var imageSplit = imagesUrl.split("/");
        var domain = QGlobal.Common.fRandomBy(3,4);
        var thumb = 'http://img0' + domain + ".static.yohobuy.com/";
        var thumbBox = thumbSize.split("x");
        if (thumbBox[0].length > 4 || thumbBox[1].length > 4) { return ''; }
        var newFileFormat = sprintf("%04d",thumbBox[0]) + 'x' + sprintf("%04d",thumbBox[1]);
        try {
            var fileBox = imageSplit[imageSplit.length - 1].split('.');
            var newFile = fileBox[0] + '-' + newFileFormat + '-' + mode + '-' + project + "." + fileBox[1];
            imageSplit.splice(imageSplit.length - 1, 1);
            thumb += "thumb" + imageSplit.join("/") + "/" + newFile;
        } catch (err) { thumb = ""; }
        return thumb;
    },
    fRandomBy:function(under, over){
        switch(arguments.length){
            case 1: return parseInt(Math.random()*under+1);
            case 2: return parseInt(Math.random()*(over-under+1) + under);
            default: return 0;
        }
    },
    /**
	 * 获取图片地址
	 * QGetImages('/2010/08/19/23/014425e77c83612e86c6d76d453ccc5b97.jpg','50x50','album');
	 * QGetImages('/2010/08/19/23/014425e77c83612e86c6d76d453ccc5b97.jpg','source','album');
	 */
    QGetImagesMongo : function(imageUrl, type, project, croptype) {
    	if (typeof(croptype) == 'undefined'){
    		croptype = 'thumbnail';
    	}
        if (!imageUrl || !type) {
            return '';
        }
        var imgArr = imageUrl.split("/");
        if (imgArr.length < 5) {
            return '';
        }
        if (type == 'source') {
            var newImages = 'http://img' + imgArr[imgArr.length - 1].substr(0, 2) + ".static.yoho.cn/";
            newImages += project + imageUrl;
        } else {
            var newImages = 'http://img0' + (parseInt(imgArr[imgArr.length - 1].substr(1, 1), 10) + 2) + ".static.yoho.cn/";
            var typeArr = type.split("x");
            if (typeArr[0].length > 4 || typeArr[1].length > 4) {
                return '';
            }
            var newType = sprintf("%04d",typeArr[0]) + 'x' + sprintf("%04d",typeArr[1]);       
            try {
                var fileArr = imgArr[imgArr.length - 1].split('.');
                var newFile = fileArr[0] + '-' + newType + '-' + QGlobal.Common.CropTypes[croptype] + "." + fileArr[1];
                imgArr.splice(imgArr.length - 1, 1);
                newImages += project + imgArr.join("-") + "-" + newFile;
            } catch (err) {
                newImages = "";
            }
        }
        return newImages;
    }
};

QGlobal.Passport = {
    // 登录验证
    QIS_LOGIN : false,
    // 域
    QSITE_DOMAIN : '.yohobuy.com',
    /**
	 * 验证用户是否登录
	 */
    QCheckUserStatus : function() {
        var _UID = $.cookie('_UID');
        if (typeof (_UID) == 'undefined' || _UID == null) {
            return 0;
        }
        var userInfo = _UID.split('::');
        if(typeof userInfo == 'undefined' || userInfo.length < 4)
    	{
        	return 0;
    	}
        return userInfo[1];
    }
};
QGlobal.Check = {
	//收藏检测时间arvar
	QFavorite_time : 1800,
	//系统消息检测时间
	QMessage_time : 600,
	
	QSITE_DOMAIN : 'yohobuy.com',
	
	HideTips : function(){
		$.cookie('hideTips', 1, {expires: 90, path: '/', domain: this.QSITE_DOMAIN});
		$('#new_tip_div').hide();
	},
	QCheck : function(){
		if(!QGlobal.Passport.QCheckUserStatus())
		{
			return false;
		}
		//获得收藏cookie
		var _FTime = $.cookie('_FTime');

		//获得系统消息cookie
		var _MTime = $.cookie('_MTime');

		//标识
		var type = 0;
		
		//验证收藏cookie
		if(typeof (_FTime) == 'undefined' || _FTime == null)
		{
			type = parseInt(type) + 1;
		}
		//验证系统消息cookie
		if(typeof (_MTime) == 'undefined' || _MTime == null)
		{
			type = parseInt(type) + 2;
		}
		if(type > 0)
		{
			this.QSendCheckStatus(type);
		}
	},
	QSendCheckStatus : function(_type)
	{
		$.get('/center',{'type':_type,'time':Math.random()}, function(){
			
		});
	},
	QGetLoginInfo : function (_type)
	{
		var _UID = $.cookie('_UID');
        if (typeof (_UID) == 'undefined' || _UID == null) {
        	this.QShow(_type);
            return false;
        }
        var userInfo = _UID.split('::');
        if(typeof userInfo == 'undefined' || userInfo.length < 4)
    	{  
        	this.QShow(_type);
        	return false;
    	}
        $.get('/message?user_id='+userInfo[1], function (html){
        	var _logout = '';
        	if(/http:\/\//.test(user[3])){
        		_logout = user[3];
        	}else{
        		_logout = 'http://www.yohobuy.com/logout_' + user[3] + '.html';
        	}
        	var _str = '<dd>您好,<a href="http://www.yohobuy.com/home?t='+Math.random()+'" class="a_rz">'+userInfo[0]+'</a> [ '+userInfo[2]+' ] <a href="'+_logout+'" class="a_g">退出</a></dd>';
            if(_type == 1){
            	_str += '<dd><a href="http://www.yohobuy.com/home/orders?t='+Math.random()+'">我的订单</a></dd>';
                _str += '<dt>';
    	        _str += '<div id="myyoho">';
    	        _str += '<ol><a href="http://www.yohobuy.com/home?t='+Math.random()+'">个人中心</a></ol>';
    	        _str += '<ul>';
    	        _str += '<li><a href="http://www.yohobuy.com/home/favorite?t='+Math.random()+'">我的收藏</a></li>';
    	        _str += '<li><a href="http://www.yohobuy.com/home/exhibit?t='+Math.random()+'">潮拍晒物</a></li>';
    	        _str += '<li><a href="http://www.yohobuy.com/home/coupons?t='+Math.random()+'">优惠券</a></li>';
    	        _str += '</ul>';
    	        _str += '</div>';
    	        _str += '</dt>';
    	        _str += html;
    	        _str += '<dd><a href="http://www.yohobuy.com/help">帮助中心</a></dd>';
            }
            $('#loginInfoBox').html(_str);
            $("#mymsg").hover(function(){
            	$(this).addClass("mymsg_a");
            	$(this).find("ul").css('display', 'block');
            },function(){
            	$(this).removeClass("mymsg_a");
            	$(this).find("ul").css('display', 'none');
            });
	        $('#mymsgclose').click(function() {
	            $("#mymsg").removeClass("mymsg_a");
	            $('#mymsg ul').css('display', 'none');
            });
            return true;
		});
        this.QShow(_type);
        return true;
	},
	QShow : function(_type)
	{
		var html = '<div id="noLoginBox" style="display:inline;">';
		if(_type == 3){
			html += '<dd><a href="javascript:void(0);" onclick="QINRegister.showLoginBox();">登录</a></dd><dd><a href="javascript:void(0);" onclick="QINRegister.showLoginBox(\'register\');">注册</a></dd>';
		}else{
			html += '<dd><a href="http://www.yohobuy.com/signin.html">登录</a></dd><dd><a href="http://www.yohobuy.com/reg.html">注册</a></dd></div>';
		}
		html +='<dd><a href="http://www.yohobuy.com/help">帮助中心</a></dd>';
		 $('#loginInfoBox').html(html);
	},
	QGetLogin : function (_type)
	{
		var _UID = $.cookie('_UID');
        if (typeof (_UID) == 'undefined' || _UID == null) {
            return false;
        }
        var userInfo = _UID.split('::');
        if(typeof userInfo == 'undefined' || userInfo.length < 4)
    	{  
        	return false;
    	}
        $.get('/message?user_id='+userInfo[1], function (html){
        	
            $('#mymsg').html(html);
            $("#mymsg").hover(function(){
            	$(this).addClass("mymsg_a");
            	$(this).find("ul").css('display', 'block');
            },function(){
            	$(this).removeClass("mymsg_a");
            	$(this).find("ul").css('display', 'none');
            });
	        $('#mymsgclose').click(function() {
	            $("#mymsg").removeClass("mymsg_a");
	            $('#mymsg ul').css('display', 'none');
            });
            return true;
		});
        return true;
	},
	checkGender : function()
	{
		var gender = $.cookie('gender');
		if (ender == 'undefined' || gender == '')
		{
			return false;
		}
		var genderArr = gender.split('::');
		if(genderArr.length < 2 || genderArr[1] == 1)
		{
			return false;
		}
		return true;
	}
};

QGlobal.Address = {
		
    provinceDomId : 'province',  //省的控件ID
    cityDomId:'city',  //城市的控件ID
    areaDomId:'area_code',  //地区的控件ID
		
    initDomIds : function(domOptions){
        if(domOptions['provinceDomId'] != undefined){
            this.provinceDomId = domOptions['provinceDomId'];
        }
        if(domOptions['cityDomId'] != undefined){
            this.cityDomId = domOptions['cityDomId'];
        }
        if(domOptions['areaDomId'] != undefined){
            this.areaDomId = domOptions['areaDomId'];
        }
    },	
		
    //初始化地址数据
    loadAreaData : function(pCode, toDomId, defaultValue, allCode) {
        var toDom = $('#' + toDomId);
        toDom.empty();
        if (pCode < 91) {
            $("#area_code").empty();
            $("#county").attr('disabled', 'disabled');
        }
        jQuery.ajax({
            type : "GET",
            url : "/area",
            data : 'id=' + pCode,
            success : function(jsonData) {
                if (jsonData.code != 200) {
                    alert('暂无数据');
                    return false;
                }
                toDom.append("<option value='0'>" + defaultValue
                    + "</option>");
                for ( var i in jsonData.data) {
                    var val = jsonData.data[i];
                    var selecter = '';
                    nId = val.id;
                    if (typeof (allCode) != 'undefined' && allCode != 0
                        && nId == allCode.substr(0, nId.length)) {
                        selecter = 'selected';
                    }
                    toDom.append("<option value='" + nId + "' "
                        + selecter + ">" + val.caption
                        + "</option>");
                }
            }
        });
    },
    bindAreaChange : function(domOptions) {
    	
    	if($('#' + this.provinceDomId).data("events") != undefined){return;}
        //初始化
        //this.loadAllData(0,{});
        $('#' + this.provinceDomId).change(function() {
            var pCode = $('#' + QGlobal.Address.provinceDomId).val();
            if(pCode == 0) {
            	return;
            }
            QGlobal.Address.loadAreaData(pCode, QGlobal.Address.cityDomId, '请选择城市', pCode);
            $('#' + QGlobal.Address.areaDomId).hide();
            QGlobal.Address.showAreaSel(domOptions["dispDomId"]);
        });
        $('#' + this.cityDomId).change(function() {
            var pCode = $('#' + QGlobal.Address.cityDomId).val();
            if(pCode == 0) {
            	return;
            }
            QGlobal.Address.loadAreaData(pCode, QGlobal.Address.areaDomId, '请选择区县', pCode);
            $('#' + QGlobal.Address.areaDomId).show();
            QGlobal.Address.showAreaSel(domOptions["dispDomId"]);
        });
        $('#' + this.areaDomId).change(function(){
        	QGlobal.Address.showAreaSel(domOptions["dispDomId"]);
        });
        QGlobal.Address.showAreaSel(domOptions["dispDomId"]);
    },
    
    /**
     * 显示地区选择
     */
    showAreaSel:function(dispDomId){
    	if(dispDomId != undefined && dispDomId!=""){
    		var strAddr = "";
    		var strProvince = $("#" + this.provinceDomId).find("option:selected").text();
    		if(strProvince.indexOf('选择')<0){
    			strAddr = strProvince;
    		}    		
    		var strCity = $('#' + this.cityDomId).find("option:selected").text();
    		if(strCity != '' && strCity.indexOf('选择')<0)
    		{
    			strAddr += ',' + strCity;
    		}
    		var strArea = $('#' + this.areaDomId).find("option:selected").text();
    		if(strArea != '' && strArea.indexOf('选择')<0)    			
    		{
    			strAddr += ',' + strArea;
    		}
    		$('#' + dispDomId).html(strAddr);
    	}
    },
    
    loadAllData : function(areaCode, domOptions){
        this.initDomIds(domOptions);
        
        areaCode += '';  //把数字型转换为字符型
        if(areaCode<91)
        {
            this.loadAreaData(0, this.provinceDomId, '请选择省份', '');
            $('#' + this.areaDomId).hide();
				
        }
        else if(areaCode.length == 4)
        {
            this.loadAreaData(0, this.provinceDomId, '请选择省份', areaCode);
            this.loadAreaData(areaCode.substr(0,2), this.cityDomId, '请选择城市', areaCode);
            this.loadAreaData(areaCode, this.areaDomId, '请选择区县', areaCode);
            $('#' + this.areaDomId).show();
				
        }else if(areaCode.length == 6){
            this.loadAreaData(0, this.provinceDomId, '请选择省份', areaCode);
            this.loadAreaData(areaCode.substr(0,2), this.cityDomId, '请选择城市', areaCode);
            this.loadAreaData(areaCode.substr(0,4), this.areaDomId, '请选择区县', areaCode);
            $('#' + this.areaDomId).show();	
        }
		this.bindAreaChange(domOptions);
    }
		
};

QGlobal.Page = {
    QSend_Url : '',
    QCallBack : '',
    QItem : 'itemList',
    /**
	 * Ajax获取分页内容
	 * 
	 * @param page
	 * @param obj
	 * @return
	 */
    getList : function(page, obj) {
        var sendUrl = this.QSend_Url;
        var itemName = this.QItem;
        var callback = this.QCallBack;
        if (sendUrl == '') {
            alert('请求的URL不正确');
            return false;
        }
        $.ajax({
            type : "GET",
            url : sendUrl,
            data : page,
            dataType : 'html',
            success : function(html) {
                if (html != '') {
                    $("#" + itemName).html(html);
                    jQuery('#' + itemName).animate({
                        opacity : "show"
                    }, "slow");
                    if (callback != '') {
                        callback();
                    }
                    return true;
                } else {
                    return false;
                }
            }
        });
    }
};

/*
 * 与界面相关的公用函数
 */
QGlobal.UI = {

    /**
	 * 气泡弹出提示,带倒计时,带关闭按钮,但是需要添加bubblepopup引用 domId:html dom 标签的ID,
	 * tipText:要显示的内容 hasCountDown:是否有倒计时功能,如果是1,则有倒计时功能,0则没有倒计时功能
	 */
    popupTip : function(domId, tipText, hasCountDown, seconds_to_wait) {

        var domObj = $('#' + domId);
		
        domObj.RemoveBubblePopup();   //清除该控件上原有的提示
		
        domObj.CreateBubblePopup({
            tail : {
                hidden : true
            }
        });

        var bubble_popup_id = domObj.GetBubblePopupID(); // 获取弹出层的ID

        var showHtml = '<p>' + tipText + '</p>';
        if (hasCountDown == 1) {
            showHtml = showHtml + '<p>剩余<span class="countdown">'
            + seconds_to_wait + '</span>秒</p>';
        }
        showHtml += '<p><a href="#null">[&nbsp;关闭&nbsp;]</a></p>';

        domObj.ShowBubblePopup({

            align : 'center',
            innerHtml : showHtml,

            innerHtmlStyle : {
                color : '#c68436',
                'text-align' : 'center'
            },

            themeName : 'yellow',
            themePath : 'http://static.yohobuy.com/js/jquery-bubblepopup/theme'

        }, false);

        domObj.FreezeBubblePopup();

        $('#' + bubble_popup_id + ' a:last').click(function() {
            domObj.HideBubblePopup();
        });

        function doCountdown() {
            var timer = setTimeout(function() {
                seconds_to_wait--;
                if ($('#' + bubble_popup_id + ' span.countdown').length > 0) {
                    $('#' + bubble_popup_id + ' span.countdown').html(
                        seconds_to_wait);
                }
                ;
                if (seconds_to_wait > 0) {
                    doCountdown();
                } else {
                    domObj.HideBubblePopup();
                }
            ;
            }, 1000);
        }
        if (hasCountDown == 1) {
            doCountdown();
        }
    },
    alertWindow: function(message, options)
    {
    	if(message == '' || typeof message == 'undefined')
    	{
    		return false;
    	}
    	
    	var message_id = options.messageId || 'alertMessageBox';
    	var box_id = options.boxId || 'alertDialog';
    	var boxWidth = options.boxWidth || 300;
    	var boxHeight = options.boxHeight || 130;
    	var modal = options.modal || false;
    	var code = options.code || '';
    	
    	$('#' + box_id).dialog({
			autoOpen: false,
			width:boxWidth,
	        height:boxHeight,
			modal: modal,
			resizable: false
		});
    	
    	if(code != '')
    	{
			var className = 'correct';
			if(code != 200)
			{
				className = 'error';
			}
			$("#" + message_id).attr('class', className);
    	}
		
    	$("#" + message_id).html(message);
    	$("#" + box_id).dialog('open');
    },
    alertWindowClose: function(box_id)
    {
    	if(box_id == '' || typeof box_id == 'undefined')
    	{
    		return false;
    	}
    	$("#" + box_id).dialog('close');
    	return false;
    }
};

QGlobal.Viewhelper = {
	
    /**
		 * 更新页头的购物车信息
		 */
    updateCartStatusInHeader : function (){	
        var cartInfo = eval('(' + $.cookie('_g') + ')');
        if(cartInfo == null ){
        	$('#goodsNumInCartShowInHeader').html(0);
        	var uid = QGlobal.Passport.QCheckUserStatus();
        	if(uid == false){
        		return;
        	}            
            //发起一次cookie请求,用于cookie失效,但用户登录已上去也能显示cookie
            $.getJSON('http://www.yohobuy.com/shopping/cart/setshoppingcookie', function(){});
        }else{
            $('#goodsNumInCartShowInHeader').html(parseInt(cartInfo._nac) + parseInt(cartInfo._ac));
        }
								
    },
		
    /**
		 * 自动更新页头的购物车商品数量
		 */
    autoUpdateCartStatusInHeader : function(){
        this.updateCartStatusInHeader(); //页面加载后先立即执行一次
        setInterval(this.updateCartStatusInHeader, 2000);
    },
    
    formatMoney : function(s, n)
    {
       s = Math.ceil(s);
       n = n > 0 && n <= 20 ? n : 2;
       s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
       var l = s.split(".")[0].split("").reverse(),
       r = s.split(".")[1];
       t = "";
       for(i = 0; i < l.length; i ++ )
       {
          t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
       }
       //'¥' +  t.split("").reverse().join("") + "." + r;
       return  '¥' +  t.split("").reverse().join("") + ".00";
    },
    
    dispDom : function(ctrlObj, domId) {
    	$(ctrlObj).toggleClass("mycart_i_up");
        $('#' + domId).slideToggle(300);

    }
};
/**
 * 以下为页面加载完后就需要执行的脚本
 */
//定时更新购物车商品数量
//QGlobal.Viewhelper.autoUpdateCartStatusInHeader();

function sprintf () {
    // http://kevin.vanzonneveld.net
    // +   original by: Ash Searle (http://hexmen.com/blog/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Paulo Freitas
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: sprintf("%01.2f", 123.1);
    // *     returns 1: 123.10
    // *     example 2: sprintf("[%10s]", 'monkey');
    // *     returns 2: '[    monkey]'
    // *     example 3: sprintf("[%'#10s]", 'monkey');
    // *     returns 3: '[####monkey]'
    var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
    var a = arguments,
    i = 0,
    format = a[i++];

    // pad()
    var pad = function (str, len, chr, leftJustify) {
        if (!chr) {
            chr = ' ';
        }
        var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
        return leftJustify ? str + padding : padding + str;
    };

    // justify()
    var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
        var diff = minWidth - value.length;
        if (diff > 0) {
            if (leftJustify || !zeroPad) {
                value = pad(value, minWidth, customPadChar, leftJustify);
            } else {
                value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
            }
        }
        return value;
    };

    // formatBaseX()
    var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
        // Note: casts negative numbers to positive ones
        var number = value >>> 0;
        prefix = prefix && number && {
            '2': '0b',
            '8': '0',
            '16': '0x'
        }
        [base] || '';
        value = prefix + pad(number.toString(base), precision || 0, '0', false);
        return justify(value, prefix, leftJustify, minWidth, zeroPad);
    };

    // formatString()
    var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
        if (precision != null) {
            value = value.slice(0, precision);
        }
        return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
    };

    // doFormat()
    var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
        var number;
        var prefix;
        var method;
        var textTransform;
        var value;

        if (substring == '%%') {
            return '%';
        }

        // parse flags
        var leftJustify = false,
        positivePrefix = '',
        zeroPad = false,
        prefixBaseX = false,
        customPadChar = ' ';
        var flagsl = flags.length;
        for (var j = 0; flags && j < flagsl; j++) {
            switch (flags.charAt(j)) {
                case ' ':
                    positivePrefix = ' ';
                    break;
                case '+':
                    positivePrefix = '+';
                    break;
                case '-':
                    leftJustify = true;
                    break;
                case "'":
                    customPadChar = flags.charAt(j + 1);
                    break;
                case '0':
                    zeroPad = true;
                    break;
                case '#':
                    prefixBaseX = true;
                    break;
            }
        }

        // parameters may be null, undefined, empty-string or real valued
        // we want to ignore null, undefined and empty-string values
        if (!minWidth) {
            minWidth = 0;
        } else if (minWidth == '*') {
            minWidth = +a[i++];
        } else if (minWidth.charAt(0) == '*') {
            minWidth = +a[minWidth.slice(1, -1)];
        } else {
            minWidth = +minWidth;
        }

        // Note: undocumented perl feature:
        if (minWidth < 0) {
            minWidth = -minWidth;
            leftJustify = true;
        }

        if (!isFinite(minWidth)) {
            throw new Error('sprintf: (minimum-)width must be finite');
        }

        if (!precision) {
            precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
        } else if (precision == '*') {
            precision = +a[i++];
        } else if (precision.charAt(0) == '*') {
            precision = +a[precision.slice(1, -1)];
        } else {
            precision = +precision;
        }

        // grab value using valueIndex if required?
        value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];

        switch (type) {
            case 's':
                return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
            case 'c':
                return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
            case 'b':
                return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'o':
                return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'x':
                return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'X':
                return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
            case 'u':
                return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'i':
            case 'd':
                number = (+value) | 0;
                prefix = number < 0 ? '-' : positivePrefix;
                value = prefix + pad(String(Math.abs(number)), precision, '0', false);
                return justify(value, prefix, leftJustify, minWidth, zeroPad);
            case 'e':
            case 'E':
            case 'f':
            case 'F':
            case 'g':
            case 'G':
                number = +value;
                prefix = number < 0 ? '-' : positivePrefix;
                method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
                textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
                value = prefix + Math.abs(number)[method](precision);
                return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
            default:
                return substring;
        }
    };

    return format.replace(regex, doFormat);
};

//表单验证
function validateRight(str, id){
    $("#"+id+"_dl").attr('class','tips-box-error');
    $("#c_"+id).hide('fast');
    if( id == 'phone' &&  $('#mobile').val() != '' ){
        $("#phone_dl").removeClass();
        return "&nbsp;";
    }else if(id == 'mobile' &&  $('#phone').val() != '' ){
        $("#mobile_dl").removeClass();
        return "&nbsp;";
    }else{
        return '<span class="tips-error" id="error_'+id+'">'+str+'</span>';
    }
}
/* 下拉菜单 */
function showMenu(act, flag, msort) {
    $("#menu" + flag).css('display', 'block');
	$("#" + act).addClass("over");
	selectMenu(flag, msort);
}
function hideMenu(act, flag, msort) {
    $("#menu" + flag).css('display', 'none');
	$("#" + act).removeClass("over");
	selectMenu(flag, msort);
}
function hideMenuHit(act, flag, msort) {
    $("#menu" + flag).css('display', 'none');
	$("#" + act).removeClass("over");
	$("#" + act).removeClass("act");
}
function selectMenu(flag, msort)
{
	if(flag == msort)
	{
		$("#n" + flag).addClass('act');
	}
}
$(document).ready(function() {
	QGlobal.Check.QCheck();
});

var QINImgReady = (function () {
    var list = [], intervalId = null,

    // 用来执行队列
        tick = function () {
            var i = 0;
            for (; i < list.length; i++) {
                list[i].end ? list.splice(i--, 1) : list[i]();
            };
            !list.length && stop();
        },

    // 停止所有定时器队列
        stop = function () {
            clearInterval(intervalId);
            intervalId = null;
        };

    return function (url, ready, load, error) {
        var onready, width, height, newWidth, newHeight,
            img = new Image();

        img.src = url;

        // 如果图片被缓存,则直接返回缓存数据
        if (img.complete) {
            ready.call(img);
            load && load.call(img);
            return;
        };

        width = img.width;
        height = img.height;

        // 加载错误后的事件
        img.onerror = function () {
            error && error.call(img);
            onready.end = true;
            img = img.onload = img.onerror = null;
        };

        // 图片尺寸就绪
        onready = function () {
            newWidth = img.width;
            newHeight = img.height;
            if (newWidth !== width || newHeight !== height ||
                // 如果图片已经在其他地方加载可使用面积检测
                newWidth * newHeight > 1024
                ) {
                ready.call(img);
                onready.end = true;
            };
        };
        onready();

        // 完全加载完毕的事件
        img.onload = function () {
            // onload在定时器时间差范围内可能比onready快
            // 这里进行检查并保证onready优先执行
            !onready.end && onready();

            load && load.call(img);

            // IE gif动画会循环执行onload,置空onload即可
            img = img.onload = img.onerror = null;
        };

        // 加入队列中定期执行
        if (!onready.end) {
            list.push(onready);
            // 无论何时只允许出现一个定时器,减少浏览器性能损耗
            if (intervalId === null) intervalId = setInterval(tick, 40);
        };
    };
})();


function stripscript(s) {
    var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()&mdash;—|{}【】‘;:”“'。,、?]")
        var rs = "";
    for (var i = 0; i < s.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, '');
    }
    return rs;
}

var list_index = -1;
var query_num = 0;

$(document).ready(function(){
	
	 $("#query_key").keyup(function(event){
		        if(event.which == 38){
		          //up
			      if(query_num == 0) {
				      return;
			      }         
		          if(list_index == -1){list_index = 0;} 
		          var tmp_list = list_index;
		          list_index = (list_index - 1 + query_num)%query_num;
		          $("#shelper li:eq(" + tmp_list + ") a").css("background-color","#fff");
		          $("#shelper li:eq(" + list_index + ") a").css("background-color","#eee");
		          $("#query_key").attr("value", $("#shelper li:eq(" + list_index + ") a").attr("title"));
		        }else if(event.which == 40){
		          //down
		           if(query_num == 0) {
					      return;
				   }    
		          var tmp_list = list_index;
		          list_index = (list_index + 1)%query_num;
		          $("#shelper li:eq(" + tmp_list + ") a").css("background-color","#fff");
		          $("#shelper li:eq(" + list_index + ") a").css("background-color","#eee");
		          $("#query_key").attr("value", $("#shelper li:eq(" + list_index + ") a").attr("title"));
		          
		        }else if(event.which == 13)
		        {
			        var actUrl = $("#shelper li:eq(" + list_index + ") a").attr("act");
			        if(actUrl == undefined) {
			        	$('#searchForm').submit();
			        } else {
			        	window.location.href = actUrl;
			        }
		        }else{
		          //从后台提取词条,并重置 query_num 值
		        	var key = $.trim($('#query_key').val());
		        	key = key.replace(new RegExp("'","gm"),'');  //去掉特殊字符
		        	key = encodeURI(key);   //编码
					if(key != '') {
						$.get('/search/autocomplete?key=' + key, function(htmlData){
							$('#shelper').html(htmlData);
							query_num = $('#shelper li').length;
							list_index = -1;
							if(query_num > 0) {
								$('#shelper').show();
							} else {
								$('#shelper').hide();
							}
							//绑定事件					
							$("#shelper li a").hover(
								    function(){
								      $(this).css("background-color", "#eee");
								    },function(){
								      $(this).css("background-color", "#fff");
								    }
								  );
							  
						});
					} else {
						$('#shelper').hide();
					}
		        }
		}); 
		
});
$.extend({
browse : function (product_id, goods_id){
	if(parseInt(product_id) < 1 || parseInt(goods_id) < 1){
		return false;
	}
	$.getJSON('/product/index/userbrowse',{product_id : product_id, goods_id : goods_id}, function(eData){
		return true;
	});
}
});
//$(function() {          
//    $("img").lazyload({
//       // placeholder : "img/grey.gif", 
//    	threshold : 200,
//        effect : "fadeIn" 
//    });
//});