/*!
 * MazdaUSA.com namespace, includes all common and landing page functionality.
 * @author Chris Kennedy
 * @author Adam Abouraya
 */
 
Musa = {}

Musa.Common = {  
	elements : {
		
	},
	
	initialize : function(){
		var _this = this;
		
		//Locate a Dealer input in global nav, submit and default-clear
		var searchFieldID = $('.genericSearchField');
		var searchFieldVal = searchFieldID.val();
		var defaultText = '';
		var submitBtn = $('a.submit_btn');
		if(searchFieldID){
			defaultText = 'C\363digo postal';
		}
		if(searchFieldID){
			//submit
			searchFieldID.keyup(function(e){
				if(e.keyCode == 13){
					$('#dealerSearchForm').submit();
					return false;
				}
			});
			
			//default-clear
			searchFieldID.bind('focus',function(e){
				e.preventDefault();
				if(this.value == defaultText){
					this.value = '';
				}else{
					return;	
				}
			});
			
			submitBtn.bind('click',function(e){
				//omniture tag
				s.linkTrackVars="eVar2";
				s.eVar2="globalnav_dealer_locate";
				s.tl();
				s.trackExternalLinks=false;
				void(s_gi(s_account));
				
				$('#dealerSearchForm').submit();
			});
			footerLinkHover();
		}
		
		//Hover animation for social media icons on VLPs
		_this.toggleIcons('#garage_subNav ul.social_links li a');
		
		//Survey popup and cookie functionality
		if($('.topnav_menu').length > 0 || $('#marketnav').length > 0){
			return;
		}else{
			var pageCount,pVal,pCk,pArr,cDate,eDate,p,sp,st,stv,sWin;
			var sID = $('.surveyUserId').val();
			if($.cookie('survey_pop') == null){
				cDate = new Date();
				cDate.setDate(cDate.getDate()+90);
				eDate = cDate.toGMTString();
				p = eDate;
				st = '0';
				document.cookie = "survey_pop="+pageCount+"&"+st+"&"+p+"; expires="+eDate;
			}
			var pCk = $.cookie('survey_pop');
			pArr = pCk.split("&");
			pVal = pArr[0];
			stv = pArr[1];
			sp = pArr[2];
			if(pVal >= 1){
				pVal++;
				document.cookie = "survey_pop="+pVal+"&"+stv+"&"+sp+"; expires="+sp;
				if(pVal % 3 == 0 && stv == '0'){
					s.linkTrackVars="eVar29";
					s.eVar29=sID;
					s.tl();		
					void(s_gi(s_account));
					st = '1';
					document.cookie = "survey_pop="+pVal+"&"+st+"&"+sp+"; expires="+sp;
					sWin = window.open('http://www.zaazresearch.com/se.ashx?s=251137453133E6EC'+'&mazdaid='+sID,'MazdaSurvey','width=700,height=535');
					if(self.closed){
						sWin.focus();
					}
				}
			}else{
				pVal = 1;
				document.cookie = "survey_pop="+pVal+"&"+stv+"&"+sp+"; expires="+sp;
			}
		}

	},
	
	popup: function(url,w,h,scroll,resize,locbar) {
		window.open(url, 'newWindow','width='+ w + ',height=' + h +',scrollbars='+scroll + ',resizable=' + resize + ',location='+ locbar);
	
	},
	
	/*Global hover animation function for icons
	 * Pass in parent anchor/link elements for querying to ('ele')
	 * To call use: Musa.Common.toggleIcons('ele');
	 * Example: Musa.Common.toggleIcons('#homeID ul.media_icons li a');
	 */
	toggleIcons : function(ele){
		$(ele).hover(
			//handlerIn
			function(){
				$(this).find('div.on').stop().fadeTo('slow', 1.0).show();		
			},
			//handlerOut
			function(){
				$(this).find('div.on').stop().fadeTo('slow', 0);
		});		
	}
	
} 

