/**
 * @(#)library/lib_moreinfo.js
 *
 * Copyright 1999-2007(c) MijnWinkel B.V.
 *
 * Version 7.10.0 7-nov-2007
 */

function getItemIndex(count,oid,cid){
	if(cid==null)cid=getCID();
	if(oid==null)oid=getOID();
	else{
		var i=(""+oid).indexOf("__");
		if(i!=-1)oid=oid.substr(i+2);
	}
	if(count==null&&self.getActiveRow)count=getActiveRow();
	return cid+"."+oid+"."+count;
}
var itemStock={
	"set":function(v){
		var n=getItemIndex();
		itemStock["list"][n]=v;
		return v
	},
	"get":function(def,oid,basketCorrection){
		if(basketCorrection==null)basketCorrection=true;
		var id=getItemIndex(null,oid);
		v=itemStock["list"][id];
		if(v==null){
			v=def;
			itemStock["list"][id]=v;
		}
		if(!isNaN(v)){
			var n=_i(v);
			if(n==parseFloat(v))v=n;
			if(basketCorrection)v-=(self.getBasketInfo)?getBasketInfo().getProductQuantity(oid,getCID()):0;
		}
		return v
	},
	"list":[]
}

function doFlush(e){
	if(!e)e=window.event;
	return(e.keyCode!=13);
}

function refreshProduct(){
	
	var c=getElementOnId("myshp-header");
	if(c)c.innerHTML=headerInner();
	c=getElementOnId("myshp-product");
	if(c)c.innerHTML="<table cellspacing=0 cellpadding=2 width=100% border=0><tr><td>"+buildBlock(getNrOfFields())+"</td></tr></table>";
}

function refreshReleadtedProduct(){
	relatedBuildBlock(getNrOfFields(),_rel);
}

function refreshReladtedProductInner(){
	var c=getElementOnId("myshp-related"+_rel.active);
	if(c)c.innerHTML=relatedBuildBlockInner(getNrOfFields(),_rel);
}

function setRaw(n,v){
	n=_i(n);
	if(__rowData!=null&&n<__rowData.length)__rowData[n]=v
}

function Related(){
	var me=this,buf=[],lst,flds=[];
	me.reset=function(){
		me.count=0;
		me.index=0;
		me.active=0;
		lst=[];
	};
	me.clear=function(){
		lst=null;
		var c=getElementOnId("myshp-related");
		if(c)c.innerHTML="";
		buf=[];
		self._stc=null;
		flds=[];
		//if(_relData)_relData.clear();
	};
	me.append=function(){for(var i=0,p=me.append.arguments,n=p.length;i<n;i++)buf.push(p[i])};
	me.toString=function(s){return buf.join("")};
	me.add=function(v){lst[lst.length]=v};
	me.enabled=function(){return lst!=null&&lst.length>0}
	me.increment=function(){
		me.count++;
		me.active=me.count;
	};
	me.hasNext=function(){return(lst!=null&&me.index<lst.length)};
	me.next=function(){return lst[me.index++]};
	me.isFirst=function(){return me.index==0};
	me.redraw=function(){
		var c=getElementOnId("myshp-related");
		if(c)c.innerHTML=_rel.toString();
	};
	me.setStock=function(v){
		if(self._stc==null)self._stc=[];
		_stc[__rowData[0]]=v;
	};
	me.fldAdd=function(n){
		for(var i=1;i<_m.length;i++)if(_m[i][0]==n){
			flds[i]=1;
			break;
		}
	};
	me.show=function(i){return flds[i]}
	me.reset();
	me.init=function(){
		if(self.RelatedData&&self._stc){
			var i=0,d=new RelatedData(),l=d.count();
			for(;i<l;i++)_stc[d.getOid(i)]=d.getStock(getCID(),i);
		}
	};
	me.ClassName="Related";
}
var _rel=new Related();


/*
 * Load the next related product or show the product list if the last is loaded.
 */
