var gObj = {
numKeyCode: ['8','9','13','48','49','50','51','52','53','54','55','56','57','46'],
onlyNumKeyCode: ['8','9','13','48','49','50','51','52','53','54','55','56','57']
}

var isIE = (document.all) ? true : false;

function selectAll(_id){
	var thisobj = $(_id);
	thisobj.checked = !thisobj.checked;
	var cb=document.getElementsByClassName("cbitems");
	for(i=0;i<cb.length;i++){
		if(thisobj.checked==true){
			cb[i].checked=true;
		}
		if(thisobj.checked==false){
			cb[i].checked=false;
		}
	}
}

function selectOther(_id){
	var thisobj = $(_id);
	var cb=document.getElementsByClassName("cbitems");
	for(i=0;i<cb.length;i++){
		if(cb[i].checked==true){
			cb[i].checked=false;
		}else if(cb[i].checked==false){
			cb[i].checked=true;
		}
	}
}
/**
 * _inputArr中的input对象 允许输入的keyCode
 * @param _inputArr
 * @param _keyCodeArr
 * @return boolean
 */
function keypressCheck(_inputArr, _keyCodeArr) {
	_inputArr.each( function(_obj, index) {
		_obj.observe("keypress", function(e) {
			var _isInArr = false;
			 //alert(e.charCode);
				for (i = 0; i < _keyCodeArr.length; i++) {
					if (e.keyCode == _keyCodeArr[i]
							|| e.charCode == _keyCodeArr[i]) {
						_isInArr = true;
						break;
					}
				}
				if (window.event) {
					e.returnValue = _isInArr;
				} else {
					if (!_isInArr) {
						e.preventDefault();
					}
				}

				return _isInArr;
			}.bindAsEventListener(_obj, _keyCodeArr));
	});
}

function getQueryString(name){
	// 如果链接没有参数，或者链接中不存在我们要获取的参数，直接返回空

	if(location.href.indexOf("?")==-1 || location.href.indexOf(name+'=')==-1){
		return '';
	}

	// 获取链接中参数部分
	var queryString = location.href.substring(location.href.indexOf("?")+1);
	// 分离参数对 ?key=value&key2=value2
	var parameters = queryString.split("&");
	var pos, paraName, paraValue;
	for(var i=0; i<parameters.length; i++){
		// 获取等号位置
		pos = parameters[i].indexOf('=');
		if(pos == -1) { continue; }
		// 获取name 和 value
		paraName = parameters[i].substring(0, pos);
		paraValue = parameters[i].substring(pos + 1);
		// 如果查询的name等于当前name，就返回当前值，同时，将链接中的+号还原成空格
		if(paraName == name){
			return unescape(paraValue.replace(/\+/g, " "));
		}
	}
	return '';
}

function trim(str){  //删除左右两端的空格   
	return str.replace(/(^[\s\n]*)|([\s\n]*$)/g, "");   
}   
function ltrim(str){  //删除左边的空格   
	return str.replace(/(^[\s\n]*)/g,"");   
}   
function rtrim(str){  //删除右边的空格   
	return str.replace(/([\s\n]*$)/g,"");   
}

//，转,
function checkQj(obj) {
   var objValue = obj.value;
	 var p1 = /，+/g;
     if(p1.test(objValue)){
	    obj.value = objValue.replace(p1,",");
	 }
}

//图片按比例缩放
function DrawImage(ImgId,iwidth,iheight){
	//参数(图片,允许的宽度,允许的高度)
	var ImgD = $(ImgId);
	var _image=new Image();
	_image.src=ImgD.src;

	_image.width = Object.isUndefined(arguments[3]) ? _image.width : arguments[3];
	_image.height = Object.isUndefined(arguments[4]) ? _image.height : arguments[4];

	if(_image.width>0 && _image.height>0){
		if(_image.width/_image.height>= iwidth/iheight){
			if(_image.width>iwidth){
				ImgD.width=iwidth;
				ImgD.height=(_image.height*iwidth)/_image.width;
			}else{
				ImgD.width=_image.width;
				ImgD.height=_image.height;
			}
			ImgD.alt=_image.width+"×"+_image.height;
		}
		else{
			if(_image.height>iheight){
				ImgD.height=iheight;
				ImgD.width=(_image.width*iheight)/_image.height;
			}else{
				ImgD.width=_image.width;
				ImgD.height=_image.height;
			}
			ImgD.alt=_image.width+"×"+_image.height;
		}
	}
}

