/**
 * DynamicCart class
 *
 * [2007-10-01 js] created
 *
 * $Rev: 480 $ Revision of last commit
 * $Author: jan $ Author of last commit
 * $Date: 2008-09-26 08:30:09 +0200 (Fr, 26 Sep 2008) $ Date of last commit
 */

var DynamicCart = function() {

	var
		// the cart button object (initiated with jquery)
		button,

		// the item shop list object (initiated with jquery)
		list,

		// positions for the cart itself and its list
		cartFixedPosition = { x: 0,	y: 0 },
		listFixedPosition = {	x: 0,	y: 0 },

		// possibility to see the fixed cart in preview mode.
		// Added, because of placing the cart easier.
		preview = new Boolean(false),

		// state can be "default" or "fixed"
		state = "default",

		// further settings (defaults)
		options = {
			opacity: 0.85,
			automaticClose: 4000
		},

		// used for detecting refresh(F5)
		firstLoadDone = new Boolean(false),

		// timer
		timer = null;

	function update(url, obj, callback) {

		// take care of this =)
		var self = this;

		// count items before updating cart
		var count_items_before_upd = this.countItems();

		// reset timer actions, to let the cart open due manipulating
		// the cart content
		if (timer)
			clearTimeout(timer);

	  $.ajax({
		  type: "POST",
		  url: url,
		  dataType: "json",
	    data: obj,
		  success: function(data) {

		  	// when message occurs
		  	if (data.message && data.message.length > 0) {

		  		alert(data.message);
		  	}

        // changing cart images
    		if (data.image.src) {

    			// images
	        $("img.pid-"+obj.product_id+"-"+obj.variation_id).each(function(i) {

	        	$(this).attr("src", data.image.src);
	        	$(this).attr("title", data.image.title);
	        });

	        // buttons
	        $("div.pid-"+obj.product_id+"-"+obj.variation_id).each(function(i) {

	        	$(this).text(data.image.title);
	        });
	  		}

	  		// generell cart results
	  		if (data.cart) {

		  		// update cart items in the dynamic cart
		  		$(".cart-item-list").html(data.cart.items);

	        // update the count cart items in the header
	        $("#count_cart_items").text(data.cart.countItems);

	        // update cart price in the header
	        $("#cart_price").text(data.cart.price);
	  		}

	    	// check if cart is open or not
				if (!self.listIsClosed()) {

					// reintialize scroll (need for resize)
					$(".cart-item-list").jScrollPane({
						showArrows:	true,
						// added feature: forceScroll
						// 1. It shows the jscrollPane always.
						// 2. When no scrolling is possible, a deactivated CSS style(.deactivatedjScrollPaneDrag) will be added.
						forceScroll: true
					});

					// close cart when no items are in
					if (!data.cart.countItems) {

						self.closeList(function() {

							// callback: when the cart list has been closed
							self.checkPosition();
						});
					}
				}

				// a new items has been added
				if ( (data.cart.countItems-count_items_before_upd) > 0 && firstLoadDone == true) {

					self.openList(function() {

						// close automatically timer
						timer = setTimeout(function() {

							self.closeList();
						}, options.automaticClose);
					});
				}

				// check cart position when cart has been filled
				if (data.cart.countItems) {

					self.checkPosition();
				}

		  	// callback after update execution
		  	if (typeof callback == "function") {

		  		callback.call(document);
		  	}

		  	firstLoadDone = true;
			},
		  error: function (data) {

		  	alert("__ERROR__\n\n" + data.responseText);
		  }
		});
	}

	return {

		init: function(settings) {

			// extending options
			options = $.extend({}, options, settings);

			// init for CO/CPS the cart button
			button = $(".navi-cart, .cps_cart");

			// init the generally named cart item list
			list = $(".cart-item-box");
		},
		update: function(url, obj, callback) {

			update.apply(this, arguments);
		},
		openList: function(callback) {

    	list.show();

    	// initialize scroll
  		$(".cart-item-list").jScrollPane({
				showArrows:	true,
				forceScroll: true
			});

			// slide down
    	list.animate({height: 228}, 400, "swing", function() {

		  	if (typeof callback == "function") {

		  		callback.call(document);
		  	}
    	});

    	// reset timer actions
    	if (timer)
    		clearTimeout(timer);

		},
		closeList: function(callback) {

			// slide up
      list.animate({height: 0}, 400, "swing", function() {

      	list.hide();

		  	if (typeof callback == "function") {

		  		callback.call(document);
		  	}
      });

    	// reset timer actions
    	if (timer)
    		clearTimeout(timer);
		},
		listIsClosed: function() {

			return list.is(":hidden");
		},
		setCartFixedPosition: function(x, y) {

			cartFixedPosition.x = x;
			cartFixedPosition.y = y;
		},
		setListFixedPosition: function(x, y) {

			listFixedPosition.x = x;
			listFixedPosition.y = y;
		},
		getCartFixedPosition: function() {

			return cartFixedPosition;
		},
		getListFixedPosition: function() {

			return listFixedPosition;
		},
		checkList: function() {

			if (!this.countItems())
				return false;

			return this.listIsClosed()
		},
		countItems: function() {

			return $(".cart-item-list div.cart-item").length;
		},
		setState: function(currentState) {

			state = currentState;

			// go for animation
			this.animate();
		},
		getState: function() {

			return state;
		},
		setPreview: function(state) {

			preview = state;

			if(preview) {

				this.setState("fixed");
			}
		},
		animate: function() {

			var listIsClosed = this.listIsClosed();

			switch(state) {

				case "fixed":

					button.hide();

					// set fixed attributes
					button.addClass("cart-fixed").css({"opacity": options.opacity});
					list.addClass("cart-fixed").css({"opacity": options.opacity});

					// change button design
					button.removeClass("btn-white-medium");
					button.addClass("btn-white-black-border-medium");

					// position for the cart button (belongs to button object)
					$(".cart-position").css("left", cartFixedPosition.x);
					$(".cart-position").css("top", cartFixedPosition.y);

					// position for the cart list (belongs to list object)
					$(".cart-list-position").css("left", listFixedPosition.x);
					$(".cart-list-position").css("top", listFixedPosition.y);

					if (listIsClosed)
						button.css({"opacity":0}).show().fadeTo("slow", options.opacity);
					else
						button.show();

				break;
				default:

					button.stop(); // stops the animation
					button.hide();

					// remove fixed attributes
					button.removeClass("cart-fixed").css({"opacity": ""});
					list.removeClass("cart-fixed").css({"opacity": ""});

					button.removeClass("btn-white-black-border-medium");
					button.addClass("btn-white-medium");

					$(".cart-position").css("left", 0);
					$(".cart-position").css("top", 0);

					$(".cart-list-position").css("left", 0);
					$(".cart-list-position").css("top", 25);

					button.show();

				break;
			}
		},
		checkPosition: function() {

			// check position only when preview is deactivated
			if (!preview) {

				// only when items are in the cart
			  if (this.countItems() > 0) {

					// cart is out of sight
					if ($(window).scrollTop() > parseInt($(".cart").offset().top + button.height() + 35) ) {

						if (state != "fixed") {

				  		this.setState("fixed");
						}

					} else {

						this.setState(false);
					}
			  } else {

			  	this.setState(false);
			  }
			}
		}
	}
};