var myRequest;
var _RELBASEPATH_;

(location.host == "localhost" || location.host == 'barisciano' || location.host  == '192.168.0.20' ) ? _RELBASEPATH_ = "/OR/" : _RELBASEPATH_ = "/";

/* function do detect browser type */
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

// Crea un oggetto XMLHTTPRequest in base ai parametri passati in input. serverFile: lo script lato server che si occupa ri rispondere alla richiesta,
// getVars: una stringa nel formato var1=value1&var2=value2 rappresentante le variabili da passare in get allo script lato server e onReadyFunction: la // function JavaScript chiamata al momento della risposta alla richiesta in oggetto.
function createRequest(serverFile, onReadyFunction, getVars) {
  url = serverFile + '?' + getVars;
  if (window.XMLHttpRequest) {
    myRequest = new XMLHttpRequest();
    myRequest.open("GET", url, true);
    myRequest.onreadystatechange = eval(onReadyFunction);
    myRequest.send(null);
  }
  // se siamo su MS IE...
  else if (window.ActiveXObject) {
    myRequest = new ActiveXObject("Microsoft.XMLHTTP");
    //myRequest = new ActiveXObject("Msxml2.XMLHTTP");
    myRequest.open("GET", url, true);    
    myRequest.onreadystatechange = eval(onReadyFunction);
    //myRequest.onreadystatechange = changeCSS;
    myRequest.send();
  }
} // end of createFontRequest


// processa la risposta alla XMLHTTPRequest, viene richiamata nella function createRequest
function processRequest() {
  // only if req shows "loaded"
  if (myRequest.readyState == 4) {
    // only if "OK"
    if (myRequest.status == 200) {
      response = myRequest.responseText;
      // Splitto la risposta in base al separatore '@' in tal modo avrò un array che contiene all'indice 0 la
      // funzione Javascript da richiamare e che si occupa materialmente di popolare il menu a tendina, a questa
      // funzione passerò 2 array: responseArray[1] i valori della risposta e responseArray[2] le chiavi della
      // risposta.
      responseArray = response.split('@');
      eval(responseArray[0] + "(responseArray[1], responseArray[2])");
    }
    else {
      window.alert("There was a problem retrieving the XML data:\n" +
      myRequest.statusText);
    }
  }
} // end of processRequest


// Riempie il menu a tendina idSubsector in base all'idSector selezionato
function fillSubsectorList(values, keys) {
  // creo 2 array uno per le chiavi e l'altro per i valori in base alle 2 stringhe passate in input
  subsectorValueArray = new Array();
  subsectorKeyArray = new Array();
  // In questo caso non controllo se values è vuoto o meno in quanto il menu da popolare è una select singola ed il primo valore vuoto verrà occupato
  // dalla stringa "Seleziona...".
  subsectorValueArray = values.split("|");
  subsectorKeyArray = keys.split("|");
  subsectorList = document.getElementById('idSubsector'); 
  categoryList = document.getElementById('idCategory');
  emptySelectList('idCategory');
  emptySelectList('idSubsector');
  // inserisco un opzione fittizia "seleziona..." nel menu a atendina idCategory
  newOption = new Option(_CHOOSEFROMMENU_ + "...", "");
  categoryList.options[0] = newOption;
  // riempio il menu a tendina in base ai due array keys e values
  if (subsectorValueArray.length > 0) {
    for (fillMenuIndex = 0; fillMenuIndex < subsectorValueArray.length; fillMenuIndex++) {
      newOption = new Option(subsectorKeyArray[fillMenuIndex], subsectorValueArray[fillMenuIndex]);
      subsectorList.options[fillMenuIndex] = newOption;
    }
  }
} // end of fillSubsectorList


// Riempie il menu a tendina idCategory
function fillProductCategoryList(values, keys) {
  // creo 2 array uno per le chiavi e l'altro per i valori in base alle 2 stringhe passate in input
  categoryValueArray = new Array();
  categoryKeyArray = new Array();
  // In questo caso non controllo se values è vuoto o meno in quanto il menu da popolare è uan select singola ed il primo valore vuoto verrà occupato
  // dalla stringa "Seleziona...".
  categoryValueArray = values.split("|");
  categoryKeyArray = keys.split("|");
  categoryList = document.getElementById('idCategory');
  emptySelectList('idCategory');
  // riempio il menu a tendina in base ai due array keys e values
  if (categoryValueArray.length > 0) {
    for (fillMenuIndex = 0; fillMenuIndex < categoryValueArray.length; fillMenuIndex++) {
      newOption = new Option(categoryKeyArray[fillMenuIndex], categoryValueArray[fillMenuIndex]);
      categoryList.options[fillMenuIndex] = newOption;
    }
  }
} // end of fillCategoryList


// Esegue il trim sulla stringa passata, la RegExp eseguita sulla stringa passata in input elimina sia gli spazi che i ritorni a capo, avanzamento
// riga, tabulatore, tabulatore verticale la sequenza di caratteri '&nbsp'; e la sequenza di caratteri '<br />'.
function trim(toTrimString) { 
  // elimino spazi, ritorni a capo, avanzamento riga, tabulatore verticale
  toTrimString = toTrimString.replace(/^\s+|\s+$/g, '');
  // elimino la sequenza di caratteri '<br />', utile per le textarea gestite con FCKEditor
  toTrimString = toTrimString.replace(/^(\<br \/>)+|(\<br \/>)+$/g, '');
  // elimino la sequenza di caratteri '&nbsp', utile per le textarea gestite con FCKEditor
  return toTrimString.replace(/^(\&nbsp\;)+|(\&nbsp\;)+$/g, '');
} // end of trim


