$(document).ready(function() {

	$(".artwork_grid_item").live("click", function () { 
		var artwork_id = $(this).attr("id");
	
/*
		$("#artworkDetail").show();
		$("#artworkDetail").html("<a href=\"#\"><img src=\"/6x6x2009_images/" + artwork_id + ".jpg\"></a>");	
		$("#artworkGrid").hide();
*/
		
		showImageDetails(artwork_id);
		
		return false;
		});
	
	$("#artworkDetail a").live("click", function () {
		var artwork_id = $(this).attr("id");
		$(this).parent().parent().hide();

		// determine which page this ID resides on
		var pageNum = getPageForID(artwork_id);
		var firstID = getFirstIDForPage(pageNum);
		showGrid(firstID, "2009");

		return false;
	});
	
	$("#next_grid_button").live("click", function () {
		showNextGrid();
		return false;
	});

	$("#prev_grid_button").live("click", function () {
		showPrevGrid();
		return false;
	});

	$("#next_detail_button").live("click", function () {
		var nextArtworkID = $("#artworkDetail a img").attr("id");
		nextArtworkID++;
		showImageDetails(nextArtworkID);
		return false;
	});

	$("#prev_detail_button").live("click", function () {
		var prevArtworkID = $("#artworkDetail a img").attr("id");
		prevArtworkID--;
		if (prevArtworkID < 1)
			return;
			
		showImageDetails(prevArtworkID);
		return false;
	});
	
	$("#artworkDetail").hide();
	$("#add_to_cart_form").hide();
	$("#prev_detail_button").hide();
	$("#next_detail_button").hide();
	
	
	$("#findByIDButton").live("click", function () {
		
		var findByID = $("#findByIDInput").attr("value");

		var currentTime = new Date();
		$.ajax({
			type: "POST",
			url: "/include/validate_id.php",
			data: {
				IDtoValidate: findByID,
				year: "2009",
				time: currentTime
			},
			dataType: "xml",
		   	success: function(xml)
			{
				// grab the results
				var validID = $("validID", xml).text();
				var numArtworks = $("numArtworks", xml).text();
				
				if (parseInt(findByID) < 1)
				{
					findByID = 1;
				}
				
				if (parseInt(findByID) > parseInt(numArtworks))
				{
					findByID = numArtworks;
				}

				if (!onGalleryPage())
				{
					location.href = "6x6x2009.php?artwork_id=" + findByID;
				}
				else
				{
					showImageDetails(parseInt(findByID));
				}
		   	},
			failure: function(xml)
			{
				alert("error occurred");
			}
			});
		
		return false;

	});
	
	// Random Artwork button handler
	$("#random_button").live("click", function () {	

		if (!onGalleryPage())
		{
			location.href = "6x6x2009.php?random_artwork=1";
		}

		loadRandomArtwork();
		
		return false;
	});
	
	// check for View Orders checkbox clicks
	$(".order_check_box").live("click", function () {
		var orderID = $(this).attr("id");
		var checked = this.checked;
		
		var currentTime = new Date();
		$.ajax({
			type: "POST",
			url: "/include/mark_on_wall.php",
			data: {
				order_id: orderID,
				year: "2009",
				mark_on_wall: checked,
				time: currentTime
			},
			dataType: "xml",
		   	success: function(xml)
			{
				// grab the results
				var succeeded = $("success", xml).text();
				
				if (succeeded)
					alert("Order has been updated in the database.");
				else
					alert("There was a problem updating the order in the database.");

		   	},
			failure: function(xml)
			{
				alert("error occurred");
			}
			});
		
		
	});

	// check for View Orders checkbox clicks
	$(".delivered_check_box").live("click", function () {
		var orderID = $(this).attr("id");
		var checked = this.checked;
		
		var currentTime = new Date();
		$.ajax({
			type: "POST",
			url: "/include/mark_delivery_state.php",
			data: {
				order_id: orderID,
				delivered: checked,
				time: currentTime
			},
			dataType: "html",
		   	success: function(xml)
			{
				// grab the results
				var succeeded = $("success", xml).text();
				
				if (succeeded)
					alert("Order has been updated in the database.");
				else
					alert("There was a problem updating the order in the database.");

		   	},
			failure: function(xml)
			{
				alert("error occurred");
			}
			});
		
		
	});
		
	$(".artist_column_header").live("click", function() {
		var sort_field = $(this).html();
		
		GetFullArtistList(sort_field);
	});

	GetFullArtistList("name");
	
	
	/*
	$("#submitDonation").live("click", function() {
		var theForm = $("#6x6x2009_shopping_cart_form");
		
		theForm.submit();
		
	});
	*/
	
});

