/* Work/client section scripts */

var campaignCategoryId = 0;
var selectedWork = {"client": [], "category": []};
var filterActions = 0; //a counter for how many times a filter was applied, even if it didn't change the displayed tiles
var filterActionChanges = 0; //a counter for how many times a filter was applied that changed the tiles
var filterHistory = [];
var filterActionColors = ["#cc0000", "#a20101", "#730101"];
var filterActionItemColors = ["#ffffff", "#737373", "#484848"];

var projectTile;

//variables to keep track of which tiles are being faded in or out, for callbacks
var numToFilter = 0;
var numFiltered = 0;
var operationLabel = "";

function initWorkSection() {
    positionWorkContent();
    addRollovers();
    addTileClickHandlers(".work_tile");
    
	$("#work_drawer").click(function() {
	    if($(this).hasClass("can_click")) {
    	    openWorkDrawer();
    	}
	});
    $("#work .drawer_close").click(function() {
	    closeDrawer("#work_drawer");
	});
	
    //Add 'campaign' category to selected work
    selectedWork['category'].push(campaignCategoryId);
    filterHistory.push(selectedWork);
    
    //Hide all non-campaign items
    $(".work_tile").not(".cat_" + campaignCategoryId).hide();
    $(".work_display_num").html($("#work_content .cat_" + campaignCategoryId).length);
}

function openWorkDrawer() {
    //estimate how big the drawer should be
    var drawerHeight = Math.max($(".drawer_category").length * 35, $("#drawer_clients table tr").length * 63) + 30;
    openDrawer("#work_drawer", {height: drawerHeight});  
    return false;
}

function positionWorkContent() {
    setMinimumWorkHeight();
    
    var pos = $(window).scrollTop();
    var workTop = $("#work").offset().top;
    var drawer = $("#work_drawer");
    var scrollThreshold = $("#about").offset().top - ($(window).height() / 2);
    if(pos < workTop - 250 || pos > scrollThreshold) {
        if(drawer.is(":visible")) {
            if(drawer.find(".expanded_content").is(":visible")) {
                closeDrawer(drawer);
            }
            drawer.slideUp();
        }
    } else {
        if(isMobile) {
            drawer.css("position", "absolute");
            drawer.css("top", (pos - workTop + 43) + "px");
            drawer.show();
        } else {
            if(!drawer.is(":visible")) {
                drawer.slideDown();
            }
            drawer.css("position", "fixed");
            drawer.css("top", 43);
        }
    }
}

function setMinimumWorkHeight() {
    $("#work_content_wrapper").css("min-height", $(window).height());
    /*
    if($("#work_content").height() <= $(window).height()) {
        $("#work_content_wrapper").css("height", $(window).height());
    } else {
        $("#work_content_wrapper").css("height", "auto");
    }*/
}

function goToProject(proj_id) {
    var projectTile = $("#work_content .work_tile[proj_id='" + proj_id + "']");
    if(projectTile !== null) {
        projectTile.show();
        projectTile.click();
        scrollWindow("#work", {'offset': -80});
    }
    return false;
}

function addRollovers() {
    if(!isMobile) {
        $(".work_tile").hover(function() {
            $(this).find(".rollover").show();
        }, function() {
            $(this).find(".rollover").hide();
        });
    }
}

function clientSelect(link) {   
    var img = $(link).find("img");
    var src = img.attr("src");
    img.attr("src", img.attr("selected"));
    img.attr("selected", src);   
}

function addTileClickHandlers(selector) {
    $(selector).click(function() {
        resetWork(false);
        projectTile = $(this);
        
        // iterate through the next few elements until the offset top changes, this means it's a new row and the project should 
        // go after it
        var top = $(this).offset().top;
        var next = $(this).next();
        while(next.is(":hidden") || top == next.offset().top) {
            next = next.next();
        }
        // We actually want to insert the content AFTER, since our tile is disappearing
        $(next).after('<div id="project_detail_wrapper" style="display: none"/>');
        var query = "project_id=" + $(this).attr("proj_id");
        if($(this).attr("proj_id") == undefined) {
            query = "campaign_id=" + $(this).attr("campaign_id");
        }
        projectTile.fadeOut(function() {
            loadProjectDetail(loadProjectUrl + "?" + query);
        });
    });
}

function addRelatedClickHandlers(selector) {
    $(selector).click(function() {        
        projectTile = $(".work_tile[proj_id='" + $(this).attr("proj_id") + "']");
        $("#project_detail_wrapper").attr("id", "project_detail_wrapper_old");
        
        // iterate through the next few elements until the offset top changes, this means it's a new row and the project should 
        // go after it
        var top = $(this).offset().top;
        var next = projectTile.next();
        
        // We actually want to insert the content AFTER, since our tile is disappearing
        $(next).after('<div id="project_detail_wrapper" style="display: none"/>');
        var query = "project_id=" + $(this).attr("proj_id");
        if($(this).attr("proj_id") == undefined) {
            query = "campaign_id=" + $(this).attr("campaign_id");
        }
        $("#project_detail_wrapper_old").fadeOut(function() {
            $("#project_detail_wrapper_old").remove();
            loadProjectDetail(loadProjectUrl + "?" + query);
        });
    });
}

