/**

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

Get and display the Amiado widget with a partner product

@author: Sebastien Roch
@version: 06.2009

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

HOW-TO
=======

- 	Embedd this file in your page:
	<script src="amiado_shop_api.js" type="text/javascript"></script>

-	Overwrite the default widget constructor for your site (comes AFTER embedding this file in page)
	The data you need is in the second argument (offerdata)
	Example:	

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

-	Use function getOffer in your HTML page to get the offer of the day:
	
	<script type="text/javascript">
		AmiadoShopAPI.getOffer([containerId, options]);
	</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.
	
	Second argument is also an optionnal object and accept following parameters:
	- imagewidth : int
	- imageheight : int
	These are the prioroty rules if you provide both imagewidth and imageheight:
	- if the picture is more wide than high, imagewidth has priority
	- if the picture is more high than wide, imageheight has priority
	
	Example: AmiadoShopAPI.getOffer();
	Example: AmiadoShopAPI.getOffer(null, {"imagewidth":150});
	Example: AmiadoShopAPI.getOffer('my_widget_container', {"imagewidth":150});
	
*/
	var AmiadoShopAPI = {
		
		API_URL: 'http://shop.amiadogroup.com/api/',
		
		GA_DATA: {
			'utmac': 'UA-111341-15',
			'utmwv': '4.3'
		},
		
		SITE: window.location.hostname.match(/[^.]+\.[^.]+$/)[0].replace('www.', ''),
		
		ajax_request: null,
		
		result: 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
		getOffer: function(containerId, options){
			if(typeof containerId == "undefined" || containerId == null){
				containerId = "amiado_shop_container_" + Math.round(Math.random()*1000);
				document.write("<div id='" + containerId + "'></div>");
			}
			AmiadoShopAPI.containerId = containerId;
			
			if(document.getElementById(containerId)){
				AmiadoShopAPI._getOffer(containerId, options);
			} else{
				window.setTimeout(function(){AmiadoShopAPI._getOffer(containerId, options)}, 3000);
			}
		},
		
		_getOffer: function(containerId, options){
			var url = AmiadoShopAPI.API_URL + 'getoffer/?site=' + AmiadoShopAPI.SITE;
			if(typeof options != "undefined"){
				if(typeof options.imagewidth != "undefined")
					url += '&imagewidth=' + options.imagewidth;
				if(typeof options.imageheight != "undefined")
					url += '&imageheight=' + options.imageheight;
			}

   			onloadFct = function(){
   				if(typeof AmiadoShopAPI_last_result != 'undefined'){
   					AmiadoShopAPI.result = AmiadoShopAPI_last_result;
   					if(AmiadoShopAPI.result != null && typeof AmiadoShopAPI.result.today == 'object'){
   						AmiadoShopAPI.widgetConstructor(containerId, AmiadoShopAPI.result.today);
   						AmiadoShopAPI.statLog('impressions');
   						AmiadoShopAPI.initOrderLinks(containerId, AmiadoShopAPI.result.today);
   					}
   				}
   			};
   			AmiadoShopAPI.cdajax(url, onloadFct);
		},
		
		// called after widget constructor
		// Adds onclick event on each link to article, for statistics
		initOrderLinks: function(containerId, offerdata){
			if(document.getElementById(containerId)){
				//var elems = document.getElementById(containerId).getElementsBySelector('[href="' + offerdata.url + '"]');
				var elems = document.getElementById(containerId).getElementsByTagName('a');
				for(var i=0; i< elems.length; i++){
					var link = elems[i];
					if(link.getAttribute('href') == offerdata.url){
						if(link.addEventListener)
							link.addEventListener('click', function(){AmiadoShopAPI.statLog('clicks')}, false); 
						else if(link.attachEvent)
							link.attachEvent('onclick', function(){AmiadoShopAPI.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 + '/' + AmiadoShopAPI.result.today.id + '_' + AmiadoShopAPI.result.today.title + '/' + AmiadoShopAPI.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=' + AmiadoShopAPI.GA_DATA.utmwv + 
				'&utmn=' + utmn + '&utmsr=-&utmsc=-&utmul=-&utmje=0&utmfl=-&utmdt=-&utmhn=' + 
				utmhn + '&utmr=' + referer + '&utmp=' + utmp + '&utmac=' + AmiadoShopAPI.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(AmiadoShopAPI.containerId).appendChild(img);
		},
		
		// default constructor for the widget
		widgetConstructor: function(containerId, offerdata){
			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'>OFFER OF THE DAY</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'>" + offerdata.title + "</div>";
			html +=				"<div style='float:left'>";
			html += 				"<a href='" + offerdata.url + "' target='_blank'><img style='margin-right:5px; margin-bottom:5px; border: 1px solid #BBB; padding:1px' src='"+ offerdata.picturepath + "' /></a><br />";
			html += 			"</div>";
			html +=				offerdata.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 +=							"<span style='color:black; font-size:10px'>statt " + offerdata.originalprice + "</span><br />";
			html +=							"<span style='color:red; font-weight:bold; font-size:12px'>CHF " + offerdata.price + "</span>";
			html +=						"</td>";
			html +=						"<td style='border:none'>";
			html +=							"<div style='background:#EEE; padding:4px 6px; color:#0991CA; cursor:pointer'>";
			html +=								"<a style='font-weight:bold' target='_blank' href='" + offerdata.url + "'>&gt;&gt; Bestellen!</a>";
			html +=							"</div>";
			html +=						"</td>";
			html +=					"</tr>";
			html +=				"</table>";
			html +=			"</div>";
			html +=		"</div>";
			
			document.getElementById(containerId).innerHTML = html;
		}
	};