var defaultRow;

var infowindow = null
var countCountries = null;
var layersData = new Array();

$(document).ready(function() {

    defaultRow = "<tr>" + $('#mapsCountriesList').find('tr').eq(0).html() + "</tr>";

    /*
    $('.simple_color').simpleColor({
        cellWidth: 15,
        cellHeight: 15,
        columns: 16,
        border: '1px solid #333333',
        buttonClass: 'button'
    });

    $('#mapsAddNewRow').click(function(event) {

        $('#mapsCountriesList').append(defaultRow);

        $('.simple_color').eq( $('.simple_color').length - 1 ).simpleColor({
            cellWidth: 15,
            cellHeight: 15,
            columns: 16,
            border: '1px solid #333333',
            buttonClass: 'button'
        });
    })
    */

});

function countryDelete(_this){

    if( $("#mapsCountriesList tr").size() < 2){
        alert("At list one country should be selected!");
    } else {
        $(_this).parent().parent().remove();
    }

    return false;
}

function GMapInit() {

    var centered = new google.maps.LatLng(20, 0);

    map = new google.maps.Map(document.getElementById('GMapContainer'), {
        center: centered,
        zoom: 2,

        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL
        },

        mapTypeControlOptions: {
                position: google.maps.ControlPosition.TOP_CENTER
        },

        streetViewControl: false,

        mapTypeId: google.maps.MapTypeId.ROADMAP
    });


    google.maps.event.addListener(map, 'zoom_changed', function() {
        zoomChangeBoundsListener =
            google.maps.event.addListener(map, 'bounds_changed', function(event) {
                if (this.getZoom() > 5 ) {
                    this.setZoom(5);
                }
                if (this.getZoom() < 2 ) {
                    this.setZoom(2);
                }
        });
    });

    countCountries = $("input[@name~='name-']").size() ;
    infowindow = new google.maps.InfoWindow();

    drawColorMap2();

    
    var controlDiv = document.createElement('DIV');
    controlDiv.style.padding = '6px 4px 4px 4px';
    controlDiv.style.background = '#ffffff';

    var controlUI = document.createElement('DIV');
    controlUI.style.backgroundColor = 'transparent';
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'center';
    controlUI.title = 'oconex';
    controlDiv.appendChild(controlUI);


    var controlText = document.createElement('DIV');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    //controlText.innerHTML = '<a href="/" target="_blank"><img src="/images/bg_logo_old_3.gif" width="100px" height="15px"/></a>';
    controlText.innerHTML = '<a href="/" target="_blank"><img src="/images/bg_logo_map.gif" /></a>';
    controlUI.appendChild(controlText);

    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);



    legendView = $("#legendView").val();
    if(legendView == 1){
        legendViewClass = ' style="position: relative; cursor:default; float: right;" class="viewInline" ';
    } else {
        legendViewClass = ' style="position: relative; clear: both; cursor:default; float: right;" ';
    }

    var legendHtml = '';
    for(i=0; i<layersData.length; i++){

        color = layersData[i].color;
        legend = layersData[i].legend;

        if( isNewColorForLegend(color, i) ){
            
            legendHtml +=
            '<div ' + legendViewClass + ' >' +
                '<span style="background-color: ' + color + '; width: 20px; height: 20px; position: absolute; top: 0; right: 8px;">&nbsp;</span>' +
                '<span style="margin: 4px 34px 8px 0; float:left; ">' + legend + '</span>' +
            '</div>';
        }
        
    }

    legendPosition = $("#legendPosition").val();
    if(legendPosition == 1){ $("#LegendDivBottom").html(legendHtml); } else { $("#LegendDivTop").html(legendHtml); }



    /*
    var controlDiv2 = document.createElement('DIV');
    controlDiv2.style.padding = '4px';

    var controlUI2 = document.createElement('DIV');
    controlUI2.style.backgroundColor = '#ffffff';
    controlUI2.style.border = '2px solid #eeeeee';
    controlUI2.title = 'oconex';
    controlDiv2.appendChild(controlUI2);


    var controlText2 = document.createElement('DIV');
    controlText2.style.fontFamily = 'Arial,sans-serif';
    controlText2.style.fontSize = '12px';
    controlText2.style.paddingLeft = '4px';
    controlText2.style.paddingRight = '4px';
    controlText2.innerHTML = legendHtml;

    controlUI2.appendChild(controlText2);

    map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(controlDiv2);
    */
}