function nextRelated(){
	if(_rel.enabled()){
		if(_rel.isFirst())relatedHeader();
		if(_rel.hasNext())new Remote().request(this.response2,"catalog_item_data","_oid",_rel.next());
		else{
			relatedFooter();
			_rel.redraw();
		}
	}
}

/*
 * Field selection base class, used to create on the fly field 
 * selection objects.
 */
function FieldSelection(){
	var me=this,fld=[],fldsel=[];
	me.set=function(col,lst){fld[col]=lst};
	me.setActive=function(col,v){fldsel[col]=v};
	me.get=function(i){return fld[i]};
	me.active=function(i){return fldsel[i]};
}

function parseDocument(doc,rel){

	function get(c){
		var v="";
		try{v=c.firstChild.nodeValue}
		catch(e){}
		return v
	}
	function getAttr(c,n){
		var v="";
		try{v=c.getAttribute(n)}
		catch(e){}
		return v
	}
	function getCols(r){return r.getElementsByTagName('col')}
	 
	var index=0,rows=doc.getElementsByTagName('row'),type,done=[];
	
	for(;index<rows.length;index++){
		row=rows[index];
		type=row.getAttribute("type")
	 	if(!done[type]&&type=="catalog"){
	 		done[type]=true;
			var cols=row.getElementsByTagName('col'),s="",v,item=[],l=cols.length,c,node;
			item[0]=row.getAttribute("number");
			for(var i=0;i<l;i++){
				node=cols[i].firstChild;
				if(node!=null){
					v=node.nodeValue;
					if(v)item[i+1]=v;
					else item[i+1]="";
				}
			}
			setCtlVal("_oid",_i(item[0]+1));
			_d[0]=item;
			__rowData=_d[0];
			__activeRow=0;
			__catalog[_i(item[0])]=item;
			
		}
		else if(!done[type]&&type=="catalog_nav"){
	 		done[type]=true;
			var cols=getCols(row),v,l=cols.length,c,t;
			for(var i=0;i<l;i++){
				c=cols[i];
				v=get(c);
				t=getAttr(c,"type");
				if(t=="next")_inf['oidnext']=v;
				else if(t=="prev")_inf['oidprev']=v;
			}
		}
		else if(!done[type]&&type=="catalog_replace"){
	 		done[type]=true;
			var cols=row.getElementsByTagName('col'),l=cols.length,n,c,i=0,node;
			for(;i<l;i++){
				c=cols[i];
				n=c.getAttribute("number");
				node=c.firstChild;
				if(node!=null){
					v=node.nodeValue;
					if(v!=null&&v!='*'){
						if(n)setRaw(n,v);
						else{
							n=c.getAttribute("name");
							if(n&&n=="stock"){
								_rel.setStock(v);
								itemStock.set(v);
								setRaw(getStockFld(),itemStock.get(v,getOID(),true));
							}
						}
					}
				}
			}
		}
		else if(type=="catalog_selection"){
			if(this.selection)selection.reset();
			var cols=row.getElementsByTagName('col'),l=cols.length,col,i=0,opts,optsl,opti,opt,node,oid=_i(row.getAttribute("number"))+1;
			var info=new FieldSelection(),val;
			_fs[oid]=info;
			for(;i<l;i++){
				col=cols[i];
				colNr=cols[i].getAttribute("number");
				opts=cols[i].getElementsByTagName('option');
				optsl=opts.length;
				var lst=[],sel="";
				for(opti=0;opti<optsl;opti++){
					opt=opts[opti];
					node=opt.firstChild;
					if(node!=null){
						lst[opti]=node.nodeValue;
						if(sel==""&&opt.getAttribute("selected")){
							sel=opt.getAttribute("inline");
							if(sel=="")sel=lst[opti];
						}
					}
				}
				lst[optsl]="";
				info.set(colNr,lst);
				info.setActive(colNr,sel);
			}
		}
		else if(!done[type]&&type=="catalog_localstock"){
	 		done[type]=true;
			var cols=row.getElementsByTagName('col'),l=cols.length,n,c,i=0,node;
			for(;i<l;i++){
				c=cols[i];
				node=c.firstChild;
				if(node!=null){
					v=_i(node.nodeValue);
					if(v!=null&&v!='*'){
						//setRaw(getStockFld(),v);
						_rel.setStock(v);
						itemStock.set(v);
						setRaw(getStockFld(),itemStock.get(v,getOID(),true));
					}
				}
			}
		}
		else if(rel&&type=="catalog_related"){
			var cols=row.getElementsByTagName('col'),l=cols.length,i=0,node;
			if(l>0){
				_rel.reset();
				for(;i<l;i++){
					node=cols[i].firstChild;
					if(node!=null)_rel.add(node.nodeValue);
				}
			}
		}
		else if(!done[type]&&type=="catalog_related_fields"){
			done[type]=true;
			var cols=row.getElementsByTagName('col'),node;
			if(cols)for(var l=cols.length,i=0;i<l;i++){
				node=cols[i].firstChild;
				if(node!=null)_rel.fldAdd(node.nodeValue);
			}
		}
	}
}

