/*
 * Put all Cufon.replace() here...
 * 
 */
function replaceFonts() {
	Cufon.replace('.nav-container a', {
		hover: true
	});
	Cufon.replace('.page .category-description');
	Cufon.replace('.page-title h1');
	Cufon.replace('.col5-set .col h2');
	Cufon.replace('.categoryparent-flavors h2');
	Cufon.replace('.block-title strong');
	Cufon.replace('.block .block-subtitle');
	Cufon.replace('.ingredients strong');
	Cufon.replace('.footer .block-subscribe label');
	Cufon.replace('.footer h2');
	Cufon.replace('.footer .store-name');
	Cufon.replace('.contact-form h2');
	Cufon.replace('.category-about-us h1');
	Cufon.replace('.profiles h1');
	Cufon.replace('.store-locator h2');
	Cufon.replace('.welcome');
	Cufon.replace('.widget-title');
	Cufon.replace('.wp-page-title');
	Cufon.replace('.bottom-container h2');
	Cufon.replace('.cms-index-index .home-text h1');
}
replaceFonts();

// Adjust padding ++ page-title. Had to use timer on document load is too slow...
new PeriodicalExecuter(function (pe) {
	function mainContainerPadding() {
		if ($$('.main-container').length == 0) return false;
		var mainContainer = $$('.main-container')[0];
		
		if ($$('.page-title').length == 0) return false;
		var pageTitle = $$('.page-title')[0];

		var diff = pageTitle.getDimensions().height - parseInt(mainContainer.getStyle('paddingTop'));
		if (Math.abs(diff) - 5 > 0) {
			mainContainer.setStyle({ paddingTop: pageTitle.getDimensions().height + 'px' });
		}
		return true;
	}

	if (!mainContainerPadding()) {
		if (document.loaded) {
			mainContainerPadding();
			pe.stop();
		}
	} else {
		pe.stop();
	}
},0.1);


//Adjust padding ++ footer. Had to use timer on document load is too slow...
function pagePadding() {
	if ($$('.page').length == 0) return false;
	var page = $$('.page')[0];
	
	if ($$('.footer-container').length == 0) return false;
	var footerContainer = $$('.footer-container')[0];

	var diff = footerContainer.getDimensions().height - parseInt(page.getStyle('paddingBottom'));
	if (Math.abs(diff) - 15 > 0) {
		page.setStyle({ paddingBottom: footerContainer.getDimensions().height + 'px' });
	}
	return true;
}

new PeriodicalExecuter(function (pe) {
	if (!pagePadding()) {
		if (document.loaded) {
			pagePadding();
			pe.stop();
		}
	} else {
		pe.stop();
	}
},0.1);


var InlineForm = Class.create({
	initialize : function(formId) {
		this.form = $(formId);
		if (this.form == null) {
			return;
		}
		this.textareas = $$('#' + this.form.identify() + ' textarea');
		this.selects = $$('#' + this.form.identify() + ' select');
		this.fileuploads = $$('#' + this.form.identify() + ' input[type="file"]')
		
		if (this.textareas.length > 0) {
			this.setTextAreas();
		}
		
		if (this.selects.length > 0) {
			this.setSelects();
		}
	},
	
	/* Textarea start --- */
	setTextAreas : function () {
		this.textareas.each(function(item) {
			this.cols = parseInt(item.readAttribute('cols'));
			var rows = parseInt(item.readAttribute('rows'));
			this.lineHeight = parseInt(this.textareas[0].getStyle('line-height'));
			item.setStyle({height: this.lineHeight*rows + 'px'});
			this.checkRows(item);
			item.observe('keypress',this.keyPressed.bind(this));
			item.observe('keyup',this.keyPressed.bind(this));
		}.bind(this));
	},
	
	keyPressed : function (event) {
		var key = event.which || event.keyCode;
		
		if (key == Event.KEY_BACKSPACE) {
			return;
		}
		this.checkRows(event.element());
	},
	
	checkRows : function(item) {
		var value = Form.Element.getValue(item);
		if (value.length > 0) {
			var rows = parseInt(item.readAttribute('rows'));
			if (rows == null) {
				return;
			}
			var i = this.getLinesCount(value);
			
			if (i >= rows) {
				item.writeAttribute('rows', i+1);
				item.setStyle({height: this.lineHeight*(i+1) + 'px'});
				
			}
		}
	},
	
	getLinesCount : function(text) {
		var returnCount = text.split("\n").length;
		var i = 0;
		text.split("\n").each(function(line) {
			i+=(line.length / this.cols).floor() + 1;
		}.bind(this));
		
		return (returnCount < i) ? i : returnCount;
	},
	/* Textarea End ==== */
	
	/* Selects Start ---- */
	setSelects : function() {
		this.selects.each(function(item) {
			var fakeSelect = new Element('span');
			item.insert({ before: fakeSelect });
			fakeSelect.setStyle({width: item.getStyle('width')});
			fakeSelect.setStyle({height: item.getStyle('height')});
		    fakeSelect.addClassName('fake-select');
		    item.observe('focus', this.toggleActive);
		    item.observe('blur', this.toggleActive);
		    item.observe('change',this.selectChange);
		}.bind(this));
	},
	
	toggleActive : function (event) {
		var span = event.element().adjacent('span.fake-select')[0];
		if (span.hasClassName('active')) {
			span.removeClassName('active');
		} else {
			span.addClassName('active');
		}
	},
	
	selectChange : function (event) {
		var option = event.element().childElements().find(function(option){
			return option.selected == true;
		});
		var span = event.element().adjacent('span.fake-select')[0];
		if (option != null && span != null) {
			span.innerHTML = option.innerHTML;
		}
	}
	/* Selects End ===== */
	
});

