﻿// Icon utilisé pour chaque point de la carte
var _Icon = new GIcon(G_DEFAULT_ICON);
_Icon.image = "images/icon.png";
_Icon.iconAnchor = new GPoint(15, 15); // permet de recentrer les puces
_Icon.infoWindowAnchor = new GPoint(0, 0);
_Icon.shadow = ""; // vire l'ombre
_Icon.iconSize.height = 30;
_Icon.iconSize.width = 30;

var formControls;
var map;

// Combox du menu
var comboInstr;
var comboPeuples;
var comboInstitutions;
var comboLocs;


// objet utilisé en cas de failure lors d'une recherche
var _objRequest;

// Cet objet contiendra l'historique des recherches (les id de sessions de recherche)
var Historique = [];
var HistoriqueNext = [];

/*
* Relance la recherche via l'objet récupéré de la derniere failure
*/
function Retry() {
    Ext.Ajax.request(_objRequest);
}

/*
* Méthode appelée lors d'une failure lors d'une requete ajax
* Propose à l'utilisateur de reprendre là où il s'était arrêté
*/
function RequestFailure(resp, objRequest) {
    _objRequest = objRequest;

    document.getElementById('searchInProgress').style.display = 'none'; ;
    document.getElementById('LabelLocEnCours').innerHTML = "Echec lors de la recherche";
    document.getElementById('nbresRight').innerHTML = "<a href='#retry' onClick=\"javascript:Retry();return false;\">Réessayer</a>";
    return;
}

/*
* Méthode permettant de calculer le positionnement correct de l'affichage détaillé d'une notice
*/
function resizeAffichageFull() {
    //alert('begin');
    // je règle la hauteur du pane4
    var taille = $('#noticedetailleebox').css('border', '0px solid green').height(); // taille de la box
    taille = taille - $('#TitreHaut').css('border', '0px solid red').height();
    taille = taille - $('#ExtractDiv').css('border', '0px solid blue').height();
    taille = taille - $('#AlbumDiv').css('border', '0px solid yellow').height();
    taille = taille - 40; // marge

    $('#pane4').height(taille).jScrollPane({ scrollbarOnLeft: true, showArrows: true, scrollbarWidth: 3, scrollbarWidth: 15, arrowSize: 6 });

    $("a.fancy").fancybox({
        'hideOnContentClick': false,
        'frameWidth': 600
    });
    //alert('end');
}

/*
* Méthode permettant de récupérer les résultats d'une localisation
* @idLocClicked : l'id de la localisation cliquée
* @NomLocalisation : le libellé de la localisation cliquée
* @NombreDeRes : le nombre de résultats à afficher
*/
function displayNotices(idLocClicked, NomLocalisation, NombreDeRes) {

    $('#HomePageBox').hide();
    $('#doc').show();
    $('#affichageFull').slideUp('fast');
    $('#displayNotices').slideDown('fast');

    $('#NBRES').val(NombreDeRes);
    
    carousel.clear(); // vide le carrousel actuel

    //$('#tooltips-gmap').remove(); // supprime les markers

    // Affiche le résultat courant
    document.getElementById('LabelLocEnCours').innerHTML = NomLocalisation;

    var libelleResultat = "";

    if (NombreDeRes == "1" || NombreDeRes == "0") {
        libelleResultat = document.getElementById('nbresRight').innerHTML = NombreDeRes + " spectacle";
    } else {
        document.getElementById('nbresRight').innerHTML = NombreDeRes + " spectacles";
    }

    // Affiche le loading en cours
    document.getElementById('searchInProgress').style.display = 'block';
    
    // récupération des informations courantes
    var searchRequest = formControls.item('QUERY').getEl().getValue();
    var instr = comboInstr.getValue();
    var peuples = comboPeuples.getValue();
    var institutions = comboInstitutions.getValue();


    var idNotice = $('#idNotice').text();
    if (idNotice != '') {
        searchRequest = idNotice;
    }

    Ext.Ajax.request({
        url: 'api.ashx?cmd=LaunchQuery',
        success: function(resp) {
            // Je récupère la session
            searchStrCarousel = resp.responseText; // cette valeur est celle surveillée par le carousel
            searchTrips(); // récupération des notices associées
        },
        failure: RequestFailure,
        params: {
            query: searchRequest,
            menuLoc: idLocClicked,
            menuPeuple: peuples,
            menuInstruments: instr,
            menuInstitutions: institutions
        }
    });
}

