
var panelStatus = 'hidden';

var JSONURI = 'http://www.boarshead.com/digicatessen.php?mode=AJAX';
var panelData = {};
var currentIndeces = [];
var currentCategory = null;
var fadeIn, fadeOut;

function parseQuery(str) {
	var args = str.replace(/\+/g, ' ').split('&');
	var params = {};
	for (i = 0; i < args.length; i++) {
		arg = args[i].split('=');
		params[arg[0]] = decodeURIComponent(arg[1]);
	}
	return(params);
}

function updateProductShot(prod, oldidx, idx) {
	// ie6 doesn't get the fade in/out effect. don't know where the breakage is, so just skip that pile of junk
	$('prodshot').getElements('img').each(function(el) {
		if (!el.fx) {
			el.fx = new Fx.Morph(el, { link: 'ignore', duration: 750, onComplete: function() { var x = el.getParent(); if (x) { x.destroy(); } } } );
			if (Browser.Engine.trident4) {
				el.fx.start({ 'left': [0, (oldidx > idx) ? -300 : 300] });
			} else {
				el.fx.start({ 'opacity': [1, 0], 'left': [0, (oldidx < idx) ? -300 : 300] });
			}
		}
	});

	newimg = new Element('div', {
		'class': 'shot',
		'html': '<img src="/images/products/' + prod.code + '.jpg" width="285" height="200" alt="' +  prod.name + ' ' + prod.code + '" />'
	});

	var slideIn = new Fx.Morph(newimg.getElement('img'), { duration: 750 });
	var startX, endX;
	if (oldidx > idx) {
		startX = -300; // prev, slide in from the left
		endX = 0;
	} else if (oldidx < idx) {
		startX = 300; // next, slide in from the right
		endX = 0;
	} else {
		startX = 0;
		endX = 0;
	}
		
	newimg.getElement('img').setStyle('left', startX);
	if (Browser.Engine.trident4) {
		slideIn.start({ 'left': [startX, endX] });
	} else {
		slideIn.start({ 'opacity': [0, 1], 'left': [startX, endX] });
	}

	$('prodshot').adopt(newimg);
}

var productFlags = {};
productFlags['fein'] = {'src': 'fein.gif', 'alt': 'Feingold Association', 'href': 'feingold.php'};
productFlags['aha'] = { 'src': 'aha.gif', 'alt': 'American Heart Association', 'href': 'aha.php' };
productFlags['gluten'] = { 'src': 'gluten.gif', 'alt': 'Gluten Free', 'href': 'gluten_free.php'};
productFlags['dairy'] = { 'src': 'dairy.gif', 'alt': 'Dairy Free' };
productFlags['lowsod'] = { 'src': 'lowsod.gif', 'alt': 'Low Sodium' };
productFlags['lowersod'] = { 'src': 'lowersod.gif', 'alt': 'Lower Sodium' };

function updateProductFlags(prod) {
	var pf = $('prodflags');
	pf.empty();
	var html = new String;
	for (i = 0; i < prod.flags.length; i++) {
		html = '<img src="/images/prodflags/' + prod.flags[i] + '.jpg" width="306" height="43" alt="' + productFlags[prod.flags[i]].alt + '" />';
		if (productFlags[prod.flags[i]].href) {
			html = '<a href="' + productFlags[prod.flags[i]].href + '" target="_new">' + html + '</a>';
		} 
		var d = new Element('div', {
			'class': 'prodflag',
			'html': html
		});
		pf.grab(d, 'bottom');
	}
}
function updateProductNav(cID, idx, direction) {
	var newidx = (direction == 'next') ? idx + 1 : idx - 1;
	var id = 'prod' + direction;
	var nav = $(id);
	nav.blur();
	var span = nav.removeEvents().getElement('span');
	span.removeEvents();
	if (panelData[cID]['products'][newidx]) { 
		nav.setStyle('visibility', 'visible');
		span.addEvent('click', function() { updatePanel(cID, newidx); });
		// preload next product shot
		var x = new Image();
		x.src = '/images/products/' + panelData[cID]['products'][newidx].code + '.jpg'; // Pre-load next product shot
		if (panelData[cID]['products'][newidx]['nutritionpanel']) {
			var y = new Image();
			y.src = '/images/nutrition_panels/' + panelData[cID]['products'][newidx].code + '.gif'; // Pre-load next nut panel, if there is one
		}
	} else {
		nav.setStyle('visibility', 'hidden');
		nav.addEvent('click', function() { return(false); });
	}
	$('prodnavpos').set('html', (idx + 1) + ' of ' + panelData[cID]['prodcount']);
}
function updateProductNutritionPanel(cID, idx, prod) {
	if (panelData[cID]['products'][idx]['nutritionpanel']) {
		$('nutpanel').setProperty('html', '<img src="/images/nutrition_panels/' + panelData[cID]['products'][idx]['code'] + '.gif" />').setStyle('display', 'block');
		$('prodnut').setStyle('display', 'block');
	} else {
		$('prodnut').setStyle('display', 'none');
		$('nutpanel').setProperty('html', null);
	}
}

