// JavaScript Document
Selector.findChildElements = function(element, expression){
    expression = expression.join(", ");
    var results = window.Sizzle(expression, element);
    if(results.length > 0){
        for(var i=0,l=results.length; i < l; i++){
            results[i] = Element.extend(results[i]);
        }
    }
    return results;
};
function intval(e){
	if(isNaN(parseInt(e))){
		return 0;
	}else{
		return parseInt(e);
	}
}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
};
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
};
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))==6;
Prototype.Browser.IE7 = Prototype.Browser.IE && !Prototype.Browser.IE6;


if (!document.ELEMENT_NODE) {
  document.ELEMENT_NODE = 1;
  document.ATTRIBUTE_NODE = 2;
  document.TEXT_NODE = 3;
  document.CDATA_SECTION_NODE = 4;
  document.ENTITY_REFERENCE_NODE = 5;
  document.ENTITY_NODE = 6;
  document.PROCESSING_INSTRUCTION_NODE = 7;
  document.COMMENT_NODE = 8;
  document.DOCUMENT_NODE = 9;
  document.DOCUMENT_TYPE_NODE = 10;
  document.DOCUMENT_FRAGMENT_NODE = 11;
  document.NOTATION_NODE = 12;
}
if(!document.importNode){

	document.importNode=function(p1,p2){
		xmlImportNode(document, p1, p2);
	};
}
document.createElementN = function (name, value) {
	v=document.createElement(name);
	if(value){
		n=document.createTextNode(value);
		v.appendChild(n);
	}
	return v;
}
function createNamedElement(dest, type, name) {
   var element = null;
   // Try the IE way; this fails on standards-compliant browsers
   try {
      element = dest.createElement('<'+type+' name="'+name+'">');
   } catch (e) {
   }
   if (!element || element.nodeName != type.toUpperCase()) {
      // Non-IE browser; use canonical method to create named element
      element = dest.createElement(type);
      element.name = name;
   }
   return element;
}

function dateDiff(date1, date2) {
	diff = new Date();
	// sets difference date to difference of first date and second date

	diff.setTime(Math.abs(date1.getTime() - date2.getTime()));

	timediff = diff.getTime();

	weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
	timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

	days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
	timediff -= days * (1000 * 60 * 60 * 24);

	hours = Math.floor(timediff / (1000 * 60 * 60)); 
	timediff -= hours * (1000 * 60 * 60);

	mins = Math.floor(timediff / (1000 * 60)); 
	timediff -= mins * (1000 * 60);

	secs = Math.floor(timediff / 1000); 
	timediff -= secs * 1000;	

	return {
		'fullWeeks':weeks ,'weeks':weeks ,
		'fullDays':days + (weeks*7),'days':days,  
		'fullHours':hours+(days + (weeks*7)*24),'hours':hours,    
		'fullMins':mins+((days + (weeks*7)*24)*60) ,'mins':mins ,  
		'fullSecs':secs+(((days + (weeks*7)*24)*60)*60),'secs':secs
		};
}

/* XMLDOM */

var userAgent = { };
userAgent.isOpera            = (navigator.userAgent.match(/\bOpera\b/));
userAgent.isInternetExplorer = (navigator.userAgent.match(/\bMSIE\b/) && !userAgent.isOpera);
userAgent.isMozilla          = (navigator.userAgent.match(/\bGecko\b/));
userAgent.isKHTML            = (navigator.userAgent.match(/\b(Konqueror|KHTML)\b/));

// Implements the Document.importNode DOM method. If the browser implements
// importNode natively, then that implementation is used.
//
// Parameters:
//     xmlDocument: The document to which to import the node.
//     node:        The node to import.
//     deep:        True to import all of the node's children, false to only
//                  import the node and its attributes.

