/***************************************************************
 * Initialization
 ***************************************************************/

$(window).addEvent("domready", __load);

function __load()
{
	__initializeThumbnails();
}

function __initializeThumbnails()
{
	__initializeFlagging();
	//__initializePreloading();
}

/***************************************************************
 * Flagging
 ***************************************************************/

function __initializeFlagging()
{
	var table = $("thumbnailTable");
	if (table != null)
	{
		var tds = $$("#thumbnailTable td.thumbnailContainer");
		for (var i = 0; i < tds.length; i++)
		{
			//Add listeners
			var td = tds[i];
			td.addEvent("click", function(event) { _stopEvent(event); toggleFlagged(this); });
	
			var checkbox = td.getElement("input");
			$(checkbox).addEvent("click", function(event) { _stopEventPropagation(event); toggleFlagged(tdNodeForCheckbox(this)); });
			if (checkbox.checked)
			{
				td.addClass("thumbnailFlagged");
			}
		}
		
		var images = $$(".thumbnailImage");
		for (var i = 0; i < images.length; i++)
		{
			$(images[i]).addEvent("contextmenu", function(event) { _stopEvent(event); });
		}
	}
	
	var flag = $("displayOnlyFlagged");
	if (flag != null)
	{
		flag.addEvent("click", function(event) { _stopEvent(event); toggleDisplayOnlyFlagged(); });
		var anchor = flag.getElement("a");
		if (anchor != null)
		{
			anchor.addEvent("click", function(event) { _stopEvent(event); toggleDisplayOnlyFlagged(); });
		}
	}
}

function toggleFlagged(element)
{
	var checkbox = $(element).getElement("input");
	var isFlagged = $(element).hasClass("thumbnailFlagged");
	if (isFlagged)
	{
		checkbox.checked = false;
		$(element).removeClass("thumbnailFlagged");
	}
	else
	{
		checkbox.checked = true;
		$(element).addClass("thumbnailFlagged");
	}
	
	var request = new Request({
			method: 'post',
			url: BPAjaxURLUpdateFlagged,
			data: {'index': checkbox.value, 'state': (isFlagged ? '0' : '1')},
			onRequest: function () { /*console.log("Request made");*/ },
			onComplete: function (response) { _hideLoading(); /* console.log("Response received: " + response); */}
			}).send();
}

function tdNodeForCheckbox(element)
{
	return $(element).getParent("td");
	
	var node = element;
	while (node != null && node.tagName.toLowerCase() != "td")
	{
		node = node.parentNode;
	}
	return node;
}

function toggleDisplayOnlyFlagged()
{
	var ajaxRequest = new Request.HTML({
		method: 'post',
		url: BPAjaxURLToggleDisplayOnlyFlagged,
		onRequest: function() { _showLoading(); },
		onComplete: function() { _hideLoading(); },
		onSuccess: _toggleDisplayOnlyFlaggedResponse
		});
	ajaxRequest.send();
}

function _toggleDisplayOnlyFlaggedResponse(responseTree, responseElements, responseHTML, responseJavaScript)
{
	var element = _findElementInNodeList(responseTree);
	if (element != null)
	{
		element.replaces($('proofsWrapper'));
		__initializeThumbnails();
	}
}

/***************************************************************
 * Change Page
 ***************************************************************/

function switchPage(targetPage)
{
	var ajaxRequest = new Request.HTML({
		method: 'post',
		url: BPAjaxURLSwitchPage,
		data: {'page': targetPage},
		onRequest: function() { _showLoading(); },
		onComplete: function() { _hideLoading(); },
		onSuccess: _switchPageResponse
		});
	ajaxRequest.send();
}

function _switchPageResponse(responseTree, responseElements, responseHTML, responseJavaScript)
{
	var element = _findElementInNodeList(responseTree);
	if (element != null)
	{
		element.replaces($('proofsWrapper'));
		__initializeThumbnails();
	}
}

/***************************************************************
 * Number per Page
 ***************************************************************/

function changeNumberPerPage(targetNumber)
{
	var ajaxRequest = new Request.HTML({
		method: 'post',
		url: BPAjaxURLChangeNumberPerPage,
		data: {'number': targetNumber},
		onRequest: function() { _showLoading(); },
		onComplete: function() { _hideLoading(); },
		onSuccess: _changeNumberPerPageResponse
		});
	ajaxRequest.send();
}

function _changeNumberPerPageResponse(responseTree, responseElements, responseHTML, responseJavaScript)
{
	var element = _findElementInNodeList(responseTree);
	if (element != null)
	{
		element.replaces($('proofsWrapper'));
		__initializeThumbnails();
	}
}

/***************************************************************
 * Show Preview
 ***************************************************************/

/*
function __initializePreloading()
{
	var anchors = $$(".thumbnailLink");
	for (var i = 0; i < anchors.length; i++)
	{
		var a = anchors[i];
		
		a.addEvent("mouseover", function(event) { _preloadPreview(this); });
	}
}
*/

