/*
 * Read.ru Showcase
 * Simple read.ru goods exposure
 * 
 * http://read.ru/partner/plugins/showcase/
 *
 * Copyright (c) 2010 Ayrat Yakupov
 *
 * Requires: jQuery v1.3+
 * Requires: Read.ru API library
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */

;(function($) {
	var defaults = {
		full_info: 1,
		cards_in_row: 3,
		limit_items: 2
	},
	self = this;
	this.defaults = defaults;
	this.card_callback = [];
	this.c_card_callback = [];
	this.options = {};
	
	this.init = function () {
		if (typeof this.api == 'undefined') {
			if (typeof rrApi != 'function') {
				alert('Error. No read.ru API connection found');
				return false;
			}
			this.api = new rrApi;
			this.defaults.pp = this.api.pp;
		}
		
		return true;
	}
	
	this.getSimpleCard = function (callback) {
		if (self.card) {
			callback(self.card);
		}
		else {
			
			var f = 'f_rr_simplecard';
			
			if (callback) {
				self.card_callback.push(callback);
			}
			
			if (typeof window[f] == 'undefined') {
				window[f] = function (html) {
					self.card = html;
					for (var i in self.card_callback) {
						var func = self.card_callback[i];
						func(html);
					}
				};
				
				self.api._jsonp(self.api.opts.path + 'simplecard.js'+(self.api.enc ? '?enc='+self.api.enc : ''));
			}
		}
	}
	
	this.getCustomCard = function (template, callback) {
		if (self.custom_card) {
			callback(self.custom_card);
		}
		else {
			if (callback) {
				self.c_card_callback.push(callback);
			}
			
			$.get(
				template,
				{},
				function (html) {
					self.custom_card = html;
					for (var i in self.c_card_callback) {
						var func = self.c_card_callback[i];
						func(html);
					}
				}
			);
		}
	}
	
	this.isEmpty = function isEmpty(obj){
		for(var i in obj){ return false;}
		return true;
	}

	$.extend($.fn, {
	
		rr_showcase: function(options, callback) {
			if (!self.init()) return this;
			
			var opts = {};
			
			$.extend(opts, self.defaults);
			$.extend(opts, options);
			options = opts;
			self.options = opts;
			$(this).data('rr_options', options);
			
			var cont = this;
			
			$(this).html("");
			
			var loaded = 0;
			var books = {};
			var check_loaded = function (obj) {
				if (typeof obj == 'object') {
					books = obj;
				}
				
				if (loaded) {
					$(cont).processBooks(cont, books, options.template);
					if (typeof callback == 'function') {
						callback();
					}
				}
				else {
					loaded += 1;
				}
			}
			
			if (typeof options.template != 'string') {
				self.getSimpleCard(check_loaded);
			}
			else {
				self.custom_card = null;
				self.getCustomCard(options.template, check_loaded);
			}
			self.api.getBooksList(options, check_loaded);
			
			return this;
		},
		
		rr_slider: function(options) {
			var cont = this;
			var c_options = options.carousel || {};
			
			var slide_callback = function(carousel) {
				carousel.buttonNext.bind('click', function() {
					carousel.startAuto(0);
				});

				carousel.buttonPrev.bind('click', function() {
					carousel.startAuto(0);
				});

				carousel.clip.hover(function() {
					carousel.stopAuto();
				}, function() {
					carousel.startAuto();
				});
			}
			
			$.extend(c_options, { scroll: 1, initCallback: slide_callback });
			
			var slide = function () {
				$(cont).jcarousel(c_options);
			}
			options.cards_in_row = 0;
			options.carousel = true;
			$(this).rr_showcase(options, slide);
		},
		
		processBooks: function (cont, obj, custom) {
			if ('errors' in obj) {
				$(this).placeErrors(obj.errors);
				return;
			}
			
			var card = null;
			var book = null;
			var k = 1;
			var pp = $(this).data('rr_options').pp;
			
			if ($(this).data('rr_options').carousel) {
				cont = $('<ul></ul>').addClass("jcarousel-list").appendTo(cont);
			}
			
			for (id in obj.books) {
				if (self.card && !custom) {
					card = $(self.card);
				}
				else if (self.custom_card) {
					card = $(self.custom_card);
				}
				else
					continue;
				
				book = obj.books[id];
				$("a.rr_card_name:first", card).html(book.name).attr("title", book.name).attr("href", "http://read.ru/id/"+id+"/?pp="+pp);
				if (book.img) {
					$("div.rr_card_cover:first", card).css("background-image", "url('http://read.ru/covers_rr/small/"+id+".jpg')");
				}
				$("div.rr_card_cover a:first", card).attr("href", "http://read.ru/id/"+id+"/?pp="+pp);
				$("span.rr_card_supply_date:first", card).html(book.supply_date_str);
				
				$(this).placeCardItems('genre', book.genre, card);
				$(this).placeCardItems('series', book.series, card);
				$(this).placeCardItems('pubhouse', book.pubhouse, card);
				$(this).placeCardItems('author', book.author, card);
				
				$("span.rr_card_price_value:first", card).html(book.price);
				$("div.rr_card_add_book a:first", card).attr("title", book.name).attr("href", "http://read.ru/id/"+id+"/?pp="+pp);
				
				if ($(this).data('rr_options').carousel) {
					$('<li></li>').addClass("jcarousel-item-"+k).append(card).appendTo(cont);
				}
				else {
					card.appendTo(cont);
				}
				
				if (!(k % $(this).data('rr_options').cards_in_row) && $(this).data('rr_options').cards_in_row) {
					$('<br />').attr("clear", "all").appendTo(cont);
				}
				k++;
			}
			
			$('<br />').attr("clear", "all").appendTo(cont);
		},
		
		placeCardItems: function(url, obj, card) {
			var item = null;
			var k = 0;
			
			if (!self.isEmpty(obj)) {
				item = $("span.rr_card_"+url+":first", card);
				for (i_id in obj) {
					if ($(this).data('rr_options').limit_items && k == $(this).data('rr_options').limit_items) {
						item.append(" ...");
						break;
					}
					else {
						if (k) item.append(", ");
						k++;
					}
					$('<a></a>').html(obj[i_id]).attr("target", "_blank").attr("href", "http://read.ru/"+url+"/"+i_id+"/?pp="+$(this).data('rr_options').pp).appendTo(item);
				}
			}
			else {
				$("div.rr_card_"+url+"_cont:first", card).css("display", "none");
			}
		},
		
		placeErrors: function (errors) {
			jQuery.each(errors, function () {
				alert(this);
			});
		}
	});
	
})(jQuery);
