function findRecord(field,value,data){
	var res = false;
	if(data){
		$each(data, function(el){
			if(el[field] == value){
				res = el;
			}
		});
		return res;
	}
	
	return res;
}

function findRecords(field,value,data){
	var res = [];
	if(data){
		data.each(function(el,k){
      if(typeOf(field) == "object" && value == null){
        //Filter the data by the keys in field
        var hits = 0;

        for(key in field){
			if(Object.keys(el).contains(key) && el[key] && field[key] && el[key].search(field[key]) > -1 && typeof(field[key]) == "string")
				hits++; //Search matched
			else if(Object.keys(el).contains(key) && el[key] && field[key] && el[key] == field[key] && typeof(field[key]) == "number")
				hits++; //Allows for matching numbers specifically
			else if(Object.keys(el).contains(key) &&(!el[key] || !field[key]))
				hits++; //Allows passthrough of null values
        }

        if(hits == Object.keys(field).length)
          res.push(el); //Add the item to the stack if hits indicates that the conditions are met
      } else if(el[field] == value){
				res.push( el );
			}
		});
	}

	return res;
}

function printIt(printThis){
    win = window.open();
    self.focus();
    win.document.open();
    win.document.write('<'+'html'+'><'+'head'+'><'+'style'+'>');
    win.document.write('body, td { font-family: Verdana; font-size: 10pt;}');
    win.document.write('<'+'/'+'style'+'><'+'/'+'head'+'><'+'body'+'>');
    win.document.write(printThis);
    win.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
    win.document.close();
    win.print();
    win.close();
}

/* dynamicTable */

var dynamicTable = new Class({	
	table:null,
	id: null,	
	ds: null,
	headers:null,
	footer:null,	
	pagination:{start:0,index:0,count:25,page:1,total:null},
	parent: null,	
	Implements: [Options],
	options: {
		autorender:true,
		iclass:null,
		clear_on_update:false,
		numbering:false,
		selector: 'checkbox',
		selector_custom: null,
		selector_custom_top: null,
		selector_field: null,
		selector_name: null,
		selector_id: null,
		selector_value: null,
		selector_action: null,
		selector_label:null,
		header:true,
		footer:false,
		footer_content:'',
		pagination:null,
		pagination_class:'',
		pagination_first_class:'',
		pagination_previous_class:'',
		pagination_next_class:'',
		pagination_last_class:'',
		sorted:true,
		mouseover:'',
		mouseout:'',
		sort:false,
		zebra:true,
		zebraclass:'',
		onInitialize:null, //function(self)
		onCreationComplete:null, //function(self)
		onHeaderRender:null, //function(self, headers)
		onHeaderRendered:null, //function(self, headers)
		onPaginate: null, //function(self)
		onRowClick:null, //function(event)
		onRowDblClick:null,	//function(event)
		onRowRender:null, //function(self, row, rowIndex, rowData)
		onRowColumnRender:null, //function(self, column, row, columnIndex, columnData)
		onRender:null, //function(self)
		onRendered:null, //function(self)
		onUpdate:null //function(self)
	},
	initialize: function(id,options,headers,ds,parent){
		//Initialize the table
		this.id = id||this.id;
		this.setOptions(options);
		this.headers = headers||this.headers;
		this.ds = ds||this.ds;
		this.parent = parent||this.parent;
		this.pagination = this.options.pagination||this.pagination;
		
		//When the HTMLTable element is created reference it in base
		this.table = new HtmlTable({
			properties: {
				id:this.id,
				'class':this.options.iclass,
				border: this.options.border||0,
				cellspacing: this.options.cellspacing||0,
				cellpadding: this.options.cellpadding||0				
			},
			zebra:this.options.zebra||true,
			classZebra:this.options.zebraclass||'',
			sortable:this.options.sortable||false
			}
		);		
		
		//Fire onInitialize event
		if(this.options.onInitialize)
			this.options.onInitialize(this);
		
		if($(this.parent))
			$(this.parent).adopt(this.table);			
		
		//Fire onCreationComplete event
		if(this.options.onCreationComplete)
			this.options.onCreationComplete(this);
		
		if(this.options.autorender)
			this.render(true);
	},
	render: function(clear){		
		if(clear)
			this.table.empty();
		//Fire onRender event
		if(this.options.onRender)
			this.options.onRender(this);
			
		//Process and render the headers
		if(this.options.header && this.headers){
			var h = this.headers.clean();
			this.headers.empty();
			
			//Handle numbering
			if(this.options.numbering)
				this.headers.include('#');
			
			//Handle selector
			if(this.options.selector)
				this.headers.include("*");
			
			this.headers.combine(h);
			
			if(this.options.onHeaderRender)
				this.options.onHeaderRender(this, this.headers);
				
			if(this.options.zebra)
				this.table.setHeaders(this.headers);
			else
				this.table.headers = this.headers;
		}
		
		var he = this.table.thead.getElements('th');			
		if(he.length && this.options.sort){
			$each(he, function(h, x, d){
				if(x == 0 && this.options.selector_custom_top){
					//Do something here if needed
				} else {
					h.removeEvent('click', this.sort,false);
				
					h.addEvent('click', function (e){
						this.sort(e.target.get('title')||e.target.get('text'), null, '');
					}.bind(this));
				}
			}.bind(this));
		}
		
		//Process and render the rows
		if(this.ds){
			this.pagination.total = this.ds.length;
			var headers = this.headers;
			var x=0;
			var w=this.pagination.start;
			
			while(this.ds[x+w]){	
				//Start data handling using pagination object
				var el = this.ds[x+w];
				var i = x+w;
				if(el && x < (this.pagination.count)? this.pagination.count : this.pagination.total){
					var out = new Array(headers.length);
					var props = {};
					if(this.options.onRowRender)
						this.options.onRowRender(this, el, i, this.ds[i], props);
					
					$each(headers, function(field, index, data){
						//Handle numbering						
						if(this.options.numbering && field == '#'){
							out[index] = i+1;
						} else if(this.options.selector && field == "*"){ //Handle selector
							if(this.options.selector_custom)
								n = this.options.selector_custom;
							else
							var elem = new Element('input', {
									'type':this.options.selector,
									'name':this.options.selector_name,
									'value':el[this.options.selector_field]||this.options.selector_value,
									'onclick':this.options.selector_action,
									'class':this.options.selector_class
								});
							var node = new Element('div').adopt(elem);
							var n = node.get('html');
							//Assign the selector	
							out[index] = {content:n};
						} else {
							if(this.options.onRowColumnRender)
								out[index] = this.options.onRowColumnRender(this, field, el, index, data)||'';
							else
								out[index] = el[field]||'';
						}
					}.bind(this)); //end column data handling
					
					var row = this.table.push(out, props);

					if(row && this.options.onRowClick)
						row.tr.addEvent('click', this.options.onRowClick);
					if(row && this.options.onRowDblClick)
						row.tr.addEvent('click', this.options.onRowDblClick);
					
					//Set the pagination index
					this.pagination.index = i;//+(this.pagination.count * (this.pagination.page-1));
					
				} else {
					break;
				}
				x++;
			}; //end row data handling
			this.pagination.pages = Math.ceil( this.ds.length / this.pagination.count)||1;
		}
		
		//Once the table is rendered replace the selector field value with the custom selector if there is one.
		if(this.options.selector_custom_top && he)
			$each(he, function(el, i, d){
				el.set('title', el.get('text'));
				
				if(i == 0 && this.options.selector_custom_top && this.options.selector){
					el.set('html', this.options.selector_custom_top);
				}
			}.bind(this));
		
		if(this.options.onHeaderRendered)
			this.options.onHeaderRendered(this, he);
		
		//Fire onRendered event
		if(this.options.onRendered)
			this.options.onRendered(this);		
	},
	/* Pagination control */
	firstPage: function(){
		//Return to the first page
		this.pagination.start = 0;
		this.update();
	},
	lastPage:function(){		
		this.pagination.start = this.ds.indexOf( this.ds[ (this.ds.length - Number(this.pagination.count)) ] );
		this.update();
	},
	gotoPage:function(page){
		this.pagination.start = ((Number(page) * this.pagination.count) > this.pagination.count)? (Number(page) * this.pagination.count)-this.pagination.count:0;
		this.pagination.page = Number(page);
		this.update();
	},
	nextPage: function(){
		this.pagination.start = (this.pagination.index + 1);
		if(this.pagination.start >= this.ds.length)
			this.pagination.start = 0;
		this.update();
	},
	previousPage: function(){
		this.pagination.start = (this.pagination.start - this.pagination.count);
		/*if(this.pagination.start < 0)
			this.pagination.start = this.pagination.count */
		this.update();
	},
	/* end Pagination control */
	sort: function(field, direction, parser){
		//Sort the ds by the column and direction		
		if(this.options.onSort)
			this.options.onSort(this, this.ds, field, direction, parser||'String');
		else
			this.ds.sort(function(a, b){
				var res = 0;				
				//Convert to string to make comparison easier
				var a1 = a[field];
				var b1 = b[field];
									
				switch(typeof a1){
					case "string":
						a1 = String(a1).toLowerCase()||''; 
						b1 = String(b1).toLowerCase()||'';
						if(a1 == b1)
							res = 0;
						else if(a1 > b1)
							res = 1;
						else 
							res = -1;
						break;
					case "date": 
						res = new Date(a1) - new Date(b1);
						break;					
					case "number": 
						res = ( Number( a1 ) - Number( b1 ) ) || -1;
						break;
					case "boolean": 
						res = ( Number( a1 ) - Number( b1 ) ) || -1;
						break;
				}
				return res;
			});		
		
		this.pagination.start=0;
		this.update();
	},
	update: function(){
		if(this.options.onUpdate)
			this.options.onUpdate(this);
		this.render(this.options.clear_on_update);
	}
});

