
//--FONT---------------------

//enable cufon
Cufon.replace('.futura', { textShadow: '#fff 1px 1px 0', hover:true });
Cufon.replace('.expertise_detail .services li');
Cufon.replace('#header li a', { fontFamily: 'Centaur',  hover: true, textShadow: '#fff 1px 1px 0' });

Array.prototype.has=function(v){
for (i=0;i<this.length;i++){
if (this[i]==v) return i;
}
return false;
}

var players = new Array();
var initAsset = new Array();



//--SCROLLING----------------

//setup scrolling on a page
function initScroll(conf) {
	
	//get the scrollable instance when there are multiple instances, like during ajax page changing
	var sel = 'div.scrollable';
	var scrollable = $(sel).eq($(sel).length - 1);
	
	//init scroller
	scrollable.scrollable({
		alert: false,
		size: 1,
		easing: 'easeInOutQuint',
		speed: 1200,
		loop: true,
		onBeforeSeek: function(i) {
			
			//beginning reached
			if (i == 0 && this.getPageIndex() == 0) {
				this.end();
				return false;
			}
			
			
			
		},
		onSeek : function() {

			//start videos
			if ($('.work_detail').length) {
				var page = $('div.items').children().eq(this.getPageIndex());
				var assetId = page.attr('id').split('_')[1];

				
				// stop already playing video
				for (var i=0; i < players.length; i++) {
					playerId = players[i];
					if($('#'+playerId).length) {
						if ($('#'+playerId).get(0).sendEvent) {
							$('#'+playerId).get(0).sendEvent('PLAY', false);	
						};				
					}
				};

				if(initAsset[assetId]) {
					initAsset[assetId]();
				}

			}
			
			//set page
			$('ul.pages a').removeClass('active');
			var page = $('ul.pages').children('li').eq(this.getPageIndex());
			while(page.is(':hidden')) {
				page = page.prev();
			};
			page.find('a').addClass('active');
			
			Cufon.refresh();
			
		}
	});
	
	// get handle to the API 
	var api = scrollable.scrollable();
	initScroll.api = api;

	//prev click
	$('.prev').click(function(e) {
		e.preventDefault();
		
		//get page
		var page = api.getPageIndex() - 1;
		if (page < 0) page = api.getPageAmount() - 1;
		
		//set path
		setLinkFromPageIndex(page);

	});
	
	//next click
	$('.next').click(function(e) {
		e.preventDefault();

		//get page
		var page = api.getPageIndex() + 1;
		if (page >= api.getPageAmount()) page = 0;
		
		//set path
		setLinkFromPageIndex(page);
		
	});
	var types = new Array();
	$('ul.pages').find('li').each(function() {
		var type = $(this).attr('id').split('_')[0];
		if(!types.has(type)) {
			types.push(type);
		} else {
			$(this).hide();
		}
	})
	
	//goto page
	$('ul.pages a').click(function(e) {
		e.preventDefault();
		
		//get page
		var el = $(this);
		var ul = el.parents('ul.pages');
		var li = el.parents('ul.pages li');
		var page = ul.children('li').index(li);
		
		//set path
		setLinkFromPageIndex(page);
				
	});
	
	//Attach Omniture here.
	//sc_Track();
	$.gaTracker('UA-9707382-1');
	
}

//change scroll page, called from deep links
function changeScrollPage(url, now) {
	
	//get the page
	if (url.indexOf('/page/') > 0) var page = url.substr(url.indexOf('/page/') + 6, 1);
	else var page = 1;
	
	//update the page
	if (now == true) initScroll.api.seekTo(page - 1, 200);
	else initScroll.api.seekTo(page - 1);
}

//--DEEP LINKS--------------

//set link from a page value
function setLinkFromPageIndex(page) {
	
	//vars
	page += 1;
	var path = removePage($.address.path());
	
	//if homem head slides, don't do pagination
	if (path == '/') {
		initScroll.api.seekTo(page - 1);
		return;
	}
	
	//change page
	if (page > 1) path += '/page/' + page;
	$.address.value(path)
}

