// JavaScript Document

$('html').addClass('js');

$(document).ready(function(){

var $topMenu = $('#menu ul li');
var $subMenu = $('#menu ul li ul');

if($subMenu.length){
	$subMenu.addClass('subMenu');
	
	$($subMenu).each(function(){
		$(this).parent().addClass('topMenu');
	});
	
	$('.topMenu a:not(ul.subMenu li a)').click(function(){ return false });
	
	$('#menu ul li').hover(function(){
		$(this).find('.subMenu').show();
	}, function(){
		$(this).find('.subMenu').hide();
	});
}

//-- change login text to read "dealer login"
if($('#loginBtn a').text() != 'Logout'){
	$('#loginBtn a').prepend('Dealer ');
	$('#loginBtn').attr('title', 'Dealer Central Login');
}else{
	$('#loginBtn').attr('title', 'Logout of Dealer Central');
}

//-- search bar
	$("#search a").html(''); 				//----- renmove "search" text
	//$("#search a").removeClass('search');	//----- remove the original class
	//$("#search a").addClass('searchAlt');	//----- add new class to replace the text with a button

if($('#level2_nav'))
{
    var value = $('h3 .Head').text();
    var menuVal = $('#level2_nav li:contains('+ value +')');
        menuVal.addClass('highlight');

	$('#level2_nav > li').each(function(){
		
		$(this).hover(function(){
			$(this).find('#level2_subNav').css({'display' : 'block'});
		}, function(){
			$(this).find('#level2_subNav').css({'display' : 'none'});
		});
	});
}

	//right column height fix. if it gets cut off then extend it to it's full height.
	if( $("#col2").height() <= 398)
	{
		$("#col2").height(398);
		//alert($("#col2").height())
	}
	/*Fix browser bug. Resize footer when the width is below the static	value of the content area.*/


if( $(window).width() <= 1200 )
{
	$('footer').addClass('fixWidth');
	$("body").addClass('fixWidth');
}else{
	$('footer').removeClass('fixWidth');
	$("body").removeClass('fixWidth');
}

	$(window).resize(function(){
		if( $(window).width() <= 1200 )
		{	
			$('footer').addClass('fixWidth');
			$("body").addClass('fixWidth');
			//alert($("#footer").width());
		}else{
			$('footer').removeClass('fixWidth');
			$("body").removeClass('fixWidth');
		}
	  });
	
 //-- Panel 1 list items
    $('.panel1 ul li').addClass('pnlBorder'); // add bottom borders to all the li tags
	$('.panel1 ul li:last').removeClass('pnlBorder');
	$('.panel1 ul li:last-child').addClass('noBorder'); // remove the last border from the li tags  

//-- call ie6 fix function
   
//-- dealer central dynamic list
    $('#services li ul').css({position : 'absolute'}); //-- dynamically position sub menus absolutely
    
    var hideAll = $('#services li ul');
    hideAll.addClass('hideSub');
	//-- dealer central buttons
	
	//-- set default value to 0 or Off.
	var marketing_info = 0;
	var suppInfo = 0;
	var trainInfo = 0;
	var resources = 0;
	var forms = 0;
	
	/*
	 ****** For All Functions Below ******
		If the value of the current selector = 0 or Off hide anything else that appears then show the current sub value.
		Then set the selector value to 1 or On. If it's on then when clicked again it will hide the sub menu and set the selector value back to 0.
	*/
	$('.marketing_info a').click(function(){
		if(marketing_info == 0)
		{
			hideAll.animate({height: 'hide', opacity: '0'}, 'fast');
			$('.marketing_info a').next('ul').animate({height: 'show', opacity: '1'}, 'fast');

			marketing_info = 1;
			suppInfo = 0;
			trainInfo = 0;
			resources = 0;
			forms = 0;
		}else{
			$('.marketing_info a').next('ul').animate({height: 'hide', opacity: '0'}, 'fast');
			marketing_info = 0;
		}
		
	});
	
	$('.service_info a').click(function(){
		if(suppInfo == 0)
		{
			hideAll.animate({height: 'hide', opacity: '0'}, 'fast');
			$('.service_info a').next('ul').animate({height: 'show', opacity: '1'}, 'fast');
			
			marketing_info = 0;
			suppInfo = 1;
			trainInfo = 0;
			resources = 0;
			forms = 0;
		}else{
			$('.service_info a').next('ul').animate({height: 'hide', opacity: '0'}, 'fast');
			suppInfo = 0;	
		}
	});
	
	$('.training_info a').click(function(){		
		if(trainInfo == 0)
		{
			hideAll.animate({height: 'hide', opacity: '0'}, 'fast');
			$('.training_info a').next('ul').animate({height: 'show', opacity: '1'}, 'fast');
			
			marketing_info = 0;
			suppInfo = 0;
			trainInfo = 1;
			resources = 0;
			forms = 0;
		}else{
			$('.training_info a').next('ul').animate({height: 'hide', opacity: '0'}, 'fast');
			trainInfo = 0;
		}
	});
	
	$('.resources a').click(function(){		
		if(resources == 0)
		{
			hideAll.animate({height: 'hide', opacity: '0'}, 'fast');
			$('.resources a').next('ul').animate({height: 'show', opacity: '1'}, 'fast');
			
			marketing_info = 0;
			suppInfo = 0;
			trainInfo = 0;
			resources = 1;
			forms = 0;
		}else{
			$('.resources a').next('ul').animate({height: 'hide', opacity: '0'}, 'fast');
			resources = 0;
		}
	});
	
	$('.forms a').click(function(){		
		if(forms == 0)
		{
			hideAll.animate({height: 'hide', opacity: '0'}, 'fast');
			$('.forms a').next('ul').animate({height: 'show', opacity: '1'}, 'fast');
			
			marketing_info = 0;
			suppInfo = 0;
			trainInfo = 0;
			resources = 0;
			forms = 1;
		}else{
			$('.forms a').next('ul').animate({height: 'hide', opacity: '0'}, 'fast');
			forms = 0;
		}
	});
	
//-- accordian navigation
	$('#accordian div').css({cursor : 'pointer'});
	$('#accordian div a').attr('onclick', 'return false');

	$('#accordian div span').addClass('hideSub');
	$('#accordian div span:first').animate({height: 'show', opacity:'1'}, 'slow');
	$('#accordian a:first').addClass('hideImg');
	$('#accordian a:not(a:first)').addClass('showImg');
	
	var active = 1;
	
	$('#accordian div a:first').click(function(){
		activeCheck($(this));
		return false;
	});
	
	$('#accordian div a:not(a:first)').click(function(){
		$('#accordian div span p a').removeAttr('class');
		$('#accordian div span p a').unbind();
		$('#accordian div span p a').removeAttr('onclick'); // - allows links within the text to opperate
		activeCheck($(this));
		return false;
	});
	
	// -- shows/hides elements, checks parameters to determine the functionality
	function showHide(obj, action){
		var opacity_lvl;
		
		if(action == 'show'){
			opacity_lvl = 1;
			active = 1;
			$(obj).removeClass('showImg');
			$(obj).addClass('hideImg');
			$('#accordian div span p a').removeAttr('class');
		}else{
			opacity_lvl = 0;
			active = 0;
			$(obj).removeClass('hideImg');
			$(obj).addClass('showImg');
		}

		$(obj).next('span').animate({height: action, opacity:opacity_lvl}, 'slow');
		return false;
	}
	
	function activeCheck(obj)
	{
		if(active == 1){
			$('#accordian div span').animate({'height' : 'hide', opacity : '0'}, 'slow');
			$('#accordian div a').each(function(){
				$(this).removeClass('hideImg');
				$(this).addClass('showImg');
			});
			active = 0;
			showHide(obj, 'show');
		}else{
			active = 1;
			showHide(obj, 'hide');
		}
	}//-- end accordian functions	
	
//-- table lines
$('.tbl_lines tr:not([th]):odd').addClass('oddcol');
$('.tbl_lines th').addClass('evencol');

//----------------------------- rotator: main page -----------------------------------------------------------------------------

		var rotatorCount = $('#rotator li').length;
		var currentSlide = 0;
		var oldSlide = 0;
        var hiddenPosition = 0;
		var rotateTimeout;
        var rotateInProgress = false;
		var $crosslink;		

			// -- generate UI base menu tags
			$('<ul></ul>').attr('id', 'rotator_menu').appendTo('#rotator');
//----------------------------------------------------------------------- setup list menu
			$('#content #rotator li').each(function(e){
				var revOrder = e + 1;		
				var curOrder = rotatorCount + 1;
				var elem = $(this).find('img').attr('src');
				var createThumb = elem.replace('images/', 'images/thumbnail.aspx?img=');
				
				// generate LI Tags with links
				var $link = $('<a></a>').attr('href', '#' + (e + 1)).addClass('cross-link').html("<img src='" + createThumb + "' />");
				$("<li></li>").html($link).appendTo("#rotator_menu");
				
				// append attributes to rotator list
				$(this).attr('id', e + 1);
				$(this).css({'z-index' : curOrder - revOrder -1});

				$(this).addClass('rotate_heading');
				
				highLight(currentSlide);
				
			});
//------------------------------------------------------------------------------------------ begin rotate			
			var beginRotate = function(){
				if (!rotateInProgress) {
					rotateInProgress = true;
                    rotateTimeout = false;
					
					currentSlide = (oldSlide + 1) % rotatorCount ;
					highLight(currentSlide);

					$('li.rotate_heading:eq(' + oldSlide + ')').animate({ "opacity": 0 }, 'slow', function() {
                    	$(this).css({'top': hiddenPosition, 'z-index': 0});
						var cur = currentSlide -1;
						
                    });
			
                    $('li.rotate_heading:eq(' + currentSlide + ')').animate({ "opacity": 1}, 'slow', function() {
						rotateInProgress = false;
						var cur = currentSlide -1;
						
						if(!rotateTimeout){
						$(this).css({'z-index': 1});
							rotateTimeout = setTimeout(beginRotate, 5000);
						}
                     });
                     oldSlide = currentSlide;
				}
			}; // end rotate function		
			rotateTimeout = setTimeout(beginRotate, 5000);
		
			function highLight(dt)
			{	
				$('#rotator_menu li img').removeClass('highlight');
				$('#rotator_menu li img').eq(dt).addClass('highlight');
			}
		
			$(function(){
				$(".cross-link").click(function(event){
					clearTimeout(rotateTimeout);
					rotateTimeout = false;
				
					var value1 = $(this).attr('href');
					var valInt = value1.slice(1) -1; // value of the link selected -1
					
					//alert(value1);
					
					if(valInt == rotatorCount -1)
					{
						oldSlide = rotatorCount -1;
						currentSlide = 0;
					}else{
						oldSlide = valInt -1;
						currentSlide = valInt;
					}

					$('#rotator div li').css({'opacity' : 0, 'z-index': 0});
					//$('#rotator div li p').css({'opacity' : 0});
					
					$(value1).animate({ "opacity": 1}, 'fast');
					$(value1).css({'z-index': 1});
					
					highLight(valInt);
					
	
					if (!rotateTimeout){
						rotateTimeout = setTimeout(beginRotate, 5000); // pause for 5 seconds		
					}
				return false;
				});

        }); // -- end rotator init function;
        //---------------------------------------------------------------------------------- Dealer lookup

        $('#dealers a').remove();
        //$('#directory #country').load('../../../../../Portals/_default/Skins/Autofarm/dealer_lookup/dealers.aspx');

	$.get("../../../../../Portals/_default/Skins/Autofarm/dealer_lookup/dealers.aspx", function(data){
	  if(data == 'error'){
  	    $('<div></div>').html("A database error occured. Please contact the website administrator.").css({'color': '#ff0000'}).appendTo('#directory');
	  }else{
	    $('#directory #country').append(data);
	    $('#country').fadeIn();
	  }
	
	});


        $('#country').change(function() {
            $('#state').html('');
            $.post('../../../../../Portals/_default/Skins/Autofarm/dealer_lookup/states.aspx', { 'country': $('#country option:selected').text() }, function(data) {
                $('#state').html(data);
                showDealer($('#state option:selected').text());
            });
            $('#state').fadeIn();
        });

        $('#state').change(function() {
            showDealer($('#state option:selected').text());
        });

        function showDealer(state) {
            var $ulContacts = $('<div></div>').attr("id='accordian'");
            $('#dealers').html("<div id='accordian'></div>");

            $.post('../../../../../Portals/_default/Skins/Autofarm/dealer_lookup/address.aspx', { 'state': state }, function(data) {
                $('#accordian').html(data);

                $('#accordian div').css({cursor : 'pointer'});
	$('#accordian div a').attr('onclick', 'return false');

	$('#accordian div span').addClass('hideSub');
	$('#accordian div span:first').animate({height: 'show', opacity:'1'}, 'slow');
	$('#accordian a:first').addClass('hideImg');
	$('#accordian a:not(a:first)').addClass('showImg');
	
	var active = 1;
	
	$('#accordian div a:first').click(function(){
		activeCheck($(this));
		return false;
	});
	
	$('#accordian div a:not(a:first)').click(function(){
		$('#accordian div span p a').removeAttr('class');
		$('#accordian div span p a').unbind();
		$('#accordian div span p a').removeAttr('onclick'); // - allows links within the text to opperate
		activeCheck($(this));
		return false;
	});
	
	// -- shows/hides elements, checks parameters to determine the functionality
	function showHide(obj, action){
		var opacity_lvl;
		
		if(action == 'show'){
			opacity_lvl = 1;
			active = 1;
			$(obj).removeClass('showImg');
			$(obj).addClass('hideImg');
			$('#accordian div span p a').removeAttr('class');
		}else{
			opacity_lvl = 0;
			active = 0;
			$(obj).removeClass('hideImg');
			$(obj).addClass('showImg');
		}

		$(obj).next('span').animate({height: action, opacity:opacity_lvl}, 'slow');
		return false;
	}
	
	function activeCheck(obj)
	{
		if(active == 1){
			$('#accordian div span').animate({'height' : 'hide', opacity : '0'}, 'slow');
			$('#accordian div a').each(function(){
				$(this).removeClass('hideImg');
				$(this).addClass('showImg');
			});
			active = 0;
			showHide(obj, 'show');
		}else{
			active = 1;
			showHide(obj, 'hide');
		}
	}//-- end accordian functions	
            });
        }

//---------------------------------------------------------------------------------- news rotator
//-- startRss is initially set to 0 if it remains at 0 then a timer will check every second until it is
//-- launched then it is set to 1 and the timer is no longer executed.
var startRss = 0;
var headlineTimeout;
if($('.headline p').text() != '')
{
	beginRotation();
}
function beginRotation(){
	startRss = 1;
	$('#news-feed').removeClass('formatting'); // remove current class
	$('#news-feed').addClass("news-style"); // add new class
	$('.headline').css({'position':'absolute', 'height':'100px', 'top':'70px', 'left':'10px', 'overflow':'hidden', 'background-color':'#ffffff', 'font-family':'Arial', 'width':'265px'}); // add new styles

	$('#news-feed').each(function() {
	
		// Set up rotator
		// reformat the RSS dates ----------------------------------------
		var date = new Date($('.publication-date').html());
		var dy = date.getFullYear();
		var dm = date.getMonth() + 1;
		var dd = date.getDate();
		$('.publication-date').html(dm + '/' + dd + '/' + dy)
		
        var currentHeadline = 0, oldHeadline = 0;
        var hiddenPosition = $('#news-feed').height() + 10;
        $('div.headline:eq(' + currentHeadline + ')').css('top', 0);
        var headlineCount = $('div.headline').length;
		
		// hide summary ----------------------------------------------
		$('.news_summary').each(function(g){
			$(this).attr('id', 'summary_' + g);
		});
		//$('.news_summary').appendTo('#news-feed');

		$('.news_summary').css({'display' : 'none'});

        // perform the rotation
        var headlineTimeout;
        var rotateInProgress = false;

        var headlineRotate = function() {
			if (!rotateInProgress) {
				rotateInProgress = true;
				headlineTimeout = false;

        	currentHeadline = (oldHeadline + 1) % headlineCount;
        	//headline rotation will occur here
        	$('div.headline:eq(' + oldHeadline + ')').animate({ top: -hiddenPosition }, 'slow', function() {
        		$(this).css('top', hiddenPosition);
        	});

        	$('div.headline:eq(' + currentHeadline + ')').animate({ top: 0 }, 'slow', function() {
        		rotateInProgress = false;

        		if (!headlineTimeout) {
        			headlineTimeout = setTimeout(headlineRotate, 5000);
				}
         	});
        		oldHeadline = currentHeadline;
        	}
        };
        headlineTimeout = setTimeout(headlineRotate, 5000);

	/* -- hover function ------------------------------------------*/
        $('#news-feed').hover(function(event) {
        	clearTimeout(headlineTimeout);
        	headlineTimeout = false;
			
			// -- Create bubble ------------------------------------
			var summaryTxt = getSummary(currentHeadline);
			$('#showSummary').remove();
			var bubbleTop = $('<div></div>').attr('id', 'blb_top');
			var bubbleBottom = $('<div></div>').attr('id', 'blb_bottom');
			var bubblePointer = $('<div><span>Summary</span></div>').attr('id', 'blb_pointer');
			var bubbleDiv = $('<div></div>').attr('id', 'summary').html(summaryTxt); //.css({'display' : 'none'});
			
			$('<div></div>').attr('id', 'showSummary').css({'display' : 'none'}).appendTo('#rss_summary');
			$('#showSummary').append(bubbleTop, bubbleDiv, bubbleBottom, bubblePointer);
			
			var curXval = $('#showSummary').height(); //-- height of current object
			$('#showSummary').css({'top': -(curXval + 2)}); //-- change the top positioning

			
			$('#showSummary').fadeIn(); //-- show summary
			
        }, function() {
			$('#showSummary').fadeOut(); //-- fade summary
			if (!headlineTimeout) {
				headlineTimeout = setTimeout(headlineRotate, 250);
			}
        }); // -- end hover function
		
		//-- grab summary text
		function getSummary(txt){
			return $('#summary_' + txt).text();
		}
	});
}// -- end rotation function

//-- if the RSS feed is updated the script will not run initially.
// -- need to set a timer to check if the "startRss" variable is set to 0. If so begin the timer and check every 1 second.
var rssTimeout;
if(startRss == 0){
	rssTimeout = setTimeout(beginRotation, 5000);
}

// --------------------------------------------------------------------------------------------- press release icons
var pr = $(".pr_table a:contains('read more ...')");
pr.addClass('pr_icon');
$('.pr_icon').css({'padding-left' : '12px'});
//alert(pr.text());

// --------------------------------------------------------------------------------- Custom JQuery Tabs
	$('.jtabs div').attr('class', 'hide'); // -- *** add hide to all the DIV tags *** --
	$('.jtabs div:first').attr('class', 'show'); // -- *** add show to the first DIV tag *** --
	
	// -- *** Build Menu *** --
	$('<ul></ul>').attr('id', 'tabs').prependTo('.jtabs');
	$('.jtabs div').each(function(z)
	{
		var idTag = $(this).attr('id'); // -- *** get titles from the DIV tags *** --
		var title = $(this).attr('title'); // -- *** get titles from the DIV tags *** --
		$('<li></li>').attr('title', idTag).attr('class', 'off').html(title).appendTo('#tabs'); // -- *** create the list items *** --
	});
	$('#tabs li:first').attr('class', 'on'); // -- *** add the ON class attribute to the first LI tag in the list *** --
	
	$('#tabs li').hover(function(){
		$(this).addClass('tab_hover');
	}, function(){
		$(this).removeClass('tab_hover');
	});
	
	var e, i = 0;
	e = $('#tabs li');
	
	e.each(function(i){
	if($(this).attr('class') == 'on' || $(this).attr('class') == 'off'){
		$(this).click(function(){
			var getEls = $('.jtabs div');

			$('.jtabs div').each(function(z)
			{
				getEls[z].className = getEls[z].className.replace('show', 'hide');
			});
			
			$('#tabs li').attr('class', 'off');
			
			$(this).attr('class', 'on');
			var show = $(this).attr('title');
			$('#' + show).attr('class', 'show');

		});
	}
	});

	if($('#supported_vehicles').length > 0){
		
		function getPage(option){
			$.get('../../../../../Portals/_default/Skins/Autofarm/supported_vehicles/' + option + ".htm", function(data){
				if(data == 'error'){
				$('<div></div>').html("An error occured. Please contact the website administrator.").css({'color': '#ff0000'}).appendTo('#tractor-lists');
			  }else{
				$('#supported_vehicles #tractor-lists').html('').append(data);
				beginRotation();
			  }	
			});
		}
		
		var firstOption = $('#company_list option:selected').text();
		// -- initial function;
		getPage(firstOption);
		
		$('#company_list').change(function(){
			getPage( $(this).find('option:selected').attr('value') );
		});
		
		function beginRotation(){
			var numItems = $('#tractor-lists .rotate-mini');
			
			for(var i=0; i < numItems.length; i++){
				var ids = '#' + $(numItems[i]).attr('id');

				if($(ids + ' li').length > 1)
				{
					rotator.init(ids);
				}
			}
		}
	}
}); // -- end js page load function

