/**
 * Bars anzeigen
 */
showBars = function(parameters)
{
	if(parameters.top)
		display_toggle('barlist_truncated', 'barlist_top');
	else
		display_toggle('barlist_top', 'barlist_truncated');
	$$('.topnavi_selected').invoke('removeClassName', 'topnavi_selected');
	if(parameters.l)
		$('topnavi_'+parameters.l).addClassName('topnavi_selected');
	
	$('barlist_wait').show();
	new Ajax.Updater('barlist_thumbs', 'pages/bar/bar_ajax.php?request=barthumbs', {
		method: 'post',
		parameters: parameters,
		onComplete: function() {
			$('barlist_wait').hide();
		}
	});
	return false;
}

editBar = function(id, action)
{
    showMessage("Daten werden geladen");
	new Ajax.Request('pages/bar/bar_ajax.php?request=edit', {
		method: 'post',
        parameters: {action: action, bar: id},
		onSuccess: function(r) {
            if (ajaxUpdate('singlebar', r))
            {
                hideMessage();
                initAddBar(1);
            }
		}
	});
}

adminBar = function(id, action)
{
    showMessage("Anfrage wird bearbeitet...");
	new Ajax.Request('pages/bar/bar_ajax.php?request=admin', {
		method: 'post',
        parameters: {action: action, bar: id},
		onSuccess: function(r) {
            if (ajaxUpdate('singlebar', r))
            {
                hideMessage();
            }
		}
	});
}



/**
 * Kommentar eintragen
 */
Comments = {
	ajax_file: '/pages/bar/bar_ajax.php/',
	oldAdd: '',
	form: '',
    twitter: true,
	submit: function(bar) {
        showMessage("Komentar eintragen");
		new Ajax.Request(Comments.ajax_file + '?request=save&bar='+bar, {
			method: 'post',
			parameters: $('comments_form').serialize(true),
			onSuccess: function(r) {
				ajaxUpdate('comments', r);
                hideMessage();
			},
			onFailure: function(r) { ajaxFailure(); }
		});
		return false;
	},
	showForm: function(bar) {
		if (Comments.form.length > 0)
        {
            $('comments_add').update(Comments.form);
            location.href = "#comments";
        }
        else
        {
            Comments.oldAdd = $('comments_add').innerHTML;
            new Ajax.Request(Comments.ajax_file + '?request=show', {
                method: 'post',
                parameters: {
                    bar: bar
                },
                onSuccess: function(r){
                    ajaxUpdate('comments_add', r);
                    location.href = "#comments";
                },
                onFailure: function(r){
                    ajaxFailure();
                }
            });
        }
		return false;
	},
	restore: function() {
		Comments.form = $('comments_add').innerHTML;
		$('comments_add').update(Comments.oldAdd);
		return false;
	},
    checkTwitter: function() {
        if ($('twitter2').checked)
        {
            $('twitter_pass').show('table-row');
            $('twitter_password').show('inline');
            $('twitter_username').show('inline');
            Comments.twitter = true;
        }
        else
        {
            $('twitter_pass').hide();
            $('twitter_password').hide();
            $('twitter_username').hide();
            Comments.twitter = $('twitter1').checked;
        }
        if (Comments.twitter)
        {
            $('twitter_text').show('table-row');
        }
        else
        {
            $('twitter_text').hide();
        }
    },
    checkTwitterText: function(length) {
        if (Comments.twitter)
        {
            $('twittertext').update($('comment').value.substr(0, length));
        }
    }
}
 
/**
 * Funktonen für kleine Bildergallerie
 */
Gallery = {
 	n: 0,
 	pages: [],
 	load: function() {
		document.observe('dom:loaded', function() {
			Gallery.pages = $$('div#imprssion_pic img')
			if(Gallery.pages.length > 0)
			{
				Gallery.updateN(0);
                
                if ($('impression_prev'))
                {
                    $('impression_prev').observe('click', Gallery.prev);
                    $('impression_prev').observe('mouseout', function(){
                        $('impression_prev').src = "/bilder/icons/prev.png";
                    });
                    $('impression_prev').observe('mouseover', function(){
                        $('impression_prev').src = "/bilder/icons/prev_hilite.png";
                    });
                }
                if ($('impression_next'))
                {
                    $('impression_next').observe('click', Gallery.next);
                    $('impression_next').observe('mouseout', function(){
                        $('impression_next').src = "/bilder/icons/next.png";
                    });
                    $('impression_next').observe('mouseover', function(){
                        $('impression_next').src = "/bilder/icons/next_hilite.png";
                    });
                }
			}
		});
	},
    updateN: function(n) {
 	    Gallery.pages[Gallery.n].hide();
 	    Gallery.pages[n].show('inline');
        $('impression_nr').update((n+1) + "/" + Gallery.pages.length);
        Gallery.n = n;
    },
 	next: function() {
        Gallery.updateN((Gallery.n < Gallery.pages.length - 1) ? (Gallery.n + 1) : 0);
 	},
 	prev: function() {
 	    Gallery.updateN((Gallery.n > 0) ? (Gallery.n - 1) : Gallery.pages.length - 1);
 	}
 }
 