/* jsFileUploader */
var jsFileUploader = new Class({
	Implements: [Options,Events,Chain],
	id:'jsFileUploader1',
	instance:0,
	status:0,
	parent:null,
	options: {
		action:'',
		autodispose:true,
		autostart:true,
		closebtn:true,
		target:'',
		iclass:'',
		multiple:false,
		multiInstance:false,
		transition: Fx.Transitions.Quart.easeInOut,
		delay:0,
		duration:'long',
		label:'Uploader: ',
		label_style:'',
		label_class:'',
		button_label:'Go',
		button_style:'',
		button_class:'',
		iframe_class:'',
		file_name:'',
		parent:null,
		onSelectFile:null,
		onStart:null,
		onProgress:null,
		onComplete:null,
		onFailure:null
	},
	initialize: function(id,options){
		this.setOptions(options);
		this.id = (id)?id:this.id;
		this.parent = (this.options.parent)? this.options.parent:document.body;
		if(this.parent){
			this.holder = new Element('div',{id:this.id,'class':this.options.iclass});
			this.form = new Element('form',{method:'post',enctype:"multipart/form-data",action:this.options.action,target:(this.options.target)?this.options.target:this.id+'_iframe', events:{'submit':this.onStart.bind(this)}});
			this.label = new Element('label',{html:this.options.label,'style':this.options.label_style,'class':this.options.label_class});
			this.file = new Element('input',{type:'file',name:(this.options.file_name)?this.options.file_name:'userfile',multiple:this.options.multiple,'style':this.options.label_style,'class':this.options.label_class, events:{'change':this.onSelectFile.bind(this)}});
			this.button = new Element('input',{type:'submit',value:this.options.button_label,'style':this.options.button_style,'class':this.options.button_class});
			this.closebtn = new Element('input',{type:'button',value:'x','class':'dispose',events:{'click':function(){ this.holder.dispose(); }.bind(this)}});
			this.iframe = new Element('iframe',{src:'',id:this.id+'_iframe',name:this.id+'_iframe','class':this.options.iframe_class, events:{load:this.onSuccess.bind(this)}});
			this.form.adopt(this.label,this.file);
			if(!this.options.autostart)
				this.form.adopt(this.button);
			if(this.options.closebtn)
				this.form.adopt(this.closebtn);
			this.holder.adopt(this.form,this.iframe);
			this.parent.adopt(this.holder);
			this.holder.fade('in');
			this.status = 1;
		} else {
			alert('jsFileUploader: not parent present!');
			return false;
		}
	},
	onSelectFile: function(e){
		this.fireEvent('selectFile',e);
		if(this.options.autostart){
			if(this.file.value)
				this.form.submit();
		}
	},
	onStart: function(e){
		if(!this.options.autostart)
			this.button.set('disabled',true);
		this.fireEvent('start',e);
	},
	onSuccess: function(e){
		if(!this.options.autostart)
			this.button.set('disabled',false);
		var b = (this.iframe.contentDocument.body.innerHTML)?this.iframe.contentDocument.body.innerHTML.clean():null;
		if(!b) return false;
		var r = JSON.decode(b);
		/*if(r && r.message)
			alert(r.message);*/
		if(r && r.success){
			//Successful
		}
		
		this.fireEvent('complete',[this,r]);
			
		if(this.options.autodispose){
			this.holder.dispose();
			//this.dispose();
		}
	}
});

/* end jsFileUploader */

/* timeExec */

var timeExec  =  {
    setStartTime:function (){
        d = new Date();
        time  = d.getTime();
    },

    getDiff:function (){
        d = new Date();
        return (d.getTime()-time);
    }
}

/* end timeDiff */

/* jsNavi */

var jsNavi = new Class({
	Implements: [Options,Events,Chain],
	id:'jsNavi',
	parent:null,
	menu:null,
	options: {
		effect:'fade',
		delay: 3000,
		openFx: 'linear',
		closeFx: 'linear',
		'class':'',
		menu:null,
		onInitialize:null,
		onRefresh:null
	},
	initialize: function(id,options,parent){
		this.id = id||this.id;
		this.parent = $(parent)||document.body;
		this.setOptions(options);
		if(this.options.menu && this.options.menu.length){
			//Start building the dropdown menu.
			this.makeMenu(this.options.menu);
		}
		this.fireEvent('initialize',this);
	},
	makeMenu: function(nodes){
		this.fireEvent('makeMenu',[this,nodes]);
		if(nodes && nodes.length){
			//Start building the dropdown menu.
			//Check if the object already exists and create it.
			if(!this.menu)
				this.menu = new Element('ul',{id:this.id,'class':this.options['class']});
			else
				this.menu.empty();
			
			this.options.menu.each(function(node,index){
				this.fireEvent('menu',[this,node,index]);
				//Create the anchor and then add it to the new li
				var a = new Element('a',{href:node.uri, html:node.title});
				var m = new Element('li');
				
				m.adopt(a);
				
				//Check for links on the node
				if(node.links){
					this.makeSubMenu(m, node.links,index);
				}
				
				//Attach events
				m.addEvent('mouseenter',this.mouseOver.bind(this));
				m.addEvent('mouseleave',this.mouseLeave.bind(this));
				
				//Attach lu to node.
				this.menu.adopt(m);
			}.bind(this));
			if(!$(this.menu.id))
				this.parent.adopt(this.menu);
		}
	},
	makeSubMenu: function(node, subs, index){
		this.fireEvent('makeSubMenu',[this,node,subs,index]);
		//Check the node and subs then proceed
		if(node && subs){
			var s = new Element('ul',{
				id:this.id+'_sub'+index,
				'class':this.id+'_sub'
				/*styles:{
					'display':'none',
					'position':'absolute'
				}*/
			});
			s.addClass(this.options['class']);
			
			$each(subs,function(el,index){
				this.menu.fireEvent('subMenu',[this,el]);
				var a = new Element('a',{href:el.uri,html:el.title})
				var m = new Element('li');
				
				m.adopt(a);
				
				//Check for links on the node
				if(el.links){
					this.makeSubMenu(m, el.links,index);
					//m.setStyle('position','absolute');
				}
				
				//Attach Events
				m.addEvent('mouseenter',this.mouseOver.bind(this));
				m.addEvent('mouseleave',this.mouseLeave.bind(this));
				
				s.adopt(m);
			}.bind(this));
			
			node.adopt(s);
		}
	},
	attachSub: function(target, subject){
		var x = target.getStyle('left');
		var y = target.getStyle('top');
		
		//Attach to the bottom left of the target
		x += target.getStyle('width')+2;
		subject.setStyle('left',x);
		y += target.getStyle('height')+2;
		subject.setStyle('top',y);
	},
	hideLayers:function(){
		var c = this.menu.getChildren('li');
		Array.each(c,function(el){
			//Fade the child ul if one is present
			if(el.getElement('ul'))
				el.getElement('ul').hide().fade('out');
		});
	},
	mouseOver: function(e){
		//Get the top parent menus and hide all its children
		//if(this.menu.getChildren.contains(e.target))
			//this.hideLayers();
		
		var x = e.target.getElement('ul');
		if(x){
			this.fireEvent('mouseOver',[this,x]);
			this.attachSub(e.target, x);
			if(this.options.openFx)
				x.set('tween',{transition:this.options.openFx,delay:this.options.delay});
			if(this.options.effect == 'slide')
				x.show().tween('height','auto').fade('in');
			if(this.options.effect == 'fade')
				x.show().fade('in');
		}
	},
	mouseLeave: function(e){		
		var x = e.target.parentNode.getElement('ul');		
		if(x){
			this.fireEvent('mouseLeave',[this,x]);
			if(this.options.closeFx)
				x.set('tween',{transition:this.options.closeFx,delay:this.options.delay});
			if(this.options.effect == 'slide')
				x.hide().tween('height','0').fade('out');
			if(this.options.effect == 'fade')
				x.hide().fade('out');
		}
	},
	refresh: function(){
		this.fireEvent('refresh',this);
		
		if(this.options.menu && this.options.menu.length)
			this.makeMenu(this.options.menu);	
	}
});

