function trim($val){
    return $val.replace(/(^\s*)|(\s*$)/g, "");
}

function isabc($val) {
    var pattern = /^[a-z]*$/i;
    if(pattern.exec($val)) {
        return true;
    } else {
        return false;
    }
}

function isnum($val) {
    var pattern = /^([\d|\+|\-|\*|\/|=])*$/;
    if(pattern.exec($val)) {
        return true;
    } else {
        return false;
    }
}

function istel($val) {
    var pattern =/^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/;
    if(!pattern.exec($val)) {
        return false;
    } else {
        return true;
    }
}

function isemail($val) {
    var pattern =/^[a-zA-Z0-9_\-]{1,}@[a-zA-Z0-9_\-]{1,}\.[a-zA-Z0-9_\-.]{1,}$/;
    if(!pattern.exec($val)) {
        return false;
    } else {
        return true;
    }
}

function ismobile($val) {
    var reg = /^(([0\+]\d{2,3})?(1\d{10}))$/;
    if(reg.exec($val)) {
		return true;
	} else {
		return false;
	}
}

function checkform($eform) {
	if (!$eform) return true;
    $objs = $eform.getElementsByTagName("*");
    for ($i=0;$i<$objs.length;$i++) {
		if ($objs[$i].nodeType != '1') continue;
		__tag = $objs[$i].tagName.toLowerCase();
		if (__tag!='input' && __tag!='textarea' && __tag!='select') continue;
		var __name = $objs[$i].getAttribute('name') || null;
		var __type = $objs[$i].getAttribute('type') || null;
		var __require = $objs[$i].getAttribute('require')=='true' || $objs[$i].getAttribute('require')=='1' ? true : false;
		var __datatype = $objs[$i].getAttribute('datatype') || null;
		var __init = $objs[$i].getAttribute('init') || null;
		var __maxlen = $objs[$i].getAttribute('maxlen') || 0;
		var __notify = $objs[$i].getAttribute('notify') || '未知节点名称';
		var __val = '';
		if (__tag=='input') {
			if (__type=='text' || __type=='file' || __type=='password') {
				__val = trim($objs[$i].value);
			} else if (__type=='radio' || __type=='checkbox') {
				if (!__name) continue;
				__tobj = document.getElementsByName(__name);
				for(j=0;j<__tobj.length;j++) {
					if (__tobj[j].checked==true) {
						__val = 1;
						continue;
					}
				}
			}
		} else if (__tag=='select') {
			__val = __init && $objs[$i].value==__init ? '' : $objs[$i].value;
		} else {
			__val = trim($objs[$i].value);
			
		}
		if (__require==true && __val=='') {
			alert('[ '+__notify+' ]必须填写或选择');
			try {
				$objs[$i].focus();
			} catch(e) {
				__tobj[0].focus();
			}
			return false;
		}
		switch (__datatype) {
			case 'num' :
				if (isnum(__val)==false) {
					alert('[ '+__notify+' ]输入不合法,只允许输入(数字,+,-,*,/)');
					$objs[$i].focus();
					return false;
				}
				break;
			case 'abc' :
				if (isabc(__val)==false) {
					alert('[ '+__notify+' ]输入不合法,只允许输入字母');
					$objs[$i].focus();
					return false;
				}
				break;
			case 'tel' :
				if (istel(__val)==false) {
					alert('[ '+__notify+' ]输入不合法,只允许电话号码\r\n格式如:+86-000-00000000,000-00000000,00000000等格式');
					$objs[$i].focus();
					return false;	
				}
				break;
			case 'mobile' :
				if (ismobile(__val)==false) {
					alert('[ '+__notify+' ]输入不合法,只允许手机号码\r\n格式如:+86-13812345678,13812345678等格式');
					$objs[$i].focus();
					return false;	
				}
				break;
			case 'email' :
				if (isemail(__val)==false) {
					alert('[ '+__notify+' ]输入不合法,只允许输入电子邮箱地址');
					$objs[$i].focus();
					return false;	
				}
				break;
		}
		if (__maxlen>0) {
			if (__val.length>__maxlen) {
				alert('[ '+__notify+' ]输入不合法,字符长度必须小于'+__maxlen+'个字符');
				$objs[$i].focus();
				return false;
			}
		}
	}
}

