var items = null;
var index = 0;

$(function(){

    setupTestimonials();
    getCategories();
    
    $(".popularItems").button();
    $(".newItems").button();
    $(".browse").button();
    $(".welcomeButton").button();
    
    var dialog = $("#itemDetailsDialog");
    
    $("td").hover(
    function(){
        if($(this).data("contactName") === undefined)
            return;
        
        $(this).addClass("thumbnailCellHover");
            
        $(dialog).find(".itemName").html($(this).data("itemName"));
        $(dialog).find(".itemRate").html($(this).data("itemRate"));
            
        var locationOwner = "Listed by <span style='color:blue'>" + $(this).data("contactName") + "</span> in " +
            "<span style='color:blue'>" + $(this).data("location") + "</span>";
            
        $(dialog).find(".itemLocationOwner").html(locationOwner);
    
        var cellPosition = $(this).position();
            
        $(dialog).css("left", cellPosition.left + 45 - $(dialog).width() / 2);
        $(dialog).css("top", cellPosition.top - 75);
            
        dialog.show(0, function(){
            //correct the dialog after shown (may be off a little depending on last selection)
            $(dialog).css("left", cellPosition.left + 45 - $(dialog).width() / 2);
            $(dialog).css("top", cellPosition.top - 75);
        });
    },
    function(){
        $(this).removeClass("thumbnailCellHover");
            
        dialog.hide();
    });
        
    getPresentableItems(true);
});

function startSlideshow()
{
    //create the slideshow
    $('.slideshow').cycle({
        fx: 'fade',
        autostop: 1,
        speed: 1000,
        timeout: 3500
    });
}

function setupTestimonials()
{
    var testimonials = $(".testimonial");
    var testimonialDiv = $(".testimonialDiv");
    
    $(testimonials).each(function(index){
        var testimonial = $(testimonials).get(index);
        
        $(testimonial).find(".author").append("<span class='addTestimonialLink' title='Add Your Testimonial' onclick='showAddTestimonialDialog()'>+</span>");
    });
    
    //choose the testimonial randomly
    var testimonialIndex = Math.floor(Math.random() * $(testimonials).length);
    $(testimonials.get(testimonialIndex)).removeClass("hidden");
    
    setInterval(function() {

        if(!focused)
            return;
    
        var lastTestimonial = $(testimonials).get(testimonialIndex);
        
        testimonialIndex++;
        
        if(testimonialIndex == testimonials.length)
            testimonialIndex = 0;
        
        var nextTestimonial = $(testimonials).get(testimonialIndex);

        var currentHeight = $(lastTestimonial).height();
        $(nextTestimonial).show();
        var newHeight = $(nextTestimonial).height();
        $(nextTestimonial).hide();
        
        $(testimonialDiv).css("height", currentHeight + "px");
        
        $(lastTestimonial).fadeOut(500, function() {
        
            $(".testimonial").css("display", "none");
        
            $(nextTestimonial).fadeIn(1000);
        
            $(testimonialDiv).animate({
                height: newHeight + "px"
            })
        });
    }, 10000);
}