/* end jsNavi */

/* Dynamic Form element generator */
function onType(holder, type){
	var target = $(holder);
	var obj = $(type);
			
	//Check for valid target and obj elements.
	if(!$target || !obj)
		return false;
		
	switch(obj.value){
		case "checkbox":
			preview.innerHTML = obj.form.title.value+'<br>'+getValue('checkbox');
			break;
		case "radio":
			preview.innerHTML = obj.form.title.value+'<br>'+getValue('radio');
			break;
		case "select":
			preview.innerHTML = obj.form.title.value+'<br><select title="'+obj.form.title.value+'">'+getValue('select')+'</select>';
			break;
		case "text":
			preview.innerHTML = obj.form.title.value+'<br><input type="text" title="'+obj.form.title.value+'" '+obj.form.attribs.value+' value="'+getValue()+'" />';
			break;
		case "textarea":
			preview.innerHTML = obj.form.title.value+'<br><textarea type="button" title="'+obj.form.title.value+'" '+obj.form.attribs.value+' value="'+getValue()+'" </textarea>';
			break;
	}			
}
function getValue(obj){
	//
	var val = window.document.getElementById('value').value.split('\n');
	var raw = window.document.getElementById('value').value;
	var s = '';
	switch(obj){
		case "select": //parse the values to present options back as text.					
			for(var i=0; i<val.length;i++){
				data = val[i].split('|');
				if(data[1] == undefined)
					s+= '<option value="'+data[0]+'">'+data[0]+'</option>';
				else
					s+= '<option value="'+data[1]+'">'+data[0]+'</option>';
			}
			break;
		case "checkbox": //parse the values to present options back as text.					
			for(var i=0; i<val.length;i++){
				data = val[i].split('|');
				if(data[1] == undefined)
					s+= '<label><input type="checkbox" value="'+data[0]+'"/>'+data[0]+'</label>';
				else
					s+= '<label><input type="checkbox" value="'+data[1]+'"/>'+data[0]+'</label>';
			}
			break;
		case "radio": //parse the values to present options back as text.					
			for(var i=0; i<val.length;i++){
				data = val[i].split('|');
				if(data[1] == undefined)
					s+= '<label><input type="radio" value="'+data[0]+'"/>'+data[0]+'</label>';
				else
					s+= '<label><input type="radio" value="'+data[1]+'"/>'+data[0]+'</label>';
			}
			break;
		default: /* default handles text, textarea and others.*/					
			s = raw; 
			break;
	}
	return s;
}
/* end Dynamic Form element generator */

function dateCheck(el){

	var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/

	// check to see if in correct format

	if(!objRegExp.test(el.value)){

		el.errors.push("Please enter a valid date (MMDDYYYY)");

		return false; // doesn't match pattern, bad date

	} else {

		var strSeparator = el.value.substring(2,3) 

		var arrayDate = el.value.split(strSeparator); 

			// create a lookup for months not equal to Feb.

			var arrayLookup = { '01' : 31,'03' : 31, 

					'04' : 30,'05' : 31,

					'06' : 30,'07' : 31,

					'08' : 31,'09' : 30,

					'10' : 31,'11' : 30,'12' : 31}

			var intDay = parseInt(arrayDate[1],10); 



			// check if month value and day value agree

			if(arrayLookup[arrayDate[0]] != null) {

				if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)

					return true; // found in lookup table, good date

			}



			// check for February (bugfix 20050322)

			// bugfix for parseInt kevin

			// bugfix biss year O.Jp Voutat

			var intMonth = parseInt(arrayDate[0],10);

			if (intMonth == 2) { 

				var intYear = parseInt(arrayDate[2]);

				if (intDay > 0 && intDay < 29) {

					return true;

				}

				else if (intDay == 29) {

					if ((intYear % 4 == 0) && (intYear % 100 != 0) || 

							(intYear % 400 == 0)) {

						// year div by 4 and ((not div by 100) or div by 400)
						// ->ok

						return true;

					}   

				}

			}

		}  

	return false; // any other values, bad date

}

function samecheck(target,value){
	return (target.value == value);
}

function formtohash(form){
	var r = {};
	var els = form.getElements('input,select,textarea')||form.elements;
	if(form){
		if(els)
			$each(els, function(el,index){
				switch(el.type){
					case 'checkbox':
						if(el.get('checked') && el.get('checked') == true && el.name)
							r[el.name] = el.value;
						break;
					case 'radio':
						if(el.get('checked') && el.get('checked') == true && el.name)
							r[el.name] = el.value;
						break;
					case 'select':
						if(el.name)	r[el.name] = el.value;
						break;
					case 'select-one':
						if(el.name)	r[el.name] = el.value;
						break;
					case 'select-multiple':						
						if(el.name){ 
							//Parse the target for multiple selections							
							var values = '';
							Array.each(el.getElements('option'), function(o){
								values += o.value+',';
							});
							
							if(values[values.length-1] == ',') values = values.substring(0,values.length-1);
							
							r[el.name] = values;
						}
						break;
					case 'textarea':
						if(el.name)	r[el.name] = el.value;
						break;
					case 'text': 
						if(el.name)	r[el.name] = el.value;
						break;
					case 'password': 
						if(el.name)	r[el.name] = el.value;
						break;
					case 'hidden': 
						if(el.name)	r[el.name] = el.value;
						break;
					case 'submit': 
						if(el.name)	r[el.name] = el.value;
						break;
				}
			});
	}
	return r;
}

function showMessage(msg, type, title, delay, img, hold){
	if(msg)
		growlBezel(type,title,msg,delay,img,hold)
}

function closeMessage(){
	$('system_messages').hide().fade('out');
}

/*function checkusername(field){
	var uname = field.get('value');
	if(uname){
		var ajaxquery = new Request.JSON({
			url: '/ajaxquery/checkUsername/'+uname,
			onComplete: function(resp){
				if(resp.return_type == 'alert')
				showMessage(resp.message)
			}
		}).send();
	}
}*/