function showPreview(targetIndex, event)
{
	_stopEvent(event);
	
	var bodySize = $(document.body).getSize();
	var overlayObject = new Element("div",
	{
		'styles':
		{
			'position': 'fixed',
			'top': 0,
			'left': 0,
			'background-color': "#000000",
			'opacity': 0.0,
			'z-index': 200,
			'width': bodySize.x,
			'height': bodySize.y
		},
		'class': "pageOverlay",
		'id': "pageOverlay",
		'events': 
		{
			'click': function(event)
						{
							_stopEvent(event);
							
							hidePreview();
						}
		}
	});
	
	$(document.body).appendChild(overlayObject);
	
	var fxOptions = {
						duration: 300, 
						transition: Fx.Transitions.Cubic.easeInOut, 
						wait: false, 
						property: 'opacity'
					};
	var fxIn = new Fx.Tween(overlayObject, fxOptions);
	fxIn.addEvent('start', function() { _showLoading(); });
	fxIn.addEvent('complete', function() { _showPreviewOverlayFadeInComplete(targetIndex); });
	fxIn.start(0.0, 0.7);
}

function _showPreviewOverlayFadeInComplete(targetIndex)
{
	_hideLoading();
	var ajaxRequest = new Request.HTML({
		method: 'post',
		url: BPAjaxURLShowPreview,
		data: {'index': targetIndex},
		onSuccess: _showPreviewResponse
		});
	ajaxRequest.send();
}

function _showPreviewResponse(responseTree, responseElements, responseHTML, responseJavaScript)
{
	var element = _findElementInNodeList(responseTree);
	if (element != null)
	{
		$(document.body).appendChild(element);
		_resetAddToCartPrice();
		
		var windowSize = $(window).getSize();
		var windowScrollSize = $(window).getScroll();
		var previewContainerSize = element.getSize();
		
		//Preview box
		var xOffset = Math.floor((windowSize.x - previewContainerSize.x) / 2) + windowScrollSize.x;
		var yOffset = Math.max(Math.floor(windowScrollSize.y) + 35, 35);
		
		element.setStyles({
			left: xOffset,
			top: yOffset
		});
		
		//Position the close box
		var closeBox = $("proofsPreviewCloseBox");
		if (closeBox != null)
		{
			var closeBoxSize = closeBox.getSize();
			xOffset = Math.floor(0 - closeBoxSize.x / 2);
			yOffset = Math.floor(0 - closeBoxSize.y / 2);
		
			closeBox.setStyles({
				left: xOffset,
				top: yOffset
			});	
		}
		
		$('proofsPreviewImage').addEvent("contextmenu", function(event) { _stopEvent(event); });
		
		if (initPlaceholders) initPlaceholders();
	}
}

function showPreviousPreview(targetIndex)
{
	var ajaxRequest = new Request.HTML({
		method: 'post',
		url: BPAjaxURLShowPreviousPreview,
		data: {'index': targetIndex},
		onSuccess: _updatePreviewResponse
		});
	ajaxRequest.send();
}

function showNextPreview(targetIndex)
{
	var ajaxRequest = new Request.HTML({
		method: 'post',
		url: BPAjaxURLShowNextPreview,
		data: {'index': targetIndex},
		onSuccess: _updatePreviewResponse
		});
	ajaxRequest.send();
}

function _updatePreviewResponse(responseTree, responseElements, responseHTML, responseJavaScript)
{
	var element = _findElementInNodeList(responseTree);
	if (element != null)
	{
		element.replaces($('proofsPreviewWrapper'));
		_resetAddToCartPrice();
		
		var windowSize = $(window).getSize();
		var windowScrollSize = $(window).getScroll();
		var previewContainerSize = element.getSize();
		
		//Preview box
		var xOffset = Math.floor((windowSize.x - previewContainerSize.x) / 2) + windowScrollSize.x;
		var yOffset = Math.max(Math.floor(windowScrollSize.y) + 35, 35);
		
		element.setStyles({
			left: xOffset,
			top: yOffset
		});
		
		//Position the close box
		var closeBox = $("proofsPreviewCloseBox");
		var closeBoxSize = closeBox.getSize();
		xOffset = Math.floor(0 - closeBoxSize.x / 2);
		yOffset = Math.floor(0 - closeBoxSize.y / 2);
		
		closeBox.setStyles({
			left: xOffset,
			top: yOffset
		});
		
		$('proofsPreviewImage').addEvent("contextmenu", function(event) { _stopEvent(event); });
		
		if (initPlaceholders) initPlaceholders();
	}
}

function hidePreview()
{
	var previewObject = $("proofsPreviewWrapper");
	if (previewObject != null)
	{
		previewObject.dispose();
	}
	
	var overlayObject = $("pageOverlay");
	if (overlayObject != null)
	{
		var fxOptions = {
							duration: 400, 
							transition: Fx.Transitions.Cubic.easeInOut, 
							wait: false,
							property: 'opacity'
						};
		var fxIn = new Fx.Tween(overlayObject, fxOptions);
		fxIn.addEvent('complete', function() { _removeOverlay(); });
		fxIn.start(0.7, 0.0);
	}
}

