/*** Start of file: generic\common\resultlist.js ***/
/**
 * A wrapper providing result-list functionality, as used on many places where list of results with accommodations are found.
 * @class Functionality for a list of accommodation results, as used on search page, offers page, location page, etc. It essentially binds
 * to an accommodation list with id 'result-list'. It provides extra javascript behavior: making all 'li' elements clickable, showing which accommodations
 * on the list have already been viewed, etc.
 * @constructor
 * @param {jQuery} $ Reference to the jQuery object
 */
var ResultList = function($) {

    /**
    * @namespace Private methods and variables
    */
    var priv = {

        /**
        * Selector string to select the items of the list
        * @type String
        * @private
        */
        resultListElements: "#result-list>li",

        /**
        * Selector for the anchor elements in each list item. The whole list item will
        * have a click event handler that will navigate to the url this anchor
        * points to.
        * @type String
        * @private
        */
        resultListAnchorElement: ".acco-name a",

        /**
        * Selector string for the 'last viewed' elements, containing info on when the
        * acco in the list item was last viewed.
        * @type String
        * @private
        */
        lastViewedTimestamp: "span.last-viewed-timestamp",

        /**
        * marks items from the given array with the given className if they are found in the cookie
        * @param {Array} items, cookieItems
        * @param {String} activeClassName, className to give when active
        * @param {String} (optional) string that represents the html element that can hold the date (jQuery syntax) 
        * @private
        */
        markItems: function(items, activeClassName, dateElement) {
            Log.Debug("setting " + activeClassName, 0);

            //loop through the pageElements and set according class
            $(priv.resultListElements).each(function(i) {
                thisId = $(this).attr("id");

                //check whether this is a valid list-item
                if (!thisId) {
                    return true;
                }
                thisId = thisId.substring(thisId.lastIndexOf("-") + 1);

                //set default
                $(this).removeClass(activeClassName);

                //loop through array items, to test if thisId is stored in the array, set activeClassName if matched
                for (var j = 0; j < items.length; j++) {
                    if (thisId == items[j].id) {
                        //prepare for the animate for showing of the already-viewed tags, to make the user experience better
                        $tagElement = $(this).find("div." + activeClassName + "-tag");
                        $tagElement.css("opacity", "0");

                        //set the active class
                        $(this).addClass(activeClassName);

                        //now animate the fade-in
                        $tagElement.animate({ "opacity": "1" }, 1000);

                        //if dateElement parameter is provided write date to element
                        if (typeof (dateElement) != "undefined") {
                            //prepare the correct date format
                            var currentDate = new Date();
                            var itemDate = PersonalItems.GetDate(items[j].date);
                            var oneDay = 1000 * 60 * 60 * 24; //day in millisecs

                            var $dateElement = $("#" + this.id + " " + dateElement);

                            // Calculate the difference in milliseconds
                            var difference_ms = Math.abs(currentDate.getTime() - items[j].date);
                            // Convert back to days and return
                            var diffDays = Math.round(difference_ms / oneDay);
                            
                            //count days, and write accordingly
                            if (diffDays == 0) {
                                // today, write from resource "today"
                                var html = Resource.GetText("search_already_viewed", Resource.GetText("result_date_today"))
                                $dateElement.html(html);
                                //today, write timestamp hh:mm
                                //hours = (itemDate.getHours() < 10 ? ("0" + itemDate.getHours()) : itemDate.getHours());
                                //mins = (itemDate.getMinutes() < 10 ? ("0" + itemDate.getMinutes()) : itemDate.getMinutes());
                                //$("#" + this.id + " " + dateElement).html(hours + ":" + mins);
                            } else if (diffDays == 1) {
                                //yesterday, write from resource "yesterday"                                
                                var html = Resource.GetText("search_already_viewed", Resource.GetText("result_date_yesterday"))
                                $dateElement.html(html);
                            } else {
                                //older than yesterday write datestamp d MMM
                                var dateText = itemDate.getDate() + " " + Resource.GetText('date_months_short')[itemDate.getMonth()]
                                var html = Resource.GetText("search_already_viewed_date", dateText)
                                $dateElement.html(html);
                            }
                            $dateElement.parent().css("opacity", "0");
                            $dateElement.parent().css({ "visibility": "visible" });

                            //animate the text (fadein)
                            $dateElement.parent().animate({ "opacity": "1" }, 1000);

                            Log.Debug(diffDays, 0);
                        }
                        break;
                    }
                }
            });

            //recalculate and show the counters on the personal item links
            PersonalItems.ShowItemLinks();
        },

        /**
        * Bind events on result list elements: hover, click, etc.
        * @private
        */
        bindResultListElements: function() {
            // Hover on list element
            $(priv.resultListElements).hover(function() {
                //mouseover
                $(this).addClass("hover");
            }, function() {
                //mouseout
                $(this).removeClass("hover");
            }).bind("click", function() {
                //get the current id
                thisId = $(this).attr("id");

                //check if we have a valid list-item
                if (!thisId) {
                    return false;
                }
                thisId = thisId.substring(thisId.lastIndexOf("-") + 1);

                //adding to the alreadyviewed array
                PersonalItems.Add("alreadyviewed", thisId);

                //now direct to new url
                //get the url to direct to
                var url = $("#" + $(this).attr("id") + " " + priv.resultListAnchorElement).attr("href");
                var rel = $("#" + $(this).attr("id") + " " + priv.resultListAnchorElement).attr("rel");
                if (typeof (rel) != "undefined" && rel != null && rel != "") {
                    var separatorChar = '?';
                    if (url.indexOf('?') != -1) {
                        separatorChar = '&';
                    }
                    var urlSplit = url.split('#');
                    if (urlSplit.length > 1) {
                        url = urlSplit[0] + separatorChar + "objectIndex=" + rel + "#" + urlSplit[1];
                    }
                    else {
                        url += separatorChar + "objectIndex=" + rel;
                    }
                }

                document.location.href = url;
                // Should bubble to be overwritten by a possible <a> element
                return true;
            });
            
            $(priv.resultListElements).find(".compare").bind("click", function() {
                // Prevent click next to 'vergelijk' checkbox to open accommodation
                return false;
            }).find('.compareCheck').bind('click', function() {
                if ($(this).hasClass("checked")) {                    
                    $(this).removeClass("checked");
                } else {
                    if ($('#result-list div.compareCheck.checked').length > 2) {
                        alert(Resource.GetText('compare_maximum'));
                        return false;
                    }
                    $(this).addClass("checked");
                }
                return false;
            }).prev('a').bind('click', function() {
                if ($('#result-list div.compareCheck.checked').length < 2) {
                    alert(Resource.GetText('compare_minimum'));
                } else {
                    var compareUrl = "";
                    $('#result-list div.compareCheck.checked').each(function(i) {
                        var prefix = (compareUrl == '') ? 'id=' : ',';
                        compareUrl = compareUrl + prefix + this.id.replace('check_', '');
                    });
                    var extraUrl = $('div.compare a').attr('class');
                    var realUrl = $(this).attr('href') + '?personal=' + extraUrl + '&' + compareUrl;
                    location.href = realUrl;
                }
            });
        }
    };

    /** @scope ResultList */
    return {

        /**
        * Initialize the ResultList. It will mark all items that were already viewed and bind event handlers to the result list elements.
        * Called on $(document).ready
        */
        OnReady: function() {
            priv.markItems(PersonalItems.Load("alreadyviewed"), "already-viewed", priv.lastViewedTimestamp);
            priv.bindResultListElements();
        }
    };
} (jQuery);/*** End of file: generic\common\resultlist.js ***/