function isNewColorForLegend(color, currentI){
    for(var i=0; i < layersData.length; i++){
        if( currentI != i && color == layersData[i].color && currentI > i){
            return false;
        }
    }
    return true
}

// old version "Fusion Tables"
function drawColorMap(){

    var layerCode = ' new google.maps.FusionTablesLayer({ ';
        layerCode = layerCode + ' query: { select: "geometry", from: "1014818" }, ';
        layerCode = layerCode + ' suppressInfoWindows: true, ';
        layerCode = layerCode + ' styles: [{ polygonOptions: { fillColor: "#eeeeee", fillOpacity: 0.2 } }';

    if( countCountries ){
        $("input[@name~='name-']").each( function(i){

            var name = $("input[@name='name-" + i + "']").val();
            var icode = $("input[@name='icode-" + i + "']").val();
            var color = $("input[@name='color-" + i + "']").val();
            var description = $("input[@name='description-" + i + "']").val();
            var legend = $("input[@name='legend-" + i + "']").val();

            layerCode = layerCode + ', { where: "Code = \'' + icode + '\'", polygonOptions: { fillColor: \'' + color + '\', fillOpacity: 0.5 } }';
            layersData[i] = { name: name, icode: icode, color: color, description: description, legend: legend };

        });

        layerCode = layerCode + ' ] } ); ';
        layer = eval(layerCode);
        layer.setMap(map);

        google.maps.event.addListener(layer, 'click', displayData );

    }
}

function displayData(mouseEvent){

    closeAllInfoWindow();

    for(i=0; i<layersData.length; i++){

        if( mouseEvent.row["Code"].value == layersData[i].icode ){

            infowindow = new google.maps.InfoWindow( {
                content: layersData[i].description,
                position: mouseEvent.latLng
            });
            infowindow.open(map);
        }
    }

}

function closeAllInfoWindow(){
    infowindow.close();
}


// new version
function drawColorMap2(){

    if( countCountries ){

        $("input[@name~='name-']").each( function(i){

            var name = $("input[@name='name-" + i + "']").val();
            var icode = $("input[@name='icode-" + i + "']").val();
            var color = $("input[@name='color-" + i + "']").val();
            var description = $("input[@name='description-" + i + "']").val();
            var legend = $("input[@name='legend-" + i + "']").val();


            $("input[@name~='coordinats-"+icode+"-']").each( function(i){
                var path = [];
                points = $(this).val();
                if( points.length ){
                    var pointA = points.split(";");
                    for(i=0; i<pointA.length; i++){
                        if (pointA[i].length ) {
                            var point = new google.maps.LatLng( parseFloat( pointA[i].split(",")[1]), parseFloat(pointA[i].split(",")[0]));
                            path.push(point);
                        }
                    }
                    createPolygon(path, description, color);
                }
            });

            layersData[i] = { name: name, icode: icode, color: color, description: description, legend: legend };
            
        });
    }

}

function createPolygon(path, Message, color) {
    var polygon = new google.maps.Polygon({
        paths: path,
        strokeColor: "#555555",
        strokeOpacity: 0.8,
        strokeWeight: 1,
        fillColor: color,
        fillOpacity: 0.6,
        map: map,
        bounds: map.getBounds()
    });
    google.maps.event.addListener(polygon,'click', function(event) {
        infowindow.setContent(Message);
        if (event) point = event.latLng;
        infowindow.setPosition(point);
        infowindow.open(map);
    });
    return polygon;
}
