/**
____________________________________________________________________
Copyright 2009-2011 NeoDoc SARL

This file is part of Calenco.

   Calenco is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as
   published by the Free Software Foundation, either version 3 of
   the License, or (at your option) any later version.

   Calenco is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public
   License along with Calenco.  If not, see
   http://www.gnu.org/licenses/

____________________________________________________________________
*/

/**
 * This assumes the following:
 * <ol>
 *   <li>dojo 1.6+ is already loaded, make sure you load dojo first.</li>
 *   <li>there's a nlsUI object defined having all i18n strings as properties</li>
 * </ol>
 */
dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");

/**
 * Ticket #155 and Ticket #181
 * Firefox (only known browser at this time) submits automatically a form
 * containing only one input when the ENTER key is pressed. This leads
 * to unexpected and annoying behaviour.
 */
function enterKeyValidates(evt, formdijit) {
    if (evt.keyCode == dojo.keys.ENTER) {
        evt.preventDefault();
        return formdijit.validate();
    }
    return true;
}

/**
 * Check provided passwords match
 */
function checkPassMatch(npass, vpass) {
    return (npass.value == vpass.value);
}

/**
 * Check if the given string ends with the given suffix
 */
function endsWith(string, suffix) { return new RegExp(suffix+"$").test(string); }

/**
 * Check if the given string starts with the given prefix
 */
function startsWith(string, prefix) { return new RegExp("^"+prefix).test(string); }

/**
 * Check if the given object is an array.
 * Taken from http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
 */
function isArray(testObject) {
    return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}

/**
 * Trims the given string to the given length. If the string is to be trimmmed
 *  (that is, its length is greater than the desired maximum length), then
 *  ellipsis are put in the 'middle' of the trimmed string.
 */
function trimString(string /* The String to trim */, maxLength /* Desired length for the trimmed string */) {
    var sl = string.length;
    if (sl <= maxLength) {
        return string; // Leave as is
    }
    var index = (maxLength - 3) / 2;
    return (string.slice(0, index) + '...' + string.slice(-index));
}

/**
 * Hides the circling 'loading' div
 */
function hideLoader(loaderDiv, mainDiv) {
    dojo.fadeOut({
        node: loaderDiv,
        duration: 1000/*msec*/,
        onEnd: function() {
            dojo.style(loaderDiv, "display", "none");
            var _mainDijit = dijit.byId(mainDiv);
            if (_mainDijit) {
                _mainDijit.resize(); // Quick hack to have 1st tab title display fully, thanks kgf!
            }
        }
    }).play();
}

/**
 * Info dialog
 */
function infoDialog(theTitle, msg) {
    var dlg = new dijit.Dialog({title: theTitle});
    var contDiv = dojo.create('div', {style: {width: '500px'}});
    var msgDiv = dojo.create('div', {'class': 'info'}, contDiv);
    dojo.create("div", {'class': 'admon', innerHTML: "<img src='/res/img/dlg-info.png' alt='" + nlsUI.lbl_info +"' />"}, msgDiv);
    dojo.create("div", {'class': 'msg', innerHTML: msg}, msgDiv);
    var btnDiv = dojo.create('div', {'class': 'brow'}, contDiv);
    new dijit.form.Button({label: nlsUI.btn_close, onClick: function() {dlg.hide();}}).placeAt(btnDiv);
    dlg.set('content', contDiv);
    var handle = dojo.connect(dlg, 'hide', function() {dojo.disconnect(handle);setTimeout(function(){dlg.destroyRecursive();}, dlg.duration + 100);});
    dlg.show();
}

/**
 * Error dialog
 */
function errorDialog(theTitle, msg, response) {
    var dlg = new dijit.Dialog({title: theTitle});
    var contDiv = dojo.create('div', {style: {width: '400px'}});
    var msgDiv = dojo.create('div', {'class': 'error'}, contDiv);
    dojo.create('div', {'class': 'admon', innerHTML: "<img src='/res/img/dlg-err.png' alt='" + nlsUI.lbl_err + "' />"}, msgDiv);
    dojo.create('div', {'class': 'msg', innerHTML: (msg != null ? msg : response.responseText + '\n[HTTP Status: ' + response.status + ']')}, msgDiv);
    var btnDiv = dojo.create('div', {'class': 'brow'}, contDiv);
    new dijit.form.Button({label: nlsUI.btn_close, onClick: function() {dlg.hide();}}).placeAt(btnDiv);
    dlg.set('content', contDiv);
    var handle = dojo.connect(dlg, 'hide', function() {dojo.disconnect(handle);setTimeout(function(){dlg.destroyRecursive();}, dlg.duration + 100);});
    dlg.show();
}

