var CURRENT_PAGE_THUMBS = 'thumbs';
var CURRENT_PAGE_DETAIL = 'detail';
var CURRENT_PAGE_CART = 'cart';
var CURRENT_PAGE_NEWS = 'news';
var CURRENT_PAGE_STOCKISTS = 'stockists';
var CURRENT_PAGE_PHOTOS = 'photos';
var CURRENT_PAGE_PHOTOALBUM = 'photoalbum';
var CURRENT_PAGE_PRESS = 'press';

var debugThis = false;
			
var alertBoxIsRunning = false;

var currentCategory = null;
var currentItem = null;
var currentPage = null;

var DEFAULT_CATEGORY = 'Spring2010';
var DEFAULT_FABRIC = 'default';
var ALBUM_PATH = 'photoalbums/';
var IMG_PATH = 'res/images/';
var SHOPITEMS_PATH = 'dresses/';
var FABRICS_PATH = 'dresses/fabrics/';
var PHOTO1_SUFFIX = '1.jpg';
var PHOTO2_SUFFIX = '2.jpg';
var PHOTO3_SUFFIX = '3.jpg';

var DELIVERY = 0;

var cartResultParam = null;
var cart = null;	
var shopItems = new Array();
var newsItems = new Array();
var photoAlbums = new Array();
var categories = new Array();
var fabrics = new Array();

var currentFabricPopup = '';
var fabricPopupShown = false;

var HTML_CLEAR = '<div class="clear"><\/div>';
var SPACE = '%20';


/******************************/
/*** THIS LOADS THE DETAILS ***/
/*** PAGE OF THE SHOP *********/
/******************************/

function init(page)
{	
	/*jQuery("body").height((jQuery(document).height() - 50));
	
	jQuery(window).resize(function(){
		jQuery("body").height((jQuery(document).height() - 50));
		
	});*/
	if(page != null || typeof(page) != 'undefined')
	{
		currentPage = page;	
	}
	else
	{
		currentPage = '';
	}
	
	initNav();
	
	loadCartFromCookie();
	
	paintCart();
	
	if(currentCategory != null && currentCategory != 'all')
	{
		jQuery("a[title='SHOP']").attr("href", "shop.html?cat=" + escape(currentCategory));
	}
}


function initDetails(id)
{	
	var nextActiveImage = PHOTO2_SUFFIX;
	currentItem = getShopItem(id);
	
	paintShopItemDetails(id);
	
	jQuery('#main #content #shopItemDetails #buyBox a.button').click(function()
	{
		addToCart();
	});
	
}

function initShop(id)
{
	if(id != null)
	{
		loadShopItems(id);
	}
	else
	{
		loadShopItems();
	}
}

function initNews()
{
	if (newsItems == null || newsItems.length == 0) 
	{
		currentPage = CURRENT_PAGE_NEWS;
		loadNewsItems();
	}
}

function initPhotos(id)
{
	if(id != null)
	{
		loadPhotoAlbums(id);
	}
	else
	{
		loadPhotoAlbums();
	}
}


function initNav()
{
    var srcroot = 'res/images/';

	jQuery("#nav ul li a img:not(.active)").mouseover(function()
    {
        jQuery(this).attr('src', srcroot + jQuery(this).attr('alt').toLowerCase() + '_on.png');
    }).mouseout(function(){
        jQuery(this).attr('src', srcroot + jQuery(this).attr('alt').toLowerCase() + '_off.png');
    });    
}

function initCart()
{
	loadShopItems();
	
}

/********************/
/*** BEAN METHODS ***/
/********************/

function getDressesInCategory()
{
	
	var dressesInCategory = new Array();
	
	if(categories  == null || typeof(categories) == 'undefined' || categories.length == 0)
	{
		categories = DEFAULT_CATEGORY;	
	}
	
	if(currentCategory == 'all')
	{
		shopItems.sort(shopItemSorter);
		return shopItems;	
	}
	else
	{
		for(var i = 0; i < categories.length; i++)
		{
			if(categories[i].getName() == currentCategory)
			{
				var ids = categories[i].getIds();
				
				for(var j = 0; j < ids.length; j++)
				{
					dressesInCategory.push(getShopItem(ids[j]));
				}
				
				break;
			}
		}
		
		
	}
	
	return dressesInCategory;
}


function getShopItem(id)
{
	if(id == null || typeof(id) == 'undefined')
	{
		return null;
	}
	
	if(shopItems == null || typeof(shopItems) == 'undefined' || shopItems.length == 0)
	{
		loadShopItems();
	}
	
	if(currentItem != null && currentItem.getId() == id)
	{
		return currentItem;
	}
	
	for(var i = 0; i < shopItems.length; i++)
	{
		var item = shopItems[i];
		
		if(item != null && typeof(item) != 'undefined')
		{
			if(item.getId() == id)
			{
				return item;
			}
		}
	}
	return null;
}

function getNewsItem(id)
{
	if(id == null || typeof(id) == 'undefined')
	{
		return null;
	}
	
	if(newsItems == null || typeof(newsItems) == 'undefined' || newsItems.length == 0)
	{
		loadNewsItems();
	}
	
	for(var i = 0; i < newsItems.length; i++)
	{
		var item = newsItems[i];
		
		if(item != null && typeof(item) != 'undefined')
		{
			if(item.getId() == id)
			{
				return item;
			}
		}
	}
	return null;
}

function getPhotoAlbum(id)
{
	if(id == null || typeof(id) == 'undefined')
	{
		return null;
	}
	
	if(photoAlbums == null || typeof(photoAlbums) == 'undefined' || photoAlbums.length == 0)
	{
		loadPhotoAlbums();
	}
	
	for(var i = 0; i < photoAlbums.length; i++)
	{
		var item = photoAlbums[i];
		
		if(item != null && typeof(item) != 'undefined')
		{
			if(item.getId() == id)
			{
				return item;
			}
		}
	}
	return null;
}


/*********************/
/*** PAINT METHODS ***/
/*********************/

function paintCartItem(cartRow, paypalRowIndex)
{
	var html = '';
	var shopid = cartRow.getShopitemid();
	var shopitem = getShopItem(shopid);
	var hasFabric = cartRow.getFabric() != null && typeof(cartRow.getFabric()) == 'string' && cartRow.getFabric() != DEFAULT_FABRIC;
	
	html += '<div class="cartRow" id="row' + cartRow.getRowid() + '">';
	html += '<img src="dresses/' + shopid + PHOTO1_SUFFIX + '" height="140" width="118" alt="' + shopitem.getName() + '" class="cartThumb" />';
	html += '<div class="cartDetails">';
	html += '<div class="upperRow">';
	html += '<h3>';
	html += shopitem.getName();
	
	if(hasFabric)
	{
		//html += ' <span class="gray">(' + cartRow.getFabric() + ')<\/span>';
	}
	
	html += '<\/h3>';
	
	if(hasFabric)
	{
		html += '<img src="' + FABRICS_PATH + cartRow.getFabric() + '.jpg' +'" alt="' + cartRow.getFabric() + '" class="popup" width="30" height="30" />';	
	}
	html += '<\/div>';
	html += '<div class="lowerRow">';
	//html += '<h4>' + shopitem.getShortdescription() + '<\/h4>';
	html += '<p>';
	html += 'QUANTITY: ' + cartRow.getQuantity() + '<br \/>SIZE: ' + cartRow.getSize();
	html += '<\/p>';
	html += '<\/div>';
	html += '<\/div>';
	html += '<span class="cartRowTotal">£' + (shopitem.getPrice() * cartRow.getQuantity()) + '<\/span>';
	html += '<input type="hidden" name="item_name_' + paypalRowIndex + '" value="' + shopitem.getName() + ' (Fabric: ' + cartRow.getFabric() + ')" \/>';
	html += '<input type="hidden" name="quantity_' + paypalRowIndex + '" value="' + cartRow.getQuantity() + '" \/>';
	html += '<input type="hidden" name="item_number_' + paypalRowIndex + '" value="' + shopitem.getId() + '" />';
	html += '<input type="hidden" name="amount_' + paypalRowIndex + '" value="' + shopitem.getPrice() + '.00" />';
	html += '<div class="buttonRow">';
	html += '<a href="javascript:void(0);" class="removebutton cartbutton"><span>REMOVE</span></a>';
	html += '<\/div>';
	html += '<\/div>';
	
	return html;
}

