function noop() {}


function sessionExport( varname, varvalue ) {
   var jspath = '../lib/regsession.php';
   var url = jspath + "?" + varname + '=' + varvalue;
	// prompt( '', url );
   var ajax = new Ajax( url );
   ajax.send();
}


var ProductImageList = function() {}
ProductImageList.m_ids = new Array();
ProductImageList.m_hidden = true;

ProductImageList.addImageId = function( id ) {
	// alert('adding ' + id);
	ProductImageList.m_ids.push( id );
}

ProductImageList.toggleImages = function() {
	for(i=0;i<ProductImageList.m_ids.length;i++) {
		var img = document.getElementById( ProductImageList.m_ids[i] );
		if( img ) {
			if( ProductImageList.m_hidden ) { // show element
				img.style.visibility = 'visible';
				img.style.display = '';
			} else { // hide element
				img.style.visibility = 'hidden';
				img.style.display = 'none';
			}
		}
	}
	ProductImageList.m_hidden = ! ProductImageList.m_hidden;
	sessionExport( 'SHOW_IMAGES_IN_LIST', ProductImageList.m_hidden ? 'false' : 'true' );
}

// Hack to add startsWith to a string
String.prototype.startsWith = function(sStart)
{
    return (this.substr(0,sStart.length)==sStart);
}

/**
Mostrar uma layer na posição actual do rato
@param id ID da layer
*/
function showAtMouse( id ) {
	var div = document.getElementById( id );
	var top = Event.MOUSEMOVE.pageY;
	var left = Event.MOUSEMOVE.pageX;
	div.style.top = top;
	div.style.left = left;
	alert( top + ":" + left );
	
// 	toggle( id, '' );
}


/**
Imprimir o produto
@param pid ID do produto
*/
function printWindow( pid ) {
	var href = 'print.php?reffab=' + pid + '&media=print';
	var opener = document;
	/*
	Features:
	status  	The status bar at the bottom of the window.
	toolbar 	The standard browser toolbar, with buttons such as Back and Forward.
	location 	The Location entry field where you enter the URL.
	menubar 	The menu bar of the window
	directories 	The standard browser directory buttons, such as What's New and What's Cool
	resizable 	Allow/Disallow the user to resize the window.
	scrollbars 	Enable the scrollbars if the document is bigger than the window
	height 	Specifies the height of the window in pixels. (example: height='350')
	width 	Specifies the width of the window in pixels.
	*/
	var title = 'print';
	var features = 'scrollbars=yes, toolbar=false, menubar=false, status=false, width=800, height=600';
	var w = document.open( href, title, features );
	w.focus();
// 	if( w.confirm( 'Quer imprimir os detalhes do produto?' ) ) {
		w.print();
// 	}
}

/**
Show form components
@param obj The form object
*/
function listFormFields( obj ) {
	var names = '';
	for( j=0; j<obj.elements.length; j++ ) {
		theName = obj.elements[j].name != '' ? obj.elements[j].name : 'NULL';
      	names +=  theName + '=' + obj.elements[j].value + '\n';
	}
	alert( names );
}

/**
Open a Window
@param url Page to open in the window
@param w Window's width
@param h Window's height
@param scroll Wether scrollbars are to be shown
*/
function openWindow( url, w, h, scroll ) {
	return window.open(url,"url","width="+w+",height="+h+",status=no,toolbar=no,menubar=no,location=no,resizable=yes,directories=no,scrollbars="+scroll);
}


/**
Submeter o formulário com um determinado id
@param formId O ID do formulário
*/
function submitform( formId ) {
// 	var form = document.getElementById( formId );
// 	if( form ) form.submit();
	var forms = document.getElementsByTagName("form");
	var str = '';
 	for( i=0; i<forms.length; i++ )
		str += forms[i].id + ';';
	alert ( str );
}

/**
Round a number with decimal places
@param number Number to round
@param dp Decimal places
*/
function decround( number, dp ) {
	var newnumber = Math.round(number*Math.pow(10,dp))/Math.pow(10,dp);
	return newnumber;
}

/**
 Hide/Show the layer specified in ID and switch the image, from the plus sign
 to minus if the layer is to be shown, and from minus to plus otherwise
 @param imgId The image ID
 @param id The layer ID
*/
function toggle( imgId, id ) {

	var img = document.getElementById( imgId );
	var submenu = document.getElementById( id );

	if( !submenu ) return;
		
	colapseOthers( id, submenu.className );
	
	if( submenu.style.visibility == 'hidden' || submenu.style.visibility == '' ) {
		submenu.style.visibility = 'visible';
		submenu.style.display = 'block';
		if( img ) {
			img.src = '../images/menu/minus.gif';
			img.alt = '-';
		}
	} else {
		submenu.style.visibility = 'hidden';
		submenu.style.display = 'none';
		if( img ) {
			img.src = '../images/menu/plus.gif';
			img.alt = '+';
		}
	}
	
}


