﻿var pageTracker; // declare it here so this script knows about it before google redeclares it.

var trackHash = (function() {

	var last = null;

	return function(action) {
		var loc = window.location;
		var hash = loc.hash || '#';
		var prefix = 'track.cfm?mcaction='+action+'&mcrecipe=';
		var report;
		if (hash !== last && pageTracker && typeof pageTracker._trackPageview == 'function') {
			last = hash;
			report = loc.pathname + loc.search + hash.replace('#', prefix);
			
			// for debugging:
			//alert(report);
			
			// for google analytics:
			pageTracker._trackPageview(report);
			
			// for access logs:
			new Request({url:report}).send().onSuccess = function(text) {
				// for debugging:
				//alert(report+"\n"+text);
			}; 
		}
	}
	
})();

function couponHover(img) {
	var src;
	function over() {
		img.src = 'images/locator-coupon-hover.gif';
	}
	function out() {
		img.src = src;
	}
	src = img.src;
	img.onmouseover = over;
	img.onmouseout = out;
	over();
}

// MooTools doesn't seem to have a getElementsByClassName equivalent
// for searching inside a given element, unless that element has an ID.
function gebcn(parent, className) {
	var classNames, divs, i, j;
	divs = parent.getElementsByTagName('div');
	for (i = 0; i < divs.length; i++) {
		classNames = divs[i].className.split(/\s+/);
		for (j = 0; j < classNames.length; j++) {
			if (className == classNames[j]) {
				return divs[i];
			}
		}
	}
}

function setUpHashPoll(microwave) {

	var lastHash;

	function useHash() {
		microwave.showById(lastHash);
	}
	function pollHash() {
		if (!microwave.isDown) {
			if (window.location.hash != lastHash) {
				lastHash = window.location.hash;
				useHash();
				trackHash('scroll');
			}
		}
	}
	pollHash();
	setInterval(pollHash, 100);
}

function Unhasher(prefix) {
	var pattern = new RegExp('^'+prefix);
	function unhash(ids) {
		var i, e;
		for (i = 0; i < ids.length; i++) {
			if ((e = document.getElementById(ids[i]))) {
				e.id = prefix + e.id;
			}
		}
	}
	function rehash(unhashed) {
		return unhashed.replace(pattern, '');
	}
	this.unhash = unhash;
	this.rehash = rehash;
}

function setUpFloaters(microwave) {

	function update(floater, open) {
		floater.style.display = open ? 'block' : 'none';
	}
	
	function Pair(link, id) {
		var anchors,
			anchor,
			floater,
			i,
			timeout,
			xbox;
		
		function schedule(fn) {
			if (timeout) {
				clearTimeout(timeout);
			}
			timeout = setTimeout(fn, 0);
		}
		function show() {
			hideAll();
			schedule(function() {
				showing = true;
				link.onclick = hide;
				link.onmouseover = show;
				update(floater, true);
			});
			return false;
		}
		function hide() {
			showing = false;
			schedule(function() {
				link.onclick = show;
				link.onmouseover = null;
				update(floater, false);
			});
			return false;
		}
		function click() {
			var id,
				hash = this.href.indexOf('#');
			if (hash >= 0) {
				id = this.href.substring(hash);
				microwave.showById(id);
				trackHash('click');
			}
			hide();
		}

		floater = $(id);
		floater.onmousedown = function() {
			suppress = true;
		};
		anchors = floater.getElementsByTagName('a');

		// close the floater if a link is clicked inside it
		for (i = 0; i < anchors.length; i++) {
			anchor = anchors[i];
			anchor.onclick = click;
		}
		
		link.onclick = show;
		this.hide = hide;
		
		xbox = gebcn(floater, 'floater-x');
		xbox.onmouseover = function() {
			this.className = 'floater-x-hover'; 
		};
		xbox.onmouseout = function() {
			this.className = 'floater-x'; 
		};
		xbox.onclick = function() {
			this.className = 'floater-x'; 
			hide();
		};

	}
	
	function hideAll() {
		for (var i = 0; i < pairs.length; i++) {
			pairs[i].hide();
		}
	}
	
	function bodyHideAll() {
		if (showing) {
			if (suppress) {
				suppress = false;
			} else {
				hideAll();
			}
		}
	}
	
	function setUp() {
		var panel = $('microwave-panel-buttons'),
			anchors = panel.getElementsByTagName('a'),
			anchor,
			i,
			hash,
			id;
		
		pairs = [];
		
		// set up rollover states
		for (i = 0; i < anchors.length; i++) {
			anchor = anchors[i];
			hash = anchor.href.indexOf('#');
			if (hash >= 0) {
				id = anchor.href.substring(hash+1);
				pairs.push(new Pair(anchor, id));
			}
		}
		
		$(document.body).addEvent('mousedown', bodyHideAll);
	}

	var pairs,
		showing = false, // a floater is shown
		suppress = false; // suppress clicks to body when the click originated on the floater
	
	setUp();
	
}