function updateGoesWellWith(cID, idx) {
	if (panelData[cID]['products'][idx].goeswell) {
		var p = panelData[cID]['products'][idx]['goeswell'];
		$('goeswellwithtext').set('html', '<img src="/images/products/' + p.code + '-thm.jpg" width="71" height="50" style="float: left; padding-right: 10px;" alt="' + p.name + '" /> ' + p.name);
		$('goeswellwith').setStyle('display', 'block');
	} else {
		$('goeswellwithtext').set('html', null);
		$('goeswellwith').setStyle('display', 'none');
	}
}

function updateProductExtraImage(cID, idx) {
	var p = panelData[cID]['products'][idx];
	var eb = $('extrablurb'), el;

	eb.empty();
	if (p.extradigifile) {
		if (p.extradigithumbnail) {
			el = '<img src="/images/products/extra-' + p.code + '-small.jpg" alt="' + p.qname + '" />'
		} else {
			el = p.extradigifilename;
		}

		if (p.extradigifileisimage) {
			el = new Element('a', {
				'href' : '/images/products/extra-' + p.code + '.jpg',
				'target': 'digiextrashot',
				'html': el }).inject(eb);
		} else {
			el = new Element('a', { 'href' : 'digicatessen.php?mode=download&productCode=' + p.code, 'html': el  }).inject(eb);
		}
		if (p.extrablurb && (p.extrablurb.length > 0)) {
			el = new Element('p', { 'text' : p.extrablurb }).inject(eb);
		}
		eb.setStyle('display', 'block');
	} else {
		eb.setStyle('display', 'none');
	}
		
}

function updatePanel(cID, idx) {
	prod = panelData[cID]['products'][idx];

	$('prodname').set('html', prod.name);
	
	// round trip through an element so entities get decoded
	document.title =  new Element('p', { 'html' : prod.name }).getProperty('html'); 

	var txt = '';
	if (prod.description) {
		txt = prod.description ;
	} else if (prod.servingsuggestions) {
		txt = prod.servingsuggestions;
	}
	if (txt != '') {
		$('prodblurb').set('html', txt).setStyle('display', 'block');
	} else {
		$('prodblurb').setStyle('display', 'none');
	}

	updateProductShot(prod, currentIndeces[cID], idx);
	updateProductFlags(prod);
	updateProductNav(cID, idx, 'next');
	updateProductNav(cID, idx, 'prev');
	updateProductNutritionPanel(cID, idx, prod);
	updateGoesWellWith(cID, idx);
	updateProductExtraImage(cID, idx);

	$('recipes').empty();
	if (panelData[cID]['recipes'][prod.code]) {
		$('recipes').empty();
		$('prodrecipes').setStyle('display', 'block');
		$each(panelData[cID]['recipes'][prod.code], function(recipe, idx) {
			var d = new Element('div', {
				'class': 'recipe'
			});
			var src = (recipe.hasimage == 1) ? recipe.id : 'recipe_placeholder';
			d.set('html', '<a href="recipe.php?recipeID=' + recipe.id + '" target="recipe"><span class="recipeimage"><img src="/images/recipe_pics/' + src + '-thm.jpg" width="60" height="45" alt="' + recipe.name + '" /></span> ' + recipe.name + '</a>');
			$('recipes').grab(d, 'bottom');
			if (($('recipes').getElements('div.recipe').length % 2) == 0) {
				var d2 = new Element('div', { 'class': 'clear' });
				$('recipes').grab(d2, 'bottom');
			}
		});
	} else {
		$('prodrecipes').setStyle('display', 'none');
	}
	currentIndeces[cID] = idx; // bookmark current position
}
function updateCategoryNav(cID) {
	var cat = '';
	$('typelist').getElements('li').each(function(el) {
		if (el.id.substr(3) == cID) {
			el.getElement('img').setProperty('src', '/images/digicatessen/cat_btn_on.gif');
			cat = el.get('text');
		} else {
			el.getElement('img').setProperty('src', '/images/digicatessen/cat_btn_off.gif');
		}
	});
	$('nowviewing').set('text', cat);
}

