﻿
/** 
* Copyright 2009 Simone Biondani
* License: 
* @author      Simone Biondani (simone.biondani@tiscali.it)
* @version     0.0.1, 2009-04-03
 */

if(typeof(fmw) == "undefined"){
	var fmw = {};
}

fmw.activexmodes = ["MSXML2.XmlHttp.6.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp", "Microsoft.XmlHttp"];

/*
fmw.readyState = {INATTIVO:	0, INIZIALIZZATO:	1, RICHIESTA:	2, RISPOSTA:	3, COMPLETATO:	4};

	// array descrittivo dei codici restituiti dal server
	// [la scelta dell' array è per evitare problemi con vecchi browsers]
		var statusText = new Array();
		statusText[100] = "Continue";
		statusText[101] = "Switching Protocols";
		statusText[200] = "OK";
		statusText[201] = "Created";
		statusText[202] = "Accepted";
		statusText[203] = "Non-Authoritative Information";
		statusText[204] = "No Content";
		statusText[205] = "Reset Content";
		statusText[206] = "Partial Content";
		statusText[300] = "Multiple Choices";
		statusText[301] = "Moved Permanently";
		statusText[302] = "Found";
		statusText[303] = "See Other";
		statusText[304] = "Not Modified";
		statusText[305] = "Use Proxy";
		statusText[306] = "(unused, but reserved)";
		statusText[307] = "Temporary Redirect";
		statusText[400] = "Bad Request";
		statusText[401] = "Unauthorized";
		statusText[402] = "Payment Required";
		statusText[403] = "Forbidden";
		statusText[404] = "Not Found";
		statusText[405] = "Method Not Allowed";
		statusText[406] = "Not Acceptable";
		statusText[407] = "Proxy Authentication Required";
		statusText[408] = "Request Timeout";
		statusText[409] = "Conflict";
		statusText[410] = "Gone";
		statusText[411] = "Length Required";
		statusText[412] = "Precondition Failed";
		statusText[413] = "Request Entity Too Large";
		statusText[414] = "Request-URI Too Long";
		statusText[415] = "Unsupported Media Type";
		statusText[416] = "Requested Range Not Satisfiable";
		statusText[417] = "Expectation Failed";
		statusText[500] = "Internal Server Error";
		statusText[501] = "Not Implemented";
		statusText[502] = "Bad Gateway";
		statusText[503] = "Service Unavailable";
		statusText[504] = "Gateway Timeout";
		statusText[505] = "HTTP Version Not Supported";
		statusText[509] = "Bandwidth Limit Exceeded";
*/

/**
* Developed by John Resig
* For additional info see:
* http://ejohn.org/projects/flexible-javascript-events
*/
fmw.addEvent = function(obj, type, fn){
	if(obj.addEventListener){
		obj.addEventListener(type, fn, false);
	}
	else if(obj.attachEvent){
		obj["e" + type + fn] = fn;
		obj[type + fn] = function(){
				obj["e" + type + fn](window.event);
			}
		obj.attachEvent("on" + type, obj[type+fn]);
	}
}

fmw.isOpera = function() {
  return /Opera/.test(navigator.userAgent);
}
fmw.isSafari = function() {
  return /Safari/.test(navigator.userAgent);
}
fmw.isGecko = function() {
  return navigator.product == "Gecko" && !( this.isOpera() || this.isSafari());
}
fmw.isIEWin = function() {
  //return window.external && /Win/.test(navigator.userAgent);
  return /MSIE/.test(navigator.userAgent);
}
fmw.isIEMac = function() {
  return window.external && /Mac/.test(navigator.userAgent);
}
fmw.getVersion = function() {
  if (this.isIEWin() || this.isIEMac()) {
    //alert(navigator.userAgent.match(/MSIE ([0-9.]+)/)[1]);
    return Number(navigator.userAgent.match(/MSIE ([0-9.]+)/)[1]);
  }
  else if (this.isSafari()) {
    return Number(navigator.userAgent.match(/[0-9.]+$/));
  }
  else if (this.isGecko()) {
    var n = navigator.userAgent.match(/rv:([0-9.]+)/)[1];
    var ar = n.split(".");
    var s = ar[0] + ".";
    for (var i = 1; i < ar.length; ++i) {
      s += ("0" + ar[i]).match(/.{2}$/)[0];
    }
    return Number(s);
  }
  else if (this.isOpera()) {
    return Number(navigator.userAgent.match(/Opera.([0-9.]+)/)[1]);
  }
  else {
    return null;
  }
}   

