/*////////////////////////////////////////////////////////////
JavaScript Code Library
Developed by GrafX Design Division Pty Ltd
http://www.grafx.com.au

Last Checked In By : Richard Czeiger
Public Revision No : 1.0

The software and related user documentation are
protected under copyright laws and remain the sole
property of GrafX Design Division. Full license is
available on the GrafX Design Division web site or
in the original download.

Technical support is available via the GrafX web site at
http://www.grafx.com.au
////////////////////////////////////////////////////////////*/



// Suppress javaScript errors
window.onerror = new Function("return true")



// Rollover navigation (deprecated)
sfHover = function() {
	if (!document.getElementById("navigation")) return;
	var sfEls = document.getElementById("navigation").getElementsByTagName("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"), "");
		}
	}
}



// Copy street address to postal
function copyAddress() {
	$('#postAddress1').val(	$('#address1').val()	);
	$('#postAddress2').val(	$('#address2').val()	);
	$('#postTown').val(	$('#town').val()	);
	$('#postState').val(	$('#state').val()	);
	$('#postZipcode').val(	$('#zipcode').val()	);
	$('#postCountry').val(	$('#country').val()	);
}



// Show/hide 'state' dropdown
function manageState() {
	if ($('#country').length){
		if ($('#country').val()!='AU') {
			$('#state').parent().hide();
		}
		$('#country').change( function() {
			var val = $(this).val();
			if (val == 'AU') {
				$('#state').parent().show();
			} else {
				$('#state').val('');
				$('#state').parent().hide();
			}
		});
	}
}



// Greyscale Hover Over Logo
function grayscale(el) {
	var duration = 5000;
	// Pause on red, then fade to black and back to red
	$(el+' a').delay(duration).fadeTo(duration, 0).fadeTo(duration, 1 , function() {
		grayscale(el);
	});
}
function gogray(el) {
	// Get image url and assign it to 'thumbOver'
	var thumbOver = $(el+' a').css('background-image');
	// Set a background image(thumbOver) on the <a> tag
	$(el).css({
		'background-image' 	: thumbOver,
		'background-color' 	: 'transparent',
		'background-repeat' 	: 'no-repeat',
		'background-position' 	: 'center bottom'
	});
	// Now launch the function
	grayscale(el);
}



// RSV: Really Simple Validation - global functions
function myOnComplete() {
	return true;
}
function customErrorDisplay(f, errorInfo) {
	// Disabled all errors by default
	for (var i=0; i<myRules.length; i++) {
		var parts 	= myRules[i].split(",");
		var fieldName 	= parts[1];

		// $('label[for='+fieldName+']').removeClass('errorlabel');
		$('fieldset').removeClass('errorfield');
		$('.error').remove();
	}

	for (var i=0; i<errorInfo.length; i++) {
		var fieldName;

		// Radio button
		if (errorInfo[i][0].type == undefined) {
			fieldName = errorInfo[i][0][0].name;
			fieldset = $('[name='+fieldName+']').parent().parent();
		} else {
			fieldName = errorInfo[i][0].name;
			fieldset = $('[name='+fieldName+']').parent();
		}
		// Display the error
		// fieldset.css('background-color', '#FFEEEE')
		// $('#'+fieldName).css('background-color', '#FFEEEE');
		// $('label[for='+fieldName+']').addClass('errorlabel');
		fieldset.addClass('errorfield');
		$('<span class="error">'+errorInfo[i][1]+'</span>').appendTo($('label[for='+fieldName+']').parent());
	}

	if (errorInfo.length == 0) {
		return true;
	} else {
		return false;
	}
}



// Validate email
function validateEmail() {
	submittedEmail = document.getElementById('email').value;

	// Check for a value in both fields.
	if (submittedEmail == '') {
		alert('Please enter a valid email address.');
		document.getElementById('email').focus();
		return false;
	} else {
		// Now check to see if it's actually a real email address
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if(reg.test(submittedEmail) == false) {
			alert('Invalid Email Address');
			document.getElementById('email').focus();
			return false;
		} else {
			return true;
		}
	}
}



// De-obfuscate email addresses
jQuery.fn.deobfuscate = function() {
	return this.each(function() {
		// Original Usage: <span class="email">user(put an @ here)example.com</span>
		// var email = String($(this).html()).replace(/\s*\(.+\)\s*/, "@");

		// Usage: <span class="email">user[at]example.com</span>
		var email = String($(this).html()).replace('[at]', '@');
		$(this).before('<a href="mailto:' + email + '">' + email + "</a>").remove();
	});
};



