var HERO_INDEX = 0;
var HERO_INTERVAL = null;
var CUR_SLIDE = 1;

$(document).ready(function(){
	if ($('#content-footer').children().length)
		$('#content-footer').show();
});

// Wait until all images / css have loaded before prefetching other images
$(window).load(function(){
	preFetch();
});

function startHeroSwitcher()
{
	HERO_INTERVAL = setInterval(nextHero, 4000);
}

// pre-load non-displayed images so that when they are accessed, they are quick to display
var arrPrefetch = [];
var prefetchedImages = [];
function preFetch()
{
	// load the css hero background images
	if (globals.heroes)
	{
		for (var i in globals.heroes)
			if (globals.heroes[i].img)
				arrPrefetch.push("/site_media/uploads/case_studies/hero/"+ globals.heroes[i].img);
		setTimeout(startHeroSwitcher, 1000);
	}
	
	// append images that have been specified in global's prefetch array
	if (globals.prefetch && globals.prefetch.length > 0)
		arrPrefetch = arrPrefetch.concat(globals.prefetch);
	
	for (var i = 0; i < arrPrefetch.length; i ++)
	{
		tmp = new Image();
		tmp.src = arrPrefetch[i];
		prefetchedImages.push(tmp);
	}
}

function startFGISlideshow()
{
	// Don't do anything if the slideshow is already showing.
	if (!HERO_INTERVAL)
		return

	clearInterval(HERO_INTERVAL);
	HERO_INTERVAL = null;

	$('#home-overlay').css({ backgroundColor: globals.heroes[HERO_INDEX].b });
	$('#home-overlay').show();
	$('#callout').fadeOut();
	$('#home-overlay').animate({ opacity: 1 }, { duration: 'fast', complete: function(){
		$('link[rel*=style]').each(function() {
			if (/hero\.css/.test(this.href))
				this.disabled = true;
		});
		$('#home-overlay').animate({ opacity: 0 }, { duration: 'fast', complete: function(){ $('#home-overlay').hide(); $('#slides').fadeIn(); $('#slide1').fadeIn(); $('#slideToggleRight').fadeIn(); } });
	} });
}

function nextSlide()
{
	$('#slideToggleLeft').fadeIn();

	if (CUR_SLIDE < 6)
	{
		CUR_SLIDE ++;

		if (CUR_SLIDE == 6)
			$('#slideToggleRight').fadeOut();
		$('#slide' + (CUR_SLIDE - 1)).fadeOut({ complete: function(){ $('#slide' + CUR_SLIDE).fadeIn(); } });
	}
}

function prevSlide()
{
	$('#slideToggleRight').fadeIn();

	if (CUR_SLIDE > 1)
	{
		CUR_SLIDE --;

		if (CUR_SLIDE == 1)
			$('#slideToggleLeft').fadeOut();
		$('#slide' + (CUR_SLIDE + 1)).fadeOut({ complete: function(){ $('#slide' + CUR_SLIDE).fadeIn(); } });
	}
}

function checkValidEmailAddress(emailInput)
{
	if (validators.email.regex.test(emailInput.value))
		$('#quick_submit').fadeIn();
	else
		$('#quick_submit').fadeOut();
}

function doQuickContact()
{
	REST("contact", { 'email': $('#quick_contact_email').val(), 'ajax': 1, 'quick_contact': 1 }, function(data){ trackVirtual("/homepage_contact_success/"); $('#slide6 p.input').slideUp(); $('#quick_contact_sub_message').fadeOut(); $('#slide6 .thanks').fadeIn(); });
	return false;
}

function doContact()
{
	form = validate([
		{id: "contact_name", alias: "name", validators: ["allowed_chars", {regex: new function(){ this.test = function(strInput){ return !/^name$/i.test(strInput) } }}]},
		{id: "contact_email", alias: "email", validators: ["email"]},
		{id: "contact_message", alias: "message", validators: [{regex: new function(){ this.test = function(strInput){ return !/^message$/i.test(strInput) } }}]}
	]);
	if (!form.isValid)
	{
		alertInvalidForm(form);
		$('.robot').hide();
		robotWriter('#contact-error');
		robotInsultState = 1;
	}

	if (form.isValid && !($('#attachment').val()))
	{
		clearErrors(form, true);
		form.values.ajax = 1;
		REST("contact", form.values, function(data){ trackVirtual("/contact/contact_success/"); });
		$('.robot').hide();
		if (robotInsultState > 0)
			robotWriter('#contact-success2');
		else
			robotWriter('#contact-success');
		robotInsultState = 0;
		return false;
	}
	return form.isValid;
}

function trackVirtual(url)
{
	if (globals.isGAEnabled)
		_gaq.push(['_trackPageview', url]);
}

