/*===================================	
common.js
www.sasdesign.co.uk
by Julien Decaudin http://www.juliendecaudin.com @ SAS
03/2011
===================================*/

//Apply the Javascript-enabled styles (hidding expandable boxes for instance)
$('html').addClass('js');

/************* GLOBAL VARIABLES *************/
/* BROWSER CHECK */
var ie6Check = false;

/* SEARCH PANEL */
var searchSpeedOpen = 200;
var searchSpeedClose = 300;

/* MAIN NAVIGATION */
var mainNavTimer;
var mainNavTimerDuration = 0;
var mainNavPaddingRight = 15;

/* FILTERS DROPDOWN */
var filterTimer;

/* EXPANDABLE CONTENT */
var expandSpeedOpen = 200;
var expandSpeedClose = 300;

/* PAGE SCROLL */
var pageScrollSpeed = 600;
var pageScrollOffset = -150;

/* HEADER SWITCH */
/*var headerSwitchTimer;
var headerSwitchTimerDuration = 400;
var headerSwitchSpeed = 200;
var headerBlockerDelay = 800;*/

/* PEOPLE LISTING */
var peopleSpeedHover = 100;
var peopleSpeedOut = 250;
var peopleDisabledOpacity = 0.5;

/* FEED LISTING */
var feedMoreSlideSpeed = 200;
var feedMoreRevealSpeed = 200;
var nextFeedList;
var nextFeedHolderId;
var nextLinkMore;

$(document).ready(function () {
	/* PAGE ID */
	var pageId = $('body').attr('id');

	if (pageId == 'InsightPage') {
		$('.scroll_normal').localScroll({ duration: pageScrollSpeed, offset: pageScrollOffset });
		$('.scroll_reduced').localScroll({ duration: pageScrollSpeed, offset: -130 });
	} else {
		$('#page_nav, #content .module').localScroll({ duration: pageScrollSpeed, offset: pageScrollOffset }); // init the page nav smooth scrolling
	};

	/* BROWSER CHECK */
	if ($.browser.msie && $.browser.version == "6.0") {
		ie6Check = true;
	};

	externalLink();

	$('.accordion').hoverAccordion({
		onClickOnly: true,
		speed: 0,
		keepHeight: false
	});

	/*////////////////////////////////////// INIT */
	InitMainNav();
	InitFilterNav();
	InitSections();
	InitListing('.module_people');
	//InitListing('.module_client');     

	if (document.location.hash != '') {
		if ($(document.location.hash).length > 0) {
			$.scrollTo(document.location.hash, 0, { offset: pageScrollOffset }); //init page scroll if anchor tag is available
			//HideHeader();
		}
	}

	$('.saslide').each(function () {
		if ($(this).parent().hasClass('counter')) {
			$(this).saslide({
				counter: true,
				debug: false
			});
		} else {
			$(this).saslide({
				debug: false
			});
		}
	});

	/*////////////////////////////////////// INTERACTIONS */
	/* SEARCH PANEL */
	/* click the search link */
	$('#main_nav li.search a').click(function () {
		OpenSearchPanel();
		return false;
	});

	/* click the close button */
	$('#main_search a.link_close').click(function () {
		CloseSearchPanel();
		return false;
	});

	/* click out of the opened panel */
	$(document).click(function (e) {
		var clicked = $(e.target);
		if (!clicked.is('#main_search') && !clicked.parents().is('#main_search')) {
			CloseSearchPanel();
		}
	});

	/* EXPANDABLE CONTENT */
	$('a.link_expand').click(function () {
		link = $(this);
		var content_expand = $('#content_expand_' + link.attr('id').split('link_expand_')[1]);

		if (link.hasClass('opened')) {
			//CLOSING
			link.removeClass('opened');
			content_expand.slideUp(expandSpeedClose);
		} else {
			//OPENING
			link.addClass('opened');
			content_expand.slideDown(expandSpeedOpen, function () {
				//scroll to the bottom of the page when opening the footer
				if (link.parents('#footer').length > 0) {
					$.scrollTo('#anchor_bottom', pageScrollSpeed);
				}
			});
		}
		return false;
	});

	/* HEADER SWITCH */

	/*$(window).scroll(function () {
	window.clearTimeout(headerSwitchTimer);
	if ($(window).scrollTop() > 85) {
	HideHeader();
	} else {
	ShowHeader(true);
	}
	});

	$('#header_mini').mouseover(function () {
	window.clearTimeout(headerSwitchTimer);
	ShowHeader(false);
	});

	$('#header').mouseleave(function () {
	if ($(window).scrollTop() > 85) {
	headerSwitchTimer = window.setTimeout('HideHeader(false)', headerSwitchTimerDuration);
	}
	}).mouseover(function () {
	window.clearTimeout(headerSwitchTimer);
	});*/


	/* MORE FEED LINK */
	$('#link_more_feed').click(function () {
		var feedUrl = $(this).attr('href');
		nextLinkMore = null;

		//show loading message
		$('#loading').show();

		$.ajax({
			url: feedUrl,
			type: "GET",
			dataType: "html",

			success: function (html) {
				//get the HTML of the filtered projects and the updated more feed link
				nextFeedList = $(html).find('.feed_holder .section_static');
				nextFeedHolderId = $(html).find('.feed_holder').attr('id');

				if ($(html).find('#link_more_feed').length > 0) {
					nextLinkMore = $(html).find('#link_more_feed');
				}
			},

			complete: function () {
				//update current list
				$('.feed_holder .section_static:last').removeClass('section_last');

				//append the new feed list
				$('.feed_holder').append('<div id="' + nextFeedHolderId + '" class="next_feed_holder" style="display:none"><div class="cache"></div></div>');
				$('.next_feed_holder').append(nextFeedList);


				//Preload new list images before revealing the items
				var arrayImages = new Array();
				$('.next_feed_holder .section_static .column_half_right img').each(function (n) {
					arrayImages[n] = $(this).attr('src');
				});

				if (arrayImages.length > 0) {
					$.preLoadImages(arrayImages, function () {
						RevealFeedItems();
					});
				} else {
					RevealFeedItems();
				}
			},

			error: function () {
				//called when there is an error
			}
		});
		return false;
	});
});

