/*GREETINGS!
this file contains the following classes:

Tires:
The tires class controls all of the 
*/

function tires() {		
	//protect scope
	var self = this;

	this.init = function () {
		//show the download link
		var downloadBroc = document.getElementById("download-brochure");
		downloadBroc.style.display="block";
		
		//go through the tire listings form and add event handlers
		var tireForm = document.getElementById("tire-listing-form");
		
		//we need to add event to labels AND inputs
		var tireInputs = tireForm.getElementsByTagName("input");
		var tireLabels = tireForm.getElementsByTagName("label");
		
		//for inputs we need to check to make sure its class is 
		//set to tire-radio before we assign the event handlers
		self.checkInputs(tireInputs);
		
		//for labels just assign them to 
		for(var i=0;i<tireLabels.length;i++) {
			tireLabels[i].onclick = self.toggle;
			tireLabels[i].onmouseover = self.toggle;
			tireLabels[i].onmouseout = self.toggle;
		}
	}
	
	this.checkInputs = function(inputs) {
		for(var i=0;i<inputs.length;i++) {
		match = /tire-radio/;	
		inputs[i].style.display="block";	
			if(match.test(inputs[i].className)) {
				inputs[i].onclick = self.toggle;
			}
		}
	}

	this.toggle = function(obj,reference) {
		//if the reference variable is true
		if(reference) {
			//then the object passed is assigned
			if(obj.parentNode.className == "selected"){
				obj.parentNode.className = "";
			} else {
				obj.parentNode.className = "selected";
			}
		} else {
		//otherwise, the object itself is firing the method
			if(this.parentNode.className == "selected") {
				this.parentNode.className = "";
			} else {
				this.parentNode.className = "selected";
			}
		}
	}
	
	this.test = function() {
		//this method checks to see if the inputs are checked on load
		//if they are it fires the toggle method
		var tireForm = document.getElementById("tire-listing-form");		
		var tireInputs = tireForm.getElementsByTagName("input");
		
		for(i=0;i<tireInputs.length;i++){
			if(tireInputs[i].checked) {
				self.toggle(tireInputs[i],true);
			}
		}
	}	
}

function tire() {
//  this is a tire object, its just here for reference
//	this.id; 
//	this.size = new Array();
//	this.application = new Array();
//  this.position;
}