Musa.Globalnav = {
	elements : {
		
	},
	
	initialize : function(){
		var _this = this;
		/**** Toggle navigation and flyouts BEGINS ****/
		$.fn.toggleNav = function(op){
			var mType = op;
			var winWidth = $('body').width();
			var winHeight = $('body').height();
			var grayBg = $('.gray-bg');
			var tn = $.fn.toggleNav,
				c = tn.c,
				over = function(){
					var $$ = $(this), menu = getMenu($$);
					clearTimeout(menu.sfTimer);
					$$.showNavUl().siblings().hideNavUl();
					//Display shadow BG for flyouts
					if(mType == 'alinks'){
						grayBg.css({'display':'block','width':winWidth,'height':winHeight});	
					}
				},
				out = function(){
					var $$ = $(this), menu = getMenu($$), o = tn.op;
					clearTimeout(menu.sfTimer);
					menu.tnTimer=setTimeout(function(){
						o.retainPath=($.inArray($$[0],o.$path)>-1);
						$$.hideNavUl();
						//Display shadow BG for flyouts
						if(mType == 'alinks'){
							grayBg.css('display','none');
						}
						if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
					},o.delay);	
				},
				getMenu = function($menu){
					var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
					tn.op = tn.o[menu.serial];
					return menu;
				}
				
			return this.each(function() {
				var s = this.serial = tn.o.length;
				var o = $.extend({},tn.defaults,op);
				o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
					$(this).addClass([o.hoverClass,c.bcClass].join(' '))
						.filter('li:has(ul)').removeClass(o.pathClass);
				});
				tn.o[s] = tn.op = o;
				
				$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
					if (o.autoArrows) addArrow( $('>a:first-child',this) );
				})
				.not('.'+c.bcClass)
					.hideNavUl();
				
			}).each(function() {
				var menuClasses = [c.menuClass];
				if (tn.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
				$(this).addClass(menuClasses.join(' '));
			});
		};
	
		var tn = $.fn.toggleNav;
		tn.o = [];
		tn.op = {};
		tn.IE7fix = function(){
			var o = tn.op;
			};
		tn.c = {
			bcClass     : 'tn-breadcrumb',
			menuClass   : 'tn-js-enabled',
			anchorClass : 'tn-with-ul',
			arrowClass  : 'tn-sub-indicator',
			shadowClass : 'tn-shadow'
		};
		tn.defaults = {
			hoverClass	: 'tnHover',
			pathClass	: 'overideThisToUse',
			pathLevels	: 1,
			delay		: 500,
			animation	: {opacity:'show'},
			speed		: 'normal',
			autoArrows	: false,
			dropShadows : false,
			disableHI	: false,		
			onInit		: function(){},
			onBeforeShow: function(){},
			onShow		: function(){},
			onHide		: function(){}
		};
		tn.img = {
			autoImg : ['auto_mazda2.png','','auto_mazda5.png','auto_mazda6.png','','auto_rx8.png','auto_cx5.png','auto_cx7.png','auto_cx9.png','auto_tribute.png'],
			autoWidth : ['566','','577','670','','659','627','627','591','583'],
			autoHeight : ['343','','336','314','','299','321','321','314','325']	
		};
		tn.img2 = {
			autoImg : ['auto_mazda3a.png','auto_mazda3b.png','auto_mazda3c.png'],
			autoWidth : ['321','323','330'],
			autoHeight : ['149','147','165']
		};
		tn.img3 = {
			autoImg : ['auto_mx5st.png','auto_mx5ht.png'],
			autoWidth : ['425','395'],
			autoHeight : ['169','180']
		};
		$.fn.extend({
			hideNavUl : function(){
				var o = tn.op,
					not = (o.retainPath===true) ? o.$path : '';
				o.retainPath = false;
				var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
						.find('>ul').hide().css('visibility','hidden');
				o.onHide.call($ul);
				return this;
			},
			showNavUl : function(){
				var o = tn.op,
					//sh = tn.c.shadowClass+'-off',
					$ul = this.addClass(o.hoverClass)
						.find('>ul:hidden').css('visibility','visible');
						//lazy load flyout vehicle images
						var e = $(this).index();
						var i = e - 1;
						if(i == 1){
							//load Mazda3 images
							var _this = $(this);
							$.ajax({
								beforeSend: function(){
									for(j=0; j<=2; j++){
										var k = j+1;
										_this.find('>ul .col' + k + ' .auto_image a').html('<img src="http://images.mazdausa.com/MusaWeb/musa2/images/global/loading.gif" class="loader" height="36" width="36" alt="" />');
									}
								},
								success: function(){
									for(m=0; m<=2; m++){
										var p = m+1;
										_this.find('>ul .col' + p + ' .auto_image a').html('<img src="http://www.mazdaespanol.com/mazdausa/enes/24/_images_mazdausa_com/MusaWeb/musa2/images/global/topnav/' + tn.img2.autoImg[m] + '" height="' + tn.img2.autoHeight[m] + '" width="' + tn.img2.autoWidth[m] + '" alt="" />');	
									}
								}
							});
						}else if(i == 4){
							//load MX-5 images
							var _this = $(this);
							$.ajax({
								beforeSend: function(){
									for(n=0; n<=1; n++){
										var p = n+1;
										_this.find('>ul .col' + p + ' .auto_image a').html('<img src="http://images.mazdausa.com/MusaWeb/musa2/images/global/loading.gif" class="loader" height="36" width="36" alt="" />');
									}
								},
								success: function(){
									for(r=0; r<=1; r++){
										var s = r+1;
										_this.find('>ul .col' + s + ' .auto_image a').html('<img src="http://www.mazdaespanol.com/mazdausa/enes/24/_images_mazdausa_com/MusaWeb/musa2/images/global/topnav/' + tn.img3.autoImg[r] + '" height="' + tn.img3.autoHeight[r] + '" width="' + tn.img3.autoWidth[r] + '" alt="" />');	
									}
								}
							});
						}else{
							var _this = $(this).find('>ul .subautonav_right a');
							$.ajax({
								beforeSend: function(){
									_this.html('<img src="http://images.mazdausa.com/MusaWeb/musa2/images/global/loading.gif" class="loader" height="36" width="36" alt="" />');	
								},
								success: function(){
									_this.html('<img src="http://www.mazdaespanol.com/mazdausa/enes/24/_images_mazdausa_com/MusaWeb/musa2/images/global/topnav/' + tn.img.autoImg[i] + '" height="' + tn.img.autoHeight[i] + '" width="' + tn.img.autoWidth[i] + '" alt="" />');	
								}
							});
						}
						
				tn.IE7fix.call($ul);
				o.onBeforeShow.call($ul);
				$ul.animate(o.animation,o.speed,function(){ tn.IE7fix.call($ul); o.onShow.call($ul); });
				
				return this;
			}
		});
		
		//Initiate nav to be toggled
		$('ul.globalnav_clinks').toggleNav();
		$('ul.globalnav_alinks').toggleNav('alinks');
		/**** Toggle navigation and flyouts ENDS ****/
		
		//Espanol Site
				var esl = $('#build_mazda_link').text();
		if(esl == 'Arma tu Mazda'){
			$('.all_vehicles').addClass('es_all_veh');
			$('.es_all_veh').css('margin', '-28px 13px 0 152px');
			$('.mobile_content .module_right').css('height','403px');
		}
		/*var esl = $('#build_mazda_link').text();
		if(esl == 'Arma tu Mazda'){
			var aLink = $('.globalnav_alinks');
			aLink.find('li a').addClass('es_all_veh');
			for(j=1; j<10; j++){
				var vt = $('.vt_link' + j);
				vt.css('padding-left','45px');
			}
			
			for(i=1; i<10; i++){
				var snTop = $('.globalnav_alinks .subautonav_topbg' + i);
				var sn = $('.globalnav_alinks li ul.subautonav' + i);
				snTop.removeClass('snt' + i);
				sn.removeClass('sn' + i);
				snTop.addClass('es_snt' + i);
				sn.addClass('es_sn' + i);	
			}
			$('ul.subautonav2 ul.auto_info li.auto_of ul').addClass('es_2aou');
			$('ul.subautonav2 ul.auto_info li.auto_of .bld_opt div').addClass('es_2bod');
			$('ul.subautonav2 ul.auto_info li.auto_of .spec_opt div').addClass('es_2sod');
			$('ul.subautonav2 ul.auto_info li.auto_of .auto_legal').addClass('es_2al');
			$('ul.subautonav5 ul.auto_info li.auto_of .auto_opt ul').addClass('es_5aou');
			$('ul.subautonav5 ul.auto_info li.auto_of .bld_opt div').addClass('es_5bod');
			$('ul.subautonav5 ul.auto_info li.auto_of .spec_opt div').addClass('es_5sod');
			$('.auto_opt3 div').addClass('es_o3d');
				
			//Shopping Tools title width
			$('subnav_topbg1').addClass('');
			
			//Top nav espanol bg sizing
			var sbg1 = $('.subnav_topbg1');
			var sbg2 = $('.subnav_topbg2');
			var sbg3 = $('.subnav_topbg3');
			var sbg4 = $('.subnav_topbg4');
			var esl = $('#build_mazda_link').text();
			sbg1.css('width','0');
			sbg2.css('width','0');
			sbg3.css('width','0');
			sbg4.css('width','0');
			sbg1.css('width','48px');
			sbg2.css('width','63px');
			sbg3.css('width','72px');
			sbg4.css('width','87px');
			
		}
		*/
		//IE7-8 Flyout bottom BG
		for(i=1; i<10; i++){
			var flyoutUL = $('.subautonav' + i).height();
			if(flyoutUL > 386){
				$('.subautonav' + i + ' .subautonav_btmbg').addClass('subautonav_btmbg2');	
			}else{
				$('.subautonav' + i + ' .subautonav_btmbg').removeClass('subautonav_btmbg2');	
			}
		}	
		
		$('ul.garage_shopDropnav').superfish();


		$('li.auto_explorebtn').hover(function(){
			//animation of blue arrow
			$(this).find('div').stop().animate({marginLeft:"127"},400);
			$(this).find('a').css("textShadow", "0px 0px 7px #0099CC");
		}, function(){
				//animation of blue arrow
				$(this).find('div').stop().animate({marginLeft:"124"},300);
				$(this).find('a').css("textShadow", "none");
		});
		
		$('li.opt div a').hover(function(){
			//animation of blue arrow
			$(this).next().stop().animate({marginLeft: "9"},500);
		}, function(){
				//animation of blue arrow
				$(this).next().stop().animate({marginLeft: "6"},500);
		});
		
		$('div.auto_opt div').hover(function(){
			//animation of blue arrow
			$(this).find('div').stop().animate({marginLeft: "11"},500);
		}, function(){
				//animation of blue arrow
				$(this).find('div').stop().animate({marginLeft: "8"},500);
		});

		//Incentives
		var modelObject2011, modelObject2012, modelName, modelYear, msrp, mpg, seating, incentive, msrpDislaimer, disclaimer, incentivesLink;
		var iDiv = $('div.incentive');
		var iLink = $('');
		
		// Get 2011 data
		$.getJSON(env_var + "vehicleETCRestful.action?year=2011&format=json&Gtj5mo0s=qQwdm500H", function(json){
			modelObject2011=json;
			for(i=0;i<modelObject2011.vehicles.length;i++){
				if(
					modelObject2011.vehicles[i].carline == "RX8" ||
					modelObject2011.vehicles[i].carline == "TRB"
				){
				
					if(modelObject2011.vehicles[i].carline==iDiv.attr('class')){
						mpg=modelObject2011.vehicles[i].mpg.shortDescription;
						seating=modelObject2011.vehicles[i].seatingCapacity.shortDescription;
						incentive=modelObject2011.vehicles[i].incentive.teaser;
						msrpDisclaimer=modelObject2011.vehicles[i].incentive.msrpDisclaimer;
						disclaimer=modelObject2011.vehicles[i].incentive.disclaimer;
					}
					
					$('.' + modelObject2011.vehicles[i].carline + ' div.incentive_teaser').html(modelObject2011.vehicles[i].incentive.teaser);
					$('.' + modelObject2011.vehicles[i].carline + ' div.offer_details_flyout .detailsTxt span').html(modelObject2011.vehicles[i].incentive.disclaimer);
					//Append "Details" and tool tip containers to Incentives
					$('.' + modelObject2011.vehicles[i].carline + ' div.tdw').appendTo('#globalnav ' + '.' + modelObject2011.vehicles[i].carline + ' .incentive_teaser');
					$('.' + modelObject2011.vehicles[i].carline + ' div.vdw').appendTo('.incentivesModule ' + '.' + modelObject2011.vehicles[i].carline + ' .incentive_teaser');
					
					var disclaimer = modelObject2011.vehicles[i].incentive.disclaimer;
	
					if(modelObject2011.vehicles[i].incentive.disclaimer == null || modelObject2011.vehicles[i].incentive.disclaimer == ''){
						$('.' + modelObject2011.vehicles[i].carline + ' div.detail_link_wrapper').css('visibility','hidden');
					}
				}
			}
										  	
		});
		// Get 2012 data
		$.getJSON(env_var + "vehicleETCRestful.action?year=2012&format=json&Gtj5mo0s=qQwdm500H", function(json){
			modelObject2012=json;
			for(i=0;i<modelObject2012.vehicles.length;i++){
				if(modelObject2012.vehicles[i].carline==iDiv.attr('class')){
					mpg=modelObject2012.vehicles[i].mpg.shortDescription;
					seating=modelObject2012.vehicles[i].seatingCapacity.shortDescription;
					incentive=modelObject2012.vehicles[i].incentive.teaser;
					msrpDisclaimer=modelObject2012.vehicles[i].incentive.msrpDisclaimer;
					disclaimer=modelObject2012.vehicles[i].incentive.disclaimer;
				}
				$('.' + modelObject2012.vehicles[i].carline + ' div.incentive_teaser').html(modelObject2012.vehicles[i].incentive.teaser);
				$('.' + modelObject2012.vehicles[i].carline + ' div.offer_details_flyout .detailsTxt span').html(modelObject2012.vehicles[i].incentive.disclaimer);
				//Append "Details" and tool tip containers to Incentives
				$('.' + modelObject2012.vehicles[i].carline + ' div.tdw').appendTo('#globalnav ' + '.' + modelObject2012.vehicles[i].carline + ' .incentive_teaser');
				$('.' + modelObject2012.vehicles[i].carline + ' div.vdw').appendTo('.incentivesModule ' + '.' + modelObject2012.vehicles[i].carline + ' .incentive_teaser');
				
				var disclaimer = modelObject2012.vehicles[i].incentive.disclaimer;
				if(modelObject2012.vehicles[i].incentive.disclaimer == null || modelObject2012.vehicles[i].incentive.disclaimer == ''){
					$('.' + modelObject2012.vehicles[i].carline + ' div.detail_link_wrapper').css('visibility','hidden');
				}
			}							  	
		});
				
		//Tool Tip for "Details" link hover in flyouts
		$('.detailLink').mouseover(function() {
			$(this).parent().siblings('.offer_details_flyout').fadeIn(250);
			$(this).parent().siblings('.offer_details_flyout_long').fadeIn(250);
			$(this).parent().siblings('.offer_details_flyout_long_leftArr').fadeIn(250);
		});
		$('.detailLink').mouseout(function() {
			$(this).parent().siblings('.offer_details_flyout').fadeOut(250);
			$(this).parent().siblings('.offer_details_flyout_long').fadeOut(250);
			$(this).parent().siblings('.offer_details_flyout_long_leftArr').fadeOut(250);
		});


		//omniture for social media links
		$('UL.social_links LI A').click(function() {
			
			var socialName=$(this).attr("class");
		
			// fire the following omniture tags per link
			if($('UL.social_links').parent().hasClass('enterprise_social')){
				s.linkTrackVars="eVar6";
				s.eVar6="Exit to_"+socialName;
				s.tl(this,"e","Exit to_"+socialName+"");
			} else {
				s.linkTrackVars="prop1,prop8,prop9,prop16,eVar6,eVar9,eVar16";
				s.prop1=vehicleCode;
				s.prop9=language;
				s.prop16=vehicleCode;
				s.eVar6="Exit to_"+socialName;
				s.eVar9=language;
				s.eVar16=vehicleCode;
				s.tl(this,"e","Exit to_"+socialName+"");
			}
			s.trackExternalLinks=false;
			void(s_gi(s_account));							
		});
		
		try{
			FB.Event.subscribe('edge.create', function(response) {
			
				// following Omniture tags only fire when Like is clicked.
				// dislikes are not tracked
				if($('UL.social_links').parent().hasClass('enterprise_social')){
					s.linkTrackVars="eVar6";
					s.eVar6="mazda6_enterprise_facebook";
					s.tl(this,"o","mazda6_enterprise_facebook");
				}else{
					s.linkTrackVars="eVar2";
					s.eVar2="facebook_like";
					s.tl(this,"o","topnav_facebook_like");
				}	
				void(s_gi(s_account));
				
				
			});
		}catch(e){}
		
		
		
		
		$('UL LI A.downloadLink').click(function(){
			
			var linkTag=$(this).attr("name");
			var osTag=$(this).attr("rev");
			
			s.linkTrackVars="eVar2";
			s.eVar2=linkTag+"_"+osTag;
			s.tl(this,"e","homepage_hero_"+linkTag+"_"+osTag);
			s.trackExternalLinks=false;
			void(s_gi(s_account));
		});
			
		//Omniture for Global nav links
		var topnavLink = $('.topnav_link');
		var topnavTitle = '';
		topnavLink.hover(
			function(){
				topnavTitle = $(this).attr("title");
				$(this).attr('title','');
				$(this).click(function(){
					var subnavLinkName=$(this).attr("id");
					var siteSection=topnavTitle;
					// fire the following omniture tags per link
					s.linkTrackVars="prop1,prop8,prop9,prop16,eVar2,eVar9,eVar16";
					s.prop1=vehicleCode;
					s.prop8=siteSection;
					s.prop9=language;
					s.prop16=vehicleCode;
					s.eVar2="topnav_"+siteSection+"_"+subnavLinkName;
					s.eVar9=language;
					s.eVar16=vehicleCode;
					s.tl(this,"o","topnav_"+siteSection+"_"+subnavLinkName+".");		
					void(s_gi(s_account));			
				});
			},
			function(){
				$(this).attr('title',topnavTitle);		
			}
		);
		
		
		$('.vehicle_title').hover(
			function(){
				$(this).click(function(){
					var model=$(this).attr("title");
					// fire the following omniture tags per link
					//s.linkTrackVars="prop1,prop9,prop16,eVar2,eVar9,eVar16";
					s.linkTrackVars="eVar2";
					//s.prop1=vehicleCode;
					//s.prop9=language;
					//s.prop16=vehicleCode;
					s.eVar2="topnav_"+model;
					//s.eVar9=language;
					//s.eVar16=vehicleCode;
					s.tl(this,"o","topnav_"+model);		
					void(s_gi(s_account));			
				});
			}
		);
		
		
			
		var flyoutLink = $('.flyout_link');
		var flyoutTitle = '';
		flyoutLink.hover(
			function(){
				flyoutTitle = $(this).attr("title");
				$(this).attr('title','');
				$(this).click(function(){
					var shoppingTool=$(this).attr("id");
					var model=flyoutTitle;
					// fire the following omniture tags per link
					s.linkTrackVars="prop1,prop9,prop16,eVar2,eVar9,eVar16";
					s.prop1=vehicleCode;
					s.prop9=language;
					s.prop16=vehicleCode;
					s.eVar2="vehicle flyout_"+model+"_"+shoppingTool;
					s.eVar9=language;
					s.eVar16=vehicleCode;
					s.tl(this,"o","vehicle flyout_"+model+"_"+shoppingTool+".");		
					void(s_gi(s_account));			
				});
			},
			function(){
				$(this).attr('title',flyoutTitle);		
			}
		);

		$('#globalnav .all_vehicles').click(function(){
			s.linkTrackVars="prop9,eVar2,eVar9";
			s.prop9=language;
			s.eVar2="topnav_all_vehicles";
			s.eVar9=language;
			s.tl(this,"o","topnav_all_vehicles");		
			void(s_gi(s_account));			
		});
		
		var exploreLink = $('.auto_explorebtn A');
		var exploreTitle = '';
		exploreLink.hover(
			function(){
				exploreTitle = $(this).attr("title");
				$(this).attr('title','');
				$(this).click(function(){
					var model=exploreTitle;
					// fire the following omniture tags per link
					s.linkTrackVars="prop1,prop9,prop16,eVar2,eVar9,eVar16";
					s.prop1=vehicleCode;
					s.prop9=language;
					s.prop16=vehicleCode;
					s.eVar2="vehicle flyout_"+model+"_explore_now";
					s.eVar9=language;
					s.eVar16=vehicleCode;
					s.tl(this,"o","vehicle flyout_"+model+"_explore_now");		
					void(s_gi(s_account));			
				});
			},
			function(){
				$(this).attr('title',exploreTitle);		
			}
		);
		
	}
}

