function isIE()
{
  var detect = navigator.userAgent.toLowerCase();
  var place = detect.indexOf('msie') + 1;
  return place;
}

function isLeapYear(year)
{
  return ( ((year)>0) && !((year)%4) && ( ((year)%100) || !((year)%400) ) );
}

function monthDays(month,year)
{
  month = parseInt(month);
  year = parseInt(year);
  switch(month)
  {
    case 1: return 31;
    case 2:
      if(year == 0 || isLeapYear(year))
        return 29;
      else
        return 28;
      break;
    case 3: return 31;
    case 4: return 30;
    case 5: return 31;
    case 6: return 30;
    case 7: return 31;
    case 8: return 31;
    case 9: return 30;
    case 10: return 31;
    case 11: return 30;
    case 12: return 31;
    default: return 31;
  }
}

function submitenter(myfield,e)
{
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;

  if (keycode == 13)
  {
   myfield.form.submit();
   return false;
  }
  else return true;
}

function isValidIdentifier(ident, minlength)
{
  var reg = new RegExp("^[A-Za-z0-9_\-]{" + minlength.toString() + ",}$");
  return reg.test(ident);
}

function isValidEntityName(entityname)
{
  var reg = new RegExp("^[A-Za-z0-9_\-]{2,}(\.[A-Za-z0-9_\-]{2,})*$");
  return reg.test(entityname);
}

function getViewPortHeight()
{
  if (typeof window.innerWidth != 'undefined') // Mozilla
  {
    return window.innerHeight;
  }
  else if (typeof document.documentElement != 'undefined'
      && typeof document.documentElement.clientWidth !=
      'undefined' && document.documentElement.clientWidth != 0) // IE Standards compliant
  {
    return document.documentElement.clientHeight;
  }
  else // Old IE
  {
    return document.getElementsByTagName('body')[0].clientHeight;
  }
}

function prepareIE(height, overflow)
{
  bod = document.getElementsByTagName('body')[0];
  bod.style.height = height;
  bod.style.overflow = overflow;

  htm = document.getElementsByTagName('html')[0];
  htm.style.height = height;
  htm.style.overflow = overflow;
}

function toggleSelects(visibility)
{
  selects = document.getElementsByTagName('select');
  for(i = 0; i < selects.length; i++)
  {
    selects[i].style.visibility = visibility;
  }
}

function shade()
{
  if(isIE())
  {
    prepareIE('100%', 'hidden');
    //setScroll(0,0);
    toggleSelects("hidden");
    $('shader').style.top = document.body.scrollTop + "px";
  }

  $('shader').setStyle({ opacity: 0.30 });
  $('shader').style.display = "block";
  $('lightbox').style.display = "block";
}

function unshade()
{
  if(isIE())
  {
    prepareIE("auto","auto");
    toggleSelects("visible");
    $('shader').hide();
    $('lightbox').hide();
  }
  else
  {
    $('lightbox').hide();
    Effect.Fade($('shader'), { duration: 0.4 });
  }
}

function centerWindow(id)
{
  var wnd = $(id);
  var viewheight = getViewPortHeight();
  var winheight = wnd.offsetHeight;
  var newtop = (viewheight - winheight)/2;
  if(isIE())
  {
    newtop += document.body.scrollTop;
  }
  wnd.style.top = newtop.toString() + "px";
}

function openWindow(id)
{
  shade();
  var window = $(id);
  window = window.remove();
  $('lightbox').appendChild(window);
  window.show();
  new Draggable(window, { revert: false, handle: "window-caption" });
  window.setStyle({ opacity: 1.00 });
  centerWindow(id);
}

function closeWindow(id)
{
  var window = $(id);
  window.hide();
  unshade();
}

function showHint(elem)
{
  elem = $(elem);
  var container = elem.up();
  var hintLeft = (elem.offsetLeft + elem.offsetWidth + 5).toString() + "px";
  var hintTop = (elem.offsetTop).toString() + "px";

  var div = Builder.node("div", { className: 'hint-top', style: "left: " + hintLeft + "; top: " + hintTop + ";" }, [
    Builder.node("div", { className: 'hint-bottom' }, [
      Builder.node("div", { className: 'hint-content' }, elem.alt )
    ])
  ]);

  if( elem.next() == null )
    container.appendChild(div);
  else
    container.insertBefore(div, elem.next());
}

function hideHint(elem)
{
  elem = $(elem);
  var hint = elem.next();
  if( hint != null ) hint.remove();
}