function loadRandomArtwork()
{
	var currentTime = new Date();
	$.ajax({
		type: "POST",
		url: "/include/get_random_id.php",
		data: {
			year: "2009",
			time: currentTime
		},
		dataType: "xml",
	   	success: function(xml)
		{
			// grab the results
			var randomID = $("randomID", xml).text();

			showImageDetails(parseInt(randomID));
	   	}
		});
}

function getFirstArtwork()
{
	var artworkIDArray = [];
	
	var artworkArray = $(".artwork_grid_item").each(function() {
		artworkIDArray[artworkIDArray.length] = $(this).attr("id");
	    });
	
	artworkIDArray.sort(function(a,b){return a - b});
	return artworkIDArray[0];
}

function getCurrentPage()
{
	var currentFirstArtworkID = getFirstArtwork();
	var currentPageNum = getPageForID(currentFirstArtworkID);
	return currentPageNum;
}

function getPageForID(artworkID)
{
	var currentPageNum = Math.floor((parseInt(artworkID)-1) / 36);
	return currentPageNum;
}


function getFirstIDForPage(pageNum)
{
	var firstID = (pageNum * 36) + 1;
	return firstID;
}

function showGrid(firstIDtoRetrieve, year)
{
	var currentTime = new Date();
	$.ajax({
		type: "POST",
		url: "/include/get_grid.php",
		data: {
			firstIDtoRetrieve: firstIDtoRetrieve,
			year: year,
			time: currentTime
		},
		dataType: "html",
	   	success: function(html)
		{
			// update the fields
			if (html != "")
			{
				$("#sold_badge_large:visible").remove();
				
				$('#showing_info').html("#" + firstIDtoRetrieve + " to #" + (firstIDtoRetrieve+35) + " <em>(click a thumbnail to view the larger image)</em>");

				$("#artworkDetail").hide();
				$("#artworkGrid").show();

				$('#artworkGrid').html(html);

				$("#add_to_cart_form").hide();
				
				$("#prev_grid_button").show();
				$("#next_grid_button").show();
				$("#prev_detail_button").hide();
				$("#next_detail_button").hide();
				
			}
	   	}
	 });

}


function showNextGrid()
{
	var pageNum = getCurrentPage();
	pageNum++;
	var firstIDtoRetrieve = getFirstIDForPage(pageNum);
	
	showGrid(firstIDtoRetrieve, "2009");
}

function showPrevGrid()
{
	var pageNum = getCurrentPage();
	pageNum--;
	
	if (pageNum < 0)
		return;
		
	var firstIDtoRetrieve = getFirstIDForPage(pageNum);
	
	showGrid(firstIDtoRetrieve, "2009");
}

