var aTermsList = []
// Search functionality
var iMinLength=2; // Number specifiying the number of characters required before search commences.
var searchString = "";
var arrSubTerms = new Array();
var arrSResults = new Array();
var arrURL = new Array();
var aDataSet = new Array();
var sResults = "";
var counter;
var arrSearch ;
var blnIsMatch;
var strComp;
var sOutput;

// test domain
var current_domain = (document.location.hostname.test('ford.com','i')) ? 'ford' : 'dev';
var initial_js_path  = (current_domain == 'ford') ? '/':'';

function Blank_TextField_Validator(searchform)
{   
	if (searchBox.inputbox.value.length < 1){						
		document.searchform.action= "/search/advanced-search";	
	}else{
		document.searchform.searchtext.value=searchBox.inputbox.value;						
		document.searchform.action= "/search/search-results";					
	}
	document.searchform.submit(); 
}

function updateList(newList) {
	aTermsList = newList;
}

function checkHTML(obj) {
  if (obj && obj.value != '') {
    if(/<[^>]*>/.test(obj.value)) {
      return false;
    }
    else {
      return true;
    }
  } // end if obj
}

function findMatches(sString,flashSearch){
	sResults = "";
	result_string = doSearch(sString, aTermsList, 10,'',flashSearch);

	if (flashSearch == true) {
		return result_string;
	} // end if it's flash search
} // end findMatches()

function doSearch(sString, aDataSet, iMaxResults, sResultTitle,flashSearch) {
	arrSResults.length = 0;
	arrSubTerms.length = 0;
	counter = 1;

	if ((sString.charAt(0) != " ") && (sString.length >= iMinLength)) {
		// Search Terms
		arrSearch = sString.split(" ");
		// loop through the data set
		for (var k = 0; k < aDataSet.length; k++) {

			if (matchPhrase(k, aDataSet)) {
			//if the phrase matches all the substrings in the search query add it to the results
				addToResults(aDataSet[k]);
			}
		} // end loop through the data set
	}
	else {
		arrSResults.length=0;
	} // end else sString

	if(flashSearch){
		return arrSResults;
	}else{
		formatResults(arrSResults,sResultTitle);
	}

} // end doSearch()

//See if the phrase matches the search query terms
function matchPhrase(iPhraseIndex, aDataSet) {
	var blnPhraseMatch = true;
	// for every item in the original prase, create a subset of the individual words
	arrSubTerms = aDataSet[iPhraseIndex].split(" ");
	// for each term in the search query see if it matches any word in the phrase
	for (var j = 0; j < arrSearch.length; j++) { //SearchTerm in arrSearch) {
		if (blnPhraseMatch) {
			//only try to set if it is true else leave it as false since any false result shows that the query term doesn't match at least one word in the phrase
			blnPhraseMatch = matchSearchTerm(j, arrSubTerms)
		}
	}
	return blnPhraseMatch;
}

//Determine if the search term matches at least one word in the phrase
function matchSearchTerm(iSearchIndex, arrSubTerms) {
	blnIsMatch = false;// assume it doesn't match
	searchString = arrSearch[iSearchIndex];
	// check for minimum requirements
	if (searchString.charAt(0) != " " && searchString.length >= iMinLength){
		// for each word in the phrase check if there is at lease one string match with this search term.			
		for (var i = 0; i < arrSubTerms.length; i++) { //word in arrSubTerms){
		// define the target string
		strComp = arrSubTerms[i].substr(0, searchString.length);
			if (!blnIsMatch) {//only try to set if it is false, else leave it as true to show that the search team matches at lease one word
			// check for a match
				blnIsMatch = compareStrings(searchString,strComp)
			}
		}
	}
	return blnIsMatch
}			

function compareStrings(sString,sComp){
	if(sString == sComp.toLowerCase())
		return true;
	else
		return false;
}

function addToResults(result){
	arrSResults.push(result);
	counter++;
}

function formatResults(results, sResultTitle){
	var className = "terms";
	if(results.length!=0){
		for (var t = 0; t < results.length; t++) { // in results){
			sResults += "<dd class='" + className + "'><span>" + results[t] + "</span></dd>";
		}
		sOutput = "<dl>";
		sOutput += sResults;
		sOutput += "</dl>";

	} else {
		sResults = "";
	}
	if(sResultTitle == "Possible Link Matches"){
		//writeResults(sResults);
	}
}

function writeResults(sResults){
	document.getElementById("searchResults").className = "searchRevealed";
	sOutput = "<dl>";
	sOutput += sResults;
	sOutput += "</dl>";
	document.getElementById("searchResults").innerHTML = sOutput;
}

function search_reset(fElement) {
		fElement.value = '';
		document.getElementById("searchResults").className = "searchHidden";
		document.getElementById("searchResults").innerHTML = '';
}

function getIMinLength(){
	return iMinLength;
}

function checkInputFlash(s){
	var currentinput = s;
	var url = initial_js_path + 'js/searchResults.htm?q='+ currentinput;  
	// flash is setting the number of characters before querying
	var SearchArray = new Ajax(url, {method: 'get',evalScripts:false,onComplete:processSearch}).request();
	this.inputvalue=s;      
	return findMatches(this.inputvalue.toLowerCase(), true);
	 
} // end checkInputFlash()


