﻿var dh = YAHOO.ext.DomHelper;
if(!coke){
	var coke = new YAHOO.ext.state.CookieProvider({
       path: '/',
       expires: new Date(new Date().getTime()+(1000*60*60*24*7)),//7 days
       domain: null,
       secure: false       
   })
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
  
}
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}
var VAILED = false;
function CheckID(node){
	var Flag = getEl(node.id+'_Flag');
	var success=function(o){
		if(o.responseText=='true'){
			Flag.removeClass('validLoading');
			Flag.addClass('validSuccess')
		}else{
			Flag.removeClass('validLoading');
			Flag.addClass('validFaild')
		}
	}.createDelegate(this);
	Flag.removeClass('validFaild');
	Flag.removeClass('validSuccess');
	Flag.addClass('validLoading');
	Flag.innerHTML = '&nbsp';
	var postData = "Value="+node.value + '&Field='+node.id ;
	YAHOO.util.Connect.asyncRequest('POST', 'AJAXNormal.php?Method=chkField', {success:success}, postData);
}

function CheckVaild(){
	var body = getEl(document.body);
	var VNone = body.getChildrenByClassName('validNone');
	var VValid = body.getChildrenByClassName('validFaild');
	var VLoading = body.getChildrenByClassName('validLoading');

	
	if(VNone.length){
		for(i=0;i<VNone.length;i++){
			VNNode = getEl(VNone[i].id.substring(0,VNone[i].id.length-5))
			if(VNNode.dom.value){
				VNone[i].removeClass('validNone');
				CheckVaild();
				return;
			}
			VNNode.addClass('faildField');
		}
		alert('所有的欄位都必須填寫');
		getEl(VNone[0].id.substring(0,VNone[0].id.length-5)).focus()
		return;
	}
	if(VValid.length){
		alert('必須所有的資料皆正確');
		for(i=0;i<VValid.length;i++){
			VNNode = getEl(VValid[i].id.substring(0,VValid[i].id.length-5))
			VNNode.dom.value = ''
			VNNode.addClass('faildField');
		}
		getEl(VValid[0].id.substring(0,VValid[0].id.length-5)).focus()
		return;
	}
	if(VLoading.length){
		alert('請等侯驗證完畢.');
		return
	}	
	doSubmit(function(){getEl('registerForm').dom.submit()});
}

function finishEdit(){
	doSubmit(function(){getEl('editForm').dom.submit()});
}

function CheckPassword(node){
	var Node = getEl(node.id.replace('_c',''));
	var NodeC = getEl(Node.id + '_c');
	var Flag = getEl(Node.id + '_Flag');
	Flag.removeClass('validFaild');
	Flag.removeClass('validSuccess');
	
	if(Node.dom.value != NodeC.dom.value || (Node.dom.value.length <= 3 || Node.dom.value.length >=13)){
		Flag.removeClass('validLoading');
		Flag.addClass('validFaild');
	}else{
		Flag.removeClass('validLoading');
		Flag.addClass('validSuccess');
	}
}

function ForgetPassword(Username,EMail){
	var postData = 'Username='+Username+'&EMail='+EMail;
	var success = function(o){
		alert(o.responseText);
	};
	YAHOO.util.Connect.asyncRequest('POST', 'san_mservice.php?Method=forgetpassword', {success:success}, postData);
}
var mask;
var proxy;
function PicZoomIn(pic){
	var NewImg = getEl('FullView');
	if(!NewImg){
		NewImg = YAHOO.ext.DomHelper.append(document.body,{tag:'img',src:pic,ID:'FullView',cls:'FullView'},true);
		proxy = NewImg.createProxy('FVProxy');
		mask = YAHOO.ext.DomHelper.append(document.body, {tag: 'div',ID:'Mask', cls:'ydlg-mask'}, true);
        mask.enableDisplayMode('block');
	}
		
		NewImg.setXY([YAHOO.util.Dom.getDocumentWidth()/2 - NewImg.getWidth()/2,YAHOO.util.Dom.getDocumentHeight()/2 -NewImg.getHeight()/2]);
		NewImg.on('click',PicZoomOut,this,true);
		
		
        mask.hide();

		
		YAHOO.util.Dom.addClass(document.body, 'masked');
		mask.setSize(YAHOO.util.Dom.getDocumentWidth(), YAHOO.util.Dom.getDocumentHeight());
		mask.show();

		
	    var b = getEl('photo_line', true).getBox();
		
        proxy.setSize(b.width, b.height);
        proxy.setLocation(b.x, b.y);
        proxy.show();
		proxy.setBounds(NewImg.getX(), NewImg.getY(), NewImg.getWidth(), NewImg.getHeight(), true, .35,
			function(){
				proxy.hide();
				NewImg.show();
			}.createDelegate(this)
		);


}