Musa.Home = {
	initialize : function(){
		//Home page "Explore Now" button
		$('.showcase a').hover(function() {
			$(this).parents('div.showcaseSlide')
			.find('div.exploreBtn a').css('textShadow', '0 0 7px #09c')
			.parent().find('div').stop().animate({paddingLeft : '3'}, 400);	
		}, function() {
			$(this).parents('div.showcaseSlide')
			.find('div.exploreBtn a').css('textShadow', 'none')
			.parent().find('div').stop().animate({paddingLeft : '0'}, 300);
		});
		// $('div.exploreBtn').hover(function(){
		// 	//animation of blue arrow
		// 	$(this).find('div').stop().animate({paddingLeft: "3"},400);
		// 	$(this).find('a').css("textShadow", "0px 0px 7px #0099CC");
		// }, function(){
		// 		//animation of blue arrow
		// 		$(this).find('div').stop().animate({paddingLeft: "0"},300);
		// 		$(this).find('a').css("textShadow", "none");
		// });
		
		//Hover animation for social media icons
		Musa.Common.toggleIcons('#home_showcase ul.social_links li a');
		
	}
}

/**
 *Initialize all functionality on pageload. 
 */
$(function(){
	Musa.Common.initialize();
	Musa.Globalnav.initialize();
	Musa.Home.initialize();
});




