function $() {
	var els = new Array();
	for (var i = 0; i < arguments.length;i++) {
		var el = arguments[i];
		if (typeof el == 'string') {
			el = document.getElementById(el);
		}
		if (arguments.length == 1) {
			return el;
		}
		els.push(el);
	}
	return els;
}

if( document.all && !document.getElementsByTagName ) {
  document.getElementsByTagName = function( nodeName ) {
    if( nodeName == '*' ) return document.all;
    var result = [], rightName = new RegExp( nodeName, 'i' ), i;
    for( i=0; i<document.all.length; i++ )
      if( rightName.test( document.all[i].nodeName ) )
	result.push( document.all[i] );
    return result;
  };
}

document.getElementsByClassName = function( className, nodeName ) {
  var result = [], tag = nodeName||'*', node, seek, i;
    var rightClass = new RegExp( '(^| )'+ className +'( |$)' );
    seek = document.getElementsByTagName( tag );
    for( i=0; i<seek.length; i++ )
      if( rightClass.test( (node = seek[i]).className ) )
	result.push( seek[i] );
  return result;
};

var Event = function () {
	
	// cache of wrapped event functions.
	var listeners = [];
	
	return {
		/**
		 * Appends an event handler
		 *
		 * @param {Object}   el        The html element to attach the
		 *                             event to
		 * @param {String}   eventType	The type of event to attach
		 * @param {Function} fn        The method the event invokes
		 * @return {boolean} True if the action was successful,
		 *                        false if one or more of the elements
		 *                        could not have the event attached to it.
		 */
		addEvent: function(el, eventType, fn, scope) {
			//console.log('addEvent() - el: '+el+" eventType: "+eventType+" fn: "+fn);
			if (this._isCollection(el)) {
				// we've been passed an array of elements or ids to use.
				var isOk = true;
				for (var i=0; i< el.length; ++i) {
						isOk = ( this.addEvent(el[i], eventType, fn, scope) && isOk );
				}
				return isOk;
			
			}
			else if (typeof el == "string") {
				// element we're adding to is the name, not the object.
				el = document.getElementById(el);
			}
			
			// failsafe incase we haven't transformed from a string. 
			if (!el) {
					return false;
			}
			
			var wrappedFn = function(e) {
				return fn.call(el,e,scope);
			};

			var li = [el, eventType, fn, wrappedFn, scope];
			var index = listeners.length;
			// cache the function name so we can try to unload the wrapped function by the incoming name
			listeners[index] = li;
			
			if (el.addEventListener) {
				el.addEventListener(eventType, wrappedFn, false);
			} else if (el.attachEvent) {
				el.attachEvent("on"+eventType, wrappedFn);
			}
			wrappedFn = null;
			return true;
		}, // addEvent
		removeEvent: function(el, eventType, fn) {
			if (this._isCollection(el)) {
				// we've been passed an array of elements or ids to use.
				var isOk = true;
				for (var i=0; i< el.length; ++i) {
						isOk = ( this.removeEvent(el[i], eventType, fn) && isOk );
				}
				return isOk;
			
			}
			else if (typeof el == "string") {
				// element we're adding to is the name, not the object.
				el = document.getElementById(el);
			}

			// Get wrapped function by looking up original function in the cache.
			var cacheItem = null;
			var index = this._getCacheIndex(el, eventType, fn);

			if (index >= 0) {
					cacheItem = listeners[index];
			}

			// if the event function isn't cached, we can't remove it.
			if (!el || !cacheItem) {
					return false;
			}
			
			var cachedFunction = cacheItem[3];
			
			if (el.removeEventListener) {
					el.removeEventListener(eventType, cachedFunction, false);
			} else if (el.detachEvent) {
					el.detachEvent("on" + eventType, cachedFunction);
			}
			
			// removed the wrapped handler
			delete listeners[index][3];
			delete listeners[index][2];
			delete listeners[index];
			
			return true;
		}, // removeEvent
		stopEvent: function(ev) {
				this.stopPropagation(ev);
				this.preventDefault(ev);
		},
		
		/**
		* Stop an event from firing
		*/
		stopPropagation: function(ev) {
				if (ev.stopPropagation) {
						ev.stopPropagation();
				} else {
						ev.cancelBubble = true;
				}
		},
		preventDefault: function(ev) {
				if (ev.preventDefault) {
						ev.preventDefault();
				} else {
						ev.returnValue = false;
				}
		},		
		getPageX: function(el) {
			return this.getPageXY(el).pageX;
		},
		
		getPageY: function(el) {
			return this.getPageXY(el).pageY;
		},
		
		getPageXY: function(elem) {
			var offsetTrail = elem;
			var offsetLeft = 0;
			var offsetTop = 0;
			while (offsetTrail) {
					offsetLeft += offsetTrail.offsetLeft;
					offsetTop += offsetTrail.offsetTop;
					offsetTrail = offsetTrail.offsetParent;
			}
			if (navigator.userAgent.indexOf("Mac") != -1 && 
					typeof document.body.leftMargin != "undefined") {
					offsetLeft += document.body.leftMargin;
					offsetTop += document.body.topMargin;
			}
			return {pageX:offsetLeft, pageY:offsetTop};
		},
		removeAllEvents: function(el,obj) {
			
			if (listeners && listeners.length > 0) {
				for (var i = 0; i < listeners.length; ++i) {
					var l = listeners[i];
					if (l) {
						obj.removeEvent(l[0], l[1],l[2]);
					}
				}
				listeners = null;
			}
		},
		getListeners: function() {
			return listeners;
		},
		/**
		 * @private
		 * Locating the saved event handler data by function ref
		 */
		_getCacheIndex: function(el, sType, fn) {
				for (var i=0; i< listeners.length; ++i) {
						var li = listeners[i];
						if ( li           &&
								 li[2] == fn  &&
								 li[0] == el  &&
								 li[1] == sType ) {
								return i;
						}
				}

				return -1;
		},		
		/**
		* Tests for collections/arrays.
		*
		* @param {Object}	obj	The object to test.
		* @return {boolean}	True if valid collection.
		* @private
		*/
		_isCollection: function(obj) {
			return ( obj										&& // o is something
							 obj.length							&& // o is indexed
							 typeof obj != "string"	&& // o is not a string
							 !obj.tagName						&& // o is not an HTML element
							 !obj.alert							&& // o is not a window
							 typeof obj[0] != "undefined");
		} // _isCollection */
	};
} ();

