var current_domain = (document.location.hostname.test('ford.com','i')) ? 'ford' : 'dev';
var abUrl = document.location.href;
var abTest = '';


// --------- A/B Test -------- //
function testA() {
	Metrics.setMultivariate("testA");
	abTest = 'testA';
	return;
}

function testB() {
	abUrl = '/js/index_ab.htm';
	abTest = 'testB';
	return;
}


// --------- Metrics --------- //
var Metrics = {
	initialize: function() {

		
		
		/* Error Page*/
		if(document.title.indexOf("Page Not Found")>-1){
			s.pageType="errorPage";
			s.pageName=s.pageName+": "+document.location;
		}
		//var pageNameFix = (s.pageName.indexOf("'")) ? s.pageName.split("'").join("") : s.pageName;
		if (s.pageName.indexOf("ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÂ¢Ã¢â‚¬Å¾Ã‚Â¢") > -1) {
			s.pageName = s.pageName.replace("ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÂ¢Ã¢â‚¬Å¾Ã‚Â¢", " ");
		}
		s.hier1=(s.hier1!="")?s.hier1:s.channel;
		this.modKPI();
		this.shortenTags();
		this.h2Types={fv:"brands,ford vehicles",ln:"brands,lincoln",my:"brands,mercury",mz:"brands,mazda",mzes:"brands,mazda",vv:"brands,volvo",fves:"brands,ford vehicles",ps:"services,parts and services",f:"services,financing",a:"services,accessories",d:"services,dealers",cpo:"services,certified pre owned",fl:"services,fleet",ct:"services,commercial trucks",mm:"services,mobility motoring",r:"community,racing",b:"community,blogs"};
		this.linkNameTypes={BrandBar:"brand bar",fordLatinoBrands:"latino brand bar",GlobalLinks:"top navigation",Inside:"inside our site",content_area:"content area",article_contents:"article contents",related_content:"related content",global_promo:"global promo",locate_dealer_mod:"dealer locator",schedule_maint_mod:"schedule maintenance",finance_apply:"finance apply",finance_estimatepay:"finance estimate payments",finance_access:"finance access your account",check_vehicle_status_mod: "check vehicle status",find_next_module:"find next vehicle"};
		this.onClickTypes = {tool_print: "print",tool_subs:"subscribe"};
		this.urls = {corp:'corporate',fves:"fordenespanol",fv:"ford",ln:"lincoln",my:"mercuryvehicles",mz:"mazdausa",mzes:"mazdaespanol",vv:"volvocars"};
	},
	setOnClicks: function(){
	for(var name in this.onClickTypes){
			var obj=$(name.replace("_","-"));
			if (obj!=undefined&&obj!=false){ 
				var linkName=this.onClickTypes[name];
				//obj.addEvent('click', function() {this.sendOnClick($(name.replace("_","-")),this.onClickTypes[name]);}.bind(this));
				obj.addEvent('click', function() {this.sendOnClick(obj,linkName);}.bind(this));
			}
		} // end for
		/*
		for(var name in this.onClickTypes)
		{
			function bla(n)
			{ //inside this loop, use 'n' instead of 'name'
				alert("INSIDE function(n)");
				var obj=$(n.replace("_","-"));
				if (obj)
				{
					alert("INSIDE (obj)");
					obj.addEvent('click', function() {this.sendOnClick(obj, this.onClickTypes[n]);}.bind(this));
					alert("FINISHED obj.addEvent");
				}
				alert("OUT OF if (obj)");
			}
			alert("OUT OF function(n)");
			
			bla(name);
		} */
		
		// end for
		$$("a").each(function(el){
			for (var brnd_name in this.urls) {
				// test which domain it is
				if (el.href.test(".us") == true) {
					var domain_suffix = ".us";
				} else {
					var domain_suffix = ".com";
				}
				var host=el.href.substring(el.href.indexOf('//'),el.href.indexOf(domain_suffix));
				//add referrer for non-volvo site exit links - REMOVED 1/7/2008 - NOT NEEDED
				//REFERRER SENT IN HEADER, EXCEPT FOR IE6 DOCUMENT.LOCATION.HREF, WHICH IS ONLY USED BY US IN JS WIDGETS AND WON'T BE AFFECTED BY THIS
/*				if (host.test(this.urls[brnd_name]) == true && (host.indexOf('volvo') < 0)) {
					el.href=el.href+((el.href.indexOf("?")>-1)?"&":"?")+"referrer=www%2Eford%2Ecom";
					break;
				}
*/				
				//add glbcmp for FLM site exit links
				
				/*if (host.test(this.urls[brnd_name]) == true && (host.indexOf('ford') > -1 || host.indexOf('lincoln') > -1 || host.indexOf('mercury') > -1)) {
					var oldText = el.innerHTML;
					el.href=el.href+((el.href.indexOf("?")>-1)?"&":"?")+"glbcmp=ford|"+s.channel+"|"+this.urls[brnd_name];
					if (el.innerHTML != oldText) el.innerHTML = oldText
					break;
				}*/
			}  // end for in			  
		}.bind(this));
		$$("dl.related dd a").each(function(el){
			if (el.firstChild.nodeType == 3) {
				el.addEvent('click', function() {this.sendOnClick(el,"tag: "+el.firstChild.nodeValue);}.bind(this));
			}
		}.bind(this));
		$$("#rss-subs a").each(function(el){
			el.addEvent('click', function() {this.sendOnClick(el,"rss feed: "+el.href.substring(el.href.indexOf("tag")));}.bind(this));							
		}.bind(this));
		$$(".latest a").each(function(el){
			if(el.click== undefined){
				if(el.href.indexOf("corporate.ford.com")>-1 || el.href.indexOf("corporateqa.ford.com")>-1){
					el.addEvent('click', function() {this.localLink(el);}.bind(this));	
				}
				else{
					el.addEvent('click', function() {this.exitLink(el);}.bind(this));	
				}
			}
		}.bind(this));
		$$("#search-results a").each(function(el){
			url = el.href;	
			var brandName=this.getBrandName(el.href);
			if (url.indexOf(".fordcomsearch.ford.com") > -1) url = url.split("=")[1].replace(/%2F/g,"/").replace(/%3F/g,"?").replace(/%3D/g,"=").replace(/%26/g,"&").replace(/%3A/g,":");
			if (brandName!="" && brandName!= 'corp' && url.indexOf("corporate.ford.com") < 0 && url.indexOf("corporateqa.ford.com") < 0)
				el.addEvent('click', function() {this.exitLink(el,brandName);}.bind(this));
			else
				el.addEvent('click', function() {this.localLink(el);}.bind(this));		
		}.bind(this));
		
	},
	videoLink: function(_obj,_h2Type,_url,_tags) {	
		//alert("VIDEO!"+_obj.getAttribute("id"));
		if (_obj.getAttribute("class") == "VideoWrapper") {
			_obj.setAttribute("class", "VideoWrapper clicked");
			Metrics.videoPlayOnClick(this,_obj.getAttribute("id"));
		}
	},
	exitLink: function(_obj,_h2Type,_url,_tags) {
		//alert(url+" --- "+_h2Type+" --- "+_url+" --- "+_tags);
		var h2Prefix=(_h2Type!=null&&this.h2Types[_h2Type]!=undefined)?this.h2Types[_h2Type]:"other";
		if (h2Prefix.indexOf("brands")<0&&h2Prefix.indexOf("services")<0) h2Prefix="other"; 
		h2Prefix = h2Prefix.toLowerCase();
		
		var linkParent = _obj;
		
		var url = _obj.href!=null?_obj.href:(_url!=undefined?_url:"");

		var linkArray    = this.getLinkName(linkParent);
		var linkName     = linkArray[0];
		var linkNameType = linkArray[1];
		
		if (url.indexOf(".fordcomsearch.ford.com") > -1) url = url.split("=")[1].replace(/%2F/g,"/").replace(/%3F/g,"?").replace(/%3D/g,"=").replace(/%26/g,"&").replace(/%3A/g,":");
		
		this.s=s_gi(s_account);
		this.s.linkTrackVars="prop1,prop4,prop5,hier2,eVar1,events";
		this.s.linkTrackEvents="event4";
		this.s.events="event4";
		this.s.eVar1=h2Prefix;
		
		//this.s.hier2=h2Prefix+linkNameType+","+s.hier1+","+url;
		
		var h2Temp = "";
		
		var urlArray = url.split('?');
		
		var h2PrefixSwitch = (h2Prefix!="other") ? h2Prefix.slice(0, h2Prefix.indexOf(",")) : h2Prefix;
		h2PrefixSwitch = h2PrefixSwitch.toLowerCase();
		//keep for future switch to < delimiter
		//var h2PrefixDelimited = h2Prefix.split(",").join("<");
		
		var pageNameFix = (s.pageName.indexOf(",")) ? s.pageName.split(",").join("") : s.pageName;
		
		if (s.channel=='showroom') h2PrefixSwitch="showroom";
		if (s.channel=='ford-global') h2PrefixSwitch="ford-global";
		
		urlArray[1] = (urlArray[1]) ? urlArray[1] : "";
		
		switch (h2PrefixSwitch) {
			case "brands":
				h2Temp=h2Prefix+","+urlArray[0]+","+s.channel+","+pageNameFix+","+linkNameType+","+urlArray[1];
				break;
			case "services":
				h2Temp=h2PrefixSwitch+","+urlArray[0]+","+s.channel+","+pageNameFix+","+linkNameType+","+urlArray[1];
				break;
			case "showroom":
				h2Temp=h2Prefix+","+s.channel+","+urlArray[0]+","+pageNameFix+","+linkNameType+","+urlArray[1];
				break;
			case "ford-global":
				h2Temp=h2PrefixSwitch+","+url;
				break;
			default:
				h2Temp=h2PrefixSwitch+","+urlArray[0]+","+s.channel+","+pageNameFix+","+","+linkNameType+urlArray[1];
				break;
		}
		if (h2Temp.indexOf(",,")) h2Temp = h2Temp.split(",,").join(",");
		if (h2Temp.lastIndexOf(",") == h2Temp.length-1) h2Temp = h2Temp.slice(0,h2Temp.length-1);
		
		//keep for future switch to < delimiter
		/*if (h2Temp.indexOf("<,")) { 
			h2Temp = h2Temp.split("<,").join("<");
		}*/
		
		this.s.hier2 = h2Temp;
		
		this.s.prop4 = (_tags!=null)? "link: " +_tags.toLowerCase():"";
		this.s.prop1=s.pageName;
		linkName = linkName.toLowerCase();
		
		if (document.getElementsByTagName("body")[0].id == "home")
			linkName = (_obj.flash)?   "flash: "+"exit link: "+linkName+": "+url   :   "exit link: "+this.getGrid(_obj)+linkName+": "+url;
		else
			if (linkName) linkName = "exit link: "+linkName+": "+url;
			else linkName = "exit link: "+url;
		this.s.prop5="ford: "+linkName;
		var lt=_obj.href!=null?this.s.lt(_obj.href):"";
		if (_obj.href == undefined) { _obj = '';}
		if (lt=="" || _obj.flash) { this.s.tl(_obj,"e",linkName+": " + url); }


	},
	localLink: function(_obj,_tags){
		this.s=s_gi(s_account);
		var url = _obj.href!=null?_obj.href:"";
		//Fixes the QA URL for Search Results
		if (url.indexOf(".fordcomsearch.ford.com") > -1) url = url.split("=")[1].replace(/%2F/g,"/").replace(/%3F/g,"?").replace(/%3D/g,"=").replace(/%26/g,"&").replace(/%3A/g,":");
		//Shortens the Press Release URL's
		if (url.indexOf("press-releases-detail") > -1){
			var pr = url.split("/");
			url = "pr: " + pr[pr.length - 2] + "/" + pr[pr.length - 1]
		}
		//Adds the getGrid call only if it is the HP
		if (document.getElementsByTagName("body")[0].id == "home")
			var linkName = "local link: " + this.getGrid(_obj)+": "+url;
		else
			var linkName = "local link: " +url;
		linkName = (_obj.flash)?"flash: "+linkName:linkName;
		this.s.prop4 = (_tags!=null)? "link: " +_tags.toLowerCase():"";
		this.s.prop1=s.pageName;
		this.s.prop5="ford: "+linkName;
		this.s.linkTrackVars="prop1,prop4,prop5"; 
		this.s.linkTrackEvents="None";
		this.s.tl(_obj,"o",linkName);
	},
	flashLink: function(_url,_tags){
		var obj={"href":_url,"flash":true};
		var brandName=this.getBrandName(_url);
		if (brandName==""){
			this.localLink(obj,_tags);
		}
		else{
			this.exitLink(obj,brandName,_url,_tags);
		}
	},
	sendOnClick: function(_obj,_linkName){
		this.s=s_gi(s_account);
		this.s.prop1=s.pageName;
		this.s.prop5="ford: "+_linkName;
		this.s.linkTrackVars="prop1,prop4,prop5"; 
		this.s.linkTrackEvents="None";
		this.s.tl(_obj,"o",_linkName+": "+s.pageName);
	},
	sendLead: function(_obj,_linkName){
		this.s=s_gi(s_account);
		this.s.prop1=s.pageName;
		this.s.prop5="ford: "+_linkName
		this.s.eVar28=this.s.prop5;
		this.s.prop18=this.s.prop5;
		this.s.events="event10";
		this.s.linkTrackVars="prop1,prop5,eVar28,prop18,events"; 
		this.s.linkTrackEvents="event10";
		this.s.tl(_obj,"o",_linkName);
	},
	getHier2: function(_h2Type) {
		fh2Prefix = (_h2Type!=null&&this.h2Types[_h2Type]!=undefined)?this.h2Types[_h2Type]:"other";
		fh2Prefix = fh2Prefix.toLowerCase();
		return fh2Prefix;	
	}, // end getHier2
	getHier2Url: function(url) {
		var brandName = this.getBrandName(url);
		var hier2 = '';

		if (brandName.length > 1) {
			hier2 = this.getHier2(brandName);
		} // end if final_result

		return hier2;
	},
	getBrandName: function(_url){
		var brandName = ""
		for (var brnd_name in this.urls) {
			if (_url.indexOf(this.urls[brnd_name]) > -1) {
				brandName = brnd_name;
				break;
			}
		} 
		return brandName
	},
	getLinkName:  function(linkParent) {
		var resultLinkName = '';
		var resultLinkNameType = '';

		for(var i=0; i<4 ; i++){
			if (linkParent != undefined && linkParent.id != undefined && linkParent.id != '' && linkParent.id != 'null') {
				linkNameTypetmp = this.linkNameTypes[linkParent.id.replace("-","_")];
				if(linkNameTypetmp != undefined && linkNameTypetmp != ''){
					resultLinkName=linkNameTypetmp;
					resultLinkNameType=","+linkNameTypetmp;
					break;
				}
			} // end if no id
			if (linkParent.parentNode != undefined) {
				linkParent=linkParent.parentNode;
			}
		}
		var linkArray =  new Array(resultLinkName,resultLinkNameType);
		return linkArray;
	}, // end getLinkName()
	// modify s.channel for KPI analysis
	modKPI: function() {
		if (s.hier1.test('about-ford,company-information')) {
			s.channel = 'company-information';
		}
		else if (s.hier1.test('about-ford,investor-relations')) {
			s.channel = 'investor-relations';
		}
		else if (s.hier1.test('about-ford,careers')) {
			s.channel = 'careers';
		}
		else if (s.hier1.test('about-ford,heritage')) {
			s.channel = 'heritage';
		}
		else if (s.hier1.test('about-ford,news-announcements')) {
			s.channel = 'news-announcements';
			// for featured articles
			if (s.hier1.test('featured-stories,featured-stories-detail')) {
				s.pageName="ford: featured story: "+document.title;
			} // featured articles
		}
		else if (s.hier1.test('featured-stories,featured-stories-detail')) { /* non-redundant check due to 11/18/10 navigation updates - previous rule not trapped under new structure */
			s.pageName="ford: featured story: "+document.title;
		} // featured articles		
	}, // end modKPI()
	shortenTags: function(){
		var t=s.prop4
		var t_arr=t.split(",");
		var newt="";
		for(var i=0; i<t_arr.length;i++){
			var tag=t_arr[i].substr(0,t_arr[i].indexOf("|"))
			tag = tag.length<4?tag:tag.substr(0,3)+tag.length;
			var rank=t_arr[i].substr(t_arr[i].indexOf("|"))
			newt=i==0?tag+rank:newt+","+tag+rank;
		}
		s.prop4=newt;
	},
	getGrid: function (_obj) {
		var featureRowObj = _obj.getParent()
		var featureChild = _obj;
		for( var i=0; i<4; i++){
			if(featureRowObj.hasClass("feature-row"))
				break;	
			featureChild = featureRowObj;
			featureRowObj = featureRowObj.getParent()
		}
		if (featureRowObj.hasClass("feature-row"))  {
				//counts the number of .feature-row's that are previous to clicked one
				
				var sibling = featureRowObj.getPrevious();
				var rowNo=1;
				while(sibling && sibling.hasClass("feature-row")){
					rowNo++;
					sibling = sibling.getPrevious();	
				}
				//if .feature-row is a child of #right-rail set the col to 3
				var latest =""
				if (featureRowObj.getParent().getProperty("id")=="right-rail"){
					colNo = "3";
					var latestObj = _obj;
					for( var l=0; l<4; l++){
						if(featureRowObj.hasClass("latest")){
							latest=": latest";
							break;
						}
						latestObj = latestObj.getParent()
					}
				}
				else
				//if .feature-row is a child of left-feature or right feature, ser col to 1 or 2 respectively
				switch(featureChild.getProperty("class"))
				{
					case 'left-feature' : var colNo = "1"; break;
					case 'right-feature' : var colNo = "2"; break;
					default : var colNo = "1_2";
				}
				return "r"+rowNo+"c"+colNo+latest;
			}
		else return "";
	},
	videoPlayOnClick: function(_obj,_videoName){
		this.s=s_gi(s_account);
		this.s.prop1=s.pageName;
		this.s.prop5="ford: video play "+_videoName;
		this.s.prop6="ford: "+_videoName;
		this.s.linkTrackVars="prop1,prop5,prop6"; 
		this.s.linkTrackEvents="None";
		this.s.tl(_obj,"o"," video play"+_videoName+": "+s.pageName);
	},
	articleView: function(articleID){
	}
}