function _removeOverlay()
{
	$("pageOverlay").dispose();
}

/***************************************************************
 * Add to Cart
 ***************************************************************/

var currentAddToCartCount = 0;
var currentAddToCartPrice = 0;
function _resetAddToCartPrice()
{
	currentAddToCartCount = 0;
	currentAddToCartPrice = 0;
}

function updateAddToCartPrice(element, price, secondPrice)
{
	/* don't bother trying to edit this - the value is display only.  The charged price is calculated only on the server */
	
	var previousValue = $(element).getProperty("quantity");
	if (previousValue == null || isNaN(previousValue))
	{
		previousValue = 0;
	}

	currentValue = parseInt($(element).value);
	if (currentValue == null || isNaN(currentValue))
	{
		currentValue = 0;
	}

	currentAddToCartCount -= previousValue;
	
	if (previousValue > 0)
	{
		currentAddToCartPrice -= ((previousValue - 1) * secondPrice + price);
	}

	currentAddToCartCount += currentValue;
	
	if (currentValue > 0)
	{
		currentAddToCartPrice += ((currentValue - 1) * secondPrice + price);
	}

	$(element).setProperty("quantity", currentValue);

	var container = $("cartSummary");
	if (container != null)
	{
		container.set("text", currentAddToCartCount + " photo" + (currentAddToCartCount != 1 ? "s" : "") + ", $" + currentAddToCartPrice.toFixed(2) + " total");
	}
}

function addToCart(imageIndex)
{
	if (currentAddToCartCount <= 0)
	{
		return;
	}
	
	var quantityTable = $("addToCartTable");
	if (!quantityTable)
	{
		return;
	}
	
	var queryString = "imageIndex=" + parseInt(imageIndex);
	var inputs = quantityTable.getElements("input");
	for (var i = 0; i < inputs.length; i++)
	{
		var name = inputs[i].getProperty("name");
		var value = inputs[i].value;
		queryString = queryString + "&" + escape(name) + "=" + escape(value);
	}
	
	var ajaxRequest = new Request.HTML({
		method: 'post',
		url: BPAjaxURLAddToCart,
		data: queryString,
		onSuccess: _addToCartResponse
		});
	ajaxRequest.send();
}

function _addToCartResponse(responseTree, responseElements, responseHTML, responseJavaScript)
{
	var element = _findElementInNodeList(responseTree);
	if (element != null)
	{
		element.replaces($('addToCartWrapper'));
	}
	
	reloadCartBar();
}

function reloadCartBar()
{
	var ajaxRequest = new Request.HTML({
		method: 'post',
		url: BPAjaxURLReloadCartBar,
		onSuccess: _reloadCartBarResponse
		});
	ajaxRequest.send();
}

function _reloadCartBarResponse(responseTree, responseElements, responseHTML, responseJavaScript)
{
	var element = _findElementInNodeList(responseTree);
	if (element != null)
	{
		element.replaces($('shoppingCartBar'));
	}
}

/***************************************************************
 * Email Notification
 ***************************************************************/

function notifyAddAddress(srcEvent)
{
	if (srcEvent != null)
	{
		var theEvent = new Event(srcEvent);
		if (theEvent.key != "enter")
		{
			return;
		}
	}
	
	var addressInput = $('emailAddress');
	var ajaxRequest = new Request.HTML({
		method: 'post',
		url: BPAjaxURLAddNotifyAddress,
		data: {'emailAddress': addressInput.value},
		onSuccess: _notifyAddAddressResponse
		});
	ajaxRequest.send();
}

function _notifyAddAddressResponse(responseTree, responseElements, responseHTML, responseJavaScript)
{
	var element = _findElementInNodeList(responseTree);
	if (element != null)
	{
		element.replaces($('proofsNotificationInfo'));
	}
	
	if (initPlaceholders) initPlaceholders();
}

/***************************************************************
 * Keyboard Navigation
 ***************************************************************/

(window.addEventListener) ? window.addEventListener("keydown", function(event) { return _bodyKeyPressed(event); }, true) : window.attachEvent("onkeydown", function(event) { return _bodyKeyPressed(event); });
function _bodyKeyPressed(event)
{
	var previewObject = $("proofsPreviewWrapper");
	if (previewObject == null)
	{
		return;
	}
	
	var currentPreviewIndex = $("proofsPreviewIndex").value;
	
	if (event.keyCode == 37) //Left
	{
		showPreviousPreview(currentPreviewIndex);
	}
	else if (event.keyCode == 39) //Right
	{
		showNextPreview(currentPreviewIndex);
	}
	else if (event.keyCode == 27) //Escape
	{
		hidePreview();
	}
	
	return true;
}
