/**
 * Javascripts for terexcranes.com
 * @author Bernd Basmer
 */

//	Set variable with all available languages
	var validLanguages = ['en', 'de', 'fr', 'it', 'es'];
	var lang = '';
	var selectedLang = '';

/**
 * Check if the page is located on a UCM server
 */
	function checkForUCM(){
		var ucm = false;
		if(location.href.indexOf("/ucm") >= 0 || location.href.indexOf("/contribute") >= 0)
			ucm = true;
		return ucm;
	}
	
/**
 * 	Check if the language cookie is set, if not set to default language (Browserlanguage)
 */ 
	function setLanguage(){
	//	Check if page is on UCM instance or published site
		if (checkForUCM() === false) {
		//	Set lang variable according to language folder in url
			for (i = 0; i < validLanguages.length; i++) {
				var checkValue = '/' + validLanguages[i] + '/';
				if (location.href.indexOf(checkValue) >= 0) {
					lang = validLanguages[i];
					selectedLang = validLanguages[i];
				}
			}
		} else {
		//	Set cookie language parameter and lang variable according to browser language
			if (!$.cookie("lang")) {
				var browserLang = '';
				browserLang = getBrowserLanguage();
				lang = browserLang;
				document.cookie = "lang=" + browserLang + "; path=/";
				location.reload();
			}
		}		
	}
	
	setLanguage();
	
