/**
 * Controls interactions on the booking page
 */
jQuery(function($) {
    var days, url;
    var consultantCache = {}, timesCache = {};
    $.ajaxSetup({ cache : false });
    try {
        var data = $("#appointmentDate").metadata();
        $("#appointmentDate").data("days", data.days);
        url = data.url;
    } catch (ex) {
        return;
    }
    
    // set submit button disabled
    $("input.buttonBookNow").attr("disabled", true).addClass("buttonBookNowDisabled");
    
    // setup calendar
    $("#appointmentDate").datepicker({
        'onChangeMonthYear' : function(year, month, inst) {
            var days = $("#appointmentDate").data("days");
            var prev = {
                "year" : (month == 1 ? -1 : 0) + year,
                "month" : ((month + 10) % 12) + 1
            };
            var next = {
                "year" : (month == 12 ? 1 : 0) + year,
                "month" : (month % 12) + 1
            };
            if (days[year] && days[year][month] && 
                days[prev.year] && days[prev.year][prev.month] &&
                days[next.year] && days[next.year][next.month]) {
                return;
            }
            $.getJSON(url + "/" + year + "/" + month, null, function(data, textStatus) {
                    $("#appointmentDate").data("days", $.extend(true, days, data.days)).datepicker("refresh");
            });
        },
        'beforeShowDay' : function(date) {
            var days = $("#appointmentDate").data("days");
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            //console.log(year + "-" + month + "-" + date.getDate() + " / " + (date.getDate()) + " == " + days[year][month]) + "?";
            if (days[year] && days[year][month] &&
                $.inArray(date.getDate(), days[year][month]) > -1) {
                //console.log("true");
                return [true, ''];
            }
            return [false, ''];
        },
        'dateFormat' : 'd MM, yy',
        'firstDay' : 1,
        'minDate' : new Date(),
        'onSelect' : function(date, ui) {
            $("#TimeslotTimeslotDate").val(date);
            $("#summaryDate").text(date);
            $("#boxDate .hd").text($.datepicker.formatDate("DD d MM, yy", new Date(ui.selectedYear, ui.selectedMonth, ui.selectedDay)));
            
            var isoDate = $.datepicker.formatDate("yy-mm-dd", $("#appointmentDate").datepicker("getDate"));
            var url = $("#TimeslotConsultantIdAjax").metadata();
            var salonServiceId = $("#AppointmentSalonServiceId :checked").val();
            
            $("#appointmentDate").trigger("changed");
        }
    }).datepicker("setDate", $.datepicker.parseDate("d MM, yy", $("#TimeslotTimeslotDate").val()));
    
    
    // listen to changes and refresh appointment card
    $("#AppointmentBookingForm").bind("changed", function(ev, options) {
        var origin = "";
        if (options && options.origin) {
            origin = options.origin;
        }
        
        // get all values
        var date = $.datepicker.formatDate("yy-mm-dd", $("#appointmentDate").datepicker("getDate"));
        var consultantId = $("#TimeslotConsultantIds input[type=radio]:checked").val();
        var consultantName = $("#TimeslotConsultantIds input[type=radio]:checked").next().text();
        var salonServiceId = $("#AppointmentSalonServiceId :checked").val();
        var time = $("#TimeslotStartTime :checked").val();
        
        //alert('form changed ' + origin);
        
        loadDay(date);
        
        // update consultant and time options
        if (date !== undefined && salonServiceId !== undefined &&
            consultantCache.hasOwnProperty(date) &&
            consultantCache[date].hasOwnProperty(salonServiceId))
        {
            if (consultantCache[date][salonServiceId].consultants === "")
            {
                $("#TimeslotConsultantId").attr("checked", true);
                consultantId = $("#TimeslotConsultantIds :checked").val();
                consultantName = $("#TimeslotConsultantIds :checked").next().text();
            }
            
            if (consultantCache[date][salonServiceId].times &&
                consultantCache[date][salonServiceId].times.hasOwnProperty(consultantId))
            {
                $("#TimeslotStartTime").html(consultantCache[date][salonServiceId].times[consultantId]);
                //alert(consultantCache[date][salonServiceId].times[consultantId]);
            }
            else
            {
                $("#TimeslotStartTime").html("<p>sorry, we don't have enough available time for this service</p>");
            }
            
            if (origin !== "Consultant" && origin !== "StartTime")
            {
                $("#TimeslotConsultantIdAjax").html(consultantCache[date][salonServiceId].consultants);
                $("#boxConsultants .bd").slideDown();
            }
            
            // reinstate chosen values where possible
            
            $("#TimeslotStartTime input[value=" + time + "]").attr("checked", true);
            if (origin != "Consultant" && origin != "StartTime")
            {
                $("#TimeslotConsultantIds input[value=" + consultantId + "]").attr("checked", true);
            }
            
            consultantId = $("#TimeslotConsultantIds :checked").val();
            consultantName = $("#TimeslotConsultantIds :checked").next().text();
            time = $("#TimeslotStartTime :checked").val();
            
            refreshRadioButtons();
        }
        else if (date !== undefined && salonServiceId !== undefined)
        {
            $("#TimeslotConsultantIdAjax").html("");
            $("#TimeslotConsultantId").attr("checked", true);
            $("#TimeslotStartTime").html("<p>sorry, we don't have enough available time for this service</p>");
        }
        else
        {
            $("#TimeslotConsultantIdAjax").html("");
            $("#TimeslotConsultantId").attr("checked", true);
            $("#TimeslotStartTime").html("<p></p>");
        }
        
        // update appointment card with values
        var label = $("#AppointmentSalonServiceId :checked").closest("tr").find("label").html();
        if (label === null) {
            label = $("#boxServices .hd").attr("title");
            $("#boxServices .hd").html(label);
            $("#summaryService").html("-");
            $("#AppointmentSalonServiceName").html("-");
        } else {
            $("#boxServices .hd").html(label);
            $("#summaryService").html(label);
            $("#AppointmentSalonServiceName").html(label);
        }
        
        
        $("#summaryConsultant").text(consultantName);
        if (consultantName === "") {
            $("#boxConsultants .hd").html($("#boxConsultants .hd").attr("title"));
        } else {
            $("#boxConsultants .hd").html(consultantName + "&nbsp;");
        }
        
        var $checked = $("#TimeslotStartTime :checked");
        var endTime = $checked.attr("endtime");
        var statusText = "-";
        if (time !== undefined) {
            statusText = time + " - " + endTime;
        }
        $("#summaryTime, #TimeslotTime").text(statusText);
        
        // enable/disable submit
        if (date === undefined || consultantId === undefined || salonServiceId === undefined
            || time === undefined) {
            $("input.buttonBookNow").attr("disabled", true).addClass("buttonBookNowDisabled");
            $("#readyBox").slideUp();
        } else {
            $("input.buttonBookNow").attr("disabled", false).removeClass("buttonBookNowDisabled");
            $("#readyBox").slideDown();
        }
        $(".tabs").tabs("select", "#tabAppointment");
    });
    
    // trigger "changed" event that bubbles up to form element
    $("#AppointmentSalonServiceId input").click(function(e) {
        $("#AppointmentSalonServiceId").trigger("changed", [{origin : "SalonService"}]);
    });
    
    $("#TimeslotConsultantIds input").live("click", function(e) {
        $(e.target).trigger("changed", [{origin : "Consultant"}]);
    });
    
    // listen for clicks on table cell and propagate event to underlying checkbox as 'change'
    $("#TimeslotStartTime").click(function(e) {
        if ($(e.target).is("td")) {
            var newState = !$("input", e.target).attr("checked");
            $("input", e.target).attr("checked", newState).change();
            $(e.target).trigger("change");
        }
    });
    $("#TimeslotStartTime").bind("change", function(e) {
        $(e.target).trigger("changed", [{origin : "StartTime"}]);
    });
    
    function refreshRadioButtons() {
        $("#TimeslotStartTime td").each(function() {
            if ($("input:checked", this).length > 0) {
                $(this).addClass("checked");
                $(this).removeClass("unchecked");
            } else if ($("input", this).length > 0) {
                $(this).addClass("unchecked");
                $(this).removeClass("checked");
            }
        });
    }
    
    // loads data for given day into cache
    function loadDay(date) {
        var url = $("#TimeslotConsultantIdAjax").metadata();
        var salonServiceId = $("#AppointmentSalonServiceId :checked").val();
        
        if (date !== undefined && !consultantCache.hasOwnProperty(date)) {
            $.getJSON(url.url + "/" + date, null, function(data, status) {
                consultantCache[date] = data;
                if (data.hasOwnProperty("length") && data.length === 0) {
                    // date not available
                    $("#TimeslotTimeslotDate").val("");
                } else {
                    // date is available
                }
                $("#AppointmentBookingForm").trigger("changed");
            });
        } else {
            //$("#AppointmentSalonServiceId").trigger("changed", [{cascade : true}]);
        }
    }
    
    $("#AppointmentBookingForm").trigger("changed");
    
    if ($.fn.fancybox) {
        $(".gallery li > a[rel=gallery]").fancybox({ hideOnContentClick : false });
    }
    if ($.fn.tooltip) {
        $("#boxServices label").tooltip({ position : { my : "left top", at: "right top", offset: "90 0" }});
    }
    
    // force tab redraw for webkit
    $("#tabAppointment .yui-u.first").append(" ");
});

$(window).load(function() {
    // signup popup box
    $("#paparazziSignup").dialog({
        autoOpen : true,
        title : '',
        modal : true,
        position : ['center', 'center'],
        width : 475,
        height : 400,
        hide : 'fade',
        close : function() {
            //$.cookie("Emails[status]", true, { expires : 7 });
        }
    });
    $("#paparazziSignup form").submit(function() {
        var action = $(this).attr("action");
        var data = $(this).serialize();
        var agrees = $("#paparazziSignup #EmailAgreesToTerms").is(":checked");
        if (agrees === false) {
            $("#EmailError").html("Please check the form is complete");
            return false;
        }
        $.post(action, data, function(data, textStatus) {
            $("#paparazziSignup").dialog("close");
        });
        return false;
    });
});