Options = new Class({
	initialize: function(attachto, name, width) {
		this.name=name;
		this.width=width;
		// Create div
		this.selfdiv = attachto;
		this.selfdiv.style.position = 'absolute';
		this.selfdiv.style.width='156px';
		//this.selfdiv.style.border='1px solid black';
		this.selfdiv.className='droplist';
		this.selfdiv.style.display='none';
		
	},
	hide: function() {
		//alert('hide');
		if (this.selfdiv.style.display != 'none') {
			this.selfdiv.style.display='none';
		}
	},
	show: function() {
		//alert('show '+(this.selfdiv.innerHTML+"").trim());
		if (this.selfdiv.style.display != 'block') {
			if ((this.selfdiv.innerHTML+"").trim() != '') {
				this.selfdiv.style.display='block';
			}
		}
	}
});

var DropWidget = new Class({
	setOptions: function(options) {
		// Default options
		this.options = {
			width: '146px',
			emptyMessage: null,
			onBlur: null,
			defaultValue: '',
			className:'',
			loadingImage: null
		};
		Object.extend(this.options, options || {});
	},
	
	initialize: function(name, options) {
		this.setOptions(options);
		this.name = name;
		//	this.loadurl = loadurl;
		// Document.write the textarea
		document.write('<input type="text" id="'+this.name+'_holder_id" value=""><div id="'+this.name+'_div_id"></div>');
		this.inputbox = $(this.name+'_holder_id');
		this.divholder = $(this.name+'_div_id');
		this.inputbox.value = this.options.defaultValue;
		this.inputbox.className = this.options.className;
		//dbgr.printObject(this.inputbox.style.properties);
		//var teststr="test1";
		//dbgr.printObject(teststr);
		this.inputbox.setAttribute("autocomplete", "off");
		this.optionsdiv = new Options(
			this.divholder,
			this.name,  
			this.options.width
		);
		this.inputvalue=this.inputbox.value;
		this.usedkeys = false;
		this.changedTerm = false;
		//this.checkInput.periodical(.2, this);
		this.inwidget = false;
		// Show the widget
		this.inputbox.addEvent('mouseup', this.focusInput.bind(this));
		// Don't let it hide on a document click if we are in the widget
		this.inputbox.addEvent('mouseover', function() {this.inwidget=true;}.bind(this));
		this.optionsdiv.selfdiv.addEvent('mouseover', function() {this.inwidget=true;}.bind(this));
		this.inputbox.addEvent('mouseout', function() {this.inwidget=false;}.bind(this));
		this.optionsdiv.selfdiv.addEvent('mouseout', function() {this.inwidget=false;}.bind(this));
		// Focus blank, show emptyMessage
		if (this.options.emptyMessage != null) {
			this.inputbox.addEvent('focus', function() {
				if (this.inputbox.value.trim() == '') {
					this.optionsdiv.selfdiv.innerHTML = this.options.emptyMessage;
					this.optionsdiv.show();
				}
				else if (this.inputbox.value == this.options.defaultValue) {
					this.inputbox.value = '';
					this.optionsdiv.selfdiv.innerHTML = this.options.emptyMessage;
					this.optionsdiv.show();
				}
				this.focusInput();
			}.bind(this));
			
		}
		else {
			this.inputbox.addEvent('focus', function() {
				if (this.inputbox.value == this.options.defaultValue) {
					this.inputbox.value = '';
				}
			}.bind(this));
		}
		if (this.options.onBlur != null) {
			this.inputbox.addEvent('blur', this.blurInput.bind(this));
		}
		else {
			this.inputbox.addEvent('blur', function() {
				if (this.inputbox.value == '') {
					this.inputbox.value = this.options.defaultValue;
				}
			}.bind(this));
		}
	},
	focusInput: function() {
		this.optionsdiv.show();
		// Here we register an event that hides the options window when we click anywhere else
		// TODO: what happends if this gets called before the page is done loading?
		document.onmousedown = function() {
			// Only hide if we aren't in the widget box
			if (!this.inwidget) {
				this.optionsdiv.hide();
				this.inputbox.onkeypress = null;
				this.inputbox.onkeydown = null;
				//this.inputbox.removeEvent('keypress', this.keyDown);
			}
		}.bind(this);
		//this.inputbox.onkeypress = this.keyDown.bind(this);
		//this.inputbox.addEvent('keypress', this.keyDown.bind(this));
		//this.inputbox.onkeydown = this.keyDown.bindAsEventListener(this);
		if (document.all) {
			this.inputbox.onkeyup = function (evnt) {this.keyDown(evnt);}.bind(this);
			//this.inputbox.onkeydown = this.keyDown.bindAsEventListener(this);
		} else {
			this.inputbox.onkeyup = this.keyDown.bind(this);
		}
	},
	blurInput: function() {
		if (!this.inwidget) {
			// If we are in the widget, then this will get taken care of in the clickOption event
			this.options.onBlur();
		}
	},
	keyDown: function(evnt) {
		if (window.event) {
			var keyCode = window.event.keyCode;
		} else {
			var keyCode = evnt.keyCode;
		}
		if (keyCode == 40 || keyCode == 38) {
			this.changedTerm = true;
			// 40 = Down, 38 = Up
			var currentSel = $E('dd.selected', this.optionsdiv.selfdiv);
			//dbgr.alert(currentSel.childNodes[0].childNodes[0].nodeValue);
			if (keyCode == 38) {
				// Up
				if (currentSel && currentSel.previousSibling) {
					currentSel.removeClass('selected');
					currentSel.previousSibling.addClass('selected');
					this.inputbox.value=currentSel.previousSibling.childNodes[0].childNodes[0].nodeValue;
					currentSel = currentSel.previousSibling;
					
				} else if (!currentSel) {
					var tempSel = $ES('dd', this.optionsdiv.selfdiv);
					if (tempSel && tempSel.length > 0) {
						tempSel[tempSel.length-1].addClass('selected');
						this.inputbox.value=tempSel[tempSel.length-1].childNodes[0].childNodes[0].nodeValue;
					}
					currentSel = tempSel[tempSel.length-1];
				}
			} else if (keyCode == 40) {
				// Down
				if (currentSel && currentSel.nextSibling) {
					currentSel.removeClass('selected');
					currentSel.nextSibling.addClass('selected');
					this.inputbox.value=currentSel.nextSibling.childNodes[0].childNodes[0].nodeValue;
					currentSel = currentSel.previousSibling;
				} else if (!currentSel)  {
					var tempSel = $E('dd', this.optionsdiv.selfdiv);
					if (tempSel) {
						tempSel.addClass('selected');
						this.inputbox.value=tempSel.childNodes[0].childNodes[0].nodeValue;
						return false;
						currentSel = tempSel;
					}
				}
			}
			if (currentSel != null) {
				var top = (currentSel.getTop() - this.optionsdiv.selfdiv.getFirst().getTop())
				var scroller = new Fx.Scroll(this.optionsdiv.selfdiv.getFirst()).scrollTo(false, top); 
			}
			return false;
		} 
		else if (keyCode ==  13) {
			// Press Enter
			var currentSel = $E('dd.selected', this.optionsdiv.selfdiv);
			if (!currentSel) {
				var currentSel = $E('dd', this.optionsdiv.selfdiv);
			}
			if (currentSel) {
				this.clickOption(currentSel);
			}
			return false;
		}
		else {
			this.checkInput();
			this.changedTerm = false;
		}
		return true;
	},
	checkInput: function() {
		if (!this.changedTerm) {
			var currentinput = this.inputbox.value;
			if (currentinput.length == 0) {
				if (this.options.emptyMessage == null) {
					this.optionsdiv.hide();
				} else {
					this.optionsdiv.selfdiv.innerHTML = this.options.emptyMessage;
				}
			} else if ((this.inputvalue != currentinput) && (currentinput.length == 1)) {
				var url = initial_js_path + 'js/searchResults.htm?q='+ currentinput;
				var SearchArray = new Ajax(url, {method: 'get',evalScripts:false,onComplete:processSearch}).request();
			} else if ((this.inputvalue != currentinput) && (currentinput.length >= iMinLength)) {
				this.inputvalue=this.inputbox.value;
				findMatches(this.inputvalue.toLowerCase(),false);
				if (sResults.trim() == '') {
					if (this.options.emptyMessage == null) {
						this.optionsdiv.hide();
					} else {
						this.optionsdiv.selfdiv.innerHTML = this.options.emptyMessage;
						this.optionsdiv.show();
					}
				} else {
					this.optionsdiv.selfdiv.innerHTML=	sOutput;
					this.optionsdiv.show();
				}
	
				if ($ES('dd', this.optionsdiv.selfdiv).length > 10) {
					this.optionsdiv.selfdiv.addClass('scroll');
					}
				else {
					this.optionsdiv.selfdiv.removeClass('scroll');
					}
				$ES('dd', this.optionsdiv.selfdiv).each(function(elemnt, i) {
					elemnt.addEvent('mouseover', function() {
						if (this.changedTerm) {
							$ES('dd.selected', this.optionsdiv.selfdiv).each(function (el) {
								// Take all of them off incase we used the UP and DOWN keys
								el.removeClass('selected');
							});
						}
						this.usedkeys = false;
						elemnt.addClass('selected');
					}.bind(this));
					elemnt.addEvent('mouseout', function() {
						elemnt.removeClass('selected');
					});
					elemnt.addEvent('click', function() {this.clickOption(elemnt);}.bind(this));
				}.bind(this));
			}
		}
	},
	clickOption: function(elemnt) {
		this.inputbox.value=elemnt.childNodes[0].childNodes[0].nodeValue;
		this.changedTerm = true;
		this.optionsdiv.hide();
		window.self.focus();
		return false;
	}
});
// --------- End Search bar --------- //

