function pid() {
  return $$('body').first().id;
}

function provideThumbnailTooltip() {
  var body = $$('body').first();
  var tt = $(document.createElement("div"));
  var tt_body = $(document.createElement("div"));
  var tt_head = $(document.createElement("h4"));
  tt_head.innerHTML = "Foto Informationen";
  tt_body.className = "body";
  body.appendChild(tt);
  tt.appendChild(tt_head);
  tt.appendChild(tt_body);
  tt.id = "tooltip";
  tt.hide();
  var data = {}
  var isOver = null;
  var mmove = function(e) {
    tt.setStyle({top: Event.pointerY(e) + "px", left: Event.pointerX(e) + "px" }); 
  }
  var mover = function(t) { 
    isOver = t; 
    var f = function() { 
      if (isOver == t) { 
        tt.show();
        tt_body.innerHTML = data[t.src]; 
      }
    }
    window.setTimeout(f, 750); 
  }
  var mout  = function(t) { 
    isOver = null; 
    tt.hide(); 
  }
  $$('div.thumb img').each(function(t) {
    data[t.src] = t.up('a').next('div.photo-info').innerHTML; // 4 quick access
    Event.observe(t, "mousemove", mmove);
    t.onmouseover = function() { mover(t); }
    t.onmouseout  = function() { mout(t); }
  });
}

function autoHideNotice() {
  if($('notice')) window.setTimeout("Effect.Fade('notice', {duration:.5})", 4000);
}

function externalLinks() {
  //$$("a[rel=external]").each(function(anchor) { 
  $A(document.getElementsByTagName("a")).each(function(anchor) { 
    if (anchor.rel == "external") {
        anchor.target = "_blank";
        anchor.className += " external";
        if (anchor.title.length == 0) {
        anchor.title = "Öffnet in neuem Fenster";
      }
    }
  });
}

function ieRemoveImgAlt() {
  if (document.all && document.getElementsByTagName) {
    $A(document.getElementsByTagName("img")).each(function(img) {
      img.alt = "";
    });
  }
}

/**
 * IE :hover bugfix
 *
 * Weist allen Elementen der Liste bei "mouseover"
 * die angegebene CSS-Klasse zu. 
 *
 * @param elem_list       Element Referenzliste 
 * @param class_name      Name der Klasse, die bei Mouse-Over
 *                        zugewiesen werden soll  
 */
function ieHoverBugfix(elem_list, class_name) {
  if (elem_list == null) return;
  if (document.all && document.getElementById) {
    class_name = " " + class_name;
    var fix = function(child_elem) {
      child_elem.onmouseover = function() {
        this.className += class_name;
      }
      child_elem.onmouseout = function() {
        this.className = this.className.replace(class_name, "");
      }
    };
    $A(elem_list).each(fix);
  }
}

function ieFocusBugfix() {
  if (document.all) {
    ["#navigation a", "input.text", "textarea", "select"].each(function(tag){
      $$(tag).each(function(elem) {
        elem.onfocus = function() { this.className += " focus"; }
        elem.onblur = function() { this.className = this.className.split("focus").join(""); }
      });
    });
  }
}

function blurElementOnClick(tagName) {
  $A(document.getElementsByTagName(tagName)).each(function(e){
    var e_onclick = e.onclick;
    e.onclick = function() {
      if (e_onclick instanceof Function) e_onclick.call(this);
      this.blur();
    };
  });
}
function blurLinksOnClick() {
  blurElementOnClick('a');
}
function blurButtonsOnClick() {
  blurElementOnClick('button');
}

function provideLinkOn(tagRef, url) {
  tagRef.style.cursor = "pointer";
  tagRef.onclick = function() { location.href = url; };
}

function provideAdminLink() {
  var footer = document.getElementById("footer");
  footer.innerHTML = footer.innerHTML.split("©").join('<span onclick="document.location.href=\'/admin\'">©</span>');
}

