ie = (document.all && !window.opera);
isSafari = navigator.userAgent.indexOf('Safari') != -1;
isFireFox = navigator.userAgent.indexOf('Firefox') != -1;
ie6 = ie && navigator.userAgent.indexOf('MSIE 6') != -1;
isMac = navigator.userAgent.indexOf('Mac OS X') != -1;
isMacFireFox = isFireFox && isMac;

var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

/** String Trim function **/
String.prototype.trim=function(){
    return this.replace(/^\s*|\s*$/g,'');
}

String.prototype.ltrim=function(){
    return this.replace(/^\s*/g,'');
}

String.prototype.rtrim=function(){
    return this.replace(/\s*$/g,'');
}
function hide(el) {
  el.style.display = "none";
}

function show(el) {
    el.style.display = "";
}

// Shows the first element and hides the second
// This can be done better!
function show_hide(object1, object2) {
  a = $( object1 );
  b = $( object2 );
  show(a);
  hide(b);
  //a.style.display = "";
  //b.style.display = "none";
}

uidCount = 0;
function createUID(name) {
    return (name == undefined ? "" : name + "_") +
        (new Date()).getTime() + "_" +
        (uidCount++) + "_" + Math.ceil(Math.random()*100000);
}

function replaceAll(str, from, to) {
    var idx = str.indexOf(from);

    while (idx > -1) {
        str = str.replace(from, to);
        idx = str.indexOf(from);
    }

    return str;
}

function add_option(select, option) {
  try {
    select.add(option, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    select.add(option); // IE only
  }
}

function findNextZIndex(obj) {
    var zIndex = obj.style.zIndex;
    while (obj.offsetParent) {
        if (obj.style.zIndex > zIndex) {
            zIndex = obj.style.zIndex;
        }
        obj = obj.offsetParent;
    }
    // add a little buffer...can't hurt
    return zIndex + 5;
}

function activecontentHider(el, modal) {
    if (modal) {
        var div = document.createElement("div");
        div.className = 'hider';
        div.style.position = ie6 ? "absolute" : "fixed";
        div.style.visibility = "hidden";
        div.style.opacity = 0.9;
        div.style.filter = 'Alpha(opacity=90)';
        div.style.width = el.offsetWidth + "px";
        div.style.height = el.offsetHeight + "px";
        div.style.zIndex = el.style.zIndex - 1;
        el.modal = div;
        document.body.appendChild(div);
    }

    if (!isFireFox) {
        var ifrm = document.createElement("IFRAME");
        ifrm.setAttribute("src", "#");
        ifrm.setAttribute("scroll", "no");
        ifrm.setAttribute("frameborder", "0");
        ifrm.style.position = (ie6 || isMacFireFox) ? "absolute" : "fixed";
        ifrm.style.visibility = "hidden";
        // better for IE5.5 to use old filter...
        ifrm.style.filter = 'Alpha(opacity=0)';
        ifrm.style.width = el.offsetWidth + "px";
        ifrm.style.height = el.offsetHeight + "px";
        ifrm.style.zIndex = el.style.zIndex - 2;
        ifrm.src = "about:blank";
        el.ifrm = ifrm;
        document.body.appendChild(ifrm);
    }
}

function getClientSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth, myHeight];
}

function getScreenSize() {
    var screenW = 1024, screenH = 768;
    if (parseInt(navigator.appVersion)>3) {
        screenW = screen.width;
        screenH = screen.height;
    } else if (navigator.appName == "Netscape" 
               && parseInt(navigator.appVersion)==3
               && navigator.javaEnabled()) {
        var jToolkit = java.awt.Toolkit.getDefaultToolkit();
        var jScreenSize = jToolkit.getScreenSize();
        screenW = jScreenSize.width;
        screenH = jScreenSize.height;
    }
    return [screenW, screenH];
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [scrOfX, scrOfY];
}