function str2JScript(s) {
    s = s.replace(/\n/g, '\\n');
    s = s.replace(/\\/g, '\\\\');
    s = s.replace(/'/g, "\\'");
    return s;
}

/*
* Zoom sur le marker en question
*/
function zoomOnIt(obj, NomLocalisation) {

    carousel.clear(); // lorsque l'on zoom, on choisit de vider le carousel
    
    // affichage de la localisation cliquée
    document.getElementById('LabelLocEnCours').innerHTML = NomLocalisation;

    // On relance la recherche
    Ext.getCmp('comboLocs').setValue(obj);
    Ext.getCmp('comboLocs').fireEvent('select');

}

/*
* Cette méthode permet de créer un marker (point à afficher sur la carte)
* @point
* @NomLocalisation : le nom de la localisation à afficher
* @NombreDeRes : le nombre de résultat pour cette ressource
* @hasChild : boolean permettant de choisir si on affiche ou non un zoom
*/
function creerMarker(point, NomLocalisation, NombreDeRes, uid, hasChild) {


    var marker = new GMarker(point, _Icon);


    var panel = "";

    var LibelleNbres = "";

    if (NombreDeRes == "1" || NombreDeRes == "0") {
        LibelleNbres = "1 spectacle";
    } else {
        LibelleNbres = NombreDeRes + " spectacles";
    }

    panel += '<div id="flag-hover">';
    panel += '<table id="table" width="150px" cellpadding="0px" cellspacing="0px" style="background-color : transparent;">';


    panel += '<tr>';
    panel += '<td colspan="3">';
    panel += '<table cellpadding="0px" cellspacing="0px" width="100%" height="100%" style="background-color : transparent;">';
    panel += '<tr style="background-color:#8C2D5C;color:white;font-weight:bold;text-align:center;font-family:Verdana">';
    panel += '<td style="padding:5px">' + NomLocalisation + '</td>';
    panel += '</tr>';
    panel += '<tr style="background-color:#EA670C;color:white;font-weight:bold;text-align:center;font-family:Verdana">';
    panel += "<td><a class='displayRes' href='#displayNotices' title='Afficher les spectacles' onClick=\"javascript:displayNotices(" + uid + ", '" + str2JScript(NomLocalisation) + "', '" + NombreDeRes + "');return false;\">" + LibelleNbres + "</a></td>";
    panel += '</tr>';
    panel += '</table>';
    panel += '</td>';
    panel += '</tr>';

    // Représente la derniere ligne
    panel += '<tr height="37px">';

    // colonne gauche
    panel += '<td width="50%">';
    panel += '<table height="100%"  width="100%" cellpadding="0px" cellspacing="0px" style="background-color : transparent;">';
    panel += '<tr><td style="background-color:#8C2D5C;width:100%;height:24px">&nbsp;</td></tr>';
    panel += '<tr><td style="width:100%;height:16px">&nbsp;</td></tr>';
    panel += '</table>';
    panel += '</td>';

    // loupe au centre
    panel += '<td width="28px">';


    // Si le marker a des enfants, alors on peut zoomer dessus, sinon, non
    if (hasChild) {

        panel += "<a href='#zoom' title='Zoomer sur cette zone' onClick=\"javascript:zoomOnIt(" + uid + ", '" + str2JScript(NomLocalisation) + "');return false;\">";
        panel += '<img src="images/loupe.png"/>';
        panel += "</a>";
    } else {
        panel += '<img src="images/no-loupe.png"/>';
    }

    panel += '</td>';
    panel += '<td width="50%">';
    panel += '<table height="100%"  width="100%" cellpadding="0px" cellspacing="0px" style="background-color : transparent;">';
    panel += '<tr><td style="background-color:#8C2D5C;width:100%;height:24px">&nbsp;</td></tr>';
    panel += '<tr><td style="width:100%;height:16px">&nbsp;</td></tr>';
    panel += '</table>';
    panel += '</td>';
    panel += '</tr>';
    panel += '</table>';
    panel += '</div>';


    // Lors du survol du point avec la souris
    GEvent.addListener(marker, "mouseover", function() {
        marker.openExtInfoWindow(
        map,
        "simple_example_window",
        panel
        ,
        {beakOffset: 3 }
        );
    });

    return marker;
}

/*
* Méthode a
*/
function SynchronizeMap(data) {
	
	
    try {
        // Nettoie la carte
        map.closeExtInfoWindow();
        map.clearOverlays(); // supprime les markers de la carte
    } catch (err) {
        alert(err);
        return;
    }
	
    var json = Ext.decode(data.responseText);

    // Le pere contient les informations pour la vue
    var coordonneesPere = json[0].GPS;
    var lat = coordonneesPere.lat;
    var lng = coordonneesPere.lng;
    var zm = parseInt(coordonneesPere.z);
	
    // On posistionne la carte par rapport au pere
    map.setCenter(new GLatLng(lat, lng), zm);

    // On ajoute tous les markers
    for (var i = 1; i < json.length; i++) {

        var m = json[i];

        var cds = m.GPS;

        var lattitude = cds.lat;
        var longitude = cds.lng;
        var zoom = parseInt(cds.z);

        var point = new GLatLng(parseFloat(lattitude), parseFloat(longitude), parseFloat(zoom));

        // Création du marker
        var marker = creerMarker(point, m.label, m.nb, m.uid, m.hasChild);

        // Ajout
        map.addOverlay(marker);
    }
}

/*
* Méthode appelée lors du chargement de la page
*/
function loadMap() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.disableDoubleClickZoom();
        map.setMapType(G_PHYSICAL_MAP);
        map.setCenter(new GLatLng(33.43144133557529, 14.765625), 2);
    }

    // appelé au chargement de la page
    //console.log('Chargement de la page');
    LaunchSearch(false, true, "*");
}


