/*

	CHUNKID TEMPLATES VOFAFONE PCR	
	author: Ernie
	
	Version: 0.2   
	Date of sending: 23-1-2009

	Remarks: 
	
	0.3 debug placement mouseover
	
	still needs work, lots of it
	only included in pages with filter

*/

window.addEvent('domready', function() {
	if (typeof maxiprice != 'undefined' && maxiprice != null) {
		if (maxiprice> 0) {
		 	el = $('money'),
			veld = $('maxprice'),
			ttip = $('ttool'),
			contrast= $('moneytop');
		 	
		 	
		 	if(document.categoryfilterform != null && document.categoryfilterform != undefined){
			 	categoryFilterForm= document.categoryfilterform.name ;
	
				yomoney = new Slider(el, el.getElement('.knob'), {
					steps: maxiprice,	// max price
					onChange: function(value){
						veld.setAttribute('value', value);
						ttip.empty();
						ttip.appendText(value);
						brdt=((maxiprice == 0) ? (1) : (value / maxiprice))*207+3 ; // huh?
						contrast.setStyle('width', brdt);
						veld.value = value;
					},
					onComplete: function(value){	
						// ugly call, no workey
						
						//TODO Revert back after iteration 72 that shows filter even in subscription step in PM
						//veld.focus();
						veld.blur();
						if( veld != null ){
							veld.value = value;
						}
						if (categoryFilterForm != null  ) {
							if (currentprice  != value) {
								veld.value = value;
							}
						}
						
					}
				}).set(currentprice); //startprice
		 	}
		}
	}
});




