// To change which case study is featured on the Case Studies page:
// Count from the top case study, starting at 1;
// Stop counting at the case study you want to feature;
// Type that number after the "=" symbol below.
var featuredCaseStudy = 1;


// Don't edit anything below this comment unless you know what you're doing.

var valueHolder;
var clientTimer;

$(document).ready(function(){
	replaceFonts();
	bindEvents();
	addNewSticker();
	listEmployees();
	interceptEmployeeLinks();
	preloadImages();
	parseForm();
	getCampaignStatistics();
});

$(window).load(function(){
	featureCaseStudy();
	rotateClientLogos();
	positionWorkCaptions();		
})


function getCampaignStatistics() {
	if ($('#numbers_widget').length > 0) {
		$.getJSON("/_statsSvc/getStats", null, function(response) {
			if (response.result == "OK" && response.stats.numCampaigns > 0) {
				$('#num_active_campains').html( numberWithCommas(response.stats.numCampaigns) );
				$('#num_clicks').html( numberWithCommas(response.stats.numClicks) );
				$('#num_ad_impressions').html( numberWithCommas(response.stats.numImpressions) );
				$('#stats_year').html(response.stats.year);
			}
		});
	}

}

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}

function replaceFonts() // renders Futura as javascript vectors in all browsers.
{
	Cufon.replace('nav, h2, h3');
	Cufon.replace('footer > ul', {hover: true});
//	$('.more.solo').parent().css('text-align','right');
}


function bindEvents()
{
	
	// on focus, erase the placeholder value from an <input> element.
	$('footer input').focus(function(){
		valueHolder = $(this).attr('value');
		$(this).attr('value','');
	})

	// on blur, restore the <input> element's old value.
	$('footer input').blur(function(){
		var currentValue = $(this).attr('value');
		if(currentValue == '')
			{ $(this).attr('value',valueHolder); }
	})	
	
	// expand or contract a case study on click
	$('.casestudy h2').click(function(){
		var newHeight;
		var parent = this.parentNode;
		//if it is an expanded, single-line case study, slide it back to 50px tall.
		if($(parent).hasClass('expanded') && !$(parent).hasClass('tall'))
		{
			newHeight = 50;
		}
		// otherwise, it's a two-line case study, e.g. "Reaching Your Facebook Audience".
		// slide it back to 62px.
		else if ($(parent).hasClass('expanded'))
		{
			newHeight = 62;
		}
		else {
			newHeight = parent.scrollHeight;
		}
		toggle(parent,newHeight);
	});
	
	// active the report (SE) login tab
	$('#login-item').show().click(function(){
		if(!$(this).hasClass('tab_open'))
		{
			$(this).addClass('tab_open');
			var menuForm = document.createElement('form');
			var menuContent = $('#footer-login > form').html();
			$(menuForm).html(menuContent);
			$(menuForm).addClass('js_login_form');
			$(menuForm).attr('action','http://reports.guptamedia.com/securityCheck.html');
			$('body').prepend(menuForm);
			$(menuForm).slideDown('fast');
			var uField = $(menuForm).find('input')[0];
			var pField = $(menuForm).find('input')[1];
			uField.id = 'u_tab';
			pField.id = 'p_tab';
			uField.focus();
			
			// bind events for the new form
			$('#u_tab, #p_tab').focus(function(){
				valueHolder = $(this).attr('value');
				$(this).attr('value','');
			})
			$('#u_tab, #p_tab').blur(function(){
				var currentValue = $(this).attr('value');
				if(currentValue == '')
					{ $(this).attr('value',valueHolder); }
			})
			// including a click event this time, since u_tab is focused by default
			$('#u_tab').click(function(){
				valueHolder = $(this).attr('value');
				$(this).attr('value','');
			})
			
			
			

			
			// bind new events

			$('header').click(function(){
				$('#login-item').removeClass('tab_open');
				$(menuForm).slideUp('fast', function(){$(this).remove();});
			})
		}
		else
		{
			$(this).removeClass('tab_open');
			$('.js_login_form').slideUp('fast', function(){$(this).remove();});
		}
	})
	
	// slide the client logos up or down when someone clicks the "Clients" box
	$('#clients h5').click(function(){
		slideClients();
		window.clearInterval(clientTimer) // and stop them from automatically rotating.
	});
	
	//activate client logo tooltips:
	$('#clients img[title]').tooltip({ effect: 'slide'});
	
	// slide "Our Work" captions up and down on hover
	$('.has_figures > figure').mouseenter(function(){
		$(this).find('.brief_description').slideDown('fast');
	}).mouseleave(function(){
		$(this).find('.brief_description').slideUp('fast');
	})
	
	// trigger overlays
	$("img[rel]").overlay({mask: '#000'}); // image lightboxes
	
	if($.browser.msie && $.browser.version < 8) // Contact forms for IE7
	{
		$("a[rel]").overlay({ 
			onBeforeLoad: function() {
				// grab wrapper element inside content
				var wrap = this.getOverlay().find(".holdsContent");
				// load the page specified in the trigger
				wrap.load(this.getTrigger().attr("href"));
			}
		});
	}
	else {	//contact forms for better browsers
		$("a[rel]").overlay({ 
			mask: '#000',
			onBeforeLoad: function() {
				// grab wrapper element inside content
				var wrap = this.getOverlay().find(".holdsContent");
				// load the page specified in the trigger
				wrap.load(this.getTrigger().attr("href"));
			}
		});
	}
	
}

