// Utility funtions

var W3CDOM = (document.getElementById && document.getElementsByTagName && document.createElement);
var Browser = navigator.userAgent.toLowerCase();
var IE = ((Browser.indexOf("msie") != -1) && (Browser.indexOf("opera") == -1));
var Gecko = (Browser.indexOf('gecko') != -1);
var XHTMLNS = "http://www.w3.org/1999/xhtml";


function element(name) {
    var el = null;
    if (document.getElementById != null) { // DOM3 = IE5, NS6
        el = document.getElementById(name);
    } else if (document.all != null) {
        el = document.all[name];
    } else if (document.layers != null) {
        el = document.layers[name];
    }
    // Unable to find by id -> use name
    if (el == null) {
        var el_list = document.getElementsByName(name);
        if (el_list != null && el_list.length > 0) {
            el = el_list[0];
        }
    }
    return el;
}

function elements(name, tag_name, root) {
    var root_el = root != null ? root : document;
    var els = new Array();
    var tag_els = root_el.getElementsByTagName(tag_name);
    for (var i = 0; i < tag_els.length; ++i) {
        if (tag_els[i].id == name) {
            els.push(tag_els[i]);
        }
    }
    return els;
}

function showElement(el, label, minus, display_type) {
    if (el == null) {
       return;
    }
    el.style.display = display_type == null ? "block" : display_type;

    if (label == null) {
        return;
    }
    label.innerHTML = minus == null ? "-" : minus;
}

function hideElement(el, label, plus) {
    if (el == null) {
       return;
    }
    el.style.display = "none";

    if (label == null) {
        return;
    }
    label.innerHTML = plus == null ? "+" : plus;
}

function showOrHideElement(el, label, plus, minus, display_type) {
    if (el == null) {
       return;
    }
    if (el.style.display == "none") { // Not visible
        showElement(el, label, minus, display_type);
    } else {
        hideElement(el, label, plus);
    }
}

function copySelected(source_name, target_name) {
    var source, target;

    source = element(source_name);
    target = element(target_name);

    var indx = source.selectedIndex;

    if (indx >= 0) {
        var a = new Array(0);
        for (var i = 0; i < target.options.length; i++) {
            a.push(target.options[i]);
        }
        for (var i = 0; i < source.options.length; i++) {
            if (source.options[i].selected) {
                a.push(source.options[i]);
            }
        }
        a.sort(function(x, y) {
            if (x.text.toLowerCase() < y.text.toLowerCase()) return -1;
            if (x.text.toLowerCase() > y.text.toLowerCase()) return 1;
            return 0;
        });

        for (var i = 0; i < target.options.length; i++) {
            target.removeChild(target.options[i]);
        }
        for (var i = 0; i < a.length; i++) {
            target.appendChild(a[i]);
        }

       i = 0;
       while (i < source.options.length) {
           if (source.options[i].selected) {
               source.removeChild(source.options[i]);
           } else {
               i++;
           }
       }
    }
}

function addOption (oListbox, text, value, isDefaultSelected, isSelected)
{
  var oOption = document.createElement("option");
  oOption.appendChild(document.createTextNode(text));
  oOption.setAttribute("value", value);

  if (isDefaultSelected) oOption.defaultSelected = true;
  else if (isSelected) oOption.selected = true;

  oListbox.appendChild(oOption);
}


function removeOption(source, value) {
    var i = 0;
    while (i < source.options.length) {
        if (source.options[i].value == value) {
            source.removeChild(source.options[i]);
            return;
        } else {
            i++;
        }
    }
}

function findOption(source, value) {
    var i = 0;
    while (i < source.options.length) {
        if (source.options[i].value == value) {
            return source.options[i];
        } else {
            i++;
        }
    }
    return null;
}

