/*------------------------------------------------------------------------------
	JS Functions
------------------------------------------------------------------------------*/	
var openTab, $paneTarget, current_item, max_items, speed, container_width, file, folder;

function buttonCheck() {
	$(".leftButton, .rightButton").show();
	(current_item == max_items) ? $(".rightButton").hide() : '';
	(current_item == 1) ? $(".leftButton").hide() : '';
}

function sifrcontent() {
	// in the slider
	sIFR.replace(font, {
	  selector: '.content .slider_bg h1'
	  ,wmode: 'transparent'
	  ,css: [
	      '.sIFR-root { color:#ffffff; font-size:20px; }',
	      'em { font-style:normal; color:#009bbb; font-size:20px;}'
	    ]
	});
	
	// main content h1
	sIFR.replace(font, {
	  selector: '.content h1'
	  ,wmode: 'transparent'
	  ,css: [
	      '.sIFR-root { color:#c4161c; font-size:20px; }',
	      'em { font-style:normal; color:#454545; font-size:20px; }'
	    ]
	});
}

function loadVideo(which) {
  tb_show('', which, '')
  return;
}

function newcontent() {
	/* CHECK AND SET SOME THINGS */
	if ($('.pane').length > 0){
		// basic vars
		$paneTarget = $('.pane');
		current_item = 1;
		max_items = $('.item').length;
		speed = 200;
		container_width = $('.item').outerWidth();
		
		// setting width to wrapper container
		$('.item_wrapper').css('width',container_width*max_items);
		
		// adding class to each item
		for (var i=1; i <= max_items; i++) {
			$('.item').eq(i-1).addClass('item_'+i);
			"<div class='count count_item_1' style='left:5px;'></div> "
			$('.slider_bg').append("<a href='#' class='count count_item_"+i+"' style='left:"+ 10*i +"px;'></a>");
		}
		
		buttonCheck();
		
		$('.count_item_'+current_item).css('background','#ffffff');
		
	}
}

