
if(Prototype.Browser.Gecko || Prototype.Browser.WebKit) {
	HTMLElement.prototype.click = function() {
		var evt = this.ownerDocument.createEvent('MouseEvents');
		evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
		this.dispatchEvent(evt);
	}
}

Event.observe(document, 'contentloaded', init);

function init() {return;}

var Em = {};
Em.Base = function() {};
Em.Base.prototype = {
	baseInitialize: function(wrapper, options) {
		this.wrapper 	 = $(wrapper);
		this.scrolling 	 = false;
		
		if(this.setOptions) this.setOptions(options);
			else this.options = options || {};
		
		this.events = {
			click: this.click.bindAsEventListener(this)
		};
		
		this.transition = function(pos) {
			if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,4);
			return -0.5 * ((pos-=2)*Math.pow(pos,3) - 2);    
		};
	},
	
	/*
	 * this builds a *real* HTML entity string based on Em.ENTITIES object. 
	 * avoids any escaping of the characters in the actual entity itself:
	 * '&amp;nbsp;' instead of '&nbsp;'. takes a space-delimited string of 
	 * character codes... '38 35 65 77 80 59' -> '&amp;'
	 */
	createEntityString: function(ent){
		var s = $w(ent).inject([], function(array, n, index){
			array.push(String.fromCharCode(n).toLowerCase());
			return array;
		});
		return s.join('');
	},
	moveTo: function(element, container, options){
		this.current = $(element);
		
		var containerOffset = container.cumulativeOffset();
		elementOffset = $(element).cumulativeOffset();
		
		/*Position.prepare();
		var containerOffset = Position.cumulativeOffset(container),
		elementOffset = Position.cumulativeOffset($(element));*/
	
		this.scrolling 	= new Effect.SmoothScroll(container, {
			duration:options.duration, 
			x:(elementOffset[0]-containerOffset[0]), 
			y:(elementOffset[1]-containerOffset[1]),
			beforeStart:this.updateNav.bind(this)
		});

		return false;
	},
	stop: function(){
		clearTimeout(this.timer);
	}
};

