var strSelectMaxThree = "Selezionare al massimo 3 prodotti";
var strSelectUpToThree = "Selezioni prego fino a tre prodotti";
var strInvalidEmailAddress = "Inserire un indirizzo e-mail valido";
var strNotSimilar = "Gli indirizzi e-mail sono diversi";
var strVPOLogin = "La password immessa non è corretta";
var strFillOut = "Compilare tutti i campi obbligatori";
var strInfoRequest = "Specificare il tipo di informazioni";
// this file contains functionality needed by NRG web pages

function reposition_related_link() {
document.getElementById('related_link_new_position').innerHTML = document.getElementById('related_link').innerHTML;
}

function showImg(imgID) {
	if (document.images['imgMain'] && document.images[imgID]) {
		document.images['imgMain'].src = document.images[imgID].src;
		document.images['imgMain'].style.display = 'block';
	} else {
		document.images['imgMain'].style.display = 'none';
	} 
//	alert (document.images['imgMain']);
//	alert (document.images[imgID]);
}

//random image picker
function pickImage(upperlimit, strID){
	// get a random number in the specified range (0 - upperlimit)
	var rndNumber = Math.round(upperlimit*Math.random());
	
	// create ID string
	var strSrcID = strID + rndNumber;

	//change the mainimage location
	var elmtSource = document.getElementById(strSrcID);
	var elmtTarget = document.getElementById(strID);
	if (elmtSource && elmtTarget) {
		elmtTarget.src = elmtSource.href;
	}
}

//This function replaces Show_Text_Block. Show_Text_Block should be removed.
function Show_Text_Block2(Menu_nr)
{
var Text_Block = ''; 
for (i=1; i<7; i++)
	{
	Text_Block = document.getElementById('text' + i);
	if (typeof Text_Block == 'object') 
		{
		Text_Block.style.display = 'none';
		document.getElementById('link' + i).className = "localnav006699boldclass5th";
		}
	} 
// show the selected text block and highlight the selected link
document.getElementById('text'+Menu_nr).style.display = '';
document.getElementById('link'+Menu_nr).className = "localnavff0000boldclass5th";
}

//------------------------- END OF DynamicHTML-------------------

// get the browser information

function getOsName( )

{

	var userOs      = "" ;

	var regexResult = "" ;

	var moreInfo    = true ;

	var usrAgent    = navigator.userAgent.toUpperCase( ) ;



	if ( usrAgent.indexOf("WIN") != -1 ) userOs = "Windows" ;

	if ( usrAgent.indexOf("MAC") != -1 ) userOs = "MacOS" ;

	if ( usrAgent.indexOf("X11") != -1 ) userOs = "UNIX" ;



	return userOs ;

}



function getBrowserName( )

{

	var userBrowser = "" ;

	var appName     = navigator.appName.toUpperCase( ) ;



	if ( appName.indexOf("NETSCAPE")  != -1 ) userBrowser = "Netscape" ;

	if ( appName.indexOf("MICROSOFT") != -1 ) userBrowser = "Explorer" ;



	return userBrowser ;

}



function getBrowserVersion( )

{

	var version    = "" ;

	var start      = 0  ;

	var end        = 0  ;

	var usrBrowser = getBrowserName( ) ;

	var usrAgent   = navigator.userAgent.toUpperCase( ) ;

	var appVersion = navigator.appVersion ;



	if ( usrBrowser == "Netscape" )

	{

		start   = appVersion.indexOf(" ",0) ;

		version = appVersion.substring(0,start) ;

	}

	if ( usrBrowser == "Explorer" )

	{

		start   = appVersion.indexOf("MSIE ",0) + 5 ;

		end     = appVersion.indexOf(";",start) ;

		version = appVersion.substring(start,end) ;

	}



	return version ;

}


