var PREMIUM = 200;

$(function() {
	var menus = $("#menu a, #menu div:not(.active)");
	var submenus = $(".submenu");
	var timeouts = [];

	function initilize() {
		menus.hover(menuOverHandler, menuOutHandler);
		submenus.hover(submenuOver, submenuOut);
		loadImages();
		team();
		links();
		checkQuote();
	}
	
	function checkQuote()
	{
		if(window.location.hash.search("quote")!=-1)
			$(".quote").addClass("blue");
	}
	
	function links() {
		var expr = new RegExp('http://');
		$('a').each (function() {
			if (expr.test($(this).attr('href'))) $(this).attr('target','_blank');
		});
		var link = $('div.lex a');
	}

	function menuOverHandler() {
		menuOver($(this));
	}

	function menuOutHandler() {
		menuOut($(this));
	}

	function menuOver(menu) {
		deselectMenu(menus.not(menu));
		menu.stop();
		menu.animate({
			backgroundColor : "#a3c74c"
		}, PREMIUM);

		var submenuId = menu.data("submenu");
		var submenu = $("#" + submenuId);
		if (submenu)
			showSubmenu(submenu, menu);
	}

	function showSubmenu(submenu, menu) {
		submenus.not(submenu).fadeOut(PREMIUM);

		if (timeouts[submenu.attr("id")])
			clearInterval(timeouts[submenu.attr("id")]);
		if (submenu.is("visible"))
			return;
		submenu.fadeIn(PREMIUM);
		var offset = menu.offset();

		offset.top = offset.top + menu.height();
		submenu.offset(offset);

		var line = submenu.find(".line");
		line.width(menu.width());
	}

	function menuOut(menu) {
		menu.stop();

		var submenuId = menu.data("submenu");
		if (submenuId) {
			var submenu = $("#" + submenuId);
			timeouts[submenu.attr("id")] = setTimeout(function() {
				deselectMenu(menu);
				hide(submenu);
			}, PREMIUM);
		} else {
			deselectMenu(menu);
		}

	}

	function deselectMenu(menu) {
		if (menu.hasClass("active"))
			return;
		menu.stop();
		menu.animate({
			backgroundColor : "#eaeaea"
		}, PREMIUM);
	}

	function hide(submenu) {
		submenu.fadeOut(PREMIUM);
	}

	function submenuOver() {
		var menuId = $(this).data("menu");
		menuObj = $("#" + menuId);
		menuOver(menuObj);

	}

	function submenuOut() {
		var menuId = $(this).data("menu");
		menuObj = $("#" + menuId);
		menuOut(menuObj);
	}

	function imageSort(a, b) {
		var aa = parseInt($(a).attr('order'));
		var bb = parseInt($(b).attr('order'));
		if (aa < bb)
			return -1;
		if (aa > bb)
			return 1;
		return 0;
	}

	function loadImages(section) {
		if (!section) {
			$.get($('#banner').data('url'), '', function(slides) {
				var images = [];
				$(slides).find('img').each(function() {
					images[images.length] = this;
				});
				images.sort(imageSort);
				for (i = 0; i < images.length; i++) {
					$('#slide').append(
							'<div data-id="'+$(images[i]).attr('order')+'"><img src="' + $(images[i]).attr('src') + '"></div>');
					$('#slide div img').last().load(function() {
						$(this).parent().addClass('loaded');
					});
				}
				getActive().show();
				
				setTimeout(switchImages, 4000);
			}, 'xml');
		}
	}

	function team() {
		$('#site.team #contentInner ul.team li div.content h2.name').click(
				showTeamDetail);
		$('#site.team #contentInner ul.team li img').click(
						showTeamDetail);
	}

	function showTeamDetail() {
		
		var li = $(this).closest("li");
		//$.scrollTo(li, 200);
		if (!$(li).hasClass('active')) {
			hideTeamDetail();		
			li.addClass('active');
			$(li).find('div.content').prepend('<a class="close" href="#"></a>');
			$(li).find('div.content a.close').click(hideTeamDetail);
			$(li).find('div.content div.detail').slideDown(100, function(){$.scrollTo(li, 200);});
			$(li).find('div.content h2.name').unbind('click');
			$(li).find('div.content h2.name').click(hideTeamDetail);
			$(li).find('img').unbind('click');
			$(li).find('img').click(hideTeamDetail);
			$(li).find('img').animate({width: 149, height: 149}, 100);
		}
		//return false;
	
	}

	function hideTeamDetail() {
		var li = $('#site.team #contentInner ul.team li.active');
		$(li).find('img').animate({width: 109, height: 109}, 100);
		$(li).find('div.detail').slideUp(100,function () {
			var li = $(this).parent().parent();
			$(li).find('div.content a.close').remove();
			$(li).removeClass('active');
			$(li).find('img').unbind('click');
			$(li).find('img').click(showTeamDetail);
			$(li).find('h2.name').unbind('click');
			$(li).find('h2.name').click(showTeamDetail);
		});
		//return false;
	}
	
	function getActive()
	{
		var active;
		$('#slide div').each(function(){
			if($(this).data("id")==$.cookie('slide'))
				active = $(this);
		});
		
		if(!active)
			active = $('#slide div').first();
		
		return active;
		
	}

	function switchImages() {
		active = $('#slide div.active');
		if ($(active).length == 0)
		{
			active = getActive();
		}
			
		next = $(active).next();
		if ($(next).length == 0)
			next = $('#slide div').first();

		if (($(next).hasClass('loaded')) && (active != next)) {
			$(active).fadeOut(4000, null, function() {
				$(this).removeClass('active');
			});
			$(next).fadeIn(4000, null, function() {
				$(this).addClass('active');
			});
			$.cookie('slide', $(next).data("id"));
			//switchImages();
		}
		setTimeout(switchImages, 8000);
	}
	
	initilize();
});

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