Gallery.load();




// ADDBAR

AddBar = {
    ajax_file: '/pages/bar/bar_ajax.php',
    actTab: null,
    tabs: null,
    init: function(first) {
        
        AddBar.tabs = $$("form#addbar div.tab");
        if (AddBar.tabs.length > 0)
        {
            AddBar.showTab(first);
        }
    },
    showTab: function(tabIndex) {
        
        // hide displaied tab
        if (AddBar.actTab != null)
        {
            AddBar.tabs[AddBar.actTab].hide();
        }
        
        AddBar.actTab = tabIndex;
        AddBar.tabs[AddBar.actTab].show();
        
        headers = $$('div#addBarTabs div.tabHeader');
        headers.each(function(h) {h.removeClassName("tabSelected");});
        if (tabIndex > 0)
        {
            headers[tabIndex - 1].addClassName("tabSelected");
            $('addBarTabs').style.background = "url(/pages/addBar/pics/tab"+tabIndex+".png)";
        }
        switch (tabIndex)
        {
            case 1:
                $('addbar_prev').hide();
                break;
            case 2:
                if (! Location.loaded)
                {
                    Location.load();
                }
                $('addbar_prev').show('inline');
                $('addbar_next').show('inline');
                break;
            case 3:
                $('addbar_next').hide();
                $('addbar_submit').show('inline');
        }
        
        // return false for not folowing links ect.
        return false;
    },
    nextTab: function() {
        AddBar.showTab(AddBar.actTab+1);
    },
    prevTab: function() {
        AddBar.showTab(AddBar.actTab-1);  
    },
    save: function() {
    	$(Location.FIELD_REGION).removeAttribute('disabled');
        showMessage("Daten werden übertragen");
    	new Ajax.Request(AddBar.ajax_file + '?request=saveBar', {
    		method: 'post',
            parameters: $('addbar').serialize(true),
    		onSuccess: function(r) {
                if (ajaxUpdate('addbar_content', r))
                {
                    hideMessage();
                }
                else if (Location.regionFound)
                {
                    $(Location.FIELD_REGION).writeAttribute('disabled', 'disabled');
                }
    		}
    	})
        // do not send the form
        return false;
    }
};

    langs = {
      de:{
        location:{
          addressNotFound: "Adresse nicht gefunden, bitte Position manuell eingeben oder Adresse kontrollieren",
          addressFound: "Adresse gefunden, bitte Position kontrollieren",
          searchCoordinates: "Koordinaten suchen...",
          coordinatesFound: "Koordinaten suchen...gefunden!"
        },
        imageUploader:{
          upload_error: [
            'Datei erfolgreich hochgeladen',
            'Keine Bild-Parameter definiert',
            'Keine Datei hochgeladen',
            'Datei ist zu Gross',
            'Datei ist keine gültige Bilddatei',
            'Bild ist zu klein',
            'Bildtype wird nicht unterstützt',
            'Fehler beim speichern des Bildes'
          ]
        }
      }
    }


// set language
language = langs['de'];

