var common;
common = function(){
	var urllink = location.toString();
	var caseType = urllink.substring(urllink.lastIndexOf('\/')+1, urllink.lastIndexOf('.'));
	var obj = Ext.urlDecode(urllink.substring(urllink.lastIndexOf('?')+1, urllink.length));
	var tabImg = [['images/products_more_46.jpg','images/products_more_38.jpg','images/products_more_39.jpg'],
		['images/products_more_37.jpg','images/products_more_43.jpg','images/products_more_48.jpg']];
		
	function createComponents(v){ 
		var word = '';
		data = Ext.getDom(v).value.split('|');
		var i = 0;
		while(i < data.length){
			pic = data[i].split(',')
			word += ['<table width="100" border="0" align="left" cellpadding="0" cellspacing="0"><tr>',
				'<td width="100"><table width="86" border="0" cellpadding="0" cellspacing="3" bgcolor="#EFEFEF" onmouseover="common.MM_jumpOver(this)"><tr>',
				'<td width="80"><a href="'+pic[1]+'" rel="lightbox[roadtrip_up'+v+']"><img src="Thumb.php?ID='+pic[0]+'&amp;x=80&amp;y=80" width="80" height="80" border="0" /></a></td>',
				'</tr></table></td></tr>',
				'<tr><td><table width="100" border="0" cellpadding="0" cellspacing="0">',
				'<tr><td width="120" height="5"></td></tr>',
				'<tr><td><a href="'+pic[1]+'" rel="lightbox[roadtrip'+v+']"><img src="images/acessories_list_23.jpg" width="86" height="16" border="0" /></a></td>',
				'</tr></table></td></tr><tr><td>&nbsp;</td></tr></table>'].join('');
			i++;
		}
		return word;
	}
	
	function createInquiry(v){
		var word = v.length > 0 ? '' : '您目前沒有選擇您要諮詢的產品，請至產品介紹頁面選擇您要諮詢的產品';
		var i = 0;
		while(i < v.length){
			var link = v[i].Type == 'products' ? v[i].Type+'.php?Type=more&KindID='+v[i].CategoryID+'&ID='+v[i].ID : v[i].Type+'.php?KindID='+v[i].CategoryID+'&ID='+v[i].ID;
			word += i % 2 == 0 ? '<div class="customer_inquiry_div1">' : '<div class="customer_inquiry_div1-2">';
			word += ['<table width="330" border="0" cellspacing="0" cellpadding="0"><tr>',
				'<td width="118"><table width="118" border="0" align="left" cellpadding="0" cellspacing="5"><tr>', 
				'<td width="80"><a href="'+link+'"><img src="inquiryPic.php?ID='+v[i].Img+'" width="80" height="80" border="0" /></a></td>', 
				'<td width="23" background="images/customer_inquiry_24.jpg">&nbsp;</td></tr></table></td>', 
				'<td valign="bottom"><table width="212" border="0" cellspacing="0" cellpadding="0"><tr>', 
				'<td height="66" align="left" valign="middle" class="customer_inquiry_div2"><a href="'+link+'" class="link_011customer">'+v[i].ProductNumber+'</a><br />', 
				v[i].ProductName+'</td></tr>', 
				'<tr><td height="14" align="right"><a href="javascript:common.delInquiry(\''+v[i].ID+'\', \''+v[i].Type+'\', '+v[i].Rownum+')"><img src="images/customer_inquiry_28.jpg" width="49" height="14" border="0" /></a></td></tr></table></td></tr></table></div>'].join('');
			i++;
		}
		return word;
	}
	
	return {
		backupPic: null,
		tabContent: [],
		msgCt: [],
		showRun: [],
		
		init: function(){
			var display = Ext.query('div[class=customer_div3-3]');
			for(i=0;i<display.length;i++){
				display[i].style.height = 0;
				display[i].style.display = 'none';
			}
			var accessories = Ext.query('td[id=wdaccessories'+obj.ID+']');
			for(i=0;i<accessories.length;i++){
				Ext.get(accessories[i]).replaceClass('products_more_td_tb1-2', 'products_more_td_tb1-3');
				Ext.get(accessories[i]).parent().parent().parent().parent(null, true).background = 'images/acessories_list_25.jpg';
			}
			if(Ext.get('keyword')){
				var textf = Ext.getDom('keyword');
				var thename = new Ext.form.TextField({
					emptyText: textf.value,
					fieldClass: '',
					invalidClass: '',
					emptyClass: '',
					focusClass: '',
					value: '',
					applyTo: textf.id
				});
				this.searchField = thename;
				thename.getEl().removeClass('x-form-text')
				thename.getEl().removeClass('x-form-empty-field')
				thename.getEl().addKeyListener({key:13},function(){
					this.gotosearch('keyword', 'sType');
				},this);
			}
			if(Ext.get('tabContent')){
				this.tabContent[0] = Ext.getDom('tabContent').innerHTML;
				if(this.tabContent[0] != ''){
					this.showTabLink(0);
				}else{
					tab = Ext.getDom('tabValue').value.split('|');
					if(tab[0] != '*')
						this.showTabLink(1);
					else
						this.showTabLink(2);
				}
			}
			if(Ext.get('inquiryList')){
				var cb = function(a,success,rspn){
					if(success){
						var value = eval(rspn.responseText);
						Ext.get('inquiryList').update(createInquiry(value));
						Ext.get('inquiryList').show(true);
						if(value.length == 0)
							Ext.get('inquiryed').parent().next().remove(true);
							Ext.get('inquiryed').remove(true);
					}
				}
				var cn = new Ext.data.Connection({url:"getdata.php?Type=listInquiry"}).request({
					scope: this, 
					method: "POST", 
					callback:cb
				});
			}
		},
		
		showTabLink: function(index){
			if(index < 3){
				tab = Ext.getDom('tabValue').value.split('|');
				for(var i=0;i<3;i++){
					Ext.getDom('menuTab'+i).onclick = null;
					Ext.get('menuTab'+i).removeClass('x-combo-noedit');
					if(i == index){
						Ext.getDom('menuTab'+i).src = tabImg[1][i];
					}else{
						Ext.getDom('menuTab'+i).src = tabImg[0][i];
						if(i == 0 && this.tabContent[0] != ''){
							Ext.getDom('menuTab'+i).onclick = function(){common.showTabLink(0)};
							Ext.get('menuTab'+i).addClass('x-combo-noedit');
						}else if(i == 1 && tab[0] != '*'){
							Ext.getDom('menuTab'+i).onclick = function(){common.showTabLink(1)};
							Ext.get('menuTab'+i).addClass('x-combo-noedit');
						}else if(i == 2 && tab[1] != ''){
							Ext.getDom('menuTab'+i).onclick = function(){common.showTabLink(2)};
							Ext.get('menuTab'+i).addClass('x-combo-noedit');
						}
					}
				}
				this.condition = tab;
				this.tabContext(Ext.get('tabContent'), index);
			}else{
				Ext.get('allTab').remove();
			}
		},
		
		tabContext: function(el, num){
			el.update('');
			el.addClass("loading-indicator");
			el.setStyle({"background-position": "50%", "height": "100px"});
			if(this.tabContent[num] == null){
				var cb = function(a,success,rspn){
					if(success){
						var value = eval(rspn.responseText);
						if(value.length == 0){
							this.showTabLink(num+1);
						}else{
							this.tabContent[num] = num == 2 ? this.faqWhile(value) : this.correlationWhile(value);
							this.fancy(el, this.tabContent[num]);	
						}					
					}
				}
				var cn = new Ext.data.Connection({url:"getdata.php?Type=tab"+num}).request({
					scope: this, 
					method: "POST", 
					params: {"paramID": this.condition[num-1]}, 
					callback:cb
				});
			}else{
				this.fancy(el, this.tabContent[num]);
			}
		},
		
		changeImage: function(num){
			var ci = Ext.getDom('Img').value.split(',');
			var spic = Ext.get('spic'+num);
			if(this.backupPic != null)
				this.backupPic.replaceClass('product_more_div2','product_more_div1');
			else
				Ext.get('spic1').replaceClass('product_more_div2','product_more_div1');
			spic.replaceClass('product_more_div1','product_more_div2');
			Ext.get('bgimg').update('<img src="'+ ci[num-1] +'" width="342" height="342" style="display:none;" />',true);
			Ext.get('bgimg').child('img').show({duration:.5});
			this.backupPic = spic;
		},
		
		gotosearch: function(theid, select){
			var keyword = Ext.getDom(theid).value.trim();
			var stype = Ext.getDom(select);
			var sv = stype.value;
			var link = 'products'
			if(sv == ''){
				alert(stype.options[stype.selectedIndex].text);
			}else{ 
				if(sv.indexOf('Products') != -1){
					sv = sv.replace('Products', '');
				}else{
					sv = sv.replace('Components', '');
					link = 'accessories';
				}
				if (this.searchField.getRawValue().trim() == ""){
					var kind = sv == '' ? '' : '?Type=list&KindID='+sv;
					var strURL= link+".php"+kind;
					location.href=strURL;
				}else{
					var kind = sv == '' ? '' : '&KindID='+sv;	
					keyword = encodeURIComponent(keyword);
					var strURL= link+".php?Type=search"+kind+"&Keyword="+keyword.trim();
					location.href=strURL;
				}
			}
		},
		
		fancy: function(el, value){
			el.hide();
			el.removeClass("loading-indicator");
			el.stopFx();
			el.update(value, true);
			el.autoHeight(true);
			el.fadeIn({
			    endOpacity: 1, 
			    easing: 'easeBoth',
			    duration: 1
			})
		}, 
		
		fadeIn: function(num){
			var question = Ext.get('question'+num);
			var ans = Ext.get('ans'+num);
			question.parent().setOpacity(0);
			ans.dom.style.display = 'none';
			ans.setHeight(0);
			question.replaceClass('customer_div3-2','customer_div2-2');
			question.parent().replaceClass('customer_div3','customer_div2');
			question.first().removeClass('link_03customer');
			question.first(null,true).href = "javascript:common.fadeOut("+num+")";
			question.parent().setOpacity(1, true);
		},
		
		fadeOut: function(num){
			var question = Ext.get('question'+num);
			var ans = Ext.get('ans'+num);
			question.parent().setOpacity(0);
			ans.dom.style.display = 'block';
			ans.autoHeight();
			question.replaceClass('customer_div2-2','customer_div3-2');
			question.parent().replaceClass('customer_div2','customer_div3');
			question.first().addClass('link_03customer');
			question.first(null,true).href = "javascript:common.fadeIn("+num+")";
			question.parent().setOpacity(1, true);
		},
		
		faqWhile: function(store){
			var tpl = new Ext.XTemplate(
				'<tpl for=".">',
					'<div class="customer_div2">',
					'<div class="customer_div2-2" id="question{#}"><a href="javascript:common.fadeOut({#})">{Question}</a></div>',
					'<div class="customer_div3-3" id="ans{#}" style="display:none;height:0px">',
					'<div class="customer_div3-4">{Answer}',
					'</tr></table></div>',
					'</td></tr><tr><td>',
					'<div class="support_list_div2" id="ans{#}">',
					'<div class="customer_div3-5"><a href="javascript:common.fadeIn({#})"><img src="images/customer_29.jpg" width="51" height="19" border="0" /></a></div>',
					'<br /></div></div></div>',
				'</tpl>'
			);
			var word = store.length > 0 ? tpl.apply(store) : '';
			return word;
		},
		
		correlationWhile: function(store){
			var tpl = new Ext.XTemplate(
				'<table width="100%" border="0" cellspacing="0" cellpadding="0">',
				'<tr><td>&nbsp;</td></tr><tr><td align="left" valign="top">',
				'<tpl for=".">',
					'<div class="products_list_div{Div}">',
					'<table border="0" cellpadding="0" cellspacing="0"><tr>',
					'<td width="149" align="left" valign="top"><a href="{Link}">',
					'<img src="{Img}" width="149" height="149" border="0" /></a></td>',
					'<tpl if="Div == 1">',
					'<td width="33" rowspan="3" align="left" valign="top" background="images/products_list_21.jpg">&nbsp;</td>',
					'</tpl>',
					'</tr><tr><td height="10" align="left" valign="top"></td></tr>',
					'<tr><td height="70" align="left" valign="top">',
					'<a href="{Link}" class="link_09products">{ProductNumber}</a><br />',
					'{ProductName}...<a href="{Link}" class="link_06products">VIEW<br />',
					'<br /></a></td>',
					'</tr></table></div>',
				'</tpl>',
				'</td></tr><tr><td>&nbsp;</td></tr></table>'
			);
			var word = store.length > 0 ? tpl.apply(store) : '';
			return word;
		}, 
		
		MM_jumpOver: function(divtable){
			if(this.backupPic != null){
				this.backupPic.bgColor = '#EFEFEF';
			}
			divtable.bgColor = '#803FD7';
			this.backupPic = divtable;
		},
		
		MM_photoOver: function(divtable){
			dt = Ext.get(divtable);
			if(this.backupPic != null){
				this.backupPic.replaceClass('career_album_div1-3', 'career_album_div1-2');
			}
			dt.replaceClass('career_album_div1-2', 'career_album_div1-3');
			this.backupPic = dt;
		},
		
		addInquiry: function(num, rownum){
			var cb = function(a,success,rspn){
				if(success){
					//Ext.MessageBox.confirm('Confirm', Ext.getDom('pdtName'+num).innerHTML + ' 加入您的詢價清單.<br> 您確定要詢價嗎？', function(btn){
						//if(btn == 'yes')
							//window.location.href = "customer.php?Type=inquiry";
							window.location.href = "customer.php?Type=inquiryed";
					//}, this);
				}
			}
			var cn = new Ext.data.Connection({url:"getdata.php?Type=addInquiry"}).request({
				scope: this, 
				method: "POST", 
				params: {"paramID": num, "paramTable": caseType, "rownum": rownum}, 
				callback:cb
			});
		}, 
		
		delInquiry: function(num, table, rownum){
			var cb = function(a,success,rspn){
				if(success){
					var value = eval(rspn.responseText);
					Ext.get('inquiryList').update(createInquiry(value));
					Ext.get('inquiryList').show(true);
					if(value.length == 0)
						Ext.get('inquiryed').parent().next().remove(true);
						Ext.get('inquiryed').remove(true);
				}
			}
			var cn = new Ext.data.Connection({url:"getdata.php?Type=delInquiry"}).request({
				scope: this, 
				method: "POST", 
				params: {"paramID": num, "paramTable": table, "rownum": rownum}, 
				callback:cb
			});
		},
		
		
		showComponents: function(num){
            if(this.showRun[num] == null){
            	this.msgCt[num] = Ext.get('showDisplay'+num);
				this.showRun[num] = Ext.DomHelper.append(this.msgCt[num].first(), {
					html:createComponents('acc'+num),
					style: {'height': '0px', 'display': 'none'}}, 
					true);
            }
            this.showRun[num].autoHeight({
            	afterStyle: {'display': 'block', 'height': 'auto', 'visibility': 'visible'},
            	useDisplay: true
            });
            this.showRun[num].dom.style.display = 'block';
            this.showRun[num].dom.style.visibility = 'visible';
//            this.showRun[num].slideIn('t', {
//            	afterStyle: {'display': 'block', 'height': 'auto'}, 
//            	callback : function(){common.showRun[num].dom.style.display = 'block';}
//            });
            Ext.getDom('show_1'+num).onclick = function(){common.hideComponents(num, this)};
            Ext.getDom('show_2'+num).onclick = function(){common.hideComponents(num, this)};
		},
		
		hideComponents: function(num){
            this.showRun[num].slideOut('t', {
            	afterStyle: {'display': 'none', 'height': '0px'}, 
            	callback : function(){common.showRun[num].dom.style.display = 'none';}
            });
            Ext.getDom('show_1'+num).onclick = function(){common.showComponents(num, this)};
            Ext.getDom('show_2'+num).onclick = function(){common.showComponents(num, this)};
		}
	}
}();

Ext.onReady(common.init, common);
