var infoBox = null;
var gMap;
var params;
var gIconStore;
var gIconFranchise;
var gShadow;
var geocoder;
var latlng;
var markers = [];
var storeName = [];
var franchise = [];
var store_location = [];
var stores = [];
var i = 0;
var gResponse;
var shape = {
    coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
    type: 'poly'
};

$(window).load(function(){
    gmaps();
});

/* +window load functions */
function gmaps() {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({address:'Brasil'},function(results, status){
        latlng = results[0].geometry.location;

        var myOptions = {
          zoom: 4,
          mapTypeControl: false,
          scrollwheel: false,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        gMap = new google.maps.Map(document.getElementById("map-container"), myOptions);
    });

    gIconStore = new google.maps.MarkerImage(
        rootUrl+'public/imgs/buttons/gmaps-icon-store.png',
        new google.maps.Size(20,32),
        new google.maps.Point(0,0),
        new google.maps.Point(10,32)
    );

    gIconFranchise = new google.maps.MarkerImage(
        rootUrl+'public/imgs/buttons/gmaps-icon-franchise.png',
        new google.maps.Size(20,32),
        new google.maps.Point(0,0),
        new google.maps.Point(10,32)
    );

    gShadow = new google.maps.MarkerImage(
        rootUrl+'public/imgs/buttons/gmaps-icon-shadow.png',
        new google.maps.Size(37, 32),
        new google.maps.Point(0,0),
        new google.maps.Point(18, 32)
    );

    $('#store-form').one('submit',searchStores);
}

function searchStores() {
    var loaderHtml = '<p>Carregando <span id="store-actual"></span> de <span id="store-total"></span> lojas</p>';
    var obj = $(this);
    obj.css({opacity:'0.5'});

	$('.store-list .message').hide();
	$('.store-list .loader').fadeIn(500);
    
    if ($('#store_state').val() && $('#store_city').val()) {
        // Limpar todos os marcadores anteriores
        clearInfoBox();

        clearMarkers();

        $('#store-list').empty();

        params = {state:$('#store_state').val(),city:$('#store_city').val(),franchise:$('#store-franchise').val()};

        // Montar o mapa
        $('#google-maps-container').block({message:loaderHtml,css:{width:'300px'}});
        $.getJSON(rootUrl+'whereToFind/search',params, function(data) {
            gResponse = data;
            if ($('#store-franchise').val() == 1) {
                tracker('/site/franquias/localizador-lojas/'+data.slug);
            } else {
                tracker('/site/onde-encontrar/'+data.slug);
            }

            if (typeof data.results == "undefined" || data.results.length == 0) {                
                geocoder.geocode({address:'Brasil'},function(results, status){
                    gMap.setCenter(results[0].geometry.location);
                    gMap.setZoom(4);
					$('.store-list .no-results').fadeIn(200);
                });
            } else {
                gMap.setCenter(new google.maps.LatLng(data.lat,data.lng));
                gMap.setZoom(6);
                
                stores = data.results;

                $('#store-actual').html(0);
                $('#store-total').html(data.results.length);

                i = 0;
                loadMarker();
            }
			enableClick(obj);
        });
    } else {
        $('.store-list .error').fadeIn(200);
		enableClick(obj);
    }
    return false;
}

function loadMarker() {    
    if (i < gResponse.results.length) {
        var item = gResponse.results[i];
        i++;
        $('#store-actual').html(i);
        if (item.location != null) {
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(item.location[1], item.location[0]),
                map: gMap,
                icon: (item.franchise == 'S') ? gIconFranchise : gIconStore,
                shape: shape,
                title: item.id+'-'+item.name
            });

            google.maps.event.addListener(marker,'click',function(){
                setActiveStore(marker);
            });

            markers.push(marker);
        }        
        setTimeout(loadMarker,20);
    } else {        
        $('#store-list').load(rootUrl+'whereToFind/loadStores',params, function(){
            $('.store-list .message').fadeOut(200);
            $('#store-list li').unbind('click').click(findActiveMarker);
            $('#google-maps-container').unblock();
        });
    }
}

function findActiveMarker() {
    $('#store-list li').unbind('click');
    var storeId = getListId($(this).attr('id'));

    var i = 0;
    
    while(getMarkerId(markers[i].getTitle()) != storeId) {
        i++;
    }
    
    $('#store-list li.active').removeClass('active');
    $(this).addClass('active');    

    loadInfoBox(markers[i],storeId);
}

function setActiveStore(marker) {    
    var markerId = getMarkerId(marker.getTitle());
    $('#store-list li.active').removeClass('active');
    
    var i = 0;
    
    while(stores[i].id != markerId) {
        i++;
    }
    
    $('#store-'+stores[i].id).addClass('active');
    $('.store-list .content').scrollTop(0).scrollTop($('#store-'+stores[i].id).position().top);
    loadInfoBox(marker,stores[i].id);
}

function enableClick(obj) {
	obj.css({opacity:1});
	$('#store-form').one('submit',searchStores);
}

function clearMarkers() {
    for(i=0;i<markers.length;i++) {
        markers[i].setMap(null);
    }
    markers = [];
}

function clearInfoBox() {
    if (infoBox != null) {
        infoBox.setMap(null);
    }
}
function closeInfoBox() {
    clearInfoBox();
    $('#store-list li.active').removeClass('active');
}

function loadInfoBox(marker,storeId) {
    clearInfoBox();    
    infoBox = new InfoBox({latlng: marker.getPosition(), map: gMap, content: '<img src="'+rootUrl+'public/imgs/others/loader.gif" alt="Carregando" class="loader">', closeCallback: closeInfoBox});

    $.post(rootUrl+'whereToFind/getStore',{id:storeId},function(response){
       infoBox.setContent(response);
       $('#store-list li').unbind('click').click(findActiveMarker);
    });
}

function getMarkerId(point) {
    parts = point.split('-');
    return parts[0];
}

function getListId(storeId) {
    parts = storeId.split('-');
    return parts[1];
}

/* end window load functions */