Location = {
    FIELD_MAP: 'bar_location_map',
    FIELD_LAT: 'bar_lat',
    FIELD_LNG: 'bar_lng',
    FIELD_STATUS: 'bar_location_status',
    FIELD_ADDRESS: 'bar_address',
    FIELD_CITY: 'bar_city',
    FIELD_ZIP: 'bar_zip',
    FIELD_STATE: 'bar_country',
    FIELD_REGION: 'bar_region',
    FIELD_LOCATION: 'bar_location',
    MAP_CENTER_LAT: 47,
    MAP_CENTER_LNG: 8,
    MAP_START_MAGNIFICATION: 8,
    MAP_FOUND_MAGNIFICATION: 15,
    regionFound: false,
    ajax_file: '/pages/addBar/addBar_ajax.php',
    map: null,
    geocoder: null,
    marker: null,
    address: '',
    loaded: false,
    load: function() {
        if (GBrowserIsCompatible()) {
            Location.map = new GMap2($(Location.FIELD_MAP));
            Location.map.setCenter(new GLatLng(Location.MAP_CENTER_LAT, Location.MAP_CENTER_LNG), Location.MAP_START_MAGNIFICATION);
            Location.map.addControl(new GLargeMapControl());
            Location.geocoder = new GClientGeocoder();
            
            GEvent.addListener(Location.map, 'click', Location.onMapClick);
        }
        Location.loaded = true;
        Location.update();
    },
    onMapClick: function(marker, point){
        if(marker){
        }
        if(point){
            Location.setMarker(point);
        }
    },
    update: function () {
        if (!Location.geocoder)
            return false;
        var street = $(Location.FIELD_ADDRESS).value;
        var city = $(Location.FIELD_CITY).value;
        var plz = $(Location.FIELD_ZIP).value;
        var state = $(Location.FIELD_STATE).value;
        if(city!='')
        {
        	new Ajax.Request(Location.ajax_file + '?request=get_region', {
        		method: 'post',
                parameters: {city: city},
        		onSuccess: function(r) {
        			if (r.responseText.length > 0) {
                        $(Location.FIELD_REGION).value = r.responseText;
                        $(Location.FIELD_REGION).writeAttribute('disabled', 'disabled');
                        Location.regionFound = true;
                        if ($(Location.FIELD_REGION).value == 1) {
                            $(Location.FIELD_LOCATION).show('inline');
                            $(Location.FIELD_LOCATION).removeAttribute('disabled');
                        }
                        else
                        {
                            $(Location.FIELD_LOCATION).hide();
                            $(Location.FIELD_LOCATION).writeAttribute('disabled', 'disabled');
                        }
                    }
                    else
                    {
                        $(Location.FIELD_REGION).removeAttribute('disabled');
                        $(Location.FIELD_LOCATION).writeAttribute('disabled', 'disabled');
                        Location.regionFound = false;
                    }
        		}
        	})
        }
        if($(Location.FIELD_REGION).value=='Zürich Stadt')
        	$(Location.FIELD_LOCATION).show('inline');
        else
        	$(Location.FIELD_LOCATION).hide();
        if(city!='' && street!='' && state!='' && street+", "+plz+" "+city+", "+state != Location.address) {
            Location.address = street+", "+plz+" "+city+", "+state;
            
            Location.geocoder.getLatLng(Location.address, function(point) {
                if (!point) {
                    if(Location.marker!=null){
                        Location.map.removeOverlay(Location.marker);
                        Location.clearCoordinates();
                    }
                    $(Location.FIELD_STATUS).update(language.location.addressNotFound);
                } else {
                    $(Location.FIELD_STATUS).update(language.location.addressFound);
                    Location.map.setCenter(point, Location.MAP_FOUND_MAGNIFICATION);
                    Location.setMarker(point);
                }
            });
        }
    },
    setMarker: function(point) {
        if(Location.marker!=null)
        Location.map.removeOverlay(Location.marker);
        
        Location.marker = new GMarker(point, {draggable: true});
        Location.map.addOverlay(Location.marker);
        
        GEvent.addListener(Location.marker, "dragstart", function() {
            Location.clearCoordinates();
            $(Location.FIELD_STATUS).update(language.location.searchCoordinates);
        });
        GEvent.addListener(Location.marker, "dragend", function(point) {
            Location.setCoordinates(point);
            $(Location.FIELD_STATUS).update(language.location.coordinatesFound);
        });
        Location.setCoordinates(point);
    },
    setCoordinates: function(point) {
        $(Location.FIELD_LNG).value = point.x;
        $(Location.FIELD_LAT).value = point.y;
    },
    clearCoordinates: function() {
        $(Location.FIELD_LNG).value = '';
        $(Location.FIELD_LAT).value = '';
    }
};


// object for upload responses
var UploaderResponse = {};

/**
 * Image Uploader 
 * 
 * @param {Object} uploadField
 * @param {Object} imagefields
 * @param {Object} image
 * @param {Object} settings
 */