/*
 * 
 * Navigation helper
 * 
 */
var NavHelper = Class.create({
	initialize : function(navArray){
		if (navArray.size() > 0) {
			this.container = $(navArray[0]);
			this.mainNav = $(this.container.down('#nav'));
			this.storeNav = $(this.container.down('.store-links'));
			
			if (this.mainNav != null) {
				this.absoluteSpans(this.mainNav);
			}
			
			if (this.mainNav == null && this.storeNav != null) {
				this.absoluteSpans(this.storeNav);
			}
			
			if (this.mainNav != null && this.storeNav != null) {
				if (this.mainNav.down().next('li.last').hasClassName('active') || this.mainNav.select('li.active').length == 0) {
					this.storeNav.show();
					
					// On Cufon ready: Absolutize spans and set fixed width per anchor
					new PeriodicalExecuter(function (pe) {
						if ($$('.cufon-ready').length > 0) {
							this.absoluteSpans(this.storeNav);
							pe.stop();
						}
					}.bind(this),0.1);
				}
			}
		}
	},
	
	absoluteSpans : function(container) {
		container.select('li a').each(function(item) {
			this.absoluteSpan(item);
		}.bind(this));
	},
	
	absoluteSpan : function(elem) {
		var anchor = $(elem);
		var span = $(anchor.down());
		if (anchor != null && span != null) {
			anchor.clonePosition(span,{setTop:false, setLeft:false});
			span.setStyle({width:'130%',marginLeft:'-15%'});
		}
	}
});


/*
 *  Ajax chunks request
 *  
 */
function getChunks(url,elem,type) {
	var elem = $(elem);
	if (url == '' || elem == null || type == null) return;
	new Ajax.Request(url,
	  {
		parameters: {sender: 'magento', type: type},
	    onComplete: function(transport){
	      var response = transport.responseText || "Not available";
	      elem.update(response);
	      pagePadding();
	    }
	  });
}


/*
 *	Homepage Bottles
 */