function center(id, ref) {
    var el = document.getElementById(id);
    if (el) {
        if (ref) {
            rtop = findPosY(ref);
            rleft = findPosX(ref);

            top = rtop + ((ref.offsetHeight - el.offsetHeight) / 2)
            left = rleft + ((ref.offsetWidth - el.offsetWidth) / 2)
        } else {
            clientSize = getClientSize();
            if (el.style.position != 'fixed') {
                scrollInfo = getScrollXY();
            } else {
                scrollInfo = new Array(0, 0);
            }
            
            var top = scrollInfo[1] + ((clientSize[1] - el.offsetHeight) / 2);
            if (top < 0) top = 0;
            var left = scrollInfo[0] + ((clientSize[0] - el.offsetWidth) / 2);
            if (left < 0) left = 0;
        }

        el.style.top = top + "px";
        el.style.left = left + "px";
    }
}

function toggle(id,el,text_o,text_c) {
	var e = document.getElementById(id);
	if(e.style.display == 'block') {
		if(el) {
			el.innerHTML = text_o;
		}
		e.style.display = 'none';
	}
	else {
		if(el) {
			el.innerHTML = text_c;
		}
		e.style.display = 'block';
	}
}

function toggle_display(object) {
  if (object.style.display == "none") {
    object.style.display = "";
  } else {
    object.style.display = "none";
  }
}

// Toggles the display of two elements
function toggle_display_pair(a,b) {
  toggle_display($(a));
  toggle_display($(b));
}


function createFormInput(type, name, value ) {
    var input = null;
    if (ie) {
        input = document.createElement("<INPUT name='"+ name + "'>");
    } else {
        input = document.createElement('INPUT');
        input.name = name;
    }
    input.type = type;
    if (value) {
        input.value = value;
    }
    return input;
}

function createButton(className) {
    var link = document.createElement('A');
    link.className = className;
    link.href = "#";
    link.innerHTML = "&raquo;";
    return link;
}

function createCancelButton(popup, button_class) {
    if( !button_class ){
        button_class = "btn_cancel";
    }
    var link = createButton(button_class);
    link.onclick = function() {
        popup.close();
        return false;
    }
    return link;
}


var dragObj = new Object();

function dragStart(event, id, callback) {

  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id) {
    dragObj.elNode = document.getElementById(id);
  } else {
      if (ie) {
        dragObj.elNode = window.event.srcElement;
      } else {
        dragObj.elNode = event.target;
      }

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  dragObj.callback = callback;

  // Get cursor position with respect to the page.
  if (dragObj.elNode.style.position == "fixed") {
      if (ie) {
          x = window.event.clientX;
          y = window.event.clientY;
      } else {
          x = event.clientX;
          y = event.clientY;
      }
  } else {
      if (ie) {
          x = window.event.clientX + document.documentElement.scrollLeft
              + document.body.scrollLeft;
          y = window.event.clientY + document.documentElement.scrollTop
              + document.body.scrollTop;
      } else {
          x = event.clientX + window.scrollX;
          y = event.clientY + window.scrollY;
      }
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Capture mousemove and mouseup events on the page.

  if (ie) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  } else {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.
  if (dragObj.elNode.style.position == "fixed") {
      if (ie) {
          x = window.event.clientX;
          y = window.event.clientY;
      } else {
          x = event.clientX;
          y = event.clientY;
      }
  } else {
      if (ie) {
          x = window.event.clientX + document.documentElement.scrollLeft
              + document.body.scrollLeft;
          y = window.event.clientY + document.documentElement.scrollTop
              + document.body.scrollTop;
      } else {
          x = event.clientX + window.scrollX;
          y = event.clientY + window.scrollY;
      }
  }

  // Move drag element by the same amount the cursor has moved.

  if (dragObj.callback) {
      posx = findPosX(dragObj.elNode);
      posy = findPosY(dragObj.elNode);
      
      if ((x > posx && x < posx+dragObj.elNode.offsetWidth) &&
          (y > posy && y < posy+dragObj.elNode.offsetHeight)) {
          dragObj.callback(x - dragObj.cursorStartX, y - dragObj.cursorStartY);
      }
      dragObj.cursorStartX = x;
      dragObj.cursorStartY = y;
  } else {
      move(dragObj.elNode, (dragObj.elStartLeft + x - dragObj.cursorStartX), (dragObj.elStartTop  + y - dragObj.cursorStartY));
  }

  if (ie) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  } else {
    event.preventDefault();
  }
}

