$(document).ready(function() {
    refreshUnreadMessageCount();
    setInterval(refreshUnreadMessageCount, 30000);
});

var refreshUnreadMessageCount = function() {
    $.get('/ajax/get_num_unread_messages', function(data) {
        if (data != "0")
            $("#global_unread_message_count").parent().show();
        else
            $("#global_unread_message_count").parent().hide();
        $("#global_unread_message_count").html(data);
    });
}


/* RealTime @ Students #jt */

$(document).ready(function() {
    (function($) {
        
        $.fn.vTicker = function(options) {
            var defaults = {speed:700,pause:4000,showItems:3,animation:'',mousePause:true,isPaused:false,direction:'up',height:168};
            var options = $.extend(defaults, options);
            moveUp = function(obj2, height, options) {
                if (options.isPaused)return;
                var obj = obj2.children('ul');
                var clone = obj.children('li:first').clone(true);
                if (options.height > 0) {
                    height = obj.children('li:first').height()
                }
                obj.animate({top:'-=' + height + 'px'}, options.speed, function() {
                    $(this).children('li:first').remove();
                    $(this).css('top', '0px')
                });
                if (options.animation == 'fade') {
                    obj.children('li:first').fadeOut(options.speed);
                    if (options.height == 0) {
                        obj.children('li:eq(' + options.showItems + ')').hide().fadeIn(options.speed).show()
                    }
                }
                clone.appendTo(obj)
            };
            moveDown = function(obj2, height, options) {
                if (options.isPaused)return;
                var obj = obj2.children('ul');
                var clone = obj.children('li:last').clone(true);
                if (options.height > 0) {
                    height = obj.children('li:first').height()
                }
                obj.css('top', '-' + height + 'px').prepend(clone);
                obj.animate({top:0}, options.speed, function() {
                    $(this).children('li:last').remove()
                });
                if (options.animation == 'fade') {
                    if (options.height == 0) {
                        obj.children('li:eq(' + options.showItems + ')').fadeOut(options.speed)
                    }
                    obj.children('li:first').hide().fadeIn(options.speed).show()
                }
            };
            return this.each(function() {
                var obj = $(this);
                var maxHeight = 0;
                obj.css({overflow:'hidden',position:'relative'}).children('ul').css({position:'absolute',margin:0,padding:0}).children('li').css({margin:0,padding:0});
                if (options.height == 0) {
                    obj.children('ul').children('li').each(function() {
                        if ($(this).height() > maxHeight) {
                            maxHeight = $(this).height()
                        }
                    });
                    obj.children('ul').children('li').each(function() {
                        $(this).height(maxHeight)
                    });
                    obj.height(maxHeight * options.showItems)
                } else {
                    obj.height(options.height)
                }
                var interval = setInterval(function() {
                    if (options.direction == 'up') {
                        moveUp(obj, maxHeight, options)
                    } else {
                        moveDown(obj, maxHeight, options)
                    }
                }, options.pause);
                if (options.mousePause) {
                    obj.bind("mouseenter",
                        function() {
                            options.isPaused = true
                        }).bind("mouseleave", function() {
                            options.isPaused = false
                        })
                }
            })
        }
    })(jQuery);

    $('div.ticker').vTicker({
        speed: 1000,
        pause: 3000,
        showItems: 3,
        animation: 'fade',
        mousePause: true,
        height: 168,
        direction: 'up'
    });
    
   $('div.speakersSeriesPartnerLogoTicker').vTicker({
       speed: 1000,
       pause: 5000,
       showItems: 1,
       animation: 'fade',
       mousePause: true,
       height: 105,
       direction: 'up'
   });
});

/* Student Search #jt */

$(document).ready(function() {

    var loading = false;

    $("div#student_search input").live("click", function() {
        if ($(this).val() == lang_search)
            $(this).val("");
    });

    $("div#student_search input").live("blur", function() {
        if ($(this).val() == "")
            $(this).val(lang_search);
    });

    $("div#student_search a").live("click", function() {
        $(this).parent().next("input").val("");
        $("div.student_search_results").slideUp(500);
    });

    $("div#student_search input").live("keypress", function(e) {
        var val = $(this).val();
        var filter = $(this).prev("div").find("select").val();
        var container = '<img src="/media/img/site/placeholder_m_thumb.jpg" alt=""/><div><span><strong>%1</strong></span><br/><span>%3</span></div>';
        if (val.length >= 3 && loading == false) {
            $("div.student_search_results div.result").hide();
            loading = true;
            $.post("/ajax/student_search", {term:val,filter:filter}, function(data) {
                $("div.student_search_results").slideDown((data.length / 2) * 800);
                var type = "";
                var title = "";
                for (var a = 0; a < data.length; a++) {
                    type = data[a]["type"];
                    title = data[a]["title"];
                    if (type == "Company") {
                        type = '<a href="/employers.html">' + type + '</a>';
                        title = '<a href="/employers/profile/' + data[a]["id"] + '.html">' + title + '</a>'
                    } else if (type == "Event") {
                        type = '<a href="/events/list.html">' + type + '</a>';
                        title = '<a href="/events/view/' + data[a]["id"] + '.html">' + title + '</a>'
                    } else if (type == "Job") {
                        type = '<a href="/search/jobs.html">' + type + '</a>';
                        title = '<a href="/jobs/view/' + data[a]["id"] + '.html">' + title + '</a>'
                    }
                    $("div.student_search_results div.result:eq(" + a + ")").html(container.replace("%1", title).replace("%3", type));
                    $("div.student_search_results div.result:eq(" + a + ")").show()
                }
                if (data.length == 0) {
                    $("div.student_search_results div.result:eq(" + 0 + ")").html(container.replace("%1", lang_no_results_found).replace("%3", ""));
                    $("div.student_search_results div.result:eq(" + 0 + ")").show()
                }
                loading = false
            }, "json")
        }
    });

});


