
var productos = new Array();

// Primer boton de cotizar que despliega el show
function cotizar ( )
{
	if (verificar_datos())
	{
		// Hacemos aparecer la caja
		$('#pedido_trigger').slideUp('normal', function() {
			$('#pedido_data').slideDown('fast', function() {
				agregar_producto();
				setTimeout( function(){
					$('#contacto_data').slideDown('slow', function(){
						setTimeout( function() { $('#Nombre').focus(); }, 100);
					});
				}, 1500);
			});
		});
	}
}

// Función que actualmente hace el post luego de verificar 
// la integridad del pedido. Recemos que todos los leads tengan js.
function ejecutar ( )
{
	// Contamos los elementos para saber si tenemos un pedido
	// y armamos los hidden con las caracteristicas del pedido.
	var elementos = 0;
	$('#hidden_data').html('');
	for (i in productos)
	{
		elementos++;
		$('#hidden_data').append('<input type="hidden" name="productos[]" value="'+ i +'='+ productos[i] +'" />');
	}
	
	// Procesamos el pedido...
	if (elementos > 0)
	{
		// Chequeamos el nombre
		if ($('input#nombre').val().length < 3)
		{
			alert('Por favor indicanos tu nombre');
			$('input#nombre').focus();
			return false;
		}
		
		// Chequeamos un mail válido
		if (!$('input#Mail').val().match( /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ ))
		{
			alert('Por favor indicanos un mail correcto a donde podamos enviarte la cotización');
			$('input#Nombre').focus();
			return false;
		}
		// Chequeamos el teléfono
		if ($('input#telefono').val().length < 5)
		{
			alert('Por favor indicanos un teléfono a donde podamos ubicarte para revisar algún particular de tu cotización');
			$('input#telefono').focus();
			return false;
		}
		
		// Está todo ok, posteamos.
		return true;
	}
	else
	{
		alert('Tu cotización está vacía. Por favor agregá algunas puertas blindadas.');
		$('#ancho').focus();
		return false;
	}
	
	return true;
}

// Verifica los datos al agregar una cortina nueva
function verificar_datos ( )
{
	if ($('#ancho').val() != '' && $('#alto').val() != '' && ( $('#tela_blackout').attr('checked') || $('#tela_sunscreen').attr('checked') ) )
		return true;
	else
	{
		alert('Por favor completá los datos de la puerta blindada');
		return false;
	}
}

// Hacemos todos los reemplazos para que los cientos se conviertan
// en unidades con decimales, y limpiamos en general.
function sanar_medidas ( )
{
	if ($('#ancho').val() != '')
	{
		$('#ancho').val( $('#ancho').val().replace( "," , "." ).replace( /[^0-9\.]+/g , '') );
		if ($('#ancho').val() >= 10) $('#ancho').val( $('#ancho').val() / 100 );
		if (! $('#ancho').val().match(/\./)) { $('#ancho').val( $('#ancho').val() + '.0' ); }
	}
	if ($('#alto').val() != "")
	{
		$('#alto').val( $('#alto').val().replace( "," , "." ).replace( /[^0-9\.]+/g , '') );
		if ($('#alto').val() >= 10) $('#alto').val( $('#alto').val() / 100 );
		if (! $('#alto').val().match(/\./)) { $('#alto').val( $('#alto').val() + '.0' ); }
	}
}

// Agrega un producto del formulario, o el especificado
// por $id si es llamada usando el botón + del pedido.
function agregar_producto ( id )
{
	if (! id)
	{
		// Sanamos las medidas
		sanar_medidas();
		
		// Verificamos datos
		if (!verificar_datos())
			return false;
		
		// Agregamos al array y al html
		var tela  = $('#tela_blackout').attr('checked') ? '' : '';
		var ancho = parseInt($('#ancho').val() * 100);
		var alto  = parseInt($('#alto').val() * 100);
		var id = tela + '_' + ancho + '_' + alto;
	}
	
	if (!productos[ id ])
	{
		// Agregamos el producto por primera vez
		productos[ id ] = 1;
		$('#productos_nuevos').append(
			'<div class="producto ui-corner-all" id="' + id + '" style="display:none">' +
			'  <span class="quitar"><a class="ui-corner-all" href="javascript:;" onclick="quitar_producto(\'' + id + '\')">-</a></span>' +
			'  <span class="agregar"><a class="ui-corner-all" href="javascript:;" onclick="agregar_producto(\'' + id + '\')">+</a></span>' +
			'  <span class="cantidad ui-corner-all">' + productos[id] + '</span>'+
			'  <span class="nombre">' + (tela == 'blackout' ? 'Blackout' : 'Medidas' ) + '</span>' +
			'  <span class="medidas"><span class="numero">' + ancho + '</span><small> x </small><span class="numero">' + alto + '</span> <small>cm</small></span>' +
			'</div>'
		);
		$('#' + id).fadeIn('slow');
	}
	else
	{
		// El producto ya existe, sumamos uno a la cantidad
		productos[ id ]++;
		$('#' + id + ' > span.cantidad').html( productos[ id ] )
	}
	
	// Reseteamos los campos
	$('#alto').val('');
	$('#ancho').val('');
}

