﻿// JScript Common Function
function stripNonNumeric( str ) {
      str += '';
      var rgx = /^\d|\.|-$/;
      var out = '';
      for( var i = 0; i < str.length; i++ ) {
        if( rgx.test( str.charAt(i) ) ){
          if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
                 ( str.charAt(i) == '-' && out.length != 0 ) ) ){
            out += str.charAt(i);
          }
        }
      }
      return out;
    }

    function num2money(n_value) {
      // validate input
      if (isNaN(Number(n_value)))
      return 'ERROR';

      // save the sign
      var b_negative = Boolean(n_value < 0);
      n_value = Math.abs(n_value);

      // round to 1/100 precision, add ending zeroes if needed
      var s_result = String(Math.round(n_value*1e2)%1e2 + '00').substring(0,2);

      // separate all orders
      var b_first = true;
      var s_subresult;
      while (n_value > 1) {
      s_subresult = (n_value >= 1e3 ? '00' : '') + Math.floor(n_value%1e3);
      s_result = s_subresult.slice(-3) + (b_first ? '.' : ',') + s_result;
      b_first = false;
      n_value = n_value/1e3;
      }
      // add at least one integer digit
      if (b_first)
      s_result = '0.' + s_result;

      // apply formatting and return
      return b_negative
      ? '(&euro; ' + s_result + ')'
      : '&euro; ' + s_result;
    }
    
    function removejscssfile(filename, filetype){
      var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
      var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
      var allsuspects=document.getElementsByTagName(targetelement)
      for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
        allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
      }
    }
    
    function createjscssfile(filename, filetype){
      if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
        //fileref.setAttribute("class", "dynamic")
      }
      else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
        //fileref.setAttribute("class", "dynamic")
      }
      return fileref
    }

    function replacejscssfile(oldfilename, newfilename, filetype){
      var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using
      var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
      var allsuspects=document.getElementsByTagName(targetelement)
      for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
          var newelement=createjscssfile(newfilename, filetype)
          allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])         
        }
      }
    }
    
    function prepare_inputbox(selector, default_string, search_term, activated, disabled) {
      // quale dovrebbe essere il testo di default dell'etichetta?
      var default_term = 'search...'
      if (default_string && default_string != '') {
        default_term = default_string;
      }
      
      // impostare l'etichetta di testo o il valore di default, o la stringa di ricerca
      if (search_term != '') {
        $(selector).val(search_term);
      } else {
        $(selector).val(default_term);
      }
      
      //impostare effetti su inputbox
      $(selector).focus(function(e){
	      $(this).addClass("active");
      });
      $(selector).blur(function(e){
	      $(this).removeClass("active");
      });
      
      //impostare il focus quando documento è pronto?
      if (activated) {
        $(selector).focus();
      }
      
      //impostare il disabled se richiesto
      if (disabled) {
        $(selector).attr("disabled", true); 
      }
      
      //mostra / nascondi testo predefinito, se necessario
      $(selector).focus(function(){
	      if($(this).attr("value") == default_term) $(this).attr("value", "");
      });
      $(selector).blur(function(){
	      if($(this).attr("value") == "") $(this).attr("value", default_term);
      });
    }
    
    function openPrivacy() {      
      $('#dialog').dialog('open');     
    } 
    
    function onLoadCommonFunctions() {      
      //$('#flash').hide();
    } 
    
    function onCloseCommonFunctions() {      
      //$('#flash').show();
      $('#dialog').dialog('close');
      $('#dialog').dialog().remove();
    } 
    
    function LogOut() {      
      var params = "action=logout";
      jQuery.ajax({
        url: "/ajax-login.aspx?" + params,
        async: false,
        cache: false,
        dataType: "html",
        success: function(html) {
          receiveDataLogOut(html);
        }        
      });
    }  
    
    function receiveDataLogOut(html) {
      var output = "<div id='message' title='MIA - Area Espositori'><p class='testo' style='text-align:left;'>" + html + "<\/p><\/div>";
      $('#aspnetForm').after($(output));
      $('#message').dialog({
	      bgiframe: true,
	      autoOpen: true,
	      modal: true,
	      height: 200,
	      width: 200,
	      position:  'center',	
	      buttons: {
	       Ok: function() {
		       location.reload();
		       $(this).dialog('destroy');
	       }
	      },  
        open:function(event, ui){
          onLoadCommonFunctions();
          var windowWidth = document.documentElement.clientWidth;
          var windowHeight = document.documentElement.clientHeight;
          var popupHeight = $(".ui-dialog").height();
          var popupWidth = $(".ui-dialog").width();
          $(".ui-dialog").css({
            "position": "absolute",
            "top": windowHeight/2-popupHeight/2,
            "left": windowWidth/2-popupWidth/2
          });
        }
      });      
    }
    
    function getFileNameFormFullPath(path) {
      return path.match(/[-_\w]+[.][\w]+$/i)[0];
    }

    function getQueryStringHash (url) {
      return url.slice(url.indexOf('?') + 1)
    }
    
    function openSheet(s, ilink) {
      if (s!=""){
		    switch (ilink) {
		    case 0:
	        window.top.location=s;
			    break;
		    case 1:
		      window.open(s, "sceglifacile");
			    break;
		    default:
	        window.location=s;
		    }
      }
	    return false;
    }
      
//    $.extend({
//      getUrlVars: function(url){
//        var vars = [], hash;
//        var hashes = url.slice(url.indexOf('?') + 1).split('&');
//        for(var i = 0; i < hashes.length; i++)
//        {
//          hash = hashes[i].split('=');
//          vars.push(hash[0]);
//          vars[hash[0]] = hash[1];
//        }
//        return vars;
//      },
//      getUrlVar: function(url, name){
//        return $.getUrlVars(url)[name];
//      }
//    });
