﻿
App.Search = function () {

    /* Private */

    /* Properties */

    var cmp = {};





    /* Methods */

    var init = function () {

        /* Constructor */

        //set search form
        cmp.searchForm = new TVI.Form({

            ID: 'searchForm',
            url: TVI.handlers + 'App.Search.aspx/search',
            data: {
                facilitiesOn: '',
                facilitiesOff: '',
                amenitiesOn: '',
                amenitiesOff: '',
                mapX: 0,
                mapY: 0
            },
            submit: function () {

                this.submit();


                //set search type
                if (this.hiddenData.type === undefined || this.hiddenData.type === '') {

                    if (App.Search.Results !== undefined) {

                        this.hiddenData.type = 'form';

                    }
                    else {
                        this.hiddenData.type = 'mini';
                    }

                }


                //reset page number
                if (this.hiddenData.type === 'mini' || this.hiddenData.type === 'form' || this.hiddenData.type === 'sort') {

                    this.hiddenData.page = 1;

                }


                //build filters
                this.hiddenData.facilitiesOn = '';
                this.hiddenData.facilitiesOff = '';
                this.hiddenData.amenitiesOn = '';
                this.hiddenData.amenitiesOff = '';

                var count = cmp.filters.rows.length;

                if (count > 0) {

                    for (var i = 0; i < count; i++) {

                        if (cmp.filters.rows[i][2] === 'f') {

                            if (cmp.filters.rows[i][3] === 'on') {

                                if (this.hiddenData.facilitiesOn !== '') { this.hiddenData.facilitiesOn += ','; }

                                this.hiddenData.facilitiesOn += cmp.filters.rows[i][0];

                            }
                            else {

                                if (this.hiddenData.facilitiesOff !== '') { this.hiddenData.facilitiesOff += ','; }

                                this.hiddenData.facilitiesOff += cmp.filters.rows[i][0];

                            }

                        }
                        else {

                            if (cmp.filters.rows[i][3] === 'on') {

                                if (this.hiddenData.amenitiesOn !== '') { this.hiddenData.amenitiesOn += ','; }

                                this.hiddenData.amenitiesOn += cmp.filters.rows[i][0];

                            }
                            else {

                                if (this.hiddenData.amenitiesOff !== '') { this.hiddenData.amenitiesOff += ','; }

                                this.hiddenData.amenitiesOff += cmp.filters.rows[i][0];

                            }

                        }

                    }

                }


                //send map coordinates for POI if exists

                if (cmp.map) {

                    var zoom = cmp.map.getZoomLevel();

                    if (zoom >= 10) {

                        var bounds = cmp.map.getBounds();

                        cmp.searchForm.hiddenData.mapZoom = zoom;
                        cmp.searchForm.hiddenData.minMapX = bounds.longMin;
                        cmp.searchForm.hiddenData.maxMapX = bounds.longMax;
                        cmp.searchForm.hiddenData.minMapY = bounds.latMin;
                        cmp.searchForm.hiddenData.maxMapY = bounds.latMax;

                    }

                }


                //set sorting

                //if location has changed, force sorting to distance and update control without firing change event
                var sortEl = $('#sorting-control');

                if (cmp.locationChanged) {

                    if (this.field('location').val() !== '') {

                        sortEl.val('distance');

                        this.hiddenData.sort = 'distance';

                    }
                    else if (sortEl.val() === 'distance') {

                        sortEl.val('a-z');

                        this.hiddenData.sort = 'a-z';

                    }

                    TVI.Components.CustomDDL.update(sortEl);

                    cmp.locationChanged = false;

                }

                if (sortEl.length > 0) { this.hiddenData.sort = sortEl.val(); }

            },
            validation: function (d) {

                //custom validation to check pitches and dates have been entered
                var pitches = this.field('pitches').val();
                var startDate = this.field('startDate').val();
                var endDate = this.field('endDate').val();
                var pitchTypeID = this.field('pitchTypeID').val();

                if ((pitches !== '' || startDate !== '' || endDate !== '') && (pitches === '' || startDate === '' || endDate === '' || pitchTypeID === '')) {

                    if (pitches === '') { d.errors.push({ fieldID: 'pitches', message: 'Please enter pitches.' }); }

                    if (startDate === '' || endDate === '') { d.errors.push({ fieldID: 'startDate', message: 'Please select your dates.' }); }

                    if (pitchTypeID === '') { d.errors.push({ fieldID: 'pitchTypeID', message: 'Please select a pitch.' }); }

                }

            },
            success: function (d) {

                //call base method
                this.success();


                //handle 'mini' results
                if (this.hiddenData.type === 'mini') {

                    //show locations if necessary
                    if (d.locations === true) {

                        TVI.Popup.show({

                            title: 'Choose Your Location',
                            template: '<div id="locations">{for r in rows}<div><a id="location-${r[0]}" href="#">${r[1]}</a></div>{/for}</div>'.process(d)

                        });

                        return;

                    }


                    if (d.geoLocations === true) {

                        TVI.Popup.show({

                            title: 'Choose Your Location',
                            template: '<div id="geoLocations">{for r in rows}<div><a id="location-${r[0]}" href="#">${r[1]}</a></div>{/for}<br /><div><a id="location-all" href="#">Show All</a></div></div>'.process(d)

                        });

                        return;

                    }


                    //store map coordinates
                    this.hiddenData.mapX = d.mapX;
                    this.hiddenData.mapY = d.mapY;

                    //clear selected location
                    this.hiddenData.locationID = '';

                    if (this.hiddenData.geoLocationID !== 'all') {

                        this.hiddenData.geoLocationID = '';

                    }


                    //redirect to results page
                    window.location.href = getURL();

                    return;

                }


                this.el.find('.TVI-form-submit').show();


                //otherwise set summary and call results handlers
                setSearchSummary();

                App.Search.Results.show.call(this, d);

            }

        });


        //add current search args if exist
        cmp.searchForm.val(cmp.args);

        setSearchSummary();


        //handle location changed event to clear map coordinates
        TVI.event('#searchForm-location-control', 'keyup', function () {

            cmp.searchForm.hiddenData.mapX = 0;
            cmp.searchForm.hiddenData.mapY = 0;

            cmp.searchForm.hiddenData.locationID = '';
            cmp.searchForm.hiddenData.geoLocationID = '';

            cmp.locationChanged = true;

        });


        //handle location selected event to run search on PA location
        TVI.event('#locations A', 'click', function () {

            var locationID = this.id.replace('location-', '');

            cmp.searchForm.hiddenData.locationID = locationID;

            cmp.searchForm.handler.call();

            TVI.Popup.close();

        });


        //handle geo location selected event to run search on geo location
        TVI.event('#geoLocations A', 'click', function () {

            var geoLocationID = this.id.replace('location-', '');

            cmp.searchForm.hiddenData.geoLocationID = geoLocationID;

            cmp.searchForm.handler.call();

            TVI.Popup.close();

        });


        //show location map for user to select location
        TVI.event('#btn-searchMap', 'click', function () {

            var btn = $(this);

            TVI.Mapping.load({

                success: function () {

                    //position and show map
                    var searchFormMapEl = $('#searchFormMap');

                    searchFormMapEl.css({ top: 110, left: btn.offset().left });

                    searchFormMapEl.show();

                    //set map form
                    cmp.searchFormMap = new TVI.Form({

                        ID: 'searchFormMap',
                        settings: {
                            mapPicker: {
                                useCustomMarker: true,
                                customMarkerURL: '/i/mapflag.png'
                            }
                        }

                    });


                    //set map location and zoom
                    cmp.searchFormMap.field('map').control.map.setCentre({

                        longitude: '-1.505126953125',
                        latitude: '52.37224556866933',
                        zoomLevel: 6

                    });

                    //add pin to map if already searched on location
                    if (cmp.searchForm.hiddenData.mapX !== undefined && cmp.searchForm.hiddenData.mapX != 0) {

                        cmp.searchFormMap.val({

                            mapX: cmp.searchForm.hiddenData.mapX,
                            mapY: cmp.searchForm.hiddenData.mapY

                        });

                    }

                    //add double-click event to map to set search coordinates
                    GEvent.addListener(cmp.searchFormMap.field('map').control.map.map, "dblclick", function (overlay, latlng) {

                        cmp.searchForm.hiddenData.mapX = latlng.x;
                        cmp.searchForm.hiddenData.mapY = latlng.y;

                        cmp.locationChanged = true;

                        //using yahoo GEO to find map location name
                        yqlgeo.get(latlng.y, latlng.x, function (o) {

                            //var location = o.place.locality1 ? o.place.locality1.content : "Near " + o.place.name.content;

                            cmp.searchForm.field('location').val(o.place.locality1 ? o.place.locality1.content : "Map Location");

                        });

                        //put loading text in field
                        cmp.searchForm.field('location').val('Finding location...');

                        //hide map and unbind body click
                        $('#searchFormMap').hide();

                        $('BODY').unbind('click', hideMapPopup);

                    });


                    //handle body click event to hide location map
                    setTimeout(function () {

                        $('BODY').bind('click', hideMapPopup);

                    }, 100);

                    zIndexWorkaround();

                }

            });

        });


        //handle new search button
        TVI.event('#btn-newSearch', 'click', function () {

            $('#searchSummary').hide();
            $('#searchForm').show();

        });


        App.menu('findCampsite');

    };





    var getURL = function (e) {

        /* returns a url representing this search */

        if (e === undefined) { e = {}; }

        var url = '/search/';

        var args = '';

        var data = cmp.searchForm.val();

        for (var d in data) {

            //ignore certain fields
            if (d === 'success' || d === 'type') { continue; }

            //only add distance if location exists
            if (d === 'distance' && data[d] && data[d] !== '') {

                if (!data['location'] || data['location'] === '') { continue; }

            }

            //only add page if not 1
            if (d === 'page' && data[d] && data[d] === 1) { continue; }

            //only add sort if not a-z
            if (d === 'sort' && data[d] && data[d] === 'a-z') { continue; }

            if (data[d] && data[d] !== '') { args += "&" + d + "=" + data[d]; }

        }

        if (args !== '' && args.substr(0, 1) === '&') { args = args.replace('&', '?'); }

        if (e.replacePage === true) {

            if (args.indexOf('page=')) {

                args = args.replace('page=' + data["page"], 'page=[pageNo]');

            }
            else {
                args = args + (args.indexOf('?') < 0 ? '?' : '&') + "page=[pageNo]"
            }

        }

        return url + args;

    };





    var hideMapPopup = function (e) {

        /* handles the body click event to hide location map */

        if ($(e.target).parents('#searchFormMap:first').length === 0) {

            $('#searchFormMap').hide();

            $('BODY').unbind('click', hideMapPopup);

        }

    };





    var setSearchSummary = function () {

        var d = cmp.searchForm.val();

        var summaryItems = [];

        if (d.name !== '') { summaryItems.push(['Name', d.name]); }
        if (d.location !== '') { summaryItems.push(['Location', 'Within ' + d.distance + ' mile' + (d.distance > 1 ? 's' : '') + ' of ' + d.location]); }
        if (d.pitches !== '' && d.pitchTypeID > 0 && d.startDate !== '' && d.endDate !== '') {

            summaryItems.push(['Pitches', d.pitches]);
            summaryItems.push(['Pitch', $("#searchForm-pitchTypeID OPTION[value='" + d.pitchTypeID + "']").text()]);
            summaryItems.push(['Arrive', d.startDate]);
            summaryItems.push(['Leave', d.endDate]);

        }
        //        if (d.accomodationTypeID > 0) {

        //            summaryItems.push(['Accom.', $("#searchForm-accomodationTypeID OPTION[value='" + d.accomodationTypeID + "']").text()]);

        //        }
        if (d.accomodationTypes !== '') {

            var accomodationTypeArray = d.accomodationTypes.split(',');

            var accomodationTypeText = '';

            for (var i = 0, c = accomodationTypeArray.length; i < c; i++) {

                if (accomodationTypeText !== '') {

                    accomodationTypeText += ', ';

                }

                accomodationTypeText += $("#searchForm-accomodationTypes INPUT[value='" + accomodationTypeArray[i] + "']").parent().find('LABEL').text() ;

            }

            summaryItems.push(['Accom.', accomodationTypeText]);

            //            summaryItems.push(['Accom.', $("#searchForm-accomodationTypeID OPTION[value='" + d.accomodationTypeID + "']").text()]);

        }
        //        if (d.keywords !== ''){ summaryItems.push(['Keywords', d.keywords]); }

        if (summaryItems.length === 0) { return; }


        $('#searchSummary .criteria').html('{for i in items}<div class="pad"><strong>${i[0]}: </strong> ${i[1]}</div>{/for}'.process({ items: summaryItems }));

        $('#searchSummary').show();
        $('#searchForm').hide();

        TVI.Components.layout($('#searchSummary'));

    };





    /* Public */

    TVI.apply(cmp, {

        /* Properties */

        //store arrays of results
        args: {},
        meta: { columns: ["count", "page", "pages"], rows: [] },
        campsites: { columns: ["ID", "name", "town", "rating", "distance", "mapX", "mapY"], rows: [] },
        markers: { columns: ["ID", "mapX", "mapY"], rows: [] },
        filters: { columns: ["ID", "name", "type", "state"], rows: [] },
        facilities: { columns: ["categoryID", "ID", "name", "position", "state", "count"], rows: [] },
        amenities: { columns: ["categoryID", "ID", "name", "position", "state", "count"], rows: [] },
        pointers: { columns: ["ID", "name", "mapX", "mapY"], rows: [] },

        /* Methods */

        getURL: function (e) {

            return getURL(e);

        }

    });


    TVI.ready(init);


    return cmp;


} ();