//google plus omniture callback
function plusone_vote() {   
	if($('UL.social_links').parent().hasClass('enterprise_social')){
		s.linkTrackVars="eVar6";
		s.eVar6="mazda6_enterprise_google_plus1";
		s.tl(this,"o","mazda6_enterprise_google_plus1");
	} else {
		s.linkTrackVars="eVar2";
		s.eVar2="google_plus";
		s.tl(this,"o","topnav_google_plus");
	}
	void(s_gi(s_account));
};

/* Global Javascript Functions */
/* Nav Menu Hover */
var registeredImages = new Array();
var imgOffDelay = new Array();
var killFlicker='';
var lastDropOn='';

function imgReg(imgName,imgSrc) {
	registeredImages[imgName] = new Array( new Image(), new Image());
	registeredImages[imgName][0].src = imgSrc;
	registeredImages[imgName][1].src = imgSrc.replace("_off.","_on.");
}

function imgOn(imgName,selectCheck) {
	window.clearTimeout(imgOffDelay[imgName]);
	window.clearTimeout(killFlicker);
	window.clearTimeout(imgOffDelay["movietag"]);
	document.images[imgName].src = registeredImages[imgName][1].src;
	
	
	/* display globalnav dropdowns on IE */
	if(navigator.appVersion.indexOf("MSIE") >= 0
		&& document.getElementById(imgName+"_div")) {
		
		if(lastDropOn!=imgName && lastDropOn!='') hideDrop(lastDropOn);
		document.getElementById(imgName+"_div").style.visibility = "visible";
		document.getElementById(imgName+"_div").style.clear = "left";
	}
	/* IE7 subnav position hack (next two if statements) */
	if (navigator.appVersion.indexOf("MSIE")>=  0 && navigator.appVersion.indexOf("7.0")>= 0) {
		document.getElementById("globalnav_vehicles_div").style.position = "fixed";
		document.getElementById("globalnav_vehicles_div").style.top = "50px";
	/* FleetWeb menu is shorter and doesn't need this part of the hack*/
	if (window.location.href.indexOf('/FleetWeb/') == -1){
		document.getElementById("globalnav_vehicles_div").style.left = "232px";
	}
	}
	if (navigator.appVersion.indexOf("MSIE")>=  0 && navigator.appVersion.indexOf("7.0")>= 0) {
		// Check that div exists on Fleet
		if (document.getElementById("globalnav_shopping_tools_div")) {
			document.getElementById("globalnav_shopping_tools_div").style.position = "fixed";
			document.getElementById("globalnav_shopping_tools_div").style.top = "50px";
			document.getElementById("globalnav_shopping_tools_div").style.left = "304px";			
		}
		if (document.getElementById("globalnav_inside_mazda_div")) {
			document.getElementById("globalnav_inside_mazda_div").style.position = "fixed";
			document.getElementById("globalnav_inside_mazda_div").style.top = "50px";
			document.getElementById("globalnav_inside_mazda_div").style.left = "620px";			
		}
	}
	/* hide select boxes on IE 
	if(navigator.appVersion.indexOf("MSIE") >= 0 && document.getElementsByTagName("SELECT").length > 0 && selectCheck == true)
		for (var i=0; i<document.getElementsByTagName("SELECT").length; i++)
			document.getElementsByTagName("SELECT")[i].style.visibility = "hidden";
	 hide iframes on IE 
	if(navigator.appVersion.indexOf("MSIE") >= 0 && navigator.appVersion.indexOf("7.0") <= 0 && document.getElementsByTagName("IFRAME").length > 0 && selectCheck == true)
		for (var i=0; i<document.getElementsByTagName("IFRAME").length; i++)
			document.getElementsByTagName("IFRAME")[i].style.visibility = "hidden";
	*/
	var galObj = document.getElementById("movietag");
	if (galObj) galObj.style.visibility = "hidden";
	lastDropOn=imgName;
}

