var currentLayout = 'not set';
var currentMode = 'not set';
var currentState = 0;
var currentMax = 0;
var currentGridHeight = 0;
var currentGridWidth = 0;

function _updateDebugText() {
/*
	if(currentMax > 0) {
		document.title = currentLayout + ';' + currentMode + ';' + currentState + '/' + currentMax;
	} else {
		document.title = currentLayout + ';' + currentMode;
	}
*/
}

function _getLayout() {
	return(currentLayout);
}

function _setLayout(layout) {
	if(currentLayout == 'not set') {
		_gaq.push(['_setCustomVar',1,'Layout',layout,3]);
		_gaq.push(['_trackPageview']);
		_gaq.push(['_trackEvent', 'Layout', 'Initial', layout]);
	}
	else if(currentLayout != layout) {
		_gaq.push(['_trackEvent', 'Layout', 'Update', currentLayout + "/" + layout]);
	}
	currentLayout = layout;
	_updateDebugText();
}

function _setMode(mode) {
	currentMode = mode;
	_updateDebugText();
}

function _setProgress(s,m) {
	currentState = s;	
	currentMax = m;
}

function _getGridHeight() {
	return(currentGridHeight);
}

function _getGridWidth() {
	return(currentGridWidth);
}

function getCrossBrowserStyle(el,cssRule) {
	var strValue = "";
	
	if(window.getComputedStyle) {
		strValue = window.getComputedStyle(el,"").getPropertyValue(cssRule);
	} else if(el.currentStyle) {
		cssRule = cssRule.replace(/\-(\w)/g, function(strMatch,p1) { return p1.toUpperCase(); });
		strValue = el.currentStyle[cssRule];
	}
	
	return(strValue);
}

function getPixelValue(dim) {
	var end;
	
	if(dim == 'auto') {				/* to work around browswer funnies */
		return(0);
	}
	
	end = dim.search("px");
	if(end >= 0) {
		return(Number(dim.substring(0,end)));
	} 
	
	end = dim.search("em");
	if(end >= 0) {
		var emValue = Number(dim.substring(0,end));
		var pxValue = $(emValue).toPx();
		
		end = pxValue.search("px");
		return(Number(pxValue.substring(0,end)));
	}
	
	return(dim);
}

function updateLayout() {
	var cssStyle = $("#cssDetect").css("width");  /* hidden div to determine loaded CSS file */
	
	if(cssStyle == "200px") {
		if(_getLayout() == 'mobile') {
			return('');
		} else {
			_setLayout('mobile');
			return('data-src-mobile');
		}
	}
	else if(cssStyle == "481px") {
		if(_getLayout() == 'small') {
			return('');
		} else {
			_setLayout('small');
			return('data-src-small');
		}
	}
	else if(cssStyle == "1025px") {
		if(_getLayout() == 'large') {
			return('');
		} else {
			_setLayout('large');
			return('data-src-large');
		}
	}
	else {
		if(cssStyle == undefined) {
			_gaq.push(['_trackEvent', 'CodeIssue', 'UnknownLayout', 'could not find cssDetect']);
		} else {
			_gaq.push(['_trackEvent', 'CodeIssue', 'UnknownLayout', 'other cssDetectWidth: ' + cssStyle]);
		}
		_setLayout('small');
		return('data-src-small');
	}
}

