/*
 * Eike Pierstorff (eike@diebesteallerzeiten.de) fÃ¼r p3000.net
 * 22.04.09
 */

$(document).ready(function(){

    /*
     * Ersetzt das Serverseitige Highlight fÃ¼r MenÃ¼items durch eine URL-basierte Javascript-LÃ¶sung
     */
    $.fn.jusohighlight = function(options){
        var opts = $.extend({}, $.fn.jusohighlight.defaults, options);
        path = window.location.href.replace($.fn.jusohighlight.defaults.baseurl, '');
        if (path == "") 
            return;
        
        subpaths = path.split('/');
		
        if (subpaths[0].indexOf('pressemi') > -1) // grmpfh
            subpaths[0] = "aktuell";
        
        $('a[href^="/' + subpaths[0] + '"]').each(function(i){
            $(this).parent().addClass('active-trail');
        })
        $('a[href$="' + subpaths[0] + "/" + subpaths[1] + '"]').addClass('active');
		
	    // Logo-Top-Links Highlighting
		if (subpaths[0].indexOf('live') > -1) {
			$('#logo-top-links-live').css("color","white");
			$('#logo-top-links-website').css("color","#FF8A8A");
		}
        
    };
    
    $.fn.jusohighlight.defaults = {
        baseurl: 'http://www.jusos.de/'
    };
    
    $('#navi-main').jusohighlight();
      
    /*
     * Erzeugt in der "BÃ¼hne" im Seitenkopf aus einer JSON-Datei das nÃ¶tige Markup fÃ¼r das JQuery-Plugin JCycle
     * und ruft es anschliessend auf
     */
    $.fn.jusoheader = function(){
    
        $(this).html($('<div />').attr("id", "innerstage"));
        $.getJSON("/sites/all/themes/jusos/js/gallery.js", function(json, status){
            if (status != "success") 
                return;
            cnt = json.gallery.items.length;
            topics = "";
            for (i = 0; i < cnt; i++) {
				
				if(json.gallery.items[i].img.indexOf('.swf') > -1) {
					topics += '<div class="featureditem"><a href="' + json.gallery.items[i].link + '"><object width="950" height="250">';
					topics += '<param name="movie" value="' + json.gallery.items[i].img + '" />';
					topics += '<param name="wmode" value="transparent" />';
					topics += '<param name="allowscriptaccess" value="always" />';
					topics +='<embed src="' + json.gallery.items[i].img + '" type="application/x-shockwave-flash" wmode="transparent" width="950" height="250"></embed>';
					topics += '</object></a></div>';
				} else {
                	topics += '<div class="featureditem"><a href="' + json.gallery.items[i].link + '"><img alt="" src="' + json.gallery.items[i].img + '" /></a></div>' + "\n";
            	}
			}
            $('#innerstage').html(topics);
            
            $('#innerstage').cycle({
                fx: 'fade',
                speed: 'fast',
                timeout: 10000,
                pause: 2,
                next: '#left',
                prev: '#right'
            });
            
        });
        
        $("<a />").attr("id", "left").appendTo($(this));
        $("<a />").attr("id", "right").appendTo($(this));
    };
    
    $('#header-img-region').jusoheader();
    
    
    /*
     * Erzeugt einen Flickrbadge mit Navigation
     */
    $.fn.jusoflickr = function(){
        $(this).html($('<div />').attr("id", "innerflickrbadge"));
        
        $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=34420189@N02&lang=de-de&format=json&jsoncallback=?", function(data){
            $.each(data.items, function(i, item){
                $("<img/>").attr("src", item.media.m.replace("_m","_t")).appendTo("#innerflickrbadge").wrap("<a href='" + item.link + "'></a>");
            });
            
            maxwidth = data.items.length * 126;
            
            $("#innerflickrbadge").after($('<div />').attr("id", "flickrnavi"));
            
            $('<span />').attr("id", "previmg").html('&nbsp;').appendTo("#flickrnavi");
            $('<span />').attr("id", "nextimg").html('&nbsp;').appendTo("#flickrnavi");
            
            $('#previmg').click(function(){
                if (parseInt($('#innerflickrbadge').css('margin-left')) > -126) 
                    return;
                
                $('#innerflickrbadge').animate({
                    marginLeft: parseInt($('#innerflickrbadge').css('margin-left')) + 126 + "px"
                })
            });
            
            $('#nextimg').click(function(){
            
                if (parseInt($('#innerflickrbadge').css('margin-left')) < -(maxwidth - (7 * 126))) 
                    return;
                
                $('#innerflickrbadge').animate({
                    marginLeft: parseInt($('#innerflickrbadge').css('margin-left')) - 126 + "px"
                })
            });
            
        });
    };
    
    
    $('#front #flickrbadge').jusoflickr();
    
    /*
     * Liest den JSON-Feed aus dem Juso-Blog und fÃ¼gt die EIintrÃ¤ge auf der Startseite ein
     */
    $.fn.jusoblogfeed = function(){
        this.addClass('blogfeed');
        $(this).html($('<ul />').attr("id", "innerblogfeed"));
        $('#innerblogfeed').html('<h2>Diskutier\' mit uns im Blog</h2>');
        $.getJSON("http://blog.jusos.de/feed/json/?callback=?", function(data, status){
            i = 0;
            $.each(data.items, function(i, item){
                $("<a/>").attr("href", item.link).html(item.title).appendTo("#innerblogfeed").wrap($('<li />')).after($('<span class="arrow" />'));
                i++;
                if (i > 2) 
                    return false;
            });
            $('<a />').attr('href', 'http://blog.jusos.de/').attr('id', 'bloglink').html('&nbsp;').appendTo("#innerblogfeed");
        });
        
    };
    
    $('#blogfeed').jusoblogfeed();
    
    
    /* Shop Details anzeigen oder verbergen */
    $("#order label[id^='item']").click(function(){
        $("dd." + this.id).slideToggle(true);
        $(this).toggleClass('open');
        return false;
    });
    
    
    /*
     * Materialbestellung - bei einem KLick in das Bestellformular
     * werden die Felder die eine Bestell-Anzahl enthalten angezeigt
     */
    $("#orderform #name").click(function(){
    
        $("#order li , #order dd").hide();
        $("#order li#orderform , #order dd.ordernow").show();
        
        $("#order li").each(function(){
            if ($(this).find('input:first').val()) {
                $(this).show();
            }
            else {
                if ($(this).attr('id') != "orderform") 
                    $(this).hide();
            }
            
        });
		 $("#orderform #name").focus();
    });
    
    
	function preSelect() {
		 
		 
		$("#order li[id!=orderform]").hide();
			    
		qs = location.search.substring(1);
		urlvars = qs.split('&');
		var url = new Object();
		for(i = 0; i < urlvars.length; i++)
		{
		  eq = urlvars[i].indexOf('=');
		  url[urlvars[i].substring(0,eq).toLowerCase()] = unescape(urlvars[i].substring(eq + 1));
		}
 		

        kat = url['kat'];

        if (kat == "All" || typeof url['kat'] == "undefined") {
            kat = ""
        }
        else {
            kat = "tid" + kat
        }
        
        if (kat == "") {
            $("#order li").show();
            return false;
        }
         
        $("li." + kat).show();
    
	}
	
	 preSelect();
	 
    /*
     * Materialbestellung, filtert die Anzeige anhand der Auswahl
     * in den Dropdown-Feldern
     */
    $("#views-exposed-form-Materialienbestellen-page-1").submit(function(){
    	

		$("#order li[id!=orderform]").hide();
				  
        typ = $('#edit-kategorie option:selected').val();
        kat = $('#edit-typ option:selected').val();
      
		if (typ == "All") {
            typ = ""
        }
        else {
            typ = ".tid" + typ
        }
        if (kat == "All") {
            kat = ""
        }
        else {
            kat = ".tid" + kat
        }
        
        if (typ == "" && kat == "") {
            $("#order li").show();
            return false;
        }

		$(kat + typ ).slideDown();
        return false;
    });
    
    
    /* Mitmachen Jugendwahlkampf wird Ã¼ber ein einfaches Akkordion strukuriert */
    $("#accordion div.accordion_headings").click(function(){
        $("#accordion div.child").each(function(i, item){
            if ($(this).css('display') != "none") {
                $(this).slideUp();
            }
        });
        
        if ($("div." + this.id).css('display') != 'none') {
            $("div." + this.id).slideUp();
        }
        else {
            $("div." + this.id).slideDown();
        }
        
    });
    
    $("#accordion").css('height', '2000px');
    $("#accordion div.child").hide();
    $("div.pflicht").show();
	

	
	/* Hilfe auf Live Feed Aggregator aufklappbar */
    $("div.accordion_live div.accordion_headings_live").click(function(){
        $("div.accordion_live div.child_live").each(function(i, item){
            if ($(this).css('display') != "none") {
                $(this).slideUp();
            }
        });
        
        if ($("div." + this.id).css('display') != 'none') {
            $("div." + this.id).slideUp();
        }
        else {
            $("div." + this.id).slideDown();
        }
        
    });
    $("div.accordion_live div.child_live").hide();



	// Aufruf des Kalender, definiert in einem Plugin-Datei
	// $('#gcal').datepick();
	
    /*
     * Liest den JSON-Feed aus dem Juso-Blog und fügt die EIinträge auf der Startseite ein
     */
    $.fn.calendarfeed = function(){
        
        $(this).html($('<ul />').attr("id", "innercalendarfeed"));
		wrapper = $('<div/>').attr('id','gcalwrapper');
		$("#innercalendarfeed").wrap(wrapper);  
		
		$.fn.calendarfeed.btmLimit = 0;
		$.fn.calendarfeed.topLimit = 0;
		$.fn.calendarfeed.perpage  = 5;
		
		cur = $.fn.calendarfeed.getDate();
		nxt = $.fn.calendarfeed.getNxtDate();
		
		$.fn.calendarfeed.loadStuff(cur,nxt);	
		$.fn.calendarfeed.navi();
		
    };

	
	
	$.fn.calendarfeed.loadStuff = function(cur,nxt) {

      $.getJSON("http://www.google.com/calendar/feeds/fc0kmqlnt8aobtgi5fs4lt531k%40group.calendar.google.com/public/full?alt=json-in-script&start-min=" + cur  +  "&start-max=" + nxt + "&sortorder=a&orderby=starttime&max-results=3000&callback=?", function(data, status){
      	
			$('#innercalendarfeed').html("");
			if(typeof(data.feed.entry) == 'undefined') {
				 li = $('<li />').html('F&uuml;r dieses Datum wurden keine Veranstaltungen gefunden');
				 li.appendTo("#innercalendarfeed");
				return;
			}
			$.fn.calendarfeed.resetLimit();	
            $.each(data.feed.entry, function(i, entry){
				 
				 if(entry.content.$t.indexOf('#buvo') < 0) {
				 	return 1;
				 }
				 				 
				 start = (entry['gd$when']) ? $.fn.calendarfeed.formatDate(entry['gd$when'][0].startTime.toString()) : "";	
				 stop  = (entry['gd$when']) ? $.fn.calendarfeed.formatDate(entry['gd$when'][0].endTime.toString()) : "";	
				 
				 exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  				 entry.content.$t = entry.content.$t.replace(exp,"<a href='$1'>$1</a>"); 
				 				 
				 if (start != stop) {
				 	date = '<span class="date">' + start + " - " + stop + "</span>";
				 } else {
				 	date = '<span class="date">' + start + "</span>";				 	
				 }	
				 
				 where =  "<em>" + entry['gd$where'][0].valueString.toString() + "</em> ";
				 
				 li = $('<li />');
				 header = $("<h4/>").html(date + where + " " + entry.title.$t).addClass('event'+i)
				 li.append(header);
				
				 if (entry.content.$t) {
					header.css('cursor','pointer');
				 	header.click(function(){				 	
						$("#" + this.className).toggle('slow');					
				 	});					
				 }
 				li.append($('<div/>').attr('id', 'event' + i).addClass('description').html(entry.content.$t.replace('#buvo','')));
				
				li.appendTo("#innercalendarfeed");

            });
			
			if ($('#innercalendarfeed li').length < 1) {
				$('#nextevents').css('display','none');
				$('#prevevents').css('display','none');				
				li = $('<li />').html('F&uuml;r dieses Datum wurden keine Veranstaltungen gefunden');
				li.appendTo("#innercalendarfeed");
				return;
			}
			else {
				$.fn.calendarfeed.navigate();
			}
			
       		if($('#gcalheadline').length == 0)
					$('#gcalwrapper').before($('<h2 id="gcalheadline">Veranstaltungen</h2>'));
					
			if($('#gcal_year').length == 0)		
				$.fn.calendarfeed.year();  
			if($('#gcal_month').length == 0)		
				$.fn.calendarfeed.month();		
        });		
		
	};
	
	$.fn.calendarfeed.navigate = function () {
			$('#innercalendarfeed li').css('display','none');
			if($.fn.calendarfeed.getBtmLimit()  <= 0 ) {
				$('#prevevents').css('display','none');
			} else {
				$('#prevevents').css('display','inline');
			}
			if($.fn.calendarfeed.getTopLimit()  >= $('#innercalendarfeed li').length ) {
				$('#nextevents').css('display','none');
			} else {
				$('#nextevents').css('display','inline');
			}			
			
			$('#innercalendarfeed li').slice(  $.fn.calendarfeed.getBtmLimit(),  $.fn.calendarfeed.getTopLimit()).css('display','block');	
	};
	
	$.fn.calendarfeed.getBtmLimit = function () {
		return $.fn.calendarfeed.btmLimit;
	};

	$.fn.calendarfeed.getTopLimit = function () {		
		return $.fn.calendarfeed.topLimit = $.fn.calendarfeed.btmLimit + $.fn.calendarfeed.perpage;		
	};

	$.fn.calendarfeed.setBtmLimit = function(num){	
		$.fn.calendarfeed.btmLimit = $.fn.calendarfeed.btmLimit + num;	
	}
	
	$.fn.calendarfeed.resetLimit = function(){
		$.fn.calendarfeed.btmLimit  = 0;
		$.fn.calendarfeed.topLimit =  $.fn.calendarfeed.perpage;				
	}

	$.fn.calendarfeed.getDate = function(nxt) {
		date = new Date();	 
		return $.fn.calendarfeed.yyyy(date) + "-" + $.fn.calendarfeed.mm(date) + "-" + "01";
	};
	
	$.fn.calendarfeed.getNxtDate = function(nxt) {
		date = new Date();	 
		y = date.getFullYear();
		m = date.getMonth()+1;
		m++;
		if(m >= 12) {
			m = 1;
			y = date.getFullYear() + 1; 
		}
		return y + "-" + $.fn.calendarfeed.pad(m) + "-" + "01";
	};	

	$.fn.calendarfeed.pad =  function (x) { 
		return (x<0||x>9?"":"0") + x; 
	};
	
 	$.fn.calendarfeed.mm   = function (date,nxt) {
		if(nxt == true)
			date.setMonth(date.getMonth+1); 
		return $.fn.calendarfeed.pad(date.getMonth() + 1); 
	};
		
 	$.fn.calendarfeed.dd   = function (date) { 
		return $.fn.calendarfeed.pad(date.getDay() + 1); 
	};
		
 	$.fn.calendarfeed.yyyy   = function (date) { 
		return date.getFullYear(); 
	};	

	
	$.fn.calendarfeed.formatDate = function (dateString) {
	   parts = dateString.substring(0,10).split("-");
	   return parts[2] + '.' + parts[1] + '.' + parts[0];	
	}
	
	
	$.fn.calendarfeed.year = function(){
		sel = $('<select/>').attr({name:'jahr',id:'gcal_year'});	
		$('#gcalwrapper').before(sel);		
		date = new Date();	
		for(i=2010;i<=2012;i++) {
			if(i == date.getFullYear()) {
				$('<option/>').attr({value:i,selected:'selected'}).html(i).appendTo($('#gcal_year'));				
			} else {
				$('<option/>').attr({value:i}).html(i).appendTo($('#gcal_year'));				
			}

		}
		sel.change(function() {
			$('#innercalendarfeed').css("margin-top",0);		
			cur = get_cur();	
			nxt = get_nxt();
							
			$.fn.calendarfeed.loadStuff(cur,nxt);
		});
	}
	
	$.fn.calendarfeed.month = function(){

		sel = $('<select/>').attr({name:'jahr',id:'gcal_month'});	
		$('#gcalwrapper').before(sel);	
		date = new Date();			
		for(i=0;i<=11;i++) {
			if (i == date.getMonth()) {
				$('<option/>').attr({value:i,selected:'selected'}).html($.fn.calendarfeed.pad(i+1)).appendTo($('#gcal_month'));
			}
			else {
				$('<option/>').attr({value:i}).html($.fn.calendarfeed.pad(i+1)).appendTo($('#gcal_month'));			
			}
		}
		sel.change(function() {
			$('#innercalendarfeed').css("margin-top",0);
			cur = get_cur();	
			nxt = get_nxt();
				
			$.fn.calendarfeed.loadStuff(cur,nxt);
		});	
	}	
	
	$.fn.calendarfeed.navi = function () {
		
		if ($('#nextevents').length < 1) {
			$('#gcalwrapper').after($('<a/>').attr({
				href: '#',
				style:'display:none',
				id: 'nextevents'
			}).html('weiter &raquo;'));
			$('#gcalwrapper').after($('<a/>').attr({
				href: '#',
				style:'display:none',				
				id: 'prevevents'
			}).html('&laquo; zurueck'));
		}
		
	    $('#nextevents').click(function(){
			if($.fn.calendarfeed.getTopLimit() > $('#innercalendarfeed li').length) {
				return false;
			}
			$.fn.calendarfeed.setBtmLimit($.fn.calendarfeed.perpage);
			$.fn.calendarfeed.navigate();
			return false;			
        });
        
        $('#prevevents').click(function(){
			if($.fn.calendarfeed.getTopLimit()  <= 0 ) {
				return false;
			}
  			$.fn.calendarfeed.setBtmLimit(-1*$.fn.calendarfeed.perpage);
			$.fn.calendarfeed.navigate();  
			return false;	    
		});
	}

	$.fn.calendarfeed.navi.bak = function () {
				
		$('#gcalwrapper').after($('<a/>').attr({href:'#',id:'nextevents'}).html('mehr &raquo;'));
		$('#gcalwrapper').after($('<a/>').attr({href:'#',id:'prevevents'}).html('&laquo; zurueck'));	
		
	    $('#nextevents').click(function(){
			
			m = $('#gcal_month').val();
			m++;
			if (m > 11) {
				m = 0;
				y = $('#gcal_year').val();	
				y++;		
				$('#gcal_year').val(y);
			}
			$('#gcal_month').val(m);	
			$('#innercalendarfeed').css("margin-top",0);
			cur = get_cur();	
			nxt = get_nxt();				
			$.fn.calendarfeed.loadStuff(cur,nxt);
			return false;			
        });
        
        $('#prevevents').click(function(){
        
  			m = $('#gcal_month').val();
			m--;
			if (m < 0) {
				m = 11;
				y = $('#gcal_year').val();
				y--;
				$('#gcal_year').val(y);
			}
			$('#gcal_month').val(m);	
			$('#innercalendarfeed').css("margin-top",0);
			cur = get_cur();	
			nxt = get_nxt();				
			$.fn.calendarfeed.loadStuff(cur,nxt);		
			return false;
        });
	}
	
	function get_cur() {
			y = $("#gcal_year option:selected").text();
			m = $("#gcal_month option:selected").text();
			cur = y + "-" + m + '-01';
			return cur;
	}
	
	function get_nxt() {
			y = $("#gcal_year option:selected").text();
			m = $("#gcal_month option:selected").text();
			m++;
			if(m > 11) {
				m = 1;
				y++;
			}
			nxt = y + "-" + $.fn.calendarfeed.pad(m) + '-01';
			
			return nxt;
	}	

	
	$('#gcal').calendarfeed();
});


