if(window['console'] === undefined) window.console = {log: function(){}};

var SiteFunctions = Class.create({
	initialize: function() {
		
		if ($('scroller')) var carousel = new Carousel($('scroller'), $$('.slide'), $$('a.carousel-control'), {auto: true, frequency: 5});
	
		if ($('poll-vote')) {
			$('poll-vote').observe('click', this.vote.bind(this));
		}
		
		if ($('add-newsletter')) {
			$('add-newsletter').observe('click', function(e) {
				e.stop();
				$('form-newsletter').submit();
			});
		}
	},
	vote: function(e) {
		e.stop();
		var id = 0;
		$$('.poll-answer-input').each(function(el) {
			if (el.checked) {
				id = el.value;
			}
		});
		
		$('poll-answers-container').update('Bezig met stemmen...');
		
		new Ajax.Updater('poll-answers-container', '/', {
			method: 'post',
			parameters: {
				id: id,
				pollid: $F('pollid'),
				pollvote: true
			},
			onSuccess: function() {
				$('poll-vote').hide();
				$('poll-vote-separator').hide();
				$('poll-results').hide();
				$('poll-results-separator').hide();
			}
		});
	}
});

var RoutePlanner = Class.create({
    initialize: function(addresses, options) {

        this.map, this.geocoder, this.addressFrom, this.addressTo, this.directions = false;

        this.addresses = addresses;

        this.config = options || {};
        this.config.centerMap = this.config.centerMap || {};

        if ($('form-address-to'))   this._populateDropdown();
        if ($('map'))               this._createMap();

        if ($('form-planner')) {
            $('form-planner').observe('submit', function(e){
                this._route();
                e.stop();
            }.bind(this));
        }
        
        if ($('form-plan-route')) {
        	$('form-plan-route').observe('click', this._route.bind(this));
        }
    },
    route: function(from, to) {
        
    },
    _addressFrom: function() {
        this.addressFrom = $F('form-address-from') + ', ' + $F('form-place-from') + ', Nederland';
        return this.addressFrom;
    },
    _populateDropdown: function() {
        this.addresses.each(function(item){this._createAddressOption(item);}.bind(this));
        $('form-address-to').observe('change', function(e){
            this.addressTo = e.target.value;
        }.bind(this));
    },
    _createAddressOption: function(item) {
        $('form-address-to').appendChild(
            new Element('option', {
                id: 'rpOption-' + item.name,
                value: item.address}
            ).update(item.name)
        );
    },
    _createMap: function() {
        this.map = new GMap2($('map'));
        var lat = this.config.centerMap.lat || 52.132633;
        var lon = this.config.centerMap.lon || 5.291266;
        var zoom = this.config.centerMap.zoom || 7;
        this.map.setCenter(new GLatLng(lat, lon), zoom);

        this.directions = new GDirections(this.map, $('directions'));

        if (this.config.showMarkers) this._setMarkers();
    },
    _setMarkers: function() {
        this.geocoder = new GClientGeocoder();
        this.addresses.each(function(item){this._setMarkerByAddress(item)}.bind(this));
    },
    _setMarkerByAddress: function(item) {
        this.geocoder.getLatLng(item.address, function(point){
            var marker = new GMarker(point);
            this.map.addOverlay(marker);
            GEvent.addListener(marker, 'click', function() {
                this._selectAddressFromMarker(item);
            }.bind(this));
            GEvent.addListener(marker, 'mouseover', function() {
                marker.openInfoWindowHtml(item.name);
            });
            GEvent.addListener(marker, 'mouseout', function() {
                marker.closeInfoWindow();
            });
        }.bind(this));
    },
    _selectAddressFromMarker: function(item) {
        $('form-address-to').selectedIndex = this.addresses.indexOf(item)+1;
    },
    _route: function() {

        if (!this.addressFrom)  this.addressFrom = this._addressFrom();
        if (!this.addressTo)    this.addressTo = $F('form-address-to');

        this.directions.load('from: ' + this._addressFrom() + ' to: ' + this.addressTo, {"locale": "nl_NL", "getSteps": true});

        console.log(this.directions);
    }
});

var FieldFocus = Class.create({
    initialize: function() {

        this.oldvals = {};

        $$('input', 'textarea').each(this.elementFocus.bind(this));
    },
    elementFocus: function(el) {
        if (el.type == 'text' || el.tagName.toLowerCase() == 'textarea') {

            this.oldvals[el.id] = (el.tagName.toLowerCase() == 'input') ? el.value : el.innerHTML;

            el.observe('focus', function(e) {
                el = e.target;
                if (el.tagName.toLowerCase() == 'input' && el.value == this.oldvals[el.id]) {
                    el.value = '';
                } else if (el.tagName.toLowerCase() == 'textarea' && el.innerHTML == this.oldvals[el.id]) {
                    el.innerHTML = '';
                }
            }.bind(this));

            el.observe('blur', function(e){
                el = e.target;
                if (el.tagName.toLowerCase() == 'input' && el.value == '') {
                    el.value = this.oldvals[el.id];
                } else if (el.tagName.toLowerCase() == 'textarea' && el.innerHTML == '') {
                    console.log(el);
                    el.innerHTML = this.oldvals[el.id];
                }
            }.bind(this));
        }
    }
});

document.observe('dom:loaded', function() {
	new SiteFunctions();
	new FieldFocus();
});