/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    PrestaShop SA <contact@prestashop.com>
*  @copyright 2007-2017 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*
* Don't forget to prefix your containers with your own identifier
* to avoid any conflicts with others containers.
*/
var carte;
var ec_id_cart;
var ec_id_lang;
var ec_id_shop;
var tabMarqueurs;
var choose = false;
var idprchoose;
var idtranspo;
var address_lat;
var address_lng;
var address_rp = "";
$(document).ready(function() {
    
    var cr = $('.delivery-option.js-delivery-option input:checked').parent().parent().parent();
    $('.displayCarCCV', cr).show();

    $('body').on('click','.prev_m', function() {
        const container = document.getElementById("ec_ccv_creneau");
        container.scrollLeft -= 50;
    });
    $('body').on('click','.next_m', function() {
        const container = document.getElementById("ec_ccv_creneau");
        container.scrollLeft += 50;
    });

    $( window ).on( "load", function() {
        idtranspo = $('#popuppointrelais').attr('data-idtranspo');
        ec_id_cart = $('#popuppointrelais').attr('data-idcart');
        ec_id_lang = $('#ec_id_lang').val();
        ec_id_shop = $('#ec_id_shop').val();
        address_lat = $('#address_lat').val();
        address_lng = $('#address_lng').val();
        idSlotExi = $('#idSlot').val();
        if (idSlotExi) {
            var presel = idSlotExi.split('!');
        } else {
            var presel = [];
        }

        if ($('#checkout-delivery-step.js-current-step').length) {
            if (presel[2]) {
                if ($( ".row.delivery-option input:checked" ).attr('id') == presel[2]) {   
                    var p =  $("#"+presel[2]).closest('.js-delivery-option');
                    if ($('.displayPlaning', p).css('display') != 'none') {        
                        $('.hours_min[data-idslot="'+presel[0]+'!'+presel[1]+'"]').click();  
                    }   
                }       
            }
        }
        if  (!$('.prrr').length) {
            $( ".row.delivery-option input" ).each(function() {
                if (parseInt($(this).val())==idtranspo){
                    $(this).parent().parent().parent().hide();
                }     
            });
        }
        $( ".row.delivery-option input" ).each(function() {
            if ($(this).prop('checked')) {
                var p = $(this).closest('.js-delivery-option');
                if (parseInt($(this).val())==idtranspo){                
                    $('#popuppointrelais').show();
                    initmap();
                }
                if ($('.displayCarCCV', $(p)).length) {
                    $('.displayCarCCV', $(p)).show();
                }
            }     
        })
        $( ".delivery_option_radio" ).parent().removeClass();
           
            
        var is_iPad = navigator.userAgent.match(/iPad/i) != null;
        
        $('body').on('click','#closepr', function() {
            $('#popuppointrelais').hide();
        });
        
        $('body').on('click','.closeinfopr, .chooseotherpr', function() {
            $('.infosupp').hide();
            $('.closeinfopr').hide();
            $('.prrr').show();
            $('.masterprrr').show();
        });
        
        $('body').on('click','.choosepr', function() {
            choosePr($(this));
        });
        
        $('body').on('click','.info.bttboxg', function() {
            $('.prrr').hide();
            $('.prrr').parent().hide();
            $('#prrr'+$(this).attr('data-id')).show();
            $('#prrr'+$(this).attr('data-id')).parent().show();
            $('.prselect').hide();
            $('#prrr'+$(this).attr('data-id')+' .closeinfopr').show();
            $('#prrr'+$(this).attr('data-id')+' .closeinfopr').parent().show();
            $('#prinfosup'+$(this).attr('data-id')).slideToggle();
        });
        $( document ).ajaxComplete(function(event, xhr, settings) {
            params = settings.data;
            
            if (params) {
                if (params.indexOf("id_delivery_option="+idtranspo+",") >= 0 && params.indexOf("method=updateExtraCarrier") >= 0) {
                    if (choose) {
                        $('#praddress').html($('#prrr'+idprchoose).attr('data-addr'));
                        $('#prpostcodecity').html($('#prrr'+idprchoose).attr('data-postcode')+' '+$('#prrr'+idprchoose).attr('data-city'));
                        $('#prcountry').html($('#prrr'+idprchoose).attr('data-country'));
                        $('#pointrelaisactif').show();
                    }
                    $('#popuppointrelais').show();
                    initmap();
                    $('#carte').insertBefore('#right_column .ax_tunnelsummary_address');                    
                }  else {
                   if (params.indexOf("method=updateExtraCarrier") >= 0) {
                       $('#right_column #carte').remove();
                       $('#pointrelaisactif').hide();
                       updateTemp(false);
                   }
                }
            }
        	
        });
        
        $('body').on('click','.row.delivery-option input', function() {
            $('.displayCarCCV').hide();
            updateCreneau();
            var p = $(this).closest('.js-delivery-option');
            if (parseInt($(this).val())==idtranspo){
                if ($(this).prop("checked")) {
                    if (choose) {
                        setTimeout(function(){
                        $('#praddress').html($('#prrr'+idprchoose).attr('data-addr'));
                        $('#prpostcodecity').html($('#prrr'+idprchoose).attr('data-postcode')+' '+$('#prrr'+idprchoose).attr('data-city'));
                        $('#prcountry').html($('#prrr'+idprchoose).attr('data-country'));
                        $('#pointrelaisactif').show();
                        $( ".closeinfopr" ).trigger( "click" );
                    }, 1000);
                    }
                    $('#popuppointrelais').show();
                    initmap();
                
                
                }
                if ($(window).width()<768){
                    if ($(this).attr('checked')=='checked') {
                        $('#popuppointrelais').show();
                    }
                }
            } else {
                $('#popuppointrelais').hide();
                $('#pointrelaisactif').hide();
                updateTemp(false);
            }
            if ($('.displayCarCCV', $(p)).length) {
                $('.displayCarCCV', $(p)).show();
            }
        });
        

    });
    $('body').on('click','.prrr', function() {
        //console.log(tabMarqueurs);
        for (var i = 0; i < tabMarqueurs.length; i++ ) {  //I assume you have your infoboxes in some array
         tabMarqueurs[i].infowindow.close();
        }
         carte.setCenter(new google.maps.LatLng($(this).attr('data-lat'),$(this).attr('data-lng')));
         valcpt = parseInt($(this).attr('data-cpt'));
         //console.log(tabMarqueurs[valcpt]);
         google.maps.event.trigger( tabMarqueurs[valcpt], 'click' );;
    });
    $('body').on('click','#testsearch', function() {
        address = $('#search_ecrelay').val();
        refreshRp(address);
    });
    

    $('body').on('click','.hours_min', function() {
        $(this).closest('.displayPlaning').hide();
        var p = $(this).closest('.displayCarCCV');
        $('.confirmCreneau', $(p)).html('Livraison programmée le '+$(this).attr('data-date_dmy')+' entre '+$(this).attr('dataHMin')+' et '+$(this).attr('dataHMax')+' <span class="lnk">(modifier)</span>');
        $('.confirmCreneau', $(p)).show();
        $('.confirmCreneau', $(p)).attr('dataSlot', $(this).attr('data-idslot'));        
        updateCreneau();
    });

   
    $('body').on('click','.lnk', function() {
        //console.log('ok');
        var p = $(this).closest('.displayCarCCV');
        $('.displayPlaning',p).show();
        $('.confirmCreneau',p).hide();
    });
    
    $('body').on('keydown','input#search_ecrelay', function(event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            address = $('#search_ecrelay').val();
            refreshRp(address);
        }
    });

    $('#carte').insertBefore('#right_column .ax_tunnelsummary_address');

    $('body').on('click','.masterprrr', function(){
        $('.masterprrr').removeClass('selected');
        $(this).addClass('selected');
    });

    $('.displayCarCCV').each(function(){
        var idC = $(this).attr('rel');
        var block = $(this).prop('outerHTML');
        console.log('////', '#delivery_option_'+idC, $('#delivery_option_'+idC).length)
        if ($('#delivery_option_'+idC).length) {
            var p = $('#delivery_option_'+idC).parent().parent().parent();
            $(block).appendTo(p);
        } else if ($('#delivery_option_0_'+idC).length) {

            var p = $('#delivery_option_0_'+idC).parent().parent().parent();
            $(block).appendTo(p);
        }
        $(this).remove();
    });

    $('body').on('click','.infosplus', function() {
        id = $(this).attr('data-id');
        $('#prrr'+id+' .infosupp').slideToggle();
    });
    

    $('body').on('click','#changepoint', function() {
        $('#popuppointrelais').show();
    });
    
    //submit
    $(document).on('submit', "#checkout-delivery-step form", function(){
        res = true;
        $( "input.delivery_option_radio" ).each(function() {
            if (parseInt($(this).val())==idtranspo && (idprchoose>0) == false && $(this).prop('checked')){
                    res = false;
            }
        });

        if (!res) {
            alert($('#tradchoosepr').val());
            return false;
        } else {
            return true;
        }   
    });

    $('body').on('click','#popuppointrelais',function(){
        if (!$('.popuprelaisinner:hover').length) {
            $(this).hide();
        }
    });

    $('body').on('click', 'button[name="confirmDeliveryOption"]', function(e) {
        var p = $('.row.delivery-option input:checked').closest('.js-delivery-option');
        if ($('.displayPlaning', p).css('display') != 'none' && $('.displayPlaning', p).length == 1) {            
            alert('Confirmez un creneau');
            e.preventDefault();
            return false;
        }
    });

    $('body').on('click','#toppr',function(){
        $('#popuppointrelais').hide();
    });

});

