/*
	CODE FROM CTS-MEDIA
*/
$(document).ready(function(){
	// Check if Slider is needed...
    if ($("#das_team").length){
        // Index Team and create navi
        teamIndexer("#team", ".item",".navSquare");
        // Add animation:
        $("div.navSquare a").click(function(event){
            event.preventDefault();
            var target = $(event.target);
            // animate Scroll:
            var jump = target.attr("rel");
            $("#team").animate({
                marginLeft: "-"+jump+"px"
            }, "fast");
            // set all buttons un-highlighted:
            $(".navSquare a").removeAttr("class");
            // highlight the clicked menu-item:
            target.addClass("activ");
        });
    }

    // Check if sorting is needed:
    if ($("#fallbeispiele").length){
        // create the Dropdown-menu:
        var dropdown = $("#viewSwitch .selectSort");
        dropdown.html(
                "<a href='#' id='selected'>Nach Datum</a>"+
                "<ul id='selectList' style='position: absolute; z-index: 20'>" +
                "<li><a rel='jahr' href='#'>Nach Datum</a></li>" +
                "<li><a rel='kunde' href='#'>Nach Kunde</a></li>" +
                "</ul>"
        );
        // Hide the menu:
        dropdown.find("#selectList").slideToggle();
        dropdown.click(function(event){
            event.preventDefault();
            $(event.target).find("#selectList").slideToggle(200, function(){
				$(this).parent().find('#selected').toggleClass('selectHide');
			});
			$(event.target).toggleClass('open');
			//dropdown.find("#selected").css('color', '#ffffff');
        });
        // Make the menu useable:
        dropdown.find("li > a").click(function(event){
            event.preventDefault();
            var target = $(event.target);
            target.parent().parent().parent().find("#selected").text( target.text() );
            target.parent().parent().slideUp();
			target.parent().parent().parent().removeClass('open');
			target.parent().parent().parent().find('#selected').removeClass('selectHide');
            // Perform sort:
            sortAndDisplay( target.attr("rel") );
        });
        // Default sort by Date:
        sortAndDisplay("jahr");
    }

    // Check if project-navigation or other projects are needed:
    if ($("#fallbeispiel").length){
        projectNavigation($('#topnav > li > a.trail').attr('href'),
            '#viewSwitch .cases_overview .item',
            $('.selectProject a.more'),
            $('.selectProject a.moreBack')
        );
        customerProjects($('#topnav > li > a.trail').attr('href'),
            '#viewSwitch .cases_overview .item',
            $('#fallbeispiel .layout_full')
        );
    }
});

/**
 * Indexes the big "team"-div to switch between the members.
 * @param container_id The ID of the container, containing all Team-Member divs.
 * @param container_item_class The class which is allocated with the Team-Member divs in the container.
 * @param navi_class The class of the Navi used to switch between the members.
 */
function teamIndexer(container_id, container_item_class, navi_class){
   // Array of team-members (div's):
    var collection = [];
    collection[0] = 0;
    var index_count = 1;
    var tmp = 0;
    var container = $(container_id);
    container.children(container_item_class).each(function(index, element){
        // Get Width:
        tmp += $(element).outerWidth(true);
        // Increase:
        if ((index +1) % 3 === 0){
            collection[index_count] = tmp;
            index_count++;
        }
    });
    // Clean Up
    if (container.find(".item").length % 3 === 0){
        collection.pop();
    }
    // create navigation:
    var list = $(navi_class+" > ul");
    list.children().remove();
    $.each(collection, function(i){
        list.append("<li><a href='#' rel='"+collection[i]+"'>&nbsp;</a></li>");
    });
    list.find("li:first a").addClass("activ");
}

/**
 * Sets up the project navigation. Also adds a noProject class to the next/previous link if no further projects are found
 * @param string href the page to send a post request (ajax) to
 * @param string/jQuery Object container the project item container
 * @param string/jQuery Object next the a tag for the next project link
 * @param string/jQuery Object previous the a tag for the previous project link
 */
