/*
==========================================================================
Module:		Common.js
Written:	November 2003
Author:		Jason Aherne
==========================================================================
Function:	Javascript utility routines used by all pages.  				
				
==========================================================================
	
*/
function OpenTeam(psID, psTeam) {
    switch (psTeam) {
        case "Adelaide":
            window.open('http://www.afc.com.au');
            break;
        case "Brisbane":
            window.open('http://www.lions.com.au');
            break;
        case "Carlton":
            window.open('http://www.carltonfc.com.au');
            break;
        case "Collingwood":
            window.open('http://www.collingwoodfc.com.au');
            break;
        case "Essendon":
            window.open('http://www.bombersfc.com.au');
            break;
        case "Fremantle":
            window.open('http://www.fremantlefc.com.au');
            break;
        case "Geelong":
            window.open('http://www.gfc.com.au');
            break;
        case "Hawthorn":
            window.open('http://www.hawthornfc.com.au');
            break;
        case "Kangaroos":
            window.open('http://www.kangaroos.com.au');
            break;
        case "Melbourne":
            window.open('http://www.melbournefc.com.au');
            break;
        case "Port Adelaide":
            window.open('http://www.portadeidefc.com.au');
            break;
        case "St Kilda":
            window.open('http://www.saints.com.au');
            break;
        case "Sydney":
            window.open('http://www.sydneyswans.com.au');
            break;
        case "Richmond":
            window.open('http://www.richmondfc.com.au');
            break;
        case "Western Bulldogs":
            window.open('http://www.westerbulldogs.com.au');
            break;
        case "West Coast":
            window.open('http://www.westcoasteagles.com.au');
            break;

        default:
            window.open('http://www.afl.com.au');
            break;
    }
}

function OpenPageInFrame(psPageToOpen) {
    window.location = psPageToOpen
}

function OpenWindow(sURL, sName, iHeight, iWidth, iTop, iLeft, bToolBar, bMenu) {
    var sAttrib = "";

    sName = "";

    iHeight = 300;
    iWidth = 300;

    if (iHeight > 0)
    { sAttrib = "height=" & iHeight.toString(); }

    if (iWidth > 0)
    { sAttrib += " width=" & iWidth.toString(); }

    if (iLeft > 0)
    { sAttrib += " screenX=" & iLeft.toString(); }

    if (iTop > 0)
    { sAttrib += " screenY=" & iTop.toString(); }

    if (!bToolBar)
    { sAttrib += " toolbar=0"; }

    if (!bMenu)
    { sAttrib += " menubar=0"; }

    sAttrib += " scrollbars=1";
    sAttrib += " resizable=1";

    window.open(sURL, sName, sAttrib);
}

function WindowCloseRefresh(sURL) {
    try {
        var frames = window.opener.document.frames;
        //alert("after" + window.opener.document.body.innerHTML);
        for (var i = 0; i < frames.length; i++) {
            alert("Frame is " + frames[i].id);

            if (frames[i].id == 'ContentFrame') {
                alert("found frame");

                frames[i].location.href = frames[i].location.href;
                break;
            }
        }
        window.opener.location.href = sURL;
        window.close();
    }
    catch (e) {
        alert(e.toString());
    }
    finally {

    }
}

function ReloadFrame(oFrame, sURL) {
    oFrame.location.href = sURL;
}

function ReloadWindow(oWindow, sURL) {
    oWindow.location.href = sURL;
}

function ReloadAdjacentFrame(sFrameName, sURL) {

    try {
        window.parent.frames[sFrameName].location.href = sURL;
    }
    catch (e) {
        alert("The requested frame " + sFrameName + " could not be found.");
    }
}

function GetAttribute(sName, oNode) {
    var sResult = "";

    try {
        if (oNode.attributes.length > 0 && oNode.attributes.getNamedItem(sName)) {
            sResult = oNode.attributes.getNamedItem(sName).value;
        }
    }
    catch (e) {
        alert(e.toString());
    }
    finally {
        return sResult;
    }
}

