
window.addEvent('domready', function() {
	if($('mainform') != undefined){
		submitmainform();
	}
	if($('loginform') != undefined){
		submitloginform();
	}
	if($('poleform') != undefined){
		submitpoleform();
		var myTips = new Tips('.thisisatooltip');
		

	}
	if($('tabBoxExample') != undefined){
		viewTabs();
	}
	if($('leaguesearchform') != undefined){
		leaguesearchform();
	} 
	if($('leaguepasswordform') != undefined){
	
		leaguepasswordform();
	} 
	if($('autocompleter') != undefined){
		
	autoCompleter();
	}
	
	if($('last_tweet_id') != undefined){
		
		microblogrefreshjs();
		
	
	}
	
	if($('wall') != undefined){
		wallposter();
		//submitwallpost();
		deletewallpostevent();
		karmawallevent();
		submitwallpostcomment();
		
		refreshWall();
		wallgetallcomments();
		
	}
	if($('menu2') != undefined){
		sharewithbutton();
	}
	if($('wallpostform') != undefined){
		
		submitwallpost();
	}
	
	
	
})



function microblogrefreshjs()
{
	var tx = $('last_tweet_id').get('value');
	
	var microblogupdate = new Request({
	    method: 'post',
	    url: baseurl+'refreshmicroblog',
	    initialDelay: 60000,
	    delay: 120000,
	    limit: 15000,
	    onSuccess: function(response){
			
			var myObject = JSON.decode(response);
			myvar ='';
			
			dateTimeAgo(myObject.date);		
			for(i=0; i<myObject.microblog.length; i++)
			{
				
				if($('tweet_'+myObject.microblog[i].tweet_id) == undefined){
				x = new Element('li', {id: 'tweet_'+myObject.microblog[i].tweet_id ,html: '<a href="' + baseurl+ '"><img src="' + baseurl+ 'media/img/logo/' + myObject.microblog[i].member_logo + '" width="20" height="20"/></a> ' + myObject.microblog[i].tweet + ' <small class="datetimeago" title="' + myObject.microblog[i].tweet_date + '"> ' + myObject.microblog[i].tweet_date_ago + '</small><hr />'})
				
				x.setStyle('opacity',0);
				
				x.inject($('microbloglist'), 'top'); 
				
				var fx = new Fx.Tween(x,{duration:600});	
				x.store('fx',fx);
				fx.addEvent('complete',function(){x.set('style','');});	
				fx.start('opacity',1);
				
				}
				
				else{
					$('tweet_'+myObject.microblog[i].tweet_id).set('html', '<a href="' + baseurl+ '"><img src="' + baseurl+ 'media/img/logo/' + myObject.microblog[i].member_logo + '" width="20" height="20"/></a> ' + myObject.microblog[i].tweet + ' <small class="datetimeago" title="' + myObject.microblog[i].tweet_date + '"> ' + myObject.microblog[i].tweet_date_ago + '</small><hr />')
				}
			}
			
				
	    }
	});
	
	
	
	microblogupdate.startTimer({last_tweet_id: tx});

	
	
//alert('aa');	
//alert(baseurl);
}



function showHide(){
	
	
	if($('div_showhide').hasClass('div_hidden'))
	{
		$('div_showhide').removeClass('div_hidden');
		$('div_showhide').addClass('div_showing');
	}
	else if ($('div_showhide').hasClass('div_showing')){
		$('div_showhide').removeClass('div_showing');
		$('div_showhide').addClass('div_hidden');
	}

	 
}



function submitloginform()
{
	$('loginform').addEvent('submit', function(e) {
		//Prevents the default submit event from loading a new page.
		e.stop();
	
		//Empty the log and show the spinning indicator.
		var log = $('errorslogin').empty() //.addClass('ajax-loading');
		log.removeClass('error');	
		log.removeClass('success');
		log.addClass('inactive');
		//Set the options of the form's Request handler. 
		//("this" refers to the $('myForm') element).
			
		this.set('send', {onComplete: function(response) { 
			log.removeClass('ajax-loading');
			var myObject = JSON.decode(response);
			if(myObject.success == 1)
			{
			window.location = myObject.redirecturl;
			}
			if(myObject.success == 0)
				{
					var myvar = "";
					for(i=0; i<myObject.message.length; i++)
					{
						myvar = myvar + myObject.message[i] + "<br />";
					}
					log.addClass('error');
					log.set('html', myvar);
				}
		}});
		//Send the form.
		this.send();
	});
}
function submitpoleform()
{
	$('poleform').addEvent('submit', function(e) {
		//Prevents the default submit event from loading a new page.
		e.stop();
		
		//Empty the log and show the spinning indicator.
		
		
		var log = $('errorslogin').empty(); //.addClass('ajax-loading');
		log.removeClass('error');	
		log.removeClass('success');
		log.addClass('inactive');
		
		//Set the options of the form's Request handler. 
		//("this" refers to the $('myForm') element).
			
		this.set('send', {onComplete: function(response) { 
			log.removeClass('ajax-loading');
			var myObject = JSON.decode(response);
			if(myObject.success == 1)
			{
				log.addClass('success');
				myvar = myObject.message[0];
			}
			if(myObject.success == 0)
			{
				log.addClass('error');
				myvar = myObject.message[0];
			}
			
			
			log.set('html', myvar);

		}});
		//Send the form.
		this.send();
	});
}
// end of the mainform

function leaguesearchform()
{
	$('leaguesearchform').addEvent('submit', function(e) {
		//Prevents the default submit event from loading a new page.
		e.stop();
	
		//Empty the log and show the spinning indicator.
		var log = $('errors').empty();
		log.removeClass('error');	
		log.removeClass('success');
		log.addClass('inactive');
		//Set the options of the form's Request handler. 
		//("this" refers to the $('myForm') element).
			
		this.set('send', {onComplete: function(response) { 
			
				
			var myObject = JSON.decode(response);
			
			
			var myvar = "";
		
			if(myObject.message){
			for(i=0; i<myObject.message.length; i++)
			{
				
				myvar = myvar + myObject.message[i] + "<br />";
			}
			log.addClass('active');
			
			}
			log.addClass('error');
			log.set('html', myvar);
		
			$('foundleagues').set('html', myObject.foundhtml);

		}});
		//Send the form.
		this.send();
	});
}

function leaguepasswordform()
{
	$('leaguepasswordform').addEvent('submit', function(e) {
		//Prevents the default submit event from loading a new page.
		e.stop();
		
		//Empty the log and show the spinning indicator.
		var log = $('errorspass').empty().addClass('ajax-loading');
		log.addClass('inactive');
		//Set the options of the form's Request handler. 
		//("this" refers to the $('myForm') element).
			
		this.set('send', {onComplete: function(response) { 
			log.removeClass('ajax-loading');
			var myObject = JSON.decode(response);
			
			if(myObject.success == 1)
			{
			window.location = myObject.redirecturl;
			}
			var myvar = "";
			if(myObject.message){
			for(i=0; i<myObject.message.length; i++)
			{
				
				myvar = myvar + myObject.message[i] + "<br />";
			}
			log.addClass('active');
			log.set('html', myvar);
			}
		

		}});
		//Send the form.
		this.send();
	});
}

function analyticstrace()
{
	a = $('mainform').getElements('input');

	//alert(a.length);
	for(var i=0;i<a.length;i++)
	{
	b = a[i].getProperties('name', 'value');
	
	if(b['name'] == 'do'){
		trace_url = b['value'];
		_gaq.push(['_trackPageview', trace_url]);
		//alert(trace_url);
		
	}
	}
}


function submitmainform()
{
	
	
	
	//alert(b);
	//if ($(b).name == 'do'){
	//	alert(b.value);}
	
	//alert(a);
	
	
	
	
	$('mainform').addEvent('submit', function(e) {
		//Prevents the default submit event from loading a new page.
		e.stop();
	
		//Empty the log and show the spinning indicator.
		var log = $('errors').empty(); //.addClass('ajax-loading');
		log.removeClass('error');	
		log.removeClass('success');
		log.addClass('inactive');
		//Set the options of the form's Request handler. 
		//("this" refers to the $('myForm') element).
			

		
		
		this.set('send', {onComplete: function(response) { 
	
			var myObject = JSON.decode(response);
			analyticstrace();
			if(myObject.success == 1 && myObject.redirecturl)
			{
				log.addClass('success');
			if(myObject.alert){
				alert(myObject.alert)
			}
			window.location = myObject.redirecturl;
			}
			else if(myObject.success == 1)
			{
				log.addClass('success');
			}
			var myvar = "";
			for(i=0; i<myObject.message.length; i++)
			{
				myvar = myvar + myObject.message[i] + "<br />";
			}
			log.addClass('error');
			log.set('html', myvar);

		}});
		//Send the form.
		this.send();
	});
}
// end of the mainform
function viewTabs()
{
	tb = new TinyTab($$('ul.tabSet li'),$$('ul.panelSet li'), 'testjg');
}

(function($) {
	this.TinyTab = new Class({
		Implements: Events,
		initialize: function(tabs, contents, opt) {
			this.tabs = tabs;
			this.contents = contents;
			if(!opt) opt = {};
			this.css = opt.selectedClass || 'selected'; 
			this.select(this.tabs[0]);
			tabs.each(function(el){
				el.addEvent('click',function(e){
					this.select(el);
					e.stop();
				}.bind(this));
			}.bind(this));
		},

		select: function(el) {
			this.tabs.removeClass(this.css);
			el.addClass(this.css);
			this.contents.setStyle('display','none');
			var content = this.contents[this.tabs.indexOf(el)];
			content.setStyle('display','block');
			this.fireEvent('change',[content,el]);
		}
	});
})(document.id);


// modals
function helpmodal(help_url)
{
new StickyWin.Modal.Ajax({
	url: help_url,
	width: 520,
	height: 510,
		  modalOptions: {
	    modalStyle:{
	      'background-color':'#d6e1b9',
	      'opacity':.6
	    }
	  }
	}).update();
}

function joinleaguemodal(leagueurl)
{
	// "_trackEvent" is the pageview event, 
	_gaq.push(['_trackPageview', leagueurl]);

	var myStickyWin = new StickyWin.Modal.Ajax({
	    content: 'leagueurl',
	    	url: leagueurl,
	    	fadeDuration: 500,
	    	width: 300,
	    	//height: 200,
	    	destroyOnClose: true,
	    	 modalOptions: {
	    	    modalStyle:{
	    	      'background-color':'#d6e1b9',
	    	      'opacity':.6
	    	    }
	    	  }
	});
	myStickyWin.update();

}
function teameditmodal(dataurl){
	
	// "_trackEvent" is the pageview event, 
	
	
	var yoffset = 0;
	if(dataurl.indexOf("stat") !== -1){yoffset = -250}
	else{yoffset = 0}
		
	_gaq.push(['_trackPageview', dataurl]);
	
	var myStickyWin = new StickyWin.Modal.Ajax({
	    content: 'leagueurl',
	    	url: dataurl,
	    	fadeDuration: 500,
	    	width: 810,
	    	//relativeTo: $('header'),
	    	offset: {
		x: 0,
		y: yoffset
	},
	    	//height: 200,
	    	destroyOnClose: true,
	    	 modalOptions: {
	    	    modalStyle:{
	    	      'background-color':'#d6e1b9',
	    	      'opacity':.6
	    	    }
	    	  }
	});
	myStickyWin.update();

	
	
}