function hideDrop(imgName) {
	document.getElementById(imgName +  "_div").style.visibility = "hidden";
}

function imgOff(imgName,selectCheck) {
	 imgOffDelay[imgName] = window.setTimeout("document.images['"+imgName+"'].src = registeredImages['"+imgName+"'][0].src",50);
	/* display globalnav dropdowns on IE */
	if(navigator.appVersion.indexOf("MSIE") >= 0 && document.getElementById(imgName+"_div"))
		killFlicker=setTimeout((function(){hideDrop(imgName);}), 50);
	/* show select boxes on IE */
	if(navigator.appVersion.indexOf("MSIE") >= 0
		&& document.getElementsByTagName("SELECT").length > 0
		&& selectCheck == true)
		for (var i=0; i<document.getElementsByTagName("SELECT").length; i++)
			document.getElementsByTagName("SELECT")[i].style.visibility = "visible";
	/* show iframes on IE 
	if(navigator.appVersion.indexOf("MSIE") >= 0
		&& document.getElementsByTagName("IFRAME").length > 0
		&& selectCheck == true)
		for (var i=0; i<document.getElementsByTagName("IFRAME").length; i++)
			document.getElementsByTagName("IFRAME")[i].style.visibility = "visible";
	*/
	var galObj = document.getElementById("movietag");
	if (galObj) imgOffDelay["movietag"] = setTimeout('document.getElementById("movietag").style.visibility = "visible";',10);
}