/*
* Méthode permettant d'afficher les résultats pour une recherche prédéfinie
* @currentId : id de la session de recherche
*/
function displayDataCurrent(currentId, IsHistoryBack) {


    // Appel en Ajax des différents
    Ext.Ajax.request({
        url: 'api.ashx?cmd=GetNbres',
        success: function(respo) {
            var nbres = respo.responseText;

            if (nbres == "1" || nbres == "0") {
                document.getElementById('nbresRight').innerHTML = nbres + " spectacle";
            } else {
                document.getElementById('nbresRight').innerHTML = nbres + " spectacles";
            }

            $('#LabelLocEnCours').hide();
        },
        failure: function(respo) {
            alert(respo.responseText);
        },
        params: {
            id: currentId
        }
    });

    Ext.Ajax.request({
        url: 'api.ashx?cmd=GetMarkers',
        success: function(respo) {
            SynchronizeMap(respo);
        },
        failure: function(respo) {
            alert('Echec de récupération des markers google maps');
        },
        params: {
            id: currentId
        }
    });

    if (carousel != undefined) {

        $('#affichageFull').slideUp('fast');
        $('#displayNotices').slideDown('fast');


        carousel.clear(); // vide le carrousel actuel

        // Je récupère la session
        searchStrCarousel = currentId; // cette valeur est celle surveillée par le carousel

        // récupération des notices associées
        searchTrips();
    }



    //displayChrono(currentId);
    storeInstr.load({ params: { 'id': currentId} });
    storePeuples.load({ params: { 'id': currentId} });
    storeInstitutions.load({ params: { 'id': currentId} });
    storeLocs.load({ params: { 'id': currentId} });


    var canvas = document.getElementById('searchInProgress');
    canvas.style.display = 'none';

    if (b_displayList) {
        //+console.log('On affiche la liste de résultats');
        $('#doc').show();
        //+console.log('On cache la homepage');
        $('#HomePageBox').hide();
    } else if (b_displayHomePage) {
        //+console.log('On cache la liste de résultats');
        $('#doc').hide();
        //+console.log('On affiche la homepage');
        $('#HomePageBox').show();
    } else {
        //+console.log('On cache la liste de résultats');
        $('#doc').hide();
        //+console.log('On cache la homepage');
        $('#HomePageBox').hide();
    }    
}

/*
    * Méthode appelée lors d'un succes sur la recherche
    */
function displayData(resp, IsHistoryBack) {

    // Récupération de la session
    var currentId;

    //console.log("Is History Back :");
    //console.log(IsHistoryBack);

    if ((typeof (IsHistoryBack) != "boolean")) {
        currentId = resp.responseText;
        // sauvegarde la session
        //console.log('push : ' + currentId);
        HistoriqueNext = []; // on vide l'historique "suivant" lors de chaque recherche
        Historique.push(currentId);
    } else {
        currentId = resp;
    }

	displayDataCurrent(currentId, IsHistoryBack);
}