function dragStop(event) {
  if (ie) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  } else {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}


function move(element, x, y) {
    element.style.left = x + 'px';
    element.style.top = y + 'px';
    
    if (element.ifrm) {
        element.ifrm.style.left = x + 'px';
        element.ifrm.style.top = y + 'px';
    }
}


function setAlerts(message) {
    document.getElementById('dynamic_alerts').innerHTML = message;
}

function handleResponse(data) {
    if (data['message']) {
        setAlerts(data['message']);
    }
}


function trimAll(sString) {
    while (sString.substring(0,1) == ' ') {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ') {
        sString = sString.substring(0,sString.length-1);
    }
    return sString;
}

function blockUser(user_id, action) {
    var answer = confirm("Are you sure you want to " + action + " this user?");
    if (answer) {
        var form = document.createElement('FORM');
        form.method = 'POST';

        form.appendChild(createFormInput('hidden', '_submit_check', 'block_user'));
        form.appendChild(createFormInput('hidden', 'user_id', user_id));
        form.appendChild(createFormInput('hidden', 'block_action', action));

        document.body.appendChild(form);

        form.submit();
    }
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }

    return curtop;
}

function findMouseX(event) {
    if (ie) event = window.event;
    if (event.pageX || event.pageY) return event.pageX;
    else if (event.clientX || event.clientY) return event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    return -1;
}

function findMouseY(event) {
    if (ie) event = window.event;
    if (event.pageX || event.pageY) return event.pageY;
    else if (event.clientX || event.clientY) return event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    return -1;
}

// Useful DOM stuff

function childWithID(obj, id) {
    var nodes = obj.childNodes;
    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        if (node.id == id) {
            return node;
        } else {
            var subNode = childWithID(node, id);
            if (subNode) return subNode;
        }
    }
    return null;
}