function paintCart()
{
	html = '';
	
	if(cart != null && cart.getCartRows() != null && cart.getCartRows().length > 0)
	{
		html += '<a href="cart.html" id="goToCartButton" class="smallbutton">';
		html += '<span>' + cart.getNumberOfItems() + ' ITEMS (£' + getTotalPrice() + '). GO TO CART<\/span><\/a>';
		
		cartIsShown = true;
	}
	
	jQuery('#cart').html(html);
}

function hideCart()
{
	jQuery('#cart').hide();
}

function paintCartItems()
{
	var cartRows = null;
	var total = null;
	var html = '';
	
	if(cart != null)
	{
		cartRows = cart.getCartRows();
	}
	
	if(cartResultParam != null)
	{
		resetCart();
		
		html += '<div class="cartRow">';
		html += '<div class="cartThumb" /><\/div>';
		html += '<div class="cartDetails" style="text-align: center; width: 100%; margin: 0px; padding: 0px;">';
		html += '<h3 style="margin: 0px 70px 30px;">You\'re order is completed, thanks for shopping at Reko!<\/h3>';
		html += '<\/div>';
		html += '<\/div>';
		
		html += HTML_CLEAR;
	}
	else if(cartRows != null && cartRows.length > 0)
	{	
		for(var i = 0; i < cartRows.length; i++)
		{
			var cartRow = cartRows[i];
			
			if(cartRow != null)
			{
				html += paintCartItem(cartRow, (i+1));
			}
		}
	
		html += HTML_CLEAR;
		
		html += '<div id="cartTotalBox">';
		html += '<img class="cartSeparator" src="res/images/cartseparator.png" alt="" \/>';
		html += '<h3>ITEM TOTAL:<\/h3><span>£' + getTotalPrice() + '<\/span>';
		html += '<h3>DELIVERY:<\/h3><span>U.K £3, Rest of Europe £8<\/span>';
		html += '<img class="cartSeparator" src="res/images/cartseparator.png" alt="" \/>';
		html += HTML_CLEAR;
		html += '<a href="javascript:void(0);" id="paypalorderbutton" class="smallbutton"><span>PAYPAL CHECKOUT<\/span><\/a>';		
		html += HTML_CLEAR;
		html += '<a href="javascript:void(0);" id="sendorderbutton" class="smallbutton"><span>EMAIL ORDER<\/span><\/a>';		
		html += HTML_CLEAR;
		html += '<\/div>';
		
	}
	else
	{
		html += '<div class="cartRow">';
		html += '<div class="cartThumb" /><\/div>';
		html += '<div class="cartDetails" style="text-align: center; width: 100%; margin: 0px; padding: 0px;">';
		html += '<h3 style="margin: 0px 70px 30px;">There´s currently no items in your cart.<\/h3>';
		html += '<\/div>';
		html += '<\/div>';
		
		html += HTML_CLEAR;
	}
	
	
	jQuery("#content").html(html);

	initFabricsPopup();
	
	jQuery(".removebutton").click(function(){
		removeFromCart(jQuery(this).parent().parent().attr('id').substring(3));	
		init(CURRENT_PAGE_CART);
		initCart();
	});
	
	jQuery("#sendorderbutton").click(function(){
		showOverlay();
		showOrderForm();									  
	});
	jQuery("#paypalorderbutton").click(function(){
		document.forms.paypalForm.submit();
	});
}

function paintShopNavigation()
{
	if(categories == null || typeof(categories) == 'undefined' || categories.length == 0)
	{
		return;	
	}
	
	var html = '<ul>';

	for(var i = 0; i < categories.length; i++)
	{
		if(categories[i] != null)
		{
			var imageName = categories[i].getName().toLowerCase() != 'news' ? categories[i].getName().toLowerCase() : categories[i].getName().toLowerCase() + 's';
		html += '<li><a href="shop.html?cat=' + escape(categories[i].getName()) + '" title="' + categories[i].getName() + '">' + '<img alt="' +categories[i].getName().toUpperCase() + '" src="' + IMG_PATH + imageName + '_off.png" \/><\/a></li>';
		}
	}
	
	html += '<li><a href="shop.html?cat=all" title="' + 'all' + '">' + '<img alt="ALL" src="' + IMG_PATH + 'all_off.png" \/>' + '<\/a></li>';
	

	html += '</ul>';
	html += HTML_CLEAR;
	jQuery("#subnav").html(html);
	
	jQuery("img[alt='" + currentCategory.toUpperCase() + "']").attr('src', jQuery("img[alt='" + currentCategory.toUpperCase() + "']").attr('src').replace('off', 'on'));
	
	jQuery("#subnav ul li a img").mouseover(function(){
		jQuery(this).attr('src', jQuery(this).attr('src').replace('off', 'on'));
	});
	jQuery("#subnav ul li a img").mouseout(function(){
		if(jQuery(this).attr('alt') != currentCategory.toUpperCase())
		{
			jQuery(this).attr('src', jQuery(this).attr('src').replace('on', 'off'));
		}
	});
}


function paintShopItems()
{
	if(shopItems != null && shopItems.length > 0)
	{
		var html = '';
		
		jQuery("#content").html('');
		
		paintShopNavigation();
		
		shopItemsSelection = getDressesInCategory();
		
		for(var i = 0; i < shopItemsSelection.length; i++)
		{
			html += paintShopItem(shopItemsSelection[i]);
		}
		
		html += HTML_CLEAR + '<br \/>';
		
		jQuery("#content").html(html);
		
		jQuery("a[title='" + currentCategory + "']").css('color', '#cc2829');
	}
}

function paintPhotoAlbums()
{
	if(photoAlbums != null && photoAlbums.length > 0)
	{
		var html = '';
		
		for(var i = 0; i < photoAlbums.length; i++)
		{
			html += paintPhotoAlbumIcon(photoAlbums[i]);	
		}
		
		jQuery("#content").html(html);
	}
}

