/**
 * Initialize the main menu.
 * Add hover classes to LIs whenever they're hovered.
 * @returns {void}
 * @author Nick Davison
 */
function initMainMenu() {
	$('#page_header_menu li.main').bind('mouseover', function(e) {
		$(this).addClass('hover');
	});
	
	$('#page_header_menu li.main').bind('mouseout', function(e) {
		$(this).removeClass('hover');
	});
}

/**
 * Initialize the search field.
 * Clear and replace the default value on focus/blur
 * @returns {void}
 * @author Nick Davison
 */
function initSearchField() {
	// Clear out Drupal's version as it breaks IE6.
	if ($('#search-theme-form .form-text').length>0) {
		$('#search-theme-form .form-text')[0].onblur=function() {};
		$('#search-theme-form .form-text')[0].onfocus=function() {};
	}
	
	$('#search-theme-form .form-text').bind('focus', function(e) {
		if (this.value==this.defaultValue) {
			this.value="";
			$(this).css('color', '#9b9a9a');
		}
	});
	
	$('#search-theme-form .form-text').bind('blur', function(e) {
		if (this.value=="") {
			this.value=this.defaultValue;
			$(this).css('color', '#abaaaa');
		}
	});
}

function getSectionToggleCookieName(jElement) {
	var jElement=$(jElement);
	stripped=jElement.text().toLowerCase();
	stripped=stripped.replace(/\s+/g, '_');
	return "section_toggle_"+stripped;
}

function writeSectionToggleCookie(jElement) {
	var jElement=$(jElement);
	var parentSections=jElement.parents('.section');
	var cookieName=getSectionToggleCookieName(jElement);
	
	// Get the state from the parent LI
	var state="inactive"
	if ($(parentSections[0]).is('.active')) {
		state="active";
	}
	
	// Get the date obj for one week in the future.
	var expires=new Date();
	var plusOneWeek=expires.getTime()+(7*24*60*60*1000);
	expires.setTime(plusOneWeek);
	
	// Store the state to a cookie
	document.cookie=cookieName+"="+state+";expires="+expires.toGMTString()+"; path=/";
}

function readSectionToggleCookie(jElement) {
	var jElement=$(jElement);
	var cookieName=getSectionToggleCookieName(jElement);
	var pairs=document.cookie.split(';');
	for (var i=0; i<pairs.length; i++) {
		parts=pairs[i].split('=');
		var part0=parts[0].replace(/\s+/g, '');
		if (part0==cookieName) {
			part1=parts[1].replace(/\s+/g, '');
			return part1;
		}
	}
	return "";
}

/**
 * Initialize the section toggles
 * Make sure everything has an active or inactive class to begin with.
 * Toggle those classes on click.
 * @returns {void}
 * @author Nick Davison
 */
function initSectionToggles() {
	// Find all .section that are parents of a .section_toggle
	parentSections=$('.section_toggle').parents('.section').each(function(k, v) {
		// If they have neither an active or inactive class, make them active by default
		if ( (!$(v).is('.active')) && (!$(v).is('.inactive')) ) {
			// Attempt to read the cookie value - set to active if none exists.
			fromCookie=readSectionToggleCookie($(v).find('.section_toggle'));
			if (fromCookie=="") fromCookie="active";
			$(v).addClass(fromCookie);
			if (fromCookie=="inactive") {
				$(v).find('.section_content').css('display', 'none');
			}
		}
	});

	// Bind the clicks for all .section_toggle
	$('.section_toggle').bind('click', function(e) {
		e.preventDefault();
		// Find their parent .section
		parentSections=$(this).parents('.section');
		
		// Swap the active/inactive classes
		if ($(parentSections[0]).is('.active')) {
			$(parentSections[0]).removeClass('active');
			$(parentSections[0]).addClass('inactive');
			
			$(parentSections[0]).find('.section_content').slideUp({duration: 300});
		} else {
			$(parentSections[0]).removeClass('inactive');
			$(parentSections[0]).addClass('active');
			
			$(parentSections[0]).find('.section_content').slideDown({duration: 300});
		}
		
		// Store the state out to a cookie
		writeSectionToggleCookie(this);
	});
}