/**
 * Stuff to do after page load
 */

	$(document).ready(function(){
		
	//	Language selector
	//	-----------------------------------------
		$("#langselect").change(function(){
			
			document.cookie = "lang=" + $("#langselect :selected").val() + "; path=/";
			
		//	If Server is a UCM server just reload the page.
			if(checkForUCM() == true){
				if(location.href.indexOf('SSContributor') >= 0){
					location.reload();
				} else {
					var teile = location.href.split('?');
					location.href=teile[0];
				}
		//	If no contribution server, change the URL to the corresponding language
			} else {
				var loc = location.href;
				var selectedLang = $("#langselect :selected").val();
				var newLoc = '';
				for(i = 0; i < validLanguages.length; i++){
					var checkValue = '/' + validLanguages[i] + '/';
					if(loc.indexOf(checkValue) > 0){
						var locParts = loc.split(checkValue);
						newLoc = locParts[0] + '/' + selectedLang + '/' + locParts[1];
					}
				}
				if(newLoc != ''){
					location.href = newLoc;
				} else {
					alert('No valid language parameter found!');
				}
				
			}
		})
		
	//	Select the cookie value of "lang" as pre selected value in the language dropdown
	//	-------------------------------------------------------------------------------------
		if (checkForUCM() === true) {
			var debugAus = '';
			for (var i = 1; i <= $("#langselect option").length; i++) {
				debugAus += $("#langselect option:nth-child(" + i + ")").val() + ' --- ' + $.cookie("lang") + "\n";
				if ($("#langselect option:nth-child(" + i + ")").val() == $.cookie("lang")) {
					$("#langselect option:nth-child(" + i + ")").attr("selected", "selected");
				}
			//	alert(debugAus);
			}
		}
		
	//	Check if the language dropdown shows the same language as the url
	//	-------------------------------------------------------------------------------
		if (checkForUCM() === false) {
			//	Check if the language of the drop down is the language of the url.
			//	If not, change the dropdown. 
			for (i = 0; i < validLanguages.length; i++) {
				var checkValue = '/' + validLanguages[i] + '/';
				if (location.href.indexOf(checkValue) > 0) {
					var preSelectedLang = $("#langselect :selected").val();
					if(preSelectedLang != validLanguages[i]){
						$("#langselect option[value='" + validLanguages[i] + "']").attr("selected", "selected");
						selectedLang = validLanguages[i];
					}
				}
			}
		}

	//	Add a skin to the language dropdown
	//	----------------------------------------
	//	$("#langselect").select_skin();
		
	//	Newsletter subscription on homepage
	//	-----------------------------------------
		$("form#nlformhome").submit(function(){
			var email = $("#email").val();
			if(checkEmail(email)){
				location.href = "http://ucmdev.terex.com/cra/aboutus/newsletter/index.htm?email=" + $("#email").val();
				return false;
			} else {
				alert(tx_errPleaseEnterValidEmail);
				return false;
			}
		})
		
	//	Newsletter subscription page
	//	-----------------------------------------
		$("p.hideIt").hide();
		$(":submit").addClass("submitButton");
		$("select#type").change(function(){
			if($(this).attr("selectedIndex") == 1){
				$("p.hideIt").show(500);
			} else {
				$("p.hideIt").hide(500);
				$("input#coname").val('');
				$("select#coactivity").attr("selectedIndex", 0);
			}
		})
		
	//	Empty input fields on focus
	//	---------------------------------
		$("input.emptyOnEntry").focus(function(){
			$(this).val('');
		})
		
	//	Zebra for table rows
	//	-------------------------
		$("tr:nth-child(odd)").addClass("odd");

	//	Tabs for Product category detail
	//	--------------------------------
		var z = 1;
		$("div#categorytabs a.tabhead").each(function(){
			$(this).attr("href", "#tab" + z);
			z++;
		})
		$("div#categorytabs").tabs();

	//	Tabs for Product category detail
	//	--------------------------------
/*
		var z = 1;
		$("a.prodtabhead").each(function(){
			$(this).attr("href", "#prodTab" + z);
			z++;
		})*/
		$("div#producttabs").tabs();

		
	//	Styling for Input fields
	//	-------------------------------------
		$('input[type="text"]').addClass("idleField"); 
		$('input[type="text"]').focus(function() {   
        	$(this).removeClass("idleField").addClass("focusField");   
        	if (this.value == this.defaultValue){   
            	this.value = '';   
        	}   
        
			if(this.value != this.defaultValue){   
	            this.select();   
	        }   
    	});   

		$('input[type="text"]').blur(function() {   
	        $(this).removeClass("focusField").addClass("idleField");   
    	    if ($.trim(this.value == '')){   
        	    this.value = (this.defaultValue ? this.defaultValue : '');   
	        }   
    	});
		
		$("input[type=checkbox]").css({
			"width": "20px",
			"float": "left",
			"border": "none"
		});

	//	Hide tabs on product section pages if content is empty
	//	-----------------------------------------------------------
		var checkStrings = $('div#categorytabs div#tab2 > *').length;
		if(checkStrings < 2){
			$('div#categorytabs ul.tabnav li:eq(1)').hide();
		}
		
		var checkStrings = $('div#categorytabs div#tab3 ul > *').length;
		if(checkStrings == 0){
			$('div#categorytabs ul.tabnav li:eq(2)').hide();
		}
		
	//	Hide pdf download icon column on product section page if no spec sheet available
	//	-------------------------------------------------------------------------------------
		if($('a.pdfIcon').length == 0){
			$('table#specsTable th:eq(4)').hide();
//			$('table#specsTable tr td:last-child').each(function(){
//				$(this).hide();
//			})
		}
		
	//	Back link for news detail pages
	//	-------------------------------------
		$('a#newsBackLink').click(function(){
			var url = location.href;
			var teile = url.split('/');
			var lastIndex = teile.length - 1;
			var lastword = teile[lastIndex];
			var urlStripped = url.split(lastword);
			var newURL = urlStripped[0] + 'index.htm';
			location.href = newURL;
			return false;
		})
		
	//	Show right side of product tabs in every tab content
	//	-------------------------------------------------------
		var rightProdTab = $("#allProdTabsRight");
		$(".tabContentRight").each(function(){
			$(this).append($(rightProdTab).html());
		})
		$("#allProdTabsRight").hide(); 

	//	Image handling on product detail pages
	//	--------------------------------------------
		$('div#prodThumbsWrapper img:even').each(function(){
			$(this).addClass('prodThumbLeft');
		})
		
		var imgIndex = 0;
		$('div#prodImageWrapper img').each(function(){
			if(imgIndex != 0){
				$(this).hide();
				$(this).attr('id', 'prodImg_' + imgIndex);
			}
			imgIndex++;
		})
		$('img#prodImageBig').attr('src', $('img#prodImg_1').attr('src'));
		
		imgIndex = 1;
		$('div#prodThumbsWrapper img').each(function(){
			$(this).attr('id', 'thumbImg_' + imgIndex);
			$(this).click(function(){
				var thumbIdTeile = $(this).attr('id').split('_');
				$('img#prodImageBig').attr('src', $('img#prodImg_' + thumbIdTeile[1]).attr('src'));
			})
			imgIndex++;
		})
		
	}) //	END FUNCTIONS AFTER PAGE LOAD

