// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var Ecom = {
	initialize: function() {
		Ecom.overlay.initialize();
		Ecom.options.initialize();
	},
	popup: function (link,title,width,height) {
		return window.open(link,title,"height="+height+",width="+width+",status=no,toolbar=no,menubar=no,location=no");
	},
	inventory: {
		add: function(field) {
			return this.increment(field,1);
		},
		subtract: function(field) {
			return this.increment(field,-1);
		},
		increment: function(field,num) {
			var current_val = parseInt($F(field));
			var new_val = current_val;
			if ((current_val + num) < 0) {
				new_val = 0;
			} else {
				new_val = current_val + num;
			}
			$(field).value = new_val;
			return new_val;
		}
	},
	item: {
		detailImages: {
			current_image: 0,
			swap: function(to_num) {
				// hide current
				this.image(this.current_image).hide();
				this.thumb(this.current_image).show();
				//show to
				this.image(to_num).show();
				this.thumb(to_num).hide();
				this.current_image = to_num;
			},
			image: function(num) {
				return $('item_photo_'+num);
			},
			thumb: function(num) {
				return $('item_photo_thumb_'+num);
			}
		}
	},
	overlay: {
		overlays: {},
		initialize: function() {
			$$('.overlay_link').each(function(el) {
				el.onclick = function(e) {
					var overlay = new Overlay(el.rel,el.href);
					var pointer_y = e.pointerY();
					var scroll_top = document.viewport.getScrollOffsets()['top'];
					overlay.open((pointer_y + scroll_top)/2);
					Ecom.overlay.overlays[el.rel] = overlay;
					Event.stop(e);
				}
			});
		}
	},
	options: {
		options_id: 'option_group_selector_#{id}_options',
		select_class: '.option_group_select',
		initialize: function () {
			$$(this.select_class).each(function (el,i) {
				el.observe('change', function () {
					Ecom.options.loadForGroup(i+1,$F(el));
					Ecom.options.toggleEditOptionGroup('edit_option_group_'+(i+1),el);
				});
				Ecom.options.loadForGroup(i+1,$F(el));
				Ecom.options.toggleEditOptionGroup('edit_option_group_'+(i+1),el);
			});
		},
		loadForGroup: function(id, group_id) {
			if (!id || !group_id) return $(this.options_id.interpolate({id:id})).update('');
			new Ajax.Updater(this.options_id.interpolate({id:id}),
											'/admin/option_groups/' + group_id + '/options', {method: 'get', onComplete: Ecom.overlay.initialize})
		},
		toggleEditOptionGroup: function(edit_link_el, select_el) {
			if ($F(select_el) != "") {
				$(edit_link_el).show().href = '/admin/option_groups/'+ $F(select_el) + '/edit';
			} else {
				$(edit_link_el).hide();
			}
		}
	},
	categories: {
		updateSort: function() {
			Intersect.updateSort('categories','/admin/categories/update_sort');
		},
		addToFormSelect: function() {
			var selector = $('categories').select('p').first().cloneNode(true);
			$A(selector.select('select').first().options).first().selected = "selected";
			$('categories').insert(selector);
		} 
	},
	promos: {
		updateSort: function(sortable_id, promo_type) {
			return Intersect.updateSort(sortable_id,'/admin/promos/'+promo_type+'/update_sort');
		}
	}
};

Event.observe(window, 'load', function () {
	Ecom.initialize();
});