function teameditmodalselect(item_replace, item_id, item_type, item_name, item_cost, item_pic, baseurl, lospercentage){
	
	
	var newlogo = baseurl + 'media/img/team/' + item_pic;
	
	if(item_replace == 'D1'){
		sellvalue = stripAlphaChars($('current_driver_1_value').value) * lospercentage;
		
		$('sell_driver_1_value').set('value', sellvalue);
		$('replacement_driver_1_image').set('src', newlogo);
		$('replacement_driver_1_name').set('value', decodeURIComponent(item_name));
		$('replacement_driver_1_value').set('value', MoneyFormat(item_cost));
		
		a = stripAlphaChars($('current_driver_1_value').value) - sellvalue;
		$('driver_1_value_minus_fee').set('value', '-'+MoneyFormat(a));
		$('driver_1_value_minus_fee').set('style', 'color:red;');
		
		$('replace_driver_1_id').set('value', item_id);
		
		replacement_cost = stripAlphaChars($('sell_driver_1_value').value) - stripAlphaChars($('replacement_driver_1_value').value);
		if(replacement_cost <0 ){		
			$('replace_driver_1_cost').set('style', 'color:red;');
		}
		else{
			$('replace_driver_1_cost').set('style', 'color:#777777;');
		}
		$('replace_driver_1_cost').set('value', MoneyFormat(replacement_cost));
	}
	if(item_replace == 'D2'){
		sellvalue = stripAlphaChars($('current_driver_2_value').value) * lospercentage;
		
		$('sell_driver_2_value').set('value', sellvalue);
		$('replacement_driver_2_image').set('src', newlogo);
		$('replacement_driver_2_name').set('value', decodeURIComponent(item_name));
		$('replacement_driver_2_value').set('value', MoneyFormat(item_cost));
		
		a = stripAlphaChars($('current_driver_2_value').value) - sellvalue;
		$('driver_2_value_minus_fee').set('value', '-'+MoneyFormat(a));
		$('driver_2_value_minus_fee').set('style', 'color:red;');
		$('replace_driver_2_id').set('value', item_id);
		
		replacement_cost = stripAlphaChars($('sell_driver_2_value').value) - stripAlphaChars($('replacement_driver_2_value').value);
		if(replacement_cost <0 ){		
			$('replace_driver_2_cost').set('style', 'color:red;');
		}
		else{
			$('replace_driver_2_cost').set('style', 'color:#777777;');
		}
		$('replace_driver_2_cost').set('value', MoneyFormat(replacement_cost));
		}
	if(item_replace == 'C'){
		sellvalue = stripAlphaChars($('current_chassis_value').value) * lospercentage;
		
		$('sell_chassis_value').set('value', sellvalue);
		$('replacement_chassis_image').set('src', newlogo);
		$('replacement_chassis_name').set('value', decodeURIComponent(item_name));
		$('replacement_chassis_value').set('value', MoneyFormat(item_cost));
		
		a = stripAlphaChars($('current_chassis_value').value) - sellvalue;
		$('chassis_value_minus_fee').set('value', '-'+MoneyFormat(a));
		$('chassis_value_minus_fee').set('style', 'color:red;');
		$('replace_chassis_id').set('value', item_id);
		
		replacement_cost = stripAlphaChars($('sell_chassis_value').value) - stripAlphaChars($('replacement_chassis_value').value);
		if(replacement_cost <0 ){		
			$('replace_chassis_cost').set('style', 'color:red;');
		}
		else{
			$('replace_chassis_cost').set('style', 'color:#777777;');
		}
		$('replace_chassis_cost').set('value', MoneyFormat(replacement_cost));
	}
	if(item_replace == 'E'){
		sellvalue = stripAlphaChars($('current_engine_value').value) * lospercentage;
		
		$('sell_engine_value').set('value', sellvalue);
		$('replacement_engine_image').set('src', newlogo);
		$('replacement_engine_name').set('value', decodeURIComponent(item_name));
		$('replacement_engine_value').set('value', MoneyFormat(item_cost));
		
		a = stripAlphaChars($('current_engine_value').value) - sellvalue;
		$('engine_value_minus_fee').set('value', '-'+MoneyFormat(a));
		$('engine_value_minus_fee').set('style', 'color:red;');
		$('replace_engine_id').set('value', item_id);
		
		replacement_cost = stripAlphaChars($('sell_engine_value').value) - stripAlphaChars($('replacement_engine_value').value);
		if(replacement_cost <0 ){		
			$('replace_engine_cost').set('style', 'color:red;');
		}
		else{
			$('replace_engine_cost').set('style', 'color:#777777;');
		}
		$('replace_engine_cost').set('value', MoneyFormat(replacement_cost));
	}
	
	
	
	// calculate the new budget
	newbudget();
	// get the stickywin instance and close it
	
	//var StickInstanceID = document.id('teammodal').retrieve("instance");
    
	//alert(StickInstanceID);
	//StickInstanceID.closeBox();
	var StickInstanceID;
	StickInstanceID = document.getElement('.StickyWinInstance').retrieve('StickyWin');
	StickInstanceID.destroy();

		
}

function stripAlphaChars(pstrSource) 
{ 
var m_strOut = new String(pstrSource); 
    m_strOut = m_strOut.replace(/[^0-9\-]/g, ''); 

    return m_strOut; 
}




function newbudget()
{
	
	a = parseInt(stripAlphaChars($('replace_driver_1_cost').value)) +  parseInt(stripAlphaChars($('replace_driver_2_cost').value)) + parseInt(stripAlphaChars($('replace_chassis_cost').value)) + parseInt(stripAlphaChars($('replace_engine_cost').value));
	replacement_cost = parseInt(stripAlphaChars($('current_budget').value)) + parseInt(a);

	$('costs').set('value', MoneyFormat(a));
	if(a <0 ){		
		$('costs').set('style', 'color:red;');
	}
	else{
		$('costs').set('style', 'color:#777777;');
	}
	
	if(replacement_cost <0 ){		
		$('new_budget').set('style', 'color:red;');
	}
	else{
		$('new_budget').set('style', 'color:#777777;');
	}
	$('new_budget').set('value', MoneyFormat(replacement_cost));
	
	
	
	// todo enable/disable submit button

	// todo add not saved warning
}

// TODO should combine these two..
function showimage(baseurl){
	
	var newlogo = baseurl + 'media/img/logo/' + $('member_logo').get('value');
	$('show_member_logo').set('src', newlogo);
	
	}

function showimage_sub(baseurl){
	
	var newlogo = baseurl + 'media/img/logo/' + $('sub_logo').get('value');
	$('show_sub_logo').set('src', newlogo);
	
	}

function showitem(baseurl, item, target){
	
	
	var tmp = $(item).get('value');
	var tmp = tmp.split("|");
	var newlogo = baseurl + 'media/img/team/' + tmp[1];
	$(target).set('src', newlogo);
	
	}

function MoneyFormat(Money)  
{  

var bank = Money+"";
var bankoutput=""  
var nb = 0  
var pl = 0  
var fr = ""  
var at = 0  

negative = bank.substr(0,1)  
 if(negative == "-"){ls = bank.length-1; bank=bank.substr(1,ls);}  
  
for (index=bank.length-3;index>0;index=index-3)  
{  
       
value=bank.substr(index,3)  
  
bankoutput=","+value+bankoutput  
nb++  
}  
pl=nb*3  
at=bank.length-pl  
fr=bank.substr(0,at)  
bankoutput=fr+bankoutput  
  
if(negative == "-"){bankoutput = "-" + bankoutput} else  
{bankoutput = bankoutput}  

return bankoutput  
   
}




function getpointDetails(urlreq, destination){
	

	
	var req = new Request.HTML({url: urlreq , 
		onSuccess: function(html) {
			//Clear the text currently inside the results div.
			$('destination').set('text', '');
			//Inject the new DOM elements into the results div.
			$('destination').adopt(html);
		},
		//Our request will most likely succeed, but just in case, we'll add an
		//onFailure method which will let the user know what happened.
		onFailure: function() {
			$('destination').set('text', 'The request failed.');
		}
	});
	
	req.send();

	alert(dt.stretchtoggle);
	alert(section);
}


// MooDropMenu http://mootools.net/forge/p/moodropmenu
var MooDropMenu = new Class({

	Implements: [Options, Events],

	options: {
		onOpen: function(el){
			el.removeClass('close').addClass('open');
		},
		onClose: function(el){
			el.removeClass('open').addClass('close');
		},
		onInitialize: function(el){
			el.removeClass('open').addClass('close');
		},
		mouseoutDelay: 200,
		mouseoverDelay: 0,
		listSelector: 'ul',
		itemSelector: 'li',
		openEvent: 'mouseenter',
		closeEvent: 'mouseleave'
	},

	initialize: function(menu, options, level){
		this.setOptions(options);
		options = this.options;

		var menu = this.menu = document.id(menu);

		menu.getElements(options.itemSelector + ' > ' + options.listSelector).each(function(el){

			this.fireEvent('initialize', el);

			var parent = el.getParent(options.itemSelector),
				timer;

			parent.addEvent(options.openEvent, function(){
				parent.store('DropDownOpen', true);

				clearTimeout(timer);
				if (options.mouseoverDelay) timer = this.fireEvent.delay(options.mouseoverDelay, this, ['open', el]);
				else this.fireEvent('open', el);

			}.bind(this)).addEvent(options.closeEvent, function(){
				parent.store('DropDownOpen', false);

				clearTimeout(timer);
				timer = (function(){
					if (!parent.retrieve('DropDownOpen')) this.fireEvent('close', el);
				}).delay(options.mouseoutDelay, this);

			}.bind(this));

		}, this);
	},

	toElement: function(){
		return this.menu
	}

});

/* So you can do like this $('nav').MooDropMenu(); or even $('nav').MooDropMenu().setStyle('border',1); */
Element.implement({
	MooDropMenu: function(options){
		return this.store('MooDropMenu', new MooDropMenu(this, options));
	}
});


$('menu').MooDropMenu({
	onOpen: function(el){
	el.fade('in')
},
onClose: function(el){
	el.fade('out');
},
onInitialize: function(el){
	el.fade('hide').set('tween',{duration:1000});
}
});

function sharewithbutton()
{
$('menu2').MooDropMenu({
	mouseoutDelay: 0,
	mouseoverDelay: 0,
	onOpen: function(el){
	el.fade('in')
},
onClose: function(el){
	el.fade('out');
},
onInitialize: function(el){
	el.fade('hide').set('tween',{duration:0});
}
});
}




//This library: http://dev.clientcide.com/depender/build?download=true&version=Clientcide+3.0.10&excludeLibs=Core&excludeLibs=More-Behaviors&excludeLibs=Behavior&require=Clientcide%2FAutocompleter.Clientcide&require=Clientcide%2FAutocompleter.JSONP&require=Clientcide%2FAutocompleter.Local&require=Clientcide%2FAutocompleter.Observer&require=Clientcide%2FAutocompleter.Remote&require=Clientcide%2FAutocompleter&require=Clientcide%2FStickyWin.Ajax&require=Clientcide%2FStickyWin.Fx&require=Clientcide%2FStickyWin.Modal&require=Clientcide%2FStickyWin&excludeLibs=More
//Contents: Clientcide:Source/3rdParty/Autocompleter.Observer.js, Clientcide:Source/Core/Clientcide.js, Clientcide:Source/3rdParty/Autocompleter.js, Clientcide:Source/3rdParty/Autocompleter.Remote.js, Clientcide:Source/3rdParty/Autocompleter.Local.js, Clientcide:Source/3rdParty/Autocompleter.Clientcide.js, Clientcide:Source/Core/dbug.js, Clientcide:Source/UI/StyleWriter.js, Clientcide:Source/UI/StickyWin.js, Clientcide:Source/UI/StickyWin.UI.js, Clientcide:Source/UI/StickyWin.UI.Pointy.js, Clientcide:Source/UI/StickyWin.PointyTip.js, Clientcide:Source/UI/StickyWin.Ajax.js, Clientcide:Source/UI/StickyWin.Modal.js, Clientcide:Source/UI/StickyWin.Fx.js, Clientcide:Source/3rdParty/Autocompleter.JSONP.js

