﻿namespace('rentcycle.marketplace');

rentcycle.marketplace.search = {
    cities_pane_visible: false,
    location: '',
    query: '',
    processLocalSearch: function (location, command) {
        var new_location = location;
        var search_query = $('#hdr_src_q').val();
        var geoSvc = new rentcycle.geolocation.geoService();
        var userLoc = geoSvc.getUserLocation();

        // set global variable
        qlocation = location;

        // launch search
        rentcycle.marketplace.search.saveSearchLocation(search_query, location, userLoc);
    },
    saveSearchLocation: function (search_query, newLocation, userLocation) {
        rentcycle.marketplace.search.query = search_query;
        rentcycle.marketplace.search.location = newLocation;

        postJSONtoMVC("/session/saveSearchLocation",
            {
                query: search_query,
                location: newLocation.user_input,
                formatted_address: newLocation.formatted_address,
                city: newLocation.city,
                stateRegion: newLocation.state_region,
                postalCode: newLocation.postal_code,
                country: newLocation.country,
                latitude: newLocation.latitude,
                longitude: newLocation.longitude,
                userLatitude: userLocation.latitude,
                userLongitude: userLocation.longitude,
                userCity: userLocation.city,
                userCountry: userLocation.country,
                userStateRegion: userLocation.state_region
            },
            function (result) {
                var urlFormattedLocation = result;
                qlocation.location_url_format = urlFormattedLocation;
                rentcycle.interactive.unblockElement('#dropdown_cities_yourcity');

                var searchQueryBox = $('#hdr_src_q');
                if (searchQueryBox.val() == '') {
                    $('#button_drop_down_cities').html(qlocation.user_input);
                    $('.button_drop_down_cities').click();
                    searchQueryBox.focus();
                }
                else {
                    $('#hdr_src_form').submit();
                }

            },
            processAjaxError
        );
    },
    init: function () {

        $('#comingsoon_setlocation').click(function () {
            rentcycle.interactive.blockElement('#dropdown_cities_yourcity');
            var geoSvc = new rentcycle.geolocation.geoService();
            geoSvc.getGeoDataFromAddress($('#srch_loc').val(), rentcycle.marketplace.search.processLocalSearch, "process_local_search");
        });

        $('#button_drop_down_cities').html(qlocation.user_input);
        $('#cities_list a').click(function () {
            $('#button_drop_down_cities').html($(this).html());
            qlocation.location_url_format = $(this).attr('data-url-format');
            $('.button_drop_down_cities').click();
        });
        $('#hdr_src_form').submit(function () {
            if ($('#hdr_src_q').val() != '') {
                window.location.href = '/search/' + $('#hdr_src_q').val() + '/' + qlocation.location_url_format;
            }
            else {
                $('#hdr_src_q').focus();
            }
            return false;
        });
        $('#comingsoon_form').validate({
            errorPlacement: function (error, element) {
            }
        });
        $('#comingsoon_notifyrequest').click(function () {
            if ($('#comingsoon_form').valid()) {
                rentcycle.interactive.blockElement('#comingsoon_form');
                $('#comingsoon_error').addClass('hide');
                $.ajax({
                    url: '/userrequest/marketrequest',
                    type: 'post',
                    data: {
                        email: $('#comingsoon_email').val(),
                        zip: $('#comingsoon_zip').val(),
                        product: $('#comingsoon_product').val()
                    },
                    success: function (data) {
                        if (data.result == 1) {
                            $('#dropdown_cities_comingsoon').fadeOut('fast', function () { $('#dropdown_cities_thankyou').fadeIn(); });
                        }
                        else {
                            $('#comingsoon_error').html(data.messages[0].Message).removeClass('hide');
                        }
                    },
                    complete: function () {
                        rentcycle.interactive.unblockElement('#comingsoon_form');
                    }
                });

            }
        });

        $('.button_drop_down_cities').click(function () {
            $('#dropdown_cities_tab').fadeToggle(150);
            $('#dropdown_cities').slideToggle(200);

            if (!rentcycle.marketplace.search.cities_pane_visible) {
                $(document).unbind('click', rentcycle.marketplace.search.removeLocationPane).bind('click', rentcycle.marketplace.search.removeLocationPane);
            }

            rentcycle.marketplace.search.cities_pane_visible = !rentcycle.marketplace.search.cities_pane_visible;

            return false;
        });

        if (page == "business-products-variation") {
            this.loadBusinessOnMap();
            this.setupProductDescriptionView();
        } else if (page == "business-detail") {
            this.loadBusinessOnMap();
        } else if (page == "merchant-manual-reservation") {
            this.setupProductDescriptionView();
        }

        this.autocomplete();
    },
    autocomplete: function () {
        $("#hdr_src_q, #hp_src_q").autocomplete({
            source: "/storeapp/search_marketplace_products_byname",
            minLength: 2,
            delay: 1000,
            zIndex: 99999,
            select: function (event, ui) {
                clog(ui.item ? ("Selected: " + ui.item.label) : "Nothing selected, input was " + this.value);
            }
        });
    },
    removeLocationPane: function (e) {
        var checkParent = function (t) {
            while (t.parentNode) {
                if (t == document.getElementById('dropdown_cities')) {
                    return false;
                }
                t = t.parentNode
            }
            return true;
        }
        var target = (e && e.target) || (event && event.srcElement);
        if (rentcycle.marketplace.search.cities_pane_visible && checkParent(target) && target.id != 'button_drop_down_cities') {
            $('#dropdown_cities').slideToggle(200);
            $('#dropdown_cities_tab').fadeToggle(150);
            $(document).unbind('click', rentcycle.marketplace.search.removeLocationPane);
            rentcycle.marketplace.search.cities_pane_visible = false;
        };
    },
    loadBusinessOnMap: function () {
        var zoomLevel = 12;
        var geoSvc = new rentcycle.geolocation.geoService();

        var lat = $("#bl_loc_lat").val();
        var lng = $("#bl_loc_lng").val();
        var blid = $("#bl_loc_id").val();
        var primary_key = "bussiness_loc_" + blid;
        var html = "";

        var targetMap = geoSvc.initGMapsAPI(lat, lng, zoomLevel);
        geoSvc.createMapMarkerByCoordinates(lat, lng, html, primary_key, targetMap)
    },
    setupProductDescriptionView: function () {
        var shortText = "";
        var fullText = $("#product_details .full .text").text();
        $("#bt_view_less").hide();
        var getShortText = function () {
            return $("#product_details .full .text").hide().text()    // get the text within the div
        .trim()    // remove leading and trailing spaces
        .substring(0, 400)    // get first xx characters
        .split(" ") // separate characters into an array of words
        .slice(0, -1)    // remove the last full or partial word
        .join(" ") + "..."; // combine into a single string and append "..."
        }

        // remove formatting
        $("#product_details .full .text").text(fullText);

        // load short text if too long
        if (fullText.length > 400) {
            shortText = getShortText();
            $("#product_details .short").text(shortText);

            // view more
            $("#bt_view_more").show().click(function () {
                $("#product_details .short").hide();
                $("#bt_view_more").hide();
                $("#bt_view_less").show();
                $("#product_details .full .text").slideDown("fast");
            });

            // view less
            $("#bt_view_less").click(function () {
                $("#product_details .short").show();
                $("#bt_view_more").show();
                $("#bt_view_less").hide();
                $("#product_details .full .text").hide();
            });
        }
    }
};

$(document).ready(function () {
    rentcycle.marketplace.search.init();
});