// controlla sintatticamente l'email passata in input
function checkEmail(email) {
  var error = "";
  var validRegExp = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
  if (!validRegExp.test(email))
    return false;
  return true;
} // end of checkEmail


// limit characther length in textarea control
function limitTextArea(limitField, limitNum) {
  if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
  } 
} // end of limitTextArea


/* BEGIN OF SELECT BOX FUNCTIONS */

// empty select list according to passed select list id
function emptySelectList(toEmptyId) {
  toEmptyObj = document.getElementById(toEmptyId);
  while (toEmptyObj.length > 0) {
    toEmptyObj.options[0] = null;
  }
} // end of emptySelectList


// add an option to 'Selected Items' select
function addItem(selected, toAdd) {
  selectObj = document.getElementById(selected);
  addObj = document.getElementById(toAdd);
  // at first I scan all selected value in 'Available items' select to retrieve selected options 
  for (var j = 0; j < selectObj.length; j++) {
  // if an option has been selected and the selected option is not empty...
    if (selectObj[j].selected && selectObj.options[j].value != '') { 
      // I scan all the options presents in the select selectedItems to check if the option selected in the 
      // select availableItems it is already present in select selectedItems.
      for (i = 0; i < addObj.length; i++) {
        if (addObj.options[i].value == selectObj.options[j].value) {
        // if it is already in selectedItems or it is empty I set i value to -1 and I go out of the cycle 
          i = -1;
          break;
        }
      }
      // if it is not already present I can add the selected option to select selectedItems
      if (i != - 1) {
        textOtpion = selectObj.options[j].text
        opt = new Option (textOtpion, selectObj.options[j].value);
        addObj.options[addObj.length] = opt;
      }
    }
  }
} // end of addItem


// del Item from 'selected items' select
function delItem(selected) {
  selectObj = document.getElementById(selected);
  var i = selectObj.length - 1;
  while (i >= 0) {
    if (selectObj[i].selected)
      selectObj.options[i] = null;
    i--;
  }
} // end of delItem


// add Item to multiple select to post
function addEffect(selected, effective) {
  selectObj = document.getElementById(selected);
  effectObj = document.getElementById(effective);
    
  // empties effect select
  j = effectObj.length;
  for (i = 0; i <= j; i++) {
    effectObj.options[0] = null;
  }
  for (i = 0; i < selectObj.length; i++) {
    opt = new Option (selectObj.options[i].text, selectObj.options[i].value);
    effectObj.options[i] = opt;
    effectObj.options[i].selected = true;
  }
} // end of addEffect


// -------------------------------------------------------------------
// hasOptions(obj)
//  Utility function to determine if a select object has an options array
// -------------------------------------------------------------------
function hasOptions(obj) {
  if (obj!=null && obj.options!=null) {
    return true;
  }
	return false;
} // end of hasOptions


// -------------------------------------------------------------------
// moveOptionDown(select_object)
//  Move selected option in a select list down one
// -------------------------------------------------------------------
function moveOptionDown(obj) {
	if (!hasOptions(obj)) {
    return;
  }
	for (i=obj.options.length-1; i>=0; i--) {
		if (obj.options[i].selected) {
			if (i != (obj.options.length-1) && ! obj.options[i+1].selected) {
				swapOptions(obj,i,i+1);
				obj.options[i+1].selected = true;
			}
		}
	}
} // end of moveOptionDown


// -------------------------------------------------------------------
// moveOptionUp(select_object)
//  Move selected option in a select list up one
// -------------------------------------------------------------------
function moveOptionUp(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			if (i != 0 && !obj.options[i-1].selected) {
				swapOptions(obj,i,i-1);
				obj.options[i-1].selected = true;
			}
		}
	}
} // end of moveOptionUp


// -------------------------------------------------------------------
// swapOptions(select_object,option1,option2)
//  Swap positions of two options in a select list
// -------------------------------------------------------------------
function swapOptions(obj,i,j) {
	var o = obj.options;
	var i_selected = o[i].selected;
	var j_selected = o[j].selected;
  var iBGColor = o[i].style.backgroundColor;
  var jBGColor = o[j].style.backgroundColor;
  var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
	o[i] = temp2;
  o[i].style.backgroundColor = iBGColor;
  o[j] = temp;
  o[j].style.backgroundColor = jBGColor;
	o[i].selected = j_selected;
	o[j].selected = i_selected;
} // end of swapOptions


// -------------------------------------------------------------------
// selectAllOptions(select_object)
//  This function takes a select box and selects all options (in a 
//  multiple select object). This is used when passing values between
//  two select boxes. Select all options in the right box before 
//  submitting the form so the values will be sent to the server.
// -------------------------------------------------------------------
function selectAllOptions(obj) {
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		obj.options[i].selected = true;
	}
} // end of selectAllOptions

/* END OF SELECT BOX FUNCTIONS*/