function formatURLFriendly(str) {
    str = str.replace(/ä/g, 'ae');
    str = str.replace(/Ä/g, 'Ae');
    str = str.replace(/ö/g, 'oe');
    str = str.replace(/Ö/g, 'Oe');
    str = str.replace(/ü/g, 'ue');
    str = str.replace(/Ü/g, 'Ue');
    str = str.replace(/ß/g, 'ss');
    str = str.replace(/\s+/g, '_');
    str = str.replace(/(\s+)?[+&](\s+)?/g, '_und_');
    str = str.replace(/[^a-z0-9_.-]/gi, '');
    return str;
}

function embedMainSwf() {
    $("#tip_trip").flash({
        src: BASE_URL + "swf/AusfluegeGalerieAS3.swf", width: 340, height: 226});

}

function embedSwfGallery(trip_id) {
    var flashvars = { xml_url: escape(SITE_URL + "xml/pictures/" + trip_id) };
    var params = { wmode: 'opaque' };
    swfobject.embedSWF(BASE_URL + "swf/gallery.swf", "gallery", "338", "180", "9.0.0", "", flashvars, params);
}

function raise_popup(uri_string, event) {
    var formdata = $("div.overlay form").serialize();
    formdata += '&' + event + '=submit'; // to check whether form is really submitted
    $.ajax({
        type: "POST",
        data: formdata,
        url: SITE_URL + uri_string,
        success: function(data) {
            data = '<div class="close">&nbsp;</div>' + '<div style="position:relative">' + data + '</div>';
            $("div.overlay")
                .html(data)
                .attr("name", uri_string)
                .overlay()
                .load();
            $("div.overlay form").submit(function(event) {
                raise_popup(uri_string, event.type);
                return false;});
        }
    });
}

function globalMapNavBindTabClicks() {
    scrollPane();
    $("#nav li.map a").unbind('click').click(function() {
        /*logic.showMap();
        return false;*/
    });
    $("#nav li.list a").unbind('click').click(function() {
       /* logic.showList();
        return false;*/
    });
    $("#nav li.trip a").unbind('click').click(function() {
       /* logic.showTrip();
        return false;*/
    });
    $("#nav li.events a").unbind('click').click(function() {
  /*      logic.showEvents();
        return false;*/
    });
}

bookmark_btn = {
    texts: {
        addable: {
            title: "Ausflug auf die Merkliste setzen",
            text: "merken"
        },
        removable: {
            title: "Ausflug von der Merkliste nehmen",
            text: "nicht mehr merken"
        }
    },

    init: function() {
        var that = this;
        var $bm_elem = $("a.bookmark_btn");
        $bm_elem.click(this.onclick);

        $bm_elem.each(function() {
            var $that = $(this);
            if ($that.hasClass("addable")) {
                $that
                    .attr("title", that.texts.addable.title)
                    .text(that.texts.addable.text);
            } else if ($bm_elem.hasClass("removable")) {
                $that
                    .attr("title", that.texts.removable.title)
                    .text(that.texts.removable.text);
            }
        });
    },

    onclick: function() {
        var $that = $(this);
        var data = this.href.substring(this.href.lastIndexOf("#") + 1).split("_");
        var trip_id = data[0];
        var event_id = data[1] || '';
        var action = $(this).hasClass('removable') ? 'remove' : 'add';

        $that
            .unbind('click').click(function(){ return false; })
            .removeClass('addable').removeClass('removable')
            .addClass('loading').addClass('inactive');

        $.ajax({
            type: "GET",
            url: SITE_URL + "main/ac_bookmark_" + action + "/" + trip_id + "/" + event_id,
            success: function(res) {
                res = res.split('|');

                if (res[0] != '1') return;

                if(action == 'add') {
                    if (window.map)
                        window.map.markTrip(trip_id);
                    $that.addClass('removable');
                    if (res[1] == 'showinfo') {
                        var view = logic._currentView == 'list' ? 'trip_list' : logic._currentView;
                        var param = logic._currentView == 'trip' ? logic._currentTrip : logic._currentTag;
                        raise_popup('overlay/guestbookmarks/main/' + view + '/' + param);
                    }
                } else {
                    if (window.map)
                        window.map.unmarkTrip(trip_id);
                    if (logic._currentView == 'list' && logic._currentTag == 'Favoriten') {
                        $("#trip_" + trip_id).fadeOut('normal', function() {
                            $(this).remove();

                            var trip_count = $("#trip_list > li").length;
                            $("#ajax_content > h2 span.tripcount").text(trip_count);

                            if (!trip_count) {
                                $("#trip_list").remove();
                                $("#empty_bookmarks").fadeIn('fast');
                            }
                        });
                    } else {
                        $that.addClass('addable');
                    }
                }
            },
            complete: function() {
                $that.removeClass('loading');
                $that.mouseleave(function() {
                    $that
                        .unbind('click').click(bookmark_btn.onclick)
                        .removeClass('inactive');
                });
            }
        });

        return false;
    }
};

