﻿if (typeof (window.HomePartnerModule) == "undefined") {
    window.HomePartnerModule = {};
}

(function(HomePartnerModule, $) {

    // Retrieves the results from the web service.
    HomePartnerModule.Init = function (id, serviceUrl, contentName, urlRoot, rotationTimeSeconds) {
	
		var module = $("#" + id);
		
        //load initial content
        getResults(module, serviceUrl, contentName, urlRoot);
        
        //start the timed rotation of items
        var timeout = setInterval(function () {
            displayNextResult(id, urlRoot, "Random");
        }, rotationTimeSeconds * 1000);
		
		setProperties(module, "currentIndex", -1);
		setProperties(module, "rotationTimeSeconds", rotationTimeSeconds);
		setProperties(module, "timeout", timeout);
		setProperties(module, "urlRoot", urlRoot);
    }

    function getResults($module, serviceUrl, contentName, urlRoot) {
        $.ajax({
            type: 'POST',
            url: serviceUrl + '/GetPartnerItems',
            data: "{ContentName:\"" + contentName + "\"}",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(result)
                 {
                    if (result.d != null && result.d.length > 0)
                    {
						var id = $module.attr("id");
                        //store the item data for this module, as well as a list of valid indexes (used by the randomizer)
                        $module.data("items", result.d).data("indexes", getIndexArray(result.d));
                        //show the first (random) item using the retrieved data
                        displayNextResult(id, urlRoot, "Random");
						setupScroll(id, urlRoot);
                    }
                 },
            failure: function(error)
                 {
                    //TODO: Do something
                 }
        });
    }

    // Displays the next (random) result. Assumes that data has been loaded by a prior call to getResults.
    function displayNextResult(id, urlRoot, action) {
      
		var module = $('#' + id),
			item = null;
			
		if (action === "Random") {
			item = pickNextItem(module);
		} else if (action == "Next") {
            item = getNextItem(module);
		} else if (action == "Prev") {
			item = getPreviousItem(module);
		}
        
        if (module.length > 0 && item) {
			var url = item.URL.replace('~/', urlRoot);
            module.find('.Title').html(item.Title).attr('href', url);
            module.find('.Text').html(item.Text).attr('href', url);
            module.find('.Image').empty().append('<img src="' + item.ImageURL + '" alt="' + item.ImageLabel + '" />');
        }
    }
	
	function getNextItem($module) {
		return getItemByAction($module, "Next");
	}
	
	function getPreviousItem($module) {
		return getItemByAction($module, "Prev");
	}
	
	function getItemByAction($module, action) {
		var items = $module.data("items"),
			currentIndex = getProperties($module, "currentIndex"),
			timeout = getProperties($module, "timeout");
		
		var id = $module.attr("id"),
			urlRoot = getProperties($module, "urlRoot"),
			rotationTimeSeconds = getProperties($module, "rotationTimeSeconds");
				
		clearTimeout(timeout);
		timeout = setInterval(function () {
			displayNextResult(id, urlRoot, "Random");
		}, rotationTimeSeconds * 1000);
		setProperties($module, "timeout", timeout);
		
		var newIndex = (action == "Prev")
				? getPreviousIndex(currentIndex, items.length)
				: getNextIndex(currentIndex, items.length);
				
		setProperties($module, "currentIndex", newIndex);
		return items[newIndex];
	}
    
    // Uses the module's item list and list of valid (i.e. not yet shown) indices to pick a random successor.
    function pickNextItem($module) {
        var result = null,
			items = $module.data("items"),
            indexes = $module.data("indexes"),
			currentIndex = getProperties($module, "currentIndex");
        
		if (items.length == 1) {
			currentIndex = 0;
			result = items[currentIndex];
        } else if (indexes.length > 1) {
            var randIdx = randomNumber(indexes.length);
			currentIndex = indexes[randIdx];
            result = items[currentIndex];
            $module.data("indexes", removeIndex(indexes, randIdx));
        } else if (indexes.length == 1) {
            //last index
			currentIndex = indexes[0];
            result = items[currentIndex];
            $module.data("indexes", getIndexArray(items));
        }
		
		setProperties($module, "currentIndex", currentIndex);
		return result;
    }
	
	function setupScroll(id, urlRoot) {
		var scroll = $("#" + id + " .Scroll").show();
		var next = $(".Next", scroll).bind("click", function() {
			displayNextResult(id, urlRoot, "Next");
			});
		var prev = $(".Prev", scroll).bind("click", function() {
			displayNextResult(id, urlRoot, "Prev");
			});
	}
    
    function randomNumber(max) {
        //note that max is exclusive (i.e. will never return max)
        return Math.floor(Math.random() * (max));
    }
    
    function getIndexArray(items) {
        // returns an array of all possible indices in array "items"
        var result = [];
        for (var i = 0; i < items.length; i++) {
            result[i] = i;
        }
        return result;
    }
	
	function getNextIndex(index, size) {
		return (index == size - 1) ? 0 : index + 1;
	}
	
	function getPreviousIndex(index, size) {
		return (index == 0) ? size - 1 : index - 1;
	}
    
    function removeIndex(indexArray, index) {
        //removes the item at the given index from the given array
        return indexArray.slice(0, index).concat(indexArray.slice(index+1));
    }
	
	function setProperties($module, key, value) {
		var properties = $module.data("properties");
		if (typeof properties == "undefined") {
			properties = {};
		}
		properties[key] = value;
		$module.data("properties", properties);
	}
	
	function getProperties($module, key) {
		var properties = $module.data("properties");
		if (typeof properties != "undefined") {
			return properties[key];
		}
		return null;
	}
    
})(HomePartnerModule, jQuery);