Em.Genres = Class.create();
Object.extend(Object.extend(Em.Genres.prototype, Em.Base.prototype), {
	initialize: function(wrapper, options){
		this.baseInitialize(wrapper, options);
		this.title = this.options.title;
		this.categoryURL = this.options.categoryURL;
		this.styleURL = this.options.styleURL;
		this.mode = this.options.mode;
		this.initializeContainer();
		Object.extend(this.events,{
			revealChildGenres: this.revealChildGenres.bindAsEventListener(this),
			toggleGenreState: this.toggleGenreState.bindAsEventListener(this)
		});
		this.arrayOfSelectedElements = [];
		this.Genres = [];
		this.savedSelectionsInProfile = '';
		this.populatingSelected = 0;
		//this.selectionsBody = (this.mode=='profile') ? $('selectionsBody') : $('selectionsBody').appendChild($ul());
		this.selectionsBody = $('selectionsBody');
	},
	alertAjaxFailure: function(){
		alert('Por alguna razón, la página no pudo cargarse correctamente. Por favor intenta de nuevo más tarde.');
	},
	click: function(event){
		Event.stop(event);
		return false;
	},
	initializeContainer: function(){
		var div1 = $div({'id':'parentList'});
		var div2 = $div({'id':'childList'});
		this.wrapper.appendChild(div1);
		this.wrapper.appendChild(div2);
		this.parentList = div1;
		this.childList = div2;
		this.loadParentGenres();
	},
	getChildGenres: function(pos){
		pid = this.Genres[pos].id;
		
		if(this.childList.select('div.childColumn')){
			this.childList.select('div.childClass').invoke('remove');
			this.childList.select('div.childColumn').invoke('remove');
		}
		
		var loadingMsg = 'Loading...';
		var loadingDiv = $div({'class':'childColumn clearfloats'}).appendText(loadingMsg);
		
		if(!this.Genres[pos].styles){
			var url = this.styleURL;
			var params = {genreId:pid};
			new Ajax.Request(
				url, {
					method: 'get',
					parameters: params,
					onCreate: function(){this.childList.appendChild(loadingDiv)}.bind(this),
					onSuccess: this.loadChildGenres.bind(this),
					onFailure: this.alertAjaxFailure.bind(this)
				}
			);
		} else {
			this.showChildGenres();
		}
	},
	loadChildGenres: function(transport){
	
		if(this.childList.select('div.childColumn')){
			this.childList.select('div.childClass').invoke('remove');
			this.childList.select('div.childColumn').invoke('remove');
		}
	
		var resp = transport.responseXML;
		var childDocRoot = resp.documentElement;
		var parent = this.Genres[this.selectedParentPosition];
		Object.extend(parent,{styles:[]});
		
		var itemsArray = [];
		/*if (this.mode == 'flat'){
			__pGenre = childDocRoot.getElementsByTagName('genre')[0];
			__id = __pGenre.attributes.getNamedItem('fluxId').value;
			__name = __pGenre.firstChild.data;
			itemsArray.push({'name':__name, 'id':__id});
		}*/
		var childItems = $A(childDocRoot.getElementsByTagName('style')).inject(itemsArray, function(array, s, index){
			var id = s.attributes.getNamedItem('fluxId').value;
			var name = s.firstChild.data;
			array.push({'name':name, 'id':id});
			return array || [];
		}.bind(this));
		parent.styles = childItems;
		this.showChildGenres();
	},
	loadParentGenres: function(){
		var url = this.categoryURL;
		
		var loadingMsg = 'Cargando...';
		var loadingDiv = $div({'class':'clearfloats'}).appendText(loadingMsg);
					
		new Ajax.Request(
			url, {
				method: 'get',
				onCreate: function(){this.parentList.appendChild(loadingDiv)}.bind(this),
				onSuccess: this.showParentGenres.bind(this),
				onFailure: this.alertAjaxFailure.bind(this)
			}
		);
	},
	revealChildGenres: function(event){
		var el = getEventTarget(event);
		//var el = Event.element(event);
		el = $(el);

		//var msg = '<strong>'+el.innerHTML+' Styles</strong> (Click to select or remove)';
		var msg = 'Estilos de ' + el.innerHTML;
		if(this.selectedParent){
			if(this.selectedParent == el) return
				else this.selectedParent.removeClassName('selected');
		}
		$('current').update(msg);
		var pos = el.id.split('_')[1];
		this.selectedParentPosition = parseInt(pos);
		el.addClassName('selected');
		this.selectedParent = el;
		this.getChildGenres(pos);
	},
	showChildGenres: function(){
		var parent = this.Genres[this.selectedParentPosition];
		var styles = parent.styles;
		var grouping = this.options.columnHeight;
		var childDivs = $A(styles).inject([], function(array, s, index){
			var div = $div({'id':'c_'+s.id, 'class':'childClass'}).appendText(s.name);
			if(this.arrayOfSelectedElements){
				var test = this.arrayOfSelectedElements.find(function(pair){
					return (parseInt(pair.id) === parseInt(s.id));
				});
				if(test) div.addClassName('selected');
			}
			array.push(div);
			return array || [];
		}.bind(this));
		$A(childDivs).eachSlice(grouping, function(divs, index){
			//if (this.mode=='profile')
				divs.invoke('observe', 'click', this.events.toggleGenreState);
			//else
			//	divs.invoke('observe', 'click', this.events.toggleGenreStateFlat);
			var cntnr = $div({'class':'childColumn clearfloats'});
			divs.each(function(div){cntnr.appendChild(div);});
			this.childList.appendChild(cntnr);
		}.bind(this));
	},
	showParentGenres: function(transport){
		var resp = transport.responseXML;
		var list = [];
		var parentDocRoot = resp.documentElement;
		var parentDivs = $A(parentDocRoot.getElementsByTagName('genre')).inject([], function(array, genre, index){
			var gname = genre.firstChild.data;
			var gid = genre.attributes.getNamedItem('id').value;
			var fluxId = genre.attributes.getNamedItem('fluxId').value;
			this.Genres.push({
				name:gname, 
				id:gid,
				fid:fluxId
			});
			var div = $div({'class':'parentClass', 'id':'p_'+index}).appendText(gname);
			array.push(div);
			return array || [];
		}.bind(this));
		
		this.parentList.update();
		$A(parentDivs).each(function(div){
			div.onclick = this.events.revealChildGenres;
			//div.onclick = this.revealChildGenres(event,div).bind(this)
			this.parentList.appendChild(div);
		}.bind(this));
		this.parentDocRoot = parentDocRoot;
		
	},
	setOptions: function(options) {
		this.options    = Object.extend({
			title: 'Genres',
			columnHeight: 10,
			categoryURL: '',
			styleURL: '',
			mode: ''
		}, options || {});
	},
	/*toggleGenreStateFlat:function(event){
		var el = Event.element(event);
		var divID = 'pDIV'+this.selectedParentPosition;
		el = $(el);
		var cid = parseInt(el.id.split('_')[1]);
		var pPos = this.selectedParentPosition;
		var cdat = el.innerHTML;
		var selections = this.selectionsBody;
		el.toggleClassName('selected');
		if(this.arrayOfSelectedElements){
			if(el.hasClassName('selected')){	
				cdat = cdat.unescapeHTML();
				var li = $li({'id':'s'+cid});
				var img = $img({'src':'/sitewide/img/accounts/selected-style-bullet3.gif','border':'0','alt':'Remove','align':'absmiddle','class':'removeBtn'});
				var imgBtn = $a({'title':'Remove','href':'#','class':'selectedGenres'});
				imgBtn.onclick = function(){this.removeSelected(cid,pPos); return false;}.bind(this);
				imgBtn.appendChild(img);
				li.appendChild(imgBtn);
				li.appendChild(document.createTextNode(cdat));
				selections.appendChild(li);
				this.arrayOfSelectedElements.push({'id':cid,'name':cdat,'pid':pid});
			}else{
				selections.down('#s'+cid).remove();
				this.arrayOfSelectedElements = this.arrayOfSelectedElements.reject(function(pair){
				   return parseInt(pair.id)==parseInt(cid);
				});
				
			}
		}
	},*/
	toggleGenreState:function(event){
		var el = Event.element(event);
		var parent = this.Genres[this.selectedParentPosition];
		var pid = this.Genres[this.selectedParentPosition].id;
		var genre = parent.name;
		var fid = parent.fid;
		var ulID = 'pUL'+this.selectedParentPosition;
		var divID = 'pDIV'+this.selectedParentPosition;
		el = $(el);
		var cid = parseInt(el.id.split('_')[1]);
		var pPos = this.selectedParentPosition;
		var cdat = el.innerHTML;
		var selections = this.selectionsBody;
		el.toggleClassName('selected');
		if(this.arrayOfSelectedElements){
			if(el.hasClassName('selected')){
				//if (this.mode=='profile'){
					var selectionsList = (selections.down('#'+ulID)) ? selections.down('#'+ulID) : selections.appendChild($ul({'id':ulID}));
					if(!selectionsList.down('#'+divID)){
						var div = $div({'id':divID,'class':'genreHead'}).appendText(genre);
						selectionsList.appendChild(div);
					}
				//}
				cdat = cdat.unescapeHTML();
				//var li = $li({'id':'s'+cid}).appendText(cdat);
				var li = $li({'id':'s'+cid});
				var img = $img({'src':'/sitewide/img/accounts/selected-style-bullet3.gif','border':'0','alt':'Remove','align':'absmiddle','class':'removeBtn'});
				var imgBtn = $a({'title':'Remove','href':'#','class':'selectedGenres'});
				imgBtn.onclick = function(){this.removeSelected(cid,pPos); return false;}.bind(this);
				imgBtn.appendChild(img);
				li.appendChild(imgBtn);
				li.appendChild(document.createTextNode(cdat));
				selectionsList.appendChild(li);
				//this.arrayOfSelectedElements.push({'id':cid,'name':cdat,'pid':pid});
				this.arrayOfSelectedElements.push({'id':cid,'name':cdat,'pid':pid,'fid':fid});
			}else{
				selections.down('#s'+cid).remove();
				if(selections.down('#'+ulID).select('li').length<1){
					selections.down('#'+divID).remove();
					selections.down('#'+ulID).remove();
				};
				this.arrayOfSelectedElements = this.arrayOfSelectedElements.reject(function(pair){
				   return parseInt(pair.id)==parseInt(cid);
				});
				
			}
		}
	},
	removeSelected:function(c_id,parentPos){
		//alert(c_id + "," + parentPos);
		var _el = $("c_"+c_id);
		var cid = c_id;
		var ulID = 'pUL'+parentPos;
		var divID = 'pDIV'+parentPos;
		var selections = this.selectionsBody;
		if (_el) _el.toggleClassName('selected');
		if(this.arrayOfSelectedElements){
			selections.down('#s'+cid).remove();
			//if (this.mode=='profile'){
				if(selections.down('#'+ulID).select('li').length<1){
					selections.down('#'+divID).remove();
					selections.down('#'+ulID).remove();
				};
			//}
			this.arrayOfSelectedElements = this.arrayOfSelectedElements.reject(function(pair){
			   return parseInt(pair.id)==parseInt(cid);
			});
		}
	},
	/*populateSelectionsWithIDs: function(arr){ // with comma separated values
		var selections = this.selectionsBody;
		var catList = '';
		var getAllCatURL = "/sitewide/dataservices/getAllCategories.jhtml?mode=flat";
		var getAllCatReq = new Ajax.Request(getAllCatURL, {
			method: 'get',
			contentType: 'text/xml',
			onCreate: function(){
				selections.update('<em>Loading...</em>');
			},
			onSuccess: function(transport) {
				selections.update();
				xml = transport.responseXML;
				catList = xml.documentElement;
				var _styles = $A(catList.getElementsByTagName('style'));
				
				var selectionsList = selections.appendChild($ul());
				$(arr).each(function(i){
					var _style = _styles.find(function(st){return st.attributes.getNamedItem('fluxId').value==i});
					var text = _style.firstChild.data.unescapeHTML();
					var li = $li({'id':'s'+i});
					var img = $img({'src':'/sitewide/img/accounts/selected-style-bullet3.gif','border':'0','alt':'Remove','align':'absmiddle','class':'removeBtn'});
					var imgBtn = $a({'title':'Remove','href':'#','class':'selectedGenres'});
					imgBtn.onclick = function(){$G.removeSelected(i,0); return false;}.bind(this);
					imgBtn.appendChild(img);
					li.appendChild(imgBtn);
					li.appendChild(document.createTextNode(text));
					selectionsList.appendChild(li);
					$G.arrayOfSelectedElements.push({'id':i,'name':text})
				});
			},
			onFailure: function(transport) {
				selections.update('<em>Loading selected genres failed, please try again later.</em>');
				return false;
			}
		});
	},*/
	populateSelectionsWithIDs: function(arr){ // with comma separated values
		var selections = this.selectionsBody;
		var catList = '';
		var getAllCatURL = "/sitewide/dataservices/getAllCategories.jhtml";
		var getAllCatReq = new Ajax.Request(getAllCatURL, {
			method: 'get',
			contentType: 'text/xml',
			onCreate: function(){
				selections.update('<em>Cargando...</em>');
			},
			onSuccess: function(transport) {
				selections.update();
				xml = transport.responseXML;
				catList = xml.documentElement;
				var _styles = $A(catList.getElementsByTagName('style'));
				
				$(arr).each(function(i){
					var _style = _styles.find(function(st){return st.attributes.getNamedItem('fluxId').value==i});
					if (_style != null){
						var text = _style.firstChild.data.unescapeHTML();
						var pid = _style.attributes.getNamedItem('parentId').value;
						var fid = _style.attributes.getNamedItem('parentFluxId').value;
						$G.arrayOfSelectedElements.push({'id':i,'name':text,'pid':pid,'fid':fid});
					}
				});

				var sortedArray = $G.arrayOfSelectedElements.sortBy(function(o){return o.fid});
				$G.Genres.each(function(genre, index){
					var id = genre.fid;
					var items = sortedArray.findAll(function(s){
						return id == s.fid;
					});
					if(items.length>0){
						var ulID = 'pUL'+index;
						var divID = 'pDIV'+index;
						var selectionsList = selections.appendChild($ul({'id':ulID}));
						var div = $div({'id':divID,'class':'genreHead'}).appendText(genre.name);
						selectionsList.appendChild(div);
						items.each(function(i){
							var text = i.name.unescapeHTML();
							var li = $li({'id':'s'+i.id});
							var img = $img({'src':'/sitewide/img/accounts/selected-style-bullet3.gif','border':'0','alt':'Remove','align':'absmiddle','class':'removeBtn'});
							var imgBtn = $a({'title':'Remove','href':'#','class':'selectedGenres'});
							imgBtn.onclick = function(){$G.removeSelected(i.id,index); return false;}.bind(this);
							imgBtn.appendChild(img);
							li.appendChild(imgBtn);
							li.appendChild(document.createTextNode(text));
							selectionsList.appendChild(li);
						});
					}						
				});
			},
			onFailure: function(transport) {
				selections.update('<em>Error al cargar la lista de estilos. Inténtalo más tarde.</em>');
				return false;
			}
		});
	},
	populateSelections: function(dl){ // with dl list
		/*var temp = document.body.appendChild($div({'id':'temp','style':'display:none;'}));
		$('temp').update(str);
		var dl = $('temp').down(0);*/
	
		this.arrayOfSelectedElements = $A(dl.childNodes).eachSlice(2, function(set){
			var id = set[0].firstChild.data;
			var name = set[1].firstChild.data;
			var pid = set[0].attributes.getNamedItem('class').value.split('_')[1];
			return {'id':id,'name':name,'pid':pid}
		});
		var selections = this.selectionsBody;
		var sortedArray = this.arrayOfSelectedElements.sortBy(function(o){return o.pid});
		this.Genres.each(function(genre, index){
			var id = genre.id;
			var items = sortedArray.findAll(function(s){
				return id == s.pid;
			});
			if(items.length>0){
				//console.log('items: '+items.length);
				var ulID = 'pUL'+index;
				var divID = 'pDIV'+index;
				var selectionsList = selections.appendChild($ul({'id':ulID}));
				var div = $div({'id':divID,'class':'genreHead'}).appendText(genre.name);
				selectionsList.appendChild(div);
				items.each(function(i){
					var text = i.name.unescapeHTML();
					var li = $li({'id':'s'+i.id});
					var img = $img({'src':'/sitewide/img/accounts/selected-style-bullet3.gif','border':'0','alt':'Remove','align':'absmiddle','class':'removeBtn'});
					var imgBtn = $a({'title':'Remove','href':'#','class':'selectedGenres'});
					//imgBtn.onclick = function(){alert('delete '+i.id);return false;};
					imgBtn.onclick = function(){$G.removeSelected(i.id,index); return false;}.bind(this);
					imgBtn.appendChild(img);
					li.appendChild(imgBtn);
					li.appendChild(document.createTextNode(text));
					selectionsList.appendChild(li);
				});
			}
				
		});
		/*this.Genres.each(function(genre){
			var items = sortedArray.findAll(function(s){return s.pid == genre.id;});
			console.log(items);
		});*/
	},
	sendSelections: function(){
		var html = [];
		html.push('<dl>');
		$A(this.arrayOfSelectedElements).inject(html, function(array, pair){
			array.push('<dt class=\'_'+pair.pid+'\'>'+pair.id+'</dt>');
			array.push('<dd>'+pair.name+'</dd>');
			return array || [];
		});
		html.push('</dl>');
		
		return html.join('');
	},
	sendSelectionsAsIds: function(){
		var ids = [];
		
		$A(this.arrayOfSelectedElements).inject(ids, function(array, pair){
			if (array.indexOf(pair.fid) < 0) array.push(pair.fid);
			array.push(pair.id);
			return array || [];
		});
		
		return ids.join();
	}
});


