var ie6 = false;

$(document).ready(function(){
	
	// Open links with http in a new window.
	$("a[href^='http://']").not("a[href^='http://kofiannanfoundation.org']").not("a[href^='http://www.kofiannanfoundation.org']").click(function(){
			window.open(this.href,'external');
			return false;
	});
	
	
	// Header dropdown navigation.
	var timeouts = new Array();
	var tabs = $('#header .menu-name-primary-links li.expanded');
	tabs.bind('mouseenter', (function(){
       	clearTimeout(timeouts[tabs.index(this)]);
   		$(this).children('a').addClass('tab-over');
		$(this).children('ul').slideDown('fast');
	})).bind('mouseleave', (function(){
		var obj = $(this);
		timeouts[tabs.index(this)] = setTimeout(function(){ 
			obj.children('a').removeClass('tab-over');
			obj.children('ul').slideUp('fast');
	    }, 150); 		
	}));
	
	/*if($('body').hasClass('page-newsroom')) {
		$('#header li.news-amp-media li.photos a').addClass('active-tab');
		var items = $('#header li.news-amp-media ul a, #footer li.news-amp-media ul a');
		items.click(function(){
			var index = items.index(this) % 6;
			$('ul#newsroom-tabs li:eq('+index+') a').trigger('click');
		});
	}*/
	
	
	// Splash slideshow (front).
	var is_paused = false;
	$('body.front .view-splash .view-content').cycle({ 
		timeoutFn: function(currSlideElement, nextSlideElement, options, forwardFlag){
			return is_paused ? 0 : 10000;
		},
		delay: 5000,
		cleartypeNoBg: true,
		slideExpr: '.views-row',
		pager: 'foo',
		pagerClick: function(zeroBasedSlideIndex, slideElement){
			is_paused = true;
		},
		before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
			$('body.front .view-splash ul.splash-pager a').removeClass('selected');
			$('body.front .view-splash ul.splash-pager li:eq(' + $('body.front .view-splash .views-row').index(nextSlideElement) + ') a').addClass('selected');
		},
		after: function(){
			if(ie6) DD_belatedPNG.fix('.splash .info');
		},
		pagerAnchorBuilder: function(index, slide){ 
			// return selector string for existing anchor 
			return 'body.front .view-splash ul.splash-pager li:eq(' + index + ') a'; 
		}
	});
	
	
	// Splash slideshow (others).
	$('body.not-front .view-splash .view-content').cycle({ 
		cleartypeNoBg: true,
		slideExpr: '.views-row',
		timeout: 10000
	});
    
    
	// Newsroom featured slideshow.
	var is_paused = false;
	$('#block-views-newsroom_featured-block_2 .view-content').cycle({
		timeoutFn: function(currSlideElement, nextSlideElement, options, forwardFlag){
			return is_paused ? 0 : 10000;
		},
		delay: 5000,
		cleartypeNoBg: true,
		pagerEvent: 'mouseover',
		pager: 'foo',
		pagerClick: function(zeroBasedSlideIndex, slideElement){
			is_paused = true;
		},
		before: function(currSlideElement, nextSlideElement, options, forwardFlag){
			$('#block-views-newsroom_featured-block_1 .views-row').removeClass('selected');
			$('#block-views-newsroom_featured-block_1 .views-row:eq(' + $('#block-views-newsroom_featured-block_2 .views-row').index(nextSlideElement) + ')').addClass('selected');
		},
		pagerAnchorBuilder: function(index, slide){ 
			// return selector string for existing anchor 
			return '#block-views-newsroom_featured-block_1 .views-row:eq(' + index + ')'; 
		}
	});
	
	$('#block-views-newsroom_featured-block_1 .view-content > div').mouseover(function(){
		$(this).addClass('selected');
		$(this).siblings().removeClass('selected');
	});
	
	
	// Newsroom AJAX grid.
	var currType = 'photos';
	var currView = 'new';
	var currTopic = 'all';
	var currDate = 'all';
	var currPage = 0;
	var filters = $('#newsroom-filters');
	var topicFilter = $('#newsroom-topic-filter');
	var monthFilter = $('#newsroom-month-filter');
	var yearFilter = $('#newsroom-year-filter');
	var filterSubmit = $('#newsroom-filters li.submit a');
	var filterReset = $('#newsroom-filters li.reset a');
	var loading = $('#newsroom-loading');
	
	var date = new Date();
	var month = date.getMonth() + 1;
	var year = date.getYear() + 1900;
	
	var height = $('#newsroom-grid').height();
	
	$('ul#newsroom-tabs a').click(function(){
		var href = $(this).attr('href').substr(1);
		var clickedType = href.split('/')[0];
		if(clickedType != currType) {
			$(this).parent('li').addClass('selected');
			$(this).parent('li').siblings().removeClass('selected');
			currType = clickedType;
			$('#newsroom-filters h3').html('Filter ' + $(this).children('span').children('b').html() + ':');
			var index = $('ul#newsroom-tabs a').index(this);
			setNewsroomActiveItem(index);
			loadGrid();
		} else
			return false;
	});
	
	filterSubmit.click(function(){
		currView = 'all';
		currPage = 0;
		loadGrid();
	});
	
	filterReset.click(function(){
		currView = 'new';
		currTopic = 'all';
		currDate = 'all';
		currPage = 0;
		loadGrid();
	});
	
	$('#newsroom-filters select').change(function(){
		if(yearFilter.children('option:selected').attr('class') == 'all' || parseInt(yearFilter.children('option:selected').attr('class')) == year) {
			if(parseInt(monthFilter.children('option:selected').attr('class') * 1) > month)
				yearFilter.children('option:eq(2)').attr('selected', 'true');
			else if(monthFilter.children('option:selected').attr('class') != 'all')
				yearFilter.children('option:eq(1)').attr('selected', 'true');		
		}
		currTopic = topicFilter.children('option:selected').attr('class');
		var newm = monthFilter.children('option:selected').attr('class');
		var newy = yearFilter.children('option:selected').attr('class');
		currDate = newy + (newm == 'all' ? '' : '-' + newm);
		updateFilters();
		updateTabs();
	});
	
	function loadGrid() {
		$('#newsroom-grid').animate({height:height, opacity:0}, 'fast', function(){
			loading.height(height);
			loading.show();
		});
		var args = currType;
		if(currType != 'contact')
			args += '/' + currView + '/' + currTopic + '/' + currDate;
		if(currView == 'all')
			args += '?page=' + currPage;
		$.get('/newsroom/ajax/' + args, function(data, status) {
			loading.hide();
			$('#newsroom-grid').html(data);
			$('#newsroom-grid').animate({height:'100%', opacity:1}, 'fast');
			if(currType == 'contact')
				filters.hide();
			else
				filters.show();
			setCellHeights();
			setGridHeight();
			registerEvents();
			updateFilters();
			updatePager();
			updateTabs();
			addMediaOverlays();
		});
	}
	
	function updateFilters() {
		topicFilter.children('option.' + currTopic).attr('selected', true);
		monthFilter.children('option.' + currDate.split('-')[1]).attr('selected', true);
		yearFilter.children('option.' + currDate.split('-')[0]).attr('selected', true);
		var href = '#' + currType + '/all/' + currTopic + '/' + currDate;
		filterSubmit.attr('href', href);
		filterReset.attr('href', '#' + currType + '/new/all/all');
		if (currView == 'all') {
			$('#newsroom-filters h3').html('You filtered by:');
			filterReset.parent('li').css('display', 'inline');
		} else {
			$('#newsroom-filters h3').html('Filter ' + $('ul#newsroom-tabs li#tab-' + currType + ' b').html() + ':');
			filterReset.parent('li').hide();
		}
	}
	
	function updatePager() {
		$.each($('.view-newsroom ul.pager a'), function(){
			var href = $(this).attr('href');
			var args = '#' + currType + '/all/' + currTopic + '/' + currDate;
			if(href.indexOf('?page=') != -1)
				args += '/' + href.split('?page=').pop();
			$(this).attr('href', args);
		});
	}
	
	function updateTabs() {
		$.each($('ul#newsroom-tabs a'), function(){
			if($(this).parent().attr('id') != 'tab-contact') {
				var args = $(this).attr('href').substr(1).split('/');
				args[1] = currView;
				args[2] = currTopic;
				args[3] = currDate;
				$(this).attr('href', '#' + args.join('/'));
			}
		});
	}
	
	function registerEvents() {
		$('.view-newsroom .view-content > div').not('.clearboth').mouseover(function(){
			$(this).addClass('selected');
		});
		$('.view-newsroom .view-content > div').not('.clearboth').mouseout(function(){
			$(this).removeClass('selected');
		});
		$('.view-newsroom ul.pager a').click(function(){
			var args = $(this).attr('href').split('/');
			currPage = args.length == 5 ? args.pop() : 0;
			loadGrid();
		});
		$('body.page-newsroom .see-all a').click(function(){
			currView = 'all';
			loadGrid();
		});
	}
	
	function setGridHeight() {
		height = $('#newsroom-grid').height();
	}
	
	function setCellHeights() {
		var maxHeight = 0;
		$.each($('.view-newsroom .view-content > div').not('.clearboth'), function(){
			if($(this).height() > maxHeight) maxHeight = $(this).height();
		});
		$('.view-newsroom .view-content > div').not('.clearboth').height(maxHeight + 80);
	}
	
	function setNewsroomActiveItem(index) {
		$('#header .menu-name-primary-links li.news-amp-media ul a').removeClass('active-tab');
		$('#header .menu-name-primary-links li.news-amp-media ul a:eq(' + index + ')').addClass('active-tab');
	}
	
	function addMediaOverlays() {
		$('.views-field-field-youtube-video-embed img, .views-field-field-flickr-photoset-embed img, .views-field-field-thumb-fid img').after('<span class="media-overlay"></span>');
	}
	
	if(location.hash.length > 1) {
	    var hash = location.hash.substr(1);
		var args = hash.split('/');
		currType = args[0];
		$('ul#newsroom-tabs li').removeClass('selected');
		$('ul#newsroom-tabs li#tab-'+currType).addClass('selected');
		var index = $('ul#newsroom-tabs li').index($('ul#newsroom-tabs li#tab-'+currType));
		setNewsroomActiveItem(index)
		if (args.length >= 4) {
			currView = args[1];
			currTopic = args[2];
			currDate = args[3];
			currPage = args[4];
		}
		loadGrid();
	} else {		
		setCellHeights();
		registerEvents();
		addMediaOverlays();
	}
	
	
	// Newsroom featured area.
	$('#block-views-newsroom_featured-block_1 .view-content > div').mouseover(function(){
		$(this).addClass('selected');
		$(this).siblings().removeClass('selected');
	});
	
	
	// Forms
	$('.view-signup input.form-text').focus(function(){
		if($(this).val() == 'Email address...') { $(this).val(''); }
	}).blur(function(){
		if ($(this).val() == '') { $(this).val('Email address...'); }
	});
	
	$('.view-signup input.form-submit').click(function(){
		var field = $('.view-signup input.form-text');
		var value = field.val();
		var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if(value == '' || !regex.test(value)) {
			field.addClass('error');
			return false;
		}
	});
	
	$('body.page-contact .form textarea').keyup(function(){
		limitChars(this, 300, 'span#char-count');
	});

	
	$('#header .views-exposed-form input.form-text').focus(function(){
		if($(this).val() == 'Search...') { $(this).val(''); }
	}).blur(function(){
		if ($(this).val() == '') { $(this).val('Search...'); }
	}).val('Search...');
	
	
	
	if($('#views-exposed-form-custom-advanced-search-page-1 .search-advanced').length){
		
		$('#views-exposed-form-custom-advanced-search-page-1 .search-advanced legend a').click(function(e){
			$('#views-exposed-form-custom-advanced-search-page-1 .search-advanced .fieldset-wrapper').toggle('fast');
			return false;
		})
		
	}
	
	
	
	

});


function limitChars(input, limit, target) {
	var text = $(input).val(); 
	var length = text.length;
	
	if(length >= limit) {
		if(length == limit) $(target).html('0');
		$(input).val(text.substr(0,limit));
		return false;
	} else {
		$(target).html(limit - length);
		return true;
	}
}
	
function fixPNGs() {
	ie6 = true;
	DD_belatedPNG.fix('.splash .info, ul.splash-pager li a, .media-overlay');
}