var projectNavigation = function(href, container, next, previous) {
    //send a post and retrieve the container from data
    $.post(href, function(data) {
        var currLocation = window.location.pathname.substr(1); 
        var jQObj = $(data);
        
        //sorting with jSort
        jQObj.find(".cases_overview").jSort({
            sort_by: '.projectNamePlus',
            item: '.item',
            order: 'asc'
        });
                      
        var cases = jQObj.find(container);
        var currCase = null;  
        
        cases.each(function() {
            //filter out all elements but the currently active one
            var element = $(this).find('a').filter("a[href$='" + currLocation  + "']");

            if(element.length > 0) {
                //get index of element
                currCase = cases.index(element.parents('.item'));
                //stop each loop
                return false;
            }
        });

        if(!isNaN(currCase)) {
            next = $(next);
            previous = $(previous);

            //set the next and previous links
            if(currCase > 0 && currCase < cases.length - 1) {
                next.attr('href', $(cases.eq(currCase + 1)).find('a').attr('href'));
                previous.attr('href', $(cases.eq(currCase - 1)).find('a').attr('href'));
            } else if (currCase <= 0) {
                next.attr('href', $(cases.eq(cases.length - 1)).find('a').attr('href'));
                previous.attr('href', $(cases.eq(currCase - 1)).find('a').attr('href'));
            } else if (currCase >= cases.length - 1) {
                next.attr('href', $(cases.eq(0)).find('a').attr('href'));
                previous.attr('href', $(cases.eq(currCase - 1)).find('a').attr('href'));
            }
        }
    });
};

/**
 * Shows additional projects by customer (below the current project)
 * @param string href the page to send a post request (ajax) to
 * @param string/jQuery Object container the project item container
 * @param string/jQuery Object appendContainer place to append other projects to
 */
var customerProjects = function(href, container, appendContainer) {
    //send a post and retrieve the container from data
    $.post(href, function(data) {
        var currLocation = window.location.pathname.substr(1);
        var cases = $(data).find(container);
        var currCase = null;

        cases.each(function() {
            //filter out all elements but the currently active one
            var element = $(this).find('a').filter("a[href$='" + currLocation  + "']");

            if(element.length > 0) {
                currCase = element.parents('.item');
                return false;
            }
        });

        if(currCase!= null && currCase.length > 0) {
            //get customer name
            var customer = currCase.find('.customer').text();
            //inject cases_customer if not found (should not happen unless template gets changed somehow. Just a safety measure)
            if($(appendContainer).find('.cases_customer').length <= 0) {
                $(appendContainer).append('<div class="cases_customer" />')
            }

            //find item containers by customer name and exclude the currently active project
            cases.not(currCase).each(function() {
                if(customer == $(this).find('.customer').text()) {
                    $(appendContainer).find('.cases_customer').append($(this).hide());
                }
            });

            if($(appendContainer).find('.item').length > 0) {
                //sorting with jSort
                $(appendContainer).find(".cases_customer").jSort({
                    sort_by: '.projectName',
                    item: '.item',
                    order: 'asc'
                });
                
                $(appendContainer).find(".cases_customer").prepend($("<h2>").text('Weitere '+customer+' Projekte'));

                //fade the projects in
                $(appendContainer).find('.item').each(function(i) {
                    $(this).delay(i * 200).fadeIn();
                });
            } else {
                $(appendContainer).find(".cases_customer").remove();
            }
        }
    });
};

/**
 * Group the Items by the creation-date.
 * @param unsorted The unsorted array.
 */
function groupByDate(unsorted){
    var sorted = {};
    $.each(unsorted, function(index, object){
        var tmp = new Date(object.find("span.date").text() * 1000).getFullYear();
        if (sorted[tmp] === undefined){
            sorted[tmp] = [];
        }
        sorted[tmp].push(object);
    });
    return sorted;
}
/**
 * Sorts the projects by their creation-date.
 *  Is called by JavaScripts ".sort()"-function!
 */
function sortByDate(a, b){
    var dateA = parseInt(a.find("span.date").text());
    var dateB = parseInt(b.find("span.date").text());
    return dateA - dateB;
}

/**
 * Sorts the projects by their creation-date in reverse.
 *  Is called by JavaScripts ".sort()"-function!
 */
function sortByDateReverse(a, b){
    var dateA = parseInt(a.find("span.date").text());
    var dateB = parseInt(b.find("span.date").text());
    return dateB - dateA;
}

/**
 * Group the Items by the customers name
 * @param unsorted The unsorted array.
 */
function groupByCustomer(unsorted){
    var sorted = {};
    $.each(unsorted, function(index, object){
        var tmp = object.find("span.customer").text();
        if (sorted[tmp] === undefined){
            sorted[tmp] = [];
        }
        sorted[tmp].push(object);
    });
    return sorted;
}
/**
 * Sorts the projects by Customer-name.
 *  Is called by JavaScripts ".sort()"-function!
 */
