var map;
var mapLoadCheckInt;

var startLatitude = 0;
var startLongitude = 0;
var startZoom = 1;

var markers = new Array();
var zoomCursor = null;
var zoomLevels = 20;
var scrollbarHeight = 102.6;
var zoomCursorPos; 


function removeAllChildsFromId(elementId){
    var root = document.getElementById(elementId);
    while(root.hasChildNodes()){
        root.removeChild(root.childNodes[0])
    }            
}
function displayDescription(data){
    $('#gmaps-description-wrap').css({visibility:"visible"});
    
    removeAllChildsFromId('gmaps-store-text');
    removeAllChildsFromId('gmaps-store-name');
    removeAllChildsFromId('gmaps-store-photos');
    
    var listItemName = document.createElement('li');
    listItemName.innerHTML = '<p><span>' + data.name + ' </span></p>';
    document.getElementById('gmaps-store-name').appendChild(listItemName);
    
    var listItem = document.createElement('p');
    listItem.innerHTML = data.description;
    document.getElementById('gmaps-store-text').appendChild(listItem);
    
    $('a[id^="link-to-store-"]').css({'color' : '#636363'});
    $('#link-to-store-'+data.id).css({'color' : 'black'});
    
    for (increment in data.pictures) {
        var divPhoto = document.createElement('div');
        // divPhoto.setAttribute("class", "gmaps-store-photo");
        divPhoto.innerHTML = '<a href="'+data.larger_pictures[increment]+'" title="'+data.name+'"><img src="'+data.pictures[increment]+'" /></a>';
        document.getElementById('gmaps-store-photos').appendChild(divPhoto);
    }
    
    if (maps_lang == 'fr') {
        _txtImage = "Image";
        _txtOf = "sur";
    } else if (maps_lang == 'en') {
        _txtImage = "Image";
        _txtOf = "of";
    } else if (maps_lang == 'ru') {
        _txtImage = "Image";
        _txtOf = "of"; 
    }
    $(function() {
        $('#gmaps-store-photos a').lightBox(
            {
            // overlayBgColor: '#FFF',
            // overlayOpacity: 0.6,
            // containerResizeSpeed: 350,                
            imageLoading: 'http://www.pierrefrey.com/images/contacts/lightbox/ico-loading.gif',
            imageBtnClose: 'http://www.pierrefrey.com/images/contacts/lightbox/close.gif',
            imageBtnPrev: 'http://www.pierrefrey.com/images/contacts/lightbox/prev.gif',
            imageBtnNext: 'http://www.pierrefrey.com/images/contacts/lightbox/next.gif',
            imageBlank: 'http://www.pierrefrey.com/images/contacts/lightbox/blank.gif',
            txtImage: _txtImage,
            txtOf: _txtOf
            
            }    
        );
    });
}

function initializePoint(pointData,i) {
    
    var PierreFreyIcon = new GIcon(); 
    PierreFreyIcon.image = '/images/contacts/gmaps/custom_icon.png';
    PierreFreyIcon.shadow = '/images/contacts/gmaps/custom_icon_shadow.png';
    PierreFreyIcon.iconSize = new GSize(105, 45);
    PierreFreyIcon.shadowSize = new GSize(150, 50);
    PierreFreyIcon.iconAnchor = new GPoint(73, 42); 
    PierreFreyIcon.infoWindowAnchor = new GPoint(73, 42);
    
    var point = new GPoint(pointData.longitude, pointData.latitude);
    var marker = new GMarker(point,PierreFreyIcon);
    
    var listItem = document.createElement('li');
    var listItemLink = listItem.appendChild(document.createElement('a'));
    listItemLink.href = "#";
    listItemLink.id = "link-to-store-"+pointData.id;
    // listItemLink.class = "";
    listItemLink.innerHTML = pointData.name + ' - ' + pointData.address;
    
    var focusPoint = function() {
        displayDescription(pointData);
        //marker.openInfoWindowHtml(pointData.address);
        map.panTo(new GLatLng(pointData.latitude, pointData.longitude)); 
        return false;
    }
    
    GEvent.addListener(marker, 'click', focusPoint); 
    listItemLink.onclick = focusPoint;
    
    document.getElementById('sidebar-list').appendChild(listItem);
    map.addOverlay(marker);
    
    if (i==0) {
        displayDescription(pointData);
    } 
}

