﻿var worldSkills = new function () {

    //--
    // redirects with search time as querystring
    this.bindSearch = function () {
        $('#btnSearch').click(function () {
            var searchTerm = $('#search').val();
            window.location = '/search?search=' + searchTerm;
            return false;
        });
    },


    this.bindSearchKeyUp = function () {
        $('#search').keyup(function (e) {
            if (e.which == 13) {
                $('#btnSearch').trigger('click');
                return false;
            }
        });
    },


    //--
    // puts twitter item into correct markup
    //    this.fixMarkupForTwitter = function () {
    //        // get twitter items
    //        $('#twitter_update_list li').each(function () {
    //            // get time
    //            var timeAgo = $(this).find('a').last().text();
    //            $('#twitter').prepend($('<details>' + timeAgo + '</details>'));

    //            var p = $('<p></p>').append($(this).find('span'));
    //            $('#twitter').prepend(p);
    //        });
    //    }


    //--
    // Binds change event for flickr dropdown list.
    // Gets collection id from list.
    this.bindFlickrDropdownPost = function () {
        $("#ddlFlickrCategory").change(function () {
            var url = location.href.substring(0, location.href.indexOf('?')) + '?icollection=' + $(this).val();
            window.location = url;
        });
    },


    //--
    // Sets flickr dropdown list value to the one in the query string.
    this.initFlickrDropdownPost = function () {
        var colIndex = location.href.indexOf('?icollection=');
        if (colIndex != -1) {
            var col = worldSkills.getQueryVariable('icollection');

            $("#ddlFlickrCategory").val(col);
        }
    },


    this.getQueryVariable = function (variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
    },

    this.bindScheduleDropdowns = function () {
        var rows = $('#schedule tbody tr:not(.day, .no-events)');

        this.bindScheduleDropdown(rows, 'date', 'date');
        this.bindScheduleDropdown(rows, 'topic', 'topic');
        this.bindScheduleDropdown(rows, 'location', 'location');
    },


    this.bindScheduleDropdown = function (rows, dropdownId, filterFlagClass) {
        $('#' + dropdownId).change(function () {
            // when first index is selected, show all
            if ($(this).attr('selectedIndex') == 0) {
                var filters = $(rows).find('input.filters.' + filterFlagClass);
                $(filters).removeClass(filterFlagClass);
                $(filters).each(function () {
                    if ($(this).is('.date, .topic, .location') == false) {
                        $(this).parents('tr').fadeIn();
                    }

                    $('.day').show();
                });

                return;
            }

            // add filterFlagClass to filters, and hide row
            for (var i = 0; i < rows.length; i++) {
                // get filters from this row's hidden field
                var f = $(rows[i]).find('input.filters');

                // get value from hidden field
                var filterValue = $(rows[i]).find('input.' + filterFlagClass).val();

                if (filterValue.indexOf($(this).val()) == -1) {
                    // add filter, and hide
                    $(f).addClass(filterFlagClass);
                    $(rows[i]).fadeOut();
                }
                else {
                    // row has this topic
                    $(f).removeClass(filterFlagClass);

                    // only show this row if there are no more filters
                    if ($(f).is('.date, .topic, .location') == false) {
                        $(rows[i]).fadeIn();
                    }
                }
            }

            setTimeout('fixRemaining()', 500);
        });
    },

    this.bindEmailScheduleForm = function () {
        var options = {
            beforeSubmit: preFormSubmission,
            success: showResponse,
            dataType: 'json'
        };

        $('#emailform').submit(function () {
            $('#emailform .message').text('').removeClass('success').removeClass('error');
            $(this).ajaxSubmit(options);

            return false;
        });
    },

    this.bindAjaxPanels = function () {
        $('.ajax-load').click(function () {
            var panelId = $(this).attr('rel');
            if ($('#' + panelId + ' .ajax-content').html().length == 0) {
                $.ajax({
                    url: 'base/rest/GetImages/' + $('#' + panelId + ' span').text() + '/',
                    dataType: 'html',
                    success: function (data) {
                        $('#' + panelId + ' .ajax-content').append(data);
                    }
                });
            }

            return false;
        });
    }
}

function preFormSubmission() {
    $.fancybox.showActivity();
}

function showResponse(data) {
    var message = '';
    var messageClass = '';

    if (data.message) {
        message = data.message;
        messageClass = 'success';
        $.fancybox.close();
    } else {
        message = data.error;
        messageClass = 'error';
    }

    $('#emailform .message').text(message).addClass(messageClass).fadeIn();

    $.fancybox.hideActivity();
}

// hack to show/hide days
function fixRemaining() {
    var days = $('.day');
    $('.day').each(function () {
        if ($(this) == days.last()) {
            if ($d(this).nextAll('tr:visible:not(.no-events)').length > 0) {
                $(this).show();
            } else {
                $(this).hide();
            }
        } else {
            if ($(this).nextUntil('.day', ':visible').length > 0) {
                $(this).show();
            } else {
                $(this).hide();
            }
        }
    });

    $("#schedule table tbody").each(function () {
        if ($("tr:visible:not(.no-events)", this).length == 0) {
            $(".no-events", this).show();
        } else {
            $(".no-events", this).hide();
        }
    });

}

function toggleEmptyTableMessage() {
    $("#schedule table tbody").each(function() {
        if ($("tr:visible:not(.no-events)", this).length == 0) {
            $(".no-events", this).show();
        } else {
            $(".no-events", this).hide();
        }
    });
}

function recursiveElement(item, selector) {
    if ($(item).hasClass(selector)) {
        return item;
    }

    return recursiveElement($(item).prev(), selector);
}

$(document).ready(function () {
    worldSkills.bindSearch();
    worldSkills.bindFlickrDropdownPost();
    worldSkills.initFlickrDropdownPost();
    worldSkills.bindSearchKeyUp();
    worldSkills.bindAjaxPanels();

    worldSkills.bindScheduleDropdowns();
    worldSkills.bindEmailScheduleForm();


    $('.viewall').click(function () {
        $('.tabletitle').each(function () {
            if ($(this).parent().siblings('tr:hidden').length > 0) {
                $(this).trigger('click');
            }
        });

        $("select").each(function () {
            $(this).val('');
        });

        $("table tr:hidden").each(function () {
            $(this).show();
        });

        return false;
    });
});


