
var timey;
function stackFunction(func, func2) {
  if (typeof func != 'function') {
    return func2;
  } else {
     return function() {
      func(this);
      func2(this);
    };
  }
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    };
  }
}

function submitSearch(){

	var searchTerm = encodeURIComponent(document.getElementById("topsearch").value);

	if(searchTerm == '' || searchTerm == 'Search'){
		alert('You have not entered a search term');
	}else{
		document.location = "/search/"+encodeURIComponent(searchTerm)+"/page1.html";
	}
	return false;
}

function checkInitValue(obj,sPassed) { 
	if(obj.value==sPassed)	{
		obj.value="";
	} 
}
function checkIsBlank(obj,sPassed) { 
	if(obj.value=='')	{
		obj.value=sPassed;
	} 
}

function make_payment(){
	document.getElementById("paymentForm").style.display = "none";
	document.getElementById("progress").style.display = "block";
	return true;
}

function wishlist_login(){
	var chkLogin = document.getElementById('chkLogin').innerHTML;
	if(chkLogin == 'Login'){
		loggedIn = 0;
	}else{
		loggedIn = 1;
	}

	if(loggedIn == 1){
		//go to wishlist page
		document.location = '/wish-list.html';
	} else {
		if(layerShowing == null){
			showLayer('login');
		}
		timey = setTimeout("wishlist_login();",1000);
	}
	return false;
}

function track_order_login(){
	var chkLogin = document.getElementById('chkLogin').innerHTML;
	if(chkLogin == 'Login'){
		loggedIn = 0;
	}else{
		loggedIn = 1;
	}

	if(loggedIn == 1){
		document.location = '/track-order.html';
	} else {
		if(layerShowing == null){
			showLayer('login');
		}
		timey = setTimeout("track_order_login();",1000);
	}
	return false;
}

function check_login(elm, from) {
	elm.focus();
	
	elm.onloginresponse = function(e) { login(e, from); };

	RPC("customer", "login", elm, "onloginresponse", Array(document.getElementById(from+'login_email').value, document.getElementById(from+'login_pass').value, document.getElementById(from+'remember_me').checked));
	return false;
}

function login(messages, from) {
	can_log_in = true;
	
	if(messages.login_email_validation != "") {
		document.getElementById(from+'login_email_validation').innerHTML = messages.login_email_validation;
		document.getElementById(from+'login_email_validation').style.visibility = 'visible';
		can_log_in = false;
	} else {
		document.getElementById(from+'login_email_validation').innerHTML = '';
		document.getElementById(from+'login_email_validation').style.visibility = 'hidden';
	}
	
	if(messages.login_pass_validation != "") {
		document.getElementById(from+'login_pass_validation').innerHTML = messages.login_pass_validation;
		document.getElementById(from+'login_pass_validation').style.visibility = 'visible';
		can_log_in = false;
	} else {
		document.getElementById(from+'login_pass_validation').innerHTML = '';
		document.getElementById(from+'login_pass_validation').style.visibility = 'hidden';
	}
	
	if(messages.login_link_html != "") {
		document.getElementById('head3_1').innerHTML = messages.login_link_html;
	}
	if(messages.register_link_html != "") {
		document.getElementById('head3_2').innerHTML = messages.register_link_html;
	}
	document.getElementById('mailing_list_link').innerHTML = messages.mailing_list_link_html;
	document.getElementById('head3_4').innerHTML = messages.track_order_link_html;
	
	
	if(can_log_in == true) {
		if(document.getElementById('logged_in_redirect')) {
			document.location = document.getElementById('logged_in_redirect').value;
		} else {
			document.getElementById('loginForm').style.display = 'none';
			document.getElementById('loggedInNotice').style.display = 'block';
			document.getElementById('customer_name').innerHTML = messages.customer_name;
			setTimeout("hideLayer('login');", 800);
		}
	}
}

function logout(elm) {
	elm.onlogoutresponse = function(e) { logout_done(e); };

	RPC("customer", "logout", elm, "onlogoutresponse", Array());
	return false;
}