function drawMap(){
    map.clearOverlays();
    removeAllChildsFromId('sidebar-list');
    removeAllChildsFromId('gmaps-error-message');
    if (markers.length == 0) {
        var noResultsWarning = document.createElement('p');
        if (maps_lang == 'fr') {
            noResultsWarning.innerHTML = "Votre recherche n'aboutit à aucun résultat. Elargissez votre périmètre de recherche .";
        } else if (maps_lang == 'en') {
            noResultsWarning.innerHTML = "Your search produced no result. Broaden the scope of your search.";
        } else if (maps_lang == 'ru') {
            noResultsWarning.innerHTML = "Указанная информация не корректна. Просьба проверить снова указанный адрес."; 
        }
        // document.getElementById('sidebar-list').appendChild(noResultsWarning);
        document.getElementById('gmaps-error-message').appendChild(noResultsWarning);
        return;
    }
    
    var bounds = new GLatLngBounds();
    var recul = 0;
    for(id in markers) {
        initializePoint(markers[id],id);
        var latlong = new GLatLng(markers[id].latitude,markers[id].longitude);
        bounds.extend(latlong);
        if (markers[id].accuracy ===4) recul = 1;
    }
    var zoomRefine = map.getBoundsZoomLevel(bounds)-recul;
    if (markers.length===1) {
        switch(markers[id].accuracy){ 
            case 1:// alert('COUNTRY');
            zoomRefine =  6;
            break;
            case 2: // alert('REGION');
            //break;
            case 3: // alert('SUBREGION');
            zoomRefine =  9;
            break;
            case 4: // alert('TOWN');
            // break;
            case 5: // alert('POSTCODE');
            zoomRefine = 14;
            break;
            case 6: // alert('STREET');
            // break;
            case 7: // alert('INTERSECTION');
            // break;
            case 8: //alert('ADDRESS');
            zoomRefine =  9; //doit permettre de voir le perimetre
            break;
            default: // alert('UNKNOWN ?') ; 
            zoomRefine =  14;
        }
    }
    map.setZoom(zoomRefine);
    map.setCenter(bounds.getCenter());
}

$(document).ready(function() {
    
    $('#gmaps-description-wrap').css({visibility:"hidden"});
    
    $(".button-input").click(function() {
        $('input.text-input').css({backgroundColor:"#FFFFFF"});
        
        var q = $("input#q").val();
        if (q == "") {
            $('input.text-input').css({backgroundColor:"#F8F7F0"});
            $("input#q").focus();
            return false;
        }
        var lang = $("input#lg").val();  

        var dataString = 'q='+ q + '&lang='+ lang; 

        $.ajax({
            type: "POST",
            beforeSend: function(x) {
             if(x && x.overrideMimeType) {
              x.overrideMimeType("application/j-son;charset=UTF-8");
             }
            },
            
            url: "../../inc/process.php",
            data: dataString,
            dataType: 'json',
            success: function(data) {
                markers = new Array();
                $.each (data, function (bb) {
                    markers.push(data[bb]);
                });
                drawMap();
            },
            error:function (xhr, ajaxOptions, thrownError){
                removeAllChildsFromId('gmaps-error-message');
                var noResultsWarning = document.createElement('p');
                if (maps_lang == 'fr') {
                    noResultsWarning.innerHTML = "Votre demande n'a pas été comprise, vérifiez que vos informations ne comportent pas d'erreur ou élargissez votre recherche.";
                } else if (maps_lang == 'en') {
                    noResultsWarning.innerHTML = "The information given wasn't understood, please make sure all street and city names are spelled correctly or broaden the scope of you search.";
                } else if (maps_lang == 'ru') {
                    noResultsWarning.innerHTML = "The information given wasn't understood, please make sure all street and city names are spelled correctly or broaden the scope of you search.";
                }
                document.getElementById('gmaps-error-message').appendChild(noResultsWarning);
                //alert(xhr.status + ' - ' + thrownError);
            } 
        }); //fin ajax
        return false;
    }); //fin button.click
    
    
    $('#formSearch input').bind('keypress', function(e) {
            if(e.keyCode==13){
                $(".button-input").click();
            }
    });
    
});


function init() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));

        mapTypeControl = new MMapTypeControl({direction:'H'});
        map.addControl(mapTypeControl);
        map.enableScrollWheelZoom();

        map.addControl(new GLargeMapControl());
        mapLoadCheckInt = setInterval(mapLoadCheck, 50); 
        // map.addControl(new UzikControls());
        // GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
        //     zoomCursorPos = scrollbarHeight - (newLevel * (scrollbarHeight/(zoomLevels-1)) );
        //     zoomCursor.style.padding = zoomCursorPos + 'px 0 0 0';
        // });
        
        map.setCenter(new GLatLng(startLatitude, startLongitude), startZoom);
    }
}

