var AWSM_Form = Class.create({
    /*
     Function: initialize
     Constructor for Lister Class.
     
     Parameters:
     el - {Mixed} the HTML object that Lister is initialize from. This can be either an HTML Object or ID to an HTML object.
     opt  - {Object} config Object
     */

     
    initialize: function(el, opt){
        el = $(el);
		this.controls = new Array();
        opt = opt || {};
        this.options = {
			el: el,
        };
  		Object.extend(this.options, opt);
  		Object.extend(this, this.options);

		this.getRequired();
		this.getPhones();
		this.getEmails();
		
		el.select('input[type=submit]').invoke('observe','click',function() {
			return this.preSubmit();
		}.bind(this));

		el.select('textarea').invoke('observe','keyup',function(el) {
			this.value = this.value.truncate(200,'');
		});
		
		
 		
    },

	getRequired: function()	{

			this.el.select('.required').each(function(el)	{
				this.controls.push(new AWSM_ValidationControl(el));
			}.bind(this));
			
	},

	getPhones: function()	{

			this.el.select('input.phone').each(function(el)	{
				this.controls.push(new AWSM_Phone(el));
			}.bind(this));		

	},

	getEmails: function()	{

			this.el.select('input.email').each(function(el)	{
				this.controls.push(new AWSM_ValidationControl(el));
			}.bind(this));		

	},
	
	preSubmit: function()	{
		
		// turn off all warnings
		this.turnOffWarnings();
		
		this.controls.each(function(el)	{
			el.beforeValidation();
		});

		//console.log(this.el.serialize(true));
		//console.log(this.toJSON());
		//console.log(Object.toJSON(this));
		
		//send for validation
		new Ajax.Request('/inc/Calendar/Validate.php',
			{	
				'parameters':	{'json':this.toJSON()},
				'onSuccess':	function(trn)	{
					if (trn.responseJSON)	{
						this.turnOnWarnings(trn.responseJSON);
					}	else	{
						this.el.submit();
					}
				}.bind(this)
			}
						);
	},
	
	toJSON: function()	{
		var h = new Hash;
		this.controls.each(function(el)	{
			h.set(el.el.id,{'class':el.el.className,'value':el.el.value,'msg':el.el.title});
		});
		return Object.toJSON(h);
	},
	
	turnOnWarnings: function(j)	{
		j = $H(j);
		j.each(function(jj)	{
			$('valid_' + jj.key).update('<p>' + jj.value + '</p>').show();
		});
	},
	
	turnOffWarnings: function()	{
		$$('.msg').invoke('hide');
	}
	
});
	




var AWSM_ValidationControl = Class.create({
    /*
     Function: initialize
     Constructor for Lister Class.
     
     Parameters:
     el - {Mixed} the HTML object that Lister is initialize from. This can be either an HTML Object or ID to an HTML object.
     opt  - {Object} config Object
     */
     
    initialize: function(el, opt){
        el = $(el);
		el.identify();
        opt = opt || {};
        this.options = {
			el: el 
        };
  		Object.extend(this.options, opt);
  		Object.extend(this, this.options);

		this.msg = new Element('div',{'class':'msg','style':'display:none','id':'valid_'+this.el.identify()}); 		
		this.el.insert({after: this.msg});
 	 		
    },

	beforeValidation: function()	{
		
	}

	
});


