var redAccordion;
var greenAccordion;

//Shadowbox.loadSkin('classic', 'javascript/shadowbox-2.0/src/skin');
//Shadowbox.loadLanguage('en', 'javascript/shadowbox-2.0/src/lang');
//Shadowbox.loadPlayer(['flv', 'html', 'iframe', 'img', 'swf'], 'javascript/shadowbox-2.0/src/player');

window.addEvent('domready', function() {

	Shadowbox.init();
	

	// Add the AJAX login processing if the form exists
	if( $('account_login_form') ) {
		initLoginForm(); //set up the login events and actions
	} else if ( $('account_logout_form') ) {
		initLogoutForm(); //set the logout events and actions
	}

	// add the AJAX shopcart action
	/*
	if( $('account_shopcart') ) {
		$('_shopcart').addEvent('click', function(e) {
			e = new Event(e).stop(); //stop the link event
			showCart();
		});
	}
	*/
	
	// add the AJAX ingredients action
	if( $('ingredients_detail') ) {
		if ( $('_ingredients') ) {
			$('_ingredients').addEvent('click', function(e) {
				e = new Event(e).stop(); //stop the link event
				var product_id = e.target.href.split('=')[1];
				showIngredients(product_id);
			});
		}
	}
	

	//add the image hover events
	var images = $$('.hoverChange');
	images.each(function(image) {
		image.addEvent('mouseenter', function(e) {
			e = new Event(e);
			var src = e.target.src;
			var ext = src.split('.')[src.split('.').length-1];
			if( ! src.contains('_over') ) {
				e.target.set('src', e.target.src.replace('.'+ext, '_over.'+ext));
			}
		});
		image.addEvent('mouseleave', function(e) {
			e = new Event(e);
			var src = e.target.src;
			e.target.set('src', src.replace('_over', ''));
		});
	});

	//add the background hover events
	var images = $$('.hoverBgChange');
	images.each(function(image) {
		image.addEvent('mouseenter', function(e) {
			e = new Event(e);
			var src = e.target.getStyle('backgroundImage');
			var ext = src.split('.')[src.split('.').length-1];
			if( ! src.contains('_over') ) {
				e.target.setStyle('backgroundImage', src.replace('.'+ext, '_over.'+ext));
			}
		});
		image.addEvent('mouseleave', function(e) {
			e = new Event(e);
			var src = e.target.getStyle('backgroundImage');
			e.target.setStyle('backgroundImage', src.replace('_over', ''));
		});
	});

	
	if($('content'))
	{
		//set up the accordian menus on the right
		redAccordion = new Accordion('#red_toggler div.toggler', '#red_toggler div.content', { 
			opacity: false, 
			display: false,
			alwaysHide: true,
			onActive: function(toggler, content){ toggler.addClass('menuRightOnRed'); toggler.removeClass('menuRightOffRed'); },
			onBackground: function(toggler, content){ toggler.addClass('menuRightOffRed'); toggler.removeClass('menuRightOnRed'); }
		});
		greenAccordion = new Accordion('#green_toggler div.toggler', '#green_toggler div.content', { 
			opacity: false, 
			display: false,
			alwaysHide: true,
			onActive: function(toggler, content){ toggler.addClass('menuRightOnGreen'); toggler.removeClass('menuRightOffGreen'); },
			onBackground: function(toggler, content){ toggler.addClass('menuRightOffGreen'); toggler.removeClass('menuRightOnGreen'); }
		});
	}

});

function initLoginForm() {
	//set up the button click event
	$('_login').addEvent('click', function(e) {
		e = new Event(e).stop();
		$('account_login_button').hide();
		$('account_login').fade(100);
	});

	//add the login form event
	$('account_login_form').set('send', { url: 'io/login.php', method: 'post', onSuccess: showLoginResult });
	$('account_login_form').addEvent('submit', function(e) {
		e = new Event(e).stop(); //stop the form from submitting

		if( validateLoginForm() ) {
			$('account_login_form').send();
		} else {
			showLoginError();
		}
	});
}

function deinitLoginForm() {
	$('account_login_form').removeEvents();
	$('account_login').destroy();
}

function initLogoutForm() {
	//add the logout form event
	$('account_logout_form').set('send', { url: 'io/logout.php', method: 'post', onSuccess: showLogoutResult });
	$('account_logout_form').addEvent('submit', function(e) {
		e = new Event(e).stop();
		$('account_logout_form').send();
	});
}

function deinitLogoutForm() {
	$('account_logout_form').removeEvents();
	$('account_logout_form').destroy();
}

function validateLoginForm() {
	var inputs = $('account_login').getElements('input');

	for(var i=0; i<inputs.length; i++) {
		if( ! $chk(inputs[i].value) ) {
			return false;
		}
	}

	if( ! validateEmail($('account_email').value) ) {
		return false;
	}

	return true;
}

function showLoginError() {
	alert('You have entered an invalid email or password.\n\nPlease check your information and try again.');
}

function showLogoutError() {
	alert('There was a problem logging you out of your account.\n\nPlease try again.');
}

function showLoginResult(data, xml) {
	if(data == 0) {
		showLoginError();
	} else {
		//alert('success');
		var fx = new Fx.Tween($('account_node'), {
			onComplete: function() {
				if( window.location.href.contains('billing.php') || window.location.href.contains('order_history.php') ) {  //reload page
					window.location.reload();
				} else if( window.location.href.contains('login.php') ) {
					window.location.href = 'account.php';
				} else {
					//update the "i want the usual" right menu, if it exists
					if( $('the_usual') ) {
						new Request({ method: 'get', url: 'io/the_usual.php', onSuccess: function(data) {
								$('the_usual').set('html', data);
								redAccordion.addSection($$('#the_usual .toggler')[0], $$('#the_usual .content')[0], 0);
							}
						}).send();
					}

					deinitLoginForm();
					$('account_node').set('html', data);
					initLogoutForm();
					$('account_node').fade(100);
				}
			}
		}).start('opacity', 100, 0);
	}
}