function garage() {	
	var self = this; // preserve scope
	var emptyMessage = "No se encontraron neum\341ticos"; // used to indicate an empty section
	
	//contains all the tires in the garage
	this.tires = new Array();
	
	//adds a new tire to the garage
	this.add = function(tire) {
		this.tires[tire.id] = tire;
	}
	
	this.init = function() {
		//assigns event handlers to the select menus
		self.initSize();
		self.initPosition();
		self.initApplication();
	}
	
	this.initSize = function() {
		sizeMenu = document.getElementById("find-tire-size");
		sizeMenu.onchange = self.sortTires;
	}
	
	this.initPosition = function() {
		positionMenu = document.getElementById("find-tire-position");
		positionMenu.onchange = self.sortTires;
	}	
	
	this.initApplication = function() {
		applicationMenu = document.getElementById("find-tire-application");
		applicationMenu.onchange = self.sortTires;
	}

	//finds all the tires on the page
	//and adds them to the garage
	this.stockGarage = function() {
		//first find all the inputs
		inputs = document.getElementsByTagName("input");
		
		//for all the tires with the class tire radio
		match = /tire-radio/;
		for(var i=0;i<inputs.length;i++){
			if(match.test(inputs[i].className)){
				//i found the input that is a tire
				//lets start building the tire object
				var aTire = new tire();
				
				//the name 
				aTire.id = inputs[i].id;
				tireSizes = new Array();
				
				//the sizes are encoded as classes on the input object, seperated by spaces
				var sizes = inputs[i].className.split(" ");
				
				for(var j=1;j<sizes.length;j++){ //we skip the first class, as its always 'tire-radio'
					var rimSize = sizes[j].substring(4);
					rimSize = rimSize.replace("-","\.");
					tireSizes[tireSizes.length] = rimSize;
				}
				
				//now add the tire sizes
				aTire.size = tireSizes;
				
				tireApplications = new Array();
								
				//lastly find the application, applications are listed
				//as spans that are siblings with the tire input.
				applications = inputs[i].parentNode.getElementsByTagName("span");
				for(j=0;j<applications.length;j++){
					tireApplications[tireApplications.length] = applications[j].innerHTML;
				}				
				
				//now add the applications			
				aTire.application = tireApplications;
							
				//now add the tire position
				aTire.position = inputs[i].parentNode.parentNode.id;
				
				//finally add the tire to the garage.
				self.add(aTire);
			}
		}
	}	
	
	this.sortTires = function() {
		sizeMenu = document.getElementById("find-tire-size");
		positionMenu = document.getElementById("find-tire-position");
		applicationMenu = document.getElementById("find-tire-application");
				
		//first we need to spawn a tire lackey, he'll do our searches for us
		//we need to make sure we let the lackey know which garage he's searching 
		//inside, so we have to pass the 'self' variable.
		var tireLackey = new tireAssistant(self);
		
		//we get the lackey to find us the values of the dropdown menus
		
		var sizeArr = tireLackey.getTiresBySize(sizeMenu);
		var positionArr = tireLackey.getTiresByPosition(positionMenu);
		var applicationArr = tireLackey.getTiresByApplication(applicationMenu);
		
		//we are creating two new arrays, the first to compare the first two arrays.
		//the second to compare the results of the first comparison and the third array
		var results = new Array();
		var results2 = new Array();
		
		
		//iterate through the size Array and check for matches in the position array
		//return matches into the results array
		for(var i=0;i<sizeArr.length;i++){
			for(var j=0;j<positionArr.length;j++){
				if(positionArr[j].id == sizeArr[i].id) {
					results[results.length] = positionArr[j];
				}
			}
		}
		
		
		//now we parse through results and compare it to applicationArr
		//we return the matches into results2
		for(var i=0;i<results.length;i++){
			for(var j=0;j<applicationArr.length;j++){
				if(applicationArr[j].id == results[i].id) {
					results2[results2.length] = applicationArr[j];
				}
			}
		}
		
			
		//call show tires
		self.showTires(results2);
	}	
		
	this.showTires = function(tires) {
		//shows tires based on a passed array
		
		//we need to list them in the proper order, under the three categories
		//all position
		var allPosition = document.getElementById("todas-las-posiciones");	
		allPosition.innerHTML = "";
			
		//drive axle
		var driveAxle = document.getElementById("eje-de-traccion");
		driveAxle.innerHTML = "";
		
		//trailer axel
		var trailerAxle = document.getElementById("eje-de-remolque");
		trailerAxle.innerHTML = "";
		
		//each tire has the following inside its list item
		//an input with the id of the tire, name of the tire, and a class of tire-radio
		//a label for the id of the tire with an id of the tire with a -label
		//a hyperlink inside the label
		//a span inside the label with any applications
		
		//loop through the tires array
		
		for(var i=0;i<tires.length;i++){
			var newTire = document.createElement("li");
			
			//create the input checkbox
			var newTireInput = document.createElement("input");
			newTireInput.className = "tire-radio";
			newTireInput.id=tires[i].id;
			newTireInput.name="tread";
			newTireInput.type="checkbox";
			newTireInput.value=tires[i].id;
			
			//add the input to the tire
			newTire.appendChild(newTireInput);
			
			//create the label
			var newTireLabel = document.createElement("label");
			newTireLabel.htmlFor=tires[i].id;
			newTireLabel.id=tires[i].id+"-label";
			
			//create the anchor
			var newTireLink = document.createElement("a");
			var newTireHref = "tireInfo.do?tread="+tires[i].id;
			//plus signs are bad
			newTireHref = newTireHref.replace("+","%2B");
			newTireLink.href=newTireHref;
			newTireLink.innerHTML = tires[i].id;
			//add the anchor to the label
			newTireLabel.appendChild(newTireLink);

			
			//create the applications
			for(var j=0;j<tires[i].application.length;j++){
				//create a new span
				var newTireApplication = document.createElement("span");
				newTireApplication.className="tire-label-description";
				newTireApplication.innerHTML=tires[i].application[j];
				//add the span to the label
				newTireLabel.appendChild(newTireApplication);
			}
			
			//add the label to the new tire
			newTire.appendChild(newTireLabel);
			
			//now the list item is totally built 
			//add it to the appropriate section
			
			switch(tires[i].position) {
				case "todas-las-posiciones":
					allPosition.appendChild(newTire);			
					break;
				case "eje-de-traccion":
					driveAxle.appendChild(newTire);
					break;
				case "eje-de-remolque":
					trailerAxle.appendChild(newTire);
					break;
			}
			
		}
		
		//if any of the sections have nothing in them, add a dummy list item		
		self.checkForEmpties(allPosition);
		self.checkForEmpties(driveAxle);
		self.checkForEmpties(trailerAxle);
		
		//re-add toggle events
		tireListings.init();
	}
		
	this.checkForEmpties = function(position) {
		if(position.getElementsByTagName("li").length==0) {
			var dummy = document.createElement("li");
			dummy.innerHTML = emptyMessage;
			position.appendChild(dummy);
		}
	}
}