function ShowModalDialog(sAction, sSubAction, oCallingControl, vTargetControls) {
    /*
    ------------------------------------
    GetDialogValue()
    --------------------------------------
    written :	Nov 2003 
    author:		Jason Aherne
    Purpose:	Display a modal dialog box on a web form containing a list of items
    corresponding to properties from an object.  Allows user to select item(s) from
    the list to populate controls on the calling page.
    Arguments:
    sAction			:	Type of list to display
    oCallingControl :	The control adjacent to which 
    the window must be displayed	
    vTargetControls :   Controls to receieve return values
    --------------------------------------*/

    var sQueryString = "action=" + sAction + "&mode=" + sSubAction;

    var i = 0;

    var vResult = window.showModalDialog(window.location.href + "?" + sQueryString);

    if (vResult != null) {
        for (i = 0; i < vResult.length; i++) {
            document.all[vTargetControls(i)].value = vResult[i];
        }
    }

    return true;
}

function ConfirmDeletePrompt() {
    if (confirm("Are you sure you want to delete this item?")) {
        return true;
    }
    else {
        return false;
    }
}

function ToggleFrame(sFrame, image, sFullSizePx, sMinSizePx) {
    var oElem = window.parent.document.all[sFrame];
    if (parseFloat(oElem.height) == parseFloat(sMinSizePx)) {
        //oElem.style.visibility = "hidden";
        //oElem.style.display = "none";
        oElem.height = sFullSizePx;
        image.src = image.src.replace("HeaderBarDownArrow.gif", "HeaderBarUpArrow.gif");
    }
    else {
        //if (parseFloat(oElem.height) > 30)
        //oElem.style.visibility = "visible";
        //oElem.style.display = "block";
        oElem.height = sMinSizePx;
        image.src = image.src.replace("HeaderBarUpArrow.gif", "HeaderBarDownArrow.gif");
    }
}

function ConfirmCloseWithReloadWindow(lsURL) {
    if (confirm("Click OK to cancel changes")) {
        WindowCloseRefresh(lsURL);
    }
}

//--------------------------------------------------------	
function Tag(sName, sValue, iType) {

    var sResult = "";
    var lt = "&lt;";
    var gt = "&gt;";

    switch (iType) {
        case 0: //full tag
            sResult = lt + sName + gt + sValue + lt + "/" + sName + gt;
            break;

        case 1: //open tag only

            sResult = lt + sName + gt;
            break;

        case 2: //closing tag only

            sResult = lt + "/" + sName + gt;
            break;
    }

    return sResult;

}

function xmlEscape(sValue) {
    var sResult = new String(sValue);

    sResult = sResult.replace("<", "&lt;");
    sResult = sResult.replace(">", "&gt;");
    sResult = sResult.replace("&", "&amp;");
    return sResult;

}

//--------------------------------------------------------		
function GetComboSelectedTextFromID(oCombo, value) {

    var sResult = "";
    for (var i = 0; i < oCombo.options.length; i++) {
        if (oCombo.options[i].value == value) {
            sResult = oCombo.options[i].text;
            break;
        }
    }

    return sResult;

}
//----------------------Exit from the application
function Exit() {
    //
    window.close();
}

//----------------------Convert a value to decimal, pass in the number of decimal places
function ConvertToDecimal(sValue, nDecimalPlaces) {

    return parseFloat(sValue).toFixed(nDecimalPlaces);

}

/**********************************
function ShowProgress()
displays a progress bar, as defined in the file ../common/ProgressBar.htm
***********************************/
function ShowProgress(sText) {
    document.all["ProgressText"].innerText = sText;
    ProgressBar.fgColor = "silver";
    ProgressBar.style.zIndex = 50000;
    ProgressBar.style.display = "block";
}

function HideProgress() {
    ProgressBar.style.display = "none";
}