function paintPhotoAlbum(id)
{
	var album = getPhotoAlbum(id);
	
	var albumSize = null;
	
	var html = '';
	
	if(album != null && typeof(album) != 'undefined')
	{
		var albumSizeS = album.getAlbumSize();
		albumSize = parseInt(albumSizeS);
	}
	
	if(albumSize != null && typeof(albumSize) != 'undefined' && albumSize > 0)
	{
		html += '<div id="photoAlbumContainer">';
		html += '<h3>' + album.getTitle().toUpperCase() + ' by ' + album.getPhotographer() + '<\/h3>';	
		
		if(album.getEmail() != null && typeof(album.getEmail()) != 'undefined' && album.getEmail().length > 0)
		{
			html += '<p id="photoEmail">Email: ' + album.getEmail();
			
			if(album.getWeb() != null && typeof(album.getWeb()) != 'undefined' && album.getWeb().length > 0)
			{
				html += '<br />Web: ' + album.getWeb() + '<\/p>';
			}
			else
			{
				html += '<\/p>';
			}
		}
		else if(album.getWeb() != null && typeof(album.getWeb()) != 'undefined' && album.getWeb().length > 0)
		{
			html += '<p id="photoWeb">Web: ' + album.getWeb() + '<\/p>';
		}
		
		html += '<div id="photosContainer">';
		for(var i = 0; i < albumSize; i++)
		{
			html += '<img class="albumPhoto" alt="' + album.getTitle() + '" src="' + ALBUM_PATH + album.getFolderName() + '/' + (i+1) + '.' + album.getImageType() + '" \/>';
		}
		html += '<\/div>';
		html += '<\/div>';
		html += HTML_CLEAR;
	}
	else
	{
		html += '<p>No images found for this album.<\/p>';	
	}
	
	jQuery("#content").html(html);
}

function paintNewsItems()
{
	var html = '';
	
	if(newsItems != null && newsItems.length > 0)
	{	
		for(var i = 0; i < newsItems.length; i++)
		{
			html += paintNewsItem(newsItems[i]);	
		}
		
		jQuery("#content").html(html);
		
	}
	else
	{
		jQuery("#content").css("text-align", "center").css("margin-top", "50px").html('<p>COMING SOON...<\/p>');
	}
}

function paintShopItemFabrics(fabricsArray)
{
	var html = '';
	var imgSize = 50;
	
	fabricsArray.sort(fabricsSorter);
	
	html += '<div id="fabricsBox">';
	
	html += '<h5 style="margin-bottom: 5px;">Available prints<\/h5>';
	
	for(var i = 0; i < fabricsArray.length; i++)
	{
		/*html += '<img class="fabricIcon popup" src="' + FABRICS_PATH + fabricsArray[i] + '.jpg" width="' + imgSize + '" height="' + imgSize + '" alt="' + fabricsArray[i] + '" />';*/
		html += '<div class="fabricsIcon"><span>' + fabricsArray[i] + '<\/span><img class="fabricIcon popup" src="' + FABRICS_PATH + fabricsArray[i] + '.jpg" width="' + imgSize + '" height="' + imgSize + '" alt="' + fabricsArray[i] + '" /><\/div>';
	}
	
	html += HTML_CLEAR;
	html += '<\/div>';
	
	return html;
}

function initFabricsPopup()
{
	var firstMove = true;
	
	jQuery("img.popup").mouseleave(function(e)
	{
		jQuery("#fabricDetails").fadeOut('fast');
		fabricPopupShown = false;
		currentFabricPopup = '';
	})
	.mousemove(function(e)
	{
		var pageScroll = getPageScroll();
		var scrollTop = pageScroll[1];
		var t = (e.clientY - 380) > scrollTop ? e.clientY - 380 : e.clientY + (scrollTop + 20);
		var l = (e.clientX - (350/2)) > 0 ? e.clientX - (350/2) : e.clientX + (350/2);
		
		if(firstMove)
		{
			logInfo('ON MOUSEOVER: Scrolltop: ' + scrollTop + ', mouseY: ' + e.clientY + ', mouseX: ' + e.clientX + ', Top: ' + t + ', Left: ' + l);
			firstMove = false;
		}
		
		jQuery('#fabricDetails').css("top", t).css("left", l);
		
	})
	.mouseenter(function(e)
	{
		if(!fabricPopupShown || currentFabricPopup != jQuery(this).attr('alt'))
		{
			paintFabricDetailsBox(jQuery(this).attr('alt'), e.clientX, e.clientY);
		}
	});
}

function paintFabricDetailsBox(fabricName, mouseX, mouseY)
{
	var html = '';
	var imgSize = 300;
	var pageScroll = getPageScroll();
	var scrollTop = pageScroll[1];
	
	currentFabricPopup = fabricName;
	fabricPopupShown = true;
	
	jQuery('#fabricDetails span').html(fabricName);
	jQuery('#fabricDetails img').attr("src", FABRICS_PATH + fabricName + '.jpg').attr("alt", fabricName);;
	var t = (mouseY - 380) > scrollTop ? (mouseY - 380) : mouseY + (scrollTop + 20);
	var l = (mouseX - (350/2)) > 0 ? mouseX - (350/2) : mouseX + (350/2);
	jQuery('#fabricDetails').css("top", t).css("left", l).fadeIn('fast');
}

function paintShopItemDetailsThumbs()
{
	var html = '';
	
	var id = currentItem.getId();
	var name = currentItem.getName();
	var numberOfImages = parseInt(currentItem.getNumberofimages());
	var numberOfThumbs = numberOfImages - 1;
	
	if(numberOfThumbs == 0)
	{
		return '';	
	}
	
	var w = -1;
	var h = -1;
	
	if(numberOfThumbs < 3)
	{
		w = 175;
		h = 208;
		//jQuery("#shopItemThumbs img").css("margin-right", ...);
	}
	else if(numberOfThumbs == 3)
	{
		w = 117;
		h = 139;
		//jQuery("#shopItemThumbs img").css("margin-right", ...);
	}
	else
	{
		w = 87;
		h = 103;
		//jQuery("#shopItemThumbs img").css("margin-right", ...);
	}
	
	for(var i = 1; i < numberOfImages; i++)
	{
		html += '<img src="' + SHOPITEMS_PATH + id + (i + 1) + '.jpg" alt="' + name + '" width="' + w + '" height="' + h + '" \/>';
		if(i == 4 || i == 8 || i == 12 || i == 16)
		{
			html += HTML_CLEAR;	
		}
	}
	
	return html;
}

