/**
 * common.js - all the js that is used in the site
 * keep the functions and classes in alphabetical order
 */

function pageInit() { 
	setupNav();
	setupPageMenu();
}

function setupFooter() {
	$('page_footer_wrapper').setStyle('height', 'auto');
	var scroll = window.getScrollSize().y;
	var footer = $('page_footer_wrapper').getSize().y;
	var content = $('page_wrapper').getSize().y + 26;
	
	if (scroll > content+footer) {
		var diff = scroll - content;
		$('page_footer_wrapper').setStyle('height', diff);
	}
	
}


function setupNav() {
	if ($('nav_products')) {
		$('nav_products').addEvents({
			'mouseenter': function() {
				this.getFirst('ul').removeClass('display_none');
			},
			'mouseleave': function() { 
				this.getFirst('ul').addClass('display_none');
			}
		});
		
		$$('#nav_products .has_subcategory').each(function(el) {
			el.addEvents({
				'mouseenter': function() {
					this.getFirst('ul').setStyle('left', this.getSize().x - 1);
					this.getFirst('ul').removeClass('display_none');
				},
				'mouseleave': function() { 
					this.getFirst('ul').addClass('display_none');
				}
			});
		});
	}
}

function setupPageMenu() {
	$$('#page_categories .selected').each(function(el) {
		el.getParent().removeClass('display_none');
	});
}

/** 
 * slideShow
 ***********
 */
var slideShow = new Class({
    initialize: function() {
       	this.slideDelay = 7500;
       	this.num_of_slides = 0;
       	this.zIndex = 1;
       	this.slides = Array();
       	this.init();
    },
	
	init: function() {
		$$('#slideshow .slide').each(function(el) {
			el.setStyles({
				'opacity': 0,
				'visibility': 'visible'
			});
			
			this.num_of_slides++;
			this.slides[this.num_of_slides] = el.id;
		}.bind(this));
		
		this.start();
	},
	
	start: function() {
		this.showSlide(1);
		if (this.num_of_slides > 1) {
			for (var i = 1; i < this.num_of_slides; i++) {
				(function(i){ 
					this.showSlide(i+1)
				}).delay(i * this.slideDelay, this, i);
			}
		}
	},
	
	showSlide: function(slide_num) {
		$(this.slides[slide_num]).setStyle('zIndex', this.zIndex++);
		$(this.slides[slide_num]).fade('in');
			
		if (this.num_of_slides > 1) {
			if ($(this.slides[slide_num-1])) {
				$(this.slides[slide_num-1]).fade('out');
			} else {
				$(this.slides[this.num_of_slides]).fade('out');
			}
		
			if (slide_num == this.num_of_slides) {
				(function() {
					this.start();
				}).delay(this.slideDelay, this);
			}
		}
	}

});

function toggleShippingForm() {
	$('shipping_form').toggleClass('display_none');
}

/**
 * AjaxForm
 * handles the form submit
 * this function allows a page to setup a form to submit via ajax and
 * to obtain a json response. 
 * Note: This function expects a common naming convention and relys on the function showSystemMessage()
 */
