//////////////////////////////////////////////
//Simple Class that handles default form data
//Just create a new instance and refer to the 
//id of the form element
/////////////////////////////////////////////a

var toggleFormData	=	Class.create({

	initialize: function(id, options) {
		if(typeof id != 'string') {
			alert('you must provide an id');
		} else {
			this.id				=	id;
			this.defaultText	=	$(this.id).value;
			if(options != '') {
				this.validate 	= options.validate;
				this.validator 	= options.validator;
				this.errorMessage	=	options.errorMessage;
			}
			//setup observers and bind the object to them
			$(this.id).observe('blur', this.defaultFormText.bindAsEventListener(this));
			$(this.id).observe('focus', this.removeFormValue.bindAsEventListener(this));
		}
	},
	
	removeFormValue: function(e) {
		if(this.defaultText == $(this.id).value) {
			var message 	=	this.errorMessage;
			$(this.id).value = "";
			$(this.id).observe('keyup', function() {
				if(!validateEmail($(this.id).value)) {
					$('searchoutput').update(message);
				} else {
					//window.addEmailToCampaignMonitor($F(this.id), $F('formname'));
					$('searchoutput').update($F('formname'));
				}
			});
		}
	},
	
	defaultFormText: function(e) {
		if($F(this.id) == '') {
			$(this.id).value = this.defaultText;
		} 
	}
});

//////////////////////////////////////////////
//Create new instance of toggleFormData
//------options-----
//validate: 'email' {currently only option available}
//validator: this is the name of the email validator
//errorMessage: the string output which you'd like to have displayed
/////////////////////////////////////////////
var myForm = new toggleFormData('addr', {
	validate: 'email', //optional
	validator: 'validateEmail',
	errorMessage: 'enter your email address:'
});

//third party validator
function validateEmail(text) {
	var pattern = /^[^@]+@[^@]+.[a-z]{2,}$/i;
	var test 	= text.search(pattern);
	if(test == -1) {
		return false;
	} else {
		return true;
	}
}


////////////////////////////////////////////
//Added by Justin - Paypal Reg form functions
///////////////////////////////////////////
function doTotal(){
 if(document.forms['paypal'].os1.value==''){document.forms['paypal'].os1.value=0;}
 if(document.forms['paypal'].os2.value==''){document.forms['paypal'].os2.value=0;}
 tmpTotal=(parseFloat(document.forms['paypal'].os1.value) * parseFloat(document.forms['paypal'].cost.value)) + parseFloat(document.forms['paypal'].os2.value);
 document.forms['paypal'].amount.value=tmpTotal;
 document.getElementById('total').innerHTML=tmpTotal;
}

function formProc(){
 doTotal();
 if(document.forms['paypal'].os0.value==''){
  alert('Please enter the name of the person who is registering.');
  document.forms['paypal'].os0.focus();
 }else{
  document.forms['paypal'].submit();
 }
}

////////////////////////////////////////////
//Load Overlay with button to remove
///////////////////////////////////////////
$('content').observe('click', function(e) {
	var ele	=	e.target;
	var elId = $(ele).id;

	var	bodyel	=	document.getElementsByTagName('body')[0];
	if( ($(ele).tagName == 'IMG' && $(ele).up().tagName == 'A') || ($(ele).tagName == 'A' && $(ele).hasClassName('donatelink')) ) {

		//check if overlay exists
		if(!$('overlay')) {
			//does the element have an id set
			if($(ele).id) {
				//insert the overlay
				$(bodyel).insert({top:'<div id="overlay">'});
				$(bodyel).insert({bottom:'</div>'});
				//build the url - id needs to match the page name
				var url	=	'/'+$(ele).id+'.html';
				new Ajax.Request(url, {
					onLoading: function(t) {
						var img	=	"<img src=\"/assets/images/icn_loading.gif\" id=\"loader\" />";
						$('content').insert({
							top: img
						});
					},
					onComplete: function(t) {
						$('loader').remove();
						var text	=	t.responseText;
						$('content').insert({
							top: text
						});
					}
				});
			}
		} else {
			if($(ele).tagName == 'IMG' && $(ele).hasClassName('closebox')) {
				$(ele).up(1).remove();
				var parent = $(ele).getOffsetParent();
				if($('overlay')) {
					$('overlay').remove();
				}
			}
		}
	} else {
		if($(ele).tagName == 'IMG' && $(ele).hasClassName('closebox')) {
			$(ele).up(1).down().remove();
			var parent = $(ele).getOffsetParent();
			if($('overlay')) {
				$('overlay').remove();
			}
		}
	}
});


