var LSS = {
	options: {
		updateSort: function(sortable_id, group) {
			return Intersect.updateSort(sortable_id,'/admin/options/'+group+'/update_sort');
		}
	},
	ratings: {

	},
	items_form: {
		blank_id: "blank_item_form",
		items_table: "items_fields",
		num_field: "num_items",
		addFields: function(how_many) {
			var current_num = parseInt($F(this.num_field));
			how_many.times(function (i) {
				this.insertItemFields(current_num + i);
			}.bind(this))
		},
		insertItemFields: function(num)  {
 			var new_blank_el = $(this.blank_id).down(2).cloneNode(true);
			$(new_blank_el).select('input, select').each(function(el) {
				el.name = el.name.replace('-1',num);
				el.id = el.id.replace('-1',num);
			});
			$(this.items_table).insert(new_blank_el);
		}
	},
	other_options: {
		other_select_class: 'select_with_other',
		other_field_template: '<input type="text" name="#{name}" value="Other" style="width:93%;"/>',
		initialize: function() {
			$$('select.'+this.other_select_class).each(function(el) {
				el.observe('change', function(e) {
					if ($F(el) == '!') {
						this.addOtherOptionField(el);
					}
				}.bind(this));
			}.bind(this));
		},
		addOtherOptionField: function(select_element) {
			select_element = $(select_element);
			var select_name = select_element.name;
			var select_name_parts = select_name.split(/\]\[/);
			var other_field_name = select_name_parts[0] + "[" + select_name_parts[1] + "][" + select_name_parts[2].replace(/id/,'other');
			select_element.hide();
			select_element.insert({after: this.other_field_template.interpolate({name: other_field_name})});
		}
	},
	overlay: {
		initialize: function() {
			$$('.overlay_link').each(function(el) {
				el.observe('click', 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);
					Event.stop(e);
				})
			});
		}
	},
	mini_browser: {
		mini_browser_id: 'mini_browser',
		form_id: 'mini_browser_form',
		loading_id: 'mini_browser_loading',
		base_url: '/looks/browse',
		initialize: function() {
			this.resetPaginationLinks();
		},
		load: function() {
			if (!$(this.mini_browser_id)) return;
			this.base_url = $(this.form_id).action;
			this.getContent(this.base_url);
			this.setFormSubmit();
		},
		getContent: function(url, params) {
			return new Ajax.Request(url,
				{ method: 'get',	
					evalScripts:true,
					parameters: params,
					onLoading: function () { this.showLoading(); }.bind(this),
					onComplete: function () { this.hideLoading(); }.bind(this) 
				});
		},
		resetPaginationLinks: function() {
			$(this.mini_browser_id).select('.pagination a.pagination_link').each(function (el) {
				el.observe('click', function (e) {
					Event.stop(e);
					this.getContent(el.href);
				}.bind(this));
			}.bind(this));
		},
		setFormSubmit: function () {
			$(this.mini_browser_id + '_form').observe('submit', function(e) {
				Event.stop(e);
				this.getContent(this.base_url,Form.serialize(Event.element(e)));
			}.bind(this));
		},
		showLoading: function () {
			$(this.loading_id).show();
		},
		hideLoading: function () {
			$(this.loading_id).hide();
		}
	}
}