function tireAssistant(self) {
	//this is the tire assistant class
	//it helps by searching for tires in the garage
	this.getTiresBySize = function(sizeMenu) {
		
		var size = sizeMenu.options[sizeMenu.selectedIndex].value;
      
		var returnTires = new Array();		
		if(size == "Todos" || size == ""){
			//if all tires is chosen, just pass the showTires method
			//the entire garage of tires.
			for(var i in self.tires) {
				returnTires[returnTires.length] = self.tires[i];	
			}
		}
		//iterate through the tires finding the 'size' variable
		//and return an array with all the tires that match that size

		for(var i in self.tires){
			tireSizes = self.tires[i].size;
			for(var j=0;j<tireSizes.length;j++){
				if(tireSizes[j] == size) {
					returnTires[returnTires.length] = self.tires[i];
				}
			}
		}
		return returnTires;
	}
	
	this.getTiresByPosition = function(positionMenu) {
		var position = positionMenu.options[positionMenu.selectedIndex].value;
		position = position.replace(" ", "-").toLowerCase();
		// Replace second space
		position = position.replace(" ", "-").toLowerCase();
		position = position.replace("\u00F3", "o").toLowerCase();
		
		var returnTires = new Array();

		if(position == "todas" || position == "") {
			//if all position are chosen, show all tires.
			for(var i in self.tires) {
				returnTires[returnTires.length] = self.tires[i];	
			}
		}
				
		for(var i in self.tires) {
			tirePositions = self.tires[i].position;
			if(position == tirePositions) {
				returnTires[returnTires.length] = self.tires[i];
			}
		}
		return returnTires;
	}
	
	this.getTiresByApplication = function(applicationMenu) {
		var application = applicationMenu.options[applicationMenu.selectedIndex].value;
		var returnTires = new Array();
		
		if(application == "Todos" || application == "") {			
			//if all position are chosen, show all tires.
			for(var i in self.tires) {
				returnTires[returnTires.length] = self.tires[i];	
			}
		}

		for(var i in self.tires) {
			tireApplications = self.tires[i].application;
			for(j=0;j<tireApplications.length;j++){
				if(tireApplications[j]==application) {
					returnTires[returnTires.length] = self.tires[i];
				}
			}
		}		
		return returnTires;
	}
}
var myTires = new garage();
//stock that garage!
//Event.addEvent(window,'load',myTires.stockGarage);
//add event hooks to dropdowns
//Event.addEvent(window,'load',myTires.init);
//sort the tires!
//Event.addEvent(window,'load',myTires.sortTires);

var tireListings = new tires();
//Event.addEvent(window,'load',tireListings.init);
//Event.addEvent(window,'load',tireListings.test);

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(myTires.stockGarage);
addLoadEvent(myTires.init);
addLoadEvent(myTires.sortTires);
addLoadEvent(tireListings.init);
addLoadEvent(tireListings.test);