function logout_done(messages) {
	if(messages.login_link_html != "") {
		document.getElementById('head3_1').innerHTML = messages.login_link_html;
	}
	
	if(messages.register_link_html != "") {
		document.getElementById('head3_2').innerHTML = messages.register_link_html;
	}
	document.getElementById('mailing_list_link').innerHTML = messages.mailing_list_link_html;
	document.getElementById('head3_4').innerHTML = messages.track_order_link_html;
	
	if(document.getElementById('logged_out_redirect')) {
		document.location = document.getElementById('logged_out_redirect').value;
	}
}/* Category Menu */

var catCurrentOpen = null;

addLoadEvent(initLeftNav);

function initLeftNav() {
	if(document.getElementById('navid')) {
		if(document.getElementById(document.getElementById('navid').value)) {
//			showNextCatLevel(document.getElementById(document.getElementById('navid').value));
		}
	}
}

function showNextCatLevel(elm) {	
	if(catCurrentOpen==elm) {
		change_menu_state(catCurrentOpen, "off");
		catCurrentOpen = null;
		return false;
	}

	if(catCurrentOpen != null) {
		change_menu_state(catCurrentOpen, "off");
	}

	catCurrentOpen = elm;
	return change_menu_state(elm, "on");
}

function change_menu_state(elm, state) {
	if(state=="on") {
		classN = "on";
		display = "block";
	} else if(state=="off") {
		classN = "";
		display = "none";
	} else {
		return false;	
	}
	
	result = true;
	
	navNodes = elm.parentNode.childNodes;
	for(i=0; i<navNodes.length; i++) {
		if(navNodes[i].tagName == "UL") {
			navNodes[i].style.display = display;
			//yes this is the opposite of what you'd expect - return false if there are items under the menu and follow the a link if there are not
			result = false;
		}
	}
	
	elem = elm.parentNode;
	do {
		if(elem.tagName == 'UL') {
			elem.style.display = display;
		}
		if(elem.tagName == 'LI') {
			elem.className = classN;
		}
		if(elem.parentNode.id == "mainNav") {
			break;
		}
		elem = elem.parentNode;
	} while (elem.parentNode);
	
	return result;
}



/* Right Menu */

var currentOpen = null;
var divHeight = 250;
var numItems;
var headingHeight = 30;
var queueItem = null;
var menusReady = new Array();

addLoadEvent(initMenu);

function initMenu() {
	c = 0;
	if(!document.getElementById('rightMenu')){
		return;
	}
	n = document.getElementById('rightMenu').childNodes;
	for(i=0; i<n.length; i++) {
		if(n[i].tagName == 'DIV') {
			c++;
		}
	}
	numItems = c;
	if(document.getElementById('right_menu_open')) {
		startOpen = document.getElementById('right_menu_open').value;
	} else {
		startOpen = 0;
	}

	for(var i=0; i<numItems; i++) {
		if(i <= startOpen) {
			addOn = 0;
		} else {
			addOn = divHeight;
		}
		if(i == startOpen) {
			document.getElementById('rightMenuHead'+i).className = "on";
		}
		document.getElementById('rightMenu'+i).style.height = parseInt(divHeight+headingHeight)+"px";
		document.getElementById('rightMenu'+i).style.top = parseInt((i*headingHeight)+addOn)+"px";
		menusReady[i] = 1;
	}
	document.getElementById('rightMenu').style.height = parseInt(divHeight+(numItems*headingHeight))+"px";
	currentOpen = parseInt(startOpen);
}

function openRightMenu(id) {
	if(id != currentOpen) {
		if(checkMenuReady() == true) {
			
			if(id<currentOpen) {
				for(var i=parseInt(id+1); i<=currentOpen; i++) {
					changeMenu(i, '+');
				}
			} else {
				for(var i=parseInt(id); i>currentOpen; i--) {
					changeMenu(i, '-');
				}
			}
			currentOpen = id;
			
			for(var i=0; i<numItems; i++) {
				if(document.getElementById('rightMenuHead'+i).className == "on") {
					document.getElementById('rightMenuHead'+i).className = "off";
				}
			}
			document.getElementById('rightMenuHead'+id).className = "on";
		} else {
			queueItem = id;
		}
	}
	return false;
}

