var innerGalleryTemplate = '<div class="top"></div><div class="mid"><div class="mid-inside"><div class="mid-inside-container"><div class="close-button"><a href="#"></a></div><div class="pop-up-header"><h2 class="big-icon flare-fp2dc">HD Viewer <span class="header-small-text">(Higher Definition)</span></h2><div class="media-navigation switcher"><ul><li class="media-title">Choose Media:</li><li>{type_buttons}</ul></div><div class="common-actions"><ul><li class="action-print"><a href="javascript:window.print()">Print</a></li></ul></div></div><div class="hd-media-area"><div class="hd-media"><div class="search-thumb-text"><div class="pad-me" style="height:16px;"><span class="forward"></span><span class="photo-caption"></span></div></div><img class="hd_bigpic bigpic_img@src bigpic_w@width bigpic_h@height style@style" width="500" height="333" src="" style="" alt="Apartment Community Name in City, State" /></div></div><div class="hd-chooser"><div class="photos-pager"></div><div class="photo-thumbs" style="overflow-x:none;"><div class="left-photo-slide"></div><div class="right-photo-slide"></div><div id="thumbs_container" style="width:710px;height:55px;overflow:hidden;"><ul class="thumbs_field"> </ul></div></div></div></div><div class="pop-up-footer hd-info-area"><div class="row"><div class="left"><h4>Viewing</h4></div><div class="right"><div class="large-flare-info"><ul class="flare_field"></ul></div></div> <!-- End right --><a class="aptcart-button {cart}" href="#" title="Add this apartment to my AptCart">Add to My AptCart</a></div> <!-- End row --></div></div> <!-- mid-inside --></div> <!-- mid --><div class="btm"></div>';

var hdGalleryTemplate = $('<div id="pop-up-hd-viewer" class="pop-up big-module hd-viewer">' + innerGalleryTemplate + '</div>').get(0);

var innerYoutubeTemplate = '<div class="top"></div><div class="mid"><div class="mid-inside"><div class="mid-inside-container"><div class="close-button"><a href="#"></a></div><div class="pop-up-header"><h2 class="big-icon flare-fp2dc">HD Viewer <span class="header-small-text">(Higher Definition)</span></h2><div class="media-navigation switcher"><ul><li class="media-title">Choose Media:</li>{type_buttons}</ul></div><div class="common-actions"><ul><li class="action-print"><a href="javascript:window.print()">Print</a></li></ul></div></div><div class="hd-media-area"><div class="hd-media" id="popup_ytapiplayer">You need Flash player 8+ and JavaScript enabled to view this video.</div></div><div class="hd-chooser"></div></div><div class="pop-up-footer hd-info-area"><div class="row"><div class="left"><h4>Viewing</h4></div><div class="right"><div class="large-flare-info"><ul><li class="the-flare flare-youtube"><a href="#" class="name_field@title" title=""><h6>Community Video Tour<span class="small-title">{comm_name}</span></h6></a></li></ul></div></div> <!-- End right --><a class="aptcart-button {cart}" href="#" title="Add this apartment to my AptCart">Add to My AptCart</a></div> <!-- End row --></div></div> <!-- mid-inside --></div> <!-- mid --><div class="btm"></div>';

var youtubeTemplate = $('<div id="pop-up-hd-viewer" class="pop-up big-module hd-viewer">' + innerYoutubeTemplate + '</div>').get(0);

var communityTemplate = '<li class="the-flare flare-community_photos"><h6>{name}<span class="small-title">Choose a photo to view!</span></h6></li>';

var floorplanTemplate = '<li class="the-flare flare-community_photos"><h6>2 Beds / 2 Baths,<span class="small-title">{fpname}, {sqft}, {rent}</span></h6></li>';

var floorplan3dTemplate = '<li class="the-flare flare-fp3d"><h6>{bed_bath},<span class="small-title">{fpname}, {sqft}, {rent}</span></h6></li>';


var smallGalleryWidth = 276;
var smallGalleryHeight = 184;
var smallGalleryThumbWidth = 46;
var smallGalleryThumbHeight = 31;
var largeGalleryWidth = 720;
var largeGalleryExternalWidth = 818;
var largeGalleryHeight = 480;

var hdGalleryImageWidth = 500;
var hdGalleryImageHeight = 333;

