﻿// This file will contain the common functions used throughout the AJAX functionality
// ~/Scripts/Common.js

// Common variables
var _MainPage = "../Index.aspx";
var _DefaultPage = "./Forms/Public/Home.aspx";
var _DefaultLeague = 0;
var _iFramePage = "iFrameSRC";
var _iFrameCntrl = "frmContent";
var _CookieExpiry = 60;
var browserType = undefined;
var hasTextContent = true;

// Login Messages
var _LoginFailed = 'Incorrect Username or Password';
var _LoginLocked = 'This account is locked.  Please contact the system administrator';
var _LoginExpired = 'This account is expired.  Please change your password';

// Access Denied
var _AccessDenied = 'Access Denied.  Please contact the system administrator.';
// Required Messages
var _RequiredIncomplete = "Please ensure all required fields are complete before continuing.";
var _ErrorMessages = "Please ensure all values are entered in the correct format before continuing.";

// Save messages
var _SavingMsg = "Saving, please wait...";
var _SaveFailed = 'Save failed.  Please try again.';
var _SaveFailedDuplicate = 'Save failed.  Cannot create duplicate records.';
var _SaveFailedNotAll = 'Save failed.  Please try again.';
var _SaveFailedTeamsInUse = 'Save failed.  One of the scheduled teams is already playing on this day.  Please try a different day.';
var _SaveSuccess = 'Save Successful.';

// Delete record messages
var _DelActiveRecord = 'Record cannot be deleted as it is an active record.'; // -2
var _DelDeactivated = 'Record has been deactivated only.'; // -1
var _DelFailed = 'Delete Failed.'; // 0
var _DelSuccess = 'Delete Successful.'; // > 0

// Loading messages
var _Loading = 'Loading data, please wait...';
var _LoadComplete = 'Loading complete';

// Data grid
var _ItemStyle = "dgItemStyle";
var _AltItemStyle = "dgAltStyle";

// Calendar
var months = new Array(13);
months[0] = "Jan";
months[1] = "Feb";
months[2] = "Mar";
months[3] = "Apr";
months[4] = "May";
months[5] = "Jun";
months[6] = "Jul";
months[7] = "Aug";
months[8] = "Sep";
months[9] = "Oct";
months[10] = "Nov";
months[11] = "Dec";

var weekday = new Array(7);
weekday[0] = "Sun";
weekday[1] = "Mon";
weekday[2] = "Tue";
weekday[3] = "Wed";
weekday[4] = "Thu";
weekday[5] = "Fri";
weekday[6] = "Sat";

// ENUM's
var _Leagues = {
    Coed: 0,
    Mens: 1,
    Womens: 2
}

var _AddressBookType = {
    Player: 0,
    Umpire: 1
}

var _ContactType = {
    Primary: 0,
    Secondary: 1
}

var _AdType = {
    BannerAd: 0,
    SideAd: 1
}