(function($) {
$.fn.fadeNRotate = function(options) {
	this.each(function(){ 	
		var settings = {
			speed: 'normal',
			timeout: 2000
		};
	
		if(options)
			$.extend(settings, options);
		
		var elements = $(this).children();
		
		if (elements.length > 1) {
			$(this).css('position', 'relative');
			var parentHeight = 0;
			
			for ( var i = 0; i < elements.length; i++ ) {
				$(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute');	
				
				if (parentHeight < $(elements[i]).height()) {
					parentHeight = $(elements[i]).height();
				}
			}
			
			$(this).css('height', parentHeight);
			
			setTimeout(function(){
				$.fadeNRotate.next(elements, settings, 1, 0);
			}, settings.timeout);
			
		}
	});
};

$.fadeNRotate = function() {}
$.fadeNRotate.next = function (elements, settings, current, last) {
	
	$(elements[last]).animate({
		opacity:0
	}, settings.speed);
	
	$(elements[current]).animate({
		opacity:1
	}, settings.speed);
	
	
	if ( ( current + 1 ) < elements.length ) {
		current = current + 1;
		last = current - 1;
	} else {
		current = 0;
		last = elements.length - 1;
	};
	setTimeout((function(){$.fadeNRotate.next(elements, settings, current, last);}), settings.timeout);
};
})(jQuery);

$(document).ready( function() {
	
	if ($('.fadeNRotate').fadeNRotate) {
		$('.fadeNRotate').fadeNRotate({
			speed: 1000,
			timeout: 5000
		});
	}
	
	/*
	padding							Padding around content
	imageScale					If true, images are scaled to fit in viewport
	zoomOpacity					If true, changes content transparency when animating
	zoomSpeedIn					Speed in miliseconds of the zooming-in animation 
											(no animation if 0)
	zoomSpeedOut				Speed in miliseconds of the zooming-out animation 
											(no animation if 0)
	zoomSpeedChange			Speed in miliseconds of the animation when changing gallery items
											(no animation if 0)
	easingIn, 
	easingOut, 
	easingChange				Easing used for animations
	
	frameWidth					Default width for iframed and inline content
	frameHeight					Default height for iframed and inline content
	overlayShow					If true, shows the overlay (false by default) 
											Overlay color is defined in CSS file
											
	overlayOpacity			Opacity of overlay (from 0 to 1; default - 0.3)
	overlayColor				Color of overlay (default - #666)
	enableEscapeButton	Hides FancyBox when clicked on "Esc" button
	showCloseButton			Option to show/hide close button
	hideOnOverlayClick	Hides FancyBox when clicked on overlay
	hideOnContentClick	Hides FancyBox when clicked on opened item
	centerOnScroll			If true, content is centered when user scrolls page
											itemArray	Optional, can set custom item array
	
	callbackOnStart			Optional, called on start
	callbackOnShow			Optional, called on displaying content
	callbackOnClose			Optional, called on close
	*/
	
	$("a.iframe").fancybox({
		'frameWidth'			: 776,
		'frameHeight'			: 700,
		'padding'					: 5,
		'overlayOpacity' 	: .6
	});
	
	$('a.zoom').fancybox({
		'imageScale'			: true,
		'zoomSpeedIn'			: 250
	});
		
		$('.chevron li:last').css('border','none');
		
		/* increase / decrease font size */
		$('a.decreaseFont').click( function() {
			var curSize = $('body').css('font-size').replace('px','');
			if (curSize > 11)
			{
				$('body').css('font-size',--curSize);
			}	
			return false;
		});
		
		$('a.increaseFont').click( function() {
			var curSize = $('body').css('font-size').replace('px','');
			if (curSize < 13)
			{
				$('body').css('font-size',++curSize);
			}
			return false;
		});
		
		/*set some spaces dynamically in nested lists */
		$('.secondary_nav .products .selected').next().children().css('margin-top','10px');
		
		$('a.count').live('click', function() {
			var slideTo = $(this).attr('class').replace('count count_item_','');
			
			$('.item h1').css('display','block');
			$paneTarget.stop().scrollTo('.item_' + slideTo, speed);
			
			current_item = slideTo;
			buttonCheck();
			$('.count').css('background','#cccccc');
			$(this).css('background','#ffffff');
			$('.item h1').css('display','none');
			$('.item_'+current_item+' h1').css('display','block');
			return false;
		});
		
		// tabs in the news section
		if ($('.news_tabs').length > 0) {
			var news_tab = (window.location.hash != '' && window.location.hash != '#') ? window.location.hash : $('.news_tabs a:first').attr('href');
			$('.news_tabs a[href="'+news_tab+'"]').addClass('active_news');

			var startIndex = 1;
			startIndex = startIndex + news_tab.lastIndexOf('#');
			var content_tab = 'content_' + news_tab.substring(startIndex);			
			//var content_tab = 'content_'+ news_tab.replace('#','');
			
			$('.news_content div').hide();
			$('#'+content_tab).show();
			$('.news_content .border li:first-child').css('border-top','none');
		}
		
		$('.news_tabs a').click( function() {
			var news_tab = $(this).attr('href');
			$('.news_tabs a').removeClass('active_news');
			$(this).addClass('active_news');
			
			$('.news_content div').hide();
			
			var startIndex = 1;
			startIndex = startIndex + news_tab.lastIndexOf('#');
			var content_tab = 'content_' + news_tab.substring(startIndex);	
			//var content_tab = 'content_'+ news_tab.replace('#','');
			
			$('#'+content_tab).show();
		});
		
		// if need tabs
		if ($('.tabs a').length > 0) {
			openTab = (window.location.hash != '' && window.location.hash != '#') ? window.location.hash : $('.tabs a:first').attr('href');
			file = openTab.replace('#','') + '.html';
			folder = window.location.pathname.substr(0, window.location.pathname.lastIndexOf('/')+1);
			$('.tabs a.selected').removeClass('selected');
			$('.tabs a[href='+openTab+']').addClass('selected');
			$('#section').load('/assets/content'+folder+file, {time: new Date().getTime()}, function() {
				sifrcontent();
				newcontent();
			});
		}
		
		
		$('.tabs a').click( function() {
			startScroll = $(document).scrollTop();
			var openTab = $(this).attr('href');
			$('.tabs a.selected').removeClass('selected');
			$('.tabs a[href='+openTab+']').addClass('selected');
			window.location.hash = $(this).attr('href');
			$(document).scrollTop(startScroll);
			openTab = (window.location.hash != '' && window.location.hash != '#') ? window.location.hash : $('.tabs a:first').attr('href');
			file = openTab.replace('#','') + '.html';
			folder = window.location.pathname.substr(0, window.location.pathname.lastIndexOf('/')+1);
			$('#section').load('/assets/content'+folder+file, {time: new Date().getTime()}, function() {
				sifrcontent();
				newcontent();
			});
			return false;
		});
		
		//sets up basic button states (preventing min and max scrolling)
		function arrowNavigation(rightDir){
			$(".leftButton, .rightButton").show();
			
			// checking the max / min
			if(rightDir){ (current_item !== max_items) ? current_item++ : ''; } 
			else { (current_item !== 1) ? current_item-- : ''; }
			
			// hides or displays buttons if needed
			buttonCheck();
			
			// colors boxes appropriately
			$('.count').css('background','#cccccc');
			$('.count_item_'+current_item).css('background','#ffffff');
			$('.item h1').css('display','block');
			$paneTarget.stop().scrollTo('.item_' + current_item, speed);
			$('.item h1').css('display','none');
			$('.item_'+current_item+' h1').css('display','block');
		}
		
		// the functions that runs it
		if ($('.leftButton').length > 0) { jQuery(document).bind('keyup', 'left', function (evt){ arrowNavigation(); return false; }).bind('keyup', 'right', function (evt){ arrowNavigation(true); return false; }); }
		
		// left
		$('.leftButton').live('click',function(){ arrowNavigation(); return false;});
		
		// right
		$('.rightButton').live('click',function(){ arrowNavigation(true);return false;});
		
		// hide product dropdown lists at the start
		$('.listOfApps div').hide();
		$('.listOfTypes div').hide();
		
		// hide img alt in IE
		if($.browser.msie)
		{
			$('img').removeAttr('alt');
		}
		
		//sort product drop down lists
		// no code at this time

		
}); /* document ready */

/*------------------------------------------------------------------------------
	News Section JS Functions - Not sure if we will use this
------------------------------------------------------------------------------*/
function showAllNews(currentYear)
{
	// show all articles
	var elementName = "li." + currentYear;
	$(elementName).css("display", "block");
	
	// hide more news link
	var newsLink = "li.more_news_link_" + currentYear;
	$(newsLink).css("display", "none");
}
/*------------------------------------------------------------------------------
	Product Dropdown Lists JS Functions
------------------------------------------------------------------------------*/
function showAppList(parentNodeId)
{
	$('.listOfTypes div').hide();
	$('.listOfApps div').hide();
	var divToShow = parentNodeId + "_div";
		
	$("#" + divToShow).show();	
}

function showTypeList(parentNodeId)
{
	$('.listOfTypes div').hide();
	var divToShow = parentNodeId + "_div";
	$("#" + divToShow).show();
}

/*------------------------------------------------------------------------------
	Contact US JS Functions
------------------------------------------------------------------------------*/
	// global variables
	var lastSubjectSelected = "";
	
	function clearItems(items)
	{
		var lastItem = document.getElementById(items);
		if(lastItem){
			lastItem.style.display = "none";
		}else{
			// do nothing
		}	
	}
	
	function getLastSubjectSelected()
	{
		return lastSubjectSelected;
	}
	
	function setLastSubject(lastSubject)	
	{
		lastSubjectSelected = lastSubject;
	}
	
	function checkSafetyFields(safetyFlag)
	{
		var safety = safetyFlag;
		if(safety)
		{
			if(safety == 1)
			{
				// jquery - Show a div
				$("#safety_fields").show();
				
				// Javascript - Show a div
				//var safetyDiv = document.getElementById("safety_fields");
				//if(safetyDiv)
				//{
				//	if (safetyDiv.style.display == "none")
				//	{
				//		safetyDiv.style.display = "block";
				//	}else{
				//		// do nothing
				//	}	
				//}
			}
		}
	}
	
	function updateContactUsForm(subject)
	{
		var newSubject = subject;
		if(newSubject.length > 0)
		{
			if(newSubject == "problem")
			{
				// Jump to the form
				window.location.href = "/en/contact/problem/index.htm";
			
			}else{
				checkForRelatedFields(newSubject);
			}
			
			// Add tracking to subject field
			var subjectStr = "/contact/form";
			if(newSubject == "info")
			{
				subjectStr = subjectStr + "/general/";
			}else if(newSubject == "support")
			{
				subjectStr = subjectStr + "/service/";
			}else{
				subjectStr = subjectStr + "/" + newSubject + "/";
			}
			_gaq.push(['_trackPageview', subjectStr]);
		}
	}

	function checkForRelatedFields(subject)
	{
		// First hide any related fields showing
		var lastSubject = getLastSubjectSelected();
		if (lastSubject.length > 0)
		{	
			if((lastSubject == "catalog") || (lastSubject == "support"))
			{
				clearItems(lastSubject + "_fields");
			}else{
				clearItems("general_fields");
			}	
		}
		
		// Show Newsletter Box
		var newsletterDiv = document.getElementById("newsletterBox");
		if (newsletterDiv)
		{
			newsletterDiv.style.display = "block";
		}
			
		// Show additional fields for certain subjects
		var subjectSelected = subject;
		if (subjectSelected.length > 0)
		{
			if((subjectSelected == "catalog") || (subjectSelected == "support"))
			{
				var subjectDivID = subjectSelected + "_fields";
				var subjectDiv = document.getElementById(subjectDivID);
				if (subjectDiv)
				{
					if (subjectDiv.style.display == "none")
					{
						subjectDiv.style.display = "block";
					}else{
						// do nothing
					}	
				}
				
			}else{
				var subjectDiv = document.getElementById("general_fields");
				if (subjectDiv)
				{
					if (subjectDiv.style.display == "none")
					{
						subjectDiv.style.display = "block";
					}else{
						// do nothing
					}	
				}
			}	
		}
		
		setLastSubject(subject);
	}
	
	function clearFields(theForm)
	{
		// clear standard fields
		theForm.Name.value = "";
		theForm.Email.value = "";
		theForm.Company.value = "";
		theForm.Address1.value = "";
		theForm.Address2.value = "";
		theForm.City.value = "";
		theForm.State.value = "";
		theForm.Country.value = "";
		theForm.Postal_code.value = "";
		theForm.Phone.value = "";
		theForm.Fax.value = "";
		theForm.Subject.value = "";
		theForm.Send_newsletter.checked = false;
		
		// clear additional fields
		theForm.General_comments.value = "";
		
		theForm.Catalog_additionalInfo[0].checked = false;
		theForm.Catalog_additionalInfo[1].checked = false;
		
		theForm.Catalog_comments.value = "";
		
		theForm.Support_sitenumber.value = "";
		theForm.Support_system_number.value = "";
		theForm.Support_parts_support.checked = false;
		theForm.Support_field_support.checked = false;
		theForm.Support_technical_support.checked = false;
		theForm.Support_technical_options.value = "";
		theForm.Support_message.value = "";
		
		// hide all additional fields
		clearItems("catalog_fields");
		clearItems("support_fields");
		clearItems("general_fields");
		//clearItems("safety_fields");
		
	}
	
	function setInitialValuesAndSubmit(theForm)
	{
		var subject = theForm.Subject.value;
		
		if(subject == "info")
		{
			//theForm.MTSEmailAddresses.value = "info@mts.com";
			theForm.MTSEmailAddresses.value = "info@mts.com";
			theForm.MTSSubject.value = "General Info";
			
		}else if(subject == "sales")
		{
			//theForm.MTSEmailAddresses.value = "info@mts.com";
			theForm.MTSEmailAddresses.value = "info@mts.com";
			theForm.MTSSubject.value = " Sales Enquiry / Request a Quote";
		}else if(subject == "support")
		{
			//theForm.MTSEmailAddresses.value = "info@mts.com";
			theForm.MTSEmailAddresses.value = "info@mts.com";
			theForm.MTSSubject.value = "Service and Technical Support";
			theForm.required.value = theForm.required.value + ",Support_sitenumber,Support_systemnumber,Support_message";
		}else if (subject == "catalog")
		{
			//theForm.MTSEmailAddresses.value = "catalogs@mts.com";
			theForm.MTSEmailAddresses.value = "catalogs@mts.com";
			theForm.MTSSubject.value = "Catalog or Pricing Request";
		}else if (subject == "website")
		{
			//theForm.MTSEmailAddresses.value = "webmaster@mts.com";
			theForm.MTSEmailAddresses.value = "webmaster@mts.com";
			theForm.MTSSubject.value = "WWW Webmaster Request";
		}else{
			//do nothing
		}	
		submitForm(document.contactUSForm);
	}
/*------------------------------------------------------------------------------
	About - Global Map and Contact US - Country Contact JS
------------------------------------------------------------------------------*/

			var country;
			
			$(document).ready(function(){
				
				// For the Global Map
				//$(".country").click(function(){ loadContent( $(this).attr('id') ); return false; });
				
				// For the Contact US Form
				$(".countryList").change(function(){ loadContent( $("option:selected",this).attr('id') ); return false; });	
			
				// Load contact information
				
				var contactLink = window.location.href; 
				var urlIndex = contactLink.indexOf("/about/global/");
				
				// Only execute this code on the global contacts page
				if (urlIndex >= 0)
				{
					var array1 = contactLink.split("?")
		
					if(array1.length > 1)
					{
						var array2 = array1[1].split("&");
						var continentArray = array2[0].split("=");
						var countryArray = array2[1].split("=");
						
						var selContinent = continentArray[1];
						var selCountry = countryArray[1];

						if (selContinent.length > 0)
						{
							if (selContinent.indexOf("South_America") >= 0)
							{
								selContinent = "South_America";
							}
							swapMap(selContinent.toLowerCase());
						}
					}
				}
			
			});
		
			function loadContent(country){
				
				$('.result_offices').empty();
				xml = '/ucm/groups/public/documents/contacts/' + country.toLowerCase() + '.xml';
				
				$.get(xml, function(d){
					// Checking to see if the contact is Korea or China
					
					var countryName = country;
					if (countryName == 'Korea_Republic_of')
					{
						countryName = 'Korea, Republic of';
					}
					if (countryName == 'China_Republic_Of')
					{
						countryName = 'China, People\'s Republic Of';
					}
					if (countryName == 'Greece_Cypress')
					{
						countryName = 'Greece, Cypress';
					}
					if (countryName == 'Russian_Federation')
					{
						countryName = 'Russian Federation and CIS Countries';
					}
					
					
					
					var html_results = '<h1 class="section_main_text_heading">'+ countryName.replace(/_/g, " ") +'</h1>';
					var html_results_cur_length = html_results.length;
					
					// check for subtitle
					var subtitle = $(d).children().eq(0).children("[name='Subtitle']").eq(0).text();
			
					if(subtitle.length > 0)
					{
						html_results += subtitle + '<br /><br />';
					}
					
					// steps through the xml tree to wcm:list - then gets the children of it
					$(d).children().eq(0).children([name='ListOfOffices']).children().each( function() {
						
						i = 0;
						// loops through rows
						$(this).children().each( function() {
							if (i%2 == 0){ 
								html_results += '<div class="english"> ' + $(this).text() + '</div>';
							}else{
								html_results += '<div class="translated"> ' + $(this).text() + '</div><div class="clearL">&nbsp;</div><br />';
							}
							i++;
						});
											
					});
					
					// Check to see if any contact info was added
					if (html_results_cur_length == html_results.length)
					{
						html_results += 'No contact information was found.<br /><br />';
					}
					
					$('.office_results').html(html_results);
					
					
				});
				
				// Adding tracking to contact form dropdown
				var pageString = '/contact/dealer/' + country.toLowerCase() + '/';
				_gaq.push(['_trackPageview', pageString]);
			
			}
	
	
	
	
			function swapMap(whichCountry){			
				$('.map_rollover').css('display', 'none');
				$('.' + whichCountry).css('display', 'block');
			
				$('.all_content').css('display', 'none');
				$('.instructions').css('display', 'none');
				$('.content_' + whichCountry).css('display', 'block');
				
			}
			

