﻿var Trifil = function () {
    var map, geocoder, retornoCoder, directionDisplay, directionsService;
    return {
        //Consulta dados e adiciona no html
        RetornaDadosJson: function (produtoId, appendId, templateId, tipoBusca) {
            $.getJSON("/Shared/Ashx/ConsultaDadosJson.ashx",
            {
                id: produtoId,
                tipo: tipoBusca
            },
            function (data) {
                if (data != null) {
                    $(appendId).empty();
                    $(templateId).tmpl(data).appendTo(appendId);
                }
            });
        },

        //Randomiza imagens
        ShowImage: function () {
            var theImages = new Array();
            theImages[0] = "/images/img-modelo-home01.png";
            theImages[1] = "/images/img-modelo-home02.png";
            theImages[2] = "/images/img-modelo-home03.png";
            theImages[3] = "/images/img-modelo-home04.png";
            theImages[4] = "/images/img-modelo-home05.png";

            var j = 0
            var p = theImages.length;
            var preBuffer = new Array()
            for (i = 0; i < p; i++) {
                preBuffer[i] = new Image()
                preBuffer[i].src = theImages[i]
            }
            var whichImage = Math.round(Math.random() * (p - 1));
            document.write('<img src="' + theImages[whichImage] + '">');
        },

        //Realiza votação na enquete
        VotaNaEnquete: function () {
            var radio = $("#divEnquete").find("input");
            for (var i = 0; i <= radio.length - 1; i++) {
                if ($(radio[i]).is(":checked")) {
                    $.ajax({
                        type: "POST",
                        url: "/Shared/Ashx/TransfereDados.ashx",
                        data: "&tipo=enquete&i=" + $(radio[i]).val(),
                        dataType: "json",
                        success: function (retorno) {
                            if (retorno != null) {
                                $("#perguntas").css("display", "none");
                                $("#respMsg").css("display", "block");

                                //$("#respostas").empty();
                                //$("#respostasTemplate").tmpl(retorno).appendTo("#respostas");
                            }
                        }
                    });
                }
            }
        },

        //Inicializa o mapa
        InicializarMapa: function (mapaId, idDivMapa) {
            geocoder = new google.maps.Geocoder();
            directionsDisplay = new google.maps.DirectionsRenderer();
            directionsService = new google.maps.DirectionsService();

            var latLng = new google.maps.LatLng('-23.5489433','-46.6388182');
            var opcoes = {
                zoom: 12,
                scrollwheel: true,
                streetViewControl: true,
                center: latLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                navigationControlOptions: {
                    style: google.maps.NavigationControlStyle.ZOOM_PAN
                }
            };
            map = new google.maps.Map($('#' + idDivMapa)[0], opcoes);
            directionsDisplay.setMap(map);
        },

        //Retorna a logitude, latitude e Maracador
        GeoCoder: function (endereco) {
            if (geocoder) {
                geocoder.geocode({ 'address': endereco }, function (result, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        
                        var infoWindow = new google.maps.InfoWindow({
                            content: endereco
                        });

                        map.setCenter(result[0].geometry.location);
                        var marker = new google.maps.Marker({
                            map: map,
                            position: result[0].geometry.location,
                            title: endereco
                        });

                        google.maps.event.addListener(marker, 'click', function () {
                            infoWindow.open(map, marker);
                        });

                        retornoCoder = result[0].geometry.location.ua + ',' + result[0].geometry.location.wa;
                        directionsDisplay.setMap(map);
                    }
                });
            }
        },

        //Traça a rota no mapa
        Route: function (origem, destino) {
            var waypts = [];
            var request = {
                origin: origem,
                destination: destino,
                waypoints: waypts,
                optimizeWaypoints: true,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

            directionsService.route(request, function (result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    $('#msg').empty();
                    directionsDisplay.setDirections(result);

                    $('#trajeto').css('display', 'block');
                    directionsDisplay.setPanel(document.getElementById('trajeto'));

                }else{
                    $('#msg').text('Não foi possível traçar a rota.');
                }
            });
        },
    }
} ();