function loadProjectDetail(url) {
    projectTile.after('<div id="project_loading">Loading project...</div>');
    
    $("#project_detail_wrapper").load(url, function() {
        $(this).fadeIn();
        projectTile.next().remove();
        var img = $(this).find("#work_project_image");
        if(img.length > 0) {
            img.load(function() {
                scrollWindow("#project_detail", {'offset': -80});
            });
            $("#work_project_details,#work_project_content").css("min-height", img.attr("image_height"));
            $("#work_project_content,#project_detail").css("min-width", parseInt(img.attr("image_width")) + 250);
        } else {
            loadProjectVideo("#project_video_wrapper");
            scrollWindow("#project_detail_wrapper", {'offset': -80});
        }

        addRollovers();
        setMinimumWorkHeight();
        addRelatedClickHandlers("#project_detail .tile_related");
    });
}

function loadProjectVideo(wrapperSelector) {
    var wrapper = $(wrapperSelector);
    videos['projectplayer'] = {
        "yt_id": wrapper.attr("data-video-id"),
        "wrapperSelector": wrapperSelector,
        "embed": "projectPlayer"
    };
    
    // Lets Flash from another domain call JavaScript
    var params = { allowScriptAccess: "always", wmode: 'transparent' };
    // The element id of the Flash embed
    var atts = { id: "projectPlayer" };
    
    // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
    swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=projectplayer", "project_video_div", wrapper.width(), wrapper.height(), "8", null, null, params, atts, function(e) {
        if(!e.success) {
            jwplayer("project_video_div").setup({
                file: "http://www.youtube.com/watch?v=" + videos['projectplayer']['yt_id'],
                width: wrapper.width(),
                height: wrapper.height(),
                modes: [{ type: "html5" }],
                controlbar: 'bottom'
            });
            $("#project_video_wrapper .hover").hide();
        }
    });    
    return false;
}

function filterBy(type, category, link) {
    // Start from the last object in filter history
    selectedWork = $.extend(true, {}, filterHistory[filterHistory.length - 1]);
    
    //first, add or remove the selected filter and update the UI selections
    var filterIndex = $.inArray(category, selectedWork[type]);
    // client or category was deselected
    if(filterIndex > -1) {
        selectedWork[type].splice(filterIndex, 1);
        $(link).removeClass('selected');
        if(type == 'client') {
            clientSelect(link);
        }
    } // 'all' category selected
    else if(category == "all") {
        selectedWork['category'] = [];
        $(link).addClass('selected');
    } // client or category was selected
    else {
        selectedWork[type].push(category);
        $(link).addClass('selected');
        if(type == 'client') {
            clientSelect(link);
        }
    }
    filterHistory.push(selectedWork);
    
    // Handle 'all categories' being either selected or deselected
    if(selectedWork['category'].length == 0) {
        $(".drawer_category a").removeClass('selected');
        $("#work_drawer .category_all a").addClass('selected');
    } else {
        $("#work_drawer .category_all a").removeClass('selected');
    }
    
    // Close any currently open projects
    resetWork(false);
    
    var lastFilter = filterHistory[filterActions];
    var addWork = true;
    var numVisibleBefore = $(".work_tile:visible").length;
    
    // All the possible actions.  This could probably be simplified.
    var noFilter = selectedWork['client'].length == 0 && selectedWork['category'].length == 0;
    var catFilterAdded = lastFilter['category'].length < selectedWork['category'].length;
    var catFilterRemoved = lastFilter['category'].length > selectedWork['category'].length && selectedWork['category'].length > 0;
    var clientFilterAdded = lastFilter['client'].length < selectedWork['client'].length;
    var clientFilterRemoved = lastFilter['client'].length > selectedWork['client'].length;
    var lastClientFilterRemoved = lastFilter['client'].length == 1 && selectedWork['client'].length == 0;
    var firstCatFilter = lastFilter['category'].length == 0 && selectedWork['category'].length > 0;
    var firstClientFilter = lastFilter['client'].length == 0 && selectedWork['client'].length > 0;
    var clientAndCatFilter = selectedWork['client'].length > 0 && selectedWork['category'].length > 0;
    
    if(firstClientFilter || firstCatFilter || catFilterRemoved || (clientFilterRemoved && !lastClientFilterRemoved)) {
        addWork = false;
    }
    
    // if there are multiple categories selected or multiple clients selected, we have to create a cross-product of 
    // client-category combination selectors.
    var selectors = [];
    if(clientAndCatFilter) {
        $.each(selectedWork['client'], function(index, selClient) {
            $.each(selectedWork['category'], function(index, selCat) {
                if(addWork) {
                    selectors.push(".work_tile:hidden.client_" + selClient + ".cat_" + selCat);
                } else {    
                    selectors.push(".client_" + selClient + ".cat_" + selCat);
                }
            });
        });
    } else {
        $.each(selectedWork['client'], function(index, selClient) {
            selectors.push(addWork ? ".work_tile:hidden.client_" + selClient : ".client_" + selClient);
        });
        $.each(selectedWork['category'], function(index, selCat) {
            selectors.push(addWork ? ".work_tile:hidden.cat_" + selCat : ".cat_" + selCat);
        });
    }
    
    if(noFilter) {
        //Show everything
        var fadeEmIn =  $(".work_tile:hidden");
        numToFilter = fadeEmIn.length;
        fadeEmIn.fadeIn(function() {
            onFadeWork(numVisibleBefore, type, category);
        });
    } else if(addWork) {
        var fadeEmIn =  $(selectors.join(","));
        numToFilter = fadeEmIn.length;
        fadeEmIn.fadeIn(function() {
            onFadeWork(numVisibleBefore, type, category);
        });
    } else {
        var fadeEmOut = $(".work_tile:visible").not(selectors.join(","));
        numToFilter = fadeEmOut.length;
        fadeEmOut.fadeOut(function() {
            onFadeWork(numVisibleBefore, type, category);
        });
    }        
    if(numToFilter == 0) {
        updateFilterVariables();
    }
    
    return false;
}

