﻿/// <reference path="jquery-1.4.1-vsdoc.js" />

/**
* Переключение вкладок
*
* @param {String} tab_wtap Закладки
* @param {String} tab_body Табы
* @param {Object} tab
*/



function switch_tab(tabWtap, tabBody, tab) {
    //Open tab
    var li = $(this).parent();
    $(tabWtap + ' li').removeClass('active');
    tab.addClass('active');

    var tabIndex = ($(tabWtap + ' li').index(tab));

    $(tabBody + ' div.tab').hide();
    $(tabBody + ' div.tab' + tabIndex).show();

    return tabIndex;
}

$(function () {
    // mainmenu hover
    $('#mainmenu ul li').hover(function () {
        $(this).addClass('hover');
    },
   function () {
       $(this).removeClass('hover');
   });

    // Tabs
    $('#top-recipes .tabs li a').click(function () {
        switch_tab('#top-recipes .tabs', '#top-recipes div.tab-content', $(this).parent());

        // Инициализируем карусели 2,3,4 во время переключения табов. Иначе не правильно считается ширина контейнера
        $("#trcarusel-1").jcarousel({
            buttonNextHTML: null,
            buttonPrevHTML: null
        });
        $("#trcarusel-2").jcarousel({
            buttonNextHTML: null,
            buttonPrevHTML: null
        });
        $("#trcarusel-3").jcarousel({
            buttonNextHTML: null,
            buttonPrevHTML: null
        });
        $("#trcarusel-last").jcarousel({
            buttonNextHTML: null,
            buttonPrevHTML: null
        });

        return false;
    });


    //    // Начальную карусель инициализируем при готовности документа
    //    $("#testScr").load(function () {
    //        alert('123');
    //    });

    $("#trcarusel-0").jcarousel({
        scroll: 1,
        animation: "100",
        initCallback: caruselNavigation0,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });

    $("#trcarusel-1").jcarousel({
        scroll: 1,
        animation: "100",
        initCallback: caruselNavigation1,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });

    $("#trcarusel-2").jcarousel({
        scroll: 1,
        animation: "100",
        initCallback: caruselNavigation2,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
    $("#trcarusel-3").jcarousel({
        scroll: 1,
        animation: "100",
        initCallback: caruselNavigation3,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });

    $("#trcarusel-last").jcarousel({
        scroll: 1,
        animation: "100",
        initCallback: caruselNavigationlast,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });

    function caruselNavigation0(carousel) {
        $('#nav-prev0').bind('click', function () { carousel.prev() });
        $('#nav-next0').bind('click', function () { carousel.next(); });
    }
    function caruselNavigation1(carousel) {
        $('#nav-prev1').bind('click', function () { carousel.prev() });
        $('#nav-next1').bind('click', function () { carousel.next(); });
    }
    function caruselNavigation2(carousel) {
        $('#nav-prev2').bind('click', function () { carousel.prev() });
        $('#nav-next2').bind('click', function () { carousel.next(); });
    }
    function caruselNavigation3(carousel) {
        $('#nav-prev3').bind('click', function () { carousel.prev() });
        $('#nav-next3').bind('click', function () { carousel.next(); });
    }
    function caruselNavigationlast(carousel) {
        $('#last-prev').bind('click', function () { carousel.prev() });
        $('#last-next').bind('click', function () { carousel.next(); });
    }

    //TODO: слайдшоу по таймоуту
    // mainimage
    $('#image-navigation li.tab a').click(function () {
        var elementIndex = $('#image-navigation li.tab a').index(this);
        $('#image-navigation li.tab a').removeClass('active');
        $(this).addClass('active');

        $('#image a.active').fadeOut('slow').removeClass('active');
        $('#image a:eq(' + elementIndex + ')').fadeIn('slow').addClass('active');
        return false;
    });

    // TODO: Объеденить в одну функцию
    // mainimage prev / next
    $('#image-navigation li.prev a').click(function () {
        var elementIndex = $('#image a.active').index();
        if (elementIndex > 0) {
            var prevIndex = elementIndex - 1;
            $('#image a.active').fadeOut('slow').removeClass('active');
            $('#image a:eq(' + prevIndex + ')').fadeIn('slow').addClass('active');
            $('#image-navigation li.tab a:eq(' + elementIndex + ')').removeClass('active');
            $('#image-navigation li.tab a:eq(' + prevIndex + ')').addClass('active');
        }
        return false;
    });

    $('#image-navigation li.next a').click(function () {
        var elementIndex = $('#image a.active').index();
        var countElements = $('#image a').length;
        if (elementIndex < countElements - 1) {
            var nextIndex = elementIndex + 1;
            $('#image a.active').fadeOut('slow').removeClass('active');
            $('#image a:eq(' + nextIndex + ')').fadeIn('slow').addClass('active');
            $('#image-navigation li.tab a:eq(' + elementIndex + ')').removeClass('active');
            $('#image-navigation li.tab a:eq(' + nextIndex + ')').addClass('active');
        }
        return false;
    });

    function clearLabelClass() {
        $('#ed').removeClass('easy-active');
        $('#md').removeClass('middle-active');
        $('#hd').removeClass('hard-active');
    }
    // add fields
    $('#ed label, #ed input').click(function () {
        clearLabelClass();
        $('#ed').addClass('easy-active');
    });
    $('#md label, #md input').click(function () {
        clearLabelClass();
        $('#md').addClass('middle-active');
    });
    $('#hd label, #hd input').click(function () {
        clearLabelClass();
        $('#hd').addClass('hard-active');
    });

    // grey fields

    $('#add td.ingr div, #add td.mera div').live('click', function () {
        var inp = '<input type="text" value="" name="" />';


        if ($(this).html() == '') {
            $(this).append(inp);
            $(this).find('input').focus();
        }
        // Если внутри есть текст
        if ($(this).text() != '') {
            var inpValue = $(this).find('input').attr('value');
            $(this).html('<input type="text" value="' + inpValue + '" name="" />');
            $(this).find('input').focus();
        }
        // Узнаем в какой строке нажали на элемент
        var trWrap = $(this).parent().parent();
        var rowIndex = $('#Ingredients tr.row').index(trWrap) + 1;
        var countRows = $('#Ingredients tr.row').size();
        var row = '<tr class="row"><td class="num">' + (countRows + 2) + '</td><td class="ingr"><div></div></td><td class="mera"><div></div></td></tr>';

        // Если нажали на последний вставляем еще строку
        if (countRows == rowIndex) {
            $('#Ingredients').append(row);
        }


    });

    //Clear row, set text
    $('#add td.ingr input, #add td.mera input').live('blur', function () {
        var inpValue = $(this).attr('value');
        var divWrap = $(this).parent();
        var divWidth = divWrap.width();

        if (inpValue != '') {
            var tdWrapClass = divWrap.parent().attr('class');
            switch (tdWrapClass) {
                case 'ingr':
                    var inpName = 'IngredientName';
                    break;
                case 'mera':
                    var inpName = 'IngredientCount';
                    break;
            }
            divWrap.html('<span>' + inpValue + '</span><input type="hidden" name="' + inpName + '" value="' + inpValue + '" />');
        }
        else {
            divWrap.html('');
        }
        // Адская проверка на длинуу, чтобы обрезать, которая не работает.
        var spanWidth = $(divWrap).find('span').width();

        if (spanWidth > divWidth) {
            $(divWrap).find('span').css('width', divWidth + 'px');
        }

    });

    $('#next-step').click(function () {
        var textarea = '<div class="b-textarea-wrap"><div><textarea class="textarea"></textarea></div></div>';
        var row = $(this).prev('div');

        row.append(textarea);
        return false;
    });


});

// Для комментариев
function answer(id, recipeId) {
    if (window.oldAnswerForm != null)
        $("#" + window.oldAnswerForm).children("form").remove();
    var form = document.getElementById('answerForm' + id);
    window.oldAnswerForm = form.id;
    var formHTML = '';
    if (formHTML == '') {
        formHTML = formHTML + "<form action='/Catalog/AddComment' method='post' onsubmit=\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, httpMethod: 'POST', updateTargetId: 'recipeComments' });\">";
        formHTML = formHTML + "<input id='comment_RecipeID' name='comment.RecipeID' type='hidden' value='" + recipeId + "' />";
        formHTML = formHTML + "<input id='comment_ParentCommentID' name='comment.ParentCommentID' type='hidden' value='" + id + "' />";
        formHTML = formHTML + "<textarea class='textarea-style' cols='30' onkeypress = 'return imposeMaxLength(this, 500);' id='comment_Comment' name='comment.Comment' rows='5'>";
        formHTML = formHTML + " </textarea> <br />";
        formHTML = formHTML + "<input type='image' src='/Content/Images/Template/send-comment.png'  alt='Сохранить' style='cursor: hand;margin-top:5px;' />";
        formHTML = formHTML + "</form>";
        form.innerHTML = formHTML;
    } else
        form.innerHTML = '';
}
function imposeMaxLength(Object, MaxLen) {
    return (Object.value.length <= MaxLen);
}
function ClearCommentText(ajaxContext) {
    $("#comment_Comment").val('');
    return;
}

// Быстрый поиск
$(document).ready(function () {
    $("select#MealCourse").change(function () {
        var mealCourseId = $("#MealCourse > option:selected").attr("value");
        var objSel = document.getElementById("MainIngredient");
        if (mealCourseId == 1) {
            objSel.options[0] = new Option("Яйцом", "41");
            objSel.options[1] = new Option("Молоком", "40");
            objSel.options[2] = new Option("Сыром", "36");
        }
        if (mealCourseId == 3) {
            objSel.options[0] = new Option("Курицей", "37");
            objSel.options[1] = new Option("Картошкой", "45");
            objSel.options[2] = new Option("Рыбой", "42");
            objSel.options[3] = new Option("Грибами", "58");
        }
        if (mealCourseId == 5) {
            objSel.options[0] = new Option("Свининой", "33");
            objSel.options[1] = new Option("Говядиной", "34");
            objSel.options[2] = new Option("Бараниной", "46");
        }

    });
});

var test;

//Рейтинг
$(document).ready(function () {
    test = $("#recipe-card .stars[att!=notmark]").html();
    SetRating();
    $("#recipe-card .stars[att!=notmark]").mouseleave(function () {
        $(".stars").html(test);
        SetRating();
    });


});

function SetRating() {
    $("#recipe-card .stars[att!=notmark] i").hover(function () {
        $(this).nextAll().addClass("empty");
        $(this).nextAll().removeClass("full");
        $(this).nextAll().removeClass("half");
        $(this).prevAll().removeClass("empty");
        $(this).prevAll().removeClass("half");
        $(this).prevAll().addClass("full");
        $(this).addClass("full");
        $(this).removeClass("empty");
        $(this).removeClass("half");
    });
}




function AjaxLink(url, data, updatePanel) {
    $.post(url, data, function (data) {
        $("#" + updatePanel).html(data);
    });
}



function PostRecipeComment(url, updatePanel) {
    var dataPost = "comment.RecipeID=" + $("#comment_RecipeID").val() + "&comment.Comment=" + $("#comment_Comment").val();
    $.post(url, dataPost, function (data) {
        $("#" + updatePanel).html(data);
        $("#comment_Comment").val('');
    })

}

function SendMessageToUser(url, userID, updatePanel) {
    var dataPost = "messageText=" + $("#messageText").val() + "&id=" + userID;
    $.post(url, dataPost, function (data) {
        $("#" + updatePanel).html(data);
        if (before == '')
            before = "#updateMessages";
        $(before).before("<div style=\"clear: both; height: 10px;\"></div>");
        var formHTML = '';
        formHTML = formHTML + "<div id=\"" + randomnumber + "\" style=\"float: left;margin-left:10px;clear:both;margin-top:10px;\">";
        formHTML = formHTML + "Сообщение отправлено";
        formHTML = formHTML + "<div style=\"color: #444444; font-size: 15px;font-weight:bold;\">";
        formHTML = formHTML + $('textarea#messageText').val(); ;
        formHTML = formHTML + "</div></div>";

        $(before).before(formHTML);

        $("textarea#messageText").attr("value", "");

        before = "#" + randomnumber;
        randomnumber = Math.floor(Math.random() * 1000);
    })
}