function showSuccess(txt)
{
  var adminSuccess = $('admin-success');
  adminSuccess.innerHTML = txt;
  adminSuccess.show();
  new PeriodicalExecuter(function(pe) {
    pe.stop();
    Effect.Fade(adminSuccess);
  }, 8);
}

function track(rel, lookup, recursive, referer)
{
  var params = "&w=" + screen.width;
  params = params + "&h=" + screen.height;
  params = params + "&c=" + screen.colorDepth;
  params = params + "&l=" + lookup;
  params = params + "&r=" + recursive;
  params = params + "&ref=" + referer;
  var ajax = new Ajax.Request('ajax.php',
    {method: 'post', evalScripts: true, parameters: 's=' + rel + '/callback/track.php' + params, onComplete: track_complete }
  );
}

function track_complete(xhr)
{
}

/*
 *  Global responders for Ajax events.
 *  OnCreate   - an Ajax request was initiated. Show the throbbing loader.
 *  OnComplete - an Ajax request was completed. Hide the throbbing loader
 *               (but only when there are no more active requests).
 *
 */
var globalResponders =
{
  onCreate: function()
  {
    Element.show('loader');
  },
  onComplete: function()
  {
    if(Ajax.activeRequestCount == 0)
    {
      Element.hide('loader');
    }
  }
};
Ajax.Responders.register(globalResponders);



/*
 *  Add automatic hint display for form fields.
 */
Event.observe(window, 'load', function() {
  var inputs = $$('textarea[alt]', 'input[alt]');
  inputs.each(function(input) {
    input.onfocus = function() { showHint(input); return false; };
    input.onblur = function() { hideHint(input); return false; };
  });
});





var uploadControlList = {};