/////////////////////////////////////////////////
//Calendar overlay
/////////////////////////////////////////////////

if($('vol_cal')) {
	var events = $$('.eventitem');
	$('vol_cal').observe('click', function(e) {
		var item = e.target;
		if(item.tagName == 'A' && $(item).up().hasClassName('eventitem')) {
			var eid = $(item).id;
			eid = eid.split("_");
			var	bodyel	=	document.getElementsByTagName('body')[0];
			$(bodyel).insert({top:'<div id="overlay">'});
			$(bodyel).insert({bottom:'</div>'});
			var url	=	'/get_vol_event?id='+eid[1];
			new Ajax.Request(url, {
				onLoading: function(t) {
					var img	=	"<img src=\"/assets/images/icn_loading.gif\" id=\"loader\" />";
					$('content').insert({
						top: img
					});
				},
				onComplete: function(t) {
					$('loader').remove();
					var text	=	t.responseText;
					$('content').insert({
						top: text
					});
				}
			});
		}
	});
	
}



if($('eventform')) {
	$('eventform').observe('change', function() {
		amount	=	($F('donatecost') * $F('eventqty'));

		additionals	=	$$('.additional');
		addMore		=	0;
		for(i=0; i<additionals.length; i++) {
			addMore	+=	$(additionals[i]).value * 1;
		}
		amount	=	amount+addMore;

		if($('mailinglist').checked) {
			$('mlval').update('Yes');
			$('USER10').value	=	'true'
		} else {
			$('mlval').update('No');
			$('USER10').value	=	'false'
		}

		//$('totalamount').update('TOTAL AMOUNT:'+amount);
		$('AMOUNT').value	= amount;
	});
}

if($('eventform')) {
	$('eventform').observe('submit', function() {
		if($('eventqty').value == '') {
			$('eventqty').value = '1';
			amount		=	($F('donatecost') * $F('eventqty'));
			additionals	=	$$('.additional');
			addMore		=	0;
			for(i=0; i<additionals.length; i++) {
				addMore	+=	$(additionals[i]).value * 1;
			}
			amount	=	amount+addMore;
			//$('totalamount').update('TOTAL AMOUNT:'+amount);
			$('AMOUNT').value	= amount;

		}
	});
}

function addEmailToCampaignMonitor(email, formname) {
	
	url	=	'/assets/snippets/campaign_monitor/Subscriber.AddWithCustomFields.php?e='+email+'&formname='+formname;
	
	new Ajax.Request(url, {
		onSuccess: function(t) {
			alert(t.responseText);
		}
	})
	
}

var InsertContent = Class.create({
	
	initialize: function() {
		
	},
	
	insert: function(id) {
		
	}
	
});

/*
	Event class
	handles loading event data from and Ajax request
	and updates the event info based on the main event navigation
	and sub tabs of each event
*/

