function cmwPedidos(instancia,archivoEnvioMail,idioma){
	this.instancia = instancia;
	this.idioma = idioma;
	if(typeof(this.idioma) == 'undefined') this.idioma = 'es';
	
	this.txt = new Object();
	switch(this.idioma){
		case 'es':
			this.txt.eliminar = 'Eliminar';
			this.txt.cantidad = 'Cant.';
			this.txt.agregado = 'Agregado al pedido.';
			this.txt.removido = 'Removido del pedido.';
			this.txt.reiniciado = 'Se ha reiniciado el pedido.';
			this.txt.no_productos = 'No hay productos solicitados.';
			this.txt.validacion_error = 'Se han encontrado los siguientes errores';
			this.txt.envio_error = 'Ha ocurrido un error durante el envio del pedido.';
			this.txt.envio_exito = 'Pedido enviado con exito.';
		break;
		case 'en':
			this.txt.eliminar = 'Delete';
			this.txt.cantidad = 'Total';
			this.txt.agregado = 'Added at the order.';
			this.txt.removido = 'Removed from the order.';
			this.txt.reiniciado = 'The order has been restarted.';
			this.txt.no_productos = "No products.";
			this.txt.validacion_error = 'The next errors has been found';
			this.txt.envio_error = 'An error has ocurred in the sending process.';
			this.txt.envio_exito = 'The order has been sent successfully.';
		break;
	}
	//Pedido
	this.pedido = '#pedido';
	//this.pedidoTimeout = '';
	
	this.pedidoEnviar = pedidoEnviar;
	this.pedidoLimpiar = pedidoLimpiar;
	this.pedidoValidar = pedidoValidar;
	
	//Productos
	this.productos = '#productos';
	
	this.productoAgregar = productoAgregar;
	this.productoRemover = productoRemover;
	this.verCaracteristicas = verCaracteristicas;
	
	//Funciones Popup's
	this.minMax = minMax;
	this.minimizar = minimizar;
	this.maximizar = maximizar;
	//this.timePopup = timePopup;
	
	//Estado
	this.estado = '.estado';
	this.estadoTimeout = '';
	
	this.estadoTexto = estadoTexto;
	this.estadoOcultar = estadoOcultar;
	this.timeEstado = timeEstado;
	
	//Formulario
	this.form = '#formulario';
	
	//archivo php
	if(!archivoEnvioMail)
		this.archivoEnvioMail = 'inc/envioForm.php';
	else
		this.archivoEnvioMail = archivoEnvioMail;
		
	this.archivoEnvioMail += '?idioma='+this.idioma;
}

function productoAgregar(id,datos,funcion){
	var clase = this;
	var nombre = '';
	if(!(typeof(datos) == 'array')){
		datos = datos.split('***CristalMedia***');
		nombre = datos;
	} else
		nombre = datos.shift();
	var html = '';
	var caracteristicas = '';
	var destino = clase.productos+' .body';
	var efecto = false;
	if($('#producto'+id).length == 0){
		var nl = '';
		if(typeof(datos) == 'array'){
			$.each(datos,function(i){
				var cv = this.split('=');
				if(cv[0]){
					caracteristicas += nl+'<b>'+cv[0]+":</b><br/>"+cv[1].replace(/\n/gi,'<br/>');
					if(nl == '') nl = '<br/><br/>';
				}
			});
		}
		var accionVer = clase.instancia+".verCaracteristicas(\"#producto"+id+"\");";
		var accionEliminar = clase.instancia+".productoRemover(\""+id+"\");";
		
		html += "<div id='producto"+id+"' style='display:none;'>";
		html += 	"<div class='nombre'>";
		if(!(caracteristicas == ''))
			html += 	"<span>+</span><u onclick='"+accionVer+"'>";
		html += '<span class="titulo-producto">'+nombre+"</span>";
		if(!(caracteristicas == ''))
			html += 	"</u> ";
		html +=			"<span class='prodAcciones'>( <span onclick='"+accionEliminar+"'>"+clase.txt.eliminar+"</span> ) | "+clase.txt.cantidad+": <input type='text' value='1'/></span>";
		html += 	"</div>";
		if(!(caracteristicas == ''))
			html += 	"<div class='caracteristicas'>"+caracteristicas+"</div>";
		html += "</div>";
		if($(destino+' span').length == 0) efecto = true;
		if(efecto){
			$(destino).stop().slideUp(efecto,function(){
				$(destino).html(html);
				if($(destino).css('display') == 'none'){
					$(destino).slideDown(250);
					$(clase.productos).animate({ opacity:1 },500);
				}
				$('#producto'+id).slideDown(250);
			});
		} else {
			$(destino).append(html);
			if($(destino).css('display') == 'none') $(destino).slideDown(250);
			$('#producto'+id).slideDown(250);
		}
		clase.estadoTexto(clase.txt.agregado,clase.productos,3000,funcion);
	}
}