function doComment()
{
	form = validate([
		{id: "comment_name", alias: "name", validators: ["allowed_chars"]},
		{id: "comment_email", alias: "email", validators: ["email"]},
		{id: "comment_comment", alias: "comment"},
		//{id: "comment_url", alias: "url", validators: ["url"], required: false},
	]);
	if (!form.isValid)
	{
		alertInvalidForm(form);
		$('#comment-error').slideDown();
	}

	else
	{
		$('#comment-error').hide();
		clearErrors(form, true);
		form.values.ajax = 1;
		form.values.entry_id = $('#entry_id').val();
		//form.values.user_ip = $('#uip').val();
		//form.values.user_agent = $('#uag').val();
		//form.values.subscribe = $('#subscribe')[0].checked ? 1 : 0;
		REST("comment", form.values, function(data){ $('#comment-success').slideDown(); });
	}
	return false;
}


typewriterTimeout = null;
typewriterText = null;
var robotInsultState = 0;
function robotWriter(elementId, index)
{	
	var index = index || 0;
	if (index == 0)
	{
		typewriterText = $(elementId).html();
		$(elementId).empty();
		$(elementId).show();
		clearTimeout(typewriterTimeout);
	}

	var useString = typewriterText.substring(0, index);
	var delay = 30;
	var curChar = typewriterText.substr(index, 1);
	if (/[^a-z0-9\ _]/.test(curChar))
		delay = 100;
	$(elementId).html(useString);
	if(index < typewriterText.length)
		typewriterTimeout = setTimeout(function(){robotWriter(elementId, index + 1)}, delay);
}

function checkClientPortalForm()
{
	form = validate([ {id: "username"}, {id: "password"} ]);
	if (!form.isValid)
		alertInvalidForm(form);
	return form.isValid
}
function checkClientPortalForgotPasswordForm()
{
	form = validate([ {id: "email", validators: ["email"]} ]);
	if (!form.isValid)
		alertInvalidForm(form);
	return form.isValid
}
function nextHero(){ HERO_INDEX = (((HERO_INDEX + 1) >= globals.heroes.length) ? 0 : HERO_INDEX + 1); switchHero(HERO_INDEX); }
function switchHero(heroIndex)
{
	var curHero = globals.heroes[heroIndex];

	$('#home-overlay').show();
	//$('#callout h2').fadeOut({complete: function(){$(this).html(curHero.title);}}).fadeIn();//).html('lll');
	$('#home-overlay').animate({ opacity: 1, backgroundColor: curHero.b }, { complete: function(){
		$('link[rel*=style]').each(function() {
			if (/hero\.css/.test(this.href))
				this.disabled = true;
			if (this.title == curHero.s)
				this.disabled = false;
			$('#callout h2').html(curHero.title);
		});
		$('#callout a').attr('href', '/case-studies/' + curHero.s + '/');

		$('#home-overlay').animate({ opacity: 0 }, { duration: 'slow', complete: function(){ $('#home-overlay').hide(); } });
	} });
}

var curInfoboxState = '';
function getLeadershipDetails(domElement, id) { getDetails('leadership', domElement, id); }
function getServiceDetails(domElement, id) { getDetails('service', domElement, id); }
function getDetails(strType, domElement, id, callback)
{
    var infobox = $(domElement).parent().next();
    var infoboxArrow = $('#infobox-arrow');
    if (curInfoboxState == domElement.id)
    {
        infoboxArrow.animate({ top: (infoboxArrow.position().top + infoboxArrow.height()) }, { 'duration': 'normal', complete: function(){
            infoboxArrow.hide();
            infobox.slideToggle('fast');
        } });
        curInfoboxState = '';
    }
    else
    {
        callback = typeof(callback) == "function" ? callback : function(){};
        REST('get_'+ strType +'_details', { 'id': id },
            function(responseText){
                var arrowX = $(domElement).offset().left + Math.ceil($(domElement).width() / 2) - 10;
                if (infobox.css('display') == 'block') // clicked on a widget in the same row as an already opened widget
                {
                    var tmp = infobox.find('.inner');
                    tmp.animate({ opacity: 0 }, { complete: function(){
                        tmp.html(responseText);
                        tmp.animate({ opacity: 1 });
                        infoboxArrow.animate({ 'left': arrowX }, { 'duration': 'fast' });
                        callback();
                    }});
					if (infoboxArrow.css("display") == "none")
						infoboxArrow.css({ 'top': (infobox.position().top + infoboxArrow.height()) + 'px', 'left': arrowX + 'px' }).show().animate({ 'top': infobox.position().top + 5 }, { 'duration': 'normal' });
                }
                else
                {
                    if (curInfoboxState && $(".infobox").length) // clicked on a widget in a different row from an already opened widget
					{
						infoboxArrow.hide();
						$('.infobox').hide();
					}
					infobox.find('.inner').html(responseText);
					infobox.slideDown('fast', function(){ infoboxArrow.css({ 'top': (infobox.position().top + infoboxArrow.height()) + 'px', 'left': arrowX + 'px' }).show().animate({ 'top': infobox.position().top + 5 }, { 'duration': 'normal' }); });
                }
            },
            { type: 'get', dataType: 'html' });
        curInfoboxState = domElement.id;
    }
}

function quickModal(strOut)
{
	modalBox(strOut, { 'pin': false });
}