Em.DEFAULTS = {
	seperator : '/',
	popup: {
		name: 'popupWindow',
		features: 'width=500, height=500, left=10, top=10, scrollbars=1, toolbar=1, resizable=1, location=1',
		replace: false
	}
};

Em.ENTITIES = {
	NBSP: '38 35 49 54 48 59', 
	SP: '38 35 51 50 59', 
	AMP: '38 35 65 77 80 59',
	BULLET: '38 35 56 50 53 48 59'
};

$w('a div img p span form input select option button ul li dl dt dd').each(function(e) {
	window['$' + e] = function() {
		return new Element(e, arguments[0]);
	}
});

AjaxLoader = {
	timeUntilShow: 250,
	opacity: 0.8,

	// Start waiting status - show loading element
	startWaiting: function(element, className, timeUntilShow) {
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (className == undefined)
			className = 'waiting';
		if (timeUntilShow == undefined)
			timeUntilShow = AjaxLoader.timeUntilShow;
		
		element._waiting = true;
		if (!element._loading) {
			var e = document.createElement('div');
			(element.offsetParent || document.body).appendChild(element._loading = e);
			e.style.position = 'absolute';
			try {e.style.opacity = AjaxLoader.opacity;} catch(e) {}
			try {e.style.MozOpacity = AjaxLoader.opacity;} catch(e) {}
			try {e.style.filter = 'alpha(opacity='+Math.round(AjaxLoader.opacity * 100)+')';} catch(e) {}
			try {e.style.KhtmlOpacity = AjaxLoader.opacity;} catch(e) {}
		}
		element._loading.className = className;
		window.setTimeout((function() {
			if (this._waiting) {
				var left = this.offsetLeft, 
					top = this.offsetTop,
					width = this.offsetWidth,
					height = this.offsetHeight,
					l = this._loading;
					
				l.style.left = left+'px';
				l.style.top = top+'px';
				l.style.width = width+'px';
				l.style.height = height+'px';
				l.style.display = 'inline';
			}
		}).bind(element), timeUntilShow);
	},
	
	// Stop waiting status - hide loading element
	stopWaiting: function(element) {
		if (element._waiting) {
			element._waiting = false;
			element._loading.parentNode.removeChild(element._loading);
			element._loading = null;
		}
	}
};