function paintShopItemDetails(id)
{
	var shopItem = currentItem;
	var hasFabrics = getFabricSet(shopItem.getFabricset()) != null;
	var html = '';
	
	if(shopItem != null)
	{	
		html += '<div id="shopItemImages">';
		html += '<img alt="' + shopItem.getName() + '1' + '" class="pointer" src="' + SHOPITEMS_PATH + shopItem.getId() + PHOTO1_SUFFIX + '" id="largeImage" \/>';
		html += '<div class="clear"><\/div>';
		html += '<div id="shopItemThumbs">';
		html += paintShopItemDetailsThumbs();
		html += HTML_CLEAR;
		html += '<\/div>';
		html += HTML_CLEAR;
		html += '<\/div><!-- END OF SHOPITEMIMAGES -->';
		html += '<div id="shopItemDetails">';
		html += '<h3>' + shopItem.getName().toUpperCase() + ' ' + '£' + shopItem.getPrice() + '<\/h3>';
		html += '<p>' + shopItem.getDescription() + '<\/p>';
		html += '<div id="infoBox">';
		html += '<ul>';
		html += '<li id="fabricdescription">' + shopItem.getFabricdescription() + '<\/li>';
		html += '<li id="careinstructions">' + shopItem.getCareinstructions() + '<\/li>';
		html += '<li id="productdescription">' + shopItem.getProductiondescription() + '<\/li>';
		html += '<\/ul>';
		html += '<\/div>';
		html += HTML_CLEAR;
		
		if(hasFabrics)
		{
			html += paintShopItemFabrics(getFabricSet(shopItem.getFabricset()));
			html += HTML_CLEAR;
		}
		
		html += '<div id="buyBox">';
		
		if(hasFabrics)
		{
			var fabricsArray = getFabricSet(shopItem.getFabricset());
			
			html += '<div class="buyBoxRow">';
			html += '<label for="fabric">FABRIC:</label>';
			html += '<select id="fabric" name="fabric">';
			
			for(var i = 0; i < fabricsArray.length; i++)
			{
				var fabricName = fabricsArray[i];
				html += '<option value="' + fabricName + '">' + fabricName + '<\/option>';
			}
			
			html += '<\/select>';
			html += '<\/div>';
			html += HTML_CLEAR;
		}
		else
		{
			html += '<input type="hidden" name="fabric" id="fabric" value="' + DEFAULT_FABRIC + '" \/>';
		}
		
		html += '<div class="buyBoxRow">';
		html += '<label for="sizes">SIZE:<\/label>';
		
		if(shopItem.getSizes() == null || shopItem.getSizes().length < 2)
		{
			html += '<span class="sizeLabel">One size<\/span>';
			html += '<input type="hidden" name="sizes" id="sizes" value="One size" \/>';
		}
		else
		{
			var sizesArray = shopItem.getSizes();
			html += '<select id="sizes" name="size">';
			
			for(var i = 0; i < sizesArray.length; i++)
			{
				var size = sizesArray[i];
				html += '<option value="' + size + '">' + size + '<\/option>';
			}
			
			html += '<\/select>';
		}
		html += '<\/div>';
		
		html += '<div class="buyBoxRow">';
		html += '<label for="quantityField">QUANTITY:<\/label>';
		html += '<select id="quantityField" name="quantity">';
		html += '<option selected="selected" value="1">1<\/option>';
		html += '<option value="2">2<\/option>';
		html += '<option value="3">3<\/option>';
		html += '<option value="4">4<\/option>';
		html += '<option value="5">5<\/option>';
		html += '<option value="6">6<\/option>';
		html += '<option value="7">7<\/option>';
		html += '<option value="8">8<\/option>';
		html += '<option value="9">9<\/option>';
		html += '<option value="10">10<\/option>';
		html += '<option value="11">11<\/option>';
		html += '<option value="12">12<\/option>';
		html += '<option value="13">13<\/option>';
		html += '<option value="14">14<\/option>';
		html += '<option value="15">15<\/option>';
		html += '<\/select>';
		html += '<\/div>';
		html += '<div class="clear"><\/div>';
		html += '<a href="javascript:void(0);" class="button"><span>BUY<\/span><\/a>';		
		html += '<\/div><!-- END OF BUYBOX -->';
		html += HTML_CLEAR;
		html += '<\/div><!-- END OF SHOPITEMDETAILS -->';
		html += HTML_CLEAR;
	}
	
	jQuery('#content').html(html);
	
	if(hasFabrics)
	{
		initFabricsPopup();
	}
	
	jQuery("#shopItemThumbs img").click(function(){
		var thumbSrc = jQuery(this).attr('src');
		var mainSrc = jQuery("#largeImage").attr('src');
		
		jQuery("#largeImage").attr('src', thumbSrc);
		jQuery(this).attr('src', mainSrc);
	});
}

/** Paints icon for shopitem on main shop page */
function paintShopItem(shopitem)
{
	var html = '';
	
	if(shopitem != null && typeof(shopitem) != 'undefined')
	{
		var hasFabrics = getFabricSet(shopitem.getFabricset()) != null;
		
		var linkUrl = currentCategory != null && typeof(currentCategory) != 'undefined' && currentCategory != 'all' ? 'shop.html?id=' + shopitem.getId() + '&cat=' + currentCategory + '" title="' + shopitem.getName() : 'shop.html?id=' + shopitem.getId() + '" title="' + shopitem.getName();
		
		html += '<div class="shopitem" id="item' + shopitem.getId() + '">';
		html += '<div class="dress">';
		html += '<a href="' + linkUrl + '" title="' + shopitem.getName() + '"><img alt="' + shopitem.getName() + '" height="188" width="158" src="' + SHOPITEMS_PATH + shopitem.getId() + PHOTO1_SUFFIX + '"\/><\/a>';
		html += '<\/div>';
		html += '<div class="description">';
		html += '<a href="shop.html?id=' + shopitem.getId() + '" title="' + shopitem.getName() + '"><h3>' + shopitem.getName() + '<\/h3><\/a>';
		html += '<h3>£' + shopitem.getPrice() + '<\/h3>';
		
		if(hasFabrics)
		{
			html += '<h3 style="color: #de2e2e;">More prints</h3>';
		}
		
		html += '<\/div>';
		html += '<\/div>';
	}
	jQuery("#content").append(html);
	jQuery("#content").append('<p><\/p>'); //INTERNET EXPLORER FIX, KEEP THIS!!!
	return html;
}


function paintNewsItem(newsitem)
{
	var html = '';

	if(newsitem != null && typeof(newsitem) != 'undefined')
	{
		html += '<div class="newsRow" id="row' + newsitem.getId() + '">';
		html += '<img src="' + newsitem.getPhoto() + '" alt="' + newsitem.getTitle() + '" class="newsThumb" \/>';
		html += '<div class="newsContent">';
		html += '<h3>' + newsitem.getTitle() + '"<\/h3>';
		html += '<p>' + newsitem.getContent() + '"<\/p>';
		html += '<\/div>';
		html += '<\/div>';
	}
	return html;
}

function paintPhotoAlbumIcon(albumItem)
{
	
	var html = '';

	if(albumItem != null && typeof(albumItem) != 'undefined')
	{
		html += '<div class="photoalbum" id="album' + albumItem.getId() + '">';
		html += '<div class="cover">';
		html += '<a href="photos.html?id=' + albumItem.getId() + '" title="' + albumItem.getTitle() + '"><img alt="' + albumItem.getTitle() + '" width="239" height="284" src="' + ALBUM_PATH + albumItem.getFolderName() + '/' + albumItem.getAlbumCover() + '"\/><\/a>';
		html += '<\/div>';
		html += '<div class="description">';
		html += '<a href="photos.html?id=' + albumItem.getId() + '" title="' + albumItem.getTitle() + '"><h3>' + albumItem.getTitle() + '<\/h3><\/a>';
		html += '<p>' + albumItem.getPhotographer() + '<\/p>';
		html += '<\/div>';
		html += '<\/div>';
	}
	return html;
}

function showOverlay()
{
	var height = jQuery(document).height();
	var width = jQuery(document).width();
 	if(jQuery.browser.msie && jQuery.browser.version < 9 )
 	{
 		jQuery("#overlay").css({'filter' : 'alpha(opacity=50)', 'display' : 'block', 'height' : height, 'width' : width});
 	}
 	else
 	{
 		jQuery("#overlay").height(height).width(width).fadeIn("fast");
 	}
}
 
function hideOverlay()
{
	jQuery("#overlay").fadeOut("fast").width(1).height(1);
}


/**************************/
/***VALIDATION FUNCTIONS***/
/**************************/
function validateTextInput(string)
{
	if(string != null && typeof(string) == 'string' && string.length > 0)
	{
		return true;	
	}
	
	return false;
}

function validateEmail(email)
{
	var emailReg = "^[\\w-_\.+]*[\\w-_\.]\@([\\w]+\\.)+[\\w]+[\\w]$";
	var regex = new RegExp(emailReg);
	return regex.test(email);
}


