/*
    Library functions for moca CMS
    Wed Nov 12 14:20:39 2008
    brendon@actrix.co.nz

    $Id$

*/

function $() {
/* $('a');.
   $('a','b',obj,obj2,'c','d'); */

    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
            element = document.getElementById(element);
        if (arguments.length == 1)
            return element;
        elements.push(element);
    }
    return elements;
}

function mk(typ){return document.createElement(typ);}
function mktxt(txt){return document.createTextNode(txt);}

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,"");
}

String.prototype.unformatNumber = function() {
   return this.replace(/([^0-9\.\-])/g,'')*1;
};

String.prototype.formatNumber = function(prefix) {

   prefix = prefix || '';
   var a = this.split('.');
   var l = a[0];
   var r = a.length > 1 ? '.' + a[1] : '';
   var regx = /(\d+)(\d{3})/;
   while (regx.test(l)) {
      l = l.replace(regx, '$1' + ',' + '$2');
   }
   return prefix + l + r;
};

String.prototype.entify = function () {
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};

String.prototype.stripTags = function () {
   return this.replace(/<([^>]+)>/g,'');
}
Object.prototype.isArray = function() {
   return this.constructor == Array;
}

String.prototype.quote = function () {
/* Returns string wrapped in quotes with all quote and backslash\
   characters preceded with backslash */

    var c, i, l = this.length, o = '"';
    for (i = 0; i < l; i += 1) {
        c = this.charAt(i);
        if (c >= ' ') {
            if (c === '\\' || c === '"') {
                o += '\\';
            }
            o += c;
        } else {
            switch (c) {
            case '\b':
                o += '\\b';
                break;
            case '\f':
                o += '\\f';
                break;
            case '\n':
                o += '\\n';
                break;
            case '\r':
                o += '\\r';
                break;
            case '\t':
                o += '\\t';
                break;
            default:
                c = c.charCodeAt();
                o += '\\u00' + Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }
        }
    }
    return o + '"';
};

Array.prototype.numericSort = function() {
   return this.sort( function (a,b) { return a-b; } );
}

Array.prototype.map = function(f) {
  var a = [];
  for (i=0; i<this.length; i++) {
    a.push(f(this[i]));
  }
  return a;
}

Array.prototype.exists = function (x) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == x) return true;
    }
    return false;
}

Array.prototype.remove = function(x) {

    if (idx = this.indexOf(x)) {
        return this.splice(this.indexOf(x),1);
    }
}

// IE has no indexOf for arrays?
    if(!Array.indexOf){
        Array.prototype.indexOf = function(obj){
            for(var i=0; i<this.length; i++){
                if(this[i]==obj){
                    return i;
                }
            }
            return -1;
        }
    }

Array.prototype.swap=function(a, b) {
    var tmp=this[a];
    this[a]=this[b];
    this[b]=tmp;
}


function addEvent(elm, evType, fn, useCapture) {

// addEvent(window,'load',func1,false);

    if (elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    }
    else if (elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    }
    else {
        elm['on' + evType] = fn;
    }
}

Object.prototype.getElementsByClass = function (searchClass, tag) {
   var returnArray = [];
   tag = tag || '*';
   var els = this.getElementsByTagName(tag);
   var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
   for (var i = 0; i < els.length; i++) {
      if ( pattern.test(els[i].className) ) {
         returnArray.push(els[i]);
      }
   }
   return returnArray;
}

  function isIE(){

	return navigator.userAgent.indexOf('MSIE')!=-1;
  }


// Old style:
function getElementsByClass(searchClass,node,tag) {
    var classElements = new Array();
    if ( node == null )
        node = document;
    if ( tag == null )
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
    for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

function insertAfter(parent, node, referenceNode) {
    parent.insertBefore(node, referenceNode.nextSibling);
}
function getCookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ';', len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
    var today = new Date();
    today.setTime( today.getTime() );
    if ( expires ) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = name+'='+escape( value ) +
        ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
        ( ( path ) ? ';path=' + path : '' ) +
        ( ( domain ) ? ';domain=' + domain : '' ) +
        ( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
    if ( getCookie( name ) ) document.cookie = name + '=' +
            ( ( path ) ? ';path=' + path : '') +
            ( ( domain ) ? ';domain=' + domain : '' ) +
            ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
// MOCA

    function hasCheck(nam) {

        var chk = document.getElementsByName(nam + '[]');
        for (var i = 0; i < chk.length; i++){
            if (chk[i].checked) {return true;}
        }
        return false;
    }

    function hasSelect(nam) {

        var chk = document.getElementsByName(nam + '[]');
        var idx = chk[0].selectedIndex;
        if (idx > -1) {return true;}
        return false;
    }

function getNodeValue(tree, el){

	// Useful for node trees returned by ajax object below:
    return tree.getElementsByTagName(el)[0].firstChild.nodeValue;
}


function ajaxObject(url, callbackFunction) {
  var that=this;
  this.updating = false;
  this.abort = function() {
    if (that.updating) {
      that.updating=false;
      that.AJAX.abort();
      that.AJAX=null;
    }
  }
  this.update = function(passData,postMethod) {
    if (that.updating) { return false; }
    that.AJAX = null;
    if (window.XMLHttpRequest) {
      that.AJAX=new XMLHttpRequest();
    } else {
      that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (that.AJAX==null) {
      return false;
    } else {
      that.AJAX.onreadystatechange = function() {
        if (that.AJAX.readyState==4) {
          that.updating=false;
          that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);
          that.AJAX=null;
        }
      }
      that.updating = new Date();
      if (/post/i.test(postMethod)) {
        var uri=urlCall+'?'+that.updating.getTime();
        that.AJAX.open("POST", uri, true);
        that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        that.AJAX.setRequestHeader("Content-Length", passData.length);
        that.AJAX.send(passData);
      } else {
        var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime());
        that.AJAX.open("GET", uri, true);
        that.AJAX.send(null);
      }
      return true;
    }
  }
  var urlCall = url;
  this.callback = callbackFunction || function () { };
}
