// 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");
	},
	addForm: function(num, from, content_type) {
		if (typeof content_type == undefined) { content_type = 'item'; }
		var params = {num: num, from: from, content_type: content_type};
		Intersect.appRequest('/admin/contents/add_form', params, 'get');
	},
	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);
			}
		}
	},
	variations: {
		variation_count: 0,
		sorting: false,
		addVariationForm: function () {
			this.variation_count++;
			Ecom.addForm(this.variation_count, 'variations');
		},
		toggleSort: function () {
			$('variations_table').toggleClassName('sorting');
			if (!this.sorting) {
				Sortable.create('variations', {tag: 'div', handle:'sort_handle'});
				this.sorting = true;
			} else {
				var sequence = Sortable.sequence('variations').without('');
				Sortable.destroy('variations');
				sequence.each(function(v, i) {
					$('item_variation_' + v).select('input').each(function(el) { 
						el.name = el.name.replace('[' + v + ']', '[' + i + ']');
					});
				});
				this.sorting = false;
			}
			return false;
		}
	},
	related_items: {
		related_items_count: 0,
		addRelatedItemForm: function (content_type) {
			this.related_items_count++;
			Ecom.addForm(this.related_items_count, 'related_items', content_type);			
		}
	},
	videos: {
		videos_count: 0,
		addVideoForm: function (content_type) {
			this.videos_count++;
			Ecom.addForm(this.videos_count, 'videos', content_type);			
		}
	},
	gated_rewards: {
		gates_count: 0,
		rewards_count: 0,
		gate_types: {},
		type_elements: {},
		addGateForm: function() {
			this.gates_count++;
			Ecom.addForm(this.gates_count, 'gated_rewards_gate', 'gated_reward');
		},
		addRewardForm: function() {
			this.rewards_count++;
			Ecom.addForm(this.rewards_count, 'gated_rewards_reward', 'gated_reward');
		},
    updateGateArgumentsForm: function(index, gateName) {
      Intersect.appRequest(
        '/admin/gated_rewards_arguments_form', 
        {parent_form_index: index, gate_or_reward: 'gate', gate_or_reward_name: gateName}, 
        'get'
      );
    },
    updateRewardArgumentsForm: function(index, rewardName) {
      Intersect.appRequest(
        '/admin/gated_rewards_arguments_form', 
        {parent_form_index: index, gate_or_reward: 'reward', gate_or_reward_name: rewardName}, 
        'get'
      );
    },
		observeGatedRewardValueField: function(index) {
			var gated_rewards = this;
			$('gated_reward_gates_' + index + '_type_name').observe('change', function(e) {
				var gate_type = $F(e.element);
				var value_type = gated_rewards.gate_types[gate_type];
				var type_element = gated_rewards.type_elements[value_type];
				if (typeof type_element != 'undefined') {
					$('gated_reward_value_' + index).update(type_element.interpolate({'index': index}));
				}
			});
		}
	},
	overlay: {
		overlays: {},
		initialize: function() {
			var overlay = this;
			$$('.overlay_link').each(function(el) {
				el.onclick = function(e) {
					e = e || window.event  // IE does not pass the event down to the function
					Event.stop(e);
					overlay.openURL(el.rel, el.href, e);
				}
			});
		},
		openURL: function(name, href, e) {
			var overlay = new Overlay(name,href);
			var pointer_y = 100;
			if (typeof e != 'undefined') {
				var pointer_y = e.pointerY();
			}
			var scroll_top = document.viewport.getScrollOffsets()['top'];
			overlay.open((pointer_y + scroll_top)/2);
			Ecom.overlay.overlays[name || 0] = overlay;
		}
	},
	categories: {
		updateSort: function(sortable_id,section_id) {
		 Intersect.updateSort(sortable_id,'/admin/categories/'+ section_id +'/update_sort');
		},
		select_num: 0,
		addToFormSelect: function(content_type) {
			this.select_num++
			var number = this.select_num;
			var selector = $('categories').select('p').first().cloneNode(true);	
			$A(selector.select('select').first().options).first().selected = "selected";
			if (number){
				selector.select('select')[0].id = 'section_select_'+number; 
				selector.select('select')[1].id = content_type + '_categories_' + number; 
				selector.select('select')[1].disabled = 'disabled'; 
				$(selector.select('select')[0]).stopObserving('change'); // stop observing event that comes with cloneNode
				selector.select('select')[0].observe('change',function(el) { Ecom.categories.replaceCategorySelection(content_type, $('section_select_'+number).value,number); });				
			}
			$('categories').insert(selector);			
		},
		replaceCategorySelection: function(content_type, section_id,selection_id) {
			Intersect.appRequest('/admin/categories/'+section_id+'/by_section/',{content_type: content_type, selection_id: selection_id}, 'get');		  
		}		
	},
	categories2: {
		updateSort: function(sortable_id,section_id) {
		 Intersect.updateSort(sortable_id,'/admin/categories/'+ section_id +'/update_sort');
		},
		select_num: new Hash(),
		addToFormSelect: function(id_suffix) {
			var number = this.select_num[id_suffix] + 1;
			this.select_num[id_suffix] = number

			var categories = $("categories_" + id_suffix);
			var section_and_category = categories.select('p').first().cloneNode(true);	

			$A(section_and_category.select('select').first().options).first().selected = "selected";
			if (number) {
				var section_box = section_and_category.select('select')[0];
				var category_box = section_and_category.select('select')[1];
				
				section_box.id = 'section2_select_' + id_suffix + '_' + number; 
				category_box.id = 'category2_select_' + id_suffix + '_' + number; 
				category_box.disabled = 'disabled';
				
				section_box.stopObserving('change'); // stop observing event that comes with cloneNode
				section_box.observe('change', function(el) {
					Ecom.categories2.replaceCategorySelection(section_box, category_box);
				});
			}
			categories.insert(section_and_category);
		},
		addChangeActionToAllBoxes: function(id_suffix) {
			$("categories_" + id_suffix).select('p').each(function(section_and_category) {
				var section_box = section_and_category.select('select')[0];
				var category_box = section_and_category.select('select')[1];

				section_box.stopObserving('change'); // Just in case
				section_box.observe('change', function(el) {
					Ecom.categories2.replaceCategorySelection(section_box, category_box);
				});
			});
		},
		replaceCategorySelection: function(section_box, category_box) {
			Intersect.appRequest('/admin/categories/'+section_box.value+'/by_section2/',{category_select_id: category_box.id, category_select_name: category_box.name}, 'get');		  
		}		
	},
	promos: {
		updateSort: function(sortable_id, promo_type) {
			return Intersect.updateSort(sortable_id,'/admin/promos/'+promo_type+'/update_sort');
		}
	},
	tasks: {
		finished: false,
		options: {},
		initialize: function(task_id, options) {
			var tasks = this;
			if (typeof options != 'undefined') { tasks.options = options; }
			new PeriodicalExecuter(function(pe) {
				tasks.update(task_id);
				if (tasks.finished) {
					pe.stop();
				}
			}, 2);
		},
		update: function(task_id) {
			var tasks = this;
			new Ajax.Request('/admin/tasks/' + task_id + '.json', {
        method: 'get', 
        evalScripts: true,
        evalJSON: true,
        onSuccess: function(or) {
          //tasks.updateDisplay(or.responseText.evalJSON());
          tasks.updateDisplay(or.responseJSON);
        }
      });
		},
		updateDisplay: function(task) {
			if (typeof task == 'undefined') { 
				this.finished = true;
				return false; 
			} else {
        // determine the task type
        var task_type = "";
        for (var i in task) {
          if (i.endsWith("bg_task")) {
            task_type = i;
            break;
          }
        }
        task = task[task_type];
				// update message
        if (task.message) {
          var message = $(task_type + '_' + task.id + '_message');
          message.update(task.message);
          message.addClassName('task_' + task.state);
        }
				// update pct
				if (task.pct_completed) {
          var pct_bar	= $(task_type + '_' + task.id + '_pct');
					pct_bar.up().show();
					pct_bar.setStyle({'width' : task.pct_completed + '%'})
				}
				if (task.state != 'idle' && task.state != 'running') {
					this.finished = true;
					if (this.options.onComplete) {
						this.options.onComplete(this, task);
					}
				}
			}
		}
	}
};

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/admin/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;
		}
	}
});

function closeOverlays() {
	for (var key in Ecom.overlay.overlays) {
		Ecom.overlay.overlays[key].close();
	}
}

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");
	},
	urlify: function(title) {
		// self.downcase.gsub(/(_|-|\/|\\|\&|,| )/,'_')[0..40]
		return title.toString().strip().toLowerCase().gsub(/ /, '_').gsub(/[^a-z0-9\-_]/,'').truncate(40,'');
	},
	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.idnterpolate({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: {
		hover_suffix: '_on',
		active_suffix: '_on',
		deactive_suffix: '_off',
		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,this.deactive_suffix,this.active_suffix);
		},
		deactivateSrc: function (for_el) {
			return this.replaceSrc(for_el,this.active_suffix,this.deactive_suffix);
		},
		hoverSrc: function (for_el) {
			return this.replaceSrc(for_el,this.deactive_suffix,this.hover_suffix);
		},
		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;
}

function fireEvent(element,event) {
	if (document.createEventObject){
		// dispatch for IE
		var evt = document.createEventObject();
		return element.fireEvent('on'+event,evt)
	}
	else {
		// dispatch for firefox + others
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent(event, true, true ); // event type,bubbling,cancelable
		return !element.dispatchEvent(evt);
	}
}