var zeroCart = null;
var snode = new Array();
var scount = 0;
var payEl = new Array();
var payID = new Array();




function addQuickShop(){
	var shopcart = coke.get('shopcart',null);
	if(!shopcart){
		shopcart = new Array();
	}
	
	var QuickList = document.getElementsByTagName('input');
	var QList = new Array();
	
	for(i=0;i<QuickList.length;i++){
		if(QuickList[i].id.indexOf('Quantity') != -1 && parseInt(QuickList[i].value)){
			QList.push(QuickList[i].id);
		}
	}

	QList.sort();
	if(!shopcart.length	 && QList.length){
		tmpID = QList[QList.length-1]
		tmpID = tmpID.substring(tmpID.indexOf('[')+1,tmpID.indexOf(']'))
		for(i=0;i<=tmpID;i++){
			shopcart.push({});;
		}
	}
	
	for(i=0;i<QList.length;i++){
		var existID = 'no'
		var pID = QList[i].substring(QList[i].indexOf('[')+1,QList[i].indexOf(']'));
		var pCount = getEl(QList[i]).dom.value;
		if(shopcart[pID])if(shopcart[pID].ID)existID = pID;
		
		if(existID=='no'){
			shopcart[pID] = ({'ID':pID,'Count':pCount});
		}else{
			shopcart[existID].Count = parseInt(shopcart[existID].Count)+parseInt(pCount);
		}
	}
	if(QList.length){
		window.navigate('san_shopping.php?Method=pay');
	}
	
	coke.clear();
	coke.set('shopcart',shopcart);
	
}




function addShopCart(ID,Count,dir){
	var shopcart = coke.get('shopcart',null);
	if(!shopcart){
		shopcart = new Array();
	}
	
	var existID = 'no';
	for(i in shopcart){
		if(shopcart[i].ID){
			var si = i
			if(shopcart[i].ID ==ID){
				existID = i;
				if(!dir)alert('數量已改變');
			}
		}
	}
	
	if(existID=='no'){
		shopcart[ID] = ({'ID':ID,'Count':Count});
	}else{
		shopcart[existID].Count = parseInt(shopcart[existID].Count)+parseInt(Count);
	}
	coke.clear();
	coke.set('shopcart',shopcart);
	if(existID=='no'){
		
		alert('已加入購物車');
		if(zeroCart){
			zeroCart.hide(true,.35,function(){
				getEl('slist').setHeight(zeroCart.getHeight());
				zeroCart.remove();
				zeroCart = null;
				getShopCart(ID);
			});
		}else{
			getShopCart(ID);
		}
	}
}

function delShopCart(si,dir){
	var shopcart = coke.get('shopcart',null);
	var newscart = new Array();
	if(confirm('此物品購買數量為'+shopcart[si].Count+'個\n是否確定要刪除')){
		for(i in shopcart){
			if(i!=si && shopcart[i].ID){
				newscart[i] = ({'ID':shopcart[i].ID,'Count':shopcart[i].Count});
			}
		}
		
		if(getEl('paylist') && !dir){
			delPayEl(si,si,true);
		}
		
		coke.clear();
		scount--;
		if(scount){
			coke.set('shopcart',newscart);
		}else{
			coke.set('shopcart',null);
		}

		snode[si].hide(true,.35,
			function(){
				snode[si].remove()
				if(!scount){
					zeroCart = dh.append(getEl('slist').dom,
					{	
							tag:'span',
							html:'<table width="100%" border="0" cellspacing="0" cellpadding="0"><td class="quickly_1"><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>'+
								 '<td width="62%" valign="top" align="center" class="index_1">購物車是空的</td>'+
								 '</tr></table></td></tr><tr><td><img src="images/main_38.jpg" width="187" height="5" border="0"></td></tr></table>',
							style:'visibility:hidden;'
					},true)
					zeroCart.show(true);
				}
			})
		return true;
	}else{
		return false;
	}
}


function getShopCart(si){
	var shopcart = coke.get('shopcart',null);
	var postData = 'shopcart='+shopcart[si].ID;

	
	var success=function(o){
		scount++
		snode[si] = dh.append(getEl('slist').dom,
					{	
						tag:'span',
						html:'<table width="100%" border="0" cellspacing="0" cellpadding="0"><td class="quickly_1"><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>'+
							 '<td width="8%" valign="top" class="quickly_2"><img src="images/main_36.jpg" width="14" height="12" border="0"></td>'+
							 '<td width="62%" valign="top" class="index_1"><a href="san_products.php?Method=more&ID='+shopcart[si].ID+'">'+o.responseText+'</a></td>'+
							 '<td width="30%" valign="top" class="index_1">| <a id="Link['+si+']" href="javascript:void delShopCart('+si+',false)" class="link7">刪除</a></td>'+
							 '</tr></table></td></tr><tr><td><img src="images/main_38.jpg" width="187" height="5" border="0"></td></tr></table>',
						style:'visibility:hidden;'
					},true);
		snode[si].show(true);
	}.createDelegate(this);
	YAHOO.util.Connect.asyncRequest('POST', 'san_products.php?Method=getShopCart', {success:success}, postData);
}


