var firebug = 0; // 0 for normal, 1 for debug

var ie7 = 0; // declaration
var lastTab = 0;
function getText()
{
    var txt1 = $('#mainColumn #pageDetails, .tab_content1, .tab_content1 p, #pageDescription, .product_text, .product_detail_content p, .product_detail_content ul');
    var txt2 = $('.prod2ArticleDesc, .prod2ArticleLink, .product_detail_content ol, .product_detail_content h2, .product_detail_content h4, .msArticleHolder, .mslArticleHolder, .msArticleDetails, .msArticleLink');
    var txt3 = $('#PageContent, .contentPhotoCaption p, ent.msltab_container, .pagination, .pagination#pagFirst, .formA ul li label, .formA ul li h3, .formA ul li textarea');
	var txt4 = $('.formA ul li select, #theseErrors, p.formOptions a, .eventHolder, #pageSubTitle h2, .eventOverviewTitle, .eventOverview');
	var txt5 = $('.dailyHighlights, #eventPageDescription, .EventInfo, .eventMainPhotoHolder, .dailyHighlightsTitle, .articleOverview, #inlineTable, .item-meta, .paginationPage h3, .paginationPage p, .paginationPage a');
	var txt6 = $('#compare-specs-content, #compDisclaimer, .parentTitle, .dealerDescription, .dealerInfo h2, .image_gallery_tab_container');
	var txt7 = $('#yearTarget, .imgItem a, .listtree li, .resultsInfo, #support-no-results h2, .nraDetailsTitle, .nraDetailsUpdated, .nraDetailsText, .nraArticleLink, .nraSideBarLinks, .holder');
	var txt8 = $('.holder h4, .holder .cta, .prod2ArticleTitle, .productName a, .tab_container1 ul, .searchResultTitle, ,.smcolumn1, .smcolumn2'); // regulsr copy
	var txt = $.merge($.merge($.merge($.merge($.merge($.merge($.merge(txt1, txt2), txt3), txt4), txt5), txt6), txt7), txt8);
	return txt;
}