function changeMenu(menuid, direction) {
	menusReady[menuid] = 0;
	
	elm = document.getElementById('rightMenu'+menuid);
	
	if(direction == "+") {
		
		startPos = parseInt(elm.style.top.replace("px", ""));
		endPos = parseInt((divHeight+(numItems*headingHeight))-((numItems-menuid)*headingHeight));
		
		dist = parseInt(endPos - startPos);
		speed = parseInt(dist/4);
		if (speed == 0) speed = 1;
		
		elm.style.top = eval("(parseInt(elm.style.top.replace('px', ''))"+ direction + speed + ") + 'px'");
		
		if(parseInt(elm.style.top.replace("px", "")) < endPos) {
			setTimeout("changeMenu('"+menuid+"', '"+direction+"')", 20);
		} else {
			menusReady[menuid] = 1;
			if(checkMenuReady() == true && queueItem!=null) {
				openRightMenu(queueItem);
				queueItem = null;
			}
		}
	} else {
		startPos = parseInt(elm.style.top.replace("px", ""));
		endPos = parseInt(menuid*headingHeight);
		
		dist = parseInt(startPos - endPos);
		speed = parseInt(dist/4);
		if (speed == 0) speed = 1;
		
		elm.style.top = eval("(parseInt(elm.style.top.replace('px', ''))"+ direction + speed +") + 'px'");
		
		if(parseInt(elm.style.top.replace("px", "")) > endPos) {
			setTimeout("changeMenu('"+menuid+"', '"+direction+"')", 20);
		} else {
			menusReady[menuid] = 1;
			if(checkMenuReady() == true && queueItem!=null) {
				openRightMenu(queueItem);
				queueItem = null;
			}
		}
	}
}

function checkMenuReady() {
	for(var i=0; i<numItems; i++) {
		if(menusReady[i] == 0) {
			return false;
		}
	}
	return true;
}

function hideCartAdded(){
	if(document.getElementById("cartAdded")){
		document.getElementById("cartAdded").style.display = 'none';
	}
}
var loginWidth = 470;
var loginHeight = 321;

var mailinglistWidth = 470;
var mailinglistHeight = 321;

var layerShowing = null;
var tempSelectStates = new Array();
var isScrolling = false;
var fadeBox = false;
function fnClearLogin() {
	document.getElementById("layerlogin_email").value = "";
	document.getElementById("layerlogin_pass").value = "";
}

