var background_timer=null;
var background_current_image=0;
var background_total_images=0;
var product_info_timer=null;

$(document).ready(function() {
	route = getURLVar('route');
	
	if (!route) {
		$('#tab_home').addClass('selected');
	} else {
		part = route.split('/');
		
		if (route == 'common/home') {
			$('#tab_home').addClass('selected');
		} else if (route == 'account/login') {
			$('#tab_login').addClass('selected');	
		} else if (part[0] == 'account') {
			$('#tab_account').addClass('selected');
		} else if (route == 'checkout/cart') {
			$('#tab_cart').addClass('selected');
		} else if (part[0] == 'checkout') {
			$('#tab_checkout').addClass('selected');
		} else {
			$('#tab_home').addClass('selected');
		}
	}
	
	$('.draggable').draggable();
	
	$(".wrap").css({'position':'fixed', 'right':'25px', 'top':$(window).height()*.9-250});
	

	$('#search input').keydown(function(e) {
		if (e.keyCode == 13) {
			moduleSearch();
		}
	});
	$('.switcher').bind('click', function() {
		$(this).find('.option').slideToggle('fast');
	});
	$('.switcher').bind('mouseleave', function() {
		$(this).find('.option').slideUp('fast');
	}); 
	
	
	if($('#logo_class').val()!=undefined){
		$('body').addClass($('#logo_class').val());	
	}
	else{
		$('body').addClass('black');	
	}
	
	$('#category_list>li ul li.current').each(function(){
		$(this).closest('ul').show().parent().addClass('current');
	});
	
	$('#category_list>li>a').click(function(){
		if($(this).parent().find('.children li').size()>0){
			$('#category_list>li ul').hide();
			$('#category_list>li').removeClass('current');
			
			$(this).closest('li').find('ul').show();
			$(this).closest('li').addClass('current');
			
			if($('#background').size()>0){
				$('body').removeClass('black');
				$('body').addClass('white');
				$('#hider').hide();
				$('#newsletter_container').hide();
				$('#background .visible_image img').attr('src',$(this).closest('li').find('.image img').attr('src'));
				$('#background .hidden .width').html($(this).closest('li').find('.image img').attr('width'));
				$('#background .hidden .height').html($(this).closest('li').find('.image img').attr('height'));
				$('#background').show();
				$('.corner_legend .text').html($(this).html());
				$('.corner_legend').show();
				background_resize();
			}
			return false;
		}
	});

	$('.cart_remove').live('click', function () {
		if (!confirm('<?php echo $text_confirm; ?>')) {
			return false;
		}
		id=this.id;
		$(this).removeClass('cart_remove').addClass('cart_remove_loading');
		$.ajax({
			type: 'post',
			url: 'index.php?route=module/cart/callback',
			dataType: 'html',
			data: 'remove=' + this.id,
			success: function (html) {
				window.location.reload();
			}
		});
	});
	
	$('.product_info').delay(750).fadeOut();
	$('.fullsize_image').hover(
		function(){
			clearTimeout(product_info_timer);
			$('.product_info').show();
		},
		function(){
			product_info_timer=setTimeout("$('.product_info').stop(true,true).fadeOut();",300);
		}
	);
	$('.product_info').hover(
		function(){
			clearTimeout(product_info_timer);
		},
		function(){
			product_info_timer=setTimeout("$('.product_info').stop(true,true).fadeOut();",100);
		}
	);

	//Window resize event
	background_resize();
	$(window).resize(function(){
		if($('#background').size()>0){
			background_resize();
		}
	});
	
	//Super Fader
	/*
	if($('#background').size()>0){
		background_total_images=$('#background li').size();
		background_current_image = Math.floor(Math.random()*background_total_images)
		background_fade_image();
		background_timer=setInterval('background_fade_image();',5000);
	}
	*/
});

function background_fade_image(){
	source=$('#background li:eq('+background_current_image+') .source').html();
	width=parseInt($('#background li:eq('+background_current_image+') .width').html());
	height=parseInt($('#background li:eq('+background_current_image+') .height').html());
	ratio=width/height;
	window_ratio=$(window).width()/$(window).height();
	
	if(ratio>window_ratio){
		$('#background .hidden_image').html($('<img/>').attr('src',source).height($(window).height()).css({'margin-left':($(window).width()-ratio*$(window).height())/2}));
	}
	else{
		$('#background .hidden_image').html($('<img/>').attr('src',source).width($(window).width()));
	}
	
	$('#background .hidden_image').fadeIn();
	$('#background .visible_image').fadeOut(function(){
		$('#background .visible_image').html($('#background .hidden_image img').clone()).show();
		$('#background .hidden_image').hide();
	});
	
	if(background_current_image<background_total_images-1){
		background_current_image++
	}
	else{
		background_current_image=0;
	}
}
function background_resize(){
	source=$('#background li:eq('+background_current_image+') .source').html();
	width=parseInt($('#background li:eq('+background_current_image+') .width').html());
	height=parseInt($('#background li:eq('+background_current_image+') .height').html());
	ratio=width/height;
	window_ratio=$(window).width()/$(window).height();
	
	if(ratio>window_ratio){
		$('#background .visible_image img').height($(window).height());
		$('#background .visible_image img').width(ratio*$(window).height());
	}
	else{
		$('#background .visible_image img').width($(window).width());
		$('#background .visible_image img').height($(window).width()/ratio);
	}
}