// based on initSectionToggles(), stock ticker is now being created after page load
function initStockSectionToggle() {
	if ( !$('#section_stock').is('.active') && !$('#section_stock').is('.inactive') ) {
		fromCookie=readSectionToggleCookie( $('#section_stock').find('.section_toggle') )
		if (fromCookie=="") fromCookie="active";
		$('#section_stock').addClass(fromCookie);
		if (fromCookie=="inactive") {
			$('#section_stock').find('.section_content').css('display', 'none');
		}
	};
	
	$('#section_stock .section_toggle').bind('click', function(e) {
		e.preventDefault();
		
		if ($('#section_stock').is('.active')) {
			$('#section_stock').removeClass('active');
			$('#section_stock').addClass('inactive');
			$('#section_stock').find('.section_content').slideUp({duration: 300});
		}
		else {
			$('#section_stock').removeClass('inactive');
			$('#section_stock').addClass('active');
			$('#section_stock').find('.section_content').slideDown({duration: 300});
		}
		writeSectionToggleCookie($('#section_stock').find('.section_toggle'));
	});
}

/**
 * Initialize the expand menus
 * Make sure everything has an active or inactive class to begin with.
 * Toggle those classes on click.
 * @returns {void}
 * @author Nick Davison
 */
function initExpandMenus() {
	// Default closed
	parentSections=$('.expand_menu li').each(function(k, v) {
		// If they have neither an active or inactive class, make them inactive by default
		if ( (!$(v).is('active')) && (!$(v).is('inactive')) ) {
			$(v).addClass('inactive');
			$(v).find('.content').css('display', 'none');
		}
	});

	// Bind the clicks for all h3s within expand menus
	$('.expand_menu h3').bind('click', function(e) {
		e.preventDefault();
		// Find their parent li
		parentLis=$(this).parents('li');
		
		// Swap the active/inactive classes
		if ($(parentLis[0]).is('.active')) {
			$(parentLis[0]).removeClass('active');
			$(parentLis[0]).addClass('inactive');
			
			$(parentLis[0]).find('.content').slideUp({duration: 200});
		} else {
			$(parentLis[0]).removeClass('inactive');
			$(parentLis[0]).addClass('active');
			
			$(parentLis[0]).find('.content').slideDown({duration: 200});
		}
	});
	
	// Bind the close links
	$('.expand_menu .close').bind('click', function(e) {
		e.preventDefault();
		// Find their parent li
		parentLis=$(this).parents('li');
		
		$(parentLis[0]).removeClass('active');
		$(parentLis[0]).addClass('inactive');
		
		$(parentLis[0]).find('.content').slideUp({duration: 200});
	});
}

/**
 * Initialize the expand/contract system for the contacts page.
 * Go through all of the expand buttons on the page.
 * If they're not display:none (a sign they're not wanted):
 * Default the content closed, bind the links to toggle state and bind the close button to close them.
 * @returns {void}
 * @author Nick Davison
 */
function initContactsExpander() {
	$('.block-contacts a.expand_contacts').each(function(k, v) {
		parentNode=$(this).parents('.block-contacts');
														 
		// If we're showing the link
		// Default content closed
		if ($(v).css('display').indexOf('none')==-1) {
			parentNode.addClass('closed');
			parentNode.find('.content').css('display', 'none');
		}
		
		// Bind the link to toggle state												 
		$(v).click(function(e) {
			e.preventDefault();
			parentNode=$(this).parents('.block-contacts');
			if (parentNode.is('.closed')) {
				parentNode.removeClass('closed');
				parentNode.addClass('open');
				parentNode.find('.content').slideDown();
			} else {
				parentNode.removeClass('open');
				parentNode.addClass('closed');
				parentNode.find('.content').slideUp();
			}
		});
		
		// Bind the close buttons
		parentNode.find('.close').click(function(e) {
			e.preventDefault();
			parentNode=$(this).parents('.block-contacts');
			if (!parentNode.is('.closed')) {
				parentNode.removeClass('open');
				parentNode.addClass('closed');
				parentNode.find('.content').slideUp();
			}
		});
	});
}

