''/*
 * Utility functions for aiding development with the tibet platform.
 *
 * Categories:
 * - Common utils
 * - String format
 * - IE vs Firefox fixes
 *
 * Usage:
 * <script type="text/javascript" src="/resources/ui/scripts/tibet-utils-0.1.js"></script>
 *
 * @author <a href="mailto:richard.sandstrom@tibetserver.com">Richard Sandström</a>
 * @version $Id: tibet-utils-0.1.js
 */

///////////////////////////
// Common utils
///////////////////////////

/*
* Toggle between two style.display properties for an element
*
* Vaild modes are:
* none, inline, block, list-item, run-in, compact, marker,
* table, inline-table, table-row-group, table-header-group
* table-footer-group, table-row, table-column-group,
* table-column, table-cell, table-caption
*
* Tested with IE6,7 and Firefox 2
* @param id        the id of the element to toggle
* @param mode1     the first mode of the style.display property
* @param mode2     the second mode of the style.display property
* @author <a href="mailto:richard.sandstrom@tibetserver.com">Richard Sandström</a>
*/
function toggleDisplay(id, mode1, mode2) {
    var el = document.getElementById(id);

    if(el.style.display == mode1) {
        el.style.display = mode2;
    } else {
        el.style.display = mode1;
    }
}

///////////////////////////
// String format
///////////////////////////

/*
 * Formats the time field as:
 * H:mm if Hmm is entered
 * HH:mm if HHmm is entered
 * Tested with IE6,7 and Firefox 2
 * @param field     the field to be formated
 * @author <a href="mailto:richard.sandstrom@tibetserver.com">Richard Sandström</a>
 */
function formatTimeField(timeField){
    if(!isNaN(timeField.value)) {
        if(timeField.value.substring(0,1) == "0"){
            timeField.value = timeField.value;
        }

        if(timeField.value.length == 4) {
            timeField.value = timeField.value.substring(0,2) + ":" + timeField.value.substring(2,4);
        } else if(timeField.value.length == 3) {
            timeField.value = timeField.value.substring(0,1) + ":" + timeField.value.substring(1,3);
        }
    }
}

///////////////////////////
// IE vs Firefox fixes
///////////////////////////

/*
 * Gets the x-coordinate of the mouse from the current event
 * Tested with IE6,7 and Firefox 2
 * @param event     (optional) the triggering event
 * @author <a href="mailto:richard.sandstrom@tibetserver.com">Richard Sandström</a>
 */
function mouseX(event) {
    event = getEvent(event);
    if (event.pageX) {
        return event.pageX;
    } else if (event.clientX) {
        return event.clientX + (document.documentElement.scrollLeft ?
                                document.documentElement.scrollLeft :
                                document.body.scrollLeft);
    } else {
        return null;
    }
}

/*
 * Gets the y-coordinate of the mouse from the current event
 * Tested with IE6,7 and Firefox 2
 * @param event     (optional) the triggering event
 * @author <a href="mailto:richard.sandstrom@tibetserver.com">Richard Sandström</a>
 */
function mouseY(event) {
    event = getEvent(event);
    if (event.pageY) {
        return event.pageY;
    } else if (event.clientY) {
        return event.clientY + (document.documentElement.scrollTop ?
                                document.documentElement.scrollTop :
                                document.body.scrollTop);
    } else {
        return null;
    }
}

/*
 * Gets the current event
 * Tested with IE6,7 and Firefox 2
 * @param event     (optional) the triggering event
 * @author <a href="mailto:richard.sandstrom@tibetserver.com">Richard Sandström</a>
 */
function getEvent(event) {
    if (!event) {
        return window.event;
    }
    return event;
}

/*
 * Gets the taget of the current event
 * Tested with IE6,7 and Firefox 2
 * IE uses event.srcElement
 * Firefox uses event.target
 * @param event     (optional) the triggering event
 * @author <a href="mailto:richard.sandstrom@tibetserver.com">Richard Sandström</a>
 */ 
function getEventTarget(event) {
    event = getEvent(event);
    if (!event.target) {  //IE fix
        return event.srcElement;
    }
    return event.target;
}


///////////////////////////
// Validation
///////////////////////////

