// Prototype required for IE8 compatibility
if (!String.prototype.trim) {
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };
}

// Extract the value of a GET parameter set in the URL
function parseURL(val, defaultVal) {
    var result = defaultVal;
    var urlParam = window.location.search;
    if (urlParam != '') {
        paramArray = urlParam.substr(1).split("&");
        for (var i = 0; i < paramArray.length; i++) {
            var tmpArray = paramArray[i].split("=");
            if ((tmpArray.length === 2) && (tmpArray[0] === val)) {
                result = decodeURIComponent(tmpArray[1]);
                break;
            }
        }
    }
    return result;
}

// Execute a XOR operation between two boolean values
function XOR(a, b) {
    return (a || b) && !(a && b);
}

// Check if mandatory fields are empty
function isMandatoryFieldEmpty(aFieldName) {
    return isEmptyFieldMaybeMandatory(aFieldName, true);
}

// Check if fields are empty (it's ok, they are not mandatory, so will not be given focus)
function isOptionalFieldEmpty(aFieldName) {
    return isEmptyFieldMaybeMandatory(aFieldName, false);
}

/*
// Check if optional view is checked
function isOptionalViewChecked(aFieldName) {
    return isEmptyFieldMaybeMandatory(aFieldName, true);
}
*/

// Check if fields are empty. If empty field is mandatory, will give focus
function isEmptyFieldMaybeMandatory(aFieldName, mandatory) {
    var isEmpty = false;

    var currentObj = document.getElementById(aFieldName);
    if (currentObj == null) { // Can't locate the field!
        parent.Dialog("Erreur", "Champ inconnu - ID = " + aFieldName);
        isEmpty = true;
    }

    if (currentObj.value.trim() == '') {
        // Field exist but is empty: give focus if mandatory
        if (mandatory) {
            currentObj.focus();
        }
        isEmpty = true;
    }

    return isEmpty;
}

// Check if field value is numeric
function isNumber(aFieldName) {
    var isNumberFormat = false;
    var currentObj = document.getElementById(aFieldName);
    if (currentObj.value == parseInt(currentObj.value) + "") {
        isNumberFormat = true;
    }
    return isNumberFormat;
}

// Form submission and prerequisite checks
function sendForm(targetUrl) {
    if (checkForm()) {
        /* Display loading bar and hide buttons */
        document.getElementById("loading").style.display = '';
        document.getElementById("btZone").style.display = 'none';

        PostForm(targetUrl, "reportQueryForm");
    }
}

// Callback method after AJAX request
function ServerResponseForPostForm() {
    if (objPostRequest.readyState === 4) {
        if (objPostRequest.status === 200) {
            var queryResponse = JSON.parse(objPostRequest.responseText);

            if (queryResponse.status === "success") {
                parent.Dialog("Confirmation", queryResponse.success);
            } else {
                parent.Dialog("Erreur", queryResponse.error);
            }
        } else if (objPostRequest.status === 500) {
            parent.Dialog("Erreur", "Erreur interne du serveur d&eacute;tect&eacute;e.");
        } else {
            parent.Dialog("Erreur", "La connexion avec le site semble interrompue.");
        }

        /* Display buttons and hide loading bar */
        document.getElementById("loading").style.display = 'none';
        document.getElementById("btZone").style.display = '';
    }
}

// Create the default date picker
var picker;
function initPicker(pickerId, containerId) {
    new Pikaday({
        field : document.getElementById(pickerId),
        firstDay : 1,
        minDate : new Date('2000-01-01'),
        maxDate: new Date('2030-12-31'),
        yearRange: [2000, 2030],
        bound : true,
        container : document.getElementById(containerId)
    });
}

// Try to close the current browser
function closeWindow() {
    if (self === top) {
        /* Closing instruction when the current window is not an IFRAME */
        window.close();
    } else {
        /* Closing instruction when the current window is an IFRAME */
        parent.window.close();
    }
}

// Clear all fields from a form
function clearForm(formId) {

    var objForm = document.getElementById("reportQueryForm");
    var formElArray = objForm.elements;

    /* Browse each field and clear its content */
    for (var i = 0; i < formElArray.length; i++) {
        field_type = formElArray[i].type.toLowerCase();
        switch (field_type) {
        case "text":
        case "password":
        case "textarea":
        case "hidden":
            formElArray[i].value = "";
            break;
        case "radio":
        case "checkbox":
            if (formElArray[i].checked) {
                formElArray[i].checked = false;
            }
            break;
        case "select-one":
        case "select-multi":
            formElArray[i].selectedIndex = -1;
            break;
        default:
            break;
        }
    }
}