//Begin: Source/3rdParty/Autocompleter.Observer.js
/*
---
name: Autocompleter.Observer

description: Observe formelements for changes

version: 1.0rc3

license: MIT-style license
author: Harald Kirschner <mail [at] digitarald.de>
copyright: Author

requires: [Core/Class.Extras, Core/Element.Event, Core/JSON]

provides: [Autocompleter.Observer, Observer]

...
*/
var Observer = new Class({

	Implements: [Options, Events],

	options: {
		periodical: false,
		delay: 1000
	},

	initialize: function(el, onFired, options){
		this.setOptions(options);
		this.addEvent('onFired', onFired);
		this.element = document.id(el) || $$(el);
		/* Clientcide change */
		this.boundChange = this.changed.bind(this);
		this.resume();
	},

	changed: function() {
		var value = this.element.get('value');
		if ($equals(this.value, value)) return;
		this.clear();
		this.value = value;
		this.timeout = this.onFired.delay(this.options.delay, this);
	},

	setValue: function(value) {
		this.value = value;
		this.element.set('value', value);
		return this.clear();
	},

	onFired: function() {
		this.fireEvent('onFired', [this.value, this.element]);
	},

	clear: function() {
		clearTimeout(this.timeout || null);
		return this;
	},
	/* Clientcide change */
	pause: function(){
		clearTimeout(this.timeout);
		clearTimeout(this.timer);
		this.element.removeEvent('keyup', this.boundChange);
		return this;
	},
	resume: function(){
		this.value = this.element.get('value');
		if (this.options.periodical) this.timer = this.changed.periodical(this.options.periodical, this);
		else this.element.addEvent('keyup', this.boundChange);
		return this;
	}

});

var $equals = function(obj1, obj2) {
	return (obj1 == obj2 || JSON.encode(obj1) == JSON.encode(obj2));
};

//packager build Clientcide/StickyWin.Ajax Clientcide/StickyWin.Fx Clientcide/StickyWin.Modal +use-only Clientcide
/*
---

name: Clientcide

description: The Clientcide namespace.

license: MIT-style license.

provides: Clientcide

...
*/
var Clientcide = {
	version: '2.2.1dev',
	assetLocation: "http://github.com/anutron/clientcide/raw/master/Assets",
	setAssetLocation: function(baseHref) {
		Clientcide.assetLocation = baseHref;
		if (Clientcide.preloaded) Clientcide.preLoadCss();
	},
	preLoadCss: function(){
		if (window.StickyWin && StickyWin.ui) StickyWin.ui();
		if (window.StickyWin && StickyWin.pointy) StickyWin.pointy();
		Clientcide.preloaded = true;
		return true;
	},
	preloaded: false
};
(function(){
	if (!window.addEvent) return;
	var preload = function(){
		if (window.dbug) dbug.log('preloading clientcide css');
		if (!Clientcide.preloaded) Clientcide.preLoadCss();
	};
	window.addEvent('domready', preload);
	window.addEvent('load', preload);
})();
setCNETAssetBaseHref = Clientcide.setAssetLocation;

/*
---

name: dbug

description: A wrapper for Firebug console.* statements.

license: MIT-style license.

authors:
- Aaron Newton

provides: dbug

...
*/
var dbug = {
	logged: [],
	timers: {},
	firebug: false, 
	enabled: false, 
	log: function() {
		dbug.logged.push(arguments);
	},
	nolog: function(msg) {
		dbug.logged.push(arguments);
	},
	time: function(name){
		dbug.timers[name] = new Date().getTime();
	},
	timeEnd: function(name){
		if (dbug.timers[name]) {
			var end = new Date().getTime() - dbug.timers[name];
			dbug.timers[name] = false;
			dbug.log('%s: %s', name, end);
		} else dbug.log('no such timer: %s', name);
	},
	enable: function(silent) { 
		var con = window.firebug ? firebug.d.console.cmd : window.console;

		if((!!window.console && !!window.console.warn) || window.firebug) {
			try {
				dbug.enabled = true;
				dbug.log = function(){
						try {
							(con.debug || con.log).apply(con, arguments);
						} catch(e) {
							console.log(Array.slice(arguments));
						}
				};
				dbug.time = function(){
					con.time.apply(con, arguments);
				};
				dbug.timeEnd = function(){
					con.timeEnd.apply(con, arguments);
				};
				if(!silent) dbug.log('enabling dbug');
				for(var i=0;i<dbug.logged.length;i++){ dbug.log.apply(con, dbug.logged[i]); }
				dbug.logged=[];
			} catch(e) {
				dbug.enable.delay(400);
			}
		}
	},
	disable: function(){ 
		if(dbug.firebug) dbug.enabled = false;
		dbug.log = dbug.nolog;
		dbug.time = function(){};
		dbug.timeEnd = function(){};
	},
	cookie: function(set){
		var value = document.cookie.match('(?:^|;)\\s*jsdebug=([^;]*)');
		var debugCookie = value ? unescape(value[1]) : false;
		if((set == null && debugCookie != 'true') || (set != null && set)) {
			dbug.enable();
			dbug.log('setting debugging cookie');
			var date = new Date();
			date.setTime(date.getTime()+(24*60*60*1000));
			document.cookie = 'jsdebug=true;expires='+date.toGMTString()+';path=/;';
		} else dbug.disableCookie();
	},
	disableCookie: function(){
		dbug.log('disabling debugging cookie');
		document.cookie = 'jsdebug=false;path=/;';
	},
	conditional: function(fn, fnIfError) {
		if (dbug.enabled) {
			return fn();
		} else {
			try {
				return fn();
			} catch(e) {
				if (fnIfError) fnIfError(e);
			}
		}
	}
};

(function(){
	var fb = !!window.console || !!window.firebug;
	var con = window.firebug ? window.firebug.d.console.cmd : window.console;
	var debugMethods = ['debug','info','warn','error','assert','dir','dirxml'];
	var otherMethods = ['trace','group','groupEnd','profile','profileEnd','count'];
	function set(methodList, defaultFunction) {
		
		var getLogger = function(method) {
			return function(){
				con[method].apply(con, arguments);
			};
		};
		
		for(var i = 0; i < methodList.length; i++){
			var method = methodList[i];
			if (fb && con[method]) {
				dbug[method] = getLogger(method);
			} else {
				dbug[method] = defaultFunction;
			}
		}
	};
	set(debugMethods, dbug.log);
	set(otherMethods, function(){});
})();
if ((!!window.console && !!window.console.warn) || window.firebug){
	dbug.firebug = true;
	var value = document.cookie.match('(?:^|;)\\s*jsdebug=([^;]*)');
	var debugCookie = value ? unescape(value[1]) : false;
	if(window.location.href.indexOf("jsdebug=true")>0 || debugCookie=='true') dbug.enable();
	if(debugCookie=='true')dbug.log('debugging cookie enabled');
	if(window.location.href.indexOf("jsdebugCookie=true")>0){
		dbug.cookie();
		if(!dbug.enabled)dbug.enable();
	}
	if(window.location.href.indexOf("jsdebugCookie=false")>0)dbug.disableCookie();
}


/*
---
name: StyleWriter

description: Provides a simple method for injecting a css style element into the DOM if it's not already present.

license: MIT-Style License

requires: [Core/Class, Core/DomReady, Core/Element, dbug]

provides: StyleWriter

...
*/

var StyleWriter = new Class({
	createStyle: function(css, id) {
		window.addEvent('domready', function(){
			try {
				if (document.id(id) && id) return;
				var style = new Element('style', {id: id||''}).inject($$('head')[0]);
				if (Browser.ie) style.styleSheet.cssText = css;
				else style.set('text', css);
			}catch(e){dbug.log('error: %s',e);}
		}.bind(this));
	}
});

/*
---

name: StickyWin

description: Creates a div within the page with the specified contents at the location relative to the element you specify; basically an in-page popup maker.

license: MIT-Style License

requires: [
  Core/DomReady,
  Core/Slick.Finder,
  More/Element.Position,
  More/Class.Binds,
  More/Element.Shortcuts,
  More/Element.Pin,
  More/IframeShim,
  More/Object.Extras,
  Clientcide,
  StyleWriter
]

provides: [StickyWin, StickyWin.Stacker]
...
*/


var StickyWin = new Class({
	Binds: ['destroy', 'hide', 'togglepin', 'esc'],
	Implements: [Options, Events, StyleWriter],
	options: {
//		onDisplay: function(){},
//		onClose: function(){},
//		onDestroy: function(){},
		closeClassName: 'closeSticky',
		pinClassName: 'pinSticky',
		content: '',
		zIndex: 10000,
		className: '',
//		id: ... set above in initialize function
/*  	these are the defaults for Element.position anyway
		************************************************
		edge: false, //see Element.position
		position: 'center', //center, corner == upperLeft, upperRight, bottomLeft, bottomRight
		offset: {x:0,y:0},
		relativeTo: document.body, */
		width: false,
		height: false,
		timeout: -1,
		allowMultipleByClass: true,
		allowMultiple: true,
		showNow: true,
		useIframeShim: true,
		iframeShimSelector: '',
		destroyOnClose: false,
		closeOnClickOut: false,
		closeOnEsc: false,
		getWindowManager: function(){ return StickyWin.WM; }
	},

	css: '.SWclearfix:after {content: "."; display: block; height: 0; clear: both; visibility: hidden;}'+
		 '.SWclearfix {display: inline-table;} * html .SWclearfix {height: 1%;} .SWclearfix {display: block;}',
	
	initialize: function(options){
		this.options.inject = this.options.inject || {
			target: document.body,
			where: 'bottom'
		};
		this.setOptions(options);
		this.windowManager = this.options.getWindowManager();
		this.id = this.options.id || 'StickyWin_'+new Date().getTime();
		this.makeWindow();
		if (this.windowManager) this.windowManager.add(this);

		if (this.options.content) this.setContent(this.options.content);
		if (this.options.timeout > 0) {
			this.addEvent('onDisplay', function(){
				this.hide.delay(this.options.timeout, this);
			}.bind(this));
		}
		//add css for clearfix
		this.createStyle(this.css, 'StickyWinClearFix');
		if (this.options.closeOnClickOut || this.options.closeOnEsc) this.attach();
		if (this.options.destroyOnClose) this.addEvent('close', this.destroy);
		if (this.options.showNow) this.show();
	},
	toElement: function(){
		return this.element;
	},
	attach: function(attach){
		var method = attach != null && attach ? 'addEvents' : 'removeEvents';
		var events = {};
		if (this.options.closeOnClickOut) events.click = this.esc;
		if (this.options.closeOnEsc) events.keyup = this.esc;
		document[method](events);
	},
	esc: function(e) {
		if (e.key == "esc") this.hide();
		if (e.type == "click" && this.element != e.target && !this.element.contains(e.target)) this.hide();
	},
	makeWindow: function(){
		this.destroyOthers();
		if (!document.id(this.id)) {
			this.win = new Element('div', {
				id: this.id
			}).addClass(this.options.className).addClass('StickyWinInstance').addClass('SWclearfix').setStyles({
			 	display: 'none',
				position: 'absolute',
				zIndex: this.options.zIndex
			}).inject(this.options.inject.target, this.options.inject.where).store('StickyWin', this);
		} else this.win = document.id(this.id);
		this.element = this.win;
		if (this.options.width && typeOf(this.options.width.toInt())=="number") this.win.setStyle('width', this.options.width.toInt());
		if (this.options.height && typeOf(this.options.height.toInt())=="number") this.win.setStyle('height', this.options.height.toInt());
		return this;
	},
	show: function(suppressEvent){
		this.showWin();
		if (!suppressEvent) this.fireEvent('display');
		if (this.options.useIframeShim) this.showIframeShim();
		this.visible = true;
		return this;
	},
	showWin: function(){
		if (this.windowManager) this.windowManager.focus(this);
		if (!this.positioned) this.position();
		this.win.show();
	},
	hide: function(suppressEvent){
		if (typeOf(suppressEvent) == "event" || !suppressEvent) this.fireEvent('close');
		this.hideWin();
		if (this.options.useIframeShim) this.hideIframeShim();
		this.visible = false;
		return this;
	},
	hideWin: function(){
		this.win.setStyle('display','none');
	},
	destroyOthers: function() {
		if (!this.options.allowMultipleByClass || !this.options.allowMultiple) {
			$$('div.StickyWinInstance').each(function(sw) {
				if (!this.options.allowMultiple || (!this.options.allowMultipleByClass && sw.hasClass(this.options.className))) 
					sw.retrieve('StickyWin').destroy();
			}, this);
		}
	},
	setContent: function(html) {
		if (this.win.getChildren().length>0) this.win.empty();
		if (typeOf(html) == "string") this.win.set('html', html);
		else if (document.id(html)) this.win.adopt(html);
		this.win.getElements('.'+this.options.closeClassName).each(function(el){
			el.addEvent('click', this.hide);
		}, this);
		this.win.getElements('.'+this.options.pinClassName).each(function(el){
			el.addEvent('click', this.togglepin);
		}, this);
		return this;
	},
	position: function(options){
		this.positioned = true;
		this.setOptions(options);
		this.win.position(
			Object.cleanValues({
				allowNegative: [this.options.allowNegative, this.options.relativeTo != document.body].pick(),
				relativeTo: this.options.relativeTo,
				position: this.options.position,
				offset: this.options.offset,
				edge: this.options.edge
			})
		);
		if (this.shim) this.shim.position();
		return this;
	},
	pin: function(pin) {
		if (!this.win.pin) {
			dbug.log('you must include element.pin.js!');
			return this;
		}
		this.pinned = pin != null && pin;
		this.win.pin(pin);
		return this;
	},
	unpin: function(){
		return this.pin(false);
	},
	togglepin: function(){
		return this.pin(!this.pinned);
	},
	makeIframeShim: function(){
		if (!this.shim){
			var el = (this.options.iframeShimSelector)?this.win.getElement(this.options.iframeShimSelector):this.win;
			this.shim = new IframeShim(el, {
				display: false,
				name: 'StickyWinShim'
			});
		}
	},
	showIframeShim: function(){
		if (this.options.useIframeShim) {
			this.makeIframeShim();
			this.shim.show();
		}
	},
	hideIframeShim: function(){
		if (this.shim) this.shim.hide();
	},
	destroy: function(){
		this.destroyed = true;
		if (this.windowManager) this.windowManager.remove(this);
		if (this.win) this.win.destroy();
		if (this.options.useIframeShim && this.shim) this.shim.destroy();
		if (document.id('modalOverlay')) document.id('modalOverlay').destroy();
		this.fireEvent('destroy');
	}
});

