/*
 * Static Class VentanaModal
 * 
 * Creado por Victor Manuel Merino Martinez
 * Version: 1.0
 *
 *
 * Metodos "publicos":
 *		- getInstancia()
 *		- setSize(Number: ancho, Number: alto)
 *		- setClaseVentana(String: nombreClase)
 *		- setSombra(Boolean: sombra)
 *		- setSombraSize(Number: sombraSize)
 *		- setClaseSombra(String: nombreClase)
 *		- setIdVentana(String: idVentana)
 *		- setClaseFondo(String: nombreClase)
 *		- setContenido(String: contenidoHtml)
 *		- mostrar()
 *		- cerrar()
 *
 * Metodos "privados":
 *		- inicializar()
 *		- redimensionar()
 *		- crear()
 *
 * Metodos de utilidades:
 *		- medio()
 *
 *
 *
 *
 */

var VentanaModal = {
	
	inicializado		: false,
	creado				: false,
	ancho				: 0,
	alto				: 0,
	sombra				: false,
	csombra				: null,
	tsombra				: 0,
	claseSombra			: "",
	ventana				: null,
	idVentana			: "",
	claseVentana		: "",
	MSIE				: false,
	fondo				: null,
	claseFondo			: "",
	
	getInstancia: function() {
		this.inicializar();
		this.crear();
		return this;
	},
	
	setSize: function(ancho, alto) {
		this.alto = parseInt(alto);
		this.ancho = parseInt(ancho);
		this.ventana.style.width = this.ancho + "px";
		this.ventana.style.height = this.alto + "px";
		this.csombra.style.width = this.ancho + "px";
		this.csombra.style.height = this.alto + "px";
		this.redimensionar();
		
	},
	
	setClaseVentana: function(nombreClaseVentana) {
		this.claseVentana = nombreClaseVentana;
		this.ventana.className = this.claseVentana;
	},
	
	setSombra: function(sombra) {
		if (sombra == true) {
			this.sombra = true;
			this.csombra.style.display = "inline";
		}
		else {
			this.sombra = false;
			this.csombra.style.display = "none";
		}
	},
	
	setSombraSize: function(tsombra) {
		this.tsombra = tsombra;
		this.redimensionar();
	},
	
	setClaseSombra: function(claseSombra) {
		this.claseSombra = claseSombra;
		this.csombra.className = this.claseSombra;
	},
	
	setIdVentana: function(id) {
		this.idVentana = id;
		this.ventana.id = this.idVentana;
	},
	
	setClaseFondo: function(claseFondo) {
		this.claseFondo = claseFondo;
		this.fondo.className = this.claseFondo;
	},
	
	setContenido: function(html) {
		this.ventana.innerHTML = html;
	},
	
	mostrar: function() {
		document.body.style.overflow = "hidden";
		this.fondo.style.display = "inline";
		this.ventana.style.display = "inline";
		if (this.sombra)
			this.csombra.style.display = "inline";
	},

	cerrar: function() {
		document.body.style.overflow = "auto";
		this.ventana.style.display = "none";
		this.csombra.style.display = "none";
		this.fondo.style.display = "none";
	},
	
	medio: function(v1, v2) {
		if (isNaN(v1) && v1.indexOf("px") != -1)
			v1 = v1.replace("px", "");
		if (isNaN(v2) && v2.indexOf("px") != -1)
			v2 = v2.replace("px", "");
		var aux = parseInt(v1) / 2;
		aux = aux - (parseInt(v2) / 2);
		return parseInt(aux) * (+1);
	},
	
	inicializar: function() {
		if (this.inicializado) 
			return;
		window.onresize = function() {
			VentanaModal.redimensionar();
		};
		
		this.ancho = 300;
		this.alto = 200;
		this.sombra = true;
		this.tsombra = 5;
		this.claseSombra = "ventana-modal-sombra";
		this.claseFondo = "ventana-modal-fondo";
		this.claseVentana = "ventana-modal-ventana";
		
		if (navigator.userAgent.indexOf('MSIE') >= 0) 
			this.MSIE = true;
			
		this.inicializado = true;
		this.crear();
	},
	
	redimensionar: function() {
		var top = 0;
		var left = 0;
		var alto = 0;
		if (this.MSIE) {
			this.fondo.style.width = document.body.clientWidth;
      if (document.body.clientHeight)
				this.fondo.style.height = document.body.clientHeight;
				
			else if (document.documentElement)
				this.fondo.style.height = document.documentElement.clientHeight;
		}
		else {
			this.fondo.style.width = "100%";
			this.fondo.style.height = "100%";
		}
		if (this.MSIE) {
			//top = this.medio(document.body.clientHeight, this.alto);
			top = this.medio(window.screenTop, this.alto);
			left = this.medio(document.body.clientWidth, this.ancho);
			window.scrollTo(0,0);
		}
		else {
			top = this.medio(innerHeight, this.alto);
			left = this.medio(innerWidth, this.ancho);
		}
		this.ventana.style.top = top + "px";
		this.ventana.style.left = left + "px";
		this.csombra.style.top = (parseInt(top) + this.tsombra) + "px";
		this.csombra.style.left = (parseInt(left) + this.tsombra) + "px";
	},
	
	crear: function() {
	   //return false;
		if (this.creado) 
			return;
		this.fondo = document.createElement("DIV");
		this.fondo.style.position = "absolute";
		this.fondo.style.left = "0px";
		this.fondo.style.top = "0px";
		this.fondo.style.display = "none";
		this.fondo.className = this.claseFondo;
		this.fondo.style.zIndex = 90000;
		this.fondo.style.textAlign = "center";
		document.body.appendChild(this.fondo);
		
		this.ventana = document.createElement("DIV");
		document.body.appendChild(this.ventana);
		this.ventana.style.display = "none";
		this.ventana.style.position = "absolute";
		//this.ventana.style.overflow = "auto";
		this.ventana.style.zIndex = 100000;
		//this.ventana.style.top = "400px";
		//this.ventana.style.left = "300px";
		this.ventana.style.width = this.ancho + "px";
		this.ventana.style.height = this.alto + "px";
		this.ventana.className = this.claseVentana;
		
		this.csombra = document.createElement("DIV");
		document.body.appendChild(this.csombra);
		this.csombra.style.display = "none";
		this.csombra.style.position = "absolute";
		this.csombra.style.zIndex = 95000;
		this.csombra.style.width = this.ancho + "px";
		this.csombra.style.height = this.alto + "px";
		this.csombra.className = this.claseSombra;
		
		this.creado = true;
		this.redimensionar();
	}
};