//--------------------------------------------- SECTIONS */
function InitSections() {
	$(window).load(
        function () {
        	//Set the min-height/height of static sections depending of the content
        	$('div.section_static').each(function () {
        		if ($(this).find('img.profile').length > 0) {
        			var imageHeight = $(this).find('img.profile').height();
        			if (ie6Check == true) {
        				$(this).find('.content_holder').css('height', imageHeight);
        			} else {
        				$(this).find('.content_holder').css('min-height', imageHeight);
        			};
        			$(this).find('img.profile').css('position', 'absolute');
        		}
        	});
        });

	if ($('#content').hasClass('section_manual')) {
		//remove sections if not found in the page navigation (for manually .net page sections)
		$('#content div[class^=section_]').each(function () {
			var sectionId = $(this).attr('id');

			if ($('#page_nav a[href=#' + sectionId + ']').length == 0) {

				$(this).hide();
			}
		});
	}
}

//--------------------------------------------- MAIN NAV */
function InitMainNav() {
	//Open the subnav on click
	/*$('#main_nav > li').click(function () {
	window.clearTimeout(mainNavTimer);
	$(this).find('div.dd_outer').show();
	if ($(this).find('div.dd_outer').length) {
	$(this).addClass('hover');
	}
	$(this).find('div.dd_outer a').click(function () {
	var link = $(this).attr('href');
	location.href = link;
	});
	if ($(this).hasClass('dropdown')) {
	return false;
	}        
	});*/

	//Close the subnav on hover
	$('#main_nav > li').hover(function () {
		if (!$(this).hasClass('hover')) {
			HideSubnav();
		}
		mainNavTimer = window.setTimeout('HideSubnav("' + $(this).attr('id') + '")', mainNavTimerDuration);
	});

	//Open the subnav on rollover
	$('#main_nav > li').hoverIntent(function () {
		window.clearTimeout(mainNavTimer);
		HideSubnav();
		$(this).find('div.dd_outer').show();

		if ($(this).find('div.dd_outer').length) {
			$(this).addClass('hover');
		}
	},
    function () {
    	if ($(this).find('div.dd_outer').length) {
    		mainNavTimer = window.setTimeout('HideSubnav("' + $(this).attr('id') + '")', mainNavTimerDuration);
    	} else {
    		$(this).removeClass('hover');
    	}
    });

	//deactivate the click on links with subnav
	$('#main_nav > li.dropdown > a').click(function () {
		return false;
	});
}

function HideSubnav(current_id) {
	if (arguments.length > 0) {
		$('#' + current_id).find('div.dd_outer').hide();
		$('#' + current_id).removeClass('hover');
	} else {
		$('#main_nav div.dd_outer').hide();
		$('#main_nav > li').removeClass('hover');
	}
}