var AjaxForm = new Class({
	Implements: Options,
    options: {
    	'is_modal': false,
        'stop_enter_key' : false,
        'success_function' : '',
        'success_location' : '',
        'target_window' : '',
        'track_form_changes' : false
    },
    
    initialize: function(form, options) {
        this.setOptions(options);
        this.form = form;
        this.btn = $(this.form.id.replace('form', 'btn'));
        this.cancel_btn = this.form.id.replace('form', 'cancel_btn');
       	this.default_success_location = this.options.success_location;
       	this.bindEvents();
       	if (this.options.track_form_changes == true) {
       		this.trackFormChanges();
       	}
       	// this is set for proper error handling of ajax requests
       	if (!$('is_ajax')) {
			new Element('input', {
				'type': 'hidden',
				'id': 'is_ajax',
				'name': 'is_ajax',
				'value': 'true'
			}).inject(this.form);
		} 
		
		// set the action that will be used when the form is sent
		this.form.set('send', {
			onComplete: function(response) { 
				response = JSON.decode(response);
				if (response.success == true) {
					this.setFormHasChanges(false);
					removeSystemMessage();
					
					this.btn.disabled = false;						
											
					/*
					$('throbber').set('src', '/images/app/checkmark.gif');
					(function() {
						throbber.fade('out');
					}).delay(3000);
					*/
					$('throbber').fade('out');
					this.onSuccess(response);
				} else {
					if (response.error_message == 'login_required') {
						window.location = bounce_url+'?landing_location='+window.location+'&bounce=true';
					} else {
						this.resetSuccessLocation();
						showSystemMessage(response.error_message, this.form, 'error');
						
						if (response.errors) {
							for(var i=0; i<response.errors.length; i++) {
								if ($(response.errors[i])) {
									$(response.errors[i]).addClass('form_field_error');
								}
							}
						}
						
						// insure the hidden cancel buttons are visible
						$$('.' + this.cancel_btn).each(function(el) {
							el.removeClass('display_none');
						});
						
						$('throbber').dispose();
						this.btn.disabled = false;
					}
				}
				this.btn.disabled = false;
			}.bind(this)
		});
		
    },
    
    bindEvents: function() {  	
		this.form.addEvent('keydown', function(e) {
			this.onKeydown(e);
		}.bind(this));
		this.form.addEvent('submit', function(e) {
			this.onSubmit(e);
		}.bind(this));
		
		if (this.btn) {
			this.btn.addEvent('click', function(e) {
				if (e) {
					e.stop();
				}
				this.form.fireEvent('submit');
			}.bind(this));
		}
		
		
		$$('.' + this.cancel_btn).each(function(el) {
			el.addEvent('click', function(e) {
				if (e) {
					e.stop();
				}
				if (this.options.is_modal == true) {
					objModalWindow.hide();
				} else {
					this.resetSuccessLocation();
					this.onSuccess();
				}
			}.bind(this));
		}.bind(this));
    },
    
    onKeydown: function(e) {
    	if (this.options.stop_enter_key == true) {
			if (e.key == 'enter' && e.target.tagName != 'TEXTAREA') {
				if (e) {
					e.stop();
				}
			}
		} else {
			if (e.key == 'enter' && e.target.tagName != 'TEXTAREA') {
				if (e) {
					e.stop();
				}
				this.form.fireEvent('submit');
			}
		}
    },
    
    onSubmit: function(e) {
    	// stop the normal submit
		try {
			e.stop();
		} catch (exception) {}
		if (this.options.track_form_changes == false || this.form_has_changes == true) {
			// show the throbber
			if ($('throbber')) {
				$('throbber').dispose();
			}
			new Element('img', {
				src: '/images/throbber.gif',
				id: 'throbber'
			}).inject(this.btn,'after');
			
			this.btn.disabled = true;
			
			// clear any existing errors
			$$('.form_field_error').each(function(item) {
				item.removeClass('form_field_error');
			});
			
			this.form.send();
		} else {
			this.onSuccess();
		}
    },
    
    onSuccess: function(response) {
    	if (this.options.success_function != '') {
    		window[this.options.success_function](response);
    	} else if (this.options.success_location != '') {
    		if (this.options.target_window == '') {
    			window.location = this.options.success_location;
    		} else {
				var pdf_window = window.open(this.options.success_location, this.options.target_window);
				if (pdf_window == null || typeof(pdf_window) == "undefined") {
					alert('A popup blocker has prevented the system from printing. To print allow popups for this site.');
				}
				this.setTargetWindow('');
				this.resetSuccessLocation();
			}
    	}
    },
    
    resetSuccessLocation: function() {
    	if (this.default_success_location != '') {
    		this.setSuccessFunction('');
    		this.setSuccessLocation(this.default_success_location);
    	}
    },
    
    setFormHasChanges: function(form_has_changes) { 
    	if (typeof readonly !== 'undefined' && readonly == false) { 
			this.form_has_changes = form_has_changes;
		}
    },
    
    setSuccessFunction: function(success_function) { 
    	this.options.success_function = success_function;
    },

    setSuccessLocation: function(success_location) { 
    	this.options.success_location = success_location;
    },

	setTargetWindow: function(target_window) {
		this.options.target_window = target_window;
	},

	trackFormChanges: function(e) { 
    	this.setFormHasChanges(false);
    	this.form.addEvents({
    		'keyup': function(e) {
				this.setFormHasChanges(true);
			}.bind(this),
			'mouseup': function(e) {
				if (e.rightClick) {
					this.setFormHasChanges(true);
				}
			}.bind(this),
			'change': function(e) {
				this.setFormHasChanges(true);
			}.bind(this),
    	});
    	
    	// special case for the date picker
    	$$('.calendar').each(function(el) {
    		el.addEvent('click', function(e) {
    			this.setFormHasChanges(true);
    		}.bind(this));
    	}.bind(this));
    },
});

/**
 * show system message
 * will inject a div into the identified section of the page using containing 
 * the error text passed.
 * message_type = (error, success, notice)
 */
function showSystemMessage(message_text, section, message_type) {
	removeSystemMessage();
	
	var system_message = new Element('div', {
		'id' : 'system_message',
		'class' : message_type
	});
	system_message.set('html', message_text);
	system_message.inject(section, 'top');
	window.scrollTo(0, $(section).getPosition().y - 100);
}

/*
 * remove system message
 */
function removeSystemMessage() {
	if ($('system_message')) {
		$('system_message').destroy();
	}
}