function checkusername(el){
	var ajax = new Request.JSON({url:location.pathname, data:{requestedClass:'UserObject',requestedMethod:'checkusername', 'username':el.value}, async:false}).send()
	if (!ajax.response.json.data) {
		el.errors.push("The username '"+el.value+"' is not available");
		return false;
	} else {
		return true;
	}
}

function checkemail(el){
	var ajax = new Request.JSON({url:location.pathname, data:{requestedClass:'UserObject',requestedMethod:'checkemail', 'email':el.value}, async:false}).send()
	if (!ajax.response.json.data) {
		el.errors.push("The email '"+el.value+"' is not available");
		return false;
	} else {
		return true;
	}
}

function checkAvailable(el){
	var value = el.get('value');
	var ajaxquery;
	var response;
	if(el.id == 'email' || el.name == 'email' || el.id == 'email_address' || el.id == 'acc_email_address'){
		var ajaxquery = new Request.JSON({
			async: false,
			data:{requestedClass:'UserObject', requestedMethod:'isAvailable', 'value':value, type:'email'},
			onSuccess: function(resp){
				if(typeof resp == "string") 
					resp = JSON.decode(resp);
				response = resp;
			}
		}).send();
	}
	else if(el.id == 'signup_username' || el.id == 'acc_username' || el.id == 'username' || el.name == 'username'){
		var ajaxquery = new Request.JSON({
			async: false,
			data:{requestedClass:'UserObject', requestedMethod:'isAvailable', 'value':value, type:'username'},
			onSuccess: function(resp){
				if(typeof resp == "string") 
					resp = JSON.decode(resp);
				response = resp;
			}
		}).send();
	}
	
	if(value && !response.data){
		if(el.errors) el.errors.push(response.message);
		return false;
	}
	else{
		return true;
	}
}

function resetform(form){
	if(form.elements.length)
		$each(form.elements, function(el){
			switch(el.type){
				case 'radio':
					el.checked = false;
					break;
				case 'submit': 
					el.set('disabled',false);
					break;
				case 'button':
					el.set('disabled',false);
					break;
				case 'reset':
					el.set('disabled',false);
					break;
				case 'hidden':
					el.set('value','');
					break;
				case 'text':
					el.set('value','');
					break;
				case 'textarea': 
					el.set('value','');
					break;
				case 'password':
					el.set('value','');
					break;
				case 'select-one':
					el.set('value','');
					break;
				case 'select-multiple':
					el.getElements('option').set('selected',false);
					break;
			}
		});
}

function fillform(form,ds,extra){
	var els = form.getElements('input,select,textarea') || form.elements;
	if(els.length){
		Array.each(els, function(el){
			if(ds[el.name]){
				el = document.id(el);
				switch(el.type){
					case 'checkbox':
						el.set('checked', (ds[el.name] == el.value));
						break;
					case 'radio':
						el.set('checked', (ds[el.name] == el.value));
						break;
					case 'hidden':
						el.set('value',ds[el.name]);
						break;
					case 'text':
						el.set('value',ds[el.name]);
						break;
					case 'textarea': 
						el.set('value',ds[el.name]);
						break;
					case 'password':
						el.set('value',ds[el.name]);
						break;
					case 'select-one':
						el.set('value',ds[el.name]);
						break;
					case 'select-multiple':
						var s = ds[el.name].split(',');
						if(s.length){
							Array.each(el.getElements('option'),function(o){
								if(s.contains( o.get('value') ))
									o.set('selected',true);
							});
						}						
						break;
				}
				if(extra){
					var e = extra.split(',');
					$each(e, function(x){
						el.set(x, ds[el.name]);
					});
				}
			}
		});
	}
}

function getStates(){
	var response = null;
	var ajaxquery = new Request.JSON({
		url: '/ajax/getStates',
		async: false,
		noCache: true,
		onComplete: function(resp){
			response = resp.data;
		}
	}).send();
	
	return response;
}

function getCountries(){
	var response = null;
	var ajaxquery = new Request.JSON({
		url: '/ajax/getCountries',
		async: false,
		noCache: true,
		onComplete: function(resp){
			response = resp.data;
		}
	}).send();
	
	return response;
}

function objectToOptions(target,data,label,value,defaultOption){
	if(data && target){
		if(!arguments[3])
			target.empty();
		if(defaultOption)
			target.adopt(new Element('option',{text:defaultOption.name||'Choose one',value:defaultOption.id||''}));
		var l = (label)?label.split(','):null;
		$each(data, function(el,index){
			var n='';
			if(l && l.length)
				for(var i=0;i<l.length;i++)
					n += el[l[i]]+((i+1 < l.length)? ' ':'');
			else
				n = el;
			target.adopt(new Element('option',{text:n,value:(value)?el[value]:n}));
		});
	}
}

function arrayToOptions(target, data){
	target.empty();
	if(data)
		$each(data, function(el,index){
			target.adopt(new Element('option', {text:el}));
		});
}

function changeImage(form){
	var u = new jsFileUploader('jsLogo',{action:'/ajax/changeImage','iclass':'uploader',parent:$(form),file_name:'userfile',
		onComplete: function(e,resp){
			if(resp && resp.message)
				showMessage(resp.message);
			if(resp && resp.success){
				var target = e.parent.getElement('input[name=image]');
				if(target)
					target.set('value', resp.data['file_name']);
			}
		}
	});
	u.file.click();
}

function populateItems(ds,ids,target){
	if(ids && target && ds){
		ids = ids.split(',');
		target.empty();
		$each(ds, function(el){
			for(var i=0;i<ids.length;i++){
				if(el.id == ids[i])
					target.adopt( new Element('div',{'class':'item'}).adopt( 
							new Element('p').adopt(
									new Element('span',{'class':'item_product', html:el.name+' ('+el.sku+')'}),
									new Element('span',{'class':'item_price', html:el.price})
							)
					));
			}
		});
	}
}

