/*
 *
 * author: Andrew Violette
 */

// Get the key code (ascii value) for a key event
function getKeyCode(event) {
    return (event.charCode) ? event.charCode : (event.which ? event.which : event.keyCode);
}

// Get the character (as String) for a key event
function getKey(event) {
    var w = getKeyCode(event);
    return String.fromCharCode(w);
}

function isCharOfType(t) {
    return function (event) {
        var w = (event.charCode) ? event.charCode : (event.which ? event.which : event.keyCode);
        return t == w;
    }
}

function isNumeric(str) {
    if (str.match(/^\d+$/))
       return true;
    else
       return false;
 }

/**
 * Returns true if the event specified was generated by pressing the return
 * key.
 */

var isReturn = isCharOfType(13);
var isUpArrow = isCharOfType(38);
var isDownArrow = isCharOfType(40);



var log = new function() {

this.debug = function(str) {}
this.warning = function(str) {}
this.info = function(str) {}
this.error = function(str) {}
}





/**
 * Cancels the propagation of an event to the window.
 */

function cancelPropagation(event) {
    if(isReturn(event)) {
        if(navigator.appName == "Microsoft Internet Explorer") {
            event.cancelBubble = true;
            event.returnValue = false;
        } else {
            event.preventDefault();
            event.stopPropagation();
        }
  }

}

String.prototype.rightPad = function(n, c) {
    s = this;
    if (this.length >= n) return this;
    for (i = this.length; i < n; i++) {
        s = s + c;
    }
    return s;
};

function enableControls(enabled, controls) {
    for (var i = 0; i < controls.length; i++) {
        var element = $(controls[i]);
        if(!element) continue;
        element.disabled = enabled ? false : true;
    }
}

function bindPopupLinks() {
    $$("a.popupLink").each(function(node) {
        Event.observe(node, 'click', function(evt) {
            Event.stop(evt);
            var width = 775;
            var height = 650;
            if (node && node.hasClassName && node.hasClassName('popupLinkSmall')) {
                width = 730;
                height = 400;
            }
            else if (node && node.hasClassName && node.hasClassName('popupLinkTiny')) {
                width = 400;
                height = 450;
            }
            else if (node && node.hasClassName && node.hasClassName('popupLinkLarge')) {
            	width = 935;
            	height = 640;
            }
            return popupWindow(node.getAttribute("href"), 'nwaPopup', width, height, 'no', 'yes', 'no', 'no', 'no');
        });
    });
}

function popupWindow(page, pagename, width, height, menubar, scrollbars, toolbar, directories, location) {
    window.open(page, pagename, "width="+width +",height="+ height + ',resizable=yes,menubar=' + menubar + ',status=no,scrollbars=' + scrollbars + ',toolbar=' + toolbar + ',directories=' + directories + ',location='+location+',top=0,left=0');
    return false;
}

var targetCell = null;

// pops up the airport list - the cell parameter is the ID of the field that
// will receive the airport
function popupAirportCode(cell) {
    targetCell = cell;
    var lookupUrl="/help/airportLookup.nw";
    var thisURL=document.location.href;
    if(thisURL!=null && thisURL!='' && thisURL.indexOf('https') == 0){
           lookupUrl = "/secure/help/airportLookup.nw";
     }
    return popupWindow(lookupUrl, 'airportcode', 730, 725, 'no', 'yes', 'no', 'no', 'no');
}

// called by the airport popup to populate the airport code in the field.
function setAirport(ap) {
    if(targetCell == null) {
        return;
    }
    $(targetCell).value = ap;
    fireEvent($(targetCell),"blur");
    targetCell = null;
}

function checkAll(form) {
    for (var i=0;i<form.elements.length;i++) {
        var e = form.elements[i];
        if (e.type=='checkbox') {
            e.checked = true;
        }
    }
}

function toggleCheckBox(toggleValue, checkBoxList){
    checkBoxList.each(function(checkBox){
        if($(checkBox)){
            $(checkBox).checked = toggleValue;
        }
    });
}

// An event handler for input field that takes only numbers. Uages: either write inline onkeypress event handler or
// bind the event handler on page load.
// Note: function keys still work.
function handleNumericInput(evt) {
    var w = getKeyCode(evt);
    if (evt.keyCode && !/MSIE/.test(navigator.userAgent) && (w == Event.KEY_BACKSPACE || w == Event.KEY_LEFT || w == Event.KEY_RIGHT || w == Event.KEY_DELETE || w == Event.KEY_TAB)) {
        return true;
    }
    else {
        var s = String.fromCharCode(w);
        if (! (isNumeric(s))) {
            Event.stop(evt);
            return false;
        }

        return true;
    }
}
// An event handler for input field that takes phone numbers. A phone number is composed of numbers and "-".
// Uages: either write inline onkeypress event handler or bind the event handler on page load
function handlePhoneInput(evt) {
    var w = getKeyCode(evt);
    if (evt.keyCode && !/MSIE/.test(navigator.userAgent) && (w == Event.KEY_BACKSPACE || w == Event.KEY_LEFT || w == Event.KEY_RIGHT || w == Event.KEY_DELETE || w == Event.KEY_TAB)) {
        return true;
    }
    else {
    	//pass through for non IE and firefox browsers
    	if(!(/MSIE|Gecko/.test(navigator.userAgent))){
    		return true;
    	}
    	//for '-'
    	var dashKey = getDashKeyCode();
    	
        var s = String.fromCharCode(w);
        //IE returns ascii codes under Prototype 1.6, so for versions below that, we need to
        //check the previous non-ascii codes.
        if (isNumeric(s) || s == '-' || s == ' ') {
            return true;
        }
        Event.stop(evt);
        return false;
    }
}