var AWSM_Phone = Class.create({
    /*
     Function: initialize
     Constructor for Lister Class.
     
     Parameters:
     el - {Mixed} the HTML object that Lister is initialize from. This can be either an HTML Object or ID to an HTML object.
     opt  - {Object} config Object
     */
     
    initialize: function(el, opt){
 
       	el = $(el);
		el.identify();
        opt = opt || {};
        this.options = {
			el: el 
        };
  		Object.extend(this.options, opt);
  		Object.extend(this, this.options);

		this.msg = new Element('div',{'class':'msg','style':'display:none','id':'valid_'+this.el.identify()}); 		
		this.el.insert({after: this.msg});
 		
  		this.splitUpInputs();
		this.splitNumber();
 		
    },

	splitUpInputs: function()  {
          
		this.area_code = new Element('input',{'type':'text', 'class':'phone', 'name':this.el.name+'1', 'id':this.el.name+'1', 'maxlength':3});
		this.exchange = new Element('input',{'type':'text', 'class':'phone', 'name':this.el.name+'2', 'id':this.el.name+'2', 'maxlength':3});
		this.sln = new Element('input',{'type':'text', 'class':'phone switch', 'name':this.el.name+'3', 'id':this.el.name+'3', 'maxlength':4}); 
		
		this.el.insert({before: this.area_code});
		this.el.insert({before: this.exchange});
		this.el.insert({before: this.sln});
 		this.el.hide();

	},
	
	splitNumber: function()	{
		
		var ph = this.el.value.split('-');
		this.area_code.value = ph[0] ? ph[0] : '';
		this.exchange.value = ph[1] ? ph[1] : '';
		this.sln.value = ph[2] ? ph[2] : '';
		
	},
	
	joinNumber: function()	{

		this.el.value = this.area_code.value + '-' + this.exchange.value + '-' + this.sln.value;

	},
	
	beforeValidation: function()	{

		this.joinNumber();

	}
    
  });