// --------- Flash Replacement ------- //
// some global variables for flash window sizing
var swf_minwidth = 0;
var swf_minheight = 0;
var swf_width = 0;
var swf_height = 0;
var swf_block_id = '';

var SWFWrite = {

	/**
	* @param String FLASHNAME the page name for the flash to load
	*/
	initialize: function(FLASHNAME) { 
		if (FLASHNAME != 'home') { 
			this.flMarker = Cookie.get('nflc');
			this.section = '';
			this.page_url = document.location.href;
			this.refUrl = document.referrer;
			this.default_path = (current_domain == 'ford') ? '/':'';
			// see which section we are writing our swf into
			if (FLASHNAME.length > 1) {
				this.setPage(FLASHNAME);
			}
			//this.loadFlash =  (document.location.href.indexOf("flash=false")>-1)?false:true;
			if (this.page_url.indexOf('flash=false')>-1 || this.refUrl.indexOf('flash=false')>-1 || (this.flMarker == 'flashoff' && this.page_url.indexOf('flash=true')<0)) {
				Cookie.set('nflc', 'flashoff', {duration:false, path:"/"});
				this.loadFlash = false;
			} else if (this.page_url.indexOf('flash=true')>-1) {
				Cookie.set('nflc', 'flashon', {duration:false, path:"/"});
				this.loadFlash = true;
			} else {
				this.loadFlash = true;
			}
			 
			this.checkSection();
			this.flashLoaded = false;
		}
	}, // end initialize()
	setPage: function(FLASHNAME) {
		if (FLASHNAME.length > 1) {
			this.flashName = FLASHNAME;
		} // end if length
	}, // end setPage()
	// debug
	debug: function(url) {
		this.page_url = url;
	}, // end debug()
	checkConnection: function(){
		if(this.flashLoaded==false && this.loadFlash==true){
			this.loadFlash = false;
			document.location = document.location.href+((document.location.href.indexOf("?")>-1)?"&":"?")+"flash=false";
		}
		clearTimeout(this.t);
	},

	flashLoad: function(bool) {
		this.flashLoaded = bool;
	}, // end flashLoad()

	flashTimerStop: function() {
		clearTimeout(this.t);
	},

	/*flashTimerStart: function() {
		if (this.page_url.test('home') || document.location.pathname == '/') {
			this.t=setTimeout("SWFWrite.checkConnection()",25000);
		}
	},*/

	checkSection: function() {
		// test to see which section it is
		if (this.flashName == 'careers') {
			this.section      = 'about-ford';
			this.block_id     = 'career-opps';
			this.swf_url      = this.default_path + 'swf/career_opps_feature.swf';
			this.swf_name     = 'careers';
			this.swf_width    = '515';
			this.swf_height   = '214';
			this.swf_player   = '9.0.45';
			this.swf_bgcolor  = '#FFFFFF';
			this.page_bgcolor = '#255788';
			this.page_bgImage = 'images/body-bg.jpg';
			this.s_account    = s_account;
			this.flashLoaded = true;
		}
		if (this.flashName == 'owning') {
			this.section      = 'owner-services';
			this.block_id     = 'owner-feature';
			this.swf_url      = this.default_path + 'swf/owner_feature.swf';
			this.swf_name     = 'owning';
			this.swf_width    = '514';
			this.swf_height   = '241';
			this.swf_player   = '8';
			this.swf_bgcolor  = '#FFFFFF';
			this.page_bgcolor = '#255788';
			this.page_bgImage = 'images/body-bg.jpg';
			this.s_account    = s_account;
			//this.oas_url      = this.default_path + 'swf/OmnitureActionSource.swf';
			this.flashLoaded = true;
		}
		if (this.flashName == 'global') {
			this.section      = 'ford-global';
			this.block_id     = 'global-links';
			this.swf_url      = this.default_path + 'swf/global.swf';
			this.swf_name     = 'Global';
			this.swf_width    = '514';
			this.swf_height   = '300';
			this.swf_player   = '8';
			this.swf_bgcolor  = '#FFFFFF';
			this.page_bgcolor = '#255788';
			this.page_bgImage = 'images/body-bg.jpg';
			this.s_account    = s_account;
			this.oas_url      = this.default_path + 'swf/OmnitureActionSource.swf';
			this.flashLoaded = true;
		}
		if (this.flashName == 'showroom') {
			this.section      = 'showroom';
			this.block_id     = 'vehicles';
			this.swf_url      = this.default_path + 'swf/showroomContainer.swf';
			this.swf_name     = 'showroomSwf';
			this.swf_width    = '950';
			this.swf_height   = '770';
			this.swf_player   = '8';
			this.swf_bgcolor  = '#255788';
			this.page_bgcolor = '#255788';
			this.page_bgImage = 'images/body-bg.jpg';
			this.s_account    = s_account;
			this.oas_url      = this.default_path + 'swf/OmnitureActionSource.swf';
			this.flashLoaded = true;
		}
		/*if  (this.flashName == 'home') {
			this.section       = 'home';
			this.block_id      = 'home';
			this.swf_url       = this.default_path + 'swf/home.swf';
			this.swf_name      = 'Ford';
			this.swf_width     = '100%';
			this.swf_height    = '100%';
			this.swf_player    = '8';
			this.swf_bgcolor   = '#091632';
			this.page_bgcolor  = '#091632';
			this.page_bgImage  = '';
			this.add_div       = true;
			this.minWidth      = '950';
			this.minHeight     = '710';
			this.swf_minwidth  = this.minWidth;
			this.swf_minheight = this.minHeight;
			this.swf_block_id  = this.block_id;
			swf_block_id       = this.block_id;
			swf_width	   = this.swf_width;
			swf_height	   = this.swf_height;
			swf_minwidth       = this.minWidth;
			swf_minheight      = this.minHeight;
			this.s_account     = s_account;
			this.oas_url       = this.default_path + 'swf/OmnitureActionSource.swf';
			this.add_attributes = 'position:absolute;top:0;left:0;width:950px;height:710px;z-index:-1;';
			this.flashLoaded = false;
			this.t=setTimeout("SWFWrite.checkConnection()",25000);
		}*/

	if (this.loadFlash == true) {
		this.blockResize();
	}

	}, // end checkSection()

	blockResize: function() {
			/*
			$('js').style.display = 'block';
			$('js').style.position = 'absolute';
			$('js').style.zIndex = '1000';
			$('js').style.width = (Window.getWidth() - 1) + 'px';
			$('js').style.height = (Window.getHeight() - 1) + 'px';
			$('js').style.backgroundColor = this.page_bgcolor;
			/*if (this.page_bgImage != '') {
				$('js').style.backgroundImage = 'url(' + this.default_path + this.page_bgImage + ')';
				$('js').style.backgroundRepeat = 'repeat-y';
			}*/

	}, // end blockResize()

	write: function() { 
		if (!$defined(this.flashName) || this.flashName.length < 1) return;
	
		// see which flash we're loading
		this.checkSection();
		falsepositive = false;
		var flashcheck = 0;
		if (this.block_id != undefined && this.block_id.length > 1) {
			switch(this.section) {
				case 'about-ford':
					// check to see if the ID exists
					if (!$('career-opps')) {
						falsepositive = true;
					}
					this.so =  new SWFObject(this.swf_url, this.swf_name, this.swf_width, this.swf_height, this.swf_player, this.swf_bgcolor);
					this.so.addParam("scale", "noscale");
					this.so.addParam("wmode", "transparent");
					this.so.addParam("AllowScriptAccess", "always");
					this.so.addVariable("xmlPpath", "/xml/career_opps_feature.xml");
					flashcheck = 1;
				break;
				
				
				case 'owner-services':
					// check to see if the ID exists
					if (!$('owner-feature')) {
						falsepositive = true;
					}
					// IE 6 swfobjeft hack
					if (window.ie6) { 
						this.swf_url += '?url1=' + url1 + '&url2=' + url2 + '&url3=' + url3 + '&url4=' + url4 + '&url5=' + url5 + '&url6=' + url6 + '&url7=' + url7;
					}
					this.so =  new SWFObject(this.swf_url, this.swf_name, this.swf_width, this.swf_height, this.swf_player, this.swf_bgcolor);
					this.so.addParam("scale", "noscale");
					this.so.addParam("wmode", "transparent");
					this.so.addParam("AllowScriptAccess", "always");
					
					this.so.addVariable("url1", url1);
					this.so.addVariable("url2", url2);
					this.so.addVariable("url3", url3);
					this.so.addVariable("url4", url4);
					this.so.addVariable("url5", url5);
					this.so.addVariable("url6", url6);
					this.so.addVariable("url7", url7);

					flashcheck = 1;
				break;
				case 'ford-global':
					// check to see if the ID exists
					if (!$('global-links')) {
						falsepositive = true;
					}
					// IE 6 swfobjeft hack
					if (window.ie6) { 
						this.swf_url += '?XMLURL=' + document.location.href;
						this.swf_url += '&s_account=' + this.s_account;
						this.swf_url += '&oas_url=' + this.oas_url;
					}
					this.so =  new SWFObject(this.swf_url, this.swf_name, this.swf_width, this.swf_height, this.swf_player, this.swf_bgcolor);
					this.so.addParam("scale", "noscale");
					this.so.addParam("wmode", "transparent");
					this.so.addParam("AllowScriptAccess", "always");
					this.so.addVariable("XMLURL", document.location.href);
					this.so.addVariable("s_account", this.s_account);
					this.so.addVariable("oas_url", this.oas_url);
					flashcheck = 1;
				break;
				case 'showroom':
					// check to see if the ID exists
					if (!$('showroom')) {
						falsepositive = true;
					}
					// let's see if it's a ford latino showroom page
					if (document.getElementsByTagName('body')[0].id == 'fordlatino') {
						this.block_id = 'fordlatino';
					} // end if ford latino

					// IE 6 swfobject hack
					if (window.ie6) {
						this.swf_url += '?base_url=' + document.location.href;
						this.swf_url += '&nav_data=' + document.location.href;
						this.swf_url += '&spanish_url=' +  document.getElementById("tool-esp");
						this.swf_url += '&english_url=' + document.getElementById("tool-eng");
						this.swf_url += '&header_url=' +  this.default_path + "swf/topnav.swf";
						this.swf_url += '&showroom_url=' + this.default_path +  "swf/showroom.swf";
						this.swf_url += '&s_account=' + this.s_account;
						this.swf_url += '&oas_url=' + this.oas_url;
					}
					this.so =  new SWFObject(this.swf_url, this.swf_name, this.swf_width, this.swf_height, this.swf_player, this.swf_bgcolor);
					this.so.addParam("scale", "noscale");
					this.so.addParam("wmode", "transparent");
					this.so.addParam("AllowScriptAccess", "always");
					this.so.addVariable("base_url", document.location.href);
					this.so.addVariable("nav_data", document.location.href);
					this.so.addVariable("browser", BrowserDetect.browser);
					this.so.addVariable("spanish_url", document.getElementById("tool-esp"));
					this.so.addVariable("english_url", document.getElementById("tool-eng"));
					this.so.addVariable("header_url", this.default_path + "swf/topnav.swf");
					this.so.addVariable("showroom_url", this.default_path + "swf/showroom.swf");
					this.so.addVariable("s_account", this.s_account);
					this.so.addVariable("oas_url", this.oas_url);
					flashcheck = 1;
				break;
				case 'home':
					// check to see if the ID exists
					if (!$('home')) {
						falsepositive = true;
					}

					// IE 6 swfobject hack
					if (window.ie6) {
						this.swf_url += '?nav_data=' + abUrl;
						this.swf_url += '&header_url=' +  this.default_path + "swf/topnav.swf";
						this.swf_url += '&s_account=' + this.s_account;
						this.swf_url += '&oas_url=' + this.oas_url;
						this.swf_url += '&plaza_data=' + this.default_path + "xml/plazaSettings.xml";
					}
					
					//flash cachebuster
					if (document.getElementById("flcb")) { var swfv = document.getElementById("flcb").getAttribute("swfv"); }
					this.swf_url += (swfv) ? ((this.swf_url.indexOf("?")<0) ? "?swfv=" + swfv : "&swfv=" + swfv) : "";

					// testing minimim height and width for firefox and IE bug
					if (Window.getWidth() < this.swf_minwidth) {
						width = this.swf_minwidth;
					} else {
						width = this.swf_width;
					}

					if (Window.getHeight() < swf_minheight) {
						height = this.minHeight;
					} else {
						height = this.swf_height;
					}


					this.so =  new SWFObject(this.swf_url, this.swf_name, width, height, this.swf_player, this.swf_bgcolor);
					this.so.addParam("scale", "noscale");
					this.so.addParam("wmode", "transparent");
					this.so.addParam("AllowScriptAccess", "always");
					this.so.addVariable("nav_data", abUrl);
					this.so.addVariable("topnav_swf", this.default_path + "swf/topnav.swf");
					this.so.addVariable("plaza_data", this.default_path + "xml/plazaSettings.xml");
					this.so.addVariable("plaza_swf", this.default_path + "swf/plaza.swf");
					this.so.addVariable("s_account", this.s_account);
					this.so.addVariable("oas_url", this.oas_url);
					flashcheck = 1;
				break;
			} // end switch

			if (falsepositive == false && this.loadFlash==true) {
				flashReplaced = this.so.write(this.block_id);
			} // end if falsepositive

			if ($('js')) {
				$('js').style.width = '1px';
				$('js').style.height = '1px';
				$('js').style.display = 'none';
				$('js').style.zIndex = '-1';
			}
			// scrollbars fix
			if (this.add_div == true && falsepositive == false && this.loadFlash == true) {
				if (document.all) {
					// IE does not handle 100% width and height
					// for flash correctly
					// this is the workaround
					this.resize();
					window.onresize = this.resize;
				} else {
					$(this.block_id).innerHTML += '<div style="' + this.add_attributes + '">&nbsp</div>';
				}
			}
		}
		if ($('js')) {
			$('js').style.width = '1px';
			$('js').style.height = '1px';
			$('js').style.zIndex = '-1';
		}				
		//write div for locally hosted div-popup surveys
		//this.fsrWindowObj = new Element('div').setProperty('id','fsr_window_outer').injectInside(document.body);
		//$('fsr_window_outer').innerHTML = '&nbsp;';

		//text link on flash pages for non-flash option (screen reader accessibility)
		var baseFlashUrl = document.location.href;
		
		if (baseFlashUrl.indexOf("flash=false")<0 && (Cookie.get('nflc') == false || Cookie.get('nflc') == null || Cookie.get('nflc') == 'flashon')) {
			//trim url for showroom
			if (baseFlashUrl.indexOf('#')>-1) { 
				baseFlashUrl = baseFlashUrl.split("#", 1);
			}
			
			if (baseFlashUrl.indexOf('flash=true')>-1) {
				this.repStrRex = /flash=true/;
				var nfLink = baseFlashUrl.replace(this.repStrRex, "flash=false");
			} else {
				var nfLink = (baseFlashUrl.indexOf('?')>-1) ? baseFlashUrl + '&flash=false' : baseFlashUrl + '?flash=false';
			}
			
			this.nfLinkObj = new Element('div').setProperty('id','nonFlashLink').injectInside(document.body);
			$('nonFlashLink').innerHTML = '<a href="' + nfLink + '">Click here for non flash page</a>';
		}

		//if (flashcheck == 1) { var script = new Asset.javascript('//group11.iperceptions.com/Invitations/Javascripts/ip_Layer_Invitation_489.js', {id: 'ipsurvey'}); }

	}, // end write()

	resize: function() {
		if (Window.getWidth() < this.swf_minwidth) {
			width = swf_minwidth;
		} else {
			width = swf_width;
		}

		if (Window.getHeight() < this.swf_minheight) {
			height = swf_minheight;
		} else {
			height = swf_height;
		}
		if (width != 0) {
			$(swf_block_id).style.width = width;
		}
		$(swf_block_id).style.height = height;
	} // end resize()
	

} // end SWFWrite

