var buyinlist;

buyinlist = function(){
	var msgCt;
	var pdtID = "";
	var pdtName = "";
	var getlist = null;
	var checklist = null;
	
	function changeTotal(theid,addamount){
		var totalmoney = 0;
		var totalamount = 0;
		var freight = 0;
		var finalmoney = 0;
		for (var i=1; i < fcount+1; i++) {
			var paylist = getlist.getAt(i-1).data;
			var cmv = paylist.amount*paylist.RealPrice;
			totalmoney += cmv;
			totalamount += parseInt(paylist.amount);
			if(paylist.ID == theid){
				Ext.get('money'+theid).dom.innerHTML = MoneyFormat(cmv);
				Ext.get('amount'+theid).dom.onblur = function(){buyinlist.ChangeValue(theid,addamount);}
			}
		}
		var freightstyle = Ext.get('FreightStyle').dom;
		if(totalmoney >= Ext.get('FreightLimit').dom.value){
			freight = (totalamount - 1) * parseInt(Ext.get('FreightMoney').dom.value);
			freightstyle.style.color = 'red';
			freightstyle.style.fontWeight = 'bold';
			freightstyle.innerHTML = '(可抵 ' + Ext.get('FreightMoney').dom.value + ' 元)';
		}else{
			freight = totalamount * parseInt(Ext.get('FreightMoney').dom.value);
			freightstyle.style.color = 'black';
			freightstyle.style.fontWeight = 'normal';
			freightstyle.innerHTML = '';
		}
		finalmoney = totalmoney + freight;
		Ext.get('Freight').dom.innerHTML = '運費共 ' + Ext.get('FreightMoney').dom.value + ' * ' + (totalamount - 0) + ' (箱) = ' + MoneyFormat(parseInt(Ext.get('FreightMoney').dom.value) * totalamount);
		Ext.get('TotalMoney').dom.innerHTML = MoneyFormat(totalmoney);
		Ext.get('FinalTotal').dom.innerHTML = MoneyFormat(finalmoney);
	}
	
	function taf(text){
		if (text == "" || text == 0){
			alert('你尚未填入數量');
			return false;
		}else if (isNaN(text) === false){
			if (parseInt(text) <= 0){
				alert('您填寫的單位有誤');
				return false;
			}else if (parseInt(text) > 0){
				return true;
			}
		}else if (isNaN(text) === true){
			alert('您填寫的單位有誤');
			return false;
		}
	}
	
	function createBox(t, s){
        return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    }
	
	function getview(thetype,theid,theamount){
		var urlvalue = "";
		if(thetype){
			urlvalue = 'getview.php?Type='+thetype+'&ID='+theid+'&Amount='+theamount;
		}else{
			urlvalue = 'getview.php';
		}
		return search_tabledata = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({url: urlvalue}),
			reader: new Ext.data.JsonReader({
				root: 'results',
				totalProperty: 'total',
				id: 'ID'
			},[ 'ID', 'CategoryID', 'ProductName', 'Spec', 'amount', 'RealPrice']),
			remoteSort: false
		});
	}
	
	function MoneyFormat(value){
		value = value.toString()
		var newvalue = "";
		for (var i=value.length; i > 0;i=i-3){
			var j = (i-3 > 0) ? i-3 : 0 ;
			newvalue = ',' + value.substring(j,i) + newvalue;
		}
		return newvalue.replace(',','');
	}
	
	function creatlist(type){
		var listhtml = '';
		fcount = getlist.getCount(getlist);
		if(fcount > 0){
			for (var i=1; i < fcount+1; i++) {
				var listunit = getlist.getAt(i-1).data;
				if (type == 'slist'){
					listhtml += listbox1(listunit);
				}else if(type == 'checklist'){
					var thed = '<input name="textfield" type="text" class="vip_mellcenter_div_input_1" id="amount'+listunit.ID+'" value="'+listunit.amount+'" onblur="buyinlist.ChangeValue('+listunit.ID+','+listunit.amount+')" />';
					listhtml += listbox2(listunit,thed,type);
				}else if(type == 'checklisted'){
					var thed = listunit.amount;
					listhtml += listbox2(listunit,thed,type);
				}
			}
		}else{
			if (type == 'slist'){
				listhtml = '<div class="shoppinglist_div_3" align="center">購物車是空的</div>';
			}else if(type == 'checklist'){
				listhtml = '<div class="vip_mellcenter_td_1" align="center" style="width:100%;">購物車是空的</div>';
				Ext.get('ifnopdt').hide(true);
				Ext.get('listbuttom1').hide(true);
				Ext.get('listbuttom2').hide(true);
			}else if(type == 'checklisted'){
				listhtml = '<div class="vip_mellcenter_td_1" align="center" style="width:100%;">購物車是空的</div>';
				Ext.get('ifnopdt').hide(true);
				window.location='products.php';
			}
		}
		Ext.get(type).dom.innerHTML = "";
		zeroCart = Ext.DomHelper.append(Ext.get(type).dom,
		{	
			tag:'span',
			html:listhtml,
			style:'visibility:hidden;'
		},true)
		zeroCart.show(true);
	}
	
	function listbox1(paylist){
		return ['<div class="shoppinglist_div_3">',
				'<div class="shoppinglist_div_4"><a href="products_more.php?ID='+paylist.ID+'&KindID='+paylist.CategoryID+'" class="main_B">'+paylist.ProductName+'('+paylist.amount+')</a></div>',
				'<div class="shoppinglist_div_5"><a href="javascript:buyinlist.delbuypdt('+paylist.ID+',\''+paylist.ProductName+'\', \'slist\')" class="main_C">刪除</a></div>',
				'</div>'].join('');
	}
	
	function listbox2(paylist,thed,type){
		var spec = (paylist.Spec != null)?paylist.Spec:'';
		var total = paylist.amount*paylist.RealPrice;
		return ['<table width="617" border="0" cellpadding="0" cellspacing="0">',
                    '<tr>',
                      '<td width="617"><table width="617" border="0" cellpadding="0" cellspacing="0">',
                        '<tr>',
                          '<td width="178" class="vip_mellcenter_td_1"><a href="products_more.php?ID='+paylist.ID+'&KindID='+paylist.CategoryID+'">'+paylist.ProductName+'</a></td>',
                          '<td width="6">&nbsp;</td>',
                          '<td width="86" align="center" class="vip_mellcenter_td_1">'+spec+'</td>',
                          '<td width="6" align="center">&nbsp;</td>',
                          '<td width="56" align="center" class="vip_mellcenter_td_1">'+thed+'</td>',
                          '<td width="6" align="center">&nbsp;</td>',
                          '<td width="74" align="center" class="vip_mellcenter_td_1">'+MoneyFormat(paylist.RealPrice)+'</td>',
                          '<td width="6" align="center">&nbsp;</td>',
                          '<td width="78" align="center" class="vip_mellcenter_td_1" id="money'+paylist.ID+'">'+MoneyFormat(total)+'</td>',
                          '<td width="6">&nbsp;</td>',
                          '<td align="center" class="vip_mellcenter_td_1"><a href="javascript:buyinlist.delbuypdt('+paylist.ID+',\''+paylist.ProductName+'\', \''+type+'\')"><img src="images/mallcenter_check_26.jpg" width="41" height="21" border="0" /></a></td>',
                        '</tr>',
                      '</table></td>',
                    '</tr>',
                    '<tr>',
                      '<td><img src="images/mallcenter_check_27.jpg" width="617" height="8" /></td>',
                    '</tr>',
                  '</table>'].join('');
	}
	
	return {
		init : function(){
			if(Ext.get('keyword')){
				var thename = new Ext.form.TextField({
					emptyText:'請輸入商品名稱',
					fieldClass:'',
					invalidClass:'',
					emptyClass:'',
					focusClass:''
				});
				thename.applyTo(Ext.get('keyword'));
				thename.getEl().removeClass('x-form-text')
				thename.getEl().removeClass(' x-form-empty-field')
			}
			
			if(Ext.get('slist')){
				getlist = getview();
				getlist.on('load', function() {
					creatlist('slist');
				});	
				getlist.load();
			}
			if(Ext.get('checklist')){
				getlist = getview();
				getlist.on('load', function() {
					creatlist('checklist');					
				});
				getlist.load();
			}
			if(Ext.get('checklisted')){
				getlist = getview();
				getlist.on('load', function() {
					creatlist('checklisted');					
				});
				getlist.load();
			}
		},
		
		msg : function(title, format){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst('CallButtom', {id:'msg-div'}, true);
            }
            msgCt.alignTo(document, 't-c');
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
            m.slideIn('t').pause(2).ghost("t", {remove:true});
        },
		
		buychick: function(productid,productname){
			pdtID = productid;
			pdtName = productname;
			Ext.MessageBox.prompt(productname, '請輸入您要購買的數量:', this.showResultText);
		},
		
		showResultText: function(btn, text){
			this.taf = taf(text);
			if (btn == 'ok' && this.taf === true){
				getlist = getview('ADD',pdtID,text);
				getlist.on('load', function() {
					creatlist('slist');
				});	
				getlist.load();
				buyinlist.msg('置物完成', '您選了{0}單位的"{1}"至你的購物車', text, pdtName);
			}
		},
		
		addbuypdt: function(theid, thename){
			var addamount = Ext.get('amount').dom.value
			this.taf = taf(addamount);
			if(this.taf === true){
				getlist = getview('ADD', theid, addamount);
				getlist.on('load', function() {
					creatlist('slist');
				});	
				getlist.load();
				buyinlist.msg('置物完成', '您選了{0}單位的"{1}"至你的購物車', addamount, thename);
			}
		},
		
		delbuypdt: function(theid, thename, type){
			if(confirm('是否確定要刪除'+thename)){
				getlist = getview('DEL',theid,'');
				getlist.on('load', function() {
					creatlist(type);
					if(type == 'checklist'){
						changeTotal(theid);
					}else if(type == 'checklisted'){
						changeTotal(theid);
					}
				});	
				getlist.load();
				buyinlist.msg('刪除完成', '您取出"{0}"於你的購物車', thename);	
			}
		},
		
		ChangeValue: function(theid,amount){
			var test = Ext.get('Remark').dom.innerHTML;
			test = test.replace("CHR(10)","<br>");
			var addamount = Ext.get('amount'+theid).dom.value;
			this.taf = taf(addamount);
			if (addamount != amount && this.taf === true){
				getlist = getview('EDIT', theid, addamount);
				getlist.on('load', function() {
					changeTotal(theid,addamount);
				});	
				getlist.load();
			}else{
				Ext.get('amount'+theid).dom.value = amount;
			}
		}
	};
}();

