/*  
COMMON SCRIPTS

Copyright Overlandia, S.L.
http://www.overlandia.com
*/


/* IE corrections */


$(document).ready(function() {
	if ( jQuery.browser.msie ) {
		buttonIEFix();
		if ( jQuery.browser.version == 8 ) {
			header3TabsIE8Fix();
		} else if ( jQuery.browser.version < 7 ) {
			pngToGif();
		}
	}
});

// IE -> input buttons doesn't change text color when mouse is over it
function buttonIEFix() {
	$('.button').mouseover(function() {
		$('input', this).addClass('link-hover');
	});
	$('.button').mouseout(function() {
		$('input', this).removeClass('link-hover');
	});
	return false;
}

// IE6 -> PNG images are replaced by GIF images (IE6 does not show the transparency of PNG images)
function pngToGif() {
	$(document).ready(function() {
		$('img').each(function() {
			imageUrl = $(this).attr('src');
			if ( imageUrl.substr(imageUrl.length-3, imageUrl.length) == 'png' ) {
				imageUrl = imageUrl.substr(0, imageUrl.length-3) + 'gif';
				$(this).attr('src', imageUrl);
			}
		});
	});
	return false;
}

// IE8 fix for the orange tabs
function header3TabsIE8Fix() {
	$('#header-3-tabs ul li').mouseover(function() {
		$('a .header-3-tabs-variable', this).css({'height':'0.8929em'});
		$('a .header-3-tabs-middle .header-3-tabs-middle-right', this).addClass('header-3-tabs-mouseover-button');
	});
	$('#header-3-tabs ul li').mouseout(function() {
		$('a .header-3-tabs-variable', this).css({'height':'0'});
		$('a .header-3-tabs-middle .header-3-tabs-middle-right', this).removeClass('header-3-tabs-mouseover-button');
	});
	return false;
}


/* Show/hide some HTML elements when javascript is working */


$(document).ready(function() {
	$('.jq-hide').hide();
	$('.jq-show').show();
});


/* ZoomText (zoom in/zoom out of the whole page) */


$(document).ready(function() {
	$('.zoom-text').click(function() {
		zoomText('body', $(this).attr('rel'));
	});
});

// Function to increment/decrement of the whole page dimensions
var defaultSizes = Array();
function zoomText(element, action) {

	// ----- Config - start ----- //
	var min=75 // Minimum size (percentage)
	var max=200 // Maximum size (percentage)
	var increment=12.5;// Increment/decrement value on each click (percentage) - 12.5% = 2px (exact)
	// ----- Config - end ----- //

	currentSize=convertDimensionTo($(element).css('font-size'), '%');

	if ( !defaultSizes[element] ) {
		defaultSizes[element] = currentSize;
	}

	increment=parseFloat(defaultSizes[element]*increment/100);

	if( action=='reset' ){
		$(element).css({'font-size':defaultSizes[element]+'%'});
	} else if( action=='more' && ((currentSize+increment)*100/defaultSizes[element] <= max )){
		$(element).css({'font-size':currentSize+increment+'%'});
	} else if( action=='less' && ((currentSize-increment)*100/defaultSizes[element] >= min )){
		$(element).css({'font-size':currentSize-increment+'%'});
	}

	return false;

}


/* Hovertip */


// Hovertip (jQuery)
$(document).ready(function() {
	$('.hovertip').hovertip();
	$('#hovertip').addClass('border-radius-16-10');
	$('#hovertip').addClass('box-shadow-16-0-5-20');
});


/* ScrollTo */


// ScrollTo (jQuery)
$(document).ready(function() {
	$('#to-top').hide();
	$('#to-top').click(function() {
		$.scrollTo(0, 2000, {axis:'y', easing:'easeOutBounce'});
		return false;
	});
	$('.scrollto').click(function() {
		$.scrollTo($(this).attr('href'), 2000, {axis:'y', easing:'easeInOutCubic'});
		return false;
	});
	$(window).scroll(function() {
		if ( $(window).scrollTop() > 50 ) {
			$('#to-top').fadeIn();
		} else {
			$('#to-top').fadeOut();
		}
	});
});


/* Warning popup */


/***************************/
//@Author: Adrian "yEnS" Mato Gondelle
//@website: www.yensdesign.com
//@email: yensamg@gmail.com
//@license: Feel free to use it, but keep this credits please!					
/***************************/

$(document).ready(function() {

	// Close button animation
	var warningPopupCloseImgMouseOut = $('#warning-popup-close img').attr('src');
	var warningPopupCloseImgMouseOver = '';
	var tmp = warningPopupCloseImgMouseOut.split('/');
	for (i=0; i<tmp.length-1; i++){
		warningPopupCloseImgMouseOver = warningPopupCloseImgMouseOver + tmp[i] + '/';
	}
	warningPopupCloseImgMouseOver = warningPopupCloseImgMouseOver + 'warning-popup-close-mouseover.gif';
	$('#warning-popup-close img').mouseover(function() {  
		$(this).attr('src', warningPopupCloseImgMouseOver);
	});
	$('#warning-popup-close img').mouseout(function() {  
    	$(this).attr('src', warningPopupCloseImgMouseOut);
	});

	// Closing popup - Click the x event
	$('#warning-popup-close').click(function() {
		unloadWarningPopup();
	});
	// Closing popup - Click out event
	$('#warning-popup-background').click(function() {
		unloadWarningPopup();
	});
	// Closing popup - Press escape event
	$(document).keyup(function(e){
		if ( e.keyCode==27 && popupStatus ){
			unloadWarningPopup();
		}
	});

	// centering popup on resize
	$(window).resize(function() {
		if ( popupStatus ){
			centerWarningPopup();
		}
	});

	defaultWarningPopupWidth = parseInt($('#warning-popup').css('width'))/parseInt($('body').css('font-size'))*16/14+'em';

});

