$(document).ready(function() {
	$('.mainContent').css('display', 'none');

	if ($('div.regzaPopup.ourtech').length) {
		ourTechDiv = $('div.regzaPopup.ourtech');
	}
	if ($('div.regzaPopup.closerlook').length) {
		closerLookDiv = $('div.regzaPopup.closerlook');
	}
	if ($('div.regzaPopup.news').length) {
		newsDiv = $('#info');

		$('#subfooter .floatright a').not(':first-child').click(function() {
			showNews($(this).attr('href'));
			return false;
		});
	}
	if ($('.learnmore').length) {
		$('.learnmore').click(function() {
			showExperience($(this).attr('id'));
			return false;
		});
	}

}); // end of $(document).ready();


/******************  global vars ********************/
var ourTechDiv;
var modelTechDiv;
var closerLookDiv;
var newsDiv;

var basePath = '/regza/';

var paths = {
	JSPath: basePath + 'js/',
	XMLPath: basePath + 'xml/',
	SWFPath: basePath + 'swf/'
};

var mainConfig = {
	// this is hacky, and should be replaced with XML if we have further addtions to the model detail popups (chief)
	fourImageModels : [
		'26av502r','32av502r','37av502r','40rv525r','46rv525r','46sv670u','55sv670u','26lv610u','22lv611u','22lv610u','19lv611u','19lv610u' //'22av600u','19av600u',
	],
	foregroundFadeEvent: 'foregroundFade',
	screenSize: {
		width: window.innerWidth,
		height: window.innerHeight
	},
	bgFadeInTime: 1000,
	// in ms
	backgroundDiv: $('<div id="popupBackground">&nbsp;</div>'),
	defaultOption: $('<option value="0">Select A Model...</option>'),
	
	viewingExp: {
		xmlFile: paths.XMLPath + 'viewingexperience.xml',
		swfPath: paths.SWFPath + 'viewingexperience/'
	},

	ourTech: {
		xmlFile: paths.XMLPath + 'ourtechnology.xml',
		swfPath: paths.SWFPath + 'ourtechnology/'
	}
};

/*********** Helper Functions *************/

/* this function sets up the specific model page on load */
var modelPage = function() {
	var contentContainerDiv = $('#modelholder .contentscenter');
	var contentDivs = $('#modeldetails,#modelcontent',contentContainerDiv);

	if($.browser.msie && $.browser.version < 7)
		$('h1 img').css({ top: '4px', right: '15px' });

	// hide the content
	contentDivs.hide();  

	$('h1 img',contentDivs)
		.show()
		.wrap('<a href="#close" title="Close Section"></a>')
			.parent() // get anchor we just inserted
			.click(function() {
				$(this).parent().parent().slideUp('slow');
				return false;
			});
		
	$('#viewButtons a').click(function() {
		var divToSlide = $($(this).attr('href'));
		divToSlide.slideDown('slow',function() {
			$.scrollTo($(this),{ duration: 600, easing: 'easeOutCubic' });
		});
		return false;
	});
};

var fadeEverythingIn = function(foregroundDiv) {
	if ($('#popupBackground').length) {
		var background = $('#popupBackground');

		if (background.is(':visible')) // if background exists AND is visible already
		foregroundDiv.trigger(mainConfig.foregroundFadeEvent);
		else { // if background exists but is not visible
			mainConfig.backgroundDiv.css('opacity', 0).css('background-color', '#000000').show().fadeTo(mainConfig.bgFadeInTime, .75,
			function() {
				foregroundDiv.trigger(mainConfig.foregroundFadeEvent);
			});
		}
	} else {
		mainConfig.backgroundDiv.css('opacity', 0).css('background-color', '#000000').show().prependTo('body').fadeTo(mainConfig.bgFadeInTime, .75,
		function() {
			foregroundDiv.trigger(mainConfig.foregroundFadeEvent);
		});

	} // end main if then
}; // end of fadeEverythingIn()

var scrollToTop = function() {
	if ($.browser.msie && ($.browser.version < 7)) {
		$('html').animate({
			scrollTop: 0
		},
		'fast');
	}
};

var positionPopup = function(divToPosition) {
	var leftOffset = 0;
	var topOffset = 0;
	if (String(divToPosition.css('width')).search(/%/) > 0 || divToPosition.css('width') == 'auto') leftOffset = '-35%';
	else leftOffset = -(Number(divToPosition.css('width').slice(0, (divToPosition.css('width').length - 2))) / 2);
	topOffset = -(divToPosition.height() / 2);
	divToPosition.css({
		'margin-left': leftOffset,
		'margin-top': topOffset
	});
};