var PopAlert = Class.create( {
	initialize : function(msg) {
		var _str = '<div id="popUpContent" class="popUpContent" style="height:340px; width:570px;">';
		_str += '<div class="ggpopup2 force340">';
		_str += '<div class="ggpopup2inner">';
		_str += '<p style="text-align:center; padding:20px 10px 20px 0; font-size:14px; font-weight:700; color:#3D870B"><img src="../template/images/confirm.gif" align="absmiddle" /> #{msg}</p>';
		_str += '</div>';
		_str += '</div>';
		_str += '</div>';
		
		var defaults = {
			tplStr:_str,
			mainDiv:$("main").up("body"),
			nInt: 70, //每循环一次的时间
			fadetime:1000,
			stopTime:1000
		};

		this.options = Object.extend(defaults, arguments[1]||{});

		this.nDur = this.options.fadetime;
		this.nTime = 0;

		var tpl = new Template(this.options.tplStr);
		
		this.popDiv = new Element("div",{className:'popUpDiv', style:"display:block;width:409px;margin-left:-205px; position:absolute; left:50%"}).update(tpl.evaluate({msg:msg}));

		this.popDiv.style.filter = "alpha(opacity=100)";
		this.popDiv.style.opacity = 1;

		//居中
		this.popDiv.style.top = document.documentElement.clientHeight/2 + "px";
		this.popDiv.style.marginTop = -this.popDiv.offsetHeight/2 + document.documentElement.scrollTop + "px";

		this.options.mainDiv.insert({"bottom":this.popDiv});

		this.nID1 = setTimeout(function(){this._fade();}.bind(this), this.options.stopTime);
	},

	_fade : function(){
		this.nTime += this.options.nInt;

		var op = this._easeInOut(this.nTime, 0, 1, this.nDur); //获得的缓冲值
		var ieop = (op+0.3) * 100;
	
		if(isIE){
			this.popDiv.style.filter = "alpha(opacity=" + (100 - ieop) + ")";
		}else{
			this.popDiv.style.opacity = 1-op;
		}

		this.nID2 = setTimeout(this._fade.bind(this), this.options.nInt);

		if (this.nTime >= this.nDur){
			clearTimeout( this.nID2 );
			this.popDiv.remove();
		}
	},

	_easeInOut : function(t,b,c,d){
		return -c *(t/=d)*(t-2) + b;
	}
} );

function addFav(itemId){
	var logId = Object.isUndefined(arguments[1]) ? 0 : arguments[1];
	var url = "/feed/handle/addFavAjax.php?itemId="+itemId;
	new Ajax.Request(url, {
		method:"post", 
		onComplete: function(response){
			var result = trim(response.responseText);
			var info = new Hash({
				succ:"收藏成功",
				fav_exist:"您已经收藏过该商品了！"
			});
			new PopAlert(info.get(result));
			if(result == 'succ'){
				if($("favNum-"+logId)!=null){
					var _strNum = $('favNum-'+logId).innerHTML;
					_strNum = _strNum.replace("(", '');
					_strNum = _strNum.replace(")", '');
					_strNum ++;
					$('favNum-'+logId).update("("+_strNum+")");
				}
			}
		}.bindAsEventListener(this, logId)
	});
}

//编辑
function modRec(uRecId, issour, from){
	var _url = "../recommend/modRecAjax.php?uRecId="+uRecId+"&f="+from;
	
	var _style = issour==0?
			{'height': "390px", 'width': "770px"}:
			{'height': "520px", 'width': '950px'};

	popDiv.ajaxOpen(_url + "&" + Math.random(),
	{
		ajaxCallback:function(){
			new TagLimiter('alltag');

			for(var i=0; i < 51; i++){
				var cImgD = $('img-'+i);

				if(Object.isUndefined(cImgD)){
					continue;
				}

				if(i == 0){
					$("topimg").value=cImgD.src;
					cImgD.up('div').className="showF";
					cImgD.next('a').update('首张显示');
				}

				cImgD.observe("click", function(e){
					this.up(0).previous(0).down(0).checked = !this.up(0).previous(0).down(0).checked;
				});

				//mouseon,mouseout 事件
				cImgD.up('div').observe("mouseover",function(){
					if(this.className.blank())
					this.className = "show";
				});

				cImgD.up('div').observe("mouseout",function(){
					if(this.className == "show")
					this.className = "";
				});
			}
		},
		mainDivClass: 'dropShadow fetachRec',
		mainDivStyle: _style
	}
	);
}

//表单提交检查
function modItemCheck(){
	if($F("name").blank()){
		alert("宝贝名称不能为空");
		return false;
	}

	if($F('price-custom')=='custom'){
		if($F('price_text').blank()){
			alert("宝贝价格不能为空");
			return false;
		}
	}

	if($F("reason").blank()||trim($F("reason")).length<5){
		alert("推荐理由不能少于5个字符");
		return false;
	}

	if($F("alltag").blank()){
		alert("推荐标签不能为空");
		return false;
	}

	var sorts = document.getElementsByName("sortstr[]");
	var sortsHasChecked = false;
	var selectSortCount = 0;

	for(var i=0;i<sorts.length;i++){
		if(sorts[i].checked){
			sortsHasChecked = true;
			selectSortCount++;
		}
	}

	if(!sortsHasChecked){
		alert("必须勾选一个分类");
		return false;
	}

	if(selectSortCount>3){
		alert("只能选择3个一下分类");
		return false;
	}

	if($F("input-isDefault") == 0){
		var images = document.getElementsByName("images[]");
		var tempImages = document.getElementsByName("tempimages[]");
		var imagesHasChecked = false;

		for(var i=0;i<images.length;i++){
			if(images[i].checked){
				imagesHasChecked = true;
				break;
			}
		}

		for(var i=0;i<tempImages.length;i++){
			if(tempImages[i].checked){
				imagesHasChecked = true;
				break;
			}
		}

		//得到图片
		//var _allImg = document.getElementsByClassName("input-images");

		if( !imagesHasChecked ){
			alert("你至少要添加一张图片!");
			return false;
		}
	}

	popDiv.close();
	var wait_popDiv = new PopDiv('outwrap', {mainDivClass: 'dropShadow fetachRec',mainDivStyle: {"min-height":"500px","_height":"500px"}});
	wait_popDiv.loading('950px','520px','dropShadow','推荐信息提交中，请稍候^-^');

	return true;
}