// "false" means disabled, "true" means enabled
var popupStatus = false;
// Loading popup
function loadWarningPopup(text, title, width, height){

	$('#warning-popup-text').html(text);
	if ( title ) {
		$('#warning-popup-title').html(title);
		$('#warning-popup-title').show();
	} else {
		$('#warning-popup-title').hide();
	}

	$('#warning-popup').css({'max-width':(($(window).width()/parseInt($('body').css('font-size'))*16/14)-3)+'em'});
	$('#warning-popup-text').css({'max-height':(($(window).height()/parseInt($('body').css('font-size'))*16/14)-(title?8:5))+'em'});

	if (width)
		$('#warning-popup').css({'width':( parseInt(width)*parseInt($('body').css('font-size'))*14/16 < $(window).width()-(3*parseInt($('body').css('font-size'))) ? width : (($(window).width()/parseInt($('body').css('font-size'))*16/14)-3)+'em' )});
	if (height)
		$('#warning-popup-text').css({'height':( parseInt(height)*parseInt($('body').css('font-size'))*14/16 < $(window).height()-((title?8:5)*parseInt($('body').css('font-size'))) ? height : (($(window).height()/parseInt($('body').css('font-size'))*16/14)-(title?8:5))+'em' )});

	centerWarningPopup();

	if( !popupStatus ){
		$('#warning-popup-background').css({'opacity': '0.7'});
		$('#warning-popup-background').fadeIn('slow');
		$('#warning-popup').fadeIn('slow');
		popupStatus = true;
	}

	return false;

}

// Disabling popup
function unloadWarningPopup() {

	if( popupStatus ){
		$('#warning-popup-background').fadeOut('slow');
		$('#warning-popup').fadeOut('slow');
		popupStatus = false;
		setTimeout("$('#warning-popup').css({'width':defaultWarningPopupWidth});", 1000);
		setTimeout("$('#warning-popup-text').css({'height':'auto'});", 1000);
	}

	return false;

}

// Centering popup
function centerWarningPopup() {

	var windowWidth = $(window).width();
	var scrollLeft = $(window).scrollLeft();
	var windowHeight = $(window).height();
	var scrollTop = $(window).scrollTop();
	var popupHeight = $('#warning-popup').height();
	var popupWidth = ( $('#warning-popup').width() ? $('#warning-popup').width() : parseInt($('#warning-popup').css('width')) );

	$('#warning-popup').css({
		'position': 'absolute',
		'top': (windowHeight/2)+scrollTop-(popupHeight/2),
		'left': (windowWidth/2)+scrollLeft-(popupWidth/2)
	});

	if ( jQuery.browser.msie && jQuery.browser.version < 7 ) {
		$('#warning-popup-background').css({'width': $('body').width()});
		$('#warning-popup-background').css({'height': $('body').height()});
	}

	return false;

}


/* Really Simple Validation (RSV) */


// RSV (jQuery)
function showRSVError(f, errorInfo) {
	for ( var i=0; i<f.length; i++ ) {
		$(f[i]).removeClass('form-field-error');
		if ( $(f[i]).attr('id') != '' ) {
			$('#' + $(f[i]).attr('id') + '-error').hide();
		}
	}
	if ( errorInfo.length == 0 ) {
		return true; // "true" if there were no errors
	} else {
		var text = ( errorInfo.length == 1 ? '' : '<ul>' );
		for ( var i=0; i<errorInfo.length; i++ ) {
			text = text + ( errorInfo.length == 1 ? '' : '<li>' ) + errorInfo[i][1] + ( errorInfo.length == 1 ? '' : '</li>' );
			$(errorInfo[i][0]).addClass('form-field-error');
			$('#' + $(errorInfo[i][0]).attr('id') + '-error').show();
		}
		text = text + ( errorInfo.length == 1 ? '' : '</ul>' );
		loadWarningPopup(text);
		return false;
	}
	return false;
}


/* Miscellaneous */


// Expansion of the framework to include regular expressions in the jQuery selectors
jQuery.expr[':'].regex = function(elem, index, match) {
	var matchParams = match[3].split(','),
		validLabels = /^(data|css):/,
		attr = {
			method: matchParams[0].match(validLabels) ?
				matchParams[0].split(':')[0] : 'attr',
			property: matchParams.shift().replace(validLabels,'')
		},
		regexFlags = 'ig',
		regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
	return regex.test(jQuery(elem)[attr.method](attr.property));
}

