$(document).ready(function() {
    rooms_rus = ["Двухместный", "Четырехместный", "Шестиместный", "Восьмиместный"];
    rooms_eng = ["Double", "4-bedded dorm", "6-bedded dorm", "8-bedded dorm"];
    amount_of_places = ["2", "4", "6", "8"];
    amount_of_rooms = ["1", "3", "4", "1"];

    // Вывод категорий номеров
    if ($("#order").val() == "yes") {
        dis = "disabled=\"disabled\"";
    } else {
        dis = "";
    }
    $("#rooms").append("<select id=\"rooms_table\" name=\"rtype\" " + dis + " \">");
    $("#rooms_table").append("<option value=\"false\">- Select Number -</option>");
    for (i = 0; i < rooms_eng.length; i++) {
        num = i + 1;
        c = "";
        if (i == 0) {
            c = "checked=\"checked\"";
        }
        $("#rooms_table").append("<option value=\"" + num + "\">" + rooms_eng[i] + "</option>");
    }
    $("#rooms").append("</select>");

    // Вывод количества человек в номере
    for (i = 0; i < 4; i++) {
        num = i + 1;
        d = "style=\"display: none;\"";
        $("#showpeople").append("<div class=\"showpeople" + num + "\" " + d + ">");
        $(".showpeople" + num + "").append("<table id=\"showpeopletable" + num + "\" class=\"radiogroup\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr>");
        if (num == 1) {
            $("#showpeopletable1").append("<td valign=\"top\" class=\"RGRadio\"><input name=\"numberofpeople\" value=\"1_2\" type=\"radio\" checked=\"checked\" /></td><td valign=\"top\" class=\"RGLabel\"><label class=\"label_ru2\">2</label></td>");
            continue;
        }
        for (o = 0; o < amount_of_places[i]; o++) {
            num2 = o + 1;
            $("#showpeopletable" + num + "").append("<td valign=\"top\" class=\"RGRadio\"><input name=\"numberofpeople\" value=\"" + num + "_" + num2 + "\" type=\"radio\" /></td><td valign=\"top\" class=\"RGLabel\"><label class=\"label_ru2\">" + num2 + "</label></td>");
        }
        $(".showpeople" + num + "").append("</tr></table>");
        $("#showpeople").append("</div>");
    }

    // При выборе даты прибытия и отбытия
    $("#enddate, #begindate").keyup(function() {
        first = $("#begindate").val();
        second = $("#enddate").val();
        d1 = first.split(".");
        d2 = second.split(".");
        m1 = d1[1] - 1;
        m2 = d2[1] - 1;
        Date1 = new Date(d1[2], m1, d1[0]);
        Date2 = new Date(d2[2], m2, d2[0]);

        non = Math.round((Date2.getTime() - Date1.getTime())/(1000*60*60*24));

        if (non > 0) {
            $("#noofnights").html(non);
            $(":input[name=amount_of_nights]").val(non);
        } else {
            $("#noofnights").html("<small>departure date can't be before arrival date</small>");
        }
    });

    // При выборе категорий номера
    $(":select[name=rtype]").change(function() {
        for (i = 1; i <= 4; i++) {
            $(".showpeople" + i).hide();
        }
        check = $(":select[name=rtype]").val();
        $(".showpeople" + check).show();
        if (check == "showpeople1") {
            $("#additionalbedid").show();
            $(":button[name=addmore]").attr("disabled", "disabled");
        } else {
            $("#additionalbedid").hide();
            $(":radio[name=numberofpeople]").attr("checked", "");
            $(":button[name=addmore]").attr("disabled", "disabled");
        }
        $(":radio[name=additionalbed]").attr("checked", "");
    });

    // При выборе количества человек в номере
    $(":radio[name=numberofpeople]").change(function() {
        $(":radio[name=additionalbed]").attr("checked", "");
        $("#additionalbedid").hide();
        check = $(":radio[name=numberofpeople]").filter(":checked").val();
        if (check == "1_2" || check == "2_4" || check == "3_6" || check == "4_8") {
            $(":button[name=addmore]").attr("disabled", "disabled");
            $("#additionalbedid").show();
            $(":radio[name=additionalbed]").change(function() {
                if ($(":select[name=rtype]").val()) {
                    $(":button[name=addmore]").attr("disabled", "");
                }
            });
        } else {
            $(":radio[name=additionalbed]").attr("checked", "");
            if ($(":select[name=rtype]").val()) {
                $(":button[name=addmore]").attr("disabled", "");
            }
        }
    });

    // При нажатие на кнопку добавить номер
    count = 0;
    if ($(":hidden[name=total]").val()) {
        total = $(":hidden[name=total]").val();
    } else {
        total = 0;
    }
    $("#total").html(total);
    if ($(":hidden[name=firstdaypay]").val()) {
        firstdaypay = $(":hidden[name=firstdaypay]").val();
    } else {
        firstdaypay = 0;
    }
    $("#firstdaypay").html(firstdaypay);
    $(":button[name=addmore]").click(function() {
        amo_of_ni = $(":input[name=amount_of_nights]").val();
        if (amo_of_ni) {
            count++;
            roomtype2 = $(":select[name=rtype]").val();
            roomtype = $(":select[name=rtype]").val();
            numofpep = $(":radio[name=numberofpeople]").filter(":checked").val();
            numofpep = numofpep[2];
            morebed = $(":radio[name=additionalbed]").filter(":checked").val();
            if (morebed != 0 && morebed != undefined) {
                mb = "yes";
            } else {
                mb = "no";
            }
            amount_of_rooms[roomtype - 1] = amount_of_rooms[roomtype - 1] - 1;
            if (amount_of_rooms[roomtype - 1] == 0) {
                $(":button[name=addmore]").attr("disabled", "disabled");
                $(":select[name=rtype] option[value=" + roomtype + "]").attr("disabled", "disabled");
                $(":select[name=rtype]").val("no");
                $("#additionalbedid").hide();
                for (i = 1; i <= 4; i++) {
                    $(".showpeople" + i).hide();
                }
            }
            
            check_payment = $(":radio[name=payment]").filter(":checked").val();
            function TimeCost(SDate, EDate, f2, f4, f6, f8, bed)
            {
                this.SDate = SDate;
                this.EDate = EDate;
                this.Cost = [f2, f4, f6, f8, bed];
                this.GetAllDiffDays = function (inSDate, inEDate) {
                    if (this.Between(inSDate) && this.Between(inEDate)) {
                        return this.GetDiffDays(inEDate, inSDate);
                    }
                    else if (this.Between(inSDate)) {
                        return this.GetDiffDays(this.EDate, inSDate);
                    }
                    else if (this.Between(inEDate)) {
                        return this.GetDiffDays(inEDate, this.SDate);
                    }
                    else {
                        return 0;
                    }
                }
                this.GetCost = function (inSDate, inEDate) {
                    if (mb == "да") {
                        pb = this.Cost[4];
                    } else {
                        pb = 0;
                    }
                    if (roomtype == 1) {
                        result = (this.GetAllDiffDays(inSDate, inEDate) * this.Cost[0]) + (this.GetAllDiffDays(inSDate, inEDate) * pb);
                        return result;
                    } else if (roomtype == 2) {
                        result = (this.GetAllDiffDays(inSDate, inEDate) * this.Cost[1] * numofpep) + (this.GetAllDiffDays(inSDate, inEDate) * pb);
                        return result;
                    } else if (roomtype == 3) {
                        result = (this.GetAllDiffDays(inSDate, inEDate) * this.Cost[2] * numofpep) + (this.GetAllDiffDays(inSDate, inEDate) * pb);
                        return result;
                    } else if (roomtype == 4) {
                        result = (this.GetAllDiffDays(inSDate, inEDate) * this.Cost[3] * numofpep) + (this.GetAllDiffDays(inSDate, inEDate) * pb);
                        return result;
                    }
                }
                this.GetFirstDayCost = function (inSDate, inEDate) {
                    if (roomtype == 1) {
                        if (this.GetAllDiffDays(inSDate, inEDate)) {
                            if (mb == "да") {
                                pb = this.Cost[4];
                            } else {
                                pb = 0;
                            }
                            result = this.Cost[0] + pb;
                            return result;
                        }
                    } else if (roomtype == 2) {
                        if (this.GetAllDiffDays(inSDate, inEDate)) {
                            if (mb == "да") {
                                pb = this.Cost[4];
                            } else {
                                pb = 0;
                            }
                            result = (this.Cost[1] * numofpep) + pb;
                            return result;
                        }
                    } else if (roomtype == 3) {
                        if (this.GetAllDiffDays(inSDate, inEDate)) {
                            if (mb == "да") {
                                pb = this.Cost[4];
                            } else {
                                pb = 0;
                            }
                            result = (this.Cost[2] * numofpep) + pb;
                            return result;
                        }
                    } else if (roomtype == 4) {
                        if (this.GetAllDiffDays(inSDate, inEDate)) {
                            if (mb == "да") {
                                pb = this.Cost[4];
                            } else {
                                pb = 0;
                            }
                            result = (this.Cost[3] * numofpep) + pb;
                            return result;
                        }
                    }
                }
                this.Between = function (TryDate) {
                    return (TryDate >= this.SDate) && (TryDate <= this.EDate);
                }
                this.GetDiffDays = function(Date1, Date2)
                {
                    return Math.round((Date1.getTime() - Date2.getTime()) / (1000 * 60 * 60 * 24));
                }
            }

            var Diapazons = new Array();
            Diapazons.push(
                new TimeCost(new Date(2011, 0, 1), new Date(2011, 0, 11), 2500, 640, 600, 500, 450) // 01-01-2011 - 10-01-2011
            );
            Diapazons.push(
                new TimeCost(new Date(2011, 0, 10), new Date(2011, 4, 1), 1700, 550, 500, 400, 350) // 11-01-2011 - 30-04-2011
            );
            Diapazons.push(
                new TimeCost(new Date(2011, 4, 1), new Date(2011, 5, 11), 2500, 740, 670, 600, 450) // 01-05-2011 - 10-06-2011
            );
            Diapazons.push(
                new TimeCost(new Date(2011, 5, 11), new Date(2011, 5, 14), 3300, 900, 850, 800, 550) // 11-06-2011 - 13-06-2011
            );
            Diapazons.push(
                new TimeCost(new Date(2011, 5, 14), new Date(2011, 9, 1), 2500, 740, 670, 600, 450) // 14-06-2011 - 30-09-2011
            );
            Diapazons.push(
                new TimeCost(new Date(2011, 9, 1), new Date(2011, 11, 24), 1800, 600, 550, 450, 400) // 01-10-2011 - 23-12-2011
            );
            Diapazons.push(
                new TimeCost(new Date(2011, 11, 24), new Date(2012, 0, 1), 2500, 740, 670, 600, 450) // 24-12-2011 - 31-12-2011
            );

            var dt1_control = $("#begindate").val();
            var dt2_control = $("#enddate").val();

            var dt1_ms = dt1_control.split(".");
            var dt2_ms = dt2_control.split(".");

            mon1 = dt1_ms[1] - 1;
            mon2 = dt2_ms[1] - 1;

            var StartDate = new Date(dt1_ms[2], mon1, dt1_ms[0]);
            var EndDate = new Date(dt2_ms[2], mon2, dt2_ms[0]);

            var Cost = 0;
            var FDCost = 0;
            for (var i = 0; i < Diapazons.length; i++) {
                var Diapazon = Diapazons[i];
                Cost += Diapazon.GetCost(StartDate, EndDate);
                if (Diapazon.GetFirstDayCost(StartDate, EndDate) != undefined) {
                    FDCost = Diapazon.GetFirstDayCost(StartDate, EndDate);
                }
            }

            total += Cost;
            firstdaypay += FDCost;
            
            save = "<tr id=\"room_n_" + count + "\"><td>" + count + "</td><td>" + rooms_eng[roomtype - 1] + "<input type=\"hidden\" name=\"room_type[]\" value=\"" + rooms_eng[roomtype - 1] + "\" /><input type=\"hidden\" name=\"room_index[]\" value=\"" + roomtype + "\" /></td><td>" + numofpep + "<input type=\"hidden\" name=\"amount_of_people[]\" value=\"" + numofpep + "\" /></td><td>" + mb + "<input type=\"hidden\" name=\"additional_bed[]\" value=\"" + mb + "\" /></td><td><input type=\"button\" value=\"delete\" onclick=\"delete_number('room_n_" + count + "', " + roomtype + ", " + Cost + ", " + FDCost + ");\" /><input type=\"hidden\" name=\"total_price[]\" value=\"" + Cost + "\" /><input type=\"hidden\" name=\"first_day_price[]\" value=\"" + FDCost + "\" /></td></tr>";

            $("#not_select_number").remove();
            $("#morenumber table").append(save);
            
            delete_number = function(delete_id, amount_p, cst, fdcst) {
                $("#" + delete_id).remove();
                amount_of_rooms[amount_p - 1] = amount_of_rooms[amount_p - 1] + 1;
                $(":select[name=rtype] option[value=" + amount_p + "]").attr("disabled", "");
                old_pr = $(":input[name=total]").val();
                new_pr = old_pr - cst;
                total = new_pr;
                $("#total").html(new_pr);
                $(":input[name=total]").val(new_pr);
                old_fpr = $(":input[name=firstdaypay]").val();
                new_fpr = old_fpr - fdcst;
                firstdaypay = new_fpr;
                $("#firstdaypay").html(new_fpr);
                $(":input[name=firstdaypay]").val(new_fpr);
            }

            $("#total").html(total);
            $(":input[name=total]").val(total);
            $("#firstdaypay").html(firstdaypay);
            $(":input[name=firstdaypay]").val(firstdaypay);

            $(":input[name=deletenumder]").click(function() {
                alert($(":input[name=deletenumder]").val());
            });
        } else {
            alert("You haven't entered arrival and departure date.");
        }
    });

    $(".calendar").simpleDatepicker();
    $(".calendar").each(function() {
        $this = this;
        $(this).after($("<img alt=\"\" src=\"/pics/cal.jpg\"/>").simpleDatepicker({target : $this}));
    });
});