//swtich page
function transition(new_url, old_url) {
	
	if(players) {
		players = new Array();
	}
	
	//get the old and new pages
	var sel = '#content div.content_view';
	var old_page = $(sel).eq($(sel).length-1);
	$(sel).after("<div class='content_view'></div>");
	var new_page = $(sel).eq($(sel).length-1);
	
	//animation properties
	if (old_url) var duration = 1200;
	else var duration = 0;
	var easing = 'easeInOutQuint';
	if (new_url == '/home' || old_url.substr(0,6) == '/work/' || old_url.substr(0,6) == '/news/' || old_url.substr(0,12) == '/contact/id/') var change = '-'+'700px'; //new_page.height()+'px'
	else var change = '700px'; //old_page.height()+'px'
	
	//animate old page
	$('#content').css({position:'relative'});
	old_page.css({position:'absolute'});
	old_page.animate({top : '-='+change}, duration, easing, function() { old_page.remove(); });
	
	//show loader
	$('#wrapper').prepend('<div id="loader">Loading</div>');
	$('#loader').css({opacity: 0});
	setTimeout(function() {
		if (old_url) $('#loader').animate({opacity : 1}, 300)
	}, 400);

	//show new page
	var showNewPage = function() {		
		
		//animate new page
		new_page.animate({top : '-='+change}, duration, easing);
		
		//update the logo color
		var css_class = new_page.children('div').attr('class');
		$('#header_container').removeClass();
		if (css_class) $('#header_container').addClass(css_class);
		else $('#header_container').removeClass();
		
		//update the page title
		var title = new_page.children('div').attr('title');
		if (title) $.address.title('Mering Carson | '+title);
		else $.address.title('Mering Carson');
	
		//update cufon (must happen before height is calculated)
		Cufon.refresh();
		
		//resize the outside for specific sections
		if (!transition.original_height) {
			transition.original_height = $('#content').height();
			transition.offset = $('#footer').css('top').substr(0, 3) - transition.original_height;
		}
		if (new_page.find('.news .news_item').length) { // -- only for news
			$('#content').animate({height : new_page.height()+'px'}, duration);
			$('#footer').animate({top : (new_page.height() + transition.offset + 20) + 'px'}, duration); 
		} else if(new_page.find('.expertise_detail #replace').length) {
			$('#content').animate({height : new_page.height()+'px'}, duration);
			$('#footer').animate({top : (new_page.height() + transition.offset + 20) + 'px'}, duration); 
		} else if(new_page.find('.meringology #replace').length) {
			$('#content').animate({height : new_page.height()+'px'}, duration);
			$('#footer').animate({top : (new_page.height() + transition.offset + 20) + 'px'}, duration); 
		} else {
			$('#content').animate({height : transition.original_height+'px'}, duration);
			$('#footer').animate({top : (transition.original_height + transition.offset) + 'px'}, duration); 
		}
	
		//update scroll
		initScroll();
		
		//apply deep links to the new page
		new_page.find('a[rel*=address:]').address();
		
		//goto a subpage
		if (new_url.indexOf('/page/') > 0) changeScrollPage(new_url, true);
		else if (new_url.indexOf('/id/') > 0) changeContactPage(new_url, true);
		
		//add contact form toggling
		addFormToggle();
		
	}

	//request the html
	new_page.load(removePage(new_url), false, function(){
		
		//hide loader
		setTimeout(function() {
			$('#loader').animate({opacity : 0}, 300, null, function() {$('#loader').remove()});	
		}, 400);
		
		//balls
		new_page.css({position:'absolute'});
		new_page.css({top : change});
		
		//do the transition
		setTimeout(showNewPage, 250);
		
	});
		
}