var ytPlayer = false;
var viewingType;

var isIE = $.browser.msie || $.browser.opera;

(function($) {
	$.fn.gallery = function(options) {
	
		var opts = $.extend({
			slideshow: false,
			large: false
		}, options);
			
		var parentID = $(this).attr('id');
		var parentDiv = $("#" + parentID);
		
		for (type in galleryData['pics']) {
			var curGalleryType = type;
			viewingType = curGalleryType;
			break;
		}
		
		parentDiv.find("a.galleryTypeButton").eq(0).addClass("selected");
		
		parentDiv.find("div.photo-thumbs").scrollTo(parentDiv.find("table.photopage_0")),
		
		// handler for clicking on the different gallery type buttons
		parentDiv.find("a.galleryTypeButton").click(function() {
			var type = this.id.split('-')[1];
			curGalleryType = type;
			parentDiv.find("a.galleryTypeButton").removeClass("selected");
			$(this).addClass('selected');
			if (isIE) {
				$("td.photo-subarea").hide();
				$("#" + type).show();
			
			} else {	
				var toDiv = parentDiv.find("#" + type);
				parentDiv.find("div.gallery-main").scrollTo(toDiv, 1200, {axis: 'x', easing: 'easeInOutQuint', onAfter: function() {
					if (ytPlayer) {
						ytPlayer.pauseVideo();	
					}
				}});
			}
			return false;
		});
	
		// loop through all galleries
		return this.each(function() {
			// loop through each gallery sub area
			
			$(this).find("td.photo-subarea").each(function() {
			
			var zoomed = false;
			var clicked = false;
			var settings;
			var bigpic;
			var $this;
			
			if (opts.slideshow) {
				$(".slideshow").cycle({fx: 'fade'});
			}
			
			bigpic = $(this).find("div.bigpic");
			
			$this = $(this);
			
			var srcDiv = $(this).find("div.photo-thumbs img").eq(0);
			
			var oldSrc = srcDiv.length ? $(this).find("div.photo-thumbs img").eq(0).attr('src').replace('_' + smallGalleryThumbWidth + 'x' + smallGalleryThumbHeight, '_' + smallGalleryWidth + 'x' + smallGalleryHeight) : '';
			$(this).find("div.photos-pager a:eq(0)").addClass('selectedPhotoPage');
			
			$(this).find("div.photo-thumbs img").click(opts.slideshow ? clickSlideshowThumb : clickNormalThumb);
			
			var pageSettings =
			{
				click: function(page) {
					var parent = $(this).parent().parent().parent();
					parent.find("div.photo-thumbs").scrollTo(parent.find("table.photopage_" + page), 1200, {axis: 'x', easing: 'easeInOutQuint'});
				},
				numItems: $(this).find("div.photo-thumbs img").length,
				itemsPerPage: (opts.large) ? 12 : 10,
				textButtons: false,
				makeList: false,
				preText: '<li class="pages-title" style="list-style:none;">Page:</li>'
			}
			
			$(this).find("div.photos-pager").paginate(pageSettings).eq(0).addClass('page-on');
				
			function clickNormalThumb() {
				var thisSrc = $(this).attr('src');
				
				if ($this.find("img:animated").length > 0) return;
					
				if (opts['large'])
					var src = thisSrc.replace('_' + smallGalleryThumbWidth + 'x' + smallGalleryThumbHeight, '_' + hdGalleryImageWidth + 'x' + hdGalleryImageHeight);
				else var src = thisSrc.replace('_' + smallGalleryThumbWidth + 'x' + smallGalleryThumbHeight, '_' + smallGalleryWidth + 'x' + smallGalleryHeight);
					
				var id = this.id.split('_')[1];
				if (id == null) return;
				var caption = galleryData['pics'][curGalleryType][id]['label'];
						
				var width = parseInt(galleryData['pics'][curGalleryType][id]['width']);
				var height = parseInt(galleryData['pics'][curGalleryType][id]['height']);
				
				parentDiv.find("span.photo-caption").html(caption);
				
				parentDiv.find("a.selected").removeClass('selected');
				$(this).parent('a').addClass('selected');
				
				var prop = smallGalleryHeight/height;
				
				var scaleWidth = width*prop;
				var scaleHeight = height*prop;
				
				var dims = (opts['large']) ? calcImageDims(width, height, largeGalleryWidth, largeGalleryHeight) : calcImageDims(scaleWidth, scaleHeight, smallGalleryWidth, smallGalleryHeight);
				
				// update and position the image
				bigpic.find('img').attr('src', thisSrc).fadeOut(100, function() {
					$(this).attr('src', src).css({'margin': dims[3] + 'px ' + dims[2] + 'px', 'width': dims[0], 'height': dims[1]}).load(function() {
						$(this).fadeIn(100);
					});
				});
					
				oldSrc = src;
				clicked = true;
			}
			
			});
		});	// end this.each
	
		$(this).find("input.zoomButton").click(function zoomImage() {
			var img = (clicked) ? bigpic.find("img:eq(1)") : bigpic.find("img:eq(0)");
			img.animate({
				width: "500px",
				height: "335px",
				top: "-84px",
				left: "-150px"
			}, 1500);
			zoomed = true;
		});
	}
})(jQuery);