/***************************/
/***SHOP & CART FUNCTIONS***/
/***************************/
var CARTROW_ROWID_PREFIX = 'rid';
var CARTROW_QUANTITY_PREFIX = 'q';
var CARTROW_SHOPITEMID_PREFIX = 'sid';
var CARTROW_SIZE_PREFIX = 's';
var CARTROW_TOTAL_PREFIX = 't';
var CARTROW_FABRIC_PREFIX = 'f';

function resetCart()
{
	resetCartCookie();
	
	cart = Cart(new Array());
	paintCart();
}

function resetCartCookie()
{
	var hasNext = true;
	var cartIndex = 1;
	
	while(hasNext)
	{
		var rowidKey = '' + CARTROW_ROWID_PREFIX + cartIndex;
		var shopidKey = '' + CARTROW_SHOPITEMID_PREFIX + cartIndex;
		var sizeKey = '' + CARTROW_SIZE_PREFIX + cartIndex;
		var quantityKey = '' + CARTROW_QUANTITY_PREFIX + cartIndex;
		var totalKey = '' + CARTROW_TOTAL_PREFIX + cartIndex;
		var fabricKey = '' + CARTROW_FABRIC_PREFIX + cartIndex;
			
		var rid = jQuery.cookie(rowidKey);
		var sid = jQuery.cookie(shopidKey);
		var size = jQuery.cookie(sizeKey);
		var q = jQuery.cookie(quantityKey);
		var t = jQuery.cookie(totalKey);
		var f = jQuery.cookie(fabricKey);
		
		if(rid == null || sid == null || size == null || q == null || t == null)
		{
			hasNext = false;
			break;
		}
		else
		{
			jQuery.cookie(rowidKey, null);
			jQuery.cookie(shopidKey, null);
			jQuery.cookie(sizeKey, null);
			jQuery.cookie(quantityKey, null);
			jQuery.cookie(totalKey, null);
			jQuery.cookie(fabricKey, null);
		}
		cartIndex++;
	}
}

function saveCartToCookie()
{
	resetCartCookie();
	
	if(cart != null && typeof(cart) != 'undefined' && cart.getCartRows().length > 0)
	{
		var cartIndex = 1;
		var cartRows = cart.getCartRows();
		
		for(var i = 0; i < cartRows.length; i++)
		{
			var row = cartRows[i];
			
			if(row != null)
			{
				var rid = row.getRowid();
				var sid = row.getShopitemid();
				var size = row.getSize();
				var q = row.getQuantity();
				var t = row.getRowtotal();
				var f = row.getFabric();
				
				var rowidKey = '' + CARTROW_ROWID_PREFIX + cartIndex;
				var shopidKey = '' + CARTROW_SHOPITEMID_PREFIX + cartIndex;
				var sizeKey = '' + CARTROW_SIZE_PREFIX + cartIndex;
				var quantityKey = '' + CARTROW_QUANTITY_PREFIX + cartIndex;
				var totalKey = '' + CARTROW_TOTAL_PREFIX + cartIndex;
				var fabricKey = '' + CARTROW_FABRIC_PREFIX + cartIndex;
				
				jQuery.cookie(rowidKey, '' + rid);
				jQuery.cookie(shopidKey, '' + sid);
				jQuery.cookie(sizeKey, '' + size);
				jQuery.cookie(quantityKey, '' + q);
				jQuery.cookie(totalKey, '' + t);
				jQuery.cookie(fabricKey, '' + f);
				
				cartIndex++;
			}
		}
	}
	else
	{
		resetCart();
	}
	
}

function loadCartFromCookie()
{
	var hasNext = true;
	var cartIndex = 1;
	var cartRowIndex = 0;
	var cartRows = new Array();
	
	while(hasNext)
	{
		var rowidKey = '' + CARTROW_ROWID_PREFIX + cartIndex;
		var shopidKey = '' + CARTROW_SHOPITEMID_PREFIX + cartIndex;
		var sizeKey = '' + CARTROW_SIZE_PREFIX + cartIndex;
		var quantityKey = '' + CARTROW_QUANTITY_PREFIX + cartIndex;
		var totalKey = '' + CARTROW_TOTAL_PREFIX + cartIndex;
		var fabricKey = '' + CARTROW_FABRIC_PREFIX + cartIndex;
			
		var rid = jQuery.cookie(rowidKey);
		var sid = jQuery.cookie(shopidKey);
		var size = jQuery.cookie(sizeKey);
		var qS = jQuery.cookie(quantityKey);
		var tS = jQuery.cookie(totalKey);
		var fS = jQuery.cookie(fabricKey);
		
		var q = parseInt(qS) > 0 ? parseInt(qS) : 0;
		var t = parseInt(tS) > 0 ? parseInt(tS) : 0;
		var f = fS != null ? fS : DEFAULT_FABRIC;
		
		if(rid == null || sid == null || size == null || q == 0 || t == 0)
		{
			hasNext = false;
			break;
		}
		else
		{
			var cartRow = new CartRow(rid, sid, size, q, t, f);
			cartRows[cartRowIndex] = cartRow;
			cartRowIndex++;
		}
		
		cartIndex++;
	}
	
	cart = new Cart(cartRows);
}


function addToCart()
{
	if(checkQuantity())
	{
		var id = currentItem.getId();
		var size = jQuery('#sizes').val();
		var quantity = parseInt(jQuery('#quantityField').val());
		var shopItem = getShopItem(id);
		var total = shopItem.getPrice() * quantity;
		var fabric = jQuery("#fabric").val();
		
		var itemAdded = false;
		
		if(cart != null && cart.getCartRows() != null && cart.getCartRows().length > 0)
		{
			for(var i = 0; i < cart.getCartRows().length; i++)
			{
				var cartRow = cart.getCartRows()[i];
				
				if(shopItem.getId() == cartRow.getShopitemid() && size == cartRow.getSize() && cartRow.getFabric() == fabric)
				{
					cart.getCartRows()[i].quantity = (cart.getCartRows()[i].quantity + quantity);
					cart.getCartRows()[i].rowtotal = (cart.getCartRows()[i].quantity * shopItem.getPrice());
					itemAdded = true;
				}
			}
		}
		
		if(!itemAdded)
		{
			var cartRow = new CartRow(Math.round(Math.random() * 100000), id, size, quantity, total, fabric);
			addCartRow(cartRow);
		}
		
		saveCartToCookie();
		
		paintCart();
	}
}

function removeFromCart(itemId)
{
	if(cart != null && cart.getCartRows() != null && cart.getCartRows().length > 0 && itemId != null)
	{
		var oldCart = cart.getCartRows();
		var newCart = new Array();
		var newCartIndex = 0;
		
		for(var i = 0; i < oldCart.length; i++)
		{
			if(oldCart[i].getRowid() != itemId)
			{
				newCart[newCartIndex] = oldCart[i];
				newCartIndex++;
			}
			else
			{}
		}
		
		cart = new Cart(newCart);
		saveCartToCookie();
		paintCart();
	}
}

function addCartRow(cartRow){
	
	var cartRows = cart.getCartRows();
	
	if(cartRows != null)
	{
		cartRows[cartRows.length] = cartRow;
	}
	else
	{
		cartRows = new Array();
		cartRows[0] = cartRow;
	}
	cart = new Cart(cartRows);
}


function checkQuantity()
{
	var q = parseInt(jQuery("#quantityField").val());
	
	if(q != null && typeof(q) != 'undefined' && q > 0)
	{
		return true;	
	}
	
	return false;
}

