//////////////////////////////////////////////////
//TOOLTIPS
var tips = {
	options:{
		x: 0,
		y: 0,
		atb: 'rel',
		showTime: 500,
		hideTime: 400,
		effects: true,
		offsets: {'x': 20, 'y': 20},
		opacity: 0.9
	},
	initialize: function() {
		this.toolTip = new Element('div', {
			'class': 'tool-tip',
			'id': 'tool-tip',
			'styles': {
				'position': 'absolute',
				'top': '0',
				'left': '0',
				'visibility': 'hidden'
			}
		}).inject(document.body);
		this.toolTip.addEvent('click', function(){tips.hide(); });
	},
	position: function(){
		if (!this.existe)
			return false;
		var pos = $(this.el).getPosition();
		this.toolTip.setStyles({
			'left': pos.x + this.options.offsets.x,
			'top': pos.y + this.options.offsets.y
		});
	},
	createContent: function(txt) {
		if (typeof(txt) != 'undefined') {
			var cont = txt;
		} else {	
			var cont = this.el.getAttribute(this.options.atb);
			if (cont.trim() == "") {
				this.existe = false;
				return false;
			}
		}
		this.toolTipContent = new Element('div', {'class': 'tool-content'}).inject(this.toolTip);
		
		var dual = cont.split('::');
			
		if (dual.length > 1){
			this.title = new Element('div', {'class': 'tool-title'}).inject(this.toolTipContent).set('html', dual[0].trim());
			this.text = new Element('div', {'class': 'tool-text', 'id': 'demo_div'}).inject(this.toolTipContent).set('html', dual[1].trim());
		} else {
			this.text = new Element('div', {'class': 'tool-text'}).inject(this.toolTipContent).set('html', dual[0].trim());
		}
		this.existe = true;
		
	},
	assignSize: function() {
		var s = this.toolTipContent.getSize();
		this.toolTipContent.setStyles({'width': s.x+'px', 'height': s.y+'px'});
	},
	build: function(txt) {
		if($('tool-tip'))
			$('tool-tip').destroy();
		this.initialize();
		this.createContent(txt);
		this.position();
		this.assignSize();
	},
	show: function(el, txt) {
		this.el = el;
		this.build(txt);
		if ( !this.existe )
			return false;
		
		if (this.options.effects) {
			var size = this.toolTip.getSize();
			this.options.x = size.x;
			this.options.y = size.y;
			this.fxShow = new Fx.Morph(this.toolTip, {duration: this.options.showTime, wait: false});
			this.fxShow.start({
				'width':[0, size.x],
				'height':[0, size.y],
				'opacity':[0, this.options.opacity]
			});
		} else {
			this.toolTip.setStyle('visibility', 'visible');
		}
		
	},
	hide: function(){
		if (this.existe) {
			if (this.fxShow)
				this.fxShow.cancel();
			this.existe = false;
			
			if (this.options.effects) {
				var fxHide = new Fx.Morph(this.toolTip, {duration: this.options.hideTime, wait: false});
				fxHide.start({
					'width':[this.options.x, 0],
					'height':[this.options.y, 0],
					'opacity':[this.options.opacity, 0]
				});
			} else {
				this.toolTip.setStyle('visibility', 'hidden');
			}
		}
	}
};


//////////////////////////////////////////////////
//IMPLEMENTAR UN STRING PARA CREAR FUNCIONES
String.implement({
	isMail: function() {
		var txt = this.trim();
		var regex = "^[\_]*([a-z0-9]+(\.|\_*)?)+@([a-z][a-z0-9\-]+(\.|\-*\.))+\.[a-z]{2,6}$";
		var regexp = new RegExp(regex, 'i');
		return regexp.test(txt);
	},
	isDate: function () {
		
		var dateStr = this.trim();
				
		if ( typeof(dateStr) == 'undefined' ) return false;
		
		var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
		var matchArray = dateStr.match(datePat); // is the format ok?
		
		var und = "undefined";
		
		if ( matchArray == null ) return false;
		
		if ( matchArray.length < 6 ) return false;
			
		var day = parseInt(matchArray[1]);
		var month = parseInt(matchArray[3]);
		var year = parseInt(matchArray[5]);
		
		if ( day < 1 || day > 31 ) {
			//dia inválido
			return false
		}
		
		if ( month < 1 || month > 12 ) { // check month range
			//mes inválido
			return false;
		}
		
		if ( (month==4 || month==6 || month==9 || month==11) && day==31) {
			//el mes no tiene 31 dias
			return false;
		}
		
		if (month == 2) { // check for february 29th
			var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
			if (day > 29 || (day==29 && !isleap)) {
				//febrero no tiene n dias
				return false;
			}
		}
		//
		return true;
	}
});