function showLayer(type) {
	if(type == "login") {
		w = loginWidth;
		h = loginHeight;
		document.getElementById('loggedInNotice').style.display = 'none';
		document.getElementById('layerlogin_email_validation').style.visibility = 'hidden';
		document.getElementById('layerlogin_pass_validation').style.visibility = 'hidden';
		document.getElementById('loginForm').style.display = 'block';
		fnClearLogin();
	} else if(type == "postcode") {
		w = mailinglistWidth;
		h = mailinglistHeight;
	} else {
		return false;
	}
	
	if(!isScrolling) {
		//reset the width of the transparent layer, so that if the window is
		//being resized smaller, the scroll bar will shrink
		document.getElementById('overlayLayer').style.width = "980px"
		document.getElementById('overlayLayer').style.display = "none";
		
		//if layer has current x + w >980, reset x pos of the layer to default
		if((parseInt(document.getElementById(type+'Box').style.left.replace("px", "")) + w) > 980) {
			document.getElementById(type+'Box').style.left = parseInt(490-(w/2))+"px";
		}
	}
	
	if( typeof( window.innerWidth ) == 'number' ) {
   		//Non-IE
		myWidth = window.innerWidth;
    	myHeight = window.innerHeight;
		htmHeight = document.documentElement.scrollHeight;
		htmWidth = document.documentElement.scrollWidth;
		fadeBox = true;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
   		//IE 6+ in 'standards compliant mode'
    	myWidth = document.documentElement.clientWidth;
    	myHeight = document.documentElement.clientHeight;
		htmHeight = document.documentElement.scrollHeight;
		htmWidth = document.documentElement.scrollWidth;
		fadeBox = false;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    	//IE 4 compatible
    	myWidth = document.body.clientWidth;
    	myHeight = document.body.clientHeight;
		htmHeight = document.body.offsetHeight;
		htmWidth = document.body.offsetWidth;
		fadeBox = false;
	}
	if (window.innerHeight) {
		topScroll = window.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		topScroll = document.documentElement.scrollTop;
	} else if (document.body) {
		topScroll = document.body.scrollTop;
	}
	
	winW = myWidth;
	if(htmHeight > myHeight) {
		winH = htmHeight;
	} else {
		winH = myHeight;
	}
	
	if(myWidth>980) {
		winW2 = htmWidth;
		//use htmWidth here, because non-ie browsers count the scroll bar in the win width
	} else {
		winW2 = 980;
	}
	
	document.getElementById(type+'Box').style.width = w+"px";
	document.getElementById(type+'Box').style.height = h+"px";
	
	x = parseInt((winW/2) - (w/2));
	y = parseInt((myHeight/2) - (h/2)+topScroll);
	
	if(!isScrolling) {
		document.getElementById('overlayLayer').style.height = winH+"px";
		document.getElementById('overlayLayer').style.width = winW2+"px";
		document.getElementById('overlayLayer').style.display = "block";
	}
	
	document.getElementById(type+'Box').style.top = y+"px";
	document.getElementById(type+'Box').style.left = x+"px";
	document.getElementById(type+'Box').style.display = "block";
	
	//fade in
	if(layerShowing == null) {
		if (navigator.userAgent.toLowerCase().indexOf("msie") != -1) {
			saveSelectStates();
		}
		setOpacity(10, 'overlayLayer');
		if(fadeBox == true) {
			setOpacity(20, type+'Box');
			setTimeout("setOpacity(20, 'overlayLayer'); setOpacity(40, '"+type+"Box');", 40);
			setTimeout("setOpacity(30, 'overlayLayer'); setOpacity(60, '"+type+"Box');", 80);
			setTimeout("setOpacity(40, 'overlayLayer'); setOpacity(80, '"+type+"Box');", 120);
			setTimeout("setOpacity(50, 'overlayLayer'); setOpacity(100, '"+type+"Box');", 160);
		} else {
			setTimeout("setOpacity(20, 'overlayLayer')", 40);
			setTimeout("setOpacity(30, 'overlayLayer')", 80);
			setTimeout("setOpacity(40, 'overlayLayer')", 120);
			setTimeout("setOpacity(50, 'overlayLayer')", 160);
		}
	}

	layerShowing = type;
	
	if(window.document.featureFlash!=undefined) {	
		window.document.featureFlash.SetVariable("sLoginScreen", "on");
		window.document.ticker.SetVariable("sLoginScreen", "on");
		window.document.bands.SetVariable("sLoginScreen", "on");
		
	}
	
	if(type == "login") {
		document.getElementById("layerlogin_email").focus();	
	}
	
	return false;
}

function hideLayer(type) {
	//fade out, then close
	setOpacity(50, 'overlayLayer');
	if(fadeBox == true) {
		setTimeout("setOpacity(40, 'overlayLayer'); setOpacity(80, '"+type+"Box');", 40);
		setTimeout("setOpacity(30, 'overlayLayer'); setOpacity(60, '"+type+"Box');", 80);
		setTimeout("setOpacity(20, 'overlayLayer'); setOpacity(40, '"+type+"Box');", 120);
		setTimeout("setOpacity(10, 'overlayLayer'); setOpacity(20, '"+type+"Box');", 160);
	} else {
		setTimeout("setOpacity(40, 'overlayLayer')", 40);
		setTimeout("setOpacity(30, 'overlayLayer')", 80);
		setTimeout("setOpacity(20, 'overlayLayer')", 120);
		setTimeout("setOpacity(10, 'overlayLayer')", 160);	
	}
	setTimeout("closeLayer('"+type+"')", 200);
	
	return false;
}

function closeLayer(type) {
	
	if(timey){
		clearTimeout(timey);
	}
	if (navigator.userAgent.toLowerCase().indexOf("msie") != -1) {
		applySelectStates();
	}
	document.getElementById('overlayLayer').style.display = "none";
	document.getElementById(type+'Box').style.display = "none";
	
	if(window.document.featureFlash!=undefined) {	
		window.document.featureFlash.SetVariable("sLoginScreen", "off");
		window.document.ticker.SetVariable("sLoginScreen", "off");
		window.document.bands.SetVariable("sLoginScreen", "off");
	}
	
	fnClearLogin();
	
	layerShowing = null;
}