function xmlImportNode(xmlDocument, node, deep) {
  if (typeof(xmlDocument.importNode) != "undefined" && !userAgent.isInternetExplorer) {
    // If using Opera and importing a node to the HTML document, we need to fix the
    // fake "-in-opera" namespace URI used. See loadDocument.js for more information
    // about this.
    if (!(xmlDocument == document && userAgent.isOpera)) {
      return xmlDocument.importNode(node, deep);
    }
  }
  var isHtml  = (xmlDocument.documentElement && xmlDocument.documentElement.tagName.toLowerCase() == "html");
  var newNode = null;

  switch (node.nodeType) {
    case 1: // Element
      if (xmlDocument.createElementNS) {
        newNode = xmlDocument.createElementNS(node.namespaceURI, node.nodeName);
      }
      else {
    	  if(isHtml && userAgent.isInternetExplorer && node.nodeName=='input' && (node.getAttribute("type")=='radio' || node.getAttribute("type")=='checkbox')){ // ie bugfix by asmir
    		  newNode=document.createElement('<input type="'+node.getAttribute("type")+'"'+((node.getAttribute("name"))?' name="'+node.getAttribute("name")+'"':'')+'>');
    	 }
    	 else{
    		  newNode = xmlDocument.createElement(node.nodeName);
    	 }
      }

      var atts   = node.attributes; 
      var attLen = atts.length;
      for (var i = 0; i < attLen; ++i) {
        var attribute = atts.item(i);

        if (attribute.specified /*&& attribute.value*/) {
          newNode.setAttribute(attribute.name, attribute.value);
		  
         
          if (isHtml && userAgent.isInternetExplorer) {
            // Many attributes don't take effect unless you set them via element.property
            // syntax. Also, some of these properties are named/capitalized differently.
			
			//  register event handlers for IE, added by ASMIR, require prototype
 			if(attribute.name.substring(0,2)=="on"){
				eval("f=function(){"+attribute.value+"}");
				//Event.observe(newNode, attribute.name.substring(2),f);
				
				eval("newNode.attachEvent(\""+attribute.name+"\", f.bindAsEventListener(newNode));");
				
				//return;
			}		
			
            switch (attribute.name) {
              case "colspan":     newNode.colSpan       = attribute.value; break;
              case "rowspan":     newNode.rowSpan       = attribute.value; break;
              case "cellspacing": newNode.cellSpacing   = attribute.value; break;
              case "cellpadding": newNode.cellPadding   = attribute.value; break;
              case "style":       newNode.style.cssText = attribute.value; break;
              case "class":       newNode.className     = attribute.value; break;
              case "checked":     newNode.checked       = newNode.defaultChecked = true; break; // ie bugfix by asmir
              case "value":       newNode.value         = attribute.value; break; // ie bugfix by asmir
              case "enctype":    // ie bugfix by asmir  
            	  newNode['enctype'] = attribute.value;
            	  newNode['encoding'] = attribute.value;
            	  break;
              default:
                newNode[attribute.name] = attribute.value;
                break;
            }
          }
        }
      }

      break;

    case 2: // Attribute
      if (xmlDocument.createAttributeNS) {
        newNode = xmlDocument.createAttributeNS(node.namespaceURI, node.name);
      }
      else {
        newNode = xmlDocument.createAttribute(node.name);
      }
    
      newNode.value = node.value;
      break;

    case 3: // Text
    	newNode = xmlDocument.createTextNode(userAgent.isInternetExplorer?node.data.trim():node.data);
      break;

    case 4: // CDATA section
      newNode = xmlDocument.createCDATASection(node.data);
      break;

    case 5: // Entity reference
      newNode = xmlDocument.createEntityReference(node.nodeName);
      break;

    case 7: // Processing instruction
      newNode = xmlDocument.createProcessingInstruction(node.target, node.data);
      break;

    case 8: // Comment
      newNode = xmlDocument.createComment(node.data);
      break;

    case 11: // Document fragment
      newNode = xmlDocument.createDocumentFragment();
      break;

    default:
      throw new XmlException("Cannot import node: " + node.nodeName);
  }

  if (deep) {
    for (var child = node.firstChild; child != null; child = child.nextSibling) {
      newNode.appendChild(xmlImportNode(xmlDocument, child, true));
    }
  }
  
  return newNode;
};

function isTextNode(node) {
  return node.nodeType == 3 || node.nodeType == 4;
};

FrameworkUtils = {DOMLoaded:false};

if (!Array.indexOf){
  Array.indexOf = [].indexOf ?
      function (arr, obj, from) { return arr.indexOf(obj, from); }:
      function (arr, obj, from) { // (for IE6)
        var l = arr.length,
            i = from ? parseInt( (1*from) + (from<0 ? l:0), 10) : 0;
        i = i<0 ? 0 : i;
        for (; i<l; i++) {
          if (i in arr  &&  arr[i] === obj) { return i; }
        }
        return -1;
      };
}