/* dataTable extension for sorting german dates #jt */
$(document).ready(function() {
    $.fn.dataTableExt.oSort['gerdate-desc'] = function(a, b) {
        a = a.replace(/^[a-zA-Z]{1,}/, "01.01.2001");
        a = a.split('.');
        b = b.replace(/^[a-zA-Z]{1,}/, "01.01.2001");
        b = b.split('.');
        x = new Date(a.reverse().join("/")).getTime();
        y = new Date(b.reverse().join("/")).getTime();
        return((x < y) ? -1 : ((x > y) ? 1 : 0))
    };
    $.fn.dataTableExt.oSort['gerdate-asc'] = function(a, b) {
        a = a.replace(/^[a-zA-Z]{1,}/, "01.01.2001");
        a = a.split('.');
        b = b.replace(/^[a-zA-Z]{1,}/, "01.01.2001");
        b = b.split('.');
        x = new Date(a.reverse().join("/")).getTime();
        y = new Date(b.reverse().join("/")).getTime();
        return((x < y) ? 1 : ((x > y) ? -1 : 0))
    };
    $.fn.rotateBoxes = function(delay, fadingSpeed) {
        visible_items = $(this).filter(".active");
        invisible_items = $(this).filter(".hidden");
        
        var random_visible = Math.floor(Math.random()*visible_items.length);
        var random_invisible = Math.floor(Math.random()*invisible_items.length);

        // item to replace: visible_items[random_active_items]
        var el_old = $(visible_items[random_visible]);
        var el_new = $(invisible_items[random_invisible]);


        var old_data = [];
        old_data['index'] = el_old.attr('id').substr(4);
        old_data['company_title'] = el_old.find('img').attr('alt');
        old_data['href'] = el_old.attr('href');
        old_data['img_src'] = el_old.find('img').attr('src');
        old_data['img'] = el_old.find('img');
        old_data['style'] = el_old.attr('style');

        var new_data = [];
        new_data['index'] = el_new.attr('id').substr(4);
        new_data['company_title'] = el_new.find('img').attr('alt');
        new_data['href'] = el_new.attr('href');
        new_data['img_src'] = el_new.find('img').attr('src');
        new_data['img'] = el_new.find('img');
        new_data['style'] = el_new.attr('style');

        // now swap both items
        el_old.find('img').fadeOut(fadingSpeed, function() {
            clone = new_data['img'].clone();
            clone.hide();
            $(this).after(clone);
            clone.fadeIn(fadingSpeed);
            $(this).parent('a').attr('href', new_data['href']);
            $(this).parent('a').attr('style', new_data['style']);
            $(this).parent('a').attr('id', 'item' + new_data['index']);
            $(this).remove();

            el_new.attr('id', 'item' + old_data['index']);
            el_new.find('img').attr('alt', old_data['company_title']);
            el_new.attr('href', old_data['href']);
            el_new.attr('style', old_data['style']);
            el_new.find('img').attr('src', old_data['img_src']);

            window.setTimeout(function() {
                $(".TopCompanies a").rotateBoxes(delay, fadingSpeed);
            }, delay);
        });
    };

});

/* Login Button via ENTER */

$(document).ready(function() {


    $("div#jz__flyOutContainerLogin section.jz__home_flyOutContent.jz__home_bgLogin form[name='login'] input").keypress(function(e) {
        if (e.which == 13) // ENTER
            $(this).parent().find("a.jz__home_login").click();
    });

    $(".field_error").live("change", function(){
        if( $(this).hasClass("field_error") ){
            $(this).removeClass("field_error");
            $(this).parent().find("label.field_error").removeClass("field_error");
        }
    });

});

(function($){
        $.fn.divPopup = function(options) {
        var settings = {
            'id' : 'popup_name',
            'width' : 700,
            'params' : null
        }

        if (options) {
            $.extend(settings, options);
        }

        var popID = options.id;
        var popWidth = options.width;

        var what = $('#' + popID);
        var clone = what.clone();

        what.after(clone);

        if (typeof options.params != 'undefined') {
            for (key in options.params) {
                var name = '{\$' + [key] + '}';
                clone.html(clone.html().replace(name, options.params[key]));
            }
        }


        if ($.browser.msie && $.browser.version < 7) {
            $('.popup_block textarea').css('height', '200px');
        }

        clone.fadeIn().css({
            'width': Number(popWidth)
        }).prepend('<a href="" class="close"><img src="/media/img/popup/close_pop.png" class="btn_close" title="Close Window" alt="Close" border="0" /></a>');

        var popMargTop = (what.height() + 80) / 2;
        var popMargLeft = (what.width() + 80) / 2;
        clone.css({
            'margin-top' : -popMargTop,
            'margin-left' : -popMargLeft
        });

        $('body').append('<div id="fade"></div>');

        $('#fade').css({
            'filter' : 'alpha(opacity=80)'
        }).fadeIn();

        return false;
    };
});
