/*
	Created By: Richard Delph
	For: OTL Website v2 2009
	Date: 2009-05-20 10:45
*/

// change this variable to equal the case study image height + reflection height...
var caseStudyPanelHeight = "183px";
var caseStudyTimer;
var scrollTimer;
var pageTitle = 'OTL Marketing';

var contentPanelContainerHtml = '<div id="content-panel-container">\n\
    <div class="bg-top">\n\
        <div class="bg-bottom">\n\
            <a href="#" id="logo-small">OTL</a>\n\
            <a href="#" id="close-content-panel">X</a>\n\
            <div class="clear"></div>\n\
        </div>\n\
    </div>\n\
</div>';

var scrollControlsHtml = '<div id="scroll-controls-{1}" class="scroll-controls">\n\
    <a href="#" class="scroll-up" rel="{2}"><img src="/images/scroll-up.gif" width="23" height="28" /></a><a href="#" class="scroll-down" rel="{2}"><img src="/images/scroll-down.gif" width="23" height="28" /></a>\n\
</div>\n\
<div class="clear"></div>';

$(
	function ($) {
		$body = $('html,body').attr('scrollTop',0);
		$(document).ready(on_document_ready);
	}
);

function on_document_ready(e) {
	
	$contactDetails = $('#contact-details');
	
	// set active nav item and case study panel
	
	var activeNavItemId = $('div#navigation > ul > li > a.selected').attr('id').replace(/nav-/i,'');
	
	$activeCaseStudyPanel = $('#' + activeNavItemId + '.case-study-scroller-panel');
	$activeCaseStudyPanel.css( { 'height':caseStudyPanelHeight, 'display':'block' });
	
	$activeNavItem = $('#nav-' + activeNavItemId);
	
	//clone case studies
	setupCaseStudies();
	
	if ( $activeCaseStudies.length > 0 ) {
		caseStudyScroller();
	}
	
	// set event for nav item clicks
	$('div#navigation > ul > li > a').click(function(e) {
		
		var clickedNavId = $(this).attr('id').replace(/nav-/i,'')
		
		switch(clickedNavId) {
			case 'about':
			
				loadContent($(this).attr('href'));
			
				break;
			default:
				if ( clickedNavId != activeNavItemId ) {

					// highlight active nav item...
					$activeNavItem.removeClass('selected');
					$(this).addClass('selected');
					$activeNavItem = $(this);

					activeNavItemId = clickedNavId;
				

					//animate the panel up and stop the scroller...

					clearTimeout(caseStudyTimer);
					
					unbindCaseStudyEvents();
					
					if ( $activeCaseStudyPanel.height() > 0 ) {
						
						$activeCaseStudyPanel.animate( { 'height': '0px' }, 500, 'easeInOutQuad', function() {

							//set the display property to none or else the next panel appears under the 'active' panel's padding.
							$activeCaseStudyPanel.css('display','none');
							// reset the left of the previous active case study panel
							$activeScroller.css('left','0px');


							//set the active case study panel to the one we're about to animate...
							$activeCaseStudyPanel = $('#' + activeNavItemId + '.case-study-scroller-panel');

							setupCaseStudies();

							if ( $activeCaseStudies.length > 0 ) {
								$activeCaseStudyPanel.animate( { 'height':caseStudyPanelHeight }, 800, 'easeInOutQuad',	function() {
									caseStudyScroller();
								}); // end animation
							}

						}); // end animation
					} else {
						//set the display property to none or else the next panel appears under the 'active' panel's padding.
						$activeCaseStudyPanel.css('display','none');
						// reset the left of the previous active case study panel
						$activeScroller.css('left','0px');


						//set the active case study panel to the one we're about to animate...
						$activeCaseStudyPanel = $('#' + activeNavItemId + '.case-study-scroller-panel');

						setupCaseStudies();

						if ( $activeCaseStudies.length > 0 ) {
							$activeCaseStudyPanel.animate( { 'height':caseStudyPanelHeight }, 800, 'easeInOutQuad',	function() {
								caseStudyScroller();
							}); // end animation
						}
					}	

				} //end if
				
				break;
		}
			
	}) // end click
	
}