/**
* Sort of an equivalent of the famous $() function. Just with a better name :-)
* Accepts either ids (strings) or DOM node references
*/
fmw.get = function(){
	var returnNodes = new Array();
	for(var i=0; i<arguments.length; i++){
		var nodeElem = arguments[i];
		if(typeof nodeElem == "string"){
			nodeElem = document.getElementById(nodeElem);
		}
		if(arguments.length == 1){
			return nodeElem;
		}
		returnNodes.push(nodeElem);
	}
	return returnNodes;
}

fmw.getAll = function(startNode){
	// If no node was passed, use the document
	var rootNode = (startNode) ? fmw.get(startNode) : document;
	return rootNode.getElementsByTagName("*");
}

fmw.getByTagName = function(startNode, tagName){
	// If no node was passed, use the document
	var rootNode = (startNode) ? fmw.get(startNode) : document;
	return rootNode.getElementsByTagName(tagName);
}


/**
* Returns an array containing all child nodes that contain the given attribute matching a given value
* If no starting node is passed, assume the document is the starting point
*/
fmw.getNodesByAttributeValue = function(attName, attValue, startNode){
	var nodes = fmw.getAll(startNode);
	return fmw.filterNodesByAttributeValue(attName, attValue, nodes);
}

/**
* Out of a node list, returns an array containing all nodes that contain the given attribute
*/
fmw.filterNodesByAttribute = function(attName, nodes){
	var filteredNodes = new Array();
	for(var i=0; i<nodes.length; i++){
		if(nodes[i].getAttribute(attName)){
			filteredNodes.push(nodes[i]);
		}
	}
	return filteredNodes;
}

/**
* Out of a node list, returns an array containing all nodes that contain the given attribute matching a given value
*/
fmw.filterNodesByAttributeValue = function(attName, attValue, nodes){
	var filteredNodes = new Array();
	for(var i=0; i<nodes.length; i++) {
		if(nodes[i].getAttribute(attName) && (nodes[i].getAttribute(attName) == attValue)){
			filteredNodes.push(nodes[i]);
		}
	}
	return filteredNodes;
}

/**
* Add a CSS class to a given node. Accepts either an id (string) or DOM node reference
*/
fmw.addClass = function(element, className){
	var nodeElem = fmw.get(element);
	if(!nodeElem || (fmw.hasClass(nodeElem, className) == true)){
		return;
	}
	nodeElem.className += (nodeElem.className ? " " : "") + className;
}


///**
//* 26/11/2010  
//* Recupero il parent
//*/
//fmw.getParent = function getParent(element, tagName) {
//if (element == null) return null;
//else if (element.nodeType == 1 && element.tagName.toLowerCase() == tagName.toLowerCase())	// Gecko bug, supposed to be uppercase
//        return element;
//    else
//        return getParent(element.parentNode, tagName);
//}

fmw.getParent = function(el, type, value) {
    var temp = el;
    while ((temp != null) && (temp.tagName != "BODY")) {
        if (temp[type] == value) {
            return temp;
        }
        temp = temp.parentNode;
    }
    return null;
}
/**
* Check if a given node use a CSS class. Accepts either an id (string) or DOM node reference
*/
fmw.hasClass = function(element, className){
	var nodeElem = fmw.get(element);
	if(nodeElem){
		return nodeElem.className.search(new RegExp("\\b" + className + "\\b")) != -1;
	}
	return null;
}

/**
* Remove a CSS class from a given node. Accepts either an id (string) or DOM node reference
*/
fmw.removeClass = function(element, className){
	var nodeElem = fmw.get(element);
	if(!nodeElem || (fmw.hasClass(nodeElem, className) == false)){
		return;
	}
	nodeElem.className = nodeElem.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
}

/**
* Toggle a CSS class from a given node. Accepts either an id (string) or DOM node reference
*/
fmw.toggleClass = function(element, className){
	var nodeElem = fmw.get(element);
	if(fmw.hasClass(nodeElem, className)){
		fmw.removeClass(nodeElem, className);
	}
	else{
		fmw.addClass(nodeElem, className);
	}
}

