document.observe("dom:loaded", function() {
   PREX.applyDefaults($$('body')[0]);
});

PREX = {}

PREX.applyDefaults = function(el) {
  
  // override new window opening
  el.select('a[target=_blank]:not([rel=lightbox])').each(function(a) {
  	a.observe('click', function(e) {
		var w = 1020;
		var h = 650;
		var x = Math.round((screen.width-w)/2);
		var y = Math.round((screen.height-h)/2);
		var s = a.href;
		var o = 'buttons=1,scrollbars=1,location=0,menubar=0,resizable=1,status=0,directories=0,toolbar=1,';
		var n = s.replace(/[^a-z0-9]/ig, '');

		if (!(s.indexOf("http")==0 || s.indexOf("/")==0))
			s = _ABS_PATH + s;

		o+= hashToOptions({
				width: w, height: h,
				left: x, screenX: x,
				top: x, screenY: y
			});
			
		window.open(s, n, o).focus();
		e.stop();
	});
  });
  
  // amazon products handler
  el.select('.amazon-product-row').each(function(el) {
  	new PREX.AmazonProductLoader(el); 
  }); 
}

PREX.RecommendedBox = Class.create({}, {
	initialize: function (el, url, cid) {
		this.el 			= $(el);
		this.url			= url;

		this.el.down('.go-left').observe('click', this.scroll.bindAsEventListener(this, -1));		
		this.el.down('.go-right').observe('click', this.scroll.bindAsEventListener(this, 1));
		this.steps = this.el.select('a.step-indicator');
		
		this.setCID(cid);
		
		var o = this;
		this.el.down('#prnav').select('a').each(function(a) {
			a.observe('click', function(ev) {
				ev.stop();
				o.setCID(a.href.split('#').pop());
			});
		});
		
		this.steps.each(function(a) {
			a.observe('click', function(ev) {
				ev.stop();
				o.setStep(a.href.split('#').pop());
				o.request();
			});
		});
		
		this.initialized = true;
	},
	
	setCID: function(cid) {
		this.setStep(0);
		this.cid	= cid;
		
		if (this.initialized)
			this.request();
		
		this.el.down('#prnav li.on').removeClassName('on');
		this.el.down('#prnav li#c-' + this.cid).addClassName('on');
	},
	
	scroll: function(e, d) {
		e.stop();
		
		var step = this.step + d; 
		
		if (step < 0 || step >= this.steps.length)
			return;
		
		this.setStep(step);
		this.request();
	},
	
	request: function() {
		var items = this.el.down('.carousel')
		new Effect.Opacity(items, { from: 1.0, to: 0.1, duration: 0.1 });

		new Ajax.Request(this.url, {
			parameters: { scroller_step: this.step, cid: this.cid },
			onComplete: function(t) {
				items.update(t.responseText);
				Effect.Appear(items, { duration: 0.3 });
			}
		})
	},
	
	setStep: function(step)
	{
		if (this.step != undefined)
			this.steps[this.step].down('img').src = 'img/dot.gif';

		this.step = parseInt(step);
			
		this.steps[this.step].down('img').src = 'img/dot2.gif';

		if (this.step > 0) {
			this.el.down('.go-left').show();
		} else {
			this.el.down('.go-left').hide();
		}		
		
		if (this.step < this.steps.length - 1) {
			this.el.down('.go-right').show();
		} else {
			this.el.down('.go-right').hide();
		}
	}
});

PREX.ListForm = Class.create({
	initialize: function(el) {
		this.el = $(el);
		$('list-form-delete').observe('click', this.deleteListener.bind(this));
	},
	
	deleteListener: function(e) {
		e.stop();
		
		if (!confirm($('list-form-delete').getAttribute('data-confirm')))
			return;
				
		this.el.insert(new Element('input', {
			type: 'hidden', 
			name: 'delete_confirmed', 
			value: 1 
		}));
		
		this.el.submit();
	}
});

PREX.PriceAlertForm = Class.create({
	initialize: function(el) {
		this.el = $(el);
		
		$('custom_price').observe('focus', function(e) {
			$('f_price_0').checked = true;			
		});
		
		$('custom_price').observe('change', function(e) {
			$('f_price_0').value = $('custom_price').value;			
		});
		
		this.el.select('input[name="item[price]"]').each(function(e) {
			if (e.value && e.value == $('custom_price').value) {
				e.checked = true;	
				
				if (e.id != 'f_price_0')
					$('custom_price').value = $('f_price_0').value = '';
			}
		});
	}
});

PREX.FiltersSet = Class.create({
	initialize: function() {
		$$('ul.filters-list').each(function(el) {
			new PREX.Filter(el);
		});
	}
});