// process Ajax Search Results
function processSearch() {
  updateList(this.response.text.split(','));
}

// --------- Main Nav Drop Downs --------- //
var DropDownMenu = {

initialize: function() { 
  if (!$('GlobalNav')) {
	 return false
  }
  this.menu = $('GlobalNav');
  this.id = this.menu.id;
  this.duration = 250;
  this.buttons = [];

  $A(this.menu.getElementsByTagName('li')).each(
   function(li) {
    if((li.parentNode == this.menu) && (li.id != 'NavItem-1')) { this.buttons.push($(li)); }
   }.bind(this)
  );

/*
  $ES('.top-link').each(
	function(el) {
		el.href = "#";
	}.bind(this)
  );
*/

  this.submenus = $A(this.menu.getElementsByTagName('ul'));

  this.submenus.each(
   function(submenu) {
		submenu = $(submenu);
		submenu.setStyle('display','block');
    submenu.originalHeight = submenu.offsetHeight;
    submenu.effect = new Fx.Style(submenu, 'height',{ duration: this.duration });
    submenu.effect.hide();
   }.bind(this)
  );

  this.buttons.each(
   function(button) {
    button.addEvent('mouseover',this.expand.bindAsEventListener(this));
    button.addEvent('mouseout', this.collapse.bindAsEventListener(this));
   }.bind(this)
  );
  return true;
 },

 findButton: function(element) {
  var button = false;
  while(element.parentNode) {
   if(this.buttons.test(element)) { button = element; }
   element = element.parentNode;
  }
  return button;
 },

 findSubmenu: function(element) {
  var button = this.findButton(element);
  var submenu = button.getElementsByTagName('ul')[0];
  return submenu;
 },

 expand: function(event) {
  var submenu = this.findSubmenu(event.target || event.srcElement);
	submenu.effect.clearTimer();
  submenu.effect.custom(submenu.effect.now, submenu.originalHeight);
 },

 collapse: function(event) {
  var submenu = this.findSubmenu(event.target || event.srcElement);
  submenu.effect.clearTimer();
  submenu.effect.custom(submenu.effect.now, 0);
 }

};
// --------- END Main Nav Drop Downs --------- //