/**
 * Browser Language Detection
 * ------------------------------------------
 */
	function getBrowserLanguage(){
		
		var browserLang = '';
	//	No IE
		if(jQuery.support.noCloneEvent){
			browserLang = navigator.language;
	//	IE
		} else {
			browserLang = navigator.browserLanguage;
		}
		
		if(browserLang.indexOf('de') >= 0){
			return 'de';
		}
		if(browserLang.indexOf('fr') >= 0){
			return 'fr';
		}
		if(browserLang.indexOf('es') >= 0){
			return 'es';
		}
		if(browserLang.indexOf('it') >= 0){
			return 'it';
		}
		
		return 'en';		
	}
	
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2007, 2008, Oracle. All rights reserved.
// Function : FR_CRANESSUBNAV
// Comments : 
/////////////////////////////////////////////////////////////////////////////

function FR_CRANESSUBNAV(strTextColor, strHoverColor, strFocusColor, strClassName, 
							strShowHome, strStartLevel, strNumLevels)
{
	this.m_TextColor  = '';
	this.m_HoverColor = '';
	this.m_FocusColor = '';
	this.m_ClassName  = 'FR_CRANESSUBNAV';
	
	this.m_ShowHome   = false;
	
	this.m_StartLevel = 2;
	this.m_NumLevels  = 10;
	this.m_EndLevel   = 11;
	
	this.m_NavPath    = g_navNode_Path;
			
	FR_CRANESSUBNAV.prototype.Display = FR_CRANESSUBNAV_Display;
	FR_CRANESSUBNAV.prototype.DisplayNode = FR_CRANESSUBNAV_DisplayNode;
		
	if (strTextColor != '')
		this.m_TextColor = strTextColor;
		
	if (strHoverColor != '')
		this.m_HoverColor = strHoverColor;

	if (strFocusColor != '')
		this.m_FocusColor = strFocusColor;

	if (strClassName != '')
		this.m_ClassName = strClassName;

	if (strShowHome == 'true')
		this.m_ShowHome = true;
		
	if (strStartLevel != '')
	{
		var value = parseInt(strStartLevel);
		if (value != NaN)
			this.m_StartLevel = value;
	}
	
	if (strNumLevels != '')
	{
		var value = parseInt(strNumLevels);
		if (value != NaN)
			this.m_NumLevels = value;
	}

	this.m_EndLevel = this.m_StartLevel + this.m_NumLevels - 1 ;
}

function FR_CRANESSUBNAV_Display (node)
{
	document.write('<dl>');
	this.DisplayNode(node);	
	document.write('</dl>');
}

function FR_CRANESSUBNAV_DisplayNode(node)
{
	var bSelected = false;
	var nodeColor = this.m_TextColor;
	var nodeClass = this.m_ClassName

	var nodeLevel = node.m_level;
	
	if (nodeLevel > 6)
		nodeLevel = 6;
	
	if (this.m_NavPath.length > 0 && node.m_level < this.m_NavPath.length)
	{
		if (this.m_NavPath[node.m_level] == node.m_id)
		{
			if (node.m_level > 0 || (node.m_level == 0 && this.m_NavPath.length == 1))
			{
				bSelected = true;
				nodeColor = this.m_FocusColor;
				nodeClass += '-focus';
			}
		}
	}

	if (nodeLevel > 0)
		nodeClass += '-' + nodeLevel;
		
	if ( (node.m_level == 0 && this.m_ShowHome) || 
     	 (node.m_level >= this.m_StartLevel && node.m_level <= this.m_EndLevel)
	   )
	{
		var ds = new Array();
		var di = 0;

		ds[di++] = (nodeLevel <= 2) ? '<dt' : '<dd';
		ds[di++] = ' class="' + nodeClass + '"';
		ds[di++] = '>';

		ds[di++] = '<a href="' + node.m_href + '"';
		ds[di++] = ' class="' + nodeClass + '"';
		
		if (nodeColor != '')
		{
			ds[di++] = ' style="color:' + nodeColor + ';"';

			if (!bSelected && this.m_HoverColor != '')
			{
				ds[di++] = ' onmouseover="this.style.color=\'' + this.m_HoverColor + '\'"';
				ds[di++] = ' onmouseout="this.style.color=\'' + nodeColor + '\'"';
			}
		}
		
		ds[di++] = '>';
		ds[di++] = node.m_label;
		ds[di++] = '</a>';
		document.write(ds.join(''));
	}
	
	if (bSelected || node.m_level == 0)
	{	// expand sub-levels (if any)
		for (var i = 0; i < node.m_subNodes.length; i++)
		{
			this.DisplayNode(node.m_subNodes[i]);
		}
	}
}
	
var sfHover = function() {
//	var sfEls = document.getElementById("langMenu").getElementsByTagName("li");
	var sfEls = $("#langMenu li");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