/**
Toggle a layer by ID
@param id The layers ID
*/
function toggleInlineImg( divid, imgid, newImg ) {

	var layer = document.getElementById( divid );
	var img = document.getElementById( imgid );
	
	if( layer.style.visibility == 'hidden' || layer.style.visibility == '' ) {
		layer.style.visibility = 'visible';
		layer.style.display = 'block';
		if( img.src != '../images/pixel.gif' ) {
			img.src = newImg;
			img.style.visibility = 'visible';
			img.style.display = 'block';
		}
	} else {
		layer.style.visibility = 'hidden';
		layer.style.display = 'none';
	}

}

/**
 Show a specific layer and set the image to be the minus sign
 @param id The layer ID
 @param imgId The image ID
*/
function showDiv( id, imgId ) {
	
	var theDiv = document.getElementById( id );
	if( theDiv != null ) {
		theDiv.style.visibility = 'visible';
		theDiv.style.display = 'block';
	}
	
	var img = document.getElementById( imgId );
	if( img != null ) {
		img.src = '../images/menu/minus.gif';
	}
	
}

/** escupidela para o IE não dar erro no "javascript: foo()" */
function foo() {}

/**
Close all other layers at the same level then the layer width ID specifided in excluding.
The layers to hide will be searched by the name of their class (stylesheet)
@note See the implementation of Menu, MenuItem in the PHP code
@param exclude Exclude the layer with this ID
@param className The class name used to identify the level
*/
function colapseOthers( exclude, className ) {

	var divs = document.getElementsByTagName("div");
	var str = '';
 	for( i=0; i<divs.length; i++ ) {
		var div = divs[i];
		if( div.id != exclude && div.className == className ) {
			div.style.visibility = 'hidden';
			div.style.display = 'none';
			var img = document.getElementById( 'li_' + div.id );
			img.src = '../images/menu/plus.gif';	
		}
	}
 
}

/**
Close a layer
*/
function closeDiv( id ) {
	var div = document.getElementById( id );
	div.style.visibility = 'hidden';
	div.style.display = 'none';
}

/**
Show a layer
*/
function openDiv( id ) {
	var div = document.getElementById( id );
	div.style.visibility = 'visible';
	div.style.display = 'block';
}

/**
Return an object based on its ID
@param The object's ID
*/
function obj( id ) {
	return document.getElementById( id );
}

/**
Verifiy an email
@param email The E-Mail to verify
*/
function checkEmail(email) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))
		return true;
	// alert("O E-Mail introduzido não é válido!")
	return false;
}

/**
Show a specific layer (TabBar) 
@param id The layers ID
@param show TRUE to show
*/
function showTab( id, show ) {
// 	alert( id );
	var div = document.getElementById( id );
	if( div ) {
// 		alert( div.id );
		if( show ) {
			div.style.visibility = 'visible';
			div.style.display = '';
		} else {
			div.style.visibility = 'hidden';
			div.style.display = 'none';
		}
	}
}

/**
Change style to bold
@param id Layers ID
@param bold TRUE to bold, FALSE to un-bold
*/
function bold( id, bold ) {
	var div = document.getElementById( id );
	div.style.fontWeight = bold ? 'bold' : '';
}

//////////////////////// Pc Configuration ////////////////////////

/**
Actualizar o preco do item no configurador e o campo 'currentId' no
formulário
@param select A combo box
@param idprice ID da caixa do preco
@param mult Factor multiplicativo
@param idfield O campo que vai conter o ID
*/
function changePrice( select, idprice, mult, idfield ) {
	mult = '' ? 1 : mult;
	var data = select.value;
	var pricespan = document.getElementById( idprice );
	if( data == 'null' || data == -1 ) {
		select.style.backgroundColor = '';
		idfield.value = -1;
		value = 0;
	} else {
		select.style.backgroundColor='#aaa';
		var d = data.split( ';' );
		value = decround( parseFloat(d[1]) * parseInt(mult), 2 );
		idfield.value = d[0];
	}
	pricespan.innerHTML = value;
}

function changeAllPrices() {
	var forms = document.getElementsByTagName("form");
	for ( i=0; i<forms.length; i++ ) {
		if( forms[i].id.startsWith( 'pc_' ) ) {
			formid = forms[i].id;
			var form = document.getElementById( formid );
			changePrice( form.item, 'price_'+formid, form.mult.value, form.currentId );
		}
	}
}

/**
Procura por forms com o ID começado por 'pc_' e retira o valor do
campo price_<formid> para calcular os totais
@param idtotal ID da span para o toal
*/
function updatePcPrice() {
	var forms = document.getElementsByTagName("form");
	var sum = 0;
	var totalp = 0;
	var formid;
	var numpspan = document.getElementById( 'pc_totalp' );
	var totalspan = document.getElementById( 'pc_total' );
	for ( i=0; i<forms.length; i++ ) {
		if( forms[i].id.startsWith( 'pc_' ) ) {
			formid = forms[i].id;
			var pricespan = document.getElementById( 'price_' + formid );
			var price = parseFloat(pricespan.innerHTML)
			if( price != 0 ) totalp++;
			sum += price;
		}
	}
	if( numpspan && totalspan ) {
		totalspan.innerHTML = decround( sum, 2 );
		numpspan.innerHTML = totalp;
	}
	var addtocart = document.getElementById( "pcadd_cart" );
	if( addtocart ) {
		if( addtocart.doSubmit ) addtocart.doSubmit.disabled = totalp == 0 ;
		if( addtocart.doPrint ) addtocart.doPrint.disabled = totalp == 0 ;
		if( addtocart.pc_name ) addtocart.pc_name.disabled = totalp == 0 ;
	}
}