//Functions to call when the site loads
$(document).ready(function() {
    
	// check for font size cookie on load
	var textCookie = get_cookie('text');
			
	if (textCookie) {
		switch (textCookie) {
			case 'big':
				bigText();
				break;
			case 'medium':
				mediumText();
				break;
			default:
				// nothing
		}
	}

	// Firebug Lite
	if (firebug) $('body').append('<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js"></script>');

	// check for < ie8
	if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
		ie7 = 1;
	}

	$(document).pngFix();
	
	// adjust widths if necessary
	checkPageSize(); // on page load
	$(window).resize(function() { // on browser resize
		checkPageSize();
	});	

	//update canonical link for SEO
	$('link[rel=canonical]').attr("href", window.location.protocol + '//' + window.location.host + window.location.pathname);

	
    // ** BEGIN Global header/footer ** //
	// prepare DOM for playing with JS if we got this far
	$('.tabcontent').hide();
	
	//pull footer arrow back to left
	$('#bottomArrow').css('padding-left',2);
	
	// open and close header menu
	$('#mainnav li a.hoverTab').hover(function() {
		$(this).parent().parent().addClass('hovered'); // keeps submenu open when hovering off
		var px = ($(this).hasClass('menuProducts')) ? [132,-37] : [64,-105]; // set px dimensions for big or little menu; products is only big one
		openTopMenu(px);
	}, function() {
		$(this).parent().parent().removeClass('hovered');
	});
	
	// if mouse hover on non tabbing top menu items, close open tabs
	$('#mainnav li a').hover(function() {
		if (!$(this).hasClass('hoverTab')) closeTopMenu();
	}, function() {
		// do nothing!
	});
	
	// open and close footerMenus
	$('#bottomMenuMainLinks a').click(function() {
		var clicked = $(this).attr('id');
		bottomMenu(clicked);
		return false;
	});
	
	
	// trigger close on 'x' click
	$('#closeBottomMenu').click(function() {
		toggleFlashRotation("theFlash");//continue flash rotation when user deactivated bottom menu
		closeBottomMenu();
	});
	
	// change tabs
	$('a.hoverTab').hover(function() {
		// return false if link is in #bottomMenuMainLinks AND bottom menus is closed
		if ($(this).parent().attr('id') == 'bottomMenuMainLinks' && !$('#bottomMenus').hasClass('open')) return false;
		// ignore if hovered tab is already active
		if ($(this).hasClass('active')) return false;
		// switch to hovered tab
		switchTabs(this);
	}, function() {
		// do something, or even nothing!
	});
	
	// clear search field upon click
	$('#mainSearchField.unchanged').focus(function() {
		if ($(this).hasClass('unchanged')) $(this).val('').removeClass('unchanged');
	});
	
	// close main nav submenus on hover-off
	$('#mainNavBg').hover(function() {
		// do nothing!
	}, function() {
		var t = setTimeout("closeTopMenu()", 100);
	});
	
	// also close if they're open and we hover headernav (b/c they won't close when you hoveroff onto mainnav
	$('#headernav').hover(function() {
		closeTopMenu();
	}, function() {
		// do nothing!
	});
	
	// show admin toolbar when present
	var spToolbarHeight = $('#sp_admintoolbar div').height();
	$('#sp_admintoolbar div').css('top',6 - spToolbarHeight); // pull almost off page onload
	$('#sp_admintoolbar div').hover(function() {
		$(this).animate({'top': 0},1000);
	}, function() {
		// do nothing
	});
	
	// dealer locater
	
	$('#dltabLink').click(function() {
		if ($(this).hasClass('open')) { // locater is open; close it now.
			$(this).removeClass('open').parent().parent().parent().stop().animate({bottom: -257},1000,'easeOutQuint');
		} else { // locater is closed; open it now.
			$(this).addClass('open').parent().parent().parent().stop().animate({bottom: -60},1000,'easeOutQuint');
		}
		return false;
	});
	
    // ** END global header/footer ** //
	
    // ** BEGIN accordion functionality ** //
		
	//right column accordion expand and collapse
	//drawer 1 is open by default
	if ($('div.rightAccordion h3.accordion').length > 0) {
	    // add arrow
	    $('div.rightAccordion h3.accordion').append('<span></span>');
		// open first accordion
		$('div.rightAccordion h3.accordion:first').addClass('accordionOpen');
		// close all other accordion
		$('div.rightAccordion:not(.stop) div.holder:gt(0)').hide();
		
		$('div.rightAccordion h3.accordion').click(function() {
		    if($(this).hasClass('accordionOpen'))
		        return false;
		    var opened = $('div.rightAccordion h3.accordionOpen');		
			$('div.rightAccordion h3.accordion').removeClass('accordionOpen');
			// $(this).siblings('h3.accordionOpen').removeClass('accordionOpen');
			opened.siblings('div.holder').slideUp('slow');
			$(this).addClass('accordionOpen').next('div:hidden').slideDown('slow');
			//.siblings('div:visible').slideUp('slow');
		});
	}
    // ** END accordion functionality ** //

    // Text sizer

	$('#textBig, #textMedium, #textSmall').click(function() {
		var theID = $(this).attr('id');
		switch (theID) {
			case 'textBig':
				//google analytic tagging for the font sizer
				bigText();
				if(_gaq)
				    _gaq.push(['_trackEvent', 'VariableFontSize', 'LargeFont_Click', window.location.href.substring(window.location.href.indexOf('//')+2)]);				
				break;
			case 'textMedium':
			    mediumText();
			    if(_gaq)
				    _gaq.push(['_trackEvent', 'VariableFontSize', 'MediumFont_Click', window.location.href.substring(window.location.href.indexOf('//')+2)]);				
				break;
			case 'textSmall':
			    smallText();
			    if(_gaq)
				    _gaq.push(['_trackEvent', 'VariableFontSize', 'SmallFont_Click', window.location.href.substring(window.location.href.indexOf('//')+2)]);				
				break;
			default:
				return false;
		}
		return false;
	});
	
	// Products page stuff
	// When page loads
	
	var greatestHeight = 0;
    $('ul.tabs1').each(function() {
           $(this).children('li').each(function() {
                   if ($(this).height() > greatestHeight) greatestHeight = $(this).height();
           });
           $(this).children('li').height(greatestHeight);
           greatestHeight = 0;
    }); 
	
	$(".tab_content").hide(); //Hide all content
	$("ul.tabs li:first").addClass("active").show(); //Activate first tab
	$(".tab_content:first").show(); //Show first tab content
	// Check the height of the product tab li a's and drop the padding if too big
	$('ul.tabs li a').each(function(i) {
		var theHeight = $(this).height();
		if (theHeight > 14) $(this).css('padding-top','4px');
	});

	// Click series headings and change products below
	$("ul.tabs li").click(function() {
		var bigSmall = ''; // see .hover function below for explanation

		$('.tab_container1').hide(); // hide content container; remember to show again on hover
		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content

		var activeTab = '#' + $(this).find("a").attr("name"); //Find the name attribute value to identify the active tab + content
		window.location.hash = $(this).find("a").attr("href"); // update URL hash
		$('ul.tabs1').removeClass().addClass('tabs1 clearConnector'); // reset connector		
		$(activeTab).children('div.tab_container1').children('div').hide(); // clear all open details so we don't stack them
		$(activeTab).fadeIn().children('div.tab_container1').children('div:first-child').show(); //Fade in the active ID content and proper details
		
		// switch gray bg's in li a's
		$('ul.tabs1 li a').removeClass('backPos00');
		return false;
	});
	
	//When page loads...
	$(".tab_content1").hide(); //Hide all content
	$("ul.tabs1 li:first").addClass("active").show(); //Activate first tab
	$(".tab_content1:first").show(); //Show first tab content
		
    // ** BEGIN products connectors and detail box ** //
	
	// add class productx to each li in ul.tabs1 -- e.g. product1 to first iteration, product6 to sixth
	$('ul.tabs1').each(function() {
		var count = 1;
		$(this).children('li').each(function() {
			$(this).children('a').attr('rel','product' + count);
			count++;
		});
	});

    var theProduct = 0; // this needs to be global
	
	$('ul.tabs1 li a').hover(function() {
		//bigSmall will be appended to the addClass call; if list > 6, it remains empty; if list <= 6, it adds a suffix to 'theProduct+x' and to the class 'small'
		var bigSmall = ''; // declare for later -- do not delete!
		$(this).parent().each(function() {
			$(this).siblings('li').andSelf().children('a').removeClass('backPos00');
		});
		$(this).addClass('backPos00');
		$('ul.tabs1:visible').removeClass().addClass('tabs1');
		theProduct = $(this).attr('rel');
		var theID = $(this).attr('id');
		theID = theID.replace('get_','');
		var numLIs = $('ul.tabs1:visible li').length; // how many li's (models) in this ul (series)
		if (numLIs < 7) bigSmall = 'Small small'; // 6 or less so we need to alter the ul classes for short connecters
		$('ul.tabs1:visible').addClass(theProduct + 'connector' + bigSmall);
		$(this).parent().parent().parent().children('div.tab_container1').children('div').hide();
		$('.tab_container1').show();
		$('#' + theID).show();
	}, function() {
		// hide it all again
		$('ul.tabs1 li a').removeClass('backPos00');
		$('ul.tabs1').removeClass().addClass('tabs1 clearConnector');
		$('.tab_container1').hide();
	});

    // ** END products connectors and detail box ** //
	
	// squash IE dl bug
	//$('#dltabLink').css('bottom','-257px');
	$('#dltabLink').trigger('click');
	$('#dltabLink').trigger('click');
	
	// add pixel to maintenance tabs
	$('.msltabs li:last').width(164);
	
	
	
});