/**
 *
 * Calculates the resized dimensions and padding of an image for the large gallery.
 *
 */

function calcImageDims(width, height, galleryWidth, galleryHeight) {
	if (width > galleryWidth) {
		height = Math.floor(height*galleryWidth/width);
		width = galleryWidth;
	} if (height > galleryHeight) {
		width = Math.floor(width*galleryHeight/height);
		height = galleryHeight;
	}
		
	var padTop = Math.ceil(Math.abs(galleryHeight - height)/2);
	var padLeft = Math.ceil(Math.abs(galleryWidth - width)/2);
	
	return [width, height, padLeft, padTop];
}

/**
 * Creates the large pop-up gallery by using the json data and templates.
 * Calls the gallery plugin after the html is added to handle the events.
 */
function hdPopup(type, inner) {
	
	var thumbnailsPerPage = 12;
	
	var typeNames = {'community_photos': 'Photos', 'fpmodeltour': 'Model Tour', 'fpphotos': 'Floorplan Photos', 'fp3d': '3D Floor Plan Photos'};
	var typeClasses = {'community_photos': 'icon-photo', 'fpmodeltour': 'icon-photo', 'fpphotos': 'icon-photo', 'fp3d': 'icon-3d'};
	var thumb;
	var buttons = '';	// stores html of buttons that switch between galleries
	var buffer = '';
	var pageBuffer = '';	
	var firstImg;	// stores path for the image used in big picture
	var caption;
	var tableOpen = false;	// tracks if a table is left open after rendering the thumbnails
	var galleryBuffer;
	var data;		// used for templates
	var html;		// final html to insert in popup
	var fpMode = false;
	
	imgCount = 0;
	galleryBuffer = '';
	
	// build tabs to switch galleries
	
	for (curType in galleryData['pics']) {
		var sel = (curType == type) ? ' selected' : '';
		buttons += '<li><a href="#" class="galleryTypeButton' + sel + '" id="typebutton-' + curType + '"><span class="left-edge"></span><span class="center-down"><span class="' + typeClasses[curType] + '">' + typeNames[curType] + '</span></span><span class="right-edge"></span></a></li>';
	}

	if (galleryData['youtube_id']) {
		var sel = (type == 'youtube') ? ' selected' : '';
		buttons += '<li><a href="#" class="galleryTypeButton' + sel + '" id="typebutton-youtube"><span class="left-edge"></span><span class="center-down"><span class="icon-video">Videos</span></span><span class="right-edge"></span></a></li>';
	}

	if (type != 'youtube' && typeof(galleryData['pics'][type]) == 'undefined') type = 'community_photos';

	if (type == 'youtube') {
		// render the html for youtube mode
		data = {
			name_field: commInfo['name'],
			id: type
		}
	
		var cart = makeCartClass(false);
		var template = innerYoutubeTemplate.replace('{cart}', cart);
		
		// if the hd gallery is already visible, use a template that just contains the inner parts, otherwise add the container div
		var finalTemplate = (inner) ? $('<div>' + template + '</div>').get(0) : $('<div id="pop-up-hd-viewer" class="pop-up big-module hd-viewer">' + template + '</div>').get(0);
		html = pure.autoRender(finalTemplate, data);
		html = html.replace('{type_buttons}', buttons);
		html = html.replace('{comm_name}', commInfo['name']);
	} else {
	
		
		// loops through images in this gallery type
		for (var i in galleryData['pics'][type]) {
			var search = '_' + smallGalleryWidth + 'x' + smallGalleryHeight;
			if (imgCount++ == 0) {
				firstImg = galleryData['pics'][type][i]['src'];
				firstImg = '/files' + firstImg.replace(search, '_' + hdGalleryImageWidth + 'x' + hdGalleryImageHeight);
				caption = galleryData['pics'][type][i]['label'];
				if (caption == null) caption = '';
				width = parseInt(galleryData['pics'][type][i]['width']);
				height = parseInt(galleryData['pics'][type][i]['height']);
				var dims = calcImageDims(width, height, largeGalleryWidth, largeGalleryHeight);
			}
			thumb = galleryData['pics'][type][i]['src'];
			
			var replace = '_' + smallGalleryThumbWidth + 'x' + smallGalleryThumbHeight;
			
			galleryBuffer += "\n" + '<li id="thumbnum_' + (imgCount-1) + '"><a href=""><img id="popthumb_' + i + '" width="' + smallGalleryThumbWidth + '" src="/files' + thumb.replace(search, replace) + '"></a></li>' + "\n";
		}
	
		var numExtra = 12 - imgCount % 12;
	
		// draw the blank thumbnails
		for (i=0; i < numExtra; i++) {
			galleryBuffer += "\n" + '<li><a href="#"><img width="' + smallGalleryThumbWidth + '" height="' + smallGalleryThumbHeight + '" src="/images/no-image-thumb.png"></a></li>' + "\n";
		}
		
		if (type == 'fpphotos' || type == 'fp3d') {
			var beds;
			if (isNumeric(commInfo['beds'])) {
				beds = (commInfo['beds'] == 1) ? commInfo['beds'] + ' Bed' : commInfo['beds'] + ' Beds';
			}
			else beds = commInfo['beds'];
			var baths = commInfo['baths'] + ((commInfo['baths'] == 1) ? ' Bath' : ' Baths');
		}
		
		switch(type) {
			case 'community_photos':
				forwardText = commInfo['city'] + ', ' + commInfo['fullstate'];
				flare = communityTemplate.replace(/{name}/g, commInfo['name']);
			break;
			case 'fpphotos':
			case 'fpmodeltour':
				flare = floorplanTemplate.replace("{name}", commInfo['name']);
				flare = flare.replace("{bed_bath}", beds + ' ' + baths);
				flare = flare.replace("{fpname}", commInfo['fpname']);
				flare = flare.replace("{sqft}", commInfo['sqft'] + ' sq. ft.');
				flare = flare.replace("{rent}", '$' + commInfo['rent']);
				forwardText = beds + ' / ' + baths;
				fpMode = true;
				break;
			case 'fp3d':
				flare = floorplan3dTemplate.replace("{name}", commInfo['name']);
				flare = flare.replace("{bed_bath}", beds + ' / ' + baths);
				flare = flare.replace("{fpname}", commInfo['fpname']);
				flare = flare.replace("{sqft}", commInfo['sqft'] + ' sq. ft.');
				flare = flare.replace("{rent}", '$' + commInfo['rent']);
				forwardText = beds + ' / ' + baths;
				fpMode = true;
				break;
		}
		
		pageBuffer = '';
		var pageCount = Math.ceil(imgCount / thumbnailsPerPage);
	
		for (i=0; i < pageCount; i++) {
			pageBuffer += '<a id="page_' + i + '">' + (i+1) + '</a>';	
		}
	
		// render the html for this gallery
		data = {
			bigpic_img:	firstImg,
			bigpic_w: dims[0],
			bigpic_h: dims[1],
			style: 'margin: ' + dims[3] + 'px ' + dims[2] + 'px;',
			thumbs_field: galleryBuffer,
			"photos-pager": pageBuffer,
			"flare_field": flare,
			"photo-caption" : caption,
			forward : forwardText,
			id: type
		}
	
		var cart = makeCartClass(fpMode);
	
		var template = innerGalleryTemplate.replace('{cart}', cart);
		
		html = pure.autoRender((inner) ? $('<div>' + template + '</div>').get(0) : $('<div id="pop-up-hd-viewer" class="pop-up big-module hd-viewer">' + template + '</div>').get(0), data);
		html = html.replace('{type_buttons}', buttons);
	}	// end not-youtube
	
	var docWidth = $(document).width();
	var popupLeft = (docWidth - largeGalleryExternalWidth)/2;
	
	var p = parent.document;
	
	// make a new div or replace the contents of the existing pop up
	if (inner)
		$("#pop-up-hd-viewer").html(html);
	else $(p).find('body').append('<div id="backgroundPopup"></div>').append(html);
	
	if (type == "youtube") {
		var params = { allowScriptAccess: "always" };
		var atts = { id: "popup_myytplayer" };
		swfobject.embedSWF("http://www.youtube.com/v/" + galleryData['youtube_id'] + "&enablejsapi=1&playerapiid=ytplayer", "popup_ytapiplayer", "720", "480", "8", null, null, params, atts);
	}
	
	$("ul.thumbs_field").width((imgCount + numExtra) * 70);
	$("#thumbs_container").scrollTo(0,100);
	if (!inner)
		$("#pop-up-hd-viewer").css({position:'absolute',left: popupLeft + 'px', top: scrollY()}).show();
	$("#backgroundPopup").css({'height': $(document).height() + 'px', opacity: 0.7}).show().click(function() {
		$(this).remove();$("#pop-up-hd-viewer").remove();
		$("#main-gallery").gallery({});
	});
	
	var container = $("#pop-up-hd-viewer");
	
	// paginate
	var pageSettings =
	{
		click: function(page) {
			page *= 12;
			container.find("#thumbs_container").scrollTo(container.find("#thumbnum_" + page), 1200, {axis: 'x', easing: 'easeInOutQuint'});
		},
		numItems: imgCount,
		itemsPerPage: 12,
		textButtons: false,
		makeList: false
	}
			
	container.find("div.photos-pager").paginate(pageSettings).eq(0).addClass('page-on');
	
	container.find("div.close-button").click(function() {
		$("#pop-up-hd-viewer,#backgroundPopup").remove();
		$("#main-gallery").gallery({});
	});
	
	// switch gallery types
	container.find("a.galleryTypeButton").click(function() {
		type = this.id.split('-')[1];
		hdPopup(type, true);
	});
	
	$("ul.thumbs_field a").click(function() {
		$(this).find("img").click();
		return false;
	});
	
	$("ul.thumbs_field img").click(function() {
		var id = this.id.split('_')[1];
		if (typeof(id) == 'undefined') return false;
		var caption = galleryData['pics'][type][id]['label'];
				
		var width = parseInt(galleryData['pics'][type][id]['width']);
		var height = parseInt(galleryData['pics'][type][id]['height']);
		
		container.find("span.photo-caption").html(caption);
		
		var dims = calcImageDims(width, height, largeGalleryWidth, largeGalleryHeight);
		
		var thisSrc = this.src;
		var src = thisSrc.replace('_' + smallGalleryThumbWidth + 'x' + smallGalleryThumbHeight, '_' + hdGalleryImageWidth + 'x' + hdGalleryImageHeight);
		
		// update and position the image
		$("img.hd_bigpic").attr('src', thisSrc).css({'width': dims[0] + 'px', 'height': dims[1] + 'px'}).fadeOut(100, function() {
			$(this).attr('src', src).css({'margin': dims[3] + 'px ' + dims[2] + 'px', 'width': dims[0], 'height': dims[1]}).load(function() {
				$(this).fadeIn(100);
			});
		});
		return false;
	});
	
}

function scrollY() {
	var de = document.documentElement;
	
	return self.pageYOffset || (de && de.scrollTop) || document.body.scrollTop;
}

function makeCartClass(fpMode) {
	var cart = 'c-' + commInfo['commid'];
	if (fpMode && typeof(commInfo['fpid']) != 'undefined')
		cart += ' f-' + commInfo['fpid'];
	if ((fpMode && typeof(floorplanInCart) == 'number' && floorplanInCart == 1) || (!fpMode && commInCart == 1))
		cart += ' aptcart-button-added';
	return cart;
}

function isNumeric(sText) {
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;

   for (i = 0; i < sText.length && IsNumber == true; i++) { 
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
	}
	return IsNumber;   
}

