application.core.extend({
  product: {  
    AbstractProducts: function(config) {
	  this.storeConfig(config);
	  
	  return this.init();
	},
	
	Banner: function(config) {	
	  this.storeConfig({ 
		dataUrl: 'files/products.xml',
		container: '#product-banner',
		navigation: '#product-tab ul',
		delay: 3500,
		speed: 1000
	  }, config);		  

	  return this.init();
    },
	
	ChooseAssist: function(config) {	
	  this.storeConfig({ 
		dataUrl: 'files/products.xml',
		container: '#product-choose',
		selector: '#product-choose-assist',
		navigation: '#product-choose div.product-strip ul',
		grid: '#product-image-grid a'
	  }, config);		  

	  return this.init();
    },
	
	Product: function(config) {	
	  this.storeConfig({
		summary: 'ul.product-features',
		overlayInitialWidth: 200,
		overlayInitialHeight: 200,
		overlayOpacity: 0.4
	  }, config);		  

	  return this.init();
    },	
	
	WashroomProducts: function(config) {	
	  this.storeConfig({
		products: '#washroom-products',
		container: '#washroom-product'
	  }, config);		  

	  return this.init();
    }	
  }
});

application.core.extend(
  application.product.AbstractProducts.prototype, 
  application.base.Base.prototype, 
  { 
	init: function() {
      this.setProp('dataUrl', this.getGlobal('websiteResourcesPath') + this.retrieveConfigValue('dataUrl'));				  		
	  this.setProp('dataCache', null);
	  this.setProp('currentId', null);		
	  this.setProp('currentType', null);			  
	  
	  return this;
	},
	
	cache: function(data) {
	  if (!this.getProp('dataCache') && data) {
	    this.setProp('dataCache', data);
	  }
	  
	  return this.getProp('dataCache');
	},
	
	change: function() {
	  if (this.cache()) {
	    this.loading(true);
		this.updateContent(this.parseNode(this.getNode()));		  
	  } else {
		this.load();  
	  }
	},
	
	load: function() {
	  this.loading(true);
	  
	  this.ajaxGet(
		this.getProp('dataUrl'), 
		{ uid: Math.random() },
		'xml', 
		this.delegate(this.loadSuccess), 
		this.delegate(this.loadFail)
	  );
	},
	
	loadSuccess: function(data) {
	  this.cache(data);
  	  this.updateContent(this.parseNode(this.getNode()));
	},
	
	loadFail: function() {
	  alert('Product load fail.');
	},
	
	loading: function(on) {
	  var loading = $('#loading');
	  
	  if (on) {
		if (!loading.size()) {
		  $('<div id="loading">Loading...</div>').hide().css({ left: ($(window).width() / 2) - 100, top: 250 }).appendTo('body');
		  
		  $('#loading').fadeIn('fast');
		}

		this.enableUi(on);
	  } else {
		loading.fadeOut('fast');
		
		this.enableUi(on);		
	  }
	},
	
	enableUi: function(on) {},		
	
	updateContent: function(content) {},
	
	getNode: function() {
	  return $('hand-dryer[id="' + this.getProp('currentId') + '"]', this.getProp('dataCache'));	
	},
	
	parseNode: function(node) {
	  return {
		id: node.attr('id'),
		name: $('name', node).text(),
		mediumImage: $('medium-image', node).text(),
		largeImage: $('large-image', node).text(),		
		description: $('description', node).text(),
		text: $('banner-text', node).text(),
		types: $('types', node).text().split(',')
	  };
	}
  }
);

