var Work = Class.create({
	initialize: function(s)
	{
		this.id = s['Work']['id'];
		this.path = s['Image']['image_path'];
		this.url_path = s['Work']['Category']['name'] + '/' + s['Work']['url_name'];
		this.category = s['Work']['Category']['name'];
		this.work = s['Work']['name'];
		
		CARL.log('id: ' + this.id + ' path: ' + this.path + ' category: ' + this.category + ' work: ' + this.work);
	}
});

var WorkSlide = Class.create({

	initialize: function (slideData)
	{
		CARL.log('constructor called');
		this.wait = 4000;
		this.fadeIn = null;
		this.fadeOut = null;
		this.slides = new Array();
		this.lazySlides = new Array();
		this.slideIndex = 0;
			
		ctr = 0;
		slideData.evalJSON().each(function(slide, index)
		{
			// only load up 5 slides into the rendering page so as not to bog the page
			// down with a bunch of hidden image downloads.
			if(ctr++ < 5) {
				CARL.log('slide processed ' + ctr);
				this.slides.push(new Work(slide));
			}
			// the rest get placed in a lazySlides list to be meted out one at a time
			// to make a large collection of slides look seamless
			else
			{
				CARL.log('lazy slide processed');
				this.lazySlides.push(new Work(slide));
			}
			
		}, this);
	},

	startSlide: function ()
	{
		CARL.log('startSlide called');
		firstSlide = this.randomWork();
		$('slide_' + firstSlide.id).show();
		
		CARL.log('reveal ' + 'slide_category_' + firstSlide.id);
		$('slide_category_' + firstSlide.id).show();
		
		if ($('slide_work_' + firstSlide.id) != undefined)
		{
			$('slide_work_' + firstSlide.id).show();
		}
		
		this.fadeOut = firstSlide;
		
		setInterval(this.swapFade.bind(this), this.wait);
	},
	
	swapFade: function ()
	{
		this.fadeIn = this.randomWork();
		CARL.log('next slide ' + this.fadeIn.id);
		
		Effect.Fade('slide_' + this.fadeOut.id, { duration:1, from:1.0, to:0.0 });
		Effect.Fade('slide_category_' + this.fadeOut.id, { duration:1, from:1.0, to:0.0 });
		
		if ($('slide_work_' + this.fadeOut.id) != undefined)
		{
			CARL.log('fade out: ' + this.fadeOut.id);
			Effect.Fade('slide_work_' + this.fadeOut.id, { duration:1, from:1.0, to:0.0 });
		}
		
		Effect.Appear('slide_' + this.fadeIn.id, { duration:1, from:0.0, to:1.0});
	    Effect.Appear('slide_category_' + this.fadeIn.id, { duration:1, from:0.0, to:1.0});
	
		if ($('slide_work_' + this.fadeIn.id) != undefined)
		{
			Effect.Appear('slide_work_' + this.fadeIn.id, { duration:1, from:0.0, to:1.0});
		}
	    
		CARL.log('set the new to the old');
		this.fadeOut = this.fadeIn;
		
		// ******************************************************
		
		// grab lazy slides now. For each slide we fade in/out using the logic above, pop one of
		// the slides in the lazySlides list and insert it into the DOM as a hidden image. Then
		// introduce it as a 'normal' slide by pushing it onto the slides list.		
		newLazySlide = this.lazySlides.pop();
		
		if (newLazySlide)
		{
			CARL.log("insert a new lazy slide with id " + newLazySlide.id);
			// with the new lazy slide, use its information to append markup to the slides divs
			$('slide_images').insert({
				bottom: "<div id='slide_" + newLazySlide.id + "' style='display: none' class='slide'>" +
					"<a href='" + newLazySlide.url_path + "'><img src='" + CARL.webroot + "img/" + newLazySlide.path + "'/></a>" +
					"</div>"
			});
		
			$('holder').insert({
				bottom: "<div style='color: black;text-transform: capitalize;display:none;' id='slide_category_" + newLazySlide.id + "'>" +
					newLazySlide.category.gsub('_', ' ') +
					"</div>" +
					"<div style='color: #777;top: 10px;display: none' id='slide_work_" + newLazySlide.id + "'>" +
					newLazySlide.work +
					"</div>" 
			});
			
			// make the new slide part of the randomness
			this.slides.push(newLazySlide);
		}
		else
		{
			CARL.log("no more lazys to pop!");
		}
	},
	randomWork: function ()
	{
		while (true)
		{
			if ((this.slideIndex + 1) == this.slides.length)
			{
				this.slideIndex = 0;  	
			}
			newSlide = this.slides[this.slideIndex++];
			
			if (this.fadeOut == null) {
				break;
			}
			
			break;
		}
		
		return newSlide;
	}
	
});