function toggle(what,whereTo)
{
	$(what).animate({
	height: whereTo
	}, 'fast', function() {		// add class "expanded" at animation end
		$(what).toggleClass('expanded');
	})
}

function addNewSticker()
// addNewSticker looks for elements with the class "new" and overlays the 
// sticker-like NEW! button in their top-right corners.
{
	var theseAreNew = $('.new');
	$(theseAreNew).each(function(){
		var sticker = document.createElement('img');
		sticker.src = 'images/new.png';
		sticker.className = 'sticker';
		$(this).prepend(sticker);
	});
}

function listEmployees()
// looks for elements with the class "employee", gets everyone's name, title
// and portrait, and adds them to a list.  This probably only
// runs on the "Who We Are Page" but could be called anywhere.
{
	var employees = $('.employee');
	if (employees.length > 0)
	{
		var list = $('#employee_links');
		$(list).empty();
		
		var holdsPageHeader = document.createElement('section');
		holdsPageHeader.id = 'holds_page_header';
		$(holdsPageHeader).html('<h2>Meet Our Team</h2>');
		$('#content').prepend(holdsPageHeader);
		
		$(employees).each(function(index){
			$(this).css('position','absolute').css('left','0').css('top','0');
			$(this).hide();
			var sectionId = $(this).attr('id');
			var nameText = $(this).find('h2').text();
			var titleText = $(this).find('h3').text();			
			var portraitSrc = $(this).find('img').attr('src');
			var name = document.createElement('p');
			var title = document.createElement('p');
			var portrait = document.createElement('img');
			portrait.alt = 'employee portrait';
			var item = document.createElement('li');
			var link = document.createElement('a');
			link.href = 'who/' + sectionId + '.html';
			item.id = sectionId + '-item';
			$(name).text(nameText);
			$(title).text(titleText);
			portrait.src = portraitSrc;
			name.className = 'name';
			title.className = 'title';
			$(link).append(portrait);
			$(item).append(link).append(name).append(title);
			$(list).append(item);
			
			// This list of employees won't be all that useful unless each
			// item shows information about the relevant employee when clicked.
			// Now is a good time to make that happen.
			$(item).click(function(event){
				event.preventDefault();
				if(!$(this).hasClass('active'))
				{
					var oldEmployee = $('.shown');
					var oldActiveItem = $('li.active');
					var newMinHeight = $(oldEmployee).height();
					oldEmployee.toggleClass('shown');
					oldActiveItem.toggleClass('active');
					var newEmployee = document.getElementById(sectionId);
					$(newEmployee).addClass('shown');
					$(this).addClass('active');
					$(newEmployee).css('min-height',newMinHeight);
					$('#holds_page_header').show();
					Cufon.replace('#holds_page_header');
					$(newEmployee).fadeIn('fast', function(){
						$(oldEmployee).hide()
						});
//					window.location.hash = sectionId;
				}
				
			})
			
			// also, let's add a "Next Employee" button to each employee page but the last one
			if(index < employees.length -1)
			{
				var nextLink = document.createElement('a');
				var nextLinkContainer = document.createElement('p');
				$(nextLink).text('Next');
				$(nextLink).addClass('more');
				$(nextLinkContainer).append(nextLink);
				$(this).append(nextLinkContainer);
				$(nextLink).click(function(){ nextEmployee(); })
			}
		})
		$('#content').height($('#employee-list').height()+50);
		
		
		// and finally, let's accomodate hashes
		var hash = window.location.hash.replace(/#/i,''); // slicing away the "#" symbol
		var mightBeName = document.getElementById(hash);
		
		if(mightBeName != null); // if the sliced hash tag isn't empty
		{
			try { // try to find an element with an ID that matches mightBeName.
				var triggerString = mightBeName.id + '-item';
				var triggerMe = document.getElementById(triggerString)
				$(triggerMe).trigger('click');
				}
			catch(err)
				{
				// do nothing on error
				}
		}
	}
}

function interceptEmployeeLinks(){
	$('#employee_links li').each(function(){
		$(this).click(function(event){
			event.preventDefault();
			// the classes "active" and "shown" are reserved for the employee nav links and <section> elements, respectively.
			if(!$(this).hasClass('active')) 
			{
				var oldEmployee = $('.shown');
				var oldActiveItem = $('li.active');
				var newMinHeight = $(oldEmployee).height();
				oldEmployee.toggleClass('shown');
				oldActiveItem.toggleClass('active');
				var sectionId = this.id;
				sectionId = sectionId.slice(0,-5); // slicing '-item' from the id of the <li>.
				var newEmployee = document.getElementById(sectionId);
				$(newEmployee).addClass('shown');
				$(this).addClass('active');
				$(newEmployee).css('min-height',newMinHeight);
				$(newEmployee).fadeIn('fast', function(){
					$(oldEmployee).hide()
					});
			}
		})
	});
}

function nextEmployee()
{
	var thisEmployee = $('li.active')[0];
	$(thisEmployee).next().trigger('click');
}

function prevEmployee() // this function never got used, but you can call it from the console if you want.
{
	var thisEmployee = $('li.active')[0];
	$(thisEmployee).prev().trigger('click');
}

//slideClients toggles which of the two rows of the Client Logos is visible.
function slideClients(){ 
	var a = $('#first_row');
	var h = $(a).height();
	if(h > 0)
	{
//		toggle(a,0);		
		$(a).animate({
		top: -75,
		height: 0
		}, 'fast');		
	}
	else {
		$(a).animate({
		top: 0,
		height: 75
		}, 'fast');
	}
}

function rotateClientLogos(){
	clientTimer = window.setInterval(slideClients,15000);
}

function preloadImages() {
	var imgObj = new Image();
	var iAr = [];
	iAr[0] = 'images/black_arrow.png';
	iAr[1] = 'images/f-hover.png';
	iAr[2] = 'images/t-hover.png';	
	for (var i in iAr)
	{
		imgObj.src = iAr[i];
		i++;
	}
}

function featureCaseStudy(){ // when you set the variable featuredCaseStudy up at the top, this is the bit that gets affected.
	var feature = $($('.casestudy')[featuredCaseStudy-1]).find('h2');
	$(feature).trigger('click');
}

function positionWorkCaptions(){ // adjusts the height of the "Our Work" captions so they line up with their images.
	$('.work_images img').each(function(index){
		var offset = $(this).height()
		var cap = $('.caption')[index];
		$(cap).css('height',offset + 25);
		if(index == 0)
		{
			var introH = $('.work_intro').height();
			$(cap).css('margin-top',introH);
		}
	});
}

// JEF Code
 
var contactForm;
  
   function parseForm(){
       contactForm = $("form[action='CONTACT']");
       //destroy placeholder values on focus.
       contactForm.find('.floating').find('input').focus(function(){this.value = ''; });
		contactForm.validate({
		 submitHandler: function(form) {
		   handleContactSubmit();
		 }
		});
       // add hidden form fields (this could be done in HTML instead)
       $(contactForm).append("<input type='hidden' name='token' id='token'/>")
       $(contactForm).append("<input type='hidden' name='timestamp' id='timestamp'/>");

       // load token and timestamp.  We could also periodically call this function,
       // to make sure the token doesn't get stale.
       loadTokenAndTimestamp();
       
//       var refresh_timestamp = window.setInterval(loadTokenAndTimestamp,30000)

       // attach submit handler to the contact form
   }

   function loadTokenAndTimestamp(myFunction) {
       $.getJSON("/svc/getToken", null, function(response) {
    	   
    	   if(typeof myFunction == 'function') {
    		   myFunction();
    	   }
    	  
           $("#token").val(response.token);
           $("#timestamp").val(response.timestamp);
       });
   }

   function handleContactSubmit() {
	   
	   //re-up on the token
	   loadTokenAndTimestamp(contactSubmit);
   }
   
   function contactSubmit(){
   		// see if there are any retargeting pixel(s) associated with the contact form.
	   // We'd like to set these regardless of the message submit succeeding, because
	   // the user tried.
	   $("input[name='retargetingPixel']", contactForm).each(function(i) {
		   var url = $(this).val();
		   var img = $("<img height='1' width='1' style='border-style:none;' alt=''/>");
		   img.attr("src", url);
		   $("body").append(img);
	   });
	   
	   // allow for pre-processing of the form data, to allow for additional form fields
	   // that we may want on different contact forms.
	   var formData = {};
	   var formSerialized = contactForm.serializeArray();
	   for (var i=0; i<formSerialized.length; i++) {
		   var key = formSerialized[i].name;
		   var value = formSerialized[i].value;
		   var input = $("[name='" + key + "']", contactForm);
		   var target = input.attr("target");
		   var valSoFar = formData[key];
		   if (target != null && target != "") {
			   valSoFar = formData[target];
			   value = key + ": " + value;
			   key = target;
		   } 
		   if (valSoFar) {
			   formData[key] = valSoFar + "\n" + value;
		   } else {
			   formData[key] = value;
		   }
	   }
	   
       $.ajax({url: "/svc/submitMessage", data: formData, dataType:"json",
           error: function(a,b,c) { onContactError(); },
           success: function(data, textStatus, XMLHttpRequest) {
               if (data.result == "OK") {
                   onContactSuccess();
               } else {
                   onContactError();
               }
           }
       });
   }

   function onContactError() {
//       alert('Sorry! An error occurred. Please email marketing@guptamedia.com');
   }

   function onContactSuccess() {
   		$('.close').trigger('click'); // close any open overlays!
		var errorOverlay = document.createElement('div')
		errorOverlay.className = 'lightbox';
		var errorContent = document.createElement('div');
		errorContent.className = 'holdsContent';
		$(errorContent).append('<h2>Thank you!</h2><h3>Your message was sent successfully.</h3>');
		$(errorOverlay).append(errorContent);
		$('body').append(errorOverlay);
		$('form').each(function(){this.reset()});       
		if($.browser.msie && $.browser.version < 8)
		{
			$(errorOverlay).overlay({
					load: true
				});
		}
		else {
			$(errorOverlay).overlay({
					mask: '#000', // IE7 doesn't play nicely with masking.
					load: true
				});
		}
   }
// End JEF Code -->
