﻿/// <reference path="~/scripts/jquery-1.3.2-vsdoc2.js" />

(function($) {
    jQuery.fn.listview = function(o) {
        if (o != null) {
            return $.each(this, function() {
                plugin._proxy = new AAjaxProxy.POSAccommodationService();
                plugin._options = jQuery.extend({}, listviewcfg, o);
                _attachListView($(this));
            });
        }
    };
    //
    // Public functions
    //

    var listviewcfg = {
        templateId: 'itemTemplate',
        itemsToDisplay: 10,
        paging: true,
        imagePath: 'images/',
        listLoadedFn: null,
        getDataFn: null,
        mask: null,
        listType: 'hotel'
    };
    //
    // Private variables
    //
    var plugin = {
        _list: null,
        _pagerdiv: null,
        _pager: null,
        _template: null,
        _options: null,
        _mask: null,
        _currentPage: null,
        _pageCount: null,
        _proxy: null,
        _options: null
    };
    //
    // Private functions
    //
    //
    // Create the elements of the plugin
    //
    function _attachListView(target) {

        plugin._list = jQuery('<ul>').addClass('listview').appendTo(target);
        plugin._pagerdiv = jQuery('<div>').addClass('list-pager').appendTo(target)
        plugin._pager = jQuery('<ul>').addClass('list-pager-buttons');
        plugin._pagerdiv.append(plugin._pager);
        jQuery('<input/>').attr({ type: 'hidden', id: 'templateId' }).val(plugin._options.templateId).appendTo(target);
        jQuery('<input/>').attr({ type: 'hidden', id: 'listType' }).appendTo(target);
        plugin._pagerdiv.css({
            top: plugin._list.offset().top + plugin._list.height(),
            left: plugin._list.offset().left
            //width: plugin._list.width()
            //position: 'absolute'
        }).hide();

        //target.width(plugin._list.width());
        //target.height(plugin._list.height() + plugin._pagerdiv.height());

        plugin._template = jQuery('#' + plugin._options.templateId).clone();
        var imagePath = plugin._options.imagePath;
        var backgroundPath = '#E3E3E3 url("' + imagePath + 'grid-loading.gif") no-repeat scroll center center'
        plugin._mask = jQuery('<div style="text-align: centre; font-size: 12px; font-weight:bold;">Be with you now, we’re busy searching for the best rates available!</div><div>').addClass('modalmask').css({
            height: target.height()
            //width: target.width(),
            //top: 50,
            //left: 50,
            //position: 'absolute',
            //background: '#E3E3E3 url("' + imagePath + 'grid-loading.gif") no-repeat scroll center center'
        }).appendTo(target).hide();
	jQuery('<div><image id="progress" src="/images/loading.gif" /></div>').css({position:"absolute", top:100, left:100}).appendTo(target);

        plugin._mask.show();
        plugin._currentPage = 1;
        plugin._pageCount = 0;

        jQuery('<li>')
        .addClass('button-first')
        .append(jQuery('<img>')
        .mouseover(function() { jQuery(this).attr('src', imagePath + 'page-first.png') })
        .mouseout(function() { jQuery(this).attr('src', imagePath + 'page-first-off.png') })
        .mousedown(FirstPage)
        .attr('src', imagePath + 'page-first-off.png')
        .attr('disabled', 'disabled'))
        .appendTo(plugin._pager);

        jQuery('<li>')
        .addClass('button-previous')
        .append(jQuery('<img>')
        .mouseover(function() { jQuery(this).attr('src', imagePath + 'page-prev.png') })
        .mouseout(function() { jQuery(this).attr('src', imagePath + 'page-prev-off.png') })
        .mousedown(PrevPage)
        .attr('src', imagePath + 'page-prev-off.png')
        .attr('disabled', 'disabled'))
        .appendTo(plugin._pager);

        jQuery('<label>')
        .addClass('pager-currentpage')
        .text('Page ' + plugin._currentPage)
        .appendTo(plugin._pager);

        jQuery('<li>')
        .addClass('button-next')
        .append(jQuery('<img>')
        .mouseover(function() { jQuery(this).attr('src', imagePath + 'page-next.png') })
        .mouseout(function() { jQuery(this).attr('src', imagePath + 'page-next-off.png') })
        .mousedown(NextPage)
        .attr('src', imagePath + 'page-next-off.png'))
        .attr('disabled', 'disabled')
        .appendTo(plugin._pager);

        jQuery('<li>')
        .addClass('button-last')
        .append(jQuery('<img>')
        .mouseover(function() { jQuery(this).attr('src', imagePath + 'page-last.png') })
        .mouseout(function() { jQuery(this).attr('src', imagePath + 'page-last-off.png') })
        .mousedown(LastPage)
        .attr('src', imagePath + 'page-last-off.png'))
        .appendTo(plugin._pager);

        plugin._mask.show();

        GetListItems(plugin, target);
    }

    function FirstPage(e) {
        var _settings = GetSettings(e);
        _settings._currentPage = 1;
        _settings._pager.find('label.pager-currentpage').text('Page ' + _settings._currentPage);
        _settings._pager.find('li.button-previous img').attr('disabled', 'disabled').attr('src', plugin._options.imagePath + 'page-prev-off.png');
        _settings._pager.find('li.button-first img').attr('disabled', 'disabled').attr('src', plugin._options.imagePath + 'page-first-off.png');
        _settings._pager.find('li.button-next img').attr('disabled', '');
        _settings._pager.find('li.button-last img').attr('disabled', '');
        plugin._proxy.GetResults(_settings._template, _settings._currentPage, _settings._itemsToDisplay, GetResults, AjaxError, _settings);
    }

    function PrevPage(e) {
        var _settings = GetSettings(e);
        ShowMask(_settings._mask);
        _settings._currentPage--;
        _settings._pager.find('label.pager-currentpage').text('Page ' + _settings._currentPage);
        if (_settings._currentPage == 1) {
            _settings._pager.find('li.button-previous img').attr('disabled', 'disabled').attr('src', plugin._options.imagePath + 'page-prev-off.png');
            _settings._pager.find('li.button-first img').attr('disabled', 'disabled').attr('src', plugin._options.imagePath + 'page-first-off.png');
            _settings._pager.find('li.button-next img').attr('disabled', '');
            _settings._pager.find('li.button-last img').attr('disabled', '');
        }
        else {
            _settings._pager.find('li.button-previous img').attr('disabled', '');
            _settings._pager.find('li.button-first img').attr('disabled', '');
            _settings._pager.find('li.button-next img').attr('disabled', '');
            _settings._pager.find('li.button-last img').attr('disabled', '');
        }

        plugin._proxy.GetResults(_settings._template, _settings._currentPage, _settings._itemsToDisplay, GetResults, AjaxError, _settings);
    }

    function GetSettings(e) {
        var sender = e.target.parentNode.parentNode.parentNode.previousSibling;
        var pager = jQuery(e.target.parentNode.parentNode.parentNode);
        var templateId = $(sender.parentNode).find('#templateId').val();

        var settings = {
            _list: $(sender),
            _mask: $(sender.parentNode).find('.modalmask'),
            _pager: pager,
            _currentPage: pager.find('label.pager-currentpage').text().replace('Page ', ''),
            _pageCount: pager.find('label.pager-pagecount').text().replace(' of ', ''),
            _itemsToDisplay: 5, //sender.children.length,
            _listType: $(sender.parentNode).find('#listType').val(),
            _templateId: $(sender.parentNode).find('#templateId').val(),
            _template: jQuery('#' + templateId).html()
        };
        return settings;
    }

    function NextPage(e) {
        var _settings = GetSettings(e);
        if (_settings._currentPage == _settings._pageCount) {
            return;
        }

        ShowMask(_settings._mask);
        _settings._currentPage++;

        _settings._pager.find('label.pager-currentpage').text('Page ' + _settings._currentPage);
        if (_settings._currentPage == _settings._pageCount) {
            _settings._pager.find('li.button-next img').attr('disabled', 'disabled').attr('src', plugin._options.imagePath + 'page-next-off.png');
            _settings._pager.find('li.button-last img').attr('disabled', 'disabled').attr('src', plugin._options.imagePath + 'page-last-off.png');
            _settings._pager.find('li.button-first img').attr('disabled', '');
            _settings._pager.find('li.button-previous img').attr('disabled', '');
        }
        else {
            _settings._pager.find('li.button-first img').attr('disabled', '');
            _settings._pager.find('li.button-previous img').attr('disabled', '');
        }
        plugin._proxy.GetResults(_settings._template, _settings._currentPage, _settings._itemsToDisplay, GetResults, AjaxError, _settings); //{ '_list': $(sender), '_pageCount': _pageCount, '_itemsToDisplay': _itemsToDisplay, '_listType': _listType, '_mask': _mask });
    }

    function LastPage(e) {
        var _settings = GetSettings(e);
        ShowMask(_settings._mask);
        _settings._currentPage = _settings._pageCount;
        _settings._pager.find('label.pager-currentpage').text('Page ' + _settings._currentPage);
        _settings._pager.find('li.button-next img').attr('disabled', 'disabled').attr('src', plugin._options.imagePath + 'page-next-off.png');
        _settings._pager.find('li.button-last img').attr('disabled', 'disabled').attr('src', plugin._options.imagePath + 'page-last-off.png');
        _settings._pager.find('li.button-previous img').attr('disabled', '');
        _settings._pager.find('li.button-first img').attr('disabled', '');
        plugin._proxy.GetResults(_settings._template, _settings._currentPage, _settings._itemsToDisplay, GetResults, AjaxError, _settings);
    }

    function ShowMask(mask) {
        mask.show();
    }

    function HideMask(mask) {
        mask.hide();
    }

    function GetListItems(objValues, sender) {
        switch (objValues._options.listType) {
            case 'hotel':
                var searchString = document.location.search;
                sender.find('#listType').val('hotel');
                searchString = searchString.substring(1);
                var siteId = CMS_SiteId;
                var hotelItemsProxy = new AAjaxProxy.POSAccommodationService();
                hotelItemsProxy.GetHotels(siteId, searchString, GetResults, AjaxError,
                {
                    '_template': objValues._template.html(),
                    '_currentPage': objValues._currentPage,
                    '_itemsToDisplay': objValues._options.itemsToDisplay,
                    '_listType': 'hotel',
                    '_sender': sender,
                    '_mask': objValues._mask,
                    '_pageCount': 0,
                    '_listLoadedFn': objValues._options.listLoadedFn,
                    '_pager': objValues._pagerdiv
                });
                break;
            case 'promo':
                var promoItemsProxy = new AAjaxProxy.POSAccommodationService();
                sender.find('#listType').val('promo');
                promoItemsProxy.GetPromotions(GetResults, AjaxError,
                {
                    '_template': objValues._template.html(),
                    '_currentPage': objValues._currentPage,
                    '_itemsToDisplay': objValues._options.itemsToDisplay,
                    '_listType': 'promo',
                    '_sender': sender,
                    '_mask': objValues._mask,
                    '_pageCount': 0,
                    '_listLoadedFn': objValues._options.listLoadedFn,
                    '_pager': objValues._pagerdiv
                });
                break;
        }
    }

    function GetResults(result, objValues) {
        switch (objValues._listType) {
            case 'hotel':
                if (result.length > 0) {
                    plugin._proxy.GetResults(objValues._template, objValues._currentPage, objValues._itemsToDisplay, BuildList, AjaxError, objValues);
                }
                else {
                    //alert('We are not able to find what you’re looking for. Please modify your search or give us a call on 0860 119 119.');
                    $('#NoResults').show();
                    $('#progress').hide();
                }
                break;
            case 'promo':
                if (result.length > 0) {
                    plugin._proxy.GetPromos(objValues._template, objValues._currentPage, objValues._itemsToDisplay, BuildList, AjaxError, objValues);
                }
                else {
                    $('#promoList').hide();
                }
                break;
        }
        HideMask(objValues._mask);
    }

    function BuildList(markup, objValues) {
        var _list;
        if (objValues._sender != null) {
            _list = objValues._sender.find('ul.listview');
        }
        else {
            _list = objValues._list;
            _list.empty();
        }

        var objMap = getById('myMap');

        for (var i = 0; i < markup.length; i++) {
            jQuery('<li>')
            .addClass('listview-item')
            .html(markup[i])
            .appendTo(_list);
        }

        if (_list.children.length > 0) {
            objValues._pager.show();
        }
        else {
            objValues._pager.hide();
        }

        if (objValues._listType == "hotel") {
            $('#searchResults .listview-item').each(function(i, result) {
                $(result).click(
                    function(e) {
                        var mapIcon = new VELatLong(shapes[$(this).find('.resourceid').text()].Latitude, shapes[$(this).find('.resourceid').text()].Longitude);

                        map.SetCenterAndZoom(mapIcon, 16);
                        map.ShowInfoBox(shapes[$(this).find('.resourceid').text()]);
                    })
            });
        }

        if (objValues._pageCount == 0) {
            // the list loaded callback only needs to run when the list is built for the first time
            // so we put it in here.
            if (objValues._listLoadedFn != null) {
                objValues._listLoadedFn();
            }
            var _itemsToDisplay;
            var _listType;
            if (objValues._itemsToDisplay != null) {
                _itemsToDisplay = objValues._itemsToDisplay;
            }
            else {
                _itemsToDisplay = objValues._options.itemsToDisplay;
            }

            if (objValues._listType != null) {
                _listType = objValues._listType;
            }
            else {
                _listType = objValues._options.listType;
            }
            plugin._proxy.GetTotalPages(_itemsToDisplay, _listType, ShowPageCount, AjaxError, objValues)
        }
        HideMask(objValues._mask);
        $("#searchResults .listview-item:even").addClass("altRow");
        $("#promoResults .listview-item:even").addClass("altRow");
    }

    function ShowPageCount(result, objValues) {
        objValues._pageCount = result;
        var _pagerlabel = objValues._pager.find('label.pager-currentpage');
        jQuery('<label>').addClass('pager-pagecount').text(' of ' + objValues._pageCount).insertAfter(_pagerlabel);
    }

    function AjaxError(error, userContext, methodName) {
        //TODO: I suggest we develop a type of popup here that gives some descriptive feedback 
        //with some concrete actions that the user can take.
        //alert('Unexpected error while calling service.');
        alert(error._message + "\r\n" + userContext + "\r\n" + methodName);
    }
})(jQuery);