// --------- Util (top right) Drop Downs --------- //
var ExpandMenu = {

 initialize: function() {
  if ($('home') && $('FordLatino')) {
  	this.menu = $('GlobalLinks');
  	this.id = this.menu.id;
  	this.duration = 450;
  	this.buttons = [];
  	this.buttons.push($('FordLatino'));
		submenu = $('FordLatino').getElementsByTagName('div')[0];
		submenu.style.display = 'block';
		submenu.originalHeight = submenu.offsetHeight;
		submenu.effect = new Fx.Style(submenu, 'height',{ duration: this.duration });
		submenu.effect.hide();
  	this.buttons.each(
   	function(button) {
    	button.addEvent('mouseover',this.expand.bindAsEventListener(this));
    	button.addEvent('mouseout', this.collapse.bindAsEventListener(this));
   	}.bind(this)
  	);
  	return true;
  } // end if home && FordLatino
 },

 findButton: function(element) {
  var button = false;
  while(element.parentNode) {
   if(this.buttons.test(element)) { button = element; }
   element = element.parentNode;
  }
  return button;
 },

 findSubmenu: function(element) {
  var button = this.findButton(element);
  var submenu = button.getElementsByTagName('div')[0];
  return submenu;
 },

 expand: function(event) {
  var submenu = this.findSubmenu(event.target || event.srcElement);
  submenu.effect.clearTimer();
  submenu.effect.custom(submenu.effect.now, submenu.originalHeight);
 },

 collapse: function(event) {
  var submenu = this.findSubmenu(event.target || event.srcElement);
  submenu.effect.clearTimer();
  submenu.effect.custom(submenu.effect.now, 0);
 }

};
// --------- Util (top right) Drop Downs --------- //


// --------- Bubbles (Glossary, Email Form, etc.) ------- //
var Bubble =  {
	setOptions: function(options){
		this.options = {
			maxTitleChars: 30,
			maxOpacity: 1,
			timeOut: 100,
			className: 'tooltip'
		}
		Object.extend(this.options, options || {});
	},							 

	initialize: function(elements, options){
		//hide footnote
		if($$('.tip') == '' && ($('print-head')) && $$('.external') == '' ) { 
			return false;
		}
		
		if ($('footnote') && $$('.tip') != '') { $('footnote').setStyle('display', 'none') }
		if ($$('.mod-term')) { 
			$A($$('.mod-term')).each(function(el){
				el.setStyle('display', 'block') 
			}, this);
		}
		if ($$('.mod-glossary')) { 
			$A($$('.mod-glossary')).each(function(el){
				el.setStyle('display', 'none') 
			}, this);
		}
		this.tipElements = $$('.tip');
		this.extLinks = $$('.external');
		this.setOptions(options);
		this.toolTip = new Element('div').addClass(this.options.className).setStyle('position', 'absolute').injectInside(document.body);
		this.toolTipInner = new Element('div').addClass('tooltipinner').injectInside(this.toolTip);
		this.toolTitle = new Element('H4').injectInside(this.toolTipInner);
		this.toolText = new Element('p').injectInside(this.toolTipInner);
		this.toolBot = new Element('div').addClass('tooltipbot').injectInside(this.toolTip);
		this.toolTip.setStyle('display', 'none');
		$A(this.tipElements).each(function(el){
			if ($('footnote')) {
			$ES('dt','footnote').each(function(term,idx){
				if (term.innerHTML.test(el.innerHTML,"ig") != null) {
					if (el.innerHTML == term.innerHTML.substr(0,term.innerHTML.indexOf(':'))) {
					  el.myTitle = term.innerHTML;
				  	  el.myText =  $ES('dd','footnote')[idx].innerHTML;
					}
				}
			});
			} else if (el.getParent().hasClass('mod-term')) {
				getID = el.href.split("#")
				title = $(getID[1]).getFirst();
				text = title.getNext();
				el.myTitle = title.innerHTML;
				el.myText =  text.innerHTML;
			};
			el.onmouseover = function(){
				this.show(el);
				return false;
			}.bind(this);
			el.onmousemove = this.locate.bindAsEventListener(this);
			el.onmouseout = function(){
				this.disappear();
			}.bind(this);
		}, this);
		$A(this.extLinks).each(function(el){
			el.myTitle = '';
			if (el.getProperty('tip')) { el.myText = el.getProperty('tip'); }
			else { el.myText = 'Clicking on this link will take you to a third-party website.' }
			el.onmouseover = function(){
				this.show(el);
				return false;
			}.bind(this);
			el.onmousemove = this.locate.bindAsEventListener(this);
			el.onmouseout = function(){
				this.disappear();
			}.bind(this);

		}, this);
		return true
	},
	

	show: function(el){
		if(el.hasClass('external') || el.hasClass('lang')) { this.toolText.addClass('ext'); this.toolTitle.setStyle('display', 'none') }
		else { this.toolText.removeClass('ext'); this.toolTitle.setStyle('display', 'block') }
		this.toolTitle.innerHTML = el.myTitle;
		this.toolText.innerHTML = el.myText;
		this.toolTip.setStyle('display', 'block')
	},

	appear: function(){
		this.toolTip.setStyle('display', 'block')
	},

	locate: function(evt){
		var doc = document.documentElement;
		
		if ((evt.clientX + doc.scrollLeft) >= 450 ) {
			var leftPos = evt.clientX + doc.scrollLeft - 220;
			this.toolTipInner.addClass('right');
			this.toolBot.addClass('rightbot');
		}
		else {
			var leftPos = evt.clientX + doc.scrollLeft + 35;
			this.toolTipInner.removeClass('right');
			this.toolBot.removeClass('rightbot');
		}	
		this.toolTip.setStyles({'top': evt.clientY + doc.scrollTop - 35 + 'px', 'left': leftPos + 'px'});
	},

	disappear: function(){
		this.toolTip.setStyle('display', 'none')
	}

};