function filter_list(parent) {
    var reg = new RegExp(parent.find("input.term").val(), "i");
    /*
    type = (parent.find("input.type:checked").val() == "name" ? "h4 a" : "h4 + ul li");
    console.log(parent);
    */
    type = "h4 a";
    type2 = "h4 + ul li";
    
    $("ul#trip_list div.trip").each( function() {
        var txt = $(this).find(type).text();
        var trip_id = this.parentNode.id.substring(this.parentNode.id.lastIndexOf('_') + 1);

        // if the given text is found in the name of the trip
        if (txt.search(reg) > -1) {
            $(this).parent().show();
            if (allLocations[trip_id] && allLocations[trip_id].marker)
                allLocations[trip_id].marker.show();
        } else {
            var txt = $(this).find(type2).text();
            var trip_id = this.parentNode.id.substring(this.parentNode.id.lastIndexOf('_') + 1);
            var tags = allLocations[trip_id].TAGS, found = false;
            
            // if the given text is found in the location of the trip
            if (txt.search(reg) > -1) {
                $(this).parent().show();
                if (allLocations[trip_id] && allLocations[trip_id].marker)
                    allLocations[trip_id].marker.show();
            } else {
            	// check for the tags
            	$(tags).each(function(index, Element) { 
            		if(Element.search(reg) > -1) {
            			found = true;
            			return false;
            		}
            	});
            	// if there's a hit in the tags
            	if(found === true) {
            		$(this).parent().show();
            		if (allLocations[trip_id] && allLocations[trip_id].marker)
                        allLocations[trip_id].marker.show();
            	} else {
	                $(this).parent().hide();
	                if (allLocations[trip_id] && allLocations[trip_id].marker) {
	                    allLocations[trip_id].marker.hide();
	                    allLocations[trip_id].marker.closeInfoWindow();
	                }
            	} // end if found
            }
        } // end first search reg
    });

    itemWidth($("ul#trip_list div.trip:visible").length);
    (!$("ul#trip_list div.trip:visible").length) ? $("ul#trip_list li:first").show() : $("ul#trip_list li:first").hide();
}

function order_list(parent) {
    var reg = new RegExp(parent.find("a.sort").attr('rel'), "i");
    type = (parent.find("a.sort.active").attr('rel') == "abc" ? "name" : "distance");

    var items = $('#trip_list > li').get();
    if(type == 'name') {
     items.sort(function(a,b){
          var keyA = $(a).find('.info h4 a').text();
          var keyB = $(b).find('.info h4 a').text();

          if (keyA < keyB) return -1;
          if (keyA > keyB) return 1;
          return 0;
     });
    } else {
     items.sort(function(a,b){
          var keyA = parseInt(($(a).find('.info h4 span').text()).split(" ")[0]);
          var keyB = parseInt(($(b).find('.info h4 span').text()).split(" ")[0]);

          if(isNaN(keyA)) return 1;
          if (keyA < keyB) return -1;
          if (keyA > keyB) return 1;
          return 0;
     });
    }
    var ul = $('#trip_list');
    $.each(items, function(i, li){
     ul.append(li);
    });

    $(this).parent().find('#trip_list').html(ul);
}

/*
 * This function object holds the whole logic for the events/termine page
 * Takes the date of the day to get from the db as an argument
 * 
 */
