var CM2GO = CM2GO || {};
CM2GO.searchTriggered = false;
CM2GO.continents = ["Americas", "Europe", "Africa", "Asia", "Other"];
CM2GO.markersInitial = [];
CM2GO.markersFinal = [];
CM2GO.areaMarker = {isShown: false};
CM2GO.Util = {};
CM2GO.Util.doInThreadingLoop = function(toExecute, noOfTimes) {
    var i = 0;
    var busy = false;
    var processor = setInterval(function() {
        if (!busy) {
            busy = true;
            toExecute(i);
            if (++i >= noOfTimes) {
                clearInterval(processor);
            }
            busy = false;
        }
    }, 10);
};
CM2GO.Util.loadStylesheet = function(sheetSource) {
   var head = document.getElementsByTagName('head')[0];
   var sheet = document.createElement('link');
   sheet.rel = 'stylesheet';
   sheet.type = 'text/css';
   sheet.href = sheetSource;
   head.appendChild(sheet);
};
CM2GO.addStarsRating = function(rating) {
    var returnHTML = "";
    var fullStars = Math.floor(rating / 2);
    var halfStar = rating % 2;
    var emptyStars = Math.floor((10 - rating) / 2);
    for (var i = 0; i < fullStars; i++) {
        returnHTML += '<img src="'+CM2GO.pluginRoot+'/wp-content/plugins/citymaps2go-map/images/icon_star_full.png" alt="*" />';
    }
    if (halfStar === 1) {
        returnHTML += '<img src="'+CM2GO.pluginRoot+'/wp-content/plugins/citymaps2go-map/images/icon_star_half.png" alt="*" />';
    }
    for (var i = 0; i < emptyStars; i++) {
        returnHTML += '<img src="'+CM2GO.pluginRoot+'/wp-content/plugins/citymaps2go-map/images/icon_star_empty.png" alt="" />';
    }
    return returnHTML;
};
CM2GO.defineMarkersFromCities = function() {
    var mapBounds = CM2GO.map.getBounds();
    for (var i = 0; i < CM2GO.cities.length; i++) {
        var marker = new CM.Marker(new CM.LatLng(CM2GO.cities[i].x, CM2GO.cities[i].y), {title: CM2GO.cities[i].label, icon: CM2GO.markerIcon});
        if (mapBounds.contains(marker.getLatLng())) {
            CM2GO.markersInitial.push(marker);
        }
        else {
            CM2GO.markersFinal.push(marker);
        }
        var addListenerWrapper = function(cityIndex) {
            CM.Event.addListener(marker, 'click', function(latlng) {
                CM2GO.markerClickHandler(cityIndex);
            });
        }(i);
    }        
};
CM2GO.markerClickHandler = function(cityIndex) {
    var ratingString = '<div class="citymaps2go-info-data-rating-wrapper">';
    if (CM2GO.cities[cityIndex].q >= 0 && CM2GO.cities[cityIndex].q <= 10) {
        ratingString += '<div class="citymaps2go-info-data-rating"><span>map rating:</span>'+CM2GO.addStarsRating(CM2GO.cities[cityIndex].q)+'</div>';
    }
    ratingString += '</div>';
    CM2GO.map.openInfoWindow(new CM.LatLng(CM2GO.cities[cityIndex].x, CM2GO.cities[cityIndex].y),'<div class="citymaps2go-info-header"><p class="citymaps2go-info-title">'+CM2GO.cities[cityIndex].label+'</p></div>'+
        '<div class="citymaps2go-info-data-entry"><div class="citymaps2go-info-data-entry-column"><img src="'+CM2GO.pluginRoot+'/wp-content/plugins/citymaps2go-map/images/icon_POIs.png" alt="All POI" title="All POI" /><div>'+CM2GO.cities[cityIndex].p+'</div></div><div class="citymaps2go-info-data-entry-column"><img src="'+CM2GO.pluginRoot+'/wp-content/plugins/citymaps2go-map/images/icon_streets.png" alt="Streets" title="Roads" /><div>'+CM2GO.cities[cityIndex].s+'</div></div></div>'+
        ratingString+
        '<div class="citymaps2go-info-data-entry"><div class="citymaps2go-info-data-entry-column"><img src="'+CM2GO.pluginRoot+'/wp-content/plugins/citymaps2go-map/images/icon_drinks.png" alt="Drink" title="Drink" /><div>'+CM2GO.cities[cityIndex].d+'</div></div><div class="citymaps2go-info-data-entry-column"><img src="'+CM2GO.pluginRoot+'/wp-content/plugins/citymaps2go-map/images/icon_eats.png" alt="Eat" title="Eat" /><div>'+CM2GO.cities[cityIndex].e+'</div></div></div>'+
        '<div class="citymaps2go-info-data-entry"><div class="citymaps2go-info-data-entry-column"><img src="'+CM2GO.pluginRoot+'/wp-content/plugins/citymaps2go-map/images/icon_sleeps.png" alt="Sleep" title="Sleep" /><div>'+CM2GO.cities[cityIndex].z+'</div></div><div class="citymaps2go-info-data-entry-column"><img src="'+CM2GO.pluginRoot+'/wp-content/plugins/citymaps2go-map/images/icon_attractions.png" alt="Attraction" title="Sights" /><div>'+CM2GO.cities[cityIndex].a+'</div></div></div>', {pixelOffset: new CM.Size(0, -40)});
        CM2GO.showAreaMarker(cityIndex);
};
CM2GO.showAreaMarker = function(cityIndex) {
    if (CM2GO.cities[cityIndex].x1 === undefined) {
        return;
    }
    if (CM2GO.areaMarker.isShown) {
        CM2GO.map.removeOverlay(CM2GO.areaMarker.marker);
    }
    CM2GO.areaMarker.isShown = true;
    CM2GO.areaMarker.marker = new CM.Polygon([new CM.LatLng(CM2GO.cities[cityIndex].x1, CM2GO.cities[cityIndex].y1), new CM.LatLng(CM2GO.cities[cityIndex].x1, CM2GO.cities[cityIndex].y2), new CM.LatLng(CM2GO.cities[cityIndex].x2, CM2GO.cities[cityIndex].y2), new CM.LatLng(CM2GO.cities[cityIndex].x2, CM2GO.cities[cityIndex].y1)]);
    CM2GO.map.addOverlay(CM2GO.areaMarker.marker);
};
CM2GO.searchCity = function(cityName) {
    if (cityName === "") return;
    CM2GO.map.closeInfoWindow();
    $("div#citymaps2go-search-not-found").html("");
    $("div#citymaps2go-map").show();
    $("div#citymaps2go-list").hide();
    var cityFound = false;
    for (var i = 0; i < CM2GO.cities.length; i++) {
        if (CM2GO.cities[i].label.toLowerCase() === cityName.toLowerCase()) {
            cityFound = true;
            CM2GO.map.setCenter(new CM.LatLng(CM2GO.cities[i].x, CM2GO.cities[i].y));
            CM2GO.map.setZoom(7);
            CM2GO.map.setZoom(10);
            $("input#citymaps2go-search-box").autocomplete("close");
            CM2GO.markerClickHandler(i);
        }
    }
    if (!cityFound) {
        $("div#citymaps2go-search-not-found").html("Could not find &lt;"+cityName+"&gt; in our database.");
    }
    pageTracker._trackEvent("CityMaps 2GO", "Search", cityName);
};
CM2GO.getCityListByContinent = function() {
    var cityList = '<a href="#" id="citymaps2go-list-close"></a>';
    var getContinentList = function(continent, last) {
        returnString = '<div class="citymaps2go-list-continent';
        if (last) {
            returnString += ' citymaps2go-list-continent-last';
        }
        returnString += '"><div class="citymaps2go-list-continent-label">'+CM2GO.continents[continent]+'</div><div class="citymaps2go-list-continent-city-wrapper">';
        var i = 0;
        var no_cities = 0
        do {
            if (CM2GO.cities[i].c === (continent + 1) && CM2GO.cities[i].label.length < 16) {
                returnString += '<div class="citymaps2go-list-continent-city">'+CM2GO.cities[i].label+'</div>';
                no_cities++;
            }
            i++;
        } while (no_cities < 20 && i < CM2GO.cities.length);
        returnString += '</div><a href="#" class="citymaps2go-list-continent-link">Show all</a>';
        returnString += '</div>';
        return returnString;
    };
    cityList += getContinentList(0);
    cityList += getContinentList(1);
    cityList += getContinentList(2);
    cityList += getContinentList(3);
    cityList += getContinentList(4, true);
    return cityList;
};
CM2GO.getCityListForContinent = function(continent) {
    var continentIndex = 4;
    for (var i = 0; i < CM2GO.continents.length; i++) {
        if (CM2GO.continents[i] === continent) {
            continentIndex = i;
        }
    }
    var cityList = '<a href="#" id="citymaps2go-list-close"></a>';
    cityList += '<div class="citymaps2go-list-continent-label citymaps2go-list-continent-label-solo">'+continent+'</div>';
    columnsContent = [];
    var column = 0;
    for (var j = 0; j < 5; j++) {
        columnsContent[j] = "";
    }
    for (var i = 0; i < CM2GO.cities.length; i++) {
        if (CM2GO.cities[i].c === continentIndex + 1) {
            columnsContent[column] += '<div class="citymaps2go-list-continent-city">'+CM2GO.cities[i].label+'</div>';
            column++;
            if (column > 4) {
                column = 0;
            }
        }
    }
    for (var j = 0; j < 5; j++) {
        cityList += '<div class="citymaps2go-list-continent-solo">' + columnsContent[j] + '</div>';
    }
    return cityList;
};
CM2GO.threadedAddMarkersToClusterer = function(i) {
    var offset = i * 20;
    for (var j = offset; j < offset + 20 && j < CM2GO.markersFinal.length; j++) {
        CM2GO.clusterer.addMarker(CM2GO.markersFinal[j]);
    }
    var citiesLoaded = CM2GO.markersInitial.length + j;
    CM2GO.cityCounterElement.text("Cities loaded: "+citiesLoaded+"/"+CM2GO.cities.length);
};
CM2GO.addMarkersToClusterer = function() {
    CM2GO.clusterer.addMarkers(CM2GO.markersInitial);
    $("div#citymaps2go-city-counter").html('<div class="citymaps2go-city-counter-loading-text">Cities loaded: ' + CM2GO.markersInitial.length + "/" + CM2GO.cities.length + '</div>');
    CM2GO.cityCounterElement = $("div#citymaps2go-city-counter div.citymaps2go-city-counter-loading-text");
    CM2GO.Util.doInThreadingLoop(CM2GO.threadedAddMarkersToClusterer, CM2GO.markersFinal.length / 20);
};
CM2GO.initializeHandlers = function(pluginRoot) {
    $("input#citymaps2go-search-box").keypress(function(event){
        if (event.which == 13 && !CM2GO.searchTriggered){
            CM2GO.searchCity($(this).val());
        }
    });
    $("a#citymaps2go-search-link").click(function(event){
        event.preventDefault();
        $("div#citymaps2go-list").show();
        $("div#citymaps2go-map").hide();
        $("div#citymaps2go-list").html(CM2GO.getCityListByContinent());
        $("div.citymaps2go-list-continent-city").each(function(){
            $(this).click(function(event){
                CM2GO.searchCity($(this).text());
            });
            $(this).css("cursor","pointer");
        });
        $("a#citymaps2go-list-close").click(function(event){
            event.preventDefault();
            $("div#citymaps2go-map").show();
            $("div#citymaps2go-list").hide();
        });

        $("a.citymaps2go-list-continent-link").click(function(event){
            event.preventDefault();
            $("div#citymaps2go-list").html(CM2GO.getCityListForContinent($(this).parent().children("div.citymaps2go-list-continent-label").text()));
            $("div.citymaps2go-list-continent-city").each(function(){
                $(this).click(function(event){
                    CM2GO.searchCity($(this).text());
                });
                $(this).css("cursor","pointer");
            });
            $("a#citymaps2go-list-close").click(function(event){
                event.preventDefault();
                $("div#citymaps2go-map").show();
                $("div#citymaps2go-list").hide();
            });
        });
    });
    $("input#citymaps2go-search-box").autocomplete({
        source: CM2GO.cities,
        open: function(event, ui){
            $("ul.ui-autocomplete").css("z-index", "100");
        },
        select: function(event, ui){
            CM2GO.searchTriggered = true;
            CM2GO.searchCity($(ui.item).val());
        },
        close: function(event, ui){
            CM2GO.searchTriggered = false;
        }
    });
};
CM2GO.initialize = function(pluginRoot) {
    if (pluginRoot === undefined) {
        return;
    }
    CM2GO.pluginRoot = pluginRoot;
    //CM2GO.Util.loadStylesheet("http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css");
    //CM2GO.Util.loadStylesheet(CM2GO.pluginRoot+"/wp-content/plugins/citymaps2go-map/css/style.css");
    CM2GO.tiles = new CM.Tiles.OpenStreetMap.Mapnik();
    CM2GO.map = new CM.Map('citymaps2go-map', CM2GO.tiles);
    CM2GO.markerIcon = new CM.Icon();
    CM2GO.markerIcon.image = CM2GO.pluginRoot+"/wp-content/plugins/citymaps2go-map/images/pin_01.png";
    CM2GO.markerIcon.iconSize = new CM.Size(40, 35);
    CM2GO.markerIcon.iconAnchor = new CM.Point(12, 35);

    CM2GO.map.setCenter(new CM.LatLng(47.000, 12.000), 5);
    CM2GO.map.addControl(new CM.LargeMapControl());
    CM2GO.clusterer = new CM.MarkerClusterer(CM2GO.map, {maxZoomLevel: 9});
    CM2GO.oldZoom = 5;
    CM.Event.addListener(CM2GO.map, 'zoomend', function(){
        if (CM2GO.map.getZoom() < CM2GO.oldZoom) {
            $("div.wml-info-window").css("visibility", "hidden");
            $("div.wml-info-window-content").html("");
            if (CM2GO.areaMarker.isShown) {
                CM2GO.areaMarker.isShown = false;
                CM2GO.map.removeOverlay(CM2GO.areaMarker.marker);
            }
        }
        CM2GO.oldZoom = CM2GO.map.getZoom();
    });
    CM.Event.addListener(CM2GO.map, 'infowindowclose', function(){
        if (CM2GO.areaMarker.isShown) {
            CM2GO.areaMarker.isShown = false;
            CM2GO.map.removeOverlay(CM2GO.areaMarker.marker);
        }
    });

    $(function() {
        CM2GO.defineMarkersFromCities();
        CM2GO.addMarkersToClusterer();

        CM2GO.initializeHandlers();
    });

    $("a.111[href='#coverage']").click(function() {
        setTimeout(function() {
            CM2GO.map.zoomOut();
            CM2GO.map.zoomIn();
        }, 1000);
    });
};