// ** BEGIN global header/footer functions ** //

function checkPageSize() {
	// loosen page content background if browser width is greater than 1071px, adjust #productNav
	var bWidth = $(window).width();	
	if (bWidth > 1071) {
		$('#pageContentBg').width(1038);
		$('#productNav').css({left:'-39px',width:'706px'}).children('ul.tabs').css('width','625px');
		$('.tabs').addClass('wide');
		$('#subnavigation').addClass('wide');
		$('.tabs1').css('margin-left','0');
		$('.tab_container1').css('margin-left','0');
	} else {
		$('#pageContentBg').width(970);
		$('#productNav').css({left:'-5px',width:'672px'}).children('ul.tabs').css('width','591px');
		$('.tabs').removeClass('wide');
		$('#subnavigation').removeClass('wide');
		$('.tabs1').css('margin-left','-20px');
		$('.tab_container1').css('margin-left','-20px');
	}
}

function openTopMenu(px) {
	// open top menu and correct tab content
	// node is hovered anchor
	// px is an array of dimensions for height and background-position
	var time = 0;
	if ($('#mainNavBg').hasClass('open')) {
		time = 500;
	} else {
		$('#mainNavBg').addClass('open');
		time = 850;
	}
	if (ie7) {
		$('#productsMenu').fadeIn(800);
		$('#mainNavBg').show().stop().css({display: 'block', height: px[0]});
	} else {
		$('#productsMenu').show();
		$('#mainNavBg').show().stop().animate({height: px[0]},time,'easeOutQuint');
	}
}

