var emc_parcels = null;
var infowindow = null;
var carrier_code = '';
var map = null;
var bounds = null;
var markers = [];
var parcels_info = [];

jQuery(window).load(function(){

	// see function load_pickup_point_js in class envoimoinscher
	jQuery('body').append(map_container);

	// close map if selected carrier is changed and remove parcel point selection
	jQuery('body').delegate('input.shipping_method', 'change', function() {
        close_map();
        jQuery('input[name="_pickup_point"]').remove();
    });

	jQuery('body').delegate('.select-parcel','click',function(){

		init_map();
		carrier_attributes = jQuery(this).attr('id').split('_');
		carrier_code = carrier_attributes[1]+'_'+carrier_attributes[2];
		jQuery.ajax({
			url:ajaxurl,
			data: { action: 'get_points', security: ajax_nonce, carrier_code: carrier_code },
			dataType:'json',
			timeout:15000,
			error:error_pickup_points,
			success:show_pickup_points
		});
		if(typeof jQuery(this).attr("shown") == "undefined"){
			google.maps.event.trigger(map, 'resize');
		}
	});

	jQuery('#emcMap').delegate('.parcelButton','click',function(e) {
        e.preventDefault();
        select_pickup_point(jQuery(this).attr("data"));
    });

	jQuery('.emcClose').click(close_map);
});

/*
 * Initialize the google map for a new display
 */
