// Metanol -- Meta-directory of local French organizations
// By: Emmanuel Raviart <infos-pratiques-devel@listes.infos-pratiques.org>
//
// Copyright (C) 2009 Easter-eggs & Emmanuel Raviart
// http://wiki.infos-pratiques.org/wiki/Metanol
//
// This file is part of Metanol.
//
// Metanol 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.
//
// Metanol 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 this program.  If not, see <http://www.gnu.org/licenses/>.


// Note: This script reads variables the following variables that must be defined elsewhere:
//   - metanolBaseUrl
//   - metanolBaseWhat
//   - metanolBaseWhere
//   - metanolCss
//   - metanolShowWhatInput
//   - metanolShowWherePath
//   - metanolShowWhereInput
//   - metanolTarget


function adjustGadgetHeight(height) {
    // Parameter height is optional and should not be given in most cases.
    if (typeof gadgets != 'undefined' && top.location != location) {
        if (typeof gadgets.window == 'undefined' || typeof gadgets.window.adjustHeight == 'undefined') {
            _IG_AdjustIFrameHeight(height);
        } else {
            gadgets.window.adjustHeight(height);
        }
    }
}


function checkAndGo(jDialog, node) {
    jDialog.html([
        '<div>',
            '<div class="progress-dialog-notification-area">',
                '<p>Recherche :</p>',
                '<ul>',
                    '<li><strong class="what-search-result"></strong></li>',
                    '<li><strong class="where-search-result"></strong></li>',
                '</ul>',
            '</div>',
            '<div class="progress-dialog-please-wait">',
                '<image alt="" />',
                '<p>Veuillez patienter...</p>',
            '</div>',
        '</div>'
    ].join(''));
    jDialog.find('img').attr('src', metanolBaseUrl + 'static/images/please-wait.gif');
    jDialog.find('.what-search-result').text(node.title);
    jDialog.find('.where-search-result').text(node.territoryTitle);
    jDialog.dialog({draggable: true, modal: true, resizable: true, title: 'Recherche en cours...'});
    adjustGadgetHeight(Math.max(jQuery(document).height(), jDialog.height() + 100));
    requestCheck(jDialog, node);
}


function metanolUrl(args) {
    var pathFragments = [];
    if (args.format) {
        pathFragments.push(args.format);
    }
    if (args.path) {
        // Rempve path of default directory from URL (needed by Metanol-OEM).
        pathFragments.push(metanolDefaultWherePath 
            ? args.path
                .replace(new RegExp('(^|/)' + metanolDefaultWherePath + '$'), '')
                .replace(new RegExp('^' + metanolDefaultWherePath + '($|/)'), '')
                .replace(new RegExp('(^|/)' + metanolDefaultWherePath + '/'), '/')
            : args.path);
    }
    if (args.action) {
        pathFragments.push(args.action);
    }

    var queryParams = {};
    if (args.what) {
        queryParams.what = args.what;
    }
    if (args.where) {
        queryParams.where = args.where;
    }
    // When asked for a dummy URL, generate only a URL that looks good, but without optional arguments, because the URL
    // won't be really used.
    if (!args.dummy && args.format) {
        if (metanolBaseWhat) {
            queryParams.base_what = metanolBaseWhat;
        }
        if (metanolBaseWhere) {
            queryParams.base_where = metanolBaseWhere;
        }
        if (args.format == 'json') {
            if (typeof args.depth == 'number' && args.depth != 1) {
                queryParams.depth = args.depth;
            }
        } else {
            if (metanolCss) {
                queryParams.css = metanolCss;
            }
            if (!metanolShowWhatInput) {
                queryParams.show_what_input = 0;
            }
            if (!metanolShowWhatPath) {
                queryParams.show_what_path = 0;
            }
            if (!metanolShowWhereInput) {
                queryParams.show_where_input = 0;
            }
            if (!metanolShowWherePath) {
                queryParams.show_where_path = 0;
            }
            if (metanolTarget) {
                queryParams.target = metanolTarget;
            }
        }
    }

    var url = metanolBaseUrl + pathFragments.join('/');
    var query = jQuery.param(queryParams);
    if (query) {
        url += '?' + query;
    }
    if (args.format == 'json' && metanolBaseUrl.indexOf(':') >= 0) {
        // This is a JSON URL and metanol server is not the same as the site server => Use jsonp.
        // Note: we can't use jQuery.param for jsonp, because the function replaces "jsonp=?" with "jsonp=%3F".
        url += (query ? '&' : '?') + 'jsonp=?';
    }
    return url;
}