/*----- Begin: Flash Replacement -----*/
flashReplaced = false;

/*----- Begin: Initialization Functions -----*/
window.addEvent('domready', Metrics.setOnClicks.bind(Metrics));
/*----- End: Initialization Functions -----*/




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 Blank_TextField_Validator(searchform)
{  
	if ((searchBox.inputbox.value == "Search Ford Motor Company") || (searchBox.inputbox.value.length <1) ){						
		return false;	
	}else{
		searchform.searchtext.value=searchBox.inputbox.value;                             
		document.searchform.action= "/search/search-results"; 
		return true;  					
	}
	//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);
		
		var submenuItems = submenu.getChildren();

		if (submenuItems.length < 2) {	
			if (submenuItems.length == 1) {		
				var topLink = $E('.top-link', submenu.getParent()),
					submenuLink = submenuItems[0].getFirst();
					
				if (topLink.href && submenuLink.href) {			
					topLink.href = submenuLink.href;
				}
			}
		}
		else {
			var lastItems = submenu.getElementsByClassName('last');
			
			if (lastItems.length > 1) {
				for (var i=0, j=lastItems.length-1; i<j; i++) {
					lastItems[i].removeClass('last');
				}
			}
		
			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);
  
  if (submenu && submenu.effect && submenu.effect.clearTimer) {
	submenu.effect.clearTimer();
	submenu.effect.custom(submenu.effect.now, submenu.originalHeight);
  }
 },

 collapse: function(event) {
  var submenu = this.findSubmenu(event.target || event.srcElement);
  
  if (submenu && submenu.effect && submenu.effect.clearTimer) {
	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) {
			var vehicleType = "fv";
			switch ($('goSelectList'+n).selectedIndex){
				case 1:
					vehicleType = "fv";
					break;
				case 2:
					vehicleType = "ln";
					break;
				case 3:
					vehicleType = "my";
					break;
				case 4:
					vehicleType = "vv";
					break;
			}
			Metrics.exitLink($('goSelectList'+n),vehicleType,$('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 - 130 + '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 = '';
	  }
	});
    }
  }
}