application.core.extend(
  application.product.Banner.prototype, 
  application.product.AbstractProducts.prototype, 
  { 
	init: function() {
	  application.product.AbstractProducts.prototype.init.call(this);
	  
	  $.extend({
	    easing: {
		  easein: function(x, t, b, c, d) {
			return c*(t/=d)*t + b; // in
		  }
	    }
	  });	  
	  
	  this.ready(function() {
		this.setProp('container', $(this.retrieveConfigValue('container')));
		this.setProp('carousel', $('div.carousel', this.getProp('container')));

		this.carousel();
	  });

	  return this;
	},
	
	carousel: function() {
	  var carousel = this.getProp('carousel');
	  var over = false, clicked = false;
	  
	  this.getProp('container').hover(function(){ over = true; }, function(){ over = false; }).find('.product-menu li a').bind('click', function(){ clicked = true; });
	  carousel.find('li').show().end().jCarouselLite({
		visible: 1,
		auto: this.retrieveConfigValue('delay'),
		speed: this.retrieveConfigValue('speed'),
		easing: 'easein',
		btnGo: ['.product-menu .1', '.product-menu .2', '.product-menu .3', '.product-menu .4', '.product-menu .5', '.product-menu .6', '.product-menu .7', '.product-menu .8', '.product-menu .9'],
		beforeStart: function() {
		  var pause = clicked ? false : over;
		  clicked = false;
		  return pause;
		}
	  });		
	},
	
	bind: function() {
	  this.getProp('images').bind('click', this.delegate(this.imageClick));
	},
	
	imageClick: function(el) {
	  var a = $(el.target).is('a') ? $(el.target) : $(el.target).parent('a');

	  this.setProp('currentId', a.attr('rel'));

	  this.change();

	  return false;
	},
	
	updateContent: function(content) {
	  var self = this, iconHtml = '', image = $('<img src="' + self.getGlobal('websiteResourcesPath') + content.largeImage + '?' + Math.random() + '" alt="' + content.name + '" />');
	  
	  this.loading(false);	  
	  
	  image.bind('load', function() {
	    self.getProp('image').html(this);
	  });
	  
	  this.getProp('content').html(content.text);
	  this.getProp('iconSet').empty();
	  
	  $.each(content.types, function(i, n) { 
		iconHtml += '<li><img src="' + self.getGlobal('websiteResourcesPath') + 'images/' + n + '.gif" alt="' + n + '" width="25" height="25" /></li>';
	  });

	  this.getProp('iconSet').html(iconHtml);
	}
  }
);

application.core.extend(
  application.product.ChooseAssist.prototype, 
  application.product.AbstractProducts.prototype, 
  { 
	init: function() {
	  application.product.AbstractProducts.prototype.init.call(this);
	  
	  this.ready(function() {
		this.setProp('container', $(this.retrieveConfigValue('container')));
		this.setProp('selector', $(this.retrieveConfigValue('selector')));
		this.setProp('content', $('div.product-choices', this.getProp('container')));		
		this.setProp('navigation', $(this.retrieveConfigValue('navigation')));
		this.setProp('images', this.getProp('navigation').find('li a'));		
		this.setProp('imageGrid', $(this.retrieveConfigValue('grid')));		

		this.bind();
		this.selectorChange();
	  });

	  return this;
	},
	
	bind: function() {
	  var self = this;
	  
	  this.getProp('selector').bind('change', this.delegate(this.selectorChange))[0].selectedIndex = 0;
	  this.getProp('images').find('img').attr('alt', '');

	  application.ui.tooltip.associate(this.getProp('imageGrid'), {
		bodyHandler: function() { return self.tooltip.call(self, $(this)); }
	  });

	  application.ui.tooltip.associate(this.getProp('images'), {
		bodyHandler: function() { return self.tooltip.call(self, $(this)); }
	  });
	},
	
	selectorChange: function() {
	  var v = this.getProp('selector').val();
	  
	  this.setProp('currentType', v);
	  
	  this.change();
	},	
	
	tooltip: function(a) {
	  this.setProp('currentId', a.attr('rel'));

	  if (this.cache() && !a.hasClass('disabled')) {
		var content = this.parseNode(this.getNode());  
		  
		return '<div class="wrap"><div class="image"><img src="' + this.getGlobal('websiteResourcesPath') + content.mediumImage + '"/></div><div class="content"><h1>' + content.name + '</h1>' + content.description + '</div><div class="clear"></div></div>';
	  } else {
		return '';
	  }
	},
	
	enableUi: function(on) {
	  this.getProp('selector').attr('disabled', !!on ? 'disabled' : '');
	},			
	
	updateContent: function(content) {
	  var self = this, ids = this.getIdsByType();
	  
	  this.loading(false);	  

	  if (!this.getProp('content').find('div.' + this.getProp('currentType') + ':visible').length) {
	    this.getProp('content').find('> div').hide().end().find('.' + this.getProp('currentType')).slideDown('fast');
	  }
	  
	  this.getProp('images').each(function() {
	    var node = $(this);

		if ($.inArray(node.attr('rel'), ids) >= 0) {
		  node.removeClass('disabled');
		  node.find('img').fadeTo('fast', 1);
		} else {
		  node.addClass('disabled');			
		  node.find('img').fadeTo('fast', 0.3);	  
		}
	  });
	},
	
	getNodesByType: function() {
	  var type = this.getProp('currentType'), allTypes = type.indexOf('all') >= 0;

	  return $('hand-dryer', this.getProp('dataCache')).filter(function() {
		return allTypes || $.inArray(type, $('types', this).text().split(',')) !== -1;
	  });	
	},	
	
	getIdsByType: function() {
	  var a = [];
	  
	  this.getNodesByType().each(function(){ a.push($(this).attr('id')); });

	  return a;
	}
  }
);