/**
* Return an instance of an XMLHttpRequest (either native or Active-X) depending on browser and environment
*/
fmw.HttpRequest = function() {
	
	var requestObj = {};
  
  //onreadystatechange
  //readyState
  //status
  //open
  //send
  //se POST >= ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded")
  // ulteriore header consigliato per richieste get o post da scrivere prima di utilizzare send
 //ajax.setRequestHeader("connection", "close");

  if(window.XMLHttpRequest){
	  requestObj = new XMLHttpRequest();
  }
	
	else if (window.ActiveXObject) {
	  for (var i=0; i<fmw.activexmodes.length; i++) {
      try {
	      requestObj = new ActiveXObject(fmw.activexmodes[i]);
      }
      catch(e) {
        //Mannaggia
      }
	  }
	}
	
	if (!requestObj) {
	  alert("HttpRequest non supportate.");
	}
	else {

  }
	
	return requestObj;
}

/**
* Apro una pagona con testo dell'errore 
*/
fmw.showErrorPage = function(text) {

  var winerror = window.open("", "winerror");
  winerror.opener = self;
  var docerror = winerror.document;
  docerror.write(text);
  docerror.close();
  
}


/**
* Visualizzo Warning ed Errori. Deve arriva un JSon
*/
fmw.showWarningError = function(obj) {
	obj = obj.substring(0, obj.lastIndexOf("}") +1);
	try {
		var jwe = eval('(' + obj + ')');
		for (var i = 0; i < jwe.warnings.length; i++) {
			alert("Warning: " + jwe.warnings[i].descrizione);
		}
		for (var i = 0; i < jwe.errors.length; i++) {
			alert("Errori: " + jwe.errors[i].descrizione);
		}
	}
	catch (e) {
		alert(obj);
	}
}

/**
* Creo una stringa con tutte le proprietà di un oggetto 
*/ 
fmw.showProps = function(obj, objName) {
   var result = "";
   for (var i in obj) {
      result += objName + "." + i + " = " + obj[i] + "\n";
   }
   return result;
} 

fmw.fixE = function(e) {

    if (typeof e == 'undefined') e = window.event;
    if (typeof e.srcElement == 'undefined') e.srcElement = e.target;
    if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
    if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
    if (typeof e.keyCode == 'undefined') e.keyCode = e.which;
    //if (typeof e.cancelBubble == 'undefined') e.keyCode = e.which;
    e.stopEvents = function() {
        if (this.cancelBubble)
            this.cancelBubble = true;
        if (this.stopPropagation)
            this.stopPropagation();
        if (this.returnValue)
            this.returnValue = false;
    }

    return e;
}
  
/**
* Aggiungo il div modal.
*/

fmw.addModalPanel = function(idPanel) {

    var zIndex = 10000;
    var div = document.createElement("DIV");

    var scrollY = (window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop);

    div.setAttribute("id", idPanel);
    div.setAttribute("style", "position: absolute; top: " + scrollY + "px; left: 0px; height: 100%; width: 100%; background-color: Gray; z-index: " + zIndex + "; opacity: .5;	-ms-filter:\"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)\";");

    document.body.appendChild(div);

    //Così fa un pò schifetto ma per intanto funzia!!!
    window.idPanel = idPanel;
    window.onscroll = function() {
            var scrollY = (window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop);
            scrollY = (scrollY ? scrollY : 0);
            fmw.get(window.idPanel).style.top = scrollY + "px";
    }
    return div
}  

/**
* Rimuovo il div modal
*/ 
fmw.removeModalPanel = function(idPanel) {
  
  var div = document.getElementById(idPanel);
  document.body.removeChild(div);

 }

/**
* 24.11.09 (Alex)
* Ritorno il nome della pagina.
* @ext (boolean) : true -> ritorno pagina.estensione
* @ext (boolean) : false / senza parametro -> ritorno pagina
**/
 fmw.getPageName = function(ext) {
 	var loc = window.location.href;
 	loc = loc.split("?")[0];
 	loc = loc.split('#')[0];
 	loc = loc.substring(loc.lastIndexOf("/") + 1, loc.length);
 	loc = loc.toLowerCase();

 	if (ext == null) ext = false;
 	if (ext == true) return loc;
 	else return loc.substring(0, loc.lastIndexOf("."));
 }