function showImageDetails(IDtoRetrieve)
{
	var currentTime = new Date();
	$.ajax({
		type: "POST",
		url: "/include/get_details.php",
		data: {
			year: "2009",
			IDtoRetrieve: IDtoRetrieve,
			time: currentTime
		},
		dataType: "html",
	   	success: function(html)
		{
			// update the fields
			if (html != "")
			{
				$("#sold_badge_large:visible").remove();
				
				$('#showing_info').html("#" + IDtoRetrieve + " <em>(click the image to return to the Grid View)</em>");

				$("#artworkGrid").hide();
				$("#artworkDetail").show();

				$('#artworkDetail').html(html);
				
				var sold_badge_visible = $("#sold_badge_large:visible");
				if (sold_badge_visible && sold_badge_visible.length && !isUserLoggedIn())
				{
					$("#add_to_cart_form").hide();
				}
				else
				{
					$("#add_to_cart_form").show();
					$("#my_item_id").val(IDtoRetrieve);
					$("#my_item_name").val(IDtoRetrieve);
				}

				$("#prev_grid_button").hide();
				$("#next_grid_button").hide();
				$("#prev_detail_button").show();
				$("#next_detail_button").show();
			}
	   	}
	 });

	return false;
}

function isUserLoggedIn()
{
	var userLoggedIn = false;
	
	var currentTime = new Date();
	$.ajax({
		type: "POST",
		url: "/include/get_current_user.php",
		async: false,
		data: {
			time: currentTime
		},
		dataType: "xml",
	   	success: function(xml)
		{
			// grab the results
			var current_user = $("current_user", xml).text();
						
			if (current_user != "")
			{
				userLoggedIn = true;
			}
	   	},
		failure: function(xml)
		{
		}
		});
		
	return userLoggedIn;
}

function verifyCheckout()
{
	updateForm();
	
	var membershipLevelValue = $("#membershipLevel").val();
	var shippingOptionValue = $("#shippingOption").val();
	
	var numEntries = $(".6x6_entries").length;
	
	if ((numEntries <= 0) && (membershipLevelValue == "-1"))
	{
		alert("Nothing is in your shopping cart. Please add artwork or select a Membership Level to purchase.");
		return false;
	}
	if (shippingOptionValue == "-1")
	{
		alert("Please select whether you will pick up your pieces or have them shipped to you.")
		return false;
	}
	else if (shippingOptionValue == "0") // extra warning for pick-ups
	{
		if (!confirm("You have selected that you will pick up your pieces. Are  you sure?"))
			return false;
	}

	// make sure the items in the cart are still available
	return verifyInventory();
}

// checks current shopping cart to see if any items have been sold since being added to the cart. 
// shows an alert and return false if any are found sold
function verifyInventory()
{
	var inventoryClean = true;
	
	var currentTime = new Date();
	$.ajax({
		type: "POST",
		url: "/include/verify_inventory.php",
		async: false,
		data: {
			time: currentTime
		},
		dataType: "xml",
	   	success: function(xml)
		{
			var soldItems = "";
			
			// grab the results
			$("sold", xml).each(function(){
				if (soldItems != "")
				{
					soldItems += ", ";
				}
				soldItems += $(this).text()
			});
						
			if (soldItems != "")
			{
				alert("The following items have been sold. you should remove them from your cart and try checking out again: " + soldItems);
				inventoryClean = false;
			}
	   	},
		failure: function(xml)
		{
			alert("error occurred");
		}
		});
		
	return inventoryClean;
}

function updateForm()
{
	var membershipLevelValue = $("#membershipLevel").val();
	var membershipLevelName = $('#membershipLevel option:selected').text() 
	var shippingOptionValue = $("#shippingOption").val();
	var shippingOptionName = $('#shippingOption option:selected').text() 
	var checkoutForm = $("#6x6x2009_shopping_cart");
	
	var numEntries = $(".6x6_entries").length;
	numEntries++;
	
	if (membershipLevelValue != "-1")
	{
		// remove any previously created inputs
		$(".membershipLevelInput").remove();
		
		// add new value
		var membershipLevelNameEntry = '<input class="membershipLevelInput" type="hidden" name="item_name_' + numEntries + '" value="' + membershipLevelName + '">';
		var membershipLevelAmountEntry = '<input class="membershipLevelInput" type="hidden" name="amount_' + numEntries + '" value="' + membershipLevelValue + '">';
		var membershipLevelQtyEntry = '<input class="membershipLevelInput" type="hidden" name="quantity_' + numEntries + '" value="1">';
	
		checkoutForm.append(membershipLevelNameEntry);
		checkoutForm.append(membershipLevelAmountEntry);
		checkoutForm.append(membershipLevelQtyEntry);

		numEntries++;
	}
	
	if (shippingOptionValue != "-1")
	{
		// remove any previously created inputs
		$(".shippingOptionInput").remove();
		
		// add new value
		var shippingOptionNameEntry = '<input class="shippingOptionInput" type="hidden" name="item_name_' + numEntries + '" value="' + shippingOptionName + '">';
		var shippingOptionAmountEntry = '<input class="shippingOptionInput" type="hidden" name="amount_' + numEntries + '" value="' + shippingOptionValue + '">';
		var shippingOptionQtyEntry = '<input class="shippingOptionInput" type="hidden" name="quantity_' + numEntries + '" value="1">';

		checkoutForm.append(shippingOptionNameEntry);
		checkoutForm.append(shippingOptionAmountEntry);
		checkoutForm.append(shippingOptionQtyEntry);
	}
	
}

