$(document).ready(function() {
	init();
	
	$('#accordion1').accordionza({
		autoPlay: false,
		captionDelay: 1000,
		captionEasing: 'easeOutBounce',
		captionHeight: 60,
		captionHeightClosed: 10,
		navKey: true,
		slideDelay: 4000,
		firstSlide: 'slide5'
	});
	
	$('.slide_handle').click( function () {
		
		if (bFirstClick) {
			// remove the startImage and show '.content' on art tab
			$('.startImage').remove();
			$('#art .content').show();
			
			bFirstClick = false;
		}
		
		//wipe previous gallery;
		cleanUp();
		
		if ($(this).parent().hasClass('gallery')) {
			//load gallery
			loadGallery($(this).parent());
			
		}
		
		// reset about us content
		$('#about-us .description').html($(window.content).find('#about-us description').text());
		$('#about-us h2').html($(window.content).find('#about-us name').text())
		
	});
	
	$('.subtitle').live("click", function () {
		
		//wipe previous gallery;
		cleanUp();
		
		if ($(this).hasClass('subgallery')) {
			//we want to load a sub gallery
			loadGallery($(this));
		} else {
			mainContent = $(this).parent().siblings('.main');
			mainContent.find('.description').html($(window.content).find('subsection[class^="' + $(this).attr("id") + '"]').text());
			mainContent.find('h2').html($(window.content).find('subsection[class^="' + $(this).attr("id") + '"]').attr("name"));
		}
	});
	

				
				$('.slide_caption').live('click', function(){
					$(this).toggleClass('slide_caption_open');
				})

});

function init () {
	bFirstClick = true;
	
	$.ajax({
		type: "get",
		url: "/xml/ai_content.xml",
		dataType: "xml",
		success: parseXml
	});
}

function parseXml (xml) {
	$(xml).find("section").each( function (){
		
		var id = $(this).attr('id');
		var title = $(this).find('name').text();
		var sContentClass = '';
		var sSetClass = "";
		var sSubs = ""; 
		var subSection = $(this).find('subsection');
		
		window.content = xml;

		if (subSection.length > 1) {
		
			sContentClass = "subs subs" + $(this).find("subsection").length;
		
			// loop over subsections and check their type
			subSection.each( function (i){
				sTitleClass = " sub" + (i + 1);
				
				if ($(this).attr("type") == "gallery") {
					sTitleClass = sTitleClass + " subgallery";
				}
				
				sSubs = sSubs + '<div id="' + $(this).attr("class") + '" class="subtitle ' + $(this).attr("class") + sTitleClass + '">' + $(this).attr("name") + '</div>';
			});
			
		} else if (subSection.length == "1" && subSection.attr("type") == "gallery") {
			sSetClass = " gallery";
		}
		
		$section = $('#' + id ).find('.content');
		// load in section data
		$section.html('<div class="subNav">' + sSubs + '</div><div class="main"><h2>' + title + '</h2>'
			+ '<div class="description">' + $(this).find("description").text() + '</div></div>');
		
		$section.parents('li').addClass(sContentClass + sSetClass);

	});
	
	var startImageTotal = 3;
	var randomNumber = Math.round(Math.random()*(startImageTotal-1))+1;
	var imgPath = ('/images/'+randomNumber+'.jpg');
	
	$('#art .content').hide();
	$('#art .slide_content').append('<img class="startImage" src="' + imgPath + '" alt="" \/>');
	$('.startImage').hide().delay(200).fadeIn();
}