function showLogoutResult(data, xml) {
	if(data == 0) {
		showLogoutError();
	} else {
		var fx = new Fx.Tween($('account_node'), {
			onComplete: function() {
				if( window.location.href.contains('billing.php') || window.location.href.contains('order_history.php') ) {  //reload page
					window.location.reload();
				} else if( window.location.href.contains('account.php') ) {
					window.location.href = 'login.php';
				} else {
					//update the "i want the usual" right menu, if it exists
					if( $('the_usual') ) {
						new Request({ method: 'get', url: 'io/the_usual.php', onSuccess: function(data) {
								$('the_usual').set('html', data);
								redAccordion.addSection($$('#the_usual .toggler')[0], $$('#the_usual .content')[0], 0);
							}
						}).send();
					}

					deinitLogoutForm();
					$('account_node').set('html', data);
					initLoginForm();
					$('account_node').fade(100);
				}
			}
		}).start('opacity', 100, 0);

	}
}

function validateEmail(email) {
	//use a reular expression to check if the email is valid (very simple, but effective enough for internal use)
	if(email.match(/^[a-z0-9]+[a-z0-9_-]*(([\.])|([a-z0-9_-]*))[a-z0-9_-]+[@]{1}[a-z0-9_-]+[.](([a-z]{2,6})|([a-z]{2,6}[.]{1}[a-z]{2,3}))$/i)) {
		return true;
	} else {
		return false;
	}
}


function showCart() {
	var target = $('account_shopcart');
	target.setStyle('visibility', 'hidden');
	showShader();

	//target.load('io/shopping_cart.php');
	var request = new Request({ url: 'io/shopping_cart.php', onSuccess: function(data) {

		var drawDelay = 200;
		target.innerHTML = data;

		target.set('tween', { duration: 700, onComplete: function(){ $('shader').set('html', ''); } });
		target.fade.delay(drawDelay, target, [0, 2]);

		if(Browser.Engine.trident) {
			target.center.delay(drawDelay, $('account_shopcart'));
			window.addEvent('resize', function(e) { target.center(); });
			window.addEvent('scroll', function(e) { target.center(); });
		} else {
			var top = window.getSize().y.toInt()/2 - target.getSize().y.toInt()/2;
			var left = window.getSize().x.toInt()/2 - target.getSize().x.toInt()/2;
			//target.setStyle.delay(drawDelay, target, ['top', top]);
			//target.setStyle.delay(drawDelay, target, ['left', left]);
			//target.setStyle.delay(drawDelay, target, ['position', 'fixed']);
			target.setStyles({
				'top': top,
				'left': left,
				'position': 'fixed'
			});
		}
	} }).send();
}


function showIngredients(product_id) {
	var target = $('ingredients_detail');
	target.setStyle('visibility', 'hidden');
	showShader();

	//target.load('io/shopping_cart.php');
	var request = new Request({ method: 'get', url: 'io/ingredients_detail.php', onSuccess: function(data) {

		var drawDelay = 200;
		target.innerHTML = data;

		target.set('tween', { duration: 700, onComplete: function(){ $('shader').set('html', ''); } });
		target.fade.delay(drawDelay, target, [0, 2]);

		if(Browser.Engine.trident) {
			target.center.delay(drawDelay, $('ingredients_detail'));
			window.addEvent('resize', function(e) { target.center(); });
			window.addEvent('scroll', function(e) { target.center(); });
		} else {
			var top = window.getSize().y.toInt()/2 - target.getSize().y.toInt()/2;
			var left = window.getSize().x.toInt()/2 - target.getSize().x.toInt()/2;
			//target.setStyle.delay(drawDelay, target, ['top', top]);
			//target.setStyle.delay(drawDelay, target, ['left', left]);
			//target.setStyle.delay(drawDelay, target, ['position', 'fixed']);
			target.setStyles({
				'top': top,
				'left': left,
				'position': 'fixed'
			});
		}
	} }).send('product_id='+product_id);
}


function showShader() {
	if(!$('shader')) { //insert the shader if it doesn't exist
		var shader = new Element('div', {
			id: 'shader'
		});
		shader.inject($$('body')[0]);
	}

	$('shader').setStyles({
		'width': window.getSize().x,
		'height': window.getSize().y,
		'text-align': 'center',
		'padding-top': 20,
		'font-size': '14pt',
		'font-weight': 'bold'
	})
	.set('html', 'Loading...')
	.show()
	.setOpacity(0.7);

	if(Browser.Engine.trident) {
		$('shader').center();
		window.addEvent('resize', function(e) { showShader(); });
		window.addEvent('scroll', function(e) { showShader(); });
	} else {
		//$('shader').setStyle('position', 'fixed');
		var top = window.getSize().y.toInt()/2 - $('shader').getSize().y.toInt()/2;
                var left = window.getSize().x.toInt()/2 - $('shader').getSize().x.toInt()/2;
                $('shader').setStyles({ 
                        'top': top,
                        'left': left,
			'position': 'fixed'
                });
	}
}

function hideCart() {
	$('account_shopcart').set('tween', { duration: 700, onComplete: function() { $('shader').hide(); } });
	$('account_shopcart').fade(1, 0);
	window.removeEvents();
}

function hideIngredients() {
	$('ingredients_detail').set('tween', { duration: 700, onComplete: function() { $('shader').hide(); } });
	$('ingredients_detail').fade(1, 0);
	window.removeEvents();
}