var Events = Class.create({
	
	initialize: function(obj, options) {
		this.section			=	options.section; //which nav bar was clicked
		this.obj				=	obj; //the id of the tab menu, used to create new tab object
		this.load_into			=	options.load; //the id to load into
		this.current_tab;
		this.subid;
		this.r;
		
		//event properties
		this.event_title;
		this.event_code;
		this.gallery;
		this.ticket_form;
		this.promo_text;
		this.location_text;
		this.date_time;
		this.description_text;
		this.main_sponsor;
		this.sponsor_text;
		
		//test if a default tab is specified, default to overview
		if(typeof options.default_tab === 'undefined') {
			this.current_tab 	= 'overview'
		} else {
			this.set_current_tab(options.default_tab);
			this.load_data(this.current_tab);
		}
		
		new PeriodicalExecuter(this.check_change.bind(this), 1);
	},
	
	//sets current tab
	set_current_tab: function(tab_name) {
		
		this.current_tab = tab_name;
		this.obj.set_default_tab(this.current_tab);
		
	},
	
	//tests for tab changes
	check_change: function() {
		
		if(this.current_tab != this.obj.getCurrent()) {
			this.current_tab = this.obj.getCurrent();
			this.load_data(this.current_tab);
		}
		
	},
	
	//loops through the subnav and set the active state
	get_sub_id: function() {
		var subs = $$('.sub_name');
		for(i=0; i<subs.length; i++) {
			if($(subs[i]).hasClassName('active')) {
				this.subid = $(subs[i]).down().id;
			}
		}
	},
	
	//loops through the mainnav and set the active state
	get_main_id: function() {
		var main = $$('.event_name');
		for(i=0; i<main.length; i++) {
			if($(main[i]).hasClassName('active')) {
				this.mainid = $(main[i]).down().id;
			}
		}
		
	},
	
	
	//get the event data from the server,
	//a tab id is passed which decides which data is output
	load_data: function(id) {
		
		var loadto = this.load_into;
		this.get_sub_id();
		this.get_main_id();
		var params	=	{'page':this.mainid, 'subid':this.subid};
		
		//get the data
		new Ajax.Request('/load.html', {
			parameters:params,
			method: 'post',
			
			//show loader
			onLoading: function() {

				var overlay = new Element('div', {id:'overlay', position: 'absolute', top: '0px', left: '0px', width: '100%', height: '100%'}).update('<div id="large_loader" class="loader"><img src="/assets/images/ajax-loader-large.gif" />');
				
				$('event_holder').insert({
					top: overlay
				});
			},
			
			//get the response
			onComplete: function(r) {

				$('overlay').remove();
				this.r = json_parse(r.responseText);
				this.output();
				
			}.bind(this)
			
		});
		
	},
	
	output: function() {

		$('event_logo').update(new Element('img', {src:this.r.event_logo}));
		if(this.r.main_sponsor === 'COMING SOON' || this.r.main_sponsor === '') {
			
			$('sponsored_by').setStyle({
				display: 'none'
			});
			
		} else {
			
			$('sponsored_by').setStyle({
				display: 'block'
			});
			
			$('main_sponsor').update(this.r.main_sponsor);
			
		}
		
		$('event_date').update(this.r.event_date);
		$('event_name').update(this.r.event_name);
		$('event_info').update(this.r.event_info);
		$('event_location').update(this.r.location);
		$('event_description').update(this.r.description);
		this.set_overview(this.subid);
	},
	
	set_overview: function(id) {

		switch(id) {
			
			case 'photos':
			$('event_overview').update(this.r.gallery);
			break;
			
			case 'details':
			$('event_overview').update(this.r.full_detail);
			break;
			
			case 'overview':
			$('event_overview').update(new Element('img', {src:this.r.main_image}))
			break;
			
			case 'sponsors':
			$('event_overview').update(this.r.sponsor_list);
			break;
			
			case 'buytickets':
			$('event_overview').update(this.r.ticket_form);
			//new ticket form, handles quantity and total per item
			var tix = new TicketsForm(this.r.prods);
			break;
			
		}
		
	}
	
});


