document.documentElement.className += " hasJS";

var map;
var markers;
var F6 = function(id) {
    return (typeof id == 'string') ? document.getElementById(id) : id;
}

var Ajax = function() {
    this.initialize.apply(this, arguments);
}; //only call the initialize
Ajax.prototype = {
    options: {
        method: 'get',
        url: '',
        async: true,
        noCache: true,
        data: {}
    },

    constructor: Ajax,
    initialize: function(options) { //constructor
        var _self = this;
        this.setOptions(options);
        this.xhr = this.getXHR();
        this.xhr.onreadystatechange = function() {
            _self.onReadyStateChange();
        };
    },

    onReadyStateChange: function(fromAsync) {
        if (!this.options.async && !fromAsync) {
            return;
        } //si mode synchrone, alors cette fonction ne doit pas etre executee
        if (this.xhr.readyState == 4) {
            /* 4 : etat "complete" */
            if (this.xhr.status == 200) {
                /* 200 : code HTTP pour OK */
                this.fireEvent('onSuccess');
            } else {
                this.fireEvent('onError');
            }
        }
    },

    send: function(data) {
        var o = this.options;
        this.setData(data);
        this.fireEvent('onStart');
        switch (this.options.method.toLowerCase()) {
        case "get":
            var url = this.dataStr.length > 0 ? o.url + "?" + this.dataStr: o.url;
            this.xhr.open("GET", this.addNoCache(url), o.async);
            this.xhr.send(null);
            break;
        case "post":
            this.xhr.open("POST", this.addNoCache(o.url), o.async);
            this.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            this.xhr.send(this.dataStr);
            break;
        default:
            return false;
        }
        if (!o.async) {
            this.onReadyStateChange(true);
        }
    },

    addData: function(data) {
        var i;
        if (!data) {
            return;
        }
        if (typeof data == 'string') {
            var dataArr = data.split('&');
            data = {};
            for (i = 0; i < dataArr.length; i++) {
                var vals = dataArr[i].split('=');
                data[vals[0]] = vals[1];
            }
        }
        for (i in data) {
            if (data[i] !== null) {
                this.options.data[i] = data[i];
            }
        }
    },

    setData: function(data) {
        if (typeof data == 'string') {
            this.dataStr = data;
        } else {
            this.addData(data);
            var dataArr = [];
            for (var i in this.options.data) {
                if (typeof this.options.data[i] != 'function') {
                    dataArr.push(i + '=' + this.options.data[i]);
                }
            }
            this.dataStr = dataArr.join('&');
        }
    },

    addNoCache: function(url) {
        if (this.options.noCache) {
            if (url.indexOf("?") == -1) {
                url += "?";
            } else if (url.charAt(url.length - 1) != "&") {
                url += "&";
            }
            url += "nocache" + parseInt(Math.random() * 1000000, 10) + "=" + parseInt(Math.random() * 1000000, 10);
        }
        return url;
    },

    fireEvent: function(event) {
        if (this.options[event] && typeof this.options[event] == 'function') {
            this.options[event](this.xhr);
        }
    },

    getXHR: function() {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else {
            if (window.ActiveXObject) {
                var x = ['Msxml2', 'Microsoft'];
                for (var i = 0; i < x.length; i++) {
                    try {
                        return new ActiveXObject(x[i] + '.XMLHTTP');
                    } catch(e) {}
                }
            }
        }
        return null;
    },

    setOptions: function(options) {
        if (!options) {
            return;
        }
        var savedOpt = this.options;
        this.options = {};
        for (var i in savedOpt) this.options[i] = savedOpt[i];
        for (var i in options) this.options[i] = options[i];
    }
};

function setHere(lat, lng) {
    map.setCenter(new GLatLng(lat, lng), 13);
}

function load() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("locator"));
        map.setCenter(new GLatLng(46.85984, 2.788281), 5);
    }
}


