/* FBM Utilities */

Object.extend(Number.prototype, {

  byteToStr: function() {
    // human readable filesize
    var quantities = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    var val = parseFloat(this);
    var t = 0;
    while(val >= 1000) {
      t++, val /= 1024;
    }

    if (typeof sprintf == 'undefined')
      return ((val<1) ? val : Math.round(val)) +' '+ quantities[t];

    // round value to get 2 most significant places
    if (val >= 10) {
      // no digits after decimal points
      val = Math.round(val);
    } else if (val >= 1) {
      // 1 digit after decimal point
      val = sprintf('%01.1f', val);
    } else {
      // 2 digits after decimal point
      val = sprintf('%01.2f', val);
    }
    
    return val +' '+ quantities[t];
  }

});
    
// just shortcut to create number object
function $N(object) {
  if (object && object.constructor == Number) return object;
    return new Number(object);
};

// append passed code to the body of current function und return updated function object
Function.prototype.appendCode = function(code) {
  var currCode = this.toString();
  var last = currCode.lastIndexOf('}');
  if (last > -1) {
    currCode = currCode.substring(0, last) + code + '}';
  }
  
  if (typeof this.name != 'undefined' && this.name != '') {
    eval(this.name + '=' + currCode + ';');
    return this;
  } else {
    eval('var nfunc = ' + currCode + ';');
    return nfunc;
  }
}

Date.prototype.toEUStr = function(withSec) {
  // format date like this: 2008.02.21, 08:03
  if (typeof withSec == 'undefined')
    withSec = 0;

  var Y = this.getFullYear();
  var d = this.getDate();
  if (d < 10) d = '0' + d;
  var m = this.getMonth() +1;
  if (m < 10) m = '0' + m;
  var H = this.getHours();
  if (H < 10) H = '0' + H;
  var i = this.getMinutes();
  if (i < 10) i = '0' + i;
  var s = this.getSeconds();
  if (s < 10) s = '0' + s;
  
  return Y + '.' + m + '.' + d + ', ' + H + ':' + i + ((withSec) ? ':' + s : '');
};  

// found @de.selfhtml.org
String.prototype.utf8Encode = function() {
  // dient der Normalisierung des Zeilenumbruchs
  var rohtext = this.replace(/\r\n/g,"\n");
  var utftext = "";
  for(var n=0; n<rohtext.length; n++) {
    // ermitteln des Unicodes des  aktuellen Zeichens
    var c=rohtext.charCodeAt(n);
    // alle Zeichen von 0-127 => 1byte
    if (c<128) {
      utftext += String.fromCharCode(c);
    } else if((c>127) && (c<2048)) {
      // alle Zeichen von 127 bis 2047 => 2byte
      utftext += String.fromCharCode((c>>6)|192);
      utftext += String.fromCharCode((c&63)|128);
    } else {
      // alle Zeichen von 2048 bis 66536 => 3byte
      utftext += String.fromCharCode((c>>12)|224);
      utftext += String.fromCharCode(((c>>6)&63)|128);
      utftext += String.fromCharCode((c&63)|128);
    }
  }
  return utftext;
};

// found @de.selfhtml.org
String.prototype.utf8Decode = function() {
  var utftext = this;
  var plaintext = ""; var i=0; var c=c1=c2=0;
  // while-Schleife, weil einige Zeichen uebersprungen werden
  while(i<utftext.length) {
    c = utftext.charCodeAt(i);
    if (c<128) {
      plaintext += String.fromCharCode(c);
      i++;
    } else if((c>191) && (c<224)) {
      c2 = utftext.charCodeAt(i+1);
      plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
      i+=2;
    } else {
      c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
      plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
      i+=3;
    }
  }
  return plaintext;
};