//////////////////////////////////////////////////
//VERIFICA SI EL VALOR ENVIADO ES UN NUMERO
function isNumber(value) {
    return Number(value).toString() != 'NaN';
}

//////////////////////////////////////////////////
//FUNCION SOLAMENTE ACEPTA NUMEROS
function acceptNum(evt){
	// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57, 'up' = 38, 'down' = 40, 'left' = 37, 'right' = 39
	var key = evt.which || evt.keyCode;
	return (key <= 13 || (key >= 48 && key <= 57) || key == 37 || key == 39 );
}

//////////////////////////////////////////////////
//FUNCION SOLAMENTE ACEPTA NUMEROS Y PUNTO
function acceptNumPoint(evt){
	// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57, 'up' = 38, 'down' = 40, 'left' = 37, 'right' = 39, '.' = 46
	var key = evt.which || evt.keyCode;
	return (key <= 13 || (key >= 48 && key <= 57) || key == 46 || key == 37 || key == 39 );
}

//////////////////////////////////////////////////
//SIMULADOR DE PANTALLAS (PRESUPUESTOS)
var sim = {
	options:{
		mod: {
			'BEL16': [1.024, 0.768, "F", 64, 48, 3906, 75, 552, 14],
			'BEL25': [0.8, 0.8, "F", 32, 32, 1600, 75, 226, 20],
			'BEL762': [0.976, 0.732, "F", 128, 96, 17222, 55, 550, 6]
		},
		modelo: 'BEL16',
		init: false,
		tbl: false
	},
	data: {
		modelo:'', area:'', anchoTotal:'', altoTotal:'', resolucionVF:'', anchoPx:'', altoPx:'', densidadLP:'', densidad:'', peso:'', consumo:'', distancia:''
	},
	initialize: function() {
		var opt = this.options;
		if ( !opt.tbl )
			this.crearTabla();
		opt.rows = $$('.row');
		opt.items = $$('.item');
		opt.init = true
	},
	crearTabla: function() {
		var opt = this.options;
		for ( i = 9, f = 1; i > 0; i--, f++ ) {
			var row = new Element('div', {'class':'row'});
			for ( j = 1; j <= 9; j++ ) {
				var item = new Element('div', {'class':'item'}).inject(row);
				var link = new Element('a', {
					'href': '#',
					'html': j+'x'+i,
					'events': {
						'click': function (x, y, a) {
							sim.calculo(x, y, a);
							return false;
						}.pass([j, f, i])
					}
				}).inject(item);
			}
			row.inject('contenedor');
		}
		opt.tbl = true;
	},
	marcar: function() {
		var opt = this.options;
		opt.items.each(function(item, index) {
			item.removeClass('marcado')
		});
		this.options.rows.each(function(row, index) {
			if ((opt.y - 1) <= index)
				row.getElements('.item').each(function(item, indexItem){
					if ( indexItem < opt.x )
						item.addClass('marcado')
				});
		});
	},
	calculo: function (x, y, alto, modelo) {
		var opt = this.options;
		if (typeof(x) != 'undefined' && x != ''){
			opt.x = x;
			opt.ancho = x;
		}
		if (typeof(y) != 'undefined' && y != '')
			opt.y = y;
		if (typeof(alto) != 'undefined' && alto != '')
			opt.alto = alto;
		if (typeof(modelo) != 'undefined' && modelo != '')
			opt.modelo = modelo;
		if ( !opt.init )
			this.initialize();
		this.marcar();
		this.cargarDatos();
	},
	cargarDatos: function() {
		var opt = this.options;
		var hash = new Hash(opt.mod);
		if (!hash.has(opt.modelo))
			return false;
		var mod = opt.mod[opt.modelo];
		var anchoTotal = (mod[0] * opt.ancho).toFixed(3);
		var altoTotal = (mod[1] * opt.alto).toFixed(3);
		var anchoDemo = ( opt.ancho >= opt.alto )?(( mod[3] == mod[4] )?300:400):(anchoTotal * 300 / altoTotal);
		var altoDemo = ( opt.ancho > opt.alto )?(( mod[3] == mod[4] )?(altoTotal * 300 / anchoTotal):(altoTotal * 400 / anchoTotal)):300;
		var morph = new Fx.Morph('ripple', {duration: 400, wait: false});
		var s = $('ripple').getSize();
		morph.start({
			'width':[s.x, anchoDemo],
			'height':[s.y, altoDemo]
		});
		/*$('ripple').setStyles({
			'width': anchoDemo+'px',
			'height': altoDemo+'px'
		});*/
		
		var area = (anchoTotal * altoTotal).toFixed(2);
		var anchoPx = (mod[3] * opt.ancho).toFixed(0);
		var altoPx = (mod[4] * opt.alto).toFixed(0);
		var pesoMail = (area * mod[6]).toFixed(0);
		var consumo = (area * mod[7]).toFixed(0);
		
		$('ancho').set('html', anchoTotal);
		$('alto').set('html', altoTotal);
		
		$('modelo').set('html', opt.modelo);
		$('area').set('html', area);
		$('ancho_dato').set('html', anchoTotal);
		$('alto_dato').set('html', altoTotal);
		//$('resolucion_v').set('html', ( mod[2] == 'V' )?'Visual':'Física');
		//$('anchoPx').set('html', anchoPx);
		//$('altoPx').set('html', altoPx);
		//$('densidad_v').set('html', ( mod[2] == 'V' )?'LEDs':'pixeles');
		//$('densidad').set('html', mod[5]);
		$('peso').set('html', pesoMail);
		$('consumo').set('html', consumo);
		$('distancia').set('html', mod[8]);

		
		$('p_ancho_total').set('value', anchoTotal);
		$('p_alto_total').set('value', altoTotal);
		
		$('p_modelo').set('value', opt.modelo);
		$('p_area').set('value', area);
		
		
		$('p_ancho_px').set('value', anchoPx);
		$('p_alto_px').set('value', altoPx);
		
		$('p_peso').set('value', pesoMail);
		$('p_consumo').set('value', consumo);
		$('p_distancia').set('value', mod[8]);
		
		//--
		var d = this.data;
		d.modelo = opt.modelo; d.area = area; d.anchoTotal = anchoTotal; d.altoTotal = altoTotal; d.resolucionVF = ( mod[2] == 'V' )?'Visual':'Física'; d.anchoPx = anchoPx; d.altoPx = altoPx; d.densidadLP = ( mod[2] == 'V' )?'LEDs':'pixeles'; d.densidad = mod[5]; d.peso = pesoMail; d.consumo = consumo; d.distancia = mod[8];
		//--
		
		return false;
	}
}