var liteGrid = new Class({
	Implements: [Options,Events,Chain],
	id:'litegrid',
	items:null,
	index:0,
	options: {
		ds:null,
		pagination:{ count:9,page:1,pages:null,total:null },
		'class':'',
		navigation:true,
		fields:[{type:'hidden',value:'id'},{type:'img',value:'image',path:'/images/'},{type:'div',value:'name'},{type:'span',value:'price'}],
		custom_items:false,
		empty_show:true,
		empty_message:'There are no items to display at this time.',
		empty_class:null,
		onInitialize: null,
		onMake:null,
		onRender: null,
		onNext: null,
		onPrevious: null,
		onGotoPage: null,
		onClick: null,
		onDblClick: null,
		onMouseOver: null,
		onMouseOut: null,
		onBlur: null,
		onFocus: null
	},
	initialize: function(id,holder,options){
		this.setOptions(options);
		this.id = id || this.id;
		this.holder = (typeof holder == 'string')? $(holder):holder;
		
		this.el = new Element('div', {id:this.id,'class':this.options['class']});
		
		this.render();
		
		this.holder.adopt(this.el);
		
		this.fireEvent('initialize',this);
	},
	make: function(){		
		var maker = function(el,index,source){			
			var o = new Element('div', {id:this.id+'_item'+i,'class':this.id+'_item',align:'center'});
			if(this.options.custom_items && this.options.custom_items == true)
				this.fireEvent('make', [this, o, el, index]);
			else {
				this.options.fields.each( function(e,x,s){
					var l;
					switch(e.type){
						case 'img': 
							var p;
							if(e.path)
								p = e.path;
							l = new Element(e.type,{src:p+el[e.value],'class':'image'});
							break;
						case 'div':
							l = new Element(e.type,{html:el[e.value],'class':'name'});
							break;
						case 'span':
							l = new Element(e.type,{html:el[e.value],'class':'price'});
							break;
						case 'p':
							l = new Element(e.type,{html:el[e.value],'class':'name'});
							break;
					}
					
					//Adopt the new element
					if(o)
						o.adopt( l );					
				}.bind(this) );				
			}
			
			//Add the element to the items stack
			this.items.push( o );			
		}.bind(this);
		
		//Process the data if there is any		
		if(this.options.ds){
			if($type(this.options.ds) == 'object')
				this.options.ds = Array.each( this.options.ds );
			
			var i = 1;
			var j = ((this.options.pagination.count * this.options.pagination.page) == this.options.pagination.count)? 0 : (this.options.pagination.count * this.options.pagination.page)-1;
			
			while(this.options.ds[j]){
				if(i > this.options.pagination.count)
				return;
			
				if(j > j+this.options.pagination.count){
					return;
				}
				
				maker(this.options.ds[j],j,this.options.ds);
				this.index = j-1;
				j++;
				i++;
			}
		}
	},
	render: function(){
		this.el.empty();
		this.items = [];
		this.make();
		if(!this.options.ds)
			return;
		
		this.options.pagination.total = this.options.ds.length;
		this.options.pagination.pages = Math.floor(this.options.pagination.total / this.options.pagination.count);
		if(this.items && this.items.length){
			this.el.adopt( this.items );
			if(this.options.navigation && this.options.navigation == true){
				this.navigation = new Element('div',{id:this.id+'_navigation', 'class':'navigation',align:'center'});
				this.navigation.adopt( new Element('span',{html:'Pages: '}) );
				for(var x=0;x<this.options.pagination.pages;x++){
					this.navigation.adopt( new Element('a',{html:x+1,href:'javascript:;', rel:x+1,events:{click:this.gotoPage.bind(this,x+1)}}) );
				}
				
				this.el.adopt( this.navigation );
				var pc = new Element('select',{name:'pc',styles:{'display':'inline-block','margin-left':4,'width':60},events:{
					change: function(e){
						this.options.pagination.count = e.target.get('value');
						this.render();
					}.bind(this)}
				}); 
				Array.each([3,6,9,15,30,60,90,120],function(el){
					pc.adopt( new Element('option',{text:el,value:el}) );
				});
				pc.set('value',this.options.pagination.count);
				this.navigation.adopt( pc );
				
			}
		} else {
			if(this.options.empty_show){
				this.el.adopt( new Element('h2',{html:this.options.empty_message,'class':this.options.empty_class}) );
			}
		}
		
		this.fireEvent('render',this);
	},
	next: function(){
		this.options.pagination.page += 1;
		if(this.options.pagination.page > this.options.pagination.pages)
			this.options.pagination.page = 1;
		
		this.fireEvent('next',this);
		this.render();
	},
	previous: function(){
		this.options.pagination.page -= 1;
		if(this.options.pagination.page < 1)
			this.options.pagination.page = 1;
		
		this.fireEvent('previous',this);
		this.render();
	},
	gotoPage: function(page){
		this.options.pagination.page = page;
		this.fireEvent('gotopage',this);
		this.render();
	}
	
});

