﻿/**
* Custom inital load handler. Called when the carousel loads the initial
* set of data items. Specified to the carousel as the configuration
* parameter: loadInitHandler
*/
var loadInitialItems = function(type, args) {

    //console.info('loadInitialItems');

    if (searchStrCarousel != "") {
        var start = args[0];
        var last = args[1];

        // fetch twice the number for caching. images are create once.
        makeRequest(this, 'api.ashx?cmd=GetResultats', searchStrCarousel, start, (last - start + 1) * 2);
    }
};

/**
* Custom load next handler. Called when the carousel loads the next
* set of data items. Specified to the carousel as the configuration
* parameter: loadNextHandler
*/
var loadNextItems = function(type, args) {

    //console.info('loadNextItems');
    //console.log(args[0]);
    //console.log(args[1]);
    //console.log(args[2]);

    var nbres = parseInt($('#NBRES').val());

    console.log(nbres + "<" + args[1]);

    if (nbres <= args[1]) {
        //console.log('oui');
        $('#down-arrow')[0].src = './images/vide.gif';
    } else {
        //console.log('non');
    }

    var start = args[0];
    var last = args[1];
    var alreadyCached = args[2];

    //console.log('start : ' + start);
    //console.log('last : ' + last);

    if (!alreadyCached) {
        makeRequest(this, 'api.ashx?cmd=GetResultats', searchStrCarousel, start, (last - start + 1) * 2);
    }

};

/**
* Custom load previous handler. Called when the carousel loads the previous
* set of data items. Specified to the carousel as the configuration
* parameter: loadPrevHandler
*/
var loadPrevItems = function(type, args) {

var nbres = parseInt($('#NBRES').val());
    //console.info('loadPrevItems');
    //console.log(args[0]);
    //console.log(args[1]);
    //console.log(args[2]);

    if (nbres >= args[1]) {
        //console.log('oui');
        $('#down-arrow')[0].src = $('#down-arrow')[0].src = './images/down-enabled.gif';
    } else {
        //console.log('non');
    }
    
    var start = args[0];
    var last = args[1];
    var alreadyCached = args[2];

    if (!alreadyCached) {
        makeRequest(this, 'api.ashx?cmd=GetResultats', searchStrCarousel, start, (last - start + 1) * 2);
    }
};

/**
* Custom button state handler for enabling/disabling button state. 
* Called when the carousel has determined that the previous button
* state should be changed.
* Specified to the carousel as the configuration
* parameter: prevButtonStateHandler
*/
var handlePrevButtonState = function(type, args) {

    //console.info('handlePrevButtonState');
    
    var enabling = args[0];
    var upImage = args[1];

    if (enabling) {
        upImage.src = "images/up-enabled.gif";
    } else {
        upImage.src = "images/vide.gif";
    }
};

var showButtons = function(type, args) {
    YAHOO.util.Dom.setStyle("up-arrow", "visibility", "visible");
    YAHOO.util.Dom.setStyle("down-arrow", "visibility", "visible");
};


/**
* You must create the carousel after the page is loaded since it is
* dependent on an HTML element (in this case 'dhtml-carousel'.) See the
* HTML code below.
*/
var carousel; // for ease of debugging; globals generally not a good idea
var searchStrCarousel = "";
var firstTimeThrough = true;
var pageLoad = function() {

    carousel = new YAHOO.extension.Carousel("dhtml-carousel",
		{
		    itemWidth: 81,
		    itemHeight: 70,
		    numVisible: 5,
		    animationSpeed: 0.1,
		    scrollInc: 1,
		    loadInitHandler: loadInitialItems,
		    prevElement: "up-arrow",
		    nextElement: "down-arrow",
		    orientation: "vertical",
		    loadNextHandler: loadNextItems,
		    loadPrevHandler: loadPrevItems,
		    prevButtonStateHandler: handlePrevButtonState
		}
	);

};

/**
* Called via the YUI Connection manager (see makeRequest).
*/
var handleSuccess = function(callbackResponse) {

    //console.info('handleSuccess');
    
    var canvas = document.getElementById('searchInProgress');
    canvas.style.display = 'none';

    var start = callbackResponse.argument[0];
    var numResults = callbackResponse.argument[1];
    var carousel = callbackResponse.argument[2];

    if (callbackResponse.responseXML !== undefined) {

        var docXml = callbackResponse.responseXML;

        var elements = $(docXml).find('results').find('res');

        if (elements.length == 0) {
            $('#displayNotices').hide();
            YAHOO.util.Dom.setStyle("down-arrow", "visibility", "hidden");
            
        }
        else {
            // Allume le bouton descendre
            $('#down-arrow')[0].src = './images/down-enabled.gif';

            YAHOO.util.Dom.setStyle("down-arrow", "visibility", "visible");

            $('#displayNotices').show();

            elements.each(function(i, val) {
                var li = carousel.addItem(start + i, fmtTripInnerHTML(val));
            });
        }
    }

    $('.carousel-list').children().each(function() {
        if ($(this).text() != '') {
            $(this).css("border-bottom", "1px solid white");
        } else {
            $(this).prev().css("border-bottom", "none");
            $(this).css("border-bottom", "none");
        }
    })


    $('#dhtml-carousel').css("border-top", "1px solid white");
    $('#dhtml-carousel').css("border-bottom", "1px solid white");

    if (firstTimeThrough) {
        firstTimeThrough = false;
        carousel.calculateSize();
    }
};

