/**
 * jQuery treasurehunter
 * 
 * this is the javascript part of the TYPO3 Extension tn_treasurehunter. 
 * 
 * Extension Description:
 * 		A TYPO3 raffle extension. The raffle is based on finding words/letters/images in the frontend. 
 * 		The word/letter/image is placed randomly on every x pages.
 *
 * @author Florian Strauss <florian.strauss@wgo-online.com>
 * @access public
 *
 * @example
 * 		$.treasurehunter({
 *			container: '#CE',
 *			showAt: '2'
 *		});
 *
 * Options:
 * 		container	jQuery Selektor		Selector where the item is placed
 * 		showAt		Integer				every X Page a item is shown
 * 		positions	Array				a Array with favorite positions
 * 										Example:  [{top: 45, left: 60},{top: 60, left: 90}}
 * 			
 */

/**
 * Example Data
 * 
 */ 
var treasurehunterExample = {
	"baseURL" : "http://portal.buenting-tee.loc",
	"imagePath" : "fileadmin/templates/images/schatzsuche/",
	"searchWordPage":"index.php?=145",
	"letterFoundPage":"index.php?=138",
	"allLetterFoundPage":"index.php?=139",
	"excludePages": ['services/teebeutel-schatzsuche/navigation/impressum.html', '/nc/services/teebeutel-schatzsuche.html'],
	"startTreaserhunt":1,
	"cookieDomain": ".buenting-tee.loc",
	"cookiePath" : "/",
	"cookieExpire" : "0",
	letters : [
            	{found: 0, uid: 51, images:['schatzsuche/01_teebeutel.gif','schatzsuche/01_teebeutel_found.gif','schatzsuche/01_teebeutel_empty.gif']},
            	{found: 0, uid: 51, images:['schatzsuche/02_teebeutel.gif','schatzsuche/02_teebeutel_found.gif','schatzsuche/02_teebeutel_empty.gif']},
            	{found: 0, uid: 51, images:['schatzsuche/03_teebeutel.gif','schatzsuche/03_teebeutel_found.gif','schatzsuche/03_teebeutel_empty.gif']},
            	{found: 0, uid: 51, images:['schatzsuche/04_teebeutel.gif','schatzsuche/04_teebeutel_found.gif','schatzsuche/04_teebeutel_empty.gif']}
            ]		
};

/**
 * Set the example data in a cookie
 * disabled! we get a fresh cookie from our TYPO3 friend! ;)
 */
// $.cookie('tntreasurehunter', JSON.stringify(treasurehunterExample));

