$().ready(function() {

	// Selects dependientes tipos, inicio **********************
        $("#bloque").change(function(event){
            var id = $("#bloque").find(':selected').val();
            $("#familia").load('../includes/genera_select.php?id='+id);	// Los archivos genera_select deben estar en el mismo directorio que el index.php
        });
        $("#familia").change(function(event){
            var id = $("#familia").find(':selected').val();
            $("#categoria_id").load('../includes/genera_select.php?id='+id);
        });
        $("#categoria_id").change(function(event){
            var id = $("#categoria_id").find(':selected').val();
            $("#producto_id").load('../includes/genera_producto.php?id='+id);
        });
	// Selects dependientes tipos, fin *************************


	// GESTIONAR - Actualizar precios, inicio **********************
		$('#publico_tpc').blur(function(){		// blur (al abandonar el campo), se podria poner change

			var costes = calcular_precio_coste();

			var coste = costes[0];
//alert(coste);

			var netos = calcular_precios_venta(coste);
//alert(netos[0]+' '+netos[1]+' '+netos[2]+' '+netos[3]);
			var costein = $.formatNumber(costes[0], {format:"#,###.00", locale:"us"});
			var costeii = $.formatNumber(costes[1], {format:"#,###.00", locale:"us"});
			var neto_tiendas = $.formatNumber(netos[0], {format:"#,###.00", locale:"us"});
			var neto_tiendasii = $.formatNumber(netos[1], {format:"#,###.00", locale:"us"});
			var neto_publico = $.formatNumber(netos[2], {format:"#,###.00", locale:"us"});
			var neto_publicoii = $.formatNumber(netos[3], {format:"#,###.00", locale:"us"});

			$("#coste_in").html(costein);
			$('#coste_ii').html(costeii);
			$("#pvn_tiendas_in").html(neto_tiendas);
			$('#pvn_tiendas_ii').html(neto_tiendasii);
			$("#pvn_publico_in").html(neto_publico);
			$('#pvn_publico_ii').html(neto_publicoii);

		});
	// GESTIONAR - Actualizar precios, fin *************************


	// GESTIONAR - Calcular margen equivalente, inicio **********************
		$('#pvp_reg').blur(function(){		// blur (al abandonar el campo), se podria poner change
			// Variables de entrada
				var pvp_reg		= parseFloat($('#pvp_reg').get(0).value);
				var iva_ir		= parseFloat($('#iva_ir').get(0).value);

			// Variable de salida
				var margen		= 12.34;

			// Calculos
				var costes		= calcular_precio_coste();
				var coste		= costes[0];
//alert(coste);
				var	reg_neto	= parseInt(     pvp_reg / ( (100+iva_ir)/100 )     * 100 + 0.5     )/100;
				var margen		= parseInt( (reg_neto - coste) / coste * 100 * 100 + 0.5 ) / 100;

			$('#margen_equiv').html(margen);
		});
	// GESTIONAR - Calcular margen equivalente, fin *************************


	// Validate, inicio *************************
		$("#commentForm").validate();
	// Validate, fin ****************************


	// Garage door, inicio ----------------------------------------------------------------

		// Set css in Firefox (Required to use the backgroundPosition js)
			$('#shutter1').css({backgroundPosition: '0px 0px'});
			$('#shutter2').css({backgroundPosition: '0px 0px'});
			$('#shutter3').css({backgroundPosition: '0px 0px'});
			$('#shutter4').css({backgroundPosition: '0px 0px'});
			$('#shutter5').css({backgroundPosition: '0px 0px'});
			$('#shutter6').css({backgroundPosition: '0px 0px'});
			$('#shutter7').css({backgroundPosition: '0px 0px'});
			$('#shutter8').css({backgroundPosition: '0px 0px'});
	
		// Animate the shutter  
			$(".link").hover(function(){
				  $(this).parent().animate({backgroundPosition: '(0px -100px)'}, 500 );
				}, function() {
				  $(this).parent().animate({backgroundPosition: '(0px 0px)'}, 500 );
			}); 

	// Garage door, fin -------------------------------------------------------------------



	// Scroll animado, inicio ********************************
		$("a.scroll").click(function () {
		var elementClick = $(this).attr("href");
		var destination = $(elementClick).offset().top;
		$("body").animate({ scrollTop: destination}, 1000 );
		return false;
		});
	// Scroll animado, fin ***********************************



/*
	$("#recordClientPhone").mask("(999) 999-9999");
	$("#recordClientPhoneAlt").mask("(999) 999-9999");
	$("#recordClientZip").mask("99999");
	$("#recordPropertyZip").mask("99999");	
	$("#recordPurchaseZip").mask("99999");	
*/
	// add * to required field labels
	$('label.required').append('&nbsp;<strong>*</strong>&nbsp;');
 
	// accordion functions
	var accordion = $("#stepForm").accordion(); 
	var current = 0;
	
	$.validator.addMethod("pageRequired", function(value, element) {
		var $element = $(element)
		function match(index) {
			return current == index && $(element).parents("#sf" + (index + 1)).length;
		}
		if (match(0) || match(1) || match(2)) {
			return !this.optional(element);
		}
		return "dependency-mismatch";
	}, $.validator.messages.required)
	
	var v = $("#cmaForm").validate({
		errorClass: "warning",
		onkeyup: false,
		onblur: false,
		submitHandler: function() {
//			alert("Submitted, thanks!");
			form.submit();
		}
	});
	
	// back buttons do not need to run validation
	$("#sf2 .prevbutton").click(function(){
		accordion.accordion("activate", 0);
		current = 0;
	}); 
	$("#sf3 .prevbutton").click(function(){
		accordion.accordion("activate", 1);
		current = 1;
	}); 
	// these buttons all run the validation, overridden by specific targets above
	$(".open2").click(function() {
	  if (v.form()) {
	    accordion.accordion("activate", 2);
	    current = 2;
	  }
	});
	$(".open1").click(function() {
	  if (v.form()) {
	    accordion.accordion("activate", 1);
	    current = 1;
	  }
	});
	$(".open0").click(function() {
	  if (v.form()) {
	    accordion.accordion("activate", 0);
	    current = 0;
	  }
	});





	$("#myForm").validate();


// Autocomplete, inicio
		function log(event, data, formatted) {
			$('<li>').html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result");
		}
		
		function formatItem(row) {
			return row[0] + " (<strong>id: " + row[1] + "</strong>)";
		}
		function formatResult(row) {
			return row[0].replace('/(<.+?>)/gi', '');
		}

		$("#buscar_texto").autocomplete("../eco/js/autocompletar/search.php", {
			width: 400,			/* Anchura del listado de búsqueda, si no se indica la anchura se adaptará al input */
//			highlight: true, 	// Si se indica 'false' no resaltará los valores de búsqueda
//      	  scroll: true,		// Si tendrá scroll el campo de búsqueda
			max: 50,
			scrollHeight: 150,	/* Altura del scroll en el campo de búsqueda */
//			autoFill: true,
//			matchContains: true,
//			multiple: true,
			selectFirst: false
		});

		$(":text, textarea").result(log).next().click(function() {
			$(this).prev().search();
		});

		$("#buscar_texto").result(function(event, data, formatted) {
			if (data)
				$(this).parent().next().find("input").val(data[1]);
		});
// Autocomplete, fin


/********************************** SOLUCION PARA EXPLORER (no funciona bien onChange) INICIO 1 ***********************/
	if (jQuery.browser.msie) {
		trig_bind()
	}
/********************************** SOLUCION PARA EXPLORER (no funciona bien onChange) FIN 1 ***********************/

});

