// Javascript for masked input controls
// ------
//
// CHANGELOG
// - initial, Leonard Slingerland
// - 2006, 09, 29, Leonard Slingerland: added typeAhead support for comboboxes
//

//browser detection
var strUserAgent = navigator.userAgent.toLowerCase(); 
var isIE = strUserAgent.indexOf("msie") > -1; 
var isNS6 = strUserAgent.indexOf("netscape6") > -1; 
var isNS4 = !isIE && !isNS6  && parseFloat(navigator.appVersion) < 5; 
			
//regular expressions
var reValidChars = /\d/;
var reValidString = /^\d*$/;
var reKeyboardChars = /[\x00\x03\x08\x0D\x16\x18\x1A]/;
var reClipboardChars = /[cvxz]/i;

//mask functions
function maskKeyPress(objEvent){
	var iKeyCode, strKey, objInput;  
	
	if(isIE){
	    iKeyCode = objEvent.keyCode;
		objInput = objEvent.srcElement;
	} else {
	    iKeyCode = objEvent.which;
		objInput = objEvent.target;
	}
	
	strKey = String.fromCharCode(iKeyCode);
	
	if(isValid(objInput.value)){
		objInput.validValue = objInput.value;
		if(!reValidChars.test(strKey) && !reKeyboardChars.test(strKey) && !checkClipboardCode(objEvent, strKey)){
			return false;
		}
	} else {
		objInput.value = objInput.validValue;
		return false;
	}
}

function checkClipboardCode(objEvent, strKey){
  	if(isNS6)
    	return objEvent.ctrlKey && reClipboardChars.test(strKey);
  	else
    	return false;
}

function isValid(strValue) {
	return reValidString.test(strValue) || strValue.length == 0;			
}

function maskChange(objEvent){
  	var objInput;

  	if(isIE){
    	objInput = objEvent.srcElement; 
  	} else {
    	objInput = objEvent.target;
  	}
 
  	if(!isValid(objInput.value)){
		objInput.value = objInput.validValue || "";
		objInput.focus();
    	objInput.select(); 
  	} else {
		objInput.validValue = objInput.value;
	}
}

function maskPaste(objEvent){
	var strPasteData = window.clipboardData.getData("Text");
	var objInput = objEvent.srcElement;
	
	if(!isValid(strPasteData)){
		objInput.focus();
		return false;
	}
}		

// DHTML Stuff for showing and hiding objects
// ------
//
function showhide(id){
  if (document.getElementById) {
    obj = document.getElementById(id);
    if (obj.style.display == 'none') {
      obj.style.display = '';
    } else {
      obj.style.display = 'none';
    }
  }
}

function show(id){
    if (document.getElementById) {
        obj = document.getElementById(id);
        obj.style.display = '';
    }
}

function hide(id){
    if (document.getElementById) {
        obj = document.getElementById(id);
        obj.style.display = 'none';
    }
}

function validateShowToelichting(tekst){
}

// Allow typeAhead for comboboxes
// ------
//
// global storage object for type-ahead info, including reset() method
var typeAheadInfo = {last:0, 
                     accumString:"", 
                     delay:2000, // default 500ms
                     timeout:null, 
                     reset:function() {this.last=0; this.accumString=""}
                    };

// function invoked by select element's onkeydown event handler
function typeAhead() {
   // limit processing to IE event model supporter; don't trap Ctrl+keys and TABs
   if (window.event && !window.event.ctrlKey && !(9==event.keyCode)) {
      // timer for current event
      var now = new Date();
      // process for an empty accumString or an event within [delay] ms of last
      if (typeAheadInfo.accumString == "" || now - typeAheadInfo.last < typeAheadInfo.delay) {
         // make shortcut event object reference
         var evt = window.event;
         // get reference to the select element
         var selectElem = evt.srcElement;
         // get typed character ASCII value
         var charCode = evt.keyCode;
         // get the actual character, converted to uppercase
         var newChar =  String.fromCharCode(charCode).toUpperCase();
         // append new character to accumString storage
         typeAheadInfo.accumString += newChar;
         // grab all select element option objects as an array
         var selectOptions = selectElem.options;
         // prepare local variables for use inside loop
         var txt, nearest;
         // look through all options for a match starting with accumString
         for (var i = 0; i < selectOptions.length; i++) {
            // convert each item's text to uppercase to facilitate comparison
            // (use value property if you want match to be for hidden option value)
            txt = selectOptions[i].text.toUpperCase();
            // record nearest lowest index, if applicable
            nearest = (typeAheadInfo.accumString > 
                       txt.substr(0, typeAheadInfo.accumString.length)) ? i : nearest;
            // process if accumString is at start of option text
            if (txt.indexOf(typeAheadInfo.accumString) == 0) {
               // stop any previous timeout timer
               clearTimeout(typeAheadInfo.timeout);
               // store current event's time in object 
               typeAheadInfo.last = now;
               // reset typeAhead properties in [delay] ms unless cleared beforehand
               typeAheadInfo.timeout = setTimeout("typeAheadInfo.reset()", typeAheadInfo.delay);
               // visibly select the matching item
               selectElem.selectedIndex = i;
               // prevent default event actions and propagation
               evt.cancelBubble = true;
               evt.returnValue = false;
               // exit function
               return false;   
            }            
         }
         // if a next lowest match exists, select it
         if (nearest != null) {
            selectElem.selectedIndex = nearest;
         }
      } else {
         // not a desired event, so clear timeout
         clearTimeout(typeAheadInfo.timeout);
      }
      // reset global object
      typeAheadInfo.reset();
   }
   return true;
}

// function to add the onkeydown-event to all select elements
function addTypeAhead(){
    x = document.getElementsByTagName("select");
    for(var i=0; i<x.length; i++){
        x[i].onkeydown = typeAhead;
    }
}

// Jaargangen.php related stuff
// ------
//
function addNewSprekersCombo(){
    var iUniqueNo = frmJaargangen.elements.length;
    
    var theNewFragment = document.createDocumentFragment();
    
    // span
    var theSpan = document.createElement('span');
    theSpan.id = 'spreker' + iUniqueNo;
    
    // combobox
    var theNewCombo = document.createElement('select');
    theNewCombo.name = 'spreker' + iUniqueNo;

    var arLen=sprekers.length;
    for(var i=0,len=arLen;i<len;i++){
        theNewCombo.options[theNewCombo.options.length] = new Option(sprekers[i][1],sprekers[i][0]);
    }
    
    // delete-link
    var theDeleteLink = document.createElement('span');
    theDeleteLink.innerHTML = '&nbsp;&nbsp;<a href=\"javascript:deleteCombo(\'spreker' + iUniqueNo + '\');\">verwijderen</a>';

    // break
    var theBreak = document.createElement('br');
    
    // add elements to theNewFragment
    theNewFragment.appendChild(theSpan);
    theSpan.appendChild(theNewCombo);
    theSpan.appendChild(theDeleteLink);
    theSpan.appendChild(theBreak);
    
    x = document.getElementById('DivPlaceholderModifySprekersPerMannendag');
    x.parentNode.insertBefore(theNewFragment,document.getElementById('DivPlaceholderModifySprekersPerMannendag'));
}

function deleteCombo(id){
    if(document.getElementById){
        var obj = document.getElementById(id);
        obj.parentNode.removeChild(obj);
    }
}