//open window

function popup(url,winName,w,h) {
	newWin = window.open(url,winName,"width=" + w + ",height=" + h + ",menubar=no,scrollbars=yes,resizable=yes,toolbar=no")
}
function popup2(url,winName,w,h) {
	newWin = window.open(url,winName,"width=" + w + ",height=" + h + ",menubar=no,scrollbars=no,resizable=no,toolbar=no")
}
// w=width, h=height, m=menubar, s=scrollable, r=resizeable, t=toolbar
function popup3(url,winName,w,h,m,s,r,t) {
	newWin = window.open(url,winName,"width=" + w + ",height=" + h + ",menubar=" + m + ",scrollbars=" + s + ",resizable=" + r + ",toolbar=" + t + "")
}



/* submit button through link */
function formSubmit(thisForm,name,value) {
	if (name && value) {
		var hiddenField = document.createElement("input");
		hiddenField.setAttribute("type","hidden");
		hiddenField.setAttribute("name",name);
		hiddenField.setAttribute("value",value);
		thisForm.appendChild(hiddenField);
	}
	thisForm.submit();
}

/* formats a number with appropriate commas */
function commaNum(num) {
	var formattedNum = "";
	var stringNum = "" + num;
	var numPart = 0;
	var separator = "";
	for (var i = stringNum.length; i > 0; i=i-3) {
		numPart = ((i-3) < 0) ? 0 : (i-3);
		formattedNum = "" + stringNum.substring(numPart,i) + separator + formattedNum;
		separator = ",";
	}
	return formattedNum;
}