StickyWin.Stacker = new Class({
	Implements: [Options, Events],
	Binds: ['click'],
	instances: [],
	options: {
		zIndexBase: 9000
	},
	initialize: function(options) {
		this.setOptions(options);
	},
	add: function(sw) {
		this.instances.include(sw);
		$(sw).addEvent('mousedown', this.click);
	},
	click: function(e) {
		this.instances.each(function(sw){
			var el = $(sw);
			if (el == e.target || el.contains($(e.target))) this.focus(sw);
		}, this);
	},
	focus: function(instance){
		if (this.focused == instance) return;
		this.focused = instance;
		if (instance) this.instances.erase(instance).push(instance);
		this.instances.each(function(current, i){
			$(current).setStyle('z-index', this.options.zIndexBase + i);
		}, this);
		this.focused = instance;
	},
	remove: function(sw) {
		this.instances.erase(sw);
		$(sw).removeEvent('click', this.click);
	}
});
StickyWin.WM = new StickyWin.Stacker();

 /*
---
name: StickyWin.ui

description: Creates an html holder for in-page popups using a default style.

license: MIT-Style License

requires: [Core/Element.Style, More/String.Extras, StyleWriter, StickyWin]

provides: StickyWin.UI
...
*/
StickyWin.UI = new Class({
	Implements: [Options, StyleWriter],
	options: {
		width: 300,
		css: "div.DefaultStickyWin {font-family:verdana; font-size:11px; line-height: 13px;position: relative;}"+
			"div.DefaultStickyWin div.top{-moz-user-select: none;-khtml-user-select: none;}"+
			"div.DefaultStickyWin div.top_ul{background:url({%baseHref%}full.png) top left no-repeat; height:30px; width:15px; float:left}"+
			"div.DefaultStickyWin div.top_ur{position:relative; left:0px !important; left:-4px; background:url({%baseHref%}full.png) top right !important; height:30px; margin:0px 0px 0px 15px !important; margin-right:-4px; padding:0px}"+
			"div.DefaultStickyWin h1.caption{clear: none !important; margin:0px !important; overflow: hidden; padding:0 !important; font-weight:bold; color:#555; font-size:14px !important; position:relative; top:8px !important; left:5px !important; float: left; height: 22px !important;}"+
			"div.DefaultStickyWin div.middle, div.DefaultStickyWin div.closeBody {background:url({%baseHref%}body.png) top left repeat-y; margin:0px 20px 0px 0px !important;	margin-bottom: -3px; position: relative;	top: 0px !important; top: -3px;}"+
			"div.DefaultStickyWin div.body{background:url({%baseHref%}body.png) top right repeat-y; padding:8px 23px 8px 0px !important; margin-left:5px !important; position:relative; right:-20px !important; z-index: 1;}"+
			"div.DefaultStickyWin div.bottom{clear:both;}"+
			"div.DefaultStickyWin div.bottom_ll{background:url({%baseHref%}full.png) bottom left no-repeat; width:15px; height:15px; float:left}"+
			"div.DefaultStickyWin div.bottom_lr{background:url({%baseHref%}full.png) bottom right; position:relative; left:0px !important; left:-4px; margin:0px 0px 0px 15px !important; margin-right:-4px; height:15px}"+
			"div.DefaultStickyWin div.closeButtons{text-align: center; background:url({%baseHref%}body.png) top right repeat-y; padding: 4px 30px 8px 0px; margin-left:5px; position:relative; right:-20px}"+
			"div.DefaultStickyWin a.button:hover{background:url({%baseHref%}big_button_over.gif) repeat-x}"+
			"div.DefaultStickyWin a.button {background:url({%baseHref%}big_button.gif) repeat-x; margin: 2px 8px 2px 8px; padding: 2px 12px; cursor:pointer; border: 1px solid #999 !important; text-decoration:none; color: #000 !important;}"+
			"div.DefaultStickyWin div.closeButton{width:13px; height:13px; background:url({%baseHref%}closebtn.gif) no-repeat; position: absolute; right: 0px; margin:10px 15px 0px 0px !important; cursor:pointer;top:0px}"+
			"div.DefaultStickyWin div.dragHandle {	width: 11px;	height: 25px;	position: relative;	top: 5px;	left: -3px;	cursor: move;	background: url({%baseHref%}drag_corner.gif); float: left;}",
		cornerHandle: false,
		cssClass: '',
		buttons: [],
		cssId: 'defaultStickyWinStyle',
		cssClassName: 'DefaultStickyWin',
		closeButton: true
/*	These options are deprecated:
		closeTxt: false,
		onClose: function(){},
		confirmTxt: false,
		onConfirm: function(){}	*/
	},
	initialize: function() {
		var args = this.getArgs(arguments);
		this.setOptions(args.options);
		this.legacy();
		var css = this.options.css.substitute({baseHref: this.options.baseHref || Clientcide.assetLocation + '/stickyWinHTML/'}, /\\?\{%([^}]+)%\}/g);
		if (Browser.ie) css = css.replace(/png/g, 'gif');
		this.createStyle(css, this.options.cssId);
		this.build();
		if (args.caption || args.body) this.setContent(args.caption, args.body);
	},
	toElement: function(){
		return this.element;
	},
	getArgs: function(){
		return StickyWin.UI.getArgs.apply(this, arguments);
	},
	legacy: function(){
		var opt = this.options; //saving bytes
		//legacy support
		if (opt.confirmTxt) opt.buttons.push({text: opt.confirmTxt, onClick: opt.onConfirm || function(){}});
		if (opt.closeTxt) opt.buttons.push({text: opt.closeTxt, onClick: opt.onClose || function(){}});
	},
	build: function(){
		var opt = this.options;

		var container = new Element('div', {
			'class': opt.cssClassName
		});
		if (opt.width) container.setStyle('width', opt.width);
		this.element = container;
		this.element.store('StickyWinUI', this);
		if (opt.cssClass) container.addClass(opt.cssClass);
		

		var bodyDiv = new Element('div').addClass('body');
		this.body = bodyDiv;
		
		var top_ur = new Element('div').addClass('top_ur');
		this.top_ur = top_ur;
		this.top = new Element('div').addClass('top').adopt(
				new Element('div').addClass('top_ul')
			).adopt(top_ur);
		container.adopt(this.top);
		
		if (opt.cornerHandle) new Element('div').addClass('dragHandle').inject(top_ur, 'top');
		
		//body
		container.adopt(new Element('div').addClass('middle').adopt(bodyDiv));
		//close buttons
		if (opt.buttons.length > 0){
			var closeButtons = new Element('div').addClass('closeButtons');
			opt.buttons.each(function(button){
				if (button.properties && button.properties.className){
					button.properties['class'] = button.properties.className;
					delete button.properties.className;
				}
				var properties = Object.merge({'class': 'closeSticky'}, button.properties);
				new Element('a').addEvent('click', button.onClick || function(){})
					.appendText(button.text).inject(closeButtons).set(properties).addClass('button');
			});
			container.adopt(new Element('div').addClass('closeBody').adopt(closeButtons));
		}
		//footer
		container.adopt(
			new Element('div').addClass('bottom').adopt(
					new Element('div').addClass('bottom_ll')
				).adopt(
					new Element('div').addClass('bottom_lr')
			)
		);
		if (this.options.closeButton) container.adopt(new Element('div').addClass('closeButton').addClass('closeSticky'));
		return this;
	},
	setCaption: function(caption) {
		this.caption = caption;
		if (!this.h1) {
			this.makeCaption(caption);
		} else {
			if (document.id(caption)) this.h1.adopt(caption);
			else this.h1.set('html', caption);
		}
		return this;
	},
	makeCaption: function(caption) {
		if (!caption) return this.destroyCaption();
		var opt = this.options;
		this.h1 = new Element('h1').addClass('caption');
		if (opt.width) this.h1.setStyle('width', (opt.width-(opt.cornerHandle?55:40)-(opt.closeButton?10:0)));
		this.setCaption(caption);
		this.top_ur.adopt(this.h1);
		if (!this.options.cornerHandle) this.h1.addClass('dragHandle');
		return this;
	},
	destroyCaption: function(){
		if (this.h1) {
			this.h1.destroy();
			this.h1 = null;
		}
		return this;
	},
	setContent: function(){
		var args = this.getArgs.apply(this, arguments);
		var caption = args.caption;
		var body = args.body;
		this.setCaption(caption);
		if (document.id(body)) this.body.empty().adopt(body);
		else this.body.set('html', body);
		return this;
	}
});
StickyWin.UI.getArgs = function(){
	var input = typeOf(arguments[0]) == "arguments"?arguments[0]:arguments;
	if (Browser.opera && 1 === input.length) input = input[0];

	var cap = input[0], bod = input[1];
	var args = Array.link(input, {options: Type.isObject});
	if (input.length == 3 || (!args.options && input.length == 2)) {
		args.caption = cap;
		args.body = bod;
	} else if ((typeOf(bod) == 'object' || !bod) && cap && typeOf(cap) != 'object'){
		args.body = cap;
	}
	return args;
};

StickyWin.ui = function(caption, body, options){
	return document.id(new StickyWin.UI(caption, body, options));
};