var BottlesZoom = Class.create({
	initialize : function(bottles){
		// queues
		this.inQueue = 'inQueue';
		this.clicked = false;
		
		// init container
		this.container = $(bottles);
		if (this.container == null) return;
		
		// init list-items
		this.wrappers = this.container.select('li');
		if (this.wrappers.length == 0) return;
		
		// init anchors (ul li a)
		this.anchors = this.container.select('li a');
		if (this.anchors.length == 0) return;
		
		this.initWrappers();
		this.initAnchors();
	},
	
	initWrappers : function(){
		this.wrappers.each(function(item){
			item.setStyle({position: 'relative'});
			item.clonePosition(item.down(), {setLeft: false, setTop: false});
		});
	},
	
	initAnchors : function() {
		this.anchors.each(function(item) {
			item.absolutize();
			
			item.observe('mouseover',this.onMouseOver.bind(this));
			item.observe('mouseout',this.onMouseOut.bind(this));
			item.observe('click',this.onClick.bind(this));
		}.bind(this));
	},
	
	onMouseOver : function(event) {
		if (this.clicked) return;
			
		el = $(event.element().up());
		if (!el.hasClassName('active')) {
			Effect.Queues.get(this.inQueue).invoke('cancel');
			var a = new Effect.Morph(el, { 
				style: {
				    width: '200px',
				    height: '528px',
				    top: '-90px',
					left: '-50px'
				},
				queue: { position: 'end', scope: this.inQueue},
				delay: 0.2,
				duration: 0.6,
				afterSetup: this.toggleElement.bind(this,el,true)
			});
		}
	},
	
	onMouseOut : function(event) {
		if (this.clicked) return;
		
		el = $(event.element().up());
		Effect.Queues.get(this.inQueue).each(function(effect) {
			if (effect.element == el) {
				// if zoom in didn't even started cancel it, otherwise cancel+zoom out
				effect.cancel();
				if (effect.currentFrame == 0) {
					return;
				}
			}
		});
		this.resetBottle(el);
	},
	
	onClick : function(event) {
		event.stop();
		if (this.clicked) return;
		
		this.clicked = true;
		el = $(event.element().up());
		
		// queue. Let it zoom...
		var queue = Effect.Queues.get(this.inQueue);
		if (queue.size() > 0) {
			Effect.Queues.get(this.inQueue).each(function(effect) {
				// may...
				if (effect.element == el) {
					effect.options.afterFinish = this.prestige.bind(this,el);
				}
			}.bind(this));
		} else {
			this.prestige(el);
		}
		
		this.redirect.delay(0.2, el.readAttribute('href'));
	},
	
	prestige : function(element) {
		new Effect.Move(element, { y: -40, transition: Effect.Transitions.spring });
	},
	
	redirect : function(url) {
		setLocation(String(url));
	},
	 
	resetBottle : function(el) {
		new Effect.Morph(el, { 
			style: {
			    width: '100px',
			    height: '264px',
			    top: '0px',
				left: '0px'
			},
			duration: 0.2,
			afterFinish: this.toggleElement.bind(this,el,false)
		});
	},
	
	toggleElement : function (el, activate) {
		var index = 100;
		if (activate) {
			if (!el.hasClassName('active')) {
				el.addClassName('active');
			}
			index = 102;
		} else {
			if (el.hasClassName('active')) {
				el.removeClassName('active');
			}
		}
		el.setStyle({zIndex: index});
		el.up().setStyle({zIndex: index});
	}
	
});

/* start */
document.observe("dom:loaded", function() {
    new BottlesZoom('bottles-zoom');
});


var Referral = Class.create();
Referral.prototype = {
    initialize: function(form){
        this.form = form;
        if ($(this.form)) {
        	$(this.form).select('.fieldset').each(function(item){
        		var padding = parseInt($(item).getStyle('paddingBottom')) + parseInt($(item).getStyle('paddingTop'));
        		$(item).makeClipping().setStyle({
            		height: ($(item).getHeight() - padding) + 'px'
            	});
        	});
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }
        this.saveUrl = $(this.form).readAttribute('action');
        this.onSave = this.success.bindAsEventListener(this);
        this.onError = this.error.bindAsEventListener(this);
    },
    
    setLoadWaiting: function(){
		Element.hide('referral-button');
		Element.show('please-wait');
    },

    save: function(){
        var validator = new Validation(this.form);
        if (validator.validate()) {
            this.setLoadWaiting();

            var request = new Ajax.Request(
                this.saveUrl,
                {
                    method: 'post',
                    onSuccess: this.onSave,
                    onFailure: this.onError,
                    parameters: Form.serialize(this.form)
                }
            );
        }
    },
    
    showFeedback: function(text){
    	Element.hide('please-wait'),
    	$$('ul.form-list')[0].hide();
    	$$('h2.legend')[0].update(text);
    	
    },

    success: function(transport){
    	this.showFeedback(transport.responseText);
    },
    
    error: function(transport){
    	this.showFeedback('Unable to process your request. Please try again later.');
    }
}