function SingleDay(dateText) {
	
	/*
	 * initialize templates, references to dom elements and other variables	 
	 */

	
	this.tripTemplate = $('.event_list > li:first').clone(true);
    this.tripTemplate.attr("style","display:block");// The template element generated in events.php is by default hidden "display:none"
	

	this.tripTemplate.find('h4');
	this.tripTemplate.find('.trip_address').empty();
	this.tripTemplate.find('.event_details').empty();
	this.tripTemplate.find('.detail_link, .bookmark_btn, .trip_link').attr('href','');
	this.tripTemplate.find('.bookmark_btn').removeClass('addable').removeClass('removable');

	this.dateText = dateText;
	this.currentdate = $('.calendar').datepicker('getDate');
	this.head = $('.event_title_some').size() === 1 ? $('.event_title_some') : $('.event_title_none');
	this.root = $('.event_list');
	this.next = $('.next'); // the references to the next and previous button
	this.previous = $('.previous');
	
	var that = this;

	
	/*
	*   This function gets the next and the previous day as text for the specified timestamp
	*/
	function getLinkDays(daytimestamp) {
		var nextdate, prevdate;
		
		nextdate = new Date(daytimestamp + (86400 * 1000));
		prevdate = new Date(daytimestamp - (86400 * 1000));

	    // because getMonth gets the months from 0 till 11, add one..
	    nextdate = getFormattedDate(nextdate);
	    prevdate = getFormattedDate(prevdate);

	    return {'prevday': prevdate, 'nextday': nextdate};
	}
	
	/*
	 * Sets the next and previous day links based upon the currently active day
	 */
	function setNextDays() {
		var tstamp,links;
		
		tstamp = new Date(that.currentdate).getTime();
		links = getLinkDays(tstamp);
		
		// reset the link
		that.next.attr('href',SITE_URL +'termine/' + links.nextday);
		that.previous.attr('href',SITE_URL +'termine/' + links.prevday);
		
		return true;
	}
	
	/*
	 * creates a single Event based upon an array argument
	 */
	function createEvent(event) {
    	
        var daterange, datespan, from, fromday,
        	frommonth, till, tillday, tillmonth, line, eventname, description;
        
        daterange = $('<dt></dt>');
        description = $('<dd></dd>');
        
        eventname = $('<span></span>')
        			.text(event.eventname)
        			.addClass('event_description');


		
        // if its either only on this day or the last day, there is no date entry for this event
        if (event['range']['from'] === undefined) {

        	datespan = $('<span></span>').addClass('range').text(event['range']+' ');
            daterange.append(datespan);
        
        } else {

        	from = $('<span></span>')
        				.addClass('event_from');
        	fromday = $('<span></span>')
        				.addClass('day')
        				.text(event['range']['from']['day']);
        	frommonth = $('<span></span>')
    					.addClass('month')
    					.text(event['range']['from']['month']);
        	
            from.append(fromday);
            from.append(frommonth);

            till = $('<span></span>')
            			.addClass('event_till');
            tillday = $('<span></span>')
	            		.addClass('day')
	            		.text(event['range']['till']['day']);
            tillmonth = $('<span></span>')
	            		.addClass('month')
	            		.text(event['range']['till']['month']);
            
            till.append(tillday);
            till.append(tillmonth);

            line = $('<span></span>')
            	.addClass('line')
            	.text('-');
            
            daterange.append(from);
            daterange.append(line);
            daterange.append(till);
        }

        description.append(eventname);

        // return an object with the information
        return {
        	eventdate: daterange,
        	description: description
        };
        
	}
	
	/*
	 * creates a whole trip based upon an array given
	 */
	function createTrip(trip) {
		var container, address, pic_url, eventhtml;
		container = that.tripTemplate.clone();

		address = trip.address;
		pic_url = trip.pic_url;
		
		delete trip.address;
		delete trip.pic_url;
		

        // trip head
    	container.find('.trip_img').attr('src',pic_url)
    				.attr('alt',trip[0]['trip_name']);
        
        container.find('.trip_address').text(address);
        
        container.find('h4 > a').attr('href',SITE_URL + 'ausflug/'+trip[0]['trip_id'])
						.text(trip[0]['trip_name']);

        container.find('.trip_link').attr('href',SITE_URL + 'ausflug/'+trip[0]['trip_id']);
        // the bookmark buttons
        container.find('.bookmark_btn')
        					.attr('href',SITE_URL + 'suche/Favoriten#'+trip[0]['trip_id'])
                            .text('x');

        if (allLocations[trip[0]['trip_id']]['bookmarked'] === true) {
        	container.find('.bookmark_btn').addClass('removable');
        } else {
        	container.find('.bookmark_btn').addClass('addable');
        }
        
        container.find('.detail_link')
                            .attr('href',SITE_URL + 'ausflug/'+trip[0]['trip_id'])
                            .text('auf der Karte anzeigen');
		
        // loop through each event of the trip
        $.each(trip,function(index, Event) {

        	eventhtml = createEvent(Event);

            container.find('.event_details')
            			.append(eventhtml.eventdate)
            			.append(eventhtml.description);
        }); // end each

        return container;
	}
	
	/*
	*   The function to create a single event on the events (termine) page
	*/
	function createSingleEventday(data) {
		
	    var triphtml;

	    that.head.removeClass();
	    
	    if (data.events.length === 0) {
	    	// only hide the content if there are no events on that day
		$('.scroll-pane').fadeOut('fast');
	        that.head.addClass('event_title_none');
	    	that.head.addClass('event_none');
	    } else {
		$('.event_list').empty();
		


	    	that.head.addClass('event_title_some');
	    	$('.scroll-pane').fadeIn('fast');
	    }

	    setNextDays(); // set the next and previous day in the head
	    
		that.head.find('.wday')
					.removeClass()
					.addClass('wday')
					.addClass(data.daytype)
					.text(data.week_day);

		that.head.find('.mday').text(data['month_day']+'.');

    	that.head.find('.month').text(data['month']);

        if (data.events_count !== 0) {
            that.head.find('.count').text('('+data['events_count']+' Termine)');
        } else {
        	that.head.find('.count').text('(Keine Termine)');
        }

	    // if there are events to display..
	    if (data.events !== undefined) {
		
	        // loop through each trip
	        $.each(data.events,function(index,trip) {

	        	triphtml = createTrip(trip);
	            that.root.append(triphtml);
	        }); // end $.each
	        
	    } // end if
	    
	    bookmark_btn.init();
	    scrollPane();
	    
	    // only fade in, if the list isnt hided because there are no events
	    if($('.scroll-pane').css('display') !== 'none') {
	    	$('.scroll-pane').fadeIn('fast');
	    }
	    return true;
	
	} // end create single event

	/*
	 * This function gets the data for the day specified as param
	*/
	function getSingleDay(dateText) {
	
	    $.ajax({
	            url: SITE_URL + 'main/events_of_day/'+dateText,
	            type: 'GET',
	            success: createSingleEventday,
	            dataType: 'json',
	            error: function(XMLHttpRequest, textStatus, errorThrown) {
	                    alert('Ein Error ist aufgetreten. \n Bitte teilen Sie uns diesen mit!');
	                    return false;
	                }
	    });
	    return true;
	}
	
	/*
	 * this function gets the ball rolling..
	 */
	this.newSingleDay = function() {
		getSingleDay(this.dateText);
		return true;
	};
	
}