PREX.Filter = Class.create({
	initialize: function(el) {
		this.el 		= el;
		this.showAll 	= el.down('.filter-show-all-options');
		
		this.showAll.observe('click', this.showAllObserver.bind(this));
		
		var list = this.el.select('li').select(function(li) {
			return !li.hasClassName('filter-option-selected');
		}).sortBy(function(li) {
			return li.getAttribute('data-count') * -1;
		}).slice(10);
		
		if (!list.length)
			return;
			
		list.invoke('hide');
					
		this.showAll.show();
	},
	
	showAllObserver: function(e) {
		e.stop();
		this.showAll.hide();
		this.el.select('li').invoke('show');
	}
});

PREX.CategorySelect = Class.create({
	initialize: function() {
		var $this = this;
		
		this.options = Object.extend({
			container: 'category_select_container',
			field: 'category_id',
			tree: [],
			onChange: Prototype.emptyFunction
		}, arguments[0]);
		
		this.container 	= $(this.options.container);
		this.field		= $(this.options.field);
		
		this.select = new Element('select', {
			size: 10
		});		
		
		$A(this.options.tree).each(function(item) {
			$this.select.insert(new Element('option', {
				value: item.i
			}).update($this.optionTitle(item)));
		});
		
		this.container.insert(this.select);
		this.select.observe('change', this.selectObserver.bind(this));
	},
	
	selectObserver: function(e) {
		this.destroyBranch();
		this.setValue('');
		
		var id = $F(this.select); 
		var branch = this.options.tree.find(function(item) {
			return item.i == id;	
		});
		
		if (!branch)
			return;
					
		if (branch.c.length > 0)
			this.createBranch(branch);
		else
			this.setValue(id);
	},
	
	createBranch: function(branch) {
		this.branch = new PREX.CategorySelect(Object.extend(Object.clone(this.options),{
			tree: branch.c
		}));
	},
	
	destroyBranch: function() {
		if (!this.branch)
			return;
			
		this.branch.destroy();
		this.branch = null;
	},
	
	setValue: function(v) {
		var tmp = this.field.value;
		
		this.field.value = v;
		
		if (tmp != v)
			this.options.onChange(v);
	},
	
	optionTitle: function(item) {
		return item.c.length > 0 ? item.t + ' &raquo;' : item.t;
	},
	
	destroy: function() {
		this.destroyBranch();
		Element.remove(this.select);
	}
});

PREX.SecondhandPhotoUpload = Class.create({
	initialize: function(form, iframe) {
		this.form = $(form);
		this.iframe = $(iframe);
		this.input = this.form.down('input[type=file]');
		this.input.disable();
	
		this.input.observe('change', this.fileChangeListener.bind(this));
		this.iframe.observe('load', this.loadListener.bind(this));
	},
	
	fileChangeListener: function(){
		if (!$F(this.input).match(/(jpg|gif|png|jpeg)$/i)) 
			return;
		
		this.form.submit();
		this.form.down('#loader').show();
		this.input.disable();
	},
	
	loadListener: function(r) {
		this.input.value = '';
		this.form.down('#loader').hide();

		if ($(this.iframe.contentWindow.document.body).select('.photo').length < 4)
			this.input.enable();				
	}
});

PREX.PhotosViewer = Class.create({
	initialize: function(container) {
		var $this = this;
		
		this.container = $(container);
		this.links = this.container.select('.photo-viewer-thumb-link');
		
		this.links.each(function(a) {
			a.observe('click', $this.thumbListener.bindAsEventListener($this, a));
		})
		
		if (this.links)
			this.selectThumb(this.links[0]);
	},
	
	thumbListener: function(e, a) {
		e.stop();
		this.container.down('.photo-viewer-stage').src = a.href;
		this.selectThumb(a);		
	},
	
	selectThumb: function(a) {
		this.links.each(function(l) {
			if (l == a)
				l.down('img').addClassName('selected');
			else
				l.down('img').removeClassName('selected');
		});
	}
});

PREX.Template = Class.create(Template, {
	initialize: function($super, template) {
		$super(template, /(^|.|\r|\n)(%%\s*(\w+)\s*%%)/);
	}
});

PREX.AmazonProductLoader = Class.create({
	initialize: function(el) {
		this.el = el;
		
		new Ajax.Request(_ABS_PATH + 'ajax/aws/product.php?id=' + el.readAttribute('data-product-id'), {
			onSuccess: this.responseHandler.bind(this)
		});
	},
	
	responseHandler: function(t) {
		var data = t.responseJSON || [];

		if (!data[0]) 
			return;
		
		var tpl 	= new PREX.Template(this.el.innerHTML);
		var vars 	= data[0];
		
		vars['url'] = encodeURIComponent(vars['url']) 
		
		this.el.update(tpl.evaluate(vars));
		
		PREX.applyDefaults(this.el);
		
		new Effect.Appear(this.el);
	}
});