// Called when a piece of work is faded in or out.  numToFilter should be set by the initiating method.  Makes sure that the 
// content is only executed after all the works have been faded.
function onFadeWork(numVisibleBefore, filterType, category) {
    numFiltered += 1;
    if(numFiltered == numToFilter) {
        var numVisibilityChanged = numVisibleBefore - $(".work_tile:visible").length;
        var actionMessage1 = "Adding " + Math.abs(numVisibilityChanged);
        if(numVisibilityChanged > 0) {
            actionMessage1 = "Removing " + numVisibilityChanged;
        } 
        var actionMessage2 = "Client";
        if(category == 'all') {
            actionMessage2 = "Everything";
        } else if(filterType == 'category') {
            var cat = $(".drawer_category[cat_id='" + category + "']");
            if(Math.abs(numVisibilityChanged) > 1) {
                actionMessage2 = cat.attr("plural");
            } else {
                actionMessage2 = cat.attr("singular");
            }
        } 
    
        // Display the action notifier before the ajax call, or during the DOM element removal
        var action = "<div class='drawer_filter_action'>";
        action += "<div class='action' style='color: " + filterActionColors[0] + "'>" + actionMessage1 + "</div>";
        action += "<div class='item' style='color: " + filterActionItemColors[0] + "'>" + actionMessage2 + "</div></div>";
    
        // Fade out the previous actions
        if(filterActionChanges > 3) {
            $(".drawer_filter_action").first().slideUp(function() {
                $(this).remove();
                displayFilterAction(action);
            });
        } else {
            displayFilterAction(action);
        }

        filterActionChanges++;
        postFilterActions();
    }
}

function displayFilterAction(action) {
    var whichToFade = 0;
    if(filterActions > 2) {
        $(".drawer_filter_action .action").slice(whichToFade, whichToFade + 1).css("color", filterActionColors[2]);
        $(".drawer_filter_action .item").slice(whichToFade, whichToFade + 1).css("color", filterActionItemColors[2]);
        whichToFade += 1;
    }
    if(filterActions > 1) {
        $(".drawer_filter_action .action").slice(whichToFade, whichToFade + 1).css("color", filterActionColors[1]);
        $(".drawer_filter_action .item").slice(whichToFade, whichToFade + 1).css("color", filterActionItemColors[1]);
    }
    
    $("#drawer_filter_actions").append(action);
}

// Called after the filtering is complete.
function postFilterActions() {
    //setTimeout("closeDrawer('#work_drawer')", 1500);
    $("#next_group_" + filterActions).attr("id", "next_group_" + (filterActions + 1));
    
    //update display count
    $(".work_display_num").html($("#work_content .work_tile:visible").length);
    setMinimumWorkHeight();
    //reset variables
    updateFilterVariables();
}

function updateFilterVariables() {
    numToFilter = 0;
    numFiltered = 0;
    filterActions += 1;
}

// Closes any opened project detail, resetting the tiles to their current filter status.
function resetWork(doScroll) {
    if($("#project_detail_wrapper").length > 0) {
        $("#project_detail_wrapper").fadeOut(function() {
            $(this).remove();
            projectTile.fadeIn();
            if(doScroll) {
                scrollWindow("#work", {'offset': -62});
            }
        });
    }
    setMinimumWorkHeight();
    return false;
}