//add deep links
function initDeepLinks() {

	//on startup
	$.address.init(function(event) {

	//on page change
	}).change(function(event) {
		
		//get the target
		var old_url = $.address.last_url; if (!old_url) old_url = '';
		var new_url = event.value;
		$.address.last_url = event.value;
		if (event.value == '/' || (event.value == '/home' && !old_url)) {
			$('#content .content_view').removeAttr('style'); //reomve the autohide from _content.phtml
			return;
		}
		
		//if a simple page transition, run it now
		if (removePage(new_url) == removePage(old_url)) {
			if (new_url.indexOf('/contact') != -1) changeContactPage(new_url);
			else changeScrollPage(new_url);
			return;
		}
		
		//dont allow fast clicking (not useful unless we also track how many clicks are queued)
		var d = new Date()
		if ($.address.last_click && (d.getTime() - $.address.last_click) < 1000) {
			//setTimeout(function() {transition(new_url, old_url);}, 1200 - (d.getTime() - $.address.last_click));
			return false;
		}
		$.address.last_click = d.getTime();
		transition(new_url, old_url);
	});
}

//--CAREERS ANIMATION-------

//add contact form toggles
function addFormToggle() {
	$('.contact form input:text, .contact form textarea').toggleVal({
		focusClass : 'text_focus',
		changedClass : 'text_entered'
	});
}

//goto a contact page
function changeContactPage(url, now) {
	
	//settings
	var duration = now == true ? 100 : 1200;
	var easing = 'easeInOutQuint';
	
	//get id
	if (url.indexOf('/id/') != -1) var id = url.substr(url.indexOf('/id/') + 4);
	else return;
	
	//transition
	$('.contact .infinite').animate({left: '-530px'}, duration, easing);
	$('.contact .info').animate({opacity: 0}, duration);
	setTimeout(function() {
		$('.contact .page_nav').slideDown(duration/4);
	}, duration - duration/4);
	
	//show the correct slide
	$('.contact .career div').fadeOut(0);
	$('.contact .career div#career_'+id).fadeIn(duration/4);
	selectedCareer = $('.contact .career div#career_'+id).eq(0);
	
	var new_height = selectedCareer.height() + 300;
	if (new_height < (transition.original_height + 300)) {new_height = transition.original_height + 300; }
	
	$('#content').animate({height : new_height+'px'}, duration);
	$('.contact_info').animate({height : new_height+'px'}, duration);
	
	var calculatedTop = (selectedCareer.height()+200 + transition.offset);
	var footerTop = calculatedTop < transition.original_height + 100 ? transition.original_height + 100 : calculatedTop;
	
	$('#footer').animate({top: footerTop+'px'}, duration);
	
	
	//set active state
	$('.contact .careers p a').removeClass('active');
	$('.contact .careers p a[rel="'+id+'"]').addClass('active');
	//$(this).addClass('active');
	Cufon.refresh();
	
}