function saveSelectStates() {
	tags = document.getElementsByTagName("select");
	for(var i=0; i<tags.length; i++) {
		tempSelectStates[i] = new Array();
		tempSelectStates[i]['elm'] = tags[i];
		tempSelectStates[i]['state'] = tags[i].disabled;
		tags[i].disabled = "disabled";
		tags[i].style.backgroundColor = "#000000";
	}
}

function applySelectStates() {
	for(var i=0; i<tempSelectStates.length; i++) {
		tempSelectStates[i]['elm'].disabled = tempSelectStates[i]['state'];
		tempSelectStates[i]['elm'].style.backgroundColor = "";
	}
}

function setOpacity(opacity, id) {
	var object = document.getElementById(id).style;
	object.MozOpacity = (opacity / 100);
	object.opacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function fnGetVisibleHeight() {
	if( typeof( window.innerHeight ) == 'number' ) {
		//Non-IE
		return window.innerHeight;
	} else if( document.documentElement && (document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		return document.documentElement.clientHeight;
	} else if( document.body && (document.body.clientHeight ) ) {
		//IE 4 compatible
		return document.body.clientHeight;
	}
}


var resizingTimer;
window.onresize = function () {
	if(layerShowing != null) {
		clearTimeout(resizingTimer);
		resizingTimer = setTimeout(window.onresizeend, 50);
	}
}
window.onresizeend = function() {
	if(layerShowing != null) {    
		showLayer(layerShowing);
	}
}


window.onscroll = function () {
	if(layerShowing == "login") {
		h = loginHeight;
	} else if(layerShowing == "postcode") {
		h = mailinglistHeight;
	} else {
		return false;
	}
	var myHeight = fnGetVisibleHeight();
	if (myHeight > h) {
		isScrolling = true;
		showLayer(layerShowing);
		isScrolling = false;
	}
}

function addValidation() {
	for(var q=0; q < 3; q++) {
		if(q == 0) el = document.getElementsByTagName("input");
		if(q == 1) el = document.getElementsByTagName("textarea");
		if(q == 2) el = document.getElementsByTagName("select");
		
		for(var i = 0; i < el.length; i++) {
			if(el[i].type != "submit" && el[i].type != "button" && el[i].type != "hidden") {
				ar = el[i].name.split(":", 2);
				if(ar[0] != "optional" && ar.length==2) {
					el[i].onvalidateresponse = function(e) { if(e != null && e != "") { document.getElementById(this.id+'_validation').innerHTML = e; document.getElementById(this.id+'_validation').style.visibility = 'visible'; } else { document.getElementById(this.id+'_validation').innerHTML = ''; document.getElementById(this.id+'_validation').style.visibility = 'hidden'; } };
					el[i].validateAs = ar[0];
					if(q==2) {
						if(typeof el[i].onchange == 'function') {
							el[i].onchange = stackFunction(el[i].onchange,function(obj){RPC("validate", obj.validateAs, obj, "onvalidateresponse", Array(obj.value));});
						} else {
							el[i].onchange = function(){RPC("validate", this.validateAs, this, "onvalidateresponse", Array(this.value));};
						}
					} else if(el[i].type == "checkbox") {
						if(typeof el[i].onchange == 'function') {
							el[i].onclick = stackFunction(el[i].onchange,function(obj){RPC("validate", obj.validateAs, obj, "onvalidateresponse", Array(obj.checked));});
						} else {
							el[i].onclick = function(){RPC("validate", this.validateAs, this, "onvalidateresponse", Array(this.checked));};
						}
					} else {
						if(ar[0] == "password" || ar[0] == "opt_password") {
							//this section is for checking passwords match, password fields must be called password1 and password2 and there should be one validation message field which is called 'password_validation'
							el[i].onvalidatepasswordresponse = function(e) { if(document.getElementById('password1').hasHadFocus && document.getElementById('password2').hasHadFocus) { if(e != null && e != "") { document.getElementById('password_validation').innerHTML = e; document.getElementById('password_validation').style.visibility = 'visible'; } else { document.getElementById('password_validation').innerHTML = ''; document.getElementById('password_validation').style.visibility = 'hidden'; } } };
							//if(typeof(el[i].onblur) == 'function' || typeof(el[i].onblur) == 'object') {
								el[i].onblur = stackFunction(el[i].onblur,function(obj){RPC("validate", obj.validateAs, obj, "onvalidatepasswordresponse", Array(document.getElementById('password1').value, document.getElementById('password2').value));});
							//} else {
							//	el[i].onblur = function(){RPC("validate", this.validateAs, this, "onvalidatepasswordresponse", Array(document.getElementById('password1').value, document.getElementById('password2').value));};
							//}
						} else {
							if(typeof el[i].onblur == 'function') {
								el[i].onblur = stackFunction(el[i].onblur,function(obj){RPC("validate", obj.validateAs, obj, "onvalidateresponse", Array(obj.value));});
							} else {
								el[i].onblur = function(){RPC("validate", this.validateAs, this, "onvalidateresponse", Array(this.value));};
							}
						}
					}
				}
			}
		}
	}
}


function associateActions(actions) {
  for(var element in actions) {
	var e;
	e = document.getElementById(element);
	if(e != null) {
	  events = actions[element];
	  for(var event in events) {
		e["on" + events[event][0]] = events[event][1];
	  }
	}
  }
}

function do_focuses() {
	if(document.getElementById('password1')) {
		document.getElementById('password1').hasHadFocus=false;
		document.getElementById('password1').onblur = stackFunction(document.getElementById('password1').onblur,function() { document.getElementById('password1').hasHadFocus=true; });
	}
	if(document.getElementById('password2')) {
		document.getElementById('password2').hasHadFocus=false;
		document.getElementById('password2').onblur = stackFunction(document.getElementById('password2').onblur,function() { document.getElementById('password2').hasHadFocus=true; });
	}
}

function jump_to_validation_error() {
	n = document.getElementsByTagName('SPAN');
	for(i=0; i<n.length; i++) {
		if(n[i].id.match("_validation$") && n[i].innerHTML!="") {
			if(document.getElementById(n[i].id.replace('_validation',''))) {
				document.location='#'+n[i].id.replace('_validation','');
				return true;
			}
			if(n[i].id=="password_validation") {
				document.location='#password1';
				return true;
			} else {
				document.location='#'+n[i].id;
				return true;
			}
		}
	}
}

function check_for_error_messages() {
	n = document.getElementsByTagName('SPAN');
	for(i=0; i<n.length; i++) {
		if(n[i].id.match("_validation$") && n[i].innerHTML!="") {
			return true;
		}
	}
	return false;
}

function show_main_error_message() {
	if(document.getElementById('main_error_message')) {
		if(check_for_error_messages()) {
			document.getElementById('main_error_message').style.display='block';
		}
	}
}

addLoadEvent(addValidation);
addLoadEvent(do_focuses);
//addLoadEvent(jump_to_validation_error);
addLoadEvent(show_main_error_message);
function RPC(remoteModel,remoteMethod,listener,method,parameters){
	rpc = new Call
	rpc.listener = listener;
	rpc.onComplete = function (){
		if(this.listener[method]){
			this.listener[method](this.retval);
		}else{
			alert(method);
		}
	}
	if(parameters){
		rpc.doCallA(remoteModel,remoteMethod,parameters);
	}else{
		rpc.doCall(remoteModel,remoteMethod);
	}
}

function RequestPoolObj(){
	this.req = 0;
	this.uniqueHandler = reponse_handler;
	this.state = 0;
	this.retObj = 0;
}

var requestPoolSize = 4;

var requestPool = Array(requestPoolSize);

for(var i = 0; i<requestPoolSize; i++){
	requestPool[i] = new RequestPoolObj();
}

function Call(){
	this.retval = 0;
	this.onComplete = 0;		
	this.reuse = 0;
}

function doCall(obj,method){
	if(arguments.length<2){
		return;
	}
	var url = "/javascriptInterface.php"
	post = "";
	post += "object="+encodeURIComponent(obj).replace("+","%2B")+"&";
	post += "method="+encodeURIComponent(method).replace("+","%2B");
	if(arguments.length>2){
		post+="&";
	}
	for (var i = 2;i < arguments.length;i++){
		
		post += "arg"+i+"="+encodeURIComponent(arguments[i]).replace("+","%2B");
		if(i+1 < arguments.length)post+="&";
	}
	loadXMLDoc(url,this,post);
}

function doCallA(obj,method,param){
	if(arguments.length<2){
		return;
	}
	var url = "/javascriptInterface.php"
	post = "";
	post += "object="+encodeURIComponent(obj).replace("+","%2B")+"&";
	post += "method="+encodeURIComponent(method).replace("+","%2B");
	if(arguments.length>2){
		post+="&";
	}
	if(param){
		for (var i = 0;i < param.length;i++){
			post += "arg"+i+"="+encodeURIComponent(param[i]).replace("+","%2B");
			if(i+1 < param.length)post+="&";
		}
	}
	
	loadXMLDoc(url,this,post);
}

Call.prototype.doCall = doCall;
Call.prototype.doCallA = doCallA;

function find_by_url(){
	loadXMLDoc(buildRequest("Product","find_all"));
}

function reponse_handler(){
	if (this.req.readyState == 4) {
		this.state = 0
        if (this.req.status == 200) {
			if(this.req.responseXML){
				
				response  = this.req.responseXML.documentElement;
				if(!response){
					alert(this.req.responseText);
					return;
				}			
				this.retObj.retval = parseXML(response,null);
				this.retObj.onComplete();	
				d = new Date();
				//alert(d.getTime() - this.startTime);
				//alert(this.req.responseText);
			}else{
				alert(this.req.responseText);
			}
        } else {
            //alert("There was a problem retrieving the XML data:\n" + this.req.statusText);
        }
    }
}

function parseXML(d,obj){
	var x = d.childNodes;
	switch(d.nodeName){
		case 'response':
			for(i=0; i<x.length; i++){
				if(x[i].nodeType==1){
					return parseXML(x[i],null);
				}
			}
		break;
		case 'scaler':
			return d.getAttribute('value');
		break;
		case 'json':
			eval('tmp = (' + x[0].nodeValue + ')');
			return tmp;
		break;
		case 'array':{
			var  tmp = new Array();
			for(var i=0; i<x.length; i++){
				if(x[i].nodeType==1){
					tmp[tmp.length] = parseXML(x[i],null);
				}
			}
			return tmp;
			break;
		}
		case 'arrayitem':{
			for(i=0; i<x.length; i++){
				if(x[i].nodeType==1){
					return parseXML(x[i],null);
				}
			}
			break;
		}
		case 'php_object':
			eval ('var  tmp = new Object()');
			for(i=0; i<x.length; i++){
				if(x[i].nodeType==1){
					parseXML(x[i],tmp);
				}
			}
			return tmp;
			break;
		case 'php_object_attribute':
			for(i=0; i<x.length; i++){
				if(x[i].nodeType==1){
					eval('obj.'+d.getAttribute('name') +' = parseXML(x[i],null)');
					return "";
				}
			}
		break;
	}
	return "";
}

function loadXMLDoc(url,retobj,post) {
	var d = new Date();
	for(var i=0;i<requestPool.length;i++){
		if (requestPool[i].state==0){
			break;
		}else{
			if((retobj == requestPool[i].retObj) && (retobj.reuse == true)){
				break;
			}
		}
	}
	if(requestPool.length==i){
		//alert("too many open requests");
		return;
	}
    // branch for native XMLHttpRequest object
	if(requestPool[i].state){
		requestPool[i].req.abort();
		requestPool[i].state = 0;
	}
    if (window.XMLHttpRequest) {
        requestPool[i].req = new XMLHttpRequest();
		requestPool[i].uniqueHandler = reponse_handler;
        eval ('requestPool[i].req.onreadystatechange = function() { requestPool['+i+'].uniqueHandler() }');
        requestPool[i].req.open("POST", url, true);
        requestPool[i].req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        requestPool[i].req.send(post);
   
        requestPool[i].startTime = d.getTime();
		requestPool[i].state = 1;
		requestPool[i].retObj = retobj;
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        requestPool[i].req = new ActiveXObject("Microsoft.XMLHTTP");
        if (requestPool[i].req) {
			requestPool[i].uniqueHandler = reponse_handler;
            eval ('requestPool[i].req.onreadystatechange = function() { requestPool['+i+'].uniqueHandler() }');
			requestPool[i].req.open("POST", url, true);
			requestPool[i].req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        	requestPool[i].req.send(post);
			requestPool[i].state = 1;
			requestPool[i].startTime = d.getTime();
			requestPool[i].retObj = retobj;
        }
    }
}

