 $(document).ready(function() {

/* ----------------------------------- */
/* BASIC FUNCTIONS */
/* ----------------------------------- */

    function sendToFlow(data,target,action) {

        var action;

        $.ajax({
            url: "http://www.snuffer.ch/schnupf/flow.php",
            data: data,
            method: "GET",
            success: function(html){

            if(action == "prepend_latest_comment") {


                $(target).prepend(html);

                $("div[class^='kommentar']:first").hide();
                $("div[class^='kommentar']:hidden").toggle("blind",{},800);


            } else if(action == "html") {

            $(target).html(html);
            $(target).fadeTo(0.5,500);
            $(target).fadeTo(1,1000);

            } else if(action == "justsend_thenreload") {
				window.location.reload();
                return true;
            } else if(action == "justsend") {
                return true;
            }

            }});



        }

// Default Functions

		function nl2br (str, is_xhtml) {
		    // Converts newlines to HTML line breaks  
		    // 
		    // version: 911.1619
		    // discuss at: http://phpjs.org/functions/nl2br    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		    // +   improved by: Philip Peterson
		    // +   improved by: Onno Marsman
		    // +   improved by: Atli Þór
		    // +   bugfixed by: Onno Marsman    // +      input by: Brett Zamir (http://brett-zamir.me)
		    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		    // +   improved by: Brett Zamir (http://brett-zamir.me)
		    // +   improved by: Maximusya
		    // *     example 1: nl2br('Kevin\nvan\nZonneveld');    // *     returns 1: 'Kevin\nvan\nZonneveld'
		    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
		    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
		    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
		    // *     returns 3: '\nOne\nTwo\n\nThree\n'    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>';
		 	breakTag = "<br />";
		    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
		}
	
	    function SuchenUndErsetzen(QuellText, SuchText, ErsatzText)
        {   // Erstellt von Ralf Pfeifer
            // Fehlerpruefung
            if ((QuellText == null) || (SuchText == null))           { return null; }
            if ((QuellText.length == 0) || (SuchText.length == 0))   { return QuellText; }

            // Kein ErsatzText ?
            if ((ErsatzText == null) || (ErsatzText.length == 0))    { ErsatzText = ""; }

            var LaengeSuchText = SuchText.length;
            var LaengeErsatzText = ErsatzText.length;
            var Pos = QuellText.indexOf(SuchText, 0);

            while (Pos >= 0)
            {
                QuellText = QuellText.substring(0, Pos) + ErsatzText + QuellText.substring(Pos + LaengeSuchText);
                Pos = QuellText.indexOf(SuchText, Pos + LaengeErsatzText);
            }
            return QuellText;
        }
	
		function isURL(s){
			var regexp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
			return regexp.test(s);
		} 
		
		function isEmail(email){
		    var RegExp = /^((([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/;
		    if(RegExp.test(email)){
		        return true;
		    }else{
		        return false;
		    }
		} 
	
		function countElements(selector) {
			i = 0;
			$(selector).each(function() {
				i++;
			});
			return i;
		}

		function isInt (i) {
				return (i % 1) == 0;
		}

		function urlize(string) {
			val = jQuery.trim(string);
			val = encodeURI(val);
			val = SuchenUndErsetzen(val,"&","[::]");
			return val; 
		}

		function getIdByName(name) {
			name = name.split("_");
			anzahl = name.length;
			anzahl--;
			return name[anzahl];
		}
	
		function time() {
		return Math.round(new Date().getTime()/1000);
	}

		function removeEggli(str) {
			strTmp = str.substr(1,str.length);
			return strTmp;
		}

/* ----------------------------------- */

    // Klick auf Kleineselement

    $(".smallblock_snuff").click(function() {

     $(this).effect("bounce");
     id = $(this).attr("id");
     url = $("#link-"+id).attr("href");
     window.location.href = url;
      });

    // über rating fahren

    var opa = 0.5;

    $("#schnupfbewertung_redaktion .snuffdetail_bewertung").fadeTo("slow", opa);
    $("#schnupfbewertung_redaktion .snuffdetail_bewertung:not(:last)").hover(function() { $(this).stop().fadeTo("slow", 0.9); } , function() { $(this).stop().fadeTo("slow",opa);} );
    $("#schnupfbewertung_redaktion .snuffdetail_bewertung:last").fadeTo("slow",1);

    // User Vote Animation

    $(".snuffdetail_uservote img").fadeTo("slow", 0.5);
    $(".snuffdetail_uservote img").hover(
    // do first.
    function() {
        $(this).stop().animate(
                { top: "0px", opacity: "1" }
            , 300);
        }
    ,
    // do then
    function() {
        $(this).stop().animate(
                { top: "10px", opacity: "0.5" }
            , 100);
        }
        );

    $(".snuffdetail_uservote img").click(
        function() {
        var clicked = $(this).attr("id");
        clicked = clicked.split("-");
        $(this).fadeOut(500);
        $(this).fadeIn(1000);
        datastring = "v="+clicked[1]+"&id="+clicked[0]+"&action=updateUserVoting";
        sendToFlow(datastring,"#snuffdetails_uservote_result","html");
		$("#snuffdetails_uservote_result").stop().effect("pulsate");
        }
    );

    // *****************
    // Kommentar senden
    // *****************

    var formSendOptions = {
         target:        '#sendcommentarea',   // target element(s) to be updated with server response
         beforeSubmit:  sendRequest, // pre-submit callback
         success: loadNewEntry
    }

    function sendRequest() {

        $("#CommentFormDiv").slideUp(300);

        name = $("#name").val();
        titel = $("#titel").val();
        text = $("#text").val();

        name = jQuery.trim(name);
        titel = jQuery.trim(titel);
        text = jQuery.trim(text);

        if(name != "" && titel != "" && text != "") {
            return true;
        } else {
            alert("Es ist en Fehler aufgetreten. Bitte fuelle jedes Feld aus.");
            $("#CommentFormDiv").slideDown(300);
            $("#CommentFormDiv").effect("pulsate");
            return false;
        }


    }

    function loadNewEntry() {
        $("#CommentFormDiv").resetForm();
        snuffid = $("#CommentForm input[id='id']").val();
        sendToFlow("action=getLastComment&id="+snuffid,"#ShowAllComments","prepend_latest_comment");
    }

    $("#CommentForm").ajaxForm(formSendOptions);


    // *****************
    // Kommentar l�schen
    // *****************

    $("img[id^='deletecomment']").click(function () {
        commentId = $(this).attr("id");
        commentId = commentId.split("-");
        commentId = commentId[1];

        target = "#CommentId-"+commentId;
        $(target).slideUp(300,function() {

        if(confirm("Moechtest du deinen Kommentar wirklich entfernen?")) {
        data = "action=deleteComment&id="+commentId;
        sendToFlow(data,target,"justsend");

        } else { $(target).slideDown(300); } });

    });


    //*******
    // Kommentar toggle
    //*******

    $("#leaveAComment").click(function() {
        $(this).slideUp(300);
        $("#CommentFormDiv").slideDown(300);
        return false;
    });

    $("#closeCommentForm").click(function() {
        $("#CommentFormDiv").slideUp(300);
        $("#leaveAComment").slideDown(300);
        return false;
    });


    //*******
    // Kommentar Karma Update
    //*******

    $("img[id^='thumbup']").click( function() {

        $(this).effect("pulsate");

        commentId = $(this).attr("id");
        commentId = commentId.split("-");
        commentId = commentId[1];

        data = "action=updateCommentKarma&id="+commentId+"&operation=1";
        target = "#karma-"+commentId;
        action = "html";

        sendToFlow(data,target,action);

        return false;

    });


    $("img[id^='thumbdown']").click( function() {

        $(this).effect("pulsate");

        commentId = $(this).attr("id");
        commentId = commentId.split("-");
        commentId = commentId[1];

        data = "action=updateCommentKarma&id="+commentId+"&operation=-1";
        target = "#karma-"+commentId;
        action = "html";

        sendToFlow(data,target,action);

        return false;

    });
	
    //*******
    // Spruch Karma Update
    //*******

    $("img[id^='sthumbup']").click( function() {

        $(this).effect("pulsate");

        commentId = $(this).attr("id");
        commentId = commentId.split("-");
        commentId = commentId[1];

        data = "action=updateSpruchKarma&id="+commentId+"&operation=1";
        target = "#karma-"+commentId;
        action = "html";

        sendToFlow(data,target,action);

        return false;

    });


    $("img[id^='sthumbdown']").click( function() {

        $(this).effect("pulsate");

        commentId = $(this).attr("id");
        commentId = commentId.split("-");
        commentId = commentId[1];

        data = "action=updateSpruchKarma&id="+commentId+"&operation=-1";
        target = "#karma-"+commentId;
        action = "html";

        sendToFlow(data,target,action);

        return false;

    });

    // Slider

    $("#BilderSlide").easySlider({
        auto: true,
        continuous: true,
        controlsShow: false,
        speed: 800,
        pause: 6000
    });

	// Explorer
	
	$("#explorer").accordion({
			header: "h3",
			alwaysOpen: false,
			clearStyle: true
		});


	// Sprueche Archiv Navigation
	
		// Variablen setzen

//	var sa_maxperpage = $("#DefinePerpageDiv").text();
//	var sa_maxperpage = sa_maxperpage - 1;			
	var sa_maxperpage = 0;
	var currfirst = 0;
	var currlast = sa_maxperpage;
	var sa_entries = $("#DefineEntries").text();
	var lastnote = "123";
	var firstnote = "123";
	var steps = 1;
	//var define_selector = "div[id^='SpruchId']";
	var define_selector = ".pagebreak";
	var sa_navikeys = "off";
	
	if(sa_entries > 0) {
		var sa_navikeys = "on";
	}

	$("#Prevpage").fadeTo(100,0.3); 

	if (sa_entries-1 <= sa_maxperpage) {
		$("#Nextpage").fadeTo(100, 0.3);
	}


	$(define_selector+":gt("+ sa_maxperpage +")").hide();


	function jumpToNextPage() {

		if (currlast+1 < sa_entries) {

			currfirst = currfirst+steps;
			currlast = currlast+steps;
		
			$(define_selector+":lt(" + currfirst + ")").slideUp(500);
			$(define_selector+":eq(" + currlast + ")").slideDown(500);
			
		} 
		else {
			if (lastnote != "stop") {
				lastnote = "stop";
					$("#Nextpage").after("<div style='margin: auto; text-align: center; margin: 5px;'><img src='http://www.snuffer.ch/schnupf/secure/img/ic/ic_letzteseite.png' alt='Seitenschluss' /></div>").next().hide().slideDown(100,function() { $(this).effect("shake",{ times: 1, distance: 5},"300",function()  { lastnote = "0"; $(this).slideUp(100); })});
//					$("#ToMouse").html("<div>Letztes Element (" + currlast + ")</div>").hide().slideDown(100,function() { $(this).effect("shake",function() {$(this).fadeOut(100,function() { lastnote = "0"; })});
			}
		}
		
		if(currfirst >= 1) {
			$("#Prevpage").fadeTo(100,1); 
		}
	
		if(currlast+1 == sa_entries) {
			$("#Nextpage").fadeTo(100,0.3); 
		} 
	
		
	}

	function jumpToPrevPage() {
		
		if (currfirst > 0) {

			currfirst = currfirst-steps;
			currlast = currlast-steps;
		
			$(define_selector+":eq(" + currfirst + ")").slideDown(500);
			$(define_selector+":gt(" + currlast + ")").slideUp(500);
			
		}  
		else {
			if (firstnote != "stop") {
				firstnote = "stop";
				
					$("#Nextpage").after("<div style='margin: auto; text-align: center; margin: 5px;'><img src='http://www.snuffer.ch/schnupf/secure/img/ic/ic_seitenanfang.png' alt='Seitenanfang' /></div>").next().hide().slideDown(100,function() { $(this).effect("shake",{ times: 1, distance: 5},"300",function()  { firstnote = "0"; $(this).slideUp(100); })});
//					$("#ToMouse").html("<div>Erstes Element (" + currfirst + ")</div>").hide().slideDown(100,function() { $(this).fadeOut(3000,function() { firstnote = "0"; })});
					
			}
		}
		
		if(currlast < sa_entries && sa_entries-1 > sa_maxperpage) {
			$("#Nextpage").fadeTo(100,1); 
		}
		
		if(currfirst == 0) {
			$("#Prevpage").fadeTo(100,0.3); 
		}
	}


	$("#Nextpage").click(function(){
		if (sa_navikeys == "on") {
			jumpToNextPage();
		}
	});
	$("#Prevpage").click(function(){
		if (sa_navikeys == "on") {
			jumpToPrevPage();
		}
	});


	// Navigation mit Tastatur


		$(document).keyup(function(event){

		if (sa_navikeys == "on") {
		
		if (event.keyCode == 37) {
				jumpToPrevPage();
			}
			else 
				if (event.keyCode == 38) {
					jumpToPrevPage();
				}
				else 
					if (event.keyCode == 39) {
						jumpToNextPage();
					}
					else 
						if (event.keyCode == 40) {
							jumpToNextPage();
						}
					
		}
					
		});
		
	 
	 // Suchen in Sprüche Archiv
	 
	 $("#SucheSpruch").focus(function() { sa_navikeys = "off"; $("#Nextpage").fadeTo(100,0.3);  $("#Prevpage").fadeTo(100,0.3);  })
	 $("#SucheSpruch").blur(function() { if ($(this).val() == "") {
	 	sa_navikeys = "on";
		
		if (sa_entries - 1 > sa_maxperpage) {
			$("#Nextpage").fadeTo(100, 1);
		}
		 $("#Prevpage").fadeTo(100,0.3);  
	 	} })
	 
	 $("#SucheSpruch").keyup( function() {
	 	
		suchbegriff = $(this).val();
		suchbegriff = suchbegriff.toLowerCase();
		
		$(define_selector).show();
		
		if(suchbegriff != "") {
		// Hide ALL
		
		if ($.browser.mozilla) {
			$("div[id^='SpruchId']:visible").not($(this + ":contains('" + suchbegriff + "')")).fadeOut(100);
			$("div[id^='SpruchId']:contains('" + suchbegriff + "')").not($(this + ":visible")).fadeIn(500);
		} else {
			$("div[id^='SpruchId']:visible").hide();
			$("div[id^='SpruchId']:contains('" + suchbegriff + "')").show();
		}
	
//		$("#SucheBegriff").html("<div id='SuchergebnisText'>Suchergebnisse zu <b>"+suchbegriff+"</b></div>");
		$("#ToMouse").html("<div id='SuchergebnisText'>Suchergebnisse zu <b>"+suchbegriff+"</b></div>");
			
		} else {

			$("#SuchergebnisText").remove();
			$(define_selector).show();
			$("div[id^='SpruchId']:hidden").show();
			$(define_selector+":gt("+ sa_maxperpage +")").hide();

			currfirst = 0;
			currlast = sa_maxperpage;
									
		}		
		
								
	 });
	 
	 
	 $("body").append("<div id='ToMouse' style='position: absolute; top: 0px; left: 0px;'></div>");
	 
	 $(document).mousemove( function(e) {
		

		$("#ToMouse").css(
			{
	            top: (e.pageY + 15) + "px",
	            left: (e.pageX + 15) + "px"
			}
		);		
				
	 });
	
	// Sprucharchiv freischalten
	
	$("#link_set_free").click(
	
		function() {
			data = "action=setspruechefree&input=JA";
			target = "nirvana";
			action = "justsend_thenreload";
			sendToFlow(data,target,action); 
			
		}	
	
	);
	
	// Spruch einreichen
	
	function validateSpruchSenden(){
	
		// FOrmular Validieren
		
		$("#SendSpruch").slideUp(100);
		
		name = $("#se_name").val();
		spruch = $("#se_spruch").val();
		
		name = jQuery.trim(name);
		spruch = jQuery.trim(spruch);
		
		if (name != "" && spruch != "") {
			return true;
		}
		else {
			alert("Es ist ein Fehler aufgetreten. Bitte ueberpruefe deine Eingabe....");
			$("#SendSpruch").slideDown(100);
			return false;
			}
	}
	
	
	function giveSuccessMessageSpruch() {

		
	}
	
	
	 var formSendOptionsSpruch = {
         target:        '.main_entry:first',   // target element(s) to be updated with server response
		 beforeSubmit:  validateSpruchSenden,
         success: giveSuccessMessageSpruch
    }

    $("#SendSpruch").ajaxForm(formSendOptionsSpruch);

	// Spruch freischalten - oder loeschen
	
	$("a[id^='Spruch-Freischalten-Link-']").click( function() {

		id = $(this).attr('id');
		id = id.replace(/Spruch-Freischalten-Link-/,"");
		
		sprache = $("#Spruch-Sprache-Id-"+id).val();
		data = "action=spruchfreischalten&id="+id+"&sprache="+sprache;
		target = "#AdminSpruchId-"+id;

		$(target).slideUp(300);
		sendToFlow(data,target,"html");
		$(target).slideDown(300);

		return false;
			
	});
	
		
	$("a[id^='Spruch-Loeschen-Link-']").click( function() {

		id = $(this).attr('id');
		id = id.replace(/Spruch-Loeschen-Link-/,"");
		
		data = "action=spruchloeschen&id="+id;
		target = "#AdminSpruchId-"+id;

		$(target).slideUp(300);
		sendToFlow(data,target,"html");
		$(target).slideDown(300);

		return false;
			
	});


	$("input[id^='NR_'],textarea[id^='NR_']").keyup(function() {
		value = $(this).val();
		value = nl2br(value);
			value2 = SuchenUndErsetzen(value,"<","&lt;");
			value2 = SuchenUndErsetzen(value2,">","&gt;");
			value2 = SuchenUndErsetzen(value2,"&lt;br /&gt;","<br />");
			value2 = SuchenUndErsetzen(value2,"[titel]","<h3>");
			value2 = SuchenUndErsetzen(value2,"[/titel]","</h3>");
			value2 = SuchenUndErsetzen(value2,"[textblock]","<p>");
			value2 = SuchenUndErsetzen(value2,"[/textblock]","</p>");
		id = $(this).attr('id');
		if(id == "NR_SnuffTitle") {
			$("#NRLive_Titel,#NRLive_Titel2").text(value);
		} else if(id == "NR_Slogan"){
			$("#NRLive_Slogan").text(value);
		} else if(id == "NR_Text") {
			$("#NRLive_Text").html(value2);
		}
	});

	$("select[id^='NR_']").change(function() {
		value = $(this+":selected").text();
		id = $(this).attr('id');
		if(id == "NR_Hersteller") {
			$("#NRLive_Hersteller").text(value);
		} 
	});

	// Star Rating JS
	
	$("img[id^='NRStar_']").hover(function() {
		getCurrentStar = getIdByName($(this).attr('id'));
		getAdditionalInfoInId = $(this).attr('id').split('_');
		getRatingCat = getAdditionalInfoInId[1];
		fullStar = $(this).attr('alt');
		halfStar = $(this).attr('rel');
		for(i = 1;i <= 10;i++) {
			if(getCurrentStar >= i) {
				src = fullStar;
			} else {
				src = halfStar;
			}
			$("#NRStar_"+getRatingCat+"_"+i).attr('src',src);
		}
	},function() {
		getAdditionalInfoInId = $(this).attr('id').split('_');
		getRatingCat = getAdditionalInfoInId[1];
		getCurrentStar = $("#NRVote_"+getRatingCat).val();
		fullStar = $(this).attr('alt');
		halfStar = $(this).attr('rel');
		for(i = 1;i <= 10;i++) {
			if(getCurrentStar >= i) {
				src = fullStar;
			} else {
				src = halfStar;
			}
			$("#NRStar_"+getRatingCat+"_"+i).attr('src',src);
		}
	}).click(function() {
		getAdditionalInfoInId = $(this).attr('id').split('_');
		getRatingCat = getAdditionalInfoInId[1];
		$("#NRVote_"+getRatingCat).val(getAdditionalInfoInId[2]);
		NR_LivePreviewRatings(getRatingCat,getAdditionalInfoInId[2]);
	}).dblclick(function() {
		getAdditionalInfoInId = $(this).attr('id').split('_');
		getRatingCat = getAdditionalInfoInId[1];
		$("#NRVote_"+getRatingCat).val(0);
		NR_LivePreviewRatings(getRatingCat,0);
	});

	function NR_LivePreviewRatings(which,rating) {
//		getCurrentStar = getIdByName($("#NRStar_"+which+"_"+rating).attr('id'));
//		getAdditionalInfoInId = $("#NRStar_"+which+"_"+rating).attr('id').split('_');
//		getRatingCat = getAdditionalInfoInId[1];
		fullStar = $("#NRStar_"+which+"_1").attr('alt');
		halfStar = $("#NRStar_"+which+"_1").attr('rel');
		for(i = 1;i <= 10;i++) {
			if(rating >= i) {
				src = fullStar;
			} else {
				src = halfStar;
			}
			$("#NRStarLive_"+which+"_"+i).attr('src',src);
		}
	}

	$("#SubmitNewRating").click(function() {
		
		Titel = urlize($("#NR_SnuffTitle").val());
		Hersteller = $("#NR_Hersteller").val();
		Slogan = urlize($("#NR_Slogan").val());
		Text = urlize($("#NR_Text").val());
		BGeschmack = $("#NRVote_Geschmack").val();
		BKonsistenz = $("#NRVote_Konsistenz").val();
		BCharakter = $("#NRVote_Charakter").val();
		BPreis = $("#NRVote_Preis").val();
		BGesamt = $("#NRVote_Gesamteindruck").val();
		action = "submitRating";
		
		data = "action="+action+"&Titel="+Titel+"&Hersteller="+Hersteller+"&Slogan="+Slogan+"&Text="+Text+"&BGeschmack="+BGeschmack+"&BKonsistenz="+BKonsistenz+"&BCharakter="+BCharakter+"&BPreis="+BPreis+"&BGesamteindruck="+BGesamt;
		error = 0;

		if(jQuery.trim(Titel) == "" || jQuery.trim(Hersteller) == "0" || jQuery.trim(Slogan) == "" || jQuery.trim(Text) == "") {
			error++;
		} 

		if(error == 0) {
			
	       $.ajax({
	            url: "http://www.snuffer.ch/schnupf/flow.php",
	            data: data,
	            method: "GET",
	            success: function(html){
					window.location.href = html;
				}
				});
		} else {
			
			alert("Bitte überprüfe ob du alle Angaben ausgefüllt hast. \nDie Anfrage konnte nicht gesendet werden.")
			
		}


		
		return false;
		
	});

	
	$(".FBLikeTop").fadeTo(500,0.75);


    // Schluss klammer
});
