var main_host;
var img_array = new Array();
var swap_img = "";
var debug = false;

$().ready(function() {

  main_host = $('base').attr('href');

  log('Campi restricted: '+$('.restricted').size());
  $('.restricted').bind('keypress', function(e) {
    return restricted(e, $(this).attr('rel'));
  });

  $('.maph').maphilight({fade: false, fillColor :'5cabfa', fillOpacity : 1, stroke:false});

  hReplace();
});

function log(str) {
 if(debug) {
   if(typeof(console) != 'undefined') {
     console.info(str);
   }
 }
}

function error(str) {
 if(typeof(console) == 'undefined') {
   alert(str);
 } else {
   console.error(str);
 }
}

function getTextFromKey(module, key) {
  if(typeof(Lang[module]) == 'undefined') {
    str = 'Lang Module '+module+' not found ('+module+"."+key+')';
    if(typeof(console) == 'undefined') {
      alert(str);
    } else {
      error(str);
    }
    return module+"."+key;
  } else {
    if(typeof(Lang[module][key]) == 'undefined') {
      str = 'Key '+key+' not found in module '+module;
      if(typeof(console) == 'undefined') {
        alert(str);
      } else {
        error(str);
      }
      return module+"."+key;
    } else {
      return Lang[module][key];
    }
  }
}



/**
 * Funzione che fa da wrapper al componente ui.dialog.js (sostituisce l'alert)
 */
function modal_dialog(title, contenuto) {
  $('<div>'+contenuto+'<br /><br /></div>').dialog({
    title: title,
    modal : true,
    overlay: {
      backgroundColor: '#000',
      opacity: 0.5
    },
    buttons: {
      'Ok': function() {
        $(this).dialog('close').remove();
      }
    }
  });

  total_height = $('.ui-dialog').height();
  before_resize_content_height = $('.ui-dialog-content').height();
  button_pane_height = $('.ui-dialog-buttonpane').height();
  interface_height = total_height - before_resize_content_height;
  $('.ui-dialog-content').css({'height':'auto'});
  after_resize_content_height = $('.ui-dialog-content').height();
  $('.ui-dialog').css({'height':after_resize_content_height+interface_height+button_pane_height+'px'});
}


/**
 * Passato l'evento del keyup la funzione verifica se il valore fornito è tra quelli
 * accettati
 */
function restricted(e, allowed_chars) {
  if(debug) log(e);
  key = (e.charCode) ? e.charCode : e.which;

  if(debug) log("restricted\nkey_code:"+key);

  if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) ) return true;

  keychar = String.fromCharCode(key);
  log("restricted\nkeychar:"+keychar);
  if(debug) log("keychar:"+keychar);

  re = new RegExp(allowed_chars+'{1}');


  if(re.test(keychar)) {
    if(debug) log('OK');
    return true;
  }

  if(debug) log('KO');
  return false;
}


function hReplace() {
  $('.hreplace').each(function(){
    var data = $.metadata.get(this);
    $(this).css({'background-image':'url(\''+data.imgurl+'\')', 'width':data.width+'px', 'height':data.height+'px'});
    $(this).html('');
  });
}