/**
* checkName
*
* performs the validateFileName check after extracting the filename from the upload path
*
* @param file		the name of the file being checked
*/
function checkName(file) {
    isNixFile = file.indexOf("/") != -1;
    if (isNixFile) {
        fileName = file.substring(file.lastIndexOf("/") + 1, file.length);
    } else {
        fileName = file.substring(file.lastIndexOf("\\") + 1, file.length);
    }
    validateFileName(fileName);
}

/**
* validateFileName
*
* checks that the file has a valid extension
*
* checks that the selected file has a valid name, not including any characters other than a-z, A-Z, 0-9 and _.
* Any characters other than the given will be replaced according to the following schema:
* 						->	a
* 						->	a
* 						->	o
* 				others	->	_
* The cleaned up value is then placed in the fileName field,
* while the original value is placed in the description field.
*
* @param fileName		the name of the file being checked
* todo: make more general
*/
function validateFileName(fileName) {
    var re = new RegExp("[^a-zA-Z0-9\.]" ,"gi");

    // check that the file has a valid extension
    if (fileName != "") {
        var selFile = document.forms["frmUpload"].elements["file"].value;
        var ext = selFile.substring(selFile.lastIndexOf('.'), selFile.length).toLowerCase();
        var extLen = ext.length;

        if (fileName.indexOf('.') == -1) {
            fileName = fileName + ext;
        } else {
            var currentExt = fileName.substr(fileName.length - extLen, extLen + 1);
            if (currentExt != ext) {
                fileName = fileName.substring(0, fileName.length - currentExt.length) + ext;
            }
        }
    }

    // replace forbidden characters
    if (fileName.search(re) > -1) {
        // ,
        var reDef1 = "[" + String.fromCharCode(229) + String.fromCharCode(228) + "]";
        re = new RegExp(reDef1 ,"gi");
        cleanFileName = fileName.replace(re, "a");

        //
        var reDef2 = "[" + String.fromCharCode(246) + "]";
        re = new RegExp(reDef2 ,"gi");
        cleanFileName = cleanFileName.replace(re, "o");

        // others
        re = new RegExp("[^a-z0-9\.]" ,"gi");
        cleanFileName = cleanFileName.replace(re, "_");
    } else {
        cleanFileName = fileName;
    }

    document.forms["frmUpload"].elements["fileName"].value = cleanFileName;
    if (document.forms["frmUpload"].elements["description"].value == "") {
        document.forms["frmUpload"].elements["description"].value = fileName;
    }
}


/**
 * checkDate
 *
 * validates and completes a datestring
 */
function checkDate(elmnt) {
    var dateOK = false;
    var theDate = elmnt.value;
    var re = new RegExp("[1-2][90][0-9][0-9]");				// check that the date has the proper form of YYYY
    var res = theDate.search(re);
    if (res == 0 && theDate.length == 4) {
        dateOK = true;
    }
    re = new RegExp("[1-2][90][0-9][0-9]-[01][0-9]");				// check that the date has the proper form of YYYY-MM
    res = theDate.search(re);
    if (res == 0 && theDate.length == 7) {
        dateOK = true;
    }
    re = new RegExp("[1-2][90][0-9][0-9][01][0-9]");				// check that the date has the proper form of YYYYMM
    res = theDate.search(re);
    if (res == 0 && theDate.length == 6) {
        elmnt.value = theDate.substring(0,4) + "-" + theDate.substring(4,6);
        dateOK = true;
    }
    re = new RegExp("[1-2][90][0-9][0-9]-[01][0-9]-[0-3][0-9]");				// check that the date has the proper form of YYYY-MM-DD
    res = theDate.search(re);
    if (res == 0 && theDate.length == 10) {
        dateOK = true;
    }
    re = new RegExp("[1-2][90][0-9][0-9][01][0-9][0-3][0-9]");				// check that the date has the proper form of YYYYMMDD
    res = theDate.search(re);
    if (res == 0 && theDate.length == 8) {
        elmnt.value = theDate.substring(0,4) + "-" + theDate.substring(4,6) + "-" + theDate.substring(6,8);
        dateOK = true;
    }
    return dateOK;
}