var Overlay = Class.create();
Overlay.prototype = {
	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) {
		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.5});
		this.overlay().fade({duration: 0.7});
		$$('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 Rater = Class.create();
Rater.prototype = {
	button_class: 'rating_button',
	initialize: function(holder) {
		this.element = $(holder);
		this.buttons = [];
		this.initializeButtons();
	},
	initializeButtons: function() {
		$A($(this.element).select('.rating_button')).each(function(elem, index) {
			this.buttons.push(new Rater.Button(elem,index + 1));
		}.bind(this));
	}	
};
Rater.Button = Class.create();
Rater.Button.prototype = {
	off_image: "ratings_off_white.gif",
	greater_image: "ratings_off_magenta.gif",
  on_image: "ratings_on_#{value}.gif",
	class_prefix: "rating_button_image_",
	on: false,
	greater: false,
	initialize: function(button_element, value) {
		this.element = $(button_element);
		this.img = this.element.select('input[type=image]').first();
		this.link = this.element.select('a').first();
		this.value = value;
		this.state = $A(this.img.classNames()).first().gsub(this.class_prefix, '');
		if (this.state == "greater") {
			this.greater = true;
		}
		if (this.state == "on") {
			this.on = true;
		}
		this.img.observe('mouseover',this.hoverOn.bindAsEventListener(this));
		this.img.observe('mouseout',this.hoverOut.bindAsEventListener(this));
		this.img.observe('click',this.click.bindAsEventListener(this));
	},
	
	hoverOn: function() {
		Intersect.images.swap(this.img,this.image_path('on'));
	},
	hoverOut: function() {
		var out_state = this.greater ? 'greater' : 'off';
		Intersect.images.swap(this.img,this.image_path(out_state));
	},
	click: function(e) {
		////console.log(this);
		////console.log(e);
		if (!this.link.hasClassName('overlay_link')) {
			Event.stop(e);
			Intersect.appRequest(this.link.href);
		}
/*		return false;*/
	},
	image_path: function(state) {
		return "/images/" + this[state + "_image"].interpolate({'value': this.value});
	}
}

var MiniRater = Class.create();
MiniRater.prototype = {
	button_class: 'mini_rating_button',
	initialize: function(holder) {
		this.element = $(holder);
		this.buttons = [];
		this.initializeButtons();
	},
	initializeButtons: function() {
		$A($(this.element).select('.mini_rating_button')).each(function(elem, index) {
			this.buttons.push(new MiniRater.Button(elem,index + 1));
		}.bind(this));
	}	
};
MiniRater.Button = Class.create();
MiniRater.Button.prototype = {
	off_image: "mini_ratings_off_white.gif",
	greater_image: "mini_ratings_off_magenta.gif",
  on_image: "mini_ratings_on_#{value}.gif",
	class_prefix: "mini_rating_button_image_",
	on: false,
	greater: false,
	initialize: function(button_element, value) {
		this.element = $(button_element);
		this.img = this.element.select('input[type=image]').first();
		this.link = this.element.select('a').first();
		this.value = value;
		this.state = $A(this.img.classNames()).first().gsub(this.class_prefix, '');
		if (this.state == "greater") {
			this.greater = true;
		}
		if (this.state == "on") {
			this.on = true;
		}
		this.img.observe('mouseover',this.hoverOn.bindAsEventListener(this));
		this.img.observe('mouseout',this.hoverOut.bindAsEventListener(this));
		this.img.observe('click',this.click.bindAsEventListener(this));
	},
	
	hoverOn: function() {
		Intersect.images.swap(this.img,this.image_path('on'));
	},
	hoverOut: function() {
		var out_state = this.greater ? 'greater' : 'off';
		Intersect.images.swap(this.img,this.image_path(out_state));
	},
	click: function(e) {
		////console.log(this);
		////console.log(e);
		if (!this.link.hasClassName('overlay_link')) {
			Event.stop(e);
			Intersect.appRequest(this.link.href);
		}
/*		return false;*/
	},
	image_path: function(state) {
		return "/images/" + this[state + "_image"].interpolate({'value': this.value});
	}
}



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 this.appRequest(url,params,'get').transport.responseText;
	},
	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) {
			////console.log(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;
	},
	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;
	}
	
});

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;
}



Event.observe(window,'load',function () { 
	LSS.overlay.initialize(); 
	LSS.mini_browser.load();
	LSS.other_options.initialize();
});

function fbs_click() {
  u = location.href;
  t = document.title;
  window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
  return false;
}



$j(function() {
  $j('.nav_img').hover(
    function() {
      if ($j(this).attr('src').match(/_off/)) {
        $j(this).attr('src', $j(this).attr('src').replace(/_off/, '_hover'));
      }
    },
    function() {
      if ($j(this).attr('src').match(/_hover/)) {
        $j(this).attr('src', $j(this).attr('src').replace(/_hover/, '_off'));
      }
    });
});