/*
	Donate class
	handles working with and updating donate form fields,
	prepping hidden fields to be passed to the payment gateway
*/
var Donate_Form = Class.create({
	initialize: function(p, d) {
		if(typeof d !== 'undefined') {
			this.d = d.amount;
		} else {
			this.d = 0;
		}
		
		this.event_code = p.code;
		this.event_name = p.event_name;

		
		if(typeof p === 'undefined') {
			return false;
		}
		if(typeof p.formid === 'undefined') {
			this.form = $('paypal_form');
		} else {
			this.form = p.formid;
		}
		
		if(typeof p.load === 'undefined') {
			this.load = 'inline';
		} else {
			this.load = 'ajax';
		}
		
		if(typeof p.href !== 'undefined') {
			this.href = p.href;
		}
		this.link = $$('.donate_link');
		
		this.callback = 'load_'+this.load;
		$(this.link[0]).observe('click', this.load_overlay.bind(this));
		
		
	},
	
	load_ajax: function(d) {
		var eventcode = this.event_code;
		var cost = this.d;
		var event_name = this.event_name;

		new Ajax.Request(this.href, {
			onLoading: function() {
				this.body = document.getElementsByTagName('body')[0];
				var ol	= new Element('div', {id:'overlay'});
				this.body.insert({top:$(ol)});
				$(ol).update(new Element('img', {src:'/assets/images/icn_loading.gif'}));
			},
			
			onComplete: function(r) {
			
				if($('overlay')) {
					//build form
					var form = new Element('form', {id:'paypal_form', action:'https://payflowlink.paypal.com', method:'post'});
					var closebox = new Element('a', {className:'closebox', href:'javascript:;'}).update(new Element('img', {src:'/assets/images/closebox.png'}));
					var amount_form = new Element('input', {type:'text', id:'donate_amount', name:'donate_amount'});
					var qty_label = new Element('label', {'for':'donate_qty'}).update('How Many?');
					var qty_form = new Element('input', {type:'text', id:'donate_qty', name:'donate_qty', value: '1'});
					var login = new Element('input', {type:'hidden', id:'login', name:'LOGIN', value: 'NEARANDFARAID'});
					var partner = new Element('input', {type:'hidden', id:'partner', name:'PARTNER', value: 'VERISIGN'});
					var type = new Element('input', {type:'hidden', id:'type', name:'TYPE', value: 'S'});
					var amount = new Element('input', {type:'hidden', id:'amount', name:'AMOUNT', value: ''});
					var custom1 = new Element('input', {type:'hidden', id:'amount', name:'USER1', value: eventcode});
					var submit = new Element('input', {type:'submit', className:'submit buttonlink', value:'submit'});
					var eventname = '<div id="tix_event">'+event_name+' $'+cost+'</div>';

					
					
					$(form).insert({
						top:qty_label
					});
					
					$(form).insert({
						bottom:qty_form 
					});
					
					$(form).insert({
						bottom:submit 
					});
					
					$(form).insert({
						top:login 
					});
					
					$(form).insert({
						top:partner 
					});
					
					$(form).insert({
						top:type 
					});
					
					$(form).insert({
						top:amount 
					});

					$(form).insert({
						top:eventname
					});
					
					$(form).insert({
						top: new Element('img', {src:'/assets/images/events-title-buytickets.png', id:'buy_title'})
					})
					
					$(form).insert({
						top:closebox 
					});
					
					$(form).insert({
						bottom:custom1 
					});
					
					
					$('overlay').update(form)
					this.closebox = $$('.closebox');
					$(this.closebox[0]).observe('click', remove_overlay);
					$('amount').value = cost;
					
					if($('donate_qty')) {
						$('donate_qty').observe('change', function() {
							$('amount').value = cost * $('donate_qty').value;
							//alert($('amount').value)
						})
					}
				}
			}
		});
	},
	
	load_inline: function() {
		this.body = document.getElementsByTagName('body')[0];
		var ol	= new Element('div', {id:'overlay'});
		this.body.insert({top:$(ol)})
		$(this.form).setStyle({
			visibility: 'visible',
			display: 'block',
			zIndex: '9999'
		})
		this.closebox = $$('.closebox');
		$(this.closebox[0]).observe('click', this.remove_overlay.bind(this));
	},	
	
	load_overlay:function() {
		
		var callback = this.callback;
		this.closebox  = $$('.closebox');
		this[callback].apply(this);
		
	},
	
	remove_overlay: function() {
		//alert('here')
		$('overlay').remove();
	},
	
	kill_observe: function() {
		$(this.link[0]).stopObserving();
	},
	
	set_amount: function() {
		alert('this.d')
	},
	
	set_donateform: function() {
		return {formid:'donate'};
	}
	
});


var PayPal_Payment = Class.create({
	
	initialize: function(id, parameters) {
		this.param = parameters.serialize();
	},
	
	send: function() {
		
	}
});

function remove_overlay() {
	$('overlay').remove();
}

//////////////////////
//sets up tab function on event pages
if($('event_main')) {
	var enav = new Tabs('enav', {
				className: 'event_name',
				tabStyle: 'tab'
			});

	var subnav = new Tabs('snav', {
				className: 'sub_name',
				tabStyle: 'tab'
			});
	
}