/*
---

name: StickyWin.Modal

description: This script extends StickyWin and StickyWin.Fx classes to add Mask functionality.

license: MIT-Style License

requires: [More/Mask, StickyWin]

provides: StickyWin.Modal
...
*/
StickyWin.Modal = new Class({

	Extends: StickyWin,

	options: {
		modalize: true,
		maskOptions: {
			style: {
				'background-color':'#333',
				opacity:0.8
			}
		},
		hideOnClick: true,
		getWindowManager: function(){ return StickyWin.ModalWM; }
	},

	initialize: function(options) {
		this.options.maskTarget = this.options.maskTarget || document.body;
		this.setOptions(options);
		this.mask = new Mask(this.options.maskTarget, this.options.maskOptions).addEvent('click', function() {
			if (this.options.hideOnClick) this.hide();
		}.bind(this));
		this.parent(options);
	},

	show: function(showModal){
		if ([showModal, this.options.modalize].pick()) this.mask.show();
		this.parent();
	},

	hide: function(hideModal){
		if ([hideModal, true].pick()) this.mask.hide();
		this.parent();
	},

	destroy: function(){
		this.mask.destroy();
		this.parent.apply(this, arguments);
	}

});

StickyWin.ModalWM = new StickyWin.Stacker({
	zIndexBase: 11000
});
if (StickyWin.Fx) StickyWin.Fx.Modal = StickyWin.Modal;

/*
---

name: StickyWin.Ajax

dename: Adds ajax functionality to all the StickyWin classes.

license: MIT-Style License

requires: [Core/Request, StickyWin, StickyWin.UI]

provides: [StickyWin.Ajax, StickyWin.Modal.Ajax]

...
*/
(function(){
	var SWA = function(extend){
		return {
			Extends: extend,
			options: {
				//onUpdate: function(){},
				url: '',
				showNow: false,
				requestOptions: {
					method: 'get',
					evalScripts: true
				},
				wrapWithUi: false, 
				caption: '',
				uiOptions:{},
				handleResponse: function(response){
					var responseScript = "";
					this.Request.response.text.stripScripts(function(script){	responseScript += script; });
					if (this.options.wrapWithUi) response = StickyWin.ui(this.options.caption, response, this.options.uiOptions);
					this.setContent(response);
					this.show();
					if (this.evalScripts) Browser.exec(responseScript);
					this.fireEvent('update');
				}
			},
			initialize: function(options){
				var showNow;
				if (options && options.showNow) {
					showNow = true;
					options.showNow = false;
				}
				this.parent(options);
				this.evalScripts = this.options.requestOptions.evalScripts;
				this.options.requestOptions.evalScripts = false;
				this.createRequest();
				if (showNow) this.update();
			},
			createRequest: function(){
				this.Request = new Request(this.options.requestOptions).addEvent('onSuccess',
					this.options.handleResponse.bind(this));
			},
			update: function(url, options){
				this.Request.setOptions(options).send({url: url||this.options.url});
				return this;
			}
		};
	};
	try {	StickyWin.Ajax = new Class(SWA(StickyWin)); } catch(e){}
	try {	StickyWin.Modal.Ajax = new Class(SWA(StickyWin.Modal)); } catch(e){}
})();

/*
---

name: StickyWin.Fx

description: Extends StickyWin to create popups that fade in and out.

license: MIT-style license.

requires: [More/Class.Refactor, Core/Fx.Tween, StickyWin]

provides: StickyWin.Fx

...
*/

StickyWin = Class.refactor(StickyWin, {
	options: {
		//fadeTransition: 'sine:in:out',
		fade: true,
		fadeDuration: 150
	},
	hideWin: function(){
		if (this.options.fade) this.fade(0);
		else this.previous();
	},
	showWin: function(){
		if (this.options.fade) this.fade(1);
		else this.previous();
	},
	hide: function(){
		this.previous(this.options.fade);
	},
	show: function(){
		this.previous(this.options.fade);
	},
	fade: function(to){
		if (!this.fadeFx) {
			this.win.setStyles({
				opacity: 0,
				display: 'block'
			});
			var opts = {
				property: 'opacity',
				duration: this.options.fadeDuration
			};
			if (this.options.fadeTransition) opts.transition = this.options.fadeTransition;
			this.fadeFx = new Fx.Tween(this.win, opts);
		}
		if (to > 0) {
			this.win.setStyle('display','block');
			this.position();
		}
		this.fadeFx.clearChain();
		this.fadeFx.start(to).chain(function (){
			if (to == 0) {
				this.win.setStyle('display', 'none');
				this.fireEvent('onClose');
			} else {
				this.fireEvent('onDisplay');
			}
		}.bind(this));
		return this;
	}
});
StickyWin.Fx = StickyWin;


//This library: http://dev.clientcide.com/depender/build?download=true&excludeLibs=Core&excludeLibs=More&excludeLibs=Behavior&require=Clientcide%2FAutocompleter.JSONP&excludeLibs=More-Behaviors
//Contents: Clientcide:Source/3rdParty/Autocompleter.Observer.js, Clientcide:Source/Core/Clientcide.js, Clientcide:Source/3rdParty/Autocompleter.js, Clientcide:Source/3rdParty/Autocompleter.Remote.js, Clientcide:Source/3rdParty/Autocompleter.JSONP.js

//Begin: Source/3rdParty/Autocompleter.Observer.js
/*
---
name: Autocompleter.Observer

description: Observe formelements for changes

version: 1.0rc3

license: MIT-style license
author: Harald Kirschner <mail [at] digitarald.de>
copyright: Author

requires: [Core/Class.Extras, Core/Element.Event, Core/JSON]

provides: [Autocompleter.Observer, Observer]

...
*/
var Observer = new Class({

	Implements: [Options, Events],

	options: {
		periodical: false,
		delay: 1000
	},

	initialize: function(el, onFired, options){
		this.setOptions(options);
		this.addEvent('onFired', onFired);
		this.element = document.id(el) || $$(el);
		/* Clientcide change */
		this.boundChange = this.changed.bind(this);
		this.resume();
	},

	changed: function() {
		var value = this.element.get('value');
		if ($equals(this.value, value)) return;
		this.clear();
		this.value = value;
		this.timeout = this.onFired.delay(this.options.delay, this);
	},

	setValue: function(value) {
		this.value = value;
		this.element.set('value', value);
		return this.clear();
	},

	onFired: function() {
		this.fireEvent('onFired', [this.value, this.element]);
	},

	clear: function() {
		clearTimeout(this.timeout || null);
		return this;
	},
	/* Clientcide change */
	pause: function(){
		clearTimeout(this.timeout);
		clearTimeout(this.timer);
		this.element.removeEvent('keyup', this.boundChange);
		return this;
	},
	resume: function(){
		this.value = this.element.get('value');
		if (this.options.periodical) this.timer = this.changed.periodical(this.options.periodical, this);
		else this.element.addEvent('keyup', this.boundChange);
		return this;
	}

});

var $equals = function(obj1, obj2) {
	return (obj1 == obj2 || JSON.encode(obj1) == JSON.encode(obj2));
};

//Begin: Source/Core/Clientcide.js
/*
---

name: Clientcide

description: The Clientcide namespace.

license: MIT-style license.

provides: Clientcide

...
*/
var Clientcide = {
	version: '2.2.1dev',
	assetLocation: "http://github.com/anutron/clientcide/raw/master/Assets",
	setAssetLocation: function(baseHref) {
		Clientcide.assetLocation = baseHref;
		if (Clientcide.preloaded) Clientcide.preLoadCss();
	},
	preLoadCss: function(){
		if (window.StickyWin && StickyWin.ui) StickyWin.ui();
		if (window.StickyWin && StickyWin.pointy) StickyWin.pointy();
		Clientcide.preloaded = true;
		return true;
	},
	preloaded: false
};
(function(){
	if (!window.addEvent) return;
	var preload = function(){
		if (window.dbug) dbug.log('preloading clientcide css');
		if (!Clientcide.preloaded) Clientcide.preLoadCss();
	};
	window.addEvent('domready', preload);
	window.addEvent('load', preload);
})();
setCNETAssetBaseHref = Clientcide.setAssetLocation;

//Begin: Source/3rdParty/Autocompleter.js
/*
---
name: Autocompleter

description: An auto completer class from <a href=\"http://digitarald.de\">http://digitarald.de</a>.

version: 1.1.1

license: MIT-style license

author: Harald Kirschner <mail [at] digitarald.de>

copyright: Author

requires: [Core/Fx.Tween, More/Element.Shortcuts, More/Element.Forms, More/IframeShim, Observer, Clientcide]

provides: [Autocompleter, Autocompleter.Base]

...
*/
var Autocompleter = {};

var OverlayFix = IframeShim;

