var swfu;
var controles_subida = new Array();
$(function() {
	$('a[rel=external]').attr('target', '_blank');
	if ($('#fotos').length > 0) {
		swfu = new SWFUpload({
			file_types:'*.jpg;',
			upload_url: '/fotos/agregar/'+sID+'/1',
			flash_url: '/js/swfupload.swf',
			file_size_limit: '20 MB',
			button_placeholder_id: 'inputImagen',
			button_image_url:'/img/anadir.png',
			button_width:224,
			button_height:31,
			file_upload_limit:200,
			http_success : [201, 202, -200], 
			
			button_window_mode:SWFUpload.WINDOW_MODE.TRANSPARENT,
			flash_color:'#292e26',
			debug:false,
			requeue_on_error : true,
			button_cursor : SWFUpload.CURSOR.HAND,
	
			file_dialog_start_handler    : inicio_seleccion,
			file_dialog_complete_handler : fin_seleccion,
			file_queued_handler          : archivo_encolado,
			upload_start_handler         : inicio_subida,
			upload_progress_handler      : progreso_subida,
			upload_success_handler       : subida_ok,
			upload_complete_handler      : fin_subida,
			upload_error_handler         : subida_error,
			file_queue_error_handler     : cola_error
		});
		$('#inputAgregar').hide();
		$('#btnGuardar').hide();
		$('#fotos #main li').each(function() {
			cambiosCajas(this);
		});
		$('#fotos #main form[id!="formMasivo"] select').bind('change', cambioSelect);
		$('#fotos #main form[id!="formMasivo"] .numero').bind('change', cambioInput);
		$('#fotos #main a.img').fancybox({'hideOnContentClick':true});
		$('form[id=!"formResumen"]').bind('submit', function(e) { e.preventDefault(); return false; });
		
		$('.masivos form').hide();
		$('.masivos h4').css('cursor', 'pointer').bind('click', function() { $(this).parent().find('form').slideToggle(400); });
		if ($('#fotos #main form#formImagenes ul li').length < 2) {
			$('.masivos').hide();
		}
		
		$('.masivos .masivos_aplicar').replaceWith('<a onclick="$(\'#formMasivo\').submit()" class="masivosAplicar">Aplicar</a>');
		$('.masivos .masivos_eliminar').replaceWith('<a onclick="eliminar_todo()" class="masivosAplicar">Eliminar todo</a>');
		$('.masivos form').bind('submit', function(e) {
			if ($("#eliminar_todo").length<1 && $('#marcarFormato:checked').length < 1 && $('#marcarAcabado:checked').length < 1 && $('#marcarCantidad:checked').length < 1) {
				e.preventDefault();
				alert("Elige el campo que quieras cambiar.");
				return false;
			}
			for (var z in SWFUpload.instances) {
				var estado = SWFUpload.instances[z].getStats();
				if (estado.in_progress > 0 || estado.files_queued > 0) {
					e.preventDefault();
					alert("Espera a que terminen las subidas para hacer los cambios.");
					return false;
				}
			}
		});
		$('#formato_masivo').bind('change', function(){ 
			if ($('#formato_masivo option:selected').html() == '13x18' || $('#formato_masivo option:selected').html() == '11,40 x 17') {
				$('#acabado_masivo option:last').attr('selected', 'selected')
				$('#acabado_masivo').trigger('change').attr('disabled', 'disabled').addClass('disabled');
			} else {
				$('#acabado_masivo').removeAttr('disabled').removeClass('disabled');
			}
			if ($('#marcarFormato:checked').length < 1) $('#marcarFormato').attr('checked', 'checked'); 
		});
		$('#cantidad_masivo').bind('change', function(){ if ($('#marcarCantidad:checked').length < 1) $('#marcarCantidad').attr('checked', 'checked'); });
		$('#acabado_masivo').bind('change', function(){ if ($('#marcarAcabado:checked').length < 1) $('#marcarAcabado').attr('checked', 'checked'); });
	}
	if ($('#formato_masivo option:selected').html() == '13x18' || $('#formato_masivo option:selected').html() == '11,40 x 17') {
		$('#acabado_masivo option:first').attr('selected', 'selected')
		$('#acabado_masivo').attr('disabled', 'disabled');
	}
	if ($('#wrapper.datos').length > 0) {
		$('#formEntrega').bind('submit', comprobar_datos);
		
		$('input[type=radio]').bind('click	', cambio_envio);
		
		$('input.texto').bind('change', actualizar_datos);
	}
	if ($('#contenedor.pago').length > 0) {
		$('#pago form').bind('submit', function(e) {
			e.preventDefault();
			alert("Estado del programa: DESARROLLO\n\nEn este estado no se realiza el paso por la pasarela\nbancaria ni se envían mensajes de correo.");
			
			return false;
			
			if (confirm("Estado del programa: DESARROLLO\n\nEn este estado no se realiza el paso por la pasarela\nbancaria ni se envían mensajes de correo.\n\nPulse ACEPTAR para ver el acuse de un cobro correcto.\nPulse CANCELAR para ver la página de fallo en el cobro.\n")) {
				window.location.href = "/fin/OK";
			} else {
				window.location.href = "/fin/KO";
			}
			
			return false;
		});
	}
	$('a.img').fancybox({'hideOnContentClick':true});
	setTimeout(function() { $('#mensajes ul').slideUp('slow', function() { $(this).remove(); }) }, 5000);

	comprobar_formato_acabado();

	$('#formato').change(function() {
		if($('#formato option:selected').html() == '13x18' || $('#formato option:selected').html() == '11,40 x 17') {
			$('#acabado option:first').attr('selected', 'selected');
			$('#acabado').addClass('disabled').attr('disabled', 'disabled');
		} else {
			$('#acabado').removeClass('disabled').removeAttr('disabled');
		}
	}).trigger('change');
});
function comprobar_formato_acabado() {
	$('#formImagenes select[id^="formato_"]').each(function () {
		if($('option:selected', this).html() == '13x18' || $('option:selected', this).html() == '11,40 x 17') {
			$(this).parent().parent().find('select[name^="acabado"]').attr('disabled', 'disabled').addClass('disabled').find('option:selected').removeAttr('selected').end().find('option:last').attr('selected', 'selected').end().trigger('change');
		} else {
			$(this).parent().parent().find('select[name^="acabado"]').removeAttr('disabled').removeClass('disabled');
		}
	});
}
function eliminar_todo(){
		if(confirm("¿Seguro que desea eliminar todas las fotos de revelado?")){
			$("#formMasivo").append('<input type="hidden" id="eliminar_todo" name="eliminar_todo" value="1" />');
			$("#formMasivo").append('<input type="hidden" id="sID" name="sID" value="'+sID+'" />');
			$("#formMasivo").submit();
		}
		else{
			return false;
		}
}
function cambiosCajas(obj) {
		var num = $(obj).find('>div[id^="img_"]').attr('id').substr(4);
		//$('.lbEncuadre', obj).html('<input type="button" class="boton" value="Encuadre" id="encuadre_'+num+'" onclick="encuadrar(\''+num+'\',\''+sID+'-'+num+'.jpg\')"/>');
		$('.lbEliminar', obj).html('<input type="button" class="boton" value="Eliminar" id="eliminar_'+num+'" onclick="eliminar(\''+num+'\')"/>');
}