var Overlay = Class.create({
	overlay_id: 'overlay',
	holder_id: 'overlay_holder',
	box_class: 'overlay_box',
	close_image: '/images/button_close.gif',
	overlay_box: null,
	initialize: function(id, url, params, method) {
		this.id = id;
		this.url = url;
		this.params = (params == undefined) ? {} : method;
		this.params['_overlay'] = true;
		this.method = (method == undefined) ? 'get' : method;
	},
	build: function(content) {
		if (this.overlay_box != undefined) { this.overlay_box.show(); }
		this.overlay_box = new Element('div', {'id': this.id + '_overlay', 'class':this.box_class});
		this.close_button = new Element('img', {'class':'overlay_close', 'src':this.close_image});
		this.close_button.observe('click', this.close.bindAsEventListener(this));
		this.overlay_box.insert(this.close_button);
		this.overlay_box.insert(content);
		this.holder().insert(this.overlay_box);
	},
	open: function(at_y) {
		if (this.url.strip() == "#" || this.url.strip() == "") return false;
		this.expand();
		new Ajax.Request(this.url,
			{ 
			method: this.method,
			evalScripts:true, 
			parameters: this.params,
			onSuccess: function (or) {
				this.show();
				this.build(or.responseText);
				if (at_y != undefined) { this.overlay_box.style.top = at_y + "px"; }
			}.bind(this)
		});
	},
	show: function() {
		$$('select').each(Element.hide);
		this.overlay().show();
	},
	close: function() {
		$(this.overlay_box).fade({duration: 0.2, fps: 50});
		this.overlay().fade({duration: 0.3, fps: 50});
		$$('select').each(Element.show);
	},
	expand: function () {
		var arrayPageSize = getPageSize();
		this.overlay().setHeight(arrayPageSize[1]);
	},
	holder: function() {
		if ($(this.holder_id) != undefined) return $(this.holder_id);
		this.overlay_holder_element = new Element('div', {'id': this.holder_id});
		document.getElementsByTagName('body')[0].appendChild(this.overlay_holder_element);
		return this.overlay_holder_element;
	},
	overlay: function() {
		if ($(this.overlay_id)) { return $(this.overlay_id) }
		else {
			this.overlay_element = new Element('div', {'id': this.overlay_id});
			document.getElementsByTagName('body')[0].appendChild(this.overlay_element);
			return this.overlay_element;
		}
	}
});




