/*
Name:       Content Loader
Version:    0.0.7 (5. Mai 2011)
Author:     Finn Rudolph
Support:    rudolph@stadtwerk.org

License:    This code is licensed under a Creative Commons 
            Attribution-Noncommercial 3.0 Unported License 
            (http://creativecommons.org/licenses/by-nc/3.0/).

            You are free:
                + to Share - to copy, distribute and transmit the work
                + to Remix - to adapt the work

            Under the following conditions:
                + Attribution. You must attribute the work in the manner specified by the author or licensor 
                  (but not in any way that suggests that they endorse you or your use of the work). 
                + Noncommercial. You may not use this work for commercial purposes. 

            + For any reuse or distribution, you must make clear to others the license terms of this work.
            + Any of the above conditions can be waived if you get permission from the copyright holder.
            + Nothing in this license impairs or restricts the author's moral rights.
*/


/* Constructor */
function ContentLoader()
{
	/* Closure for this */
	var my = this;
	
	/* Setting option defaults */
	this.defaults =
	{
		containerIDList:    'stadtwerk_projects',               /* Id of the container holding the items */
		containerIDCard:    'cards',               				/* Id of the container holding the items */
		jsonId:             'project_json',                     /* Id of the container holding the JSON */
		loadLinkId:         'load_projects',   
		itemPrefix:         'project_'                          /* Prefix of the item id - like 'item_7' */
	};

	/* Initialize */
	this.init = function(options)
	{
		/* Evaluate options */
		for(var name in my.defaults)
		{
			this[name] = (options !== undefined && options[name] !== undefined) ? options[name] : my.defaults[name];
		}
		
		/* Only use the loader if there is a jsonElement that tells it what to load */
		var jsonElement = document.getElementById(my.jsonId);
		if(jsonElement)
		{
			/* Parse settings */
			this.settings = JSON.parse(jsonElement.innerHTML);
			
			/* Delete json element from DOM */
			jsonElement.parentNode.removeChild(jsonElement)
		
			this.requestCounter = 0;
	
			/* Get a reference to the load and container element */
			this.loadElement = document.getElementById(my.loadLinkId);
			if(my.loadElement)
			{
				if(my.settings.view == 'card')
				{
					this.container = document.getElementById(my.containerIDCard);
				}
				else
				{
					this.container = document.getElementById(my.containerIDList);
				}
				
				/* Add events */
				this.setOnClickEvents();			
			}
		}
	};
	
	/* Add the onclick event to each content item */
	this.setOnClickEvents = function()
	{
		my.loadElement.onclick = my.clickEvent;
	};
	
	this.clickEvent = function()
	{	
		/* Add an empty div container before the foot element in the list */
		var emptyContainer = document.createElement('DIV');
		var lastListItem = my.loadElement.parentNode;
		my.container.insertBefore(emptyContainer, lastListItem);
		my.setClassName(emptyContainer, 'loading');
		emptyContainer.innerHTML = '<img src="fileadmin/setup/images/loading.gif" width="48" height="48" alt="loading" />';
		
		/* Increment the request counter */
		my.requestCounter += 1; 
		
		/* Calculate the next limit */
		var limit = my.settings.limit + (my.settings.max * my.requestCounter);
		
		/* Delete load element parent if there are no more projects to load */
		if(limit + my.settings.max >= my.settings.projects)
		{
			my.loadElement.parentNode.parentNode.removeChild(my.loadElement.parentNode);
		}

		/* Create url */
		var path = window.location.host+window.location.pathname;
		var url = window.location.protocol+'//';
		url += (my.settings.ajax_page_url) ? my.settings.ajax_page_url+'?' : path+'?id='+my.settings.ajax_page_id+'&';
		url += 'limit='+limit;
		url += (my.settings.client !== null) ? '&client='+my.settings.client : '';
		url += (my.settings.search !== null) ? '&search='+my.settings.search : '';
		url += (my.settings.tag !== null) ? '&tag='+my.settings.tag : '';
		url += (my.settings.view !== null) ? '&view='+my.settings.view : '';		

		/* Make the request */
		var Ajax = new AJAX();
		var options =
		{
			mode: 'GET',
			url: url,
			callSource: function(){return emptyContainer;},
			returnFunction: my.update
		};
		Ajax.call(options);
	};
	
	/* Write the AJAX response to the DOM */
	this.update = function(response, getTargetElement)
	{
		var element = getTargetElement();
		my.setClassName(element, 'projects');
		element.innerHTML = response;
		if(my.settings.view == 'card')
			Views.addCards();
	};

	/* Add events */
	this.addEvent = function( obj, type, fn )
	{
		if (obj.addEventListener)
		{
			obj.addEventListener( type, fn, false );
		}
		else if (obj.attachEvent)
		{
			obj['e'+type+fn] = fn;
			obj[type+fn] = function() { obj['e'+type+fn]( window.event ); }
			obj.attachEvent( 'on'+type, obj[type+fn] );
		}
	};
	
	/* Set class attribute - className must be set for the IE family */
	this.setClassName = function(element, className)
	{
		if(element && className !== undefined)
		{
			element.setAttribute('class',className);
			element.setAttribute('className',className);
		}
	};
}

/* Create global ContentLoader instance when the DOM structure has been loaded */
domReady(function()
{
	Content = new ContentLoader();
	Content.init();
});