var liteCart = new Class({
	Implements: [Options,Events,Chain],
	id:'litecart',
	items:null,
	basket:null,
	options: {
		cartid:null,
		statusbar:null,
		basket:null,
		'class':null,
		site_name:'LiteCart v1.1',
		taxes:0.00,
		shipping:0.00,
		forcessl:false,
		tracker:null,
		autoshowcart:false,
		checkout_register:true,
		checkout_msg:'<b>Please enter your contact and purchase information to begin processing your payment.</b>',
		checkout_success:null,
		checkout_failure:null,
		checkout_process:'/ajax/purchase',
		onInitialize: null,
		onAddtoCart: null,
		onPurchase: null,
		onClear: null,
		onRemove: null,
		onUpdateCart: null,
		onShow: null,
		onHide: null,
		onUpdate: null,
		onTotals: null
	},
	initialize: function(id,options){
		this.id = id || this.id;
		this.setOptions(options);
		this.basket = this.options.basket;
		if(this.id){
			if(!this.basket){
				this.basket = new Element('div', {id:this.id, 'class':this.options['class']});
			}
			if(this.options.statusbar){
				this.statusbar_display = $(this.options.statusbar.id+'_cart');
			}
			
			//Build the basket's children and prepare it
			this.cart = new Element('div', {id:this.id+'_cart'});
			this.cart_actions = new Element('div', {id:this.cart.id+'_actions'});
			this.cart_actions.adopt( 
				new Element('span', {html:this.options.site_name}),				
				new Element('a', {html:'Checkout', href:'javascript:;',
					events:{
						click:this.checkout.bind(this)
					}
				}),
				new Element('a', {html:'Update', href:'javascript:;',
					events:{
						click:this.update.bind(this)
					}
				}),
				new Element('a', {html:'Clear', href:'javascript:;',
					events:{
						click:this.clear.bind(this)
					}
				})
			);
			this.cart.adopt( new Element('a',{'class':'close',html:'&nbsp', events:{click:this.hide.bind(this)}}) );
			this.cart.adopt( this.cart_actions );
			var y = new Date().getFullYear();
			this.counter = new Element('div', {id:this.cart.id+'_counter'});
			this.counter.adopt( 
				new Element('div', {html:this.options.checkout_msg}),
				new Element('div').adopt( new Element('form', {action:this.options.checkout_process,id:'checkout_form',method:'post'}).adopt( 
					new Element('input', {type:'hidden', name:'amount'}),
					new Element('fieldset').adopt(
						new Element('legend', {html:'Billing Information'}),
						new Element('p').adopt( 
							new Element('label',{html:'First Name: '}),
							new Element('input', {type:'text', name:'first_name', 'class':"validate['required']"}),
							new Element('label',{html:'Last Name: '}),
							new Element('input', {type:'text', name:'last_name', 'class':"validate['required']"})						
						),
						new Element('p').adopt(
							new Element('label',{html:'Email address: '}),
							new Element('input', {type:'text', name:'email', 'class':"validate['required','email']"}),
							new Element('label',{html:'Confirm Email: '}),
							new Element('input', {type:'text', name:'email_confirm', 'class':"validate['required','confirm:email']"})
						),
						new Element('p').adopt( 
							new Element('label',{html:'Address: '}),
							new Element('input', {type:'text', name:'address', 'class':"validate['required']"}),
							new Element('label',{html:'Address 2:'}),
							new Element('input', {type:'text', name:'address2'})
						),
						new Element('p').adopt( 						
							new Element('label',{html:'City: '}),
							new Element('input', {type:'text', name:'city', 'class':"validate['required']"}),
							new Element('label',{html:'State: '}), 
							new Element('select', {name:'state', 'class':"validate['required']", events:{
								change: function(e){
									if(e.target.get('value') == 'FL')
										this.options.taxes = 0.06;
									else
										this.options.taxes = 0;
									this.updatecart();
								}.bind(this)
							}})
						),
						new Element('p').adopt( 
							new Element('label',{html:'Country'}),
							new Element('select', {name:'country', 'class':"validate['required']"}),
							new Element('label',{html:'Province Non US'}),
							new Element('input', {type:'text', name:'province',title:'None US buyers only.'}),
							new Element('label',{html:'Postal/Zip'}),
							new Element('input', {type:'text', name:'postal'})
						),
						new Element('p').adopt(
							new Element('label',{html:'Phone Number: '}),
							new Element('input', {type:'text', name:'phone', 'class':"validate['required']"})
						)
					),
					new Element('fieldset').adopt(
						new Element('legend', {html:'Payment Information'}),
						new Element('p').adopt( 
							new Element('label',{html:'Method: '}),
							new Element('span').adopt(
								new Element('input', {type:'radio', name:'payment', value:'1', selected:true, 'class':"group[1]", events:{click:function(e){
									this.form.getElements('input[name=cc_number],input[name=exp_month],input[name=exp_year],input[name=ccv]').set('disabled',false);
								}}, styles:{'margin-left':6,'margin-right':6}}),
								new Element('label',{html:'Credit Card'})
							),
							new Element('span').adopt(							
								new Element('input', {type:'radio', name:'payment', value:'2', 'class':"group[1]", disabled:true, events:{click:function(e){
									this.form.getElements('input[name=cc_number],input[name=exp_month],input[name=exp_year],input[name=ccv]').set('disabled',true);
								}}, styles:{'margin-left':6,'margin-right':6}}),
								new Element('label',{html:'Paypal ExpressCheckout'})
							)
						),
						new Element('p').adopt(
							new Element('label', {html:'Card#: '}),
							new Element('input', {type:'text', name:'cc_number', maxlength:16, 'class':"validate['required','digit','lengthmin[13]','lengthmax[16]']"}),
							new Element('label', {html:'Exp MM/YYYY: '}), 
							new Element('input', {type:'text', name:'exp_month', maxlength:2, 'class':"validate['required','digit[1,12]']"}),
							new Element('input', {type:'text', name:'exp_year', maxlength:4, 'class':"validate['required','digit["+y+","+(y+10)+"]']"}),
							new Element('label', {html:'CCV: ', styles:{'min-width':38,'margin-left':8}}),
							new Element('input', {type:'text', name:'ccv', maxlength:5, 'class':"validate['required','digit']"}) 
						)
					),
					new Element('p').adopt( 
						new Element('label',{html:'Where did you find us?: <br>'}),
						new Element('select', {name:'foundus'})					
					),
					new Element('p').adopt( 
						new Element('label',{html:'Comments: '}),
						new Element('textarea', {name:'comments'})
					),
					new Element('p', {align:'center'}).adopt(
						new Element('input', {type:'submit',value:'Process','class':'submit'}),
						new Element('input', {type:'button',value:'Cancel','class':'cancel',
							events: {
								click:function(e){
									this.counter.hide().fade('out');
								}.bind(this)
							}
						})
					))
				)
			);
			this.counter.set('tween', {transition:Fx.Transitions.Linear});			
			this.cart.adopt( this.counter );
			this.cart.set('tween', {transition:Fx.Transitions.Linear});
			this.basket.adopt( this.cart );
			this.basket.set('tween', {transition:Fx.Transitions.Linear});
			document.body.appendChild( this.basket );
			this.fc = new FormCheck('checkout_form', {submitByAjax:true, display:{showErrors:1}, 
				onAjaxSuccess: function(resp,txt){
					$('checkout_form').tween('opacity',1).getElement('.submit').set('disabled', false);
					if(typeof resp == 'string')
						resp = JSON.decode(resp);
					
					if(resp && resp.message)
						alert(resp.message);
					
					if(resp && resp.success){
						//The payment was process successfully so show the info, clear the cart and return the necessary details to the customer.
						this.counter.hide().fade('out');
						resetform( $('checkout_form') );
						
						this.clear();	
						this.hide();
						if(this.options.track){
							this.tracker = new IFrame({src:this.options.track, 
								events:
								{
									load: function(){
										this.tracker.dispose;
										this.tracker = null;
									}.bind(this)	
								}
							});
						}
						if(this.options.success_page)
							window.location.replace(this.options.success_page+resp.data.transactionid);
					} else if(resp && !resp.success){
						//The payment was not processessed sucessfully for the reason stated in the message. Release the form and allow a retry.
						
					} else if(!resp){
						showMessage('There was a problem communicating with the merchant. Please try again.');
						return false;
					}
					
					this.fireEvent('purchase', [this, resp]);
				}.bind(this),
				onAjaxRequest: function(xhr){
					showMessage('Please wait while we process your payment.');
					this.form.tween('opacity',0.3);
					this.form.getElement('.submit').set('disabled',true);
				},
				onAjaxFailure: function(xhr){
					showMessage('There was a communication failure with your internet connection. Please check your connection and try again.');
					this.form.tween('opacity',1).getElement('.submit').set('disabled', false);
					return false;
				}
			});
			
			//Get the items from the cart
			this.updatecart();
			
		}
		
		this.fireEvent('initialize', this);
	},
	addtocart: function(obj){
		if(obj){
			new Request.JSON({
				url:'/ajax/addToCart',
				data:obj,
				onSuccess:function(resp,json){
					if(typeof resp == 'string')
						resp = JSON.decode(resp,true);
					
					if(resp.message)
						showMessage(resp.message);
					
					if(resp.success){
						this.updatecart();
						if(this.options.autoshowcart && this.options.autoshowcart == true)
							this.show();
					}
					this.fireEvent('addtocart', [this, resp]);
				}.bind(this)
			}).send();		
		}
	},
	clear: function(){
		if(this.items){
			$each(this.items,function(e){
				this.remove(e.rowid);
			}.bind(this));
			this.items = null;
		}
		this.fireEvent('clear', this);
	},
	remove: function(id){		
		if(id){
			new Request.JSON({
				url:'/ajax/removeFromCart',
				data:{rowid:id,qty:0},
				async:false,
				onSuccess:function(resp,json){
					if(typeof resp == 'string')
						resp = JSON.decode(resp,true);
					
					if(resp.message)
						showMessage(resp.message);
					
					if(resp.success){
						this.updatecart();
					}
					this.fireEvent('remove', this);
				}.bind(this)
			}).send();		
		}
	},
	totals:function(){
		var totals = {
			subtotal: 0.00,
			taxes: 0.00,
			shipping: this.options.shipping||0.00,
			total: 0.00
		};
		
		if(this.items){
			$each(this.items,function(el){
				totals.subtotal += Number(el.subtotal);
			});
			totals.taxes = (totals.subtotal * this.options.taxes).round(2);
			totals.total = (totals.subtotal + totals.taxes + totals.shipping).round(2);
		}
		
		/*this.cart.getElement('.subtotal').set('html','$'+totals.subtotal);
		this.cart.getElement('.taxes').set('html','$'+totals.taxes);
		this.cart.getElement('.total').set('html','$'+totals.total);*/
		
		this.fireEvent('totals', this);
		return totals;
	},
	update: function(){
		//Gather the items and pair them up
		var rows = this.cart.getElements('input.qty');
		var ids = [];
		if(rows && rows.length){
			rows.each(function(el){
				var id = el.get('rel');
				var qty = el.get('value');
				ids.push(id+"|"+qty);
			});
			if(ids.length){
				new Request.JSON({
					url:'/ajax/updateCart',
					method:'post',
					data: {'ids':ids.join(',')},
					async:false,
					noCache:true,
					onSuccess: function(resp,json){
						if(typeof resp == 'string')
							resp = JSON.decode(resp,true);
						
						if(resp.message && !resp.success)
							showMessage(resp.message);
						
						if(resp.success)
							this.updatecart();
						
						this.fireEvent('update', this);
					}.bind(this)
				}).send();
			}
		}
	},
	updatecart: function(){
		new Request.JSON({
			url:'/ajax/getCart',
			onSuccess:function(resp,json){
				if(typeof resp == 'string')
					resp = JSON.decode(resp,true);
				
				if(resp.message && !resp.success)
					showMessage(resp.message);
				
				if(resp.success){
					this.items = resp.data.items;
					
					//Now rebuild the basket itself
					this.cart.getElements('div.item').hide().fade('out').dispose();
					var i = 1;
					$each(this.items,function(el){
						this.cart.adopt( 
							new Element('div', {'class':'item'}).adopt( 
								new Element('span', {html:'#'+i, 'class':'num'}),
								new Element('span', {html:el.id, 'class':'sku'}),
								new Element('span', {html:el.name, 'class':'name'}),
								new Element('input', {'type':'text', value:el.qty,'rel':el.rowid, 'class':'qty'}),
								new Element('span', {html:el.price, 'class':'price'}),
								new Element('span', {html:el.subtotal, 'class':'price'}),
								new Element('a', {html:'Remove', 'class':'remove', rel:el.rowid, events:{click: function(e){ this.remove(e.target.get('rel')); }.bind(this)}})
							).show().fade('in')
						);
						i++;
					}.bind(this));
					
					//update the amount
					this.cart.getElements('div.totals').hide().fade('out').dispose();
					this.total = resp.data.total;
					var totals = this.totals();
					this.cart.adopt( 					
						new Element('div', {'class':'totals','align':'center'}).adopt(
							new Element('span', {html:'Sub Total: '+totals.subtotal, 'class':'price'}),
							new Element('span', {html:'Shipping: '+totals.shipping, 'class':'price'}),
							new Element('span', {html:'Taxes: '+totals.taxes, 'class':'price'}),
							new Element('span', {html:'Total: '+totals.total+' USD', 'class':'price'})
						).show().fade('in')
					);
					this.cart.getElement('input[name=amount]').set('value',totals.total);
					
					//Update the statusbar_display if there is one
					if(this.statusbar_display && (i-1)){
						this.statusbar_display.empty();
						this.statusbar_display.adopt( new Element('a', {html:(i-1)+' item(s) in your basket, Do you want to Checkout?', href:'javascript:;', events:{click:this.show.bind(this)}}) );
					} else if(this.statusbar_display && !(i-1)){
						this.statusbar_display.empty();
						this.statusbar_display.adopt( new Element('a', {html:'Your basket is empty', href:'javascript:;'}) );
					}
					
					//Update the topbar if there is one
					if(this.options.topbar && (i-1)){
						this.options.topbar.set('html', (i-1)+' item(s) in your basket, Do you want to Checkout?' );
					} else if(this.options.topbar && !(i-1)){
						this.options.topbar.set('html','Your basket is empty' );
					}
					
					this.fireEvent('updatecart', this);
				}
			}.bind(this)
		}).send(); 
	},
	checkout: function(){		
		this.show();
		//Catch attempts to checkout an empty cart.
		if(!this.items){
			showMessage('There are no items in your cart, therefore checkout is not available at this time.');
			return false;
		}
		
		//Now show the checkout options right below the cart. If the user isn't logged in, the ask them to in order to checkout.
		if(this.options.checkout_register && !this.options.cartid){
			//Force registration and get the cartid
			if(this.options.checkout_registration){
				//This process should always return a cartid that links back to the users session.
				this.options.checkout_registeration();				
			} else {
				alert('It appears registration is required to process your purchase. Please check the site for the registration process or login before attempting to process your payment.');
			}
		} else {
			//This means the user is either already logged in or there is no registration requirement.
			this.counter.show().fade('in');
		}
		
		this.fireEvent('checkout', this);
	},
	show: function(){
		if(this.options.forcessl == true && window.location.protocol == 'http:'){
			window.location.replace('https://'+window.location.host+window.location.pathname);
			return;
		}
		if(this.basket.getStyle('display') == 'none')
			this.basket.show().tween('opacity',0.98);
		
		this.fireEvent('show', this);
	},
	hide: function(){
		if(this.basket.getStyle('display') != 'none')
			this.basket.hide().tween('opacity',0);
		
		this.fireEvent('hide', this);
	}
});

