var twitterSpeed = 200;
var footerSpeed = 200;
var footerFadeSpeed = 100;
var footerLoadSpeed = 500;
var contentFadeSpeed = 500;
var easing = '0';
var easingArr = new Array('jswing', 'easeInQuad', 'easeOutQuad', 'easeInOutQuad', 'easeInCubic', 'easeOutCubic', 'easeInOutCubic', 'easeInQuart', 'easeOutQuart', 'easeInOutQuart', 'easeInQuint', 'easeOutQuint', 'easeInOutQuint', 'easeInSine', 'easeOutSine', 'easeInOutSine', 'easeInExpo', 'easeOutExpo', 'easeInOutExpo', 'easeInCirc', 'easeOutCirc', 'easeInOutCirc', 'easeInElastic', 'easeOutElastic', 'easeInOutElastic', 'easeInBack', 'easeOutBack', 'easeInOutBack', 'easeInBounce', 'easeOutBounce', 'easeInOutBounce')
var leftOpen = 0;
var clickedEl;
var menuClosed = false;
var showTimer = false;
var elementsReady;
var loadingElements = new Array();
var elementCount;
var content;
var galleryCount = 0;
var galleryIndex = 0;
var galleryInterval;
var galleryFadeTimer = 500000;
var galleryFadeSpeed = 500;
var toggleMenuText = 'Less Details';
var whoFading = false;
var nextFading = '';
var menusHaveBeenOpened = false;

$(document).ready(function () {
    //easing = easingArr[location.hash.substr(1)];
    easing = easingArr[14];

    setupAutoClears();
    setupForms();
    setupTwitterBar();
    setupMenuBar();

    $(window).resize(function () {
        resize();
    });

    resize();

    $('#details').appendTo('#footer');
    $('#moreDetails').click(function () {
        $(this).fadeOut(200, function () {
            $('.cmsFilledArea_1').slideToggle(footerSpeed, function () {
                var t = $('#moreDetails').text();
                $('#moreDetails').text(toggleMenuText).fadeIn(100);
                toggleMenuText = t;
            });
        });
        return (false);
    });

    $('.wwa').click(function () {
        $('.wwa').removeClass('selected');
        $(this).addClass('selected');
    });

    $('.wwaDetails, .wwaAbout').addClass('clearfix');

    var lastIndex = window.location.href.lastIndexOf("/");
    var currentPage = window.location.href.substr(lastIndex);

    $('.contentDiv').css('min-height', '150px');

    setupWhoWeAre();

    if (currentPage.length > 1)
        setupClosedMenu(currentPage);

    setupGallery();
    setupLoading();
});

function setupWhoWeAre() {
    if ($('.contentDiv').length == 0) {
        $('.wwaDetails').css('display', 'block').fadeOut(0);

        $('.wwa').click(function() {
            if (whoFading) {
                nextFading = $(this);
            }
            else {
                if ($('.wwaDetails.selected').length > 0) {
                    var clicked = this;
                    whoFading = true;
                    $('.wwaDetails.selected').removeClass('selected').fadeOut(galleryFadeSpeed, function() {
                        if ($('.wwaDetails.' + $(clicked).attr('id')).length > 0)
                            $('.wwaDetails.' + $(clicked).attr('id')).addClass('selected').fadeIn(galleryFadeSpeed, function() {
                                whoFading = false;
                                if (nextFading.length > 0) {
                                    $(nextFading).trigger('click');
                                    nextFading = '';
                                }
                            });
                    });
                }
                else {
                    whoFading = true;
                    $('.wwaDetails.' + $(this).attr('id')).addClass('selected').fadeIn(galleryFadeSpeed, function() {
                        whoFading = false;
                        if (nextFading.length > 0) {
                            $(nextFading).trigger('click');
                            nextFading = '';
                        }
                    });
                }
            }
        });
    }
    else {
        $('.wwaDetails').css('display', 'block');
    }
}