var closeWindow = function(divToClose) {

	mainConfig.backgroundDiv.click(function() {
		$('.closeWindow', $('.regzaPopup:visible')).trigger('click');
		return false;
	});

	$('.closeWindow', divToClose).click(function() {
		var foreground = divToClose;
		var background = mainConfig.backgroundDiv;

		$('.closeWindow,.leftButton,.rightButton', foreground).fadeOut('fast',
		function() {

			$('.mainContent', foreground).fadeOut('fast',
			function() {
				foreground.fadeOut();
				foreground.find('select').unbind('change').empty();

				foreground.find('.leftButton,.rightButton').unbind('click').find('.leftButton').attr('href', '#1').find('.rightButton').attr('href', '#3');

				background.fadeOut(500,
				function() {
					$(this).css('opacity', 0).remove();
					foreground.find('.flash-replaced').empty();
					foreground.find('.mainContent.ourtech .content,.mainContent.news .content,.mainContent.modeltech .content').empty();
				});
			}); // end of mainContent fadeOut 
		}); // end of buttons fadeOut

		$(this).unbind('click');
		return false;

	}) //end of click event
	// unbind all events attached to the div !!! IMPORTANT
	divToClose.unbind();
}; // end of closeWindow()
var createSelectBox = function(select, modelData) {
	select.empty().append(mainConfig.defaultOption);

	modelData.each(function() {
		var tmpOption = $('<option value="' + $(this).text() + '">' + $(this).text().toUpperCase() + '</option>');
		select.append(tmpOption);
	});
	return select;

}; // end of populateSelectBox()

/*************** main functions *******************/