$(document).ready(function() {

	// Current Page Selection
	$('#subnav li ul').hide();
	//curvyCorners.redraw();
	 		
	if ($('body').hasClass('product')) {
		var path = $('#breadcrumbs li:last a').attr('href');
		var catAlias = $('#breadcrumbs li:eq(2) a').attr('href');
		if (catAlias) var catAlias = catAlias.split('/');
		if (catAlias) var catAlias = catAlias[catAlias.length-1];
		$('body').addClass( catAlias );
	} else {
		//alert(location.pathname);		
		var path = '';//location.pathname.substring(1);
	}
	if ( path ) {
		$('#subnav a[href$="'+ path +'"]').attr('class', 'selected');
		$('#subnav a[href$="'+ path +'"]').parents('#subnav ul, #subnav li').attr('class', 'active');
		$('#subnav a[href$="'+ path +'"]').parents('#subnav ul, #subnav li').show();
		$('#subnav a[href$="'+ path +'"]').next().show();
	}


	// Greyscale the logo
	gogray('h1');


	// De-obfuscate email addresses
	$('.email').deobfuscate();


	// Search box hint
	var hint = $('#search label').attr('title');
	$('#keyword').val( hint );
	$('#keyword').addClass('inactive-input');
	$('#keyword').focus(function(){
		if ($(this).val()==hint) {
			$(this).val('');
			$(this).removeClass('inactive-input')
		}
	});
	$('#keyword').blur(function(){
		if ($(this).val()=='') {
			$(this).val( hint );
			$(this).addClass('inactive-input')
		}
	});


	if ($('#calculator').length) {
            $('.numeric').keydown(function(event) {
                // Allow only backspace and delete		                
                if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 35 || event.keyCode == 17 || event.keyCode == 36 || event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40 
		|| event.keyCode == 67 // ctrl+c
		|| event.keyCode == 86 // ctrl+v		
		|| event.keyCode == 9 // tab
		|| (event.keyCode >= 96 && event.keyCode <= 105) // numerical keyboard
		) {                
                // let it happen, don't do anything
                }
                else {  
//alert(event.keyCode);              
                    // Ensure that it is a number and stop the keypress
                    if (event.keyCode < 48 || event.keyCode > 57 ) {
                        event.preventDefault(); 
                    }       
                }
            });
	}

	if ($('.tablesorter').length){
		// Extend the default setting to always include the zebra widget.
		$.tablesorter.defaults.widgets = ['zebra'];
		// Extend the default setting to always sort on the first column
		$.tablesorter.defaults.sortList = [[1,0]];
		// Call the tablesorter plugin
		$('.tablesorter').tablesorter();

		// Highlight current row of table
		$('.tablesorter tbody tr').mouseover(function(){
			$(this).addClass('row-highlight');
		});
		$('.tablesorter tbody tr').mouseout(function(){
			$(this).removeClass('row-highlight');
		});
	}


	// Show/hide 'state' dropdown
	manageState();

	// Test password strength: password-strength.js
	$('#password').keyup(function(event) {
		// checkPassword($('#password').val());
	});
	if ($('#password').length > 0) {
		//makePasswordStrength();
	}


	// jCoverFlip
	if ($('#flip').length){
		// $('#flip').jcoverflip();
	}


	// Popup window
	if ($('body.popup').length==0){
		$('a[rel$="popup"]').colorbox({
			width:'600px',
			height:'450px',
			current:'',
			previous:'',
			next:'',
			scrolling:true,
			iframe:true,
			title: function(){
				// var url = $(this).attr('href');
				// return '<a href="'+url+'" target="_blank">Open In New Window</a>';
				return ' ';
			}
		});
	}


	// Target _blank
	$('a[rel$="external"]').click(function(){
		this.target = "_blank";
		this.title = (this.title!='') ? this.title+' [Opens in a new window]' : '[Opens in a new window]' ;
	});

	// Datepicker defaults
	var currentYear = new Date().getFullYear();
	$.datepicker.setDefaults({
		// appendText: '(dd-mm-yyyy)',
		buttonImage: '/images/icon-calendar.png',
		buttonImageOnly: true,
		buttonText: 'Calendar',
		changeMonth: true,
		changeYear: true,
		dateFormat: 'dd-mm-yy',
		firstDay: 1,
		showOn: 'both',
		// showAnim: 'slide',
		// showOptions: { direction: 'up' },
		yearRange: '1920:'+currentYear
	});


	$('#calculate').click(function(){
		var radialLoad = $('#radialLoad').val();		
		var radialLoadMax = $('#radialLoadMax').val();
		var axialLoad = $('#axialLoad').val();
		var axialLoadMax = $('#axialLoadMax').val();
		var speed = $('#speed').val();
		var maxSpeed	= $('#maxSpeed').val();
		var temperture	= $('#temperture').val();				
		var maxTemp = ($('#maxTemp')) ? $('#maxTemp').val() : 200;
		
		var error = "";		 
		if (error=="" && (radialLoad=='' || isNaN(radialLoad) || parseInt(radialLoad) <= 0))	error = "Radial Load must be > 0.";
		if (error=="" && (isNaN(radialLoad) || parseInt(radialLoad) > parseInt(radialLoadMax))) error = "Maximum value for Radial Load is "+radialLoadMax+".";		
		if (error=="" && (axialLoad=='' || isNaN(axialLoad) || parseInt(axialLoad) < 0))	error = "Axial Load "+$('#axialLoadHint').html().replace("&gt;", '>').replace("&lt;", '<')+"."; //must be >= 0.";
		if (error=="" && (parseInt(axialLoadMax) > 0) && (isNaN(axialLoad) || parseInt(axialLoad) > parseInt(axialLoadMax))) error = "Maximum value for Axial Load is "+axialLoadMax+".";		
		if (error=="" && (speed=='' || isNaN(speed) || parseInt(speed) < 0))			error = "Speed must be >= 0.";
		if (error=="" && (isNaN(speed) || parseInt(speed) > parseInt(maxSpeed)))		error = "Maximum value for Speed is "+maxSpeed+".";
		if (error=="" && (isNaN(temperture) || parseInt(temperture) < 0))			error = "Tempeture must be > 0.";
		if (error=="" && (isNaN(temperture) || parseInt(temperture) > parseInt(maxTemp)))	error = "Maximum value for Temperture is "+maxTemp+".";		
		if (error != "") {
			alert(error);
			return false;
		}
		
		doCalculate();
		
	});
	
	
	$('#btnShowProducts').click(function(){
		if ($('#ropeGrade').val()==0) {
			alert('You have to select appropriate Rope Grade.');
			return false;
		}
	});

	// IE6?!?!?	
	// it's not working
	/*$.reject({
		paragraph1: 'Your browser is out of date, and may not be compatible with our website. On top of this, Internet Explorer 6 has a major security flaw that the Australian Government (as well as other countries around the world) has <a href="http://www.abc.net.au/news/stories/2010/01/19/2795684.htm" target="_blank">officially acknowledged</a>. A list of the most popular web browsers can be found below.',
		imagePath: newsite+'/images/browsers/',
		closeCookie: true
	});	*/

});



