
function utils_add_event(obj, evType, fn, useCapture){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
	//	alert("Handler could not be attached");
	}
}

function utils_remove_event(obj, evType, fn, useCapture){
	if (obj.removeEventListener){
		obj.removeEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.detachEvent){
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	} else {
	//	alert("Handler could not be removed");
	}
}

/*
 * Imposta un cookie per il documento. Se il terzo parametro e' false il cookie
 * scadra' con la sessione, se invece viene specificato un valore intero questo 
 * valore rappresentera' la durata del cookie
 */ 
function utils_set_cookie(name, value, days) {
    cookie = name + "=" + escape(value);
    if (days != null) {
        var today = new Date();
        var expires = new Date();
        expires.setTime(today.getTime() + 24 * days * 3600000);
        cookie += "; expires=" + expires.toGMTString();
    }
    document.cookie = cookie;
}

function utils_get_cookie(name) {
    var cookies = document.cookie.split("; ");
    // ciclo su tutti i cookies
    for (var i = 0; i < cookies.length; i++) {
        // leggo singolo cookie "Nome = Valore"
        var cookie = cookies[i].split("=");
        if (name == cookie[0]) { 
            return (unescape(cookie[1]));
        }
    }
    return false;
}


/**
 *
 * Copy some text to the clipboard, if the browser supports it
 *
 * @param  widget  form widget containing the text to copy
 *
 */
function utils_copyClip(text) {
   if (navigator.appName.indexOf("Microsoft") != -1) {
     // IE only
     theForm = text.form;
     theForm.copyArea.value=text.value;
     r=theForm.copyArea.createTextRange();
     r.select();
     r.execCommand('copy');
   } else if (navigator.appName.indexOf("Netscape") != -1) { 
     // Netscape/Mozilla

     // you have to sign the code to enable this
     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

     var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
     if (!clip) return;

     var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
     if (!trans) return;

     trans.addDataFlavor('text/unicode');

     var str = new Object();
     var len = new Object();

     var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

     var copytext=text.value;

     str.data=copytext;

     trans.setTransferData("text/unicode",str,copytext.length*2);

     var clipid=Components.interfaces.nsIClipboard;

     if (!clip) return false;

     clip.setData(trans,null,clipid.kGlobalClipboard);
   }

   text.select();
}

/**
 *
 * Create printer-friendly pages
 *
 */
function utils_printPage() {
   var print=window.open('','print','width=600, height=400, menubar=yes, resizable=yes, scrollbars=yes, toolbar=yes');

   print.document.open();
   print.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="it" lang="it"><head><meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /><style type="text/css">.notprinted { display: none !important }</style></head>');
   print.document.write('<body onLoad="self.print()">');
   print.document.write(document.getElementById("primaryContent").innerHTML);
   print.document.write('</body></html>');
   print.document.close();
   print.focus();
}

/**
 *
 * Show and hide a DIV (see http://www.netlobo.com/div_hiding.html)
 *
 */
function utils_toggleHiddenLayer(layer) {
   if (layer == null) { layer = "hiddenLayer"; }
   if (document.getElementById) {
      // this is the way the standards work
      var style2 = document.getElementById(layer).style;
   }
   else if (document.all)
   {
      // this is the way old msie versions work
      var style2 = document.all[layer].style;
   }
   else if (document.layers)
   {
      // this is the way nn4 works
      var style2 = document.layers[layer].style;
   }
   style2.display = (style2.display == "block") ? "none" : "block";
}

/**  
 * 
 * insert text at the current cursor position in a textarea or input field
 * (see http://parentnode.org/javascript/working-with-the-cursor-position/)
 *
 */ 
function utils_insertAtCaret(obj, text) { 
    if (document.selection) { 
        // Go the IE way

        /* First of all, focus the object, we want to work with
           If we do not do so, it is possible, that the selection
           is not, where we expect it to be
        */
        obj.focus();
 
        /* Create a TextRange based on the document.selection
           This TextRanged can be used to replace the selected
           Text with the new one
        */
        var range = document.selection.createRange(); 

        /* If the range is not part of our Object (remember the
           textarea or input field), stop processing here
         */ 
        if (range.parentElement() != obj) { 
            return false; 
        } 

        /* Save the current value. We will need this value later
           to find out, where the text has been changed
         */ 
        var orig = obj.value.replace(/rn/g, "n"); 

        /* Replace the Text */ 
        range.text = text;

        /* Now get the new content and save it into
           a temporary variable
        */ 
        var actual = tmp = obj.value.replace(/rn/g, "n");

        /* Find the first occurance, where the original differs
           from the actual content. This could be the startposition
           of our text selection, but it has not to be. Think of the
           selection "ab" and replacing it with "ac". The first
           difference would be the "c", while the start position
           is the "a"
        */ 
        for(var diff = 0; diff < orig.length; diff++) { 
            if(orig.charAt(diff) != actual.charAt(diff)) break; 
        } 

       /* To get the real start position, we iterate through
           the string searching for the whole replacement
           text - "abc", as long as the first difference is not
           reached. If you do not understand that logic - no
           blame to you, just copy & paste it ;)
        */ 
        for(var index = 0, start = 0; 
            tmp.match(text) 
                && (tmp = tmp.replace(text, "")) 
                && index <= diff; 
            index = start + text.length 
        ) { 
            start = actual.indexOf(text, index); 
        }  
    } else if (obj.selectionStart) { 
        // Go the Gecko way

        // Find the Start and End Position
        var start = obj.selectionStart;
        var end   = obj.selectionEnd;

        // Remember obj is a textarea or input field
        obj.value = obj.value.substr(0, start) + text + obj.value.substr(end, obj.value.length);
    } // else Fallback for any other browser

    if(start != null) {  
        utils_setCaretTo(obj, start + text.length);  
    } else {  
        obj.value += text;  
    }  
}

function utils_setCaretTo(obj, pos) {
    if(obj.createTextRange) {
        /* Create a TextRange, set the internal pointer to
           a specified position and show the cursor at this
           position
        */
        var range = obj.createTextRange();
        range.move("character", pos);
        range.select();
    } else if(obj.selectionStart) {
        /* Gecko is a little bit shorter on that. Simply
           focus the element and set the selection to a
           specified position
        */
        obj.focus();
        obj.setSelectionRange(pos, pos);
    }
}
