/// <reference path="jQuery.js" />

var agt = navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie4up = (is_ie && (is_major >= 4));
var is_opera = (agt.indexOf("opera") != -1);
var is_gecko = ((agt.indexOf('gecko') != -1) && (agt.indexOf("konqueror") == -1));

function declareNS(name) {
  if (typeof window[name]==='undefined') {
    window[name] = {};
  }
}

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

if (!Array.prototype.remove)
{
  Array.prototype.remove = function(element)
  {
    return this.filter(function(el) {
      return el!==element;
    });
  };
}

function escapeSelector(value) {
    value = value.replace(/\[/, "\\[");
    value = value.replace(/\]/, "\\]");

    return value;
}

function implode(items, prepend, append) {
    var result = "";
    for (i = 0; i < items.length; i++)
        result += (result != "" ? "," : "") + prepend + items[i] + append;
    return result;
}

function focusTextField(form) {
//TODO: jQuery
    if ((typeof form != 'object') || (typeof form.elements != 'object')) {
        return false;
    }

    var elements = form.elements;
    for (var i = 0; i < elements.length; i++) {
        if ((elements[i].type != 'text') && (elements[i].type != 'password')
                && (elements[i].type != 'textarea')) {
            continue;
        }
        if (elements[i].value == '') {
            elements[i].focus();
            break;
        }
    }

    return true;
}

function toggleCode(id) {
    $("#code" + id).toggle();
    $("#plusFor" + id).toggle();
    $("#minusFor" + id).toggle();
    $("#hintFor" + id).toggle();
}

function toggleScroll(id, theHeight) {
    var theCode = $("#code" + id);
    var full = $("#fullFor" + id);
    var half = $("#halfFor" + id);

    if (full.is(':visible')) {
        theCode.css("height", "");
    } else {
        theCode.css("height", theHeight + "px");
    }

    full.toggle();
    half.toggle();

    if (!theCode.is(':visible'))
        toggleCode(id);
}


function setCheckboxes(theForm, elementName, isChecked) {
    $("[name='" + escapeSelector(theForm) + "'] [name='" + escapeSelector(elementName)+"']").attr("checked", isChecked);
}

function selectAll(codeId) {
    var pre = $("#code" + codeId + " table td:eq(1) pre:eq(0)");

    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(pre[0]);
        range.select();
    }
    else if (window.getSelection) {
        var range = document.createRange();
        range.selectNodeContents(pre[0]);
        var codeSelection = window.getSelection();
        codeSelection.removeAllRanges();
        codeSelection.addRange(range);
    }
    else
        alert('Dein Browser unterstützt diese Funktion leider nicht.');
}