function showconfirm(msg,url) {
    if (confirm(msg)) {
        location.href = url;
    }
}

//title为弹出窗的标题,width为宽度,height为高度,如果指定url格式为[url=]则为iframe模式,否则为html模式
function showwin($title,$width,$height,$url) {
    if ($("#popwin").length>0) return;
    if (!$width || $width == '') $width = 500;
    if (!$height || $height == '') $height = 300;
    $width = parseInt($width,10);
    $height = parseInt($height,10);
    $("body").append('<div id="mask" style="position:absolute;left:0px;top:0px;width:'+$(window).width()+'px;height:'+$("body").height()+'px;background:#ffffff;z-index:999;opacity:0.6;filter:alpha(opacity:60);"></div>');
    $("body").append('<div id="popwin" style="position:absolute;width:'+$width+'px;height:'+$height+'px;border:#cccccc 3px solid;background:#ffffff;z-index:1000;overflow:hidden;"><div id="wintitle" style="clear:both;padding:0px 5px;background:#ebebeb;height:30px;line-height:30px;font-size:14px;font-weight:bold;" onselectstart="return false;" oncontextmenu="return false;"><span style="float:left">'+$title+'</span><span style="float:right"><a href="javascript:void(0);" onclick="hidewin()">关闭</a></span></div><div id="wincontent" style="height:'+($height-30)+'px;clear:both;text-align:left;overflow:hidden;overflow-y:scroll;"></div></div>');
    $st = $(window).scrollTop();
    $mt = parseInt(($(window).height()-$height)/2,10);
    $ml = parseInt(($(window).width()-$width)/2,10);
    $("#popwin").css({
        left:$ml+"px",
        top:($mt+$st)+"px"
    });
    var $reg = /^\[url=.+\]$/i;
    if ($reg.exec($url)) {
        $url = trim($url.replace('[url=','').replace(']',''));
        $("#wincontent").html('<iframe frameborder="0" width="'+$width+'" height="'+($height-30)+'" scrolling="auto" src="'+$url+'"></iframe>');
    } else {
        $("#wincontent").html($url);
    }
}

function selectimg($target,$dir) {
    if ($dir==null || $dir=='undefined') $dir = '';
    if ($("#popwin").length==0) {
        $.getJSON(cfg_root+'user/userfile_json.php?type=img&dir='+$dir,function(data){
            $html = '<div class="s_img_list"><ul>';
            $.each(data,function($k,$v){
                $html += '<li>';
                if ($v.filetype == 'dir') {
                    $html += '<a href="javascript:void(0);" onclick="selectimg(\''+$target+'\',\''+$v.linkpath+'\');" title="'+$v.filename+'"><img src="'+cfg_root+'templets/user/images/folder_64.gif" />';
                } else {
                    $html += '<a href="javascript:void(0);" onclick="returnsrc(\''+$target+'\',\''+$v.linkpath+'\');" title="'+$v.filename+'"><img src="'+$v.linkpath+'" />';
                }
                $html += '<div class="s_title">'+$v.filename+'</div></a></li>';
            });
            $html += '</ul></div>';
            showwin('请选择图片...',600,500,$html);
        });
    } else {
        if ($dir == '') return;
        $.getJSON(cfg_root+'user/userfile_json.php?type=img&dir='+$dir,function(data){
            $html = '<div class="s_img_list"><ul>';
            $.each(data,function($k,$v){
                $html += '<li>';
                if ($v.filetype == 'dir') {
                    $html += '<a href="javascript:void(0);" onclick="selectimg(\''+$target+'\',\''+$v.linkpath+'\');" title="'+$v.filename+'"><img src="'+cfg_root+'templets/user/images/folder_64.gif" />';
                } else {
                    $html += '<a href="javascript:void(0);" onclick="returnsrc(\''+$target+'\',\''+$v.linkpath+'\');" title="'+$v.filename+'"><img src="'+$v.linkpath+'" />';
                }
                $html += '<div class="s_title">'+$v.filename+'</div></a></li>';
            });
            $html += '</ul></div>';
            $('#wincontent').html($html);
        });
    }
}