function parentWithID(obj, id) {
    if (obj.parentNode) {
        if (obj.parentNode.id == id) {
            return obj.parentNode;
        } else {
            return parentWithID(obj.parentNode, id);
        }
    } else {
        return null;
    }
}

  function toggle_tab(baseId, tabNum) {
    i=0;
    while (true) {
      var el = $(baseId + "_tab_" + i);
      if (el) el.className = remove_class(el.className, "selected");
      else break;
      i++;
    }

    i=0;
    while (true) {
      var el = $(baseId + "_content_" + i);
      if (el) el.style.display = "none";
      else break;
      i++;
    }
    var el = $(baseId + "_tab_" + tabNum);
    if (el) el.className = add_class(el.className, "selected");
    var el = $(baseId + "_content_" + tabNum);
    if (el) {
        el.style.display = "";
        if (el.show) el.show();
        fireImageOnload(el.id, function(image) {image.style.width="0px"; image.style.visibility="hidden";});
    }
  }

  function add_class(className, name) {
      if (className && className.indexOf(name) == -1) {
          className += ' ' + name;
      } else {
          className = name;
      }
      return className;
  }

  function remove_class(className, name) {
      if (className) {
          var index = className.indexOf(name);
          if (index != -1) {
              className = className.substr(0, index) + className.substr(index+name.length);
          }
      }
      return className;
  }

  function toggle_subnav(baseId, tabNum, width) {
    i=0;

    while (true) {
      var el = document.getElementById(baseId + "_tab_" + i);
      if (el) {
          el.className = remove_class(el.className, 'open');
          el = document.getElementById(baseId + "_content_" + i);
          if (el) el.style.display = "none";
      } else break;
      i++;
    }

    var tab = document.getElementById(baseId + "_tab_" + tabNum);
    var content = document.getElementById(baseId + "_content_" + tabNum);
    if (content) {
        tab.className = add_class(tab.className, 'open');
        content.style.left = (findPosX(tab) - 1) + 'px';
        content.style.top = (findPosY(tab) + tab.offsetHeight - 3) + 'px';
        content.style.zIndex = findNextZIndex(tab);
        content.style.width = ((width == undefined || width == null) ? (tab.offsetWidth) : width) + 'px';
        content.style.display = "block";
    }
  }

  function array_contains(array, value) {
      if (array == null || array == undefined || array.length == 0) return false;

      for (var i=0; i<array.length; i++) {
          if (array[i] == value) return true;
      }
      return false;
  }

  function array_remove(array, value) {
      if (array == null || array == undefined || array.length == 0) return;

      for (var i=0; i<array.length; i++) {
          if (array[i] == value) array.splice(i, 1);
      }
  }

  var menu_watch = new Array();

  function startMenuWatch(baseId) {
      if (menu_watch.length == 0) {
          menu_watch.push(baseId);
          if (ie) {
              document.attachEvent("onmousemove", checkMenuWatch);
          } else {
              document.addEventListener("mousemove", checkMenuWatch, false);
          }
      } else if (!array_contains(menu_watch, baseId)) {
          menu_watch.push(baseId);
      }
  }

  function checkMenuWatch(event) {
      if (ie) {
          x = window.event.clientX + document.documentElement.scrollLeft
              + document.body.scrollLeft;
          y = window.event.clientY + document.documentElement.scrollTop
              + document.body.scrollTop;
      } else {
          x = event.clientX + window.scrollX;
          y = event.clientY + window.scrollY;
      }

      // find the current open tab
      var tmp_menu_watch = menu_watch.slice(0);
      for (var j=0; j<tmp_menu_watch.length; j++) {
          var i=0;
          while (true) {
              var tab = document.getElementById(tmp_menu_watch[j] + '_tab_' + i);
              if (!tab) {
                  stopMenuWatch();
                  break;
              }
              if (tab.className.indexOf('open') != -1) {
                  var content = document.getElementById(tmp_menu_watch[j] + '_content_' + i);
                  if (!is_in_area(x, y, tab.id) && (content == undefined || !is_in_area(x, y, content.id))) {
                      tab.className = remove_class(tab.className, 'open');
                      if (content) content.style.display = 'none';
                      array_remove(menu_watch, tmp_menu_watch[j]);
                      stopMenuWatch();
                      break;
                  }
              }
              i++;
          }
      }
  }

  function stopMenuWatch() {
      if (menu_watch.length ==0) {
          if (ie) {
              document.detachEvent("onmousemove", checkMenuWatch);
          } else {
              document.removeEventListener("mousemove", checkMenuWatch, false);
          }
      }
  }

function is_in_area(x, y, id) {
    var node = document.getElementById(id);

    if (node) {
        posx = findPosX(node);
        posy = findPosY(node);

        if ((x >= posx && x <= (0+posx+node.offsetWidth)) &&
            (y >= posy && y <= (0+posy+node.offsetHeight))) {
            return true;
        }
    }
    return false;
}

function createFormOption(text, value, selectedValue) {
    var option = new Option();
    option.text = text;
    option.value = value;
    option.selected = (value == selectedValue);
    return option;
}

function fireImageOnload(id, callback) {
    el = document.getElementById(id);
    if (el) {
        var images = el.getElementsByTagName('IMG');
        for (i=0; i<images.length; i++) {
            if (images[i].onload) {
                if (callback) callback(images[i]);
                images[i].onload();
            }
        }
    }
}

function truncate(value, limit) {
  if (value.length > limit) {
    return value.substring(0, limit-2) + '...';
  } else {
    return value;
  }
}

function getFormField(form, field) {
    for (var i = 0; i < form.elements.length; i++) {
        element = form.elements[i];
        if (element.name == field) {
            if (element.type == "checkbox" || element.type == "radio") {
                if (element.checked) {                
                    return element;
                }
            } else {
                return element;
            }
        }
    }
    return null;
}
