var curpos, items = [];

var ajaxloaderCar = new YAHOO.util.Element('ajax-loaderCarousel'); 
ajaxloaderCar.setStyle('display', 'block');

// When the container is loaded
YAHOO.util.Event.onAvailable("container_carousel", function(){
	var carousel;
  
  
  carousel = new YAHOO.widget.Carousel("container_carousel", {
	 // Items visibles per page
     numVisible: 5,
	 // number of items which will be displayed, get in carousel.tpl (script)
     numItems: numberOfItems,
	 // Function called to load the items
	 //loadItemsHandler: getImages(),
	 // Reveal a part of the logo
	 revealAmount: 0,
	 // Infinite carousel ?
	 isCircular: false,
	 // Animation
	 animation: { speed: 1, effect: YAHOO.util.Easing.easeOut },
	 // Button naviguation 
	 navigation: { prev: null, next: null }
  });
   
  curpos = 0;
  
  YAHOO.util.Connect.asyncRequest("GET", "/ajax/carousel_ajax.php?pos="+curpos, {
		  success: function (o) {
			var i;
			r = eval(o.responseText);
			curpos = r.length;
	
			for (i = 0; i < curpos; i++) {
			  items.push(r[i]);
			}
	
			// check if the Carousel widget is available
			if (typeof carousel != "undefined") {
			  for (i = 0; i < curpos; i++) {
				// if so, shove the elements into it
				carousel.addItem(getImageTag(items[i]));
			  }
			  carousel.set("selectedItem", 0);
			  items = [];
			}
		  },
	
		  failure: function (o) {
			alert("Ajax request failed!");
		  }
  }
  , null);
  
	carousel.on("loadItems", function (o) {
		// more items available?
		getImages.call(this);
	});
	
	
	carousel.on("itemSelected", function (index) {
		var item = carousel.getElementForItem(index);
	});
	
	
	carousel.render();
	ajaxloaderCar.setStyle('display', 'none');
	carousel.show();
});

function getImageTag(img) {
	// if only one location
	if(img.count == 1) {
		linkString = "<a href=\"/page/charity/" + img.loc_id + "\" title=\"" + img.name + "\" >";
	}
	// if many locations
	else {
		linkString = "<a href=\"/page/charitylocations/" + img.id + "\" title=\"" + img.name + "\" >";
	}
			tag = linkString;
			tag += "<img src=\"/images/charity/" + img.image_code + "_logo.jpg\" width=\"83px\" title=\"" + img.name + "\" alt=\"" + img.name + "\" />";
			tag += "</a>";
			tag += "<p class=\"logoFont\" style=\"width:83px; text-align:center;\">";
			tag += linkString + img.name + "</a>";
			tag += "</p>";
	

	return tag;
}


function getImages() {
	var carousel = this;
	                
    YAHOO.util.Connect.asyncRequest("GET",
				    "/ajax/carousel_ajax.php?pos="+curpos, {
            success: function (o) {
				var i = curpos,
				j = 0,
				r = eval(o.responseText);
			
			curpos += r.length;
			
			while (i < curpos) {
				if (r[j]) {
					carousel.addItem(getImageTag(r[j]));
				} 
				else {
					break;
				}
				i++;
				j++;
			}
			
			carousel.set("selectedItem", carousel.get("firstVisible"));
	    },
					    
	    failure: function (o) {
	        alert("Ajax request failed!");
	    }
    });
}