/**
 * The ipmd namespace
 */
var IPMD = {
	/**
	 * IPMD auto complete
	 */
	autocomplete:{
		/**
		 * The time auto-hide
		 */
		_hideTimeout:5000,
		/**
		 * The number of results to retun
		 */
		_limit:10,
		/**
		 * The suggestions container
		 */
		_overlay:document.createElement('UL'),
		/**
		 * The hide timeout reference
		 */
		_timeout:null,
		/**
		 * The ajax url
		 */
		_url:'/assets/popups/ipmd_search.php?m=3&input=',
		/**
		 * Hide the overlay
		 */
		hide:function(){
			$(this._overlay).hide();
		},
		onKeyPress:function(e){
			
		},
		onKeyUp:function(e){
			
		},
		/**
		 * Show the auto complete list
		 *
		 * @param HTMLInputElement input
		 */
		show:function(input){
			
			/*
			// set keyup handler for field
			var p = this;			
			// NOTE: not using addEventListener because UpArrow fired twice in Safari
			input.onkeypress 	= function(ev){ return p.onKeyPress(ev); };
			input.onkeyup      = function(ev){ return p.onKeyUp(ev); };
		  	// ARN-DEBUG Chances are we want to reset the timeout when they lose focus, at least that's what I prefer
			input.onblur = function(ev){ p.resetTimeout(); return true; };	
		  	*/
			input.setAttribute("AutoComplete","off");
			
			
			clearTimeout(IPMD.autocomplete._timeout);
			//IPMD.autocomplete.hide();
			IPMD.autocomplete._overlay.innerHTML = '';
			
			var url = this._url+input.value+'&limit='+this._limit;			
			new Ajax.Request(url, {
				onSuccess: function(response) {
					var li;
					try{												
						var results = response.responseXML.getElementsByTagName('item');
						for(var i=0;i<results.length;i++)
						{
							li = document.createElement('LI');
							li._input = input;
							li._text = new String(results[i].getAttribute('value'));
							li.onclick = function(){
								input.value = this._text;
								IPMD.autocomplete.hide();
							}
							li.onmouseover = function(){$(this).addClassName('over');}
							li.onmouseout = function(){$(this).removeClassName('over');}
							
							var val 	= li._text;
        					var st 		= val.toLowerCase().indexOf(li._input.value.toLowerCase()); // HERE WE CHECK AGAINST THE SPLITTED VALUE IF ANY***
        					li.innerHTML 	= val.substring(0,st) + '<span>' + val.substring(st,st+li._input.value.length) + '</span>' + val.substring(st+li._input.value.length);
							
							IPMD.autocomplete._overlay.appendChild(li);
						}
						//alert(SITESYNC.util.getAbsoluteLeft(input));
						IPMD.autocomplete._overlay.style.marginTop = input.offsetHeight+'px';
						input.parentNode.insertBefore(IPMD.autocomplete._overlay,input);
						$(IPMD.autocomplete._overlay).addClassName('ipmd-suggestion-box shadow bulletless');
						$(IPMD.autocomplete._overlay).show();
						IPMD.autocomplete._timeout = setTimeout(function(){IPMD.autocomplete.hide();},IPMD.autocomplete._hideTimeout);
					}catch(e){
					}
				}
			});
		}
	},
	/**
	 * Directory search functions
	 */
	directorySearch:{
		
		_currentGroup:null,
		_currentProducts:null,
		
		_treeOpenDuration:0.2,
		
		_urlGroups:'/assets/popups/ipmd_search.php?m=0&c=',
		_urlProducts:'/assets/popups/ipmd_search.php?m=2&s=',
		_urlRegions:'/assets/popups/ipmd_search.php?m=4&p=',
		_urlCountries:'/assets/popups/ipmd_search.php?m=5&r=',
		_urlSectors:'/assets/popups/ipmd_search.php?m=1&g=',
		/**
		 * A handler for after the products have been retrieved
		 */
		afterGotProducts:function(){
			//
		},
		/**
		 * A handler for after the products have been retrieved
		 */
		afterGotRegions:function(){
			
		},
		/**
		 * When a group is selected, create a sector list
		 *
		 * @param HTMLInput input
		 */
		onGroupChangeV2:function(input){
			
			//$('ipmd-search-product').parentNode.fade();
			
			this._currentGroup = input.value;
			
			var url = this._urlSectors+this._currentGroup;//+'&c='+$('country_0').value;
			new Ajax.Request(url, {
				onSuccess: function(response) {
					try{		
						var li,id,el;
						$('ipmd-sector-list-header').innerHTML = input.title+'<br/><small><em>Sub-Categories</em></small>';
						el = $('ipmd-sector-list');
						el.innerHTML = '';			
						var items = response.responseXML.documentElement.getElementsByTagName('item');
						for(var item=0;item<items.length;item++)
						{
							try{								
								id = items[item].getAttribute('id');
								
								li = document.createElement('LI');
								
								li._span = document.createElement('SPAN');
								li._span.innerHTML = items[item].getAttribute('name');
								li._selectAll = document.createElement('INPUT');
								//li._selectAll.style.display = 'none';// Initially hide the checkbox
								li._selectAll.type='checkbox';
								li._selectAll.value = 0;
								li._selectAll._checkboxes = [];
								li._selectAll.onclick = function(){								
									if(this._checkboxes.length==0)
									{
										var me = this;
										IPMD.directorySearch.afterGotProducts = function(){me.onclick();}
										this.parentNode._span.onclick();
									}
									else
									{
										for(var i=0;i<this._checkboxes.length;i++)
										{
											this._checkboxes[i].checked = this.checked;
										}
										IPMD.directorySearch.onProductsChange();
									}
								}							
								li.innerHTML = '';
								li.appendChild(li._selectAll);
								li.appendChild(li._span);
								
								
								li._span.sector = id;
								li._span.onclick = function(){									
									if(this.parentNode.getElementsByTagName('DIV').length>0)
									{
										// Item is open, so close it
										if($(this.parentNode).hasClassName('open'))
										{
											var p = $(this.parentNode);
											p.removeClassName('open');
											this.parentNode.getElementsByTagName('DIV')[0].blindUp({duration:IPMD.directorySearch._treeOpenDuration});										
										}
										// Item is closed, so open it
										else
										{
											$(this.parentNode).addClassName('open');
											this.parentNode.getElementsByTagName('DIV')[0].blindDown({duration:IPMD.directorySearch._treeOpenDuration});
										}
									}
									// Fetch the sub-items
									else
									{
										$(this.parentNode).addClassName('open');
										IPMD.directorySearch.onSectorClick(this.parentNode,this.sector);
									}
								}
								el.appendChild(li);
								
							}catch(e){
							}
						}		
						
						$(el.parentNode).appear({afterFinish:function(){
							$('directory-search-submit').appear();
						}});
						
					}catch(e){
						alert('141: '+e);
					}
			  	}
			});
		},
		/**
		 * When the products change, create the region inputs
		 */
		onProductsChange:function(){
			
			var url = this._urlRegions;
			var items = $('ipmd-sector-list').getElementsByTagName('input');
			this._currentProducts = [];
			for(var i=0;i<items.length;i++)
			{
				if(items[i].checked)
				{
					this._currentProducts.push(items[i].value);
				}
			}
			
			url+=this._currentProducts.join(',');
			
			//window.open(url);
			
			new Ajax.Request(url, {
				onSuccess: function(response) {
					try{		
						
						
						
						var li,id,el,input,label;
						el = $('ipmd-region-list');
						el.innerHTML = '';					
						$(el.parentNode).appear();
						var items = response.responseXML.documentElement.getElementsByTagName('item');
						for(var item=0;item<items.length;item++)
						{
							try{								
								id = items[item].getAttribute('id');
								li = document.createElement('LI');								
								input = document.createElement('INPUT');
								label = document.createElement('LABEL');
								input._label = label;
								input.id = 'ipmd_region_'+id;
								input.name = 'region['+id+']';
								//input.style.marginLeft = '-20px';
								//input.style.position = 'absolute';
								input.type = 'checkbox';
								input.value = id;
								input.onclick = function(){									
									var ip = this.parentNode.getElementsByTagName('INPUT');
									if(ip.length==1)
									{
										var me = this;
										IPMD.directorySearch.afterGotRegions = function(){me.onclick();}
										this._label.onclick();
									}
									else
									{
										for(var i=0;i<ip.length;i++)
										{
											if(ip[i]!=this)
											{
												ip[i].checked = this.checked;
											}
										}
									}
								};
								label.id = id;
								label.innerHTML = '<span>'+items[item].getAttribute('name')+'</span>';
								label.onclick = function(){
									if(this.parentNode.getElementsByTagName('DIV').length>0)
									{
										// Item is open, so close it
										if($(this.parentNode).hasClassName('open'))
										{
											var p = $(this.parentNode);
											p.removeClassName('open');
											this.parentNode.getElementsByTagName('DIV')[0].blindUp({duration:IPMD.directorySearch._treeOpenDuration});
										}
										// Item is closed, so open it
										else
										{
											$(this.parentNode).addClassName('open');
											this.parentNode.getElementsByTagName('DIV')[0].blindDown({duration:IPMD.directorySearch._treeOpenDuration});
										}
									}
									// Fetch the sub-items
									else
									{
										$(this.parentNode).addClassName('open');
										IPMD.directorySearch.onRegionClick(this.parentNode,this.id);
									}
								}
								li.appendChild(input);	
								li.appendChild(label);					
								el.appendChild(li);
								
							}catch(e){
							}
						}
					}catch(e){
						alert(e);
					}
				}
			});
		},
		
		onRegionClick:function(parentLi,region_id){
			var url = this._urlCountries+region_id+'&p='+this._currentProducts.join(',');			
			
			
			//window.open(url);
			
			
			new Ajax.Request(url, {
				onSuccess: function(response) {
					try{		
						var div,table,tr,td,input,items,label;
						// Clear out any existing lists
						if(parentLi.getElementsByTagName('DIV').length>0)
						{
							div = parentLi.getElementsByTagName('DIV')[0];
							div.innerHTML = '';
						}
						else
						{
							div = parentLi.appendChild(document.createElement('DIV'));
							div.style.display = 'none';
						}
						table = document.createElement('TABLE');
						tbody = document.createElement('TBODY');
						table.appendChild(tbody);
						div.appendChild(table);
						
						items = response.responseXML.documentElement.getElementsByTagName('item');
						for(var item=0;item<items.length;item++)
						{
							try{
								tr = document.createElement('TR');
								
								id = items[item].getAttribute('id');
								input = document.createElement('INPUT');
								input.id = 'ipmd_country_'+id;
								
								
								td = document.createElement('TD');
								td.setAttribute('width','100%');
								label = document.createElement('LABEL');
								label.setAttribute('for',input.id);
								label.innerHTML = items[item].getAttribute('name');
								td.appendChild(label);
								tr.appendChild(td);
								
								td = document.createElement('TD');
								td.setAttribute('align','right');
								td.innerHTML = '('+items[item].getAttribute('count')+')';
								tr.appendChild(td);
								
								td = document.createElement('TD');
								input.name = 'country['+id+']';
								input.type="checkbox";
								input.value = id;
								td.appendChild(input);
								tr.appendChild(td);
								
								tbody.appendChild(tr);
							}catch(e){}
						}
						
						IPMD.directorySearch.afterGotRegions();
						$(div).blindDown({duration:IPMD.directorySearch._treeOpenDuration});
						
					}catch(e){
						//alert('252: '+e);
					}
				}
			});
		},
		/**
		 * Get the products
		 *
		 * @param HTMLLIElement parentLi
		 * @param integer sector_id
		 */
		onSectorClick:function(parentLi,sector_id){			
			var url = this._urlProducts+sector_id+'&g='+this._currentGroup;
			parentLi._selectAll._checkboxes = [];
			//window.open(url);
			new Ajax.Request(url, {
				onSuccess: function(response) {
					try{		
						var div,table,tr,td,input,items,label;
						// Clear out any existing lists
						if(parentLi.getElementsByTagName('DIV').length>0)
						{
							div = parentLi.getElementsByTagName('DIV')[0];
							div.innerHTML = '';
						}
						else
						{
							div = parentLi.appendChild(document.createElement('DIV'));
							div.style.display = 'none';
						}
						table = document.createElement('TABLE');
						tbody = document.createElement('TBODY');
						table.appendChild(tbody);
						div.appendChild(table);
						
						items = response.responseXML.documentElement.getElementsByTagName('item');
						for(var item=0;item<items.length;item++)
						{
							try{
								tr = document.createElement('TR');
								
								id = items[item].getAttribute('id');
								input = document.createElement('INPUT');
								input.id = 'ipmd_product_'+id;
								
								td = document.createElement('TD');
								td.style.paddingLeft = '16px';
								td.style.paddingRight = '5px';
								td.innerHTML = items[item].getAttribute('code');
								tr.appendChild(td);
								
								td = document.createElement('TD');
								td.setAttribute('width','100%');
								label = document.createElement('LABEL');
								label.setAttribute('for',input.id);
								label.innerHTML = items[item].getAttribute('name');
								td.appendChild(label);
								tr.appendChild(td);
								
								td = document.createElement('TD');
								input.name = 'product['+id+']';
								input.type="checkbox";
								input.value = id;
								input.onclick = function(){
									IPMD.directorySearch.onProductsChange();
								}
								td.appendChild(input);
								tr.appendChild(td);
								
								tbody.appendChild(tr);
								
								parentLi._selectAll._checkboxes.push(input);
							}catch(e){
								alert(e);
								
							}
						}
						
						$(div).blindDown({duration:IPMD.directorySearch._treeOpenDuration});
						$(parentLi._selectAll).appear();
						
						IPMD.directorySearch.afterGotProducts();
						
					}catch(e){
						//alert('252: '+e);
					}
			  	}
			});
		}
	},
	/**
	 * RPC style login
	 */
	login:{
		/**
		 * The handler url
		 *
		 * @param String
		 */
		_loginUrl:'/assets/popups/ipmd_login.php?',
		/**
		 * The lostpassword url
		 *
		 * @param String
		 */
		_lostPasswordUrl:'/assets/popups/ipmd_login.php?send_password=1&',
		/**
		 * Send the password to the user
		 *
		 * @param HTMLElement b The caller element (typically a button)
		 * @param String u 		The username
		 */
		lostPassword:function(b,u){
			$(b).addClassName('waiting');
			$(b).value = 'Sending password...';
			new Ajax.Request(this._lostPasswordUrl+'username='+u, {
				onSuccess: function(response){
					//alert(response.responseText);
					if(parseInt(response.responseText)==1)
					{
						$(b.parentNode).fade();
						$('loginmessage').innerHTML = 'Password sent. Please check your email and login below';
						Effect.BlindUp('lostpasswordform',{duration:0.3});
						Effect.BlindDown('loginform',{duration:0.3});
						document.getElementById('f_pass').focus();
						
					}
					else
					{
						alert('Sorry, your email address is not registered with us.'+response.responseText);
					}
					$(b).removeClassName('waiting');
					$(b).value = 'Send Password';
					//$(b).enabled = true;
				}
			});
		},
		/**
		 * Submit a login
		 *
		 * @param HTMLElement b The caller element (typically a button)
		 * @param String u 		The username
		 * @param String p		The password
		 */
		submit:function(b,u,p){
			$(b).addClassName('waiting');
			$(b).value = 'Logging in...';
			//$(b).enabled = false;
			new Ajax.Request(this._loginUrl+'username='+u+'&password='+p, {
				onSuccess: function(response){
					if(response.responseText==1)
					{
						$(b.form).fade();
						$(b.form.parentNode).removeClassName('notloggedin');
						$(b.form.parentNode).addClassName('loggedin');
					}
					else
					{
						alert('Login failed. Please try again.');
					}
					$(b).removeClassName('waiting');
					$(b).value = 'Login';
					//$(b).enabled = true;
				}
			});
		}	
	},
	/**
	 * The IPMD/PIM mini cart display
	 */
	minicart:{
		/**
		 * Attempt to remove an item from the cart with ajax.
		 *
		 * @param HTMLAElement a
		 * @return boolean
		 */
		ajaxRemoveItem:function(a){
			var a,src,ajax,img;
			
			img = a.getElementsByTagName('IMG')[0];
			// Store the original image src
			src = img.src;
			// Set the image to the loading gif
			img.src = '/assets/images/icons/ajax-loader-circle-ball.gif';
			
			ajax = new SITESYNC.util.ajax();
			ajax.load(a.href+'&ajax=1',function(){
				
				//alert(ajax.getText());
				if(parseInt(ajax.getText())==1)
				{
					//a.parentNode.parentNode.removeChild(a.parentNode);
					$(a.parentNode.parentNode).puff({afterFinish:function(){
						//recalculate the total and item count
						a.parentNode.parentNode.parentNode.removeChild(a.parentNode.parentNode);
						IPMD.minicart.recalculateMiniCart();
					}});
				}
				else
				{
					// Something's gone wrong, just open the cart url
					window.location.href = a.href;
				}
			});
			return false;
		},
		/**
		 * Recalculate the minicart summary
		 */
		recalculateMiniCart:function(){
			var td;
			var total = 0;
			var trs = $('miniCartDetailsTable').getElementsByTagName('TR');
			for(var i=0;i<trs.length;i++)
			{
				total+= parseFloat(trs[i].getElementsByTagName('TD')[1].firstChild.nodeValue.split('£').join(''));
			}
			$('miniCartItemCount').innerHTML = trs.length+' Items';
			$('miniCartItemTotal').innerHTML = '£'+total.toFixed(2);
		},
		/**
		 * Shows the mini cart display
		 */
		togglecart:function(){
			var d = 0.3;
			Effect.toggle('miniCartDetails','blind',{duration:d});
			Effect.toggle('miniCartDetailsTable','appear',{duration:d+1});			
		}
	},	
	/**
	 * Functions for the subscribers
	 */
	subscribers:{
		/**
		 * The url of the ajax approve handler
		 *
		 * @param String
		 */
		_approveUrl:'/assets/popups/ipmd_approve.php?id=',
		/**
		 * Approve a subscriber via AJAX in the adminlisting
		 *
		 * @param integer id
		 * @param HTMLAElement a
		 */
		approve:function(id,a){
			
			// Store the original anchor html			
			var txt = a.innerHTML;
						
			// Set the image to the loading gif
			a.innerHTML = '<img src="/assets/images/icons/ajax-loader-circle-ball.gif"/>';
			
			ajax = new SITESYNC.util.ajax();
			ajax.load(this._approveUrl+id,function(){
				
				if(parseInt(ajax.getText())==1)
				{
					//a.parentNode.parentNode.removeChild(a.parentNode);
					$(a.parentNode.parentNode).fade({afterFinish:function(){
						//recalculate the total and item count
						a.parentNode.parentNode.parentNode.removeChild(a.parentNode.parentNode);
					}});
				}
				else
				{
					// Something's gone wrong, just open the cart url					
					alert('User could not be approved. '+ajax.getText());
					a.innerHTML = txt;
				}
			});
			return false;
		}
	},
	util:{
		emptyDropdown:function(id){
			$(id).innerHTML = '';
		}
	}
};