/* Multi-Purpose overlay background */
function overlayBknd(){
	var overlay_bknd = new Element('div',{
		id: 'overlay_bknd',
		styles: {
			'width': window.innerWidth?window.innerWidth:window.screen.availWidth,
			'height': window.innerHeight?window.innerHeight:window.screen.availHeight,
			'background-image': 'url(/images/overlay_bknd.png)',
			'position': 'fixed',
			'top': 0,
			'left': 0,
			'z-index': 9999
		},
		events: {
			click: function(e){
				var target = (e.target)? e.target : e;
				if(target.get('close') && target.get('close') == 0)
					return;
				if(e.id == 'overlay_bknd' || e.target.id == 'overlay_bknd'){
					this.set('tween',{
						onComplete: function(){
							this.dispose();
						}.bind(this)
					});
					$$('.fc-tbx').setStyle('opacity',0);
					this.tween('opacity',0);
				}
			}
		}
	});
		
	return overlay_bknd;
}

/* General Overlay - pass header(HTML:string), content(HTML:string), footer(HTML:string) */
function overlay(header,content,footer){
	var overlay_bknd = overlayBknd();
	
	if(!header) var header_wrap = new Element('div');
	else{
		var header_wrap = new Element('div',{
			id:'overlay_header_wrap',
			html:header
		});
	}
	
	if(content && typeof(content) == 'object'){
		content_html = '<ul>';
		$each(content,function(array){
			if(typeof(content) == 'object'){
				$each(array,function(el){
					if(typeof(el) == 'string') content_html += '<li>'+el+'</li>';
				});
			}
			else{
				if(typeof(array) == 'string') content_html += '<li>'+array+'</li>';
			}
		});
		content_html += '</ul>';
	}
	else if(!content) var content_html = '';
	else var content_html = content;
	
	if(!footer) var footer_wrap = new Element('div');
	else var footer_wrap = new Element('div',{id:'overlay_footer_wrap',html:footer});
	
	var content_wrap = new Element('div',{
		id: 'content_wrap',
		html: content_html
	});
	
	var overlay_close = new Element('span',{
		text: 'close',
		styles: {
			'background': 'url(/images/overlay_close_x.png) no-repeat right top',
			'display': 'block',
			'width': 65,
			'height': 18,
			'text-align': 'right',
			'position': 'absolute',
			'top': 20,
			'right': 20,
			'padding-right': 22,
			'color': '#000',
			'font-size': 14,
			'font-family': 'AvenirLTStd35Light,sans-serif',
			'cursor': 'pointer',
			'z-index': 9999
		},
		events: {
			click: function(){
				this.tween('opacity',0);
			}.bind(overlay_bknd)
		}
	});
	var overlay_table = new Element('table',{
		id: 'overlay_table',
		'cellpadding': 0,
		'cellspacing': 0,
		styles: {
			'z-index': 9999,
			'margin': '200px auto',
			'position': 'relative'
		}
	});
	var overlay_tl = new Element('td',{
		styles: {
			'background-image': 'url(/images/overlay_corners.png)',
			'background-position': 'top left',
			'background-repeat': 'no-repeat',
			'height': 19,
			'width': 18
		},
		html: '&nbsp;'
	});
	
	var overlay_tr = new Element('td',{
		styles: {
			'background-image': 'url(/images/overlay_corners.png)',
			'background-position': 'top right',
			'background-repeat': 'no-repeat',
			'height': 19,
			'width': 18
		},
		html: '&nbsp;'
	});
	var overlay_bl = new Element('td',{
		styles: {
			'background-image': 'url(/images/overlay_corners.png)',
			'background-position': 'bottom left',
			'background-repeat': 'no-repeat',
			'height': 19,
			'width': 18
		},
		html: '&nbsp;'
	});
	var overlay_br = new Element('td',{
		styles: {
			'background-image': 'url(/images/overlay_corners.png)',
			'background-position': 'bottom right',
			'background-repeat': 'no-repeat',
			'height': 19,
			'width': 18
		},
		html: '&nbsp;'
	});
	
	overlay_table.adopt(
		new Element('tr').adopt(
			overlay_tl,
			new Element('td',{
				styles: {
					'border-top': '7px solid #ffbc2a',
					'background-color': 'white',
					'position': 'relative'
				}
			}).adopt(overlay_close),
			overlay_tr
		),
		new Element('tr').adopt(
			new Element('td',{
				styles: {
					'border-left': '7px solid #ffbc2a',
					'background-color': 'white'
				}
			}),
			new Element('td',{
				styles: {
					'background-color': 'white',
					'max-width': 500,
					'padding': '20px 25px 20px 15px',
					'position': 'relative'
				}
			}).adopt(header_wrap,content_wrap,footer_wrap),
			new Element('td',{
				styles: {
					'border-right': '7px solid #ffbc2a',
					'background-color': 'white'
				}
			})
		),
		new Element('tr').adopt(
			overlay_bl,
			new Element('td',{
				styles: {
					'border-bottom': '7px solid #ffbc2a',
					'background-color': 'white'
				}
			}),
			overlay_br
		)
	);

	overlay_bknd.inject($('header_wrap')||$('header'),'before');
	overlay_table.inject(overlay_bknd,'inside');
}

/* Video Overlay */