function load2() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("locator"));
        map.setCenter(new GLatLng(46.85984, 2.788281), 5);
        find();
    }
}


//http://playtex-exchange.dev2.fullsix.com/store-locator/
//ABQIAAAAm_EE4RkwU89EQ2fnyFY8JRQDUGCxnM5MAaVtKIa-OilDpfX74RSjlWh5RwLPiKhLZfyeBIU9GyWr6g
//<![CDATA[
var geocoder;

var address = "";
// On page load, call this function
function find() {
    // Create new map object
    if (document.getElementById("locationSearch").value == '75000') document.getElementById("locationSearch").value = 'Paris';
    var placetofind = document.getElementById("locationSearch").value + " France";
    // Create new geocoding object
    geocoder = new GClientGeocoder();

    // Retrieve location information, pass it to addToMap()
    geocoder.getLocations(placetofind, addToMap);
}


// This function adds the point to the map
function addToMap(response) {
    // Retrieve the object
    if (response.Placemark) place = response.Placemark[0];
    else {
        F6('results').innerHTML = "<dt>&nbsp;</dt><dd>Pas de r&eacute;sultat.</dd>";
        return false;
    }
    doTheMap(place.Point.coordinates[1], place.Point.coordinates[0], 1);
}

function doTheMap(lat, lng, page) {
    map = new GMap2(document.getElementById("locator"));
    map.addControl(new GSmallMapControl());

    // Retrieve the latitude and longitude
    point = new GLatLng(lat, lng);

    // Center the map on this point
    map.setCenter(point, 13);

    var icon = new GIcon();
    var iconWidth = 58;
    var iconHeight = 57;
    icon.image = "/img/marker-off.png";
    icon.iconSize = new GSize(iconWidth, iconHeight);
    icon.iconAnchor = new GPoint(iconWidth / 2, iconHeight / 2);
    icon.infoWindowAnchor = new GPoint(iconWidth / 2, iconHeight / 2);

    // Create a marker
    marker = new GMarker(point, new GIcon(icon));

    // Add the marker to map
    map.addOverlay(marker);

    // Add address information to marker
    //marker.openInfoWindowHtml(place.address);
    var datasend = "lat=" + place.Point.coordinates[1] + "&lng=" + place.Point.coordinates[0] + "&page=" + page;

    new Ajax({
        url: "serverloc.php",
        onSuccess: function(data) {
            markers = new Array();
            var allResp = data.responseText;
            var lengthStr = allResp.length;
            var gstart = allResp.indexOf("<GLOP>");
            var gend = allResp.indexOf("</GLOP>");
            var htmlResp = allResp.substr(0, gstart)
            var dataResp = allResp.substr(gstart + 6, gend - gstart - 6);
            var pointsJs = eval(dataResp);
            for (i = 0; i < pointsJs.length; i++) {
                point = new GLatLng(pointsJs[i].lat, pointsJs[i].lng);
                var icon = new GIcon();
                var iconWidth = 58;
                var iconHeight = 57;
                icon.image = "/img/marker-on.png";
                icon.iconSize = new GSize(iconWidth, iconHeight);
                icon.iconAnchor = new GPoint(iconWidth / 2, iconHeight / 2);
                icon.infoWindowAnchor = new GPoint(iconWidth / 2, iconHeight / 2);

                // Create a marker
                var marker = new GMarker(point, new GIcon(icon));
                marker['obj'] = pointsJs[i];
                map.addOverlay(marker);
                markers.push(marker);
                
                GEvent.addDomListener(marker, "click", function(){
                    this.openInfoWindowHtml(this.obj.content);
                });
            }
            F6('results').innerHTML = htmlResp;
        }
    }).send(datasend);
}

function paging(pageid, lat, lng) {
    doTheMap(lat, lng, pageid);
}

function moveTo(ind){
    markers[ind].openInfoWindowHtml(markers[ind].obj.content);
}