Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

removeFlaskLeakInIE = function(id) {
    var obj = document.getElementById(id);
        if (obj) {
            for (var i in obj) {
                if (typeof obj[i] == "function") {
                obj[i] = null;
                }
        }
        obj.parentNode.removeChild(obj);
    }
}

Gallery = {
	currentImage: 0,
	imageCountHolder: null,
	parentWidth: null,
	parentHeight: null,
	maxCount: null,
	thumbHolder: null,
	nextButton: null,
	prevButton: null,
	custom: false,
	active: false,
	init: function( custom, thumbHolder, imageCountHolder, nextButton, prevButton) {
		// set custom variables
		this.custom = custom;
		this.imageCountHolder = imageCountHolder;
		this.maxCount = $("img", thumbHolder).length;
		this.nextButton = nextButton;
		this.prevButton = prevButton;
		this.parentWidth = $("#main-content").width()-20;
		this.parentHeight = $("#main-content").height()-20;
				
		// check if a specific image has been specified in the URL
		if(document.URL.match(/#[0-9]+/)) {
			this.gotoImage(new Number(new String(document.URL.match(/#[0-9]+/)).replace("#", "")) - 1);
		} else {
			this.gotoImage(0);
		} 
		// 
		this.attachEvents();
	},
	attachEvents: function() {
		// write next/prev functions
		this.nextButton.click(function(e) {
		e.preventDefault();
			if(!Gallery.active) {
				Gallery.next();
				//this.blur();
			}
			
			return false;
		});
		this.prevButton.click(function(e) {
		e.preventDefault();
			if(!Gallery.active) {
				Gallery.previous();
				//this.blur();
			}
			
			return false;
		});

	},
	next: function() {
		// show next image
		this.gotoImage(this.currentImage + 1);
	},
	previous: function() {
		// show previous image
		this.gotoImage(this.currentImage - 1);
	},
	addCart: function(param) {
		
		
		if (param != '#' && !Gallery.active) {
			
			Gallery.active = true;
			
			$cart = $('#add-to-cart a');
			$cartPreloader = $('#cart-preloader');	
			$cart
			.removeAttr("onclick")
			.attr('href','#')
			
		
			
			$cartPreloader
				.stop()
				.animate({'opacity':1}, 300, function() { 
										
						$.ajax({
							type: "POST",
							url: param,
							success: function(response) {
								if(response == "success") {
									$.ajax({
										type: "GET",
										url: "php/getGalleryJSON.php",
										dataType: 'json',
										data: {id: galleryID},
										success: function(data) {
											$.each(data, function(key, value) {
												galleryList[key] = value;
											});
										},
										complete: function() {
											
											$cartPreloader.stop().animate({'opacity':0}, 300, function(){
												$cart
												.html('In cart')
												$('#cart-holder')
												.css('visibility','visible')
												Gallery.active = false;	
											});	
																	
										}
									}); 
								}
							}
						});
				});
						
		}
		
	},
	updateCount: function(newCount) {
		// set current image
		this.currentImage = newCount;
		//
		var newCountPrefix = (newCount < 9) ? "0" : "";
		var maxCountPrefix = (this.maxCount < 9) ? "0" : "";
		// update current image display
		this.imageCountHolder.innerHTML = newCountPrefix + "" + (newCount + 1) + "/" + maxCountPrefix + this.maxCount;
		// update url
		window.location.hash = (newCount + 1);
		return false;
	},
	
	gotoImage: function(num) {
		//initialise variables
	if (!Gallery.active) {	
		Gallery.active = true;
		
		var highResPath, lowResPath, priceVal, cartVal, nextSet;
		var preload = [];
		//assign variables
		$custom = this.custom;
		$container = $('#gallery-container');
		$preloader = $('#preloader');
		$imageHolder = $('#image-placeholder');
		$flashHolder = $('#flash-placeholder');
		$descHolder = $('#description');
		$priceHolder = $('#price');
		$cartHolder = $('#add-to-cart');

		//check current image is not more than the total list of images
		if(num >= this.maxCount) {
			num = 0;
		} else if(num < 0) {
			num = this.maxCount - 1;
		}
		//hide containing div to being changes		
		$([$container.get(0), $descHolder.get(0), $priceHolder.get(0), $cartHolder.get(0) ])
			.stop()
			.animate({ 'opacity': 0}, 300, function() {
				//show preloader while doing changes
				
				$preloader
					.css({'left':"50%"})
					.stop()
					.animate({'opacity':1}, 300, function() { 
						
						//get current type - swf or image
						var type = galleryList[num].type;
		
						if(type!="video") {
							
							//remove flash div
							if($flashHolder.length > 0){
								$flashHolder.remove();
								//memory leak fix in ie
								if (jQuery.browser.msie) {
       		 						removeFlaskLeakInIE('flash-placeholder');
								}
							}
							//if image holder div is removed rebuild it
							/*if(!$imageHolder.length > 0){
								$container.append('<div id="image-placeholder"><a href="" id="image" rel="lightbox"><img src="docs/images/blank.gif" /></a></div>');
							}*/
							$imageHolder.css({"position":"relative", "left": 0});
							
							//assign variables from array
							var image = galleryList[num].image;
							var text = galleryList[num].text;
							var price = galleryList[num].price;
							var waterMark = galleryList[num].waterMark;
							var inCart = galleryList[num].inCart;
							var currency = galleryList[num].currency;
							var textContainsCartLinks = galleryList[num].textContainsCartLinks;
							//check if item has watermark
							if(waterMark && !$custom) {
								if(showHighRes){
									highResPath='php/includes/image.php?id='+galleryID+'&imageid='+num+'&highRes=1';
								}else{
									highResPath='php/includes/image.php?id='+galleryID+'&imageid='+num+'&highRes=0';
								}
								
								lowResPath='php/includes/image.php?id='+galleryID+'&imageid='+num+'&highRes=0';
							} else {
								if(showHighRes){
									highResPath='highRes/'+image;
								}else{
									highResPath='images/'+image;
								}
								lowResPath='images/'+image;				
							}
							
							//add currency and price
							
							//check if current image is added to cart
							if(!$custom) {
								if(!inCart) {
									if(textContainsCartLinks){
										cartVal = '<a href="#">Disabled</a>';
										priceVal = '';
									}else{
										priceVal = 'Price: $'+currency+price;
										cartVal = '<a href="add-to-cart.php?galleryid='+galleryID+'&imageid='+num+'&price='+price+'" onclick="Gallery.addCart(this.href); return false;">Add to cart &rarr;</a>';
									}
								} else {
									cartVal = '<a href="#">In cart</a>';
									if(textContainsCartLinks){
										priceVal = '';
									}else{
										priceVal = 'Price: $'+currency+price;
									}
								}
							}
							
							//assign variables to dom elements
							
							$('a[rel="lightbox"]')
								.attr('href', highResPath)
								.find('img')
								.attr('src', lowResPath)
								.load( function(){ 
									//$(this).attr('width', $(this).width()).attr('height', $(this).height());
									$(this).removeAttr('width').removeAttr('height');
									var currWidth = $(this).width();
									var currHeight = $(this).height();
									if (currWidth > Gallery.parentWidth) {
										$(this).attr('width',Gallery.parentWidth);
									} else if (currHeight > Gallery.parentHeight) {
										$(this).attr('height',Gallery.parentHeight);
									}
								
									//check to see if description div is available - used for custom template
									if(!$custom) {
										$('#description').html(text).scrollTop(0);
									}
									$('#price').html(priceVal);
									$('#cart-holder').html(cartVal);
									if(textContainsCartLinks && !inCart){
										$('#cart-holder').css('visibility','hidden');
									}else{
										$('#cart-holder').css('visibility','visible');
										
									}
									//show containing div and hide preloader when all changes have been done
									
										$([$container.get(0),$descHolder.get(0), $priceHolder.get(0), $cartHolder.get(0)]).stop().animate({ 'opacity': 1}, 300, function() {
											$preloader.stop().animate({'opacity':0}, 300, function(){$preloader.css({'left':"-9999px"}); });	
										}); 
								
								});
									
							
						} else {
							//video
							var text = galleryList[num].text;
							var price = galleryList[num].price;
							var inCart = galleryList[num].inCart;
							var currency = galleryList[num].currency;
							var textContainsCartLinks = galleryList[num].textContainsCartLinks;
							//remove image holder div
							if($imageHolder.length > 0){
								$imageHolder.css({"position":"absolute", "left": -9999});
								//memory leak fix in ie
								if (jQuery.browser.msie) {
									removeFlaskLeakInIE('flash-placeholder');
								}
							}
							//if flash holder div is removed rebuild it
							if(!$flashHolder.length > 0){
								$container.append('<div id="flash-placeholder"><div id="flash"></div></div>');
							}
							
							//check if current image is added to cart
							if(!$custom) {
								if(!inCart) {
									if(textContainsCartLinks){
										cartVal = '<a href="#">Disabled</a>';
										priceVal = '';
									}else{
										priceVal = 'Price: $'+currency+price;
										cartVal = '<a href="add-to-cart.php?galleryid='+galleryID+'&imageid='+num+'&price='+price+'" onclick="Gallery.addCart(this.href); return false;">Add to cart &rarr;</a>';
									}
								} else {
									cartVal = '<a href="#">In cart</a>';
									if(textContainsCartLinks){
										priceVal = '';
									}else{
										priceVal = 'Price: $'+currency+price;
									}
									
									
								}
							}
							$('#price').html(priceVal);
							$('#cart-holder').html(cartVal);
							if(textContainsCartLinks && !inCart){
								$('#cart-holder').css('visibility','hidden');
							}else{
								$('#cart-holder').css('visibility','visible');
								
							}
							if(!$custom) {
								$('#description').html(text).scrollTop(0);
							}
							
							//assign variable from array
							var image = galleryList[num].image;
							//change extension to flv
							var video = image.replace('.jpg','.flv');
							//load up swfobject
							//if (swfobject.hasFlashPlayerVersion("8")){
								var videoflashvars = {};
								videoflashvars.vidFileName = video;
								var videoparams = {};
								
								videoparams.menu="false";
								videoparams.wmode="transparent";
								swfobject.embedSWF("video-player.swf", "flash", "615", "385", "8.0.0",false,videoflashvars,videoparams);
								//show containing div and hide preloader when all changes have been done
							
								$([$container.get(0), $descHolder.get(0), $priceHolder.get(0), $cartHolder.get(0)]).stop().animate({ 'opacity': 1}, 300, function() {
									$preloader.stop().animate({'opacity':0}, 300, function(){$preloader.css({'left':"-9999px"}); });	
									
								});
								

							//}		
						}
						Gallery.active = false;
						
			});
			
		
		});
		//preload the next set of images
		nextSet = num+5;
		//get total no of elements in object
		var totalEl = Object.size(galleryList);
		//if set is not more than the total no of elements then preload				
		if (nextSet < totalEl) {
			for (var i = num; i < nextSet; i++) {
				var type = galleryList[i].type;
				var image = galleryList[i].image;
				var waterMark = galleryList[i].waterMark;
				//only preload images
				if(type!="video") {	
					if(waterMark) {
						preload.push('php/includes/image.php?id='+galleryID+'&imageid='+i+'&highRes=0');
					} else {
					//add images to preloady array
					preload.push('images/'+image);
								
					}
				}
			}
		}
		//run preload function
		$.preload(preload, {ext: ''});		
		//update counter
		this.updateCount(num);							
		
	}
	
	}
}