function onGalleryPage()
{
	var pageName = location.href.substring(location.href.lastIndexOf('/') + 1);
	return (pageName == "6x6x2009.php");
}

function MarkItemsAsSold()
{
	var customerID = $("#CustomerID").attr("value");
	
	if (customerID == "")
	{
		alert("Please enter a Customer ID");
		return false;
	}

	var shippingOptionValue = $("#shippingOption").val();
	if (shippingOptionValue == "-1")
	{
		alert("Please select whether you will pick up your pieces or have them shipped to you.")
		return false;
	}
	
	if (verifyInventory())
	{
		if (confirm("Are you sure you want to mark these items as SOLD?"))
		{
			var currentTime = new Date();
			$.ajax({
				type: "POST",
				url: "/include/mark_as_sold.php",
				data: {
					time: currentTime,
					shipping: shippingOptionValue,
					customer_id: customerID
				},
				dataType: "xml",
			   	success: function(xml)
				{
//					var string = (new XMLSerializer()).serializeToString(xml);
//					alert(string);
					
					alert("Thanks. Those items have been MARKED AS SOLD in the database, as well as a new ORDER has been added to the database.");
					// refresh the page
					location.href = "donate.php";
			   	},
				failure: function(xml)
				{
					alert("an error occurred");
				}
				});
		}
	}
		
	return false;
}

function MarkItemsAsUnSold()
{
	if (confirm("Are you sure you want to mark these items as UNSOLD?"))
	{
		var currentTime = new Date();
		$.ajax({
			type: "POST",
			url: "/include/mark_as_unsold.php",
			data: {
				time: currentTime
			},
			dataType: "xml",
		   	success: function(xml)
			{
				alert("Thanks. Those items have been MARKED AS UNSOLD in the database.");
		   	},
			failure: function(xml)
			{
				alert("an error occurred");
			}
			});
	}
		
	return false;
}

function DeleteOrder(order_id)
{
	var prompt = "Are you sure you want to DELETE THIS ORDER #" + order_id + "?";
	if (confirm(prompt))
	{
		var currentTime = new Date();
		$.ajax({
			type: "POST",
			url: "/include/delete_order.php",
			data: {
				order_id: order_id,
				time: currentTime
			},
			dataType: "xml",
		   	success: function(xml)
			{
				alert("The ORDER has been DELETED.");

				// refresh the page
				location.href = "view_orders.php";
		   	},
			failure: function(xml)
			{
				alert("an error occurred");
			}
			});
	}
		
	return false;
}

function GetFullArtistList(sort_by_field)
{
	var currentTime = new Date();
	$.ajax({
		type: "POST",
		url: "/include/get_full_artist_list.php",
		data: {
			sort_by_field: sort_by_field,
			year: "2009",
			time: currentTime
		},
		dataType: "html",
	   	success: function(html)
		{
			// update the fields
			if (html != "")
			{
				$('#artist_list').html(html);
			}
	   	}
	 });

	return false;
}



