//Event.observe('window', 'click', hideProductList);
/*document.observe('click', function(event){

					var elem = event.element()
					if (!elem.descendantOf('productList') && $('productList').visible() && (elem.id != 'productList'))
						$('productList').hide();
					}
)*/
//antes q nada agregamos la categoria montaje
//addCatego(104, 'Montaje');
//addObject('Montaje Ejemplo', 1, 1, 1, 104, 0, 0, 0);

var actualArrayPos = 0;
var goingTable = '';
var actualCat = 0;
var productsOrd = Array();
var lastIdOrd = 0;
var activeList = Array();
var rowTemplate = new Template('<tr id="itemTr_#{arrPos}" #{classe} ><td class="check"><input type="checkbox" onclick="uncheck(#{categoId}, #{arrPos})" #{check} name="check_#{arrPos}" id="check_#{arrPos}" /></td><td class="lup1"><a href="#{catURL}" target="_blank"><img src="images/lupita-presup.gif" width="10" height="12" alt="." border="0" /></a></td><td class="catego"><a href="#" onclick="showProductList(#{categoId}, #{arrPos}); return false;">#{categoName}</a></td>#{proHref}<td class="qtty"><input onkeyup="redrawSubTotales(#{arrPos});" type="text" value="1" name="qtty_#{arrPos}" id="qtty_#{arrPos}" /></td><td valign="middle" class="precio"><div id="precio_#{arrPos}">#{productPrice}</div></td></tr>');
var hrefTemplate = new Template('<td class="lup2"><a href="#{productURL}" target="_blank"><img src="images/lupita-presup.gif" width="10" height="12" alt="." border="0" /></a></td><td class="item"><a href="#" onclick="showProductList(#{categoId}, #{arrPos}); return false;">#{productName}</a></td>');
var devolTemplate = new Template('#{devolucion} <img src="#{devImg}" width="7" height="7" border="0" />');
var totalTemplate = new Template('<table width="655" border="0" align="center" cellpadding="0" cellspacing="0"><tr><td width="170" height="40" align="center" class="leftToo">Base Imponible<br />#{baseImponible}</td><td width="139" align="center">% IVA<br />16,0</td><td width="173" align="center">Importe IVA<br />#{importeIVA}</td><td width="173" align="center">Total Presupuesto<br /><span class="totalPresup">#{totalPresup}</span></td></tr></table>');
var defaultCats = [
	{id: 1, checkd: 1},
	{id: 2, checkd: 0},
	{id: 96, checkd: 1},
	{id: 3, checkd: 1},
	{id: 4, checkd: 1},
	{id: 5, checkd: 1},
	{id: 6, checkd: 1},
	{id: 7, checkd: 1},
	{id: 8, checkd: 1},
	{id: 93, checkd: 1},
	{id: 10, checkd: 1},
	{id: 27, checkd: 1},
	{id: 11, checkd: 1},
	{id: 12, checkd: 1},
	{id: 15, checkd: 1},
	{id: 103, checkd: 1}
	];

function firstProduct(catId) {
	var tmp_pr = Array();
	for (var i = 0; i < articulos.length; i++) {
		if (articulos[i].cat == catId)
			tmp_pr[tmp_pr.length++] = articulos[i];
	}

	tmp_pr.sort(SortRank);

	return tmp_pr[0];
}

function devol(devolucion) {
	var devImg = '', simbolo = '%';

	if (devolucion != 88) {
			 if (devolucion > 3) devImg = '/imf-dis/semaforo-rojo.gif';
		else if (devolucion > 2) devImg = '/imf-dis/semaforo-naranja.gif';
		else if (devolucion > 1) devImg = '/imf-dis/semaforo-amarillo.gif';
		else 					 devImg = '/imf-dis/semaforo-verde.gif';

		devolucion = fmtMoney(devolucion, 1, ",", '.');
	} else {
		devolucion = 'S/D';
		simbolo = '';
		devImg = '/imf-dis/semaforo-gris.gif';
	}

	return {devImg: devImg, devolucion: devolucion +' '+ simbolo};
}