function getTotalPrice()
{
	var rows = cart.getCartRows();
	var total = 0;
	
	if(rows != null && typeof(rows) != 'undefined')
	{	
		for(var i = 0; i < rows.length; i++)
		{
			var row = rows[i];
			
			total += row.getRowtotal();
		
		}
	}
	return total;
}

function getTotalPriceInclDelivery()
{
	return getTotalPrice() + DELIVERY;
}

function showEditCartRowBox(cartRowId)
{
	jQuery("#editCartRowBox").html('');
	var cartRows = cart.getCartRows();
	var cartRow = null;
	var shopItem = null;
	
	for(var i = 0; i < cartRows.length; i++)
	{
		if(cartRows[i].getRowid = cartRowId)
		{
			cartRow = cartRows[i];
			shopItem = getShopItem(cartRow.getShopitemid());
		}
	}
	
	if(cartRow != null && shopItem != null)
	{
		var currentSize = cartRow.getSize();
		var currentQuantity = cartRow.getQuantity();
		var html = '';
		
		html += '<label for="sizes">SIZE:<\/label>';
		
		if(shopItem.getSizes() == null || shopItem.getSizes().length == 0)
		{
			html += '<input type="hidden" name="sizes" id="sizes" value="One size fits all" \/>';
		}
		else
		{
			html += '<select id="sizes" name="size">';
		
			var sizesArray = shopItem.getSizes();
		
			for(var i = 0; i < sizesArray.length; i++)
			{
				var size = sizesArray[i];
				
				if(cartRow.getSize() == size)
				{
					html += '<option value="' + size + '" selected="selected"">' + size + '<\/option>';
				}
				else
				{
					html += '<option value="' + size + '">' + size + '<\/option>';
				}
				
			}
			
			html += '<\/select>';
		}
		
		html += HTML_CLEAR;
		
		html += '<label for="quantityField">QUANTITY:<\/label>';
		html
		html += '<select id="quantityField" name="quantity">';
		for(var i = 1; i < 16; i++)
		{
			if(i == currentQuantity)
			{
				html += '<option value="' + i + '" selected="selected">' + i + '<\/option>';
			}
			else
			{
				html +=	'<option value="' + i + '">' + i + '<\/option>';
			}
		}
		html += '<\/select>';		
		html += HTML_CLEAR;
		html += '<a class="button smallbutton" href="javascript:void(0);" id="editActionButton"><span>EDIT<\/span><\/a>';
		html += '<a class="button smallbutton" href="javascript:void(0);" id="editCancelButton"><span>CANCEL<\/span><\/a>';
		html += HTML_CLEAR;
		
		var editBox = jQuery("#editCartRowBox");
		editBox.html(html);
		
		var editH = editBox.height();
		var editW = editBox.width();
		var windowH = jQuery(window).height();
		var windowW = jQuery(window).width();
		
		var cssObj = {
        "top": (windowH / 2) - (editH / 2) * 0.7,
        "left": (windowW / 2) - (editW / 2)
      }
		editBox.css(cssObj).fadeIn("fast");	
		
		jQuery("#editActionButton").click(function(){
			var newSize = jQuery("#sizes").val();
			var newQuantity = parseInt(jQuery("#quantityField").val());
			
			if(newSize != currentSize || newQuantity != currentQuantity)
			{
				var theCartRows = cart.getCartRows();
				var theNewCartRows = new Array();
				
				for(var i = 0; i < theCartRows.length; i++)
				{
					/*TODO FIX THIS. UPDATE CART, GO TO SLEEP. KISS KISS KISS */	
					
				}
			}
			hideOverlay();
			jQuery("#editCartRowBox").fadeOut();	
		});
		jQuery("#editCancelButton").click(function(){
			hideOverlay();
			jQuery("#editCartRowBox").fadeOut();	
		});
	}
}

function writeOrderMail()
{
	if(cart != null && cart.getCartRows() != null && cart.getCartRows().length > 0)
	{
		var form = jQuery("#contactForm");
		var firstName = jQuery("#firstName").val();
		var lastName = jQuery("#lastName").val();
		var email = jQuery("#email").val();
		var address = jQuery("#address").val();
		var zipCode = jQuery("#zipCode").val();
		var city = jQuery("#city").val();
		var country = jQuery("#country").val();
		
		var orderMail = '';
		orderMail += 'ORDER FROM REKO.CO.UK\n************************************\n\n' + cart.getNumberOfItems() + ' items. Total price incl Delivery: £' + getTotalPriceInclDelivery() + '\n\nName: ' + firstName.toUpperCase() + ' ' + lastName.toUpperCase() + '\n';
		orderMail += 'Street: ' + address.toUpperCase() + '\nPostal code: ' + zipCode + '\nCity: ' + city.toUpperCase() + '\nCountry: ' + country.toUpperCase() + '\n\n';
		orderMail += 'Email: ' + email + '\n\n';
		orderMail += 'ORDER:\n****************************************************************************\n';
		
		var cartRows = cart.getCartRows();
		
		for(var i = 0; i < cartRows.length; i++)
		{
			var cartRow = cartRows[i];
			
			var quantity = '' + cartRow.getQuantity();
			var shopItem = getShopItem(cartRow.getShopitemid());
			
			orderMail += (i+1) + ': ' + quantity + ' pcs. ID:' + shopItem.getId() + ', NAME: ' + shopItem.getName() + '. FABRIC: ' + cartRow.getFabric() + '. ';
			orderMail += 'PRICE/PCS: ' + shopItem.getPrice() + ', SIZE: ' + cartRow.getSize() + ', ROW TOTAL: £' + cartRow.getRowtotal() + '.\n';
		}
		
		
		orderMail += '****************************************************************************\n';
		var delivery = country == 'GB' ? 3 : 8;
		orderMail += 'DELIVERY: £' + delivery + '\n';
		orderMail += 'TOTAL PRICE: £' + (getTotalPrice() + delivery) + ' (' + getTotalPrice() + ' + ' + delivery + ').';
		
		return orderMail;
	}
	
	return null;
}


function paintAlert(message)
{
	var theTimeOut = null;
	
	if(!alertBoxIsRunning)
	{
		alertBoxIsRunning = true;
		
		showOverlay();
		
		var alertBox = jQuery('<div id="alertBox"><\/div>').insertAfter('#content');
		
		var html = '<p>' + message + '<\/p>';
		alertBox.html(html);
		
		var alertH = alertBox.height();
		var alertW = alertBox.width();
		var windowH = jQuery(window).height();
		var windowW = jQuery(window).width();
		
		var top = (windowH / 2) - (alertH / 2) * 0.8;
		var left = (windowW /2) - (alertW / 2);
	
		jQuery('#overlay').click(function(){
			hideAlert();
			theTimeOut = null;
		});
		jQuery("#alertBox").css('top', top).css('left', left).fadeIn(500, function(){
			theTimeOut = setTimeout('hideAlert()', 2500);
		});	
	}
}

function hideOrderForm()
{
	jQuery("#orderFormContainer").fadeOut("fast");
}

function writeCustomerOrderMail()
{
	return "pip";
}

