var map = null;
var gMap;

window.onload = function()
{
    window.projectsInstance = new projects();
    window.projectsInstance.init();

    if (typeof GUnload == 'undefined')
    {
        return;
    }

    window.onunload = GUnload;


    var mapLoaded = false;

    function goMap()
    {
        if (typeof mapConfig != 'undefined' )
        {

            map = new mapScript( mapConfig );
            if (!map.ok)
            {
                return;
            }
            map.initGMap();
        }
    }


    var mapButton = document.getElementById('mapButton');
    if (mapButton)
    {
        mapButton.onclick = function()
        {
            var box = document.getElementById( mapConfig.boxId );
            if (!box)
            {
                return;
            }

            var buttonBox = document.getElementById( 'mapButtonBox' );

            var isOpen = (box.className == 'mapBox');

            if (isOpen)
            {
                box.className = 'mapBoxClosed';
                buttonBox.className = 'mapButtonClosed';
            }
            else
            {
                box.className = 'mapBox';
                buttonBox.className = 'mapButtonOpen';
                if (!mapLoaded)
                {
                    goMap();
                }
                mapLoaded = true;
            }



        }
    }

}


function projects()
{

}

projects.prototype.init = function()
{
    this.initProjectSearch();
}

projects.prototype.initProjectSearch = function()
{
    this.searchForm = document.getElementById('projectSearchForm');
    if (!this.searchForm)
    {
        return;
    }

    this.initTextLabels();
    this.initCounties();
}


projects.prototype.initCounties = function()
{
    this.regionsSelect  = document.getElementById('regionSelect');
    this.countiesSelect = document.getElementById('countySelect');

    if (
        (!this.regionsSelect)
        ||
        (!this.countiesSelect)
    )
    {
        return;
    }

    // store all county options in a property
    this.countiesSelect.fullOptions = [];
    for (var i=0; i<this.countiesSelect.options.length; i++)
    {
        this.countiesSelect.fullOptions[ i ] = this.countiesSelect.options[ i ];
    }

    var script = this;
    this.regionsSelect.onchange = function()
    {
        script.updatecounties();
    }

    this.updatecounties();
}

projects.prototype.updatecounties = function()
{
    var parentValue = this.regionsSelect.value;
    var visibleClass = (parentValue.length == 0) ? null : 'parent-'.concat( parentValue );

    // remove all not-empty county options (in reverse index order)
    for (var i=this.countiesSelect.options.length-1; i>=0; i--)
    {
        if (this.countiesSelect.options[i].className == 'empty')
        {
            continue;
        }
        this.countiesSelect.remove(i);
    }

    // if visibleClass not empty, reinsert those with matching class names

    if (visibleClass)
    {
        for (var i=0; i<this.countiesSelect.fullOptions.length; i++)
        {
            var option = this.countiesSelect.fullOptions[i];
            if (option.className == visibleClass)
            {
                try
                {
                    this.countiesSelect.add( option, null ); // w3c
                }
                catch (ex)
                {
                    this.countiesSelect.add( option ); // ie
                }
            }
        }
    }
}

projects.prototype.initTextLabels = function()
{
    var fieldInputIds = ['projectSearchInput'];

    for (var i = 0; i < fieldInputIds.length; i++ )
    {
        var input = document.getElementById( fieldInputIds[ i ] );
        var label = document.getElementById( fieldInputIds[ i ].concat('Label') );
        if (
            (!input)
            ||
            (!label)
        )
        {
            continue;
        }

        input.labelText = label.firstChild.nodeValue;

        input.onfocus = function()
        {
            if (input.value == input.labelText)
            {
                input.value = '';
            }
        }
        input.onblur = function()
        {
            if (input.value == '')
            {
                input.value = input.labelText;
            }
        }

        if (input.value == '')
        {
            input.value = input.labelText;
        }

        // will break with multiple text inputs
        input.form.onsubmit = function()
        {
            if (input.value == input.labelText)
            {
                input.value = '';
            }
            return true;
        }

    }

}


function mapScript( config )
{
    this.ok = false;
    this.config = config;

    if (!this.config)
    {
        return;
    }

    this.box = document.getElementById( this.config.boxId );
    if (
        (!this.box)
        ||
        (this.box.className != 'mapBox')
        ||
        (!GBrowserIsCompatible())
    )
    {
		alert('asd');
        return;
    }

    this.map = null;
    this.ok = true;
}

mapScript.prototype.initGMap = function()
{
    if (this.config.points.length < 1)
    {
        return;
    }



    this.map = new GMap2( this.box );
	gMap = this.map;

    var center = new GLatLng( parseFloat ( this.config.center.lat ) , parseFloat ( this.config.center.lng ));

	var imageDir = 'http://'.concat( document.location.hostname, '/images/');
	var mapIcon    = imageDir.concat('map-pin.png');
	var mapAltIcon = imageDir.concat('map-pin.gif');

    var icon = new GIcon();
    icon.image      = mapIcon;
    icon.printImage = mapAltIcon;
    icon.iconSize = new GSize(18, 18);
    icon.iconAnchor = new GPoint(9, 9);
    icon.infoWindowAnchor = new GPoint(9, 9);

    with (this.map)
    {
        addControl(new GLargeMapControl());

        enableScrollWheelZoom();
        enableDoubleClickZoom();
        enableContinuousZoom();

        setCenter( center , this.config.defaultZoom );

        var tmpInfoWindow = getInfoWindow(); // init

        // add points
        var points = [];
        for (var i=0; i < this.config.points.length; i++)
        {
            var pointData = this.config.points[i];

            if (
                (pointData.lat.toString().length < 1)
                ||
                (pointData.lng.toString().length < 1)
            )
            {
                continue;
            }


            var point = new GLatLng( parseFloat ( pointData.lat ) , parseFloat ( pointData.lng) );
            points[points.length] = point;

            var marker = new GMarker(point, icon);
            marker.pointData = pointData;

            GEvent.addListener(marker, "mouseover", function()
	        {
                this.openInfoWindowHtml(this.pointData.infoWindowHtml);
	        });
            GEvent.addListener(marker, "click", function()
	        {
                document.location.href = this.pointData.parnterUrl;
	        });


            addOverlay( marker );
        }

        if (points.length == 0)
        {
            return;
        }

        // zoom / center to fit all points
        var hasMultiplePoints = (points.length > 1);

        var bounds = new GBounds( points );
        var sw = new GLatLng( bounds.maxY,  bounds.minX);
        var ne = new GLatLng( bounds.minY,  bounds.maxX);

        var b = new GLatLngBounds(sw, ne);
        var newzoom = getBoundsZoomLevel( b );

        if (newzoom > 8)
        {
            newzoom = 8;
        }
        var newcenter = b.getCenter();
        setCenter (newcenter, newzoom);


    }
    var self = this;
}