/*
* Reviens d'un pas en arrière
*/
var IsFirstPopAfterRequest = false;
function GoBack() {

    //??
    IsFirstPopAfterRequest = false;
    
    if (IsFirstPopAfterRequest) {
        Historique.pop();
    }

    IsFirstPopAfterRequest = false;

    if (Historique.length == 0) {
        return;
    }
    var idsession = Historique.pop();

    if (idsession != undefined) {
        displayData(idsession, true);
    }
}

function GoNext() {
    var idsession = HistoriqueNext.pop();
}


var b_displayList = false;
var b_displayHomePage = false;

/*
* Cette méthode lance une recherche, 
* @query : mot clés recherché
* @displayList : boolean
* @displayHomePage : boolean
*/
function LaunchSearch(displayList, displayHomePage, query) {

    b_displayList = displayList;
    b_displayHomePage = displayHomePage;

    //+console.log('displayList : ' + displayList);
    //+console.log('displayHomePage : ' + displayHomePage);
    
    // Si c'est une recherche prédéfinie (permalien, recherche via API, etc.)
    // alors on appele une méthode qui affiche les résultats correspondant à la recherche courante
    var idSession = $('#isSessionSearch').text();
    if (idSession != '' && idSession != 0 && idSession != "0") {
        $('#isSessionSearch').text('');
        displayDataCurrent(idSession, true);
		return;
    }
        
    IsFirstPopAfterRequest = true;
    
    // on affiche l'icone de recherche en cours
    var canvas = document.getElementById('searchInProgress');
    canvas.style.display = 'block';

    var searchRequest;
    if (query == null) {
        searchRequest = formControls.item('QUERY').getEl().getValue();
    } else {
        searchRequest = '*';
    }

    var instr = comboInstr.getValue();
    var peuples = comboPeuples.getValue();
    var locs = comboLocs.getValue();
    var institutions = comboInstitutions.getValue();
    var audio = $('#checkboxAudio').attr('checked');
    var video = $('#checkboxVideo').attr('checked');

    if (audio == "false") audio = null;
    if (video == "false") video = null;

    
    Ext.Ajax.request({
        url: 'api.ashx?cmd=LaunchQuery',
        success: displayData,
        failure: RequestFailure,
        params: {
            query: searchRequest,
            menuLoc: locs,
            menuPeuple: peuples,
            menuInstruments: instr,
            menuInstitutions: institutions,
            audio:audio,
            video:video
        }

    });
}

function DisplayHomePage() {
    ReloadAll();
    $('#affichageFull').hide();
    $('#HomePageBox').show().find(':first').show();
}

/*
* Méthode vidant toutes les recherches en cours, et lancant une nouvelle recherche
*/
function ReloadAll() {

    carousel.clear();

    $('#idNotice').text('');
    comboInstr.clearValue();
    comboPeuples.clearValue();
    comboLocs.clearValue();
    comboInstitutions.clearValue();
    formControls.item('QUERY').reset();
    $('#checkboxAudio').removeAttr('checked');
    $('#checkboxVideo').removeAttr('checked');
    $('#LabelLocEnCours').html('');

    //+console.log('Reload all');
    LaunchSearch(false, true, '*');
}