function verCaracteristicas(id){
	var clase = this;
	var obj = $(id+' .caracteristicas');
	var signo = '-';
	$('.caracteristicas').not(obj).slideUp(500);
	$('.nombre span:first').text('+');
	if(obj.css('display') == 'none'){
		obj.slideDown(500);
	} else {
		obj.slideUp(500);
		signo = '+';
	}
	$(id+' .nombre span:first').text(signo);
}

function productoRemover(id){
	var clase = this;
	var obj = '';
	if(id.indexOf(',') > -1){
		var idObj = [];
		var ids = id.split(',');
		$.each(ids,function(){ idObj.push('#producto'+this); });
		obj = $(idObj.join(','));
	} else {
		obj = $('#producto'+id);
	}
	var destino = $(clase.productos+' .body');
	if(obj.length > 0){
		obj.slideUp(250,function(){
			obj.remove();
			if(destino.html() == '') destino.slideUp(250,function(){
				destino.html(clase.txt.no_productos).slideDown(250);
			});
		});
	}
	if(destino.css('display') == 'none') clase.maximizar(clase.productos);
	clase.estadoTexto(clase.txt.removido,clase.productos);
}

function pedidoLimpiar(funcion){
	var clase = this;
	var ids = [];
	clase.datos = [];
	$(clase.form+' input[type!=button],'+clase.form+' textarea').val('');
	clase.estadoTexto(clase.txt.reiniciado,clase.pedido,3000,funcion);
	
	if($(clase.pedido+' .body').css('display') == 'none') clase.maximizar(clase.pedido);
	$(clase.productos+' .body div[id^=producto]').each(function(){
		ids.push($(this).attr('id').replace('producto',''));
	});
	clase.productoRemover(ids.join(','));		
	if($(clase.productos+' .body').css('display') == 'none') clase.maximizar(clase.productos);
}

function pedidoEnviar(){
	var clase = this;

	if($(clase.pedido+' .body').css('display') == 'none') clase.maximizar(clase.pedido);
	if(clase.pedidoValidar()){
		var ids = [];
		var cantidades = [];
		var nombres = [];
		var caracteristicas = [];
		var productos = $('#productos .body div[id^=producto]');
		$.each(productos,function(i){
			var id = $(this).attr('id');
			var cant = $('#'+id+' .nombre input').val();
			var nom = $('#'+id+' .titulo-producto').text();
			var car = $('#'+id+' .caracteristicas').html();
			ids.push(id.replace('producto',''));
			cantidades.push(cant);
			nombres.push(nom);
			caracteristicas.push(car);
		});
		$.post(clase.archivoEnvioMail,{
			nombre:$('#nombre').val()
			,empresa:$('#empresa').val()
			,direccion:$('#direccion').val()
			,ciudad:$('#ciudad').val()
			,provincia:$('#provincia').val()
			,telefono:$('#telefono').val()
			,email:$('#email').val()
			,comentarios:$('#comentarios').val()
			,pIds:ids.join('@@@')
			,pCants:cantidades.join('@@@')
			,pNom:nombres.join('@@@')
			,pCar:caracteristicas.join('@@@')
			,idioma:clase.idioma
		},function(data){
			var mensaje = '';
			if(data == 'ok'){
				mensaje = clase.txt.envio_exito;
				clase.pedidoLimpiar();
			} else mensaje = clase.txt.envio_error;
			alert(mensaje);
		});
	}
}