function launchWin(URL,width,height,top,left) {
	window.open(URL,'','width='+ width +',height='+ height +',top='+ top +',left='+ left +',toolbar=1,status=1,scrollbars=1,resizable=1,menubar=1'); 
	return false
}

var isFordFormsLoaded = false;
var fordFormsLoading = false;
var isToolsLoaded = false;
var toolsLoading = false;
var isValidateLoaded = false;
var validateLoading = false;
var isFaqLoaded = false;
var faqLoading = false;

function setLoaded(scriptName) {
	switch (scriptName) {
		case 'fordForms': 
			isFordFormsLoaded = true;
			break;
		case 'tools': 
			isToolsLoaded = true;
			break;
		case 'validate': 
			isValidateLoaded = true;
			break;
		case 'faq': 
			isFaqLoaded = true;
			break;
	}
}

var initModule =  {
	initialize: function(moduleName){
		var newModule = new loadAssets(moduleName);
	}
};

var loadAssets = new Class({
	initialize: function(moduleName){
		this.moduleID = moduleName;
		switch (moduleName) {
			case 'rebatesIncentivesForm': 
				this.loadFordForms();
				this.loadTools();
				this.loadValidate();
				assets = ['fordForm','tools','validate'];
				this.checkLoaded(moduleName,assets);
				break;
			case 'schedMaintForm': 
				this.loadFordForms();
				this.loadTools();
				this.loadValidate();
				assets = ['fordForm','tools','validate'];
				this.checkLoaded(moduleName,assets);
				break;
			case 'accessoriesForm': 
				this.loadFordForms();
				this.loadTools();
				this.loadValidate();
				assets = ['fordForm','tools','validate'];
				this.checkLoaded(moduleName,assets);
				break;
			case 'findDealerForm': 
				this.loadFordForms();
				this.loadTools();
				this.loadValidate();
				assets = ['fordForm','tools','validate'];
				this.checkLoaded(moduleName,assets);
				break;
			case 'findVehicleForm': 
				this.loadFordForms();
				assets = ['fordForm']
				this.checkLoaded(moduleName,assets)
				break;
			case 'finance-vehicle': 
				this.loadFordForms();
				assets = ['fordForm']
				this.checkLoaded(moduleName,assets)
				break;
			case 'schedMaintForm': 
				this.loadFordForms();
				this.loadTools();
				this.loadValidate();
				assets = ['fordForm','tools','validate']
				this.checkLoaded(moduleName,assets)
				break;
			case 'specificInfoForm': 
				this.loadFordForms();
				assets = ['fordForm']
				this.checkLoaded(moduleName,assets)
				break;
			case 'checkVehicleStatusForm': 
				this.loadFordForms();
				this.loadValidate();
				assets = ['fordForm','validate']
				this.checkLoaded(moduleName,assets)
				break;
			case 'rate-page-form': 
				this.loadFordForms();
				assets = ['fordForm']
				this.checkLoaded(moduleName,assets)
				break;
			case 'email-form': 
				this.loadFordForms();
				this.loadTools();
				this.loadValidate();
				assets = ['fordForm','tools','validate']
				this.checkLoaded(moduleName,assets)
				break;
			case 'eventRegisterForm': 
				this.loadFordForms();
				this.loadTools();
				this.loadValidate();
				assets = ['fordForm','tools','validate']
				this.checkLoaded(moduleName,assets)
				break;
			case 'contactForm': 
				this.loadFordForms();
				this.loadTools();
				this.loadValidate();
				assets = ['fordForm','tools','validate']
				this.checkLoaded(moduleName,assets)
				break;
			case 'getExtSearch': 
				this.loadTools();
				assets = ['tools']
				this.checkLoaded(moduleName,assets)
				break;
			case 'fordLatinoBrands': 
				this.loadTools();
				assets = ['tools']
				this.checkLoaded(moduleName,assets)
				break;
			case 'homepageBrands': 
				this.loadTools();
				assets = ['tools']
				this.checkLoaded(moduleName,assets)
				break;
			case 'faqs': 
				this.loadFaqs();
				assets = ['faq']
				this.checkLoaded(moduleName,assets)
				break;
			case 'goSelectForm1': 
				this.loadFordForms();
				assets = ['fordForm']
				this.checkLoaded(moduleName,assets)
				break;
			case 'goSelectForm2': 
				this.loadFordForms();
				assets = ['fordForm']
				this.checkLoaded(moduleName,assets)
				break;
			case 'goSelectForm3': 
				this.loadFordForms();
				assets = ['fordForm']
				this.checkLoaded(moduleName,assets)
				break;
			case 'goSelectForm4': 
				this.loadFordForms();
				assets = ['fordForm']
				this.checkLoaded(moduleName,assets)
				break;
		}
	},
	loadFordForms: function() {
		if (!isFordFormsLoaded && !fordFormsLoading ) { 
				var script = new Asset.javascript('/js/fordForm.js', {id: 'fordForm'});
				fordFormsLoading = true;
		}
	},
	loadTools: function() {
		if (!isToolsLoaded && !toolsLoading ) { 
				var script = new Asset.javascript('/js/tools.js', {id: 'toolJS'});
				toolsLoading = true;
		}
	},
	loadValidate: function() {
		if (!isValidateLoaded && !validateLoading ) { 
				var script = new Asset.javascript('/js/validate.js', {id: 'validateJS'});
				validateLoading = true;
		}
	},
	loadFaqs: function() {
		if (!isFaqLoaded && !faqLoading ) { 
				var script = new Asset.javascript('/js/faqs.js', {id: 'faqsJS'});
				faqLoading = true;
		}
	},
	checkLoaded: function(moduleName,assets) {
		var toLoad = assets.length;
		if (assets.test('fordForm')) { 
			if (!isFordFormsLoaded) {
				var fordFormLoop = (
					function(){ 
						if (isFordFormsLoaded) { 
							$clear(fordFormLoop); 
							toLoad = toLoad-1;
						}	
					}.bind(this)
				).periodical(1)
			}		
			else {
				toLoad = toLoad-1;
			}
		}
		if (assets.test('validate')) { 
			if (!isValidateLoaded) {
				var validateLoop = (
					function(){ 
						if (isValidateLoaded) { 
							$clear(validateLoop); 
							toLoad = toLoad-1;
						}	
					}.bind(this)
				).periodical(1)
			}		
			else {
				toLoad = toLoad-1;
			}
		}
		if (assets.test('tools')) { 
			if (!isToolsLoaded) {
				var toolLoop = (
					function(){ 
						if (isToolsLoaded) { 
							$clear(toolLoop); 
							toLoad = toLoad-1;
						}	
					}.bind(this)
				).periodical(1)
			}		
			else {
				toLoad = toLoad-1;
			}
		}
		if (assets.test('faq')) { 
			if (!isFaqLoaded) {
				var faqLoop = (
					function(){ 
						if (isFaqLoaded) { 
							$clear(faqLoop); 
							toLoad = toLoad-1;
						}	
					}.bind(this)
				).periodical(1)
			}		
			else {
				toLoad = toLoad-1;
			}
		}
			
		var loadLoop = (
			function(){ 
				if (toLoad == 0) { 
					$clear(loadLoop); 
					this.activateModule(moduleName);
				}	
			}.bind(this)
		).periodical(1)

	},
	activateModule:function(moduleName){
		switch (moduleName) {
			case 'rebatesIncentivesForm': 
				var rebatesIncentives = new rebatesIncentivesForm($('rebatesIncentivesForm'));
				break;
			case 'schedMaintForm': 
				var findDealer = new schedMaintForm($('schedMaintForm'));
				break;
			case 'accessoriesForm': 
				var findDealer = new accessoriesForm($('accessoriesForm'));
				break;
			case 'findDealerForm': 
				var findDealer = new findDealerForm($('findDealerForm'));
				break;
			case 'findVehicleForm': 
				var findVehicle = new findVehicleForm($('findVehicleForm'));
				break;	
			case 'finance-vehicle': 
				var financeVehicle = new financeForm($('finance-vehicle'));
				break;	
			case 'specificInfoForm': 
				var specificInfo = new specificInfoForm($('specificInfoForm'));
				break;	
			case 'schedMaintForm': 
				var schedMaint = new schedMaintForm($('schedMaintForm'));
				break;	
			case 'checkVehicleStatusForm': 
				var checkStatus = new checkStatusForm($('checkVehicleStatusForm'));
				break;	
			case 'rate-page-form': 
				var ratePage = new ratePageForm($('rate-page-form'));
				break;	
			case 'email-form': 
				emailThis.initialize()
				break;	
			case 'eventRegisterForm': 
				registerForm.initialize()
				break;	
			case 'getExtSearch': 
				extSearchQuery.initialize()
				break;	
			case 'contactForm': 
				contactForm.initialize()
				break;	
			case 'homepageBrands': 
				if (flashReplaced != true) {
					linkLabels.initialize('BrandBar')
				}
				break;	
			case 'fordLatinoBrands': 
				linkLabels.initialize('fordLatinoBrands')
				break;	
			case 'faqs': 
				faq.initialize('')
				break;	
			case 'goSelectForm1': 
				var goSelect1 = new goSelectForm($('goSelectForm1'),'1');
				break;	
			case 'goSelectForm2': 
				var goSelect2 = new goSelectForm($('goSelectForm2'),'2');
				break;	
			case 'goSelectForm3': 
				var goSelect3 = new goSelectForm($('goSelectForm3'),'3');
				break;	
			case 'goSelectForm4': 
				var goSelect4 = new goSelectForm($('goSelectForm4'),'4');
				break;
		}
	}
});