//////////////////////////////////////////////////
//VALIDA EL FORMULARIO DEL PRESUPUESTADOR
function validaPresupuesto(idFrm) {
	var frm = $(idFrm);
	if (!frm)
		return false;
	var d = sim.data;
	/*frm.p_modelo.value = d.modelo;
	frm.p_area.value = d.area;
	frm.p_ancho_total.value = d.anchoTotal;
	frm.alto_total.value = d.altoTotal;
	frm.resolucion_vf.value = d.resolucionVF;
	frm.ancho_px.value = d.anchoPx;
	frm.alto_px.value = d.altoPx;
	frm.densidad_lp.value = d.densidadLP;
	frm.densidad.value = d.densidad;
	frm.peso.value = d.peso;
	frm.consumo.value = d.consumo;
	frm.distancia.value = d.distancia;
	*/
	//validar campos
	if (frm.nombre.value.trim() == "") {
		tips.show(frm.nombre);
		frm.nombre.focus();
		return false;
	}
	if (frm.email.value.trim() == "") {
		tips.show(frm.email);
		frm.email.focus();
		return false;
	} else if ( !frm.email.value.isMail() ) {
		tips.show(frm.email, 'E-MAIL::El e-mail proporcinado es inválido.');
		frm.email.focus();
		return false;
	}
	if (frm.telefono.value.trim() == "") {
		tips.show(frm.telefono);
		frm.telefono.focus();
		return false;
	}
	if (frm.ciudad.value.trim() == "") {
		tips.show(frm.ciudad);
		frm.ciudad.focus();
		return false;
	}
	
	tips.hide();
	
	
	$('div_btn').set('html', '<div id="loading" class="loading">Enviando...</div>');
	frm.submit();
	return true;
}
//////////////////////////////////////////////////
//VALIDA EL FORMULARIO DE CONTACTO
function validaContacto(idFrm) {
	var frm = $(idFrm);
	if (!frm)
		return false;
		
	//validar campos
	if (frm.nombre.value.trim() == "") {
		tips.show(frm.nombre);
		frm.nombre.focus();
		return false;
	}
	if (frm.email.value.trim() == "") {
		tips.show(frm.email);
		frm.email.focus();
		return false;
	} else if ( !frm.email.value.isMail() ) {
		tips.show(frm.email, 'E-MAIL::El e-mail proporcinado es inválido.');
		frm.email.focus();
		return false;
	}
	if (frm.telefono.value.trim() == "") {
		tips.show(frm.telefono);
		frm.telefono.focus();
		return false;
	}
	if (frm.code.value.trim() == "") {
		tips.show(frm.code);
		frm.code.focus();
		return false;
	}
	
	tips.hide();
	
	
	
	$('div_btn').set('html', '<div id="loading" class="loading">Enviando...</div>');
	frm.submit();
	return true;
}