function showAddTestimonialDialog()
{
    $("#addTestimonialDialog").dialog({
        title: "Add Your Testimonial",
        modal: true,
        draggable: false,
        width: 500,
        resizable: false,
        buttons:
            {
            "Submit": function()
            {
                $("#testimonialName").removeClass("invalid");
                $("#testimonialCityState").removeClass("invalid");
                $("#testimonialTextArea").removeClass("invalid");
                
                var formValid = true;
                
                if($.trim($("#testimonialName").val()).length == 0)
                {
                    $("#testimonialName").addClass("invalid");
                    formValid = false;
                }
                
                if($.trim($("#testimonialCityState").val()).length == 0)
                {
                    $("#testimonialCityState").addClass("invalid");
                    formValid = false;
                }
                
                if($.trim($("#testimonialTextArea").val()).length == 0)
                {
                    $("#testimonialTextArea").addClass("invalid");
                    formValid = false;
                }
                
                if(!formValid)
                    return;
                
                //show the 'working' dialog
                $("#workingDialog").dialog({
                    title: "Working",
                    modal: true,
                    draggable: false,
                    closeOnEscape: false,
                    resizable: false
                });
                
                $.ajax({
                    url: "/ws/feedback/addTestimonial",
                    type: "POST",
                    dataType: "json",
                    data: {
                        name : $("#testimonialName").val(),
                        cityState:$("#testimonialCityState").val(),
                        testimonial: $("#testimonialTextArea").val()
                    },
                    success: function(data, textStatus, jqXHR) {
                        $("#workingDialog").dialog("close");
                        $("#addTestimonialDialog").dialog("close");
                        
                        if(!data.success)
                            showError();
                    },
                    error: function(data, textStatus, jqXHR) {
                        $("#workingDialog").dialog("close");
                        $("#addTestimonialDialog").dialog("close");
            
                        showError();
                    }
                });
                
                //remove the close 'x' component
                $("#workingDialog").parent().find(".ui-dialog-titlebar-close").remove();
            },
            "Cancel": function()
            {
                $(this).dialog("close");
            }
        }
    });
}

function getCategories()
{
    $.ajax({
        url: "/ws/item/categories",
        type: "GET",
        dataType: "json",
        success: function(data, textStatus, jqXHR) {
            
            var categories = $(".categories");
            
            for(var j = 0; j < data.length; j++)
            {
                categories.append("<div id='category" + data[j].id + "' class='category'>" + data[j].name + "</div>");
                
                $("#category" + data[j].id).hover(function(){
                    $(this).addClass("categoryOver");
                },
                function(){
                    $(this).removeClass("categoryOver");
                });
                
                $("#category" + data[j].id).data("categoryId", data[j].id);
                
                $("#category" + data[j].id).click(function(){
                    var categoryId = $(this).data("categoryId");
                    
                    window.location.href = "/browse.html?categoryId=" + categoryId;
                });
            }
            
            //match the right to the left
            $(".rightSide").height($(".leftSide").height() - 10);
            
            minimumResultsHeight = $(".rightSide").height();
            
            for(j = 0; j < data.length; j++)
            {
                $("#category" + data[j].id).addClass("hidden");
                $("#category" + data[j].id).delay(25 * j).fadeIn(500);
            }
        },
        error: function(data, textStatus, jqXHR) {
            showError();
        }
    });
}

function getPresentableItems(popularItems)
{
    $(".popularNewWorkingImage").show();

    if(popularItems)
    {
        $(".popularItems").addClass("selectedButton");
        $(".newItems").removeClass("selectedButton");
    }
    else
    {
        $(".popularItems").removeClass("selectedButton");
        $(".newItems").addClass("selectedButton");
    }
    
    index = 0;
    
    $.ajax({
        url: "/ws/item/presentableItems",
        type: "GET",
        dataType: "json",
        data: {
            popular: popularItems
        },
        complete: function(data, textStatus, jqXHR) {
            $(".popularNewWorkingImage").hide();
        },
        success: function(data, textStatus, jqXHR) {
            items = data;
            showItems();
        },
        error: function(data, textStatus, jqXHR) {
            showError();
        }
    });
}

function showItems()
{   
    for(var j = 0; j < 16; j++)
    {
        var cell = $("#item" + j);
        
        var image = "<img class='thumbnail hidden' src='/ws/item/thumbnail?identifier=" + items[index].bestImageIdentifier + "' onload='$(this).delay(100).slideDown(400)'/>";
        
        cell.html(image);
        
        $(cell).data("identifier", items[index].identifier);
        $(cell).data("itemName", items[index].itemName);
        $(cell).data("itemRate", items[index].itemRate);
        $(cell).data("contactName", items[index].contactName);
        $(cell).data("location", items[index].location);
        
        $(cell).unbind("click");
        $(cell).click(function(){
            window.location.href = "/item.jsp?id=" + $(this).data("identifier");
        });
        
        index++;
        if(index == items.length)
            index = 0;
    }
}

function showError()
{
    showErrorDialog("Failed to communicate with RentBOLD.  Please try again later.");
}