var ImageUploader = Class.create({
    ajax_file: "/php/imageUpload.php",
    initialize: function(uploadField, image, settings){
        
        // this.uploadField = input-upload tag
        // this.form = form that contains the input
        
        // check for fileupload-input
        this.uploadField = $(uploadField);
        if(this.uploadField.tagName.toLowerCase()!='input' || this.uploadField.type.toLowerCase()!='file')
            throw('ImageUploader works only with upload fields');
        
        
        // check for form create one ev.
        var p=this.uploadField.parentNode;
        while(p && p.tagName && p.tagName.toLowerCase()!='form')
            p=p.parentNode;
        if(!p || !p.tagName || p.tagName.toLowerCase()!='form')
            this.form = this.uploadField.wrap('form');
        else
            this.form = $(p);
        
        // create fields
        this.name = this.uploadField.name;
        
        this.originalPath = new Element('input', { type: 'hidden', name: this.name + '_original' });
        this.resizedPath  = new Element('input', { type: 'hidden', name: this.name + '_resized'  });
        this.thumbPath    = new Element('input', { type: 'hidden', name: this.name + '_thumb'    });
        
        this.form.insert(this.originalPath);
        this.form.insert(this.resizedPath);
        this.form.insert(this.thumbPath);
        
        // add submit observer to the form
        this.form.observe('submit', this.submit.bind(this));
        
        // check image tag for prewiev
        this.image = $(image);
        if(this.image) {
            if(this.image.tagName.toLowerCase()!= 'img')
                throw 'preview parameter must be an IMG - Element';
        }
        
        // copy source in case there is already a picture selected
        if (this.image.alt.length > 0 )
        {
            this.resizedPath.value = this.image.alt;
            this.image.src = this.image.alt;
            this.image.show();
        }
        
        //settings
        this.settings = Object.extend({
            language: 'en',
            max_filesize: 0 // 0 no limit
        }, settings || {})
        
        //backup form attributes
        this.formAttributes = {
            action: this.form.action,
            target: this.form.target,
            method: this.form.method,
            enctype: this.form.enctype,
            onsubmit: this.form.onsubmit
        };
        
        // iframe
        this.iframe = new Element('iframe',{
            style: 'display:none;',
            name: 'image_iframe_'+this.uploadField.id
        });
        this.form.insert(this.iframe);
        
        // Event Listeners
        this.firstLoad = true;
        this.uploadField.observe('change', this.upload.bindAsEventListener(this));
        this.iframe.observe('load', this.update.bindAsEventListener(this));
    },
    /**
     * Upload file: called when the upload field changes (user selects a file)
     * @param {Event Object} e
     */
    upload: function(e){
        
        // show Message
        showMessage("Bild wird hochgeladen");
        
        /*
        if(this.files) {
            // delete created images
            query = '';
            for(name in this.files) query+='&files[]='+this.files[name];
            new Ajax.Request(this.ajax_file + '?request=unlink' + query, {
                    method: 'post'
            });
        }
        */
        this.firstLoad = false;
        with(this.form){
            action = this.ajax_file + '?request=upload&type=bar&upload_param_name=' + this.name;
            target = this.iframe.name;
            method = 'post';
            enctype = 'multipart/form-data';
            onsubmit = function() {return true};
            submit();
            // restore form arguments
            action = this.formAttributes.action;
            target = this.formAttributes.target;
            method = this.formAttributes.method;
            enctype = this.formAttributes.enctype;
            onsubmit = this.formAttributes.onsubmit;
        }
    },
    update: function(){
        
        // hide cover
        hideMessage();
        
        // if iframe is loaded when loading the page dont update
        if(this.firstLoad) return;
        response = UploaderResponse[this.uploadField.name];
        if(response.ERRORNO==0){
            this.originalPath.value = response.FILENAME_ORIGINAL;
            this.resizedPath.value  = response.FILENAME_RESIZED;
            this.thumbPath.value    = response.FILENAME_THUMB;
            
            if(this.image)
                this.image.src = response.FILENAME_RESIZED;
            this.image.show();
        }
        else
            alert(language.imageUploader.upload_error[response.ERRORNO]);
    },
    submit: function() {
        if(this.files)
            this.imagefields.each((function(field){
                field.value = this.files[field.name];
            }).bind(this));
    }
});


Event.observe(window, 'load', function() {
    if ($('addbar'))
    {
        initAddBar(0);
    }
});

// load tabs
// initialize image uploaders
initAddBar = function(first)
{
    new ImageUploader('bar_pic1', 'bar_pic1_img');
    new ImageUploader('bar_pic2', 'bar_pic2_img');
    AddBar.init(first);
}