function copySelectedOptionsInCombo(source, target) {
    var indx = source.selectedIndex;

    if (indx >= 0) {
        for (var i = 0; i < source.options.length; i++) {
            var option = source.options[i];
            if (option.selected) {
               if (findOption(target, option.value) != null) {
                   continue;
               }
               addOption(target, option.innerHTML, option.value);
            }
        }
    }
}


function updateAllCombos(combo, form, name) {
    var els = form.getElementsByTagName('select');
    var value = combo.options[combo.selectedIndex].value;
    for (var i = 1; i < els.length; ++i) {
        if (els[i].disabled) {
            continue;
        }
        if (els[i].name == name) {
            for (var j = 0; j < els[i].options.length; ++j) {
                if (els[i].options[j].value == value) {
                  els[i].selectedIndex = j;
                  break;
                }
            }
        }
    }
}

function disableAllOptionsInCombo(comboId, disabled) {
    var combo = element(comboId);
    for(var i = 0; i < combo.length; ++i) {
        combo.options[i].disabled = disabled;
    }
}

function selectAllOptionsInCombo(comboId, selected) {
    var combo = element(comboId);
    for (var i = 0; i < combo.length; ++i) {
        combo.options[i].selected = selected;
    }
}

function checkAll(el, form, name) {
    var thisCheckBoxes = form.elements;
    for (var i = 1; i < thisCheckBoxes.length; i++) {
        if (thisCheckBoxes[i].disabled) {
            continue;
        }
        if (thisCheckBoxes[i].name == name) {
            thisCheckBoxes[i].checked = el.checked;
            if (thisCheckBoxes[i].onchange) {
                thisCheckBoxes[i].onchange();
            }
        }
    }
}

function submitForm(form) {
    var ready = true;
    if (form.onsubmit) {
        ready = form.onsubmit();
    }

    return ready ? form.submit() : ready;
}

function sort(name) {
    var target = element(name);
    var a = new Array(0);
    for (var i = 0; i < target.options.length; i++) {
        a.push(target.options[i]);
    }
    a.sort(function(x, y) {
        if (x.text.toLowerCase() < y.text.toLowerCase()) return -1;
        if (x.text.toLowerCase() > y.text.toLowerCase()) return 1;
        return 0;
    });
    for (var i = 0; i < target.options.length; i++) {
        target.removeChild(target.options[i]);
    }
    for (var i = 0; i < a.length; i++) {
        target.appendChild(a[i]);
    }
}

/**
 * Removes duplicates in the given array
 */
function unique(name) {
    var target = element(name);
    var tmp = new Array(0);
    var a = new Array(0);
    for (var i = 0; i < target.options.length; i++) {
        a.push(target.options[i]);
    }
    for (var i = 0; i < a.length; i++) {
        if (!contains(tmp, a[i])) {
            tmp.length += 1;
            tmp[tmp.length - 1] = a[i];
        }
    }
    for (var i = 0; i < target.options.length; i++) {
        target.removeChild(target.options[i]);
    }
    for (var i = 0; i < tmp.length; i++) {
        target.appendChild(tmp[i]);
    }
}

/**
 * Returns true if 's' is contained in the array 'a'
 */
function contains(a, e) {
    for (var j = 0; j < a.length; j++) {
        if (a[j] == e) {
            return true;
        }
    }
    return false;
}

/**
 * Filter user input
 * @param filter - a string representing filter applied to the user input
 * Usage: <input type="... onKeyPress='return filter("abcde")' ... /> - allows to user to input "abcde" characters only
 */

function filterInput(event, filter) {
    var keyCode;
    if (window.event) {
        keyCode = window.event.keyCode;
    } else if (event) {
        keyCode = event.which;
    } else {
    // unable to determine key code - allow any input
        return true;
    }

    // If the Key Pressed is a CTRL key like Esc, Enter etc - allow 
    if((keyCode==null) || 
       (keyCode==0) || 
       (keyCode==8) || 
       (keyCode==9) || 
       (keyCode==13) || 
       (keyCode==27)) {
        return true;
    }

    var char = String.fromCharCode(keyCode);

    return (filter.indexOf(char) > -1);
}