function updateCreneau() {
    var p = $('.row.delivery-option input:checked').closest('.js-delivery-option');
    if ($('.confirmCreneau',p).css('display') != 'none') {
        var carrier = $('.row.delivery-option input:checked').attr('id');
        if ($('.confirmCreneau',p).attr('dataslot')!==undefined) {
            var cren = ($('.confirmCreneau',p).attr('dataslot'))+'!'+carrier;
        } else {
            var cren = '';
        }
    } else {
        var cren = '';
    }
    $.ajax({
        url: ajaxFileRelayPoint,
        type: 'POST',
        data: ({
            confRes: '1',
            cren: cren
        }),
        dataType: 'html'
    });
}
     
function initmap() {
    var latlng = new google.maps.LatLng(address_lat, address_lng);
            //objet contenant des propriétés avec des identificateurs prédéfinis dans Google Maps permettant
            //de définir des options d'affichage de notre carte
    var options = {
        center: latlng,
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };      
            //constructeur de la carte qui prend en paramêtre le conteneur HTML
            //dans lequel la carte doit s'afficher et les options
    carte = new google.maps.Map(document.getElementById("carte"), options);
    if (address_rp.length > 0) {
        $('#search_ecrelay').val(address_rp);
    }
    refreshMarqueur(); 
    
}

