/**
 * @(#)/views/library/lib_myshop.js
 *
 * Copyright 2000-2010(c) MijnWinkel B.V.
 *
 * Version 10.4.0 28-mai-2010
 */


function __onLoadPage(){}
function w(s){document.write(s)}
function hasMenu(s){return false}

function _i(v){return(v==null)?0:parseInt(v,10)}
function getElementOnId(n,d){
	var ref;
	if(d==null)d=document;
	if(d.layer)ref=layer[n];
	else if(d.all==null)ref=d.getElementById(n);
	else ref=d.all[n];
	return ref
}
function showDeliveryFields(n){
	var e=getElementOnId("delivery_fields");
	if(e!=null)e.style.display=(n)?"":"none";
}

function MyShopRemoveHTMLTags(htmlString){
    if(htmlString){
        var mydiv = document.createElement("div");
        mydiv.innerHTML = htmlString;
        if (document.all){return mydiv.innerText;} 
        else{return mydiv.textContent;}                           
    }
} 

function MyShopState(){
	var me=this,events=[],check=[];
	
	me.register=function(name,func){
		events[name]=func;
		check[name]=true;
	};
	me.trigger=function(name){
		return(events[name])?events[name]():true;
	}
	me.exist=function(name){
		return check[name];
	}
}
var _myshop=new MyShopState(),_myshop_popup=null,_myshop_event_block=-1,_myshop_help;

function myshopConsole(s){
	if(true)try{if(self.console)console.log(s)}catch(e){}
}


function MyShopVoid(){
	var me=this,pass=function(){return me};
	me.version=3;
	me.action=function(){return false};
	me.location=function(){return me};
	me.popup=function(){return me};
	me.confirm=function(){return me};
	me.set=function(){return me};
	me.duplicate=pass;
	me.reload=function(){};
	me.submitPage=function(){};
	me.validate=function(){return me};
	me.keypress=function(e){
		if(!e)e=window.event;
		return(e.keyCode!=13);
	}
	me.form=function(n){return me};
	me.checked=function(n){return me};
	me.get=function(){return ""};
	me.scroll=function(){return me};
	me.init=function(){return me};
	me.item=function(){return me};
}