/**
 * Warning dialog
 */
function warnDialog(theTitle, msg) {
    var dlg = new dijit.Dialog({title: theTitle});
    var contDiv = dojo.create('div', {style: {width: '400px'}});
    var msgDiv = dojo.create('div', {'class': 'warn'}, contDiv);
    dojo.create("div", {'class': 'admon', innerHTML: "<img src='/res/img/dlg-warn.png' alt='" + nlsUI.lbl_warn +"' />"}, msgDiv);
    dojo.create("div", {'class': 'msg', innerHTML: msg}, msgDiv);
    var btnDiv = dojo.create('div', {'class': 'brow'}, contDiv);
    new dijit.form.Button({label: nlsUI.btn_close, onClick: function() {dlg.hide();}}).placeAt(btnDiv);
    dlg.set('content', contDiv);
    var handle = dojo.connect(dlg, 'hide', function() {dojo.disconnect(handle);setTimeout(function(){dlg.destroyRecursive();}, dlg.duration + 100);});
    dlg.show();
}

/**
 * Generic Yes/No confirmation dialog with a callback on Yes, and cancelling on
 *  No.
 */
function confirmDialog(theTitle, width, msg, okCallback) {
    var dlg = new dijit.Dialog({title: theTitle});
    var contDiv = dojo.create('div', {style: {width: width}});
    var msgDiv = dojo.create('div', {'class': 'info'}, contDiv);
    dojo.create('div', {'class': 'admon', innerHTML: '<img src="/res/img/dlg-info.png" alt="' + nlsUI.lbl_info + '" />'}, msgDiv);
    dojo.create('div', {'class': 'msg', innerHTML: msg}, msgDiv);
    var btnDiv = dojo.create('div', {'class': 'brow'}, contDiv);
    new dijit.form.Button({label: nlsUI.btn_yes, onClick: function() {okCallback();dlg.hide();}}).placeAt(btnDiv);
    new dijit.form.Button({label: nlsUI.btn_no, onClick: function() {dlg.hide();}}).placeAt(btnDiv);
    dlg.set('content', contDiv);
    var handle = dojo.connect(dlg, 'hide', function() {dojo.disconnect(handle);setTimeout(function(){dlg.destroyRecursive();}, dlg.duration + 100);});
    dlg.show();
}

/**
 * Logout
 */
function logout() {
    dojo.xhrPost({
        url: "/system/logout",
        user: "bogus@calenco.com",
        password: "bogus",
        content: {user: "bogus@calenco.com", password: "bogus"},
        handle: function(response, ioArgs) {
            if (ioArgs.xhr.status == 401) {
                window.location = "/static/logged-out";
            } else {
                console.log("Cannot logout!", response, ioArgs);
            }
            return response;
        }
    });
}

/**
 * Shut Calenco server down, only SA is able to perform this
 */

function shutServerDown() {
    var dlg = new dijit.Dialog({title: nlsUI.dlg_shut_title});
    var contDiv = dojo.create('div', {style: {width: '400px'}});
    var msgDiv = dojo.create('div', {'class': 'warn'}, contDiv);
    dojo.create('div', {'class': 'admon', innerHTML: "<img src='/res/img/dlg-warn.png' alt='" + nlsUI.lbl_warn + "' />"}, msgDiv);
    dojo.create('div', {'class': 'msg', innerHTML: nlsUI.dlg_shut_msg}, msgDiv);
    var btnDiv = dojo.create('div', {'class': 'brow'}, contDiv);
    dojo.create('button', {id: 'shut.yes', dojoType: 'dijit.form.Button', innerHTML: nlsUI.dlg_shut_yes}, btnDiv);
    dojo.create('button', {id: 'shut.no', dojoType: 'dijit.form.Button', innerHTML: nlsUI.dlg_shut_no}, btnDiv);
    dlg.set('content', contDiv);
    var handle = dojo.connect(dlg, 'hide', function() {dojo.disconnect(handle);setTimeout(function(){dlg.destroyRecursive();}, dlg.duration + 100);});
    var nhandle = dojo.connect(dijit.byId('shut.no'), 'onClick', function() {dojo.disconnect(nhandle);dlg.hide();});
    var yhandle = dojo.connect(dijit.byId('shut.yes'), 'onClick', function() {
        dojo.disconnect(yhandle);
        dlg.hide();
        window.location = '/static/server-shutdown';
        dojo.xhrPost({
            url: '/system/control/shutdown',
            handle: function(response) {
                return response;
            }
        });
    });
    dlg.show();
}

