jQuery.noConflict();
jQuery('html').addClass('cms-default'); // RM MOD 2011-08-16

var isIE7 = (jQuery.browser.msie && jQuery.browser.version.substring(0,1) == "7")? true : false;
var isIE8 = (jQuery.browser.msie && jQuery.browser.version.substring(0,1) == "8")? true : false;

if(location.href.indexOf("ford.com") != -1) window.fmcDomain = window.location.href.split(".com")[0] + ".com";
else window.fmcDomain = "..";

jQuery(document).ready(function(){

	// RM MOD 2011-08-16 ==> next 5 lines
	jQuery("#BodyWrapper > div.hub-span-5:nth-child(3) > div.hub-span-3 div.hub-feature:first" +
			",#BodyWrapper > div.hub-span-5:nth-child(3) > div.hub-span-2 div.hub-feature:first" + 
			",#BodyWrapper > div.hub-span-5:nth-child(3) > div.hub-span-2 > div.hub-row:first-child > div.hub-span-1 > div.hub-row:first-child div.hub-feature:first-child" +
      ",#BodyWrapper .first-after-nav div.hub-span-5:first > div.hub-span-2:first div.hub-feature:first" +
      ",#BodyWrapper .first-after-nav div.hub-span-5:first > div.hub-span-3:first div.hub-feature:first" +
      ",#BodyWrapper .first-after-nav > div.hub-span-3:first div.hub-feature:first" +
      ",#BodyWrapper .first-after-nav > div.hub-span-4:first div.hub-feature:first" +
      ",#BodyWrapper .first-after-nav > div.hub-span-2:first div.hub-feature:first"
	).addClass("first-in-stack");
	jQuery('html').removeClass('cms-default');
  
  jQuery(".first-in-stack > h1").each(function(){
    jQuery(this).html("<span class='w430'>" + jQuery(this).text() + "</span>");
  });
  
  if(jQuery(".col .mod .more").length){
    jQuery(".col .mod .more").each(function(){
      jQuery(this).click(function(e){
        e.preventDefault();
        window.location = jQuery(this).attr("data-target");
        return false;
      });
    });
  }
  
	var plantTYPESelected = "";
	jQuery('#select-plant-type').change(function(){
    var v = jQuery('#select-plant-type option:selected').attr("value");
    if(v != "All") plantTYPESelected = "[type='"+jQuery('#select-plant-type option:selected').attr("value")+"']";
    else plantTYPESelected = "";
		if(!jQuery("#plant-list").length) loadGlobalBingMap(plantTYPESelected);
    if(jQuery(".list-view").length) buildList("COUNTRY");
	});
  
  /* Bing map on global operations hub page*/
  if(jQuery("div#global-map div#bingMap").length){
    function loadGlobalBingMap(plantTYPESelected){
			jQuery.ajax({
				type: "GET",
				dataType: "xml",
				url: window.fmcDomain + "/xml/plant.xml",
        success: function(xml){
          var fmcMap = null;
          var MM = Microsoft.Maps;
          fmcMap = new MM.Map(jQuery("#bingMap").get(0), {
            credentials: "AgvKEIvYd0awvawDOUCccO8Exxg6LenOWhdRqvwhZ0_VKAxmcid5PIi2zgRBhz3f",
            center: new MM.Location(18, 5),
            mapTypeId: "r",
            showScalebar: false,
            showDashboard: false,
            disableZooming: false,
            zoom: 1.5
          });
          var currMarkerId = "";

          function displayEventInfo(e){
            jQuery("#bingMap").append(jQuery("<div class='pushpinPop'><span class='name'>name</span><span class='address'>addr</span></div>"));
            var infobox = jQuery("div.pushpinPop");
            infobox.bind('mouseleave', function(e){ closeInfoBox(e); });
            //pushpinPopMouseOut = MM.Events.addHandler(infobox.get(0), 'mouseleave', closeInfoBox);
            
            if(e.targetType == "pushpin"){
              var pix = fmcMap.tryLocationToPixel(e.target.getLocation(), MM.PixelReference.control);
              var infobox = jQuery("div.pushpinPop");
              jQuery(".name", infobox).html(e.target.title);
              jQuery(".address", infobox).html(e.target.description);
              infobox.css({left: (pix.x - 117) + "px", top: (pix.y - 147) + "px"}).each(function(){
                currMarkerId = jQuery(e.target).attr("_id");
                jQuery("#" + currMarkerId).hide();
                jQuery(this).fadeIn(300);
                infobox.click(function(){
                  window.location = e.target.link;
                });
              });
            }
          }

          function closeInfoBox(e){
            jQuery(e.target).closest("div.pushpinPop").fadeOut(300, function(){
              jQuery(this).remove();
            });
            jQuery("#" + currMarkerId).show();
          }
          
          var plants = jQuery("PLANT" + plantTYPESelected, xml);
          if(plants.length){
            jQuery.each(plants, function(i){
              var plant = jQuery(this);
              var address = "";
              address = jQuery("ADDRESS_LINE1", plant).text();
              address += ((jQuery("ADDRESS_LINE1", plant).text() == "")? "" : "<br />");
              address += jQuery("ADDRESS_LINE2", plant).text();
              address += ((jQuery("ADDRESS_LINE2", plant) == "")? "" : "<br />");
              address += jQuery("CITY", plant).text() + ", " + jQuery("STATE", plant).text() + " " + jQuery("POSTAL_CODE", plant).text() + "<br />";
              address += jQuery("COUNTRY", plant).text();
              
              var pushpinId = "pushpin_" + (Math.floor(Math.random()*100000));
              var pushpinOptions = {icon: window.fmcDomain + "/images/marker.png", width: 30, height: 30, id: pushpinId};
              var pushpin = new MM.Pushpin(new MM.Location(jQuery("LATITUDE", plant).text(), jQuery("LONGITUDE", plant).text()), pushpinOptions);
              MM.Pushpin.prototype.title = null;
              var title = jQuery("NAME", plant).text();
              if(title.length > 60) title = title.substring(0,60) + "&#133";
              pushpin.title = title;
              MM.Pushpin.prototype.description = null;
              pushpin.description = address;
              MM.Pushpin.prototype.link = null;
              pushpin.link = jQuery("DETAIL_URL", plant).text();
              pushpinMouseOver = MM.Events.addHandler(pushpin, 'mouseover', displayEventInfo);
              //MM.Events.addHandler(fmcMap, 'viewchangestart', closeInfoBox);
              fmcMap.entities.push(pushpin);
              jQuery("#" + pushpinId).addClass("pushpin");
            });
          }
				},
				error: function(xhr, status, error){
					alert("Ford facility coordinates temporarily unavailable.\nWe apologize for inconvenience.");
				}
			});
    }
    
    if(jQuery.browser.mozilla){
      jQuery.getScript("http://ecn.dev.virtualearth.net/mapcontrol/v6.3/js/atlascompat.js", function(){
        loadGlobalBingMap(plantTYPESelected);
      });
    }
    else loadGlobalBingMap(plantTYPESelected);
  }
  
  /* Static bing map on global operations details page*/
  if(jQuery("div#plant-details").length){
    var addr = (jQuery("div.adr span.locality").text() + ", " + jQuery("div.adr div.country-name").text());
    var photo = (jQuery("div.mapandimg img.photo").length)? 383 : 566;
    jQuery("#bingMap").css({width: photo+"px", height:"170px"});
    var fmcMap = null;
    
    function loadBingMap(container){
      fmcMap = new VEMap(container);
      var latLon = new VELatLong(40, 73); 
      fmcMap.LoadMap(latLon, 8, VEMapStyle.Road, true, VEMapMode.Mode2D, false); //latLon, 8, VEMapStyle.Road, fixed, VEMapMode.Mode2D, false
      StartGeocoding(addr);
    }
  
    function UnloadMap(){ if(fmcMap != null) fmcMap.Dispose(); }
   
    function StartGeocoding(address){
      fmcMap.Find(null,    // what
        address, // where
        null,    // VEFindType (always VEFindType.Businesses)
        null,    // VEShapeLayer (base by default)
        null,    // start index for results (0 by default)
        null,    // max number of results (default is 10)
        null,    // show results? (default is true)
        null,    // create pushpin for what results? (ignored since what is null)
        null,    // use default disambiguation? (default is true)
        null,    // set best map view? (default is true)
        GeocodeCallback);  // call back function
    }
      
    function GeocodeCallback(shapeLayer, findResults, places, moreResults, errorMsg){
      jQuery("div#bingMap").css({visibility:"visible"});
      if(places == null){
        alert((errorMsg == null) ? "There were no results" : errorMsg);
        return;
      }
      var bestPlace = places[0];
      var location = bestPlace.LatLong;
      var newShape = new VEShape(VEShapeType.Pushpin, location);
      //var desc = "Latitude: " + location.Latitude + "<br>Longitude:" + location.Longitude;
      newShape.SetTitle(jQuery(".vcard .org").text());
      newShape.SetDescription(jQuery(".vcard .adr").html());
      var icon = "<img class='static-pin' src='/images/pin.png'/>";
      newShape.SetCustomIcon(icon);
      fmcMap.AddShape(newShape);
      fmcMap.SetCenterAndZoom(location, 8);
      fmcMap.HideDashboard();
    }
    
    /* FF4 fix to load Bing Maps */
    var interval = setInterval(function(){if ((eval("typeof VEMap") != "undefined") && (document.getElementById("bingMap").attachEvent != undefined)) {clearInterval(interval); loadBingMap("bingMap");}}, 10);
  }
  
  // share wireup
  if(jQuery(".utilities .share").length){ 
    jQuery(".utilities .share a.txt").click(function(e){
      e.preventDefault();
      jQuery(this).siblings(".dd").slideDown();
    });
    jQuery(".utilities .share a.close").click(function(e){ // share close wireup
      e.preventDefault();
      jQuery(".utilities .share .dd").slideUp("fast");
    });
    jQuery(document).click(function(e){
      if(!jQuery(e.target).parents().hasClass("share") && !jQuery("#email-wrap").hasClass("on")){
        jQuery(".utilities .share .dd").slideUp("fast");
      }
    });
  }

	// CHILDREN FIXES FOR IE
	if(jQuery.browser.msie){
    jQuery("#sub-nav li:first").addClass("first-child"); // RM MOD 2011-08-16
		jQuery("#sub-nav li:last-child").addClass("last-child");	
	}
  
  //ARTICLE padding fix
  if(jQuery(".utilities .share").length){
    jQuery(".hub-feature:first .hub-feature-body").addClass("editorial");
    jQuery(".hub-feature:first .hub-feature-body").children(":not(br)").addClass("ed-child");
  }
  
  //Anchor links scrollTo wireup
  if(jQuery("a.top").length){
    function bindBackToTop(){
      jQuery("a.top").bind("click", function(e){
        e.preventDefault();
        //jQuery('html, body').animate({scrollTop:0}, 'fast');
        jQuery.scrollTo("0px", 1000, {easing:"easeOutExpo"});
        return false;
      });
    }
    if(typeof jQuery("body").scrollTo != "function"){
      jQuery.getScript("/js/jquery.scrollTo-1.4.2-min.js", function(){
        bindBackToTop();
      });
    }
    else bindBackToTop();
  }
  if(jQuery("a[href^='#']").length){
    function bindAnchors(){
      jQuery("a[href^='#']").each(function(){
        if(jQuery(this).attr("href").length > 1 && !jQuery(this).hasClass("top") && !jQuery(this).hasClass("q") && jQuery(this).parents("#floating-nav").length == 0){
          jQuery(this).bind("click", function(e){
            e.preventDefault();
            jQuery.scrollTo(jQuery(this).attr("href"), 1000, {offset:-190, easing:"easeOutExpo"});
            return false;
          });
        }
      });
    }
    if(typeof jQuery("body").scrollTo != "function"){
      jQuery.getScript("/js/jquery.scrollTo-1.4.2-min.js", function(){
        bindAnchors();
      });
    }
    else bindAnchors();
    var o = window.location.href;
    if(o.indexOf("#") != -1){
      var target = jQuery("#" + o.split("#")[1].toLowerCase());
      setTimeout(function(){ jQuery.scrollTo(target, 1000, {offset:-197, easing:'easeOutExpo'}); }, 300);
    }
  }
  
  //LI links with a border mouse over wireup
  jQuery(".news-feeds ul li").each(function(e){
    var link = jQuery("a:first", jQuery(this));
    if(link.length == 0){ //for autoshow boxes
      link = jQuery(this).parent("a");
      jQuery(this).parent("a").click(function(e){ e.preventDefault(); });
    }
    link.click(function(e){ e.preventDefault(); });
    jQuery(this).click(function(e){
      if(link.attr("target") == "" || link.attr("target") == "undefined") window.location = link.attr("href");
      else window.open(link.attr("href"), '_blank');
    });
  });

  jQuery("#buy-a-ford").click(function(){ jQuery(this).children(".overlay").show(); });
  jQuery("#buy-a-ford .close").click(function(){ 
    jQuery(this).parent(".overlay").hide();
    return false;
  });
    
	//COUNTRY/VEHICLE SELECTOR
	jQuery("select#country-hdr, select#country").each(function(){
    var o = jQuery(this).parents("#select-vehicle");
    var l1 = jQuery("li:first-child", o);
    var a1 = (l1.length)? jQuery("a", l1) : jQuery("a", o);
    var s1 = jQuery("span", a1);
    var l2 = jQuery("li:nth-child(2)", o);
    var a2 = (l2.length)? jQuery("a", l2) : jQuery("a", o);
    var s2 = jQuery("span", a2);
    a1.attr("target", "_blank");
    a2.attr("target", "_blank");
		a1.attr('href', jQuery('select option:selected', o).attr("value"));
		s1.text("Ford "+jQuery('select option:selected', o).text());
		if(jQuery('select option:selected', o).attr("name") != "undefined" && l2.length){
			a2.attr('href', jQuery('select option:selected', o).attr("name"));
			s2.text("Lincoln "+jQuery('select option:selected', o).text());
		}
		else{
			l2.hide();
			l1.addClass("center");
		}
		jQuery('select', o).bind("change", function(){
      l1.removeClass("center");
			l2.show();
			a1.attr('href', jQuery('select option:selected', o).attr("value"));
			s1.text("Ford "+jQuery('select option:selected', o).text());
			if(jQuery('select option:selected', o).attr("name") != "undefined" && l2.length){
				a2.attr('href', jQuery('select option:selected', o).attr("name"));
				s2.text("Lincoln "+jQuery('select option:selected', o).text());
			}
			else{
				l2.hide();
				l1.addClass("center");
			}
		}).click(function(e){
      e.preventDefault();
    });
	});
	
	/* #### RM MODS NEXT */
	if (jQuery.client && jQuery.client.os == "Windows"){ /* RM MOD 2011-08-16 add initial check for jQuery.client */
		if (jQuery.browser.mozilla){
			jQuery('html').addClass('antenna-pc-gecko');
		}
		else if (jQuery.browser.webkit){
			jQuery('html').addClass('antenna-pc-webkit');
		}
	}
	
	//STORY
	jQuery(".chapter-index ul").each(function(){
		jQuery(this).children("li").append("<span></span>");
		indexWidth = (jQuery(this).children("li").size() * (62 + 10)) - 10;
		jQuery(this).css("width",indexWidth);
		jQuery(this).children("li").click(function(){
			jQuery(this).siblings("li").removeClass("selected");
			jQuery(this).addClass("selected");
			selectedIL = jQuery(this).index() +1;
			jQuery(this).parents(".chapter-index").siblings("ul").children("li").removeClass("selected");
			jQuery(this).parents(".chapter-index").siblings("ul").children("li:nth-child("+selectedIL+")").addClass("selected");			
		});
	});  
  
	//CAROUSEL
	//jQuery("#story-slideshow").each(function(){
  //  carousel(jQuery(this).attr("id"));
	//});
	
  /*
	function carousel(carouselID){
		var slidesNo = jQuery("#"+carouselID+" ul li").size();
		var slideSelected = 1;
		var slideCounter = 1;
		if(jQuery("#hot-topic:not(.slides)").length) jQuery("#"+carouselID).append("<ul id='"+carouselID+"-controls'></ul>");
		jQuery("#"+carouselID+" ul:first-child li").each(function(){
			jQuery(this).addClass("slide"+slideCounter);
			if(jQuery("#hot-topic:not(.slides)").length) jQuery("#"+carouselID+"-controls").append("<li class='slide"+slideCounter+"'></li>");
			slideCounter+=1;
		});
		if(jQuery("#hot-topic:not(.slides)").length) jQuery("#"+carouselID+"-controls li:first-child").addClass("selected");
		slideCounterPrint = slideCounter - 1;
		jQuery("#"+carouselID+" .slide-no").html(slideSelected+"/"+slideCounterPrint);
		
		//first chapter h4 & h5
		selectedH4 = jQuery("#"+carouselID+" li:first-child h4").text();
		selectedH5 = jQuery("#"+carouselID+" li:first-child h5").text();
		selectedH6 = jQuery("#"+carouselID+" li:first-child h6").text();
		jQuery("#"+carouselID).parents(".chapter-body").parents("li").children("h4").html(selectedH4);
		jQuery("#"+carouselID).parents(".chapter-body").parents("li").children("h5").html(selectedH5);
		jQuery("#"+carouselID).parents(".chapter-body").parents("li").children("h6").html(selectedH6);
		
		jQuery("#"+carouselID+" #next").click(function(){
			jQuery("#"+carouselID+" li:nth-child("+slideSelected+")").removeClass("selected");
			slideSelected += 1;
			if (slideSelected > slidesNo) slideSelected = 1; 
			jQuery("#"+carouselID+" li:nth-child("+slideSelected+")").addClass("selected");
		});
		jQuery("#"+carouselID+" #previous").click(function(){
			jQuery("#"+carouselID+" li:nth-child("+slideSelected+")").removeClass("selected");
			slideSelected -= 1;
			if (slideSelected < 1) slideSelected = slidesNo; 
			jQuery("#"+carouselID+" li:nth-child("+slideSelected+")").addClass("selected");
		});
		
		jQuery("#"+carouselID+" .next").click(function(){
			jQuery("#"+carouselID+" li:nth-child("+slideSelected+")").removeClass("selected");
			slideSelected += 1;
			if (slideSelected > slidesNo) slideSelected = 1; 
			jQuery("#"+carouselID+" li:nth-child("+slideSelected+")").addClass("selected");
			slideCounterPrint = slideCounter - 1;
			jQuery("#"+carouselID+" .slide-no").html(slideSelected+"/"+slideCounterPrint);
			selectedH4 = jQuery("#"+carouselID+" li:nth-child("+slideSelected+") h4").text();
			selectedH5 = jQuery("#"+carouselID+" li:nth-child("+slideSelected+") h5").text();
			selectedH6 = jQuery("#"+carouselID+" li:nth-child("+slideSelected+") h6").text();
			jQuery(this).parents(".slideshow-wrapper").parents(".chapter-body").parents("li").children("h4").html(selectedH4);
			jQuery(this).parents(".slideshow-wrapper").parents(".chapter-body").parents("li").children("h5").html(selectedH5);
			jQuery(this).parents(".slideshow-wrapper").parents(".chapter-body").parents("li").children("h6").html(selectedH6);
		});
		jQuery("#"+carouselID+" .previous").click(function(){
			jQuery("#"+carouselID+" li:nth-child("+slideSelected+")").removeClass("selected");
			slideSelected -= 1;
			if (slideSelected < 1) slideSelected = slidesNo; 
			jQuery("#"+carouselID+" li:nth-child("+slideSelected+")").addClass("selected");
			slideCounterPrint = slideCounter - 1;
			jQuery("#"+carouselID+" .slide-no").html(slideSelected+"/"+slideCounterPrint);
			selectedH4 = jQuery("#"+carouselID+" li:nth-child("+slideSelected+") h4").text();
			selectedH5 = jQuery("#"+carouselID+" li:nth-child("+slideSelected+") h5").text();
			selectedH6 = jQuery("#"+carouselID+" li:nth-child("+slideSelected+") h6").text();
			jQuery(this).parents(".slideshow-wrapper").parents(".chapter-body").parents("li").children("h4").html(selectedH4);
			jQuery(this).parents(".slideshow-wrapper").parents(".chapter-body").parents("li").children("h5").html(selectedH5);
			jQuery(this).parents(".slideshow-wrapper").parents(".chapter-body").parents("li").children("h6").html(selectedH6);
		});
		
	}
	*/
  
	//Mosaic Slides
  jQuery("#mosaic ul li:last-child").addClass("last");
	jQuery("#mosaic ul li ul").hover(function(){
      if(isIE7) jQuery("li h4", this).fadeIn("slow");
      else jQuery("li h4", this).slideDown("fast");
	  }, function(){
	  	if(isIE7) jQuery("li h4", this).fadeOut("fast");
      else jQuery("li h4", this).slideUp("fast");
	  }
	).click(function(){
    window.location = jQuery(this).siblings("a").attr("href");
  });
	
	//FORD FACT BUBBLE
	jQuery(".ford-fact").toggle(function(){
		jQuery(this).addClass("expanded");
	}, function(){
		jQuery(this).removeClass("expanded");
	});
	
	jQuery("#take-mustang-tour").click(function(){
		jQuery('html, body').animate({scrollTop:jQuery(".part").offset().top-60}, 500);
	});

  //Ford mustang page
	if(jQuery("#timeline").length){
		doHover=1;
		contentON = jQuery("#timeline li:first-child").html();
		jQuery("#timeline").css("top",jQuery(".part").offset().top-135);
		jQuery("#timeline #flag").html(contentON);
		yearOn = jQuery(".part").attr("id").split("-");
		yearOn2 = yearOn[1];
		yearOnPos = ((yearOn2 - 1960) * 9.1) + 33;
		jQuery("#timeline #flag").css("top",yearOnPos);
		selectedYear = 1;
		jQuery(".part").each(function(){
			yearOn = jQuery(this).attr("id").split("-");
			yearOn2 = yearOn[1];
			yearOnPos2 = (yearOn2 - 1960) * 9.1;
			yearOrder = jQuery(this).index()-1
			jQuery("#timeline li:nth-child("+yearOrder+")").css("top",yearOnPos2);
			jQuery("#timeline li:nth-child("+yearOrder+") strong").html(yearOn2);
		});
		jQuery("#timeline li").hover(
		  function () {
			jQuery("#timeline #flag").html(jQuery(this).html());
			jQuery("#timeline #flag").animate({top:jQuery(this).position().top+33}, 250);
		  }, 
		  function () {
		  	jQuery("#timeline #flag").html(contentON);
        jQuery("#timeline #flag").animate({top:yearOnPos}, 500);
		  }
		);
		jQuery("#timeline li").click(function(event){
			doHover=0;
			contentON = jQuery(this).html();
			yearOnPos = jQuery(this).position().top + 33;
			jQuery("#timeline li").removeClass("selected");
			jQuery(this).addClass("selected");
			jQuery("#timeline #flag").html(contentON);
			jQuery("#timeline #flag").animate({top:yearOnPos}, 500);	
			var target_href = jQuery(this).children("a").attr("href");
			var target_top = jQuery(target_href).offset().top;
			jQuery('html, body').animate({scrollTop:target_top}, 500);
			jQuery("#timeline").animate({top:target_top-150}, 500, function() {doHover=1;});
		});
		jQuery(".part").hover(
		  function(){
        if(doHover){
          jQuery("#timeline li").removeClass("selected");
          selectedLI = jQuery(this).index()-1;
          jQuery("#timeline li:nth-child("+selectedLI+")").addClass("selected");
          contentON = jQuery("#timeline li.selected").html();
          jQuery("#timeline #flag").html(contentON);
          yearOn = jQuery(this).attr("id").split("-");
          yearOn2 = yearOn[1];
          yearOnPos = ((yearOn2 - 1960) * 9.1) + 33;
          timelinePos = jQuery(this).offset().top -150;
          jQuery("#timeline").animate({top:timelinePos}, 500);
          jQuery("#timeline #flag").animate({top:yearOnPos}, 500);
        }
		  }, function(){}
    );
	}
	
	if(jQuery("#social-directory").length){
		jQuery("#social-directory .Investors-contact dd dd dl:even").addClass("left");
		jQuery("#social-directory .Investors-contact dd dd dl:odd").addClass("right");
	}
	
	jQuery("#related-content-bar .hub-span-1").click(function(){
		window.location = jQuery(this).children(".hub-feature").children(".hub-feature-body").children("a").attr("href");
	});
	
	jQuery("#welcome-video").click(function(){
		window.location = jQuery(this).children(".video-wrapper").children("a").attr("href");
	});
	
	jQuery("#news-feeds li").click(function(){
		window.location = jQuery(this).children(".hub-feature").children(".hub-feature-body").children("a").attr("href");
	});
  
  if(1 || jQuery("#investors").length || jQuery("#careers").length){
    // HELVATICA NUEUE OVERRIDES FOR PC
    if (jQuery.client && jQuery.client.os == "Windows"){ /* RM MOD 2011-08-16 add initial check for jQuery.client */
      jQuery('body, .FAQs-topic dt a.expand, events-webcasts .highlight .webcast, #details h2').css('font-family', 'Arial');
    }
    
    if (jQuery.browser.msie && jQuery.browser.version == "6.0"){		
      jQuery(".news-feeds li").hover(function() {jQuery(this).css("border","5px solid #d1d0ca").css("padding","10px 5px 11px").css("background-color","#fff");}, function () {jQuery(this).css("border","0").css("border-bottom","1px solid #e0dfda").css("padding","15px 10px").css("background-color","#F6F5F2");});
      jQuery("#investors .hub-span-2 .hub-span-1:first-child").css("margin-right","12px");		
      jQuery("#related-content-bar .hub-span-1, #related-content-bar .hub-span-2").hover(function() {jQuery(this).css("background-color","#fff").css("border","5px solid #d1d0ca");jQuery(this).find("h2").css("color","#000");}, function () {jQuery(this).css("background-color","#b7b6b2").css("border","5px solid #b7b6b2");});	
      jQuery("#stock-chart-controls dd").hover(function() {jQuery(this).css("background","url('../images/bg-stock-chart-controls.gif') 0 0 no-repeat").css("color","#fff");}, function () {jQuery(this).css("background"," ").css("color","#056BB3");});
      jQuery(".hub-span-2 .hub-row:first-child").css("margin-top","-18px");
    }
    
    // CHILDREN FIXES FOR IE
    if (jQuery.browser.msie){
      jQuery("#annual-reports th:nth-child(2), #quarterly-results .hub-span-3 #details th:nth-child(2), #quarterly-results .hub-span-3 #details td:nth-child(2), #quarterly-results .hub-span-3 th:nth-child(2)").addClass("second-child");
      jQuery(".hub-span-2 #quarterly-results th:nth-child(3), .hub-span-2 #quarterly-results td:nth-child(3), .hub-span-2 #recent-reports th:nth-child(2)").addClass("second2last-child");
      jQuery("#annual-reports th:nth-child(3)").addClass("third-child");
      jQuery("#quarterly-results .hub-span-3 th:nth-child(4), #quarterly-results .hub-span-3 td:nth-child(4), #events-webcasts.hub-span-5 .hub-row .hub-feature-body .twrapper:nth-child(4)").addClass("fourth-child");
      jQuery("th:last-child, td:last-child, #annual-reports td:last-child, #annual-reports td:nth-child(2), #annual-reports .hub-row .hub-feature-body li:nth-child(3n), #events-webcasts .twrapper tr th:nth-child(3), #events-webcasts .twrapper tr th:nth-child(4), #events-webcasts .twrapper tr th:nth-child(5), #events-webcasts .twrapper tr td:nth-child(3), #events-webcasts .twrapper tr td:nth-child(4), #events-webcasts .twrapper tr td:nth-child(5), #stock-chart-tabs li:last-child").addClass("last-child");
      jQuery("#careers #careers-search .hub-span-1:nth-child(2)").css("margin-right","15px");			
    }
    
    function StockQuote(){
      var percentage = (jQuery(this).find("Change").text()*100) / jQuery(this).find("PreviousClose").text();
      if (jQuery(this).find("Change").text() < 0){
        percentage=percentage* (-1);
        jQuery("#stock-quote-change").addClass("negative");
      }
      jQuery("#stock-quote-company").append(jQuery(this).attr("Company"));
      jQuery("#stock-quote-date").append(jQuery(this).find("Date").text());
      jQuery("#stock-quote-trade").append(jQuery(this).find("Trade").text());
      jQuery("#stock-quote-change").append(jQuery(this).find("Change").text()+" ("+percentage.toFixed(4)+"%)");
      jQuery("#stock-quote-volume").append("Volume "+jQuery(this).find("Volume").text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
      if (jQuery("#stock-quote #stock-quote-date").length){
        jQuery("#stock-quote-date").append(" <i> (30 Min. Delay)</i>");
      }
      jQuery("#stock-quote-open").append(jQuery(this).find("Open").text());
      jQuery("#stock-quote-previous").append(jQuery(this).find("PreviousClose").text());
      jQuery("#stock-quote-high").append(jQuery(this).find("High").text());
      jQuery("#stock-quote-low").append(jQuery(this).find("Low").text());
      jQuery("#stock-quote-high52").append(jQuery(this).find("FiftyTwoWeekHigh").text());
      jQuery("#stock-quote-low52").append(jQuery(this).find("FiftyTwoWeekLow").text());
    }
    // STOCK CHART
    var ChartTime="1dy";
    var ChartFreq="1hr";
    var ChartSize=1;
    var ChartType=64;
    var ChartComparison="aaaaa:0";
    var ChartEvents="0";
    
    jQuery("#stock-chart-controls dd").click(function(){
      if (jQuery("#stock-performance").length) {
        ChartSize=2;
        ChartTime=jQuery(this).attr("title");
        if ((ChartTime != "1dy") && (ChartTime != "5dy")){
          jQuery("#stock-chart-tabs input[value='1hr']").parent("dd").addClass("disabled");
          jQuery("#stock-chart-tabs input[value='1hr']").attr("disabled",true);	
          jQuery("#stock-chart-tabs input[value='1dy']").attr("checked",true);
          ChartFreq="1dy";
        }
        else{
          jQuery("#stock-chart-tabs input[value='1hr']").parent("dd").removeClass("disabled");
          jQuery("#stock-chart-tabs input[value='1hr']").attr("disabled",false);	
        }
        jQuery("#stock-chart-frame img").attr("src","http://chart.corporate-ir.net/custom/ccbn-com/stockchart/chart.asp?symb=F&time="+ChartTime+"&freq="+ChartFreq+"&compidx="+ChartComparison+"&uf=0&style=457&size="+ChartSize+"&ma=&maval=&type="+ChartType+"&lf=&nosettings=1&comp=&rand=030103");
      }
      else{
        jQuery("#stock-chart-frame img").attr("src","http://chart.corporate-ir.net/custom/ccbn-com/stockchart/chart.asp?symb=F&"+jQuery(this).attr("title")+"&compidx=&uf=0&style=457&size="+ChartSize+"&ma=&maval=&type=64&lf=&nosettings=1&comp=&rand=030103");
      }
      jQuery("#stock-chart-controls dd").removeClass("selected");
      jQuery(this).addClass("selected");
    });
    jQuery("#stock-chart-tabs h3").click(function(){
      if (!jQuery(this).parents("li").is(':last-child')){
        jQuery("#stock-chart-tabs li").removeClass("selected");
        jQuery(this).parents("li").addClass("selected");
      }
      else{
        jQuery("#stock-chart-frame img").attr("src","http://chart.corporate-ir.net/custom/ccbn-com/stockchart/chart.asp?symb=F&time=1dy&freq=1hr&compidx=&uf=0&style=457&size=2&ma=&maval=&type=64&lf=&nosettings=1&comp=&rand=030103");
        jQuery("#stock-chart-controls dd").removeClass("selected");
        jQuery("#stock-chart-controls dd").first().addClass("selected");
        jQuery("#stock-chart-tabs li").removeClass("selected");
        jQuery("#stock-chart-tabs li").first().addClass("selected");
        jQuery("#stock-chart-tabs input").attr("checked",false);
        jQuery("#stock-chart-tabs input[value='1hr']").attr("checked",true);
        jQuery("#stock-chart-tabs input[value='1hr']").parent("dd").removeClass("disabled");
        jQuery("#stock-chart-tabs input[value='1hr']").attr("disabled",false);	
      }
    });
    
    jQuery("#stock-chart-tabs input").click(function(){
      switch(jQuery(this).attr("name")){
        case "ChartTime":
          ChartTime = jQuery(this).attr("value");
          break;
        case "ChartFreq":
          ChartFreq = jQuery(this).attr("value");
          break;
        case "ChartType":
          ChartType = jQuery(this).attr("value");
          break;
        case "ChartComparison":
          ChartComparison = jQuery(this).attr("value");
          break;
        case "ChartEvents":
          ChartEvents = jQuery(this).attr("value");
          break;
      }
      jQuery("#stock-chart-frame img").attr("src","http://chart.corporate-ir.net/custom/ccbn-com/stockchart/chart.asp?symb=F&time="+ChartTime+"&freq="+ChartFreq+"&compidx="+ChartComparison+"&uf="+ChartEvents+"&style=457&size2&ma=&maval=&type="+ChartType+"&lf=&nosettings=1&comp=&rand=030103");
    });

    //FAQs
    if(jQuery("#FAQs").length){
      FAQURL = window.location.href;
      if(FAQURL.indexOf("#") > 0){
        FAQAnchor = FAQURL.split("#");
        jQuery("a.q[name="+FAQAnchor[1]+"]").parents("dd").addClass("expanded");
        jQuery.scrollTo("-=30px", 1000, {easing:"easeOutExpo"});
      }
      jQuery(".FAQs-topic .q").toggle(
        function(){
          jQuery(this).parents("dd").addClass("expanded");},
        function(){
          jQuery(this).parents("dd").removeClass("expanded");
        });
      jQuery(".FAQs-topic .expand").toggle(function() {
        jQuery(this).parents("dl").children("dd").addClass("expanded");
        jQuery(this).addClass("expanded");
        jQuery(this).html("Collapse All");
      }, function() {
        jQuery(this).parents("dl").children("dd").removeClass("expanded");
        jQuery(this).removeClass("expanded");
        jQuery(this).html("Expand All");
      });
    }
    
    //Social Directory
    if(jQuery("#social-directory").length){
      jQuery("#social-directory .control").each(function(){
        jQuery(this).addClass("expanded").siblings("dl").addClass("expanded");
        jQuery(this).click(function(e){
          e.preventDefault();
          if(jQuery(this).hasClass("expanded")){
            jQuery(this).removeClass("expanded").siblings("dl").removeClass("expanded");
          }
          else {
            jQuery(this).addClass("expanded").siblings("dl").addClass("expanded");
          }
        });
      });
      //jQuery("#social-directory .index dd a").each(function(){
      //  jQuery(this).click(function(){
      //    jQuery(".control", jQuery("" + jQuery(this).attr("href") + "").parent().parent()).click();
      //  });
      //});
    }
    
    //IMAGE OVERLAY
    jQuery(".imgwrapper").click(function(){
      var imgfile = jQuery(this).children("img").attr("src").split(".");
      var imgfileFull = jQuery(this).children("img").attr("src");
      imgfileSrc = imgfile[2]+"-large."+imgfile[3];
      if (jQuery(this).children(".caption").html() != null) imgCaption = "<span class='caption'>"+jQuery(this).children(".caption").html()+"</span>";
      else imgCaption = "";
      if (jQuery(this).children(".credit").html() != null) imgCredit = "<span class='credit'>"+jQuery(this).children(".credit").html()+"</span>";
      else imgCredit = "";
      jQuery(this).after("<div class='imgwrapper overlay'><div><img src='"+imgfileSrc+"' />"+imgCaption+imgCredit+"<span class='close'></span></div></div>");
      if(jQuery(".imgwrapper.overlay img").attr("width") == 0) jQuery(".imgwrapper.overlay img").attr("src",imgfileFull);
      jQuery(".imgwrapper.overlay .close").click(function () {
        jQuery(this).parents(".imgwrapper.overlay").remove();
      });
      jQuery("body").mouseup(function(){ 
          jQuery(".imgwrapper.overlay").remove();
      });
    });
    
    //ADD TO CALENDAR
    jQuery("a.calendar, div.calendar").click(function(e){
      e.preventDefault();
      e.stopPropagation();
      addToCalendar(jQuery(this), jQuery(this).attr("name"));
    });
    jQuery(document).click(function(e){
      if(!jQuery(e.target).parents().hasClass("news-feeds") || !jQuery(e.target).parents().hasClass("select-event")){ closeCalendar(e); }
    });
    function addToCalendar(target,CID){
      if(!(jQuery("#add-calendar.overlay").length)){
        target.append("<div class='overlay' id='add-calendar'><div><span class='overlay-header'>Add to My Calendar </span><span class='overlay-intro'>Dynamic Messaging</span><span class='overlay-body'><dl class='link-list'><dd class='calendar'><a target='_blank' href='/servlet/Satellite?pagename=FordCom%2FGlobalModules%2FRenderCalendarAppointment&c=FmcContentC&cid="+CID+"&account=outlook'>Add to Outlook</a></dd><dd class='calendar'><a target='_blank' href='/servlet/ContentServer?c=FmcContentC&cid="+CID+"&pagename=FordCom%2FGlobalModules%2FAddCalendarEvent&account=google'>Add to Google Calendar</a></dd><dd class='calendar'><a target='_blank' href='/servlet/ContentServer?c=FmcContentC&cid="+CID+"&pagename=FordCom%2FGlobalModules%2FAddCalendarEvent&account=yahoo'>Add to Yahoo Calendar</a></dd><dd class='calendar'><a target='_blank' href='/servlet/Satellite?pagename=FordCom%2FGlobalModules%2FRenderCalendarAppointment&c=FmcContentC&cid="+CID+"&account=ical'>Add to iCal</a></dd></dl></span><span class='close'>Close</span></div></div>");
      }
      target.parents("li").addClass("on");
      jQuery("#add-calendar.overlay").parents(".hub-row").parent().css({"z-index": "900"});
      jQuery("#add-calendar.overlay").css({top: "-15px", left: "-75px"}).click(function(){ return false; }).fadeIn();
      jQuery("#add-calendar.overlay .close").click(function(e){ closeCalendar(e); return false; });
      jQuery("#add-calendar.overlay .overlay-body dd a").click(function(e){
        e.preventDefault();
        if(jQuery(":contains('Yahoo'), :contains('Google')", this)){ window.open(this.href, '_blank'); }
        else { window.location = jQuery(this).attr("href"); }
        closeCalendar(e);
        return false;
      });
    }
    function closeCalendar(e){
      jQuery("#add-calendar.overlay").parents("li").removeClass("on");
      jQuery("#add-calendar.overlay").fadeOut("fast", function(e){
        jQuery(this).parents(".hub-span-1").parent().css({"z-index": "200"});
        jQuery(this).remove();
      });
    }
    //END ADD TO CALENDAR

    jQuery("#related-content-bar .hub-span-1").click(function(){
      window.location = jQuery(this).children(".hub-feature").children(".hub-feature-body").children("a").attr("href");
    });
    
    jQuery("#related-content-bar .hub-span-2").click(function(){
      window.location = jQuery(this).children(".hub-feature").children("a").attr("href");
    });
    
    jQuery("#welcome-video").click(function(){
      window.location = jQuery(this).children(".video-wrapper").children("a").attr("href");
    });

    jQuery("#contact-us .select-all").click(function(){
      jQuery("#contact-us-documents input").attr("checked",true);
    });
    
    jQuery("#contact-us-documents li").click(function() {
      if (jQuery(this).children("input").attr("checked"))
        jQuery(this).children("input").attr("checked",false);
      else
        jQuery(this).children("input").attr("checked",true);
    });
    
    jQuery("#contact-us .select-all").toggle(function() {
      jQuery("#contact-us-documents input").attr("checked",true);
      jQuery(this).html("Deselect All");
    }, function() {
      jQuery("#contact-us-documents input").attr("checked",false);
      jQuery(this).html("Select All");
    });
    
    //FORM VALIDATION
    jQuery('#contact-phone').keyup(function () { this.value = this.value.replace(/[^0-9\.]/g,'');});
    jQuery('#contact-fax').keyup(function () { this.value = this.value.replace(/[^0-9\.]/g,'');});
    
    if (jQuery("#contactMainTopic").length){		
      function contactMainTopic(switchPar){
        switch(switchPar)
        {
          case "InvestorRelations":
            jQuery("#contact-inquiry").show();
            jQuery("#contact-information-2").show();
            break;
          case "VehicleServiceIssues":
            jQuery("#contact-inquiry").show();
            jQuery("#vehicle-information").show();
            jQuery("#contact-information-1").show();
            break;
          case "VehicleWarrantyQuestions":
            jQuery("#contact-inquiry").show();
            jQuery("#vehicle-information").show();
            jQuery("#contact-information-1").show();
            break;
          default: 
            jQuery("#contact-information-2").show();
            break;
        }
      }
      
      jQuery(".contact-us-wrapper").hide();
      jQuery("#email-information").show();
      
      var EMAILURL = window.location.href;
      if(EMAILURL.indexOf("#") > 0){
        EMAILURL = EMAILURL.split("#");
        switchPar = EMAILURL[1];
        jQuery("#contactMainTopic option").attr("selected",false);
        jQuery("#contactMainTopic option[value='"+switchPar+"']").attr("selected",true);
      }
      else{
        switchPar = jQuery("#contactMainTopic option:selected").attr("value");
      }
      contactMainTopic(switchPar);
      jQuery('#contactMainTopic').change(function () {
        switchPar = jQuery("#contactMainTopic option:selected").attr("value");
        jQuery(".contact-us-wrapper").hide();
        jQuery("#email-information").show();
        contactMainTopic(switchPar);
      });
    }
  }
  
  //================= Alex Shapiro JS ================//
  jQuery("#plant-list .twrapper .header th").bind("click", function(){
    if(!jQuery(this).hasClass("on")){
      jQuery("#plant-list .twrapper .header th").removeClass("on");
      jQuery(this).addClass("on");
      var sortBy = jQuery(this).data("val");
      buildList(sortBy);
    }
  });
  jQuery("#plant-list .twrapper .header th[data-val='TYPE']").css({width: "117px"});
  jQuery("#plant-list .twrapper .header th[data-val='NAME']").css({width: "345px"});
  jQuery("#plant-list .twrapper .header th[data-val='TOTAL_EMPLOYMENT']").css({width: "65px"});
  jQuery("#plant-list .twrapper .header th[data-val='YEAR_OPENED']").css({width: "45px"});
  jQuery("#plant-list .twrapper .header th[data-val='PLANT_SIZE']").css({width: "90px"});
  jQuery("#plant-list .twrapper .header th[data-val='SITE_SIZE']").css({width: "71px"});
  jQuery("#plant-list .twrapper .header th[data-val='COUNTRY']").css({width: "92px"}).click();
  
  function buildList(sortBy){
    var URL = window.fmcDomain + "/xml/plant.xml";
    jQuery.get(URL, function(data){
      var plants = jQuery("PLANT" + plantTYPESelected, data);
      if(plants.length){
        var arr = [];
        var arr_e = [];
        plants.each(function(){
          jQuery(this).children().each(function(){ (jQuery(this).text().trim() == "")? jQuery(this).text("&mdash;") : ""; });
          var str = jQuery(sortBy, jQuery(this)).text();
          (str == "&mdash;")? arr_e.push(jQuery(this)) : arr.push(str);
        });
        
        arr.sort(function(a, b) {
          if((a.match(/[0-9 -()+]+$/ig))? true : false){
            a = parseInt(a); b = parseInt(b);
          }
          return (a < b) ? -1 : (a > b) ? 1 : 0;
        });
        
        jQuery("#plant-count strong").text(arr.length);
        var container = jQuery("#plant-list .twrapper tbody");
        container.find("tr:gt(0)").remove();
        
        var multiples = 0;
        var currVal = arr[0];
        jQuery.each(arr, function(i){
          if(currVal != arr[i]) multiples = 0;
          //var plant = jQuery(sortBy + ":contains('" + arr[i] + "')", plants).parent();
          var plant = jQuery(sortBy, plants).filter( function (index) {
            return jQuery(this).text() == arr[i];
          }).parent();

          if(plant.length > 1){
            plant = plant[multiples];
            multiples++;
          }
          currVal = arr[i];
          makeRow(plant, i).appendTo(container);
        });
        jQuery.each(arr_e, function(i){
          makeRow(jQuery(this), i).appendTo(container);
        });
      }
    }).error(function() { alert("Our apologies but the data source is temporarily unavailable."); });
  }
  
  function makeRow(plant, i){
    return jQuery('<tr' + ((i % 2 == 1)? " class='odd'" : "") + '>'
            + '<td><span class="val">' + jQuery("COUNTRY", plant).text().trim() + '</span></td>'
            + '<td><span class="val">' + jQuery("TYPE", plant).text().trim() + '</span></td>'
            + '<td><span class="val"><a href="' + jQuery("DETAIL_URL", plant).text().trim() + '">' + jQuery("NAME", plant).text().trim() + '</a></span></td>'
            + '<td><span class="val">' + formatNum(jQuery("TOTAL_EMPLOYMENT", plant).text().trim()) + '</span></td>'
            + '<td><span class="val">' + jQuery("YEAR_OPENED", plant).text().trim() + '</span></td>'
            + '<td><span class="val">' + jQuery("LEGAL_ENTITY", plant).text().trim() + '</span></td>'
            + '<td><span class="val">' + formatNum(jQuery("PLANT_SIZE", plant).text().trim()) + " " + ((jQuery("PLANT_SIZE", plant).text() == "&mdash;")? "" : jQuery("PLANT_SIZE", plant).attr("units")) + '</span></td>'
            + '<td><span class="val">' + formatNum(jQuery("SITE_SIZE", plant).text().trim()) + " " + ((jQuery("SITE_SIZE", plant).text() == "&mdash;")? "" : jQuery("SITE_SIZE", plant).attr("units")) + '</span></td>'
            + '</tr>');
  }
  
  function formatNum(str){
    var deci = "";
    if(str.indexOf(".") != -1){
      deci = str.substring(str.indexOf("."), str.length);
      str = str.substring(0, str.indexOf("."));
    }
    if(str.length > 3 && parseInt(str)){
      var ret = [];
      for(var i=0; i < str.length; i += 3){
         ret.push(str.substring(str.length-(i+3), str.length-i));
      }
      ret.reverse();
      return (ret.join(",")) + "";
    }
    else return str + deci;
  }

  /* Slides init */
  if(jQuery(".slides").length){
    var cache = [];
    var loadedCount = 0;
    var cacheDone = false;
    var cacheArr = jQuery(".slides_container img");
    jQuery.each(cacheArr, function(i){
      var cacheImage = document.createElement('img');
      cacheImage.onload = function(){loadedCount++;}
      cacheImage.src = this.src;
      cache.push(cacheImage);
      
    });

    function checkSlides(){
      if(loadedCount == (cacheArr.length)){cacheDone = true;}
      if(cacheDone || jQuery(".slides_container img").length == 0){ clearInterval(checkSlidesState); readySlides();
    }}
    var checkSlidesState = setInterval(checkSlides, 100);
    
    function readySlides(){
      jQuery(".vehicles-wrapper.slides, #hot-topic.slides").each(function(){
        jQuery(this).slides({
          slideEasing: "easeInOutQuad",
          slideSpeed: 300,
          pagination: (jQuery(this).attr("id") == "hot-topic")? true : false
        });
      });
      
      jQuery("#History-slideshow-1, #Environment-slideshow-1, #Back-Story-slideshow-2, #story-slideshow, #mustang-story .slides").each(function(){
        var _root = jQuery(this);
        if(!_root.hasClass("cf")) _root.addClass("cf");
        jQuery(this).slides({
          animationComplete: function(current) {
            jQuery(".slide-no", _root).html(current + "/" + jQuery(".slides_control", _root).children().length);
          },
          slideEasing: "easeInOutQuad",
          slideSpeed: 300,
          pagination: false
        });
        jQuery(".slide-no", this).html("1/" + jQuery(".slides_control", this).children().length);
      });
    }
  }

  /* FLOATING NAV on focus and fiesta (dependent on .slides load if present to get the right height of parts) */
	if(jQuery("#focus-story").length){
    jQuery("<img>").attr({src: "/images/bg-floating-nav.png"}).appendTo("#floating-nav").css({display: "none"});
		if(jQuery.browser.msie){
			floatingnavliCounter= 0
			jQuery("#floating-nav li").each(function(){
				floatingnavliCounter+=1;
				jQuery(this).attr('id', "nav"+floatingnavliCounter);
			});
		}

    var parts = [];
    function getParts(){
      parts[0] = {id: "focus-story", top: jQuery("#focus-story").offset().top, height: jQuery("#focus-story .hub-span-4:first").outerHeight(true), menu_offset: 280};
      jQuery(".part").each(function(i){
        parts[i+1] = {id: jQuery(this).attr("id"), top: jQuery(this).offset().top, height: jQuery(this).outerHeight(true), menu_offset: jQuery("#floating-nav li:eq("+(i+1)+")").position().top + 280};
      });
      jQuery(window).scroll();
    }
    
    if(jQuery(".slides").length){
      function checkSlidesStatus(){if(cacheDone){ clearInterval(runGetParts); getParts(); }}
      var runGetParts = setInterval(checkSlidesStatus, 100);
    }
      
    var fn = {};
    fn.left = jQuery("#floating-nav").offset().left;
    fn.top = jQuery("#floating-nav").offset().top;
    jQuery("#floating-nav").css({left: fn.left + "px", top: fn.top + "px", position: "fixed"});
    
		jQuery("#floating-nav li a").click(function(e){
      e.preventDefault();
      if(!jQuery("body").hasClass("collapsed")){ getParts(); }
      var _root = jQuery(this);
      var target = _root.attr("href");
      var menuNum = _root.parents("#floating-nav").children().index(_root.parent());
      jQuery.scrollTo(target, 1500, {queue: true, offset: {top: (parts[menuNum].menu_offset)*(-1)}, easing:'easeOutExpo', onAfter: function(){
        jQuery("#floating-nav li").removeClass("selected");
        if(target != "#focus-story") _root.parent().addClass("selected");
      }});
		});
    
    jQuery(window).scroll(function(){
      var s = jQuery(window).scrollTop();
      if(s > jQuery("#footer").offset().top - 550){
        jQuery("#floating-nav").css({left: ((isIE8)?1:0) + "px", top: (jQuery("#footer").offset().top - 525) + "px", position: "absolute"});
      }
      else {
        if(jQuery("#floating-nav").css("position") == "absolute") jQuery("#floating-nav").css({left: fn.left + "px", top: fn.top + "px", position: "fixed"});
        for(var i=0; i<parts.length; i++){
          var o = jQuery("#floating-nav li a[href=\"#" + parts[i].id + "\"]").parent();
          if((s) > (parts[i].top - (50 + parts[i].menu_offset)) && s < (parts[i].top + parts[i].height) && !o.hasClass("selected")){
            jQuery("#floating-nav li").removeClass("selected");
            if(parts[i].id != "focus-story") o.addClass("selected");
          }
        }
      }      
    }).resize(function(){
      fn.left = jQuery("#floating-nav").parent().offset().left;
      jQuery("#floating-nav").css({left: fn.left + "px"});
    });
	}	/* FLOATING NAV END */

  /* World Map (country websites) */
  if(jQuery("#world-map").length){
    jQuery("<img/>")[0].src = window.fmcDomain + "/images/world-map-dd-bg.png";
    var selRegion = "";
    var regionsArr = jQuery.parseJSON('{"na":"north-america", "la":"latin-america", "eu":"europe", "me":"middle-east", "ap":"asia-pacific", "af":"africa"}');
    jQuery.each(regionsArr, function(key, val){
      jQuery("#world-map").append("<img class='region-on " + key + "' src='/images/world-map-" + val + ".png' />");
    });    
    var URL = window.fmcDomain + "/xml/country-websites.xml";
    jQuery.get(URL, function(data){
      xmlCountry = jQuery(data).find("COUNTRY");
      xmlCountry.each(function(){
        jQuery("#world-map .co." + jQuery(this).find("REGION_CODE").text().toLowerCase() + " .dd-wrap select").append("<option data-iso='" + jQuery(this).find("ISO").text() + "'>" + jQuery(this).find("NAME").text() + "</option>");
      });
    });
    
    function mapAreaIn(r){
      jQuery("#world-map .co." + r).addClass("on");
      jQuery("#world-map img.region-on." + r).fadeIn(200, "easeOutQuad", function(){ });
    }
    function mapAreaOut(r){
      if((selRegion != r || arguments.length > 1) && r != ""){
        if(arguments.length > 1) jQuery("#world-map .cn").hide();
        jQuery("#world-map .co." + r).removeClass("on top");
        jQuery("#world-map .co." + r + " .dd-wrap").hide();
        jQuery("#world-map img.region-on." + r).fadeOut(300, "easeOutQuad", function(){ });
      }
    }
    jQuery("#world-map #map-bg").click(function(e){ e.preventDefault(); mapAreaOut(selRegion, true); selRegion = ""; });
    jQuery("#world-map .co a.title").click(function(e){ e.preventDefault(); });
    
    jQuery("#world-map map area").each(function(){
      var region = jQuery(this).attr('class');
      var settings = {sensitivity: 4, interval: 40,
        over: function(){ mapAreaIn(region) },
        out: function(){ mapAreaOut(region) }
      };
      jQuery(this).hoverIntent(settings);
      jQuery(this).bind("click", function(e){
        e.preventDefault();
        e.stopPropagation();
        if(selRegion != region && selRegion != ""){
          var temp = selRegion;
          selRegion = region;
          mapAreaOut(temp);
        }
        selRegion = region;
        var thisRegion = jQuery("#world-map .co." + region);
        jQuery(".dd-wrap", thisRegion).show();
        thisRegion.addClass("top");
        if(selRegion != ""){
          jQuery("#world-map .co." + selRegion + " .dd-wrap select").val("Please select");
          jQuery("#world-map .co." + selRegion + " .dd-wrap .customStyleSelectBoxInner").text("Please select");
        }
      }).bind("mouseup", function(){
        jQuery(this).blur();
      });
      
      jQuery("#world-map .co." + region + " .dd-wrap select").bind("change", function(){
        var currCountry = jQuery("option:selected", this).val();
        var URL = window.fmcDomain + "/xml/country-websites.xml";
        jQuery.get(URL, function(data){
          xmlCountry = jQuery(data).find("COUNTRY").filter(function(){
            return jQuery(this).find("NAME").text() == currCountry;
          });
          var cn = jQuery("#world-map .cn");
          
          if(jQuery("li", cn).length) cn.animate({top: "400px"}, 120, "easeOutQuad", function(){ countryProps(); });
          else countryProps();
          
          function countryProps(){
            jQuery(".site", cn).remove();
            jQuery(".name", cn).text(jQuery("NAME", xmlCountry).text());
            jQuery("SITE", xmlCountry).each(function(i){
              var iconUrl = jQuery(this).attr("icon_url");
              jQuery(cn).append("<li class='site" + (((i+1) % 2)? "" : " nm") + "'>" + ((iconUrl == "")? "" : "<img src='" + iconUrl + "' />") + "<a href='" + jQuery(this).text() + "' target='" + jQuery(this).attr("url_loc") + "'>" + jQuery(this).attr("name") + "</a></li>");
            });
            cn.show().animate({top: (380 - cn.height()) + "px"}, 120, "easeInQuad");
          }

        }).error(function() { alert("Our apologies but the data source is temporarily unavailable."); });
      }).bind("mouseenter", function(){
        jQuery(this).siblings(".customStyleSelectBox").addClass("mo");
      }).bind("mouseleave", function(){
        jQuery(this).siblings(".customStyleSelectBox").removeClass("mo");
      });
    });
  } /* World Map (country websites) end */
  
  /* Country Websites List */
  if(jQuery("#country-list").length){
    function openTarget(t){
      jQuery(".region div.control, .region div.countries").removeClass("expanded");
      jQuery(t).siblings("div.control").addClass("expanded").parent().siblings("div.countries").addClass("expanded");
    }

    var o = window.location.href;
    if(o.indexOf("#") != -1){ openTarget("#" + o.split("#")[1].toLowerCase()); }
    
    jQuery("#country-list div.regions ul li a").each(function(){
      var targetId = jQuery(this).attr("href").toLowerCase();
      if(jQuery(targetId).length){
        jQuery(this).bind("mousedown", function(e){  
          openTarget(targetId);
        }).click(function(e){e.preventDefault();});
      }
      else{
        jQuery(this).unbind("click").click(function(e){e.preventDefault();});
      }
    });
  
    jQuery("#country-list div.control").each(function(){
      jQuery(this).click(function(){
      
        if(jQuery(this).hasClass("expanded")){
          jQuery(this).removeClass("expanded");
          jQuery(this).parent().siblings(".countries").removeClass("expanded");
        }
        else {
          jQuery(this).addClass("expanded");
          jQuery(this).parent().siblings(".countries").addClass("expanded");
        }
        
      });
    });
  }
  
  FMCVideo.init();
  
  //Style SELECT boxes
  jQuery(".styled-select").customStyle();

}); //END ONREADY --------------------------------------------------------------------------------------------------------------------------------

jQuery.urlParam = function(name, src){
  var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec( src || window.location.href); // if src is undefined defualt is window.location.href
  if (!results) { return 0; }
  return results[1] || 0;
}

// jQuery video player interface
function onYouTubePlayerReady(playerId){
  var ytplayer = jQuery("#FMCplayer-" + playerId).get(0);
  ytplayer.addEventListener("onStateChange", '(function(state) { return FMCVideo.trackStateChange(state, "' + playerId + '"); })');
  ytplayer.addEventListener("onError", '(function(state) { return FMCVideo.errorHandler(state, "' + playerId + '"); })');
}
var FMCVideo = {
  object: function(playerId){
    return jQuery("#FMCplayer-" + playerId).get(0);
  },
	init: function(){
    jQuery(".video-wrap").each(function(){
      var settings = jQuery.parseJSON(jQuery(this).data("target").replace(/'/g,"\""));
      var videoURL = "http://www.youtube.com/v/" + settings.id + "?wmode=opaque&enablejsapi=1&playerapiid=" + settings.id + "&version=3&theme=light&autohide=1&showinfo=1&modestbranding=1";    
      jQuery(this).css({width: settings.width, height: settings.height});
      jQuery("<div id='FMCplayer-" + settings.id + "' />").addClass("FMCplayer").html("You need Flash player 8+ and JavaScript enabled to view this video.").appendTo(jQuery(this));
      if(swfobject.getFlashPlayerVersion().major >= 8){
        var params = {allowScriptAccess: "always", wmode: "opaque"};
        var atts = {id: "FMCplayer-" + settings.id};
        swfobject.embedSWF(videoURL, "FMCplayer-" + settings.id, settings.width, settings.height, "8", null, null, params, atts);
      }
    });
    jQuery(window).unload(function(){
      //console.log(FMCVideo.videoOmnitureCall("nz7zGZdBxvc", "play"));
      //FMCVideo.videoOmnitureCall("nz7zGZdBxvc", "play");
    });
	},
  trackStateChange: function(state, playerId){
    var ytplayer = this.object(playerId);
    var isNew = (ytplayer.id.indexOf("FMCplayer") != -1)? true : false;
    var videoURL = ytplayer.getVideoUrl();
    var duration = ytplayer.getDuration();
    var percentage = Math.round((ytplayer.getCurrentTime() * 100) / duration);
    switch(state){
      case -1:
        //console.log("case -1, video " + playerId + " loaded but unstarted. Total length: " + duration + " seconds");
        break;
      case 0:
        //console.log("case 0, video " + playerId + " has ended");
        //this.videoOmnitureCall(playerId, "ended");
        break;
      case 1:
        //console.log("case 1, video " + playerId + " is playing");
        this.videoOmnitureCall(playerId, "play");
        break;
      case 2:
        //console.log("case 2, paused " + playerId + " at " + ytplayer.getCurrentTime() + " seconds, (" + percentage + "%)");
        //this.videoOmnitureCall(playerId, "paused at " + Math.round(ytplayer.getCurrentTime()) + " seconds, (" + percentage + "%)");
        break;
      case 3:
        //console.log("case 3, video " + playerId + " is buffering");
        break;
      case 5:
        //console.log("case 5, video " + playerId + " is qued");
        break; 
      default:
        //console.log("default: ", playerId, state, videoURL);
    }
  },
	videoOmnitureCall: function(playerId, action){
    var obj = this.object(playerId);
		this.s = s_gi(s_account);
		this.s.prop1 = s.pageName;
		this.s.prop5 = "ford: video play "+ playerId;
		this.s.prop6 = "ford: "+ playerId;
		this.s.linkTrackVars = "prop1,prop5,prop6"; 
		this.s.linkTrackEvents = "None";
    this.s.tl(this,"o"," video play"+playerId+": "+s.pageName);
		//this.s.tl(this,"o","videoId: " + playerId + " | action: " + action + " | page: " + s.pageName);
    //console.log("Omniture track: video " + playerId + " on page: " + s.pageName + " | action: " + action);
	},
  errorHandler: function(code, playerId){
    //console.log(code, playerId)
  }
  
}; // END FMCVideo