Object.extend(Event, (function() {
	var cache = Event.cache;

	  function getEventID(element) {
	    if (element._eventID) return element._eventID;
	    arguments.callee.id = arguments.callee.id || 1;
	    return element._eventID = ++arguments.callee.id;
	  }
	  function getDOMEventName(eventName) {
	    if (eventName && eventName.include(':')) return "dataavailable";
	    return eventName;
	  }

	  function getCacheForID(id) {
	    return cache[id] = cache[id] || { };
	  }

	  function getWrappersForEventName(id, eventName) {
	    var c = getCacheForID(id);
	    return c[eventName] = c[eventName] || [];
	  }

	return {
		fireNative :  function(element, eventName, newOptions) {
			var element = $(element);
		    var id = getEventID(element), name = getDOMEventName(eventName);
		    var wrapers = getWrappersForEventName(id, eventName);
		    var options = Object.extend({
	    		    pointerX: 0,
	    		    pointerY: 0,
	    		    button: 0,
	    		    ctrlKey: false,
	    		    altKey: false,
	    		    shiftKey: false,
	    		    metaKey: false,
	    		    bubbles: true,
	    		    cancelable: true
	    	}, newOptions || {}) ;
		    var eventMatchers = {
			    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
			    'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
			};
		    	
		    
		    
		    if (document.createEventObject){// dispatch for IE
		        options.clientX = options.pointerX;
		        options.clientY = options.pointerY;
		        evt = Object.extend(document.createEventObject(), options);
		        element.fireEvent('on' + eventName, evt);
		    } else{  // dispatch for firefox + other
		    	
				for (var name in eventMatchers) {
				    if (eventMatchers[name].test(eventName)) { eventType = name; break; }
				}
				
		        var evt = document.createEvent(eventType);

		        if (eventType == 'HTMLEvents') {
		        	evt.initEvent(eventName, options.bubbles, options.cancelable);
		        }else{
		        	evt.initMouseEvent(eventName, options.bubbles, options.cancelable , document.defaultView,
		            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
		            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
		        }
		        element.dispatchEvent(evt);       
		    }
		    
		    wrapers.each(function(gestore){ // dispatch eventi registrati con prototype       	
		    	(gestore.bindAsEventListener(this.elemento,this.evento))(); 
		    }.bind({elemento:element,evento:evt}));	
		}
	};
})());
Element.addMethods({
	cloneWithAttributeAlter:function(element, attributeToAlter, alterCallback) {
		if(typeof(attributeToAlter)=="string"){
			attributeToAlter = [attributeToAlter];
		}
		var clonato = element.cloneNode(true);
		
		clonato.select(".do_not_clone_me").each(Element.remove);
		
		clonato.select("*").each(function(nodo){
			for (var i = 0; i<nodo.attributes.length; i++){
				var attributo = nodo.attributes[i];
				if(attributo.specified && attributeToAlter.indexOf(attributo.name)!=-1){
					attributo.value=alterCallback(attributo.value, attributo);
				}
			}
		});	
		return $(clonato);
	},
	remove: function(element) {
		var element = $(element);
		if(element.parentNode)
			element.parentNode.removeChild(element);
		return element;
	},	
	removeChilds: function(element) {
		var element = $(element);
		while(element.firstChild){
			element.removeChild(element.firstChild);
		}
	},
	fireNative: function(element, event,opt) {
		Event.fireNative($(element), event, opt);
	}	
});
Ajax.Request.prototype.abort = function() {
    // prevent and state change callbacks from being issued
    this.transport.onreadystatechange = Prototype.emptyFunction;
    // abort the XHR
    this.transport.abort();
    // update the request counter
    Ajax.activeRequestCount--;
};


Ajax.NiceRequest = Class.create(Ajax.Request, {
	  initialize: function($super, url, options) {
	    options = options || { };
	    var onCreate = options.onCreate; // loading
	    options.onCreate = (function(response, param) {
	      this.createLoader();
	      if (Object.isFunction(onCreate)) onCreate(response, param);
	    }).bind(this);
	    
	    var onException = options.onException; // error 1
	    options.onException = (function(response, param) {
	      this.errorLoader(response,param);
	      if (Object.isFunction(onException)) onException(response, param);
	    }).bind(this);
	    
	    var onFailure = options.onFailure; // error 2
	    options.onFailure = (function(response, param) {
	      this.errorLoader(response, response.status);
	      if (Object.isFunction(onFailure)) onFailure(response, param);
	    }).bind(this);
	    
	    var onSuccess = options.onSuccess; // ok
	    options.onSuccess = (function(response, param) {
	      this.removeLoader();
	      if (Object.isFunction(onSuccess)) onSuccess(response, param);
	    }).bind(this);
	    
	    $super(url, options);
	  },
	  positionize:function(ele){
		  width = $(ele).getWidth() ? $(ele).getWidth() : 100;
		  $(ele).setStyle({
				position :Prototype.Browser.IE6 ? 'absolute' : 'fixed',
				top :Prototype.Browser.IE6 ? document.viewport.getScrollOffsets().top + "px" : '0',
				left : ((document.viewport.getWidth() - width) / 2) + "px"
		  });
	  },
	  errorLoader: function(instance, params) {
		  	if($('NiceRequest_Loading')){
		  		$('NiceRequest_Loading').remove();
		  	}
		  	loader = $('NiceRequest_Err');
			if (!loader) {
				throw params;
				loader = Builder.node('div', {id: 'NiceRequest_Err'},
						[
						 Builder.node('img', {src: 'ambient.resources/img/icons/cancel.png'}),
						 "Errors: "+(typeof(params)=='object' && params.message?params.message:params)
						 ]);
			}
			this.positionize(loader);
			document.body.appendChild(loader);
	  },
	  removeLoader: function() {
		  $$("#NiceRequest_Err, #NiceRequest_Loading").each(Element.remove);
	  },
	  createLoader: function() {
		if($('NiceRequest_Err')){
	  		$('NiceRequest_Err').remove();
	  	}
		loader = $('NiceRequest_Loading');
		if (!loader) {
			loader = Builder.node('div', {id: 'NiceRequest_Loading'},
					[
					 Builder.node('img', {src: 'ambient.resources/img/loading.gif'}),
					 'Loading...'
			        ]);
		}
		this.positionize(loader);
		document.body.appendChild(loader);
	  }
});

new Image().src = 'ambient.resources/img/loading.gif';
new Image().src = 'ambient.resources/img/icons/cancel.png';
document.observe('dom:loaded', function () { window.FrameworkUtils.DOMLoaded=true; });