function requestCheck(jDialog, node) {
    var url = metanolUrl({format: 'json', path: node.path, action: 'verification'});
    jQuery.getJSON(url, function (data) {
        if (data === null) {
            jDialog.dialog('close'); // Dialog needs to be closed and open to be centered.
            jDialog.dialog('option', 'title', 'Aucun résultat !');
            jDialog.find('div.progress-dialog-please-wait').hide();
            jDialog.find('.progress-dialog-notification-area > p').text('La recherche a échoué.');
            jDialog.find('.what-search-result').text(node.title);
            jDialog.find('.where-search-result').text(node.territoryTitle);
            jDialog.dialog('open');
            adjustGadgetHeight(Math.max(jQuery(document).height(), jDialog.height() + 100));
        } else if (data.resultsFound) {
            jDialog.dialog('close'); // Dialog needs to be closed and open to be centered.
            jDialog.dialog('option', 'title', 'Résultats trouvés');
            jDialog.find('div.progress-dialog-please-wait').hide();
            jDialog.find('.progress-dialog-notification-area > p').text('Affichage des résultats :');
            jDialog.find('.what-search-result').text(data.title);
            jDialog.find('.where-search-result').text(data.territoryTitle);
            if (data.form) {
                jDialog.append(data.form);
                var jForm = jDialog.children(':last');
                if (metanolTarget == '_blank') {
                    jForm.append("<p>Si les résultats ne s'affichent pas au bout de quelques secondes,"
                        + " cliquez sur le bouton ci-dessous pour les faire apparaître.</p>");
                    jForm.append('<input name="afficher" type="submit" value="Afficher les résultats" />');
                }
                jDialog.dialog('open');
                adjustGadgetHeight(Math.max(jQuery(document).height(), jDialog.height() + 100));
                jForm.attr('target', metanolTarget).submit();
            } else if (metanolTarget) {
                // There seems to be no easy way to do a window.location in _blank or _top target, hence this trick.
                jDialog.append('<form><\/form>');
                jDialog.dialog('open');
                var jForm = jDialog.children(':last');
                jForm.attr('action', data.url).attr('target', metanolTarget);
                if (metanolTarget == '_blank') {
                    jForm.append("<p>Si les résultats ne s'affichent pas au bout de quelques secondes,"
                        + " cliquez sur le bouton ci-dessous pour les faire apparaître.</p>");
                    jForm.append('<input name="afficher" type="submit" value="Afficher les résultats" />');
                }
                jDialog.dialog('open');
                adjustGadgetHeight(Math.max(jQuery(document).height(), jDialog.height() + 100));
                jForm.submit();
            } else {
                jDialog.dialog('open');
                adjustGadgetHeight(Math.max(jQuery(document).height(), jDialog.height() + 100));
                window.location = data.url;
            }
        } else if (data.url) {
            jDialog.dialog('close'); // Dialog needs to be closed and open to be centered.
            jDialog.find('.progress-dialog-notification-area > p').text('Élargissement de la recherche :');
            jDialog.find('.what-search-result').text(data.title);
            jDialog.find('.where-search-result').text(data.territoryTitle);
            jDialog.dialog('open');
            adjustGadgetHeight(Math.max(jQuery(document).height(), jDialog.height() + 100));
            requestCheck(jDialog, data);
        }
        else {
            jDialog.dialog('close'); // Dialog needs to be closed and open to be centered.
            jDialog.dialog('option', 'title', 'Aucun résultat !');
            jDialog.find('div.progress-dialog-please-wait').hide();
            jDialog.find('.progress-dialog-notification-area > p').text('La recherche a échoué.');
            jDialog.find('.what-search-result').text(node.title);
            jDialog.find('.where-search-result').text(node.territoryTitle);
            jDialog.dialog('open');
            adjustGadgetHeight(Math.max(jQuery(document).height(), jDialog.height() + 100));
        }
    });
}