/*---- wrapper for sharethis ---*/
var FordShareThis = {
  _items: [],

  addItem: function(params, config) {
    var id = 'fst-' + FordShareThis._items.length;

    FordShareThis._items[FordShareThis._items.length] = {
      'id': id,
      'params': FordShareThis.cleanParams(params),
      'config': config
    };
		
    document.writeln('<span id="' + id + '"></span>');
  },

  renderItems: function() {
    if ((typeof SHARETHIS) == "undefined" || window.ie6) return;

    for (var i = 0, j = FordShareThis._items.length; i < j; i ++) {
      var item = FordShareThis._items[i];
			
      var trigger = $(item.id);
      var button = SHARETHIS.addEntry(item.params, item.config);

      trigger.adopt(button.button);
      button.attachButton(button.button);
    }
  },

  cleanParams: function(params) {
    for (var p in params) {
      if ((typeof params[p]) == 'string') {
        params[p] = params[p].replace(/<[^>]+>/g, '');
      }
    }

    return params;
  }
};

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

window.addEvent('load', function() {
  if ((typeof SHARETHIS) != "undefined" && (typeof window.ie6) == "undefined") {
    SHARETHIS.bodyLoaded = true; // OVERRIDE SHARETHIS PROPERTY TO PREVENT DOCUMENT.WRITELN
    FordShareThis.renderItems();
  }
});

/* Validate Search*/
window.addEvent('domready', function() {
	$each($$('input[name=submit]'),function(el) {
		el.addEvent('click',function(e) {
			if ((document.getElementById("search-bar") != null) && (document.getElementsByName("searchtext").item(0).value == "")) {
				var e = new Event(e).stop();
			}
		});
	});
});
/*----- End: Initialization Functions -----*/