function showOrderForm()
{
	var orderForm = jQuery("#orderFormContainer");
	var theName = "";
	
	jQuery("#orderFormContainer #cancelButton").click(function(){
		hideOrderForm();
		hideOverlay();
	});
	
	jQuery("#orderFormContainer #orderButton").click(function(){
		var result = validateOrderForm();
		
		if(result != null)
		{
			alert(result);	
		}
		else
		{
			var order = writeOrderMail();
			var customerOrder = writeCustomerOrderMail();
			
			if(order != null)
			{
				var success = false;
				var returnMessage = '';
				
				while(order.indexOf('&') > 0)
				{
					order = order.replace('&', encodeURIComponent('&'));
				}
				while(order.indexOf('=') > 0)
				{
					order = order.replace('=', encodeURIComponent('='));
				}

				jQuery.ajax({
				  	type: 'POST',
				  	url: 'sendorder.php',
					cache: false,
				  	data: 'aName=' + theName + '&theMessage=' + order,
				  	success: function(msg)
					{
						if(msg != null && typeof(msg) == 'string')
						{
							if(msg == "ok")
							{
								resetCart();
								paintAlert('Your order has been sent.');
							}
							else if(msg == "oops" || msg == "nono")
							{
								paintAlert('An error occured while processing your order, please try again.');
							}
						}
						else
						{
							hideOrderForm();
							hideOverlay();
							paintAlert('An error occured, please try again.');
							msg = msg == null || typeof(msg) != 'string' ? 'null/undefined' : msg;
							logInfo(msg);	
						}
				  	}
				});
				
				hideOrderForm();
				hideOverlay();
			}
			
			init(CURRENT_PAGE_CART);
			initCart();
		}
	});
	
	var orderH = orderForm.height();
	var orderW = orderForm.width();
	var windowH = jQuery(window).height();
	var windowW = jQuery(window).width();
	
	 var cssObj = {
        "top": ((windowH / 2) - (orderH / 2)) * 0.8,
        "left": (windowW / 2) - (orderW / 2)
      }


	jQuery("#orderFormContainer").css(cssObj).fadeIn("fast");
}

function hideAlert()
{
	if(alertBoxIsRunning)
	{
		alertBoxIsRunning = false;
		
		jQuery("#alertBox").fadeOut(1200, function(){
			clearAlert();
			hideOverlay();
		});
	}
}

function clearAlert()
{
	jQuery("#alertBox").html('');
}

function validateOrderForm()
{
	var invalidFields = new Array();
	var invalidFieldsIndex = 0;
	
	var form = jQuery("#contactForm");
	var firstName = jQuery("#firstName").val();
	var lastName = jQuery("#lastName").val();
	var email = jQuery("#email").val();
	var address = jQuery("#address").val();
	var zipCode = jQuery("#zipCode").val();
	var city = jQuery("#city").val();
	var country = jQuery("#country").val();
	
	if(!validateTextInput(firstName))
	{
		invalidFields[invalidFieldsIndex] = 'First name';
		invalidFieldsIndex++;
	}
	if(!validateTextInput(lastName))
	{
		invalidFields[invalidFieldsIndex] = 'Last name';
		invalidFieldsIndex++;
	}
	if(!validateTextInput(address))
	{
		invalidFields[invalidFieldsIndex] = 'Address';
		invalidFieldsIndex++;
	}
	if(!validateTextInput(zipCode))
	{
		invalidFields[invalidFieldsIndex] = 'Zip code';
		invalidFieldsIndex++;
	}
	if(!validateTextInput(city))
	{
		invalidFields[invalidFieldsIndex] = 'City';
		invalidFieldsIndex++;
	}
	if(!validateEmail(email))
	{
		invalidFields[invalidFieldsIndex] = 'Email';
		invalidFieldsIndex++;
	}
	
	if(invalidFields.length == 0)
	{
		return null;	
	}
	else if(invalidFields.length == 1)
	{
		if(invalidFields[0] == 'Email')
		{
			if(email.length == 0)
			{
				return 'The email field is blank';	
			}
			else
			{
				return 'The email address seems invalid';
			}
		}
		else
		{
			return 'The field ' + invalidFields[0] + ' must not be empty.';
		}
	}
	else 
	{
		var returnString = 'You following field have illegal values:\n';
		
		for(var i = 0; i < invalidFields.length; i++)
		{
			returnString += invalidFields[i];
			returnString += '\n';
		}
		
		return returnString;
	}
	return "Unknown error";
}

function getFabricSet(fabricName)
{
	if(fabricName == null || typeof(fabricName) != 'string' || fabrics == null || fabrics.length == 0)
	{
		return null;	
	}
	else
	{
		for(var i = 0; i < fabrics.length; i++)
		{
			var f = fabrics[i];
			if(f.getName() != null && f.getName() == fabricName)
			{
				return f.getIds();
			}
		}
	}
	
	return null;
}

/************/
/*** AJAX ***/
/************/

function loadShopItems(currentShopItem)
{
	var items = new Array();
	jQuery.ajax(
	{ 
		type: "GET", url: "res/xml/rekoshop.xml", dataType: (jQuery.browser.msie) ? "text" : "xml", error: function(x, errorType, errorThrown) { alert('Error type is: ' + errorType + ', Error thrown: ' + errorThrown ); },
success: function(data)
		{
			var xml;
		    if (typeof data == "string") 
			{
		     	xml = new ActiveXObject("Microsoft.XMLDOM");
		       	xml.async = false;
		       	xml.loadXML(data);
		    } 
			else {
		       	xml = data;
		    }
			
			data = null;
			
			var alertString = "";
			var shopItemIndex = 0;
			
			if(xml != null)
			{
				fabrics = new Array();
				
				jQuery(xml).find('fabrics').each(function()
				{
					var nameS = jQuery(this).find('name').text();
					var name = nameS != null && typeof(nameS) != 'undefined' ? nameS : '';
					var fabricsInFabricsSet = new Array();
					var fabricsIndex = 0;
					
					jQuery(this).find('id').each(function()
				 	{
						fabricsInFabricsSet[fabricsIndex] = jQuery(this).text();
						fabricsIndex++;
					});
						
					fabrics.push(new Fabrics(name, fabricsInFabricsSet));
				});
				
				jQuery(xml).find('shopitem').each(function()
				{
					var idS = jQuery(this).find('id').text();
					var nameS = jQuery(this).find('name').text();
					var shortdescriptionS = jQuery(this).find('shortdescription').text();
					var descriptionS = jQuery(this).find('description').text();
					var priceS = jQuery(this).find('price').text();
					var sizesS = new Array();
					var productiondescriptionS = jQuery(this).find('productiondescription').text();
					var careinstructionsS = jQuery(this).find('careinstructions').text();
					var fabricdescriptionS = jQuery(this).find('fabricdescription').text();
					var fabricssetS = jQuery(this).find('fabricset').text();
					var numberofimagesS = jQuery(this).find('numberofimages').text();
					
					var id = idS != null && typeof(idS) != 'undefined' ? idS : '';
					var name = nameS != null && typeof(nameS) != 'undefined' ? nameS : '';
					var shortdescription = shortdescriptionS != null && typeof(shortdescriptionS) != 'undefined' ? shortdescriptionS : '';
					var description = descriptionS != null && typeof(descriptionS) != 'undefined' ? descriptionS : '';
					var price = priceS != null && typeof(priceS) != 'undefined' ? priceS : '';
					var sizes = new Array();
					var productiondescription = productiondescriptionS != null && typeof(productiondescriptionS) != 'undefined'? productiondescriptionS : '';
					var careinstructions = careinstructionsS != null && typeof(careinstructionsS) != 'undefined' ? careinstructionsS : '';
					var fabricdescription = fabricdescriptionS != null && typeof(fabricdescriptionS) != 'undefined' ? fabricdescriptionS : '';
					var fabricsset = fabricssetS != null && typeof(fabricssetS) != 'undefined' ? fabricssetS : '';
					var numberofimages = numberofimagesS != null && typeof(numberofimagesS) != 'undefined' ? numberofimagesS: '';
					
					var sizeIndex = 0;
					
					jQuery(this).find('sizes').each(function()
					{	
						jQuery(this).find('size').each(function()
					 	{
							sizes[sizeIndex] = jQuery(this).text();
							sizeIndex++;
						});
					});
					//Valid shopitem. Place it in shopitemcontainer.
					var newShopItem = new ShopItem(id, name, shortdescription, description, price, sizes, fabricdescription, careinstructions, productiondescription, fabricsset, numberofimages);
					
					if(debugThis)
					{
						logInfo(newShopItem.toString());	
					}
					
					shopItems[shopItemIndex] = newShopItem;
					shopItemIndex++;
				});
				
				//shopItems.sort(shopItemSorter);
				
				categories = new Array();
				
				jQuery(xml).find('category').each(function()
				{
					var nameS = jQuery(this).find('name').text();
					var name = nameS != null && typeof(nameS) != 'undefined' ? nameS : '';
					
					jQuery(this).find('dresses').each(function()
					{	
						var dressesInCategory = new Array();
						var categoryIndex = 0;
						
						jQuery(this).find('id').each(function()
					 	{
							dressesInCategory[categoryIndex] = jQuery(this).text();
							categoryIndex++;
						});
						
						categories.push(new Category(name, dressesInCategory));
					});
					
				});
				
				if(currentPage == CURRENT_PAGE_CART)
				{
					paintCartItems();
				}
				else if((currentShopItem != null) && currentPage == CURRENT_PAGE_DETAIL)
				{
					initDetails(currentShopItem);	
				}
				else 
				{
					paintShopItems();
				}
			}
			else
			{
				logError('Could not load data.');
				alertString = 'Could not load data.';
			}
		}
	});
}