// typ can be:
// 0 = no conversion of quota chars
// 1 = convert only single quota
// 2 = convert only double quota (default)
// 3 = convert single and double quotas
// 4 = convert only characters with code > 160
// found @www.infocamp.de
String.prototype.htmlentities = function(typ) {
  var str = this;
  
  if (typeof typ == 'undefined') typ = 2;
  typ = Math.max(0, Math.min(4, parseInt(typ)));
  
  var html = new Array();
  if (typ != 4) {
    html[38] = "&amp;";
    html[60] = "&lt;";
    html[62] = "&gt;";
  }
  if (typ==1 || typ==3) html[39] = "&#039;";
  if (typ==2 || typ==3) html[34] = "&quot;";
  
  // GJ 2008.06.05 - this line does not work with prototype, so new version
  //for (var i in html) eval("str=str.replace(/"+String.fromCharCode(i)+"/g, \""+html[i]+"\");");
  $H(html).each( function(pair) {
      if (pair.value.constructor == Function) return;  // prototype addons come here too, so skip them
      eval("str = str.replace(/"+ String.fromCharCode(pair.key) +"/g, \""+ pair.value +"\");");
  });
  
  
  var entity = new Array(
    "&nbsp;","&iexcl;","&cent;","&pound;","&curren;","&yen;","&brvbar;","&sect;",
    "&uml;","&copy;","&ordf;","&laquo;","&not;","&shy;","&reg;","&macr;",
    "&deg;","&plusmn;","&sup2;","&sup3;","&acute;","&micro;","&para;","&middot;",
    "&cedil;","&sup1;","&ordm;","&raquo;","&frac14;","&frac12;","&frac34;","&iquest;",
    "&Agrave;","&Aacute;","&Acirc;","&Atilde;","&Auml;","&Aring;","&AElig;","&Ccedil;",
    "&Egrave;","&Eacute;","&Ecirc;","&Euml;","&Igrave;","&Iacute;","&Icirc;","&Iuml;",
    "&ETH;","&Ntilde;","&Ograve;","&Oacute;","&Ocirc;","&Otilde;","&Ouml;","&times;",
    "&Oslash;","&Ugrave;","&Uacute;","&Ucirc;","&Uuml;","&Yacute;","&THORN;","&szlig;",
    "&agrave;","&aacute;","&acirc;","&atilde;","&auml;","&aring;","&aelig;","&ccedil;",
    "&egrave;","&eacute;","&ecirc;","&euml;","&igrave;","&iacute;","&icirc;","&iuml;",
    "&eth;","&ntilde;","&ograve;","&oacute;","&ocirc;","&otilde;","&ouml;","&divide;",
    "&oslash;","&ugrave;","&uacute;","&ucirc;","&uuml;","&yacute;","&thorn;","&yuml;"
  );
  
  for(var i=0; i<entity.length; i++)
    eval("str = str.replace(/"+ String.fromCharCode(i*1+160) +"/g,\""+ entity[i] +"\");");
  
  return str;
};

addBookmark = function(url, title) {
  if (typeof title == 'undefined')
    title = document.title;

  if(document.all) {
    window.external.AddFavorite(url, title);
  } else if (window.sidebar) { 
    window.sidebar.addPanel(title, url, ''); 
  } else if(window.opera && window.print) {
    return true;
  }  
};

dialogbox = function(dialogboxUrl, width, height, options) {
  if (typeof width == 'undefined')  width  = 630;
  if (typeof height == 'undefined') height = 460;
  
  window.profileWin = new Window(Object.extend({
    className:      'dialogbox',
    draggable:      false,
    resizable:      false,
    minimizable:    false,
    maximizable:    false,
    hideEffect:     Element.hide,
    showEffect:     Element.show,
    width:          width,
    height:         height,
    destroyOnClose: !Prototype.Browser.IE,  // GJ 2008.06.04 - setting to true makes errors in IE7 after dialog close, FF+Safari OK
    zIndex:         1000,
    url:            dialogboxUrl
  }, options || {}));
  //contentWin.setContent('downloadbox', true, true);
  window.profileWin.showCenter(true);
};

popupWindow = function(url, width, height, options) {
  if (typeof width == 'undefined')  width  = 400;
  if (typeof height == 'undefined') height = 300;
  
  options = Object.extend({
    name:          '_blank',
    width:         parseInt(width),
    height:        parseInt(height),
    center:        false,
    left:          100,
    top:           100,
    
    //innerWidth:     width,
    //innerHeight:    height,
    //screenX:          100,
    //screenY:          100,

    //location:      'no',
    //menubar:       'no',
    //scrollbars:    'no',
    //status:        'no',
    //toolbar:       'no'

    //dependent:     'no',
    //hotkeys:       'yes',
    resizable:     'yes'

  }, options || {});
  
  if (options.center) {
    options.left = (screen.width - options.width)/2;
    options.top  = (screen.height - options.height)/2;
  }
  
  var optionsStr = [];
  $H(options).each(function(pair) {
      if (pair.key == 'name') return;
      if (pair.key == 'center') return;
      optionsStr.push(pair.key + '=' + pair.value);
  });

  win = window.open(url, options.name, optionsStr.join(','));
  win.focus();
  
  return win;
};