function selectfile($target,$dir) {
    if ($dir==null || $dir=='undefined') $dir = '';
    if ($("#popwin").length==0) {
        $.getJSON(cfg_root+'user/userfile_json.php?dir='+$dir,function(data){
            $html = '<div class="s_file_list"><ul>';
            $.each(data,function($k,$v){
                $html += '<li>';
                if ($v.filename == '..') {
                    $html += '<a class="up" href="javascript:void(0);" onclick="selectfile(\''+$target+'\',\''+$v.linkpath+'\');" title="返回上级" >返回上级</a>';
                } else if ($v.filetype == 'dir') {
                    $html += '<a class="dir" href="javascript:void(0);" onclick="selectfile(\''+$target+'\',\''+$v.linkpath+'\');" title="'+$v.filename+'">'+$v.filename+'</a>';
                } else {
                    $html += '<a class="file" href="javascript:void(0);" onclick="returnsrc(\''+$target+'\',\''+$v.linkpath+'\');" title="'+$v.filename+'">'+$v.filename+'</a>';
                }
                $html += '</li>';
            });
            $html += '</ul></div>';
            showwin('请选择文件...',600,500,$html);
        });
    } else {
        if ($dir == '') return;
        $.getJSON(cfg_root+'user/userfile_json.php?dir='+$dir,function(data){
            $html = '<div class="s_file_list"><ul>';
            $.each(data,function($k,$v){
                $html += '<li>';
                if ($v.filename == '..') {
                    $html += '<a class="up" href="javascript:void(0);" onclick="selectfile(\''+$target+'\',\''+$v.linkpath+'\');" title="返回上级" >返回上级</a>';
                } else if ($v.filetype == 'dir') {
                    $html += '<a class="dir" href="javascript:void(0);" onclick="selectfile(\''+$target+'\',\''+$v.linkpath+'\');" title="'+$v.filename+'">'+$v.filename+'</a>';
                } else {
                    $html += '<a class="file" href="javascript:void(0);" onclick="returnsrc(\''+$target+'\',\''+$v.linkpath+'\');" title="'+$v.filename+'">'+$v.filename+'</a>';
                }
                $html += '</li>';
            });
            $html += '</ul></div>';
            $('#wincontent').html($html);
        });
    }
}

function returnsrc($target,$src) {
    $('#'+$target).val($src);
    hidewin();
}

function hidewin() {
    $("#mask").remove();
    $("#popwin").remove();
}

function showuploader($target,$obj,$filetype) {
    if ($('#uploader').length>0) return;
    $html = '<div id="uploader" style="position:absolute;width:260px;border:#ccc 1px solid;background:#fff;"><div style="width:100%;height:20px;line-height:20px;font-weight:bold;background:#ebebeb;color:#666;"><span style="float:left;padding-left:10px;">文件上传...</span><span style="float:right;padding-right:10px;"><a href="javascript:void(0);" onclick="if($(\'#uploader>#status\').attr(\'status\')!=\'inprocess\'){hideuploader();}else{alert(\'正在上传中,上传完毕会自动关闭!\');}">&#215;关闭</a></span></div><div style="height:22px;line-height:22px;padding:3px;" id="status"><form action="'+cfg_root+'user/upload.php" method="post" enctype="multipart/form-data" target="upframe" onsubmit="$(this).parent().attr(\'status\',\'inprocess\');"><input class="ipt_file" type="file" name="upfile" style="width:200px;" />&nbsp;<input class="ipt_btn_small" type="submit" value="上传"><input type="hidden" name="target" value="'+$target+'" /><input type="hidden" name="uptype" value="'+$filetype+'" /></form></div><iframe name="upframe" style="display:none;" src="about:blank"></iframe></div>';
    $('body').append($html);
    $('#uploader').css({
        'left':$($obj).position().left+'px',
        'top':($($obj).position().top+$($obj).height())+'px'
    });
}

function hideuploader() {
    $('#uploader').remove();
}

function user_addcat() {
    $cat_name = trim($('#newcat').val());
    if ($cat_name == '') {
        alert('分类名称不允许为空');
        return;
    }
    $.getJSON(cfg_root+'user/mycat.php?callback=?',{
        act : 'add',
        type : 'ajax',
        cat_name : $cat_name
    },function(data){
        $('#newcat, #newcat_btn, #newcat_cel').hide();
        $('#newcat_add').show();
        $('#newcat').val('');
        $ucat = $('#ucat')[0];
        $ucat.options[$ucat.length] = new Option('·'+data.cat_name,data.id);
        $ucat.options[$ucat.length-1].selected = 'selected';
    });
}

