/*global C4 */

/**
 * Additional sugar for gallery pages
 * Simply adds mesh images overlays to thumbnails
 * @author: jnewbery
 * @version: 1.0
 **/

var c4Gallery = {
	
	MESH_IMAGE_SRC: "/media/global/pf/gallery-mesh.gif",
	protoImage: null,
	
	/**
	 * Return an initiation function called on DOM content ready.
	 * Init function creates a prototype mesh image node and iterates through linked thumbnails to insert a clone in the DOM
	 * @return Function
	 **/
	getInit: function () {
		var that = this;
		return function () {
			// Insert mesh image into all thumbnail list items with a link
			var thumbContainer = C4.DOM.getElementsByClassName("thumb-display-list", "ul");
			that.createProtoImage();
			if (thumbContainer.length) {
				var thumbLinks = thumbContainer[0].getElementsByTagName('a');
				for (var i = 0; i < thumbLinks.length; i++) {
					that.insertMeshImage(thumbLinks[i]);
				}
			}
		};
	},
	
	/**
	 * Creates a prototype mesh image node
	 **/
	createProtoImage: function () {
		this.protoImage = document.createElement('img');
		this.protoImage.src = this.MESH_IMAGE_SRC;
		this.protoImage.width = 58;
		this.protoImage.height = 38;
		this.protoImage.alt = "";
		this.protoImage.className = "mesh-image";
	},
	
	/**
	 * Inserts a mesh image into the node provided
	 * @param	par	Element
	 **/
	insertMeshImage: function (par) {
		var thisMeshImage = this.protoImage.cloneNode(false);
		if (typeof par === "object") {
			par.appendChild(thisMeshImage);
		}
	}
	
};

/* Check for required objects and methods and add event listener */
if (C4 && C4.BOM && C4.BOM.addDOMLoadEvent) {
	C4.BOM.addDOMLoadEvent(c4Gallery.getInit());
}

/* Counter For Upload Form */

function userGalleryCounter(inputObj, counterObj, limit) {
	// Dynamically builds object (textarea) variable
	// this is done to cope with multiple objects with the same ID in different forms
	inputForm = inputObj.form;
	var counterObj = eval("document." + inputForm.name + "." + counterObj);
	var thisObj = eval("document." + inputForm.name + "." + inputObj.name);
	var textAreaObj =  eval("document." + inputForm.name + "." + counterObj.id);	

	if (parseInt(limit) - parseInt(thisObj.value.length) >=0) {
		thisObj.style.color = "#000";
	} else {
		thisObj.style.color = "#f00";
	}
	textAreaObj.value = parseInt(limit) - parseInt(thisObj.value.length);
}