application.core.extend(
  application.product.Product.prototype, 
  application.base.Base.prototype, 
  { 
	init: function() {
	  this.ready(function() {
		this.setProp('summary', $(this.retrieveConfigValue('summary')));
		this.setProp('summaryItems', $('li', this.getProp('summary')));		
		
		this.summary();
		this.lightbox();
	  });

	  return this;		
	},
	
	summary: function() {
	  this.getProp('summaryItems').filter(':has(ul)').css({ cursor: 'pointer' }).bind('click', this.delegate(this.summaryClick)).hover(
		function(){ 
		  $(this).addClass('over'); 
		}, function(){ 
		  $(this).removeClass('over'); 
		}
	  );
	},
	
	summaryClick: function(e) {
	  var el = $(e.target);
	  var c = el.find('ul');
	  
	  if (c.size()) {
		c.toggle('fast');  
	  }
	},
	
	lightbox: function() {
	  application.ui.colorbox.associate('a.lightbox', {  
		scrolling: false, 
		opacity: this.retrieveConfigValue('overlayOpacity'),
		initialWidth: this.retrieveConfigValue('overlayInitialWidth'),
		initialHeight: this.retrieveConfigValue('overlayInitialHeight'),
		maxWidth: '75%', 
		maxHeight: '75%'
	  });
	  
	  $(window).bind('cbox_complete', function(){
		var title = $('#cboxTitle').hide();
		var html = title.html();
		
		title.html(
		  $.map(html.split('|'), function(n, i) {
			return i == 0 ? '<h1>' + n.replace(/([^:]:\s+)(.+)/i, '$1<span>$2</span>') + '</h1>' : n;
		  }).join('<br />')
		);
		
		if(html.length) {
		  title.slideDown('fast');	
		}		
	  });
	}
  }
);

application.core.extend(
  application.product.WashroomProducts.prototype, 
  application.base.Base.prototype, 
  { 
	init: function() {
	  this.ready(function() {
	    this.setProp('products', $(this.retrieveConfigValue('products')));
	    this.setProp('container', $(this.retrieveConfigValue('container')));
	    this.setProp('images', this.getProp('products').find('li a'));		

		this.showImage();
	    this.bind();
	  });
	  
	  return this;
	},
	
	bind: function() {
	  var self = this;
	  
	  this.getProp('images').find('img').attr('alt', '');
	  this.getProp('images').bind('click', this.delegate(this.imageClick));	
	},
	
	showImage: function() {
	  var id = window.location.hash;
	  
	  this.changeImage(id);
	},
	
	imageClick: function(e) {
	  var a = $(e.target).is('img') ? $(e.target).parent() : $(e.target);
	  var id = a.attr('href');
	  
	  this.changeImage(id);
	  
	  return false;
	},
	
	changeImage: function(id) {
	  if (id && id.length > 1 && this.getProp('container').find(id).size())
	  {
	    this.getProp('container').find('div').hide().end().find(id).slideDown('fast');
	    this.getProp('images').removeClass('current').filter('[href=' + id + ']').addClass('current');
		
		window.scrollTo(0, $(id).offset().top);
	  }
	}
  }
);