//pop up that takes different parameters
// this will center the window within the browser and bring the window to focus
var legendWin;
function createWin(url,width,height) {

	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2;
	if(legendWin == null || legendWin.closed) {
		var props = "resizable,scrollbars=no,left=" + left + ",top=" + top + ",width=" + width + ",height=" + height;
		legendWin = window.open(url, "legend", props);
		legendWin.focus();
	} else {
		legendWin.close();
		var props = "resizable,scrollbars=no,left=" + left + ",top=" + top + ",width=" + width + ",height=" + height;
		legendWin = window.open(url, "legend", props);
		legendWin.focus();
	}
}


/* incentives popup */
function winincentivesopen() {
	var w = 580, h = 600;

	if (document.all || document.layers) {
	w = screen.availWidth;
	h = screen.availHeight;
	}

	var popW = 580, popH = 600;
	var leftPos = (w-popW)/2, topPos = (h-popH)/2;

	var myWindow;
	myWindow = window.open("http://www.mazdaespanol.com/mazdausa/enes/24/_images_mazdausa_com/MusaWeb/musa2/js/displayRegionalIncentivesPopup.action", "regionalIncentives", "width=" + popW + ",height=" + popH + ",top=" + topPos + ",left=" + leftPos + ",resizable=no,status=no,scrollbars=yes");
	myWindow.focus();
}

function winincentivesopenCX7() {
	var w = 540, h = 500;

	if (document.all || document.layers) {
	w = screen.availWidth;
	h = screen.availHeight;
	}

	var popW = 540, popH = 500;
	var leftPos = (w-popW)/2, topPos = (h-popH)/2;

	var myWindow;
	myWindow = window.open("http://www.mazdaespanol.com/mazdausa/enes/24/_images_mazdausa_com/MusaWeb/musa2/js/displayRegionalIncentivesCX7Popup.action", "regionalIncentives", "width=" + popW + ",height=" + popH + ",top=" + topPos + ",left=" + leftPos + ",resizable=no,status=no,scrollbars=yes");
	myWindow.focus();
}

function cleanWin(url,width,height) {
	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2;
	newWin = window.open(url,"popup","left=" + left + ",top=" + top + ",width=" + width + ",height=" + height + ",menubar=no,scrollbars=no,resizable=no,toolbar=no")
}

function safariSniff() {
	var appVer = navigator.appVersion;
	var safariVer = -1;
	if (appVer.indexOf("Safari")>0)
		safariVer = appVer.substr(appVer.indexOf("Safari")+7);
	if (safariVer > 0 && safariVer < 200)
		document.getElementById("globalnav_box").style.width = "523px";
}