function clearSearchField() {
	if ($F('q') == 'Buscar Articulo') $('q').clear();
}
function whenLoad() {

	/*Autocompletamos el presupuesto*/
	for (var i = 0; i < defaultCats.length; i++) {

		var arti = firstProduct(defaultCats[i].id);

		if ((defaultCats[i].id == 1) && (arti.descripcion.toLowerCase().indexOf('intel') >= 0)) {
			defaultCats[1].checkd = 1
			defaultCats[2].checkd = 0
		}

		if  (defaultCats[i].checkd != 0) {
			var check_checkd = 'checked="checked"';
			var proLink = hrefTemplate.evaluate({
										   productName: arti.descripcion,
										   productURL: GetURL(getCategoStr(defaultCats[i].id) +' '+ arti.descripcion)+'.php',
										   categoId: arti.cat,
										   arrPos: lastIdOrd
										   });

			var proPrce = fmtMoney(arti.precio, 2, ",", '.') + '  &euro;';

			productsOrd[lastIdOrd] = {
				idRow: lastIdOrd,
				descr: arti.descripcion,
				idCat: arti.cat,
				price: arti.precio,
				devol: arti.devolucion,
				table: 0,
				defau: 1
			};

		} else {
			var check_checkd = '';
			var proLink	= '<td class="lup2"><img src="images/lupita-presup.gif" width="10" height="12" alt="." border="0" /></td><td class="item">&nbsp;</td>';
			var proPrce = '&nbsp;';

			productsOrd[lastIdOrd] = {
				idRow: lastIdOrd,
				descr: '',
				idCat: 0,
				price: 0,
				devol: 0,
				table: 0,
				defau: 1
			};

		}

		$('ordenador').insert(
			rowTemplate.evaluate({
				categoId: defaultCats[i].id,
				categoName: getCategoStr(defaultCats[i].id),
				check: check_checkd,
				catURL: GetURL(getCategoStr(defaultCats[i].id))+'.htm',
				proHref: proLink,
				productPrice: proPrce,
				arrPos: lastIdOrd,
				devol: devolTemplate.evaluate(devol(productsOrd[lastIdOrd].devol)),
				classe: ''
			})
		);

		lastIdOrd++;

	}

	/*rellenamos el campo familia en el listado/buscador de productos*/
	for (var i = 0; i < categorias.length; i++) {
			$('familia').insert('<option value="'+categorias[i].id+'">'+categorias[i].name+'</option>');
	}

	/*arreglamos los left de los dialogos*/
	$('presupSent').setStyle({
		left: ($('presupuesto-holder').getWidth() / 2) - (81) + 'px',
		opacity: 1,
		display: 'none'
	});

	redrawSubTotales();

}
function debug() {
	$('debug').update(Object.toJSON(productsOrd));
}
function showProductList(idCatego, arrPos) {
	var topp = '100px';
	var leftt = ($('presupuesto-holder').getWidth() / 2) - ($('productList').getWidth() / 2) + 3 + 'px';
	//var topp = parseInt($(linkElement).cumulativeOffset().top) + 20 + 'px';
	//var leftt = $(linkElement).cumulativeOffset().left + 10 + 'px';

	$('productList').setStyle({
	top:  topp,
	left: leftt
	});

	$('itemAddedMsg').setStyle({
	left: ($('presupuesto-holder').getWidth() / 2) - (81) + 'px',
	opacity: 1,
	display: 'none'
	});

	if (idCatego > 0) $('familia').disable();
	else 			  $('familia').enable();

	$('familia').selectedIndex = 0;
	$('q').value = 'Buscar Articulo';

	actualArrayPos = arrPos;
	actualCat = idCatego;

	if (idCatego >= -1)		 goingTable = 0;
	else if (idCatego == -2) goingTable = 1;

	newActiveList(idCatego);


	$('productList').show();
	return false;
}
function uncheck(idCatego, arrPos) {

	if ($('check_'+arrPos).checked) {

		if ( arrPos < 0 ) $('check_'+arrPos).checked = false;
		return showProductList(idCatego, arrPos);

	}

	if (productsOrd[arrPos].defau == 1) {
		//productsOrd[arrPos] = '';

		var proLink	= '<td class="lup2"><img src="images/lupita-presup.gif" width="10" height="12" alt="." border="0" /></td><td class="item">&nbsp;</td>';
		var proPrce = '&nbsp;';

		var newRow = rowTemplate.evaluate({
							categoId: idCatego,
							categoName: getCategoStr(idCatego),
							check: '',
							catURL: GetURL(getCategoStr(defaultCats[arrPos].id))+'.htm',
							proHref: proLink,
							productPrice: '&nbsp;',
							arrPos: arrPos,
							devol: devolTemplate.evaluate(devol(productsOrd[arrPos].devol)),
							classe: ''
						});

		var trToReplace = $('itemTr_'+arrPos).replace(newRow);
		//esto pone a 0 el elemento
		productsOrd[arrPos] = {
				idRow: arrPos,
				descr: '',
				idCat: 0,
				price: 0,
				devol: 0,
				table: 0,
				defau: 1
			};

	} else {
		var trToReplace = $('itemTr_'+arrPos).up().remove();
		//esto borra el elemento
		productsOrd[arrPos] = null;
		productsOrd = productsOrd.compact();
	}

	 redrawSubTotales()
}
function selectProduct(ordenador, arrPos, itemPos) {

	tablaToUse = (ordenador == 0) ? 'ordenador' : 'otros-articulos';

	if (ordenador != 0) {
	$$('table.addmore').each(function(elem){elem.setStyle({borderTop: 'none'})})
	}

	$$('tr.last').each(function(elem){elem.removeClassName('last')})

	arrPosNew = (arrPos < 0) ? lastIdOrd++ : arrPos;

	var defau = (Object.isUndefined(productsOrd[arrPosNew])) ? 0 : productsOrd[arrPosNew].defau;

	productsOrd[arrPosNew] = {
			idRow: arrPosNew,
			descr: activeList[itemPos].descripcion,
			idCat: activeList[itemPos].cat,
			price: activeList[itemPos].precio,
			devol: activeList[itemPos].devolucion,
			table: goingTable,
			defau: defau
	};

	var check_checkd = 'checked="checked"';
	var proLink = hrefTemplate.evaluate({
								   productName: activeList[itemPos].descripcion,
								   productURL: GetURL(getCategoStr(activeList[itemPos].cat) +' '+ activeList[itemPos].descripcion)+'.php',
								   categoId: activeList[itemPos].cat,
								   arrPos: arrPosNew
								   });

	var proPrce = fmtMoney(activeList[itemPos].precio, 2, ",", '.') + '  &euro;';


	var newRow = rowTemplate.evaluate({
			categoId: 		activeList[itemPos].cat,
			categoName: 	getCategoStr(activeList[itemPos].cat),
			check: 			check_checkd,
			proHref: 		proLink,
			catURL: 		GetURL(getCategoStr(activeList[itemPos].cat))+'.htm',
			productPrice: 	proPrce,
			arrPos: 		arrPosNew,
			devol: 			devolTemplate.evaluate(devol(activeList[itemPos].devolucion)),
			classe: 'class="last"'
	});

	if (arrPos >= 0) {
		var trToReplace = $('itemTr_'+arrPos).replace(newRow);
	} else {
		$(tablaToUse).insert(newRow);
	}

	$('productList').hide();
	$('itemAddedMsg').show();
	Effect.Fade('itemAddedMsg', { duration: 3.0, from:1, to:0 });
	redrawSubTotales();
}
function newActiveList(idCatego, boton) {
	activeList = [];


	if ($('familia').disabled) idCatego = (idCatego == -1) ? actualCat : idCatego;
	else idCatego = $F('familia');

	query = ($F('q') == '' || $F('q') == 'Buscar Articulo') ? '' : $F('q');

	if (((idCatego != 0) && (query == '')) || !boton) {
		for (var i = 0; i < articulos.length; i++) {
			if (articulos[i].cat == idCatego) activeList[activeList.length++] = articulos[i];
		}
	} else if (query != '') {
		//determino las keywords
		var keywords = query.match(/"[^"]*"|[^ ]*/g);
		keywords = array_delEmpty(unique(keywords));

		for (i = 0; i < articulos.length; i++) {

			var articulo = getCategoStr(articulos[i].cat)+' '+articulos[i].descripcion.toLowerCase();

			if (
			keywordsInStr(keywords, articulo) &&
			((articulos[i].cat == idCatego) || (idCatego == 0))
			) {
				activeList[activeList.length++] = articulos[i];
			}

		}

	}

	activeList.sort(SortRank);

	buildProductList();
}
function buildProductList() {

	$('produListTable').update('');
	/*var rowTemplatePrL = new Template(
	 '<tr>'+
        '<td width="20">&nbsp;</td>'+
        '<td width="94" class="catName"><div style="width:94px; overflow:hidden; white-space:nowrap">#{categoName}</div></td>'+
        '<td width="3">&nbsp;</td>'+
        '<td width="81">'+
		'#{rankStr}'+
		'</td>'+
        '<td width="10" align="left">&nbsp;</td>'+
        '<td width="310"><div class="artName"><a href="#" onclick="selectProduct(#{ordenador}, #{arrayPos}, #{itemPos}); return false;">#{productName}</a></div></td>'+
        '<td width="57" align="right" nowrap="nowrap"><strong>#{price}</strong></td>'+
        '<td width="12" align="center">&nbsp;</td>'+
        '<td>#{stockGraph} #{stock}</td>'+
      '</tr>'
	);*/
	var rowTemplatePrL = new Template(''+
	'<div class="trtable clearfix">'+
    	'<div class="lup1"><a href="#{catURL}" target="_blank"><img class="lup" src="images/lupita-presup.gif" alt="." width="10" height="12" border="0" /></a></div>'+
        '<div class="catego">#{categoName}</div>'+
        '<div class="dots">#{rankGraph}</div>'+
        '<div class="rankpos">#{rankPos} #{rankUD}</div>'+
        '<div class="lup2"><a href="#{productURL}" target="_blank"><img class="lup" src="images/lupita-presup.gif" alt="." width="10" height="12" border="0" /></a></div>'+
        '<div class="desc"><a href="#" onclick="selectProduct(#{ordenador}, #{arrayPos}, #{itemPos}); return false;">#{productName}</a></div>'+
        '<div class="precio">#{price}</div>'+
        '<div class="squares">#{stockGraph}</div>'+
        '<div class="stock">#{stock}</div>'+
        '<div class="devol">#{devol}</div>'+
    '</div>');



	for (var i = 0; i < activeList.length; i++) {
		/*puntos rank*/
		var to = Math.floor(activeList[i].iRank / 2);
		var produRankGraph = '<span class="punto-arial-13p">';
		for(var u = 1; u <= to; u++) {
			produRankGraph+= '&#9679;';
		}
		produRankGraph+= (activeList[i].iRank%2 != 0) ? '</span><span class="punto-arial-9p">&#9679;</span>' : '</span>';

		switch(activeList[i].iUpDown) {
			case 0: produRankUD = '<span class="punto-stock-verde">&#9650;</span>'; produRankPos = activeList[i].rank; break;
			case 1: produRankUD = '<span class="punto-stock-rojo">&#9660;</span>'; produRankPos = activeList[i].rank; break;
			case 2: produRankUD = '<img align="absbottom" src="images/nuevo-presupuesto.gif"/>'; produRankPos = ''; break;
			case 3: produRankUD = '<img align="absbottom" src="images/oferta-presupuesto.gif"/>'; produRankPos = ''; break;
		}

		/* stock */
		var produStockGraph = '<span class="punto-stock-verde">';
		for(u = 1; u <= activeList[i].iStock; u++) {
			produStockGraph+= '&#9632;';
		}
		produStockGraph+='</span><span class="punto-stock-rojo">';
		for(u = activeList[i].iStock+1; u <= 4; u++) {
			produStockGraph+= '&#9632;';
		}
		produStockGraph+='</span>';


		$('produListTable').insert(
			rowTemplatePrL.evaluate({
				categoName:	getCategoStr(activeList[i].cat),
				productURL: GetURL(getCategoStr(activeList[i].cat) +' '+ activeList[i].descripcion)+'.php',
				catURL: 	GetURL(getCategoStr(activeList[i].cat))+'.htm',
				rankGraph: 	produRankGraph,
				rankPos:	produRankPos,
				rankUD:		produRankUD,
				productName:activeList[i].descripcion,
				price: 		fmtMoney(activeList[i].precio, 2, ",", '.') + '  &euro;',
				stockGraph:	produStockGraph,
				stock:		activeList[i].stock,
				devol:		devolTemplate.evaluate(devol(activeList[i].devolucion)),
				ordenador: 	goingTable,
				arrayPos: 	actualArrayPos,
				itemPos:	i
			})
		)
	}

}
function redrawSubTotales(arrPos) {
	var subA = 0;
	var subB = 0;

	if (typeof(arrPos) != 'undefined')
	$('precio_'+arrPos).update(fmtMoney(productsOrd[arrPos].price * $F('qtty_'+productsOrd[arrPos].idRow), 2, ",", '.') +' &euro;')

	for (i = 0; i < productsOrd.length; i++) {
		if (productsOrd[i].table == 0)	subA+=productsOrd[i].price * $F('qtty_'+productsOrd[i].idRow)
		else 							subB+=productsOrd[i].price * $F('qtty_'+productsOrd[i].idRow)
	}

	var total = subA + subB;
	var base = total / 1.16;
	var iva = total - base;


	$('total-ordenador').update(fmtMoney(subA, 2, ",", '.') +' &euro;');
	$('total-otros').update(fmtMoney(subB, 2, ",", '.') +' &euro;');

	$('presupuesto-total').update(totalTemplate.evaluate({
														 baseImponible: fmtMoney(base, 2, ",", '.')+' &euro;' ,
														 importeIVA: fmtMoney(iva, 2, ",", '.')+' &euro;',
														 totalPresup: fmtMoney(total, 2, ",", '.')+' &euro;'
														 }))
	var hiddenTemplate = new Template('<input name="#{name}" type="hidden" id="#{name}" value="#{value}" />')
	var totales = '';

	[
		{value: subA, name: "subtotalA"},
		{value: subB, name: "subtotalB"},
		{value: base,  name: "base_imp"},
		{value: iva ,  name: "imp_iva"},
		{value: total,  name: "total_pr"}
	].each(
		function(field) {
			totales+=hiddenTemplate.evaluate({
											name: field.name,
											value: field.value
											})
		}
	)

	$('hiddens').update(totales);
}
function sendEmail() {

var descripciones = Array();
var categorias = Array();
var precios = Array();
var tablas = Array();
var cantds = Array();
var largo = 0;

/*descr: activeList[itemPos]['DESC'],
idCat: activeList[itemPos].cat,
price: activeList[itemPos].precio,
*/
	var except = false;
	fields = [
	 {fname: 'email_send', label: 'E-mail', mail: true}/*,
	 {fname: 'name_send', label: 'Nombre', mail: false},
	 {fname: 'coment_send', label: 'Comentario', mail: false},
	 {fname: 'name_client', label: 'Nombre', mail: false},
	 {fname: 'email_client', label: 'E-mail', mail: true},
	 {fname: 'tel_client', label: 'Teléfono', mail: false}*/
	].each(function(e) {
		if ($F(e.fname) == '') {
			alert('Complete el campo '+e.label+' por favor');
			$(e.fname).activate();
			except = true;
			throw $break;
		}

		if ((e.mail) && ( !$F(e.fname).match(/[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/)/*regex*/)/*term*/)/*if*/ {
			alert('Debe ingresar un E-Mail v&aacute;lido');
			$(e.fname).activate();
			except = true;
			throw $break;
		}
	})

	if (except) return false;

	for(i = 0; i < productsOrd.length; i++) {

		if( productsOrd[i].idCat != 0 ) {
			descripciones[largo] = productsOrd[i].descr;
			categorias[largo] = productsOrd[i].idCat;
			precios[largo] = productsOrd[i].price;
			cantds[largo] = $F('qtty_'+productsOrd[i].idRow) || 1;
			tablas[largo] = productsOrd[i].table;
			largo++;
		}

	}

	params = {
		idPresupuesto: $F('presupNumb'),

		"products[]": descripciones,
		"categos[]": categorias,
		"prices[]": precios,
		"cantds[]": cantds,
		"tables[]": tablas,


		name_dest: $F('name_send'),
		email_dest: $F('email_send'),
		coment_dest: $F('coment_send'),

		name_client: $F('name_client'),
		email_client: $F('email_client'),
		tel_client: $F('tel_client'),


		subtotalA: $F('subtotalA'),
		subtotalB: $F('subtotalB'),
		base_imp: $F('base_imp'),
		imp_iva: $F('imp_iva'),
		total_pr: $F('total_pr'),

		suscribir:  0
	}

	if ($('suscBoletin').checked)
		showTemsAndConditions($F('email_send'));


	new Ajax.Request('template.php', {
					 	parameters:params,
					 	onCreate: function() {
							$('resultado').update('<img src="images/ajax-loader.gif" width="16" height="16" alt="Espere..." />')
						},
						onComplete: function(elem) {
							if (elem.responseText == 'ok') {
							$('resultado').update('El Presupuesto se envio correctamente!');
							$('presupSent').show();
							Effect.Fade('presupSent', { duration: 3.0, from:1, to:0 });
							} else
							$('resultado').update('Error al enviar presupuesto')
						}
					 })

}
function printPresup() {
	window.ifrprint.$('presupuesto').update($('presupuesto').innerHTML)

	for(i = 0; i < productsOrd.length; i++) {
		window.ifrprint.$('qtty_'+productsOrd[i].idRow).replace($F('qtty_'+productsOrd[i].idRow))
	}

	/*$('presupuesto-holder').insert(
					{top: '<div id="presupuesto-ty">Gracias por confiar en APP!</div>'}
					)*/
	window.ifrprint.focus();
	window.ifrprint.window.print()
//	window.ifrprint.window.print();
}

function showTemsAndConditions(email) {
	$('presupuesto-holder').insert(new Element('div', {id: 'temsAndConds'}).setStyle({top: "710px"}).update('<p>De acuerdo con lo establecido por la Ley Org&aacute;nica 15/1999, de 13 de diciembre, de Protecci&oacute;n de Datos de Car&aacute;cter Personal, doy mi consentimiento para que estos datos sean incluidos en un fichero del que es titular APP Inform&aacute;tica, Asesor&iacute;a y Programaci&oacute;n Profesional S.L. y puedan ser utilizados para el env&iacute;o de informaci&oacute;n sobre las tiendas APP as&iacute; como ofertas de sus productos y servicios. Asimismo, se le informa tambi&eacute;n de que tiene el derecho a acceder a los datos, a rectificarlos y cancelarlos en su caso, as&iacute; como a oponerse a su tratamiento en los t&eacute;rminos contemplados en la referida Ley Org&aacute;nica 15/1999. Estos derechos podr&aacute; ejercerlos en la siguiente direcci&oacute;n: APP Inform&aacute;tica, Asesor&iacute;a y Programaci&oacute;n Profesional S.L.  C/Pintor Sorolla, 9 pta 2 46002 Valencia.</p><div class="bntholder clearfix"><a href="#" id="suscribirOk" onclick="suscribirEmail(\''+email+'\'); return false;">Continuar</a><a id="suscribirCancel" href="#" onclick="$(\'temsAndConds\').remove(); return false;">Cancelar</a></div>'));
}