function setUpLocators() {
	var floaterBottles,
		recipes,
		sliderBottles,
		locator,
		bodyDown = false,
		i, j;
		
	function bind(trigger, locator) {
		var timeout,
			delay = 250;
		
		function clear() {
			if (timeout) {
				clearTimeout(timeout);
				timeout = null;
			}
		}
		function hide() {
			clear();
			timeout = setTimeout(function(){
				locator.style.display = 'none';
			}, delay);
		}
		function show() {
			if (!bodyDown) {
				clear();
				locator.style.display = 'block';
			}
//			alert('show');
		}
		trigger.onmouseover = show;
		locator.onmouseover = show;
		trigger.onmouseout = hide;
		locator.onmouseout = hide;
	}
	
	function recipeTrigger() {
		var div = document.createElement('div');
		div.className = 'locator-trigger-container';
		div.innerHTML = '<div class="locator-trigger"><a href="/specialoffers/">Coupon</a> | <a href="/product_locator/">Locator</a></div>';
		return div;
	}
	
	$(document.body).addEvent('mousedown', function() {
		bodyDown = true;
	}).addEvent('mouseup', function() {
		bodyDown = false;
	});
	
	recipes = $$('.recipe');
	for (i = 0; i < recipes.length; i++) {
//		recipes[i].insertBefore(recipeTrigger(), recipes[i].firstChild);
		recipes[i].appendChild(recipeTrigger());
		// it has to go after the recipe text, or else in IE, 
		// the reg marks show through, even with z-index.
	}
	
	floaterBottles = $$('.floater-sauce-bottle');
	for (i = 0; i < floaterBottles.length; i++) {
		locator = gebcn(floaterBottles[i], 'floater-sauce-locator');
		bind(floaterBottles[i], locator);
		sliderBottles = $$('.'+locator.id.replace(/locator/,'recipe')+' .locator-trigger');
		for (j = 0; j < sliderBottles.length; j++) {
			locator = locator.cloneNode(true);
			sliderBottles[j].appendChild(locator);
			bind(sliderBottles[j], locator);
		}
	}

}

function Microwave(unhasher) {
	var cel,
		delay = 0,
		isDown = false,
		fluidity = 100,
		index = 0,
		dragging = false,
		recipes,
		indexIds,
		recipeWidth,
		slider;

	function indexToStep(index) {
		return index * fluidity;
	}
	function stepToIndex(step) {
		return Math.round(step / fluidity);
	}
	function snap() {
		var step = fluidity * stepToIndex(slider.step);
		slider.set(step);
		slider.knob.setStyle(slider.property, slider.toPosition(step));
	}
	function update(value) {
		var left = -value * recipeWidth / fluidity;
		cel.setStyle('left', left+'px');
	}
	function up() {
		isDown = false;
		if (dragging) {
			release();
		}
	}
	function drag() {
		dragging = true;
	}
	function release() {
		dragging = false;
		snap();
	}
	function down() {
		isDown = true;
	}
	function move() {
		if (isDown) {
			drag();
		}
	}
	function show(i) {
		index = i;
		slider.set(indexToStep(i));
	}
	function showById(id) {
		if (id && (id.charAt(0) === '#')) {
			id = id.substring(1);
			if (indexIds[id] || indexIds[id]===0) {
				show(indexIds[id]);
				return true;
			}
		}
		return false;
	}
	function next() {
		if (index < recipes.length - 1) {
			show(index + 1);
		}
	}
	function previous() {
		if (index > 0) {
			show(index - 1);
		}
	}
	
	function change(value) {
		if (!isDown || dragging) {
			index = stepToIndex(this.step);
			update(value);
		}
	}
	function tick(pos) {
		if (!isDown) {
			this.knob.setStyle(this.property, this.toPosition(this.step));
		}
	}
	function complete(value) {
		if (!isDown) {
			snap();
			index = stepToIndex(this.step);
			window.location.href = '#' + unhasher.rehash(recipes[index].id);
		}
	}
	
	function unhashIds() {
		var ids = [];
		for (var i = 0; i < recipes.length; i++) {
			ids[i] = recipes[i].id;
		}
		return ids;
	}
	
	function setUp() {
		var bar,
			i,
			knob,
			pane,
			recipeStyles;
		
		pane = $('pane');
		recipes = pane.getElements('.recipe');
		
		indexIds = {};
		for (i = 0; i < recipes.length; i++) {
			recipe = recipes[i];
			indexIds[recipe.id] = i;
		}
		
		recipeStyles = recipes[0].getStyles('width','paddingLeft','paddingRight');
		recipeWidth = parseInt(recipeStyles.width, 10) + parseInt(recipeStyles.paddingLeft, 10) + parseInt(recipeStyles.paddingRight, 10);
	
		cel = $('cel');
		cel.setStyle('width', (recipeWidth * recipes.length)+'px');
		cel.setStyle('display', 'block');
	
		bar = $('bar');
		knob = $('knob');
	
		slider = new Slider(bar, knob, {
			steps: (recipes.length - 1) * fluidity,
			onChange: change,
			onTick: tick,
			onComplete: complete
		});
		
		knob.addEvent('mousedown', down);
		knob.addEvent('mousemove', move);
		window.addEvent('mouseup', up);
		document.addEvent('mouseup', up);
		document.addEvent('keypress', function(k) {
			switch (k.key) {
				case 'left': previous(); break;
				case 'right': next(); break;
			}
		});
	}

	this.isDown = isDown;
	this.show = show;
	this.showById = showById;
	this.next = next;
	this.previous = previous;
	this.unhashIds = unhashIds;
	
	setUp();
}

/* 
var box = new EchoBox('box');
var microwave, unhasher;
unhasher = new Unhasher('nohash-');
microwave = new Microwave(unhasher);
unhasher.unhash(microwave.unhashIds());
setUpFloaters(microwave);
setUpHashPoll(microwave);

window.addEvent('domready', function(){
});
*/