function updateResponsiveImages(slider,showProgress,imgClass) {
	var imgCount = 0;
	var imgLoadCount = 0;
	var lastImgLoadCount = 0;
	var imgWaitCount = 0;
	var imgLastWaitCount = 0;
	var dataSrc;
	var startTime;
	var endTime;
	
	var $time = Date.now || function() { return +new Date; };

	var progressBar = $("#progressbar");
	
	startTime = $time();

	dataSrc = updateLayout();
	if(dataSrc == '') {
		return;
	}

	if(slider) {
		slider.pause();
	}
	
	if(showProgress) {
		progressBar.progressbar({value: 0});
	}
	
	var elements = $(imgClass);
	elements.each(function(){
		if($(this).attr('src') != $(this).attr(dataSrc)) {
			$(this).attr('src',$(this).attr(dataSrc)).load(function(){ imgLoadCount++; });
		  imgCount++;
		}
	});
	if(imgCount == 0) {
		if(slider) {
			slider.resume();
		}
		return;
	}
	
	/* wait for images to finish loading */
	if(showProgress) {
		$.doTimeout(100,function(){
			progressBar.progressbar({value: imgLoadCount*100/imgCount});
			if(imgLoadCount > lastImgLoadCount) {
				lastImgLoadCount = imgLoadCount;
				lastImgWaitCount = imgWaitCount;
			}
			if(imgLoadCount == imgCount){
				$("#progressPopup").dialog('close');
				if(slider) {
					slider.resume();
				}
	
				endTime = $time();
				if(endTime > startTime) {
					_gaq.push(['_trackEvent', 'Timing', 'ImageLoad', 'n/a', Math.round((endTime - startTime)/1000)]);
				}
				
				return false;
			}
			if(imgWaitCount == 25) {
				$("#progressPopup").dialog('open');
			}
			if(imgLoadCount > 5 && imgWaitCount > 2 * lastImgWaitCount) {
				$("#progressPopup").dialog('close');
				if(slider) {
					slider.resume();
				}

				endTime = $time();
				if(endTime > startTime) {
					_gaq.push(['_trackEvent', 'Timing', 'ImageLoad', 'n/a', Math.round((endTime - startTime)/1000)]);
				}

				_gaq.push(['_trackEvent', 'CodeIssue', 'ImageLoadTimeout', imgLoadCount + "/" + imgWaitCount]);
				return false;
			}
			imgWaitCount++;
			return true;
		});
	}
	else {
		if(slider) {
			slider.resume();
		}
	}
};
		
function updateGrid(width,height,posIcons){
	var imageContainer = document.getElementById("featuredImages");
	var topSpaceValue = $("tr.responsiveGridHeaderRow").height();
	var bottomSpaceValue = $("tr.responsiveGridFooterRow").height();
	var leftSpaceValue = getPixelValue(getCrossBrowserStyle(imageContainer,"margin-left"));
	var rightSpaceValue = getPixelValue(getCrossBrowserStyle(imageContainer,"margin-right"));
	var imgWidth;
	var imgHeight;
	var spacerWidth;
	
	currentGridWidth = width;
	currentGridHeight = height;
	
	/* configure fluid grid table */
	if((height - topSpaceValue - bottomSpaceValue) * 1.5 < (width - leftSpaceValue - rightSpaceValue)) {
		/* height constrained */
		imgHeight = height - topSpaceValue - bottomSpaceValue;
		imgWidth = imgHeight * 1.5;
		spacerWidth = (width - imgWidth - leftSpaceValue - rightSpaceValue) / 2;

		$("tr.responsiveGridContentRow").height(imgHeight);

		$("td.responsiveGridLeftSpacer").width(spacerWidth);
		$("td.responsiveGridContentColumn").width(width - (spacerWidth * 2));
		$("#responsiveGridStage").height(imgHeight);
		$("#gallery").width(imgWidth);
	  $("#gallery").height(imgHeight);
		$("td.responsiveGridRightSpacer").width(spacerWidth);
	} else {
		imgWidth = width - leftSpaceValue - rightSpaceValue;
		imgHeight = (imgWidth / 1.5);
		
		$("tr.responsiveGridContentRow").height(imgHeight);

		$("td.responsiveGridLeftSpacer").width(0);
		$("td.responsiveGridContentColumn").width(width);
		$("#responsiveGridStage").height(imgHeight);
		$("#gallery").width(imgWidth);
	  $("#gallery").height(imgHeight);
		$("td.responsiveGridRightSpacer").width(0);
	}
	
	/* position floating header */
	var logoMarginValue = getPixelValue(getCrossBrowserStyle(document.getElementById("logo"),"margin-right"));
	var contactMarginValue = getPixelValue(getCrossBrowserStyle(document.getElementById("contactInfo"),"margin-right"));
	var headerPos = $("#floatingHeaderAnchor").offset();
	var headerOffset = $("#logo").width() + logoMarginValue + $("#contactInfo").width() + contactMarginValue + 40;  /* help IE with rounding */
	
	$("#floatingHeader").css({"left": headerPos.left-headerOffset, "top": headerPos.top});
	$("#floatingHeader").width(headerOffset);
	
	/* position & scale background elements */
	var menuPos = $("#navLinks").offset();
	
	$("#backgroundMenuBox").css({"left": menuPos.left, "top": menuPos.top});
	
	/* position the icons */
	if(posIcons) {
		var iconPos = $("#gallery").offset();
		var iconHeight = $("#navIcons").height();
		
		$("#navIcons").css({"left": iconPos.left - 75, "top": iconPos.top + imgHeight - iconHeight});
	}
};