function modRecCheck(){
	if($F("reason").blank()||trim($F("reason")).length<5){
		alert("推荐理由不能少于5个字符");
		return false;
	}

	if($F("alltag").blank()){
		alert("推荐标签不能为空");
		return false;
	}
	return true;
}

//分类选择次数
function checkSortCount(thisId){
	var _thisObj = $(thisId);
	var _allCb = document.getElementsByClassName('cb-sort');
	var _cbCount = 0;
	for(var i=0; i < _allCb.length; i++){
		if(_allCb[i].checked){
			_cbCount++;
		}
	}
	if(_cbCount > 3){
		_thisObj.checked=false;
	}
	return true;
}

//set event source image is top image
function setTop(thisObjId){
	var thisObj = $(thisObjId);
	
	$("topimg").value = thisObj.previous(0).src;
	var all_els = thisObj.up('ul').childElements();

	for(var i=0;i<all_els.length;i++){
		all_els[i].down('div').className = "";
		all_els[i].down('a').update("设为首张显示");
	}
	thisObj.update("首张显示");
	thisObj.up('li').down('input').checked = true;
	thisObj.up('div').className = "showF";
}

//图片获取
function getTempImg(){
	new PeriodicalExecuter( function(pe){
		var _objIfrm = window.frames["ifr-upload"].document;

		var _filename = Object.isUndefined(_objIfrm.getElementById('filename')) ? '' : _objIfrm.getElementById('filename').innerHTML;
		if(!_filename.blank()){
			if(_filename == 'error'){
				alert('对不起，图片尺寸过大或者上传文件格式不正确 !');
				pe.stop();
				return false;
			}

			$("file-input-tempimg").value="";

			var html = "<span><input type=\"checkbox\" name=\"tempimages[]\" value=\"#{filename}\"  checked /></span>";
			html += "<div><img id=\"img-#{id}\" src=\"#{src}\" />";
			html += "<a href=\"javascript:setTop('a-set-top-#{id}')\" class=\"isTop\" id=\"a-set-top-#{id}\">设为首张显示</a></div>";

			var _tpl = new Template(html);

			var _w = parseInt(_objIfrm.getElementById('width').innerHTML);
			var _h = parseInt(_objIfrm.getElementById('height').innerHTML);

			var _src = '../upload/images/temp/' + _filename;
			var _imgId = _filename.split(".")[0];

			var _img = new Element("li").update(_tpl.evaluate({filename:_filename, id:_imgId ,src:_src}));
			$("ul-img").insert({"top":_img});
			//this.initImage(_w, _h);
			$('img-'+_imgId).height = _h;
			$('img-'+_imgId).width = _w;

			//alert("图片上传成功!");

			DrawImage('img-'+_imgId, 100, 100, _w, _h);

			$('img-'+_imgId).observe("click", function(e){
				this.up(0).previous(0).down(0).checked = !this.up(0).previous(0).down(0).checked;
			});

			//mouseon,mouseout 事件
			$('img-'+_imgId).up('div').observe("mouseover",function(){
				if(this.className.blank())
					this.className = "show";
			});

			$('img-'+_imgId).up('div').observe("mouseout",function(){
				if(this.className == "show")
					this.className = "";
			});

			pe.stop();
		}
	}.bind(this),1);
}

function insideRec(uRecId){
	var _url = '../recommend/handle/isRecedAjax.php?uRecId='+uRecId;
	new Ajax.Request(_url + "&" + Math.random(),
		{
			method:"get",
			onComplete:function(transport){
				var _response = transport.responseText.strip();
				if(_response==0){
					var _url = '../recommend/insideRecAjax.php?uRecId='+uRecId;
					popDiv.ajaxOpen(_url + "&" + Math.random(),
					{
						ajaxCallback:function(){
							new TagLimiter('alltag');
							//alert('i got~!');
						},
						mainDivClass: 'dropShadow fetachRec',
						mainDivStyle:{'height': "390px", 'width': "770px"}
					}
					);
				}else{
					new PopAlert('你已经推荐过该商品了!');
				}
			}.bind(this)
		}
	);
}

function addPic(o){
	$(o).next(0).toggle();
}

function array_remove(arr, val)
{
	var result = new Array();
	for(var i=0; i<arr.length; i++)
	{
		if(arr[i] != val){
			result.push(arr[i]);
		}
	}
	return result;
}