function sortByCustomer(a, b){
    var customerA = a.find("span.customer").text().toLowerCase();
    var customerB = b.find("span.customer").text().toLowerCase();
    if (customerA < customerB) return -1;
    if (customerA > customerB) return 1;
    else return 0;
}

/**
 * Group the Items by the medium-name.
 * @param unsorted The unsorted array.
 */
function groupByMedium(unsorted){
    var sorted = {};
    $.each(unsorted, function(index, object){
        var tmp = object.find("span.subcategory").text();
        if (sorted[tmp] === undefined){
            sorted[tmp] = [];
        }
        sorted[tmp].push(object);
    });
    return sorted;
}
/**
 * Sorts the Projects by Medium
 *  Is called by JavaScripts ".sort()"-function!
 */
function sortByMedium(a, b){
    var mediumA = a.find("span.subcategory").text().toLowerCase();
    var mediumB = b.find("span.subcategory").text().toLowerCase();
    if (mediumA < mediumB) return -1;
    if (mediumA > mediumB) return 1;
    else return 0;
}

/**
 * Performs the sort and displays the results on the Site.
 * Called by the "sortAndDisplay()"-function!
 * @param sort_callback The callback-function used to sort the projects.
 * @param groub_callback The callback-function to group the sorted items.
 * @param filter_class The class which the filter-div gets (to determine
 *  if it was sorted by customer, date or whatever).
 */
function performSort(sort_callback, groub_callback, filter_class){
    // Collect Dates:
    var items = [];
    $("#viewSwitch div.filter").remove();
    $("#viewSwitch div.item").each(function(index, object){
        var tmp = $(object);
        // Delete all Styles:
        tmp.removeAttr("class");
        items[index] = tmp;
        tmp.remove();
    });

    // First sort: By given Callback:
    items.sort(sort_callback);
    // Second sort: Group by given Callback:
    items = groub_callback(items);
    // Third sort: Sort by Date (always):
    var order = [];
    if (filter_class === 'filter_jahr'){
        $.each(items, function(index, object){
            object.sort(sortByDateReverse);
            order.push(index);
        });
    } else {
        $.each(items, function(index, object){
            object.sort(sortByDateReverse);
            order.push(index);
        });
    }

    // Dirty...
    // hours_wasted_to_optimize_this = 19;
    if (filter_class === 'filter_jahr'){
        order.reverse();
    }

    // Display sorted Data:
    var switcher = $("#viewSwitch div.cases_overview");
    $.each(order, function(i, val){
        var object = items[val];
        // Spacer
        switcher.append("<div class='filter item "+filter_class+"'><span>"+val+"</span></div>");
        var odd_even = 0;
        $.each(object, function(index, dom){
            if (odd_even % 2 == 0){
                dom.addClass("odd item");
            } else {
                dom.addClass("even item");
            }
            switcher.append(dom);
            odd_even++;
        });
    });
    // Fade images in:
    $("#viewSwitch div.item").each(function(index){
        $(this).find("img").delay(index * 200).fadeIn();
    });
}

/**
 * Crawls over the project-list and adds the picture of the
 *  first Project to the "filter"-div.
 * Used in the "customer"-sorted list only!
 */
function addPictureToFilter(){
    $("#viewSwitch div.filter").each(function(index, object){
        var tmp = $(object);
        var customerName = tmp.next().find(".customer").text()
        //replace umlauts/ special signs and remove whitespaces
        var customerImageName = customerName.toLowerCase().replace(/ /g,"").replace(/ä/g, "ae").replace(/ü/g, "ue").replace(/ö/g, "oe").replace(/[^a-z 0-9]+/g,'');
	    //append new image tag
        tmp.append($("<img />").attr('src', '/tl_files/bilder/kunde/logo_' + customerImageName + '.gif').attr('alt', customerName))
    });
}

/**
 * Executes the sorting-function by parsing the given String-argument
 * @param how The String describing what sort-function should be used.
 */
function sortAndDisplay(how){
    switch(how){
        case "jahr":
            performSort(sortByDate ,groupByDate, "filter_jahr");
            $('#viewSwitch').removeClass('customer_view');
            break;
        case "kunde":
            performSort(sortByCustomer, groupByCustomer, "filter_kunde");
            $('#viewSwitch').addClass('customer_view');
            addPictureToFilter();
            break;
        case "medium":
            performSort(sortByMedium, groupByMedium, "filter_medium");
            $('#viewSwitch').removeClass('customer_view');
            break;
    }
}