function pedidoValidar(){
	var clase = this;
	var noError = true;
	var msjErrores = clase.txt.validacion_error;
	$.each($('.cObligatorio'),function(){
		var valor = $(this).val();
		var id = $(this).attr('id');
		var nombre = $(this).attr('nombre');
		if($(this).hasClass('cTexto')){
			if(!valor.match(/[^\s]+.*/i)){
				noError = false;
				switch(clase.idioma){
					case 'es': msjErrores += '\n- El campo "'+nombre+'" no puede quedar vacio.'; break;
					case 'en': msjErrores += '\n- "'+nombre+'" can\'t be empty.'; break;
				}
			}
		}else if($(this).hasClass('cEmail')){
			if(!valor.match(/[^@]+@[^.]+\..+/i)){
				noError = false;
				switch(clase.idioma){
					case 'es': msjErrores += '\n- El campo "'+nombre+'" no contiene un email valido del tipo:\ndominio@servidor.com.'; break;
					case 'en': msjErrores += '\n- "'+nombre+'" doesn\'t have a valid email, like:\ndomain@server.com.'; break;
				}
			}
		}
		if($(this).hasClass('cIgualque')){
			var compId = $(this).attr('cIgualque');
			var compNombre = $(compId).attr('nombre');
			var comparar = $(compId).val();
			if(!(comparar == valor)){
				noError = false;
				switch(clase.idioma){
					case 'es': msjErrores += '\n- El campo "'+nombre+'" debe ser igual a "'+compNombre+'".'; break;
					case 'en': msjErrores += '\n- "'+nombre+'" has to be equal to "'+compNombre+'".'; break;
				}
			}
		}
	});
	if($(clase.productos+' div[id^=producto]').length == 0){
		switch(clase.idioma){
			case 'es': msjErrores += '\n- Debe elegir algun producto antes de enviar el pedido.'; break;
			case 'en': msjErrores += '\n- You have to add a product before to send the order.'; break;
		}
		noError = false;
	}
	if(!noError) alert(msjErrores);
	return noError;
}

function minMax(id,funcion){
	var clase = this;
	if($(id+' .body').css('display') == 'none') clase.maximizar(id,funcion);
	else clase.minimizar(id,funcion);
}

function minimizar(id,funcion){
	var clase = this;
	$(id+' .body').slideUp(500);
	$(id).animate({ opacity:.75 },500,funcion);
}

function maximizar(id,funcion){
	var clase = this;
	$(id+' .body').slideDown(500);
	$(id).animate({ opacity:1 },500,funcion);
}

function estadoTexto(mensaje,donde,tiempo,funcion){
	var clase = this;
	var efecto = 250;
	var selector = donde+' '+clase.estado;
	if(!$(selector+' span')) efecto = 0;
	$(selector+' span').stop().fadeOut(efecto,function(){
		$(selector+' span').html(mensaje).fadeIn(250,funcion);
	});
	if($(selector).css('display') == 'none') $(selector).stop().slideDown(250); 
	if(!(tiempo == 0)) clase.timeEstado(tiempo);
}

function timeEstado(tiempo){
	var clase = this;

	if(!tiempo) tiempo = 3000;
	clearTimeout(clase.estadoTimeout);
	clase.estadoTimeout = setTimeout(clase.instancia+'.estadoOcultar();',tiempo);
}

function estadoOcultar(){
	var clase = this;
	$(clase.estado).slideUp(250);
}