/** 
  * @InializeAsBroadcaster
  * @desc - for broadcasting messages each broadcaster must have:
  * a listener property and 
  * a broadcastMessage method
  * 
  * @obj - object doing the broadcasting
  */
var InializeAsBroadcaster = function(obj){
	obj.listeners = new Array();
	/* loops thru listeners calling 'msg' */
	obj.broadcastMessage = function(msg,obj){this.listeners.each(function(item,i){item[msg](obj);}.bind(this))};
	/* add to the array of event listeners */
	obj.addListener = function(obj){this.listeners.push(obj);};
	/* remove a listener */
	obj.removeListener = function(obj){for(var i=0;i<this.listeners.length;i++){if(obj==this.listeners[i]){delete this.listeners[i];break;}}};
	obj.removeListeners = function(obj){for(var i=0;i<this.listeners.length;i++){delete this.listeners[i];}};
};

/* create a dispatcher for handling the updates from the AJAX calls */
var inlineDispatcher = new Object();
InializeAsBroadcaster(inlineDispatcher);
/**
 * @MyBuilder	
 * @desc 		- dynamically created and append html
 */
var MyBuilder = {
	make:function(node,attributes,classname,text,childs){var element=document.createElement(node);for(var each in attributes){element.setAttribute(each,attributes[each]);}if(classname!=undefined){element.className=classname}if(text!=undefined){var tnode=document.createTextNode(text);element.appendChild(tnode);}if(childs!=undefined){var len=childs.length;for(var i=0;i<len;i++){if(childs[i]){element.appendChild(childs[i]);}}}return element;}
};
/**
 * @GetCookie
 * @desc 		- returns the value for named cookie
 */
var getCookie = function(c_name){if (document.cookie.length>0){c_start=document.cookie.indexOf(c_name + "=");if (c_start!=-1){c_start=c_start + c_name.length+1;c_end=document.cookie.indexOf(";",c_start);if (c_end==-1) c_end=document.cookie.length;return unescape(document.cookie.substring(c_start,c_end));}}return "";};
var setCookie = function(name, value, expires, path, domain, secure) {
   var curCookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
   document.cookie = curCookie;
};
var deleteCookie = function(name, path, domain) {
   if (getCookie(name))
       document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
};
/* 
 * limit the no of character in a textarea
*/
function limit_textarea(field,maxlimit,count)
{
	if (field.value.length > maxlimit)
		field.value = field.value.substring(0, maxlimit);
	else if(count)
		count.update(maxlimit - field.value.length);
}
/**
 * @zipHandler
 * @t 			- no idea
 * @json		- response
 */
