/* Funciones del menu de HEADER */
/* -.- */
 

function mtPopUp(address, width, height) {
	if(typeof width  == 'undefined'){ width  = 560; }
	if(typeof height == 'undefined'){ height = 300; }
	var winPopUp;
	winPopUp = window.open(address, '', 'toolbar=0,statusbar=0,scrollbars=yes,location=0,menubar=0,resizable=0,width=' + width + ',height=' + height + ',left = 100,top = 100');
} 
function mtPopUpText(address) {
	var winPopUp;
	winPopUp = window.open(address, '', 'toolbar=0,statusbar=0,scrollbars=yes,location=0,menubar=0,resizable=1,width=700,height=500,left=100,top=100');
} 
function mtMenuHeaderOut(oThis){
	oThis.className='ButtonHeader';
	oThis.style.cursor = 'default';
}

function mtMenuHeaderOver(oThis){
	oThis.className='ButtonHeaderSelect';
	oThis.style.cursor = 'hand';
}

function mtMenuHeaderOutSelected(oThis){
	oThis.style.cursor = 'default';
}

function mtMenuHeaderOverSelected(oThis){
	oThis.style.cursor = 'hand';
}

function mtMenuHeaderClick(oThis, sUrl){
		window.location=sUrl;
}


/* Funciones del menu de LEFT */

var arrMenuLabel = new Array();
			

function mtMenuSectionsOut(oName){
	identity=document.getElementById("tr"+oName);
	identity.className='boton-bg';
	identity.style.cursor = 'default';

	var imgFlecha;	
	imgFlecha=document.getElementById("imgFlecha"+oName);
	if (imgFlecha != null){
		imgFlecha.src="/images/boton-flecha.gif"
	}
	
	
	var imgBordeDerecho;	
	imgBordeDerecho=document.getElementById("imgBordeDerecho"+oName);
	if (imgBordeDerecho != null){
		imgBordeDerecho.src="/images/boton-rightborder.gif"
	}
	
}

function mtMenuSectionsChildOut(oNameOption, oNameSelectedOption){
	
	if (oNameOption!=oNameSelectedOption){
		mtMenuSectionsOut(oNameOption);
	}
	
}

function mtMenuSectionsOver(oName){
	identity=document.getElementById("tr"+oName);
	identity.className='boton-bgSelect';
	identity.style.cursor = 'hand';

	var imgFlecha;	
	imgFlecha=document.getElementById("imgFlecha"+oName);
	if (imgFlecha != null){
		imgFlecha.src="/images/boton-flecha-over.gif"
	}
	
	var imgBordeDerecho;	
	imgBordeDerecho=document.getElementById("imgBordeDerecho"+oName);
	if (imgBordeDerecho != null){
		imgBordeDerecho.src="/images/boton-rightborder-over.gif"
	}
	
}


function mtMenuSectionsClick(oName){
	oThis=document.getElementById("LinkMenu"+oName);
	if(event.srcElement.tagName=='TD'){
		oThis.children.tags('A')[0].click();
	 }
}






/* Ver que quitar */


// MENU MOUSE OVER 
function menuOver(itemName) {
 clearTimeout(timeOn)
 menuActive = 1
}

// MENU MOUSE OUT 
function menuOut(itemName) {
 if(document.layers) {
 	menuActive = 0 
 	timeOn = setTimeout("hideAllMenus()", 400)
  }
}

// SET BACKGROUND COLOR 
function getImage(name) {
  if (document.layers) {
    return findImage(name, document);
  }
  return null;
}



function findImage(name, doc) {
  var i, img;
  for (i = 0; i < doc.images.length; i++)
    if (doc.images[i].name == name)
      return doc.images[i];
  for (i = 0; i < doc.layers.length; i++)
    if ((img = findImage(name, doc.layers[i].document)) != null) {
      img.container = doc.layers[i];
      return img;
    }
  return null;
}



function getImagePageLeft(img) {
  var x, obj;
  if (document.layers) {
    if (img.container != null)
      return img.container.pageX + img.x;
    else
      return img.x;
  }
  return -1;
}

function getImagePageTop(img) {
  var y, obj;
  if (document.layers) {
    if (img.container != null)
      return img.container.pageY + img.y;
    else
      return img.y;
  }
  return -1;
}

//document.write('<style> .menu{position: absolute;}</style>');
var timeOn = null
var numMenus = 100;
document.onmouseover = hideAllMenus;
document.onclick = hideAllMenus;
window.onerror = null;

function getStyleObject(objectId) {
    // cross-browser function to get an object's style object given its id
    if(document.getElementById && document.getElementById(objectId)) {
	// W3C DOM
	return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
	// MSIE 4 DOM
	return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
	// NN 4 DOM.. note: this won't find nested layers
	return document.layers[objectId];
    } else {
	return false;
    }
} 

// getStyleObject