/**
* Since carousel.addItem uses an HTML string to create the interface
* for each carousel item, this method takes an individual trip plan
* result and cobbles together HTML for the innerHTML argument.
*/
var fmtTripInnerHTML = function(result) {

    //console.info('fmtTripInnerHTML');
    var res = $(result);

    var titre = res.find('titre').text();
    var descr = res.find('description').text();
    var image = res.find('image').text();
    var partenaire = res.find('partenaire').text();

    var id = res.find('id').text();
    var tripInnerHTML =

  		"<a style='border:0px' href='#full' style='text-decoration:none' onClick=\"javascript:DisplayFull('" + id + "');return false;\">" +

        "<table border='0px' cellpadding='0' cellspacing='0' width='100%'>" +
            "<tr>" +
                "<td colspan='3' height='20px' style='font-weight:bold;font-size:12px;text-align:left;color:black'>" +
                    trunc(titre, 25, 20) +
                "</td>" +
            "</tr>" +
            "<tr>" +
                "<td width='40px' height='40px'>" +
                    "<img height='37px' src='" + image + "'></img>" +
                "</td>" +
                "<td width='10px'>" +
                "</td>" +
                "<td class='descriptionListeCourte'>" +
                    trunc(descr, 60, 15) +
                "</td>" +
            "</tr>" +
            "<tr>" +
               "<td colspan='3' height='20px' style='font-weight:bold;font-size:10px;text-align:right;color:black'>" +
                    partenaire +
                "</td>" +
            "</tr>" +
        "</table>" +

    //"<img src='" +
    //result.Image.Url +
    //"' width='" +
    //75 +
    //"' height='" +
    //75 +
    //"'/>" +
  		"<\/a>";


    return tripInnerHTML;

};

var handleFailure = function(o) {

    var result = o.status + " " + o.statusText;
    alert("Transaction failed.  The error is: " + result);
};

/**
* A utility function for invoking the YUI connection manager (Ajax)
* with a URL that matches the Yahoo! developer network Trip Planner
* APIs (see: http://developer.yahoo.com/travel/tripservice/V1/tripSearch.html)
*
* The callback object is the configuration object for the YUI Connection
* manager. If this is successful, the 'handleSuccess' function is called.
*/
var makeRequest = function(carousel, url, idSession, start, nbreswanted) {

    //console.log('ask here');

    var params = 'idSession=' + idSession +
	             '&start=' + start +
	             '&nbreswanted=' + nbreswanted +
	             '&displayXML=' + false;

    var callback =
	{
	    success: handleSuccess,
	    failure: handleFailure,
	    argument: [start, nbreswanted, carousel]
	};
    
    YAHOO.util.Connect.asyncRequest("POST", url, callback, params);
};

/**
* Just a utility function for cleaning up the returned HTML response
* and truncating it.
*/
var trunc = function(str, maxLen, maxWordLen) {
    // Strip markup
    str = str.replace("<b>", "");
    str = str.replace("<\/b>", "");
    str = str.replace("<B>", "");
    str = str.replace("<\/B>", "");

    // Simple truncation
    if (str.length > maxLen) {
        str = str.substring(0, maxLen) + "...";
    }

    // Truncate for long words
    var start = 0;
    var loopCnt = 0;
    var strSlice = str;

    do {
        var spaceBreak = strSlice.indexOf(' ');
        var lenOfWord = spaceBreak;
        if (lenOfWord == -1) {
            lenOfWord = strSlice.length;
        }

        if (lenOfWord > maxWordLen) {
            //debugMsg("Long word found in: " + strSlice);
            str = str.substring(0, maxWordLen);  // TRUNCATE
        }
        start = spaceBreak + 1;
        strSlice = strSlice.substring(start);
        spaceBreak = strSlice.indexOf(' ');
    } while (spaceBreak != -1)


    return str;
};

var searchTrips = function(e) {
    carousel.reload();
};

YAHOO.util.Event.addListener(window, 'load', pageLoad);