function bookmark(url, title) {
	if (window.sidebar) { // firefox
    window.sidebar.addPanel(title, url, "");
	} else if(window.opera && window.print) { // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} else if(document.all) {// ie
   		window.external.AddFavorite(url, title);
	}
}

function moduleSearch() {
	url = 'index.php?route=product/search';
	
	var filter_keyword = $('#filter_keyword').attr('value')
	
	if (filter_keyword) {
		url += '&keyword=' + encodeURIComponent(filter_keyword);
	}
	
	var filter_category_id = $('#filter_category_id').attr('value');
	
	if (filter_category_id) {
		url += '&category_id=' + filter_category_id;
	}
	
	location = url;
}

function validate_newsletter(){
	
	if($('#newsletter_name').val()=='NOMBRE'){
		alert('Nombre es un campo obligatorio.');
		$('#newsletter_name').focus();
		return false;
	}
	if(!isValidEmailAddress($('#newsletter_email').val())){
		alert('Dirección de correo electrónico no válida.');
		$('#newsletter_email').focus();
		return false;
	}
	if($('#newsletter_tipo').val()==''){
		alert('Tipo de newsletter es un campo obligatorio.');
		return false;
	}
	if(!$('#newsletter_accept').is(':checked')){
		alert('Debes acpetar las condiciones');
		return false;
	}
	
	$.ajax({
		type: 'post',
		url: 'index.php?route=information/newsletter/register',
		data: 'nombre=' + $('#newsletter_name').val() +'&email=' + $('#newsletter_email').val()+'&tipo=' + $('#newsletter_tipo').val(),
		success: function (response) {
			//console.log(response);
			$('.newsletter_content').hide().html('<div class="balloon_icon"></div><div class="title">Gracias!</div>').fadeIn();
		}
	});
}

function validate_recambios(){

	if($('#recambios_name').val()=='NOMBRE'){
		alert('Nombre es un campo obligatorio.');
		$('#recambios_name').focus();
		return false;
	}
	if(!isValidEmailAddress($('#recambios_email').val())){
		alert('Dirección de correo electrónico no válida.');
		$('#recambios_email').focus();
		return false;
	}
	if($('#recambios_tel').val()=='TELÉFONO'){
		alert('Teléfono es un campo obligatorio.');
		$('#recambios_tel').focus();
		return false;
	}

	if($('#recambios_marca').val()==''){
		alert('Marca es un campo obligatorio.');
		return false;
	}
	if($('#recambios_modelo').val()==''){
		alert('Modelo es un campo obligatorio.');
		return false;
	}
	
	$('.newsletter_content').hide();
	$.ajax({
		type: 'post',
		url: 'index.php?route=information/recambios/sendmail',
		data: 'nombre=' + $('#recambios_name').val() +'&email=' + $('#recambios_email').val()+'&tel=' + $('#recambios_tel').val()+'&marca=' + $('#recambios_marca').val()+'&modelo=' + $('#recambios_modelo').val()+'&num=' + $('#recambios_num').val()+'&ano=' + $('#recambios_ano').val()+'&mensaje=' + $('#enquiry').val(),
		success: function (response) {
			//console.log(response);
			$('.newsletter_content').hide().html('<div class="balloon_icon"></div><div class="title">Gracias!<br/>En breve nos comunicaremos contigo.</div>').fadeIn();
		}
	});
}

function validate_contact_form(){
	if($('#newsletter_name').val()=='NOMBRE'){
		alert('Nombre es un campo obligatorio.');
		$('#newsletter_name').focus();
		return false;
	}
	if(!isValidEmailAddress($('#newsletter_email').val())){
		alert('Dirección de correo electrónico no válida.');
		$('#newsletter_email').focus();
		return false;
	}
}

function isValidEmailAddress(emailAddress) {
 		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
 		return pattern.test(emailAddress);
}

function getURLVar(urlVarName) {
	var urlHalves = String(document.location).toLowerCase().split('?');
	var urlVarValue = '';
	
	if (urlHalves[1]) {
		var urlVars = urlHalves[1].split('&');

		for (var i = 0; i <= (urlVars.length); i++) {
			if (urlVars[i]) {
				var urlVarPair = urlVars[i].split('=');
				
				if (urlVarPair[0] && urlVarPair[0] == urlVarName.toLowerCase()) {
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	
	return urlVarValue;
} 

function focus_placeholder(container, text){
	if($(container).val()==text){
		$(container).val('');
	}
}
function blur_placeholder(container, text){
	if($(container).val()==''){
		$(container).val(text);
	}
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init(); 

