// since IE doesn't have a console object, this will prevent errors
if (typeof console == 'undefined') console = {log:function(){}};


// ====================================================
// = surf(newLocation, historyData) =
// ====================================================
// load the contents of the appropriate page
//  note: each page's contents are loaded dynamically via ajax from index.php
// ====================================================
var surf = function(newLocation, historyData) {
	var highlight = true;
	switch (newLocation) {
		case 'video_animation' : 
			commonTransition();
			$('flash_video_player_container').show();
			var url = 'pages/' + newLocation + '.html';
			var container = 'framed_content_main_container';
			loadPage(url, container, 'video_animation');
		break;
		
		case '' : // this should probably never happen
			window.location = 'index.php';
			console.log('how you get here now?');
		break;
			
		case 'homepage' :
			highlight = false;
			$$('.landing_page_only').show();	
			var url = 'pages/' + newLocation + '.html';
			var container = 'framed_content_main_container';
			loadPage(url, container, 'homepage');
		break;
			
		default :
			commonTransition();
			// $('flash_video_player_container').hide();
			var url = 'pages/' + newLocation + '.html';
			var container = 'framed_content_main_container';
			loadPage(url, container, newLocation);
		break;
	}
	
	// highlight the appropriate nav item
	if (highlight) highlightCurrentNav();	

	// just to get rid of any uncaught link click events
	return false;
}


// Triggers to be performed on page load
window.addEvent('domready', function() {
	window.CURRENT_PAGE = getCurrentPage();

	// set up navigation links
	// attach an event listener to each item in the list to handle clicks
	$$('.static_nav').each( function(nav_item){
		nav_item.addEvent('click', function(event){
			window.location.href = this.getChildren('a');
		})
	});

	// the ticker AKA marquee
	(function(){
		$('ticker_container').show();
		window.mq = new mooquee($('ticker_container'), { 
			direction: 'left', 
			pauseOnOver: false,
			marHeight: 14,
			marWidth: 310
		});
	}).delay(3000); // delay the start to allow flash, images etc. to load

	// get a global Roar object to use for notifications
	window.RRR = new Roar({position: 'upperRight'});

	console.log('CURRENT_PAGE = ' + CURRENT_PAGE);	

	// some pages process thumbnail clicks differently:
	// 		homepage : load a URL  
	// 		video_animation : load a video
	document.addEvent('slideshow-loaded', function(){
		switch (CURRENT_PAGE) {

			// special handling for homepage
			case 'homepage' :
			case 'contact_us':
			case 'about_us':			
				myShow.pause(1);
				myShow.image.hide();

				var thumbs = $$('#slideshow_container div.slideshow-thumbnails ul li a');
				// get rid of the default click behavior
				thumbs.removeEvents('click');

				// do our own thang
				thumbs.addEvent('click', function (event){
					event.stop();
					var t = $(event.target);
					var pageToLoad = t.getParent().title.replace(/\<h3\>(.+)\<\/h3\>/, '$1');
					console.log( 'thumbinfo : ' + pageToLoad );
					window.location.search = pageToLoad;
				});
			break;


			case 'video_animation' :
				myShow.pause(1);
				myShow.image.hide();
				var thumbs = $$('#slideshow_container div.slideshow-thumbnails ul li a');
				// get rid of the default click behavior
				thumbs.removeEvents('click');

				// do our own thang
				thumbs.addEvent('click', function (event){
					event.stop();
					var t = $(event.target);
					
					window.th = t;
					
					var vidToShow = 'flash/video/' + t.src.replace( /.+\/([^\/]+)\.jpg\_.+/ , '$1'  ) + '.flv';
					$('player_flash_object').sendEvent('LOAD', vidToShow);
					$('player_flash_object').sendEvent('PLAY','true');
					
					$$('.slideshow-thumbnails a').removeClass('slideshow-thumbnails-active')
					$$('.slideshow-thumbnails a').addClass('slideshow-thumbnails-inactive')
					t.getParent('a').removeClass('slideshow-thumbnails-inactive');
					t.getParent('a').addClass('slideshow-thumbnails-active');
					
					
					var caption = t.getParent('a').title;
					console.log('caption updated to ' + caption);
					$("photo_description_container").set('html', caption);					
					
				});

				$$('.slideshow-thumbnails a').addClass('slideshow-thumbnails-inactive')				
				$$('.slideshow-thumbnails a')[0].removeClass('slideshow-thumbnails-inactive');
				
		 		$('player_flash_object').sendEvent('PLAY','true');
			break;
			
			default :
				$$(".slideshow-images").addClass('white-border');
				if (typeof myShow != 'undefined') myShow.first();
				
			break;
		}
	});
	
	// load the page (this is quite important)
	surf(CURRENT_PAGE);
});


// ========================================
// =  highlightCurrentNav(navToHighlight) =
// ========================================
function highlightCurrentNav(navToHighlight){
	if (typeof navToHighlight == 'undefined') var navToHighlight = $(CURRENT_PAGE); // for the lazy
	else navToHighlight = $(navToHighlight); // for the obsessive

	if (navToHighlight) { // make sure it's not null!
		$$('.static_nav').each( function(someNav){ // the king is dead
			someNav.removeClass('highlighted_nav');				
		});
	
		navToHighlight.addClass('highlighted_nav');	// long live the king		
	}
}


// ======================
// = commonTransition() =
// ======================
// common tasks to perform when navigating to a new page
function commonTransition(){
	// these 2 handle the transition out of the landing page
	$("framed_content_area").addClass('framed_background');	
}


