/* On window load */
Event.observe(window, "load", function(event){

	//Get the windows current location
	var location = window.location.href.split("/");
	var errors = [];	
	
	/* Menu stuff */
	//Loop through al of the menu list items and attach mouseover and mouse out functions
	$$("#menu li").each(function(el){
		el.observe("mouseover", function(e){ this.addClassName("sfhover") });
		el.observe("mouseout", function(e){ this.removeClassName("sfhover") });
	});
	
	
	/* If the image scroller is on the page */
	if ($('scroller') != null){		
		//Global variables
		var pe;
		var nextItem = '2';
		
		//A function to change the scoller
		var selectScrollerItem = function(id){
			//Check if the item exists and isn't selected
			var scrollerItem = $("scroller_item_" +id);
			if (scrollerItem == null || scrollerItem.hasClassName("selected_scroller_item")){
				return false;
			}
			
			//Get some elements
			var scrollerImage =  $("scroller_image_" +id);
			var selectedScrollerItem = $$("div.selected_scroller_item:first img")[0];
			var selectedScrollerImage = $("scroller_image_" +selectedScrollerItem.id.substr(14));		
			
			//Change the scroller item
			new Effect.Parallel([
				new Effect.Appear(scrollerImage.id, { sync: true }),
				new Effect.Fade(selectedScrollerImage.id, { sync: true }),
				new Effect.Morph(scrollerItem.id, { style: 'background: #7badd4; color: #fff;', sync: true, afterFinish: function(effect){ effect.element.addClassName('selected_scroller_item'); }}),
				new Effect.Morph(selectedScrollerItem.id, { style: 'background: #f7f7f7; color: #707070;', sync: true, afterFinish: function(effect){ effect.element.removeClassName('selected_scroller_item'); }})
			], {duration: 0.75});
			
			//Reset the scroller switcher
			nextItem = selectedScrollerItem.id.substr(14);
		}
		
		//Observe all of the scroller items
		$$("#scroller .scroller_items .scroller_item").each(function(el){
			el.observe("click", function(e){ selectScrollerItem(this.id.substr(14)) });
		});
		
		//A delegate function for the periodical updater
		var peDelegator = function(){
			//Change the scroller item
			selectScrollerItem(nextItem);
			
			//Reset the periodical updater
			if (pe) pe.stop();
			pe = new PeriodicalExecuter(peDelegator, 10);
		}
		
		//Start the periodical updater
		pe = new PeriodicalExecuter(peDelegator, 10);
	}
	
	/* If we're in the "my account" screen the default module */
	if (location.inArray('myaccount') && location.inArray('account')){
		$("shipping_identical").observe("click", function(){
			if ($("shipping_identical").checked){				
				$("shipping_address").disabled = true;
				$("shipping_address2").disabled = true;
				$("shipping_zipcode").disabled = true;
				$("shipping_city").disabled = true;
				$("shipping_state").disabled = true;
				$("shipping_country").disabled = true;	
			}
			else {
				$("shipping_address").disabled = false;
				$("shipping_address2").disabled = false;
				$("shipping_zipcode").disabled = false;
				$("shipping_city").disabled = false;
				$("shipping_state").disabled = false;
				$("shipping_country").disabled = false;
			}
		});
	}
	
	
	/* If we're in the newsletters section in the default module */
	if (location.inArray('newsletters')){
		/* General functions */
		//Create the error messages
		displayError = function(error){
			//Create the error list
			var ul = new Element('ul').addClassName("errors");		
			
			//Stuff the error item in the list
			var li = new Element('li');
			li.setStyle({display: "none"});
			li.id = error.key +"_errors";
			
			//Stuff the contents in the list item
			var div = new Element('div').update(error.value);
			
			//Put the error element on the screen
			li.insert(div);
			ul.insert(li);
			$(error.key).ancestors()[0].insert(ul);
			
			//Display the error messages
			Effect.BlindDown(li.id, {duration: 0.3, queue: {position: 'end', scope: 'subscribe'}});			
		}
		
		//Hide the error messages
		hideErrors = function(formName){
			$A($$("#" +formName +" ul.errors")).each(function(element){
				element.remove();
			});
		}
		
		
		/* Subscribing */		
		//Handle if the form is submitted
		submitSubscribeForm = function(){

			//Get the length of the queue
			var queue = Effect.Queues.get('subscribe');
			var queueLength = 0;
			queue.each(function(element){
				queueLength++;
			});
						
			//Submit the form if the queue is empty
			if (queueLength == 0){				
				//Hide the old errors
				hideErrors("newsletter_subscribe_form");
				
				//Send the ajax request
				new Ajax.Request(
					ajaxUrl +'newsletters/subscribe',
					{
						method: 'post',
						requestHeaders: {'x-ajax-request': true},
						parameters: $('newsletter_subscribe_form').serialize(true),
						onSuccess: function(transport){
							//Get the response
							var jsonResponse = transport.responseJSON;
						
							//If an error occured
							if (jsonResponse.result == "error"){
								//Loop through the errors and create them
								$H(jsonResponse.errors).each(function(error){
									displayError(error);
								});
							}
								
							
							//Otherwise if all went well
							else if (jsonResponse.result == "ok"){
								//Stop the observing
								$('subscribe_submit_button').stopObserving('click');
								$('newsletter_subscribe_form').stopObserving('submit');
								
								//Remove the form
								var parentDiv = $('newsletter_subscribe_form').ancestors()[0];
								parentDiv.childElements().each(function(child){
									if (child.tagName == "FORM"){
										child.remove();
									}
								});
								
								//Display the success message
								var div = new Element('div').update(jsonResponse.message);
								div.addClassName("message");
								div.setStyle({
									textAlign: "center",
									padding: "40px 0 25px"
								});
								
								parentDiv.insert(div);
							}
						}
					}
				);
			}
		}
		
		//Make sure the submit button actually submits
		$("subscribe_submit_button").observe("click", function(event){ 
			submitSubscribeForm();
			return false;
		});
		
		//Observe if the subscribe form is being submitted
		$("newsletter_subscribe_form").observe("submit", function(event){ 
			//Submit the form
			submitSubscribeForm();
			
			//Make sure the form isn't submitted
			Event.stop(event);
			return false;
		});
		
		
		/* Unsubscribing */
		//Handle if the form is submitted
		submitUnsubscribeForm = function(){
			
			//Get the length of the queue
			var queue = Effect.Queues.get('unsubscribe');
			var queueLength = 0;
			queue.each(function(element){
				queueLength++;
			});
						
			//Submit the form if the queue is empty
			if (queueLength == 0){				
				//Hide the old errors
				hideErrors("newsletter_unsubscribe_form");
				
				//Send the ajax request
				new Ajax.Request(
					ajaxUrl +'newsletters/unsubscribe',
					{
						method: 'post',
						requestHeaders: {'X-Ajax-Request': true},
						parameters: $('newsletter_unsubscribe_form').serialize(true),
						onSuccess: function(transport){
							//Get the response
							var jsonResponse = transport.responseJSON;
						
							//If an error occured
							if (jsonResponse.result == "error"){
								//Loop through the errors and create them
								$H(jsonResponse.errors).each(function(error){
									displayError(error);
								});
							}
								
							
							//Otherwise if all went well
							else if (jsonResponse.result == "ok"){
								//Stop the observing
								$('unsubscribe_submit_button').stopObserving('click');
								$('newsletter_unsubscribe_form').stopObserving('submit');
								
								//Remove the form
								var parentDiv = $('newsletter_unsubscribe_form').ancestors()[0];
								parentDiv.childElements().each(function(child){
									if (child.tagName == "FORM"){
										child.remove();
									}
								});
								
								//Display the success message
								var div = new Element('div').update(jsonResponse.message);
								div.addClassName("message");
								div.setStyle({
									textAlign: "center",
									padding: "40px 0px 25px"
								});
								
								parentDiv.insert(div);
							}
						}
					}
				);
			}
		}		
		
		
		//Make sure the submit button actually submits
		$("unsubscribe_submit_button").observe("click", function(event){ 
			submitUnsubscribeForm();
			return false;
		});
		
		//Observe if the subscribe form is being submitted
		$("newsletter_unsubscribe_form").observe("submit", function(event){ 
			//Submit the form
			submitUnsubscribeForm();
			
			//Make sure the form isn't submitted
			Event.stop(event);
			return false;
		});
	}
	
	if (location.inArray('support') && location.inArray('faq')){
		//Make sure the submit button actually submits
		$("faq_search_button").observe("click", function(event){ 
			Event.stop(event);
			window.location = ajaxUrl +'support/faq/keywords/' +urlencode($('keywords').value);
			return false;
		});
		
		//Observe if the search form is being submitted
		$("faq_search_form").observe("submit", function(event){ 
			Event.stop(event);
			window.location = ajaxUrl +'support/faq/keywords/' +urlencode($('keywords').value);
			return false;
		});
	}
});
