//cufon
//Cufon.replace('.light_font, h1', { fontFamily: 'light_font', hover: true });
//Cufon.replace('.book_font, h2, .light_font strong', { fontFamily: 'regular_font', hover: true });
//Cufon.replace('.medium_font, h3, .book_font strong', { fontFamily: 'semibold_font', hover: true });

//some vars
var cornerLogo, footer, loginRequest, shadowTimer = function(){}, messageOpen = false, preventLoginPageRefresh = false, pageNeedsRefresh = false, newsSubNavToHide;


//for add this
var addthis_config = {
	ui_click: true,
	ui_cobrand: "Winvale",
	ui_header_color: "#ffffff",
    ui_header_background: "#003E7E",
	services_compact: 'print,email,favorites,google,digg,delicious,linkedin,twitter,facebook,stumbleupon'
}
var addthis_share = {
	templates: { 
		twitter: 'Take a look at {{title}} (from @winvale) at {{url}}' 
	}
}

//a class for the "quick" side tabs
var SidePanel = new Class({
	Implements: Options,
	options: {
		fadeTime: 250,
		delay: 2000,
		closedWidth: -290,
		openWidth: 0
	},
	timer: '',
	el: '',
	state: 'closed',
	initialize: function(el, options)
	{
		this.setOptions( options );
		this.el = el;
		this.el.set('morph', {duration: this.options.fadeTime, transition: 'sine:out', link: 'cancel'});
		
		this.el.addEvents({
			'mouseenter': function() {
				this.enter();
			}.bind(this),
			'mouseleave': function() {
				if (this.state == 'open')
				{
					this.leave();	
				}
			}.bind(this)
		});
		
		this.el.getElement('.tab_area').addEvent('click', function(e) {
			e.preventDefault();
			if (this.state == 'closed')
			{
				this.expand();
			}
			else
			{
				this.contract();
			}
		}.bind(this));
	},
	leave: function()
	{
		this.timer = ( function() { 
			this.contract();
		}).delay( this.options.delay, this );
	},
	enter: function()
	{
		window.clearInterval( this.timer );
	},
	expand: function()
	{
		this.el.morph({ 'right': this.options.openWidth });
		this.state = 'open';
	},
	contract: function()
	{
		this.el.morph({ 'right': this.options.closedWidth});
		this.state = 'closed';
	}
});

window.addEvent('domready', function() {
	
		
	//search
	setupSearch();
	
	var hiddenNav = $$('.side_nav_item.selected li a');
	if(hiddenNav.get("href") == "/about/newsletter/thanks/") hiddenNav.setStyle('display', 'none');
	
	//shadow
	if ( document.id('shadow') )
	{
		if ( ! Browser.ie6 )
		{
			document.id('shadow').set('morph', {duration: 500, transition: 'sine:out', link: 'cancel'}); 
			document.id('shadow').setStyle('opacity', 0);
		}
		document.id('shadow_close').addEvent('click', function(e)
		{
			e.preventDefault();
			closeShadow();
		});
	}
	
	//login request
	loginRequest = new Request({
		url: '/user/ajax_login_form',
		link: 'cancel',
		method:'post',
		onRequest: function()
		{
			document.id('shadow_content_inner').set('html', '<img src="/images/css/ajax_loader.gif" alt="" />');
			openShadow();
		},
		onSuccess: function(response)
		{
			//alert(loginRequest.data);
			document.id('shadow_content_inner').set('html', response);
			setupLogin();
		},
		onFailure: function(xhr)
		{
			alert('An error occurred: ' + xhr);	
		}
	});
	
	//login/logout functionality
	setupLoginLogout();
	
	//quick connect and quick links
	if ( document.id('quick_links') )
	{
		new SidePanel( document.id('quick_links') );
	}
	if ( document.id('quick_connect') )
	{
		new SidePanel( document.id('quick_connect') );
		setupQuickConnectForm();
	}
	
	
	//setup social media icons
	//if ( document.id('social_icons') )
	//{
	//	var url = location.href;
	//	var title = document.id(document.head).getFirst('title').get('text');
		
	//	document.id('facebook').setProperty('href', 'http://www.facebook.com/sharer.php?u=' + encodeURI(url) + '&t=' + encodeURIComponent(title));
	//	document.id('twitter').setProperty('href', 'http://twitter.com/home?status=' + encodeURIComponent(title + ' - ' + url) );
	//	document.id('linked_in').setProperty('href', 'http://www.linkedin.com/shareArticle?mini=true&url=' + encodeURIComponent(url) + '&title=' + encodeURIComponent(title) + '&source=' + location.href);
	//	document.id('social_icons').setStyles({'display': 'block', 'opacity': 0});
	//	document.id('social_icons').set('tween', {duration: 1000, transition: 'sine:out', link: 'cancel'});
	//	document.id('social_icons').tween('opacity', 1);
	//}
});