function showVideo(url) {	
	$('#lightbox_content').css('width', '880px');
	lightbox.load({
		url: url,
		success: function(data, ref) {
			
			var videoID=''
			var selChapter='0';
			
			var holderText=$('#vid_pop_holder').text(); // Get the content of the div
			holderText=holderText.replace(/^(\s)+/, ''); // Trim whitespace off the front
			holderText=holderText.replace(/(\s)+$/, ''); // Trim whitespace off the end
			var parts=holderText.split('|'); // Split it at the |
			if (parts.length==2) { // IF there were two parts (videoID)|(chapter)
				videoID=parts[0]; // Get the videoID
				selChapter=parts[1]; // Get the chapter
			}		
			
			// If a chapter was passed in the page call
			if (ref.url.toString().indexOf("?chapter=")!=-1) {
				// set the chapter to that value
				pos=ref.url.toString().indexOf("?chapter=")+9;
				selChapter=ref.url.toString().substring(pos);
			}
					
			// Initialize Flash Player
			var flashvars={
				videoID: videoID,
				selChapter: selChapter,
				filePath: '/apps/lifetech/docroot/sites/all/themes/lifetech/swfs/',
				xmlPath: '/apps/lifetech/docroot/feeds/video_list_3-5-10.xml'
			};
			
			var params={
				quality: 'high',
				wmode: 'transparent',
				salign: '',
				allowFullScreen: 'true',
				allowScriptAccess: 'sameDomain'
			};
			
			if (typeof console!="undefined") {
				if (typeof console.debug!="undefined") {
					console.debug(flashvars);
				}
			}
			
			var attributes={};
			
			swfobject.embedSWF("/apps/lifetech/docroot/sites/all/themes/lifetech/swfs/videoplayer.swf", "vid_pop_holder", "615", "380", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
		}
	});
}

function flashready(videoId, chapter) {
	//showVideo("node/"+videoId+"?chapter="+chapter);
	if (chapter) {
		showVideo(videoId+".videodisplay.html?chapter="+chapter);
	} else {
		showVideo(videoId);
	}
}

function showImage(url, photoUrl) {
	$('#lightbox_content').css('width', '653px');
	lightbox.load({
		url: url,
		success: function() {
			com.digitaria.ImgCarousel.ShowUrl(photoUrl);
		}
	});
}

/**
 * Bind the a.launch_video_popup and a.launch_image_popup links.
 * @returns {void}
 * @see showVideo (calls)
 * @see showImage (calls)
 */
function initLaunchLinks() {
	// Bind the launch_video_popup links
	$('a.launch_video_popup').live('click', function(e) {
		e.preventDefault();
		url=$(this).attr('href');
		showVideo(url);
	});
	
	// Bind the launch_image_popup links
	// Supports either photo or image as people can never remember which it should be. ;)
	$('a.launch_photo_popup, a.launch_image_popup').live('click', function(e) {
		e.preventDefault();
		url=$(this).attr('href');
		photoUrl=$(this).attr('rel');
		showImage(url, photoUrl);
	});
}

/**
 * Initialize the page body menu system.
 * Initialize the toggles.
 * Initialize the expandable menus.
 * @returns {void}
 * @see initSectionToggles (calls)
 * @see initExpandMenus (calls)
 * @author Nick Davison
 */
function initPageBodyMenu() {
	initSectionToggles();
	initExpandMenus();
}

/**
 * Set up the faux drop down system.
 * @returns {void}
 * @author Nick Davison
 */
function initFauxDrops() {
	// Bind clicking the "current" display to open/close the drop
	$('.faux_drop .current').live('click', function(e) {
		parentDrops=$(this).parents('.faux_drop');
		parentDrop=$(parentDrops[0]);
		if (parentDrop.is('.expanded_faux_drop')) {
			parentDrop.removeClass('expanded_faux_drop');
		} else {
			parentDrop.addClass('expanded_faux_drop');
		}
	});
	
	// Bind clicking any of the links in the drop itself
	$('.faux_drop a').live('click', function(e) {
		// 
		parentDrops=$(this).parents('.faux_drop');
		parentDrop=$(parentDrops[0]);
		
		// Close the drop down
		if (parentDrop.is('.expanded_faux_drop')) {
			parentDrop.removeClass('expanded_faux_drop');
		}
	
		// Copy the value in to the "current" field
		parentDrop.find('.current .value').html($(this).html());
	});
	
	$('body').click(function(e) {
		if ($(e.originalTarget).parents('.faux_drop').length==0) {
			$('.expanded_faux_drop').removeClass('expanded_faux_drop');
		}
	});
}

function checkURLForInitialLoad() {
	if (document.location.search) {
		pair=document.location.search.toString().split("=");
		
		// If there's anything other than A-Z 0-9 _ -
		if (pair[1]!=pair[1].replace(/[^\w-]/g, '')) {
			//Bail
			//return false;
		}
		
		switch(pair[0]) {
			case '?video' :				
				// Delay a second, to let the lightbox initialize.
				// Then launch the video
				//subPairs=pair[1].split('-');
				var videoId = '' ;
				var chapterId = '0' ;
				subPairs=pair[1].split('+');
				if (subPairs.length == 2) {
					chapterId = subPairs[1];
				}
				videoId=subPairs[0];
				//setTimeout("flashready("+videoId+", "+chapterId+")", 1000);				
				//setTimeout("flashready("+videoId+", "+chapterId+")", 1000);
				var videoUrl = videoId + ".videodisplay.html?chapter=" + chapterId;
				
				setTimeout("showVideo('"+videoUrl+"')", 1000);
				break;
			case '?image' :
				// Delay a second, to let the lightbox initialize.
				// Then launch the image
				setTimeout("showImage('/partials/photos', '/sites/default/files/imagecache/photo_gallery_large/photo/image/"+pair[1]+".jpg')", 1000);
		}
	}
}

function initVideoWall() {
	if (document.getElementById('video_wall_container')) {
		// Initialize Flash Player
		var flashvars={
			filePath: '/apps/lifetech/docroot/sites/all/themes/lifetech/swfs/',
			xmlPath: '/apps/lifetech/docroot/feeds/video_list_3-5-10.xml'
		};
		var params={
			bgcolor: '#000000',
			quality: 'high',
			wmode: 'transparent',
			salign: '',
			allowFullScreen: 'false',
			allowScriptAccess: 'sameDomain'
		};
		var attributes={};
		swfobject.embedSWF("/apps/lifetech/docroot/sites/all/themes/lifetech/swfs/videowall_2.swf", "video_wall_container", "763", "478", "9.0.0","expressInstall.swf", flashvars, params, attributes);
	}
	
	// Initialize the links within the video popup
	$('#vid_pop_chapters a, #vid_pop_related_links a').live('click', function(e) {
		e.preventDefault();
		showVideo($(this).attr('href'));
	});
}

function mediaResourcesAJAXLoad(url) {
	$.ajax({
		url: url,
		success: function(data) {
			$('#media_resources_ajax_holder').html(data);
			$('#media_resources_ajax_holder').fadeIn({duration: 0.5});
		}
	});
}

function initMediaResourcesJavaScript() {
	if (document.getElementById('media_resources_ajax_holder')) {
		// Bind clicks on links
		$('#media_resources_ajax_holder .paginator_title a').live('click', function(e) {
			e.preventDefault();
			url=$(this).attr('href');
			mediaResourcesAJAXLoad(url);
		});
	}
}

var addthis_pub = "YOUR ADDTHIS USERNAME";

$(document).ready(function() {
	initMainMenu();
	initSearchField();
	initPageBodyMenu();
	initContactsExpander();
	initFauxDrops();
	initLaunchLinks();
	initVideoWall();
	initMediaResourcesJavaScript();
	loadStockSection();
	flashReplace();
	checkURLForInitialLoad();
	com.digitaria.gmaps.init("Carlsbad, California");
	
	if (document.location.toString().indexOf("?print=")!=-1) {
		window.print();
		window.close();
	}
});