// The following extensions to the Array object are meant
// for browsers that do not yet support these functions
// natively.  The code for these implementations was taken
// from the Mozilla Developer Center (developer.mozilla.org).
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (fun) {
        var len = this.length, thisp = arguments[1], i = 0;
        if (typeof fun !== "function") {
            throw new TypeError();
        }

        for (; i < len; i++) {
            if (i in this) {
                fun.call(thisp, this[i], i, this);
            }
        }
    };
}

if (!Array.prototype.filter) {
    Array.prototype.filter = function (fun) {
        var len = this.length;
        var res = [];
        var thisp = arguments[1];
        var i = 0, val;
        if (typeof fun !== "function") {
            throw new TypeError();
        }

        for (; i < len; i++) {
            if (i in this) {
                val = this[i]; // in case fun mutates this
                if (fun.call(thisp, val, i, this)) {
                    res.push(val);
                }
            }
        }

        return res;
    };
}

if (!Array.prototype.map) {
    Array.prototype.map = function (fun)   {
        var len = this.length;
        var res = [];
        var thisp = arguments[1];
        var i = 0;
        if (typeof fun !== "function") {
            throw new TypeError();
        }

        for (; i < len; i++) {
            if (i in this) {
                res[i] = fun.call(thisp, this[i], i, this);
            }
        }

        return res;
    };
}

if (!Array.prototype.some) {
    Array.prototype.some = function (fun) {
        var len = this.length, thisp = arguments[1], i = 0;
        if (typeof fun !== "function") {
            throw new TypeError();
        }
        for (; i < len; i++) {
            if (i in this && fun.call(thisp, this[i], i, this)) {
                return true;
            }
        }

        return false;
    };
}

if (!Array.prototype.every) {
    Array.prototype.every = function (fun) {
        var len = this.length, thisp = arguments[1], i = 0;
        if (typeof fun !== "function") {
            throw new TypeError();
        }

        for (; i < len; i++) {
            if (i in this && !fun.call(thisp, this[i], i, this)) {
                return false;
            }
        }

        return true;
    };
}

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (elt) {
        var len = this.length,
            from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0) {
            from += len;
        }


        for (; from < len; from++) {
            if (from in this && this[from] === elt) {
                return from;
            }
        }
        return -1;
    };
}

if (!Array.prototype.lastIndexOf) {
    Array.prototype.lastIndexOf = function (elt) {
        var len = this.length,
            from = Number(arguments[1]);
        if (isNaN(from)) {
            from = len - 1;
        } else {
            from = (from < 0) ? Math.ceil(from) : Math.floor(from);
            if (from < 0) {
                from += len;
            } else if (from >= len) {
                from = len - 1;
            }
        }

        for (; from > -1; from--) {
            if (from in this && this[from] === elt) {
                return from;
            }
        }
        return -1;
    };
}


var clickHandler;
var map;
var lat;
var lng;
var locations;
var bounds;

$(document).ready(function() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(0, 0), 13);
		$.post('bencineras2.php', {comuna : 8},processLocations );

    }
    
    $('a#new_location').click(function() {
        $('a#new_location').hide();
        $('div#info').show('slow');
        clickHandler = GEvent.addListener(map, "click", function(marker, point) {
            setNewMarker(point);
        });
    });
    
    $('a#save').click(function() {
        $('div#formular').hide('slow');
        $.post('locations.php',
               { type: 'upload',
                 name: $('form').find('input').get(0).value,
                 latitude: lat,
                 longitude: lng
               }, 
               processLocations );        
    });
    
	



    $('a#cancel').click(function() {
        $('div#formular').hide('slow');
    });
    
    $('a#zoom_show_all').click(function() {
        zoomShowAll();
    });
});

function setNewMarker(point) {
    $('div#formular').show('slow');
    $('a#new_location').show();
    $('div#info').hide();
    lat = point.lat();
    lng = point.lng();
    $('div#formular').find('p:nth-of-type(0) ').html('Latitude=<b>'+lat+'</b>, Longitude=<b>'+lng+'</b>');
    $('div#formular').show();
    GEvent.removeListener(clickHandler);
}

