$(document).ready(function(){
    /* This code is executed after the DOM has been completely loaded */
    
	
	// --------------------- Cycle Plugin -------------------------------------
	
	
	$('#cyclePlugin').cycle({ 
    	fx: 'scrollHorz',						// name of transition effect (or comma separated names, ex: fade,scrollUp,shuffle)
		speed:    300, 							// speed of the transition (any valid fx speed value)
    	timeout:  8000, 						// milliseconds between slide transitions (0 to disable auto advance)
		// easing:			'easeinout',
		next:			'#cyclenext',			// selector for element to use as click trigger for next slide
		prev:			'#cycleprev',			// selector for element to use as click trigger for previous slide
		prevNextEvent:	'click.cycle',			// event which drives the manual transition to the previous or next slide
		sync:			1,						// true if in/out transitions should occur simultaneously
		// random:			1,						// true for random, false for sequence (not applicable to shuffle fx)
		pause:			1,						// true to enable "pause on hover"
	    cleartype:		1						// enable cleartype corrections 
	}); 
	
	// ------------------------------------------------------------------------
    
    // load post-it positions from the cookies
    
    $("div .note").each(function(){
        var PostIt_id = $(this).children(".data").html();
        var cookieName = "PostIt_" + PostIt_id;
        var cookieString = $.cookie(cookieName);
        if ($.cookie(cookieName) != null) {
            $(this).attr('style', cookieString);
        }
        
    });
	    
    $('#bg_atelier2').click(function(){
        $("body").css("background-image", "url(BgImages/Atelier2_1920x1080.jpg)");
        Hintergrundbild = "BgImages/Atelier2_1920x1080.jpg";
    });
        
    // Expand Panel
    $("#open").click(function(){
        $("#addButton").hide(); 
        $("div#panel").slideDown("slow");
    });
    
    // Collapse Panel
    $("#close").click(function(){
        $("div#panel").slideUp("slow", function(){
            $("#addButton").show();
        });
    });
    
    // Switch buttons from "Log In" to "Close Panel" on click
    $("#toggle a").click(function(){
        $("#toggle a").toggle();
    });
    
    // --------------------------- Cufon Replace Settings -----------------------------------
    // Cufon Settings
    Cufon.set('fontFamily', 'Anivers');
    Cufon.set('hover', 'true');
    Cufon.replace('h1');
	Cufon.replace('h2');
	Cufon.replace('h4');
    /* Cufon.replace('.tab ul.login li a'); */
    
    Cufon.set('fontFamily', 'Delicious black');
    Cufon.set('hover', 'true');
	Cufon.replace('h3');
    // IE7,IE8 can't handle it!!!!
    /* Cufon.replace('.switch li a'); */
    
	 // --------------------------- ImageBoxes -----------------------------------
    //Full Caption Sliding (Hidden to Visible)
    $('.imageBox').hover(function(){
        $(".boxcaption", this).stop().animate({
            top: '60px'
        }, {
            queue: false,
            duration: 160
        });
    }, function(){
        $(".boxcaption", this).stop().animate({
            top: '128px'
        }, {
            queue: false,
            duration: 160
        });
    });
    
    
    which = $.cookie('Switch');
    
    switch (which) {
    
        case "Alle":
        case null:
            // kein Cookie oder "Alle",
            // dann Tab "alle" aktiv setzen
            $('#Alle').addClass("active");
            $('#Werk,#Auftragsarbeiten,#Aktuelles').removeClass("active");
			$('#mainTitle .Werk, #mainTitle .Auftragsarbeiten, #mainTitle .Aktuelles').hide();
        	$('#mainTitle .Alle').show();
            $('.imageBox img').show();
            $('.boxcaption').show();
			$('#mainLinks a.Werk').parent('li').next('.sep').show();
			$('#mainLinks a.Werk').parent('li').show();
			$('#mainLinks a.Auftragsarbeiten').parent('li').next('.sep').show();
			$('#mainLinks a.Auftragsarbeiten').parent('li').show();
			// imageBoxen, mainLinks einblenden
			$('#mainImageboxes .imageBox').customFadeIn("normal");
			$('#mainLinks').customFadeIn("normal");
			// Post-it ausblenden
			$('.note').customFadeOut("normal");
            which = 'Alle';
            $.cookie("Switch", which);
            break;
            
        case "Werk":
            $('#Werk').addClass("active");
            $('#Alle,#Auftragsarbeiten,#Aktuelles').removeClass("active");
			$('#mainTitle .Alle, #mainTitle .Auftragsarbeiten, #mainTitle .Aktuelles').hide();
        	$('#mainTitle .Werk').show();
            $('.imageBox.Auftragsarbeiten img').customFadeTo("normal", 0.3);
            $('.imageBox.Werk img').customFadeTo("normal", 1);
			$('.imageBox.Auftragsarbeiten .boxcaption').hide();
        	$('.imageBox.Werk .boxcaption').show();
			$('#mainLinks a.Werk').parent('li').next('.sep').show();
			$('#mainLinks a.Werk').parent('li').show();
			$('#mainLinks a.Auftragsarbeiten').parent('li').next('.sep').hide();
			$('#mainLinks a.Auftragsarbeiten').parent('li').hide();
			// imageBoxen, mainLinks einblenden
			$('#mainImageboxes .imageBox').customFadeIn("normal");
			$('#mainLinks').customFadeIn("normal");
			// Post-it ausblenden
			$('.note').customFadeOut("normal");
            which = 'Werk';
            break;
            
        case "Auftragsarbeiten":
            $('#Auftragsarbeiten').addClass("active");
            $('#Alle,#Werk,#Aktuelles').removeClass("active");
			$('#mainTitle .Alle, #mainTitle .Werk, #mainTitle .Aktuelles').hide();
        	$('#mainTitle .Auftragsarbeiten').show();
            $('.imageBox.Werk img').customFadeTo("normal", 0.3);
            $('.imageBox.Auftragsarbeiten img').customFadeTo("normal", 1);
			$('.imageBox.Werk .boxcaption').hide();
			$('.imageBox.Auftragsarbeiten .boxcaption').show();
			$('#mainLinks a.Werk').parent('li').next('.sep').hide();
			$('#mainLinks a.Werk').parent('li').hide();
			$('#mainLinks a.Auftragsarbeiten').parent('li').next('.sep').show();
			$('#mainLinks a.Auftragsarbeiten').parent('li').show();
			// imageBoxen, mainLinks einblenden
			$('#mainImageboxes .imageBox').customFadeIn("normal");
			$('#mainLinks').customFadeIn("normal");
			// Post-it ausblenden
			$('.note').customFadeOut("normal");
			which = 'Auftragsarbeiten';
            break;
			
		case "Aktuelles":
			$('#Aktuelles').addClass("active");
			$('#Alle,#Werk,#Auftragsarbeiten').removeClass("active");
			$('#mainTitle .Alle, #mainTitle .Werk, #mainTitle .Auftragsarbeiten').hide();
        	$('#mainTitle .Aktuelles').show();
			// imageBoxen ausblenden
			$('#mainImageboxes .imageBox').customFadeOut("normal");
			// mainLinks ausblenden
			$('#mainLinks').customFadeOut("normal");
			// Post-it einblenden
			$('.note').show();
			PostIt_height = $.cookie('PostIt');
			// PostIt Cookie vorhanden? Nein:
    		if (PostIt_height == null) {
				// Div auf height = 100% setzen
				$('#mainImageboxes').height('100%');
				// Höhe des Divs #mainImageboxes auslesen
				mainImageboxesHeight = $('#mainImageboxes').height();
							
    		}  else // Ja: 
			{
				// Cookie: Div Höhe übergeben
				mainImageboxesHeight = PostIt_height;
				// Höhe des Divs #mainImageboxes setzen
				$('#mainImageboxes').height(mainImageboxesHeight);
			}
			// LinksAktuelles einblenden
			$('#LinksAktuelles').show();
			which = 'Aktuelles';
			break;
            
    }
    
    
    $('#Alle').click(function(){
        $('#Werk,#Auftragsarbeiten,#Aktuelles').removeClass("active");
        $('#mainTitle .Werk, #mainTitle .Auftragsarbeiten, #mainTitle .Aktuelles').hide();
        $('#mainTitle .Alle').show();
        $(this).addClass("active");
        $('.imageBox img').customFadeTo("normal", 1);
        $('.boxcaption').show();
		// show alle mainLinks
		$('#mainLinks a.Werk').parent('li').next('.sep').show();
		$('#mainLinks a.Werk').parent('li').show();
		$('#mainLinks a.Auftragsarbeiten').parent('li').next('.sep').show();
		$('#mainLinks a.Auftragsarbeiten').parent('li').show();
		// imageBoxen, mainLinks einblenden
		$('#mainImageboxes .imageBox').customFadeIn("normal");
		$('#mainLinks').customFadeIn("normal");
		// Post-it ausblenden
		$('.note').customFadeOut("normal");
        which = 'Alle';
        $.cookie("Switch", which);
    });
    
    $('#Werk').click(function(){
        $('#Alle,#Auftragsarbeiten,#Aktuelles').removeClass("active");
        $('#mainTitle .Alle, #mainTitle .Auftragsarbeiten, #mainTitle .Aktuelles').hide();
        $('#mainTitle .Werk').show();
        // Tab aktiv setzen
        $(this).addClass("active");
        // Imageboxen ein- und ausblenden
        $('.imageBox.Auftragsarbeiten .boxcaption').hide();
        $('.imageBox.Werk .boxcaption').show();
        // IE troubles with fade layer with an image on it. Then just fade image
        $('.imageBox.Auftragsarbeiten img').customFadeTo("normal", 0.3);
        $('.imageBox.Werk img').customFadeTo("normal", 1);
		// show only Werk mainLInks
		$('#mainLinks a.Werk').parent('li').next('.sep').show();
		$('#mainLinks a.Werk').parent('li').show();
		$('#mainLinks a.Auftragsarbeiten').parent('li').next('.sep').hide();
		$('#mainLinks a.Auftragsarbeiten').parent('li').hide();
		// imageBoxen, mainLinks einblenden
		$('#mainImageboxes .imageBox').customFadeIn("normal");
		$('#mainLinks').customFadeIn("normal");
		// Post-it ausblenden
		$('.note').customFadeOut("normal");
        which = 'Werk';
        $.cookie("Switch", which);
    });
    
    $('#Auftragsarbeiten').click(function(){
        $('#Alle,#Werk,#Aktuelles').removeClass("active");
        $('#mainTitle .Alle, #mainTitle .Werk, #mainTitle .Aktuelles').hide();
        $('#mainTitle .Auftragsarbeiten').show();
        $(this).addClass("active");
        $('.imageBox.Werk .boxcaption').hide();
        $('.imageBox.Auftragsarbeiten .boxcaption').show();
        $('.imageBox.Werk img').customFadeTo("normal", 0.3);
        $('.imageBox.Auftragsarbeiten img').customFadeTo("normal", 1);
		// show only Auftragsarbeiten mainLInks
		$('#mainLinks a.Werk').parent('li').next('.sep').hide();
		$('#mainLinks a.Werk').parent('li').hide();
		$('#mainLinks a.Auftragsarbeiten').parent('li').next('.sep').show();
		$('#mainLinks a.Auftragsarbeiten').parent('li').show();
		// imageBoxen, mainLinks einblenden
		$('#mainImageboxes .imageBox').customFadeIn("normal");
		$('#mainLinks').customFadeIn("normal");
		// Post-it ausblenden
		$('.note').customFadeOut("normal");
        which = 'Auftragsarbeiten';
        $.cookie("Switch", which);
    });
	
	$('#Aktuelles').click(function(){
		$('#Alle,#Werk, #Auftragsarbeiten').removeClass("active");
		$('#mainTitle .Alle, #mainTitle .Werk, #mainTitle .Auftragsarbeiten').hide();
        $('#mainTitle .Aktuelles').show();
		$(this).addClass("active");
		mainImageboxesHeight = $('#mainImageboxes').height();
		$.cookie("PostIt", mainImageboxesHeight);
		// Post-it einblenden
		$('.note').customFadeIn("normal");
		// imageBoxen ausblenden
		$('#mainImageboxes .imageBox').customFadeOut("normal");
		// Höhe des Divs #mainImageboxes setzen
		$('#mainImageboxes').height(mainImageboxesHeight);
		// mainLinks ausblenden
		$('#mainLinks').customFadeOut("normal");
		// LinksAktuelles einblenden
		$('#LinksAktuelles').show();
		which = 'Aktuelles';
        $.cookie("Switch", which);
    });	 
    
    $("a#LinksWerk, a#LinksAuftragsarbeiten, a#LinksImpressum, a#LinksLinks, a#LinkPost-it, a#LinksAktuelles").fancybox({
        'zoomSpeedIn': 600,
        'zoomSpeedOut': 500,
		'padding': 15,
        'easingIn': 'easeOutBack',
        'easingOut': 'easeInBack',
        'hideOnContentClick': false
    });
    
    
    $("#fancy_guest").fancybox({
        'zoomSpeedIn': 600,
        'zoomSpeedOut': 500,
        'easingIn': 'easeOutBack',
        'easingOut': 'easeInBack',
        'hideOnContentClick': false,
        'padding': 15,
        'frameWidth': 600,
        'frameHeight': 400
    });
    
    
    /* The delete button: */
    $('.deleteMe').live("click", function(){
        var selfobject = $(this);
        Sexy.confirm('Post-it Notiz wirklich l&ouml;schen?', {
            textBoxBtnOk: 'Ja',
            textBoxBtnCancel: 'Nein',
            onComplete: function(returnvalue){
                if (returnvalue) {
                    $.ajax({
                        type: "GET",
                        async: false,
                        url: "ajax/delete.php",
                        data: ({
                            getid: $(selfobject).siblings(".data").html()
                        }),
                        success: function(data){
                            /* nur ausführen, wenn das löschen in der DB erfolgreich ! (nur wenn eingeloggt) */
                            if (data == "success") {
                                $(selfobject).parent("div.note").fadeOut("slow", function(){
                                    $(this).remove();
                                });
                            }
                            else {
                                Sexy.alert(data);
                            }
                        }
                    });
                }
            }
        });
    });
    
    
    var tmp;
    
    $('.note').each(function(){
        /* Finding the biggest z-index value of the notes */
        tmp = $(this).css('z-index');
        if (tmp > zIndex) 
            zIndex = tmp;
    });
    
    /* Configuring the fancybox plugin for the "Add a note" button: */
    
    $("#addButton").fancybox({
        'zoomSpeedIn': 600,
        'zoomSpeedOut': 500,
        'easingIn': 'easeOutBack',
        'easingOut': 'easeInBack',
        'hideOnContentClick': false,
        'padding': 15,
        'onComplete': function(){
            $('#note-verfallsdatum').datepicker(); /* Callback, when fancybox is completed */
        }
    });
    
    
    $.datepicker.regional['de'] = {
        clearText: 'löschen',
        clearStatus: 'aktuelles Datum löschen',
        closeText: 'schliessen',
        closeStatus: 'ohne Änderungen schließen',
        prevText: '<zurück',
        prevStatus: 'letzten Monat zeigen',
        nextText: 'Vor>',
        nextStatus: 'nächsten Monat zeigen',
        currentText: 'heute',
        currentStatus: '',
        monthNames: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
        monthNamesShort: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
        monthStatus: 'anderen Monat anzeigen',
        yearStatus: 'anderes Jahr anzeigen',
        weekHeader: 'Wo',
        weekStatus: 'Woche des Monats',
        dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
        dayNamesShort: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
        dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
        dayStatus: 'Setze DD als ersten Wochentag',
        dateStatus: 'Wähle D, M d',
        dateFormat: 'dd.mm.yy',
        firstDay: 1,
        minDate: new Date(),
        showOn: 'both',
        buttonImageOnly: true,
        buttonImage: 'images/calendar.gif',
        buttonText: 'Kalender',
        initStatus: 'Wähle ein Datum',
        clickInput: true,
        isRTL: false
    };
    
    $.datepicker.setDefaults($.datepicker.regional['de']);
    
    
    
    /* Listening for keyup events on fields of the "Add a note" form: */
    $('.pr-body').live('keyup', function(e){
    
        if (!this.preview) 
            this.preview = $('#fancybox-inner .note');
        /* Setting the text of the preview to the contents of the input field, and stripping all the HTML tags: */
        this.preview.find($(this).attr('class').replace('pr-', '.')).html($(this).val().replace(/<[^>]+>/ig, ''));
    });
    
    /* Changing the color of the preview note: */
    $('.color').live('click', function(){
        $('#fancybox-inner .note').removeClass('yellow green blue').addClass($(this).attr('class').replace('color', ''));
    });
    
    /* The submit button: */
    $('#note-submit').live('click', function(e){
    
        if ($('.pr-body').val().length < 4) {
            Sexy.alert("Die Notiz ist zu kurz!");
            return false;
        }
        
        if ($('.pr-verfallsdatum').val().length < 6) {
            Sexy.alert("Verfallsdatum der Post-it Notiz angeben!");
            return false;
        }
        
        
        $(this).replaceWith('<img src="img/ajax_load.gif" style="margin:30px auto;display:block" />');
        
        var data = {
            'zindex': ++zIndex,
            'body': $('.pr-body').val(),
            'author': $('.pr-author').val(),
            'verfallsdatum': $('.pr-verfallsdatum').val(),
            'color': $.trim($('#fancybox-inner .note').attr('class').replace('note', ''))
        };
        
        /* Sending an AJAX POST request: */
        $.post('ajax/post.php', data, function(msg){
            /* parseint -> Wandelt eine zu übergebende Zeichenkette in eine Ganzzahl um und gibt diese als Ergebnis zurück. Sinnvoll, 
             um z.B. Anwendereingaben in Zahlen umzuwandeln, mit denen man anschließend rechnen kann. */
            if (parseInt(msg)) {
                /* msg contains the ID of the note, assigned by MySQL's auto increment: */
                
                var tmp = $('#fancybox-inner .note').clone();
                
                tmp.find('span.data').text(msg).end().css({
                    'z-index': zIndex,
                    top: 0,
                    left: 0
                });
                
                tmp.find('span.data').parent().prepend('<div class="deleteMe"></div>'); /* Delete-Button einfügen */
                tmp.find('.timestamp').css('cursor', 'pointer'); /* Cursor Style ändern */
                tmp.find('.timestamp').after('<div class="verfallsdt" style="display: none;">' + $('.pr-verfallsdatum').val() + '</div>'); /* verfallsdatum toggle einfügen */
                tmp.find('span.data').parent().css('cursor', 'move'); /* Cursor Style ändern */
                tmp.find('span.data').parent().removeAttr("id");
                
                tmp.appendTo($('#mainImageboxes'));
                make_draggable(tmp)
            }
            else {
                Sexy.alert(msg);
            } /* end if */
            $.fancybox.close();
            
            
        }); /* End AJAX POST */
        e.preventDefault();
    }); /* End submit button */
    $('.note-form').live('submit', function(e){
        e.preventDefault();
    });
    
}); /* End ready */