function comment_post($aid) {
    if (GetCookie("comment_ids").indexOf(","+$aid+",") != -1) {
        alert("您已经发表过了，先喝杯茶休息会吧！");
        return;
    }
	$noname = $("#c_noname").attr('checked') == true ? 1 : 0;
    $.getJSON(
        cfg_root+"plus/ajax.php?callback=?",
        {
            act:$("#c_opt").val(),
            aid:$("#c_aid").val(),
            pid:$("#c_pid").val(),
            nickname:$("#c_nickname").val(),
			noname:$noname,
            comment:$("#c_comment").val(),
            vcode:$("#c_verify").val()
        },
        function(data){
            if (data.msg) {
                alert(data.msg);
            } else if (data.succeed) {
				$.getJSON(
						cfg_root+'plus/ajax.php?callback=?',
						{
							act:'commentlist',
							aid:$aid,
							sid:Math.random()
						},
						function(data){
							$('#comment_new').html(data);
						});
                alert(data.succeed);
                document.getElementById("comment_form").reset();
                if (GetCookie("comment_ids") == "") SetCookie("comment_ids",",");
                SetCookie("comment_ids",GetCookie("comment_ids")+$aid+",");
            }
            $("#c_vcode").attr("src",$("#c_vcode").attr("src")+"?");
        });
}

function comment_good($comment_id){
    if (GetCookie("comment_goodbad").indexOf(","+$comment_id+",") != -1) {
        alert("先喝杯茶休息会吧！");
        return;
    }
    $.getJSON(
        cfg_root+'plus/ajax.php?callback=?',
        {
            act:'commentgood',
            comment_id:$comment_id
        },
        function(data){
			$("#comment_good_"+$comment_id+">span").html(data);
			$("#comment_good_"+$comment_id).removeAttr("href");
			$("#comment_bad_"+$comment_id).removeAttr("href");
			if (GetCookie("comment_goodbad") == "") SetCookie("comment_goodbad",",");
			SetCookie("comment_goodbad",GetCookie("comment_goodbad")+$comment_id+",");
        });
}

function comment_bad($comment_id){
    if (GetCookie("comment_goodbad").indexOf(","+$comment_id+",") != -1) {
        alert("先喝杯茶休息会吧！");
        return;
    }
    $.getJSON(
        cfg_root+'plus/ajax.php?callback=?',
        {
            act:'commentbad',
            comment_id:$comment_id
        },
        function(data){
			$("#comment_bad_"+$comment_id+">span").html(data);
			$("#comment_bad_"+$comment_id).removeAttr("href");
			$("#comment_good_"+$comment_id).removeAttr("href");
			if (GetCookie("comment_goodbad") == "") SetCookie("comment_goodbad",",");
			SetCookie("comment_goodbad",GetCookie("comment_goodbad")+$comment_id+",");
        });
}

function digg_up($aid) {
    if (GetCookie("digg").indexOf(","+$aid+",") != -1) {
        alert("先喝杯茶休息会吧！");
        return;
    }
    $.getJSON(
        cfg_root+'plus/ajax.php?callback=?',
        {
            act:'diggup',
            aid:$aid,
            sid:Math.random()
        },
        function(data){
            $("#digg_up").html(data.up);
            $("#digg_up_bar>span").css("width",data.up_percent+"%");
            $("#digg_up_percent").html(data.up_percent+"%");
            $("#digg_down").html(data.down);
            $("#digg_down_bar>span").css("width",data.down_percent+"%");
            $("#digg_down_percent").html(data.down_percent+"%");
            if (GetCookie("digg") == "") SetCookie("digg",",");
            SetCookie("digg",GetCookie("digg")+$aid+",");
        });
}

function digg_down($aid) {
    if (GetCookie("digg").indexOf(","+$aid+",") != -1) {
        alert("先喝杯茶休息会吧！");
        return;
    }
    $.getJSON(
        cfg_root+'plus/ajax.php?callback=?',
        {
            act:'diggdown',
            aid:$aid,
            sid:Math.random()
        },
        function(data){
            $("#digg_up").html(data.up);
            $("#digg_up_bar>span").css("width",data.up_percent+"%");
            $("#digg_up_percent").html(data.up_percent+"%");
            $("#digg_down").html(data.down);
            $("#digg_down_bar>span").css("width",data.down_percent+"%");
            $("#digg_down_percent").html(data.down_percent+"%");
            if (GetCookie("digg") == "") SetCookie("digg",",");
            SetCookie("digg",GetCookie("digg")+$aid+",");
        });
}