function changeObjectVisibility(objectId, newVisibility) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.visibility = newVisibility;
	return true;
    } else {
	//we couldn't find the object, so we can't change its visibility
	return false;
    }
}


 // changeObjectVisibility


function showMenu(menuNumber, eventObj, labelID) {
    hideAllMenus();
	if(document.layers) {
	img = getImage("img" + menuNumber);
 	x = getImagePageLeft(img);
 	y = getImagePageTop(img);
 	menuTop = y; // LAYER TOP POSITION
	eval('document.layers["menu'+menuNumber+'"].top="'+menuTop+'"');
 	eval('document.layers["menu'+menuNumber+'"].left="'+x+'"');
	}
	eventObj.cancelBubble = true;
    var menuId = 'menu' + menuNumber;
    if(changeObjectVisibility(menuId, 'visible')) {
	return true;
    } else {
	return false;
    }
}

function hideAllMenus() {
    for(counter = 1; counter <= numMenus; counter++) {
	changeObjectVisibility('menu' + counter, 'hidden');
    }
}




function moveObject(objectId, newXCoordinate, newYCoordinate) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.left = newXCoordinate;
	styleObject.top = newYCoordinate;
	return true;
    } else {
	// we couldn't find the object, so we can't very well move it
	return false;
    }
} // moveObject





// ***********************
// hacks and workarounds *
// ***********************

// initialize hacks whenever the page loads
window.onload = initializeHacks;

// setup an event handler to hide popups for generic clicks on the document
function initializeHacks() {
    // this ugly little hack resizes a blank div to make sure you can click
    // anywhere in the window for Mac MSIE 5
    if ((navigator.appVersion.indexOf('MSIE 5') != -1) 
	&& (navigator.platform.indexOf('Mac') != -1)
	&& getStyleObject('blankDiv')) {
	window.onresize = explorerMacResizeFix;
    }
    resizeBlankDiv();
    // this next function creates a placeholder object for older browsers
    createFakeEventObj();
}



function createFakeEventObj() {
    // create a fake event object for older browsers to avoid errors in function call
    // when we need to pass the event object to functions
    if (!window.event) {
	window.event = false;
    }
} // createFakeEventObj



function resizeBlankDiv() {
    // resize blank placeholder div so IE 5 on mac will get all clicks in window
    if ((navigator.appVersion.indexOf('MSIE 5') != -1) 
	&& (navigator.platform.indexOf('Mac') != -1)
	&& getStyleObject('blankDiv')) {
	getStyleObject('blankDiv').width = document.body.clientWidth - 20;
	getStyleObject('blankDiv').height = document.body.clientHeight - 20;
    }
}

function explorerMacResizeFix () {
    location.reload(false);
}

function mClk(src){ 
	if(event.srcElement.tagName=='TD')
		src.children.tags('A')[0].click();
}


function getObject(objectId) {
    // cross-browser function to get an object's style object given its id
    
   // cross-browser function to get an object's style object given its id
	if (document.all && document.all(objectId)) {
		// MSIE 4 DOM
		return document.all(objectId);}
	else{
		if(document.getElementById(objectId)) {
			// W3C DOM
			return document.getElementById(objectId);
			}
		else{
		
			if (document.layers && document.layers[objectId]) {
				// NN 4 DOM.. note: this won't find nested layers
				return document.layers[objectId];
				} 
			else
				{
				return false;
				}
			}
		}
} 

function mtCheckRbt(chkCurrent, rbtCurrent){
	document.getElementById(chkCurrent).checked = true;
}

function mtUnCheckChk(chkCurrent, rbtCurrent){
	if (document.getElementById(rbtCurrent).checked){
		document.getElementById(chkCurrent).checked = true;
	}
}

function updateOrder(idsArray, section){
	currentOrder=document.getElementById("ddl"+section).value;
	values=new Array(idsArray.length);		// The key is the sorting value, if the value is null, then it's the missing one!
	oldOrder=0;
	toReplace=null;
	for(i=0; i<idsArray.length; ++i){			// Loop through all dropdowns
		ddl=document.getElementById("ddl"+idsArray[i]);
		values[ddl.value-1]="";		// The order's value has been found 
		if((idsArray[i]!=section) && (ddl.value==currentOrder)){
			toReplace=ddl;		// This is the control to update
			cId=idsArray[i];
		}
	}
	for(i=0; i<values.length; ++i){
		if(values[i]==null){		// Then this value wasn't found
			toReplace.options[i].selected=true;
			break;
		}
	}
}


function mtChangeVisibilityDIV(divVisibleText, divInvisibleText, divID)
{
if (document.getElementById(divID).style.display=='none')
{
document.getElementById(divID).style.display='block';
document.getElementById(divVisibleText).style.display='none';
document.getElementById(divInvisibleText).style.display='block';
}
else
{
document.getElementById(divID).style.display='none';
document.getElementById(divVisibleText).style.display='block';
document.getElementById(divInvisibleText).style.display='none';
}
}