//--------------------------------------------- SEARCH PANEL */
function OpenSearchPanel() {
	var searchPanel = $('#main_search');
	if (!searchPanel.is(':visible')) {
		searchPanel.css('display', 'block').stop().animate({
			opacity: 1
		}, searchSpeedOpen, function () {
			//focus on the search input 
			searchPanel.find('input#main_search_keyword').focus();
		});
	}
}

function CloseSearchPanel() {
	var searchPanel = $('#main_search');

	if (searchPanel.is(':visible')) {
		searchPanel.animate({
			opacity: 0
		}, searchSpeedClose, function () {
			searchPanel.hide();
		});
	}
}

//--------------------------------------------- HEADER SWITCH */
//function HideHeader() {
//    $('#header').fadeOut(headerSwitchSpeed);
//    HideSubnav();
//    $('#header_mini').fadeIn(headerSwitchSpeed);
//}

//function ShowHeader(headerTop) {
//    if (headerTop) {
//        $('#header').addClass('header_top');
//    } else {
//        $('#header').removeClass('header_top');
//    }
//    $('#header_mini').fadeOut(headerSwitchSpeed);
//    //$('#header_blocker').show();
//    $('#header').fadeIn(headerSwitchSpeed);
//    //window.setTimeout("$('#header_blocker').hide();", headerBlockerDelay);
//}

//--------------------------------------------- LISTING */
function InitListing(moduleClass) {
	$(window).load(
        function () {
        	$(moduleClass).each(function () {
        		var moduleWidth = $(this).innerWidth();
        		var moduleHeight = $(this).innerHeight();
        		var cache = $(this).find('.cache');
        		cache
                    .css('opacity', 0)
                    .width(moduleWidth)
                    .height(moduleHeight)
                    .hide();

        		if ($(this).find('a').length > 0) {
        			cache.css('cursor', 'pointer');
        		}
        	});
        });

	$(moduleClass).hover(function () {
		var currentModuleId = $(this).attr('id');
		$(moduleClass).each(function () {
			if ($(this).attr('id') != currentModuleId) {
				$(this).find('.cache').show().stop().animate({
					opacity: peopleDisabledOpacity
				}, peopleSpeedHover);
			}
		});
	}, function () {
		$(moduleClass).find('.cache').stop().animate({
			opacity: 0
		}, peopleSpeedOut, function () {
			$(this).hide();
		});
	});
}

function RevealFeedItems() {
	//hide loading message
	$('#loading').hide();

	//set the feed holder cache dimensions
	$('.next_feed_holder .cache').width($('.feed_holder').width());
	$('.next_feed_holder .cache').height($('.feed_holder').height());

	$('.next_feed_holder').show();

	//refresh Cufon
	//Cufon.refresh('h2');

	//reload Twitter buttons
	IncludeScript("http://platform.twitter.com/widgets.js");

	//reveal the next items
	$('.next_feed_holder .cache').fadeOut(feedMoreRevealSpeed, function () {
		$('.next_feed_holder').attr('class', '');
		//scroll at the top of the new items
		$.scrollTo('#' + nextFeedHolderId, pageScrollSpeed, { offset: pageScrollOffset });
	});

	//update more feed link
	if (nextLinkMore != null) {
		$('#link_more_feed').attr('href', nextLinkMore.attr('href'));
	} else {
		$('#link_more_feed').hide();
	}
}

//--------------------------------------------- FILTER NAV */
function InitFilterNav() {
	//Open the subnav on click
	$('#filter_nav > li').click(function () {
		window.clearTimeout(filterTimer);
		$(this).find('div.dd_outer').show();

		$(this).find('div.dd_outer a').click(function () {
			var link = $(this).attr('href');
			location.href = link;
		});

		if ($(this).hasClass('dropdown')) {
			return false;
		}
	});

	//Close the subnav on hover
	$('#filter_nav > li').hover(function () {
		filterTimer = window.setTimeout('HideFilterSubnav("' + $(this).attr('id') + '")', mainNavTimerDuration);
	});
}

function HideFilterSubnav(current_id) {
	if (arguments.length > 0) {
		$('#' + current_id).find('div.dd_outer').hide();
	} else {
		$('#filter_nav div.dd_outer').hide();
	}
}

//--------------------------------------------- UTILS */
function IncludeScript(scriptUrl) {
	// Change requests to be sent synchronous
	$.ajaxSetup({ async: false });

	// Loads and executes a local JavaScript file
	$.getScript(scriptUrl);

	// Restore requests to be sent asynchronous
	$.ajaxSetup({ async: true });
}

function externalLink() {
	$('.external').click(function () {
		var link = $(this).attr('href');
		window.open(link);
		return false
	});
}