/*				show news or info function 					*/
var showNews = function(articleURL) {
	if (typeof(articleURL) === 'undefined' || !articleURL.length) return false;

	var foregroundDiv = newsDiv;

	// pauses any flash
	flashPause('flashbanner');

	foregroundDiv.bind(mainConfig.foregroundFadeEvent,
	function() {
		positionPopup($(this));
		$(this).find('.mainContent').hide().fadeIn(function() {
			$('.left,.right', foregroundDiv).height($('.content', foregroundDiv).height() + 20);
			foregroundDiv.find('.closeWindow').fadeIn('fast');
			scrollToTop();
		}).end().show().fadeIn(500,
		function() {
			closeWindow(foregroundDiv);
		}); // end of foreground fadeIn
	}); // end of event

	if (!articleURL.match(/\/regza\//) && articleURL.indexOf("http")!=0) config = {
		articleURL: basePath + articleURL
	};
	else config = {
		articleURL: articleURL
	};

	$(".content",".regzaPopup").empty();//clear content because content didnt always update
	
	if(config.articleURL.indexOf("http")==0){
		generalOpenWin(config.articleURL,'reviewWin','width=800,height=600,scrollbars=1,resizable=1');
		//$(".content",".regzaPopup").append("<iframe src='"+http:/\/google.com+"' width='100%' height='100%'></iframe>");
		/*
		$.get(config.articleURL,
		function(data) {
			foregroundDiv.find('.left').css('overflow', 'hidden').end().find('.right').css('overflow', 'hidden').end().find('.content').append($(data));
			fadeEverythingIn(foregroundDiv);
		},
		'html');*/
	} else {
		$.get(config.articleURL,
		function(data) {
			foregroundDiv.find('.left').css('overflow', 'hidden').end().find('.right').css('overflow', 'hidden').end().find('.content').append($(data).find('#article').html());
			fadeEverythingIn(foregroundDiv);
		},
		'html');
	}
	return true;

};
/* end of showNews() */

var showExperience = function(ID) {
	if (typeof(ID) == 'undefined' || !ID.length) return false;

	var swf = '';
	var relatedTechnology = {};
	var foregroundDiv = ourTechDiv;
	var techSelect = $('select', foregroundDiv);

	$('.moreInfo .left').empty();

	foregroundDiv.bind(mainConfig.foregroundFadeEvent,
	function() {
		positionPopup($(this));
		$(this).hide().find('.mainContent').hide().fadeIn('fast',
		function() {
			foregroundDiv.find('.closeWindow').fadeIn('fast');
			$(this).find('.content').flash({
				src: mainConfig.viewingExp.swfPath + swf,
				width: '100%',
				height: '470'
			},
			{
				version: 9.0
			});
		}).end().fadeIn(500,
		function() {
			closeWindow(foregroundDiv);
			scrollToTop();
			techSelect.change(function() {
				if ($('option:selected', this).val() != 0) {
					$('.closeWindow a').trigger('click');
					document.location.href = basePath + 'models/' + $('option:selected', this).val() + '/';
				}
			}); // end of techSelect.change
		}); // end of foreground fadeIn
	}); // end of event
	$.get(mainConfig.viewingExp.xmlFile,
	function(viewingExpData) {
		var item = $(viewingExpData).find('item[id="' + String(ID) + '"]');

		if ($('relatedtechid', item).text().length) {
			// get 'our technology' XML
			$.get(mainConfig.ourTech.xmlFile, 'xml',
			function(ourTechData) {
				var data = $(ourTechData);
				var newLink = $('<a href="" title=""></a>');

				relatedTechnology.ID = Number($('relatedtechid', item).text());
				relatedTechnology.Title = String(data.find('item[id="' + relatedTechnology.ID + '"] headline').text());
				relatedTechnology.swf = String(data.find('item[id="' + relatedTechnology.ID + '"] swf').text());
				relatedTechnology.models = data.find('item[id="' + relatedTechnology.ID + '"] model');
				newLink.attr('href', basePath + 'technology/').attr('title', 'Learn more about: ' + relatedTechnology.Title).text(relatedTechnology.Title).click(function() {
					foregroundDiv.find('.content').empty().flash({
						src: mainConfig.ourTech.swfPath + relatedTechnology.swf,
						width: '100%',
						height: '470'
					});

					$('.moreInfo',foregroundDiv).fadeOut(750,
					function() {
						
						$('.left',this).empty();
						var newSelect = createSelectBox($('#availableModels', foregroundDiv), relatedTechnology.models);
						techSelect = newSelect;
						$(this).fadeIn('fast');
					}); 
					$log('done');
					return false;
				});
				$('.moreInfo .left', foregroundDiv).append(newLink).prepend('Learn More About:&nbsp;');
			});
		} // end of if..then for gettin relatedtech stuff
		// get data into select box
		techSelect = createSelectBox(techSelect, item.find('model'));

		swf = $(viewingExpData).find('item[id="' + String(ID) + '"] swf').text();

		fadeEverythingIn(foregroundDiv);

	},
	'xml');
}; // end of showExperience

/* openTech function for flash call */
var openTech = function(techID) {
	// check the argument
	if (typeof(techID) == 'undefined' || techID === NaN) return false;

	var foregroundDiv = ourTechDiv;
	var swf = '';
	var techSelect = $('select', foregroundDiv);
	techSelect.append(mainConfig.defaultOption);

	foregroundDiv.bind(mainConfig.foregroundFadeEvent,
	function() {
		positionPopup($(this));
		$(this).hide().find('.mainContent').fadeIn('fast',
		function() {
			$(this).find('.content').flash({
				src: mainConfig.ourTech.swfPath + swf,
				width: '100%',
				height: '100%'
			},
			{
				version: 9
			});
			$(this).parent().find('.closeWindow').fadeIn('fast');
		}).end().fadeIn(400);

		closeWindow($(this));
		scrollToTop();

		techSelect.change(function() {
			if ($('option:selected', this).val() != 0) {
				$('.closeWindow a').trigger('click');
				document.location.href = basePath + 'models/' + $('option:selected', this).val() + '/';
			}
		}); // end of techSelect.change
	}); // end of event

	$.get(mainConfig.ourTech.xmlFile,
	function(data) {
		$(data).find('item[id=' + Number(techID) + '] model').each(function() {
			var tmpOption = $('<option value="' + $(this).text() + '">' + $(this).text().toUpperCase() + '</option>');
			techSelect.append(tmpOption);
		}); // end for each	
		swf = String($(data).find('item[id=' + techID + '] swf').text());
		fadeEverythingIn(foregroundDiv);
	},
	'xml'); // end of ajax $.get
}; // end of openTech

var openCloserLook = function(modelID, modelDescription) {
	// check the argument
	if (typeof(modelID) === 'undefined' || !modelID.length) return false;
	
	$log((mainConfig.fourImageModels.toString().search(modelID) >= 0));

	var mainDiv = '.regzaPopup.closerlook';
	var contentDiv = '.regzaPopup.closerlook .mainContent';
	var foregroundDiv = closerLookDiv;
	// config for images
	var config = {
		base: basePath + 'img/models/',
		lg_suffix: '_galleryLg_',
		sm_suffix: '_gallerySm_'
	};

	// config for models, this probably will be replaced by XML, maybe it should be JSON though?
	var models = '';

	// function to fade out large image, swap in new SRC, and then fade back in
	var swapLargeImage = function(newImageNum) {
		var oldImage = $('.content img', foregroundDiv).get(0); // get the main image DOM node
		var newImageSrc = config.base + modelID + config.lg_suffix + newImageNum + '.png';
		$(oldImage).animate({
			opacity: 0
		},
		250,
		function() {
			$(this).attr('src', newImageSrc).animate({
				opacity: 1
			},
			250);
		}); // end of animate
	}; // end of swapLargeImage

	foregroundDiv.find('.closeWindow,.leftButton,.rightButton').hide().end().find('.mainContent .content h1').text(modelID.toUpperCase()).end().find('.mainContent .content h2').text(modelDescription).end().find('.leftButton img, .rightButton img').attr('width', '33').attr('height', '34').end().find('.leftArrow a, .rightArrow', foregroundDiv).css('top', '43%').end().find('.thumbnails img').each(function(i) {
		var newThumbSrc = config.base + modelID + config.sm_suffix + Number(i + 1) + '.png';
		var newThumbHref = '#' + (i + 1);
		var newThumbAlts = ['Left view', 'Main view', 'Right view', 'Alternate view'];
		var newThumb = $('<img src="' + newThumbSrc + '" alt="' + newThumbAlts[i] + ' model ' + modelID + '" border="0" />');
		$(this).replaceWith(newThumb);
		if (i === 1) {
			newThumb.css('opacity', 1).addClass('active').parent().removeAttr('href');
		}
		else newThumb.parent().attr('href', newThumbHref);
	});

	$('.content img:first', foregroundDiv).attr('src', config.base + modelID + config.lg_suffix + '2.png').height('320px');

	foregroundDiv.css('display', 'block').find('.mainContent').css('display', 'block').css('left', '-9999px');

	foregroundDiv.bind(mainConfig.foregroundFadeEvent,
	function() {
		var hasFourImages = false;
		
		if(mainConfig.fourImageModels.toString().search(modelID) >= 0)
			{
				hasFourImages = true;
				$('.thumbnails a:hidden').show();
			}
		else
			$('.thumbnails a:nth-child(4)').hide(); 

		positionPopup($(this));
		$(this).css('left', '50%').find('.mainContent').hide().css('left', '0');
		$('.closeWindow,.leftButton,.rightButton', foregroundDiv).fadeIn(500);
		$('.mainContent', foregroundDiv).fadeIn(750,
		function() {

			$('.thumbnails img', $(this)).not('.active').animate({
				opacity: 0.5
			},
			'slow');
			scrollToTop();
			closeWindow(foregroundDiv);

			// navigate thumbnails
			$('.thumbnails a, .leftButton, .rightButton', foregroundDiv).click(function() {
				if (typeof($(this).attr('href')) === 'undefined' || !$(this).attr('href').length) return false;

				var oldMainImage = $('.content img', foregroundDiv).get(0);
				oldMainImage.src.match(/galleryLg_([1-4])/);
				var oldMainIndex = RegExp.$1;
				var newIndex = Number($(this).attr('href').match(/[1-4]/));
				var oldThumb = $('.thumbnails a:nth-child(' + newIndex + ') img', foregroundDiv);

				var newArrows = {
					left: 0,
					right: 0
				};

				switch (newIndex) {
				case 1:
					newArrows.left = hasFourImages ? 4 : 3;
					newArrows.right = 2;
					break;
				case 2:
					newArrows.left = 1;
					newArrows.right = 3;
					break;
				case 3:
					newArrows.left = 2;
					newArrows.right = hasFourImages ? 4 : 1;
					break;
				case 4:
					newArrows.left = 3;
					newArrows.right = 1;
					break;
				}

				$('.leftButton', foregroundDiv).attr('href', '#' + newArrows.left);
				$('.rightButton', foregroundDiv).attr('href', '#' + newArrows.right);

				// fade out the old thumbnail and add the link
				$('.thumbnails img.active', foregroundDiv).animate({
					opacity: .5
				},
				250).removeClass('active').parent().attr('href', '#' + oldMainIndex);

				//fade in the new thumbnail and remove it's link
				oldThumb.animate({
					opacity: 1
				},
				250).addClass('active').parent().removeAttr('href');

				swapLargeImage(newIndex);
				return false;
			}); // end of thumbnail click
		}); // end of fade
	}); // end of bind event

	fadeEverythingIn(foregroundDiv);

}; // end function openDetails


$log = function(message) {
	if(window.console)
		console.log('log: '+message);
};