// ----------------------------------------------------------------------
// CenterPoint Energy
// CNP Public Site - Utility JavaScript functions for CNP content.
// ----------------------------------------------------------------------

var imagePath = "/staticfiles/CNP/Common/SiteAssets/img/";

var isDebug = false; // turn ON/OFF debugging alerts...


/*
// Testing...
// ------------------
var imagesWithWeight = [
	['15', 'image-01', 'alt for image 1', 'http://www.cnn.com'],
	['40', 'image-02', 'alt for image 2', 'http://www.w3schools.com'],
	['10', 'image-03', 'alt for image 3'],
	['15', 'image-04', 'alt for image 4', 'http://www.google.com'],
	['20', 'image-05', 'alt for image 5', 'http://www.centerpointenergy.com']
];

//var selectedItemsForTest = selectOneByWeight(imagesWithWeight);
//var selectedItemsForTest = selectMultipleByWeight(imagesWithWeight, 2);
var selectedItemsForTest = null;
if(selectedItemsForTest != null) {
	for(i=0;i<selectedItemsForTest.length;i++) {
		var name   = selectedItemsForTest[i][1];
		var alt    = selectedItemsForTest[i][2];
		var weight = selectedItemsForTest[i][0];
		var url    = selectedItemsForTest[i][3];
		alert("name ("+i+"): "+name);
		alert("alt ("+i+"): "+alt);
		alert("weight ("+i+"): "+weight);
		alert("url ("+i+"): "+url);
	}
} // end-if(selectedItemsForTest != null)
//displayPromotionalImages(imagesWithWeight, 2);
// -------------------
*/

function displayPromotionalImages(arrayOfImagesWithWeight, numberToShow) {
	
	var selectedImages = selectMultipleByWeight(arrayOfImagesWithWeight, numberToShow);
	var selectedImagesWithoutWeight = null;
	
	if(selectedImages != null && selectedImages.length > 0) {
		
		// Build array for image display (without weight attribute)...
		selectedImagesWithoutWeight = new Array(selectedImages.length);
		for(i=0;i<selectedImages.length;i++) {
			selectedImagesWithoutWeight[i] = new Array();
			var attr1 = selectedImages[i][1];
			var attr2 = selectedImages[i][2];
			var attr3 = selectedImages[i][3];
			if(attr1 != null) selectedImagesWithoutWeight[i][0] = attr1;
			if(attr2 != null) selectedImagesWithoutWeight[i][1] = attr2;
			if(attr3 != null) selectedImagesWithoutWeight[i][2] = attr3;
		} // end-for
		
	} // end-if(selectedImages != null && selectedImages.length > 0)
	
	if(selectedImagesWithoutWeight != null) renderImagesInline(selectedImagesWithoutWeight, 'cnp-promo-images', 'v');
}

/*
Accepts a 2-D array of the form:
	Array[i][0] = image source
	Array[1][1] = image alt text (optional)
	Array[1][2] = image link url (optional)
and renders the images as inline HTML, following the direction 
specified (i.e. horizontal or vertical).

The 'wrapperDivClass' will be used in the class attribute for an outer
'div' tag that contains all images. If a link is provided, the image will
be wrapped in an appropriate <a> tag.

Options for specifying the rendering direction can be:
	horizontal, h, H
	vertical, v, V
By default, the images will render vertically if no direction is specified
or if value cannot be interpreted.
*/
function renderImagesInline(arrayOfImageData, wrapperDivClass, verticalOrHorizontal) {
	if(arrayOfImageData != null && arrayOfImageData.length > 0) {
		
		var divClass = (wrapperDivClass != null && wrapperDivClass.length > 0) ? wrapperDivClass : "inline-images";
		var outputHTML = "<div class='" + divClass + "'>";
		var isVertical = (verticalOrHorizontal != 'horizontal' || verticalOrHorizontal != 'h' || verticalOrHorizontal != 'H') ? true : false;
		
		for(i=0;i<arrayOfImageData.length;i++) {
			var imageSource = arrayOfImageData[i][0];
			var imageAlt = arrayOfImageData[i][1];
			var imageURL = arrayOfImageData[i][2];

			if(isVertical) outputHTML += "<div>";
			if(imageURL != null && imageURL.length > 0) {
				outputHTML += "<a href='";
				outputHTML += imageURL;
				outputHTML += "' title='";
				outputHTML += imageAlt;
				outputHTML += "'>";
			}
			outputHTML += "<img ";
			if(i < (arrayOfImageData.length-1)) {
				if(isVertical) {
					outputHTML += "style='margin-bottom:8px' ";
				} else {
					outputHTML += "style='margin-right:8px' ";
				}
			} // end-if(i < (arrayOfImageData.length-1))
			outputHTML += "border='0' src='";
			outputHTML += imagePath + imageSource;
			outputHTML += "' alt='";
			outputHTML += imageAlt;
			outputHTML += "'/>";
			if(imageURL != null && imageURL.length > 0) outputHTML += "</a>";
			if(isVertical) outputHTML += "</div>";
		} // end-for
		
		outputHTML += "</div>";
		
	} // end-if(arrayOfImageData != null && arrayOfImageData.length > 0)
	
	document.write(outputHTML);
	//document.write("<textarea cols='50' rows='10'>" + outputHTML + "</textarea>");
}