Ext.onReady(function() {

    formControls = new Ext.util.MixedCollection(); 	// Liste des Controles

    // Champs Texte recherche simple
    var textField = new Ext.form.TextField({
        width: 180,
        cls: 'textfieldSearch',
        emptyClass: 'textfieldSearch',
        renderTo: 'divq'
    });
    formControls.add('QUERY', textField);

    comboPeuples = new Ext.form.ComboBox({
        store: storePeuples,
        displayField: 'displayName',
        id: 'comboPeuples',
        valueField: 'id',
        renderTo: 'menuPeuples',
        typeAhead: true,
        width: 180,
        mode: 'local',
        triggerAction: 'all',
        emptyText: ' ',
        emptyClass: 'comboPeuples',
        focusClass: 'comboPeuples',
        triggerClass: 'comboPeuples',
        selectedClass: 'comboPeuplesSelected',
        listClass: 'comboPeuples',
        cls: 'comboPeuples',
        selectOnFocus: true,
        height: 15
    });
    comboPeuples.on('select', function() {
        LaunchSearch(true, false);
    });
    formControls.add('PEUPLES', comboPeuples);
    comboInstr = new Ext.form.ComboBox({
        store: storeInstr,
        displayField: 'displayName',
        renderTo: 'menuInstr',
        id: 'comboInstrs',
        valueField: 'id',
        typeAhead: true,
        mode: 'local',
        width: 180,
        triggerAction: 'all',
        emptyClass: 'comboInstr',
        focusClass: 'comboInstr',
        triggerClass: 'comboInstr',
        selectedClass: 'comboInstrSelected',
        listClass: 'comboInstr',
        cls: 'comboInstr',
        emptyText: ' ',
        height: 15,
        listWidth: 180,
        selectOnFocus: true
    });
    comboInstr.on('select', function() {
        LaunchSearch(true, false);
    });
    formControls.add('INSTR', comboInstr);
    comboLocs = new Ext.form.ComboBox({
        store: storeLocs,
        id: 'comboLocs',
        displayField: 'displayName',
        valueField: 'id',
        width: 180,
        renderTo: 'menuLocs',
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText: ' ',
        emptyClass: 'comboLoc',
        focusClass: 'comboLoc',
        triggerClass: 'comboLoc',
        selectedClass: 'comboLocSelected',
        listClass: 'comboLoc',
        cls: 'comboLoc',
        selectOnFocus: true,
        height: 15,
        listWidth: 150

    });
    comboLocs.on('select', function() {
        LaunchSearch(true, false);
    });
    formControls.add('LOCS', comboLocs);
    comboInstitutions = new Ext.form.ComboBox({
        store: storeInstitutions,
        id: 'comboInstitutions',
        displayField: 'displayName',
        valueField: 'id',
        width: 180,
        renderTo: 'menuInstitutions',
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText: ' ',
        emptyClass: 'comboInstitutions',
        focusClass: 'comboInstitutions',
        triggerClass: 'comboInstitutions',
        selectedClass: 'comboInstitutionsSelected',
        listClass: 'comboInstitutions',
        cls: 'comboInstitutions',
        //height: 15,
        selectOnFocus: true,
        listWidth: 225
    });
    comboInstitutions.on('select', function() {
        LaunchSearch(true, false);
    });
    formControls.add('INSTITUTIONS', comboInstitutions);

    loadMap();


});

function ReturnToList() {
    $('#affichageFull').fadeOut('slow');
    $('#displayNotices').fadeIn('slow');
}

function HideOrShowProgramme() {

    var pgm = $('#programme');

    if (pgm.css('display') == 'block') {
        pgm.hide('slow', function() {
            // Une fois que le programme est replié, on recalcule le panel
            $('#pane4').jScrollPane({ scrollbarOnLeft: true, showArrows: true, scrollbarWidth: 3, scrollbarWidth: 15, arrowSize: 6 });
        });
    } else {
        pgm.show('slow', function() {
            // Une fois que le programme est déplié, on recalcule le panel
            $('#pane4').jScrollPane({ scrollbarOnLeft: true, showArrows: true, scrollbarWidth: 3, scrollbarWidth: 15, arrowSize: 6 });
        });
    }
}

function DisplayFull(id) {
    //console.log(id);

    /*Appel au web service pour récupérer le full */
    Ext.Ajax.request({
        url: 'api.ashx?cmd=getfull',
        success: function(resp) {

            //console.log(resp);
            $('#affichageFull').html(resp.responseText);

            /* Quand on clique sur le détail  */
            $('#displayNotices').fadeOut('slow');
            $('#affichageFull').fadeIn('slow', function() {
                resizeAffichageFull();
            });


            
            //$('#pane4').jScrollPane({ scrollbarOnLeft: true, showArrows: true, scrollbarWidth: 3, scrollbarWidth: 15, arrowSize: 6 });
        },
        failure: RequestFailure,
        params: {
            idnotice: id
        }
    });
}


$(document).ready(function() {
    $('#checkboxAudio').click(function() {
        LaunchSearch(true, false);
    });
    $('#checkboxVideo').click(function() {
        LaunchSearch(true, false);
    });
    $('#home').click(function() {
        DisplayHomePage();
        return false;
    });
    $('#previous').click(function() {
        GoBack();
        return false;
    });
    $('#next').click(function() {
        GoNext();
        return false;
    });
});