function setupGallery() {
    if ($('input[id*=fldSectionID]').val() == 1) {
        galleryCount = $('#gallery').children('li').length - 1;
        galleryIndex = Math.floor(Math.random() * galleryCount);

        $('#gallery li').css({
            'position': 'absolute',
            'top': 0,
            'left': 0,
            'display': 'none'
        });

        $('#gallery li:eq(' + galleryIndex + ')').css('display', 'block');
        $('#gallery').css({'display': 'block', 'overflow' : 'hidden'});

        galleryInterval = setInterval('nextGalleryItem("fade");', galleryFadeTimer);
    }
    else {
        galleryCount = $('#gallery li').length;
        galleryIndex = 0;

        $('#gallery li').css({
            'position': 'absolute',
            'top': 0,
            'left': 0
        });

        $('#gallery li').each(function() {
            $(this).css('opacity',0);
        });

        $('#prevGalleryItem').css('visibility', 'hidden').click(function() {
            $('#gallery li:eq(' + galleryIndex + ')').css('zindex', 2).fadeTo(galleryFadeSpeed, 0);
            galleryIndex--;
            $('#gallery li:eq(' + galleryIndex + ')').css('zindex', 1).fadeTo(galleryFadeSpeed, 1);
            $('#nextGalleryItem').css('visibility', 'visible');

            $('#galleryPos').text((galleryIndex + 1) + '/' + galleryCount);

            if (galleryIndex == 0)
                $(this).css('visibility', 'hidden');

            return (false);
        });
        $('#nextGalleryItem').click(function() {
            $('#gallery li:eq(' + galleryIndex + ')').css('zindex', 2).fadeTo(galleryFadeSpeed, 0);
            galleryIndex++;
            $('#gallery li:eq(' + galleryIndex + ')').css('zindex', 1).fadeTo(galleryFadeSpeed, 1);
            $('#prevGalleryItem').css('visibility', 'visible');

            $('#galleryPos').text((galleryIndex + 1) + '/' + galleryCount);

            if (galleryIndex == (galleryCount - 1))
                $(this).css('visibility', 'hidden');

            return (false);
        });

        var gt = readCookie("tags");
        eraseCookie("tags");

        if (gt != null) {
            $('#gallery li').each(function () {
                var tags = $(this).attr('tags').split(",");
                var galleryTags = gt.split(",");

                for (i = 0; i < galleryTags.length; i++) {
                    for (j = 0; j < tags.length; j++) {
                        if (tags[j] == galleryTags[i]) {
                            $(this).prependTo("#gallery");
                            break;
                        }
                    }
                }
            });
        }

        $('#gallery li:first').css('opacity',1);
        $('#gallery').css('display', 'block');
    }
}

function nextGalleryItem(type) {
    if (type == "fade") {
        $('#gallery li:eq(' + galleryIndex + ')').fadeOut(galleryFadeSpeed);
    
        galleryIndex += 1;
        if (galleryIndex > galleryCount)
            galleryIndex = 0;

        $('#gallery li:eq(' + galleryIndex + ')').fadeIn(galleryFadeSpeed);
    }
}

function setupLoading() {
    $('#controls').hide();
    $('#footer').append('<div id="footerLoading"></div>');
    $('#footerLoading').fadeOut(0);
    startLoading();
}

function startLoading() {
    elementCount = 0;
    elementsReady = false;
    /*$('#content').find('img').each(function() {
        addImageToLoad($(this).attr('src'));
    });
    
    content = $('#content').html();
    $('#content').fadeOut(0).html('');*/

    if ($('#gallery img').length > 0) {
        addImageToLoad($('#gallery img:eq(' + galleryIndex + ')').attr('src'));
        $('#gallery img:eq(' + galleryIndex + ')').fadeOut(0);
        clearInterval(galleryInterval);

        $('#footerLoading').fadeOut(0).fadeIn(footerLoadSpeed);
        elementsReady = true;
        checkIfPageAlreadyLoaded();

        if (loadingElements.length == 0)
            stopLoading(true);
    }
}

function stopLoading(instant) {
    $('#controls').show();
    $('#footerLoading').stop(true, false).fadeOut(footerLoadSpeed);
    /*if (instant)
        $('#content').stop(true, false).fadeIn(0).html(content);
    else
        $('#content').fadeIn(contentFadeSpeed).html(content);*/
    if (instant)
        $('#gallery img:eq(' + galleryIndex + ')').stop(true, false).fadeIn(contentFadeSpeed);
    else
        $('#gallery img:eq(' + galleryIndex + ')').fadeIn(contentFadeSpeed);

    if (galleryCount > 1 && $('input[id*=fldSectionID]').val() == 1)
        galleryInterval = setInterval('nextGalleryItem("fade");', galleryFadeTimer);
}

function resize() {
    if ($(window).height() == 0 || $('#container').height() == 0) {
        setTimeout('resize()', 100);
        return false;
    }

	if($(window).height() > $('#container').height())
	{
		$('#footer, #header').css('position','relative');
		$('#container').css({
			'paddingBottom'	:	0,
			'paddingTop'    :   0
		});	
	}
	else
	{
		$('#footer, #header').css('position','fixed');
		$('#container').css({
			'paddingBottom'	: 	'30px',
			'paddingTop'	:	'48px'
		});	
	}	
}