function delPayEl(si,pid,ucf){
	var shopcart = coke.get('shopcart',null);
	if(ucf){
		var ci = null
		for(x in payID){
			if(si==payID[x]){
				ci=x;
			}
		}
		payEl[ci].hide(true,.15,function(){
			payEl[ci].remove(true)
			payEl[ci] = null;
			countPrice();
		});
	}else{
		if(delShopCart(pid,true)){
			payEl[si].hide(true,.15,function(){
				payEl[si].remove(true)
				payEl[si] = null;
				countPrice();
			});
		}
	}
}

function countPrice(){
	var subprice = 0;
	var shopcart = coke.get('shopcart',null);

	if(shopcart==null){
		window.location=('index.php');
	}
	var shipprice = 150;
	
	var totalprice = 0;
	
	
	for(x=0;x<payEl.length;x++){
		if(payEl[x]){
			subprice = subprice + (parseInt(getEl('price['+x+']').dom.innerHTML)*parseInt(getEl('payCount['+x+']').dom.value));
			shopcart[payID[x]].Count = 1; //為了不要誤判為新增所以設為1
			addShopCart(payID[x],parseInt(getEl('payCount['+x+']').dom.value)-1,true) //這裡減 1;
		}
	}
	
	if(subprice >= 2000){
		shipprice = 0
	}else{
		shipprice = 150
	}
	
	
	if(subprice<1000){
		getEl('cantpay').show(true);
		getEl('payfor').hide(true);
	}else{
		getEl('payfor').show(true);
		getEl('cantpay').hide(true);
	}
	
	
	totalprice = parseInt(subprice) + parseInt(shipprice);
	
	getEl('totalprice').dom.innerHTML = totalprice;
	getEl('shipprice').dom.innerHTML = shipprice;
	getEl('subprice').dom.innerHTML = subprice;
}

function getPayList(id){
	var postData = 'ID='+id;
	var payList = getEl('paylist');
	var shopcart = coke.get('shopcart',null);
	
	var success=function(o){
		//payEl = new Array;
		var root = o.responseXML.getElementsByTagName('XMLOutput')[0];
   		var items = root.getElementsByTagName('item');
   		var count = root.getElementsByTagName('Count')[0].firstChild.nodeValue;

		if(count==0){
			//var el = dh.append(payList.dom,{tag:'span',cls:'noNewProduct',html:'本分類無產品'});
			return;
		}
		
		for(i=0;i<count;i++){
			
			var PID = items[i].getElementsByTagName('ID')[0].firstChild.nodeValue;
			payID[i] = PID;
			var CategoryID = items[i].getElementsByTagName('CategoryID')[0].firstChild.nodeValue;
			var ProductName = items[i].getElementsByTagName('ProductName')[0].firstChild.nodeValue;
			var DisplayPrice = items[i].getElementsByTagName('DisplayPrice')[0].firstChild.nodeValue;
			var Spec = items[i].getElementsByTagName('Spec')[0].firstChild.nodeValue;
			var RealPrice = items[i].getElementsByTagName('RealPrice')[0].firstChild.nodeValue;
			payEl[i] = dh.append(payList.dom,{tag:'span',cls:'NewProduct',html:
				'<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td class="shopping_3">'+
				'<table width="641" border="0" cellpadding="0" cellspacing="0"><tr><td width="180" height="30" class="shopping_2">'+
				'<a href="san_products.php?Method=more&CategoryID'+CategoryID+'&ID='+PID+'" class="link11">'+ProductName+'</a>'+
				'</td><td width="6" height="30" class="shopping_2">&nbsp;</td>'+
				'<td height="30" class="shopping_2">'+Spec+'</td>'+
                '<td width="10" height="30" class="shopping_2">&nbsp;</td>'+
                '<td width="145" height="30" class="shopping_2"><span id=price['+i+']>'+RealPrice+'</span></td>'+
                '<td width="4" height="30" class="shopping_2">&nbsp;</td>'+
				'<td width="95" height="30" class="shopping_2">'+
				'<input name="payCount['+i+']" id="payCount['+i+']" type="text" value="'+shopcart[PID].Count+'" class="products_input1">'+
				'</td><td width="4" height="30" class="shopping_2">&nbsp;</td><td width="56" height="30">'+
				'<a href="javascript:delPayEl('+i+','+PID+')"><img src="images/shopping_main2_33.jpg" width="56" height="20" border="0"></a></td></tr></table></td></tr><tr><td height="1" bgcolor="#A8A28E"></td></tr></table>',
				style:'visibility:hidden;'
			},true);
			
			payEl[i].show(true,.25);
		}
		countPrice();
	};
	YAHOO.util.Connect.asyncRequest('POST','san_shopping.php?Method=getShopCart',{success:success},postData);
}