Event.addEvent(window,"unload",Event.removeAllEvents,Event);


var  dealerLocator = new function() {
	
//	this.liveUrl = /www\.michelintruck\.com/;
	
	this.init = function() {
		//find the dl button
		var buttons = document.getElementsByTagName("a");
		var match = /dealerLocator/;		
		for(var i=0;i<buttons.length;i++) {
			if(match.test(buttons[i].className)) {
				buttons[i].onclick = dealerLocator.launch;
			}
		}
		
		//find retread dealer buttons
		match = /retreadDealer/;
		for(var i=0;i<buttons.length;i++){
			if(match.test(buttons[i].className)) {
				buttons[i].onclick = dealerLocator.launch;
			}
		}
	}
		
	this.launch = function() {
		var urlParams="";
		
		
		if(this.className=="retreadDealer") {
			urlParams="?retreads=checked";
		}
		
		url = "http://" + window.location.host + "/dl/index.html";
		
		if(arguments[0] != null) {
			if(arguments[0].length > 1) {
				var zipCode = arguments[0];
				var postalMatch = /^[a-zA-Z][0-9][a-zA-Z]\s?[0-9][a-zA-Z][0-9]$/; // choose Canada if we have a postal code.
				var countryCode = postalMatch.test(zipCode) ? "CA" : "US";
				urlParams="?selCountry="+countryCode+"&txtDistance=75&txtPostalCode="+zipCode;
			} 
		}
		
		url = url + urlParams;
		
		window.open(url,null,"width=800,height=700,resizable=yes,status=yes,toolbar=yes,menubar=yes,location=no,scrollbars=1");
		return false;
	}
	this.launchFlash = function() {
		this.launch();
	}
}

var warrantyPopup = new function() {
	this.init = function() {
		//find the dl button
		var buttons = document.getElementsByTagName("a");
		var match = /warrantyPopup/;		
		for(var i=0;i<buttons.length;i++) {
			if(match.test(buttons[i].className)) {
				buttons[i].onclick = warrantyPopup.launch;
			}
		}
	}	
	this.launch = function() {
		window.open("/assets/pdf/MLN_Truck_Tire_Warranty.pdf",null,"status=yes,toolbar=no,menubar=no,location=no");
		return false;
	}
}

var retreadWarrantyPopup = new function() {
	this.init = function() {
		//find the dl button
		var buttons = document.getElementsByTagName("a");
		var match = /retreadWarrantyPopup/;		
		for(var i=0;i<buttons.length;i++) {
			if(match.test(buttons[i].className)) {
				buttons[i].onclick = retreadWarrantyPopup.launch;
			}
		}
	}	
	this.launch = function() {
		window.open("/assets/pdf/MRTWarranty.pdf",null,"status=yes,toolbar=no,menubar=no,location=no");
		return false;
	}
}


var printPreview = new function() {
	//this function should be extended down the line to show the print
	//stylesheet and pop up the print dialog box
	//for now it just runs window.print
	this.init = function() {
		var buttons = document.getElementsByTagName("a");
		var match = /print/;
		for(var i=0;i<buttons.length;i++) {
			if(match.test(buttons[i].className)) {
				//change this method to preview 
				buttons[i].onclick = printPreview.printPage;
			}
		}
	}
	this.printPage = function() {
		window.print();
		return false;
	}
}

function openInNewWindow(e) {
	// Change "_blank" to something like "newWindow" to load all links in the same new window
	var newWindow = window.open(this.getAttribute('href'), '_blank');
	newWindow.focus();
	Event.stopEvent(e);
	return false;
}

Event.addEvent(window,'load',warrantyPopup.init);
Event.addEvent(window,'load',retreadWarrantyPopup.init);
Event.addEvent(window,'load',dealerLocator.init);
Event.addEvent(window,'load',printPreview.init);