function loadContent(href) {
	
	$.ajax({
		url: 'xml/' + href.replace(/#\//i,'') + '.xml',
		global: true,
		type: "GET",
		dataType: "xml",
		success: function(xml) {
			
			// update page title
			/* var newPageTitle = pageTitle + ' - ' + $(xml).find('title').text();
			$('title').html(newPageTitle);
			document.title = newPageTitle; */
		
			// load content panel data
			$('#page-wrapper').append($(contentPanelContainerHtml));
			$('#content-panel-container div.bg-bottom').append($(xml).find('content').text());
			
			fadeContentPanel('in');
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert('Error loading data, please try again.');
		
			if ( $activeCaseStudies.length > 0 ) {
				
				bindCaseStudyEvents();
				caseStudyTimer = setTimeout('scrollCaseStudies(' + 25 + ')',25);
			}
		}
	});
	
}

function fadeContentPanel(dir) {
	
	switch(dir) {
		case 'in':
		
			// clear any timeouts
			clearTimeout(caseStudyTimer);
		
			// insert case study
			$('#content-panel-container div.bg-top').css('display','none');
		
			$('#content-panel-container').css('display','block');

			$('#content-panel-container div.bg-top').fadeIn(500,function() {
				
				$activeCaseStudyPanel.fadeOut(function() {
					//$contactDetails.fadeIn();
				});
				
				$('#content-panel-container div.bg-bottom').animate( {height:'580px'}, 1000, 'easeInOutQuart', function() {
					$('#close-content-panel').fadeIn()
					
					
					// find any divs with text-scroll-wrapper, take their id's, insert scroll controls below them
					// replacing the rel attr value with the div id and bind the events
					
					$('#content-panel-container .text-scroller-wrapper').each(function() {
						var id = $(this).attr('id');
						
						if ( $(this).children('.text-scroller-content').height() > $(this).height() ) {
							// append scroll controls
							$(this).after($(scrollControlsHtml.replace(/\{1\}|\{2\}/gi,id)));
							
							// bind events
							scrollControls = $('#scroll-controls-'+id);
							
							scrollControls.children('.scroll-up').click(function(e) {
								e.preventDefault();
							}).mouseover(function(e) {
								e.preventDefault();
								clearTimeout(scrollTimer);
								scrollTimer = setTimeout('scrollText(\''+id+'\',\'up\',15)',15);
							}).mouseout(function(e) {
								e.preventDefault();
								clearTimeout(scrollTimer);
							});
							
							scrollControls.children('.scroll-down').click(function(e) {
								e.preventDefault();
							}).mouseover(function(e) {
								e.preventDefault();
								clearTimeout(scrollTimer);
								scrollTimer = setTimeout('scrollText(\''+id+'\',\'down\',15)',15);
							}).mouseout(function(e) {
								e.preventDefault();
								clearTimeout(scrollTimer);
							});
							
							scrollControls.fadeIn();
						}
						
					});
					
				});
			});
			
			
			
			// event handler for when close case study is clicked
			$('#close-content-panel').click(function() {
				fadeContentPanel('out');
			});
		
			break;
		case 'out':
		
			$('#close-content-panel').fadeOut();
			
			//$contactDetails.fadeOut(function() {
				$activeCaseStudyPanel.fadeIn();
			//});
			
			
			/* revert to default page title
			$('title').html(pageTitle);
			document.title = pageTitle; */
		
			$('#content-panel-container div.bg-bottom').animate( {height:'67px'}, 1000, 'easeInOutQuart', function() {
			
				$('#content-panel-container div.bg-top').fadeOut(500,function() {
					
					if ( $activeCaseStudies.length > 0 ) {
						
						bindCaseStudyEvents();
						caseStudyTimer = setTimeout('scrollCaseStudies(' + 25 + ')',25);
					}
					
					$('#content-panel-container').remove();	
		
				})
			
			})
		
			break;
	}
}


//function to scroll 'scrollable' items down
function scrollText(id,dir,interval) {
	
	scrollContent = $('#'+id+' .text-scroller-content');
	curTop = parseInt(scrollContent.css('top'));
	
	clearTimeout(scrollTimer);
	
	switch(dir) {
		case 'down':
				if ( scrollContent.height() + curTop >= scrollContent.parent().height() ) {
					scrollContent.css('top',curTop-2);
					scrollTimer = setTimeout('scrollText(\''+id+'\',\''+dir+'\','+ interval +')',interval);
				}
			break;
		case 'up':
				if ( curTop < 0 ) {
					scrollContent.css('top',curTop+2);
					scrollTimer = setTimeout('scrollText(\''+id+'\',\''+dir+'\','+ interval +')',interval);
				}
			break;
	}
	
	
}


function setupCaseStudies() {
	
	$activeCaseStudies = $activeCaseStudyPanel.find(".case-study");
		
	var maxNoVisibleCaseStudies = 5

	// always has to be at least noVisibleCaseStudies + 1 on display for the left scroll to work properly...
	if ( $activeCaseStudies.length <= maxNoVisibleCaseStudies && $activeCaseStudies.length != 0 ) {

		var noToFill = (maxNoVisibleCaseStudies - $activeCaseStudies.length) + 1;

		var j = 0;

		for (var i = 0; i < noToFill; i++) {

			$activeCaseStudyPanel.find('.case-study-scroller').append('<div class="case-study">' + $activeCaseStudies.get(j).innerHTML + '</div>');

			j++;

			if ( j == $activeCaseStudies.length ) { j = 0 }
		}

		$activeCaseStudies = $activeCaseStudyPanel.children().children(".case-study")

	}
		
	if ( $activeCaseStudies.length > 0 ) {
		bindCaseStudyEvents();
	}
	
}

function bindCaseStudyEvents() {
	$activeCaseStudies.find('a').bind('mouseover',caseStudyMouseOver);	
	$activeCaseStudies.find('a').bind('mouseout',caseStudyMouseOut);
	$activeCaseStudies.find('a').bind('click',caseStudyClick);
}

function unbindCaseStudyEvents() {
	// unbind mouseover/mouseout effects for all active case studies
	$activeCaseStudies.find('a').unbind('mouseover');
	$activeCaseStudies.find('a').unbind('mouseout');
	$activeCaseStudies.find('a').unbind('click');	
}

function caseStudyClick(e) {
	
	// put case study thumb back to normal position
	$(this).animate( { 'top':'0px'}, 200, 'linear');

	unbindCaseStudyEvents();
	
	loadContent($(this).attr('href'))

}

function caseStudyMouseOver() {	

	clearTimeout(caseStudyTimer);	
	
	if ( $(this).css('top') == '0px' ) {
		$(this).animate( { 'top':'-10px' }, 200, "linear", function() {
			$(this).css('top','-10px')
		});
	}
	
	
}
function caseStudyMouseOut() {
	
	clearTimeout(caseStudyTimer);
	caseStudyTimer = setTimeout('scrollCaseStudies(' + 25 + ')',25);
	
	$(this).animate( { 'top':'0px' }, 200, "linear", function() {
		$(this).css('top','0px');
	});

}

function caseStudyScroller() {		
	
	$activeScroller = $activeCaseStudyPanel.find("div.case-study-scroller");
	$activeScroller.css('left','0px');
	
	//set the timeout for the scroll function
	clearTimeout(caseStudyTimer);
	caseStudyTimer = setTimeout('scrollCaseStudies(' + 25 + ')',25);

}

function scrollCaseStudies(interval) {
	
	var pixelstoscroll = 1;
	var desinationleft = -190;
	var currentleft = parseInt($activeScroller.css('left'));
	var newleft = (currentleft - pixelstoscroll) + 'px';
	
	if ( currentleft <= desinationleft ) {
		$activeScroller.append($activeScroller.find("div.case-study:first"))
		$activeScroller.css('left','0px')
		caseStudyTimer = setTimeout('scrollCaseStudies(' + interval + ')',interval);		
	} else {
		$activeScroller.css('left',newleft)
		caseStudyTimer = setTimeout('scrollCaseStudies(' + interval + ')',interval);
	}
	
}