/* by selfHTML */
function insert(aTag, eTag, input, doc) {
  input.focus();
  /* für Internet Explorer */
  if(typeof doc.selection != 'undefined') {
    /* Einfügen des Formatierungscodes */
    var range = doc.selection.createRange();
    var insText = range.text;
    range.text = aTag + insText + eTag;
    /* Anpassen der Cursorposition */
    range = doc.selection.createRange();
    if (insText.length == 0) {
      range.move('character', -eTag.length);
    } else {
      range.moveStart('character', aTag.length + insText.length + eTag.length);      
    }
    range.select();
  }
  /* für neuere auf Gecko basierende Browser */
  else if(typeof input.selectionStart != 'undefined')
  {
    /* Einfügen des Formatierungscodes */
    var start = input.selectionStart;
    var end = input.selectionEnd;
    var insText = input.value.substring(start, end);
    input.value = input.value.substr(0, start) + aTag + insText + eTag + input.value.substr(end);
    /* Anpassen der Cursorposition */
    var pos;
    if (insText.length == 0) {
      pos = start + aTag.length;
    } else {
      pos = start + aTag.length + insText.length + eTag.length;
    }
    input.selectionStart = pos;
    input.selectionEnd = pos;
  }
  /* für die übrigen Browser */
  else
  {
    /* Abfrage der Einfügeposition */
    var pos;
    var re = new RegExp('^[0-9]{0,3}$');
    while(!re.test(pos)) {
      pos = prompt("Einfügen an Position (0.." + input.value.length + "):", "0");
    }
    if(pos > input.value.length) {
      pos = input.value.length;
    }
    /* Einfügen des Formatierungscodes */
    var insText = prompt("Bitte geben Sie den zu formatierenden Text ein:");
    input.value = input.value.substr(0, pos) + aTag + insText + eTag + input.value.substr(pos);
  }
}

function insert_upload(path, textarea_id, size) {
  var doc = parent.document;
  var textarea = doc.getElementById(textarea_id);
  var ext = $A(path.split('.')).last().toLowerCase();
  if ('png jpg gif'.split(' ').include(ext)) {
    insert('<img src="' + path + '" alt="', '" />', textarea, doc);
  } else {
    insert('<a href="/download' + path + '">', 
      ' <span>(' + ext.toUpperCase() + (size ? ' ' + size : '') + 
      ')</span></a>', textarea, doc);
  }
}

function generate_code() {
  var alpha_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var chars = alpha_chars + "0123456789";
  var rand = function(num) { return Math.round(Math.random() * num); };
  var newpass = alpha_chars[rand(alpha_chars.length - 1)];
  var n = 4;
  while (n-- > 0) { newpass += chars[rand(chars.length - 1)]; };
  return newpass;
}

function is_admin() {
  return $$('body').first().className == 'admin';
}

function truncate_wordy(text, length, truncate_string) {
  length = length || 30;
  truncate_string = truncate_string || "...";
  if (text == null || text == "") return '';
  var new_text = text;
  if (text.length > length) {
    new_text = text.substr(0, length + 1).gsub(/\S+$/, "");
    if (new_text == "") new_text = text.substr(0, length);
    new_text += truncate_string;
  }
  return new_text;
}

function reform_gallery_selectors() {
  $A(['category-selector', 'marked-photo-actions', 'memorized-photo-actions']).each(function(e) {
    if (e = $(e)) {
      var sel = e.getElementsByTagName('select')[0];
      sel.onchange = function() { 
        var submit_onclick = sel.form.getElementsByTagName("button")[0].onclick || function() { return true; };
        if (submit_onclick()) {
          this.form.submit(); 
        } else {
          sel.selectedIndex = 0;
        }
      }
      Element.hide(e.getElementsByTagName('button')[0]);
    }
  });
  if (pid() == "G" && is_admin()) {
    /* style adjustment */
    $('selection').setStyle({ display: "inline", margin: "0" });
    $$('.actions')[0].setStyle({ bottom: "-36px", right: "0" });
    $('footer').setStyle({ paddingTop: "50px" });
  }
}
