/**
 * Smart Shelf
 *
 * @param 
 * @return void
 *
 * @author Josh Zeigler <jzeigler@resource.com>
 *
 * @requires: ATG Recommendations,
 *		MooTools 1.2.2 Core,
 *		MooTools 1.2.2.2 More (Full),
 *		QuickLook Custom Walgreen's Function
 *		Cliencide SimpleSlideShow (modified, included)
*/

/** cdnPath set in JSP */
var cdn=(typeof(cdnPath)!="undefined")?cdnPath:"";

var relativeproducts = new Class({

	/**
	 * implements
	 */
	Implements: [Options],
	
	version: "1.0.0",

	/**
	 * options
	 * Options used by default
	 */
	options: {
		'ppp': 4, //products per page
		'paginationContainer': "ss-pagination"
	},
	
	panels: {},

	initialize: function(shelf, options) {
		this.setOptions(options);
		
		//Create Loader Icon CSontainer
		//this.loader = new Element("div", {'id': "ts-loader"}).inject($("ts-shelf"), "top");
		
		//Create ATG Recommendations Builder
		this.createBuilder();		
		
		//Prepare Tabs
		//this.prepareTabs();
	},
	
	createRender: function() {
		
		ATGSvcs.renderer("relativeproducts", function(slot_element) {	
			var slides, panel, table, tbody, row, col;
			var slot_name = slot_element.id;
			
			var shelf = slot_element.id.replace("panel-","");
			var items = this.recs.length;	
			ATGSvcs.dom.tags("TABLE|TBODY|TR|TD");
			
			slides = slot_element.appendChild(ATGSvcs.dom.DIV({id: 'ss-slides-'+shelf, Class: "ss-slides"}));
			
			for(var i=0; i < items; i++) {
				if(i % 4 == 0) {
					panel = slides.appendChild(ATGSvcs.dom.DIV({Class: "ss-panel"}));
					table = panel.appendChild(ATGSvcs.dom.TABLE({width: "690"}));
					tbody = table.appendChild(ATGSvcs.dom.TBODY());
					row = tbody.appendChild(ATGSvcs.dom.TR());
				}
				
				col = ATGSvcs.dom.TD();
				col.appendChild(ATGSvcs.build_rec(slot_name, this.recs[i], "relativeproducts"));
				row.appendChild(col);
			}
			
			//External Call to relativeproducts Class
			ss.prepare(slot_name, items);
		});
	},
	
	createBuilder: function() {	
		
		ATGSvcs.rec_builder("relativeproducts", function(slot_name, rec_data) {
			var recommendation = ATGSvcs.dom.DIV();
			var imageSrc = rec_data.image;
			if (rec_data.image.indexOf('/') == 0) {
				imageSrc = cdn + rec_data.image.substring(1, rec_data.image.length);
			}
			
			var image = ATGSvcs.dom.DIV({Class: "image-container quick-look"},
				ATGSvcs.dom.A({href: "/store/store/product/view_product_details.jsp?id=" + rec_data.productId.toLowerCase(), title: rec_data.name},
					ATGSvcs.dom.IMG({src: imageSrc, title: rec_data.name, alt: rec_data.name, width: 130, height: 130})
			));
			
			var details = ATGSvcs.dom.DIV({Class: "ss-product-details"},
				ATGSvcs.dom.DIV({},
					ATGSvcs.dom.A({href: "/store/store/product/view_product_details.jsp?id=" + rec_data.productId.toLowerCase(), title: rec_data.name}, ATGSvcs.util.trunc(rec_data.name, 50))),
					ATGSvcs.dom.DIV({Class: ((rec_data.sale == "true") ? "sale" : "price")}, "$" + rec_data.price)
				
			);
			
			recommendation.appendChild(image);
			recommendation.appendChild(details);
			
			recommendation.id = ATGSvcs.rec_id(slot_name, rec_data.productId);
			recommendation.className = "cs-rec";
			
			return recommendation;
		});
		
		//Ready to create Renderer
		this.createRender();
	},
	
	prepare: function(panel, items) {
		/*if((document.all) && (navigator.userAgent.toUpperCase().indexOf('OPERA') < 0) && (navigator.userAgent.indexOf('MSIE 7') < 0)) {
			this.ie6PNGFix();
		}*/
		
		$$("#related-products .quick-look").each(function(el) { QuickLook(el) });
		
		var shelf = panel.replace("panel-", "");
		
		var pagination = new Element("div", {'class': "ss-pagination", 'id': "pagination-"+shelf}).inject(panel, "top");
		
		this.panels[shelf] = {'count': items, 'pages': Math.ceil(items/this.options.ppp), 'current': 1};
		
		//Create Pagination
		
		
		//this.loader.fade("out");
	},
	
	
	changeShelf: function(shelf) {
		$("panel-"+this.active).addClass("hide");
		this.active = shelf;
		$("panel-"+this.active).removeClass("hide");
		$("panel-"+shelf).set('morph', {'duration': 1250, 'transition': Fx.Transitions.Sine.easeIn});
		$("panel-"+shelf).morph({'opacity': 1});
		//this.loader.fade("out");
	},
	
	changePanel: function(shelf, page) {
		this.panels[shelf].slideshow.show(page-1);
		this.changePage(shelf, page-1);
	},
	
	
	ie6PNGFix: function() {
		$$('#related-products img[src$=.png]', '#related-products input[src$=.png]').each(function(img){
                    // get the dimensions
                    var width = img.getProperty('width');
                    var height = img.getProperty('height');
                    var src = img.getProperty('src');
                    src=cdn+src;

                    // force the spacer for transparent backgrounds
                    img.setProperty('src', _SPACER_IMAGE);

                    // setup the new properties (replace mouseovers)
                    img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + src + '\')';
		});
	}
});

