// JavaScript Document

/**
 * cross-browser evernt handling for IE5+, NS6+ and Mozilla/Gecko
 * By Scott Andrew
 */ 
function addEvent(elm, evType, fn, useCapture){
  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
  };
}

function submitOnReturn(elm, fn){
   
    addEvent(elm, 'keypress', function(e){
        if(checkEnter(e)) setTimeout(fn, 1);
    }, true);

}

function checkEnter(e){ //e is event object passed from function invocation
    var characterCode //literal character code will be stored in this variable

    if(e && e.which){ //if which property of event object is supported (NN4)
        e = e
        characterCode = e.which //character code is contained in NN4's which property
    }else if (window.event && window.event.keyCode){
        e = event
        characterCode = e.keyCode //character code is contained in IE's keyCode property
    }else{
        return false;
    }

    if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
        return true;
    }else{
        return false;
    }
}




  /** 
   *  Base class containing useful methods
   */     

var AntzBase = {


    /** 
     *  3 dimensional array service
     *  Loop through an array of arrays, looking for matching key=>value pairs
     *  Returns a new array of arrays that match the search request
     */
                        
    findArraysWithThisValue : function(key, value, array){
        var myArray = Array();
        var count = 0;
        //alert('looking for '+key+' = '+value);
        for(var i=0;i<array.length;i++){
        //alert(array[i][key]);
            if(array[i][key]==value){
           // alert('count '+count+': '+array[i]['title']+' '+key+' '+array[i][key]);
                myArray[count]=array[i];
                count++;
            };
        };
        //alert('found: '+myArray.length);
        return myArray;
    },

    disableSubmitButtons : function(){
        var ins = document.getElementsByTagName('input');
        for(var i=0; i<ins.length; i++){
            if(ins[i].type == 'submit'){
                ins[i].disabled = true;
            };
        };
    },





    /**
     * Creates and returns a compatible Ajax Object depending on the browser    
     * 
     */          

    createAjax : function(){
        if (window.XMLHttpRequest) { 
            return new XMLHttpRequest();
        } else if (window.ActiveXObject) { 
            return new ActiveXObject("Microsoft.XMLHTTP");
        };
    },
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    /**
     *  Dom style of adding raw text to a node
     */       
       
    addText : function(node, text, overwrite){ 
    
// for testing 
//alert(text);
    
        if (null == node.canHaveChildren || node.canHaveChildren) {
            if(overwrite === true){
                while(node.childNodes.length > 0){
                     node.removeChild(node.firstChild);
                };
            };
            node.appendChild(document.createTextNode(text));
        } else {
            if(overwrite === true){
                node.text = '';
            };
            node.text += text;
        }; 
    },
    
    
    
    
    
    
    
    
    addTextById : function(id, text, overwrite){
        if(!document.getElementById(id))return;
        AntzBase.addText(document.getElementById(id), text, overwrite);
    },
    
    
    
    
    
    
    
    
    

    
    
    
    
    /** 
     *  Sorts and returns a numeric array. Can sort asc or desc
     *  
     */
                   
    sortArrayByKey : function(array, key, direction){
        if(typeof(direction) === 'undefined'){
            direction = 'asc';
        };
        
        if(direction.toLowerCase() == 'asc'){
            direction = 'asc';
        }else if(direction.toLowerCase() == 'desc'){
            direction = 'desc';
        }else{
            direction = 'asc';
        };
      
        if(direction == 'asc'){
            var count = 0;
            var iterator = 0;
            var myArray = Array();
            while(myArray.length < array.length){
                for(var i=0;i<array.length;i++){
                    if(typeof(array[i][key]) === 'undefined' || array[i][key]==iterator || 
                       typeof(array[i][key]) === 'NaN'){
                        myArray[count] = array[i];
                        count++;
                    };
                };
                iterator++;
            };
            
            return myArray;
        
        
        }else if(direction == 'desc'){
            array = this.sortArrayByKey(array, key, 'asc');
            count = array.length-1;
            var myArray = Array();
            
            for (var i=0;i<array.length;i++){
                myArray[count]=array[i];
                count--;                    
            };
            return myArray;
        
        }else{
            return array;
        };
    },
    
    
    getKeyOfArray : function(arr, matchName, matchVal){
        for(var i=0;i<arr.length;i++){
            if(arr[i][matchName]==matchVal){
            return i;
            }
        };
        return null;
    },
    
    
    
    
    
    
    /**  
     *  Get the current selected KEY of a drop-menu. Pass the element reference
     *  Eg:
     *  var el = document.getElementById('myId');
     *  var key = AntzBase.dom_dropMenuSelectionKey(el);            
     *  alert('you have selected '+$key);
     */
     
    dom_dropMenuSelectionKey : function (el)
    
    {
        if(el.options && el.options[el.selectedIndex])
        return el.options[el.selectedIndex].value;
    },



    dom_removeChildNodes : function(el){
        if(!el || !el.childNodes)return;
        for(var i=0;i<el.childNodes.length;i++){
            //if(el.childNodes[i].childNodes)AntzBase.dom_removeChildNodes(el.childNodes[i]);
            alert(el.childNodes[i]);
            el.removeChild(el.childNodes[i]);
        };
        
    },




    /**  
     *  Get the current selected VALUE of a drop-menu. Attach to the onchange 
     *  event handler, for example
     *  
     */
     
    dom_dropMenuSelectionText : function (id)
    
    {
        if(!document.getElementById(id)){return false;};
        var x=document.getElementById(id);
        return x.options[x.selectedIndex].text;
    },
    
    
    
    
    
    /**
     *  Can use this to disable fields that don't apply in case of a drop menu selection
     *  Can take array or variable values
     *  EG:
     *    
     *    document.getElementById('myDropMenu').onchange=function(){
     *        var sKeys = Array('3', '8');
     *        var dIds = 'Name'; 
     *        AntzBase.dom_toggleDisabledForSelectOnChange('myDropMenu', sKeys, dIds, true);
     *     }
     *    
     *  In the above example, if the key of the selected item == 3 or 8, 
     *  document.getElementById('Name').disabled = disabled;
     *  For any other key, document.getElementById('Name').disabled = null;     
     *  
     */                         
    
    dom_toggleDisabledForSelectOnchange : function (selId, selKeys, disIds, disable)
    {
        if(disable === true || disable === 'disabled'){
            var d1 = 'disabled';
            var d2 = null;
        }else if (disable === false || disable === null){
            var d1 = null;
            var d2 = 'disabled';
        }else{
            var d1 = 'disabled';
            var d2 = null;
        };
        
        var id = AntzBase.dom_dropMenuSelectionKey(selId);
        
        var found = false;
        
        if(typeof(selKeys) == 'Array'){
            for(var i=0;i<selKeys.length;i++){
                if(selKeys[i]===id){
                    found = true;
                };
            };// end for
        }else{
            if(selKeys == id){
                found = true;
            };
        };
    
        if(typeof(disIds) == 'Array'){
            for(var i=0;i<disIds.length;i++){
                if(document.getElementById(disIds[i])){
                     document.getElementById(disIds[i]).disabled = (found) ? d1 : d2;
                };            
                
            };// end for
        }else{
            if(document.getElementById(disIds)){
                 document.getElementById(disIds).disabled = (found) ? d1 : d2;
            };
        };
    },
    
    
    
    dom_toggleVisible : function(el, type){
        if(!el) return ;
        if(!type || (type!='display'&&type!='visibility'))type = 'display';
        if(type=='display'){
            if(el.style.display=='none')el.style.display = 'block';
            else el.style.display = 'none';
        }else{
            if(el.style.visibility == 'hidden') el.style.visibility = 'visible';
            else el.style.visibility = 'hidden';
        };
    },
    
    hide : function(el, type){
        if(!el.style)return;
        if(!type || (type!='display'&&type!='visibility'))type = 'display';
        if(type=='display') el.style.display = 'none';
        else el.style.visibility = 'hidden';    
    },
    
    show : function(el, type){
        if(!el.style)return;
        if(!type || (type!='display'&&type!='visibility'))type = 'display';
        if(type=='display') el.style.display = 'block';
        else el.style.visibility = 'visible';
    },
    
    hideById : function(id, type){
        if(!document.getElementById(id))return;
        var el = document.getElementById(id);
        AntzBase.hide(el);
    },
    
    showById : function(id, type){
        if(!document.getElementById(id))return;
        var el = document.getElementById(id);
        AntzBase.show(el);   
    },
    
    showByIdByArray : function(arr, type){
        if(!type || (type!='display'&&type!='visibility'))type = 'display';
        for(var i=0;i<arr.length;i++){
            AntzBase.showById(arr[i]);
        };        
    },
    
    hideByIdByArray : function(arr, type){
        if(!type || (type!='display'&&type!='visibility'))type = 'display';
        for(var i=0;i<arr.length;i++){
            AntzBase.hideById(arr[i]);
        };
    }
    
  
}




/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var AntzUrl = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