function setupTwitterBar() {
    $("#tweets").tweet({
        join_text: "auto",
        username: "team_newenglish",
        avatar_size: 0,
        count: 3,
        auto_join_text_default: "",
        auto_join_text_ed: "",
        auto_join_text_ing: "",
        auto_join_text_reply: "",
        auto_join_text_url: "",
        loading_text: ""
    });

    $('#twitterExpander').click(function() {
        var state = $('#twitter').attr('state');

        if (state == undefined)
            state = 'closed';

        if (state == 'closed') {
            $('#twitter').width($('#twitter').width()).attr('startWidth', $('#twitter').width());
            $('#twitterText').fadeOut(twitterSpeed, function() {
                $('#twitter').animate({
                    width: '700px'
                }, twitterSpeed, function() {
                    $('#twitterText').attr('startText', $('#twitterText').html()).text($('.twitterFeed li:first').text()).fadeIn(twitterSpeed);
                    $('#twitter').attr('state', 'stretched');
                });
            });
        }
        else if (state == 'stretched') {
            $('#twitterDown, #twitterText').fadeOut(twitterSpeed, function() {
                $('.twitterFeed').css('display', 'block');
                $('#twitter').css('height', 'auto');
                var newHeight = $('#twitter').height();
                $('.twitterFeed').css('display', 'none');
                $('#twitter').animate({
                    'height': newHeight + 'px'
                }, twitterSpeed, function() {
                    $('.twitterFeed').fadeIn(twitterSpeed);
                    $('#twitter').attr('state', 'open');
                });
            });
        }
        else if (state == 'open') {
            $('.twitterFeed').fadeOut(twitterSpeed, function() {
                $('#twitter').animate({
                    'height': $('#twitter').css('min-height')
                }, twitterSpeed, function() {
                    $('#twitter').animate({
                        width: $('#twitter').attr('startWidth')
                    }, twitterSpeed,
                    function() {
                        $('#twitterText').html($('#twitterText').attr('startText')).fadeIn(twitterSpeed);
                        $('#twitterDown').fadeIn(twitterSpeed);
                        $('#twitter').attr('state', 'closed');
                    });
                });
            });
        }

        return false;
    });
}

function setupForms() {
    $(window).keypress(function(e) {
        if (e.which == 13)
            return false;
        else
            return true;
    });
    $('.form').find('input').keydown(function(e) {
        if (e.which == 13) {
            if ($(this).parents('.form').find('.formEnter')[0].tagName.toLowerCase() == 'a')
                window.location = $(this).parents('.form').find('.formEnter').attr('href')
            $(this).parents('.form').find('.formEnter').trigger('click');
        }
    });
}

function setupAutoClears() {
    $(".autoClear").focus(function() {
        if (!$(this).attr('originalVal')) {
            $(this).attr('originalVal', $(this).val());
            $(this).val('');
        }
    }).blur(function() {
        if ($.trim($(this).val()).length == 0) {
            $(this).val($(this).attr('originalVal'));
            $(this).removeAttr('originalVal');
        }
    });
}

function setupMenuBar() {
    $('#footer ul').append('<li class="back"></li>');
    $('#footer ul li.back').css({
        width   :   $('#footer ul li:first').width(),
        //height  :   $('#footer ul li:first').outerHeight(),
        top     :   $('#footer ul li:first').outerHeight()
    });

    prepareMenus($('#footer ul li'));
}

function prepareMenus(el) {
    attachHover($(el).children('a'));

    $(el).click(function () {
        var item, tmpItem;

        clickedEl = $(this);

        if ($(this).parent().parent()[0].nodeName == 'LI') {
            $(this).parent().children('li').removeClass('selected');
            $(this).addClass('selected');
            tmpItem = item = parseInt($(this).parent().parent().attr('item'));

            if ($(this).next().hasClass("innerMenu") && !$(this).hasClass("innerMenu")) {
                var t = $(this);
                var h = parseInt($(this).parent().css('top').substring(0, $(this).parent().css('top').length - 1));

                if ($(this).next().css('display') != 'block') {
                    while ($(t).next().hasClass("innerMenu")) {
                        t = $(t).next();
                        $(t).css('display', 'block');
                        h -= $(t).height();
                        $(t).slideUp(0).slideDown(footerSpeed);
                    }
                    $(this).parent().animate({
                        'top': h
                    }, footerSpeed);
                }
                else {
                    while ($(t).next().hasClass("innerMenu")) {
                        t = $(t).next();
                        h += $(t).height();
                        $(t).slideUp(footerSpeed);
                    }
                    $(this).parent().animate({
                        'top': h
                    }, footerSpeed);
                }
                return false;
            }
        }
        else {
            tmpItem = item = parseInt($(this).attr('item'));
            if (menuClosed) {
                reOpenMenus();
                return false;
            }
            else if (menusHaveBeenOpened) {
                closeMenu('', false);
                return false;
            }
        }

        // Hide the current open menus
        var tmpEl = $('#footer > ul > li.item' + (++tmpItem));
        leftOpen = 0;

        while ($(tmpEl).length > 0) {
            leftOpen++;
            $(tmpEl).children('ul').animate({
                top: $(tmpEl).children('ul').outerHeight() + $('#footer > ul').outerHeight()
            }, footerSpeed, function () {
                leftOpen--;

                if (leftOpen <= 0)
                    openNewMenu();

                $(this).parent().remove();
            });

            tmpItem++;
            tmpEl = $('#footer > ul > li.item' + tmpItem);
        }
        // Closed all of the previously open menus

        if (leftOpen <= 0)
            openNewMenu();

        return false;
    });
}