(function($){

$.treasurehunter = function(options) {
	
	/**
	 * Global variables 
	 */
	var pagecount,
		data,
		config = {
			container: 'body',
			showAt: '2',
			positions: []
		};
	
	$.extend(config, options);
	
	/**
	 * Init / Constructor
	 * 
	 * is called when the plugin is called
	 * 
	 * Starts the hunt when the Treasurehunt ist started and we are currently not on a HunterServicePage
	 * 
	 * @access private
	 * @return void
	 */
	$.treasurehunter.init = function() {
		
		
		/**
		 * get everything from the cookie as Javascript Object
		 */
		data = $.treasurehunter.getCookieAsObject();
		if(!data) {
			return;
		}
		
		if(!$.treasurehunter.getData('pagecount')) {
			$.treasurehunter.setData('pagecount', 0);
		}
		
		
		
		
		if($.treasurehunter.getData('startTreaserhunt') == 1 && !$.treasurehunter.isOnExcludedPage()) {
		
			$.treasurehunter.hunt();
		}		
	};
	
	/**
	 * starts the hunt!
	 * 
	 *  - get a random element which is not found yet from the letters array
	 *  - append it to the container
	 *  
	 *  @access 	private
	 *  @return 	void
	 *  @example
	 *  			$.treasurehunter.hunt(); // lets go!
	 */
	$.treasurehunter.hunt = function() {
		
		pagecount = parseInt($.treasurehunter.getData('pagecount'), 10) +1;

		$.treasurehunter.setData('pagecount', pagecount);
		
		if(pagecount == 1) {
			return false;
		}
		
		if(!(pagecount % config.showAt)) {
			
			var item	= $.treasurehunter.getElement(),
				element = $('<div>'),
				image	= $('<img>'),
				url,
				popup;
			
			/**
			 * all items are found so cancel everything!
			 */
			if(!item) {
				return false;
			}

			/**
			 * sets the parent to relative so the child can be position absolute
			 */
			$(config.container).css('position','relative');

			
			
	
			image.attr('src',$.treasurehunter.getData('baseURL')+$.treasurehunter.getData('imagePath')+item.images[0]);
			image.click(function() {
				
				$.treasurehunter.setFound(item.index);
				
				if($.treasurehunter.isFoundAll()) {
					url= $.treasurehunter.getData('baseURL')+'/'+$.treasurehunter.getData('allLetterFoundPage');
				} else {
					url= $.treasurehunter.getData('baseURL')+'/'+$.treasurehunter.getData('letterFoundPage');
				}
				
				popup = window.open(url, 'hunt', "width=500px,height=580px,status=no,toolbar=no,location=no,menubar=no,resizable=no,scrollbars=yes");
				popup.focus();
				return false;
			});
			
			element.addClass('treasurehunter findme');
			element.css({
				cursor: 'pointer'
			});
			
			element.append(image);
			
			$.treasurehunter.placeOnPage(element);
			
			
		}
	};
	/**
	 * returns the whole tntreasurehunter cookie as object
	 * 
	 * decode the JSON string from the cookie to a javascript object
	 * 
	 * @access 	private
	 * @return	Object		the cookie as javascript object
	 * @example
	 * 			console.dir($.treasurehunter.getCookieAsObject());
	 */
	$.treasurehunter.getCookieAsObject = function() {
		if(!$.cookie('tntreasurehunter')) {
			return false;
		}
		return JSON.parse($.cookie('tntreasurehunter'));
	};
	/**
	 * place the searchable item on the page (in the config.container)
	 * 
	 * if no favorits are given - get random value
	 * 
	 * @param	Object		Element Object
	 * @return 	bool
	 * @access 	private
	 */
	$.treasurehunter.placeOnPage = function(element) {
		
		var leftPx, topPx, index;
		
		
		if(!config.positions.length) {
			leftPx 	= $.treasurehunter._random(0,$(config.container).width())+'px';
			topPx	= $.treasurehunter._random(0,$(config.container).height())+'px';
		} else {
			index 	= $.treasurehunter._random(0, (config.positions.length -1));
			leftPx	= config.positions[index].left;
			topPx	= config.positions[index].left;
		}
		
		element.css({
			position: 	'absolute',
			'top': 		topPx,
			'left':		leftPx
		});
		element.hide();
		
		element.appendTo(config.container);
		
		element.fadeIn(2000);
	};
	/**
	 * checks if we are currently on an excluded page (eg. allletterfoundpage or letterfoundpage etc..)
	 * 
	 * returns true or false
	 * 
	 * @return 	bool
	 * @access 	private
	 * @example
	 * 			if($.treasurehunter.isOnExcludedPage()) {
	 * 				alert('yep! we are on an exlcuded page');
	 * 			}
	 */
	$.treasurehunter.isOnExcludedPage = function() {
		
		var url = window.location.href,
			flag = false;

		$($.treasurehunter.getData('excludePages')).each(function(i, item) {
			
			if(url == $.treasurehunter.getData('baseURL')+'/'+item) {
				flag = true;
			}
		});
		return flag;

	};
	/**
	 * sets the item to "found"
	 * 
	 * @param	integer		index of the data.letters Array
	 * @return	bool
	 * @example
	 * 			$.treasurehunter.setFound(2);
	 */
	$.treasurehunter.setFound = function(index) {
		var letters = $.treasurehunter.getData('letters');
		
		letters[index].found = 1;
		
		$.treasurehunter.setData('letters', letters);
		
		return true;
	};
		
	/**
	 * checks if all items are found
	 * 
	 * returns a true or false
	 * 
	 * @access 	private
	 * @return	bool
	 * @example
	 * 			if($.treasurehunter.isFoundAll()) {
	 * 				alert('you found everything!');
	 * 			}
	 */
	$.treasurehunter.isFoundAll = function() {
		var num = 0,
			letters;
		
		letters = $.treasurehunter.getData('letters');		
		
		$(letters).each(function(i, item) {
		
			if(item.found == 1) {
				num+=1;
			}
		});
		if(num == letters.length) {
			return true;
		} else {
			return false;
		}
	};
	/**
	 * get the next random element 
	 * 
	 * the methode checks if the element is allready found
	 * 
	 * @access	public
	 * @return	Object
	 * @example
	 * 			var item = $.treasurehunter.getElement();
	 * 			console.log(item.images);
	 */
	$.treasurehunter.getElement = function() {
		
		if($.treasurehunter.isFoundAll()) {
			return false;
		}
		var found = false,
			index,
			letters = $.treasurehunter.getData('letters'),
			item;
		
		while(found === false) {
			index = $.treasurehunter._random(0, letters.length - 1);
			item = letters[index];
			
			if(item.found === 0) {
				item.index = index;
				found = true;
				return item;
			}
		}
		
	};
	
	/**
	 * returns a random integer 
	 * 
	 * range is min <->max
	 * 
	 * @access 	private
	 * @param	integer		min value of the random number
	 * @param	integer		max value of the random number
	 * @return 	integer		random number
	 * @example
	 * 			var random = $.treasurehunter._random(0,10);
	 * 			console.log(random);
	 */
	$.treasurehunter._random = function(min, max) {
		if( min > max ) {
			return(-1);
		}
		if( min == max) {
			return(min);
		}
		
		return ( min + parseInt(Math.random() * ( max-min+1),10 ) );
	};
	/**
	 * set the value of the tntreasurehunter cookie
	 * 
	 *  - get the data out of the cookie
	 *  - decode the JSON string to javascript
	 *  - replace the key value with the new value
	 *  - encode to JSON and save back to the cookie
	 *  
	 * @param	String	key-name
	 * @param	String	key value
	 * @access 	public
	 * @return 	bool
	 * @example 
	 * 		 	$.treasurehunter.setData('pagecount', 1);
	 */
	$.treasurehunter.setData = function(name, value) {
		var data = $.cookie('tntreasurehunter');
		
		data = JSON.parse(data);
		
		data[name] = value;
		
		/**
		 * expires hard on 0 - $.cookie plugin handels the expire in days
		 * PHP in seconds. We dont want to have 60*60 days.
		 */
		$.cookie('tntreasurehunter', JSON.stringify(data),{
			expires: 0,
			path: $.treasurehunter.getData('cookiePath'),
			domain: $.treasurehunter.getData('cookieDomain')
		});
		return true;
	};
	/**
	 * get the JSON string out of the cookie and returns the value of the key
	 * 
	 * @param	String					key of the json object
	 * @return	String/Array/Object		returns the value of the key
	 * @access	public
	 * @example
	 * 		console.log($.treasurehunter.getData('letters'));
	 */
	$.treasurehunter.getData = function(name) {
		var data = $.cookie('tntreasurehunter');
		
		data = JSON.parse(data);
		
		return data[name];
	};
	
	
	
	$.treasurehunter.init();
		
};

})(jQuery);
