/**
 * Class geoname lister
 *
 */
GeonameLister = Class.create();
Object.extend(GeonameLister.prototype, {

    /**
     * Initializes this class
     *
     */
    initialize: function(sourceElement, updateTable, updateTrigger, options) {
        // save basic elements
        this.sourceElement = $(sourceElement); 
        this.updateTable  = $(updateTable);    
        this.updateTrigger = $(updateTrigger);    
    
        // save options
        if( this.setOptions ){
            this.setOptions(options);
        } else {
            this.options = options || {};
        }

        // store an optional DateController
        this.options.DateController = (this.options.DateController) ? this.options.DateController : null;
        this.options.onAfterInsertion = (this.options.onAfterInsertion) ? this.options.onAfterInsertion : null;
        
        // observe click events on trigger
        Event.observe(this.updateTrigger, 'click', this.onTrigger.bindAsEventListener(this)); 

        // fire a request for the stored locations        
        this.requestLocations();
    },

    /**
     * Fires the request for stored locations
     *
     */    
    requestLocations: function(){
        this.url = HTML_ROOT + 'ajax/ajaxZoo.php?mode=geonames&id=' + this.options.id + '&action=printGeonameUserList';
        this.url += '&date=' + (this.options.DateController ? '1' : '0');
        new Ajax.Request(this.url, {'onSuccess':this.requestLocationsOnSuccess.bind(this)});
        
        
    },

    /**
     * Handles successful ajax response. Builds table rows for each result.
     *
     * @param XMLHttpRequest request
     */    
    requestLocationsOnSuccess: function(request){
        var results = request.responseXML.documentElement.childNodes;
        for( i=0; i<results.length; i++ ){
            var res = results[i];
            this.buildRow(res);
        }
    },

    /**
     * Gets data form the node 
     *
     * @param XMLNode res Result node
     * @param String fieldname Name of the node
     * @return mixed
     */    
    getValue: function(res, fieldname){
        var child = res.getElementsByTagName(fieldname)[0].firstChild;
        return  child ? child.data : '';
    },

    /**
     * Builds a table row fro this.updateTable
     *
     * @param XMLnode res Node containing data for the row
     */    
    buildRow: function(res){
        var id           = this.getValue(res, 'id');
        var geonameid    = this.getValue(res, 'geonameid');
        var country      = this.getValue(res, 'country');
        var country_code = this.getValue(res, 'country_code');
        var area         = this.getValue(res, 'area');
        var asciiname    = this.getValue(res, 'name');
        var isCountry 	 = this.getValue(res, 'is_country'); // hier kommt is_country direkt aus der datenbank, daher nicht isCountry
        var dt_from      = this.getValue(res, 'dt_from');
        var dt_until     = this.getValue(res, 'dt_until');
        
        // convert date string
        dt_from = dt_from.substring(8,10) + '.' + dt_from.substring(5,7) + '.' + dt_from.substring(0,4);
        dt_until = dt_until.substring(8,10) + '.' + dt_until.substring(5,7) + '.' + dt_until.substring(0,4);


        // build the new table row
        var tr = Builder.node('tr', {'id':'tr'+id});
        var td1 = Builder.node('td');
        var td2 = Builder.node('td');
        var td3 = Builder.node('td');
        var img = Builder.node('img', {'src': HTML_ROOT + 'pix/flags/'+ country_code.toLowerCase() +'.gif'});
        var removelink = Builder.node('a', {'href':'#'}, 'entfernen');
        
        // combine parts
        tr.appendChild(td1);
        if (this.options.DateController) tr.appendChild(td2);
        tr.appendChild(td3);
        td1.appendChild(img);
        if (isCountry == '0') {
	        td1.innerHTML += ' <strong>' + country + '</strong> - ' +  asciiname + (''!=area?', '+area:'');
	    } else {
	    	td1.innerHTML += ' <strong>' + country + '</strong>';
	    }
	    
		if (dt_until != '31.12.2037')
	        td2.innerHTML += 'von ' + dt_from + ' bis ' + dt_until;
	    else
	    	td2.innerHTML += 'Datum noch unklar';
        td3.appendChild(removelink);

        // inserts the new row
        if( !this.updateTable.down('tbody') ){
            this.updateTable.appendChild(Builder.node('tbody'));
        }
        var tbody = this.updateTable.down('tbody');
        tbody.firstChild ? tbody.insertBefore(tr, tbody.down(0)) : tbody.appendChild(tr);
        
        // observe remove links
        Event.observe(removelink, 'click', this.onRemove.bindAsEventListener(this));

        
    },

    /**
     * Triggers insertion of new location
     *
     * @param Event event
     */    
    onTrigger: function(event){
        // run a check if a DateController has been set
        if( this.options.DateController && (this.options.DateController.validDate() || $('disableDate').checked) && ''!=this.sourceElement.down('input').value)
        {
        	this.requestInsertLocation(! this.options.DateController.validDate() );
        	return true;
        }
        
        // check if geonameid is set
        if( ''==this.sourceElement.down('input').value ){
            return false;
        }
        
        this.requestInsertLocation(false);
    },
    
    /**
     * Fires a new ajax request to insert new data.
     */
     requestInsertLocation: function(useInfty){
        var params = '&id=' + this.options.id + '&action=insertLocation';
        params += '&from=';
        params += (useInfty ? '2000-01-01' : (this.options.DateController ? this.options.DateController.getFromDateString()  :  '0000-00-00'));
        params += '&until=';
        params += (useInfty ? '2037-12-31' : (this.options.DateController ? this.options.DateController.getUntilDateString() :  '0000-00-00'));
        
        // get the geonameid
        params += '&geonameid='+this.sourceElement.down('input').value;
        
        // glue the url
        this.url = HTML_ROOT + 'ajax/ajaxZoo.php?mode=geonames' + params
        
        // fire an ajay request
        new Ajax.Request(this.url, {'onSuccess':this.requestInsertLocationOnSuccess.bind(this)});
    },

    /**
     * Handles the successful ajax response. Adds a new table row to this.updateTable
     *
     * @param XMLHttpRequest request
     */
    requestInsertLocationOnSuccess: function(request){
        var results = request.responseXML.documentElement.childNodes;
        for( i=0; i<results.length; i++ ){
            var res = results[i];
            this.buildRow(res);
            var tds = $$('#tr'+this.getValue(res, 'id') + ' td');
            tds.each( function(td){
                new Effect.Highlight(td);
            });
            
        }
        
        // reset elements
        if( this.options.DateController ){ this.options.DateController.reset(); }
        
        // if an onAfterInsertion function has been set, run it..
        if( this.options.onAfterInsertion ){ this.options.onAfterInsertion(); }
    },

    /**
     * Triggers the removal of a row.
     *
     * @param Event event 
     */
    onRemove: function(event){
        if( confirm('Willst du diesen Ort wirklich entfernen?') ){
            id = Event.findElement(event,'TR').id;
            id = id.substring('tr'.length, id.length);
            this.requestRemove(id);
        }
        Event.stop(event);
    },

    /**
     * Fires a new ajax request to delete a row.
     */    
    requestRemove: function(id){
        var params = '&id=' + this.options.id  + '&action=deleteLocation';
        params += '&rmid='+id;
        this.removedId = id;
        this.url = HTML_ROOT + 'ajax/ajaxZoo.php?mode=geonames' + params
        new Ajax.Request(this.url, {'onSuccess':this.requestRemoveOnSuccess.bind(this)});        
    },

    /**
     * Handles the successful ajax response. Removes the table row to this.updateTable
     *
     * @param XMLHttpRequest request
     */
    requestRemoveOnSuccess: function(request){
        var tbody = this.updateTable.down().next();
        var tr = tbody.down('tr#tr'+this.removedId);
        Element.hide(tr);
    }
    
});