var _AccessLevels = {
    None: 0,
    TeamContact: 1,
    Admin: 2
}
//===========================================================================
//===========================================================================
function BuildAddress(address1, address2, city, province, postal) {
    var returnvalue = '';

    // Address 1
    if (address1 != '')
        returnvalue += address1;

    // Address 2
    if (address2 != '') {
        if (returnvalue != '')
            returnvalue += ', ';
        returnvalue += address2;
    }
    
    // City
    if (city != '') {
        if (returnvalue != '')
            returnvalue += ', ';
        returnvalue += city;
    }

    // Prov
    if (province != '') {
        if (returnvalue != '')
            returnvalue += ', ';
        returnvalue += province;
    }

    // Postal
    if (postal != '') {
        if (returnvalue != '')
            returnvalue += ', ';
        returnvalue += postal;
    }

    return returnvalue;
}
//===========================================================================
//===========================================================================
function CheckParameter(variable, defaultvalue) {
    if (variable == undefined)
        variable = defaultvalue;

    return variable;
}
//===========================================================================
//===========================================================================
function CheckRequiredFields() {
    var returnvalue = true;

    for (var i = 0; i < RequiredFields.length; i++) {
        var type = document.getElementById(RequiredFields[i]).type;
        var value;
        
        // Check the different types
        switch (type) {
            case 'select-one':
                value = 0;
                break;
            default:
                value = '';
        }

        // Check the value of the required field
        if (document.getElementById(RequiredFields[i]).value == value) {
            returnvalue = false;
        }
        
        // Check if we are successful
        if (returnvalue == false) {
            // Display the error message
            setInnerText(document.getElementById('lblError'), _RequiredIncomplete);
            ResizeIFrame(_iFrameCntrl);
            break;
        }
    }
        
    // Return if it was a success or not    
    return returnvalue;
}
//===========================================================================
//===========================================================================
function CheckErrorMessages() {
    var returnvalue = true;

    for (var i = 0; i < ErrorMessages.length; i++) {
        // Is the value of the object empty?
        if (document.getElementById(ErrorMessages[i]).style.display == 'inline') {
            // Display the error message
            setInnerText(document.getElementById('lblError'), _ErrorMessages);
            ResizeIFrame(_iFrameCntrl);
            returnvalue = false;

            // Set the value of i so that we exit the loop
            i = ErrorMessages.length;
        }
    }

    // Return if it was a success or not    
    return returnvalue;
}
//===========================================================================
//===========================================================================
// CREATEOPTION - will create an OPTION object with specified values
function createOption(value, text, selected) {
    // Check the paramter
    if (selected == undefined)
        selected = false;
        
    // Create a new Drop Down option
    var newOption = document.createElement('option');
    newOption.value = value;
    newOption.text = text;

    if (selected == true)
        newOption.setAttribute("selected", "selected");
        
    // Return the newly created object
    return newOption;
};
//===========================================================================
//===========================================================================
// ADDOPTION - will add the option item to the drop down list
function addOption(ddl, option) {
    // Try to add it to the list
    try {
        ddl.add(option, null); // standards compliant; doesn't work in IE
    }
    catch (ex) {
        ddl.add(option); // IE only
    }
};
//===========================================================================
//===========================================================================
// This method will take the object name and element and remove all rows that
// currently exist within it.
function ClearRows(sObjectName, sElementName) {
    // Find the grid in question and determine how many rows currently exist
    var _Tbl = document.getElementById(sObjectName).getElementsByTagName(sElementName)[0];
    var _Rows = _Tbl.rows.length;

    // For each row in the grid, delete it
    for (var ii = (_Rows - 1); ii > -1; ii--) {
        _Tbl.deleteRow(ii);
    }
}
//===========================================================================
//===========================================================================
// This method will take the drop down list and remove all options that
// currently exist within it.
function ClearDDL(ddl) {
    var len = ddl.length

    for (var i = 0; i < len; i++)
        ddl.removeChild(ddl.options[0]);
}
//===========================================================================
//===========================================================================
// This method will return the current date
function GetDate(d) {
    return (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
}
//===========================================================================
//===========================================================================
function GetSQLDate(d) {
    return GetDate(new Date(d.substr(0, 10).replace(/-/g, '/')))
}
//===========================================================================
//===========================================================================
function GetSQLCalendarDate(d) {
    return getCalendarDate(new Date(d.substr(0, 10).replace(/-/g, '/')))
}
//===========================================================================
//===========================================================================
function getCalendarDate(d) {
    var monthnumber = d.getMonth();
    var monthname = months[monthnumber];
    var monthday = d.getDate();
    var year = d.getYear();
    var dayofweek = weekday[d.getDay()];

    if (year < 2000) { year = year + 1900; }

    var dateString = dayofweek + ' ' + monthname + ' ' + monthday + ', ' + year;
    return dateString;
}
//===========================================================================
//===========================================================================
// This method will return the current date
function GetTodaysDate() {
    return GetDate(new Date());
}
//===========================================================================
//===========================================================================
// This method will convert the string to an XML object
// Note: Internet Explorer uses the loadXML() method to parse an XML string, 
// while other browsers use the DOMParser object.
function StringtoXML(text) {
    var xmlDoc;
    
    if (window.DOMParser) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(text, "text/xml");
    }
    else // Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(text);
    } 
    
    // Return the XML Document
    return xmlDoc;
}
//===========================================================================
//===========================================================================
// This method will convert the string to an XML object
// Note: The web page and the XML file it tries to load, 
// must be located on the same server.
function LoadXMLDocument(file) {
    var xmlDoc;
    var XMLHttp;
    
    // Create XMLHttp Object
    if (window.XMLHttpRequest) {
        XMLHttp = new XMLHttpRequest();
    }
    else // Internet Explorer 5/6
    {
        XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    // Open the XMLHttp Object
    XMLHttp.open("GET", file, false);
    
    // Send an XMLHttp Request to the server
    XMLHttp.send("");

    // Set the response as an XML DOM Object
    xmlDoc = XMLHttp.responseXML;

    // Return the XML Document
    return xmlDoc;
}
//===========================================================================
//===========================================================================
// This method will convert the string to an XML object
function OpenWindow(page, modal, args, features) {
    if (modal == undefined)
        modal = false;

    if (modal == true)
        window.showModalDialog(page, ((args == undefined) ? '' : args), ((features == undefined) ? '' : features));
    else
        window.open(page);
}
//===========================================================================
//===========================================================================
// This method will resize an iFrame's height based on its source
function ResizeIFrame(frameID) {
    try {
        // Create an offset
        var iframe;
        var min = screen.height-450;
        var hOffset = 20;

        // Get the iFrame Control
        iframe = document.getElementById(frameID);
        
        if (iframe == null)
            iframe = window.parent.document.getElementById(frameID);
        
        // Find the height of the internal page
        var Height = iframe.contentWindow.document.body.scrollHeight;

        if (Height < min)
            Height = min;

        // Change the height of the iFrame
        iframe.height = (Height + hOffset);
    }
    //An error is raised if the IFrame domain != its container's domain
    catch (e) {
        window.status = 'Error: ' + e.number + '; ' + e.description;
    }
}
//===========================================================================
//===========================================================================
// This method will be used to Set Cookies via Javascript
function setCookie(c_name, value, expiremins) {
    // Create a new date for the expiry
    var exdate = new Date();
    document.cookie = value;
    // Increase the expiry time by a matter of minutes
    exdate.setTime(exdate.getTime() + (expiremins * 1000 * 60));

    // Write the cookie to file.
    // Set the value, expiry date, path that it is to be written (Root folder)
    document.cookie = c_name + "=" +
        escape(value) + ((expiremins == null) ? "" : ";expires=" + exdate.toGMTString()) 
        + (('/') ? ";path=" + '/':"");
}
//===========================================================================
//===========================================================================
// This method will be used to Get Cookies via Javascript
function getCookie(c_name) {
    // Do we have any cookies?
    if (document.cookie.length > 0) {
        // Find the cookie itself
        c_start = document.cookie.indexOf(c_name + "=");
        
        // If found, parse out the details
        if (c_start != -1) {
            // Find the starting position
            c_start = c_start + c_name.length + 1;
            
            // Find the ending position
            c_end = document.cookie.indexOf(";", c_start);
            
            // If no end exists, grab the end of file position
            if (c_end == -1) c_end = document.cookie.length;
            
            // Return the cookie value
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }

    // Return a blank value if nothing found
    return "";
}
//===========================================================================
//===========================================================================
// This method will be used to Get Cookies via Javascript
// this deletes the cookie when called
function removeCookie(name) {
    if (getCookie(name)) {
        //document.cookie = name + "=" + ((path) ? ";path=" + '/' : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
        document.cookie = name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}
//===========================================================================
//===========================================================================
// This method is used to check to see if a page is being accessed on it's own
// If accessed on it's own, write the file name to a cookie and launch the main
// page
function CheckPage(ParentLocation, MyLocation) {
    // If they are the same, the page is being called directly
    if (ParentLocation == MyLocation) {
        // Write the page that is to be loaded to a cookie.  Valid for 1 minute
        setCookie(_iFramePage, MyLocation, _CookieExpiry);

        // Launch the main page
        if (MyLocation.indexOf('Public') > 0)
            window.parent.location = '../' + _MainPage;
        else
            window.parent.location = _MainPage;
    }
}
//===========================================================================
//===========================================================================
function LoadDashboard(abcd) {
    //var _Access = window.parent.GetAccessLevel();
    //var _page = '';
    
    // Which dashboard?
//    switch (_Access) {
//        case 2:
//            _page = './Forms/AdminDashboard.aspx';
//            break;
//        default:
//            _page = './Forms/TeamAdminDashboard.aspx';
//    }

    // Load the page
    LoadIFrame('./Forms/AdminDashboard.aspx', true);
}
//===========================================================================
//===========================================================================
// This method will display the page in the iFrame
function LoadIFrame(_src, _parent) {
    var _page;
    
    // Find the page via a cookie
    if (_src == undefined) {
        _src = getCookie(_iFramePage);
        removeCookie(_iFramePage);
    }
    //else
    //setCookie(_iFramePage, _src, _CookieExpiry);

    // Determine the page to use
    if (_src != "")
        _page = _src;
    else
        _page = _DefaultPage;

    if (_parent == undefined)
        _parent = false;

    // Set the page
    if (window.parent.GetAccessLevel(window.parent.getFileName(_page)) != -1) {
        if (_parent) {
            window.parent.document.getElementById(_iFrameCntrl).src = _page;
        }
        else {
            document.getElementById(_iFrameCntrl).src = _page;
        }
    }
    else
        alert(_AccessDenied);
}
//===========================================================================
//===========================================================================
// This method is used to attach a focus to all input for CSS purposes
function sfFocus() {
    var sfEls = document.getElementsByTagName("INPUT");
    for (var i = 0; i < sfEls.length; i++) {
        sfEls[i].onfocus = function() {
            this.className += " sffocus";
            this.select();
        }
        sfEls[i].onblur = function() {
            this.className = this.className.replace(new RegExp(" sffocus\\b"), "");
        }
    }
}
//===========================================================================
//===========================================================================
// This method is used to execute a button click upon hitting enter in a textbox.
// For each textbox to have this execute you need to use the line of code below:
// <Textbox>.Attributes.Add("OnKeyPress", "return clickButton(event, '<ButtonName>')"); 
function clickButton(e, buttonid) {
    var evt = e ? e : window.event;
    var bt = document.getElementById(buttonid);

    if (bt) {
        if (evt.keyCode == 13) {
            bt.onclick();
            return false;
        }
    }
}
//===========================================================================
//===========================================================================
function WebServiceFailure(x) {
    try {
        setInnerText(document.getElementById('lblError'), x._message + ' - ' + x._stackTrace);
    }
    catch (oc) {
        alert(x._message + ' - ' + x._stackTrace);
    }
}
//===========================================================================
//===========================================================================
// This method will return the selection between Active, Inactive, All
// Radio buttons
function GetActiveRadioSelection() {
    var _act = document.getElementById('btnActive').checked;
    var _inact = document.getElementById('btnInactive').checked;
    var _all = document.getElementById('btnAll').checked;

    switch (true) {
        case _act:
            return 1;
            break;
        case _inact:
            return 0;
            break;
        case _all:
            return -1;
            break;
    }
}
//===========================================================================
//===========================================================================
// This method is used to populate a list of the leagues into a drop down list
function GetLeagues(_DDL, selected) {
    var ddl = document.getElementById(_DDL);
    var defaultleague = _DefaultLeague;

    if (selected != undefined)
        defaultleague = selected;
        
    // Iterate through the table and add HTML Rows & contents into it.
    for (var i = 0; i < 2; i++) {
        // Add it to the list
        addOption(ddl, createOption(i, GetLeagueName(i), (i == defaultleague)));
    }
}
//===========================================================================
//===========================================================================
// This method is used to populate a list of the leagues into a drop down list
function GetABType(_DDL) {
    var ddl = document.getElementById(_DDL);

    // Iterate through the table and add HTML Rows & contents into it.
    for (var i = 0; i < 2; i++) {
        var text;

        // Find the caption for this option
        switch (i) {
            case 1:
                text = "Umpire";
                break;
            default:
                text = "Player";
        }

        // Add the option
        addOption(ddl, createOption(i, text, (i == 0)));
    }
}
//===========================================================================
//===========================================================================
// This method is used to populate a list of the leagues into a drop down list
function GetContactType(_DDL) {
    var ddl = document.getElementById(_DDL);

    // Iterate through the table and add HTML Rows & contents into it.
    for (var i = 0; i < 2; i++) {
        var text;

        // Find the caption for this option
        switch (i) {
            case 0:
                text = "Primary";
                break;
            default:
                text = "Secondary";
        }

        // Add the option
        addOption(ddl, createOption(i, text, (i == 0)));
    }
}
//===========================================================================
//===========================================================================
// This method is used to populate a list of the leagues into a drop down list
function GetAdType(_DDL) {
    var ddl = document.getElementById(_DDL);

    // Iterate through the table and add HTML Rows & contents into it.
    for (var i = 0; i < 2; i++) {
        var text;

        // Find the caption for this option
        switch (i) {
            case 1:
                text = "Side Ad";
                break;
            default:
                text = "Banner Ad";
        }

        // Add the option
        addOption(ddl, createOption(i, text, (i == 0)));
    }
}
//===========================================================================
//===========================================================================
function GetLeagueName(league) {
    switch (parseFloat(league)) {
        case _Leagues.Womens:
            return 'Womens';
            break;
        case _Leagues.Mens:
            return 'Mens';
            break;
        case _Leagues.Coed:
            return 'Coed';
            break;
        default:
            return '';            
    }
}
//===========================================================================
//===========================================================================
function GetABTypeName(addressbook) {
    switch (parseFloat(addressbook)) {
        case _AddressBookType.Player:
            return 'Player';
            break;
        case _AddressBookType.Umpire:
            return 'Umpire';
            break;
        default:
            return '';
    }
}
//===========================================================================
//===========================================================================
function GetContactTypeName(contact) {
    switch (parseFloat(contact)) {
        case _ContactType.Primary:
            return 'Primary';
            break;
        case _ContactType.Secondary:
            return 'Secondary';
            break;
        default:
            return '';
    }
}
//===========================================================================
//===========================================================================
function GetAdTypeName(ad) {
    switch (parseFloat(ad)) {
        case _AdType.BannerAd:
            return 'Banner Ad';
            break;
        case _AdType.SideAd:
            return 'Side Ad';
            break;
        default:
            return '';
    }
}
//===========================================================================
//===========================================================================
function LoadDDL(cmd, parmlist, ddl) {
    var parameters = '';

    // Cycle through the parameter list
    if (typeof (parmlist) == 'object') {
        for (var i = 0; i < parmlist.length; i++) {
            parameters += parmlist[i] + ', ';
        }
    }
    else {
        parameters = parmlist + ', ';
    }
    
    // Build the command
    var command = cmd + "(" + parameters + "PopulateDDL, WebServiceFailure, '" + ddl + "')";
    
    // Execute the command
    setTimeout(command, 1);
}
//===========================================================================
//===========================================================================
function PopulateDDL(sXML, ddl) {
    var xmlObject = StringtoXML(sXML);
    var _XML = xmlObject.getElementsByTagName("Table");
    var _DDL = document.getElementById(ddl);

    // Clear the DDL
    //_DDL.length = 0;
    ClearDDL(_DDL);
    
    // Make sure that there is information to add
    if (_XML.length > 0) {
        // Iterate through the table and add HTML Rows & contents into it.
        for (var i = 0; i < _XML.length; i++) {
            var selected;
            
            // Get the properties
            var text = getNodeText(_XML[i], "Description");
            var value = getNodeText(_XML[i], "ID");
            
            // Check to see if this record is selected
            try {
                selected = (getNodeText(_XML[i], "Selected") === 'true');
            }
            catch (e) {
                if (i == 0)
                    selected = true;
                else
                    selected = false;
            }
            
            // Add the option
            addOption(_DDL, createOption(value, text, selected));
        }
    }
}
//===========================================================================
//===========================================================================
// Check the browser and determine how we are to get the text from
// the XML node objects
function checkBrowser() {
    hasTextContent = (document.getElementsByTagName('body')[0].textContent != undefined) ? true : false;
    browserType = whichBrowser();
}
//===========================================================================
//===========================================================================
// Determine which browser we are using
function whichBrowser() {
    var agt = navigator.userAgent.toLowerCase();

    if (agt.indexOf("opera") != -1) return 'Opera';
    if (agt.indexOf("staroffice") != -1) return 'Star Office';
    if (agt.indexOf("webtv") != -1) return 'WebTV';
    if (agt.indexOf("beonex") != -1) return 'Beonex';
    if (agt.indexOf("chimera") != -1) return 'Chimera';
    if (agt.indexOf("netpositive") != -1) return 'NetPositive';
    if (agt.indexOf("phoenix") != -1) return 'Phoenix';
    if (agt.indexOf("firefox") != -1) return 'Firefox';
    if (agt.indexOf("safari") != -1) return 'Safari';
    if (agt.indexOf("skipstone") != -1) return 'SkipStone';
    if (agt.indexOf("msie") != -1) return 'Internet Explorer';
    if (agt.indexOf("netscape") != -1) return 'Netscape';
    if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
    if (agt.indexOf('\/') != -1) {
        if (agt.substr(0, agt.indexOf('\/')) != 'mozilla') {
            return navigator.userAgent.substr(0, agt.indexOf('\/'));
        }
        else return 'Netscape';
    } else if (agt.indexOf(' ') != -1)
        return navigator.userAgent.substr(0, agt.indexOf(' '));
    else return navigator.userAgent;
}
//===========================================================================
//===========================================================================
// Depending on the browser type it dictates how to get the text from the node
// Accept the node as the parameter and return the text
function getNodeText(nodeList, node) {
    if (browserType == undefined)
        checkBrowser();
        
    if (hasTextContent)
        return nodeList.getElementsByTagName(node)[0].textContent;
    else
        return nodeList.getElementsByTagName(node)[0].text;
}
//===========================================================================
//===========================================================================
// Depending on the browser type it dictates how to set the text
// Accept the object as the parameter and set the text
function getInnerText(obj) {
    if (browserType == undefined)
        checkBrowser();

    // Set the text
    if (hasTextContent == true)
        return obj.textContent;
    else
        return obj.innerText;
}
//===========================================================================
//===========================================================================
// Depending on the browser type it dictates how to set the text
// Accept the object as the parameter and set the text
function setInnerText(obj, txt) {
    if (browserType == undefined)
        checkBrowser();

    // Set the text
    if (hasTextContent == true)
        obj.textContent = txt;
    else
        obj.innerText = txt;
}

//===========================================================================
//===========================================================================
function setDdlValue(ddl, value) {
    for (var i = 0; i < ddl.options.length;  i++) {
        if (ddl.options[i].value == value) {
            ddl.options[i].selected = "selected";
            break;
        }
    }
} 