function cambioSelect(e) {
	if ($(this).attr('id').substr(0, 8) == 'formato_') { 
		$(this).parent().find('[name^="origen_"]').val(0); 
		if($('option:selected', this).html() == '13x18' || $('option:selected', this).html() == '11,40 x 17') {
			$(this).parent().parent().find('select[name^="acabado"]').attr('disabled', 'disabled').addClass('disabled').find('option:selected').removeAttr('selected').end().find('option:last').attr('selected', 'selected').end().trigger('change');
		} else {
			$(this).parent().parent().find('select[name^="acabado"]').removeAttr('disabled').removeClass('disabled');
		}
	}
	$.post('/fotos/cambio/'+sID, {campo:$(this).attr('id'), valor:$(this).val()}, function(datos) { actualizar_resumen(datos); }, "json");
}
function cambioInput(e) {
	if ($(this).val() < 1) { $(this).val(1); return; }
	$.post('/fotos/cambio/'+sID, {campo:$(this).attr('id'), valor:$(this).val()}, function(datos) { actualizar_resumen(datos); }, "json");
}

function inicio_seleccion() {
	var parametros = new Object();
	parametros.formato = $('#formato').val();
	parametros.cantidad = $('#cantidad').val();
	parametros.acabado = $('#acabado').val();
	parametros.sID = sID;
	parametros.PHPSESSID = ssID;
	swfu.setPostParams(parametros);
}