function printStyleSheet( )
{
	var WIN_IE4_SRC = "/system/win_ie.css" ;
	var WIN_IE5_SRC = "/system/win_ie.css" ;
	var WIN_NN4_SRC = "/system/win_nn4.css" ;
	var WIN_NN6_SRC = "/system/win_ie.css" ;
	var WIN_OPERA_SRC = "/system/win_ie.css" ;

	var MAC_IE4_SRC = "/system/mac_ie.css" ;
	var MAC_IE5_SRC = "/system/mac_ie.css" ;
	var MAC_NN4_SRC = "/system/mac_nn4.css" ;
	var MAC_NN6_SRC = "/system/mac_nn.css" ;
	var MAC_OPERA_SRC = "/system/mac_nn.css" ;

	// put the browser information in variable
	var os      = getOsName( ) ;
	var browser = getBrowserName( ) ;
	var version = getBrowserVersion( ).charAt( 0 ) ;

	var cssSrc = null ;

	if ( os == "Windows" )
	{
		if ( browser == "Explorer" )
		{
			if ( version == 4 )
			{
				cssSrc = WIN_IE4_SRC ;
			}
			if ( version >= 5 )
			{
				cssSrc = WIN_IE5_SRC ;
			}
		}
		else if ( browser == "Netscape" )
		{
			if ( version == 4 )
			{
				cssSrc = WIN_NN4_SRC ;
			}
			if ( version >= 5 )
			{
				cssSrc = WIN_NN6_SRC ;
			}
		}
		else if ( browser == "OPERA" )
		{
			cssSrc = WIN_OPERA_SRC ;
		}
	}
	else if ( os == "MacOS" )
	{
		if ( browser == "Explorer" )
		{
			if ( version == 4 )
			{
				cssSrc = MAC_IE4_SRC ;
			}
			if ( version >= 5 )
			{
				cssSrc = MAC_IE5_SRC ;
			}
		}
		else if ( browser == "Netscape" )
		{
			if ( version == 4 )
			{
				cssSrc = MAC_NN4_SRC ;
			}
			if ( version >= 5 )
			{
				cssSrc = MAC_NN6_SRC ;
			}
		}
		else if ( browser == "OPERA" )
		{
			cssSrc = MAC_OPERA_SRC ;
		}
	}

	// output the stylesheet
	if ( cssSrc )
	{
		document.open( ) ;
		document.write( '<LINK REL="stylesheet" TYPE="text/css" HREF="' + cssSrc + '">' ) ;
		document.close( ) ;
	}
}


printStyleSheet( ) ;

//------------- END OF BrowserCheck --------------------------------


function cmdPrintPage()
{
	var lObjArrProperties = new Array()
	lObjArrProperties["Title"] = document.title
	var lObjAllPrintSpans = document.getElementsByName("PrintElement")
	if(lObjAllPrintSpans.length == 0)
	{
                                lObjArrProperties["NoElements"] = true
                               	lObjArrProperties["PrintElements"] = document.body.firstChild
	}
                else
                {
                                lObjArrProperties["NoElements"] = false
	                lObjArrProperties["PrintElements"] = lObjAllPrintSpans
                }


	var lStrFixedAttributes = "center:1;help:0;status:0;resizable:1;"
	var lStrSize			= "dialogWidth:800px;dialogHeight:600px;"
	var lStrPopupLocation	= "/system/printpage.xhtml"

	return showModalDialog(lStrPopupLocation, lObjArrProperties, lStrSize + lStrFixedAttributes);

}

function printwin()
{
               window.print();
}

function swapDisplay(element)
{
   var objULelement = element.parentNode.parentNode.children[1];
   for (i=0; i< objULelement.children.length; i++) {
      var objLIelement = objULelement.children[i];
   	if (objLIelement.style.display == "block") {
		objLIelement.style.display = "none";
	} else {
		objLIelement.style.display = "block";
   	}
   }
}


// Have Global Navigation MouseOver Swapped Static Ver.

function swaponBg(target) {
	if(window.opera){
		return true;
	}
	else{
		target.style.backgroundColor = '#006699';
	}
}

function swapoffBg(target) {
	if(window.opera){
		return true;
	}
	else{
		target.style.backgroundColor = '#44AADD';
	}
}

//this function checks if the VPO fields contain values
function vpoCheck(form){
	if ((form.username.value == "") || (form.password.value == "")){
		alert(strVPOLogin);
		return false;
	}	else	{
		return true;
	}
}

function checkWhenChecked(form, lastbox){
	// 3 products can be selected
	var total = 0;
	var box = null;
	var total = checkCheckedCheckBoxes(form);
	if (total > 3) {
		for (var cntProduct = 0; cntProduct < form.product.length; cntProduct++) {
			if (form.product[cntProduct].id == lastbox) {
				box = form.product[cntProduct];
				box.checked = false;
				alert(strSelectMaxThree);	
				return false;
			}
		}
	}	
}	

function checkProdSubmit(form) {
// at least one product must have been selected
var	total = 0;
total = checkCheckedCheckBoxes(form);
if (total < 1) {
	alert(strSelectUpToThree);
	}
else{
	form.submit();
	}
}

function checkCheckedCheckBoxes(form) {
//counts the number of checkboxes that was checked
var total = 0;
var max = form.product.length;
for (var counter = 0; counter < max; counter++) {
if (eval("form.product[" + counter + "].checked") == true) {
    total += 1;
   }
}
return total;	   
}

function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	alert(strInvalidEmailAddress)
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert(strInvalidEmailAddress)
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert(strInvalidEmailAddress)
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert(strInvalidEmailAddress)
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   alert(strInvalidEmailAddress)
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr=strInvalidEmailAddress
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}

