/*
Name: sanibel.js
Author: David R. Mullinax
Description: JavaScript library
Creation Date: 2008
Modifications:
November 07, 2009: 
Modified error messages in validate_array()
Fixed an trim() error in validate_array().
version 1.02
 */

// Missing getElementById.
if(document.all && !document.getElementById) {
    document.getElementById = function(id) {return document.all[id];}
}

// Remove trailing and leading whitespace 
if(!String.trim){String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");}}

(function(){
	// The primary namespace object.
	if(!window['sanibel']) {window['sanibel'] = {};}
	
	// Checks to see if the current browser is compatible with the entire library
	function isCompatible(other) {
	    // Use capability detection to check requirements
	    if( other===false 
	        || !Array.prototype.push
	        || !Object.hasOwnProperty
	        || !document.createElement
	        || !document.getElementsByTagName
	        ) {
	        alert('TR- if you see this message isCompatible is failing incorrectly.');
	        return false;
	    }
	    return true;
	}
	window['sanibel']['isCompatible'] = isCompatible;
	
	// document.getElementById(); replacement.
	function $() {
	   var elements = new Array();
	   
	   // Find all the elements supplied as arguments
	   for (var i = 0; i < arguments.length; i++) {
	       var element = arguments[i];
	       
	       // If the argument is a string assume it's an id
	       if (typeof element == 'string') {
	           element = document.getElementById(element);
	       }
	       
	       // If only one argument was supplied, return the element immediately
	       if (arguments.length == 1) {
	           return element;
	       }
	       
	       // Otherwise add it to the array
	       elements.push(element);
	   }
	   
	   // Return the array of multiple requested elements
	   return elements;
	};
	window['sanibel']['$'] = $;
	
	// Register an event listener on an element
	function addEvent( node, type, listener ) {
	   // Check compatibility using the earlier method
	   // to ensure graceful degradation
	   if(!isCompatible()) { return false }
	   if(!(node = $(node))) return false;   
	   if (node.addEventListener) {
	       // W3C method
	       node.addEventListener( type, listener, false );
	       return true;
	   } else if(node.attachEvent) {
	       // MSIE method
	       node['e'+type+listener] = listener;
	       node[type+listener] = function(){node['e'+type+listener]( window.event );}
	       node.attachEvent( 'on'+type, node[type+listener] );
	       return true;
	   }	
	   // Didn't have either so return false
	   return false;
	};
	window['sanibel']['addEvent'] = addEvent;
	
    function getElementsByClassName(className, tag, parent)
    {
        parent = parent || document;
        if(!(parent = $(parent))) {return false;}
        // Locate all the matching tags
        var allTags = (tag == "*" && parent.all) ? parent.all : parent.getElementsByTagName(tag);
        
        var matchingElements = new Array();
        // Create a regular expression to determine if the className is correct.
        className = className.replace(/\-/g, "\\-");
        var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
        var element;
        // Check each element.
        for(var i = 0; i < allTags.length; i++)
        {
            element = allTags[i];     
            if(regex.test(element.className)) matchingElements.push(element);
        }
        // Return any matching elements.
        return matchingElements;
    };
    window['sanibel']['getElementsByClassName'] = getElementsByClassName;	

	// Constants for note type comparison
	window['sanibel']['node'] = {
	    ELEMENT_NODE                : 1,
	    ATTRIBUTE_NODE              : 2,
	    TEXT_NODE                   : 3,
	    CDATA_SECTION_NODE          : 4,
	    ENTITY_REFERENCE_NODE       : 5,
	    ENTITY_NODE                 : 6,
	    PROCESSING_INSTRUCTION_NODE : 7,
	    COMMENT_NODE                : 8,
	    DOCUMENT_NODE               : 9,
	    DOCUMENT_TYPE_NODE          : 10,
	    DOCUMENT_FRAGMENT_NODE      : 11,
	    NOTATION_NODE               : 12
	};

	// Prevents the default event in the event flow (such as following the href in an anchor).
	function preventDefault(eventObject) {
		eventObject = eventObject || getEventObject(eventObject);
		if(eventObject.preventDefault) eventObject.preventDefault();
		else eventObject.returnValue = false;
	}
	window['sanibel']['preventDefault'] = preventDefault;
	
	// Retrieves the event object in a cross-browser way.
	function getEventObject(W3CEvent){return W3CEvent || window.event;}
	window['sanibel']['getEventObject'] = getEventObject;

	// Retrieves the element targeted by the event.
	function getTarget(eventObject){
	    eventObject = eventObject || getEventObject(eventObject);
	    // Check if the target is W3C or MSIE
	    var target = eventObject.target || eventObject.srcElement;
		
	    // Reassign the target to the parent if it is a text node like in Safari		
	    if(target.nodeType == sanibel.node.TEXT_NODE) target = node.parentNode;
	    return target;
	}
	window['sanibel']['getTarget'] = getTarget;
	
	/*** Conversion Functions ***/
	
	function toDate(id)
	{
	    if (id.value.length == 2){
	        id.value = id.value + "/";
	        return true;
	    }
	    // Insert the second dash at position 7 of the string
	    if (id.value.length == 5){
	        id.value = id.value + "/";
	        return true;
	    }
	    return false;        
	}
	window['sanibel']['toDate'] = toDate;
	
    function toPhone(id)
    {
        if (id.value.length == 3){
            id.value = id.value + "-";
            return true;
        }
        // Insert the second dash at position 7 of the string
        if (id.value.length == 7){
            id.value = id.value + "-";
            return true;
        }
        return false;
    }    
    window['sanibel']['toPhone'] = toPhone;    
    
    function toZip(id)
    {
        if (id.value.length >= 6)
        {            
            if(id.value.charAt(5) != "-")
            {
                var firstFive = id.value.slice(0, 5);
                var lastFour = id.value.slice(5);
                id.value = firstFive + "-" + lastFour;
            }            
            return true;
        }        
    }
    window['sanibel']['toZip'] = toZip;
	
	/*** Validation Library ***/
	
    window['sanibel']['TEXT'] = 1;    
    window['sanibel']['SELECT'] = 2;
    window['sanibel']['CHECKVALUE'] = 3;
    window['sanibel']['CHECKPHONE'] = 4;
    window['sanibel']['CHECKZIP'] = 5;
    window['sanibel']['CHECKDATE'] = 6;
    window['sanibel']['CHECKCURRENCY'] = 7;
    window['sanibel']['CHECKINT'] = 8;
    window['sanibel']['CHECKTIME'] = 9;	
    
    function isDate(value){
		//var d = Date.parseExact(value, "MM/dd/yyyy"); 
		var d = Date.parse(value); 
		return d ? true : false;
	};
    window['sanibel']['isDate'] = isDate;
	
    function isEmail(str){
		str = str.trim().toLowerCase();
        return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(str);
    };    
    window['sanibel']['isEmail'] = isEmail;  	
	
    function isEmpty(str){
        for(var i = 0; i < str.length; i++) if(str.charCodeAt(i) > 32) return false;
        return true;
    }
    window['sanibel']['isEmpty'] = isEmpty;	
	
    // Used by checkZip()
    function isNumeric(str){
        str = trim(str);
        var ValidChars = "0123456789.";
        var isNumber = true;
        var Char;
        for (i = 0; i < str.length && isNumber == true; i++)
        {
            Char = str.charAt(i);
            if (ValidChars.indexOf(Char) == -1) isNumber = false;
        }
        return isNumber;
    }
    window['sanibel']['isNumeric'] = isNumeric;   	
	
    function isPhone(phone_number)
    {
        // Trim leading and trailing whitespace.
        phone_number = phone_number.trim();
        // Check the phone number.
        return /^(((1))?[ ,\-,\.]?([\\(]?([1-9][0-9]{2})[\\)]?))?[ ,\-,\.]?([^0-1]){1}([0-9]){2}[ ,\-,\.]?([0-9]){4}(( )((x){0,1}([0-9]){1,5}){0,1})?$/.test(phone_number);
    }    
    window['sanibel']['isPhone'] = isPhone;	
	
    function isTime(timeStr)
    {    
        var timeExp = /^\s*[0-1]?\d(:[0-5]\d)?\s*((AM)|(PM)|(am)|(pm))\s*$/;               
        var strFormat1 = timeStr.match(timeExp);        
        // Check to see if it matches one of the 3 format strings.
        if(strFormat1 == null) return false;
        else if (strFormat1 != null)
        {
            // Validate for this format: 3:48:01 PM
            if (strFormat1[1] > 12 || strFormat1[1] < 00) return false;
            if (strFormat1[3] > 59 || strFormat1[3] < 00) return false;
            if (strFormat1[4] > 59 || strFormat1[4] < 00) return false;    
        }
        return true;                          
    }
    window['sanibel']['isTime'] = isTime;	
	
    function isURL(str){        
        str = str.trim().toLowerCase();
        return /^((http|https|ftp|file)\:\/\/([a-zA-Z0-0]*:[a-zA-Z0-0]*(@))?[a-zA-Z0-9-\.]+(\.[a-zA-Z]{2,3})?(:[a-zA-Z0-9]*)?\/?([a-zA-Z0-9-\._\?\,\'\/\+&amp;%\$#\=~])*)|((mailto)\:[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,7})|((news)\:[a-zA-Z0-9\.]*)$/.test(str);
    };    
    window['sanibel']['isURL'] = isURL;	
	
    function isZip(str)
    {
        str = trim(str);
        // This is for compatibility with the mask input control version.
        if(str.charAt(5) == "-") str = str.replace("-", "");
        var isNum = isNumeric(str);
        if(!isNum || isNum && str.length != 5 && str.length != 9) return false;
        else return true;
    }
    window['sanibel']['isZip'] = isZip;	
	
    function validate_array(form, ids){
        var error_exists = false;
        var error_messages = new Array();
        var FirstErrorField = null;        
        var id;
        var type;
        var label;
        var validate;
        var msg;    
        
        for (x in ids){    
            id = ids[x].id;
            type = ids[x].type;
            label = ids[x].label;
            value = form[id].value;
            
            validate = ids[x].validate;
            if(validate != sanibel.CHECKVALUE && isEmpty(value)) continue;
            //validate = !isEmpty(value) ? ids[x].validate : sanibel.CHECKVALUE;        
			
        
            switch(validate){
                case sanibel.CHECKVALUE:                    
                    if(isEmpty(value)){                 
                        if(type == sanibel.SELECT) msg = "Please make a selection in the \"" + label + "\" menu. ";     
                        else msg = "Please fill in the \"" + label + "\" field.";            
                        error_messages.push(msg);
                        if(!FirstErrorField) FirstErrorField = id;                        
                        error_exists = true;
                    }    
                    break;    
                    
                case sanibel.CHECKPHONE:					
                    if(!isPhone(value)){
                        msg = "Please enter a valid phone number in the \"" + label + "\" field (xxx-xxx-xxxx).";
                        error_messages.push(msg);
                        if(!FirstErrorField) FirstErrorField = id;
                        error_exists = true;
                    }                 
                    break;
                    
                case sanibel.CHECKZIP:
                    if(!isZip(value)) {
                        msg = "Please enter a valid zip code in the \"" + label + "\" field (xxxxx or xxxxx-xxxx).";
                        error_messages.push(msg);
                        if(!FirstErrorField) FirstErrorField = id;
                        error_exists = true;
                    }                 
                    break;            
                    
                case sanibel.CHECKDATE:
                    if(!isDate(value)){
                        msg = "Please enter the appropriate date format for the \"" + label + "\" field (mmm dd, yyyy).";
                        error_messages.push(msg);
                        if(!FirstErrorField) FirstErrorField = id;
                        error_exists = true;						
                    }             
                    break;
                    
                case sanibel.CHECKCURRENCY:
                    if(!isCurrency(value)){
                        msg = "Please enter the appropriate decimal format for the \"" + label + "\" field.";
                        error_messages.push(msg);
                        if(!FirstErrorField) FirstErrorField = id;
                        error_exists = true;
                    }
                    break;
                    
                case sanibel.CHECKINT:
                    if(!isNumeric(value)){
                        msg = "Please enter only numeric characters in the \"" + label + "\" field.";
                        error_messages.push(msg);
                        if(!FirstErrorField) FirstErrorField = id;
                        error_exists = true;
                    }             
                    break;
                    
                case sanibel.CHECKTIME:
                    if(!isTime(value)){
                        msg = "Please enter the appropriate time format in the \"" + label + "\" field (xx:xx am/pm).";
                        error_messages.push(msg);
                        if(!FirstErrorField) FirstErrorField = id;
                        error_exists = true;
                    }             
                    break;    
                    
                case sanibel.CHECKEMAIL:
                    if(!isEmail(value)){						
                        msg = "Please enter a valid email address in the \"" + label + "\" field.";
                        error_messages.push(msg);
                        if(!FirstErrorField) FirstErrorField = id;
                        error_exists = true;
                    }             
                    break;                                    
            }
        }
    
        //display error messages and return success
        if(error_exists)
        {               
            if(error_messages.length > 0)
            {
                // show alert() message                
                var str = "";
                for(var i = 0; i < error_messages.length; i++)
                {
                    str += error_messages[i] + "\n";
                }
                alert(str);
                // set focus to first form error, if the field supports js focus().
                if(form[FirstErrorField].type == "text"){form[FirstErrorField].focus();}
            }
            return false;
        }
        else return true;
    }
    window['sanibel']['validate_array'] = validate_array;
	
})();

sanibel.addEvent(window, "load", function(W3CEvent){
    var popups = sanibel.getElementsByClassName("popup", "a");
    // Locate all the anchor tags with the popup class in the document.
    for(var i = 0; i < popups.length; i++)
    {
        // Add a click event listener to each anchor.
        sanibel.addEvent(popups[i], "click", function(W3CEvent){
            //window.open(this.href);
			
			window.open (this.href,"sanibel","status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1,scrollbars=1,width=800,height=700"); 
			
            sanibel.preventDefault(W3CEvent);
        })        
    }
});