function archivo_encolado(archivo) {
	if ($('#fotos #main form#formImagenes ul').length < 1) {
		$('#fotos #main form#formImagenes').prepend('<ul></ul>');
		$('#fotos #main .vacio').slideUp();
	}
	$('#fotos #main ul').append('<li style="display:none" class="subida abrir"><div class="nombreArchivo">'+archivo.name+'</div><div class="barraProgreso"><div class="progreso"></div></div><div class="estado estadoEspera">En espera...</div></li>')
	controles_subida[archivo.id] = $('#fotos #main ul li.abrir');
	controles_subida[archivo.id].removeClass('abrir').slideDown();
}

function fin_seleccion(numElegidas, numEncoladas) {
	try {
		if (numElegidas > 0) this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}

function inicio_subida(archivo) {
	controles_subida[archivo.id].find('.estado').removeClass('estadoEspera').html('0% Enviando');
}

function progreso_subida(archivo, bytesRecibidos, bytesTotales) {
	var porcentaje = Math.round(((bytesRecibidos * 100) / bytesTotales));
	controles_subida[archivo.id].find('.estado').html(porcentaje+'% Enviando');
	controles_subida[archivo.id].find('.progreso').width(porcentaje*5);
}

var result = new Array();
var intentos =  new Array();
function subida_ok(archivo, datos) {
	var obj = controles_subida[archivo.id];

	datos_aux = datos.split("salida=");
	
	if (datos.indexOf('=--FIN--')!=-1) {
		cambio_subida(archivo,datos);
	} else {
		intentos[archivo.id] = 0;
		post_pieza(ssID,datos_aux[1],archivo);
	}
	
	if ($('#fotos #main form#formImagenes ul li').length > 1) {
		$('.masivos').show(500);
	}
}
function post_pieza(ssID,datos,archivo){
	var result = false;
	$.post('/fotos/get_fotos_pieza/'+ssID+'/'+datos,{},function(data){
		result = cambio_subida(archivo,data);
		intentos[archivo.id]++;
		if(!result && intentos[archivo.id]<3)
			post_pieza(ssID,datos,archivo);
		else{
			if(intentos[archivo.id] >= 3){
				alert("ALGO HA PASADO! Vamos a reponerlo todo...");
				window.location.href = window.location.href;
			}
		}
	},"text");
	
	
}
function cambio_subida(archivo,datos){
	var obj = controles_subida[archivo.id];
	datos_aux = datos.split("salida=");

	if (datos.indexOf('=--FIN--')!=-1) {
		obj.find('>*').each(function() { $(this).hide('slow', function() { $(this).remove() }); });
		obj.append(datos_aux[2]);
		obj.find('.img').fancybox({'hideOnContentClick':true}).hide().fadeIn('slow').end().find('.datos').hide().fadeIn('slow').end();
		obj.removeClass('subida');
		
		cambiosCajas(obj);
		
		$('#fotos #main select').unbind('change').bind('change', cambioSelect);
		$('#fotos #main .numero').unbind('change').bind('change', cambioInput);
		$.post('/fotos/resumen/'+sID, {}, function(datos) { actualizar_resumen(datos); }, "json");
		comprobar_formato_acabado();
		return true;
	}
	return false;
}

function fin_subida(archivo) { swfu.startUpload(); }
function subida_error(archivo, codigo, mensaje) { alert("error_subida:\ncódigo: "+codigo+"\nmensaje: "+mensaje); }
function cola_error() { alert("error_cola"); }

function encuadrar(num_archivo, nombre_tmp) {
	$('#encuadre').remove();
	$('body').append('<div id="encuadre" style="display:none"><div id="encuadrando"><div id="numEncuadre" style="display:none;">'+num_archivo+'</div><h3>Selecciona el área apoximada de imagen que te gustaría imprimir:</h3><div id="imagenEncuadre" style="display:none;"><img src="/imagenes/pantalla/'+nombre_tmp+'" alt=""/></div></div></div><a href="#encuadre" style="display:none" id="encuadreA"/>');
	$('#encuadreA').fancybox({overlayShow:true,frameWidth:940,frameHeight:580,boxCloseCallback:cerrar_encuadre,zoomSpeedIn:0,autoSize:'no'}).trigger('click').remove();
	$('#encuadre').remove();
	$('#imagenEncuadre img').bind('load', function() { centrar_imagen_encuadre(num_archivo); });
}
function centrar_imagen_encuadre(num_archivo) {
	var divImagen = $('#imagenEncuadre');
	var imagen = divImagen.find('img');
	var objImg = new Image();
	objImg.src = imagen.attr('src');
	var ancho = objImg.width;
	var alto = objImg.height;
	if (ancho < 50 || alto < 50) {
		setTimeout(centrar_imagen_encuadre, 150);
	}
	var izquierda = Math.round((940 - ancho) / 2);
	var arriba = Math.round((580 - alto ) / 2);
	divImagen.css({position:'absolute', width:ancho+'px', height:alto+'px', left:izquierda+'px', top:arriba+'px', border:'solid 5px #D8D4D2', margin:0, padding:0}).fadeIn('slow', function() { crear_encuadre(ancho, alto); });
}
function crear_encuadre(ancho, alto) {
	if ($('#imagenEncuadre.iniciado').length > 0) return;
	var divImagen = $('#imagenEncuadre');
	var imagen = divImagen.find('img');
	var num_archivo = $('#numEncuadre').text();
	var divOrigen = $('#img_'+num_archivo);
	var valX = divOrigen.find('[name^="origen_x"]').val(); valX = parseInt(valX);
	var valY = divOrigen.find('[name^="origen_y"]').val(); valY = parseInt(valY);
	var tamOrigen = {ancho:imagen.width(), alto:imagen.height()};
	var tamDestino = formatos[divOrigen.find('#formato_'+num_archivo).val()];
	if (tamOrigen.ancho > tamOrigen.alto) {
		if (tamDestino.ancho < tamDestino.alto) tamDestino = {ancho:tamDestino.alto, alto:tamDestino.ancho};
		var anchoT = Math.round((tamDestino.ancho * alto) / tamDestino.alto);
		if (anchoT > ancho) {
			alto = Math.round((tamDestino.alto * ancho) / tamDestino.ancho);
		} else ancho = anchoT;
	} else if (tamOrigen.ancho < tamOrigen.alto) {
		if (tamDestino.ancho > tamDestino.alto) tamDestino = {ancho:tamDestino.alto, alto:tamDestino.ancho};
		var altoT = Math.round((tamDestino.alto * ancho) / tamDestino.ancho);
		if (altoT > alto) {
			ancho = Math.round((tamDestino.ancho * alto) / tamDestino.alto);
		} else alto = altoT;
	} else {
		if (tamDestino.ancho > tamDestino.alto) {
			alto = Math.round((tamDestino.alto * ancho) / tamDestino.ancho);
		} else {
			ancho = Math.round((tamDestino.ancho * alto) / tamDestino.alto);
		}
	}
	var ratio = tamDestino.ancho+':'+tamDestino.alto;
	imagen.imgAreaSelect({x1:valX, x2:valX+ancho, y1:valY, y2:valY+alto, movable:true, resizable:false, persistent:true, outerOpacity:0.7, selectionOpacity:0, onSelectEnd:cambio_encuadre});
	divImagen.addClass('iniciado');
}
function cambio_encuadre(img, datos) {
	var num_archivo = $('#numEncuadre').text();
	var divOrigen = $('#img_'+num_archivo);
	divOrigen.find('[name^="origen_x"]').val(datos.x1);
	divOrigen.find('[name^="origen_y"]').val(datos.y1);
	
}
function cerrar_encuadre() {
	var num_archivo = $('#numEncuadre').text();
	var divOrigen = $('#img_'+num_archivo);
	$.post('/fotos/cambio/'+sID, {campo:'origen_x_'+num_archivo, valor:divOrigen.find('[name^="origen_x"]').val()}, function(datos) {  }, "json");
	$.post('/fotos/cambio/'+sID, {campo:'origen_y_'+num_archivo, valor:divOrigen.find('[name^="origen_y"]').val()}, function(datos) {  }, "json");
	$('[class^="imgareaselect"]').remove();
}

function eliminar(num_archivo) {
	if (!confirm("¿Seguro que quieres eliminar esta imagen del pedido?")) return;
	$.post('/fotos/eliminar/'+sID, {id_eliminar:num_archivo}, function(datos) { actualizar_resumen(datos); }, "json");
	$('#img_'+num_archivo).slideUp('slow', function() { $(this).parent().remove(); });
	if ($('#fotos #main li').length <= 1) {
		$('#fotos #main form#formImagenes ul').slideUp('slow', function() { $(this).remove(); });
		$('#fotos #main .vacio').removeClass('oculto').hide().slideDown('slow');
	}
	if ($('#fotos #main li').length < 3) {
		$('.masivos').hide(500);
	}
}

function actualizar_resumen(datos) {
	// Resumen
	$('#resumen_copias .lbPedidoCantidad span').html(datos.resumen.cantidad);
    $("#resumen_subtotal .lbPedidoPrecio span").html(datos.resumen.subtotal+ " &euro;").css('backgroundColor', '#FFF').animate({backgroundColor:'#f8cb59'}, 300).animate({backgroundColor:'#FFF'},0).animate({backgroundColor:'#f8cb59'}, 300).animate({backgroundColor:'#FFF'},0).animate({backgroundColor:'#f8cb59'}, 300);
	$('#resumen_copias .lbPedidoPrecio span').html(datos.resumen.precio + ' &euro;').css('backgroundColor', '#FFF').animate({backgroundColor:'#f8cb59'}, 300).animate({backgroundColor:'#FFF'},0).animate({backgroundColor:'#f8cb59'}, 300).animate({backgroundColor:'#FFF'},0).animate({backgroundColor:'#f8cb59'}, 300);
	// Desglose
	for (var n = 0; n < datos.formatos.length; n++) {
		var obj = $('#formato_'+datos.formatos[n].id);
		if (datos.formatos[n].cuenta == 0) {
			obj.find('.pedido').slideUp('slow', function() { $(this).remove(); });
		} else {
			if (obj.find('.pedido').length < 1) obj.append('<div class="pedido" style="display:none"></div>');
			obj.find('.pedido').html('<span class="formatoNombre">'+datos.formatos[n].cuenta+' copia'+(datos.formatos[n].cuenta == 1 ? '' : 's')+'</span><span class="formatoPrecio">'+(datos.formatos[n].cuenta * datos.formatos[n].precio_formato_usuario).toFixed(2).split('.').join(',')+' &euro;</span>').css('backgroundColor', '#f8cb59').slideDown('slow').animate({backgroundColor:'#FFF'},1500);
		}
	}
	$("#bag").html('<a href="/cesta/">VER CESTA</a> ' + datos.resumen.subtotal + ' €');

}

function comprobar_datos(e) {
	e.preventDefault();
	var error = false;
	$('#datosEntrega input').each(function(i) {
		if ($(this).val().split(' ').join('').length == 0) {
			$(this)
				.css('backgroundColor', '#9C301a')
				.animate({backgroundColor:'#D8D4D2'}, 300)
				.animate({backgroundColor:'#9C301A'},0)
				.animate({backgroundColor:'#D8D4D2'}, 300)
				.animate({backgroundColor:'#9C301A'},0)
				.animate({backgroundColor:'#D8D4D2'}, 300)
				.parent().after('<span class="error">Este campo es necesario</span>')
				.next().hide().show('slow').fadeTo(4000, 1).hide(500, 0, function() { $(this).remove(); });
			if (error === false) $(this).focus();
			error = true;
		}
	});
	if($('#datosEntrega input#datos_email').val().length && !(/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/.test($('#datosEntrega input#datos_email').val())) ) {
		if ($('#datos_email').parent().next().is('span.error')) $('#datos_email').parent().next().stop().remove();
		$('#datos_email')
			.css('backgroundColor', '#9C301a')
			.animate({backgroundColor:'#D8D4D2'}, 300)
			.animate({backgroundColor:'#9C301A'},0)
			.animate({backgroundColor:'#D8D4D2'}, 300)
			.animate({backgroundColor:'#9C301A'},0)
			.animate({backgroundColor:'#D8D4D2'}, 300)
			.parent().after('<span class="error">Debes introducir una dirección de email correcta</span>')
			.next().hide().show('slow').fadeTo(4000, 1).hide(500, 0, function() { $(this).remove(); });
		if (error === false) $('#datos_email').focus();
		error = true;
	}
	if ($('input[name="entrega"]:checked').length < 1) {
		$('#datosEnvio ul').before('<span class="error">Debes elegir una forma de entrega</span>').prev()
			.hide().show('slow').fadeTo(4000, 1).hide(500, 0, function() { $(this).remove(); });
		error = true;
	}
	if (error === false) $('#formEntrega')[0].submit();
	return false;
}

function cambio_envio(e) {
	$.post('/datos/actualizar/', {campo:'entrega', valor:$('input[name="entrega"]:checked').val()});
	// Mostrar en resumen de precio
	if ($('.entrega .lbPedidoEntrega').length < 1) {
		$('.entrega').html('<div class="lbPedidoEntrega"><span class="texto"></span> entrega</div>')
	}
	
	var precio = parseFloat($('input[name="entrega"]:checked').parent().find('.precio').text().split(' €').join('').split(' &euro;').join('').split(',').join('.'));
	$('.resumen .lbPedidoEntrega span').text(number_format(precio, 2, ',', '.') + ' €').parent().parent()
		.css('backgroundColor', '#F8CB59')
		.animate({backgroundColor:'#5C1C4F'}, 300)
		.animate({backgroundColor:'#F8CB59'},0)
		.animate({backgroundColor:'#5C1C4F'}, 300);
	$('.total .lbPedidoPrecio span').text( number_format(precioBase + precio, 2, ',', '.') + ' €' ).parent().parent()
		.css('backgroundColor', '#F8CB59')
		.animate({backgroundColor:'#5C1C4F'}, 300)
		.animate({backgroundColor:'#F8CB59'},0)
		.animate({backgroundColor:'#5C1C4F'}, 300);
}

function actualizar_datos(e) {
	$.post('/datos/actualizar/', {campo:e.target.name.split('datos_').join(''), valor:e.target.value}, function(datos) { 
		if(datos.estado=='ERROR') {
			$('#datos_'+datos.campo).focus()
				.css('backgroundColor', '#9C301a')
				.animate({backgroundColor:'#D8D4D2'}, 300)
				.animate({backgroundColor:'#9C301A'},0)
				.animate({backgroundColor:'#D8D4D2'}, 300)
				.animate({backgroundColor:'#9C301A'},0)
				.animate({backgroundColor:'#D8D4D2'}, 300);
			if ($('#datos_'+datos.campo).parent().next().is('span.error')) $('#datos_'+datos.campo).parent().next().remove();
			$('#datos_'+datos.campo).parent().after('<span class="error">'+datos.error+'</span>').next().hide().show('slow').fadeTo(4000, 1).hide(500, 0, function() { $(this).remove(); });
		}
	}, 'json');
}

function number_format( number, decimals, dec_point, thousands_sep ) {
	var n = number, prec = decimals;
	var toFixedFix = function (n,prec) { var k = Math.pow(10,prec); return (Math.round(n*k)/k).toString(); };
	n = !isFinite(+n) ? 0 : +n;
	prec = !isFinite(+prec) ? 0 : Math.abs(prec);
	var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
	var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
	var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
	var abs = toFixedFix(Math.abs(n), prec);
	var _, i;
	if (abs >= 1000) {
		_ = abs.split(/\D/);
		i = _[0].length % 3 || 3;
		_[0] = s.slice(0,i + (n < 0)) + _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
		s = _.join(dec);
	} else
		s = s.replace('.', dec);

	if (s.indexOf(dec) === -1 && prec > 1)
		s += dec+new Array(prec).join(0)+'0';

	if(s.split(dec)[1].toString().length<2){
		s +="0";
	}
	return s;
}