function resetAll(form) {
	form.reset();
	return false;
}

function enewsCheck(form){
	var strEmail=form.email.value;
	var strConfirmEmail=form.confirmemail.value;

	if (emailCheck(strEmail)){
		if (strEmail == strConfirmEmail){
			return true;
		}
		else {
			alert(strNotSimilar);
			return false;
		}
	}
	else {
		return false;
		}	
}


function productFormCheck(form){
	var strEmail=form.email.value;
	var strFirstName=form.firstname.value;
	var strLastName=form.lastname.value;
	var strCity=form.city.value;
	var strPostal=form.postCode.value;
	var strTel=form.telephone.value;
	var strCountry=form.country.value;
	var blnSpecs=form.specification.checked;
	var blnLiterature=form.literature.checked;

	if (emailCheck(strEmail)) {
	 if (strFirstName == "" || strCity == "" || strPostal=="" || strLastName == "" || strCountry == "" || strTel == "") {
	 alert (strFillOut);
	 return false;
		} else {
				if (!(blnSpecs == true || blnLiterature == true)) {
				alert (strInfoRequest);
				return false;

				} else {
				return true;
				}
	 }
	}
	else {
		return false;
		}	
}

function feedbackformcheck(form){
	var strEmail=form.email.value;
	var strFirstName=form.firstname.value;
	var strLastName=form.name.value;
	var strPostcodeCity=form.postcode_city.value;
	var strTel=form.telephone.value;
	var strComment = form.comment.value;

	if (emailCheck(strEmail)) {
		if (strFirstName == "" || strLastName == "" || strPostcodeCity =="" || strTel == "" || strComment == "") {
			alert (strFillOut);
			return false;
		}
		return true;
	}
	return false;
}

function vpoRequestFormCheck(form){

	var strFirstName=form.firstname.value;
	var strLastName=form.lastname.value;
	var strEmail=form.email.value;
	var strPublication=form.publication.value;
	var strAddress=form.address.value;
	var strPostalCode=form.postalcode.value;
	var strCity=form.city.value;
	var strCountry=form.country.value;

	if (emailCheck(strEmail)) 
	{
		if (strFirstName == "") 
		{
			alert (strFillOut);
			return false;
		} 
		else 
		{
	 		if (strLastName == "") 
	 		{
				alert (strFillOut);
				return false;
			} 
			else 
			{
				if (strPublication == "") 
				{
					alert (strFillOut);
	    			return false;
				} 
				else 
				{

					if (strAddress == "") 
					{
						alert (strFillOut);
	    				return false;
					} 
					else 
					{
						if (strPostalCode == "") 
						{
							alert (strFillOut);
	    					return false;
						} 
						else 
						{
							if (strCity == "") 
							{
								alert (strFillOut);
	    						return false;
							} 
							else 
							{
								if (strCountry == "") 
								{
									alert (strFillOut);
	    							return false;
								} 
								else 
								{
									return true;
								}
							}
						}
					}
				}
			}
		}
	}
	else 
	{
		return false;
	}	
}


function forward(href){
location.href (href.value);
}




function openWin(img, varWidth, varHeight) {
if (varWidth==0){
varWidth=640;
}
if (varHeight==0){
varHeight=480;
}
window.open(img.href, '', 'toolbar=no , width=' + varWidth + ', height= ' + varHeight);
}