var FilterDevices = {
	init : function() {
		var type = "";
		this.deviceArray = this.deviceArray || [];
		this.selectObjArray = this.selectObjArray || {};
		this.brandsObject = this.brandsObject || {};
		this.featureObject = this.featureObject || {};
		this.featureValueObject = this.featureValueObject || {};

		this.featurePrice = this.featurePrice || {};
		this.featurePriceObject = this.featurePriceObject || {};
		
		this.initFilters();
		this.initDevices();
		this.toggleFilters(true);

	},
	
	initFilters : function(cb) {
		/* brands 
		
		$E(".filters select").addEvent("change",function() {
				this.onFilterChange();
		}.bind(this));*/
//ej	
		
		var typo = $('typo');
		if (typo != null) {
			type = typo.innerHTML;
		} else {
			type="";
		};
//		
		$$(".filters select").each(function(select) {
			this.selectObjArray[select.id]=[];
			select.addEvent("change",function() {
				this.onFilterChange();
			}.bind(this));
		}.bind(this));
		
		$$(".filters select option").each(function(option) {
			this.featureValueObject[option.value] = [];
		}.bind(this));
		
		/* price */
		$$(".filters input#maxprice").each(function(input) {
			input.addEvent("focus",function() {
				this.onFilterChange();
			}.bind(this));
		}.bind(this));	

		/* features */
		$$(".filters input").each(function(input) {
			var cbName = input.name;
			var i = cbName.indexOf('brands');
			if(input.type != "checkbox") return;
			
			input.addEvent("click",function() {
				this.onFilterChange();
			}.bind(this));
			if (i == -1) 
				this.featureObject[input.id] = [];
			else
				this.brandsObject[input.id] = [];
				
		}.bind(this));
	},
	
	initDevices : function(device) {
		this.deviceArray = $$(".device");
		this.deviceArray.each(function(device) {
			var brandIdEl = device.getElement("var.brand");
			if(brandIdEl != null) {
				var brandId = brandIdEl.innerHTML;
				device.featureBrand=brandId;
//				this.brandsObject[brandId] = this.brandsObject[brandId] || [];
//				this.brandsObject[brandId].push(device);
			}
			
			var featureIdsEl = device.getElement("var.features");
			if(featureIdsEl != null) {
				var featureIds = featureIdsEl.innerHTML;
				featureIdsEl.innerHTML.split(",").each(function(id) {
					if(this.featureObject[id] == null) return;					
					this.featureObject[id].push(device);
				}.bind(this));
			}
			var featureValuesEl = device.getElement("var.featureValues");
			if (featureValuesEl != null) {
				featureValuesEl.innerHTML.split("::::").each(function(id) {
					if(this.featureValueObject[id] == null) {return;}					
					this.featureValueObject[id].push(device);
				}.bind(this));
			}
			var featurePriceEl = device.getElement("var.price");
			if (featurePriceEl != null) {
				var priceId = featurePriceEl.innerHTML;				
				device.featurePrice=priceId;
			}			
		}.bind(this));
	},
	
	onFilterChange : function(cb) {
       
		this.toggleFilters(false);
		
		this.doFilterDevices([]);
		
		var results = this.getFilterResults();

		setTimeout(function() {
			this.toggleFilterResultsDiv(false, true);
		}.bind(this), 100);
		
		setTimeout(function() {
			this.showResults(results);
		}.bind(this), 1000);		
		
	},

	getFilterResults : function() {

	  var tmp1 = [];
	  for(var id in this.brandsObject) {
		var elem = $(id);
		if (elem != undefined) {  
			if(!elem.checked)  continue;
	 		var theBrand = this.brandsObject[id];
	 		theBrand.each(function(device){
	 		    tmp1.push(device)
	 		 });
 		 }										
	  }		
	  if(tmp1.length < 1)
	    results =this.deviceArray.copy();
	  else   results = tmp1; 
	  
	  for(var id in this.featureObject) {
		var elem = $(id);
		if (elem != undefined) { 
			if(!elem.checked) continue;	
				/* get the current filter */
				var theFeature = this.featureObject[id];
				var tmp = results.copy();
				results.each(function(device) {
					/* test whether the device is part of the current feature's linked devices array */
					if(!theFeature.test(device)) {
						tmp.remove(device);
					}
				}.bind(this));	          
				results = tmp;
			}
		}
		
		$$(".filters select").each(function(select) {
			if(select.selectedIndex > 0){
				var selectedValue =select.options[select.selectedIndex].value;
//				var selectedDevice = this.featureValueObject[selectedValue];
				var tmp2 = results.copy();
				results.each(function(device) {
				/* test whether the device is part of the current feature's linked devices array */
				var selectedDevice = device.featureBrand;
				if(selectedDevice!=selectedValue) {
//					window.alert(selectedDevice+"!="+selectedValue)
//				if(!selectedDevice.test(device)) {
					tmp2.remove(device);
				}
				
			}.bind(this));
			results = tmp2;
			}
		}.bind(this));
//		
		$$(".filters input#maxprice").each(function(input) {
			var maxprice = 1*(input.value);
			var i=0;
			tmp3 = results.copy();
			results.each(function(device) {
				if(maxprice<device.featurePrice) {
					tmp3.remove(device);
				} 
			}.bind(this));
			results = tmp3;
		}.bind(this));		
//		
		return results;
	},
	
	showResults : function(results) {
//		if(results.length < this.deviceArray.length) {
			this.setFilterResultsText(results);
//			this.toggleFilterResultsDiv(true);
			
			setTimeout(function() { 
				this.doFilterDevices(results);
			}.bind(this), 500);
			
			setTimeout(function() { 
				this.toggleFilters(true); 
			}.bind(this), 500);
//		}
//		else {
//			this.toggleFilters(true);
//			this.doFilterDevices(results);
//			this.setFilterResultsText(results);
//		}
		this.toggleFilterResultsDiv(true);

	},
	
	doFilterDevices : function(devices) {
		var arr = this.deviceArray;
		var i = 0;
		var j = 0;
		arr.each(function(device) {
			if(devices.test(device)) {
				var t = (i * 60 < 420) ? i * 60 : 420;
				device.toggleIn(t);

				if (((type=="phones") || (type=="accessoires")) || (type=="modems")) {
					//ej: rearrange borders
					j++;
					if (j<5) {
						 device.addClass('firstline');
					} else {
						device.removeClass('firstline');
						};
					if ((j/4)==(Math.floor(j/4))) {
						 device.addClass('lastcol');
					} else {
						device.removeClass('lastcol');
					};

				//add tooltip 
					targ=$("toolblok"+(i+1));

					pos=j-1;
					var line=Math.floor(pos/4);
					coor=$('devicesblock').getPosition();
					yco=coor.y;
					devHeight=319;
					if (window.ie6)	{yco=yco+15}
					
					var linePos=yco+devHeight*line;
					

					var coll=pos-4*line;
					if (coll<2) {
						collPos=198+(coll+1)*187; 
						targ.setStyle('background', 'url(img/ej/bg_blue_detail.png)');
						targ.removeClass('imgright')
						targ.removeClass('imgleft')
						targ.addClass('imgright')
					} else {
						collPos=190+(coll-2)*187;
						targ.setStyle('background', 'url(img/ej/bg_blue_detail_inv.png)');
						targ.removeClass('imgright')
						targ.removeClass('imgleft')
						targ.addClass('imgleft')
					}
					targ.setStyle('top',linePos);
					targ.setStyle('left',collPos);			
				}
				

				//
			}
			else {
				if (device != undefined)
					device.toggleOut();
			}
			i++;
		});

	},
	
	reset : function() {
		//$E(".filters select").options[0].selected = true;
		for(var id in this.featureObject) {
			var elem = $(id);
			if (elem != undefined) 
				elem.checked = false;
		}
		for(var id in this.brandsObject) {
			var elem = $(id);
			if (elem != undefined)
				elem.checked = false;
		}
		for(var id in this.selectObjArray) {
			var elem = $(id);
			if (elem != undefined)
				elem.options[0].selected = true;
		}
//
	    yomoney.set(maxiprice)
//		
		this.onFilterChange();
	},
	
	setFilterResultsText : function(results) {
//		var e1 = new Element("span").addClass("red floatLeft").appendText("Resultaten: "); ej 12-1-2009
		var e1 = new Element("span").addClass("floatLeft").appendText("Resultaten: ");
		var t = "";
		switch(results.length) {
			case 0: t = "0 producten gevonden."; toggleVisibiltyOnElement('nothingfound', true); break;
			case 1: t = "1 product gevonden."; toggleVisibiltyOnElement('nothingfound', false); break;
			default: t = results.length + " producten gevonden.";toggleVisibiltyOnElement('nothingfound', false);
		}
//		var e2 = new Element("span").addClass("bold floatLeft");
		var e2 = new Element("span").addClass("floatLeft");

		e2.innerHTML = "&nbsp;&nbsp;" + t;

		if(results.length < this.deviceArray.length) {
//		var e3 = new Element("a").addClass("inline floatRight").setProperty("href","javascript:void(null);").appendText("Toon complete aanbod");
			var e3 = new Element("a").addClass("inline floatRight").setProperty("href","javascript:void(null);").appendText("Toon alle artikelen");
			e3.addEvent("click",function() {
				this.reset();
			}.bind(this));
		} else {
			var e3 = new Element("a").addClass("inline floatRight").setProperty("href","javascript:void(null);").appendText(" ");

		};
		
		var e4 = new Element("br");

		var filterDivText = $$("#filter-results")[0];
		filterDivText.innerHTML = "";
		e1.injectInside(filterDivText);
		e2.injectInside(filterDivText);
		e3.injectInside(filterDivText);
		e4.injectInside(filterDivText);
	},
	
	toggleFilters : function(toggle) {
		for(var id in this.featureObject) {
			var elem = $(id);
			if (elem != undefined) {
				elem.disabled = !toggle;
			}
		}
		for(var id in this.brandsObject) {
			var elem = $(id);
			if (elem != undefined) {
				elem.disabled = !toggle;
			}
		}
		/*for(var id in this.featureValueObject) {
			var elem1 = $(id);
			elem1.disabled = !toggle;
		}*/
		$$(".filters select").each(function(select) {
			select.disabled = !toggle;
		});
		if (typeof slidercomplete != 'undefined' && slidercomplete != null){
			$('slidercomplete').toggleClass('hidden')
		}
		
		//$E(".filters select").disabled = !toggle;
	},
		isFilterFilled : function() {
		var filterFilled= false;		
		for(var id in this.featureObject) {
			var elem = $(id);
			if ((elem != undefined) && (elem.checked)) 
				return true;
		}
		for(var id in this.brandsObject) {
			var elem = $(id);
			if ((elem != undefined) && (elem.checked)) 
				return true;
		}
		for(var id in this.selectObjArray) {
			var elem = $(id);
			if ((elem != undefined) && (elem.selectedIndex > 0)) 
				return true;
		}
		return filterFilled;
	},
	
	toggleFilterResultsDiv : function(toggle, noTweening) {
		var filterDiv = $("filter-results");
			if (filterDiv != null) {
	
			filterDiv.setStyle("display", "block");
			if(filterDiv.fxSlide == null) {
				filterDiv.fxSlide = new Fx.Slide(filterDiv, {duration: 400, transition: Fx.Transitions.circOut, fps: 50});
			}
			if(noTweening) {
				(toggle) ? filterDiv.fxSlide.show() : filterDiv.fxSlide.hide();
			}
			else if(toggle) {
				filterDiv.fxSlide.slideIn();
			}
			else {
				filterDiv.fxSlide.slideOut();
			}
		}
	}	
};

function initFilterDevices() {
	if($$(".device").length == 0) {
		return;
	}
	FilterDevices.toggleFilterResultsDiv(true,false);
	FilterDevices.init();
	if (FilterDevices.isFilterFilled())		
		FilterDevices.onFilterChange();
}

window.addEvent("load", initFilterDevices);
