// -------------
// FrontDoor.js
// -------------
var fpData; // for page data
var basePath;

// size of features
var nativeWidth = 999;
var nativeHeight = 869;

// layout rules
var stayAboveFold = false;
var layoutRatioNav = 0.30;
var layoutRatioContent = 0.70;
var minBrowserHeight = 575;
var minBrowserWidth = 700;
var minNavWidth = 220;
var maxNavWidth = 435;
var minContentWidth = 661;
var scalePriority = 'maintainAspectRatio'; // options: variableWidth or maintainAspectRatio
var spaceFromTop = 0; // default distance btw the logo and the top of the visible page
var spaceInMiddle = 0; // default distance btw the logo and the top of the visible page
var spaceFromBottom = 27; // default distance between the bottom of thumbs and bottom of the visible page

// thumb layout
var thumbHolderPadding = 20;
var thumbBorder = 2;
var thumbMax = 85;
var swatchWidth = 85; // default swatch size
var swatchHeight = 85;

// status variables
var hasFlash;
if (swfobject.hasFlashPlayerVersion("10.0.0")) { // capture if flash is available
	hasFlash = true;
} else {
	hasFlash = false;
}
var currentFeature = null;
var totalFeatures = null;
var autoPlay = true;
// browser variables
var browserWidth;
var browserHeight;
var browserHeightIncludes = 70 + 14; // 70 for top nav, 19 for the first line of the bottom nav

//image map
var imageMapStorage = new Array();



// ----------------------
// 	  DOM Triggers
// ----------------------
$(window).resize(function() {
	trace('resize event');
	doResize();
	// scroll down to top of left nav
	scrollTo(0,80);
});
window.onorientationchange = function() { 
	trace('onorientationchange event');
	doResize();
};
//$(document).ready(function()  {
$(window).load(function()  {
	// initial columns
	doResize();
	
	// scroll down to top of left nav
	scrollTo(0,80);
	
	// load data
	$.getJSON(fdConfig, function(json) {
		fpData = json;
		
		basePath = fpData.basePath;
		//trace('basePath: ' + basePath);
		
		if (hasFlash === true){
			initLayout();
		} else {
			loadMaps();
		}
		
	 });
});
// ----------------------
// 	  frontdoor init
// ----------------------
function loadMaps(){
	
	var mapURL = fpData.basePath + '/js/maps.html';
	
	// load data
	$.ajax({
		url: mapURL,
		context: document.body,
		dataType: 'html',
	  	success: function(data){
	    	$('body').append(data)
			initLayout();
	  	}
	});
	
	
}
function initLayout(){
	// override placeFooter function
	window.placeFooter = function(){ };
	
	// setup page layout
	doResize();

	// prep icons
	var iconHTML = '' // placeholder for iconHTML
	
	// loop through features
	totalFeatures = fpData.features.length;

	// loop through features and setup icons
	for (var i = 0; i < totalFeatures; i++){
		var featureName = fpData.features[i].featureName;
		var imagePath = basePath + '/features/' + featureName + '/images/icon.jpg';
		
		var newDiv = '<div class="thumbDiv" id="thumbDiv' + i + '"><img id="thumbImage' + i + '" src="' + imagePath + '" width="' + swatchWidth + '" height="' + swatchHeight + '"></div>';
		
		$('#thumbHolder').append(newDiv);
		var newThumb = $('#thumbDiv' + i);
		
		// setup button 
		newThumb.click(function () {
			onClickThumb(this.id);
	    });
	}
	
	// set initial feature
	//setTimeout(setFeature, 2000, 0) 
	doResize(); 
	setFeature(0);
	trace('initLayout complete');
}
function onClickThumb(thisThumb){
	var thumbID = thisThumb.substring(8,thisThumb.length);
	trace('onClickThumb: ' + thisThumb + ' thumbID: ' + thumbID);
	autoPlay = false;
	setFeature(thumbID);
}
function onFeatureClick(id){
	//trace('onFeatureClick: ' + id);
	var linkJS = fpData.features[currentFeatureID].links[id];
	//alert('linkJS: ' + linkJS);
	getLink(linkJS);
}
function setFeature(newFeatureID){
	trace('setFeature: ' + newFeatureID);
	
	// gather feature info
	var featureName = fpData.features[newFeatureID].featureName;
	var assetPath = basePath + '/features/' + featureName;
	
	if (hasFlash === true){
		// -----------------
		// FLASH FEATURE SETUP
		// -----------------
		
		// prepare target div
		setupFlashTarget();
		
		// prepare embed values
		var flashvars = {path: assetPath + '/js/flash_config.json'};   
		var params = { wmode:"opaque", allowScriptAccess: "always", movie: "CoachFrontDoor", allowfullscreen: "true" };
		var attributes = { }; 
		var swfPath = assetPath + '/swf/' + featureName + '.swf';
		
		// create embed
		//trace('swfPath: ' + swfPath);
		swfobject.embedSWF(swfPath, "flashTarget","100%", "100%", "10.0.0", false, flashvars, params, attributes);
	
	} else {
		// ------------------
		// STATIC FEATURE SETUP
		// ------------------
		
		// if there is a prior image...
		$('#staticTarget').remove();
		
		// setup new image
		var imagePath = assetPath + '/images/static.jpg';
		var flashAltHTML = '<img id="staticTarget" src="' + imagePath + '" class="flashAltImage" usemap="#' + featureName + '">';
		$('#staticHolder').append(flashAltHTML);
		
	}
	// manually trigger doResize to populate staticImage with width and height;
	// and be certain the flashTarget has always been resized
	doResize(); 
	
	// deactivate all icons
	for (var i = 0; i < totalFeatures; i++){
		var thumbDiv = $('#thumbDiv' + i);
		thumbDiv.removeClass("thumbActive");
		thumbDiv.addClass("thumbNormal");
	}
	
	// select the active swatch
	var thumbDiv = $('#thumbDiv' + newFeatureID);
	thumbDiv.removeClass("thumbNormal");
	thumbDiv.addClass("thumbActive");
	
	
	// set newFeatureID as currentFeatureID
	currentFeatureID = newFeatureID;
	
	
	// if we're launching static content, trigger sequenceComplete 
	if (hasFlash === false){
		// set timer for advance
		sequenceComplete();
	}
	
}
function sequenceComplete(){
	//trace('sequenceComplete: ' + currentFeatureID);
	
	// check delay value
	var delayAfterCompleted = fpData.features[currentFeatureID].delayAfterCompleted;
	setTimeout(nextFeature, delayAfterCompleted*1000); 
}
function nextFeature(){
	//trace('nextFeature');
	
	// check on divs
	var divOpen = isDivOpen();
	
	if (autoPlay === true && divOpen === false) { // no divs and set to autoplay
		
		// remove old flash
		if (hasFlash == true){ 
			$('#flashTarget').remove();			
		} else {
			$('#staticTarget').remove();
		}

		// play the next feature or begin loop again
		if (currentFeatureID < totalFeatures-1){
			var nextFeature = Number(currentFeatureID)+1;
		} else {
			var nextFeature = 0;
		}
		setFeature(nextFeature);
		
	} else if (divOpen === true){
		
		//trace('div open - try again')
		setTimeout(nextFeatureProxy, 1000); 
		
	}
}
function nextFeatureProxy(){
	//trace('nextFeatureProxy');
	nextFeature();
}