$(document).ready(
	function(){
		
		$("#carrito").css({
			width: "123px",
			height: "100%"
		});
		
		var posicionCarrito = $("#carrito").offset();
		var centroCarrito = {
			left: (posicionCarrito.left + (parseInt($("#carrito").css("width"))/2)),
			top: (posicionCarrito.top + (parseInt($("#carrito").css("height"))/2))
		}
		var peticion = false;
		$(".producto form").submit(
			function(){
				
				
							
				if(parseInt(this.stock.value) == 0){
					alert("Este producto no tiene stock.\nDisculpe las molestias");
					return false;
				}
				
				if(parseInt(this.stock.value) < 0){
					alert("Este producto esta descatalogado.\nDisculpe las molestias");
					return false;
				}
				
				if(parseInt(this.max_pedido.value) == 0){
					alert("Este producto no tiene stock actualmente.\nDisculpe las molestias");
					return false;
				}
				
				if(this.quantity){
					var cant = parseInt(this.quantity.value);
				}else{
					var cant = 1;
				}
				
				
				if(cant == 0){
					alert("No puede pedir 0 unidades.\nEspecifique una cantidad vlida");
					this.quantity.focus();
					return false;
				}
				
				var numerico = new RegExp("^([0-9]+)$");
				if(numerico.test(this.quantity.value)){

					
					
									
					if((parseInt(this.stock.value) - cant) >= 0){
						if ((cant > this.max_pedido.value) && (this.max_pedido.value!=0)){
							alert("El pedido que intenta realizar supera el número máximo unidades por pedido.\nMáximo de "+this.max_pedido.value+" unidades.\nDisculpe las molestiass.")
						}else{
							if(!peticion){
								var form = this;
								var id = this.products_id.value;
								var imagen = $("#imagenProducto"+id+" img").clone().appendTo($("#imagenProducto"+id+""));
								//alert(this.products_id[0].value);
								var posicionImagen = imagen.offset();
								
								var boton =  $(this).find("[type=submit]");
								$.ajax({
									type: "POST",
									url: "?action=add_product&ajax=1",
									data: "products_id="+id+"&quantity="+cant+"&csrf="+csrf,
									beforeSend:
										function(){
											boton.attr("disabled", "disabled");
											imagen.css({
												border:	"1px solid red",
												position: "absolute",
												left: posicionImagen.left,
												top: posicionImagen.top,
												opacity: 0.5,
												"z-index": 10,
												width: 100,
												height: 100
											});
											
											imagen.animate(
												{
													left:	(centroCarrito.left	- (parseInt(imagen.css("width"))/2)),
													top:	(centroCarrito.top	- (parseInt(imagen.css("height"))/2))
												},
												1500,
												"swing",
												function(){
													
													$(this).fadeOut(500,
														function(){
															$(this).remove();
														}
													);
													
												}
											);
											$("#carrito").html('<img id="loader" src="img/ajax-loader.gif" />');
											$("#loader").css({
												display: "block",
												margin: "10px auto"
											});
	
										},
									success:
										function(respuesta){
											form.stock.value -= parseInt(form.quantity.value);
											
											if(form.stock.value == 0){
												$(form).find("h4 img").attr("src", "/includes/languages/espanol/images/buttons/agotado.gif");
											}
											
											var productos = '';
											var total = 0;
	
											respuesta = eval(respuesta);
											
											for (i = 0; i < (respuesta.length -1); i++){
												
												productos += '<div class="productoCarrito boxText1"><span class="cantidad">'+respuesta[i].quantity+' X </span><a class="boxText1" href="http://discogame.com/'+respuesta[i].name.replace(/\s/g , "-").replace("/", "").toLowerCase()+'-p-'+respuesta[i].id+'.html">'+respuesta[i].name+'</a></div>';
	
												if(i == (respuesta.length -2)){
													$("#precioFinal").remove();
													productos +='<div id="precioFinal">'+respuesta[i+1]['total']+'</div>';
													$("#carrito").html(productos);
												}
											}
											/*boton.removeAttr("disabled");
											htmlModal = '<div id="modal"><a id="verCesta" title="'+respuesta[(respuesta.length -1)]["verCesta"]+'" href="/shopping_cart.php">'+respuesta[(respuesta.length -1)]["verCesta"]+'</a><p id="mensajeModal">'+respuesta[(respuesta.length -1)]["mensaje"]+'</p><a id="cerrarModal" title="'+respuesta[(respuesta.length -1)]["cerrar"]+'">'+respuesta[(respuesta.length -1)]["cerrar"]+'</a></div>';
											
											/*+'<style>'
											+'#modal{padding: 0px;	background: #9587f9; color: #fff; font-size: 16px; border: 1px solid blue;}'
											+'#mensajeModal{padding: 10px;}'
											+'#cerrarModal, #verCesta{padding: 2px; cursor: pointer;display: block;font-family: verdana, Sans;font-size: 18px; color: #fff; text-transform: uppercase}'
											+'#cerrarModal:hover, #verCesta:hover{color: #d4d0f5}'
											+'#cerrarModal{	background: #3C3784 url(img/cerrar.png) no-repeat center right;	}'
											+'#verCesta{background: #3C3784 url(img/circulo.png) no-repeat center right;}'
											+'</style>'
											+'<div id="modal"><a id="verCesta" title="'+respuesta[(respuesta.length -1)]["verCesta"]+'" href="/shopping_cart.php">'+respuesta[(respuesta.length -1)]["verCesta"]+'</a><p id="mensajeModal">'+respuesta[(respuesta.length -1)]["mensaje"]+'</p><a id="cerrarModal" title="'+respuesta[(respuesta.length -1)]["cerrar"]+'">'+respuesta[(respuesta.length -1)]["cerrar"]+'</a></div>';
											*/
											/*setTimeout("",1300);
											VentanaModal.inicializar();
											VentanaModal.setSize(270, 90);
											VentanaModal.setClaseVentana("modal");
											VentanaModal.setContenido(htmlModal);
											VentanaModal.setClaseFondo("fondoModal");
											VentanaModal.setSombra(true);
											VentanaModal.setClaseSombra("fondoModal");
											VentanaModal.mostrar();
											
											$("#modal").css({padding: "0px",background: "#9587f9", color: "#fff", "font-size": "16px", border: "1px solid blue"});
											$("#mensajeModal").css({padding: "10px"});
											$("#cerrarModal, #verCesta").css({padding: "2px", cursor: "pointer",display: "block","font-family": "verdana, Sans","font-size": "18px", color: "#fff", "text-transform": "uppercase"});
											$("#cerrarModal:hover, #verCesta:hover").css({color: "#d4d0f5"});
											$("#cerrarModal").css({background: "#3C3784 url(img/cerrar.png) no-repeat center right"	});
											$("#verCesta").css({background: "#3C3784 url(img/circulo.png) no-repeat center right"});
											
											$(".fondoModal").css({
												opacity: 0.6,
												background: "#333"
											});
	
											$("#cerrarModal").click(
												function(){VentanaModal.cerrar()}
											);*/
										}
								});
							}
						}
					}else if((parseInt(this.stock.value) - cant) < 0){
						if(parseInt(this.stock.value) < parseInt(this.max_pedido.value)){
							alert("El pedido que intenta realizar supera el máximo de unidades disponibles.\nEl pedido máximo para este producto es de "+this.stock.value+" unidades.\nDisculpe las molestias.");
						}else{
							alert("El pedido que intenta realizar supera el máximo de unidades disponibles.\nEl pedido máximo para este producto es de "+this.max_pedido.value+" unidades.\nDisculpe las molestias.");
						}
					} 
				}else{
					alert("debe especificar un numero en el campo 'Unidades'");
					this.quantity.focus();
				}
				return false;
				
			}
		);
		$(document).ajaxStart(
			function(){peticion = true;}
		)
		$(document).ajaxStop(
			function(){peticion = false;}
		)
	}
);