function arc_init($aid) {
    $.getJSON(
        cfg_root+'plus/ajax.php?callback=?',
        {
            act:'arcinit',
            aid:$aid,
            sid:Math.random()
        },
        function(data){
            $("#digg_up").html(data.up);
            $("#digg_up_bar>span").css("width",data.up_percent+"%");
            $("#digg_up_percent").html(data.up_percent+"%");
            $("#digg_down").html(data.down);
            $("#digg_down_bar>span").css("width",data.down_percent+"%");
            $("#digg_down_percent").html(data.down_percent+"%");
            $("#_showscore").html(data.score);
            if (data.verify==1) {
                $("#verifycode").html('验证码：<input type="text" name="vcode" id="c_verify" size="6" require="1" notify="验证码" style="text-transform:uppercase;" /> <img id="c_vcode" src="'+cfg_root+'include/verifycode.php" onclick="this.src+=\'?\'" align="absmiddle" style="cursor:pointer;" />');
            } else {
                $("#verifycode").html('<span style="padding-left:100px;"></span>');
            }
            if (data.login==1) {
                $('#comment_login').html('您已以'+data.userid+'的身份登录！ <input type="hidden" id="c_nickname" value="'+data.userid+'" /><label><input type="checkbox" id="c_noname" value="1" /> 匿名评论?</label>');
            }
        });
    $.getJSON(
        cfg_root+'plus/ajax.php?callback=?',
        {
            act:'commentlist',
            aid:$aid,
            sid:Math.random()
        },
        function(data){
            $('#comment_new').html(data);
        });
}

function digg_score($aid,$score) {
    if (GetCookie("digg_score").indexOf(","+$aid+",") != -1) {
        alert("先喝杯茶休息会吧！");
        return;
    }
    $.getJSON(
        cfg_root+'plus/ajax.php?callback=?',
        {
            act:'diggscore',
            aid:$aid,
            score:$score
        },
        function(data){
            showscore(data,$score);
            if (GetCookie("digg_score") == "") SetCookie("digg_score",",");
            SetCookie("digg_score",GetCookie("digg_score")+$aid+",");
        });
}

function SetCookie(name,value) {
    var argv=SetCookie.arguments;
    var argc=SetCookie.arguments.length;
    var expires=(2<argc)?argv[2]:null;
    var path=(3<argc)?argv[3]:null;
    var domain=(4<argc)?argv[4]:null;
    var secure=(5<argc)?argv[5]:false;
    document.cookie=name+"="+escape(value)+((expires==null)?"":("; expires="+expires.toGMTString()))+((path==null)?"":("; path="+path))+((domain==null)?"":("; domain="+domain))+((secure==true)?"; secure":"");
}

function GetCookie(Name) {
    var search = Name + "=";
    var returnvalue = "";
    if (document.cookie.length > 0)
    {
        offset = document.cookie.indexOf(search);
        if (offset != -1)
        {
            offset += search.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1)
                end = document.cookie.length;
            returnvalue=unescape(document.cookie.substring(offset,end));
        }
    }
    return returnvalue;
}


function addtocart($form) {
	$child = $form.getElementsByTagName('*');
	$string = '';
	for($i=0;$i<$child.length;$i++) {
		$tag = $child[$i].tagName.toLowerCase();
		$name = $child[$i].name;
		$value = $child[$i].value;
		if ($tag=='input' || $tag=='textarea') {
			$string += '&'+$name+'='+encodeURI($value);
		}
	}
	$.getJSON('cart.php?callback=?'+$string+'&ajax=true',function(data){
																 if (data.error) {
																	 alert(data.error);
																 } else {
																	 //$('#cart_counts').html(data.counts);
																	 //data.counts可以取得购物车的商品数量
																	 //data.items对象可以取得购物车的商品列表,使用$.each即可
																	 if (confirm('已成功加入购物车，需要立即查看购物车吗?')) location.href="cart.php";
																 }
																 });
	return false;
}