var ss = new relativeproducts('relativeproducts');



/*
Script: Clientcide.js
	The Clientcide namespace.

License:
	http://www.clientcide.com/wiki/cnet-libraries#license
*/
var Clientcide = {
	version: '2.0.3',
	setAssetLocation: function(baseHref) {
		var clean = function(str){
			return str.replace(/\/\//g, '/');
		};
		if (window.StickyWin && StickyWin.UI) {
			StickyWin.UI.implement({
				options: {
					baseHref: clean(baseHref + '/stickyWinHTML/')
				}
			});
			if (StickyWin.alert) {
				var CGFsimpleErrorPopup = StickyWin.alert.bind(window);
				StickyWin.alert = function(msghdr, msg, base) {
				    return CGFsimpleErrorPopup(msghdr, msg, base||clean(baseHref + "/simple.error.popup"));
				};
			}
			if (StickyWin.UI.Pointy) {
				StickyWin.UI.Pointy.implement({
					options: {
						baseHref: clean(baseHref + '/PointyTip/')
					}
				});
			}
		}
		if (window.TagMaker) {
			TagMaker.implement({
			    options: {
			        baseHref: clean(baseHref + '/tips/')
			    }
			});
		}
		if (window.ProductPicker) {
			ProductPicker.implement({
			    options:{
			        baseHref: clean(baseHref + '/Picker')
			    }
			});
		}

		if (window.Autocompleter) {
			Autocompleter.Base.implement({
					options: {
						baseHref: clean(baseHref + '/autocompleter/')
					}
			});
		}

		if (window.Lightbox) {
			Lightbox.implement({
			    options: {
			        assetBaseUrl: clean(baseHref + '/slimbox/')
			    }
			});
		}

		if (window.Waiter) {
			Waiter.implement({
				options: {
					baseHref: clean(baseHref + '/waiter/')
				}
			});
		}
	},
	preLoadCss: function(){
		if (window.StickyWin && StickyWin.ui) StickyWin.ui();
		if (window.StickyWin && StickyWin.pointy) StickyWin.pointy();
		Clientcide.preloaded = true;
		return true;
	},
	preloaded: false
};
(function(){
	if (!window.addEvent) return;
	var preload = function(){
		if (window.dbug) dbug.log('preloading clientcide css');
		if (!Clientcide.preloaded) Clientcide.preLoadCss();
	};
	window.addEvent('domready', preload);
	window.addEvent('load', preload);
})();
setCNETAssetBaseHref = Clientcide.setAssetLocation;

/*
Script: ToElement.js
	Defines the toElement method for a class.

License:
	http://www.clientcide.com/wiki/cnet-libraries#license
*/
Class.ToElement = new Class({
	toElement: function(){
		return this.element;
	}
});
var ToElement = Class.ToElement;

/*
Script: SimpleSlideShow.js

Makes a very, very simple slideshow gallery with a collection of dom elements and previous and next buttons.

License:
	http://www.clientcide.com/wiki/cnet-libraries#license
*/
var SimpleSlideShow = new Class({
	Implements: [Events, Options, Chain],
	options: {
		startIndex: 0,
		slides: [],
		currentSlideClass: 'currentSlide',
		currentIndexContainer: false,
		maxContainer: false,
		nextLink: false,
		prevLink: false,
		wrap: true,
		disabledLinkClass: 'disabled',
//		onNext: $empty,
//		onPrev: $empty,
//		onSlideClick: $empty,
//		onSlideDisplay: $empty,
		crossFadeOptions: {}
	},
	initialize: function(options){
		
		this.setOptions(options);
		var slides = this.options.slides;
		this.makeSlides(slides);
		this.setCounters();
		this.setUpNav();
		this.now = this.options.startIndex;
		if (this.slides.length > 0) this.show(this.now);
	},
	slides:[],
	setCounters: function(){
		if ($(this.options.currentIndexContainer))$(this.options.currentIndexContainer).set('html', this.now+1);
		if ($(this.options.maxContainer))$(this.options.maxContainer).set('html', this.slides.length);
	},
	makeSlides: function(slides){
		//hide them all
		slides.each(function(slide, index){
			if (index != this.now) slide.setStyle('display', 'none');
			else slide.setStyle('display', 'block');
			this.makeSlide(slide);
		}, this);
	},
	makeSlide: function(slide){
		slide.addEvent('click', function(){ this.fireEvent('onSlideClick'); }.bind(this));
		this.slides.include(slide);
	},
	setUpNav: function(){	
		if ($(this.options.nextLink)) {
			$(this.options.nextLink).addEvent('click', function(){
				this.forward();
			}.bind(this));
		}
		if ($(this.options.prevLink)) {
			$(this.options.prevLink).addEvent('click', function(){
				this.back();
			}.bind(this));
		}
	},
	disableLinks: function(now){
		if (this.options.wrap) return;
		now = $pick(now, this.now);
		var prev = $(this.options.prevLink);
		var next = $(this.options.nextLink);
		var dlc = this.options.disabledLinkClass;
		if (now > 0) {
			if (prev) prev.removeClass(dlc);
			if (now === this.slides.length-1 && next) next.addClass(dlc);
			else if (next) next.removeClass(dlc)
		}	else { //now is zero
			if (this.slides.length > 0 && next) next.removeClass(dlc);
			if (prev) prev.addClass(dlc);
		}
	},
	forward: function(){
		if ($type(this.now) && this.now < this.slides.length-1) this.show(this.now+1);
		else if ($type(this.now) && this.options.wrap) this.show(0);
		else if (!$type(this.now)) this.show(this.options.startIndex);
		this.fireEvent('next');
		return this;
	},
	back: function(){
		if (this.now > 0) {
			this.show(this.now-1);
			this.fireEvent('onPrev');
		} else if (this.options.wrap && this.slides.length > 1) {
			this.show(this.slides.length-1);
			this.fireEvent('prev');
		}
		return this;
	},
	show: function(index){
		if (this.showing) return this.chain(this.show.bind(this, index));
		var now = this.now;
		var s = this.slides[index]; //saving bytes
		function fadeIn(s, resetOpacity){
			s.setStyle('display','block');
			if (!Browser.Engine.trident4) {
				if (resetOpacity) s.setStyle('opacity', 0);
				s.set('tween', this.options.crossFadeOptions).get('tween').start('opacity', 1).chain(function(){
					this.showing = false;
					this.disableLinks();
					this.callChain();
					this.fireEvent('onSlideDisplay', index);
				}.bind(this));
			}
		};
		if (s) {
			if ($type(this.now) && this.now != index){
				if (!Browser.Engine.trident4) {
					var fx = this.slides[this.now].get('tween');
					fx.setOptions(this.options.crossFadeOptions);
					this.showing = true;
					fx.start('opacity', 0).chain(function(){
						this.slides[now].setStyle('display','none');
						s.addClass(this.options.currentSlideClass);
						fadeIn.run([s, true], this);
						this.fireEvent('onSlideDisplay', index);
					}.bind(this));
				} else {
					this.slides[this.now].setStyle('display','none');
					fadeIn.run(s, this);
				}
			} else fadeIn.run(s, this);
			this.now = index;
			this.setCounters();
		}
	},
	slideClick: function(){
		this.fireEvent('onSlideClick', [this.slides[this.now], this.now]);
	}
});

SimpleSlideShow.Carousel = new Class({
	Extends: SimpleSlideShow,
	Implements: [Class.ToElement],
	Binds: ['makeSlide'],
	options: {
		sliderWidth: 999999
	},
	initialize: function(container, options){
		this.setOptions(options);
		this.container = $(container);
		this.element = new Element('div').wraps(this.container).setStyles({
			width: this.container.getSize().x,
			overflow: 'hidden',
			position: 'relative'
		});
		this.container.setStyles({
			width: this.options.sliderWidth,
			position: 'relative'
		});
		this.parent(options);
	},
	makeSlides: function(slides) {
		this.slides = [];
		slides.each(this.makeSlide);
	},
	makeSlide: function(slide) {
		if (slide.retrieve('slideSetup')) return;
		slide.store('slideSetup', true);
		slide.show();
		var s = new Element('div', {
			styles: {
				'float': 'left',
				width: $(this).getSize().x
			}
		}).wraps(slide);
		this.parent(s);
		this.slides.erase(slide);
		this.setCounters();
		s.show();
		s.inject(this.container);
	},
	show: function(index) {
		if (!this.container) return;
		this.fx = this.fx || new Fx.Tween(this.container, {
			property: 'marginLeft'
		});
		if (this.showing) return this.chain(this.show.bind(this, index));
		var now = this.now;
		var s = this.slides[index]; //saving bytes
		if (s) {
			if (this.now != index) {
				this.fx.start(-s.getPosition(this.container).x).chain(function(){
					s.addClass(this.options.currentSlideClass);
					this.showing = false;
					this.disableLinks();
					this.callChain();
					this.fireEvent('onSlideDisplay', index);
				}.bind(this));
			}
			this.now = index;
			//this.setCounters();
		}
	}
});
