argos.require("utils");
argos.require("effects.autoscroll");
argos.require("widgets.Carousel");



argos.promotions = new (function() {
	// PUBLIC METHODS
	this.init = function() {
	};

	// PRIVATE METHODS

});


/**********************************************************

	Create a promotions carousel.
	Based on PDP requirements to extract promotions from 
	list and create condensed promotions carousel.

*********************************************************/
argos.promotions.carousel = new(function() {
	this.init = function(promotions, container) {
		if(promotions.length > 1 && container.length > 0) {
			_setUpPromotionCarousel(promotions, container);

			argos.promotions.omniture.pdp.carousel.init();
		}
	}

	function _setUpPromotionCarousel(promotions, container) {
		var title = container.find("h2");

		if(promotions.length > 1) {
			container.find(".offerTotal").remove();
			container.find(".promotion").remove();
			container.find(".promotion").remove();
			container.parent().removeClass("static");

			promotions.each(function() {
				var t = $(this);
				var promotion = $("<div class=\"promotion\"></div>");
				var button = $("<a title=\"Click here for full offer details\" class=\"button fullDetails\" href=\"#" + t.attr("id") + "\"><span>Full details</span></a>");
				var content = t.children().clone();
				var desc = _getShortDescription(t);

				button.click(function() {
					argos.effects.autoscroll.activate($(this).attr("href"));
					return false;
				});

				content.filter(".description").html(desc);
				promotion.append(content).append(button);
				container.append(promotion);

			});

			carousel = new argos.widgets.Carousel(container.find(".promotion"), {
				"leftOffset" : 50,
				"step" : 1,
				"titleTextNext" : "Next offer",
				"titleTextPrevious" : "Previous offer"
			});

		}
 
		container.find(".controller").parent().after(title); // Allow z-index:auto to work.

		if(promotions.length == 1) {
			title.text(title.text().replace(/s$/i,""));
		}
	}

	function _getShortDescription(promo) {
		var contents = promo.contents();
		var shortDescription = "";
		var i = 0;
		do {
			if(contents.get(i).nodeType == 8) {
				try {
					// Decent browsers...
					shortDescription = contents.get(i).nodeValue;
				}
				catch(e) {
					// And something else for IE...
					shortDescription = contents.get(i).innerHTML.replace(/<!--(shortDescription:)(.*)-->/, "$1$2");
				}
				
				if(shortDescription.indexOf("shortDescription:") >= 0) {
					shortDescription = contents.get(i).nodeValue.replace(/shortDescription:(.*)/, "$1"); 
					break; // Found it so get out of here.
				}
				else {
					// We didn't find it so reset shortDescription.
					shortDescription = "";
				}
			}
		} while(++i < contents.length);

		return shortDescription;
	}
});