function allowDigitsOnly(event) {
    var res = filterInput(event, "0123456789");
    if (!res) {
        alert("This field must contain only digits");
    }
    return res;
}

function allowFloat(event) {
    var res = filterInput(event, "0123456789.");
    if (!res) {
        alert("This field must contain only digits and decimal mark");
    }
    return res;
}


/**
 * Events
 */

function Event(Evt){
  return (Evt ? Evt : (window.event ? window.event : null));
}

function GetEvent(Evt){
  return (Evt ? Evt : (window.event ? window.event : null));
}

// Deprecated
function EventElement(Evt){
  var Evt = Event(Evt);
  if (Evt.srcElement){
    var Element = Evt.srcElement;
  }else{
    var Element = (Evt.target.tagName ? Evt.target : Evt.target.parentNode);
  }
  return Element;
}

function GetEventElement(Evt){
  var Evt = Event(Evt);
  if (Evt.srcElement){
    var Element = Evt.srcElement;
  }else{
    var Element = (Evt.target.tagName ? Evt.target : Evt.target.parentNode);
  }
  return Element;
}

function AddEventListener(Obj, Evt, Action){
  if (Obj.addEventListener){
    Obj.addEventListener(Evt, Action, false);
  }else if (Obj.attachEvent){
    Obj.attachEvent("on" + Evt, Action);
  }else{
    Obj["on" + Evt] = Action;
  }
}

function RemoveEventListener(Obj, Evt, Action){
  if (Obj.removeEventListener){
    Obj.removeEventListener(Evt, Action, false);
  }else if (Obj.detachEvent){
    Obj.detachEvent("on" + Evt, Action);
  }else{
    Obj["on" + Evt] = null;
  }
}

var CursorX = 0;
var CursorY = 0;

function GetCursorPosition(Evt){
  if (window.event){
    CursorX = window.event.clientX + document.documentElement.scrollLeft;
    CursorY = window.event.clientY + document.documentElement.scrollTop;
  }else if (Evt){
    CursorX = Evt.pageX;
    CursorY = Evt.pageY;
  }
}


function StopEvent(Evt){
  if (IE){
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }else{
    Evt.preventDefault();
    Evt.stopPropagation();
  }
  return false;
}

function GetObjectPosition(Obj){
  if (Obj.offsetParent){
      for (var X = 0, Y = 0; Obj.offsetParent; Obj = Obj.offsetParent){
        X += Obj.offsetLeft;
      Y += Obj.offsetTop;
    }
  }else{
    var X = Obj.offsetLeft;
    var Y = Obj.offsetTop;
  }
  return [X, Y];
}

AddEventListener(document, "mousemove", GetCursorPosition);

/**
 * Popup window
 */

function getWindowSize() {
  if (window.innerWidth) {
    var Width = window.innerWidth - 18;
    var Height = window.innerHeight - 18;
  }else{
    var Width = document.body.clientWidth ;
    var Height = document.body.clientHeight;
  }
  return {width: Width, height: Height};
}


function getWindowOffset(){
  if (window.innerWidth){
    var Left = window.pageXOffset;
    var Top = window.pageYOffset;
  }else{
    var Left = document.documentElement.scrollLeft;
    var Top = document.documentElement.scrollTop;
  }
  return {left: Left, top: Top};
}


