/* Javascript functions common to all pages */
var slideshows = new Object();

if (typeof(jQuery) != "undefined") {
	// Function to preload images
	(function($) {
		var cache = [];
		// Arguments are image paths relative to the current page.
		$.preLoadImages = function() {
			var args_len = arguments.length;
			for (var i = args_len; i--;) {
				var cacheImage = document.createElement('img');
				cacheImage.src = arguments[i];
				cache.push(cacheImage);
			}
		}
	})(jQuery)
	
	// Function to equalize column heights
	function equalizeHeight(group) {
		var tallest = 0;
		$(group).each(function() {
			if ($(this).height() > tallest)
				tallest = $(this).height();
		});
		$(group).height(tallest);
	}
	
	// Function to rotate source lists
	function rotateSourcelist(el){
		var last = $('#'+el).find('.selected'); // get the current item
		var next = last.next(); // get the next item
		if (next.length == 0) // if the current item is the last one in the group, move to the next group
			next = last.parents('li').next().find('li').first();
		if (next.length == 0) next = $('#'+el).find('li>ul>li').first(); // if there are no more groups, go back to the first group
		
		last.removeClass('selected'); // deselect the current item
		last.children('.source_content').fadeOut('slow'); // fade out the current item's content
		next.children('.source_content').fadeIn('slow'); // fade in the next item's content
		
		$('#'+el+'_arrow').text(next.children('a').first().text()); // put the name of the new item in the arrow
		$('#'+el+'_arrow').animate({	 // move the arrow to its new position
			top: next.position().top
		},'slow','easeOutExpo',function(){
			next.addClass('selected'); // select the next item
		});
	}
	
	// Function to rotate quotes
	function rotateQuote(el,quotes){
		var rand = Math.floor(Math.random()*quotes.length);
		var text = quotes[rand][0];
		var author = quotes[rand][1];
		while ($('.quote:contains("'+text+'")').length > 0) {
			rand = Math.floor(Math.random()*quotes.length);
			text = quotes[rand][0];
			author = quotes[rand][1];
		}
		$('#'+el).fadeOut('fast',function(){
			$(this).children('.quote_text').text(text);
			$(this).children('.quote_author').text(author);
			$(this).fadeIn();
	   });
	}
	
	// Function to rotate slideshows
	function rotateSlideshow(el,dir){
		dir = typeof(dir) != 'undefined' ? dir : 'next';
		var prev = $('#'+el).children('img:visible'); // get the current slide
		// Determine direction
		switch (dir) {
			case 'next':
				var next = prev.next('img'); // get the next slide
				if (next.length == 0) next = prev.siblings('img:first');	
				var next_bull = $('#'+el+'>p.slideshow_nav').children('a.selected').next(); // get the next bullet
				if (next_bull.length == 0) next_bull = $('#'+el+'>p.slideshow_nav').children('a:first-child');
				break;
			case 'prev':
				var next = prev.prev('img'); // get the previous slide
				if (next.length == 0) next = prev.siblings('img:last');
				var next_bull = $('#'+el+'>p.slideshow_nav').children('a.selected').prev(); // get the previous bullet
				if (next_bull.length == 0) next_bull = $('#'+el+'>p.slideshow_nav').children('a:last-child');
				break;
		}
		// Rotate slide
		next.css('z-index','200'); // move the next slide forward
		prev.css('z-index','100');
		next.fadeIn('slow',function(){ // fade in the new slide over the old
			 prev.hide(); // then hide the old
		});
		// Change caption
		if ($('#'+el).hasClass('caption')) {
			$('#'+el+'>figcaption').fadeOut('fast',function(){
				$(this).text(next.attr('title')).fadeIn('fast');
			});
		}
		// Change selected bullet
		next_bull.siblings().removeClass('selected');
		next_bull.addClass('selected'); // select the new bullet
	}
	
	// Document ready
	$(document).ready(function(){
		// Preload navbar images
		jQuery.preLoadImages(
			"http://www.iggsoftware.com/images/header/cart_selected.png",
			"http://www.iggsoftware.com/images/header/dropdown_arrow_hover.png",
			"http://www.iggsoftware.com/images/header/submenu_arrow.png"
		);
		
		// Activate obfuscated email addresses
		$('a.email').each(function(){
			var email = "";
			var string = $(this).attr('rel');
			var split = new Array();
			split = string.split('||');
			for (var i=split.length-1; i>=0; i--) {
				var segment = new Array();
				segment = split[i].split('|');
				for (var j=segment.length-1; j>=0; j--) {
					email += segment[j];
					if (j > 0) email += ".";
				}
				if (i > 0) email += "@";
			}
			if ($(this).hasClass('show')) $(this).text(email); // show address if requested
			$(this).click(function(){ // send email when clicked
				window.location.href = "mailto:"+email;
				return false;
			});
		});
		
		// Open external links in new window
		$('a[rel*=external]').click(function(){
			window.open(this.href);
			return false;
		});
		
		// Open popup links in new window
		$('a[rel*=popup]').click(function(){
			window.open(this.href,"popup","scrollbars,resizable,height=700,width=970");
			return false;
		});
		
		// Add fading to main navbar menus
		$('#main_nav li.hover').removeClass('hover').hover(function(){
			$(this).children('ul').stop(true,true).fadeIn('fast');
		},function(){
			$(this).children('ul').stop(true,true).fadeOut('fast');
		});
		
		// Set up source lists
		$('.sourcelist').each(function(){
			$(this).removeClass('hover'); // disable CSS hover effects
			var arrow = $('<p>').attr('id',$(this).attr('id')+'_arrow').addClass('source_arrow'); // create an arrow for the source list
			var first = $(this).find('li>ul>li').first().addClass('selected'); // identify the first item and select it
			arrow.text(first.children('a').first().text()); // put the name of the first item in the arrow
			var pos = first.position(); // get the position of the first item
			arrow.css({'top':pos.top,'left':pos.left}); // set the position of the arrow
			first.append(arrow); // append the arrow to the first item
			$(this).find('.source_content').first().show(); // show the first content block
			$('li>ul>li',this).click(function(e){ // show the correct content block when a source list item is clicked
				e.preventDefault();
				$(this).parent().parent().parent().find('li').removeClass('selected'); // deselect the current item
				var item = $(this);
				arrow.text(item.children('a').first().text()); // put the name of the new item in the arrow
				$(arrow).animate({ // move the arrow to the new item
					top: item.position().top
				},'slow','easeOutExpo',function(){
					item.addClass('selected');
				});
				clearInterval(slideshows[$(this).parents('.sourcelist').attr('id')]); // stop autorotation
				$(this).parents('.sourcelist').find('.source_content').fadeOut('slow'); // fade out the current item content
				$(this).find('.source_content').fadeIn('slow'); // fade in the new item content
			});
			$('.source_content').click(function(e){ // follow the link when the content area is clicked
				e.stopPropagation();
				window.location.href = $(this).children('a:first-child').attr('href');
			});
		});
		$('.sourcelist.autorotate').each(function(){ // start rotating automatically (if requested)
			slideshows[$(this).attr('id')] = setInterval("rotateSourcelist('"+$(this).attr('id')+"')",6500);
		});
		
		// Set up quotes
		var counter = 0;
		$('.quote').each(function(){
			var id = $(this).attr('id');
			$.get($(this).attr('title'),function(xml){
				var quotes = new Array();
				$(xml).find('quote').each(function(){
					q = new Array(2);
					q[0] = '"'+$(this).find('text').text()+'"';
					q[1] = '–'+$(this).find('author').text();
					quotes.push(q);
				});
				window[id] = quotes; // save the quotes to a global variable so the rotate function can access it
				rotateQuote(id,window[id]); // load the first quote
				setTimeout('setInterval("rotateQuote(\''+id+'\',window.'+id+')",13000)',6500*counter);
				counter++;
			},'xml');
		});
		
		// Set up slideshows
		$('.slideshow').each(function(){
			var id = $(this).attr('id');
			$(this).children('img:not(:first-child)').hide(); // hide all images except for the first
			$('<div>').addClass('image_frame').appendTo($(this)); // frame the slideshow
			var dots = $('<p class="slideshow_nav">'); // create a navigation bar
			$(this).children('img').each(function(){
				var src = $(this).attr('src');
				var next = $(this);
				$('<a href="'+src+'" rel="nozoom">'+$(this).attr('alt')+'</a>').click(function(e){ // change slide on click
					e.preventDefault();
					clearInterval(slideshows[id]); // cancel automatic rotation
					if (!$(this).hasClass('selected')) {
						$(this).siblings().removeClass('selected'); // change the selected dot
						$(this).addClass('selected');
						next.css('z-index','200'); // move the next slide forward
						var prev = $(this).parent().parent().children('img:visible'); // find the old slide and move it backward
						prev.css('z-index','100');
						next.fadeIn('slow',function(){ // fade in the new slide over the old
							 prev.hide(); // then hide the old
						});
						if ($(this).parent().parent().hasClass('caption')) { // change the caption if requested
							$(this).parent().siblings('figcaption').fadeOut('fast',function(){
								$(this).text(next.attr('title')).fadeIn('fast');
							});
						}
					}
				}).appendTo(dots);
				if ($(this).index() != $(this).siblings('img').length) dots.append(" &bull; "); // add a bullet between each link
				dots.children(':first-child').addClass('selected'); // select the first dot by default
			});
			$(this).append(dots);
			var arrows = $('<p class="slideshow_buttons">'); // add navigation arrows
			var prev = $('<a href=""><img src="http://www.iggsoftware.com/images/slideshow_prev.gif" alt="&#9664;"></a>').click(function(e){
				e.preventDefault();
				clearInterval(slideshows[id]); // cancel automatic rotation
				rotateSlideshow(id,'prev'); // show previous slide
			});
			var next = $('<a href=""><img src="http://www.iggsoftware.com/images/slideshow_next.gif" alt="&#9654;"></a>').click(function(e){
				e.preventDefault();
				clearInterval(slideshows[id]); // cancel automatic rotation
				rotateSlideshow(id,'next'); // show next slide
			});
			arrows.append(prev).append(next);
			$(this).append(arrows);
			if ($(this).hasClass('caption')) // add a caption (if requested)
				$(this).append('<figcaption>'+$(this).children('img:first-child').attr('title')+'</figcaption>');
			if ($(this).hasClass('autorotate')) // start rotating automatically (if requested)
				slideshows[id] = setInterval("rotateSlideshow('"+id+"')",6500);
		});
		
		// Autohide definition lists (e.g. support FAQ)
		if (typeof(ie_browser) == "undefined") {
			$('dl.autohide').each(function(){
				$(this).children('dd').each(function(){
					// Only hide if the URL doesn't include a hash for that element
					if (window.location.hash != "#"+$(this).prev().attr('id')) $(this).hide();
				});
				$(this).children('dt').each(function(){
					// Add disclosure triangles
					var link = $('<a href="">');
					if ($(this).next().is(":visible"))
						link.append('<img src="http://www.iggsoftware.com/images/disclosure_open.gif" alt=""/>');
					else
						link.append('<img src="http://www.iggsoftware.com/images/disclosure_closed.gif" alt=""/>');
					link.append($(this).text());
					// Show definition details on click
					link.click(function(e){
						e.preventDefault();
						var disclosure = $(this).children('img:first').attr('src');
						if (disclosure == 'http://www.iggsoftware.com/images/disclosure_closed.gif')
							$(this).children('img:first').attr('src','http://www.iggsoftware.com/images/disclosure_open.gif');
						else
							$(this).children('img:first').attr('src','http://www.iggsoftware.com/images/disclosure_closed.gif');
						$(this).parent().next().toggle('fast');
					});
					$(this).html(link);
				});
			});
		}
		
		// Set up tab blocks
		if (typeof(ie_browser) == "undefined") {
			$('.tab_block').each(function(){
				// Hide all internal divs except the first
				var divs = $(this).children('div');
				divs.not(':first').hide();
				// Click to change tabs
				var lis = $(this).find('nav').find('li');
				lis.click(function(e){
					e.preventDefault();
					// Change tab formatting
					lis.removeClass('selected');
					$(this).addClass('selected');
					// Show the corresponding div
					var id = $(this).children('a').attr('href');
					divs.each(function(){
						if (id == "#"+$(this).attr('id')) $(this).show('fast');
						else $(this).hide('fast');
					});
				});
			});
		}
		
		// Set up select blocks
		if (typeof(ie_browser) == "undefined") {
			$('.select_block').each(function(){
				// Hide all internal divs except the first
				var divs = $(this).children('div');
				divs.not(':first').hide();
				// Change the select box to change divs
				var sel = $(this).find('nav').find('select');
				sel.change(function(e){
					e.preventDefault();
					// Show the corresponding div
					divs.each(function(){
						if ("select_"+sel.val() == $(this).attr('id')) $(this).show('fast');
						else $(this).hide('fast');
					});
					// Change the icon (if there is one)
					if (sel.find('option:selected').data('img')) $('#select_img').attr('src',sel.find('option:selected').data('img'));
				});
			});
		}
	});
}