// called when page is loaded or resized
function doResize(){
	//alert('doResize');

	// override placeFooter function
	window.placeFooter = function(){ };
	
	//var browserWidth = getBrowserSize().width;
	//var browserHeight = getBrowserSize().height;
	
	var browserHeight = $(window).height();
	var browserWidth = $(window).width();
	
	//trace('browserWidth: ' + browserWidth + ' browserHeight: ' + browserHeight);
	
	// establish min sizes
	if (browserHeight < minBrowserHeight){
		browserHeight = minBrowserHeight;
		trace('enforcing min height');
	}
	if (browserWidth < minBrowserWidth){
		browserWidth = minBrowserWidth;
		trace('enforcing min width');
	}
	
	// set nav column height
	$('#leftNav').css({'height':browserHeight});

	// scroll down to top of left nav
	//scrollTo(0,80);
	
	// -------------------------------------------
	//          BEGIN FEATURE SCALING 
	// -------------------------------------------
	
	if (scalePriority == 'maxWidth'){
		
		if (hasFlash === true){ 
			var featureWidth = browserWidth - minNavWidth;
			var featureHeight = browserHeight; 
			var newNavWidth = minNavWidth;
		} else {
			// switch scalePriority to maintainAspectRatio for non-flash content
			scalePriority = 'maintainAspectRatio';
		}
	}
	
	if (scalePriority == 'maintainAspectRatio'){
		
		// first try scaling feature by available height
		var featureRatio = nativeWidth/nativeHeight;
		var featureWidth = Math.floor(browserHeight * featureRatio);
		var featureHeight = browserHeight; 
		var newNavWidth = browserWidth - featureWidth;

		// check if the nav has gotten too small, if so prioritize width
		if (newNavWidth < minNavWidth){
			// scale feature by available width
			var featureRatio = nativeHeight/nativeWidth;
			var featureWidth = browserWidth - minNavWidth;
			var featureHeight = Math.floor(featureWidth * featureRatio);
			var newNavWidth = browserWidth - featureWidth;
		}
	}
	
	if (scalePriority == 'variableWidth'){
		
		if (hasFlash === true){ 
			
			// HANDLE WIDTH 
			//var columnRatio = minNavWidth/minContentWidth;
			var columnRatio = 0.6; 
			//trace('columnRatio: ' + columnRatio);
			
			var newNavWidth = Math.floor(browserWidth * (1-columnRatio));
			var featureWidth = Math.floor(browserWidth * columnRatio);
			
			//var featureWidth = browserWidth - minNavWidth;
			var featureHeight = browserHeight; 
			//var newNavWidth = minNavWidth;
			
			//trace('original -- newNavWidth: ' + newNavWidth + ' featureWidth: ' + featureWidth);
			
			// check if nav is too wide
			if (newNavWidth > maxNavWidth){
				//trace('----> nav too wide! ');
				newNavWidth = maxNavWidth;
				featureWidth = browserWidth - maxNavWidth;
			}
			// check if nav isn't wide enough
			if (newNavWidth < minNavWidth){
				//trace('----> nav not wide enough! ');
				newNavWidth = minNavWidth;
				featureWidth = browserWidth - minNavWidth;
			}
			
			//trace('final ----- newNavWidth: ' + newNavWidth + ' featureWidth: ' + featureWidth);		 
			
		} else {
			// switch scalePriority to maintainAspectRatio for non-flash content
			scalePriority = 'maintainAspectRatio';
		}
	}	
	
	
	//trace('scalePriority: ' + scalePriority + ' featureHeight: ' + featureHeight + ' featureWidth: ' + featureWidth);

	
	// apply layout changes
	$('#mainContent').css({'width':featureWidth}).css({'left':newNavWidth});
	$('#leftNav').css({'width':newNavWidth});
	
	// apply feature width/height
	if (hasFlash === true){
		$('#flashHolder').css({'width':featureWidth}).css({'height':featureHeight});
	} else {
		$('#staticTarget').css({'width':featureWidth}).css({'height':featureHeight});
		
		// reset viewport ------> REVIEW IF NEEDED
		if( $.browser.msie) window.scrollTo(0,0);

		// SCALE THE IMAGE MAP
		$($("#staticTarget").attr('usemap')).children().each( function () {
			updateMap($(this), featureWidth/nativeWidth, $("#staticTarget").attr('usemap'));
		});
	}
	
	// reposition footer and thumbHolder Y
	var newDivBottom = Number(browserHeight+80);
	$('#supplementary').css({'position':'absolute'}).css({'top':newDivBottom});
	
	
	// -------------------------------------------
	// adjust thumb size, horizontal position
	// -------------------------------------------
	newNavWidth = parseInt($('#leftNav').css('width')); // get actual value
	var targetHolderWidth = newNavWidth - Number(2 * thumbHolderPadding); // how big should the whole thumbHolder be?
	var targetThumbWidth = Math.floor(targetHolderWidth/totalFeatures); // how big should the individual thumbs be?
	
	if (targetThumbWidth > thumbMax){ // is the thumb size bigger than the original size?
		targetThumbWidth = thumbMax;  // use original size
	}
	
	var actualWidth = newNavWidth - Number(targetThumbWidth*totalFeatures);
	var leftEdge = Math.floor(actualWidth/2) - 1; // -1 because its landing too far to the right
	
	//trace('targetHolderWidth: ' + targetHolderWidth + ' targetThumbWidth: ' + targetThumbWidth + ' leftEdge: ' + leftEdge + ' actualWidth: ' + actualWidth);
	
	// loop through icons, by feature
	for (var i = 0; i < totalFeatures; i++){
		var newX = Number(leftEdge + Number(i*targetThumbWidth));//

		var thumbImage = $('#thumbImage' + i);
		thumbImage.css({'width':targetThumbWidth}).css({'height':targetThumbWidth});
		
		var thumbDiv = $('#thumbDiv' + i);
		thumbDiv.css({'left': newX}).css({'width':targetThumbWidth}).css({'height':targetThumbWidth});
		//trace('i: ' + i + ' newX: ' + newX);
	}
	
	// HANDLE HEIGHT SPACING
	if (browserHeight > minBrowserHeight){ // if we've got room to space things out
		// establish ratios using ideal spacing
		var idealTop = 95;
		var idealMiddle = 150;
		var idealBottom = 95;
		var idealTotal = idealTop + idealMiddle + idealBottom;
	
		var topRatio = idealTop/idealTotal;
		var middleRatio = idealMiddle/idealTotal;
		var bottomRatio = idealBottom/idealTotal;
	
		//trace('topRatio: ' + topRatio + ' middleRatio: '+ middleRatio + ' bottomRatio: ' + bottomRatio);
	
		var heightAvailable = browserHeight-minBrowserHeight;
		
		spaceFromTop = Math.floor(topRatio * heightAvailable);
		spaceInMiddle = Math.floor(middleRatio * heightAvailable);
		spaceFromBottom = Math.floor(bottomRatio * heightAvailable);
		
		if (spaceFromBottom < 27){
			spaceFromBottom = 27;
		}
		
		//trace('spaceFromTop: ' + spaceFromTop + ' spaceInMiddle: '+ spaceInMiddle + ' spaceFromBottom: ' + spaceFromBottom);
		
	} else {
		spaceFromTop = 0;
		spaceInMiddle = 0;
		spaceFromBottom = 27;
	}
	
	// APPLY VERTICAL CHANGES
	$('#mainNav').css({'top':spaceFromTop});
	
	
	// reposition thumbHolder Y
	//var thumbHolderOffset = Number(thumbHolderPadding + targetThumbWidth + 4); //makes it equal to the padding on the sides
	var thumbHolderOffset = Number(spaceFromBottom + targetThumbWidth + 4); 
	var newThumbHolderY = browserHeight - thumbHolderOffset;
	$('#thumbHolder').css({'top':newThumbHolderY});
	
	
	setTimeout(revealHeaderFooter, 50);
}
function revealHeaderFooter(){
	
	// REVEAL header, footer and background
	$('#branding_wrapper').css({'visibility':'visible'});
	$('#supplementary').css({'visibility':'visible'});
	$('#outerContainer').css({'visibility':'visible'});
	$('body').css({'background-color': 'white'});
	
}
function isDivOpen(){
        //alert('checkDiv');
        if( $('div.popupContent').is(':visible') ) {
                return true;
        } else if ($('#DivContainer').children().length > 0) {
                return true;
        } else {
				return false;
		}
}
function setupFlashTarget(){
	//trace('setupFlashTarget');
	var flashTargetHTML = '<div id="flashTarget" style="position:relative !important;"></div>'
	$('#flashHolder').append(flashTargetHTML);
}
// ----------------------
// 	  utilities 
// ----------------------
function trace(s) {
	try { 
		console.log(s);
	} catch (e) { 
		//alert(s);
	}
};
function getFlashMovie(movieName) {
	return obj = $('#flashTarget')[0];
}
function getLink(args) {
	trace(args);
	eval(args);
}
function getBrowserSize(){
	 var viewportwidth;
	 var viewportheight;

	 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	 if (typeof window.innerWidth != 'undefined')
	 {
	      viewportwidth = window.innerWidth,
	      viewportheight = window.innerHeight
	 }

	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	 else if (typeof document.documentElement != 'undefined'
	     && typeof document.documentElement.clientWidth !=
	     'undefined' && document.documentElement.clientWidth != 0)
	 {
	       viewportwidth = document.documentElement.clientWidth,
	       viewportheight = document.documentElement.clientHeight
	 }

	 // older versions of IE
	 else
	 {
	       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
	       viewportheight = document.getElementsByTagName('body')[0].clientHeight
	 }
	return {'width':viewportwidth, 'height': viewportheight}
}
// ----------------------
// 	  image map resize
// ----------------------
function updateMap(mapArea, scale, mapname){
	var mapId = mapArea.attr('id');
	var coords = mapArea.attr('coords');
	
	//trace(mapId);
	
	if(imageMapStorage[mapname+mapId]) {
		coords = imageMapStorage[mapname+mapId];
	} else {
		imageMapStorage[mapname+mapId] = coords;
	}
	
	if (coords == undefined) return; // end processing if coords is undefined
	
	var working = coords.split(",");
	for(var i=0; i < working.length; ++i){
		working[i] = Math.round(Number(working[i])*scale).toString();
	}
	var updatedCoords = working.join(",");
	mapArea.attr('coords', updatedCoords);
}

