/*
 *  $Id: js.js 125 2011-05-05 20:15:46Z stuart $
 *  
 *  dev.stuconnolly.com
 *  Open Source Software Development
 *
 *  Copyright (c) 2011 Stuart Connolly. All rights reserved.
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Trim function from http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256C0C0062AC78
 */
function trim(value) 
{    
	var temp = value;

	var obj = /^(\s*)([\W\w]*)(\b\s*$)/;

	if (obj.test(temp)) { 
		temp = temp.replace(obj, '$2'); 
	}

	var obj = /  /g;

	while (temp.match(obj)) { 
		temp = temp.replace(obj, " "); 
	}

	return temp;
}

/**
 * Checks if the supplied email address is valid.
 */
function validateEmailAddress(emailAddress) 
{
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

	return reg.test(emailAddress);
}

/**
 * Attempts to create and return an XMLHTTPResquest based on the browser type.
 */
function createXMLHTTPRequest() 
{
	var request;

	try {
		request = new XMLHttpRequest();
	} 
	catch (trymicrosoft) {
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (othermicrosoft) {
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} 	
			catch (failed) {
				request = false;
			}
		}
	}

	return request;
}

/**
 * Validates the feedback form's input elements.
 */
function validateFeedbackForm()
{
    var errorMessage = '';
    var form = document.forms['feedbackform'];
    
    
    if (trim(form.title.value).length == 0) {
        errorMessage = "- The title field is blank\n";
    }
    
    if (form.cc.checked) {
        if (trim(form.email.value).length == 0) {
            errorMessage += "- The email field is blank\n";
        }
        else {
            if (validateEmailAddress(trim(form.email.value)) == false) {
                errorMessage += "- The email address '" + trim(form.email.value) + "' is not valid.\n";
            }
        }
    }
    
    if (trim(form.description.value).length == 0) {
        errorMessage += "- The description field is blank\n";
    }
    
    if (trim(form.year.value).length == 0) {
        errorMessage += "- The current year field is blank\n";
    }
    else {
        if (isNaN(trim(form.year.value))) {
            errorMessage += "- The current year field is not numeric\n";
        }
        else {
            var date = new Date();
                        
            if (trim(form.year.value) != date.getUTCFullYear()) {
                errorMessage += '- Anti-spam measure failed.';
            }
        }
    }
    
    if (errorMessage.length > 0) {
        alert("Form validation failed. Please take note of the following:\n\n" + errorMessage);
        
        return false;
    }
}

/**
 * Updates the available versions for the selected application.
 */
function updateApplicationVersions()
{
    var form = document.forms['feedbackform'];
    
    var app = form.application.options[form.application.selectedIndex].value;
    
    var versionsScriptURL = '/system/scripts/app.versions.php?app=' + app;
    
    var request = createXMLHTTPRequest();
    
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {		
                var versions = request.responseXML.getElementsByTagName('version');
                
                // Remove all elements from drop down
                while (form.version.length) 
                {
                    form.version.remove(0);
                }
                           
                // Add new elements
                for (var i = 0; i < versions.length; i++) 
                {                                                        
                    var versionNum = versions[i].childNodes[1].childNodes[0].nodeValue;
                                   
                    var newOption = document.createElement('option');
                    
                    newOption.value     = versionNum;
                    newOption.innerHTML = versionNum;
                    
                    form.version.appendChild(newOption); 
                }
            } 
        }
    };

    request.open("POST", versionsScriptURL, true);
    request.send(null);
}