// function refreshCalendar()
// {
//     $.ajax({
//         url: ajaxFileRelayPoint,
//         type: 'POST',
//         data: ({
//             semaCCV: '1',
//             idShopG : ec_id_shop_g,
//             cpt_date: cpt_date
//         }),
//         dataType: 'html'
//     })
//     .done(function (data) {
//         $('##displayCreneau').html(data);
//     });
// }

function choosePr(element)
{
    choose = true;
    idprchoose = element.attr('data-id');
    $('.prselect').hide();
    $('#pr'+element.attr('data-id')).show();
    $('#praddress').html(element.attr('data-addr'));
    $('#prpostcodecity').html(element.attr('data-postcode')+' '+element.attr('data-city'));
    $('#prcountry').html(element.attr('data-country'));
    $('#prname').html(element.attr('data-name'));
    $('#pointrelaisactif').show();
    $('#popuppointrelais').hide();
    //$('#right_column #carte').remove();
    $('#changepoint').show();
    updateTemp(true, idprchoose);
}

function refreshRp(address)
{
    data = ({
        majsel: 1,
        address: address,
        id_shop: ec_id_shop,
        id_lang: ec_id_lang,
        tokenecrelaypoint: tokenecrelaypoint,
    });

    $.ajax({
            url: ajaxFileRelayPoint2,
            type: "POST",
            data: data,
            dataType: "json"
        })
    .done(function (data) {
        $('#listpr').html(data.display);
        address_lat = data.lat;
        address_lng = data.lng;
        address_rp = data.address_rp;
        refreshMarqueur();
        new_pos = new google.maps.LatLng(address_lat, address_lng);
        carte.setCenter(new_pos);
    });
}