function closeTopMenu() {
	if ($('#mainnav').hasClass('hovered')) return false;
	if ($('#mainNavBg').hasClass('open')) {
		time = 500;
	} else {
		$('#mainNavBg').addClass('open');
		time = 850;
	}
	$('#mainnav .hoverTab').removeClass('active');
	if (ie7) {
		$('#productsMenu').hide();
		$('#mainNavBg').stop().css({display: 'none'});
	} else {
		$('#productsMenu').fadeOut(200);
		$('#mainNavBg').stop().animate({height: 0},time,'easeOutQuint');
	}
}

function bottomMenu(clicked) {
	// triggers bottom menu popup and shows clicked content
	var active = (clicked == 'bottomArrow') ? 'bottom1' : clicked;
	if ($('#bottomMenus').hasClass('open')) { // if bottom menu is open
		if (clicked == 'bottomArrow') { // if arrow is clicked or current active tab is clicked
			closeBottomMenu();
			toggleFlashRotation("theFlash");//pause flash rotation when user interacts with bottom menu
		} else { // inactive tab was clicked; switch to new tab // redundant with switchTabs but keep for iphone maybe?
			$('#bottomMenuMainLinks .active').removeClass('active'); // strip 'active' class from links
			$('#' + active).addClass('active'); // add 'active' class to clicked and switch to clicked tab
		}
	} else { // bottom menu is closed; open and check which tab to activate
		openBottomMenu(active);
		toggleFlashRotation("theFlash");//pause flash rotation when user interacts with bottom menu
	}
}

function closeBottomMenu() {
	if (!$('#bottomMenus').hasClass('open')) return false;
	var heightOffset = 0; // IE6 didn't quite line up
	$('#bottomArrow').removeClass('on');
	if($.browser.msie && $.browser.version < 7){ heightOffset = 5; }
	$('#bottomMenus').animate({height: 31, top: 0 + heightOffset},750,'easeOutCubic').removeClass('open'); // close it
	$('#bottomMenuMainLinks .active').removeClass('active'); // strip 'active' class from links
	$('#bottomMenus .menuContent > div').hide(); // hide menu content to reset for later
	$('#closeBottomMenu').hide(); // kill the close button
}

