/**

*******************
* Amiado Shop API *
*******************

Get and display the Game of the week from Playbay

@author: Sebastien Roch
@version: 04.2010

=========================================================

HOW-TO
=======

- 	Embedd this file in your page as javascript

-	Overwrite the default widget constructor for your site (comes AFTER embedding this file in page)
	The data you need is in the second argument, data. This is the keys to use in the template:
	data.Game.title
	data.Game.description
	data.thumburl['40x40']
	data.thumburl['60x60']
	data.thumburl['90x90']
	data.Game.target_url
	
	Example:	

	<script type="text/javascript">
		PlaybayAPI.widgetConstructor = function(containerId, data){
			var code = "<div>Widget succesfully overwritten!<br />This is the title for the game of the week: " + data.Game.title + "</div>"
			document.getElementById(containerId).innerHTML = code; // <-- set finally the code for your container (don't change)
		};
	</script>

-	Use the function getGameOfTheWeek in your HTML page to get the game and display it:
	
	<script type="text/javascript">
		PlaybayAPI.getGameOfTheWeek([containerId]);
	</script>
	
	The widget will take place where you called the getOffer function, but you can also
	call the function from where you want and specify the container id as first argument.
	
	Example: PlaybayAPI.getOffer();
	Example: PlaybayAPI.getOffer('my_widget_container');
	
-	Options
	You can overwrite the target_url by writing: 
	PlaybayAPI.target_url = 'http://www.example.com';
	
*/
	var PlaybayAPI = {
		
		API_URL: 'http://www.playbay.net/de/api/',
		
		GA_DATA: {
			'utmac': 'UA-111341-17',
			'utmwv': '4.3'
		},
		
		SITE: window.location.hostname.match(/[^.]+\.[^.]+$/)[0].replace('www.', ''),
		
		result: null,
		
		target_url: null,
		
		/*
		Cross-domain ajax calls through <script> tag
		*/
		cdajax: function(url, callback){
			request_script = document.createElement("script");
			request_script.type = 'text/javascript';
   			request_script.src = url;
   			// FF
   			request_script.onload = function(){
   				document.getElementsByTagName("head")[0].removeChild(request_script);
   				callback();
   			};
   			// IE
   			request_script.onreadystatechange = function(){
   				if (request_script.readyState == 'loaded'  || request_script.readyState == 'complete'){
   					document.getElementsByTagName("head")[0].removeChild(request_script);
   					callback();
   				}
   			};
   			document.getElementsByTagName("head")[0].appendChild(request_script);
		},
		
		// the main used function, with container and optional option object
		getGameOfTheWeek: function(containerId){
			if(typeof containerId == "undefined" || containerId == null){
				containerId = "game_container_" + Math.round(Math.random()*1000);
				document.write("<div id='" + containerId + "'></div>");
			}
			PlaybayAPI.containerId = containerId;
			
			if(document.getElementById(containerId)){
				PlaybayAPI._getGameOfTheWeek(containerId);
			} else{
				window.setTimeout(function(){PlaybayAPI._getGameOfTheWeek(containerId)}, 3000);
			}
		},
		
		_getGameOfTheWeek: function(containerId){
			var url = PlaybayAPI.API_URL + 'gameoftheweek/?site=' + PlaybayAPI.SITE;
			
   			onloadFct = function(){
   				if(typeof PlaybayAPI_last_result != 'undefined'){
   					PlaybayAPI.result = PlaybayAPI_last_result;
   					if(PlaybayAPI.result != null && typeof PlaybayAPI.result == 'object'){
   						if(PlaybayAPI.target_url != null){
   							url = PlaybayAPI.target_url;
   						}
   						PlaybayAPI.widgetConstructor(containerId, PlaybayAPI.result);
   						PlaybayAPI.statLog('impressions');
   						PlaybayAPI.initOrderLinks(containerId, PlaybayAPI.result);
   					}
   				}
   			};
   			PlaybayAPI.cdajax(url, onloadFct);
		},
		
		// called after widget constructor
		// Adds onclick event on each link to game, for statistics
		initOrderLinks: function(containerId, data){
			if(document.getElementById(containerId)){
				var elems = document.getElementById(containerId).getElementsByTagName('a');
				for(var i=0; i< elems.length; i++){
					var link = elems[i];
					/*if(link.getAttribute('href') == data.url){*/
						if(link.addEventListener)
							link.addEventListener('click', function(){PlaybayAPI.statLog('clicks')}, false); 
						else if(link.attachEvent)
							link.attachEvent('onclick', function(){PlaybayAPI.statLog('clicks')}); 
					//}
				}
			}
		},
		
		/* Google Analytics for statistics */
		statLog: function(mode) {
			var referer = encodeURIComponent(window.location.protocol + '//' + window.location.host + window.location.pathname);
			var utmn = Math.round(Math.random()*100000000);
			var utmhn = window.location.hostname;
			var utmp = encodeURIComponent(mode + '/' + PlaybayAPI.result.Game.id + '_' + PlaybayAPI.result.Game.title + '/' + PlaybayAPI.SITE);
			var cookieNr = Math.round(Math.random()*100000000);
			var rand = Math.round(Math.random()*100000000);
			var today = new Date().getTime();
			var uservar = '-';
			
			var url = 'http://www.google-analytics.com/__utm.gif?utmwv=' + PlaybayAPI.GA_DATA.utmwv + 
				'&utmn=' + utmn + '&utmsr=-&utmsc=-&utmul=-&utmje=0&utmfl=-&utmdt=-&utmhn=' + 
				utmhn + '&utmr=' + referer + '&utmp=' + utmp + '&utmac=' + PlaybayAPI.GA_DATA.utmac + 
				'&utmcc=__utma%3D' + cookieNr + '.' + rand + '.' + today + '.' + today + '.' + today + 
				'.2%3B%2B__utmb%3D' + cookieNr + '%3B%2B__utmc%3D' + cookieNr + '%3B%2B__utmz%3D' + cookieNr + 
				'.' + today + '.2.2.utmccn%3D(direct)%7Cutmcsr%3D(direct)%7Cutmcmd%3D(none)%3B%2B__utmv%3D' + 
				cookieNr + '.' + uservar + '%3B';
			
			var img = new Image();
			img.src = url;
			img.style.display = 'none';
			document.getElementById(PlaybayAPI.containerId).appendChild(img);
		},
		
		// default constructor for the widget
		widgetConstructor: function(containerId, data){
			var html = 	"<div style='font-family:Helvetica; width:160px; border:1px solid #888;'>";
			html += 		"<div style='color:#888; font-size: 12px; font-weight:bold; text-align:center; border-bottom:1px solid #888; background:#EEE'>GAME OF THE WEEK</div>";
			html +=			"<div style='padding:5px; margin:auto; overflow:hidden; font-size:11px'>";
			html +=				"<div style='color:#666; font-size: 13px; font-weight:bold; margin-bottom:4px'>" + data.Game.title + "</div>";
			html +=				"<div style='float:left'>";
			html += 				"<a href='" + '' + "' target='_blank'><img style='margin-right:5px; margin-bottom:5px; border: 1px solid #BBB; padding:1px' src='"+ data.Game.thumburl['60x60'] + "' /></a><br />";
			html += 			"</div>";
			html +=				data.Game.description;
			html +=				"<table style='clear:both; margin-top:5px; border:none; border-collapse:collapse; width:100%' border='0'>";
			html +=					"<tr>";
			html +=						"<td style='border:none'>";
			html +=							"<div style='background:#EEE; padding:4px 6px; color:#0991CA; cursor:pointer'>";
			html +=								"<a style='font-weight:bold; text-decoration: none' target='_blank' href='" + data.Game.target_url + "'>Play it now!</a>";
			html +=							"</div>";
			html +=						"</td>";
			html +=					"</tr>";
			html +=				"</table>";
			html +=			"</div>";
			html +=		"</div>";
			
			document.getElementById(containerId).innerHTML = html;
		}
	};