// Conversion from px or % or pt or em to px or % or pt or em
function convertDimensionTo(value, unit) {

	if ( value.substr(value.length-2) == 'px' ) {
		return parseFloat(value) * ( unit == 'px' ? 1 : ( unit == '%' ? 6.25 : ( unit == 'pt' ? 0.75 : ( unit == 'em' ? 0.0625 : 1 ) ) ) );
	} else if ( value.substr(value.length-1) == '%' ) {
		return parseFloat(value) * ( unit == 'px' ? 0.16 : ( unit == '%' ? 1 : ( unit == 'pt' ? 0.12 : ( unit == 'em' ? 0.01 : 1 ) ) ) );
	} else if ( value.substr(value.length-2) == 'pt' ) {
		return parseFloat(value) * ( unit == 'px' ? 1.33333333 : ( unit == '%' ? 8.33333333 : ( unit == 'pt' ? 1 : ( unit == 'em' ? 0.08333333 : 1 ) ) ) );
	} else if ( value.substr(value.length-2) == 'em' ) {
		return parseFloat(value) * ( unit == 'px' ? 16 : ( unit == '%' ? 100 : ( unit == 'pt' ? 12 : ( unit == 'em' ? 1 : 1 ) ) ) );
	} else {
		return false;
	}

}

// Function to check and correct the numerical values of input text fields
function checkNumericValue(value, decimals, defaultValue, nanValueMsg, minValue, minValueMsg, maxValue, maxValueMsg) {

	if ( typeof decimals == 'undefined' ) decimals=0;
	if ( typeof defaultValue == 'undefined' ) defaultValue=0;
	if ( typeof minValue == 'undefined' ) minValue='no';
	if ( typeof maxValue == 'undefined' ) maxValue='no';

	value = value.replace(',', '.');
	value = value.replace('\'', '.');

	value = parseInt(Math.round(value*Math.pow(10, decimals)))/Math.pow(10, decimals).toFixed(decimals);

	if ( isNaN(value) ) {
		if ( nanValueMsg ) {
			loadWarningPopup(nanValueMsg);
		}
		value = defaultValue;
	} else {
		if ( minValue != 'no' && value < minValue ) {
			if ( minValueMsg ) {
				loadWarningPopup(minValueMsg);
			}
			value = minValue;
		}
		if ( maxValue != 'no' && value > maxValue ) {
			if ( maxValueMsg ) {
				loadWarningPopup(maxValueMsg);
			}
			value = maxValue;
		}
	}

	return value;

}

// Number of decimals and thousands and decimal separators
function numberFormat(value, decimals, decimalPoint, thousandsSeparator) {

	if ( !decimals ) {
		decimals=0;
	} else {
		decimals=parseInt(decimals);
	}

	value = '' + value;
	value = value.replace(',', '.');
	value = value.replace('\'', '.');

	value = (Math.round(parseFloat(value)*Math.pow(10, decimals))/Math.pow(10, decimals)).toFixed(decimals);

	valueInteger = ( decimals ? value.substring(0, value.length-(decimals+1)) : value );
	valueDecimals = ( decimals ? value.substring(value.length-(decimals), value.length) : '' );

	if ( decimals && decimalPoint ) {
		valueDecimals = valueDecimals.replace('.', decimalPoint);
	}

	if ( parseInt(valueInteger) > 1000 && thousandsSeparator ) {
		var aux = valueInteger;
		valueInteger = '';
		for( var i=1; i<=aux.length; i++ ) {
			valueInteger = aux.substring(aux.length-(i-1), aux.length-(i)) + valueInteger;
			if ( !(i%3) && i<aux.length ) {
				valueInteger = thousandsSeparator + valueInteger;
			}
		}

	}

	return valueInteger + ( decimals && decimalPoint ? decimalPoint : '' ) + valueDecimals;

}

// Submit form links
$(document).ready(function() {
	$('.submit-form').click(function() {
		var classes = $(this).attr('class').split(' ');
		for(var i=0; i<classes.length; i++) {
			if ( ( formIDPos = classes[i].indexOf('submit-form-') ) != -1 ) {
				$('#' + classes[i].substr(formIDPos+12)).submit();
			}
		}
	});
});

// Search box
$(document).ready(function() {
	$('#search-box-input-text').focus(function() {
		if($(this).attr('value')=='Buscar...') $(this).attr('value', '');
		$('#header-3-search-box-background-onfocus').fadeIn();
	});
	$('#search-box-input-text').blur(function() {
		if($(this).attr('value')=='') $(this).attr('value', 'Buscar...');
		$('#header-3-search-box-background-onfocus').fadeOut();
	});
});

// Right sidebar main menu
$(function(){
	$('#sidebar-category-menu .sidebar-menu-box-title div h3 a').click(function(event) {
		var elem = $(this).parent('h3').parent('div').parent('div').next();
		if ( elem.hasClass('sidebar-menu-box-content') ) { /* Omit manufacturers link */
			event.preventDefault();
			$('#sidebar-category-menu .sidebar-menu-box-content:visible').not(elem).slideUp();
			elem.slideToggle();
			return false;
		}
	});
});