function init_map() {
	jQuery('#emcMap').css('display','block');
    // set offset on the middle of the page (or top of the page for small screens)
    var offset = jQuery(window).scrollTop() + (jQuery(window).height() - jQuery('#emcMap').height())/2;
    if (offset < jQuery(window).scrollTop()) {
        offset = jQuery(window).scrollTop();
    }
    jQuery('#emcMap').css('top', offset + 'px');
    var options = {
        zoom: 11,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    if(!map && jQuery('#mapCanvas').length > 0) {
        map = new google.maps.Map(document.getElementById("mapCanvas"), options);
    }
    bounds = new google.maps.LatLngBounds();

	infowindow = new google.maps.InfoWindow();
	google.maps.event.trigger(map, 'resize');
}

/*
 * Close and clear the google map
 */
function close_map() {
	jQuery('#emcMap').css('display','none');
	jQuery('#prContainer').html('');
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
	markers = [];
	parcels_info = [];
}

/*
 * We update the zoom level to the best fit
 */
function update_zoom_map() {
	// zoom only if we have all markers
	if (emc_parcels.length === 0 ||  (emc_parcels.length !== 0 && markers.length < emc_parcels.length)) {
		return;
	}
	var bounds = new google.maps.LatLngBounds();

	for(var i = 0;i<markers.length;i++) {
		if (typeof markers[i] != 'undefined') {
			bounds.extend(markers[i].getPosition());
        }
	}
	map.setCenter(bounds.getCenter());
	google.maps.event.addDomListener(window, 'resize', function() {
        map.setCenter(bounds.getCenter());
	});
	map.fitBounds(bounds);
	map.setZoom(map.getZoom()-1);
	// if only 1 marker, unzoom
	if(map.getZoom()> 15){
		map.setZoom(15);
	}
	google.maps.event.trigger(map, 'resize');
}

/*
 * Add google map events on a marker
 */
function add_google_map_events(marker, code) {
    // open popup on map click
    google.maps.event.addListener(marker,"click",function() {
        if(typeof openedWindow != 'undefined' && openedWindow !== null) {
            openedWindow.close();
        }
        openedWindow = infowindow;
        infowindow.setContent(this.get("content"));
        infowindow.open(map,this);
    });
    // open popup on right column title click
    jQuery(document).delegate(".showInfo"+code, "click", function(){
        if(typeof openedWindow != 'undefined' && openedWindow !== null) {
            openedWindow.close();
        }
        openedWindow = infowindow;
        infowindow.setContent(marker.get("content"));
        infowindow.open(map,marker);
    });
}

/*
 * Now that we have all the parcel points, we display them
 */
function show_pickup_points(parcel_points) {
	emc_parcels = parcel_points;

    if (parcel_points.length === 0) {
        alert(lang.noPP);
        return;
    }

    // get "choose this relay point" translation
    if(parcel_points[0].code) {
        var ope = parcel_points[0].code.substring(0, 4);
        choose = "";
        if (lang.relayName[ope]) {
            choose = lang.relayName[ope];
        } else {
            choose = lang.relayName.default;
        }
    }

	// add parcel point markers
    for (var i in parcel_points) {
        // prevents bizarre javascript bug when array has extra prototype function
        if (isNaN(parseInt(i))) {
            continue;
        }

		point = parcel_points[i];
        //(function(i) {
            var address = point.address;
            var city = point.city;
            var zipcode = point.zipcode;
			var name = point.name;
			var code = point.code;
            info ="<div class='emcMakerPopup'><b>"+name+'</b><br/>'+
			    '<a href="#" class="parcelButton emcPointer" data="'+code+'">'+choose+'</a><br/>' +
				address+', '+zipcode+' '+city+'<br/>'+"<b>" + lang['Opening hours'] +
                "</b><br/>"+'<div class="emcSchedule">';

			for (var j in point.schedule) {
				day = point.schedule[j];

                /* Test to prevent js errors */
                if ((typeof(day.open_am)=="undefined") || (typeof(day.close_am)=="undefined") ||
                    (typeof(day.open_pm)=="undefined") || (typeof(day.close_pm)=="undefined")) {
                    // Point not found, skipping...
                    continue;
                }

				am = day.open_am !== "" && day.close_am !== "";
				pm = day.open_pm !== "" && day.close_pm !== "";
				if (am || pm) {
					info += '<span class="emcDay">'+lang['day_'+day.weekday]+'</span>';
					if (am) {
						info += formatHours(day.open_am) +'-'+formatHours(day.close_am);
					}
					if (pm) {
						if (am) {
							info += ', '+formatHours(day.open_pm) +'-'+formatHours(day.close_pm);
						}
						else {
							info += formatHours(day.open_pm) +'-'+formatHours(day.close_pm);
						}
					}
                    info += '<br/>';
				}
			}
			info += '</div>';

			parcels_info[i] = info;

            var emcMarker = {
                url: plugin_url + "/assets/img/marker-number-"+(parseInt(i)+1)+".png",
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(13, 37),
                scaledSize: new google.maps.Size(26, 37)
            };

            var latlng = new google.maps.LatLng(parseFloat(point.latitude),parseFloat(point.longitude));

            var marker = new google.maps.Marker({
                map: map,
                position: latlng,
                icon: emcMarker,
                title : name
            });
            marker.set("content", parcels_info[i]);
            bounds.extend(marker.getPosition());

            add_google_map_events(marker, code);

            markers[i] = marker;
            // update zoom
            update_zoom_map();
        //})(i);
    }

    map.fitBounds(bounds);

    // add list of points html (in map pop)
    var html = '';
    html += '<table><tbody>';
    for (i in parcel_points) {
        // prevents bizarre javascript bug when array has extra prototype function
        if (isNaN(parseInt(i))) {
            continue;
        }
        
        point = parcel_points[i];
        html += '<tr>';
        html += '<td><img src="' + plugin_url + '/assets/img/marker-number-'+(parseInt(i)+1)+'.png" class="emcMarker" />';
        html += '<div class="emcPointTitle"><a class="showInfo' + point.code + ' emcPointer">' + point.name + '</a></div><br/>';
        html += point.address + '<br/>';
        html += point.zipcode + ' ' + point.city + '<br/>';
        html += '<a class="parcelButton emcPointer" data="'+point.code+'"><b>'+choose+'</b></a>';
        html += '</td>';
        html += '</tr>';
    }
    html += '</tbody></table>';
    jQuery('#emcMap #prContainer').html(html);


    // remove info if we click on the map
	google.maps.event.addListener(map,"click",function() {
		infowindow.close();
	});
}

/*
 * We clicked on the "choose this relay point" link on the map popup
 */
function select_pickup_point(pointCode) {
    var point;
    jQuery.each(emc_parcels, function(index, el) {
        if (el.code == pointCode) {
            point = el;
        }
    });
	code = pointCode.split('-',2)[1];
	name = point.name;
    var carrier_code;
    if (jQuery('input[type="hidden"].shipping_method').length === 1) {
        carrier_code = jQuery('input[type="hidden"].shipping_method').attr('value');
    } else {
        carrier_code = jQuery('input.shipping_method:checked').attr('value');
    }
    jQuery.ajax({
        url: ajaxurl,
        method: "post",
        data: { action: 'set_point', security: ajax_nonce, pickup_point_code: code, pickup_point_name: name, carrier_code: carrier_code },
        dataType: 'json',
        timeout: 15000,
        error: function() {
            // add input if not present (or form has been refreshed)
            if (jQuery('input[name="_pickup_point"]').length === 0) {
                jQuery('form[name="checkout"]').append(jQuery('<input type="hidden" name="_pickup_point" />'));
            }
        	jQuery('input[name="_pickup_point"]').val(code);
        },
        success: function() {
            jQuery('#emc-parcel-client').html(name);
        }
    });
	jQuery('#emcMap').css('display','none');
	close_map();
}

function error_pickup_points(jqXHR, textStatus, errorThrown ) {
	alert(lang['Unable to load parcel points']+' : '+errorThrown);
}

/* from 12:00:00 to 12:00 */
function formatHours(time)
{
    var explode = time.split(':');
    if (explode.length == 3) {
        time = explode[0]+':'+explode[1];
    }
    return time;
}