/***************************************************

	Lister pages

***************************************************/
argos.promotions.lister = new (function() {
	var _openClass = "open";
	var _closeClass = "close";

	// PUBLIC METHODS

	this.init = function(activateOnThesePages) {
		// Check list of passed pages to see if should activate.
		var activate = false;
		for(var i=0; i<activateOnThesePages.length; i++) {
			if(document.body.className.indexOf(activateOnThesePages[i]) >= 0) {
				activate = true;
				break;
			}
		}
		if(activate) {
			_setUpPromos();
			argos.promotions.omniture.lister.init();
		}
	};

	// PRIVATE METHODS

	function _setUpPromos() {
		// Convert all promos in current layout and state if they need expandable functionality
		$(".promotions .container").each(function() {
			var t = $(this);
			var offers = t.find("li");
			if(offers.length > 1) {
				t.addClass(_openClass);
				offers.removeClass("jsOnly");
				_makeSpansActLikeLinks(t, $("span", offers));
				_makeExpandable(t, offers);
			}
		});
	}

	function _makeSpansActLikeLinks(container, spans) {
		// Non-JS doesn't want links in offers. Neither does a closed promotions expander.
		// An open promotions expander does, so make spans work like links when the container is open.
		var productUrl = container.parent().siblings(".producttitle").find("a").attr("href");

		spans.each(function(i) {
			var t = $(this);
			var href = productUrl + "#promotion_" + (i + 1) + "..."; // Add the fragment identifier with autoscroll tag (...)

			t.click(function() {
				if(container.hasClass(_openClass)) {
					window.location.href = href;
				}
			});

			t.mouseover(function() {
				if(container.hasClass(_openClass)) {
					window.status = href;
				}
			})

			t.mouseout(function() {
				window.status = "";
			});
		});
	}

	function _makeExpandable(container, offers) {
		var button = container.find(".button");
		var openMeText = button.text();

		button.click(function() {
			var closeMeText = "Hide offers";
			if(container.hasClass(_openClass)){
				_expandOrClose(container, 318, offers, "close");
				$(this).html(openMeText);
			}
			else {
				_expandOrClose(container, 434, offers, "open");
				$(this).html(closeMeText);
			}
			return false;
		});

		_expandOrClose(container, 318, offers, "close");
	}

	function _expandOrClose(el, width, items, action) {
		var time = 1000;
		var height = 0;
		var list = el.find("ul"); 
		switch(action) {
			case "open" :
				items.each(function() {
					height += $(this).height();
				});
				el.removeClass(_closeClass);
				el.addClass(_openClass);
				break;
			default :
				height = (list.data("height")) ? list.data("height") : (function() { list.data("height", items.eq(0).height()); return list.data("height"); })();
				el.removeClass(_openClass);
				el.addClass(_closeClass);
		}
		el.animate({"width": width + "px"}, time);
		list.animate({"height": height}, time, function() { 
			_postExpandOrClose(list); 
		});
	}

	function _postExpandOrClose(el) {
		// After animation stuff (currently only used by IE6 for bug corrections).
	}


	//======= argos.promotions.lister IE fixes =====================================
	// Throw in any fixes for IE6 bugs (note: safe to delete this code when dropping support for IE versions).
	if(jQuery.browser.msie && Math.floor(jQuery.browser.version) <= 6) {
		var _postExpandOrClose = function(el) {
			if(el.height() % 2 != 0) el.css("height", el.height() - 1); 
		}

		var _standardSetUpPromos = _setUpPromos;
		_setUpPromos = function() {
			_standardSetUpPromos();
			$(".promotions button, .promotions span").mouseover(function() {
				$(this).addClass("hover");
			}).mouseout(function() {
				$(this).removeClass("hover");
			});
		}
	}
	//= END = argos.promotions.lister IE fixes =====================================

});