function openNewMenu() {
    var el = $(clickedEl);
    var item;

    if ($(el).parent().parent()[0].nodeName == 'LI')
        item = parseInt($(el).parent().parent().attr('item')) + 1;
    else
        item = parseInt($(el).attr('item')) + 1;

    if ($(el).hasClass('end'))
        closeMenu(el, true);
    else {
        var el2;

        if ($(el).parent().parent()[0].nodeName == 'LI')
            el2 = $(el).parent().parent();
        else
            el2 = $(el);
        
        if ($(el).children('ul').length > 0) {
            $(el2).after('<li class="item item' + item + '" item="' + item + '"></li>');
            $(el).children('ul').clone().appendTo('li.item' + item); //have it get the item number here
            prepareMenus($('li.item' + item + ' > ul > li'));
        }
            
        $(el2).next('li').children('ul').css({
            display: 'block',
            height: 'auto'
        }).animate({
            top: -$(el2).next('li').children('ul').outerHeight() + $('#footer > ul').outerHeight() - 3
        }, footerSpeed, null, function() {
            $(el).children('li.back').css({
                top: $(el).outerHeight() + $('#footer > ul').outerHeight()
            });
        });
        $(el2).next('li').children('ul').children('li.back').css({
            top: '1000px'
        });
    }
}

function closeMenu(clickedEl, redirect) {
    var item = 1;

    while ($('#footer > ul > li.item' + (++item)).length != 0) {
        leftOpen++;
        $('#footer > ul > li.item' + item).children('ul').animate({
            top: $('#footer > ul > li.item' + item).children('ul').outerHeight() + $('#footer > ul').outerHeight()
        }, footerSpeed, function () {
            menuClosed = true;
            $(this).parent().css({ display: 'none' }).after('<li class="temp-item selected item' + $(this).parent().attr('item') + '"><a href="#">' + $(this).children('li.selected').children('a').text() + '</a></li>');
            $('li.temp-item.item' + $(this).parent().attr('item')).fadeOut(0).fadeIn(footerFadeSpeed).children('a').click(function () {
                reOpenMenus();
            });
            if ($(this).children('li.selected.end').children('a').length > 0 && redirect) {
                var innerMenu = $('li.item2 li.innerMenu.selected');

                if (innerMenu.length > 0) {
                    createCookie("innerMenu", $(innerMenu).children('a').text(), 1);
                    createCookie("tags", $(innerMenu).attr('tags'), 1);
                }

                window.location = $(clickedEl).children('a').attr('href');
            }
        });
    }
}

function attachHover(el) {
    $(el).hover(
        function() {
            jumpIn($(this).parent());
            return false;
        }, function() {
            jumpOut($(this).parent());
            return false;
        }
    );
}

function jumpIn(hoveredElement) {
    var newTop;

    /*if ($(hoveredElement).parent().parent()[0].nodeName == 'LI')
        navTop = -($(hoveredElement).parent().height() - $(hoveredElement).position().top);
    else*/
        navTop = $(hoveredElement).position().top;
    
    $(hoveredElement).parent().children('li.back').stop(true,false).css({
        width   :   $(hoveredElement).outerWidth(),
		display	:	'block'
    }).animate({
        top     :   navTop,
        height  :   $(hoveredElement).outerHeight()
    }, footerSpeed, easing);
}

function jumpOut(hoveredElement) {
    var jumpTop;
	var newHeight = $(hoveredElement).parent().children('li.back').height();

    if ($(hoveredElement).parent().parent()[0].nodeName == 'LI')
        jumpTop = $(hoveredElement).parent().outerHeight() + $('#footer > ul').outerHeight();
    else
	{
        jumpTop = $(hoveredElement).parent().outerHeight();
		newHeight = 0;
	}
    
    $(hoveredElement).parent().children('li.back').stop(true,false).animate({
        top     :   jumpTop,
		height  :   newHeight
    }, footerSpeed, easing, function() {
		$(this).css('display','none');	
	});
}