// An event handler for input field that does not take numbers. Uages: either write inline onkeypress event handler or
// bind the event handler on page load
function handleNonNumericInput(evt) {
    var s = getKey(evt);
    if (isNumeric(s)) {
        Event.stop(evt);
        return false;
    }

    return true;
 }
 
 function handleEmailInput(evt){
 	var s = getKeyCode(evt);
 	if (isInvalidEmailCharacter(s)) {
 		Event.stop(evt);
        return false;
 	}
 	return true;
 }

/**
 * Returns appropriate key code for '-' based on browser
 */
function getDashKeyCode(evt){
	var dashKey = 45;
	if (/MSIE/.test(navigator.userAgent)){
    		dashKey = 189;
    }
    return dashKey;	
    	
}

/**
 * Returns appropriate key code for '/' based on browser
 */
function getSlashKeyCode(){
	var slashKey = 47;
	if (/MSIE/.test(navigator.userAgent)){
    		slashKey = 191;
    }
    return slashKey;	
    	
}

function isInvalidEmailCharacter(s){
	
	//59 - SemiColon
	//44 - Comma
	//32 - Space
	//40 - Opening Parenthesis
	//41 - Closing Parenthesis
	//58 - Colon
	//60 - Greater than
	//62 - Lesser than
	//91 - Square Opening bracket
	//93 - Square Closing bracket
	if (s == 59 || s == 44 || s == 32 || s == 40 || s == 41 || s == 58 || s == 60 || s == 62 || s == 91 || s == 93) { 		
        return true;
 	}
}

 
/**
 * Check for keypress from number pad on IE browser. This assumes
 * that the NUM LOCK is on.
 */
function isIENumberPadKey(evt, includeSlash, includeDash){

	var w = getKeyCode(evt);
	if(/MSIE/.test(navigator.userAgent)){
    		if( w >= 96 && w<=105 ){
    			return true;
    		}
    		if(includeDash && w == 109){
    			return true;
    		}
    		if(includeSlash && w == 111){
    			return true;
    		}
    }
    return false;
} 
 
// An event handler for input field that takes dates. Uages: either write inline onkeypress event handler or
// bind the event handler on page load. 
// Note: function keys still work.
function handleDateInput(evt) {
    var w = getKeyCode(evt);
    if (evt.keyCode && (w == Event.KEY_BACKSPACE || w == Event.KEY_LEFT || w == Event.KEY_RIGHT || w == Event.KEY_DELETE || w == Event.KEY_TAB)) {
        return true;
    }
    else {
    	
    	//pass through for non IE and firefox browsers
    	if(!(/MSIE|Gecko/.test(navigator.userAgent))){
    		return true;
    	}
    	var dashKey = getDashKeyCode();
    	var slashKey = getSlashKeyCode();
    	
    	var s = String.fromCharCode(w);
    	//IE returns ascii codes under Prototype 1.6, so for versions below that, we need to
        //check the previous non-ascii codes.
    	if (! (isNumeric(s) || s == '/' || s == '-'  || (/1\.5/.test(Prototype.Version)  && 
    		((!evt.shiftKey && (w == dashKey || w == slashKey)) || isIENumberPadKey(evt, true, true))))) {
            Event.stop(evt);
            return false;
        }

        return true;
    }
}


// An event handler for input field that takes dates. Uages: either write inline onkeypress event handler or
// bind the event handler on page load. 
// Note: function keys still work.
function handleZipCodeInput(evt) {
    handlePhoneInput(evt);
}

/**
 * Shows the extension text box when the phone location type work is selected
 * @param event
 * @param type
 */
function showExtension(event, type) {
      if ($(type+'PhoneType') && $(type+'PhoneType').value == 2){
        Element.show(type+'ExtDiv');
    } else if ($(type+'PhoneType')){
          $(type+'ExtDiv').value = "";
          Element.hide(type+'ExtDiv');
    }
}
/**
* Fires an event for the widget mentioned
* @param element the objcet of widget
* @param event the event to be fired. Event name as string. 
*/
function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}