function zipHandler(t,json)
{	
	if((json.state) && (json.state!='')){	
		if($('state').childNodes.length>1){
			$A($('state').options).each(function(e){
				if(e.value==json.state.strip())
					e.selected=true;
			});
			$("city").value=json.city;
		}else{
			$A($('state').firstDescendant().options).each(function(e){
				if(e.value==json.state.strip())
					e.selected=true;
			});
			$("city").firstDescendant().value=json.city;
		}
	}
}
/* used on productio details */
function do_zip_test(obj){new Ajax.Request('/api/json/registration/utils/lookup_zipcode', {parameters:'zip_code='+$(obj).value, onSuccess:zipHandler.bind(this)});}
/* 
 * show and hide header login box
*/
function loginBox(show)
{
	if (show) {
		
		//need to move login form to the end of the page
		var pop = $('frmLoginPop');
		var clone = pop.cloneNode(true);
		var b = document.getElementsByTagName("body").item(0);
		b.appendChild(clone);
		pop.remove();	//take out original
	
		$('frmLoginPop').show();
		
		var pos 	= Position.cumulativeOffset($('login_window'));
		var left	= pos[0] - 100;
		$('frmLoginPop').setStyle({left:left+'px'});
		
		$$('.user-nav-out')[0].hide();
		
		$$('#frmLoginPop input[type="submit"]').each(function(item) {
			// add the submit handler
			Event.observe(item,"click",function(evt){
				
				var e=Event.element(evt);
				var form=e.form;
				
				new Ajax.Request(form.action,{
					method:form.action,
					parameters:form.serialize()
				});
			});
		});
		
		$$('#frmLoginPop input[type="text"]')[0].focus();
		
		try { pageTracker._trackPageview('/logininpage1'); } catch(e) { }
		
	} else {
		$('frmLoginPop').hide();
		$$('.user-nav-out')[0].show();
	}
}
/* 
 * show and hide forgot pass panel in login box
*/
function loginBoxSwap(forgot) {
	if (forgot) {
		Effect.SlideUp('divLoginBox1', { duration: 0.4 });
		Effect.SlideDown('divLoginBox2', { duration: 0.4 });
	} else {
		Effect.SlideUp('divLoginBox2', { duration: 0.4 });
		Effect.SlideDown('divLoginBox1', { duration: 0.4 });
	}
	$$('#frmLoginPop input[type="text"]').each(function(item) {
		item.value = '';
	});
	$$('#frmLoginPop input[type="password"]').each(function(item) {
		item.value = '';
	});
	$$('#frmLoginPop .login_message').each(function(item) {
		item.update();
	});
	$$('#frmLoginPop .login_message_2').each(function(item) {
		item.update();
	});
}


function setup_box_toggle(prefix) {
	
	//process the form submission
	function doAj() {
		new Ajax.Request($(prefix + '-form').action,{
			method:$(prefix + '-form').method,
			parameters:$(prefix + '-form').serialize(),
			onSuccess:function(trans){
				var r_obj=trans.responseJSON;
				if(r_obj.errors!=null)
					for(var each in r_obj.errors)
						msg='<p>'+r_obj.errors[each]+'</p>';
				$(prefix + '-error').update(msg);
	
				Effect.Appear($(prefix + '-error'),{from:0.0,to:1.0,delay:0.0});
				Effect.Fade($(prefix + '-error'),{delay:3.5,afterFinish:function(){
					$(prefix + '-error').update('');
					$(prefix + '-error').hide();
				}});
			}
		});
	}
	
	//wire up submit button
	if ($(prefix + '-submit')) {
		Event.observe($(prefix + '-submit'),"click",function() {
			doAj();
		});
	}
	
	//for auto posting fields
	$$('.' + prefix + '-autofield').each(function(item, index) {
		Event.observe((item),"blur",function() {
			doAj();
		});
	});

	//wire up cancel button
	if ($(prefix + '-cancel')) {
		Event.observe($(prefix + '-cancel'),"click",function() {
			box_toggle(prefix + '-edit', prefix + '-content');
		});
	}
}

var box_toggling = false;
function box_toggle(hider,shower) {
	if (!box_toggling) {
		box_toggling = true;
		if ($(hider).visible()) {
			Effect.BlindDown(shower, { duration: 0.3 });
			Effect.BlindUp(hider, { duration: 0.3, afterFinish: function() {box_toggling=false;} });
		} else {
			Effect.BlindUp(shower, { duration: 0.3 });
			Effect.BlindDown(hider, { duration: 0.3, afterFinish: function() {box_toggling=false;} });
		}
	}
}

function doCharLimit(txt,len) {
	var count = txt.value.length;
	if (count > len) {
		txt.value = txt.value.substring(0,len);
	}
}

function doCharCount(txt,limit,reportID) {
	var count = txt.value.length;
	if (count > limit) {
		txt.value = txt.value.substring(0,limit);
		count = limit;
	}
	$(reportID).update(limit - count);
}

Event.observe(window,"load", function(){
	$$('.disabler').each(function(item){
		Event.observe(item,"click",function(){
			item.writeAttribute("disabled","true");
		});	
	});
});

$$('.month h3').each(function(item){

	Event.observe(item,"click",function(){
	    item.toggleClassName('down');
        });
					
});