var recentItems = {
	initialize: function(){
		if ($('sub-nav-area') && $E('.open','sub-nav-area')) {
			this.selectedTopicName = $E('.open','sub-nav-area').getFirst().innerHTML
			this.selectedTopicURL = $E('.open','sub-nav-area').getFirst().href
			// if it's Latino, put language in the name
			if (this.selectedTopicURL.test('fordlatino/es-')) {
				this.selectedTopicName = this.selectedTopicName + ' Espa&ntilde;ol';
			}
			if (this.selectedTopicURL.test('fordlatino/eng-')) {
				this.selectedTopicName = this.selectedTopicName + ' English';
			}
			if (Cookie.get("viewedTopic") == false) {
				Cookie.set("viewedTopic", this.selectedTopicName +'^'+ this.selectedTopicURL , {duration: false , path:"/"})
			}
			else {
				var cookieSets = Cookie.get("viewedTopic")
				if (!cookieSets.test(this.selectedTopicName)) {
					var topicSets = cookieSets.split("|");
					if (topicSets.length == '5') {
						topicSets.remove(topicSets[4])
					}
					Cookie.set("viewedTopic", this.selectedTopicName +'^'+ this.selectedTopicURL +'|'+ topicSets.join("|") , {duration: false , path:"/"})
				}
				topicSets = Cookie.get("viewedTopic").split("|");
				this.recentTopics = new Element('div').setProperty('id','recentItems').injectInside($('sub-nav-area'));
				this.recentTitle = new Element('h5').setHTML('Recently Viewed').injectInside(this.recentTopics);
				this.recentUL = new Element('ul').setProperty('id','recent').injectInside(this.recentTopics);
				$A(topicSets).each(function(topic){
					var topicSet = topic.split("^");
					var newLI = new Element('li').injectInside(this.recentUL);
					new Element('a').setProperty('href',topicSet[1]).setHTML(topicSet[0]).injectInside(newLI)
				}.bind(this));
			}
		}
	}
}