var holdBottom = 0; // must be global
function openBottomMenu(active) {
	// active = id of clicked 'a' element; opens with correct tab visible
	var heightOffset = 0; // IE6 didn't quite line up
	if($.browser.msie && $.browser.version < 7){ heightOffset = 5; }
	$('#bottomArrow').addClass('on');
	$('#' + active).addClass('active'); // add 'active' class to clicked and switch to clicked tab
	holdBottom = 1; // tab switcher will reference this.  1 indicates busy/no switching
	$('#bottomMenus').animate({height: 134 + heightOffset, top: -103 + heightOffset},1000,'easeOutCubic',function() {
		holdBottom = 0; //switching is okay now
		$('#' + active + 'Content').fadeIn(300, function() {
			if (lastTab) {
				switchTabs(lastTab);
				lastTab = 0;
			} 
		}); // show clicked tab
	}).addClass('open');
	$('#closeBottomMenu').show(); // show 'x' so we know how to close this thing
}

function switchTabs(node) {
	// switch menu tabs on hover; must follow hierarchy
	// a#someId controls div#someIdContent
	// parent div of a#someId must have sibling div.menuContent with child div#someIdContent
	if (holdBottom) { // no switching if bottom menu is moving
		lastTab = node;
		return false;
	}
	var tabName = $(node).attr('id') + 'Content';
	$(node).siblings('.active').removeClass('active'); // footer only
	$(node).parent().siblings('.menuContent').children().hide(); // footer only
	if ($(node).parent().parent().attr('id') == 'mainnav') {
		$(node).parent().siblings().children('.active').removeClass('active'); // header; node structure was different
		$('#mainNavContent .tabcontent').hide(); // header
	}
	$(node).addClass('active');
	$('#' + tabName).show();
}
// *** END global header/footer functions ** //

function clearInput(node,defaultText) {
	if (node.tagName.toLowerCase() == 'textarea') {
		if ($(node).html() == defaultText) $(node).html('');
	} else if (node.tagName.toLowerCase() == 'input') {
		if ($(node).val() == defaultText) $(node).val('');
	} else {
		return false;
	}
}

//js function to pause and start banner rotation in homepage
function toggleFlashRotation(flashid){
    getFlashMovie(flashid).togglePauseBackground();
}
function getFlashMovie(movieName) {
	return document.getElementById(movieName);
//  var isIE = navigator.appName.indexOf("Microsoft") != -1;
//  return (isIE) ? window[movieName] : document[movieName];
}

// font sizing
function bigText() {
    var text = getText();
    text.css({ 'font-size': '20px', 'line-height': '1.1' });
	set_cookie('text','big',24);
}

function mediumText() {
    var text = getText();
    text.css({ 'font-size': '14px', 'line-height': '1.1' });
	set_cookie('text','medium',24);
}

function smallText() {
    var text = getText();
    text.css({ 'font-size': '11px', 'line-height': '1.1' });
	set_cookie('text','small',24);
}


// cookie functions found at http://techpatterns.com/downloads/javascript_cookies.php
function set_cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

if ( expires )
{
expires = expires * 1000 * 60 * 60; // in hours
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


function get_cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function getCookie (name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg){
		    return getCookieVal (j);
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return null;
}

function setCookie (name, value) {
    var argv = setCookie.arguments;
	var argc = setCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) +
	((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
	((path == null) ? "" : ("; path=" + path)) +
	((domain == null) ? "" : ("; domain=" + domain)) +
	((secure == true) ? "; secure" : "");
}

function deleteCookie (name) {
	var exp = new Date();
	exp.setTime (exp.getTime() - 1);
	var cval = getCookie (name);
	//document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
	document.cookie = name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT" + ";path=/";
}