function reOpenMenus() {
    $('li.temp-item').fadeOut(footerFadeSpeed, function() {
        $('li.item').css('display', 'block').children('ul').each(function() {
            $(this).animate({
                top: -$(this).outerHeight() + $('#footer > ul').outerHeight() - 3
            }, footerSpeed, function() {
                menuClosed = false;
            });
        });
        $(this).remove();
    });
}

function addImageToLoad(src) {
    if (src.charAt(0) == '"')
        src = src.substr(1);

    if (src.charAt(src.length - 1) == '"')
        src = src.substring(0, src.length - 1);

    elementCount++;

    loadingElements.push(new Image());
    loadingElements[loadingElements.length - 1].onload = function() {
        loadingElements.splice(loadingElements.indexOf(this), 1);
        if (elementsReady) {
            if (loadingElements.length == 0)
                stopLoading(false);
        }
    }
    loadingElements[loadingElements.length - 1].src = src;
}

function checkIfPageAlreadyLoaded() {
    var toRemove = new Array();
    for (var i = 0; i < loadingElements.length; i++) {
        if (loadingElements[i].complete) {
            loadingElements[i].onload = null;
            toRemove.push(loadingElements[i]);
        }
    }

    for (i = 0; i < toRemove.length; i++)
        loadingElements.splice(loadingElements.indexOf(toRemove[i]), 1);

    if (navigator.userAgent.toLowerCase().indexOf('opera') != -1) {
        if (loadingElements.length > 0)
            setTimeout('checkIfPageAlreadyLoaded()', 100);
        else
            stopLoading(false);
    }
}

function setupClosedMenu(page) {
    var pageLi;
    var data = readCookie("innerMenu");
    eraseCookie("innerMenu");

    if (data != null) {
        $('#footer ul').find('a[href*="' + page + '"]').each(function () {
            var e = this;

            while ($(e).parent().length > 0) {
                if ($(e).parent().hasClass('innerMenu') && $(e).parent().children('a').text() == data) {
                    pageLi = $(this).parent();
                    break;
                }
                e = $(e).parent();
            }
        });
        $('.innerMenu').css('display', 'block');
    }
    else {
        $('#footer ul').find('a[href*="' + page + '"]').each(function () {
            var e = this;
            var hasInnerMenu = false;

            while ($(e).parent().length > 0) {
                if ($(e).parent().hasClass('innerMenu')) {
                    hasInnerMenu = true;
                    break;
                }
                e = $(e).parent();
            }

            if (!hasInnerMenu) {
                pageLi = $(this).parent();
            }
        });
    }


    var pageLevel = 1;
    var currentLi = pageLi;

    if (currentLi != null && $(currentLi).length > 0) {
        menusHaveBeenOpened = true;
        
        $(currentLi).addClass('selected');
        while ((currentLi = $(currentLi).parent().parent())[0].nodeName == "LI") {
            $(currentLi).addClass('selected');
            pageLevel++;
        }

        currentLi = pageLi;

        while ((currentLi = $(currentLi).parent().parent())[0].nodeName == "LI") {
            $('#footer > ul > li:first').after('<li class="item item' + pageLevel + '" item="' + pageLevel + '" style="display: none;"></li>');
            $(currentLi).children('ul').css({ 'height': 'auto', 'display': 'block' }).clone().appendTo('li.item' + pageLevel);
            $(currentLi).children('ul').css('display', 'none');
            prepareMenus($('li.item' + pageLevel + ' > ul > li'));
            $('li.item' + pageLevel).after('<li class="temp-item selected item' + pageLevel + '"><a href="#">' + $(currentLi).children('ul').children('li.selected').children('a').text() + '</a></li>');
            $('li.temp-item.item' + pageLevel).click(function() {
                reOpenMenus();
                return (false);
            });
            pageLevel--;
        }

        $('#footer > ul > li:first').removeClass('selected');
        $('#footer > ul > li:first > ul').attr('style', '');

        menuClosed = true;
    }
    //$(this).after('<li class="temp-item selected item' + $(this).parent().attr('item') + '"><a href="#">' + $(this).children('li.selected').children('a').text() + '</a></li>');
}

if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, start) {
        for (var i = (start || 0), j = this.length; i < j; i++) {
            if (this[i] === obj) { return i; }
        }
        return -1;
    }
}