var blnDebug = false;
var blnDebug2 = false;
function myDebug (strM) {
	if (blnDebug) {
		alert (strM);
	}			
}
function myDebug2 (strM) {
	if (blnDebug2) {
		alert (strM);
	}			
}
function copyToNavigation() {
	myDebug('started');
	var elmtFrom = document.getElementById('copy_to_navigation');
	var elmtTo = document.getElementById('leftnavigation');
	if (! (elmtFrom && elmtTo)) {
		myDebug ('no to or no from elmt');
		return;
	}
	myDebug ('copying from ' + elmtFrom.id + ' to ' + elmtTo.id);
	myDebug (elmtFrom.innerHTML);
	var elmtLinkList = elmtFrom.getElementsByTagName('a');
	myDebug ('found ' + elmtLinkList.length + ' links');
	var arrSubdirs = new Array();
	for (var i = 0; i < elmtLinkList.length; i++) {
		var elmtLink = elmtLinkList[i];
		var strHref = elmtLink.href;
		var strTitle = elmtLink.innerHTML;
		myDebug ('found link ' + elmtLink.outerHTML);

		var strSubdir = getSubdirFromHref (strHref, 3);
		myDebug ('subdir: ' + strSubdir);
		if (strSubdir != '') {
			if (!arrSubdirs[strSubdir]) {
				myDebug ('new subdir');
				arrSubdirs[strSubdir] = new Array(elmtLink);
			} else {
				var intCurrentLength = arrSubdirs[strSubdir].length;
				myDebug ('existing subdir with ' + intCurrentLength + ' hrefs');
				arrSubdirs[strSubdir][intCurrentLength] = elmtLink;
			}					
		}
	}
	for (strSubdir in arrSubdirs) {
		myDebug2 ('processing ' + strSubdir);
		var arrHrefs = arrSubdirs[strSubdir];
		myDebug2 (arrHrefs.length + ' links');
		myDebug2 ('looking in ' + elmtTo.outerHTML);
		var elmtLiList = elmtTo.getElementsByTagName('li');
		myDebug2 ('found ' + elmtLiList.length + ' lis');

		var elmtTargetLi;
		for (var i = 0; i < elmtLiList.length; i++) {
			var elmtLi = elmtLiList[i];
			myDebug2 (elmtLi.outerHTML);
			var elmtLiLinkList = elmtLi.getElementsByTagName('a');
			for (var j = 0; j < elmtLiLinkList.length; j++) {
				myDebug2 ('link: ' + elmtLiLinkList[j]);
				var strTargetSubdir = getSubdirFromHref (elmtLiLinkList[j].href, 3);
				myDebug2 ('comparing ' + strSubdir + ' to ' + strTargetSubdir);
				if (strSubdir == strTargetSubdir) {
					myDebug2 ('found target subdir');
					elmtTargetLi = elmtLi;
					break;
				}
			}
			if (elmtTargetLi) {
				break;
			}
		}

		if (elmtTargetLi) {
			for (var i = 0; i < arrHrefs.length; i++) {								
				myDebug2 ('filling target li, inner html = ' + arrHrefs[i].innerHTML);
				var elmtNewLi = document.createElement('li');
				elmtNewLi.className = 'selected3';
				myDebug2 ('created elmt ' + elmtNewLi.outerHTML);
				var elmtNewA = document.createElement('a');
				elmtNewA.href = arrHrefs[i].href;
				elmtNewA.innerHTML = '- ' + arrHrefs[i].innerHTML;
				myDebug2 ('created elmt ' + elmtNewA.outerHTML);
				elmtNewLi.appendChild(elmtNewA);
				myDebug2 ('elmt new li now ' + elmtNewLi.outerHTML);
				
				var elmtNextLi = elmtTargetLi.nextSibling;
				if (elmtNextLi) {
					elmtTargetLi.parentNode.insertBefore (elmtNewLi, elmtNextLi);
				} else {
					elmtTargetLi.parentNode.appendChild (elmtNewLi);
				}
				myDebug2 ('ul now ' + elmtTargetLi.parentNode.outerHTML);
			}
			elmtTargetLi = null;
		}
	}
}

function getSubdirFromHref(strHref,intLevel) {

// ignore javascript links and local links
	var re = /^(javascript:|#)/;
	if (re.test(strHref)) {
		return '';
	}
	

// strip http://domain if it is there
	re = /^\w+:\/\/[a-zA-Z0-9_\-\.]*\//;
	if (re.test(strHref)) {
		strHref = strHref.replace(re, '/');
	}

	var arrSegments = strHref.split ('/');
	var strSubdir = '';
	if (arrSegments.length < intLevel + 1) {
		intLevel = arrSegments.length - 1;
	}
	
	// for safety, check if the intLevel is 1 or more, otherwise the while loop will be infinite!
	if (intLevel <=0) {
		return '';
	}
	while (intLevel--) {
		strSubdir = '/' + arrSegments[1+intLevel] + strSubdir;
	}
	return strSubdir;
}

function fixBreadCrumbs() {
	if(document.getElementById("breadcrumbs") && document.getElementById("breadcrumbs").getElementsByTagName("li")[2] && document.getElementById("breadcrumbs").getElementsByTagName("li")[2].innerHTML.indexOf("/products/") != -1 && document.getElementById("breadcrumbs").getElementsByTagName("li")[6] && document.getElementById("breadcrumbs").getElementsByTagName("a")[3]) {
		document.getElementById("breadcrumbs").getElementsByTagName("li")[6].innerHTML = document.getElementById("breadcrumbs").getElementsByTagName("a")[3].innerHTML;	
	}
}

function openURL(url){
	window.open(url, 'MultimediaClip','width=800,height=600,left=0,screenX=0,right=0,screenY=0,directories=0,fullscreen=0,resizable=1,menubar=0,scrollbars=0,status=0,toolbar=0,onBlur=self.focus()')
}