var UploadControl = Class.create(
{
  initialize: function(elem, postbackurl, dir, fcancel, translations )
  {
    this.elem = $(elem);
    this.postbackurl = postbackurl;
    this.dir = dir;
    this.filecount = 0;
    this.fcancel = fcancel;
    this.translations = translations ? translations : {};

    if (this.hasFlash())
    {
      this.initialize_flash(fcancel);
    }
    else
    {
      this.initialize_js(fcancel);
    }
  },

  hasFlash: function()
  {
    return false;
  },

/*
  hasFlash: function()
  {
    return swfobject.hasFlashPlayerVersion("9.0.0");
  },
*/
  initialize_flash: function()
  {
    var upload_link = Builder.node("a", { href: "#" }, [ this.translations.btn_upload ? this.translations.btn_upload : "Upload" ]);
    upload_link.onclick = this.uploadFiles.bind(this);
    var cancel_link = Builder.node("a", { href: "#" }, [ this.translations.btn_cancel ? this.translations.btn_cancel : "Cancel" ]);
    cancel_link.onclick = this.onCancel.bind(this);

    var header = Builder.node("div", { className: "header" }, [
      Builder.node("div", { className: "name" }, [ this.translations.hdr_file ? this.translations.hdr_file : "File" ]),
      Builder.node("div", { className: "size" }, [ this.translations.hdr_size ? this.translations.hdr_size : "Size" ]),
      Builder.node("div", { className: "options" }, [ this.translations.hdr_remove ? this.translations.hdr_remove : "Remove?" ])
    ]);

    var list = Builder.node("div", { className: "list" });

    var control = Builder.node("div", { className: "control" }, [
      Builder.node("div", { className: "files" }, ["0 " + (this.translations.str_files ? this.translations.str_files : "files") ]),
      Builder.node("div", { className: "add" },[
        Builder.node("div", { id: this.elem.id+"_flashhost" })
      ]),
      Builder.node("div", { className: "totalsize" }, [ (this.translations.str_total ? this.translations.str_total : "Total") + ": 0 bytes"]),
      Builder.node("div", { className: "upload", style: "display:none" }, [ upload_link ]),
      Builder.node("div", { className: "cancel" }, [ cancel_link ])
    ]);

    var form = Builder.node("form", { method: "post" });

    this.elem.className = "uploadcontrol-container";
    this.elem.appendChild(header);
    this.elem.appendChild(list);
    this.elem.appendChild(control);
    this.elem.appendChild(form);

    swfobject.embedSWF(
      this.dir + "upload.swf",
      this.elem.id+"_flashhost",
      "80", "20", "9",
      false,
      { elem: this.elem.id, url: this.postbackurl, label: (this.translations.btn_add ? this.translations.btn_add : "Add more") },
      { wmode: "transparent", allowScriptAccess: "sameDomain" },
      { id: this.elem.id+"_flash" } );

    uploadControlList[this.elem.id] = this;
  },

  initialize_js: function()
  {
    var upload_link = Builder.node("a", { href: "#" }, [this.translations.btn_upload ? this.translations.btn_upload : "Upload"]);
    upload_link.onclick = this.uploadJSFiles.bind(this);
    var cancel_link = Builder.node("a", { href: "#" }, [this.translations.btn_cancel ? this.translations.btn_cancel : "Cancel"]);
    cancel_link.onclick = this.onCancel.bind(this);
    var header = Builder.node("div", { className: "header" }, [
      Builder.node("div", { className: "name" }, [this.translations.hdr_file ? this.translations.hdr_file : "File"]),
      Builder.node("div", { className: "size" }, ["-"]),
      Builder.node("div", { className: "options" }, [this.translations.hdr_remove ? this.translations.hdr_remove : "Remove?"])
    ]);
    var list = Builder.node("form", { className: "list", method: "post", enctype: "multipart/form-data" });
    var fileinput = Builder.node("input", { type: "file", size: "10", value: ""});
    var control = Builder.node("div", { className: "control" }, [
      Builder.node("div", { className: "files" }, ["0 " + (this.translations.str_files ? this.translations.str_files : "files")]),
      Builder.node("div", { className: "browse"}, [ fileinput ]),
      Builder.node("div", { className: "upload", style: "display:none" }, [ upload_link ]),
      Builder.node("div", { className: "cancel" }, [ cancel_link ])
    ]);
    this.elem.className = "uploadcontrol-container";
    this.elem.appendChild(header);
    this.elem.appendChild(list);
    this.elem.appendChild(control);
    this.id = 0;
    this.addElement(fileinput);
  },

  uploadJSFiles: function()
  {
    this.elem.down().next().submit();
  },

  addElement: function(element)
  {
    element.name = 'file_' + this.id++;
    element.uploadcontrol = this;
    var myself = this;
    element.onchange = function()
    {
      if(myself.alreadyHasFile(this.value))
      {
        this.value = "";
      }
      else
      {
        var new_element = Builder.node("input", { type: "file", size: "10" });
        this.parentNode.insertBefore( new_element, this );
        this.uploadcontrol.addElement( new_element );
        this.uploadcontrol.addListRow( this );
      }
    };
  },

  updateJSInfo: function()
  {
    var countstr = this.filecount == 1 ? ("1 " + (this.translations.str_file ? this.translations.str_file : "file")) : this.filecount.toString() + " " + ((this.translations.str_files ? this.translations.str_files : "files"));
    this.elem.down().next().next().down().innerHTML = countstr;

    // Show upload div
    var uploaddiv = this.elem.down().next().next().down().next().next();
    uploaddiv.hide(); if( this.filecount > 0 ) uploaddiv.show();
  },

  addListRow: function( element )
  {
    element = $(element);
    element.style.position = "absolute";
    element.style.left = "-1000px";
    element.remove();
    var list = this.elem.down().next();
    var delete_link = Builder.node("a", { className: "deletelink", href: "#" }, [ this.getDeleteImg() ]);
    var myself = this;
    delete_link.onclick = function() { myself.filecount--; myself.updateJSInfo(); $(this).up().up().remove(); return false; };
    var block = Builder.node("div", { className: "block" }, [
      Builder.node("div", { className: "bytes" }, [ element ] ),
      Builder.node("div", { className: "name" }, [ element.value ] ),
      Builder.node("div", { className: "size" }, [ "-" ] ),
      Builder.node("div", { className: "options" }, [ delete_link ] )
    ]);
    list.appendChild(block);
    this.filecount++;
    this.updateJSInfo();
  },

  alreadyHasFile: function( filename )
  {
    var result = false;
    var list = this.elem.down().next();
    list.select("input").each (function(input)
    {
      if(input.value == filename) result = true;
    });
    return result;
  },

  round2: function(val)
  {
    var rounded = Math.round(val*100).toString();
    var frac = ((Math.round(val*100))/100).toString();
    if(frac.length == rounded.length) frac += "0";
    return frac;
  },

  bytesToString: function(bytes)
  {
    if( bytes > 1048576 ) return this.round2(bytes/1048576) + " MB";
    else if( bytes > 1024 ) return this.round2(bytes/1024) + " KB";
    else return bytes.toString() + " bytes";
  },

  updateInfo: function()
  {
    // Calc total size
    var totalsize = 0;
    this.elem.down().next().select("div.block").each (function(block) {
      var size = parseInt(block.down().innerHTML);
      totalsize += size;
    });
    this.elem.down().next().next().down().next().next().innerHTML = (this.translations.str_total ? this.translations.str_total : "Total") + ": " + this.bytesToString(totalsize);

    var countstr = this.filecount == 1 ? ("1 " + (this.translations.str_file ? this.translations.str_file : "file")) : this.filecount.toString() + " " + ((this.translations.str_files ? this.translations.str_files : "files"));
    this.elem.down().next().next().down().innerHTML = countstr;

    // Show upload div
    var uploaddiv = this.elem.down().next().next().down().next().next().next();
    uploaddiv.hide(); if( this.filecount > 0 ) uploaddiv.show();
  },

  deleteFile: function(link)
  {
    var filename = $(link).up().previous().previous().innerHTML;
    $(this.elem.id+"_flash").jsRemoveFile(filename);
    var block = $(link).up().up();
    block.remove();
    this.filecount--;
    this.updateInfo();
    return false;
  },

  onCancel: function()
  {
    if ( this.hasFlash())
    {
      $(this.elem.id+"_flash").jsRemoveAllFiles();
      this.elem.down().next().innerHTML = "";
      this.filecount = 0;
      this.updateInfo();
    }
    else
    {
      this.elem.down().next().innerHTML = "";
      this.filecount = 0;
      this.updateJSInfo();
    }

    this.fcancel();
  },

  getDeleteImg: function()
  {
    var delete_img = Builder.node("img", { src: this.dir + "delete.gif" });
    var myself = this;
    delete_img.onmouseover = function () { this.src = myself.dir + "delete_highlighted.gif"; return false; };
    delete_img.onmouseout = function () { this.src = myself.dir + "delete.gif"; return false; };
    return delete_img;
  },

  onAddFile: function(filename, bytes)
  {
    var list = this.elem.down().next();

    // Determine size as string
    var sizestr = this.bytesToString(bytes);

    var delete_link = Builder.node("a", { className: "deletelink", href: "#" }, [ this.getDeleteImg() ]);
    delete_link.onclick = this.deleteFile.bind(this, delete_link);

    var block = Builder.node("div", { className: "block" }, [
      Builder.node("div", { className: "bytes" }, [ bytes.toString() ] ),
      Builder.node("div", { className: "name" }, [ filename ] ),
      Builder.node("div", { className: "size" }, [ sizestr ] ),
      Builder.node("div", { className: "options" }, [ delete_link ] ),
      Builder.node("div", { className: "progress_bk", style: "display: none" }, [
        Builder.node("div", { className: "progress" }, [ "0%" ] )
      ])
    ]);
    list.appendChild(block);

    this.filecount++;
    this.updateInfo();
  },

  uploadFiles: function()
  {
    $(this.elem.id+"_flash").jsUploadFiles();
    this.elem.down().next().next().down().next().next().next().hide();
    this.elem.down().next().next().down().next().next().next().next().hide();
  },

  findBlock: function(filename)
  {
    var blocks = this.elem.down().next().select("div.block");
    for(var i = 0; i < blocks.length; i++)
    {
      var blockfilename = blocks[i].down().next().innerHTML;
      if(blockfilename == filename) return blocks[i];
    }
    return null;
  },

  onOpen: function(filename)
  {
    var block = this.findBlock(filename);
    block.down().next().next().next().hide();
    block.down().next().next().next().next().show();
  },

  onProgress: function(filename, bytesLoaded, bytesTotal)
  {
    var percentage = Math.round(bytesLoaded * 100 / bytesTotal);
    var offset = Math.round(68 - (bytesLoaded * 68 / bytesTotal));
    var block = this.findBlock(filename);
    var progressbar = block.down().next().next().next().next().down();
    progressbar.style.backgroundPosition = "-" + offset.toString() + "px 0px";
    progressbar.innerHTML = percentage.toString() + "%";
  },

  onComplete: function(filename)
  {
    var block = this.findBlock(filename);
    var progressbar = block.down().next().next().next().next().down();
    progressbar.style.backgroundPosition = "0px 0px";
    progressbar.innerHTML = "100%";

    this.filecount--;
    // downloads complete, submit form.
    if( this.filecount == 0 )
    {
      this.elem.down().next().next().next().submit();
    }
  }
});

function uploadcontrol_onAddFile(elem, filename, bytes)
{
  uploadControlList[elem].onAddFile(filename, bytes);
}

function uploadcontrol_onOpen(elem, filename)
{
  uploadControlList[elem].onOpen(filename);
}

function uploadcontrol_onProgress(elem, filename, bytesLoaded, bytesTotal)
{
  uploadControlList[elem].onProgress(filename, bytesLoaded, bytesTotal);
}

function uploadcontrol_onComplete(elem, filename)
{
  uploadControlList[elem].onComplete(filename);
}