/********************************** SOLUCION PARA EXPLORER (no funciona bien onChange) INICIO 2 ***********************/
function trig_bind() {
	// unbind old events
		$("input[type='checkbox']").unbind( 'click' )
		$("input[type='radio']").unbind( 'click' )
	// bind the events
		$("input[type='checkbox']").bind( 'click', function() {
			$(this).trigger( 'change' )
		})
		$("input[type='radio']").bind( 'click', function() {
			$(this).trigger( 'change' )
		})
}
/********************************** SOLUCION PARA EXPLORER (no funciona bien onChange) FIN 2 ***********************/



/*
    $(document).bind("contextmenu",function(e){
        return false;
    });
*/



// Autocomplete, inicio extra
/*
function changeOptions(){
	var max = parseInt(window.prompt('Please type number of items to display:', jQuery.Autocompleter.defaults.max));
	if (max > 0) {
		$("#suggest1").setOptions({
			max: max
		});
	}
}
*/
	function changeScrollHeight() {
		var h = parseInt(window.prompt('Please type new scroll height (number in pixels):', jQuery.Autocompleter.defaults.scrollHeight));
		if(h > 0) {
			$("#suggest1").setOptions({
				scrollHeight: h
			});
		}
	}
// Autocomplete, fin extra


	// GESTIONAR - Actualizar precios, inicio **********************
		function calcular_precio_coste(){

			// Variables de entrada
				var precio = parseFloat($('#precio').get(0).value);
				var iva_ic = parseFloat($('#iva_ic').get(0).value);
				var dto_ha = parseFloat($('#dto_ha').get(0).value);
				var dto_ad = parseFloat($('#dto_ad').get(0).value);
				var dto_ex = parseFloat($('#dto_ex').get(0).value);
				var dto_pp = parseFloat($('#dto_pp').get(0).value);
				var coste_suplementos = parseFloat($('#coste_suplementos').get(0).value);
				var porte_unidades = parseFloat($('#porte_unidades').get(0).value);
				var porte_gasto = parseFloat($('#porte_gasto').get(0).value);
				var porte_tpc = parseFloat($('#porte_tpc').get(0).value);
				var com_cambio_tpc = parseFloat($('#com_cambio_tpc').get(0).value);
				var cambio = parseFloat($('#cambio').get(0).value);
				var iva = parseFloat($('#iva').get(0).value);

			// Variable de salida
				var costes = new Array(2);

			// Calculos
				var precio_in = parseInt(     precio / ( (100+iva_ic)/100 )     * 100 + 0.5     )/100;
				var neto_producto = parseInt(     precio_in * ( (100-dto_ha)/100 ) * ( (100-dto_ad)/100 )
														* ( (100-dto_ex)/100 ) * ( (100-dto_pp)/100 )     * 100 + 0.5     )/100;
				var neto = neto_producto + coste_suplementos;

				if ( (porte_unidades =='') || (porte_unidades == 0) ) {
					porte_unidades = 1;
				}

				var gasto_porte = parseInt(     ( porte_gasto + neto * porte_tpc/100 ) / porte_unidades    * 100 + 0.5     )/100;
				var neto_porte_inc = neto + gasto_porte;

				var gasto_cambio = neto_porte_inc * com_cambio_tpc/100;
				var neto_moneda = neto_porte_inc + gasto_cambio;

				if ( (cambio == '') || (cambio == 0) ) {
					cambio = 1;
				}

				costes[0] = parseInt(     neto_moneda / cambio     * 100 + 0.5     )/100;		// Coste sin IVA
				costes[1] = costes[0] * (100+iva)/100;											// Coste con IVA

			// Salida
				return costes;
		} 


		function calcular_precios_venta(coste){

			// Variables de entrada
				var pvp_reg		= parseFloat($('#pvp_reg').get(0).value);
				var publico_tpc	= parseFloat($('#publico_tpc').get(0).value);
				var iva_ir		= parseFloat($('#iva_ir').get(0).value);
				var iva			= parseFloat($('#iva').get(0).value);
				var reg_neto	= parseFloat(0);


			// Variable de salida
				var netos		= new Array(4);

			// Calculos
				if ( isNaN(publico_tpc) || publico_tpc == 0 ) {

					if		( coste <   50 )	tramo = 1;
					else if	( coste <  100 )	tramo = 2;
					else if	( coste <  200 )	tramo = 3;
					else if	( coste <  300 )	tramo = 4;
					else if	( coste <  500 )	tramo = 5;
					else if	( coste < 1000 )	tramo = 6;
					else if	( coste < 2000 )	tramo = 7;
					else if	( coste < 3000 )	tramo = 8;
					else if	( coste < 5000 )	tramo = 9;
					else						tramo = 0;
//alert(tramo);
					switch(tramo) {
						case 1	:	publico_tpc = 172	;	break;
						case 2	:	publico_tpc = 134	;	break;
						case 3	:	publico_tpc = 104	;	break;
						case 4	:	publico_tpc =  81	;	break;
						case 5	:	publico_tpc =  64	;	break;
						case 6	:	publico_tpc =  52	;	break;
						case 7	:	publico_tpc =  44	;	break;
						case 8	:	publico_tpc =  39	;	break;
						case 9	:	publico_tpc =  36	;	break;
						default	:	publico_tpc =  34	;
					}
				}

				tiendas_tpc = publico_tpc / 2;

				neto_tiendas = parseInt(     coste * (100+tiendas_tpc)/100     * 100 + 0.5     )/100;
				neto_publico = parseInt(     coste * (100+publico_tpc)/100     * 100 + 0.5     )/100;

				if ( !isNaN(pvp_reg) && (pvp_reg != 0) ) {

					reg_neto = parseInt(     pvp_reg / ( (100+iva_ir)/100 )     * 100 + 0.5     )/100;

					if ( reg_neto > neto_publico ) {
						neto_tiendas = reg_neto - parseInt(     ( reg_neto - coste )/2     * 100 + 0.5     )/100;
						neto_publico = reg_neto;
					}
				}
//alert(neto_publico);

				netos[0] = neto_tiendas;				// Neto tiendas sin IVA
				netos[1] = netos[0] * (100+iva)/100;	// Neto tiendas con IVA
				netos[2] = neto_publico;				// Neto publico sin IVA
				netos[3] = netos[2] * (100+iva)/100;	// Neto publico con IVA

			// Salida
				return netos;
		} 
	// GESTIONAR - Actualizar precios, fin *************************