function processLocations(content) {
	//fec = "  (Ultima actualizacion: <?php echo $fecha ?>)";
	fec = "";
	
    eval("locations = "+content);

    $('p#location_list').html('');
    locations.forEach(function(element, index, array) {
        var marker = new GMarker(new GLatLng(element.latitude, element.longitude), {title: element.name});
        map.addOverlay(marker);
        GEvent.addListener(marker, 'click', function() {
            //marker.openInfoWindowHtml('Bencinera: <b>'+element.name+'</b><br />Latitude: <b>'+element.latitude+'</b><br />Longitude: <b>'+element.longitude+'</b>');
	var usuario = GetCookie("bencina");
	formulario = "<form id='form1'><input type='hidden' id='txtUsuario' value='" + usuario + "' /></form>";
	linkseleccion = '<a href="#" onclick="agregarBencinera('+element.idb+')" title="Agregar estacion de servicio a tus favoritos">Agregar</a><br />';
	//onclick="agregarBencinera('+element.idb+')"
		tabla = "<table><tr><td class='th_per'>B93</td><td class='th_per'>B95</td><td class='th_per'>B97</td><td class='th_per'>DIESEL</td></tr><tr><td>"+element.B93+"</td><td>"+element.B95+"</td><td>"+element.B97+"</td><td>"+element.DIESEL+"</td></tr></table>";
		marker.openInfoWindowHtml('Estacion de Servicio: <b>'+element.name+'</b><br />Direccion: <b>'+element.created+'</b>' +tabla+formulario+linkseleccion+fec);
        });
        link = '<a href="#" onclick="moveMapTo('+index+')">'+element.name+' </a><font face=Arial size=1>'+ element.created +'</font><br />';
        $('p#location_list').append(link);
    });
    zoomShowAll();
}

function processLocations_inicio(content) {
	//fec = "  (Ultima actualizacion: <?php echo $fecha ?>)";
	fec = "";
	
    eval("locations = "+content);

    $('p#location_list').html('');
    locations.forEach(function(element, index, array) {
        var marker = new GMarker(new GLatLng(element.latitude, element.longitude), {title: element.name});
        map.addOverlay(marker);
        GEvent.addListener(marker, 'click', function() {
            //marker.openInfoWindowHtml('Bencinera: <b>'+element.name+'</b><br />Latitude: <b>'+element.latitude+'</b><br />Longitude: <b>'+element.longitude+'</b>');
	var usuario = GetCookie("bencina");
	formulario = "<form id='form1'><input type='hidden' id='txtUsuario' value='" + usuario + "' /></form>";
	//linkseleccion = '<a href="#" onclick="agregarBencinera('+element.idb+')" title="Agregar bencinera a tus favoritos">Agregar</a><br />';
	linkseleccion = '<a href="#" onclick="javascript:alert(\'Para agregar una estacion de servicio debe iniciar sesion\')" title="Agregar estacion de servicio a tus favoritos">Agregar</a><br />';
	//onclick="agregarBencinera('+element.idb+')"
		tabla = "<table><tr><td class='th_per'>B93</td><td class='th_per'>B95</td><td class='th_per'>B97</td><td class='th_per'>DIESEL</td></tr><tr><td>"+element.B93+"</td><td>"+element.B95+"</td><td>"+element.B97+"</td><td>"+element.DIESEL+"</td></tr></table>";
		marker.openInfoWindowHtml('<font  style="font: 12px; font-family: Verdana, Ariarl;">Estacion de Servicio: <b>'+element.name+'</b><br />Direccion: <b>'+element.created+'</b>' +tabla+formulario+linkseleccion+fec);
		//marker.openInfoWindowHtml('Bencinera: <b>'+element.name+'</b><br />Direccion: <b>'+element.created+'</b>' +tabla+formulario);
        });
        link = '<a href="#" onclick="moveMapTo('+index+')">'+element.name+' </a><font face=Arial size=1>'+ element.created +'</font><br />';
        $('p#location_list').append(link);
    });
    zoomShowAll();
}




/*
function processSeleccion(content) {
	
    eval("locations = "+content);

    $('p#seleccion_list').html('');
	
    locations.forEach(function(element, index, array) {
	
        var marker = new GMarker(new GLatLng(element.latitude, element.longitude), {title: element.name});
        map.addOverlay(marker);
        GEvent.addListener(marker, 'click', function() {
          
	linkseleccion = '<a href="#" onclick="agregarBencinera('+element.idb+')" title="Agregar bencinera a tus favoritos" id="saveBencinera">Agregar</a><br />';
	
	marker.openInfoWindowHtml('Bencinera: <b>'+element.name+'</b><br />Direccion: <b>'+element.created+'</b><br />'+linkseleccion);              
        });
	
        link = '<a href="#" onclick="moveMapTo('+index+')">'+element.empresa+' </a><font face=Arial size=1>'+ element.direccion +'</font><br />';
	$('p#seleccion_list').append(link);
    });
    zoomShowAll();
	
	alert("processSeleccion");
}
*/

function moveMapTo(index) {
    map.panTo(new GLatLng(locations[index].latitude, locations[index].longitude));
	
}

function zoomShowAll() {
    bounds = new GLatLngBounds();
    map.setCenter(new GLatLng(0,0),0);
    
    locations.forEach(function(elemet, id, array) {
        bounds.extend(new GLatLng(locations[id].latitude, locations[id].longitude));
    });
    map.setZoom(map.getBoundsZoomLevel(bounds));
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
    map.setCenter(new GLatLng(clat,clng));
}