function mapLoadCheck() {
    if (map.isLoaded()) {
    var map_ctl = $('#map div.gmnoprint img[src$="mapcontrols2.png"]');
        if (map_ctl.get(0)) {
            map_ctl.attr('src', '../../images/contacts/gmaps/mapcontrols2_custom.png');
            clearInterval(mapLoadCheckInt);
        }
    }      
};

/*
 * Custom controls
 */
function UzikControls() {
}

UzikControls.prototype = new GControl();
	
UzikControls.prototype.initialize = function(map) {
	var container = document.createElement("div");
	
	var pan = document.createElement("div");
	pan.style.background = "url('/images/contacts/gmaps/custom_pan.png')";
	pan.style.width = '58px';
	pan.style.height = '58px';
	container.appendChild(pan);
	
	var panTop = document.createElement("div");
	panTop.style.width = '18px';
	panTop.style.height = '18px';
	panTop.style.position = 'relative';
	panTop.style.left = '18px';
	panTop.style.top = '0px';
	panTop.style.cursor = 'pointer';
	pan.appendChild(panTop);
	GEvent.addDomListener(panTop, 'click', function() {
		map.panDirection(0, 1);
	});
	
	var panLeft = document.createElement("div");
	panLeft.style.width = '19px';
	panLeft.style.height = '18px';
	panLeft.style.position = 'relative';
	panLeft.style.left = '0px';
	panLeft.style.top = '0px';
	panLeft.style.cursor = 'pointer';
	pan.appendChild(panLeft);
	GEvent.addDomListener(panLeft, 'click', function() {
		map.panDirection(1, 0);
	});
	
	var panReset = document.createElement("div");
    panReset.style.width = '16px';
    panReset.style.height = '18px';
    panReset.style.position = 'relative';
    panReset.style.left = '20px';
    panReset.style.top = '-19px';
    panReset.style.cursor = 'pointer';
    pan.appendChild(panReset);
    GEvent.addDomListener(panReset, 'click', function() {
        map.setCenter(new GLatLng(startLatitude, startLongitude), startZoom);
    });
	
	var panRight = document.createElement("div");
	panRight.style.width = '19px';
	panRight.style.height = '18px';
	panRight.style.position = 'relative';
	panRight.style.left = '36px';
	panRight.style.top = '-36px';
	panRight.style.cursor = 'pointer';
	pan.appendChild(panRight);
	GEvent.addDomListener(panRight, 'click', function() {
		map.panDirection(-1, 0);
	});
	
    var panBottom = document.createElement("div");
    panBottom.style.width = '18px';
    panBottom.style.height = '18px';
    panBottom.style.position = 'relative';
    panBottom.style.left = '18px';
    panBottom.style.top = '-36px';
    panBottom.style.cursor = 'pointer';
    pan.appendChild(panBottom);
    GEvent.addDomListener(panBottom, 'click', function() {
        map.panDirection(0, -1);
    });
    
	
	var ruler = document.createElement("div");
	ruler.style.background = "url('/images/contacts/gmaps/custom_zoom.png')";
	ruler.style.width = '24px';
	ruler.style.height = '165px';
	ruler.style.margin = '5px 0 0 17px';
	container.appendChild(ruler);
	
	var plus = document.createElement("div");
	plus.style.width = '21px';
	plus.style.height = '21px';
	plus.style.margin = '1px 0 0 1px';
	plus.style.cursor = 'pointer';
	ruler.appendChild(plus);
	GEvent.addDomListener(plus, 'click', function() {
		map.zoomIn();
	});
	
	var minus = document.createElement("div");
	minus.style.width = '21px';
	minus.style.height = '21px';
	minus.style.margin = '121px 0 0 1px';
	minus.style.cursor = 'pointer';
	ruler.appendChild(minus);
	GEvent.addDomListener(minus, 'click', function() {
		map.zoomOut();
	});
	
	zoomCursor = document.createElement("div");
	zoomCursor.style.background = "url('/images/contacts/gmaps/custom_zoomcursor.png') no-repeat bottom center";
	zoomCursor.style.width = '24px';
	zoomCursor.style.height = '5px';
	zoomCursor.style.padding = '0 0 0 0';
	zoomCursor.style.margin = '-137px 0 0 0px';
	ruler.appendChild(zoomCursor);
	
	map.getContainer().appendChild(container);
	return container;
};

UzikControls.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5, 6));
};

window.onload = init;
window.onunload = GUnload;