function staticRedirect() {
	alert('Maintenance on MazdaUSA.com is complete.  You are being redirected to the MazdaUSA.com home page where all features are accessible.');
	if(window.location.href.indexOf("forward=false") < 0) window.location.href='http://www.mazdaespanol.com/mazdausa/enes/24/_images_mazdausa_com/MusaWeb/displayHomepage.action';
}

function staticRedirectMexico() {
	alert('El mantenimiento en Mazda Mexico está completo. Le están volviendo a dirigir a la página principal de Mazda Mexico donde están accesibles todas las características del sitio.');
	if(window.location.href.indexOf("forward=false") < 0) window.location.href='http://www.mazdaespanol.com/mazdausa/enes/24/_images_mazdausa_com/MazdaMexico/displayMxPage.action?pageParameter=mazdaMexico';
}

/* IE7 ActiveX Workaround */
function drawEmbed(embedType,embed,returnText) {
/* Usage:
var flash = new Array();
flash["src"] = "flash/home/p_home_base.swf";
flash["base"] = "flash/home/"
flash["FlashVars"] = "altContentURL=/MusaWeb/displayPage.action?pageParameter=blah";
flash["quality"] = "high";
flash["bgcolor"] = "#ffffff";
flash["width"] = "750";
flash["height"] = "417";
flash["name"] = "bod";
flash["align"] = "";
flash["scale"] = "noscale";
flash["menu"] = "0";
flash["wmode"] = "transparent";

drawEmbed("flash",homePageFlash);

*/
	var embedObj = new Array();
	embedObj["flash"] = new Array();
	embedObj["flash"]["type"] = "application/x-shockwave-flash";
	embedObj["flash"]["pluginspage"] = "http://www.macromedia.com/go/getflashplayer";

	embedObj["qt"] = new Array();
	embedObj["qt"]["type"] = "video/quicktime";
	embedObj["qt"]["pluginspage"] = "http://www.apple.com/quicktime/download/";

	var embedArray = embed;
	if (embedType.constructor == Array) embedArray.concat(embedType);
	else embedArray.concat(embedObj[embedType]);

	var embedHtml = "<embed ";
	for (var i in embedArray)
		embedHtml += " "+i+"=\""+embedArray[i]+"\"";
	embedHtml += "></embed>";

	if (!returnText) document.write(embedHtml);
	else return embedHtml;
}
/*
function drawObject(objType,obj,params,embed) {
	var obj = new Array();
	obj["flash"] = new Array();
	obj["flash"]["codebase"] = "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,65,0";
	obj["flash"]["classid"] = "D27CDB6E-AE6D-11cf-96B8-444553540000";

	obj["qt"] = new Array();
	obj["qt"]["codebase"] = "http://www.apple.com/qtactivex/qtplugin.cab";
	obj["qt"]["classid"] = "02BF25D5-8C17-4B23-BC80-D3488ABDDC6B";

}
*/

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

//Footer Links Hover Animation
function footerLinkHover(){

		$("ul.footer_links li a").hover(
			function() {
				$(this).stop().animate({
					color:"#0099CC"
				},300);
		},
			function() {
				$(this).stop().animate({ 
					color:"#666666"
				}, 300);
		});
		
	$(".mazda_footerLogo a").hover(
		function(){
			$(this).stop().fadeTo("slow", 1.0);
		},
		function(){
			$(this).stop().fadeTo("slow", 0.6);
	});
}
		
/* SCR05240 - LIVE CHAT for flash garages */
function mazdaChat(s_linkName){
	s_linkTrackVars='eVar2';
	s_linkTrackEvents='None';
	s_linkType='o';
	s_linkName='Haz clic en el bot\363n de chat en vivo - ' + s_linkName;
	s_eVar2='Haz clic en el bot\363n de chat en vivo - ' + s_linkName;
	s_lnk=s_co(this);s_gs('mazdausacom');
	s_objectID='Bot\363n de chat en vivo'; 
	createCookie('liveChatUser','liveChatUser',0.4);
	window.open('http://www.mazdaespanol.com/mazdausa/enes/24/_images_mazdausa_com/MusaWeb/displayPage.action?pageParameter=chatUnavailable','_blank','resizable=yes,width=590,height=590');
}

// SCR06713: Add promo banner for loyalty offer - Overlays
function openOverlay(id) {
	var IEoffset = 0;

	if(navigator.appVersion.indexOf("MSIE") >= 0)
		IEoffset = 70;

	var defaultLength = 262;
	var defaultMargin = -105;
	var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
	var objPosY = document.getElementById('overlayPosition').offsetTop;
	var offsetY = objPosY - scrollY + IEoffset;

	if (offsetY < defaultLength)
		document.getElementById('overlay').style.marginTop = defaultMargin + (defaultLength-offsetY) + "px";
	else
		document.getElementById('overlay').style.marginTop = defaultMargin + "px";

	if (id == null) id = "overlay";
	document.getElementById('overlay').style.display = "block";
}

function closeOverlay(id) {
	if (id == null) id = "overlay";
	document.getElementById(id).style.display = "none";
}

function disclaimerPop(url) {
	var winFeatures = 'width=560,height=300,scrollbars=0';
	open(url,'disclaimer',winFeatures);
}

function openNewWindow(url, windowName) {
	window.open(url, 'name', 'resizable=1',false);
}