// ================================
// = getHash(excludeQuestionMark) =
// ================================
// returns the post-hash text in a URL
// excludeQuestionMark : boolean (default: true)
//   whether to return any text after a question mark
//
// based on : 
//   http://stereointeractive.com/blog/2008/11/21/javascript-get-window-hashanchor-get-link-target/ =
// ================================
function getHash(excludeQuestionMark) {
	if (typeof excludeQuestionMark == 'undefined') var excludeQuestionMark = true;
	var hash = window.location.hash;
	var stop = hash.indexOf('?');
	// if there was no question mark in the hash, or if excludeQuestionMark is set to false
	if (stop == -1 || !excludeQuestionMark)
	 	var returner = hash.substring(1); // remove #
	else
	 	var returner = hash.substring(1,stop); // remove # and exlude everything after '?'
	return returner;
}


// ====================
// = getCurrentPage() =
// ====================
function getCurrentPage() {
	return window.location.search.substr(1) || 'homepage';
}


// ==================
// = hideCaptions() =
// ==================
function hideCaptions() {
	return (CURRENT_PAGE == 'homepage' || CURRENT_PAGE == 'about_us' || CURRENT_PAGE == 'contact_us')
}


// ============================
// = loadPage(url, container) =
// ============================
// load a page via AJAX request
// ============================
function loadPage(url, container, imageFolder){
	var ajax = new Request.HTML({update: container,
		onSuccess : function() {
			if (typeof myShow != 'undefined')  {
				myShow.destroy();
			}
		},
		onComplete : function() {
			if (CURRENT_PAGE =='about_us' || CURRENT_PAGE == 'contact_us'){ // hide captions
				imageFolder = 'homepage';
			};
			
			if (imageFolder) loadImages(imageFolder);
			
			// observe the commercial/residential links
			$$('.dynamic_nav').addEvent('click', function(){
				myShow.pause(1);
				loadImages(imageFolder, this.id);
				myShow.first();
			});			
		}
	}).get(url);
}


// ===================
// = loadSlideshow() =
// ===================
function loadSlideshow(customData, customHu){	
	var data = {
      "Architectural Illustration_Residential02.jpg": { caption: 'Data was blank!' }, 
      "Architectural Illustration_Residential01.jpg": { caption:  'Data was blank!' }, 
      "Architectural Illustration_Residential03.jpg": { caption:  'Data was blank!' }
    };
	if (typeof customHu == 'undefined')
		var customHu = 'admin/zenphoto/albums/architectural_illustration/';
	if (typeof customData == 'undefined')
		var customData = data;

	var showController = true, showLoader = {'animate': ['js/lib/moo/slideshow2/css/loader-#.png', 12]};
	if ( CURRENT_PAGE == 'homepage' || CURRENT_PAGE == 'about_us' || CURRENT_PAGE == 'contact_us' ) {
		showController = false;
		showLoader = false;
	}
  $('slideshow_container').show();
  window.myShow = new Slideshow('slideshow_container', customData, { 
		loader: showLoader, 
		paused:true, 
		captions:true, 
		controller: showController, 
		height: 340, 
		hu: customHu, 
		thumbnails: true, 
		width: 470 
	});

	document.fireEvent('slideshow-loaded');

	// event listener to update captions	
	if (! hideCaptions())
		myShow.slideshow.retrieve('captions').addEvent('update', function(){
			var caption = myShow.data.captions[myShow.slide];
			console.log('caption updated to ' + caption);
			$("photo_description_container").set('html', caption);
		});
}


// ===========================
// = loadImages(folder, tag) =
// ===========================
// prepare the data object to be 
// passed to the slideshow, 
// and launch the slideshow
// ===========================
function loadImages(folder, tag){ 
	// to-do : use send() instead of url to transmit data
	if (typeof folder == 'undefined') var folder = '';
	var returner = {};
	
	var urlWithArgs = "js/image_list.php?folder=" + folder;
	
	if (typeof tag != 'undefined')
		urlWithArgs += '&tag=' + tag;
	
	var json = new Request.JSON({url: urlWithArgs, method : 'GET',
		onComplete: function(images, text){
			console.log(images.data);
			returner.data = images.data;
			returner.hu = images.hu;
			if (typeof images.data.length != 'undefined' && images.data.length == 0) {
				// don't load an empty data set!
				console.log('empty data set');
			}
			else {
				if (typeof myShow != 'undefined' && typeof tag != 'undefined')  {
					myShow.destroy();
				}				
				loadSlideshow(images.data, images.hu);
			}

		}
	}).send();
	return returner;
}



// ===========
// = odump() =
// ===========
// utility object to inspect objects
// from : http://refactormycode.com/codes/226-recursively-dump-an-object
// ===========
var odump = (function(){
  var max, INDENT = "                                   "; // As long as you need :)
  
  function valueToStr(value, depth) {
    switch (typeof value) {
      case "object":   return objectToStr(value, depth + 1);
      case "function": return "function";
      default:         return value;
    }
  }
  
  function objectToStr(object, depth) {
    if (depth > max)
      return false;
    
    var output = "";
    for (var key in object)
      output += "\n" + INDENT.substr(0,2*depth) + key + ": " + valueToStr(object[key], depth);

    return output;  
  };
  
  return function odump(object, depth, _max) {
    max = _max || 2;
    return objectToStr(object, depth || 0);
  };
})();