function loadPhotoAlbums(currentAlbum)
{
	var items = new Array();
	jQuery.ajax(
	{ 
		type: "GET", url: "res/xml/rekophotos.xml", dataType: ($.browser.msie) ? "text" : "xml", error: function(x) { alert('response is: ' + x.responseText); },
success: function(data)
		{
			var xml;
		    if (typeof data == "string") {
		     	xml = new ActiveXObject("Microsoft.XMLDOM");
		       	xml.async = false;
		       	xml.loadXML(data);
		    } 
			else {
		       	xml = data;
		    }
			
			data = null;
			
			var alertString = "";
			var photoAlbumIndex = 0;
			
			if(xml != null)
			{
				jQuery(xml).find('album').each(function()
				{
					var idnum = -1;
					var id = jQuery(this).find('id').text();
					var photographerS = jQuery(this).find('photographer').text();
					var emailS = jQuery(this).find('email').text();
					var titleS = jQuery(this).find('title').text();
					var webS = jQuery(this).find('web').text();
					var albumCoverS = jQuery(this).find('album-cover').text();
					var imageTypeS = jQuery(this).find('image-type').text();
					var albumSizeS = jQuery(this).find('album-size').text();
					var folderNameS = jQuery(this).find('folder-name').text();
					
					var photographer = photographerS != null && typeof(photographerS) != 'undefined' ? photographerS : '';
					var email = emailS != null && typeof(emailS) != 'undefined' ? emailS : '';
					var title = titleS != null && typeof(titleS) != 'undefined' ? titleS : '';
					var web = webS != null && typeof(webS) != 'undefined' ? webS : '';
					var albumCover = albumCoverS != null && typeof(albumCoverS) != 'undefined' ? albumCoverS : '';
					var imageType = imageTypeS != null && typeof(imageTypeS) != 'undefined' ? imageTypeS : '';
					var albumSize = albumSizeS != null && typeof(albumSizeS) != 'undefined' ? albumSizeS : '';
					var folderName = folderNameS != null && typeof(folderNameS) != 'undefined' ? folderNameS : '';
					
					if(id != null && typeof(id) != 'undefined' && !isNaN(id))
					{
						idnum = parseInt(id);	
					}
					
					if(idnum > 0)
					{								
						var album = new PhotoAlbum(id, photographer, email, title, web, albumCover, imageType, albumSize, folderName);
						photoAlbums[photoAlbumIndex] = album;
						photoAlbumIndex++;
					}
					else
					{
						alert('Id ' + id + ' is not a valid id.');
					}
				});
				if(currentAlbum == null || typeof(currentAlbum) == 'undefined')
				{
					paintPhotoAlbums();
				}
				else if(currentAlbum > 0)
				{
					paintPhotoAlbum(currentAlbum);	
				}
			}
			else
			{
				logError('Could not load data.');
				alertString = 'Could not load data.';
			}
		}
	});
}

function loadNewsItems()
{
	var items = new Array();
	jQuery.ajax(
	{ 
		type: "GET", url: "res/xml/rekonews.xml", dataType: ($.browser.msie) ? "text" : "xml", error: function(x) { alert('response is: ' + x.responseText); },
success: function(data)
		{
			var xml;
		    if (typeof data == "string") {
		     	xml = new ActiveXObject("Microsoft.XMLDOM");
		       	xml.async = false;
		       	xml.loadXML(data);
		    } 
			else {
		       	xml = data;
		    }
			
			data = null;
			
			var alertString = "";
			var newsItemIndex = 0;
			
			if(xml != null)
			{
				jQuery(xml).find('newsitem').each(function()
				{
					var idnum = -1;
					var id = jQuery(this).find('id').text();
					var dateS = jQuery(this).find('date').text();
					var titleS = jQuery(this).find('title').text();
					var photoS = jQuery(this).find('photo').text();
					var contentS = jQuery(this).find('content').text();
					
					var date = dateS != null && typeof(dateS) != 'undefined' ? dateS : '';
					var title = titleS != null && typeof(titleS) != 'undefined' ? titleS : '';
					var photo = photoS != null && typeof(photoS) != 'undefined' ? photoS : '';
					var content = contentS != null && typeof(contentS) != 'undefined' ? contentS : '';
					
					if(id != null && typeof(id) != 'undefined' && !isNaN(id))
					{
						idnum = parseInt(id);	
					}
					
					if(idnum > 0)
					{
						//Valid shopitem. Place it in shopitemcontainer.
						newsItems[newsItemIndex] = new NewsItem(id, date, title, photo, content);
						newsItemIndex++;
						//alert('Id  is ' + id);
					}
					else
					{
						//alert('Id ' + id + ' is not a valid id.');
					}
				});
				paintNewsItems();
			}
			else
			{
				logError('Could not load data.');
				alertString = 'Could not load data.';
			}
		}
	});
}


// getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
}

// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
    var windowHeight
    if (self.innerHeight) { // all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }
    return windowHeight
}

function logInfo(stringToLog)
{
	if ( this.console && typeof(console.log) != 'undefined' ) 
	{ 
		// IE8, Firebug, Safari, etc. 
		console.log(stringToLog); 
	}
}

function fabricsSorter(a, b)
{
	var intA = parseInt(a);
	var intB = parseInt(b);
	
	return a - b;
}

function shopItemSorter(a, b)
{
	var aname = a.getName() != null ? a.getName().toLowerCase() : "";
	var bname = b.getName() != null ? b.getName().toLowerCase() : "";
	
	return aname - bname;
}