function refreshMarqueur()
{
    var cpt = 0;
    tabMarqueurs = new Array();
    $( ".prrr" ).each(function() {
    
        $(this).attr('data-cpt',cpt);
        var id = $(this).attr('data-id');
        var marqueur = new google.maps.Marker({
            position: new google.maps.LatLng($(this).attr('data-lat'),$(this).attr('data-lng')),
            map: carte,
            title: $(this).attr('data-id'),
        });
        //var contentString = '<div id="contentboxg">'+
//            '<div id="siteNotice">'+
//            '</div>'+
//            '<h2 id="firstHeading" class="firstHeading">'+$(this).attr('data-name')+'</h2>'+
//            '<div id="bodyContent">'+
//            '<p>'+$(this).attr('data-addr')+'</p>'+
//            '<p>'+$(this).attr('data-postcode')+' '+$(this).attr('data-city')+'</p>'+
//            '<div id="bogxbutt"><span class="info bttboxg" data-id="'+$(this).attr('data-id')+'">Informations</span> <span class="choosepr bttboxg" data-id="'+$(this).attr('data-id')+'" data-name="'+$(this).attr('data-name')+'" data-addr="'+$(this).attr('data-addr')+'" data-postcode="'+$(this).attr('data-postcode')+'" data-city="'+$(this).attr('data-city')+'" data-country="'+$(this).attr('data-country')+'">'+$('#popuppointrelais').attr('data-trad')+'</span></div></div>'+
//            '</div>'
//        ;
        var contentString = '<div id="contentboxg">'+
            '<div id="siteNotice">'+
            '</div>'+
            '<h2 id="firstHeading" class="firstHeading">'+$(this).attr('data-name')+'</h2>'+
            '<div id="bodyContent">'+
            '<p>'+$(this).attr('data-addr')+'</p>'+
            '<p>'+$(this).attr('data-postcode')+' '+$(this).attr('data-city')+'</p>'+
            '<div id="bogxbutt"><span class="info bttboxg" data-id="'+$(this).attr('data-id')+'">Informations</span> <span class="choosepr bttboxg" data-id="'+$(this).attr('data-id')+'" data-name="'+$(this).attr('data-name')+'" data-addr="'+$(this).attr('data-addr')+'" data-postcode="'+$(this).attr('data-postcode')+'" data-city="'+$(this).attr('data-city')+'" data-country="'+$(this).attr('data-country')+'">'+$('#popuppointrelais').attr('data-trad')+'</span></div></div>'+
            '</div>'
        ;
        marqueur.infowindow = new google.maps.InfoWindow({
            content: contentString
        });  
    
        marqueur.addListener('click', function() {
            for (var i = 0; i < tabMarqueurs.length; i++ ) {  //I assume you have your infoboxes in some array
                tabMarqueurs[i].infowindow.close();
            }
            marqueur.infowindow.open(carte, marqueur);
        });
        tabMarqueurs.push(marqueur); 
        //new google.maps.event.trigger( marqueur, 'click' );
        cpt++;
    });  
}
function updateTemp(add, idprchoose = null)
{
    data = ({
        id_shop: id_shop,
        id_lang: id_lang,
        id_cart: ec_id_cart,
        tokenecrelaypoint: tokenecrelaypoint,
    });
    if (add) {
        data['addtemp'] = 1;
        data['id_pr'] = idprchoose;
    } else {
        data['deltemp'] = 1;
    }
    $.ajax({
            url: ajaxFileRelayPoint,
            type: "POST",
            data: data,
            dataType: "json"
        })
    .done(function (data) {
    });
}