function MyShop(){
	var POPUP_NAME="myshoporderpopup";
	var me=this,_location=null,_target=null,_width="440",_height="280",_msg="",_quantity=null,_formName="data",_leave=false,_item=null;
	var _hasQuery=false;
	var MAX_SEARCH_FIELD=30;
	me.version=3;
	
	function i(v){return(v==null)?0:parseInt(v,10)}

	function clearSelection(id){
		var n=0,c,index;
		if(!isNaN(id)){
			index=i(id)+1;
			while(index<MAX_SEARCH_FIELD){
				c=getElementOnId("myshp_search_field_"+index);
				if(c){
					if(c.value)c.value="";
				}else break;
				c=getElementOnId("myshp_search_field_max_"+index);
				if(c&&c.value)c.value="";
				index++
			}
		}
		index=0;
		while(index<MAX_SEARCH_FIELD){
			c=getElementOnId("myshp_search_field_menu_"+index);
			if(c)c.value="";
			else break;
			index++
		}
	}
	function endsWith(s,n){
		var i=0,ret=false;
		if(s){
			i=s.length-1;
			ret=(s.indexOf(n)==i);
		}
		return ret;
	}
	function trim(v){
		if(v==null)v='';
		else v=''+v;
		return(v=='')?v:v.replace(/^\s+|\s+$|&nbsp;|&#160;/gi,'');
	} 
	function getData(){return document.forms[_formName]} 

	me.reload=function(){
		_leave=true;
		var f=getData();
		if(f){
			f.action=(_location)?_location:f["this"].value;
			f.target="_self";
			f.submit();
		} 
		else window.location.reload();
	};

	me.help=function(shopId,lang,title){
		if(_myshop_help)try{
			_myshop_help.close();
		}catch(e){}
		if(!lang)lang="nl";
		_myshop_help=window.open('http://www.mijnwinkel.nl/help/frame.html?page=hkassa_'+lang+'.html&language='+lang+'&_vid='+shopId,title,"height=450px,width=400px,left=10px,top=10px",true);
	};
	
	me.action=function(a,id,next){
		_leave=true;
		var f=getData(),useLocation=false;
		if(f&&a){
			var delay=false,cont=true;
			if(f["a"])f["a"].value=a;
			if("orderdirect"==a){
				if(_quantity!=null)id=_quantity;
				
				if(id){
					if(isNaN(id))id=id.value;
					_location+="&quantity="+encodeURIComponent(id);
					id=""; 
				}
				f.action=_location;
				f.method="post";
			}
			else if("change"==a||"remove"==a||"start-register"==a||"add"==a||"add-related"==a||"add-related-basket"==a){
				f.action=_location+((endsWith(_location,"?"))?"":"&")+"jid="+(new Date()).getTime();
			}
			else if("continue_shopping"==a){
				useLocation=true;
				f.method="get";
				/* clear the catalog id the url should specify the catalog */
				var ctl=f["cid"];
				if(ctl)ctl.value="";
				f.action=_location;
				if(_target)f.target=_target;
			}
			else if("cancel"==a){
				cont=false;
				try{window.close()}catch(e){};
			}
			else if("change_update"==a){
				if(f["id"])f["id"].value=id;
			}
			else if("select_shipping"==a){
				f.action=f["this"].value;
				delay=false;
			}
			else if("selection"==a){
				if(f["id"])f["id"].value=decodeURIComponent(id);
				if(f["xy"]){
					var xy="";
					try{
						if(document.all){
							if(document.documentElement)xy=document.documentElement.scrollLeft+';'+document.documentElement.scrollTop;
							else xy=document.body.scrollLeft+';'+document.body.scrollTop;
						}
						else xy=window.pageXOffset+';'+window.pageYOffset;
					}
					catch(e){};
					f["xy"].value=xy;
				}
				
				f.action=f["this"].value;
			}
			else if("show_error"==a){
				cont=false;
				if(self.myshopShowError)myshopShowError();
			}
			else if("search"==a){
				clearSelection(0);
				//try{
				//if(f["myshop_domain_fields"]){
				//	var n,i=0,count=f["myshop_domain_fields"].value;
				//	for(;i<count;i++){
				//		n="myshop_domain_field_"+i;
				//		if(f[n])f[n].value="";
				//	}
				//}
				//
				//}catch(e){}
				
			}
			else if("globalsearch"==a){
				f.method="post";
				if(id)f["_globalsearch"].value="";
				else f["_globalsearch"].value=f["myshp_search_field_globalsearch"].value;
				clearSelection(id);
			}
			else if("prev"==a){
				if(_location)f.action=_location;
			}
			else if("back"==a){
				if(_location)f.action=_location;
			}
			
			
			if("next"==a){
				if(self._myshop){
					if(_myshop.exist("lock_next")){
						_myshop.trigger("lock_next");
						cont=false;
					}
					else _myshop.register("lock_next", function(){alert("Processing, one moment please ...");return false});
				}
				if(cont){
					if(_location)f.action=_location;
					
					if(f["coupon_n"]&&f["coupon_n_current"]&&trim(f["coupon_n"].value)!=""&&f["coupon_n"].value!=f["coupon_n_current"].value){
						if(f["a"])f["a"].value="coupon_n";
						f.action=f["this"].value;
					}
					else if(self._myshop)cont=_myshop.trigger("on_next_page");
				}
			}
			
			if(cont){
				if(id&&f["id"])f["id"].value=decodeURIComponent(id);
				if(next&&f["next"])f["next"].value=next;
				if(_myshop_popup){
					f.target=POPUP_NAME;
					try{_myshop_popup.focus()}catch(e){};
				}
				else if(_target)f.target=_target;
				else f.target="_self";
	
				var done=false;
				if(_hasQuery&&useLocation&&(!_target)){
					document.location=f.action;
					done=true;
				}
				else if(_hasQuery)f.method="post";
				
				if(!done){
					if(delay)window.setTimeout("myshop().submitPage();",10);
					else f.submit();
				}
			}
		}
		return false;
	};
	
	me.submitPage=function(action,method){
		_leave=true;
		var f=getData();
		if(f){
			if(trim(action)!='')f.action=action;
			if(method){
				method=trim(method).toLowerCase();
				if(method=="get")f.method="get";
				else if(method=="post")f.method="post";
			}
			f.submit();
		}
	};
	me.init=function(part){
		var f=getData(),v;
		if(f){
			try{
				var i=0,l=f.length;
				for(;i<l;i++){
					var type=""+f[i].type;
					if(type.toLowerCase()=="textarea"){
						var s=""+f[i].value;
						s=trim(s);
						if(s.charAt(0)<32&&s.length<2)s="";
						f[i].value=s;
					}
				}
			}
			catch(e){}
		}
		if(self.myshopDynamicSizing)myshopDynamicSizing(part);
		
	};
	me.scroll=function(){
		var f=getData();
		if(f&&f['xy']){
			var l=f['xy'].value.split(';');
			if(l.length>1)window.scrollTo(l[0],l[1]);
			f['xy'].value="";
		}
		return me;
	};
	
	me.popup=function(l,w,h){
		_location=l;
		if(_myshop_popup){
			try{_myshop_popup.close()}catch(e){};
		}
		if(w)_width=w;
		if(h)_height=h;
			
		var settings="location=0,directories=0,toolbar=no,resizable=no,status=no,scrollbars=1,menubar=no,width=";
		settings+=_width+",height="+_height+",left="+((screen.width-_width)*0.5)+",top="+((screen.height-_height)*0.4);
		_myshop_popup=window.open("/views/clear.html",POPUP_NAME,settings);
		
		return me;
	};
	
	me.set=function(n,v){
		var f=getData();
		if(f&&f[n])f[n].value=v;
		return me;
	};

	me.duplicate=function(formName,from,to){
		var f=getData(),v=me.get(from,formName);
		if(f&&f[to])f[to].value=v;
		return me;
	};

	me.get=function(n,formName){
		var f=(formName)?document.forms[formName]:getData(),value="";
		if(f&&f[n])value=f[n].value;
		return value;
	};
	
	me.form=function(n){
		_formName=n;
		return me;
	};
	
	me.location=function(l,t){
		_hasQuery=false;
		if(l&&l!='?'){
			_location=l;
			_hasQuery=(l.indexOf('?')!=-1);
		}
		else _location=null;
		
		
		if(trim(t)!="")_target=t;
		
		if(_myshop_popup)try{_myshop_popup.close()}catch(e){};
		_myshop_popup=null;
		
		return me;
	};
	
	me.confirm=function(id){
		var c=getElementOnId(id),msg;
		return confirm((c)?MyShopRemoveHTMLTags(c.innerHTML):id)?me:new MyShopVoid();
	};
	
	function callbackValidate(doc){
		var valid=true;
		if(doc){
			var i=0,pairs=doc.getElementsByTagName('pair');
			if(pairs){
				for(;i<pairs.length;i++){
					alert(pairs[i].firstChild.nodeValue);
					valid=false;
				}
			}
		}
		return valid;
	}
	
	
	me.validate=function(product,quantity){
		if(quantity){
				_quantity=(isNaN(quantity))?quantity.value:quantity;
				var f=getData();
				if(f)f["id"].value=_quantity;
		}
		return (new Remote(false).request("validate",callbackValidate,"product",decodeURIComponent(product)))?me:new MyShopVoid();
	};
	
	
	me.keypress=function(e,action,bubble,a,id,next){
		if(!e)e=window.event;
		if(!bubble)bubble=false;
		if(e.keyCode==13&&action){
			try{action(a,id,next)}
			catch(e){};
		}
		return(bubble||e.keyCode!=13);
	}
	
	me.checked=function(n,state){
		var c=getElementOnId(n);
		if(c)c.checked=state;
		return me
	};

	
	/* remote interface */
	
	function QueryString(s){
		var me=this,_p=[],_n=[];
		me.set=function(k,v){
			var b=false,l=_n.length,i=0;
			for(;i<l;i++)if(_n[i]==k){
				b=true;
				break;
			}
			if(!b)_n[l]=k;
			_p[k]=v
		};
		me.get=function(k){return(_p[k]==null)?"":_p[k]};
		me.exist=function(k){return _p[k]!=null};
		me.getQueryString=function(){
			var s="",i=0;
			for(;i<_n.length;i++)s+=encodeURIComponent(_n[i])+"="+encodeURIComponent(_p[_n[i]])+"&";
			return s;
		};
		if(s!=null&&s!=""){
			var list=s.substr(1).split("&"),l=list.length,i=0;
			for(;i<l;i++){
				var v=list[i].split("=");
				if(v.length>1)me.set(decodeURIComponent(v[0]),decodeURIComponent(v[1]));
			}
		}
		me.keys=_n;
	}

	function Remote(async){
		if(async==null)async=true;
		var me=this,_req=null,_callback=null;
		function val(f,i){
			var v=f[i].value;
			if(v!=null&&v!="")v=v.replace("+","%2b");
			return v
		}
		me.request=function(type,cb){
			var f=getData(),i=0,l,argl=me.request.arguments,activex=null,q=new QueryString(),result=false;
			if(cb&&f){
				l=f.length;
				for(;i<l;i++)q.set(f[i].name,val(f,i));
				l=argl.length;
				for(i=2;i<l;i+=2)q.set(argl[i],argl[i+1]);
				q.set('type',type);
				qs=q.getQueryString();
				_callback=cb;
				if(window.XMLHttpRequest)_req=new XMLHttpRequest();
			    else if(window.ActiveXObject){
			        activex="Microsoft.XMLHTTP";
			        _req=new ActiveXObject("Msxml2.XMLHTTP");
			        if(!_req)_req=new ActiveXObject(activex);
			    }
			    if(_req&&f["url_rpc"].value){
			        if(async)req.onreadystatechange=processReqChange;
			        _req.open('POST',f["url_rpc"].value+"?jid="+(new Date()).getTime(),async);
		            _req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					_req.send(qs);
					if(!async)result=processReqChange();
			    }else result=_callback(null);
			}
			return result;
		};

		function processReqChange(){
			var result=false;
	    	if(_req.readyState==4){
		        if(_req.status==200){
					var doc=_req.responseXML.documentElement;
					//alert(_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)result=_callback(doc);
				}else result=_callback(null);
	        }
	    	return result;
	    }
	}
}

function myshop(block){
	var blocked=false;
	if(block==null)block="yes";
	
	if(block=="yes"){
		var now=new Date().getTime();
		blocked=true
		if(_myshop_event_block==-1){
			blocked=false;
			_myshop_event_block=now;
		}
		else if((Math.abs(now-_myshop_event_block))>500){
			_myshop_event_block=-1;
			blocked=false;
		}
	}
	return(blocked)?new MyShopVoid():new MyShop();
	
		
}