function initShopCart(){
	var shopcart = coke.get('shopcart',null);
	
	if(getEl('paylist')){
		if(shopcart==null){
			alert('您的購物清單是空的..為您導至首頁');
			window.location=('index.php');
		}
		var payary = new Array();
		for(i in shopcart){
			if(shopcart[i].ID)payary.push(shopcart[i].ID);
		}
		getPayList(payary.join(','));
	}
	
	
	if(shopcart){
		for(i in shopcart){
			if(shopcart[i].ID)getShopCart(i);
		}
	}else{
		if(getEl('slist')){
			zeroCart = dh.append(getEl('slist').dom,
				{	
						tag:'span',
						html:'<table width="100%" border="0" cellspacing="0" cellpadding="0"><td class="quickly_1"><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>'+
							 '<td width="62%" valign="top" align="center" class="index_1">購物車是空的</td>'+
							 '</tr></table></td></tr><tr><td><img src="images/main_38.jpg" width="187" height="5" border="0"></td></tr></table>'
				},true)
		}
	}
}

YAHOO.ext.EventManager.onDocumentReady(initShopCart);
function PicZoomOut(){
	var el = getEl('FullView');
	var b = getEl('photo_line', true).getBox();
    proxy.show();
    proxy.setBounds(el.getX(), el.getY(), el.getWidth(), el.getHeight());
    el.hide();
    proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
		function(){
			proxy.hide();
			mask.hide();
			YAHOO.util.Dom.removeClass(document.body, 'masked');
		}.createDelegate(this)
	);

}



function CheckAddress(Node){
	
	var Area = getEl(Node.id.replace('_Addr','_Area'));
	var City = getEl(Node.id.replace('_Addr','_City'));
	var Addr = getEl(Node.id);
	var Flag = getEl(Node.id + '_Flag');
	
	if(Addr.dom.value.length){
		Addr.removeClass('faildField');
		Flag.removeClass('validNone');
	}else{
		Flag.addClass('validNone');
	}
	
}

function InsertOD(){
	var shopcart = coke.get('shopcart',null);
	var OL = new Array();
	var postArray = '';
	for(i=0;i<shopcart.length;i++){
		if(shopcart[i].ID){
			var tmp = shopcart[i].ID+','+shopcart[i].Count
			OL.push(tmp);
		}
	}
	OL = OL.join('|');
	
	YAHOO.util.Connect.setForm(getEl('payForm').dom);
	
	var success=function(o){
		if(o.responseText.substring(0,2)=='ok'){
			alert(o.responseText);
			coke.clear();
			coke.set('shopcart',null);
			window.location='san_shopping.php?Method=success&ID='+o.responseText.substring(2,o.responseText.length);
		}else{
			alert('錯誤:'+o.responseText);
		}
	}
	var ttPrice = parseInt(getEl('totalprice').dom.innerHTML);
	var postData = 'OL='+OL+'&TotalPrice='+ttPrice;
	YAHOO.util.Connect.asyncRequest('POST','san_shopping.php?Method=InsertOD',{success:success},postData);
}

function CheckHaveFill(node){
	var Flag = getEl(node.id+'_Flag');
	var Node =  getEl(node.id);
	if(node.value.length){
		Node.removeClass('faildField')
		Flag.removeClass('validNone')
	}else{
		Flag.addClass('validNone')
	}
}

function trackHistory(){
	var HistoryID = getEl('HistoryID');
	var success=function(o){
		if(o.responseText=='true'){
			var loc = window.location.toString();
			if(loc.indexOf('san_qmanage.php?Method=fts_show')!=-1){
				window.navigate('san_qmanage.php?Method=fts_show&HistoryID='+HistoryID.dom.value)
			}else{
				MM_openBrWindow('san_qmanage.php?Method=fts_show&HistoryID='+HistoryID.dom.value,'','scrollbars=yes,width=640,height=600,resizable=yes')
			}
		}else{
			alert('很抱歉查無此產銷履歷,請您重新輸入查詢編號!!');
		}

	}

	
	YAHOO.util.Connect.asyncRequest('GET','san_qmanage.php?Method=checkFTS&HistoryID='+HistoryID.dom.value,{success:success});

}