/* if (Prototype) { */
Element.addMethods(AjaxLoader);
Object.extend(Element, AjaxLoader);
/*}*/


Element.addMethods({  
	appendText: function(element, text) {
		element = $(element);
		text = String.interpret(text);
		element.appendChild(document.createTextNode(text));
		return element;
	}
});


/*	abstracted to allow search from either header or within search page
	param 'inputElement' is a DOM handle for the form field we want - i.e.
	the one next to the button that was clicked.  */
function submitSearch(inputElement, searchType) {
	var paramString = "?searchTerm="+inputElement.value+"&searchType="+searchType;
	var re = /([?&])q=/gi;
	window.location = "/search/" + paramString;
}

/*	abstracted to permit easy updating of parametric search pages.
	locates all inputs with class "searchInput" and concatenates them
	into a query string. This approach may be a bit awkward if we use
	controls that do not have name and value properties... */
	
function submitParametricSearch() {
	var tmpParamString = "?";
	var searchInputs = document.getElementsByClass("searchInput");
	for ( var i=0; i < searchInputs.length; i++ ) {
		if (searchInputs[i].value != "") {
			tmpParamString += ( searchInputs[i].name + "=" + searchInputs[i].value + "&" );
		}
	}
	var re = /([?&])q=/gi;
	var paramString = tmpParamString.replace(re, "$1searchTerm=");

	window.location = "/search/" + paramString;
}



var globalControlFlag = false;

// set our controlflag if the control key is being held down
Event.observe(window, 'load', function() {
	Event.observe(document, 'keydown', function(event) { if (event.keyCode == 17) window.globalControlFlag = true; }	);
	});
		
// reset our controlflag if the control key is released
Event.observe(window, 'load', function() {
	Event.observe(document, 'keyup', function(event) { if (event.keyCode == 17) window.globalControlFlag = false; }	);
});


// start our global keypress observer
Event.observe(window, 'load', function() {
	Event.observe(document, 
				  'keypress', 
				  function(event){  
					  if (globalControlFlag) {	 
						  //alert('Key with code ' + event.keyCode + ' and CONTROL were pressed together!');
					  }
				  }
	);
});