var rotator = function(){
			
			var timer;
			var speed = 2000;
			var pause = false;
			
			function rotate(element, id) {
				
				var $next_li = $(element).next('li').length ? $(element).next('li') : $(id + ' li:first');
				
				function doIt() {
					rotate($next_li, id);
				}
				
				$(element).fadeOut(speed);
				
				$($next_li).fadeIn(speed, function() {
					// Slight delay.
					timer = setTimeout(doIt, 3000);
				});
			}
			
			function init(id){
				$(id + ' li:first').show();
				setTimeout(function(){rotate( $(id + ' li:visible:first'), id )}, 3000);
			}
			
			return{
				init : init,
				rotate : rotate
			}
}(); // end rotator


// --------------------------------------------------------------------------------- fix javascript psudo hover in ie6
startList = function()
{
	if(!document.getElementById("productMenu")) return false;
  if (document.all && document.getElementById)
  {
    navRoot = document.getElementById("productMenu");
    
    for (i=0; i < navRoot.childNodes.length; i++) 
    {
        node = navRoot.childNodes[i];
		
	    if (node.nodeName == "LI") 
	    {
	        node.onmouseover = function() 
	        {   
	            this.className += " over";	
	        } //-- end inner function
				
	  		node.onmouseout=function() 
        	{									
          		this.className = this.className.replace(" over", "");		
	    	} //-- end inner function
     	} //-- end second if
    } //-- end for loop
  } //-- end first if
} //-- end function