Autocompleter.Base = new Class({
	
	Implements: [Options, Events],
	
	options: {
		minLength: 1,
		markQuery: true,
		width: 'inherit',
		maxChoices: 10,
//		injectChoice: null,
//		customChoices: null,
		className: 'autocompleter-choices',
		zIndex: 42,
		delay: 400,
		observerOptions: {},
		fxOptions: {},
//		onSelection: $empty,
//		onShow: $empty,
//		onHide: $empty,
//		onBlur: $empty,
//		onFocus: $empty,

		autoSubmit: false,
		overflow: false,
		overflowMargin: 25,
		selectFirst: false,
		filter: null,
		filterCase: false,
		filterSubset: false,
		forceSelect: false,
		selectMode: true,
		choicesMatch: null,

		multiple: false,
		separator: ', ',
		autoTrim: true,
		allowDupes: false,

		cache: true,
		relative: false
	},

	initialize: function(element, options) {
		this.element = document.id($('autocompleter'));
		
		this.setOptions(options);
		this.options.separatorSplit = new RegExp("\s*["+this.options.separator.trim()+"]\s*/");
		this.build();
		this.observer = new Observer(this.element, this.prefetch.bind(this), Object.merge({
			'delay': this.options.delay
		}, this.options.observerOptions));
		this.queryValue = null;
		if (this.options.filter) this.filter = this.options.filter.bind(this);
		var mode = this.options.selectMode;
		this.typeAhead = (mode == 'type-ahead');
		this.selectMode = (mode === true) ? 'selection' : mode;
		this.cached = [];
	},

	/**
	 * build - Initialize DOM
	 *
	 * Builds the html structure for choices and appends the events to the element.
	 * Override this function to modify the html generation.
	 */
	build: function() {
		if (document.id(this.options.customChoices)) {
			this.choices = this.options.customChoices;
		} else {
			this.choices = new Element('ul', {
				'class': this.options.className,
				'styles': {
					'zIndex': this.options.zIndex
				}
			}).inject(document.body);
			this.relative = false;
			if (this.options.relative || this.element.getOffsetParent() != document.body) {
				this.choices.inject(this.element, 'after');
				this.relative = this.element.getOffsetParent();
			}
			this.fix = new OverlayFix(this.choices);
		}
		if (!this.options.separator.test(this.options.separatorSplit)) {
			this.options.separatorSplit = this.options.separator;
		}
		this.fx = (!this.options.fxOptions) ? null : new Fx.Tween(this.choices, Object.merge({
			'property': 'opacity',
			'link': 'cancel',
			'duration': 200
		}, this.options.fxOptions)).addEvent('onStart', Chain.prototype.clearChain).set(0);
		
		this.element.setProperty('autocomplete', 'off')
			.addEvent((Browser.ie || Browser.chrome || Browser.safari) ? 'keydown' : 'keypress', this.onCommand.bind(this))
			.addEvent('click', this.onCommand.bind(this, false))
			.addEvent('focus', function(){
				this.toggleFocus.delay(100, this, [true]);
			}.bind(this));
			//.addEvent('blur', this.toggleFocus.create({bind: this, arguments: false, delay: 100}));
		document.addEvent('click', function(e){
			if (e.target != this.choices) this.toggleFocus(false);
		}.bind(this));
	},

	destroy: function() {
		if (this.fix) this.fix.dispose();
		this.choices = this.selected = this.choices.destroy();
	},

	toggleFocus: function(state) {
		this.focussed = state;
		if (!state) this.hideChoices(true);
		this.fireEvent((state) ? 'onFocus' : 'onBlur', [this.element]);
	},

	onCommand: function(e) {
		if (!e && this.focussed) return this.prefetch();
		if (e && e.key && !e.shift) {
			switch (e.key) {
				case 'enter': case 'tab':
					if (this.element.value != this.opted) return true;
					if (this.selected && this.visible) {
						this.choiceSelect(this.selected);
						return !!(this.options.autoSubmit);
					}
					break;
				case 'up': case 'down':
					if (!this.prefetch() && this.queryValue !== null) {
						var up = (e.key == 'up');
						this.choiceOver((this.selected || this.choices)[
							(this.selected) ? ((up) ? 'getPrevious' : 'getNext') : ((up) ? 'getLast' : 'getFirst')
						](this.options.choicesMatch), true);
					}
					return false;
				case 'esc':
					this.hideChoices(true);
					break;
			}
		}
		return true;
	},

	setSelection: function(finish) {
		var input = this.selected.inputValue, value = input;
		var start = this.queryValue.length, end = input.length;
		if (input.substr(0, start).toLowerCase() != this.queryValue.toLowerCase()) start = 0;
		if (this.options.multiple) {
			var split = this.options.separatorSplit;
			value = this.element.value;
			start += this.queryIndex;
			end += this.queryIndex;
			var old = value.substr(this.queryIndex).split(split, 1)[0];
			value = value.substr(0, this.queryIndex) + input + value.substr(this.queryIndex + old.length);
			if (finish) {
				var space = /[^\s,]+/;
				var tokens = value.split(this.options.separatorSplit).filter(space.test, space);
				if (!this.options.allowDupes) tokens = [].combine(tokens);
				var sep = this.options.separator;
				value = tokens.join(sep) + sep;
				end = value.length;
			}
		}
		this.observer.setValue(value);
		this.opted = value;
		if (finish || this.selectMode == 'pick') start = end;
		this.element.selectRange(start, end);
		this.fireEvent('onSelection', [this.element, this.selected, value, input]);
	},

	showChoices: function() {
		var match = this.options.choicesMatch, first = this.choices.getFirst(match);
		this.selected = this.selectedValue = null;
		if (this.fix) {
			var pos = this.element.getCoordinates(this.relative), width = this.options.width || 'auto';
			this.choices.setStyles({
				'left': pos.left,
				'top': pos.bottom,
				'width': (width === true || width == 'inherit') ? pos.width : width
			});
		}
		if (!first) return;
		if (!this.visible) {
			this.visible = true;
			this.choices.setStyle('display', '');
			if (this.fx) this.fx.start(1);
			this.fireEvent('onShow', [this.element, this.choices]);
		}
		if (this.options.selectFirst || this.typeAhead || first.inputValue == this.queryValue) this.choiceOver(first, this.typeAhead);
		var items = this.choices.getChildren(match), max = this.options.maxChoices;
		var styles = {'overflowY': 'hidden', 'height': ''};
		this.overflown = false;
		if (items.length > max) {
			var item = items[max - 1];
			styles.overflowY = 'scroll';
			styles.height = item.getCoordinates(this.choices).bottom;
			this.overflown = true;
		};
		this.choices.setStyles(styles);
		this.fix.show();
	},

	hideChoices: function(clear) {
		if (clear) {
			var value = this.element.value;
			if (this.options.forceSelect) value = this.opted;
			if (this.options.autoTrim) {
				value = value.split(this.options.separatorSplit).filter(function(){ return arguments[0]; }).join(this.options.separator);
			}
			this.observer.setValue(value);
		}
		if (!this.visible) return;
		this.visible = false;
		this.observer.clear();
		var hide = function(){
			this.choices.setStyle('display', 'none');
			this.fix.hide();
		}.bind(this);
		if (this.fx) this.fx.start(0).chain(hide);
		else hide();
		this.fireEvent('onHide', [this.element, this.choices]);
	},

	prefetch: function() {
		var value = this.element.value, query = value;
		if (this.options.multiple) {
			var split = this.options.separatorSplit;
			var values = value.split(split);
			var index = this.element.getCaretPosition();
			var toIndex = value.substr(0, index).split(split);
			var last = toIndex.length - 1;
			index -= toIndex[last].length;
			query = values[last];
		}
		if (query.length < this.options.minLength) {
			this.hideChoices();
		} else {
			if (query === this.queryValue || (this.visible && query == this.selectedValue)) {
				if (this.visible) return false;
				this.showChoices();
			} else {
				this.queryValue = query;
				this.queryIndex = index;
				if (!this.fetchCached()) this.query();
			}
		}
		return true;
	},

	fetchCached: function() {
		if (!this.options.cache
			|| !this.cached
			|| !this.cached.length
			|| this.cached.length >= this.options.maxChoices
			|| this.queryValue) return false;
		this.update(this.filter(this.cached));
		return true;
	},

	update: function(tokens) {
		this.choices.empty();
		this.cached = tokens;
		if (!tokens || !tokens.length) {
			this.hideChoices();
		} else {
			if (this.options.maxChoices < tokens.length && !this.options.overflow) tokens.length = this.options.maxChoices;
			tokens.each(this.options.injectChoice || function(token){
				var choice = new Element('li', {'html': this.markQueryValue(token)});
				choice.inputValue = token;
				this.addChoiceEvents(choice).inject(this.choices);
			}, this);
			this.showChoices();
		}
	},

	choiceOver: function(choice, selection) {
		if (!choice || choice == this.selected) return;
		if (this.selected) this.selected.removeClass('autocompleter-selected');
		this.selected = choice.addClass('autocompleter-selected');
		this.fireEvent('onSelect', [this.element, this.selected, selection]);
		if (!selection) return;
		this.selectedValue = this.selected.inputValue;
		if (this.overflown) {
			var coords = this.selected.getCoordinates(this.choices), margin = this.options.overflowMargin,
				top = this.choices.scrollTop, height = this.choices.offsetHeight, bottom = top + height;
			if (coords.top - margin < top && top) this.choices.scrollTop = Math.max(coords.top - margin, 0);
			else if (coords.bottom + margin > bottom) this.choices.scrollTop = Math.min(coords.bottom - height + margin, bottom);
		}
		if (this.selectMode) this.setSelection();
	},

	choiceSelect: function(choice) {
		if (choice) this.choiceOver(choice);
		this.setSelection(true);
		this.queryValue = false;
		this.hideChoices();
	},

	filter: function(tokens) {
		return (tokens || this.tokens).filter(function(token) {
			return this.test(token);
		}, new RegExp(((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp(), (this.options.filterCase) ? '' : 'i'));
	},

	/**
	 * markQueryValue
	 *
	 * Marks the queried word in the given string with <span class="autocompleter-queried">*</span>
	 * Call this i.e. from your custom parseChoices, same for addChoiceEvents
	 *
	 * @param		{String} Text
	 * @return		{String} Text
	 */
	markQueryValue: function(str) {
		if (!this.options.markQuery || !this.queryValue) return str;
		var regex = new RegExp('(' + ((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp() + ')', (this.options.filterCase) ? '' : 'i');
		return str.replace(regex, '<span class="autocompleter-queried">$1</span>');
	},

	/**
	 * addChoiceEvents
	 *
	 * Appends the needed event handlers for a choice-entry to the given element.
	 *
	 * @param		{Element} Choice entry
	 * @return		{Element} Choice entry
	 */
	addChoiceEvents: function(el) {
		return el.addEvents({
			'mouseover': this.choiceOver.bind(this, el),
			'click': this.choiceSelect.bind(this, el)
		});
	}
});


//Begin: Source/3rdParty/Autocompleter.Remote.js
/*
---
name: Autocompleter.Remote

version: 1.1.1

description: Autocompleter extensions that enable requests for JSON/XHTML data for input suggestions.

license: MIT-style license
author: Harald Kirschner <mail [at] digitarald.de>
copyright: Author

requires: [Autocompleter.Base, Core/Request.HTML, Core/Request.JSON]

provides: [Autocompleter.Remote, Autocompleter.Ajax, Autocompleter.Ajax.Base, Autocompleter.Ajax.Json, Autocompleter.Ajax.Xhtml]

...
*/

Autocompleter.Ajax = {};

Autocompleter.Ajax.Base = new Class({

	Extends: Autocompleter.Base,

	options: {
		// onRequest: function(){},
		// onComplete: function(){},
		postVar: 'value',
		postData: {},
		ajaxOptions: {}
	},

	initialize: function(element, options) {
		this.parent(element, options);
		var indicator = document.id(this.options.indicator);
		if (indicator) {
			this.addEvents({
				'onRequest': indicator.show.bind(indicator),
				'onComplete': indicator.hide.bind(indicator)
			}, true);
		}
	},

	query: function(){
		var data = Object.clone(this.options.postData);
		data[this.options.postVar] = this.queryValue;
		this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);
		this.request.send({'data': data});
	},

	/**
	 * queryResponse - abstract
	 *
	 * Inherated classes have to extend this function and use this.parent(resp)
	 *
	 * @param		{String} Response
	 */
	queryResponse: function() {
		this.fireEvent('onComplete', [this.element, this.request, this.response]);
	}

});

Autocompleter.Ajax.Json = new Class({

	Extends: Autocompleter.Ajax.Base,

	initialize: function(el, url, options) {
		this.parent(el, options);
		this.request = new Request.JSON(Object.merge({
			'url': url,
			'link': 'cancel'
		}, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
	},

	queryResponse: function(response) {
		this.parent();
		this.update(response);
	}

});

Autocompleter.Ajax.Xhtml = new Class({

	Extends: Autocompleter.Ajax.Base,

	initialize: function(el, url, options) {
		this.parent(el, options);
		this.request = new Request.HTML(Object.merge({
			'url': url,
			'link': 'cancel',
			'update': this.choices
		}, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
	},

	queryResponse: function(tree, elements) {
		this.parent();
		if (!elements || !elements.length) {
			this.hideChoices();
		} else {
			this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice || function(choice) {
				var value = choice.innerHTML;
				choice.inputValue = value;
				this.addChoiceEvents(choice.set('html', this.markQueryValue(value)));
			}, this);
			this.showChoices();
		}

	}

});


//Begin: Source/3rdParty/Autocompleter.JSONP.js
/*
---
name: Autocompleter.JSONP

description: Implements Request.JSONP support for the Autocompleter class.

license: MIT-Style License

requires: [More/Request.JSONP, Autocompleter.Remote]

provides: [Autocompleter.JSONP]
...
*/

Autocompleter.JSONP = new Class({

	Extends: Autocompleter.Ajax.Json,

	options: {
		postVar: 'query',
		jsonpOptions: {},
//		onRequest: $empty,
//		onComplete: $empty,
//		filterResponse: $empty
		minLength: 1
	},

	initialize: function(el, url, options) {
		this.url = url;
		this.setOptions(options);
		this.parent(el, options);
	},

	query: function(){
		var data = Object.clone(this.options.jsonpOptions.data||{});
		data[this.options.postVar] = this.queryValue;
		this.jsonp = new Request.JSONP(Object.merge({url: this.url, data: data},	this.options.jsonpOptions));
		this.jsonp.addEvent('onComplete', this.queryResponse.bind(this));
		this.fireEvent('onRequest', [this.element, this.jsonp, data, this.queryValue]);
		this.jsonp.send();
	},
	
	queryResponse: function(response) {
		this.parent();
		var data = (this.options.filter)?this.options.filter.apply(this, [response]):response;
		this.update(data);
	}

});
Autocompleter.JsonP = Autocompleter.JSONP;




function autoCompleter()
{





		var opts = {
//			jsonpOptions: {
//				//this data gets added to the query string using JsonP's options
////				data: {
////					outtype: 'js',
////					method: 'artist.search',
////					api_key: 'b25b959554ed76058ac220b7b2e0a026' //this is my code, user your own!
////				}
//			},
			postVar: 'enteredtext',
			width: 350,
			//forceSelect: true,
			filterSubset: true,
			//require at least a key stroke from the user
			minLength: 2,
			
			 onSelection: function (el, sel, value, input) { $('output').set('value', sel.innerHTML); },
			
			
			injectChoice: function(choice){
				//alert(choice.member_id);
				var el = new Element('li', {
					html: this.markQueryValue(choice.member_teamname)
				});
			//	var el2 = $('output'); //.get('value');
				
				el.inputValue = choice.member_teamname;
			//	el2.inputValue.set('value', choice.member_id); // = ;
				//addids(el.inputValue);
				this.addChoiceEvents(el).inject(this.choices);
				
			}
		};
		// new Autocompleter.JSONP($('foo'), 'http://lastfm-api-ext.appspot.com/2.0/', opts);
		var opts_multi = Object.merge(opts, {
			selectMode: 'type-ahead', // type-ahead , pick,  select Instant completion,
			multiple: true,
			separator: '; '
		});
		new Autocompleter.Ajax.Json($('autocompleter'), 'http://2011.f1manager.info/searchteamname', opts_multi);

	

}
function addids(id)
{
//alert(id);
	var x;
	x = $('output').get('value');
	x = x + id;
	$('output').set('value', x);
	//$('ouput'). = $('ouput') + id;
}



/*
---
description: DynamicTextarea

license: MIT-style

authors:
- Amadeus Demarzi (http://enmassellc.com/)

requires:
 core/1.3: [Core/Class, Core/Element, Core/Element.Event, Core/Element.Style, Core/Element.Dimensions]

provides: [DynamicTextarea]
...
*/

(function(){

// Prevent the plugin from overwriting existing variables
if (this.DynamicTextarea) return;

var DynamicTextarea = this.DynamicTextarea = new Class({

	Implements: [Options, Events],

	options: {
		value: '',
		minRows: 1,
		delay: true,
		lineHeight: null,
		offset: 0,
		padding: 0

		// AVAILABLE EVENTS
		// onCustomLineHeight: (function) - custom ways of determining lineHeight if necessary

		// onInit: (function)

		// onFocus: (function)
		// onBlur: (function)

		// onKeyPress: (function)
		// onResize: (function)

		// onEnable: (function)
		// onDisable: (function)

		// onClean: (function)
	},

	textarea: null,

	initialize: function(textarea,options) {
		this.textarea = document.id(textarea);
		if (!this.textarea) return;

		this.setOptions(options);

		this.parentEl = new Element('div',{
			styles:{
				padding:0,
				margin:0,
				border:0,
				height:'auto',
				width:'auto'
			}
		})
			.inject(this.textarea,'after')
			.adopt(this.textarea);

		// Prebind common methods
		['focus','delayCheck','blur','scrollFix','checkSize','clean','disable','enable','getLineHeight']
			.each(function(method){
				this[method] = this[method].bind(this);
			},this);

		// Firefox and Opera handle scroll heights differently than all other browsers
		if (window.Browser.firefox || window.Browser.opera) {
			this.options.offset =
				parseInt(this.textarea.getStyle('padding-top'),10) +
				parseInt(this.textarea.getStyle('padding-bottom'),10) +
				parseInt(this.textarea.getStyle('border-bottom-width'),10) +
				parseInt(this.textarea.getStyle('border-top-width'),10);
		} else {
			this.options.offset =
				parseInt(this.textarea.getStyle('border-bottom-width'),10) +
				parseInt(this.textarea.getStyle('border-top-width'),10);
			this.options.padding =
				parseInt(this.textarea.getStyle('padding-top'),10) +
				parseInt(this.textarea.getStyle('padding-bottom'),10);
		}

		// Disable browser resize handles, set appropriate styles
		this.textarea.set({
			'rows': 1,
			'styles': {
				'resize': 'none',
				'-moz-resize': 'none',
				'-webkit-resize': 'none',
				'position': 'relative',
				'display': 'block',
				'overflow': 'hidden',
				'height': 'auto'
			}
		});

		this.getLineHeight();
		this.fireEvent('customLineHeight');

		// Set the height of the textarea, based on content
		this.checkSize(true);
		this.textarea.addEvent('focus',this.focus);
		this.fireEvent('init',[textarea,options]);
	},

	// This is the only crossbrowser method to determine ACTUAL lineHeight in a textarea (that I am aware of)
	getLineHeight: function(){
		var backupValue = this.textarea.value;
		this.textarea.value = 'M';
		this.options.lineHeight = this.textarea.getScrollSize().y - this.options.padding;
		this.textarea.value = backupValue;
		this.textarea.setStyle('height', this.options.lineHeight * this.options.minRows);
	},

	// Stops a small scroll jump on some browsers
	scrollFix: function(){
		this.textarea.scrollTo(0,0);
	},

	// Add interactive events, and fire focus event
	focus: function(){
		this.textarea.addEvents({
			'keydown': this.delayCheck,
			'keypress': this.delayCheck,
			'blur': this.blur,
			'scroll': this.scrollFix
		});
		return this.fireEvent('focus');
	},

	// Clean out extraneaous events, and fire blur event
	blur: function(){
		this.textarea.removeEvents({
			'keydown': this.delayCheck,
			'keypress': this.delayCheck,
			'blur': this.blur,
			'scroll': this.scrollFix
		});
		return this.fireEvent('blur');
	},

	// Delay checkSize because text hasn't been injected into the textarea yet
	delayCheck: function(){
		if (this.options.delay === true)
			this.options.delay = this.checkSize.delay(1);
	},

	// Determine if it needs to be resized or not, and resize if necessary
	checkSize: function(forced) {
		var oldValue = this.options.value,
			modifiedParent = false;

		this.options.value = this.textarea.value;
		this.options.delay = false;

		if (this.options.value === oldValue && forced!==true)
			return this.options.delay = true;

		if (!oldValue || this.options.value.length < oldValue.length || forced) {
			modifiedParent = true;
			this.parentEl.setStyle('height',this.parentEl.getSize().y);
			this.textarea.setStyle('height', this.options.minRows * this.options.lineHeight);
		}

		var tempHeight = this.textarea.getScrollSize().y,
			offsetHeight = this.textarea.offsetHeight,
			cssHeight = tempHeight - this.options.padding,
			scrollHeight = tempHeight + this.options.offset;

		if (scrollHeight !== offsetHeight && cssHeight > this.options.minRows * this.options.lineHeight){
			this.textarea.setStyle('height',cssHeight);
			this.fireEvent('resize');
		}

		if(modifiedParent) this.parentEl.setStyle('height','auto');

		this.options.delay = true;
		if (forced !== true)
			return this.fireEvent('keyPress');
	},

	// Clean out this textarea's event handlers
	clean: function(){
		this.textarea.removeEvents({
			'focus': this.focus,
			'keydown': this.delayCheck,
			'keypress': this.delayCheck,
			'blur': this.blur,
			'scroll': this.scrollFix
		});
		return this.fireEvent('clean');
	},

	// Disable the textarea
	disable: function(){
		this.textarea.blur();
		this.clean();
		this.textarea.set(this.options.disabled,true);
		return this.fireEvent('disable');
	},

	// Enables the textarea
	enable: function(){
		this.textarea.addEvents({
			'focus': this.focus,
			'scroll': this.scrollFix
		});
		this.textarea.set(this.options.disabled,false);
		return this.fireEvent('enable');
	}
});

})();





function submitwallpost()
{
	$('wallpostform').addEvent('submit', function(e) {
		e.stop();
		//Prevents the default submit event from loading a new page.
		
			insertwallpost();
			$('wall_text').set('value','Type your text here...');
			wallposter();
			
		
	});
}

function submitwallpostcomment()
{
	$$('.wallpostcommentform').removeEvents(); //('submit',
	$$('.wallpostcommentform').addEvent('submit', function(e) {
		e.stop();
		//Prevents the default submit event from loading a new page.
		//alert(1);
		
		 var formId = this.get('id');
		 //alert(formId);
		 
		 insertwallpostcomment(formId);
		 
		 a = this.getElement('textarea');
		 a2 = this.getElement('input[name=wall_id]');  
		 
		
		 
		 b = a.get('id');
		 b2 = a2.get('value');
		 
		 $(b).set('value', 'Comments...');
		 
		 
		 
		 //showHideCommentForm('hidden_comment_form_'+b2, b2);
		
	});
}

function submitprivatewallpost()
{
	$('wallpostprivateform').addEvent('submit', function(e) {
		e.stop();
		//Prevents the default submit event from loading a new page.
		
			insertprivatewallpost();
			
			wallposter();
		
	});
}

function wallfilter(filter){
	
	var myCookie = Cookie.write('wallfilter', filter, {duration: 1});
	window.location = baseurl;

}

function wallposttype(sub_id, sub_name){
	
	$('sharewith').set('html', sub_name);
	$('wall_post_sub_id').set('value', sub_id);
	
}

function deletewallpostevent()
{
	// deletewallpost attach the event to all the delete buttons (which are labeled with the .deletewallpost class
	$$(".deletewallpost").addEvent("click", function (event){
		 event.stop();
		 
		 // get the parent item id
		 var myElement = this.getParent('li');
		 a = myElement.get('id');
		
		 // send the request (acatuall the href...)
		 var myRequest = new Request({
			    url: this.href,
			    method: 'post',
			    onComplete: function(response) { 
			 
				 var myObject = JSON.decode(response);
					//alert(myObject);
					
				 // if successfull remove the deleted li 
					if(myObject.success == 1)
					{
					    $(a).set("tween", {
					    	duration: 1000,
					    	onComplete: function() {
					    		$(a).destroy();
					    		}});
					    
					    $(a).tween("opacity", 0);

					}
					// no success display an error alert 
					else{
						alert(myObject.message);
					}
		 }
	});
		 	
		 myRequest.send();
	
	});
	
	
}

function karmawallevent()
{
	//alert(10);
	$$('.karma').removeEvents();
	// deletewallpost attach the event to all the delete buttons (which are labeled with the .deletewallpost class
	$$(".karma").addEvent("click", function (event){
		 event.stop();
		 
		 // get the parent item id
		 var myElement = this.getParent('li');
		 a = myElement.get('id');
	
		 // send the request (acatuall the href...)
		 var myRequest = new Request({
			    url: this.href,
			    method: 'post',
			    onComplete: function(response) { 
			 
				 var myObject = JSON.decode(response);
					//alert(myObject);
					
				 // if successfull remove the deleted li 
					if(myObject.success == 1)
					{
					    x = a.split('_');
					   // alert(myRequest);
					    
					    //var z = Object.values(myRequest);
					    
					    //a//lert(z);

					    if(x[1] == 'id'){
					    	y = $('wall_karma_id_'+x[2]).get('html');
					    	if(myObject.posneg == '+'){
					    	y= parseInt(y) + 1;
					    	}
					    	else{
					    		y= parseInt(y) - 1;
					    	}
					    	
					    	y = y+'&nbsp;';
					    	$('wall_karma_id_'+x[2]).set('html', y);
					    	//alert(1);
					    }
					    if(x[1] == 'comment'){
					    	y = $('comment_karma_id_'+x[3]).get('html');
					    	if(myObject.posneg == '+'){
						    	y= parseInt(y) + 1;
						    	}
						    	else{
						    		y= parseInt(y) - 1;
						    	}
					    	y = y+'&nbsp;';
					    	$('comment_karma_id_'+x[3]).set('html', y);
					    	//alert(1);
					    }
					    	
					   // x = $('wall_karma_id_255').get('html');
						//x = $('wall_karma_id_255').get('html');
						//x= parseInt(x)+1;
						//$('wall_karma_id_255').set('html', x);
					}
					// no success display an error alert 
					else{
						alert(myObject.message);
					}
		 }
	});
		 	
		 myRequest.send();
	
	});
	
	
}



function insertwallpost()
{
	
	$('wallpostform').set('send', {
		
		onSuccess: function(response) { 
		//alert(1);
		var myObject = JSON.decode(response);
		//alert(myObject);
		
		if(myObject.success == 1)
		{
			if(!$('wall_id_'+myObject.wall_id)){
			
				x = new Element('li', {id: 'wall_id_'+myObject.wall_id ,html: myObject.wall_content})
				
				x.setStyle('opacity',0);
				
				//x.addClass('wall_li');
				x.inject($('wall'), 'top');  
				var fx = new Fx.Tween(x,{duration:600});	
				x.store('fx',fx);
				
				fx.addEvent('complete',function(){x.set('style',null);});	
				fx.start('opacity',1);
				// re-attach the delete events 
				deletewallpostevent();
				// re-attach the comment events 
				submitwallpostcomment();
				
				//commentposter('wall_comment_text_'+myObject.wall_id);
			}
		}
		
		if(myObject.success == 0)
			{
			alert(myObject.message);
				
			}
		
		
	},
	onFailure: function(xhr){
		//alert(xhr.status);
		if(xhr.status == 401){
			window.location = baseurl+'error/401.html';
		}
	}

	});
	//Send the form.
	$('wallpostform').send();
	
return;
}


function insertwallpostcomment(formId)
{
$(formId).set('send', {
		
		onSuccess: function(response) { 
		//alert(1);
		var myObject = JSON.decode(response);
		//alert(myObject);
		
		if(myObject.success == 1)
		{
			if(!$('wall_comment_id_'+myObject.wall_comment_id)){
				
				x = new Element('li', {id: 'wall_comment_id_'+myObject.wall_comment_id ,html: myObject.wall_comment_content})
				x.setStyle('opacity',0);
				
				x.inject($('comment_list_'+myObject.wall_id), 'bottom');  
				var fx = new Fx.Tween(x,{duration:600});	
				x.store('fx',fx);
				fx.addEvent('complete',function(){x.set('style','');});	
				fx.start('opacity',1);
		
		}
		}
		
		if(myObject.success == 0)
			{
			alert(myObject.message);
				
			}
		
		
	},
	onFailure: function(xhr){
		//alert(xhr.status);
		if(xhr.status == 401){
			window.location = baseurl+'error/401.html';
		}
	}

	});
	//Send the form.
	$(formId).send();
	
return;
}


function insertprivatewallpost()
{
	
	$('wallpostprivateform').set('send', {
		
		onComplete: function(response) { 
		
		var log = $('errors').empty();
		log.removeClass('error');
		log.removeClass('success');
		
		//alert(1);
		var myObject = JSON.decode(response);
		//alert(myObject);
		
		if(myObject.success == 1)
		{
			log.addClass('success');
			log.set('html', 'Your message was sent!')
			$('wallpostprivateform').addClass('hidden_comment_form');
		//	alert('Message send');
			
		}
		
		if(myObject.success == 0)
			{
			log.addClass('error');
			log.set('html', myObject.message)
			
				
			}
	}});
	//Send the form.
	$('wallpostprivateform').send();
	
return;
}


function showHideCommentForm(hidden_comment_form_id, wall_id){
	
	
	if($(hidden_comment_form_id).hasClass('hidden_comment_form'))
	{
		
		$(hidden_comment_form_id).removeClass('hidden_comment_form');
		$(hidden_comment_form_id).addClass('show_comment_form');
		
		// add the expanding textarea class to the comment field
		commentposter('wall_comment_text_'+wall_id);
		
	}
	else if ($(hidden_comment_form_id).hasClass('show_comment_form')){
		$(hidden_comment_form_id).removeClass('show_comment_form');
		$(hidden_comment_form_id).addClass('hidden_comment_form');
	}
	
	
	 
}

function wallposter()
{
	new DynamicTextarea('wall_text', {
	    minRows: 1,
	    
	    onFocus: function() {
	        if (this.textarea.value == 'Type your text here...'){
	            this.textarea.value = '';
	        	this.textarea.removeClass('wall_greyed');
	        	this.textarea.addClass('wall_default');}

	    },
	    onBlur: function() {
	        if (this.textarea.value == ''){
	        	this.textarea.removeClass('wall_default');
	        	this.textarea.addClass('wall_greyed');
	            this.textarea.value = 'Type your text here...';}
	        	
	    }
	    
	});	
}

function privatemodalposter(dataurl){
	
	// "_trackEvent" is the pageview event, 
	
	
	var yoffset = 0;
	if(dataurl.indexOf("stat") !== -1){yoffset = -250}
	else{yoffset = 0}
		
	_gaq.push(['_trackPageview', dataurl]);
	
	var myStickyWin = new StickyWin.Modal.Ajax({
	    content: 'leagueurl',
	    	url: dataurl,
	    	fadeDuration: 500,
	    	width: 500,
	    	//relativeTo: $('header'),
	    	offset: {
		x: 0,
		y: yoffset
	},
	    	//height: 200,
	    	destroyOnClose: true,
	    	 modalOptions: {
	    	    modalStyle:{
	    	      'background-color':'#d6e1b9',
	    	      'opacity':.6
	    	    }
	    	  }
	});
	myStickyWin.update();

	
	
}

function commentposter(wall_comment_text)
{
	//javascript:showHideCommentForm('hidden_comment_form_107', '107');
	//alert(wall_comment_text);
	
	
	new DynamicTextarea(wall_comment_text, {
	    minRows: 1,
	    delay: false,
		lineHeight: 20,
		offset: 5,
		padding: 5,

	    onFocus: function() {
	        if (this.textarea.value == 'Comments...'){
	            this.textarea.value = '';
	        	this.textarea.removeClass('wall_greyed');
	        	this.textarea.addClass('wall_default');}

	    },
	    onBlur: function() {
	        if (this.textarea.value == ''){
	        	this.textarea.removeClass('wall_default');
	        	this.textarea.addClass('wall_greyed');
	            this.textarea.value = 'Comments...';}
	        	
	    }
	});	
}


function dateTimeAgo(servertime)
{

	var today = new Date().parse(servertime);
	
	// do this periodically
	Array.each($$(".datetimeago"), function(el, index){
		var olddate  = el.get('title');
		
		
		var ago = today.diff(olddate, 'second');
		//alert(newdiff);
		
		//alert(ago);
		if(ago < 0 && ago > -60){
			newdiff = Math.abs(ago) + ' seconds ago';
		}
		else if(ago < -60 && ago > -3600){
			newdiff = Math.abs(Math.round(ago/60)) + ' minutes ago';
				}
		else if(ago <-3600 && ago > -24*3600){
			newdiff = Math.abs(Math.round(ago/(3600))) + ' hours ago';
				}
		else{
			newdiff = '@ ' + olddate;
		}
		
		
		el.set('html', newdiff);
		//el.inject(newdiff);
	    
	});;
	
	
	return;
}

function refreshWall()
{
	var x = new Request({
	    method: 'post',
	    url: baseurl+'wallrefresh',
	    initialDelay: 60000,
	    delay: 600000,
	    limit: 15000,
	    onSuccess: function(response){
			
		var myObject = JSON.decode(response);
		
		if(myObject.success == 1)
		{
			    
			for(i in myObject.comments)
				
			{
				var value = myObject.comments[i].wall_content;
				
			
			if(!$('wall_id_'+myObject.comments[i].wall_id)){
				
				
				x = new Element('li', {id: 'wall_id_'+myObject.comments[i].wall_id ,html: myObject.comments[i].wall_content})
				
				x.setStyle('opacity',0);
				
				//x.addClass('wall_li');
				x.inject($('wall'), 'top');  
				var fx = new Fx.Tween(x,{duration:600});	
				x.store('fx',fx);
				
				fx.addEvent('complete',function(){x.set('style',null);});	
				fx.start('opacity',1);
				// re-attach the delete events 
				//deletewallpostevent();
				// re-attach the comment events 
				//submitwallpostcomment();

	
		} // end if id exists
		}  // end for loop
			for(i in myObject.comments)
				
			{
				if(myObject.comments[i].comment.length > 0){
					//alert(1);
					
					
					for(j=0; j<myObject.comments[i].comment.length; j++)
					{
						//myvar = myvar + myObject.message[i] + "<br />";
						
						
						if(!$('wall_comment_id_'+myObject.comments[i].comment[j].wall_comment_id)){
							//alert(myObject.comments[i].comment[j].wall_comment_id);
							//alert(myObject.comments[i].wall_id);
							//alert(myObject.comments[i].comment[j].comment_content);
							x = new Element('li', {id: 'wall_comment_id_'+myObject.comments[i].comment[j].wall_comment_id ,html: myObject.comments[i].comment[j].wall_comment_content})
							x.setStyle('opacity',0);
							
							x.inject($('comment_list_'+myObject.comments[i].wall_id), 'bottom');  
							var fx = new Fx.Tween(x,{duration:600});	
							x.store('fx',fx);
							fx.addEvent('complete',function(){x.set('style','');});	
							fx.start('opacity',1);
					
					}
						
						
					}

				}

			}
		
		} // end if success
		
		if(myObject.success == 0)
			{
			alert(myObject.message);
				
			}

	}
	});
			
	x.startTimer();		
}


function wallgetallcomments()
{
	
	$$(".wallgetallcomments").addEvent("click", function (event){
		 event.stop();
	
		 // send the request (acatuall the href...)
		 var myRequest = new Request({
			    url: this.href,
			    method: 'post',
			    onComplete: function(response) { 
			 
				 var myObject = JSON.decode(response);
					//alert(myObject);
					
				 // if successfull remove the deleted li 
					if(myObject.success == 1)
					{
						$('more_comments_'+myObject.comment[0].wall_id).destroy();	
						
						for(i in myObject.comment)
							
						{
							//alert(myObject.comment[i].wall_comment_id);
						if(myObject.comment[i].wall_comment_id != undefined){
							if(!$('wall_comment_id_'+myObject.comment[i].wall_comment_id)){
							
								//alert(myObject.comment[i].wall_comment_id);
								
								x = new Element('li', 
										{id: 'wall_comment_id_'+myObject.comment[i].wall_comment_id,
										html: myObject.comment[i].wall_comment_content
										});
								x.setStyle('opacity',0);
								
								//alert(x);
								
								x.inject($('comment_list_'+myObject.comment[i].wall_id), 'top');  
								var fx = new Fx.Tween(x,{duration:600});	
								x.store('fx',fx);
								fx.addEvent('complete',function(){x.set('style','');});	
								fx.start('opacity',1);
								 
						
							} // end if
						}
						} // end for loop
						
						// re-attach the events
						//karmawallevent();
						

					}
					// no success display an error alert 
					else{
						alert(myObject.message);
					}
		 }
	});
		 	
		 myRequest.send();
		 
	});
	
	
}

function wallgetkarma(getkarmaurl)
{
	// "_trackEvent" is the pageview event, 
	_gaq.push(['_trackPageview', getkarmaurl]);

	var myStickyWin = new StickyWin.Modal.Ajax({
	    content: 'leagueurl',
	    	url: baseurl+getkarmaurl,
	    	fadeDuration: 500,
	    	width: 300,
	    	//height: 200,
	    	destroyOnClose: true,
	    	 modalOptions: {
	    	    modalStyle:{
	    	      'background-color':'#d6e1b9',
	    	      'opacity':.6
	    	    }
	    	  }
	});
	myStickyWin.update();
}