var CARL = {

	// will hold the json menu data
	data: {},
	// will hold the context root of the app, retrieved from the above data
	webroot: null,

	current_cat: null,
	/*
		handles the behavior for revealing the submenu section
	*/
	handleWorkHover:function ()
	{
		// if the example_section has a nav_section_perm class, grab the title for it for safe-keeping
		if ($('example_section').hasClassName('nav_section_perm'))
		{
			CARL.log('get current cat');
			CARL.current_cat = $('current_cat').innerHTML;
			CARL.log('current cat ' + CARL.current_cat);
			// remove nav_section_perm if we're currently in a work section
			$('example_section').removeClassName('nav_section_perm');
			$('example_section').update('');
		}
			
		$('sub_work_section').show();
		$('sub_play_section').show();
		CARL.log('showed work section');
	
		$('work_section').addClassName('nav_section_on');
		$('work').addClassName('nav_text_on');
		$('play').addClassName('nav_text_on');
		
		CARL.log('make work section active');
	
		// attach hover listeners to the sub_work_section links
		$$('#sub_work_section a').each(function(e)
		{
			e.observe('mouseover', CARL.prepareSectionExamples)
		});
		
		// attach hover listeners to the sub_work_section links
		$$('#sub_play_section a').each(function(e)
		{
			e.observe('mouseover', CARL.prepareSectionExamples)
		});

	},
	handlePermCategoryHover:function()
	{
		CARL.log('in the handlePermCategoryHover');
		var category = $('current_cat').textContent || $('current_cat').innerText;
		CARL.current_cat = category;
		CARL.log('set current_cat to ' + category);
		
		var example_section_content = '<span style="color: white" id="current_cat">' + category + '</span><br />';
		category = category.gsub(' ', '_');
		category = category.toLowerCase();
		
		CARL.log('category formatted to ' + category);
		
		CARL.data.each(function(cat)
		{
			if (cat['Category']['name'] == category && cat['Category']['name'] != 'sketchbooks')
			{
				// ...then loop through its individual works 
				cat['Work'].each(function(work)
				{
					example_section_content += "<a href='" + webroot + category + "/" + work['url_name'] + "' id='" + work['url_name'] + "_example'>" + work['name'] + "</a><br />";
				});
			}
		}); 
		
		$('example_section').update(example_section_content);
		$('example_section').addClassName('nav_section_perm');
	},
	handleInfoHover:function ()
	{
		$('sub_info_section').show();
		$('info_section').addClassName('nav_section_on');
		$('information').addClassName('nav_text_on');
	},
	resetWorkSection:function ()
	{
		CARL.log('reset work section');
		// we only want to do this if the example_section doesn't have the nav_section_perm classname,
		// which indicates that the section is being highlighted
		if (!$('example_section').hasClassName('nav_section_perm'))
		{
			$('work_section').removeClassName('nav_section_on');
			$('work').removeClassName('nav_text_on');
			$('play').removeClassName('nav_text_on');
		
			$('example_section').removeClassName('nav_section_on');
			$('sub_work_section').hide();
			$('sub_play_section').hide();
			$('example_section').update('');	
		}
		
		//CARL.log('current cat when reset ' + CARL.current_cat);
		// otherwise, the category section had been showing if the CARL.current_cat is present, put it back
		if (CARL.current_cat != null)
		{
			CARL.log('put the nav perm section back');
			$('example_section').addClassName('nav_section_perm');
			$('example_section').update("<span style='color: white' id='current_cat'>" + CARL.current_cat + "</span><br />");
			Event.observe($('current_cat'), 'mouseover', CARL.handlePermCategoryHover);
		}
		
	},
	resetInfoSection:function ()
	{
		CARL.log('resetInfoSection called');
		$('info_section').removeClassName('nav_section_on');
		$('information').removeClassName('nav_text_on');
		$('sub_info_section').hide();
	},
	/**
	* 	Find the anchor tag for the section and retrieve the display value for it. Populate the example header with it.
	*	Then use the anchor tag's id and retrieve the examples from the json object created at the footer
	*/
	prepareSectionExamples:function (e)
	{
		link = e.findElement('a');

		var words = link.id.gsub('_', ' ').split(' ');
		var displayName = '';
		words.each(function(w) {
			var firstLetter = w.substring(0, 1);
			var remaining = w.substring(1, w.length);
			displayName += firstLetter.toUpperCase() + remaining + ' ';			
		});
		
		var id = link.id;
		if ($(id + '_example') == undefined)
		{
			var example_section_content = '<div id="sub_examples" class="sub_examples_class"><span style="color: white">' + displayName.strip() + '</span><br />';

			// loop through each main category
			CARL.data.each(function(cat)
			{
				// if the current category matches the id of the currently hovered-over element...
				if (cat['Category']['name'] == id && cat['Category']['name'] != 'sketchbooks')
				{
					// ...then loop through its individual works 
					cat['Work'].each(function(work)
					{
						example_section_content += "<a href='" + webroot + id + "/" + work['url_name'] + "' id='" + work['url_name'] + "_example'>" + work['name'] + "</a><br />";
					});
					example_section_content += '</div>';
				}
			});

			$('example_section').update(example_section_content);
			$('example_section').addClassName('nav_section_on');
			
			Event.observe($('sub_examples'), 'mouseout', function(ev) {
				Event.stop(ev);
			});
			
			Event.observe($('sub_examples'), 'mouseover', function(ev) {
				Event.stop(ev);
			});
			
			Event.observe($('example_section'), 'mouseout', function(ev) {
				CARL.log('mouse out for example_section');
				CARL.resetWorkSection();
			});
		}
	},
	imageFormIndex:function ()
	{
		return $$('div#image_forms div.image_form').size();
	},
	log:function (msg)
	{
		//console.log(msg);
	}
};

/*
 * Now observe.
 *
 */
Event.observe(window, 'load', function()
{
	try 
	{
		$('sub_work_section').hide();
		$('sub_play_section').hide();
		$('sub_info_section').hide();

		Event.observe($('work'), 'mouseover', CARL.handleWorkHover);
		Event.observe($('information'), 'mouseover', CARL.handleInfoHover);

		['spacer_off', 'logo_container', 'container', 'info_section'].each(function(element)
		{
			Event.observe($(element), 'mouseover', CARL.resetWorkSection);
		});

		['container', 'example_section', 'nav_section_last'].each(function(element)
		{
			Event.observe($(element), 'mouseover', CARL.resetInfoSection);
		});
		// the cat_header_hightlight_mode only shows up when the example section is in perm mode
		Event.observe($('current_cat'), 'mouseover', CARL.handlePermCategoryHover);
	}
	catch(e) {}
	
	// get the menu data from the json
	CARL.data = menu_data.evalJSON();
	CARL.webroot = webroot;
	
});
