var Config = {
	wallpapersURL: 'http://www.animebox.eu/wallpapers/webappJSONConnection.php?mode=dynamic&g2_view=dynamicalbum.UpdatesAlbum',
	reviewsURL: 'http://www.animebox.eu/reviews/atom.xml',
	maxReviews: 4,
	maxWallpapers: 16
}


var COMM = (function(){

	var _getWalls = function (callback) {
		new Ajax.Request(Config.wallpapersURL, {
			onComplete: _parseWallpapers
		});
	};
	
	var _getReviews = function (callback) {
		new Ajax.Request(Config.reviewsURL, {
			onComplete: _parseReviews
		});
	};
	
	var _parseReviews = function (response) {
		var entries = $A(response.responseXML.getElementsByTagName('entry')), parsedData = [];
		entries.each(function(entry, i){
			parsedData.push({
				title: entry.getElementsByTagName('title')[0].firstChild.nodeValue,
				image: entry.getElementsByTagName('coverart')[0].firstChild.nodeValue,
				author: entry.getElementsByTagName('name')[0].firstChild.nodeValue,
				link: entry.getElementsByTagName('link')[0].attributes.href.nodeValue
			});
			if (i >= (Config.maxReviews - 1)) {
				throw $break;
			}
		});		
		Interface.addReviews(parsedData);
	};
	
	var _parseWallpapers = function (response) {
		window.Interface.addWallpapers(response.responseText.evalJSON().list);
	};
	
	var getData = function () {
		_getWalls();
		_getReviews();
	}
	
	return {getData: getData};
})();

var Interface = (function () {
	var _reviewHTML = new Template('<div><h2><a href="#{link}">#{title}</a></h2><h3>by <strong>#{author}</strong></h3><p><a href="#{link}"><img class="artwork" src="#{image}" /></a></p></div>');
	
	var addReviews = function (revData) {
		$('revs').down('.spinner').remove();
		revData.each(function(review){
			$('revs').insert(_reviewHTML.evaluate(review));
		});
		Images.checkAndResize();
	}
	
	var _wallpaperHTML = new Template('<div class="wallpaper"><a class="thumb" href="#{link}"><img class="thumb" src="#{thumbUrl}" /></a></div>');

	var addWallpapers = function (wallData)  {
		$('walls').down('.spinner').remove();
		wallData.each(function(wallpaper, i){
			$('walls').insert(_wallpaperHTML.evaluate(wallpaper));
			if (i >= (Config.maxWallpapers - 1)) {
				throw $break;
			}
		});
	}
	
	var prepare = function () {
		$(document.body).update('<div id="logo"></div><div id="main"><div id="revs"><h1>Latest <a href="/reviews">reviews</a></h1><img class="spinner" src="/assets/img/spinner.gif" /></div><div id="walls"><h1>Latest <a href="/wallpapers">wallpapers</a></h1><img class="spinner" src="/assets/img/spinner.gif" /></div></div>');
	};
	
	return {
		prepare: prepare,
		addWallpapers: addWallpapers,
		addReviews: addReviews
	};
})();

Math.nearest = function (a, b, c) {
   //returns the nearest to a of b and c
   if ( Math.abs(a - b) > Math.abs(a - c) ) {
      return c;
   } else {
      return b;
   }
};


var Layout = {
   baseline: 24,
   containerSelector: 'div#revs',
   containerWidth: 0,
   setContainerWidth: function () {
      Layout.containerWidth = $('alpha-inner').getWidth();
   },
   maxImageWidth: 286
};


var Images = (function (){

   var resize = function (img, isLandscape) {
      var newWidth;
      if (!isLandscape | img.match('img.artwork')) {
         if (img.getWidth() > Layout.maxImageWidth) {
            newWidth = Layout.maxImageWidth;
         } else {
            newWidth = Math.nearest(img.getWidth(), Math.floor(img.getWidth() / Layout.baseline) * Layout.baseline,  Math.ceil(img.getWidth() / Layout.baseline) * Layout.baseline);
         }
      } else {
         if (img.getWidth() > Layout.containerWidth) {
            newWidth = Layout.containerWidth - Layout.baseline * 2;
         } else {
            newWidth = Math.nearest(img.getWidth(), Math.floor(img.getWidth() / Layout.baseline) * Layout.baseline,  Math.ceil(img.getWidth() / Layout.baseline) * Layout.baseline);
         }
      }
      var height = Math.floor(newWidth / img.getWidth() * img.getHeight());
      var newHeight = Math.nearest(height, Math.floor(height / Layout.baseline) * Layout.baseline, Math.ceil(height / Layout.baseline) * Layout.baseline);
      img.setStyle({
         width:  newWidth + 'px',
                  height: newHeight + 'px'
      });
   };

   var center = function (img) {
      img.setStyle({
         display: 'block',
                   marginTop: '0',
                   marginBottom: '0',
                   marginLeft: 'auto',
                   marginRight: 'auto'
      });
   };

   var align = function (img, side) {
      img.setStyle({
         display: 'block',
         float: side,
         marginTop: '0',
         marginRight: side === 'left'? Layout.baseline + 'px' : '0',
         marginBottom: Layout.baseline + 'px',
         marginLeft: side === 'right' ? Layout.baseline + 'px' : '0'
      });
   };

   var isLandscape = function (img) {
      if (img.getWidth() > img.getHeight()) {
         return true;
      } else {
         return false;
      }
   };

   return {
      checkAndResize: function () {
         var helper = function (img) {
            if (isLandscape(img) && !img.match('img.artwork')) {
               center(img);
               resize(img, true);
            } else {
               align(img, 'left');
               resize(img, false);
            }
         };
         $$(Layout.containerSelector + ' img').each(function (img) {
            if (!img.match('ul.ratings img') && !img.match('.user-pic img') && !img.match('img.icon')) {
               if (img.complete) { helper(img); }
               else { img.onload = helper.bind(window, img); }
            }
         });
      }
   };

})();


var startup = function () {
	Interface.prepare();
	COMM.getData();
}

document.observe('dom:loaded', startup);