/**
Submeter os dados para a impressão da configuração
@param submitform O form contendo os campos pc_componentes e pc_labels
@param go Página para onde deve ser feito o POST dos dados
*/
function printConfiguration( submitform, go ) {

	if( submitform.pc_name.value == '' ) {
		alert( 'Tem que introduzir um nome para a configuração!' );
		submitform.pc_name.focus();
		return false;
	}

// 	submitform.doPrint.disabled = true;
	
	var forms = document.getElementsByTagName("form");
	var ids = '';
	var labels = '';
	var counts = '';
	for ( i=0; i<forms.length; i++ ) {
		if( forms[i].id.startsWith( 'pc_' ) ) {
			var f = forms[i];
			var id = f.currentId.value;
			if( id != -1 ) {
				ids += id + ',';
				labels += f.id + ',';
				counts += f.mult.value + ',';
			}
		}
	}
	submitform.pc_componentes.value = ids.substring(0, ids.length-1);
	submitform.pc_labels.value = labels.substring(0, labels.length-1);
	submitform.pc_counts.value = counts.substring(0, counts.length-1);
	
	submitform.action = go;
	
	var opener = document;
	
	var title = 'printWindow';
	var features = 'scrollbar=1, toolbar=false, menubar=false, status=false, width=800, height=600';
	var w = document.open( '', title, features );

// 	alert( submitform.target );

	submitform.target = 'printWindow';
	submitform.submit();
	
	w.focus();
	if( w.confirm( 'Quer imprimir a sua configuração?' ) ) {
		w.print();
	}

}

/**
Preencher o campo pc_componentes com os ids dos produtos, o pc_labels
com as labels de cada item
@param submitform O form contendo os campos pc_componentes e pc_labels
@param go para onde deve ser submetido o form
*/
function submitConf( submitform, go ) {

	if( submitform.pc_name.value == '' ) {
		alert( 'Tem que introduzir um nome para a configuração!' );
		submitform.pc_name.focus();
		return false;
	}
	
	submitform.doSubmit.disabled = true;
// 	submitform.pc_name.disabled = true;
	
	var forms = document.getElementsByTagName("form");
	var ids = '';
	var labels = '';
	var counts = '';
	for ( i=0; i<forms.length; i++ ) {
		if( forms[i].id.startsWith( 'pc_' ) ) {
			var f = forms[i];
			var id = f.currentId.value;
			if( id != -1 ) {
				ids += id + ',';
				labels += f.id + ',';
				counts += f.mult.value + ',';
			}
		}
	}
	submitform.pc_componentes.value = ids.substring(0, ids.length-1);
	submitform.pc_labels.value = labels.substring(0, labels.length-1);
	submitform.pc_counts.value = counts.substring(0, counts.length-1);
	
	submitform.action = go;
	submitform.target = '';
	
	return true;
}

//////////////////////// Pc Configuration (end) //////////////////

//////////////////////// OLD ////////////////////////////////

	function toggleLayer(id,idImg) {

		if( document.getElementById(id).style.display == '' ) {
			document.getElementById(id).style.display = 'none';
			document.getElementById(idImg).src = '../images/icons/plus.gif';
		} else {
			document.getElementById(id).style.display = '';
			document.getElementById(idImg).src = '../images/icons/minus.gif';
		}

	}

	function askDeleteEncomenda( num ) {
		return confirm( 'Tem a certeza que deseja apagar a encomenda n.º "' +
		num + '"?' );
	}

	function askDeleteCliente( email ) {
		return confirm( 'Tem a certeza que deseja apagar o cliente com o email "' +
		email + '"? \n Este processo apagará também todas as encomendas do cliente.' );
	}

	/**
	* Checks/unchecks all tables
	*
	* @param   string   the form name
	* @param   boolean  whether to check or to uncheck the element
	*
	* @return  boolean  always true
	*/
	function setCheckboxes(the_form, name, do_check)
	{
	
		for ( i=0 ; i < document.forms[the_form].elements.length; i++) {
			if(
				document.forms[the_form].elements[i].name.indexOf( name ) != -1
			) {
				document.forms[the_form].elements[i].checked = do_check;
			}
		}
		return true;
	}
	
	function checkMissing( obj ) {
		if( obj.missing.value == 1 ) {
			return confirm('As entradas em falta foram retiradas.\nQuer continuar mesmo assim?');
		}
	}
