// ****************************************************************************************************************
/**
 * Javascript file for Footy Fever Website.   
 *
 * Copyright 2008 - Crane Group IM
 * 
 * For information on this file please contact Peter Soluch.  
 *
 */

// ****************************************************************************************************************
/**
 * Trims leading and trailing spaces of a given string   
 * 
 * @return String with leading and trailing spaces removed 
 * 
 */
function trim(sString) {
    
    if (sString == undefined) return sString;
    if (sString.length == 0) return sString;
    
    while (sString.substring(0,1) == ' ') {
        sString = sString.substring(1, sString.length);
    }
    
    while (sString.substring(sString.length-1, sString.length) == ' ') {
        sString = sString.substring(0,sString.length-1);
    }
    
    return sString;
}

 // ****************************************************************************************************************
/**
 * Checks user input for invalid characters in username and password, if all ok then returns true   
 *
 * @return True if inputs are ok, otherwise false
 *
 */
function doLogin(){
    
    // get username object and check if ok
    var username = document.getElementById('username');
    var password = document.getElementById('password');
    
    if (trim(username.value)=="" || password.value==""){
        alert("Please ensure that you have entered a username and password.");
        return false;
    }
    
    document.getElementById("frmMain").submit();
}

// ****************************************************************************************************************
/**
 * Checks whether a string is numeric.  Contains options to check for decimals, positive numbers, and max size/value.
 * 
 * @param strString The string to test. 
 * @param positiveOnly Whether to test for positive numbers only.
 * @param wholeOnly Whether to test for whole numbers only.
 * @param maxLength The maximum length of the number, i.e. character length.
 * @param maxValue The maximum value this number can be.
 * 
 * @return True if is is a number and meets all the criteria, otherwise false.   
 * 
 */
function isNumeric(strString, positiveOnly, wholeOnly, maxLength, maxValue){
    var strValidChars = "0123456789";
    strValidChars = strValidChars.toString();
    
    if (!positiveOnly){
        strValidChars = strValidChars +  "-";
    }
    
    if (!wholeOnly){
        strValidChars = strValidChars +  ".";
    }
    
    var strChar;
    var i=0;
    
    if (strString.length == 0 || strString == undefined) return false;
    
    if (maxLength != ""){
        if (strString.length > maxLength) return false;
    }
    
    //  test strString consists of valid characters listed above
    for (i=0; i < strString.length; i++){
        strChar = strString.charAt(i);
        
        // if find invalid then return false
        if (strValidChars.indexOf(strChar) == -1){
            return false;
        }
    }
    
    if (maxValue != ""){
        if (eval(strString) > maxValue){
            return false;
        }
    }
    
    return true;
}

// ****************************************************************************************************************
/**
 * Encodes a string so that it can be sent via url.
 * 
 * @param criteria The string criteria to encode.
 * @return The encoded string.  
 *  
 */
function encodeString(criteria){
    criteria = criteria.replace(/\^/g, "^19");
    criteria = criteria.replace(/ /g, "^20");
    criteria = criteria.replace(/\\/g, "^21");
    criteria = criteria.replace(/\?/g, "^22");
    criteria = criteria.replace(/\$/g, "^23");
    criteria = criteria.replace(/\&/g, "^24");
    criteria = criteria.replace(/\@/g, "^25");
    criteria = criteria.replace(/\'/g, "^26");
    criteria = criteria.replace(/\"/g, "^27");
    return criteria;
}

function isDateTime(dtStr, showAlert){
    
    // first trim date/time
    dtStr = trim(dtStr);
    
    // split date and time
    var dtCh= "/";                  // Date delimiter
    var minYear=2006;               // Min year for dates
    var maxYear=2020;               // Max year for dates
    var spacePos = dtStr.indexOf(" ");
    var strError = "The date / time you entered is invalid.\n\nPlease ensure the date and time format used is: dd/mm/yyyy hh:mm\n\nPlease note that the year must be between " + minYear + " and " + maxYear + ".";
    
    // if no space
    if (spacePos < 6){
        if (showAlert){
            alert(strError);
        }
        return false;
    }
    
    // split date and time
    var strTime = trim(dtStr.substring(spacePos));
    dtStr = trim(dtStr.substring(0, spacePos));

    var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
    var strYr=strYear;
    
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
    
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
    }
    
    month=parseInt(strMonth);
    day=parseInt(strDay);
    year=parseInt(strYr);
    
    if (pos1==-1 || pos2==-1){
        if (showAlert){
            alert(strError);
            //alert("The date format should be : dd/mm/yyyy");
        }
        return false;
    }
    
    if (strMonth.length<1 || month<1 || month>12){
        if (showAlert){
            alert(strError);
            //alert("Please enter a valid month");
        }
        return false;
    }
    
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        if (showAlert){
            alert(strError);
            //alert("Please enter a valid day");
        }
        return false;
    }
    
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        if (showAlert){
            alert(strError);
            //alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
        }
        return false;
    }
    
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        if (showAlert){
            alert(strError);
            //alert("Please enter a valid date");
        }
        return false;
    }
    
    // date is correct, now check time
    var pos = strTime.indexOf(":");
    
    // if no delimiter then invalid time
    if (pos < 1){
        if (showAlert){
            alert(strError);
        }
        return false
    }
    
    var strHour = trim(strTime.substring(0, pos));
    var strMinute = trim(strTime.substring(pos+1));
    
    // check minute is 2 digits
    if ((strMinute.length) != 2){
        if (showAlert){
            alert(strError);
        }
        return false;
    }
    
    // check hour is also 2 digits
    if ((strHour.length) != 2){
        if (showAlert){
            alert(strError);
        }
        return false;
    }
    
    // check minute is numeric and no more than 59 minus
    if (!isNumeric(strMinute, true, true, 2, 59)){
        if (showAlert){
            alert(strError);
        }
        return false;
    }
    
    // check hour is no more than 23 hours
    if (!isNumeric(strHour, true, true, 2, 23)){
        if (showAlert){
            alert(strError);
        }
        return false;
    }
    
    return true;
}