var Intersect = {
	appRequest: function(url,params, method) {
		if (!method) {method = 'post';}
		return new Ajax.Request(url,{ method: method,	evalScripts:true, parameters: params });
	},
	jsonRequest: function(url,params) {
		return new Ajax.Request(url,{ method: 'get',	evalScripts:true, parameters: params, onSuccess: function(or) { return or.responseText.evalJSON(); } });
	},
	updateSort: function(sortable_id,url) {
		this.appRequest(url,Sortable.serialize(sortable_id));
	},
	scrollTo: function(el) {
		new Effect.ScrollTo(el, {duration: 0.5, fps: 30});
	},
	popup: function (link,title,width,height) {
		return window.open(link,title,"height="+height+",width="+width+",status=no,toolbar=no,menubar=no,location=no");
	},
	html: {
		simpleSelect: function(name,id,options,current) {
			var ht = "<select name=\"#{name}\" id=\"#{id}\">";
	    options.each(function(option) {
				var option_text = "";
	      if (typeof(option) == 'object') {
	        option_text += "<option value=\"#{value}\"";
	        if (option[1] == current) { option_text += "selected=\"selected\""}
	        option_text += ">#{name}</option>";
					ht += option_text.interpolate({name: option[0], value: option[1]});
	      } else {
					option_text += "<option value=\"#{option}\"";
	        if (option == current) { option_text += "selected=\"selected\"" }; 
	        option_text += ">#{option}</option>"
					ht += option_text.interpolate({option: option});
				}
			});
	    ht += "</select>";
			return ht.interpolate({name:name,id:id});
		}
	},
	copyTextToClipboard: function(text) {
		// create form element
		var form_element = $('clipboard_holder') ? $('clipboard_holder') : new Element('input',{'type':'hidden','id':'clipboard_holder','name':'clipboard_holder','value':text});
	  if (form_element.createTextRange) {
	    var range = form_element.createTextRange();
	    if (range && BodyLoaded==1)
	     range.execCommand('Copy');
	  } else {
	    var flashcopier = $('flashcopier') ? $('flashcopier') : new Element('div',{id: 'flashcopier'});
			$(flashcopier).innerHTML = '<embed src="/swf/_clipboard.swf" FlashVars="clipboard='+escape(form_element.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
			document.body.appendChild(flashcopier);
	 }
	},
	images: {
		swap: function(for_el,to) {
			$(for_el).src = to;
		},
		activate: function (for_el) {
			return this.swap(for_el,this.activateSrc(for_el));
		},
		deactivate: function (for_el) {
			return this.swap(for_el,this.deactivateSrc(for_el));		
		},
		hover: function (for_el) {
			return this.swap(for_el,this.hoverSrc(for_el));
		},
		replaceSrc: function (for_el,search,replace_with) {
			return $(for_el).src.replace(search,replace_with);
		},
		activateSrc: function (for_el) {
			return this.replaceSrc(for_el,/_off/,'_on');
		},
		deactivateSrc: function (for_el) {
			return this.replaceSrc(for_el,/_on/,'_off');
		},
		hoverSrc: function (for_el) {
			return this.replaceSrc(for_el,/_off/,'_on');
		},
		restore: function (for_el) {
			MM_swapImgRestore();
		}
	}
};

Element.addMethods({
	toggleClass: function(elem,css) { 
		if (Element.hasClassName(elem,css)) {
			Element.removeClassName(elem,css);
		} else {
			Element.addClassName(elem,css);
		}
	},
	setHeight: function(elem,h) {
   		elem = $(elem);
    	elem.style.height = h +"px";
	},
	setZ: function (elem,z) {
		$(elem).style.zIndex = z;
	},
	cycleClass: function(elem,on,off) {
		if (!cycles[on + '_' + off] == undefined) {
			if (cycles[on + '_' + off] == on) {
				elem.addClassName(off);
			} else {
				elem.addClassName(on);
			}
		} else {
			cycles[on + '_' + off] = on;
			elem.addClassName(on);
		}
		return elem;
	},
	toggleValue: function(elem,value_1, value_2) {
		elem = $(elem);
		if (elem.value == value_1) {
			elem.value = value_2;
		} else {
			elem.value = value_1;
		}
		return elem;
	}
	
});

var Slideshow = Class.create();
Slideshow.prototype = {
		current: 0,
		image_id: "slideshow",
		paused: false,
		cycle_time: 4,
		close_time: 1,
		open_time: 1,
		initialize: function(image_id, slides) {
			this.image_id = image_id;
			this.slides = slides;
			if (this.slides.length < 1) {
				return;
			}
			this.preloadSlides(slides);
			$(this.image_id).insert(this.image_html(this.current_slide()));
			this.startup();
		},
		preloadSlides: function(slides) {
			$A(slides).each(function (el,index) {
				MM_preloadImages(el.public_url);
			});
		},
		startup: function() { 
			new PeriodicalExecuter(function(pe) {
				if (this.paused) {
					pe.stop();
				} else {
					this.go();
				}
			}.bind(this), this.cycle_time);
		},
		current_slide: function() {
			return this.slides[this.current];
		},
		prev_id: function() {
			var prev = this.current-1;
			if (prev < 0) {
				prev = this.slides.length-1;
			}
			return prev;
		},
		next_id: function() {
			var next = this.current+1;
			if (next > this.slides.length-1) {
				next = 0;
			}
/*			alert(next);*/
			return next;
		},
		next: function () {
			this.pause();
			this.go();
			return false;
		},
		prev: function () {
			this.pause();
			this.current = this.prev_id();
			this.goToCurrent();
			return false;
		},
		go: function(slide_id, witheffect) {
			if (slide_id != undefined) {
				this.current = slide_id;
			} else {
				this.current = this.next_id();
			}
			this.goToCurrent(witheffect);
		},
		cycle: function(htid, newcontent, witheffect) { 
			if (witheffect != undefined && witheffect == false) {
					$(htid).update(newcontent);
			} else {
				this.closeEffect(htid, { 
								duration: this.close_time, 
								fps: 24,
								afterFinish: function() {
										$(htid).update(newcontent);
										this.openEffect(htid, { duration: this.open_time,	fps: 24, queue:'end'}); 
								}.bind(this)
						});
			}	
		},
		pause: function(pause_for) {
			this.paused = true;
		},
		goToCurrent: function(witheffect) {
			//cycle image
			this.cycle(this.image_id,this.image_html(this.current_slide()),witheffect);
/*			this.selectCurrentPager();*/
		},
		image_html: function(slide) {
			var html = "";
			if (slide.url != "") { html += "<a href=\""+slide.url+"\">";	}
			html += "<img src=\""+slide.public_url+"\" alt=\""+slide.title+"\" />";
			if (slide.url != "") { html += "</a>"; }
			return html;
		},
		openEffect: Effect.Appear,
		closeEffect: Effect.Fade
};

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}