//////////////////////
//Handles ticket form and processing
var TicketsForm = Class.create({
	
	initialize: function(products) {

		this.total = 0;
		this.products = new Array();
		this.qty	 = new Array();
		this.type	= new Array();
		this.attendees = '';
		this.field = Form.getInputs('ticketsform', 'text');
		var fieldlen = this.field.length;
		this.comment1 = new Array();
		this.comment2;
		
		for(i=0; i<products.length; i++) {
			
			this.products[products[i].sku] = products[i].cost;
			this.qty[products[i].sku] = 0;
			this.type[products[i].sku] = products[i].type;
		}
		
		for(i=0; i<fieldlen; i++) {
			
			$(this.field[i].id).observe('change', this.update_total.bind(this, this.field[i].id));
			
		}
		
		$('ticketsform').observe('submit', this.prep.bind(this));
		
	},
	
	update_total: function(id) {

		this.total = 0;
		for(k in this.products) {
			
			if (this.products.hasOwnProperty(k)) {
			        var next = $(k).up().next();
					switch(this.type[k]) {
						
						case 'ticket':

						if(typeof $(k).value === 'undefined' || $(k).value == '0' || isNaN($(k).value)) {
							
							var kval = $(k).value;
							var match = isNaN(kval);
							
							var itemtotal = '0';
							$(k).value = '0';
							$(next).update('$0')
							
							this.update_qty(k, '0');
							
						} else {
							this.update_qty(k, $(k).value);
							total = ($(k).value * this.products[k]) + (this.total * 1);
							this.total = total;
							
							this.comment1[k] = $(k).value;
							
							if($(next).className == 'item_total') {
								
								var itemtotal = this.qty[k] * this.products[k];
								$(next).update('$'+itemtotal)
																
							}
							
						}
						break;
						
						case 'donation':
						
						if(typeof $(k).value === 'undefined' || $(k).value == '0' || isNaN($(k).value)) {
							var itemtotal = '0';
							$(k).value = '0';
							$(next).update('$0')
							
							this.update_qty(k, '0');
						} else {
							var money = this.format_currency($(k).value)
							this.total = ($(k).value * 1) + (this.total * 1);
							this.comment1[k] = $(k).value;

							if($(next).className == 'item_total') {
								var itemtotal = ($(k).value * 1);
								$(next).update('$'+money)
							}
							
						}
						
						
						
						break;
						
					}
					
			
			    }
			
			
		}

		$('ticket_total').update(this.total);
		
	},
	
	update_qty: function(code, qty) {
		this.qty[code] = qty;
	},
	
	format_currency: function(value) {

		var nums = value.length;

		var seperator = 3;
		var digits = new Array();
		var formatted = '';
		for(i = nums; i > 0; i--) {
			
			if(i == 1 && value[i-1] == '0') {
				//skip
			} else {
				digits.push(value[i-1]);
				if(seperator == 1) {
					if(i > 1) {
						digits.push(',');
					}
					seperator = 3;
				} else {
					seperator--;
				}
			}
			
			
		}

		formatted = digits.reverse().join('');
		return formatted;
		
	},
	
	
	prep: function() {
		
		for(k in this.qty) {
			
			if (this.qty.hasOwnProperty(k)) {
				
				if(this.type[k] == 'ticket') {
					if(this.qty[k] > 0) {
						this.comment1 += k + ':' + this.qty[k] + ',';
					}
					
				}
				
				if(this.type[k] == 'donation') {
					if($(k).value > 0) {
						this.comment1 += k + ':$' + $(k).value + ',';
					}
					
				}
				
				
			}
			
		}
		

		$('comment1').value = this.comment1;
		$('comment2').value = $('attendees').value;
		$('amount').value = this.total;
		setTimeout(	this.send(), 1000 );
		var overlay = new Element('div', {id:'overlay', position: 'absolute', top: '0px', left: '0px', width: '100%', height: '100%'}).update('<div id="large_loader" class="loader"><img src="/assets/images/ajax-loader-large.gif" />');
		

		
		
	},
	
	send: function() {
		$('ticketsform').submit();
	}
	
})