var zIndex = 0;

function make_draggable(elements_1){
	/* Elements is a jquery object: */
	elements_1.draggable({
		containment: 'parent',
		start: function(e, ui){
			ui.helper.css('z-index', ++zIndex);
		},
		stop: function(e, ui){
		
			/* Sending the z-index and positon of the note to update_position.php via AJAX GET: */
			
			$.get('ajax/update_position.php', {
				x: ui.position.left,
				y: ui.position.top,
				z: zIndex,
				id: parseInt(ui.helper.find('span.data').html())
			});
		}
	});
};


function make_draggable_qookie(elements_2){
	elements_2.draggable({
		containment: 'parent',
		start: function(e, ui){
			ui.helper.css('z-index', ++zIndex);
		},
		stop: function(e, ui){
			/* Save the z-index and positon of the note to Cookie: id */
			var cookieName = "PostIt_" + parseInt(ui.helper.find('span.data').html());
			var cookieString = "left: " + ui.position.left + "px; top: " + ui.position.top + "px; z-index: " + zIndex + ";";
			$.cookie(cookieName, cookieString, {
				expires: 100,
				path: '/'
			});
		}
	});
};


/* Extrawurst für IE-Browser, And unfortunately jquery has no way of animating transparency for IE8 yet!!!!  */
(function($){
	$.fn.customFadeIn = function(speed, callback){
		$(this).fadeIn(speed, function(){
			if (!$.support.opacity) 
				$(this).get(0).style.removeAttribute('filter');
			if (callback != undefined) 
				callback();
		});
	};
	$.fn.customFadeOut = function(speed, callback){
		$(this).fadeOut(speed, function(){
			if (!$.support.opacity) 
				$(this).get(0).style.removeAttribute('filter');
			if (callback != undefined) 
				callback();
		});
	};
	$.fn.customFadeTo = function(speed, to, callback){
		return this.animate({
			opacity: to
		}, speed, function(){
			if (to == 1 && jQuery.browser.msie) 
				this.style.removeAttribute('filter');
			if (jQuery.isFunction(callback)) 
				callback();
		});
	};
})(jQuery);