function videoOverlay(embed_tag,w,h){

    var winHeight = window.innerHeight?window.innerHeight:window.screen.availHeight;

    var mTop = (winHeight/2) - (h/2);

    var overlay_bknd = overlayBknd();

    var overlay_close = new Element('span',{

        text: 'close',

        styles: {

            'background': 'url(/images/overlay_close_x.png) no-repeat right top',

            'display': 'block',

            'width': 65,

            'height': 18,

            'text-align': 'right',

            'position': 'absolute',

            'top': 4,

            'right': 4,

            'padding-right': 22,

            'color': '#000',

            'font-size': 14,

            'font-family': 'AvenirLTStd35Light,sans-serif',

            'cursor': 'pointer'

        },

        events: {

            click: function(){

                this.tween('opacity',0);

            }.bind(overlay_bknd)

        }

    });

    var content_wrap = new Element('div',{

        id: 'content_wrap',

        html: embed_tag,

        styles: {

            'position': 'relative',

            'width': w,

            'height': h,

            'margin': mTop+'px auto 0',

            'padding': '25px 10px 10px',

            'background-color': 'white',

            'border-radius': '5px',

            '-moz-border-radius': '5px'

        }

    }).adopt(overlay_close).inject(overlay_bknd);

    overlay_bknd.inject($('header_wrap'),'before');

}

function register(){
	$('quick_register').set('action','/ajax/register');
	$('quick_register').getElements('input[type!=button],select-one,select').set('disabled',false);
	$('quick_register').submit();
}
function login(){
	$('quick_register').set('action','/ajax/login');
	$('quick_register').getElements('input[type!=button],select-one,select').set('disabled',true);
	$('quick_register').getElements('input[name=username],input[name=password]').set('disabled',false);
	$('quick_register').submit();
}
function calculate(){
	var target = Number( $('c_target').get('value') );
	
	if(target){
		if(target > 1 && target < 21)
			showMessage('We recommend you try Plan 3 to achieve your target weight of '+target+' lbs');
			
		else if(target > 20 && target < 41)
			showMessage('We recommend you try Plan 2 to achieve your target weight of '+target+' lbs');
		else if(target > 40)
			showMessage('We recommend you try Plan 1 to achieve your target weight of '+target+' lbs');
	} else {
		showMessage('Please enter your target weight.');
	}
	
	return false;
}
function searchBy(field,txt,target,ds){
	var tmp = [];
	if(txt){		
		Array.each(ds,function(el,index){
			if(el[field] == txt)
				tmp.push(el);
		});
		target.ds = tmp;
	} else {
		target.ds = ds;
	}
	target.update();
}

/* jsUploader v1.0 */
var jsUploader = new Class({
	Implements:[Options,Events,Chain],
	options:{
		onRequest:null,
		onComplete:null,
		onSuccess:null,
		onFailure:null,
		'class':null,
		method:null
	},
	holder:null,
	status:0,
	queue:[],
	transport:null,
	initialize:function(holder, options){
		this.holder = holder;
		if(!this.holder)
			return false;
		
		this.setOptions(options);
		this.setup();
	},
	setup:function(){
		this.transport = new XMLHttpRequest();
		this.transport.onreadystatechange = function(e){
			//console.log('onreadystatechange', arguments);
		}.bind(this);
		this.transport.onerror = function(e){
			//console.log('onerror', arguments);
			this.fireEvent('failure', [e.target.status, e.target]);
		}.bind(this);
		this.transport.upload.onprogress = function(e){
			var loaded = e.loaded, total = e.total; 
			var progress = parseInt(loaded / total * 100, 10);
			this.update(loaded, progress);
		}.bind(this);
		this.transport.onload = function(e){
			//console.log('onload', arguments);
			this.fireEvent('complete', e.target);
			var json;
			try {
				if(e.target.response){
					json = JSON.decode( e.target.response );
				}
			} catch(err){
				if(window.console)
					console.error('onload[error]', err.message);
			}
			
			this.fireEvent('success', [json, e.target.responseText]);
			//this.transport.onsuccess(json, e.target.responseText);
		}.bind(this);
		this.transport.onloadstart = function(e){
			//console.log('onloadstart', arguments);
			this.fireEvent('request', [e.target, this]);
		}.bind(this);
		
		this.transport.upload.onerror = this.transport.onerror;
		//this.transport.upload.onprogress = this.transport.onprogress;
	},
	transfer:function(target, params){
		if(!target.files.length)
			return;
		
		var fd = new FormData();
		fd.append('requestedClass', this.options['class']);
		fd.append('requestedMethod', this.options['method']);
		
		if(params != undefined){
			if(typeof params != "object")
				fd.append('params', params);
			else
				for(key in params)
					fd.append(key, params[key]); //Append each key to the fd
		}
		
		var field = (this.options.filename)? this.options.filename : 'userfile';
		if(target.files.length == 1)
			fd.append(field, target.files[0]);
		else {
			Array.each(target.files, function(el){
				fd.append(field + '[]', el);
			}.bind(this));
		}
		
		this.start(fd); //Starts the transfer process
	},
	start:function(fd){
		//A request was made to start the upload
		this.transport.open("POST", location.pathname, true);
		this.transport.setRequestHeader('X-Request', 'JSON');
		this.transport.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        	
        	this.prepare();
        	this.transport.send(fd);
	},
	prepare:function(){
		//Make the progress bar and attaches it
		this.bar = new Element('div', {'class':'progressbar'});
		this.indicator = new Element('div', {'class':'indicator', styles:{'width':0, 'display':'inline-display'}});
		this.bar.adopt(this.indicator);
		this.holder.empty(); //Clears it out first
		this.holder.adopt(this.bar);
	},
	update:function(loaded, progress){
		//Renders the progress bar
		//console.log("onProgress: ", progress);
		var w = parseInt(this.bar.getStyle('width'));
		var i = progress / 100;
		var p = w * i;
		this.indicator.tween('width', p);
	}
});

/* openBox overlay */
function openBox(content, notify, width){
	//This will open a modal box window over the shell element
	var modalBox = closeBox();
	var first = modalBox.getNext();
	var c = new Element('div', {'class':'content', styles:{'max-height':600,'overflow-y':'auto'}});
	if(typeof content == "string")
		c.set('html', content);
	else
		c.adopt(content);
	
	width = (width)? parseInt(width) : parseInt(modalBox.getElement('div.inside').getStyle('min-width')); //Sets the default size for the modal
	modalBox.getElement('div.inside').setStyle('width', width).adopt(c);
	modalBox.show().fade('in'); //Show the modalBox
	first.fade(.2);  //Fade the shell's to 0.3
	modalBox.store('onClose', notify);
}

function closeBox(){
	var modalBox = $('modalBox');
	var first = (modalBox)? modalBox.getNext() : document.body.getFirst();
	if(modalBox){
		modalBox.set('tween', {transition:Fx.Transitions.Bounce.easeOut}); //Set the tween
		modalBox.hide().fade('out');
		var onClose = modalBox.retrieve('onClose');
		if(onClose && typeof onClose == "function")
			onClose(modalBox.getElement('div.content')); //Executes the function passing in the modalBox content element
			
		modalBox.empty();
	} else {
		modalBox = new Element('div', {'id':'modalBox', 
			styles:{display:'none', position:'fixed', top:'0px', bottom:'0px', left:'0px', right:'0px', overflow:'auto', 'z-index':1000}
		});
		
		modalBox.inject(first, 'before'); //Inject itself before the shell element
	}
	
	//Inject the handler element
	var inside = new Element('div', {'class':'inside', styles:{padding:'8px 12px 8px 12px', border:'1px solid #dfdfdf', background:'#eaeaea', margin:'10px auto','min-width':600,'min-height':200}});
	inside.adopt( new Element('div', {'class':'handler', html:'x', align:'right',
		styles:{
			'font-weight':'bold',
			color:'firebrick',
			cursor:'pointer'
		},
		events:{
			click:closeBox
		}
	}));
	modalBox.adopt(inside);
	
	modalBox.set('tween', {transition:Fx.Transitions.Bounce.easeIn}); //Set the tween again
	first.fade(1); //Restore the shell's fade to 1.0
	
	return modalBox;
}
/* end openBox overlay */