function response3(doc){
	if(doc){
		parseDocument(doc,false);
		refreshReladtedProductInner();
	}
}
function response2(doc){
	if(doc){
		parseDocument(doc,false);
		refreshReleadtedProduct();
		nextRelated();
	}
}
function response(doc){
	if(doc){
		 _rel.clear();
		parseDocument(doc,true);
		refreshProduct();
		nextRelated();
	}
}

function Remote(filter){
	var me=this,req=null,callback=null;
	if(filter==null)filter=false;
	
	function val(f,i){
		var v=f[i].value;
		if(v!=null&&v!="")v=v.replace("+","%2b");
		return v
	}
	me.request=function(cb,type){
		var qs,q=new QueryString(),f=getData(),i=0,l,argl=me.request.arguments;
		if(cb&&f){
			l=f.length;
			for(;i<l;i++){
				var n=f[i].name,add=true;
				if(filter)add=(n!="s"&&n!="c");
				if(add)q.set(n,val(f,i));
			}
			l=argl.length;
			for(i=2;i<l;i+=2)q.set(argl[i],argl[i+1]);
			q.set('type',type);
			q.set('aid',getAID(1));
			qs=q.getQueryString();
			callback=cb;
			if(window.XMLHttpRequest)req=new XMLHttpRequest();
		    else if(window.ActiveXObject)req=getReq();
		    if(req){
		        req.onreadystatechange=processReqChange;
	            if(hasNoFrames()){
	            	if(self._inf&&_inf["rpc_domain"]=="1"){
	            		if(_inf["rpc_domain_folder"]!="")req.open('POST',_inf["rpc_domain_folder"]+"rpc/"+"?jid="+(new Date()).getTime(),true);
	            		else req.open('POST',"/rpc/"+"?jid="+(new Date()).getTime(),true);
	            	}
	            	else{
	            		req.open('POST',getNewUri("rpc","")+"?jid="+(new Date()).getTime(),true);
	            	}
	            }
	            else req.open('POST',"/servlets/ClientAJAX?jid="+(new Date()).getTime(),true);
	            req.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
				
				req.send(qs);
		    }else callback(null);
		}
	};
	function getReq(){
		var activex="Microsoft.XMLHTTP",req=null;
		try{req=new ActiveXObject("Msxml2.XMLHTTP");}
		catch(err){}
		if(req==null){
			try{req=new ActiveXObject(activex);}
			catch(err){}
		}
		return req;
	}

	function processReqChange(){
    	if(req.readyState==4){
	        if(req.status==200){
				var doc=req.responseXML.documentElement;
				//logger(req.responseText);
				
				if(!doc){
					var xmlTxt=req.responseText;
					if(typeof DOMParser!="undefined")doc=(new DOMParser()).parseFromString(xmlTxt,"text/xml");
					else if(typeof ActiveXObject!="undefined"){
						doc=new ActiveXObject("Microsoft.XMLDOM");
						if(doc){
							doc.async=false;
							doc.loadXML(xmlTxt);
						}
					}
					if(doc)doc=doc.documentElement;
				}
				if(doc)callback(doc);
			}else callback(null);
			done=true;
        }
    }
}