function FindDatePartIndex(sPart, oFormat) {

    sPart = sPart.toLowerCase();

    var iResult = 0;

    for (var i = 0; i < oFormat.length; i++) {
        if (oFormat[i].toLowerCase().indexOf(sPart) > -1) {
            iResult = i;
            break;
        }
    }

    return iResult;

}

function RemoveNonNumeric(sValue) {
    var sNewValue = new String();
    var sTest = new String(sValue);

    for (var i = 0; i < sTest.length; i++) {
        if (!isNaN(parseFloat(sTest.substr(i, 1)))) {
            sNewValue += parseFloat(sTest.substr(i, 1)).toString();
        }
    }
    return sNewValue;
}

function FormatDate(oControl) {

    var sValue = CleanupDate(oControl);

    if (sValue == "") {
        //alert("You must enter a valid date.");
        oControl.value = "";
        oControl.style.backgroundColor = "gold";
        return false;
    }
    else {
        oControl.style.backgroundColor = "white";
    }

    var sDelimiter = new String(UnescapeDelimiter(oControl.delimiter));
    var sFormat = new String(oControl.dateformat);
    var oNewDate = sFormat.split(sDelimiter);
    var oDate = sValue.split(sDelimiter);

    var iYear;
    var iMonth;
    var iDay;

    for (var i = 0; i < oNewDate.length; i++) {
        if (oNewDate[i].toLowerCase().indexOf("d") > -1) {
            oNewDate[i] = FormatDatePart(oDate[i], oNewDate[i], false);
            iDay = parseFloat(oNewDate[i]);
        }

        else if (oNewDate[i].toLowerCase().indexOf("m") > -1) {
            oNewDate[i] = FormatDatePart(oDate[i], oNewDate[i], false);
            iMonth = parseFloat(oNewDate[i]);
        }

        else if (oNewDate[i].toLowerCase().indexOf("y") > -1) {
            oNewDate[i] = FormatDatePart(oDate[i], oNewDate[i], true);
            iYear = oNewDate[i];
        }
    }

    if (ValidDate(iDay, iMonth, iYear)) {
        oControl.value = oNewDate.join(sDelimiter).toString();
        return true;
    }
    else {
        alert("You must enter a valid date.");
        oControl.value = "";
        oControl.style.backgroundColor = "gold";
        return false;
    }

}

function ValidDate(iDay, iMonth, iYear) {

    if (iMonth > 12 || iMonth < 1)
        return false;

    if (iYear < 1)
        return false;

    switch (iMonth) {
        case 4:
            if (iDay > 30) { return false; }
            break;
        case 2:
            if (IsLeapYear(iYear) && iDay > 29) { return false; }
            if (!IsLeapYear(iYear) && iDay > 28) { return false; }
            break;
        case 6:
            if (iDay > 30) { return false; }
            break;
        case 9:
            if (iDay > 30) { return false; }
            break;
        case 11:
            if (iDay > 30) { return false; }
            break;
        default:
            if (iDay > 31) { return false; }
            break;
    }
    return true;
}

function UnescapeDelimiter(sDelimiter) {
    var sResult = "";
    switch (sDelimiter.toString()) {
        case "bslash":
            sResult = "\\";
            break;
        case "fslash":
            sResult = "/";
            break;
        case "hyphen":
            sResult = "-";
            break;
        default:
            sResult = "/";
    }

    return sResult;

}

function FormatDatePart(sValue, sFormat, bIsYear) {

    var i = 0;

    sValue = new String(sValue);


    var iDiff = sFormat.length - sValue.length;
    if (iDiff > 0)    //padd with leading zeros	
    {
        if (bIsYear && sValue.length == 2) {
            if (parseFloat(sValue) < 10)
                sValue = "20" + sValue;
            else
                sValue = "19" + sValue;
        }
        else {
            for (i = 0; i < iDiff; i++) {
                sValue = "0" + sValue;
            }
        }
    }
    else if (iDiff < 0) {
        if (bIsYear)		 //remove leading digits
        { sValue = sValue.slice(Math.abs(iDiff)); }
        else				//removing leading zeros
        {
            while (sValue.substr(0, 1) == "0") {
                sValue = sValue.slice(1);
            }
        }
    }

    return sValue;
}