Ext.onReady(buyinlist.init, buyinlist);

function gotosearch(){
	var keyword = Ext.get('keyword').dom.value;
	if (keyword == "" || keyword == "請輸入商品名稱"){
		alert('您尚未輸入任何商品名稱');
	}else{
		keyword = encodeURIComponent(keyword);
		var strURL="products_searched.php?keyword="+keyword;
		location.href=strURL;
	}
}

function WordOpenAnsBox(no){
	var OpenIdname = "AnswerBox"+no;
	var HideDIV = document.getElementById(OpenIdname);
	if (HideDIV.style.visibility == 'hidden' || HideDIV.style.visibility == ''){
		HideDIV.style.visibility='visible';
		HideDIV.style.height='auto';
		HideDIV.style.overflow='visible';
	}else{
		HideDIV.style.visibility='hidden';
		HideDIV.style.height='1px';
		HideDIV.style.overflow='hidden';
	}
}

function cancelOrder(orderID){
		var cn = new Ext.data.Connection({url: 'getview.php?Type=CancelOrder'})
		cn.request({
        	params : { ID:orderID}, 
        	scope: this
        });
		var strURL = "vip.php?Type=history";
		location.href = strURL;
}

function PicZoomIn(pic){
	var imgx, imgy, maskx, masky;
	var NewImg = Ext.get('FullView');
	if(!NewImg){
		NewImg = Ext.DomHelper.append(document.body,{tag:'img',src:pic,ID:'FullView',cls:'FullView'},true);
		proxy = NewImg.createProxy('FVProxy');
		themask = Ext.DomHelper.append(document.body, {tag: 'div',ID:'Mask', cls:'ydlg-mask'}, true);
        themask.enableDisplayMode('block');
	}
	var ns = (navigator.appName.indexOf("Netscape") != -1) || window.opera;
	if(!ns){
		imgx = document.documentElement.clientWidth/2 ;
		imgy = document.documentElement.scrollTop + document.documentElement.clientHeight/2;
		maskx = document.body.clientWidth;
		masky = document.body.clientHeight;
	}else{
		imgx = window.innerWidth/2;
		imgy = window.innerHeight/2;
		maskx = window.innerWidth;
		masky = window.innerHeight;
	}
	NewImg.setXY([imgx - NewImg.getWidth()/2,imgy - NewImg.getHeight()/2]);
	NewImg.on('click',PicZoomOut,this,true);
	
	
	themask.hide();

	
	YAHOO.util.Dom.addClass(document.body, 'masked');
	themask.setSize(maskx, masky);
	themask.show();

	
	var b = Ext.get('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)
	);
}

function PicZoomOut(){
	var el = Ext.get('FullView');
	var b = Ext.get('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();
			themask.hide();
			YAHOO.util.Dom.removeClass(document.body, 'masked');
		}.createDelegate(this)
	);

}
