﻿$(document).ready(function() {

    $('.star').click(function() {
        //Sternenbilder ändern
        var id_star = $(this).attr("id").substr(4);
        var id_recipe = $(this).parents("span").attr("id").substr(5);
        if ($.cookie('rezept' + id_recipe) == null) {
            var zahl = parseInt(id_star);
            setStars($(this).parents("span"), zahl);

            //Mail senden
            var dataSend = { "wertung": id_star, "rezept": id_recipe };
            dataSend = JSON.stringify(dataSend);

            $.ajax({
                type: "POST",
                url: "/doughboy/services/ajaxMethods.aspx/SendResult",
                data: dataSend,
                cache: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: function() {
                },
                success: function() {
                },
                fail: function() {
                }
            });
            //Cookies setzen
            $.cookie('rezept' + id_recipe, id_star, { expires: 1 });
        }
        else
            alert('Pro Tag und pro Rezept ist nur eine Bewertung möglich.');
    });

    $('.star').hover(function() {
        resetstars($(this));
        var id_star = $(this).attr("id").substr(4);
        var zahl = parseInt(id_star);
        while (zahl >= 1) {
            $(this).parents("span").find("#star" + zahl).attr('old', $(this).parents("span").find("#star" + zahl).attr('src'));
            $(this).parents("span").find("#star" + zahl).attr('src', '/images/star_h.png');
            zahl = zahl - 1;
        }
    }, function() {
        resetstars($(this));
    });

    $.each($('.spanstars'), function(i, obj) {
        if ($.cookie('rezept' + obj.id.substr(5)) != null) {
            setStars($(this), $.cookie('rezept' + obj.id.substr(5)));
        }
    });
});

function setStars(obj, zahl) {
    while (zahl >= 1) {
        obj.find("#star" + zahl).attr('old', '/images/star_a.png');
        obj.find("#star" + zahl).attr('src', '/images/star_a.png');
        zahl = zahl - 1;
    }
}

function resetstars(obj) {
    var zahl = 5;
    while (zahl >= 1) {
        obj.parents("span").find("#star" + zahl).attr('src', obj.parents("span").find("#star" + zahl).attr('old'));
        zahl = zahl - 1;
    }
}