//**********************************************************************************************************************
// Check whether a value is an integer (for date check)
//**********************************************************************************************************************
function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){
        
        // Check that current character is number.
        var c = s.charAt(i);
        if ((c < "0") || (c > "9")) return false;
    }
    
    // All characters are numbers.
    return true;
}


//**********************************************************************************************************************
// For date check
//**********************************************************************************************************************
function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    
    return returnString;
}


//**********************************************************************************************************************
// Number of days in Feb for a given year
//**********************************************************************************************************************
function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}


//**********************************************************************************************************************
// Number of days in an array
//**********************************************************************************************************************
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31;
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
        if (i==2) {this[i] = 29;}
    }
    
    return this;
}


// ****************************************************************************************************************
/**
 * Used to perform an ajax function.
 *
 * @param parameters The parameters to user for calling ajax.
 * @param output_element_id The element object used as the output.  If none is specified this will use "temp" 
 * @param timer_element_id The id of the element where to place the timer image.
 * 
 */ 
function ajax (parameters, output_element_id, timer_element_id) {
    var obj = document.getElementById(timer_element_id);
    
    // if have timer container then put in timer image
    if (obj != undefined){
        obj.innerHTML = '<img src="./images/timer.gif" border="0" alt="please wait"/>';
    }
    
    if (output_element_id == ""){
        output_element_id = "temp";
    }
    
    new Ajax.Updater(output_element_id, "_ajax.php?" + parameters + "&timer_element_id=" + timer_element_id, { method: 'get', evalScripts: true });    
}


// ****************************************************************************************************************
/**
 * Centre an object on the screen.
 *
 * @param obj The object to centre
 *  
 */
function centreObject (obj) {
    
    objWidth = obj.style.width.substr(0,2);
    objHeight = obj.style.height.substr(0,2);
    
    if (window.innerHeight && window.scrollMaxY) {// Firefox         
        yWithScroll = window.innerHeight + window.scrollMaxY;
        xWithScroll = window.innerWidth + window.scrollMaxX;
        
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        yWithScroll = document.body.scrollHeight;
        xWithScroll = document.body.scrollWidth;
        
    } else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
        yWithScroll = document.body.offsetHeight;
        xWithScroll = document.body.offsetWidth;
    }
    
    //get x position
    var x = (document.documentElement.clientWidth / 2) - (objWidth / 2);
    
    //get scroll top
    var sTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
    
    //get client height (Basically browser window height)
    var ch = (document.documentElement.clientHeight);
    
    //Place in centre of screen - irrespective where button is
    y = sTop + (ch/2) - (objHeight/2);
    
    obj.style.top = y + "px";
    obj.style.left = x + "px";
}



var strAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var strNumeric = "0123456789";
var strUsername = strAlpha + strNumeric + "' \",.-_";

function hasValidChars(string, validChars){
    
    // go through all characters
    for (i=0; i<string.length; i++){
        
        // get character and check if in valid chars, if not then not valid
        var chr = string.substring(i, i+1);
        
        if (validChars.indexOf(chr) < 0){
            //alert (validChars + " " + chr + " " + chr.indexOf(validChars));
            return false;
        }
    }
    
    // no invalids found - all ok
    return true;
}

function doSubmit(){
    document.getElementById("frmMain").submit();
}

function doButtonClickOnEnter(e, btnId){
    if (e.keyCode == 13){
        var obj = document.getElementById(btnId);
        obj.focus();
        obj.click();
    }    
}