function loadGallery (el) {
	$.ajax({
		type: "get",
		url: "/xml/" + el.attr("id") + ".xml",
		dataType: "xml",
		success: function(xml) {
			currentGallery = xml;
			
			$scroller = $('#imageScroller')
			$scroller.addClass(el.attr("id"));
			$scroller.append('<div id="makeMeScrollable"><div class="scrollingHotSpotLeft"></div><div class="scrollingHotSpotRight"></div><div class="scrollWrapper"><div class="scrollableArea"></div></div></div>');
			
			$(xml).find("project").each( function (){
				$('#imageScroller .scrollableArea').append('<span class="imgWrap"><img src="' + $(this).attr("projectThumbnail") + '" alt="'+ $(this).attr("projectName") +'" /></span>');
			});
			
			$("div#makeMeScrollable").smoothDivScroll({
				hiddenOnStart: "true",
				scrollStep: '10'
			});

			$("div#makeMeScrollable").fadeOut().fadeIn('slow');
			
			$scroller.find('img').mouseover( function() {
				if (!$(this).hasClass('activeThumb')) {
					var sSrc = $(this).attr('src');
					
					$(this).attr('src',sSrc.replace('.jpg','-r.jpg'));
					$(this).after('<span class="tooltip"></span>');
					$(".tooltip").html($(this).attr('alt')).css('left',$(this).position().left  + 'px').show();
				}
			}).mouseout( function() {
				if (!$(this).hasClass('activeThumb')) {
					var sSrc = $(this).attr('src');
				
					$(this).attr('src',sSrc.replace('-r.jpg','.jpg'));
					$(".tooltip").fadeOut().remove();
				}
			}).click( function(event) {
				var pos = parseInt($(this).parent().index());
				var currentProject = $(currentGallery).find("project")[pos];
				var emailAddress = '';
				var sGallery = ''
				
				if ($(currentProject).attr("projectEmail") !=undefined) { 
					emailAddress = '<br /><a class="emailLink" href="mailto:' + $(currentProject).attr("projectEmail") +'">' + $(currentProject).attr("projectEmail") +'</a>'; 
				}
				sGallery = '<div id="gallery"><div class="slide_caption"><h2>' + $(currentProject).attr("projectName") + '</h2><p>' + $(currentProject).attr("projectDescription") + emailAddress +'</p></div><div id="slides"><ul></ul></div></div>';
				
				// remove current active thumbnail
				$scroller.find('img').each( function (){
					var sSrc = $(this).attr('src');
					
					$(this).removeClass('activeThumb');
					$(this).attr('src',sSrc.replace('-r.jpg','.jpg'));
				});
				
				// add active thumbnail
				$(this).toggleClass('activeThumb');	
				$(this).attr('src',$(this).attr('src').replace('.jpg','-r.jpg'));
				
				// remove old gallery
				$('#gallery').fadeOut().remove();
				
				// add gallery display to current active slide
				$('.slide_opened .main').fadeOut();
				$('.slide_opened .content').append(sGallery);
				
				// add each gallery image
				$(currentProject).find("picture").each( function (){
					$('#slides ul').append('<li><img src="' + $(this).attr("image") + '" alt="" /></li>');
				});
				
				if ($(currentProject).find("picture").length > 1 ) {
					// we need pagination!
					$('.slide_caption h2').html('<strong>' + $('.slide_caption h2').text() + '</strong>');
					$('.slide_caption h2').append('<div class="expandBox"></div><div class="page"><span class="prev">< prev</span><span class="next">next ></span></div>');
		
					totalImages = $('#gallery img').size();
					currentPos = 1;
					
					$('#gallery img').each( function (){
						//wait until image is loaded
						$(this).load( function () {
							//calculate gallery image positions
							if ($(this).index() != '1') {
								$(this).css('left','-' + $(this).width() + 'px');
							} else {
								$(this).addClass('activePhoto');
							}
						});
					}); 
					
					//grab the width and calculate left value
					var item_width = jQuery('#slides li').outerWidth(); 
					var left_value = item_width * (-1); 
					
					jQuery("#slides ul").css({'width' : jQuery("#slides ul li").length * item_width + "px"});
			
					//move the last item before first item, just in case user click prev button
					jQuery('#slides li:first').before(jQuery('#slides li:last'));
					
					//set the default item to the correct position 
					jQuery('#slides ul').css({'left' : left_value});
					

					
					//if user clicked on prev button
					jQuery('.prev').click(function() {
					
						animationLength = 1200;
						if ($('.slide_caption strong').html() === 'Drawing Board' || $('.slide_caption strong').html() === 'DRAWING BOARD' ) {
							$('#slides').hide();
							animationLength = 0;
						}

						//get the right position            
						var left_indent = parseInt(jQuery('#slides ul').css('left')) + item_width;

						//slide the item            
						jQuery('#slides ul:not(:animated)').animate({'left' : left_indent}, animationLength,function(){    

							//move the last item and put it as first item            	
							jQuery('#slides li:first').before(jQuery('#slides li:last'));           

							//set the default item to correct position
							jQuery('#slides ul').css({'left' : left_value});
							
							currentPos = currentPos - 1;
							if(currentPos < 1) {
								currentPos = totalImages;
							}
							currentImage = jQuery(currentProject).find("picture")[parseInt(currentPos) - 1];
							jQuery('.slide_caption p').html(jQuery(currentImage).attr('description'))
						
							if ($('.slide_caption strong').html() === 'Drawing Board' || $('.slide_caption strong').html() === 'DRAWING BOARD' ) {
								$('#slides').fadeIn();
							}
							
						});

						//cancel the link behavior            
						return false;
							
					});

				 
					//if user clicked on next button
					jQuery('.next').click(function() {
					
						animationLength = 1200;
						if ($('.slide_caption strong').html() === 'Drawing Board' || $('.slide_caption strong').html() === 'DRAWING BOARD' ) {
							$('#slides').hide();
							animationLength = 0;
						}
						
						//get the right position
						var left_indent = parseInt(jQuery('#slides ul').css('left')) - item_width;;
						
						//slide the item
						jQuery('#slides ul:not(:animated)').animate({'left' : left_indent}, animationLength, function () {
							
							//move the first item and put it as last item
							jQuery('#slides li:last').after(jQuery('#slides li:first'));                 	
							
							//set the default item to correct position
							jQuery('#slides ul').css({'left' : left_value});
							
							currentPos = currentPos + 1;
							if(currentPos > totalImages) {
								currentPos = 1;
							}
							currentImage = jQuery(currentProject).find("picture")[parseInt(currentPos) - 1];
							jQuery('.slide_caption p').html(jQuery(currentImage).attr('description'))
						
							if ($('.slide_caption strong').html() === 'Drawing Board' || $('.slide_caption strong').html() === 'DRAWING BOARD' ) {
								$('#slides').fadeIn();
							}
						
						});
								 
						//cancel the link behavior
						return false;
						
					});  

				 
					//if user clicked on the image
					jQuery('#slides li').click(function() {
					
						animationLength = 1000;
						if ($('.slide_caption strong').html() === 'Drawing Board' || $('.slide_caption strong').html() === 'DRAWING BOARD' ) {
							$('#slides').hide();
							animationLength = 0;
						}
						
						//get the right position
						var left_indent = parseInt(jQuery('#slides ul').css('left')) - item_width;
						
						//slide the item
						jQuery('#slides ul:not(:animated)').animate({'left' : left_indent}, animationLength, function () {
							
							//move the first item and put it as last item
							jQuery('#slides li:last').after(jQuery('#slides li:first'));                 	
							
							//set the default item to correct position
							jQuery('#slides ul').css({'left' : left_value});
							
							currentPos = currentPos + 1;
							if(currentPos > totalImages) {
								currentPos = 1;
							}
							currentImage = jQuery(currentProject).find("picture")[parseInt(currentPos) - 1];
							jQuery('.slide_caption p').html(jQuery(currentImage).attr('description'))
						
							if ($('.slide_caption strong').html() === 'Drawing Board' || $('.slide_caption strong').html() === 'DRAWING BOARD' ) {
								$('#slides').fadeIn();
							}
						
						});
								 
						//cancel the link behavior
						return false;
						
					});  
		
					
				} else {
					jQuery('.slide_caption h2').html('<strong>' + jQuery('.slide_caption h2').text() + '</strong>');
					jQuery('.slide_caption h2').append('<div class="expandBox"></div>');
				}
				
			});
			
		}
	});
}

function cleanUp () {
	$('div#makeMeScrollable').fadeOut();
	$('#subcontent').fadeOut().remove();
	$('#imageScroller').html('').removeClass();
	$('#imageScroller').removeClass();
	$('#gallery').fadeOut().remove();
	$('.main').fadeIn();
	$('.tooltip').fadeOut().remove();
}