// --------- Checkbox Toggles ------- //
function checkboxToggle(targetID,state) {
	var target = document.getElementById(targetID);
	var checkboxArr = target.getElementsByTagName('input');
	for (i=0;i<checkboxArr.length;i++) {
		if (checkboxArr[i].type = "checkbox") {
			checkboxArr[i].checked = state;
		}
	}
}

// --------- Go Select Form --------- //
var goSelectForm = new Class({
	initialize: function(formName,n) {
		this['goSelectForm'+n] = new fordForm($(formName),{hasOptionals:true});
		this.parseButtons(n);
	},
	parseButtons: function(n) {
		$('goSelectButton'+n).onclick = this.submitForm.pass(n,this)
	},
	submitForm: function(n){
		if ($('goSelectList'+n).selectedIndex > 0) {
			Metrics.exitLink($('goSelectList'+n),"fv",$('goSelectList'+n)[$('goSelectList'+n).selectedIndex].value);
			document.location = $('goSelectList'+n)[$('goSelectList'+n).selectedIndex].value;
		}
		return false;
	}

})


// ----------REMOVED METRICS AND SWFWRITE FROM HERE -----------------//


// --------- Double Arrow Link Fix ------- //
var DoubleArrow = {
	initialize: function() {
		this.nodes = $$('div.mod-box div.innerwrap h2 a.arrow');
		this.replaceLinks();
	}, // end initialize
	replaceLinks: function() {
		this.nodes.each(function(nd) {
		nd.innerHTML += '<img src="/images/button-arrws-sml.gif" width="20" height="10" border="0" />';
		});
	}
} // end DoubleArrow

// ----------- Keynote survey ------------------ //
var keynoteInterceptLikelihood = 0.2;
var keynoteInterceptTaskKey = 'Forddotcom_SiteEssentials_2008';
var keynoteInterceptType = 'Layer';
var KeyNote = {
	initialize: function() {
		this.HandleKeynoteIntercept();
	}, // end initialize
	HandleKeynoteIntercept: function() { 
		try {
			if (Math.random() >= (keynoteInterceptLikelihood*5)) return;
			var s = document.createElement('script');
			s.src = 'http://webeffective.keynote.com/applications/intercept/filter_page.asp?inv=' + keynoteInterceptTaskKey + '&type=' + keynoteInterceptType + '&rate=' + keynoteInterceptLikelihood + '&max=5';
			document.body.insertBefore(s, document.body.firstChild);
			window.keynoteConnectorWindow = 'primary';
		}
		catch(e){}
	}
} // end KeyNote

// ----------- Vehicle Detail Javascript ------- //
var VehicleDetail = {
	initialize: function() {
		this.url = '';
		this.thisURL = document.location.href;
		this.refURL = document.referrer;
		if (this.thisURL.indexOf('flash=true')>-1) {
			Cookie.set('nflc', 'flashon', {duration:false, path:"/"});
		} else if (this.thisURL.indexOf('flash=false')>-1) {
			Cookie.set('nflc', 'flashoff', {duration:false, path:"/"});
		}			
		// test to see if has flash
/*		var flashVersion = deconcept.SWFObjectUtil.getPlayerVersion();
		if(flashVersion['major'] >= 8) {
			this.url = this.makeURL();
			if (this.url && this.url.length > 1) {
				document.location.href = this.url;
			}
		} */
		
		this.flMarker = Cookie.get('nflc');
		if ((this.flMarker == null || this.flMarker == false || this.flMarker == 'flashon') && this.thisURL.indexOf('flash=false')<0 && this.refURL.indexOf('flash=false')<0) {
			// test to see if has flash
			var flashVersion = deconcept.SWFObjectUtil.getPlayerVersion();
			if(flashVersion['major'] >= 8) {
				this.url = this.makeURL();
				if (this.url && this.url.length > 1) {
					document.location.href = this.url;
				}
			}
		}
	}, // end initialize()

	// gets the id of the vehicle detail
	makeURL: function() {
		if ($E('.vehicleDetail')) {
			var detailDiv = $E('.vehicleDetail');
			var id = $E('.vehicleDetail').getProperty('id');
			var brand_name = $E('.vehicleDetail .make').innerHTML;
			var brand = brand_name.toLowerCase();

			// test to see if it's spanish or english
			// using the 'print' language to determine
			if ($('tool-print').innerHTML == 'Imprimir') {
				var url_prefix = '/vehicles/es-showroom#/';
			} else {
				var url_prefix = '/vehicles/vehicle-showroom#/';
			}

			// so, the url is '/vehicles/vehicle-showroom/ plus the rest
			if (id.length > 1 && brand.length > 1) {
				return url_prefix + brand + '/' + id;
			} else {
				return;
			} // end make sure there's ID and brand

		} else {
			return;
		} // end else
	} // end makeURL()

} // end VehicleDetail