/*
 * Calculation 
 *
 */
function doCalculate() {
		
	var layoutID = ($('#layoutID').length > 0) ? $('#layoutID').val() : "00";
	var layouts = ["ntn", "srb"];		
	if (jQuery.inArray(layoutID, layouts) == -1) layoutID = "ntn";
	
	//if (layoutID != "ntn") layoutID = "00";
	//alert(layoutID);
	
	$('#results-wrapper').hide();
	$('#results').html('');		
	$('#calculator-params-to-print').html('');		
	$.ajax({						
		url: "/calculator-" + layoutID + ".php?" + 
			"productid=" + $("#id").val() + 
			"&radialLoad=" + $("#radialLoad").val() + 
			"&axialLoad=" + $("#axialLoad").val() +
			"&speed=" + $("#speed").val() +
			"&temperture=" + $("#temperture").val(),				 		
		success: function(jsonData) {			
			data = jQuery.parseJSON(jsonData);
			//alert(data[3].value);
			var results = //data[0].label + ': <strong>' + data[0].value + '</strong><br />'  + 
				data[1].label + ': <strong>' + data[1].value + '</strong><br />' +
				'<span style="color: #cc0000;">'+data[2].label + ': <strong>' + data[2].value + '</strong>'+'</span>' 
				//+'<br /><div id="debug-log">'+
				//'<span style="color: gray;">'+data[3].value + '</span><br />' + 
				//'<span style="color: gray;">'+data[4].value + '</span></div>'				
				;					 				
			$('#results').html('<h4>Calculator Results:</h4>' + results);
			
			$('#calculator-params-to-print').html('<br /><h4>Calculator:</h4>'+
			'Testing parameters:<br />'+
			'Radial Load: <strong>'+$("#radialLoad").val()+'kN</strong><br />'+ 
			'Axial Load: <strong>'+$("#axialLoad").val()+'kN</strong><br />'+
			'Speed: <strong>'+$("#speed").val()+'rpm</strong><br />'+
			'Temperture: <strong>'+$("#temperture").val()+'&deg;C</strong><br /><br />'+
			'Mininum Load Required:<br />'+results);			
			
			$('#results-wrapper').show();
			$('#share-this-calculator').attr('href', '/email?product='+$('#pe').val()+'&params='+$("#radialLoad").val()+'|'+$("#axialLoad").val()+'|'+$("#speed").val()+'|'+$("#temperture").val());
			
			$('#resultsWrapper').show();
//			$('#resultsWrapper').css('height', '100px');
//			$('#resultsWrapper').css('display', 'block');
//			$('#resultsWrapper').css('clear', 'both');
			//curvyCorners.adjust($('#resultsWrapper'), 'className', 'expanded');
			//curvyCorners.redraw();
		},
		error: function() {
			$('#results').html('');
			$('#calculator-params-to-print').html('');
			$('#results-wrapper').hide();
		}
	});
}