/*
*   This function takes a Date Object and formats the Date in the form 'YYYY-MM-DD'
*/
function getFormattedDate(dateObj) {

    // because the Date Object returns the month from 0 till 11, add one for the format
    var month = dateObj.getMonth() + 1;
    var day = dateObj.getDate();

    if(month < 10) {
        month = '0'+month.toString();
    }
    if(day < 10) {
        day = '0'+day.toString();
    }

    return dateObj.getFullYear()+'-'+month+'-'+day;
}

$(document).ready(function() {

    /*
     * iPhone detection
     */
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { 
        if  (document.cookie.indexOf("iphone_redirect=false") == -1) window.location =  "http://itunes.apple.com/de/app/id328166908?mt=8"; 
    }

    iPad = navigator.userAgent.match(/iPad/i) != null;
    /* use custom style sheet for iPad*/
    if(iPad) {
	$('.scroll-pane').css('background','transparent url("../img/ipad/scroll.png") top right no-repeat');
    ;
//	$('link[href=http://www.100ausfluege.de/css/css.css]').attr('href','http://www.100ausfluege.de/css/css-iPad.css');
    } 

    $('#tagcloud').css('width','365px');
    $('#tagcloud').addClass('closed');
    var $closedTagCloud = $('#tagcloud.closed');
    $closedTagCloud.css('width',$closedTagCloud.find('#taghead').width()+20);
    if(iPad) {
	$(document).click(function() {
	    var $this = $('#tagcloud');
		$this.find('ul li').hide();
		$this.removeClass('hover').addClass('closed');
		$this.css('width',$this.find('#taghead').width()+20);
	});
        $('#tagcloud').click(function(e) {
	    e.stopPropagation();
            var $this = $(this);
            $this.css('width','365px');
            $this.find('ul li').fadeIn('slow');
            $this.addClass('hover').removeClass('closed');
   
        });
    } else {
        $('#tagcloud').live('mouseover focus', function() {
            var $this = $(this);
            $this.css('width','365px');
            $this.find('ul li').fadeIn('slow');
            $this.addClass('hover').removeClass('closed').mouseleave(function() {
                $this.find('ul li').hide();
                $this.removeClass('hover').addClass('closed');
                $this.css('width',$this.find('#taghead').width()+20);
            });
        });

    }

    

   /* $('.previous, .next').live('click',function(evnt) {
        var day, date, newtime;
        
        switch(evnt.currentTarget.className) {
        
	        case 'previous':
	            // set the date to one day in the past
	            newtime = $('.calendar').datepicker('getDate');
	            newtime = new Date(newtime.getTime() - (86400 * 1000));     	
	        	break;
	        case 'next':
	        	// set the Date to one day in the future
	        	newtime = $('.calendar').datepicker('getDate');
	        	newtime = new Date(newtime.getTime() + (86400 * 1000));      	
	        	break;
        }

        date = getFormattedDate(newtime);

        $('.calendar').datepicker('setDate',date);
        $('.scroll-pane').fadeOut('fast',function() {
							        	day = new SingleDay(date);
							            day.newSingleDay();
                                    });
        return false;
    });*/

    $('.calendar').datepicker({
    	firstDay: 1,
        dateFormat: 'yy-mm-dd',
        dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
        dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
        monthNamesShort: ['Jan','Feb','M&auml;r','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
        monthNames: ['Januar','Februar','M&auml;rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
        onSelect: function(date) {
    				var day;
                    // fade out and call the function to create the Event AFTER 
                    $('.scroll-pane').fadeOut('fast',function() {
                    					day = new SingleDay(date);
                    					day.newSingleDay();
                                    });
                }
    });

    /* map initialization */
    var mapElem = document.getElementById("map");
    if (mapElem) {
        try {
            window.map = new Map();
            window.map.load(mapElem);
            if (logic && logic._currentTrip)
                window.map.showLocation(allLocations[logic._currentTrip], true, true);
        } catch(e) {
            //alert('Fehler E002 ' + e);
        }
    }

    // generate an overlay-handler
    var expose = $("div.overlay").expose({api:true, opacity: 0.4, color: "#000"});
    var overlay = $("div.overlay").overlay({
        oneInstance: true,
        api: true,
        close: 'div.close',
        onBeforeLoad: function() { expose.load(); },
        onClose: function() { expose.close(); }
    });
    $("div.overlay div.close").live('click', function() {
        $(this).parent().overlay().close();
    });

    // Trip-List-Filtering
    $('form.filter_control input.term').live('keyup', function(){
        filter_list($(this).parent());
    });

    $("form.filter_control a.sort.active").live('click', function() {
        return false;
    });

    clearSearchInput();
  
    $("form.filter_control a.noData").live('click', function() {
        if($(this).attr('rel') == "km")
            raise_popup('overlay/nologin/main/trip_list/' +logic._currentTag);
        return false;
    });

    $("form.filter_control a:not(.noData)").live("click", function () {
        /*$("form.filter_control input")*/
        $(this).parent().find("a.sort.active").toggleClass("active");
        $(this).addClass("active");
        order_list($(this).parent().parent());
    });

    $('form.filter_control input.reset').live('click', function(){
        $(this).parent().parent().find('input.term').val('');
        filter_list($(this).parent().parent());
        var current = $("#tagcloud li.current");
            current.removeClass("current");
            $("#tagcloud #tag_Alle").addClass("current");

            var tag = "Alle";
            tagcloud.highlightTag(tag);
            logic.selectTagInTagcloud(tag);
            $('#tagcloud #taghead').text($("#tagcloud li.current a").text()); 
            $("#tagcloud").css('width',$("#taghead").width()+20); 
        $(this).parent().parent().find('input.term').val('Suchwort');
        clearSearchInput();
    });

    // Service-Popups
    $("#servicebar a.overlay").live('click', function(event){
        raise_popup('overlay/' + $(this).attr("name") + '/' + $(this).attr("rel"), event.type);
        return false;
    });

    /* expand map on edit page */
    $("a.expand_geo").click(function() {
        map.savePosition();

        if ( $("#geomap").hasClass("expanded") )
            $("#geomap").animate({height: "212"},"fast", function() {
                map.checkResize();
                map.returnToSavedPosition();
            });
        else
            $("#geomap").animate({height: "450"},"fast", function() {
                map.checkResize();
                map.returnToSavedPosition();
            });

        $("#geomap").toggleClass("expanded");
        return false;
    });

    zoomTrip(); 

    /* global tab nav */
    globalMapNavBindTabClicks();


    /* trip name and top photo in trip list */
    $("ul.event_list > li, #trip_list > li").live('click', function() {
        var link = $(this).find("h4 > a").attr('href');
        window.location.href = link; 
        return false;
    });

    /* detail link in trip list */
    $("#trip_list a.detail_link,#events ul.event_list li a.detail_link").live('click', function() {
        
        $(this).parent().addClass("current").removeClass("hover");
        var trip_id = this.href.substring(this.href.lastIndexOf("/") + 1);
        if (allLocations[trip_id] && allLocations[trip_id].marker)
            GEvent.trigger(allLocations[trip_id].marker, 'click');
        return false;
    });

    /* trip links in event list */
    $("#events ul.event_list li a").live('click', function() {
        var trip_id = this.href.substring(this.href.lastIndexOf("/") + 1);
        /*logic.showTrip(trip_id);
        return false;*/
    });

    /* hover effect in trip list */
    $('#trip_list > li:not(.letter,.current),#events ul.event_list > li:not(.current)').live('mouseover', function() {
        // shows the tooltip on mouseover
        var link = $(this).find('a').attr('href');
        var trip_id = link.substring(link.lastIndexOf('/') +1);
        showTooltip(allLocations[trip_id].marker);
        $(this).addClass('hover');
        $(this).mouseleave(function() {
            tooltip.style.visibility="hidden"; // hides the tooltip again
            $(this).removeClass('hover');
        });
    });

 /* trip links in event list */

    /* show/hide details toggle */

    /* show/hide empty days toggle */
    $(".event_toggle_emptydays").live('click', function(){
        if ( $(this).text() == 'ausblenden' ) {
            $('.event_none').hide();
            $(this).text('einblenden');
        } else  {
            $('.event_none').show();
            $(this).text('ausblenden');
        }
    });

    /* bookmark icons */
    bookmark_btn.init();

    /* tags in tagcloud */
    $('#tagcloud li.tag').click(function(event) {
        var tag = this.id.substring(4);
        tagcloud.highlightTag(tag);
        logic.selectTagInTagcloud(tag);
        $('#tagcloud #taghead').text($("#tagcloud li.current").text()); 
        $('#search_field').val('');
        event.preventDefault();
        /*return false;*/
    });

    clearSearchInput();
    embedMainSwf();
    scrollPane();
});

tagcloud = {
    reset: function() {
        $("#tagcloud li").removeClass("understated");
    },
    highlightTag: function(tag) {
        $("#tagcloud li")
            .filter(".current").removeClass("current").end()
            .filter("[id='tag_"+tag+"']").addClass("current");
        $("#tagcloud li").find('#taghead').text(tag); 
    },
    highlightTripTags: function() {
        this.reset();

        var tags = allLocations[logic._currentTrip].TAGS;
        tags = $.map(tags, function(n) { return formatURLFriendly(n); }); // format to friendly url format

        var not = "[id='tag_" + tags.join("'], [id='tag_") + "']";
        $("#tagcloud li").not(not).addClass("understated");
    }
};

logic = {

/* BEGIN options */
    _fadeSpeed: 'fast',
/* END options */


/* BEGIN states */
    _currentView: 'map',
    _currentTag: 'Alle',
    _currentTrip: null,
/* END states */


/* BEGIN ajax loaders */
    _load: function(view, params, split_view, pre_callback, post_callback) {
        var that = this;
        params = params || [];
        pre_callback = pre_callback || function(){};
        post_callback = post_callback || function(){};
        $.ajax({
            type: "GET",
            url: SITE_URL + 'main/ac_' + (view == 'list' ? 'trip_list' : view) + '/' + params.join('/'),
            success: function(data) {
                pre_callback();

                var showData_callback = function() {
                    changeViewClass(view);
                    $("#ajax_content").html(data);

                    /*if($.browser.msie)
                        $("#ajax_content div.tab_content.current").css("display", "block");*/
                    $("#ajax_content").fadeIn(that._fadeSpeed, function(){
                        post_callback();
                        that.setCurrentView(view);
                        that._viewChangeEnd(view);
                    });
                };
                $("#gallery").css('visibility', 'hidden');

                var afterFadeOut_callback = function() {
                    if (split_view != null)
                        that._splitView(split_view, function() { showData_callback(); });
                    else
                        showData_callback();
                };
                // currently there are some problems with safari/chrome (=webkit)
                // that some faded out elements will not or not normally appear again when fading in;
                // therefore as a quick solution we disable the fadeout of the content
               /* if($.browser.safari)*/
                    afterFadeOut_callback();
/*                else
                    $("#ajax_content").fadeOut(that._fadeSpeed, afterFadeOut_callback);*/
            }
        });
    },
    _loadTripTab: function(trip, is_current) {
        var that = this;
        $.ajax({
            type: "GET",
            url: SITE_URL + 'main/ac_trip_tab/' + trip + '/' + (is_current ? '1' : ''),
            success: function(data) {
                var $data = $(data);
                var $tripTab = $("#nav li.trip");
                var $tripTabA = $tripTab.find('a');

                if($tripTabA.length) {
                    $tripTab.html($data);
                    $("#nav li.trip a").unbind('click').click(function() {
                        logic.showTrip();
                        return false;
                    });
                } else {
                    $tripTab.html($data.hide());
                    $data.fadeIn(that._fadeSpeed, function() {
                        $("#nav li.trip a").unbind('click').click(function() {
                            logic.showTrip();
                            return false;
                        });
                    });
                }
            }
        });
    },
/* END ajax loaders */


/* BEGIN helpers */
    _splitView: function(on, callback) {
        // need some workaround here for webkit browsers
        // see comments on _load() function for more info
        if ($.browser.safari && !on)
            $("#ajax_content").hide();

        animateInfo(on, callback);
    },
/* END helpers */


/* BEGIN view change helpers */
    _viewChangeStart: function(view) {
       /* $("#nav a").unbind('click').click(function(){return false});
        if (view == 'trip') {
            var $loadingElem = $(document.createElement('a'));
            $loadingElem
                .html('&nbsp;')
                .attr('href', '#')
                .click(function(){ return false })
                .addClass('loading');
            if($("#nav li.trip a").hasClass('current'))
                $loadingElem.addClass('current');
            $("#nav li.trip").html($loadingElem);
        } else {
            $("#nav li." + view + " a").addClass('loading');
        }*/
    },
    _viewChangeEnd: function(view) {
       /* globalMapNavBindTabClicks();
        $("#nav li." + view + " a").removeClass("loading");*/
    },
/* END view change helpers  */


/* BEGIN state setters */
    setCurrentView: function(view) {
        if (view == this._currentView) return;
        this._currentView = view;
        /*$("#nav li a").removeClass("current");
        $("#nav li." + view + " a").addClass("current");*/
    },
    setCurrentTag: function(tag, dont_show_on_map) {
        if (tag && tag != this._currentTag) {
            this._currentTag = tag;
            if (!dont_show_on_map && window.map)
                window.map.highlightTag(tag);
            return true;
        }
        return false;
    },
    setCurrentTrip: function(trip) {
        if (trip && trip != this._currentTrip) {
            this._currentTrip = trip;
            /*scrollTo(trip);*/
            return true;
        }
        return false;
    },
/* END state setters */

/* BEGIN select handlers */
    selectTripMarker: function(trip) {
        switch(this._currentView) {
            case 'trip':
                // do nothing
                break;
            case 'list':
                $("#trip_list > li.current").removeClass("current");
                $("#trip_" + trip).addClass("current");
            case 'events':
            case 'map':
            default:
                var tripChanged = this.setCurrentTrip(trip);
                if (tripChanged) {
                    this._loadTripTab(trip);
                }
                break;
        }
    },
    selectTagInTagcloud: function(tag) {
        switch(this._currentView)  {
            case 'events':
                this.showEvents(tag);
                break;
            case 'map':
            case 'trip':
            case 'list':
            default:
                this.showList(tag);
                break;
        }
    },
/* END select handlers */

/* BEGIN show handlers */
    showMap: function(tag) {
        var that = this;
        var tagChanged = this.setCurrentTag(tag);
        var params = [ this._currentTag ];

        tagcloud.reset();
        this._viewChangeStart('map');

        switch(this._currentView) {
            case 'map':
                if (tagChanged)
                    this._load('map', params);
                else
                    this._viewChangeEnd('map');
                break;
            case 'events':
            case 'list':
                    this._load('map', params, false);
                break;
            case 'trip':
                this._load('map', params, false, function() {
                    if (window.map) window.map.showOverview();
                    $("#map_zoom_detail").fadeOut(that._fadeSpeed);
                });
                break;
        }
    },
    showList: function(tag) {
        var that = this;
        var tagChanged = this.setCurrentTag(tag);
        var params = [ this._currentTag, this._currentTrip ];

        tagcloud.reset();
        this._viewChangeStart('list');

        var pre_callback = function() {
            if (window.map) window.map.showOverview();
            $("#map_zoom_detail").fadeOut(that._fadeSpeed);
        };
        var post_callback = function() {
            bookmark_btn.init();
            scrollPane();
        };

        switch(this._currentView) {
            case 'list':
                if (tagChanged)
                    this._load('list', params, null, null, post_callback);
                else
                    this._viewChangeEnd('list');
                break;
            case 'map':
                this._load('list', params, true, null, post_callback);
                break;
            case 'events':
                this._load('list', params, null, null, post_callback);
                break;
            case 'trip':
                this._load('list', params, null, pre_callback, post_callback);
                break;
        }
    },
    showTrip: function(trip, via_gm_info_window) {
        var that = this;
        var tripChanged = this.setCurrentTrip(trip);
        var params = [ this._currentTrip, this._currentTag ];

        var pre_callback = function () {
            tagcloud.highlightTripTags();
        };
        var post_callback = function () {
            that._loadTripTab(that._currentTrip, true);
            embedSwfGallery(that._currentTrip);
            bookmark_btn.init();
            if(that._currentView != 'trip')
                $("#map_zoom_detail").fadeIn(that._fadeSpeed);
            if (!via_gm_info_window && allLocations[trip] && allLocations[trip].marker)
                GEvent.trigger(allLocations[trip].marker, 'click');
        };

        switch(this._currentView) {
            case 'trip':
                if (tripChanged || via_gm_info_window) {
                    this._viewChangeStart('trip');
                    this._load('trip', params, null, pre_callback, post_callback);
                }
                break;
            case 'list':
            case 'events':
                this._viewChangeStart('trip');
                this._load('trip', params, null, pre_callback, post_callback);
                break;
            case 'map':
                this._viewChangeStart('trip');
                this._load('trip', params, true, pre_callback, post_callback);
                break;
        }
    },
    showEvents: function(tag) {
        var that = this;
        var tagChanged = this.setCurrentTag(tag);
        var params = [ this._currentTag, this._currentTrip ];

        tagcloud.reset();
        this._viewChangeStart('events');

        switch(this._currentView) {
            case 'events':
                if (tagChanged)
                    this._load('events', params);
                else
                    this._viewChangeEnd('events');
                break;
            case 'map':
                this._load('events', params, true);
                break;
            case 'trip':
                this._load('events', params, null, function() {
                    if (window.map) window.map.showOverview();
                    $("#map_zoom_detail").fadeOut(that._fadeSpeed);
                });
                break;
            case 'list':
                this._load('events', params);
                break;
        }
    }
/* END show handlers */

};

function zoomTrip(){
        if (logic._currentTrip && window.map) {
            logic.selectTripMarker(logic._currentTrip);
            window.map.showDetail(logic._currentTrip);
        }
        return false;
}

function itemWidth( numItems ){
    if(numItems > 4) {
        $("#ajax_content ul#trip_list > li").css("width", "385px");
        scrollPane();
    } else {
        $("#ajax_content ul#trip_list li").css("width", "100%");
        scrollPaneHide();
    }
}
/*
function scrollTo( trip ){
    var $selector = $('#trip_list.scroll-pane').find('#trip_'+trip);

    console.log($selector);
    $('.jScrollPaneContainer').scrollTo($selector);
    return true;
}
*/

function clearSearchInput() {
    $('#search_field').focus(function(){if($(this).attr('value') == 'Suchwort') $(this).attr('value', '');});
    $('#search_field').blur(function(){if($(this).attr('value') == '') $(this).attr('value', 'Suchwort');});
}

function scrollPane() {
	if(!iPad) {
	    var params = {
		scrollbarWidth: 7,
		scrollbarMargin: 6,
		dragMinHeight: 30,
		wheelSpeed: 150,
		showArrows: true,
		arrowSize: 2,
		mantainPosition: false
	    };

	    if($.browser.msie){
		if(!($('#ajax_content').parent().find('#tab_nav')).length){
		    $('.scroll-pane').jScrollPane(params);
		}
		else{
		    $('.scroll-pane').css("overflow-y","auto").css("width", "408px");
		}
	    } else {
		$('.scroll-pane').jScrollPane(params);
	    }
	}
}

function scrollPaneHide() {
	if(!iPad) {
		$('.scroll-pane').jScrollPaneRemove();
		/*bugfix for previous line*/
		$('.scroll-pane').css("position","relative");
	}
}

function calculateDimensions(tab_content, idx){
        var pane = $(tab_content).find('.jScrollPaneContainer .scroll-pane');
        if(idx>0)
                $(pane).parent().css("height", "430px").css("width", "406px");
        else
                $(pane).parent().css("height", "245px").css("width", "406px");

        $(pane).css("width", "auto").css("height","auto").css("position","relative");
}

function changeViewClass(view) {
/*       if(view == "trip"){
           $('#wrapper').removeClass().addClass("detail"); 
       } else if(view == "events") {
           $('#wrapper').removeClass().addClass("events"); 
       } else if(view == "trip") {
           $('#wrapper').removeClass().addClass("detail"); 
       } else if(view == "map") {
           $('#wrapper').removeClass().addClass("main"); 
       } */ 
}

// FIXME: recode with jquerys animate function
function animateInfo( show, callback ) {
    var m = document.getElementById("map");
    var d = document.getElementById("ajax_content");
    callback = callback || function(){};
    if ( ! m || ! d ) return;

    if(!show) {
        if(!$(d).hasClass('filled') && !$(m).hasClass('splitsize')) {
            callback();
            return;
        }
        $(d).removeClass('filled');
        $(m).removeClass('splitsize');
    } else {
        if($(d).hasClass('filled') && $(m).hasClass('splitsize')) {
            callback();
            return;
        }
    }

    if (map && map.map)
        map.map.savePosition();

    var width = 0;

    var itv = setInterval(function () {
        if ( show ) {
           // m.style.width = (760-width)+"px";
          //  d.style.width = (29+width)+"px";
        } else {
            m.style.width = (400+width)+"px";
            if ((389-width) < 0)
                d.style.width = 0+"px";
            else
                d.style.width = (389-width)+"px";
        }
        width += 30;
        if ( width > 390) {
            clearInterval( itv );
            if (map && map.map)  {
                map.map.checkResize();
                map.map.returnToSavedPosition();
            }
            if (show) {
                $(d).addClass('filled');
                $(m).addClass('splitsize');
            } else {
                m.style.width = "792px";
            }
            callback();
        }
    }, 10 );
}
/*
(function ($) {
  $.extend($.fn, {
    clearingInput: function (options) {
      var defaults = {blurClass: 'blur'};

      options = $.extend(defaults, options);

      return this.each(function () {
        var input = $(this).addClass(options.blurClass);
        var form  = input.parents('form:first');
        var label, text;

        text = options.text || textFromLabel() || input.val();

        if (text) {
          input.val(text);

          input.blur(function () {
            if (input.val() === '') {
              input.addClass(options.blurClass).val(text);
            }
          }).focus(function () {
            if (input.val() === text) {
              input.val('');
            }
            input.removeClass(options.blurClass);
          });

          form.submit(function() {
            if (input.hasClass(options.blurClass)) {
              input.val('');
            }
          });

          input.blur();
        }

        function textFromLabel() {
          label = form.find('label[for=' + input.attr('id') + ']');
          // Position label off screen and use it for the input text
          return label ? label.css({position: 'absolute', left: '-9999px'}).text() : '';
        }
      });
    }
  });
})(jQuery);
*/