function setIndexByPCode(cID, pcode) {
	if (pcode) {
		$each(panelData[cID]['products'], function(x, idx) {
			if (x.code == pcode) {
				currentIndeces[cID] = idx;
			}
		});
	}
}

function switchCategory(cID, pcode) {
	if (cID == currentCategory) {
		return;
	}
	updateCategoryNav(cID);
	if (panelData[cID]) {
		currentCategory = cID;
		setIndexByPCode(cID, pcode);
		if (panelData[cID].blurb) {
			if (panelData[cID].blurbseen || pcode) {
				showProducts(cID, pcode);
			} else {
				showCategoryBlurb(cID);
			}
		} else {
			showProducts(cID, pcode);
		}
	} else {
		getCategoryInfo(cID, pcode);
	}
}

function showProducts(cID, pcode) {
	$('prodshot').empty();
	$('prodnav').setStyle('display', 'block');
	$('digidata').setStyle('display', 'block');
	$('categoryblurb').setStyle('display', 'none');
	idx = (currentIndeces[cID]) ? currentIndeces[cID] : 0;
	updatePanel(cID, idx);
	if (panelStatus != 'visible') {
		fadeIn.start({ 'visibility': 'visible', 'opacity': [0, 1] });
	}
}

function showCategoryBlurb(cID) {
	$('prodnav').setStyle('display', 'none');
	$('digidata').setStyle('display', 'none');
	gangshot = new Element('div', {
		'class': 'shot',
		'html': '<img src="/images/products/category-' + cID + '.jpg" width="285" height="200" alt="" />'
	});
	$('prodshot').empty().adopt(gangshot);
	$('categoryblurb').set('html', panelData[cID].blurb).setStyle('display', 'block');
	p = new Element('p', { 'html': '<button>View Products</button>' });
	p.setStyles({ 'margin' : '1em', 'margin-left': 'auto', 'margin-right': 'auto', 'text-align': 'center' });
	p.getElement('button').addEvent('click', function() { showProducts(cID); });
	$('categoryblurb').adopt(p);
	panelData[cID].blurbseen = true;
	if (panelStatus != 'visible') {
		fadeIn.start({ 'visibility': 'visible', 'opacity': [0, 1] });
	}
	updateCategoryNav(cID);
}

function getCategoryInfo(cID, pcode) {
	j = new Request.JSON({
		'url': JSONURI,
		'method': 'get',
		'autoCancel': true,
		'onComplete': function(json) {
			if (json) {
				panelData[cID] = json;
				switchCategory(cID, pcode);
			} else {
				if (panelStatus != 'hidden') {
					fadeOut.start({'visibility': 'hidden', 'opacity': [1, 0] });
				}
			}
		},
		'onFailure': function() {
			alert("Could not contact server for product information. Please try again");
		},
		'data': 'get=category&id=' + cID
	}).send();
}
window.addEvent('domready', function() {
	fadeOut = new Fx.Morph('digicatessen', {
		duration: '250',
		link: 'cancel'
	});
	fadeOut.addEvent('start', function() { panelStatus = 'hidden'; });
	fadeOut.addEvent('complete', function() { panelStatus = 'hidden'; });
	fadeIn = new Fx.Morph('digicatessen', {
		duration: '750ms',
		link: 'cancel'
	});
	fadeIn.addEvent('start', function() { panelStatus = 'visible'; });
	fadeIn.addEvent('complete', function() { panelStatus = 'visible'; });
	$('typelist').getElements('a').each(function(el) {
		el.addEvent('click', function(e) {
			e.stop();
			categoryID = parseQuery(this.href.substr(this.href.indexOf('?') + 1))['categoryID'];
			switchCategory(categoryID);
			return(false);
		});
	});
});
