YAHOO.namespace('SympWeb');
SympWeb = YAHOO.SympWeb;

(function($) { 

	$(document).ready(function() {
		// our accordion, works better than jquery ui
		var $items = $('.accordion h3').next('div');
		$items.each(function(n, el) {
			$items.eq(n)
				.removeClass('accordion-init')
				.css('height', $items.eq(n).outerHeight())
				.toggle().stop(false,true);
		});
		$('.accordion h3').bind('click',function() {
			$(this).siblings('h3.active').removeClass('active');
			$(this).addClass('active');			
			$(this).siblings('h3').next('div.accordion-content-open').slideToggle(null, function() {
				$(this).toggleClass('accordion-content-open');	
			});
			$(this).next('div').slideToggle(null, function() {
				$(this).toggleClass('accordion-content-open');
			});
		});

		SympWeb.populateFormsFromHash();
		
		// set up ajax forms
		$('#contact_form').ajaxForm({
			success: function(responseText, statusText, xhr, $form) {
				$('<p class="form-success">'+responseText+'</p>').replaceAll($form).parent().siblings('h2').eq(0).html('Thank You');
			}
		});
	});		

})(jQuery);

// populate forms from hash 
// simple hash usage: #form_id.field_name=value
// values for checkbox or multple select may be a comma separated string of values
// - example: #form_id.field_name=value&form_id.other_field_name=value1,value2
SympWeb.populateFormsFromHash = function() {	
	if (self.location.href.indexOf('#') != -1) {
		var hash = self.location.href.substr(self.location.href.indexOf('#')+1);
		if (hash != '') {
			// break hash down, find and populate form_id.field_name=value pairs
			var args = [], argvals, argobj = {}, formid, formfield, fieldvalue,
			    fillforms = [];			
			args = hash.split('&');
			for (var i=0; i<args.length; i++) {
				argvals = args[i].split('=');
				argobj[argvals[0]] = argvals[1] || '';
				if (argvals[0].indexOf('.') != -1) {
					formid = argvals[0].split('.');
					formfield = formid[1];
					formid = formid[0];
					fieldvalue = argvals[1] || '';
					fillforms.push({ id: formid, field: formfield, value: fieldvalue });
				}
			}
			for (var i=0; i < fillforms.length; i++) {
				SympWeb.populateForm(fillforms[i].id, fillforms[i].field, fillforms[i].value);
			}
		}
	}
};
SympWeb.populateForm = function(id, field, value) {
	jQuery(document).ready(function() {
		jQuery('form#'+id+" *[name='"+field+"']")
			.has(':checkbox, :radio, *[multiple]').val(value.split(','))
			.end()
			.not(':checkbox, :radio, *[multiple]').val(value)
		;
	});
};