window.addEvent('load', function() {
	//corner logo
	cornerLogo = document.id('corner_logo');
  	footer = document.id('footer');
	window.addEvent('resize', function() 
	{
		positionCornerLogo();
	});
	window.fireEvent('resize');
	cornerLogo.setStyles({'display': 'block'});
});

function positionCornerLogo() {
	var pos = footer.getPosition();
	if ( pos.x < 181 )
	{
		cornerLogo.setStyles({'left': pos.x + 960 + 10, 'right' : 'auto', 'top': pos.y - 180 });
	}
	else
	{
		cornerLogo.setStyles({'left': 'auto', 'right': -1, 'top': pos.y - 180 });
	}
}

function getScreenSize()
{
	//get the width and height
	var x,y;
	if (self.innerHeight) //all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) //other Explorers
	{
		x = document.body.clientWidth;
	}
	
	return({'x': x, 'y': y});
}

function setupSearch()
{
	
	var searchText = htmlspecialchars_decode('Search');
	if ( document.id('mainSearchBox') )
	{
		//setup search box text
		if (undefined !== window.searchResults) 
		{
			document.id('mainSearchBox').setProperty('value', searchResults);
		}
		else
		{
			document.id('mainSearchBox').setProperty('value', searchText);
		}
		document.id('mainSearchBox').addEvents(
		{
			'blur': function() {
				if (this.getProperty('value').trim() == '')
				{
					this.setProperty('value', searchText);
				}
			},
			'focus':function() {
				var textBoxValue = this.getProperty('value');
				if ( textBoxValue.trim() == searchText)
				{
					this.setProperty('value', '');
				}
			}
		});
		
		//setup submit event
		document.id('main_search_form').addEvent('submit', function(e)
		{
			var temp = document.id('mainSearchBox').getProperty('value').trim();
			if ( (temp == 'Search') || (temp == '') )
			{
				alert('You must enter a search term');
				return false;
			}
		});
	}
}

function htmlspecialchars_decode(text)
{
	var stub_object = new Element('span',{'html':text});
	var ret_val = stub_object.get('text');
	delete stub_object;
	return ret_val;
}

