﻿/*** Base method for namespace creation - IMPORTANT: Do NOT change these!
------------------------------------------------------------------ */

/** global scope */
if (typeof _global_ === "undefined") {
    _global_ = {
        /*
        Use function @namespace to create dot separated namespaces. For example: 
        Create a nested namespace:
        _global_["@namespace"]("foo");
        _global_["@namespace"]("foo.bar");
        _global_["@namespace"]("foo.bar.something");
        Then add functions to the namespace:	
        foo.bar.something.else = function() {};
        */
        "@namespace": function(str) {
            var a = str.split(".");
            var o = window;
            for (var i = 0; i < a.length; i++) {
                if (!o[a[i]]) {
                    o[a[i]] = {};
                }
                o = o[a[i]];
            }
        }
    }
};

// Create the global AIIA namespace to avoid JS collisions with other scripts running on the page (eg. prototype, scriptaculous, or custom scripts)
_global_["@namespace"]("aiia");


/** Extend the client's native browser prototypes (where required)
------------------------------------------------------------------ */

/* 	Add Array.push() functionality 
Can add multiple elements to an array. Eg Array.push(value1[, value2[, value3]]) 
Returns the new length of the array. 
*/
if (typeof Array.prototype.push === 'undefined') {
    Array.prototype.push = function() {
        for (var i = 0, b = this.length, a = arguments, l = a.length; i < l; i++) {
            this[b + i] = a[i];
        }
        return this.length;
    };
}

// Create string trim() prototype method
if (typeof String.prototype.trim === 'undefined') {
    String.prototype.trim = function() {
        s = this.replace(/^\s+/, '');
        return s.replace(/\s+$/, '');
    };
}

// Attach functions to handle events that occur on the named event source. Doesn't override previously registered handlers for the same source/event.
// See: http://www.howtocreate.co.uk/tutorials/javascript/domevents
aiia.AddEvent = function(source, eventName, functionName, useCapture) {
    useCapture = (typeof(useCapture) == "undefined") ? false : true;  // if true the event is only handled when it occurs on child/ancestor elements of the source/target element
	if (source.addEventListener) {
		source.addEventListener(eventName, functionName, useCapture);
		return true;
	}
	else if (source.attachEvent) {
		var r = source.attachEvent('on' + eventName, functionName);
		return r;
	}
	else {
		source['on' + eventName] = functionName;
	}
}


/** String functions
------------------------------------------------------------------ */
_global_["@namespace"]("aiia.String");


// Returns true if the string parameter contains only spaces, tabs or EOL characters
aiia.String.IsBlank = function(string) {
    var _isBlank = true;
    for (var i = 0; _isBlank && (i < string.length); i++) {
        var c = string.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) _isBlank = false;
    }
    return _isBlank;
}

// Returns true if the string parameter equals null, an empty string, a tab, EOL or space character.
aiia.String.HasValue = function(value) {
    if ((value == null) || (value == "") || aiia.String.IsBlank(value)) return false;
    else return true;
}

aiia.String.IsValidEmail = function(value) {
    var emailOk = true;
    var atPos = value.indexOf('@');
    var periodPos = value.lastIndexOf('.');
    var spacePos = value.indexOf(' ');
    var length = value.length - 1;         // Array is from 0 to length-1
    if ((atPos < 1) ||                        // '@' cannot be in first position
	    (periodPos <= atPos + 1) ||             // Must be at least one valid char between '@' and '.'
	    (periodPos == length) ||             // Must be at least one valid char after '.'
	    (spacePos != -1))                    // No empty spaces permitted
        emailOk = false;
    return emailOk;
}

// Use in <asp:CustomValidator> controls to check an email field value is valid
aiia.CheckIsValidEmail = function(sender, args) {
    args.IsValid = aiia.String.IsValidEmail(args.Value);
}


/** Form functions
------------------------------------------------------------------ */

// Stores a reference to the page's "default form" (so the form will be submitted when the user presses the "Enter" key)
aiia.defaultForm = null;
// Store the UniqueID of the form's submit button, which is used in ASP.NET's __doPostBack() function.
aiia.submitButtonId = '';
// Store the form's redirect URL (if not posting to the same form)
aiia.actionUrl = '';
// Perform validation of the form?
aiia.doValidation = true;

// This is used to register a particular page's default form 
aiia.SetDefaultForm = function(frm) {
    // If no form was supplied, use the first one found on the page.
    if (!frm) frm = document.forms[0];
    aiia.defaultForm = frm;
}

// Use this to set a default form to submit if the user presses the 'Enter' key
aiia.SubmitFormOnEnterKeyPress = function(e) {
    if (aiia.EnterKeyWasPressed(e) && (aiia.defaultForm != null)) {
        // Do NOT submit the form if the 'Enter' key was pressed inside a textarea
        var target = aiia.GetEventTarget(e);
        var isOkTarget = (!target || (typeof (target) == "undefined") || (target.type != "textarea"));
        if (isOkTarget) {
            // Fire any form validation first, if specified
            if (typeof aiia.defaultForm.ValidatorMethod != 'undefined') {
                // If form validation JS exists and has been specified, only submit the form if it validates
                if (aiia.defaultForm.ValidatorMethod())
                    __doPostBack(aiia.submitButtonId, "");
                    // aiia.SubmitAspNetForm();
            }
            else
                __doPostBack(aiia.submitButtonId, "");
                //aiia.SubmitAspNetForm();
                
        }
    }
}


/*
A wrapper used to call asp.net's WebForm_DoPostBackWithOptions function
See: http://blog.csdn.net/shankaipingo/archive/2008/11/06/3236879.aspx for explaination
Function Interface: WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit) 
*/
aiia.SubmitAspNetForm = function() {
    eval('WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;' + aiia.submitButtonId + '&quot;, &quot;&quot;, ' + aiia.doValidation + ', &quot;&quot;, &quot;' + aiia.actionUrl + '&quot;, false, true))');
}

// Returns the code of the key pressed
aiia.GetKeyPressed = function(e) {
    code = -1;
    if (!e) e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    return code;
}

// Returns the target of the event (eg. a field, the window, a button etc.)
aiia.GetEventTarget = function(e) {
    target = null;
    if (!e) e = window.event;
    if (e) target = e.target || e.srcElement;
    return target;
}

// Returns true if the "Enter" key was pressed
aiia.EnterKeyWasPressed = function(e) {
    return (aiia.GetKeyPressed(e) == 13);
}


// Call this to make the page auto-submit when the user clicks the 'Enter' key
aiia.SetupForm = function(submitButtonId, doValidation, actionUrl) {
    var frm = document.forms['aspnetForm'];
    if (!frm) frm = document.aspnetForm;
    aiia.SetDefaultForm(frm);
    // We need to pass the Unique ID of the 'submit' button to ASP.NET's __doPostBack() function for it to submit.
    aiia.submitButtonId = submitButtonId;
    if (doValidation) aiia.doValidation = doValidation;
    if (actionUrl) aiia.actionUrl = actionUrl;
    // Hook into the asp.net generated client-side validation function (if it exists)
    if (typeof (Page_ClientValidate) == "function") {
        frm.ValidatorMethod = function() {
            return Page_ClientValidate();
        };
    }
    aiia.AddEvent(document, 'keyup', function(e) { aiia.SubmitFormOnEnterKeyPress(e) });
}


// Returns true if a list item/option with a value has been selected in the <select> list ('sender'). Otherwise returns false.
aiia.CheckOptionValueIsChosen = function(sender, args) {
   args.IsValid = aiia.String.HasValue(args.Value);
}