// Remueve un producto del array de productos, y adicionalmente lo borra
// del HTML si era el último de la lista.
function quitar_producto ( id )
{
	productos[ id ]--;
	if (productos[ id ] == 0)
	{
		// Removemos el html
		$( '#' + id ).fadeOut('slow', function() { $( '#' + id ).remove(); } );
		delete productos[ id ];
	}
	else
	{
		// Restamos uno en el codigo
		$('#' + id + ' > span.cantidad').html( productos[ id ] );
	}
}

$(document).ready(function()
{
	// Ocultamos el banner de conversiones de google
	$('.hiddenConversion').css('visibility','hidden');
	
	// Sanamos medidas cuando desenfocamos los campos
	$('#ancho').change( function(){ sanar_medidas(); } );
	$('#alto').change( function(){ sanar_medidas(); } );
	
	// Redondeamos bordes en explorer
	DD_roundies.addRule('.ui-corner-all', '4px');
	DD_roundies.addRule('.ui-corner-all-big', '10px');
	
	// Onda para los botones
	$('.boton').addClass('ui-button ui-state-default ui-corner-all')
		.hover( function(){ $(this).addClass('ui-state-hover'); }, function(){ $(this).removeClass('ui-state-hover'); } )
		.mousedown(function(){ $(this).addClass("ui-state-active"); })
		.mouseup(function(){ $(this).removeClass("ui-state-active"); });
	
	// We only want these styles applied when javascript is enabled
	$('div.navigation').css({'width' : '500px'});
	$('div.content').css('display', 'block');
	
	// Initially set opacity on thumbs and add
	// additional styling for hover effect on thumbs
	var onMouseOutOpacity = 0.67;
	$('#thumbs ul.thumbs li').opacityrollover({
		mouseOutOpacity:   onMouseOutOpacity,
		mouseOverOpacity:  1.0,
		fadeSpeed:         'fast',
		exemptionSelector: '.selected'
	});
	
	// Enable toggling of the caption
	var captionOpacity = 0.7;
	$('#captionToggle a').click(function(e) {
		var link = $(this);
		
		var isOff = link.hasClass('off');
		var removeClass = isOff ? 'off' : 'on';
		var addClass = isOff ? 'on' : 'off';
		var linkText = isOff ? 'Hide Caption' : 'Show Caption';
		captionOpacity = isOff ? 0.7 : 0.0;

		link.removeClass(removeClass).addClass(addClass).text(linkText).attr('title', linkText);
		$('#caption span.image-caption').fadeTo(1000, captionOpacity);
		
		e.preventDefault();
	});
	
	// Initialize Advanced Galleriffic Gallery
	var gallery = $('#thumbs').galleriffic({
		delay:                     5000,
		numThumbs:                 15,
		preloadAhead:              10,
		enableTopPager:            false,
		enableBottomPager:         false,
		maxPagesToShow:            7,
		imageContainerSel:         '#slideshow',
		controlsContainerSel:      '#controls',
		captionContainerSel:       '#caption',
		loadingContainerSel:       '#loading',
		renderSSControls:          false,
		renderNavControls:         false,
		enableKeyboardNavigation:  false,
		playLinkText:              'Play Slideshow',
		pauseLinkText:             'Pause Slideshow',
		prevLinkText:              '&lsaquo; Previous Photo',
		nextLinkText:              'Next Photo &rsaquo;',
		nextPageLinkText:          'Next &rsaquo;',
		prevPageLinkText:          '&lsaquo; Prev',
		enableHistory:             false,
		autoStart:                 true,
		syncTransitions:           true,
		defaultTransitionDuration: 900,
		onSlideChange:             function(prevIndex, nextIndex) {
			// 'this' refers to the gallery, which is an extension of $('#thumbs')
			this.find('ul.thumbs').children()
				.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
				.eq(nextIndex).fadeTo('fast', 1.0);
		},
		onTransitionOut:           function(slide, caption, isSync, callback) {
			slide.fadeTo(this.getDefaultTransitionDuration(isSync), 0.0, callback);
			caption.fadeTo(this.getDefaultTransitionDuration(isSync), 0.0);
		},
		onTransitionIn:            function(slide, caption, isSync) {
			var duration = this.getDefaultTransitionDuration(isSync);
			slide.fadeTo(duration, 1.0);
			
			// Position the caption at the bottom of the image and set its opacity
			var slideImage = slide.find('img');
			caption.width(slideImage.width())
				.css({
					'bottom' : Math.floor((slide.height() - slideImage.outerHeight()) / 2) - 2,
					'left' : Math.floor((slide.width() - slideImage.width()) / 2) + slideImage.outerWidth() - slideImage.width() 
				})
				.fadeTo(duration, captionOpacity);
		},
		onPageTransitionOut:       function(callback) {
			this.fadeTo('fast', 0.0, callback);
		},
		onPageTransitionIn:        function() {
			this.fadeTo('fast', 1.0);
		}
		
	});
	// End galleriffic
	
});


