var Fma = function () {
	//private static vars
	var IS_ANIMATING = new Boolean();
	var ANIMATION_SPEED = 1500;
	var DEFAULT_EASE = 'easeInOutQuint';
	var VIDEO_IN = new Boolean();

	// private vars
	var _fmaContainer;
	var _fmaParent;
	var _fmaPreloader;
	var _fmaControls;
	var _fmaWindow;
	var _fmaBackground;

	var _bottomBtnContainer;
	var _viewAll;
	var _fmaWrapper;
	var _backBtn;
	var _rightBtn;
	var _data;
	var _dimensions;
	var _fmaArr = new Array();
	var _textureArr = new Array();
	var _fmaHeight;
	var _fmaWidth;
	var _currentFmaNum = -1;
	var _selectedThumb = null;
	var _winWidth;
	var _winHeight;
	var _bgColor;
	var _imagePathArr = new Array();
	var _imageArr = new Array();
	var _clearDiv;
	var _parentWidth;
	var _currentURL;
	var _fmaReady = new Boolean();
	var _noImagePath = "/assets/images/fmas/amstdca/homePageRotator/no_image.jpg";

	// public vars
	this.className = "cta";
	this.currentFmaNum = 0;
	this.fmaArr = _fmaArr;
	this.textureArr = _textureArr;
	this.ready = _fmaReady;

	// public methods
	this.init = init;
	this.slideNext = slideNext;
	this.slideBack = slideBack;
	this.toggleViewAll = function () { toggleViewAll() };
	this.setFeature = function (num) { setCurrentFeature(num) };
	this.share = function () { share() };
	this.togglePlayVideo = function () { togglePlayVideo() };
	this.removePreloader = function () { removePreloader() };

	///////////////////////////////////////////
	//Initialize
	///////////////////////////////////////////

	function init(dataPath, container, dimensions) {
		IS_ANIMATING = false;

		//define container
		_fmaParent = $(container);
		_dimensions = dimensions.split(",");
		_fmaWidth = _dimensions[0];
		_fmaHeight = _dimensions[1];

		_clearDiv = "<div class='clear'></div>";

		//fetch data
		$.ajax({
			type: "GET",
			url: dataPath,
			dataType: "xml",
			success: setXML
		});

		function setXML(xml) {
			_data = xml;
			createContainers();
		}
	}

	///////////////////////////////////////////
	//Data Parsing
	///////////////////////////////////////////

	function parseXml() {
		$(_data).find("item").each(function () {
			var obj = {
				title: $('title', this).text(),
				subtitile: $('subtitile', this).text(),
				url: $('url', this).text(),
				mainImage: $('mainImage', this).text(),
				compColor: $('compColor', this).text(),
				compTexture: $('compTexture', this).text(),
				videoType: $(this).find('video').attr('type'),
				videoID: $(this).find('video').children('videoID').text()
			};

			_fmaArr.push(obj);
			_textureArr.push($('compTexture', this).text());
			_imagePathArr.push($('mainImage', this).text());
			_imagePathArr.push($('compTexture', this).text());
		});

		preloadImages();
	}

	///////////////////////////////////////////
	//Image Preloading
	///////////////////////////////////////////

	function preloadImages() {

		var images = _imagePathArr.length - 1;
		for (i = 0; i <= images; i++) {
			_imageArr[i] = new Image()
			_imageArr[i].src = _imageArr[i];
		}

		parseFeatures();
	}

	function removePreloader() {

		_fmaPreloader.animate(
			{
				"opacity": 0
			},
				ANIMATION_SPEED,
				DEFAULT_EASE,
				function () {
					_fmaPreloader.remove();
				}
			);

	}

	function parseFeatures() {
		var arrLength = _fmaArr.length - 1;
		for (i = 0; i <= arrLength; i++) {
			createFeature(i);
		}

		createThumbs();
	}

	///////////////////////////////////////////
	//Feature setup
	///////////////////////////////////////////

	function createContainers() {
		/////Create FMA Container
		_fmaContainer = "<div id='fmaContainer'></div>";
		_fmaParent.append(_fmaContainer);
		_fmaContainer = $("#" + "fmaContainer");

		/////Create FMA Background
		_fmaBackground = "<div id='fmaBg'></div>";
		_fmaContainer.append(_fmaBackground);
		_fmaBackground = $("#" + "fmaBg");

		var bgColorContainer = "<div id='bg-color-container'></div>";
		_fmaBackground.append(bgColorContainer);

		var gradOverlay = "<div id='grad-overlay'></div>";
		_fmaBackground.append(gradOverlay);
		gradOverlay = $("#" + "grad-overlay");
		gradOverlay.css({ 'height': _fmaHeight + 'px' });

		var darkOverlay = "<div id='dark-overlay'></div>";
		_fmaBackground.append(darkOverlay);
		darkOverlay = $("#" + "dark-overlay");
		darkOverlay.css({ 'height': _fmaHeight + 'px' });

		var videoBg = "<div id='videoBg'></div>";
		_fmaBackground.append(videoBg);
		videoBg = $("#" + "videoBg");


		xOffset = _fmaWidth / 2;
		videoBg.css({ 'height': _fmaHeight + 'px', 'width': _fmaWidth + 'px', 'margin-left': -xOffset + 'px' });

		/////Create FMA Window
		_fmaWindow = "<div id='fmaWindow'></div>";
		_fmaContainer.append(_fmaWindow);
		_fmaWindow = $("#" + "fmaWindow");
		_fmaWindow.css({ 'height': _fmaHeight + 'px', 'width': _fmaWidth + 'px', 'margin-top': -_fmaHeight + 'px' });

		_fmaWrapper = "<div id='fma-wrap'/>";
		_fmaWindow.append(_fmaWrapper);
		_fmaWrapper = $("#" + "fma-wrap");
		$("#fma-wrap a").css({ 'width': _fmaWidth + 'px' });

		/////Create FMA Control Container
		_bottomBtnContainer = "<div class='bottom-btn-container'></div>";
		_fmaContainer.append(_bottomBtnContainer);
		_bottomBtnContainer = $("." + "bottom-btn-container");

		/////Create FMA Preloader
		_fmaPreloader = "<div id='fmaPreloader'><img src='/assets/images/fma/interface/preloader.gif' alt='American Standard Canada' /></div>";
		_fmaContainer.append(_fmaPreloader);
		_fmaPreloader = $("#" + "fmaPreloader");
		_fmaPreloader.css({ 'height': _fmaHeight + 'px', 'margin-top': -_fmaHeight + 'px' });



		$('#videoPlayer').css({ 'margin-left': -xOffset + 'px' });

		var label = $(_data).find("close").text();
		var closeBtn = "<div class='videoClose'><a href='javascript:fma.togglePlayVideo()'></a></div>";
		$('#videoPlayer').append(closeBtn);

		parseXml();
	}

	function createFeature(num) {
		var divId = 'fma-item' + num;
		var fmaItem = "<div id='" + divId + "'" + "class='fma-frame'></div>";
		$("#fma-wrap").append(fmaItem);

		//var xOffset = _fmaWidth;
		//$('.frame-right').css({'margin-left' : xOffset + 'px'});

		var fmaURL = _fmaArr[num]["url"];

		var playOverlay = '';
		if (_fmaArr[i]["videoType"] == "brightcove") {
			playOverlay = "<div class='playOverlayBig'></div>"
			fmaURL = "javascript:fma.togglePlayVideo()"
		}

		//alert("image URL = " + _fmaArr[num]["mainImage"] );

		if (fmaURL.length > 1) $("#" + divId).html("<a href='" + fmaURL + "'><img src='" + _fmaArr[num]["mainImage"] + "'width=" + _fmaWidth + "px' height=" + _fmaHeight + "'px' alt=''/>" + playOverlay + "</a>");
		else $("#" + divId).html("<img src='" + _fmaArr[num]["mainImage"] + "'width=" + _fmaWidth + "px' height=" + _fmaHeight + "'px' alt='' />");

		$("#" + divId + ' img').error(function () {
			$("#" + divId).html("<img src='" + _noImagePath + "'width=" + _fmaWidth + "px' height=" + _fmaHeight + "'px' alt='' />");
		});


		var title = _fmaArr[num]["title"];
		title = title.replace("™", "<span class='superscript'>™</span>");
		title = title.replace("®", "<span class='superscript'>®</span>");
		title = title.replace("©", "<span class='superscript'>©</span>");

		var subtitle = _fmaArr[num]["subtitile"];
		/*	subtitle = subtitle.replace( "™", "<span class='superscript'>™</span>" );
		subtitle = subtitle.replace( "®", "<span class='superscript'>®</span>" );
		subtitle = subtitle.replace( "©", "<span class='superscript'>©</span>" );*/

		var fmaHeader = "<div class='fma-header'>" +
						"<h1>" + title + "</h1>" +
						"<p>" + subtitle + "</p>" +
						"</div>";


		if (title.length > 1) $("#" + divId).append(fmaHeader);


		if (playOverlay != '') {
			var xOffset = (_fmaHeight / 2) - ($('.playOverlayBig').height() / 2);
			var yOffset = (_fmaWidth / 2) - ($('.playOverlayBig').width() / 2);
			$('.playOverlayBig').css({ 'margin-top': xOffset + 'px', 'margin-left': yOffset + 'px' });
		}

		var arrLength = _fmaArr.length - 1;
		if (num == arrLength) {
			setCurrentFeature(0);
			setNav();
			fma.ready = true;
			EventBus.dispatch("FMA_READY");
		}
	}

	function setCurrentFeature(num) {
		if (num != _currentFmaNum) {
			if (num > _fmaArr.length - 1) num = 0;
			else if (num < 0) num = _fmaArr.length - 1;
			_currentFmaNum = num;
			this.currentFmaNum = num;
			setBackground(_fmaArr[num]["compColor"], _fmaArr[num]["compTexture"]);
			_currentURL = _fmaArr[num]["url"];
			winResize(true);
			EventBus.dispatch("FMA_CHANGE", this, _currentFmaNum);
			if (_viewAll != undefined && $(_viewAll).is(':visible')) toggleViewAll();
			setSelectedThumb();

			//alert(_fmaArr[num]["videoType"] + ", " + _fmaArr[num]["videoID"]);
		}
	}

	function setBackground(color, texture) {
		var previous = null

		if (_bgColor != null) previous = _bgColor

		_bgColor = "<div class=bg-color id='bg-color" + _currentFmaNum + "'></div>";
		$('#bg-color-container').append(_bgColor);
		_bgColor = $('#bg-color' + _currentFmaNum);

		_bgColor.css({
			'background-color': '#' + color,
			'width': '100%',
			'height': _fmaHeight + 'px',
			"opacity": 0
		});

		IS_ANIMATING = true;

		_bgColor.animate(
		{
			"opacity": 1
		},
			ANIMATION_SPEED,
			DEFAULT_EASE,
			function () {
				clearPrevious(previous);
			}
		);
	}

	function clearPrevious(p) {

		IS_ANIMATING = false;
		if (p != null) {
			p.remove();
		}
	}

	///////////////////////////////////////////
	//Thumb setup
	///////////////////////////////////////////

	function createThumbs() {
		_viewAll = "<div id='view-all'></div>";
		_fmaContainer.append(_viewAll);
		_viewAll = $("#" + "view-all");
		_viewAll.css({ 'margin-top': -_fmaHeight + 'px' });

		var overlay = "<div onClick='fma.toggleViewAll();' class='overlay'></div>";
		_viewAll.append(overlay);
		overlay = $("." + "overlay");
		overlay.css({ 'height': _fmaHeight + 'px' })

		var thumbs = "<div class='thumbs'></div>";
		_viewAll.append(thumbs);
		thumbs = $("." + "thumbs");

		var label = $(_data).find("close").text();
		var closeBtn = "<div class='closeBtn' onClick='javascript:fma.toggleViewAll();'><div class='icon'></div><p>" + label + "</p></div><div class='clear'></div>";
		thumbs.append(closeBtn);
		closeBtn = $("." + "closeBtn");

		var ul = "<ul class='thumbList'>";

		var arrLength = _fmaArr.length - 1;
		for (i = 0; i <= arrLength; i++) {
			var playOverlay = '';
			if (_fmaArr[i]["videoType"] == "brightcove") {
				playOverlay = "<div class='playOverlaySmall'></div>"
			}

			ul += "<li class='thumb-" + i + " thumb' onClick='fma.setFeature(" + i + ")'>" + "<img src='" + _fmaArr[i]['mainImage'] + "'/>" + playOverlay + "</li>"



		}

		ul += "</ul>"

		thumbs.append(ul);

		$('.thumb img').error(function () {
			//alert(_noImagePath);
			$('.thumb img').html("<img class='noImageThumb' src='" + _noImagePath + "'/>");
		});

		$('li.thumb').bind('mouseenter mouseleave', function () {
			$(this).toggleClass('thumbOver');
		});

		thumbs.append(_clearDiv);
	}

	function centerThumbs() {
		var thumbHeight = $(".thumbs").height();
		var topMargin = (_fmaHeight - thumbHeight) / 2
		$(".thumbs").css({ 'top': topMargin + 'px' });
	}

	function setSelectedThumb() {
		if (_selectedThumb != null) _selectedThumb.removeClass("selectedThumb")
		_selectedThumb = $(".thumb-" + _currentFmaNum);

		_selectedThumb.addClass("selectedThumb")
	}

	///////////////////////////////////////////
	//Navigation
	///////////////////////////////////////////


	function toggleViewAll() {

		if (!$(_viewAll).is(':animated')) {
			if (!$(_viewAll).is(':visible')) fadeIn(_viewAll);
			else fadeOut(_viewAll);
		}

		centerThumbs();
	}

	function setNav() {
		_backBtn = "<div id='back-btn' class='slide-btn'><a href='javascript:fma.slideBack();'><div class='icon'></div></a></div>";
		_fmaContainer.append(_backBtn);
		var xOffset = _fmaWidth / 2;
		var yOffset = _fmaHeight / 2 - ($('#back-btn').height() / 2);
		$('#back-btn').css({ 'margin-left': -xOffset + 'px', 'margin-top': yOffset + 'px' });

		_nextBtn = "<div id='next-btn' class='slide-btn'><a href='javascript:fma.slideNext();'><div class='icon'></div></a></div>";
		_fmaContainer.append(_nextBtn);
		xOffset = (_fmaWidth / 2) - ($('#next-btn').width());
		$('#next-btn').css({ 'margin-left': (xOffset + 1) + 'px', 'margin-top': yOffset + 'px' });

		var clear = "<div class='clear'></div>";
		_fmaContainer.append(clear);

		var viewAllLabel = $(_data).find("viewAll").text();
		var viewAllBtn = "<div onClick='fma.toggleViewAll();' class='bottomBtn viewAllBtn'><div class='icon'></div><p>" + viewAllLabel + "</p></div>";
		_bottomBtnContainer.append(viewAllBtn);
		viewAllBtn = $("." + "viewAllBtn");

		var shareLabel = $(_data).find("share").text();
		var shareBtn = "<div onClick='fma.share();' class='bottomBtn shareBtn'><div class='icon'></div><p>" + shareLabel + "</p></div>";
		_bottomBtnContainer.append(shareBtn);
		shareBtn = $("." + "shareBtn");

		_bottomBtnContainer.append(_clearDiv);

		$('.bottomBtn').bind('mouseenter mouseleave', function () {
			$(this).toggleClass('bottomBtnOver');
		});

		centerBottomNav();

		$("div.videoWrap").mouseover(function () {
			$("div.videoClose").css({ 'display': 'block' });
		}).mouseout(function () {
			$("div.videoClose").css({ 'display': 'none' });
		});

		// hide buttons if there's only one element
		if (_fmaArr.length == 1) {
			$('#back-btn').hide();
			$('#next-btn').hide();
		}
	}

	function slideNext() {
		if (!IS_ANIMATING) slide("next");
	}

	function slideBack() {
		if (!IS_ANIMATING) slide("back");
	}

	function slide(dir) {
		if (dir == "next") {
			setCurrentFeature(_currentFmaNum + 1);
		} else {
			setCurrentFeature(_currentFmaNum - 1);
		}
	}

	function centerBottomNav() {
		var offset = _bottomBtnContainer.width() / 2
		_bottomBtnContainer.css({ "margin-left": + -offset + 'px' });
	}

	///////////////////////////////
	// Video functionality
	//////////////////////////////

	function togglePlayVideo() {
		if (!$('#videoPlayer').is(':animated')) {
			if (VIDEO_IN == false) {
				bcv.playVideo(_fmaArr[_currentFmaNum]['videoID']);
				var position = $('#fmaBg').position();

				fadeIn($('#videoBg'));
				fadeIn($('#dark-overlay'));
				fadeOut(_bottomBtnContainer);
				fadeOut($('#back-btn'));
				fadeOut($('#next-btn'));
				VIDEO_IN = true;
			}
			else {
				bcv.stopVideo();
				fadeOut($('#videoBg'));
				$('#videoPlayer').css({ 'top': '-1000px' });
				fadeOut($('#dark-overlay'));
				fadeIn(_bottomBtnContainer);
				fadeIn($('#back-btn'));
				fadeIn($('#next-btn'));
				VIDEO_IN = false;
			}
		}
	}

	function setVideoPosition() {
		var position = $('#fmaContainer').position();
		$('#videoPlayer').css({ 'top': position.top + 'px' });
	}


	///////////////////////////////
	// share modal
	//////////////////////////////

	var _gaq = _gaq || [];
	modalPath = '/shareModal.html';

	function share(shareTitle, sharePath, linkPath) {

		//alert("shareTitle = " + shareTitle + " | sharePath = " + sharePath + " | linkPath = " + linkPath);
		var titlePrefix = "American Standard - "

		if (shareTitle == null) shareTitle = "Style that works better";
		if (sharePath == null) sharePath = _currentURL;
		if (linkPath == null) {
			linkPath = _currentURL;
		}

		if (linkPath == sharePath) linkPath = '';

		shareTitle = titlePrefix + shareTitle;

		//alert("shareTitle = " + shareTitle + " | sharePath = " + sharePath + " | linkPath = " + linkPath);
		openShareModal(shareTitle, sharePath, linkPath)
	}

	///////////////////////////////////////////
	//Resizing
	///////////////////////////////////////////

	function winResize(fromNav) {
		_parentWidth = _fmaParent.width();

		_winWidth = $(window).width();
		_winHeight = $(window).height();

		if (_parentWidth < _fmaWidth) _parentWidth == _fmaWidth;

		var fmaMargin = (_parentWidth - _fmaWidth) / 2;
		fmaMargin = Math.round(fmaMargin);

		var wrapWidth = (parseInt(_fmaWidth) + parseInt(fmaMargin)) * _fmaArr.length;
		var offset = (parseInt(_fmaWidth) + parseInt(fmaMargin)) * _currentFmaNum;
		var leftDif = parseInt(fmaMargin) - offset;
		//alert("_fmaWidth = " +  _fmaWidth + ", " + "fmaMargin = " + fmaMargin + ", " +  "_fmaArr.length = " + _fmaArr.length + ", " +  "wrapWidth = " + wrapWidth);

		$("#fma-wrap").css({
			"width": +wrapWidth + 'px',
			"height": _fmaHeight + 'px'
		});

		var aSpeed = ANIMATION_SPEED;
		var dEase = DEFAULT_EASE;

		if (fromNav == false) {
			aSpeed = 0;
			dEase = 'none';
		}
		$("#fma-wrap").animate(
			{
				"left": leftDif + 'px'
			},
				aSpeed,
				dEase,
				function () {

				}
			);


		$(".fma-frame").css('margin-right', fmaMargin + "px");
		$("#fma-item" + (_fmaArr.length - 1).toString()).css('margin-right', 0 + "px");


		$('#fmaContainer').css({
			"overflow": 'hidden',
			"position": 'absolute',
			"width": _parentWidth + 'px',
			"height": _fmaHeight + 'px'
		});
	}

	$(window).resize(function () {


		winResize(false);

		//clearTimeout(timer);
		//setTimeout( winResize, 100);
	});

	//var timer = setInterval(winResize,1500);


	///////////////////////////////////////////
	//Utils
	///////////////////////////////////////////

	function fadeIn(element) {
		var currentId = $(element).attr('id');

		element.css({
			"display": 'block',
			"opacity": 0
		});

		element.stop().animate(
		{
			"opacity": 1
		},
			500,
			DEFAULT_EASE,
			function () {
				if (currentId == 'videoBg') setVideoPosition();
			}
		);
	}

	function fadeOut(element) {
		element.stop().animate({
			"opacity": 0
		},
			500,
			DEFAULT_EASE,
			function () { element.css({ "display": 'none' }) }
		);
	}
}


///////////////////////////////////////////
//FMA INITIALIZE
///////////////////////////////////////////