//Check if the control has a value of a number in it.  If it hasn't then reset it to zero
function CheckForNaN(poControl) {
    //Find any comma & remove them
    var lValue = poControl.value;
    lValue = stringReplace(lValue, ",", "");

    if (isNaN(lValue)) {
        poControl.value = 0;
    }
}

//Search & replace a string
function stringReplace(originalString, findText, replaceText) {
    var pos = 0;
    var len = findText.length;
    pos = originalString.indexOf(findText);

    while (pos != -1) {
        preString = originalString.substring(0, pos);
        postString = originalString.substring(pos + len, originalString.length);
        originalString = preString + replaceText + postString;
        pos = originalString.indexOf(findText);
    }

    return originalString;
}

function ShowField(sRowID) {
    //var row = document.all[sRowID]
    var row = sRowID[0]

    if (row.style.display != "block" || row.style.visibility != "visible") {

        if (row.style.display != "block")
        { row.style.display = "block"; }

        if (row.style.visibility != "visible")
        { row.style.visibility = "visible"; }
    }
}

function HideField(sRowID) {
    //with (document.all[sRowID].style) {
    with (sRowID[0].style) {
        if (display != "none")
        { display = "none"; }

        if (visibility != "hidden")
        { visibility = "hidden"; }
    }
}

function ValidateEmail(pEmail) {

    //Now ensure the email is valid 
    if ((pEmail.value.indexOf('@') < 1) ||                     								// '@' cannot be in first position
	    (pEmail.value.lastIndexOf('.') <= pEmail.value.indexOf('@') + 1) ||     // Must be at least one valid char btwn '@' and '.'
	    (pEmail.value.lastIndexOf('.') == pEmail.value.length - 1) ||        // Must be at least one valid char after '.'
	    (pEmail.value.indexOf(' ') != -1))                    								// No empty spaces permitted
    {
        return false;
    }
    else {
        return true;
    }
}

/*****************************************************
Function Resize the Popup window()
Written 13-10-04 by Craig Wilson
Purpose: Toggles 'True' and 'False' text values for
the sub-groups.
*****************************************************/
function ResizePopup() {
    var liTitleOffset = parseInt(window.dialogHeight) - parseInt(document.body.offsetHeight);

    if (window.dialogHeight != parseInt(document.body.scrollHeight) + "px")
    { window.dialogHeight = parseInt(document.body.scrollHeight) + liTitleOffset + "px" };
}

function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue) {
    var arrElements = (strTagName == "*" && oElm.all) ? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var oAttributeValue = (typeof strAttributeValue != "undefined") ? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)", "i") : null;
    var oCurrent;
    var oAttribute;

    for (var i = 0; i < arrElements.length; i++) {
        oCurrent = arrElements[i]; oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
        if (typeof oAttribute == "string" && oAttribute.length > 0) {
            if (typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))) {
                arrReturnElements.push(oCurrent);
            }
        }
    }
    return arrReturnElements;
}

function GetTextboxValue(oElm, sControl) {
    //sControl can include a wildcard such as *txtEmail
    var oControls;

    oControls = getElementsByAttribute(oElm, "input", "id", sControl)

    if (oControls.length > 0) {
        //Return the value of the first match found
        return oControls[0].value;
    }
    else {
        return ""
    }
}

function GetTextbox(oElm, sControl) {
    //sControl can include a wildcard such as *txtEmail
    var oControls;

    oControls = getElementsByAttribute(oElm, "input", "id", sControl)

    if (oControls.length > 0) {
        //Return the value of the first match found
        return oControls[0];
    }
    else {
        return ""
    }
}