/***************************************************

	Special Offer Display (offer details page)
	 * Language...
	 * product - a product which can go into a slot
	 * slot - a position a product can fill
	 * slotProduct - a product which is already in a slot

***************************************************/
argos.promotions.odp = new (function() {
	var _module = this;
	var _promotion;
	var _configArea;
	var _infoArea;
	var _productGroups;
	var _originalPrice;
	var _maxHeight = argos.utils.getMaxHeight;
	var _height = argos.utils.height;
	
	this.priceUpdateAvailable = false;
	this.autoPopulateFromProduct = false;

	// PUBLIC METHODS
	this.init = function (activateOnThesePages) {
		// Check list of passed pages to see if should activate.
		var activate = false;
		for(var i=0; i<activateOnThesePages.length; i++) 
		{
			if(document.body.className.indexOf(activateOnThesePages[i]) >= 0) {
				activate = true;
				break;
			}
		}
		
		if(activate)
		{
			_promotion = $(".promotion");
			_productSelectors = $(".product_selector");
			_configArea = $("#odpConfiguration");
			_infoArea = $("#odpInformation");
			_productGroups = $(".productGroup", _configArea);
			_originalPrice = $(".offerPrice", _infoArea).html()

			_setUpInstantJSChanges();
			_setUpProductButtons();
			_setUpFromProductChanges();

			if(!jQuery.browser.mozilla && !jQuery.browser.msie && !jQuery.browser.opera) {
				// For some reason WebKit only wants to add inserted buttons (see _setUpProductButtons) after
				// the odp.init function has finished. Add the delay so it exits the function and we see 
				// the buttons appear. The following carousel will then have the correct height. Not good but works. 
				// Also not using jQuery 1.4+ so cannot use browser.webkit. 			
				window.setTimeout(_finishInit, 1000);
			}
			else {
				_finishInit();
			}
		}
	};

	
	/**
	 * PRIVATE METHODS
	 */

	function _finishInit() {
		// Hack/workaround to prevent incorrect height issue in Webkit browsers.
		_setUpProductGroups();
		_setUpSlots();
		_sortSlots();
		_selectFirstSuitableSlot();
		argos.promotions.omniture.odp.init();
	}	
	
	function _setUpInstantJSChanges() {
		_configArea.removeClass("javascriptOff");
		_infoArea.removeClass("javascriptOff");

		// swap outOfStock and Quick view order for desired layout.
		$(".product .actions").each(function() {
			var t = $(this);
			t.after(t.prev(".availability"));
		});
	}

	function _setUpSlots() {
		$(".product_selector").each(function(i) {
			var el = $(this);

			// Add product selector choose button events to switch between product groups.
			el.find("a.choose").click(function() {
				_toggleProductGroupView($(this).attr("href"));
				return false;
			});
		});
	}

	function _setUpFromProductChanges() {
		var partNumber = window.location.href.indexOf("fromProduct") >= 0 ? window.location.href.replace(/.*fromProduct\/(\d*)\/.*/,"$1") : "";
		var pdpHref, fromProduct;

		if(partNumber != "") {
			// Set up back button to fromProduct part number.
			pdpHref = "/static/Product/partNumber/" + partNumber + ".htm";
			$("#odpInformation .promotion").after("<a href=\"" + pdpHref + "\" class=\"backToProduct\"><span>Back to product</span></a>");

			// Get the fromProduct using part number.
			fromProduct = $(".productGroup .product .number:contains(" + partNumber.replace(/(\d{3})(\d{4})/,"$1/$2") + ")").parent();

			// If SPO and from product found, shift it to be first in list/carousel. 
			if(fromProduct.length > 0 && _isSpoPromotion()) {
				fromProduct.siblings(".instruction").after(fromProduct);
			}

			// Use fromProduct to prepopulate the first product selctor.	
			if(_module.autoPopulateFromProduct && ! _isSpoPromotion() && fromProduct.length > 0 && ! _isProductOutOfStock(fromProduct)) {
				// select the correct promotion group
				var group = fromProduct.parents(".productGroup");
				var chooser_index = _getGroupIndex(group);					
				_selectSlotIndex(chooser_index);
					
				// add the item
				_addItem(fromProduct.eq(0));
			}
		}
	}

	function _isSpoPromotion() {
		return $(".promotion", _infoArea).hasClass("SPOPromotion");
	}
	
	
	/**
	 * Bubble sorts the slots using business rules.
	 * 1) Mandatory products.
	 * 2) Prepopulated groups.
	 * 3) Groups with only one choice.
	 * 4) Groups with more than one choice.
	 */
	function _sortSlots() {
		var slots = $(".promotion dl.product_sortable");
		var comparers = [_isProductMandatory, _isSlotPopulated, _isProductChoiceSingular];
		var swap_occurred;

		do {
			swap_occurred = false;
			
			for(var i = 0; i < slots.length - 1; ++i)
			{
				var swap_items = false;
				var slot1 = slots.eq(i);
				var slot2 = slots.eq(i + 1);
				
				var sorting_status; // type { swapItems : bool, continueComparisons : bool }
				
				for(var j = 0; j < comparers.length; ++j)
				{
					sorting_status = _compareForSorting(slot1, slot2, comparers[j]);
					if(! sorting_status.continueComparisons)
					{
						break;
					}
				}
				
				if(sorting_status.swapItems)
				{
					_swapSlotGroups(slot1, slot2);
					if(! swap_occurred)
					{
						swap_occurred = true;
					}
				}
				
				slots = $(".promotion dl.product_sortable");
			}
		}
		while(swap_occurred);
		
		// reformat the slots (+ signs)
		$(".promotion .symbol.plus").remove();
		slots = $(".promotion dl.product");
		for(var i = 0; i < slots.length - 1; ++i)
		{
			slots.eq(i).after('<span class="symbol plus">+</span>');
		}
	}
	
	/**
	 *
	 */
	function _compareForSorting(a, b, assessor) {
	
		var sorting_status = {
			swapItems : false,
			continueComparisons : false
		};
		
		if(! assessor(a) || ! assessor(b))
		{
			if(assessor(a) !== assessor(b))
			{
				sorting_status.swapItems = assessor(b);
			}
			else
			{
				sorting_status.continueComparisons = true;
			}
		}
		return sorting_status;
	}
	
	/**
	 * Selects the first available slot,
	 * i.e. the first one that is neither mandatory nor populated.
	 */
	function _selectFirstSuitableSlot() {
		var slots = $(".promotion dl.product");
		for(var i = 0; i < slots.length; ++i)
		{
			var slot = slots.eq(i);
			if(! _isProductMandatory(slot) && ! _isSlotPopulated(slot))
			{
				_selectSlot(slot);
				break;
			}
		}
	}
	
	/**
	 * Discovers whether a slot is mandatory (unchangeable).
	 * @param slot JQuery A (.promotion .product).
	 * @return Boolean True if mandatory, false otherwise.
	 * @see _sortSlots.
	 */
	function _isProductMandatory(slot) {
		return ! slot.hasClass("product_selector");
	}
	
	/**
	 * Discovers whether a slot has been populated.
	 * @param slot JQuery A (.promotion .product).
	 * @return Boolean True if pre-populated, false otherwise.
	 * @see _sortSlots.
	 */
	function _isSlotPopulated(slot) {
		return slot.hasClass("product_selector_populated");
	}
	
	/**
	 * Discovers whether a product group has only one choice.
	 * @param slot JQuery A (.promotion .product).
	 * @return Boolean True if has only one choice, false otherwise.
	 * @see _sortSlots.
	 */
	function _isProductChoiceSingular(slot) {
		var index = _getSlotIndex(slot);
		return _getChoiceCountFor(index) === 1;
	}
	
	/**
	 */	
	function _isProductOutOfStock(product) {
		return product.find(".outOfStock").length > 0;
	}
	
	/**
	 * Finds the index of this group (product chooser).
	 * @param groupElement JQuery A product chooser.
	 * @return int The index of this product group. (Base 1.)
	 * @see _sortSlots.
	 */
	function _getGroupIndex(group) {
		var id_pieces = group[0].id.split("_");
		return id_pieces[id_pieces.length - 1];
	}
	
	function _getSlotIndex(slot) {
		var slot_class = slot.eq(0).attr("class");
		var group_class = slot_class.match(/product_selector_\d+/)[0];
		return group_class.match(/\d+/)[0];
	}

	/**
	 * Finds the slots corresponding to the supplied index.
	 * @param slotIndex int The base 1 index of this slot.
	 * @return JQuery A slot element.
	 */
	function _getSlot(slotIndex) {
		return $(".promotion .product_selector_" + slotIndex);
	}
	
	/**
	 * Finds the number of choices available to the given slot.
	 * @param slotIndex int The index of this slot. (Base 1.)
	 * @return int The number of product choices available.
	 * @see _sortSlots.
	 */
	function _getChoiceCountFor(slotIndex) {
		var chooser = $("#productGroup_" + slotIndex);
		return chooser.find(".product").length;
	}
	
	/**
	 * Swaps two slots, including any group siblings. 
	 * @param a JQuery First node.
	 * @param b JQuery Second node.
	 * @see _sortSlots.
	 */
	function _swapSlotGroups(a, b) {
		var b_group_classes = b.eq(0).attr("class").match(/product_selector_\d+/);
		if(b_group_classes.length > 0)
		{
			var b_group_class = b_group_classes[0];
			var b_slots = $(".promotion ." + b_group_class);
			b_slots.insertBefore(a);
		}
	}
	
	function _swapSlots(a, b) {
		var b_destination = a.next();
		a.insertBefore(b);
		b.insertBefore(b_destination);
	}
	
	/**
	 * Programmatically selects a slot.
	 * @param index int The index of the chooser, base 1.
	 */
	function _selectSlotIndex(index) {
		_selectSlot(_getSlot(index));
	}
	
	/**
	 * Programmatically selects a slot.
	 * @param slot JQuery The slot element.
	 */
	function _selectSlot(slot) {
		slot.find("a.choose").click();
	}
	
	function _toggleProductGroupView(href) {
		// clean hrefs with .replace functions added because IE6+7 adding http://blah to some. 
		var cleanHref = href.replace(/.*(#.*)/,"$1");

		// Hide unwanted product groups and show the requested one.
		_productGroups.not("id=" + cleanHref.replace("#","")).addClass("hidden"); // hide all
		$(cleanHref).removeClass("hidden");

		// Update the state of product selectors.
		$(".product_selector").each(function(i) {
			var productSelector = $(this);
			var chooser = productSelector.find(".choose");
			var chooserHref = (chooser.length > 0) ? chooser.attr("href") : productSelector.data("selector").find(".choose").attr("href");
			var cleanChooserHref = chooserHref.replace(/.*(#.*)/,"$1");
 
			if(cleanChooserHref == cleanHref) {
				productSelector.addClass("product_selector_active");
			}
			else {
				productSelector.removeClass("product_selector_active");
			}
		});
	}

	function _setUpProductButtons() {
		// Affects QuickInfo and Add item elements, changing to meet required layouts.
		$(".product .addItem").each(function(i) {
			var current = $(this);

			if(_isSpoPromotion()) {
				// Add changes to allow SPO differences in layout.
				current.parent().addClass("actionsSPO");
				current.before(current.next()); // swap QuickInfo/Add item order.
			}
			else {
				// Change checkboxes (non-JS use) into buttons and input:hidden elements.
				var inpt = current.find("input");
				var button = $("<input type=\"image\" title=\"Add this item to your package offer\" src=\"/wcsstore/argos/en_US/images/promotions/images/bttn_add_item.gif\" class=\"addItem button\" alt=\"add item\" />");
				button.click(function() {
					_addItem($(this).parents(".product"));
					return false;
				});

				current.next(".quickinfo").after(button);
				current.replaceWith("<input name=\"" + inpt.attr("name") + "\" type=\"hidden\" value=\"" + inpt.attr("value") + "\" rel=\"" + inpt.attr("rel") + "\" disabled=\"disabled\" />");
			}
		});
	}

	function _setUpProductGroups() {
		// Change wrapping product groups into carousels (not for SPOs).
		if(! _isSpoPromotion()) {
			_productGroups.each(function(i) {
				var group = $(this);
				var selections = Number(group.find(".instruction").text().replace(/.*([0-9])+.*/, "$1"));
				var carousel = new argos.widgets.Carousel(group.find(".product"), {"leftOffset" : 50, "paging" : 4});
				if(carousel.exists) {
					carousel.addSorting(argos.widgets.Carousel.products.sortPriceLowToHigh, "Price: low - high");
					carousel.addSorting(argos.widgets.Carousel.products.sortTitleAToZ, "Alphabetic");
					carousel.addSorting(argos.widgets.Carousel.products.sortRatingHighToLow, "Top Rated");
					carousel.controller.$node.parents(".productGroup").addClass("productGroupCarousel");
				}
				else {
					group.find(".instruction").html("").addClass("blank");
				}

				// Hide if not the initial group.
				if(i >= 1) {
					group.addClass("hidden");
				}
			});
		}
	}

	function _addItem(product) {
		var activeSelectors = $(".product_selector_active", _infoArea);
		var activeSelectorImages = $("dd.image img", activeSelectors);
		var selector;

		if(activeSelectorImages.length >= activeSelectors.length) {
			alert("You have chosen the maximum number of items from this selection.");
		}
		else {
			for( var i=0; i < activeSelectors.length; i++) {
				selector = activeSelectors.eq(i);
				if($("dd.image img", selector).length == 0) {
					_addProduct(selector, product);
					break;
				}
			}
		}

		if(_promotionComplete()) {
			_promotion.addClass("complete");
			_updatePrice();
		}
	}

	function _promotionComplete() {
		var selectors = $(".product_selector", _infoArea);
		return (selectors.length == $("dd.image img", selectors).length); 
	}

	function _addProduct(selector, product) {	
		var productClone = product.clone(true); 

		// replace addItem button with selection remover and change input:hidden to enabled.
		productClone.find("dd.actions .addItem").remove();
		productClone.find("dd.image").append(_selectionRemover(productClone));
		productClone.find("dd.actions input[name='promotionProduct']").attr("disabled", false);

		// convert product clone to selected item.
		productClone
			.attr("style", "")
			.addClass(selector.attr("class"))
			.addClass(selector.attr("class").replace("_active", "_populated"));

		// make copy of selector then replace original with chosen product.
		productClone.data("selector", selector.clone(true));
		selector.replaceWith(productClone);

		// sometimes the product desciption is too long for the CSS
		_correctProductSelectorHeights();
	}

	function _correctProductSelectorHeights() {
		// Corrective calculations for when content of product selectors exceeds the min-height
		// of the product selector. They have min-height due to pink background.
		// Remove this function when/if a better background application method is found.
		var promo = $(".promotion");
		var selectors = $(".product_selector");
		var activePopulatedSelectors = $(selectors).filter(".product_selector_populated");
		var activeUnpopulatedSelectors = $(selectors).filter(":not(.product_selector_populated)");
		var activeSelectors = $(selectors).filter(".product_selector_active");
		var adjustment = 0;
		var maxHeight = 0;
		var padding = 5; // Just for visual fluff.

		// 1). Clear any previous height adjustments.
		selectors.attr("style", ""); 

		// 2). Don't bother with height adjustments when nothing populated.
		if(selectors.length != activeUnpopulatedSelectors.length) {

			// 3). Correct heights of any populated active selectors where QuickInfo overlaps background edge.
			activePopulatedSelectors .each(function(i) {
				var s = $(this);
				var sBase = s.offset().top + _height(s);
				var qi = s.find(".quickinfo");
				var qiBase = (qi.length > 0) ? (qi.offset().top + qi.outerHeight() + padding) : 0;
				if(qiBase > sBase) {
					_adjustSelectorHeight(s, qiBase - sBase);
				}
				
				// 4). Repopulate max height if it's too low (so we find the tallest).
				maxHeight = (maxHeight < _height(s)) ? _height(s) : maxHeight;
			});

			// 5). Make sure all active selectors match the maxHeight value.
			activeSelectors.each(function() {
				var s = $(this);
				var h = _height(s);
				if(h < maxHeight) {
					_adjustSelectorHeight(s, maxHeight - h);
				}
			});
		}
	}

	function _adjustSelectorHeight(selector, adjustment) {
		$(this).attr("style", "");
		if(jQuery.browser.msie && Math.floor(jQuery.browser.version) <= 6) {
			selector.css("height", Number(selector.css("height").replace("px", "")) + adjustment);
		}
		else {
			selector.css("min-height", Number(selector.css("min-height").replace("px", "")) + adjustment);
		}
	}

	function _removeProduct(product) {
		var selector = product.data("selector");
		_toggleProductGroupView(selector.find(".choose").attr("href"));
	 	product.replaceWith(selector);
		_correctProductSelectorHeights();
	}

	function _selectionRemover(selector) {
		var el = $("<span class=\"remover\" title=\"Remove this selection\">Remove</span>");
		el.click(function() {
			var t = $(this);
			t.parents(".promotion").removeClass("complete");
			_removeProduct(t.parents(".product"), selector);
			_updatePrice();
		});
		return el;
	}

	function _updatePrice() {
		var op = $("#odpInformation .offerPrice");
		var products = $(".product dd.actions input[name='promotionProduct']", _infoArea);
		var data, storeId, langId, promotionIdentifier = "";

		if(products.parents(".promotion").hasClass("complete") && _module.priceUpdateAvailable) {
			// Build the data string then POST with Ajax. If error, fail silently without adjusting price.
			data = op.parents("form").serialize();
			promotionIdentifier = data.replace(/.*(promotionIdentifier=[\w]*)&?.*/,"$1");
			storeId = data.replace(/.*(storeId=[\d]*)&?.*/,"$1");
			langId = data.replace(/.*(langId=[-]?[\d]*)&?.*/,"$1");
			data = promotionIdentifier + "&" + storeId + "&" + langId + "&";

			products.each(function(i) {
				var t = $(this);
				data += "&" + t.attr("name") + "_" + (i + 1) + "=" + t.attr("rel");
			});

			$.ajax({
				url: "/webapp/wcs/stores/servlet/CalculateSpecialOfferValue",
				data: data,
				dataType: "json",
				type: "post",
				success: function(jsonResponse){
					var main = op.find(".main").eq(0); /* html occasionally has 2x span.main */
					var save = op.find(".save");
					save = (save.length > 0) ? save : $("<span class=\"save\"></span>");
					save.html("Save &pound;" + jsonResponse.saving);
					main.html("&pound;" + jsonResponse.value)
					op.empty().append(main);
					op.prepend(save);
				},
				error: function(){
					op.html(_originalPrice); // reset
				}
			});
		}
		else {
			op.html(_originalPrice); // reset
		}
	}


});



/***************************************************

	Custom Omniture tagging for Promotions

***************************************************/
argos.promotions.omniture = {};
argos.promotions.omniture.account = s_account; // s_account set in omnitureInit fragment.
	
// Omniture for the lister pages.
argos.promotions.omniture.lister = new (function() {
	this.init = function() {
		var promotions = $(".product").find(".promotions");
		promotions.siblings(".producttitle").find("a").filter(":not(.moredetail)").bind("click",{tag:"producttitle:"},_tag);
		promotions.siblings(".producttitle").find("a.moredetail").bind("click",{tag:"moredetail:"},_tag);
		promotions.find(".button").bind("click",{tag:"moreoffers:"},_tag);
		promotions.find("li span").bind("click",{tag:"shorttext:"},_tag);
	}

	function _tag(event) {
		var s = s_gi(argos.promotions.omniture.account);
		s.tl(this,'o','ar:productlist:' + event.data.tag);
	}
});

// Omniture for the PDP.		
argos.promotions.omniture.pdp = new(function() {
	var pdp = this;
	this.carousel = {
		init : function() {
			var carousel = $("#pdpPromotionsCarousel");
			$("button.forward", carousel).bind("click",{tag:"specialofferscarousel:"},pdp.carousel.tag);
			$(".promotion .fullDetails", carousel).bind("click",{tag:"fullofferdetails:"},pdp.carousel.tag);
		},
		tag : function(event) {
			var s=s_gi(argos.promotions.omniture.account);
			s.linkTrackVars="prop25";
			s.linkTrackEvents='none';
			s.prop25='ar:product:' + event.data.tag;
			s.tl(this,'o','ar:product:' + event.data.tag);
		
		}
	} 

	this.promotab = {
		init : function() {
			var promotions = $("#pdpPromotions");
			//$(".button_chooseProduct", promotions).bind("click",{tag:""},pdp.promotab.tag);
			$(".button_buyOrReserve", promotions).bind("click",pdp.promotab.tag);
		},
		tag : function() {
			var s = s_gi(argos.promotions.omniture.account);
			s.eVar56 = $(this).siblings("input[name=promotionIdentifier]").val();
			s.tl($(this).siblings("input[name=addSpecialOffer]")[0],'o','promotionbuyreservebutton');

		}
	};
});

// Omniture  for the Special Offer Details page.
argos.promotions.omniture.odp = new(function() {
	this.init = function() {
		$("#addSpecialOffer").click(function(){
			LightboxAddToTrolley.omniture.tags["eVar56"] = $(this).parents("form").find("input[name=promotionIdentifier]").val();
		});
	}
});




/***************************************************

	Initiate on document ready.

***************************************************/
$(document).ready(function() {
	argos.promotions.init();
	argos.promotions.lister.init(["search", "browselister"]);
	argos.promotions.odp.init(["offerdetails"]);
});