//break words
function breakWords()
{
	$$('.break_words a').each( 
		function(element, index)
		{
			element.set('html', element.get('html').replace(/\//g, '/&#8203;').replace(/\./g, '.&#8203;').replace(/_/g, '_&#8203;'));
		}
	);
	
	$$('.break_words').each( 
		function(element)
		{element.removeClass('.break_words');}
	);
}

//setup login and logout links
function setupLoginLogout()
{
	$$('a.logout').each( function(element, index) {
		element.removeEvents('click');
		element.set('send', {
			url: element.getProperty('href'),
			onSuccess: function(response)
			{
				alert( "You are now logged out." );
				window.location.replace( unescape(window.location.pathname) );
			},
			onFailure: function(xhr)
			{
				alert( 'An error occurred: ' + xhr, true );	
			}
		});

		element.addEvent('click', function(e) {
			e.preventDefault();
			//logout functionality
			element.send();
		});
	});
	
	$$('a.login').each( function(element, index) {
		element.removeEvents('click');
		
		element.addEvent('click', function(e) {
			e.preventDefault();
			//login functionality
			if ( this == document.id('login') )
			{
				preventLoginPageRefresh = false;
				loginRequest.options.data = 'main=true';
			}
			else
			{
				loginRequest.options.data = '';
			}
			loginRequest.send();
		});
	});
}

//setup the login
function setupLogin()
{
	var loginForm = document.id('login_holder').getFirst('form');
	Cufon.refresh();
	loginForm.set('send', {
		onSuccess: function(response)
		{
			var dummy = new Element('div');
			dummy.set('html', response);
			var message;
			
			if ( (dummy.getElement('h1').get('text') == 'The form you submitted contained the following errors') || dummy.getElement('h1').get('text') == 'The following errors were encountered' )
			{
				message = dummy.getElement('h1').get('text') + ':';
				
				dummy.getElement('ul').getChildren('li').each( 
					function( element, index)
					{
						message += '\n' + element.get('text');
					}
				);
				alert( message );
			}
			else if ( dummy.getElement('h1').get('text') == 'Thank You!' ) {
				
				if ( preventLoginPageRefresh === false )
				{
					message = "You are now logged in!";
					alert( message );
					window.location.replace( unescape(window.location.pathname) );
				}
				else
				{
					pageNeedsRefresh = true;
					//hook into the event registration
					if( undefined !== window.registerForEvent )
					{
						registerForEvent();
					}	
				}
			}
		},
		onFailure: function(xhr)
		{
			alert('An error occurred: ' + xhr);	
		}
	});
	
	document.id('ajax_login_cancel').addEvent( 'click', function(e) {
		e.preventDefault();
		closeShadow();
	});
	
	loginForm.addEvent('submit', function(e)
	{
		e.preventDefault();
		
		if ( document.id('ajax_login_username').getProperty('value') == 'Username' )
		{
			document.id('ajax_login_username').setProperty('value', '');
		}
		if ( document.id('ajax_login_password').getProperty('value') == 'Password' )
		{
			document.id('ajax_login_password').setProperty('value', '');
		}

		loginForm.send();
	});
	
	document.id('ajax_login_username').addEvents(
	{
		'blur': function() {
			if (this.getProperty('value').trim() == '')
			{
				this.setProperty('value', 'Username');
			}
		},
		'focus':function() {
			var textBoxValue = this.getProperty('value');
			if ( textBoxValue.trim() == 'Username')
			{
				this.setProperty('value', '');
			}
		}
	});
	
	document.id('ajax_login_password').setProperty('type', 'text');
	document.id('ajax_login_password').addEvents(
	{
		'blur': function() {
			if (this.getProperty('value').trim() == '')
			{
				this.setProperty('type', 'text');
				this.setProperty('value', 'Password');
			}
		},
		'focus':function() {
			var textBoxValue = this.getProperty('value');
			if ( textBoxValue.trim() == 'Password')
			{
				this.setProperty('value', '');
			}
			this.setProperty('type', 'password');
		}
	});
}

//open the shadow
function openShadow()
{
	shadowTimer = clearTimeout(shadowTimer);
	document.id('shadow_bg').removeEvents('click');
	shadowTimer = ( function() { 
		document.id('shadow_bg').addEvent('click', function(e) {
			closeShadow();
		});
	}).delay(500);
	
	document.id('shadow').setStyle('display', 'block');
	//$('shadow_bg').setStyle('opacity', .8);
	if ( ! Browser.ie6 )
	{
		document.id('shadow').morph({'opacity': 1});
	}
	
	var bodyOffset = document.id( document.body ).getScroll();
	document.id('shadow_content_holder').setStyle('margin-top', bodyOffset.y + 120);
	
	window.addEvent('scroll', shadowScroll );
}

function shadowScroll() {
	if ( getScreenSize().y > document.id('shadow_content_inner').getSize().y + 120 )
	{
		document.id('shadow_content_holder').setStyle('margin-top', document.id( document.body ).getScroll().y + 120);
	}
}

//close the shadow
function closeShadow()
{
	loginRequest.cancel();
	if ( ! Browser.ie6 )
	{
		document.id('shadow').morph({'opacity': 0});
		shadowTimer = ( function() { document.id('shadow').setStyle('display', 'none'); }).delay(500);
	}
	else
	{
		document.id('shadow').setStyle('display', 'none');
	}
	
	window.removeEvent('scroll', shadowScroll );
}


//sets up the quick connect form
function setupQuickConnectForm()
{
	var qc = document.id('quick_connect').getFirst('form');
	var qcRequest = new Request({
		url: qc.getProperty('action'),
		link: 'cancel',
		method:'post',
		onSuccess: function(response)
		{
			var json = JSON.decode(response);
			if (json.success)
			{
				alert(json.reason);
				document.id('qc_email').setProperty('value', '');
				document.id('qc_phone').setProperty('value', '');
			}
			else
			{
				alert(json.reason);
			}
		},
		onFailure: function(xhr)
		{
			alert('An error occurred: ' + xhr);	
		}
	});
	
	qc.addEvent('submit', function(e)
	{
		e.preventDefault();
		qcRequest.options.data = qc.toQueryString() + '&method=ajax';
		qcRequest.send();
	});
}