function getMaxWidth() {
	var parentHeight = $(this).height();
	var parentWidth = $(this).width();
	
	if(parentHeight * 1.5 < parentWidth){
		return(parentHeight * 1.5);
	}
	else {
		return(parentWidth);
	}
}

function getMaxHeight() {
	var parentHeight = $(this).height();
	var parentWidth = $(this).width();
	
	if(parentHeight * 1.5 < parentWidth){
		return(parentHeight);
	}
	else {
		return(parentWidth / 1.5);
	}
}

function configureGallery(selector,name,callback) {
	$.get("content.xml", function(data) {
  		$(data).find('gallery[id='+name+']').each(function() {
				var pathLarge = $(this).find('layout[id="large"]').attr('src');
				var pathSmall = $(this).find('layout[id="small"]').attr('src');
				var pathMobile = $(this).find('layout[id="mobile"]').attr('src');
			
				$(this).find('img').each(function(i,e) {
					$(selector).append('<li><img class="responsiveImage" src="images/space.png" ' +
														 'data-src-large="' + pathLarge + '/' + $(e).attr("src") + '" ' +
														 'data-src-small="' + pathSmall + '/' + $(e).attr("src") + '" ' +
														 'data-src-mobile="' + pathMobile + '/' + $(e).attr("src") + '"/></li>');
			});
		}); 

		if(typeof callback == 'function') {
			callback();
		}
	},
	"xml")
	.error(function(e) {
		_gaq.push(['_trackEvent', 'CodeIssue', 'ContentConfigError', e.statusText]);
	});
}

function configureMotionPlaylist(selector,name,callback) {
	var playerSize;
	var playerWidth, playerHeight;
	
	if(_getLayout() == "large") {
		playerSize = { width: "640px", height: "360px", cssClass: "jp-video-360p" };
		playerWidth = 670;
		playerHeight = 670;
	}
	else if(_getLayout() == "small") {
		playerSize = { width: "480px", height: "270px", cssClass: "jp-video-270p" };
		playerWidth = 510;
		playerHeight = 530;
	}
			

	$.get("content.xml", function(data) {
		$(data).find('playlist[id='+name+']').each(function() {
			var urlM4V = $(this).find('folder[id="m4v"]').attr('url');
			var urlOGV = $(this).find('folder[id="ogv"]').attr('url');
			var urlWEBMV = $(this).find('folder[id="webmv"]').attr('url');
			var urlPoster = $(this).find('folder[id="poster"]').attr('url');
		  var playList = new Array();
			var videoCount = 0;

			$(this).find('video').each(function(i,e) {
				var videoData = new Object();

				videoData.title = $(this).attr('title');
				videoData.free = false;
				videoData.m4v = urlM4V + "/" + $(this).attr('src') + ".mp4";
				videoData.ogv = urlOGV + "/" + $(this).attr('src') + ".ogv";
				videoData.webmv = urlWEBMV + "/" + $(this).attr('src') + ".webmv";
				videoData.poster = urlPoster + "/" + $(this).attr('poster');
				
				playList[videoCount] = videoData;								
				videoCount++;
			});

			$.get("scripts/jplayer.allklier-template.html", function(data) {
					$(selector).append(data);
					for(i=0;i<videoCount;i++) {
						$("#titleList").append('<li class><div><a href="javascript:;" class="jp-playlist-item" tabindex="1">title</a></div></li>');
					}
						
					new jPlayerPlaylist(
					{
						jPlayer: "#videoPlayer_1",
						cssSelectorAncestor: "#videoContainer_1"
					}, 
					playList,
					{
						play: function(e) {
							_gaq.push(['_trackEvent', 'Media', 'Play Video', e.jPlayer.status.media.title]);
						},
						solution: "html, flash",
						size: playerSize,
						supplied: "m4v, ogv, webmv",
						swfPath: "/scripts"
					}
				);
	
				if(typeof callback == 'function') {
					callback();
				}
			},
			"html")
			.error(function(e) {
				console.log("template load error: " + e.statusText);
				_gaq.push(['_trackEvent', 'CodeIssue', 'ContentTemplateError', e.statusText]);
			});
		});
	},
	"xml")
	.error(function(e) {
		console.log("content load error: " + e.statusText);
		_gaq.push(['_trackEvent', 'CodeIssue', 'ContentConfigError', e.statusText]);
	});
}