default_ask_ford_input_message = '';

/*---- Ask ford functionality ----*/
var AskFordDialog = {
	showMessages: function(FORCE) {
	  if ($('ask-ford-input').value == 'Search Ford Motor Company FAQs for general vehicle or service information.') {
		$('ask-ford-input').value = '';
		this.showTooltip();
	  }
	  if (FORCE == true) {
		this.showTooltip(FORCE);
	  }
	},
	
	checkPost: function() {
	  // get default tiptool value
	  if ($('ask-ford-input-message')) {
		default_ask_ford_input_message = $('ask-ford-input-message').innerHTML;
	  }
	  var default_message = 'Search Ford Motor Company FAQs for general vehicle or service information.';
	  // check for HTML
	  // see if we're in the right side module or the main module
	  if ($('ask-ford-text')) {
		if ($('ask-ford-text').value.length <= 1 || $('ask-ford-text').value == default_message) {
		  alert ('Please enter a question.');
		  return false;
		} else {
			result = checkHTML($('ask-ford-text'));
			if (result == false) {
			  alert ('HTML elements not allowed. Please modify your question.');
			  return false;
			} else {
			  return true;
			} // end else result == false; // end else result == false; // end else result == false;
		}
	  } else {
		if ($('ask-ford-input').value.length <= 1 || $('ask-ford-input').value == default_message) {
		  $('ask-ford-input-message').innerHTML = '<p>Please type in a question.</p>';
		  this.showTooltip(true);
		  return false;
		} else {
			result = checkHTML($('ask-ford-input'));
			if (result == false) {
			  $('ask-ford-input-message').innerHTML = '<p>HTML elements not allowed. Please modify your question.</p>';
			  this.showTooltip(true);
			  return false;
			} else {
			  return true;
			} // end else result == false
		}
	  }
	  return false;
	},
	reset: function() {
	  var default_message = 'Search Ford Motor Company FAQs for general vehicle or service information.';
	  if (default_ask_ford_input_message.length > 1) {
		$('ask-ford-input-message').innerHTML = default_ask_ford_input_message;
	  }
	  if ($('ask-ford-input').value == '' || $('ask-ford-input').value == default_message) {
		$('ask-ford-input').value = default_message;
	  }
	  $('ask-ford-input-message').style.display = 'none';
	},
	
	showTooltip: function(FORCE) {
	  this.detectEdge();
	  if ($('ask-ford-input').value == '' || FORCE == true) {
		$('ask-ford-input-message').style.display = 'block';
	  } else {
		$('ask-ford-input-message').style.display = 'none';
	  }
	},
	createTip: function() {
	  this.toolTip = new Element('div').addClass('tooltip').setStyle('position', 'absolute').injectInside(document.body);
	  this.toolTipInner = new Element('div').addClass('tooltipinner').injectInside(this.toolTip);
	  this.toolTitle = new Element('H4').injectInside(this.toolTipInner);
	  this.toolText = new Element('p').injectInside(this.toolTipInner);
	  this.toolBot = new Element('div').addClass('tooltipbot').injectInside(this.toolTip);
	  this.toolTip.setStyle('display', 'none');
	},
	detectEdge: function() {
	  var askford_input_coords = $('ask-ford-input').getCoordinates();
	  this.message_left = askford_input_coords.left + 'px';
	  this.message_top = (askford_input_coords.bottom + 3) + 'px';
	  $('ask-ford-input-message').style.left = this.message_left;
	  $('ask-ford-input-message').style.top = this.message_top;
	}

} // end AskFordDialog

/*----- Begin: Flash Replacement -----*/
//flashReplaced = false;
//SWFWrite.initialize();

/*---- temporary fix for left nav ---*/
var removeNullNav = {
  initialize: function() {
    if ($('sub-nav-area') && $E('.open','sub-nav-area')) {
	$$('#sub-nav-area .open ul a').each(function(subnavlist){
	  if (subnavlist.innerHTML == 'null') {
	    subnavlist.innerHTML = '';
	  }
	});
    }
  }
}

/*----- Begin: Initialization Functions -----*/
//window.addEvent('domready', Bubble.initialize.bind(Bubble));
window.addEvent('domready', DropDownMenu.initialize.bind(DropDownMenu)); 
//window.addEvent('domready', ExpandMenu.initialize.bind(ExpandMenu));
//window.addEvent('domready', recentItems.initialize.bind(recentItems));
//window.addEvent('domready', Metrics.setOnClicks.bind(Metrics));
//window.addEvent('domready', DoubleArrow.initialize.bind(DoubleArrow));
//window.addEvent('domready', removeNullNav.initialize.bind(removeNullNav));
//window.addEvent('domready', VehicleDetail.initialize.bind(VehicleDetail));
/*----- End: Initialization Functions -----*/