function html_entity_decode(text) {
    text = text.replace(/&gt;/g, ">");
    text = text.replace(/&lt;/g, "<");
    text = text.replace(/&#039;/g, "'");
    text = text.replace(/&quot;/g, "\"");
    text = text.replace(/&amp;/g, "&");
    text = text.replace(/&#8364;/g, "€");

    return text;
}

function umlaut_decode(text) {
    text = text.replace(/&uuml;/g, "ü");
    text = text.replace(/&Uuml;/g, "Ü");
    text = text.replace(/&auml;/g, "ä");
    text = text.replace(/&Auml;/g, "Ä");
    text = text.replace(/&ouml;/g, "ö");
    text = text.replace(/&Ouml;/g, "Ö");
    text = text.replace(/&szlig;/g, "ß");


    return text;
}


function checkAjaxError(data) {
    var error = $(data).children("root").children("error");
    if (error.length > 0) {
        alert(error.text());
        return false;
    }
    return true;
}

// Funktionen für jQuery.***
jQuery.extend({
    eeGet: function (url, data, callback, errorCallback) {
        //von jQuery.js "ausgeliehen", CS
        // shift arguments if data argument was ommited
        if (jQuery.isFunction(data)) {
            errorCallback = callback;
            callback = data;
            data = null;
        }

        if (!errorCallback)
            errorCallback = checkAjaxError;

        var theCallback = function (data) {
            if (!errorCallback(data))
                return;

            callback(data);
        }
        if (url.match('[\?&]dummy=')==null)
          url+= ((url.split('?').length==1)?'?':'&') + 'dummy='+($.now());
        return jQuery.get(url, data, theCallback);
    },

    eePost: function (url, data, callback, errorCallback) {
        //von jQuery.js "ausgeliehen", CS
        // shift arguments if data argument was ommited
        if (jQuery.isFunction(data)) {
            errorCallback = callback;
            callback = data;
            data = null;
        }

        if (!errorCallback)
            errorCallback = checkAjaxError;

        var theCallback = function (data) {
            if (!errorCallback(data))
                return;

            callback(data);
        }

        return jQuery.post(url, data, theCallback);
    }
});

// Funktionen für $()-Instanzen
jQuery.extend(jQuery.fn, {
    later: function(callback) {
      window.setTimeout(function() {
       callback.call(this);
      },0);
      return this;
    },
    selText: function() {
      if (typeof this[0].options!=="undefined" &&
          typeof this[0].selectedIndex!== "undefined")
        return $(this[0].options[this[0].selectedIndex]).text();
      return undefined;
    }
});

function jqid(myid) {
  return '#' + myid.replace(/(:|\.|\]|\[)/g,'\\$1');
}

(function($) {
  function Selection(ta) {
    this.start = function(val) {
      ta.focus();
      if (typeof val=="undefined") {
        if (typeof ta.selectionStart!=="undefined")
          return ta.selectionStart;
        if (document.selection) {
          // Thanks to tkirby
          // http://www.csie.ntu.edu.tw/~b88039/html/jslib/caret.html
          var c		= "\001";
          var sel	= document.selection.createRange();
          sel.collapse(true);
          sel.text	= c;
          len		= $(ta).val().indexOf(c);
          if (len<0) len = $(ta).val().length;
          sel.moveStart('character',-1);
          sel.text	= '';

          return len;
        }
        return -1;
      } else {
        if (typeof ta.selectionStart!=="undefined")
          ta.selectionStart = val;
        if (document.selection) {
          var sel	= document.selection.createRange();
          sel.moveStart('character', val - this.start());
          sel.select();
        }
      }
    }
    this.end = function(val) {
      ta.focus();
      if (typeof val=="undefined") {
        if (typeof ta.selectionEnd!=="undefined")
          return ta.selectionEnd;
        if (document.selection) {
          var c		= "\001";
          var sel	= document.selection.createRange();
          sel.collapse(false);
          sel.text	= c;
          len		= $(ta).val().indexOf(c);
          if (len<0) len = $(ta).val().length;
          sel.moveStart('character',-1);
          sel.text	= '';

          return len;
        }
        return -1;
      } else {
        if (typeof ta.selectionEnd!=="undefined")
          ta.selectionEnd = val;
        if (document.selection) {
          var sel	= document.selection.createRange();
          sel.moveEnd('character', val - this.end());
          sel.select();
        }
      }
    }
    this.length = function() { return this.end()-this.start() }
    this.selected = function () { return !!this.length() }
    this.text = function (val) {
      if (typeof val=="undefined") {
        return this.getControlText().substring(this.start(), this.end());
      } else {
        var txt = this.getControlText(),
            st = this.start(),
            en = this.end();
        $(ta).val(
          txt.substr(0,st)+val+txt.substr(en)
        );
        this.start(st);
        this.end(st+val.length);
      }
    }
    this.getControlText = function() {
        // IE brauchts normalisiert
        if (is_ie)
          return $(ta).val();

        var rradiocheck = /^(?:radio|checkbox)$/i; //CS: in jquery.min.js als "n" definiert

        // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
        if ( rradiocheck.test( ta.type ) && !jQuery.support.checkOn ) {
            return ta.getAttribute("value") === null ? "on" : ta.value;
        }

        // Everything else, we just grab the value
        return (ta.value || "");
    }
  }

  $.extend($.fn, {
    selection: function() {
      return new Selection(this[0]);
    }
  });
})(jQuery);


function toggleInlineAttachmentsTable(id) {
    var attachmentTable = document.getElementById('inlineAttachments'+id);
    if (attachmentTable)
        attachmentTable.style.display = (attachmentTable.style.display == '') ? "none" : "";
}