function orderTriggered(extra,oid,count){
	var f=getData(),s=new SB(),ss=new SB(),sep1='',sep2='',v,l;
	if(f){
		if(!oid)oid=getOID();
		if(selection.enabled(oid)){
			if(count!=null&&count!="")count+="_";
			else count="";
			for(var index=0,c,i=1;i<getNrOfFields();i++){
				if(selection.isInlineSelection(oid,i)){
					c=f['_selection'+count+oid+'_'+(i-1)];
					if(c){
						if(c.selectedIndex!=-1)index=c.selectedIndex;
						v=trim(c.options[index].value);
						l=fieldLabel(i);
						s.append(sep1,l," ",v);
						ss.append(sep2,l,"%3d",v);
						sep1=',';
						sep2=';';
					}
				}
			}
			if(extra){
				extra['_xd']=s.toString();
				extra['_xds']=ss.toString();
			}
		}
		c=f["productcount"];
		if(c&&extra)extra['_xc']=c.value;
	}
}

function getStockVal(count,oid){
	var v=-1,n=__rowData[0];
	if(self._stc&&_stc[n]!=null)v=_stc[n];
	if(v==-1)v=fieldRaw(getStockFld());
	v=itemStock.get(v,oid,true);
	return(v=="*")?-1:v;
}

function SB(){
	var me=this,buf=[];
	me.append=function(){for(var i=0,p=me.append.arguments,n=p.length;i<n;i++)buf.push(p[i])};
	me.toString=function(s){return buf.join("")};
}

function Selection(){
	var me=this,ins=[];
	me.has=function(oid,col){return self._fs&&_fs[oid]&&_fs[oid].get(--col)};
	me.get=function(oid,col,first){
		if(first==null)first=false;
		var sel=_fs[oid].get(--col);
		if(first)sel=sel[0];
		else if(sel.length<3&&sel[0].indexOf(';')!=-1){
			sel=sel[0].split(';');
			sel[sel.length]="";
			if(!ins[oid])ins[oid]=[];
			ins[oid][col]=true;
		}
		return sel
	};
	me.active=function(oid,col){return _fs[oid].active(--col)};
	me.enabled=function(oid){return self._fs&&_fs[oid]};
	me.isInlineSelection=function(oid,col){return(ins[oid]&&ins[oid][--col])?ins[oid][col]:false};
	me.reset=function(oid){ins[oid]=[]}; 
}
var selection=new Selection();

function _selectProduct(ctl,i,oid,callback,count){
	
	if(!selection.isInlineSelection(oid,i)){
		var n=(count=="")?"":count+"_";
		if(getVID()==579700||getVID()==685400||getVID()==788900){
			// clear the selection >n before search
			for(var f=getData(),c;i<getNrOfFields();i++){
				c=f['_selection'+n+oid+'_'+i];
				if(c)c.selectedIndex=-1;
			}
		}
		setCtlVal("_oid",oid);
		new Remote().request(callback,"catalog_item_data","_oid",oid,"counter",count)
	}
}

function selectProduct(ctl,i,oid){
	_selectProduct(ctl,i,oid,self.response,"")
}
function selectProductRel(ctl,i,oid,count){
	_rel.active=count;
	_selectProduct(ctl,i,oid,self.response3,count)
}

function initScript(){
	document.bgColor=getBGColor()
}

var _navImage=['nextinfo.gif','nextbackinfo.gif'];
function getInfoPrevButton(){return makeCmd(null,'goToInfoPage('+(_inf['oidprev'])+')',_navImage[0],m("prev"))}
function getInfoNextButton(){return makeCmd('void(0)','goToInfoPage('+(_inf['oidnext'])+')',_navImage[1],m("next"))}

function goToInfoPage(oid){selectProduct(null,0,oid)}