function mtControlContactBox()
{
	var flagName;
	var flagSurname;
	var flagEmail;
	flagName = '';
	flagSurname = '';
	flagEmail = '';
	
	// get control values by ID
	var nameVal = document.getElementById('nameContact').value;
	var surnameVal = document.getElementById('surnameContact').value;
	var emailVal = document.getElementById('emailContact').value;
	var checkAccept = document.getElementById('checkAccept').checked;
	
	
	if (!checkAccept)
	{
		alert('Obbligatorio accettare il Dlgs');
		return false;
	}

	// clean help text
	if(nameVal=='il tuo nome')
	{
		nameVal = '';
	}

	if(surnameVal=='il tuo cognome')
	{
		surnameVal = '';
	}

	if(emailVal=='il tuo email')
	{
		emailVal = '';
	}

	// check for name length
	if(!nameVal.length > 0)
	{
		flagName = 'noName';
	}

	// check for surname length
	if(!surnameVal.length > 0)
	{
		flagSurname = 'noSurname';
	}

	// check for email length
	if(!emailVal.length > 0)
	{
		flagEmail = 'noEmail';
	}
	else
	{
		if (!emailCheck(emailVal))
		{
			flagEmail = 'invalidEmail';
		}
	}
	
	if (flagName == '' && flagSurname == '' && flagEmail == '')
	{
		return true;
	}
	else
	{
		var textAlert;
		textAlert = 'Dati obbligatorio mancanti';
		if (flagName == 'noName')
		{
			//alert('You must specify a contact name');
			textAlert = 'You must specify a contact name';
		}
		
		if (flagSurname == 'noSurname')
		{
			if (textAlert.length > 0)
			{
			textAlert = textAlert + '\r\n';
			}
			//alert('You must specify a contact surname');
			textAlert = textAlert + 'You must specify a contact surname';
		}
		
		if (flagEmail == 'noEmail')
		{
			if (textAlert.length > 0)
			{
			textAlert = textAlert + '\r\n';
			}
			//alert('You must specify a contact email');
			textAlert = textAlert + 'You must specify a contact email';
		}

		if (flagEmail == 'invalidEmail')
		{
			if (textAlert.length > 0)
			{
			textAlert = textAlert + '\r\n';
			}
			//alert('You must specify a contact email');
			textAlert = textAlert + 'You must specify a valid email address';
		}

		alert('Dati obbligatorio mancanti');
		return false;
	}
}

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("Email address seems incorrect (check @ and .'s)")
	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("The username doesn't seem to be valid.")
    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("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name doesn't seem to be valid.")
    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("The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}
//  End -->

$(function(){
	var Netscience = function(opts){
		var obj = this;
		obj.pageX = undefined;
		obj.pageY = undefined;	
		
		this.init = function(){
			$(document).mousemove(function(e){
				obj.pageX = e.pageX;
				obj.pageY = e.pageY;
			});	
			
			// default ajax settings
			$.ajaxSetup({
				async: 		true,
				//timeout:	1000,
				type: 		'GET',			
				//complete:   function(){ $.overlay.hide(); },
				error:		function(XMLHttpRequest, textStatus, errorThrown){ $.Netscience.ajax_error(XMLHttpRequest, textStatus, errorThrown); }
			});
		}
		
		this.load_plugins = function(){
			if(arguments.length == 0) return false;
			
			for(var i = 0; i < arguments.length; i++){
				var script = $(document.createElement('script'))
				script.attr('type', 'text/javascript');
				script.attr('src', APP_PATH + 'Javascript/widgets/' + arguments[i]);
				$(document.body).append(script);
			}
			
			return true;
		}
		
		this.ajax_error = function(XMLHttpRequest, textStatus, errorThrown){
			var msg = "";
			switch(XMLHttpRequest.status){
				// request ok
				case 200:
				case 201:
				case 202:
				case 203:
				case 204:
				case 205:
				case 206:
					return;
				break;
				case 403:
				msg = "The page you have requested requires you to be authenticated. Please reload the page in your browser to perform authentication.";
				break;
				default:
				msg = "The page you have requested has generated a fatal error (status code: " + XMLHttpRequest.status + ")";
				break;
			}
			var p = $(document.createElement('p'));
			p.attr('class', 'error-message');
			p.text(msg);
			$.Overlay.dialog(p);
		}		
	};
	
	$.extend({
		// expose netscience into jquery
		Netscience: new Netscience()
	});	
});

$(function (){	
	// load core plugins. order is not editable
	$.Netscience.load_plugins('overlay.js', 'jquery_fn.js', 'toggler.js', 'tft_swapper.js');
	
	// initializes basic netscience support
	$.Netscience.init();
});