Event.observe(window, 'load', function() {


	$$('form.validate').each(function(fm)	{


		var f = new AWSM_Form(fm);
/*		
		fm.onsubmit = function()	{
			fm.getElements().each(function(el)	{
				el.beforeValidation();
			});
			console.log(fm.serialize(true));
			return false;
		}

		fm.select('input.phone').each(function(el)	{
			this.ph = new AWSM_Phone(el);
		});
*/

var issue_Picker = new Control.DatePicker('event_date', {
											icon: '/js/datepicker/calendar.png',
											dateFormat: 'EE, MMM d, yyyy',
											onSelect: function(dt)  {
											$('event_date').update(dt.format('DD, MMM d, yyyy'));
											}
											});
});

if ($('event_location'))	{

new Ajax.Autocompleter("event_location", "event_location_choices", "/inc/modules/venue_list.php", {
				 		paramName: "ven",
						minChars: 2,
						afterUpdateElement: function(field,li) {
					 		field.value = li.innerHTML;
							new Ajax.Updater('location_address','/inc/modules/event_location_address.php',{'parameters':{'ven':li.id}});
					 	},
						indicator: 'event_location_indicator'
					});

}

if ($('public_contact_name'))	{
	
$('public_contact_name').observe('blur',function(el)	{
	fieldMirror('public_contact_name','private_contact_name');
});
$('public_phone1').observe('blur',function(el)	{
	fieldMirror('public_phone1','private_phone1');
});
$('public_phone2').observe('blur',function(el)	{
	fieldMirror('public_phone2','private_phone2');
});
$('public_phone3').observe('blur',function(el)	{
	fieldMirror('public_phone3','private_phone3');
});
$('public_email').observe('blur',function(el)	{
	fieldMirror('public_email','private_email');
});
$('public_website').observe('blur',function(el)	{
	fieldMirror('public_website','private_website');
});

}

  	//ChangeCalendarListing();

	hookCalendarPicker();

	$$('.bo_Filter').invoke('observe','change',function()	{
		$(this.name).disabled = this.getValue() ? false : true;
	});
		
	$$('.erase').invoke('observe','focus',function()	{
		this.value = '';
	});
		
	$$('.catch_enter').invoke('observe','keydown',function(ev)	{
		if (ev.keyCode == 13)	{
			TriggerCalendarLoad(this.up('form'),this.value);
		}
	});

	$$('.trigger').invoke('observe','change',function()	{
		TriggerCalendarLoad(this.up('form'),this.value);
	});

/*
	$$('.fp_Folder').invoke('observe','click',function()	{
		fp_Fold(this.id);
	});

	$('more_settings').observe('click',function(ev)	{
		var cs = $('calendar_settings');
		console.log(ev);
		cs.setAttribute('top', ev.pointerY() + 15);
		cs.setAttribute('left', ev.pointerX());
		alert(cs.left);
		cs.toggle();
	});
*/

});
	

	function TriggerCalendarLoad(f,v)	{
		if ($('cal_form'))	{
			ChangeCalendarModule();
		}	else if ($('fm_Calendar'))	{
			//alert(Sortable.serialize('lb_CalendarSettingsOrderID',{'name': 'balls'}));
			f.setAttribute('action', '/Calendar/' + v);
			f.submit();
		}
	}


	function hookCalendarPicker()	{

		$$('table.fp_CalendarPicker').invoke('observe','click',function(ev)	{
			var el = ev.element();
			var dt = el.title;
			if (!dt.blank())	{
				
				if (el.hasClassName('traverse_months'))	{
			    new Ajax.Updater($('fp_CalendarPicker'),"/inc/modules/calendar_picker.php",{
			    	parameters:	{
			    		date: dt,
			    		viewdate: $('date').value
			    	},
					onComplete: function(){hookCalendarPicker()}
			    });
			    
				}	else	{
			
					$$('td.viewdate').invoke('removeClassName','viewdate');
					el.addClassName('viewdate');
					$(this.title).value = dt;
					TriggerCalendarLoad($(this.title).up('form'),dt);
					
				}
			
			}
			
		});
		
	}


	function ChangeCalendarModule()	{
		
		//console.log($('cal_form').serialize(true));

		var aj = new Ajax.Updater('ul_Calendar_Module','/inc/calendar_module.php',
		{
			onCreate: showIndicator('ul_Calendar_Module'),
			parameters: $('cal_form').serialize(true),
			onComplete: function(){$('progress').className = "off";}
		}
		);		
	}



	function getVenueListQuery(a,b)	{
		return b;
	}

	function getSelectionId(li, text) {
		TriggerCalendarLoad(li.up('form'),li.id);
	}



	function showIndicator(el)	{
		el = $(el);
		el.down(0).next('dl').update('<dd style="text-align: center; list-style-type: none;"><img src="/images/site/Utility/indicator_b.gif"><br>LOADING...</dd>');
	}
	
	
	function fieldMirror(el1,el2)	{
		el1 = $(el1);
		el2 = $(el2);
		if (!el2.value)	{
			el2.value = el1.value;
		}
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////
//	DEPRECATED?  STILL NEED?

	function DecodeCheckboxes(srl)	{
		
		//alert("#1: " + srl);

		if (!srl)	{
			//var srl = Sortable.serialize('lb_CalendarSettingsOrderID');
		}
		
		srl = srl.replace(/lb_CalendarSettingsOrderID\[\]\=/g,'');

		//alert("#2: " + srl);
			
		if($('ck_Events').checked)	{
			srl = srl.replace(/Events/,'Ev');
		}	else	{
			srl = srl.replace(/Events/,'ev');
		}
		
		if($('ck_Performance').checked)	{
			srl = srl.replace(/Performance/,'Pf');
		}	else	{
			srl = srl.replace(/Performance/,'pf');
		}
		
		if($('ck_Theatre').checked)	{
			srl = srl.replace(/Theatre/,'Th');
		}	else	{
			srl = srl.replace(/Theatre/,'th');
		}
		
		if($('ck_LiveMusic').checked)	{
			srl = srl.replace(/LiveMusic/,'Lm');
		}	else	{
			srl = srl.replace(/LiveMusic/,'lm');
		}
		
		if($('ck_DJs').checked)	{
			srl = srl.replace(/DJs/,'Dj');
		}	else	{
			srl = srl.replace(/DJs/,'dj');
		}

		if($('ck_KaraokeOpenMic').checked)	{
			srl = srl.replace(/KaraokeOpenMic/,'Op');
		}	else	{
			srl = srl.replace(/KaraokeOpenMic/,'op');
		}

		if($('ck_LecturesAndLit').checked)	{
			srl = srl.replace(/LecturesAndLit/,'Ll');
		}	else	{
			srl = srl.replace(/LecturesAndLit/,'ll');
		}

		if($('ck_Games').checked)	{
			srl = srl.replace(/Games/,'Gm');
		}	else	{
			srl = srl.replace(/Games/,'gm');
		}
		
		if($('ck_Classes').checked)	{
			srl = srl.replace(/Classes/,'Cl');
		}	else	{
			srl = srl.replace(/Classes/,'cl');
		}
		
		if($('ck_Meetings').checked)	{
			srl = srl.replace(/Meetings/,'Me');
		}	else	{
			srl = srl.replace(/Meetings/,'me');
		}
		
		if($('ck_Art').checked)	{
			srl = srl.replace(/Art/,'An');
		}	else	{
			srl = srl.replace(/Art/,'an');
		}
		
		if($('ck_ArtAroundTown').checked)	{
			srl = srl.replace(/ArtAroundTown/,'Aa');
		}	else	{
			srl = srl.replace(/ArtAroundTown/,'aa');
		}
		
		if($('ck_Auditions').checked)	{
			srl = srl.replace(/Auditions/,'Au');
		}	else	{
			srl = srl.replace(/Auditions/,'au');
		}
		
		if($('ck_HelpOut').checked)	{
			srl = srl.replace(/HelpOut/,'Ho');
		}	else	{
			srl = srl.replace(/HelpOut/,'ho');
		}
	
		if($('ck_Kidstuff').checked)	{
			srl = srl.replace(/Kidstuff/,'Kd');
		}	else	{
			srl = srl.replace(/Kidstuff/,'kd');
		}
		
		if($('ck_SupportGroups').checked)	{
			srl = srl.replace(/SupportGroups/,'Sg');
		}	else	{
			srl = srl.replace(/SupportGroups/,'sg');
		}
		
		if($('ck_WordOnTheStreet').checked)	{
			srl = srl.replace(/WordOnTheStreet/,'Wd');
		}	else	{
			srl = srl.replace(/WordOnTheStreet/,'wd');
		}
		
		if($('ck_Outdoors').checked)	{
			srl = srl.replace(/Outdoors/,'Ou');
		}	else	{
			srl = srl.replace(/Outdoors/,'ou');
		}

		//fp_Log($('ck_Verbose').checked);
		//alert("#3: " + srl);

		if($('ck_Verbose').checked)	{
			srl = srl + ".Vr";
		}	else	{
			srl = srl + ".vr";
		}
		//alert("#4: " + srl);

		srl = srl.replace(/\&/g,'.');
		//alert("#5: " + srl);
		
		//fp_Log(srl);
		return srl;

	}
	

	//B8:B6 Black Right Arrow
	//B9:B7 White Right Arrow
	//BE:BC Black Down Arrow
	//BF:BD White Down Arrow

	var black_right = "&#x25B6;";
	var white_right = "&#x25B7;";
	var black_down = "&#x25BC;";
	var white_down = "&#x25BD;";

/*	
	function fp_Fold(dd)	{
		
		var how = $('dd_' + dd).style.display;
		var ur = $('dd_' + dd).className;
		
		switch (how)	{
			
			case "none":
			//$('dd_' + dd).className = "open";
			$('da_' + dd).innerHTML = black_down;
			if (ur)	{
				var aj = new Ajax.Updater('dd_' + dd,'../inc/modules/calendar_listing_individual.php',{method: post,fp:dd});
			}
			break;
			
			default:
			//$('dd_' + dd).className = "closed";
			$('da_' + dd).innerHTML = black_right;
			break;
			
		}
		
		Effect.toggle('dd_' + dd,'blind',{duration: .2});
		
	}
*/





function charCounter(id, maxlimit, limited){
	if (!$('counter-'+id)){
		$(id).insert({after: '<div id="counter-'+id+'"></div>'});
	}
	if($F(id).length >= maxlimit){
		if(limited){	$(id).value = $F(id).substring(0, maxlimit); }
		$('counter-'+id).addClassName('charcount-limit');
		$('counter-'+id).removeClassName('charcount-safe');
	} else {	
		$('counter-'+id).removeClassName('charcount-limit');
		$('counter-'+id).addClassName('charcount-safe');
	}
	$('counter-'+id).update( $F(id).length + '/' + maxlimit );	
		
}

function makeItCount(id, maxsize, limited){
	if(limited == null) limited = true;
	if ($(id)){
		Event.observe($(id), 'keyup', function(){charCounter(id, maxsize, limited);}, false);
		Event.observe($(id), 'keydown', function(){charCounter(id, maxsize, limited);}, false);
		charCounter(id,maxsize,limited);
	}
}