function Window(){

  var windowElement  = null;
  var windowDelay    = null;
  var windowLeft     = 0;
  var windowTop      = 0;
  var windowDragging = false;
  var docBody        = null;

  this.opener         = window; // Save opener

    /*
    Creates a window and places its body into the document
    windowCaption  - title
    windowBody     - body
    windowSize     - size
    windowPosition - coordinates
    */
  this.makeWindow = function(windowCaption, windowBody, windowSize, windowPosition) {
    if (!W3CDOM){
      return;
    }
    if (windowElement){
      this.hideWindow();
    }
    windowElement = document.createElement("div");
    windowElement.className = "PopupWindow";
    var windowText = "<!--[if lte IE 6.5]><iframe class=\"WindowFrame\"></iframe><![endif]--><table style='border: 1; width: 100%; border-collapse: collapse;'>" +
    "<tbody><tr><td class='WindowCaption' onmousedown='PopupWindow.startDragging(event)'>"+windowCaption+"</td>"+
    "<td style='width: 16px; text-align: right; vertical-align: top;'><img src='images/ico_delete.gif' alt='Close' style='cursor: pointer;' onclick='PopupWindow.hideWindow()' />"+
    "</td></tr></tbody></table><div id='popupBody' class='WindowBody' style='height: " + (windowSize[1] - 24) + "px'>" + windowBody + "</div>";
    windowElement.innerHTML = windowText;
    document.getElementsByTagName("body")[0].appendChild(windowElement);
    windowElement.style.width = windowSize[0]+"px";
    windowElement.style.height = windowSize[1]+"px";
    windowElement = windowElement;
    windowLeft = windowPosition[0];
    windowTop = windowPosition[1];
    windowDelay = setTimeout("PopupWindow.showWindow()", 100);
    docBody = element('popupBody');
  }
    
    /*
    Sets apropriate coordinates and makes it visible
    */
    
  this.showWindow = function(){
    var elementWidth = windowElement.offsetWidth;
    var elementHeight = windowElement.offsetHeight;
    var windowSize = getWindowSize();
    var windowOffset = getWindowOffset();
    if ((windowLeft + elementWidth) > (windowSize.width + windowOffset.left)){
      if (elementWidth > windowLeft){
        elementWidth = windowLeft;
      }
      windowElement.style.left = (windowLeft - elementWidth)+"px";
    }else{
      windowElement.style.left = windowLeft+"px";
    }
    if ((windowTop + elementHeight) > (windowSize.height + windowOffset.top)){
      if (elementHeight > windowTop){
        elementHeight = windowTop;
      }
      windowElement.style.top = (windowTop - elementHeight)+"px";
    }else{
      windowElement.style.top = (windowTop + 20)+"px";
    }
    windowElement.style.visibility = "visible";
  }

  this.open = function() {
      this.showWindow();
  }
    
    /*
    Deletes the window and timeout
    */
    
  this.hideWindow = function(){
    if (windowDelay){
        clearTimeout(windowDelay);
      }
    if (windowElement){
          document.getElementsByTagName("body")[0].removeChild(windowElement);
          windowElement = null;
      }
  }

  this.close = function() {
      this.hideWindow();
  }

  this.startDragging = function(windowEvent){
    if (!windowElement || windowDragging == true){
      return;
    }
    windowDragging = true;
    windowLeft = CursorX - parseInt(windowElement.style.left);
    windowTop = CursorY - parseInt(windowElement.style.top);
    AddEventListener(document, "mousemove", this.doDragging);
    AddEventListener(document, "mouseup", this.stopDragging);
    return StopEvent(windowEvent);
  }

  this.doDragging = function(windowEvent){
    if (!windowElement || windowDragging == false){
      return false;
    }
    windowElement.style.left = (CursorX - windowLeft)+"px";
    windowElement.style.top = (CursorY - windowTop)+"px";
    return StopEvent(windowEvent);
  }

  this.stopDragging = function(){
    if (!windowElement || windowDragging == false){
      return false;
    }
    windowDragging = false;
    RemoveEventListener(document, "mousemove", window.doDragging);
    RemoveEventListener(document, "mouseup", Function);
  }

  this.document = new Object();

  this.document.open = function() {
      docBody.innerHTML = '';
  }

  this.document.close = function() {
  }

  this.document.write = function(text) {
      docBody.innerHTML += text;
  }

  this.document.writeln = function(text) {
      this.write(text + "\n");
  }

}

// Create the window instance
var PopupWindow = new Window();

