﻿
App.CampsiteList = function() {

    /* Private */

    /* Properties */

    var cmp = {};

    var template = '' +

        '<table id="searchResultsGrid" class="grid gridExpandable listings">' +
            '<tbody>' +
                '{for i in items}' +
                    '<tr id="c-${i[0]}" class="listing">' +
                        '<td class="firstColumn textCell"><strong>${i[1]}</strong> - ${i[2]}</td>' +
                        '{if i[3] > -1}<td class="distance textCell"><strong>${i[3]} Miles</strong></td>{/if}' +
                        '<td class="rating"><div class="tentScore"><div class="tents tentScore${i[4].toString().replace(".","")}"></div></div></td>' +                        
                        '{if showRemoveButton}<td class="remove"><div class="alignRight clearfix"><a class="TVI-button TVI-button-iconRight TVI-button-iconStyle-icon16RightArrow TVI-fixedWidth align favouritesButton favouriteButtonRemove" style="width:100px;" href="#">remove</a></div></td>{/if}' +                        
                        '<td class="more"><div class="alignRight clearfix"><a class="TVI-button TVI-button-iconRight TVI-button-iconStyle-icon16DownArrow TVI-fixedWidth align" style="width:125px;" href="#">more info</a></div></td>' +
                    '</tr>' +
                '{/for}' +
            '</tbody>' +
        '</table>';





    /* Methods */

    var init = function() {
        
        //handle openning/closing rows
        TVI.event('.listings .listing', 'click', function(e) {
            
            //cancel if clicking on remove button
            if (cmp.showRemoveButton && $(e.target).parents('.favouriteButtonRemove').length){ return; }
            

            var el = $(this);

            //close panel if open
            if (el.hasClass('openRow')) {

                //check if map summary and remove all
                if (el.parents('#campsiteLocationMapSummary').length > 0) {

                    el.parents('#campsiteLocationMapSummary').empty();

                    return;

                }


                //remove summary
                el.next().remove();

                //reset row
                el.removeClass('openRow');

                el.find('.TVI-button-text:last').text('more info');
                el.find('.icon16UpArrow:last').removeClass('icon16UpArrow').addClass('icon16DownArrow');

                return;

            }


            //otherwise, get campsite summary and insert after this row
            var id = this.id.replace('c-', '');

            TVI.ajax({

                url: TVI.handlers + 'App.Search.aspx/getSummary',
                data: {
                    campsiteID: id
                },
                responseType: 'string',
                success: function(d) {

                    var summaryEl = $(d);

                    el.after(summaryEl);

                    setSummary(summaryEl, id);

                    el.addClass('openRow');

                    el.find('.TVI-button-text:last').text('less info');
                    el.find('.icon16DownArrow:last').removeClass('icon16DownArrow').addClass('icon16UpArrow');

                }

            });

        });


        //handle favoutites
        TVI.event('.listings .favouritesButton', 'click', addToFavourites);


        // Thumbnail Hover
        TVI.event('.listingOpenPanel .thumb IMG, .listingOpenPanel .thumb .morePhotosButton', 'mouseover', function() {
            $(this).parent().addClass('thumbHover');
        });
        TVI.event('.listingOpenPanel .thumb IMG, .listingOpenPanel .thumb .morePhotosButton', 'mouseout', function() {
            $(this).parent().removeClass('thumbHover');
        });
        
        
        // Listing Hover
        TVI.event('.listings .listing', 'mouseenter', function() {
            $(this).addClass('gridRowHover');
        });
        TVI.event('.listings .listing', 'mouseleave', function() {
            $(this).removeClass('gridRowHover');
        });
        TVI.event('.listings .thumb', 'mouseenter', function() {
            $(this).addClass('thumbHover');
        });
        TVI.event('.listings .thumb', 'mouseleave', function() {
            $(this).removeClass('thumbHover');
        });

    };
    
    
    
    
    
    var addToFavourites = function(){
        
        if (!App.user.loggedIn){
        
            TVI.Popup.show({
            
                title: 'Favourites',
                template: 'Please <a href="/login">log in</a> or <a href="/registration">create an account</a> to manage your favourite campsites.'
            
            });
            
            return;
        
        }

        //run query adding/removing favourite            
        var btn = $(this);
        
        //get campsite id depending on button location
        var campsiteID = 0;
        
        if (btn.parents('.listing:first').length > 0){
        
            campsiteID = btn.parents('.listing:first').attr('id').replace('c-', '');
        
        }
        else{
            
            campsiteID = TVI.meta(btn.parents('.openPanelCell:first')).ID;
            
        }
        
        var remove = btn.hasClass('favouriteButtonRemove');
        
        TVI.Data.query({
        
            query: 'Campsite_addToFavourites',
            data: {
                campsiteID: campsiteID,
                remove: remove
            },
            success: function(d){
            
                if (remove){
                
                    //refresh page results if showing remove button
                    if (cmp.showRemoveButton){
                    
                        TVI.fireEvent('favouriteRemoved', campsiteID);
                        
                        return;
                    
                    }
                    
                    btn.removeClass('favouriteButtonRemove'); return;
                
                }
                
                //othewie just add remove class
                btn.addClass('favouriteButtonRemove');
            
            }
        
        });
    
    };
    
    
    
    
    
    var setSummary = function(el, id) {

        /* initiailises a summary section */

        //set components
        TVI.Components.initialize(el);

        //set map
        TVI.Mapping.load({

            success: function() {

                var mapData = TVI.meta(el.find('.map'));

                cmp.summaryMap = new TVI.Mapping.GMap({

                    id: 'sm-' + id,
                    mapControlType: 'small',
                    showViewButtons: false,
                    longitude: mapData.mapX,
                    latitude: mapData.mapY,
                    zoomLevel: 7,
                    useCustomMarker: true

                });

                cmp.summaryMap.addMarker({

                    id: 0,
                    longitude: mapData.mapX,
                    latitude: mapData.mapY,
                    customMarkerURL: '/i/mapflag.png'

                });

            }

        });

    };
    
    
    
    
    
    var process = function(rows){
    
        return template.process({ items: rows, showRemoveButton: cmp.showRemoveButton });
    
    };





    /* Public */

    TVI.apply(cmp, {

        /* Properties */
        
        showRemoveButton: false,
        
        /* Methods */
        
        process: function(rows){
        
            return process(rows);
        
        },
        
        setSummary: function(el, id) {
        
            setSummary(el, id);
        
        }

    });


    TVI.ready(init);


    return cmp;


} ();