//add careers actions
function initCareers() {
	
	//settings
	var duration = 1200;
	var easing = 'easeInOutQuint';
	
	//switch to job description
	$('.contact .careers p a').live('click', function(e) {
		e.preventDefault();
		
		//prevent double
		if ($(this).hasClass('active')) return;
		
		//goto the contact page
		var id = $(this).attr('rel');
		$.address.value('/contact/id/'+id)
		
	});
	
	//return to contact page
	$('.contact .page_nav').live('click', function(e) {
		e.preventDefault();
		
		//transition
		$('.contact .infinite').animate({left: '0px'}, duration, easing);
		$('.contact .info').animate({opacity: 1}, duration);
		$('.contact .page_nav').slideUp(duration/2);
		
		//remove active state
		$('.contact .careers p a').removeClass('active');
		Cufon.refresh();
		
		//update page
		$.address.value('/contact')
	});
	
	//setup form toggle
	addFormToggle();
	
	//capture form submission
	$('.contact form').live('submit', function (e) {
		e.preventDefault();
		
		//require fields
		if ($('#name').val() == '' 
			|| $('#name').val() == $('#name').data("defText") 
			|| $('#email').val() == '' 
			|| $('#email').val() == $('#email').data("defText")) {
			$('#message').text('You must fill in the required fields.').fadeOut(0).fadeIn();
			return false;
		}
		
		//check specific fields
		var validator = $('.contact form').validate({
			rules: {
				email: {
					required: true,
					email: true
				}
			},
			errorLabelContainer: '#message'
		});
		if (validator.element('#email') == false) {
			//$('#message').text('Not a valid email address.').fadeOut(0).fadeIn();
			return false;
		}

		//strip defaults
		$(this).find(".toggleval").each(function() {
			if($(this).val() == $(this).data("defText")) {
				$(this).val("");
			}
		});
		
		//submit
		$.post($(this).attr('action'), $(this).serializeArray(), function(data, textStatus) {
			if (data == 'success' && textStatus == 'success') $('#message').text('Thank you for contacting us.').fadeOut(0).fadeIn();
			else $('#message').text('There was a server error.').fadeOut(0).fadeIn();
		}, "text");
		
		//hide the fields
		$('.contact form li:not(#message)').fadeOut(200);
	});
	
}

//--MISC---------------------

//add site credits
function initFooter() {
	$('#footer a').click(function() {
		$('#footer a').replaceWith('Site by <a href="http://bkwld.com" target="_blank">BKWLD</a>');
		return false;
	});
}

//get a url without the page
function removePage(url) {
	if (url.indexOf('/page/') > 0) return url.substr(0, url.indexOf('/page/'));
	else if (url.indexOf('/id/') > 0) return url.substr(0, url.indexOf('/id/'));
	else return url;
}

//--STARTUP-------------------

//trigger for inital page
$(function() {
	initScroll();
	initDeepLinks();
	initFooter();
	initCareers();
});

Shadowbox.init({
	skipSetup: true,
	useSizzle: false,
	players: ["swf", "img"]
});

//--OMNITURE------------------

$.mc = {};

function sc_Track() {
	sc_clear();
	sc_reload();
	
	var s_code=s_mc.t();
	$.get(s_code,function(){return false});
}


function sc_clear() {
	//Clear Omniture variables before making another call.
	s_code="";
	s_mc.pageName="";
	s_mc.channel="";
	s_mc.pageType="";
	s_mc.prop1="";
	s_mc.prop2="";
	s_mc.prop3="";
	s_mc.prop4="";
	s_mc.prop5="";
	s_mc.prop6="";
	s_mc.prop7="";
	s_mc.prop47="";
	s_mc.prop48="";
	s_mc.prop49="";
	s_mc.prop50="";
	s_mc.campaign="";
	s_mc.events="";
	s_mc.eVar1="";
	s_mc.eVar2="";
	s_mc.eVar3="";
	s_mc.eVar4="";
	s_mc.eVar5="";
	s_mc.eVar47="";
	s_mc.eVar48="";
	s_mc.eVar49="";
	s_mc.eVar50="";
}

function sc_reload() {
	//Get new variables.
	if($.mc.pageName) s_mc.pageName=$.mc.pageName;
	if($.mc.channel) s_mc.channel=$.mc.channel;
	if($.mc.pageType) s_mc.pageType=$.mc.pageType;
	if($.mc.prop1) s_mc.prop1=$.mc.prop1;
	if($.mc.prop2) s_mc.prop2=$.mc.prop2;
	if($.mc.prop3) s_mc.prop3=$.mc.prop3;
	if($.mc.prop4) s_mc.prop4=$.mc.prop4;
	if($.mc.prop5) s_mc.prop5=$.mc.prop5;
	if($.mc.prop6) s_mc.prop6=$.mc.prop6;
	if($.mc.prop7) s_mc.prop7=$.mc.prop7;
}