/*
 Accepts an array and randomly selects one element to return.
*/	
function selectOneRandomly(arrayOfItems) {
	var numOfItems = arrayOfItems.length;
	var index = Math.floor((Math.random() * numOfItems));
	
	return arrayOfItems[index];
}

/*
Accepts any 2-D array where the first element is its probabilistic weight for 
display, and returns a randomly selected item from the array, utilizing the 
weighted probability of it being selected.

If successful, returns an array of size 1 with all of its originating elements.
*/
function selectOneByWeight(arrayOfItemsWithWeight) {
	var selectedItem = null;

	if(arrayOfItemsWithWeight != null) {
		var numOfItems = arrayOfItemsWithWeight.length;
		
		if(numOfItems > 1) {
			
			// Initialize return object...
			selectedItem = new Array(1);
			selectedItem[0] = new Array();
					
			// Build array for performing weighted selection...
			var weightedArray = new Array(numOfItems);
			for(i=0;i<numOfItems;i++) {
				if(i==0) {
					var numberValue = new Number(arrayOfItemsWithWeight[i][0] - 1)
					weightedArray[i] = numberValue;
				} else {
					var addend1 = new Number(weightedArray[i-1]);
					var addend2 = new Number(arrayOfItemsWithWeight[i][0])
					weightedArray[i] = addend1 + addend2;
				}
				if(isDebug) alert("adding["+i+"]: "+weightedArray[i]);
			} // end-for
			
			// Choose a random index and select corresponding item...
			var maxWeight = new Number(weightedArray[numOfItems-1]+1);
			if(isDebug) alert("max weight: "+maxWeight);
			var randomIndex = Math.floor((Math.random() * maxWeight));
			if(isDebug) alert("random index: "+randomIndex);
			for(j=0;j<weightedArray.length;j++) {
				var itemSpan = new Number(weightedArray[j]);
				if(randomIndex <= itemSpan) {
					if(isDebug) alert("index ("+randomIndex+") is inside item span ("+itemSpan+")");
					selectedItem[0] = arrayOfItemsWithWeight[j]
					break;
				}
			} // end-for
			
		} else if(numOfItems == 1) {
			selectedItem[0] = arrayOfItemsWithWeight[0];
		}
		
	} // end-if(arrayOfItemsWithWeight != null)
	
	return selectedItem;
}

/*
Accepts any 2-D array with the following required elements:
	Array[i][0] = probabilistic weight for display (e.g. a percentage)
	Array[1][1] = a unique item name
and returns a an array of randomly selected elements from the array (according
to the number of selections requested), utilizing the weighted probability of 
each being selected.

If successful, returns an array of size 'numToSelect' with all of its 
originating elements.

NOTE: Once an element is selected, it is removed from subsequent selections so
it can never be chosen more than once. This also means that the maximum number
to select cannot be greater than the number of elements in the array.
*/
function selectMultipleByWeight(arrayOfItemsWithWeight, numToSelect) {
	var selectedItems = null;

	if(isDebug) alert("Entered selectMultipleByWeight, looking for "+numToSelect+" items...");

	if(arrayOfItemsWithWeight != null && numToSelect > 0) {
		selectedItems = new Array(numToSelect);
		
		if(numToSelect > 1) {
			if(numToSelect <= arrayOfItemsWithWeight.length) {
				for(k=0;k<numToSelect;k++) {
					var selectedItem = selectOneByWeight(arrayOfItemsWithWeight);
					if(isDebug) alert("selected item: "+selectedItem[0].toString());
					selectedItems[k] = new Array();
					selectedItems[k] = selectedItem[0];
					var lastItem = new Number(numToSelect-1);
					if(isDebug) alert("comparing "+k+" to "+lastItem);
					if(k<lastItem) {
						if(isDebug) alert("performing select again with a removal...");
						var indexToRemove = -1;
						for(n=0;n<arrayOfItemsWithWeight.length;n++) {
							if(arrayOfItemsWithWeight[n][1] == selectedItem[0][1]) {
								indexToRemove = n;
								if(isDebug) alert("determined index to remove: "+indexToRemove);
								break;
							}
						} // end-for
						if(indexToRemove > -1) {
							if(isDebug) alert("removing entry from array: "+indexToRemove);
							var currentSize = arrayOfItemsWithWeight.length;
							if(isDebug) alert("current size: "+currentSize);
							modifiedArrayOfItemsWithWeight = new Array(currentSize-1);
							for(x=0;x<currentSize-1;x++) {
								modifiedArrayOfItemsWithWeight[x] = new Array();
								var indexToKeep = (x>=indexToRemove) ? x+1 : x;
								if(isDebug) alert("index to populate: "+x+", item to take: "+indexToKeep);
								modifiedArrayOfItemsWithWeight[x] = arrayOfItemsWithWeight[indexToKeep];
							}
							arrayOfItemsWithWeight = modifiedArrayOfItemsWithWeight;
							if(isDebug) alert("size of array is now: "+arrayOfItemsWithWeight.length);
						}
					} // end-if(i<lastSelection)
				} // end-for
			} // end-if(numToSelect <= arrayOfItemsWithWeight.length)
		
		} else {
			selectedItems[0] = selectOneByWeight(arrayOfItemsWithWeight);
		}
	
	} // end-if(arrayOfItemsWithWeight != null && numToSelect > 0)

	return selectedItems;
}