/*
	JavaScript for Cambria
	
	Author: Aaron Clinger (aaron@aaronclinger.com)
	Version: 06/19/2008
*/
var site;
var homeId = 'home';
window.addEvent('domready', function () {
	$(document.body).getElement('h1 a').addEvent('click', function(e) {
		e.stop();
		
		SWFAddress.setValue(homeId + '/');
	});
	
	var first = true;
	$(document.body).getElements('ul#nav li').each(function (li) {
		li.getElement('a').addEvent('click', function (e) {
			e.stop();
			
			SWFAddress.setValue(this.get('text').split(' ').join('-').toLowerCase() + '/');
			if ($('videoOverlay')) {
				hideVideo();
			}
		});
		
		if (li.hasClass('buy-wine')) {
			return;
		}
		
		if (first) {
			first = false;
			return;
		}
		
	});
	
	addSeparatorsToUl($('sub-nav'));
	addSeparatorsToUl($('footer'));
	
	initContent(document.body);
	
	site = new Site();
	
	var i = -1;
	var id;
	var sectionIds = $(document.body).getElements('ul#nav li a');
	$(document.body).getElements('div.section').each(function (section) {
		i++;
		
		if (i == 0) {
			id = homeId;
		} else {
			id = sectionIds[i - 1].get('text').split(' ').join('-').toLowerCase();
		}
		
		if (section.getElements('dl.section-nav').length == 0) {
			if (section.hasClass(homeId)) {
				site.addSection(new HomeSection(id, section));
			} else {
				site.addSection(new BaseSection(id, section));
			}
		} else {
			site.addSection(new SideNavSection(id, section));
		}
	});
	
	site.ready();
});

var Site = new Class({
	initialize: function() {
		this._map            = new Object();
		this._total          = -1;
		this._sectController = new SectionChanger();
		this._currentSection = null;
		this._firstSection   = true;
		this._lastmove		 = -2;
		this._scroll         = new Fx.Scroll('viewport', {
			duration: 1200,
			wheelStops: false
		});
		
		var context = this;
		
		this._sectController.addEvent('request', function(id) {
			context._sectionChange(id);
		});
	},
	
	addSection: function(sect) {
		sect.setOrder(++this._total);
		sect.setSectControllerReference(this._sectController);
		this._map[sect.getId()] = sect;
	},
	
	ready: function() {
		var context = this;
		SWFAddress.addEventListener(SWFAddressEvent.CHANGE, function() {
			context._onSWFAddressChange();
		});
		this._onSWFAddressChange();
	},
	
	_onSWFAddressChange: function() {
		var id;
		if (SWFAddress.getPath() == '/') {
			id = '/' + homeId + '/';
		} else {
			id = SWFAddress.getPath();
		}
		
		this._sectController.requestSection(id);
	},
	
	_hideSections: function(current_id,new_id) {
		var i = -1;
		$(document.body).getElements('div.section').each(function (section) {
			i++;
			
			if ((i != current_id) && (i != new_id)) {
				section.addClass('hide');
			} else {
				section.removeClass('hide');
			}
		});
	},
	
	_sectionChange: function(id) {
		var mainSection = id.split('/')[1];
		var subsections = id.split('/').slice(2, -1);
		var section     = this._map[mainSection];
		
		if (section == undefined) {
			section = this._map[homeId];
		}
		
		if (subsections.length == 0) {
			section.reset();
		} else {
			section.showSubsections(subsections);
		}
		

		if (this._currentSection != null) {
			if (this._currentSection.getId() != section.getId()) {
				//to skip the sections in between, hide them
				this._hideSections(this._currentSection.getOrder(),section.getOrder());
				this._currentSection.leaving();
				
				this._scrollToSection(section.getOrder() - this._currentSection.getOrder());
				section.visiting(this._firstSection);
			}
		} else {
			this._scrollToSection(section.getOrder());
			section.visiting(this._firstSection);
		}
		
		this._currentSection = section;
		this._firstSection   = false;
		
		var nav = $('nav');
		nav.set('class', '');
		nav.addClass(mainSection);
		
		nav.getElements('li a').each(function(a) {
			if (mainSection == a.get('text').split(' ').join('-').toLowerCase()) {
				a.getParent().addClass('active');
			} else {
				a.getParent().removeClass('active');
			}
		});
	},
	
	_scrollToSection: function(order) {
		this._scroll.cancel();
		
		var thismove = 0;
		if (order != 0) {
			thismove = order/Math.abs(order); //determine direction of move
		}

		//if this move is the same direction as the previous move, shift the starting point appropriately 
		if (this._lastmove == thismove) {
			if (thismove > 0) {
				this._scroll.set(0,0);
			} else {
				this._scroll.set(900,0);
			}
		}
		if (this._lastmove == -2) { //this occurs when returning from offsite
			this._scroll.set(900 * order, 0);
		} else {
			if (thismove == -1) {
				//if you are scrolling backwards after previously returning from offsite, 
				//this prevents a blank screen at the beginning of the animation
				this._scroll.set(900,0);
			}
			this._scroll.cancel();
			this._scroll.start(450 + 450 * order/Math.abs(order), 0);
		}
		this._lastmove = thismove;
	}
});

var BaseSection = new Class({
	initialize: function(id, container) {
		this._id        = id;
		this._container = container;
	},
	
	getId: function() {
		return this._id;
	},
	
	setOrder: function(order) {
		this._order = order;
	},
	
	getOrder: function() {
		return this._order;
	},
	
	setSectControllerReference: function(reference) {
		this._sectController = reference;
	},
	
	showSubsections: function(ids) {
		this._sectController.sectionChangeComplete();
	},
	
	visiting: function(first) {},
	
	leaving: function() {},
	
	reset: function() {
		this._sectController.sectionChangeComplete();
	}
});

var HomeSection = new Class({
	Extends: BaseSection,
	
	initialize: function(id, container) {
		this.parent(id, container);
		
		this._delay = null;
	},
	
	visiting: function(first) {
		if (first) {
			this._embedFlashHome();
		} else {
			var context = this;
			this._delay = setTimeout(function() {
				context._embedFlashHome();
			}, 1300);
		}
	},
	
	leaving: function() {
		clearTimeout(this._delay);
		
		$('homeFlash').set('html', '');
	},
	
	_embedFlashHome: function() {
		var so = new SWFObject('flash/home.swf', 'homeFlashContent', '900', '366', '8', '#3B1900');
		so.addParam('menu', 'false');
		so.addParam('wmode', 'transparent');
		so.write('homeFlash');
	}
});

var SideNavSection = new Class({
	Extends: BaseSection,
	
	initialize: function(id, container) {
		this.parent(id, container);
		
		this._current        = -1;
		this._defaultContent = this._container.getElement('div.content div.contentWrapper div.subsection').get('html');
		
		var __createContentIdByUrl = function(url) {
			return createDeepLinkPathByUrl(url).split('/').slice(-2, -1)[0];
		};
		
		var __addClickEvent = function(a, order) {
			if ((a.get('rel') != 'external') && (a.get('rel') != 'parent')) {
				a.set({
					'order': order,
					'id': __createContentIdByUrl(a.get('href'))
				});
				a.addEvent('click', function(e) {
					e.stop();
					
					SWFAddress.setValue(createDeepLinkPathByUrl(this.get('href')));
				});
			}
		};
		
		var i       = -1;
		var firstDt = true;
		var context = this;
		this._container.getElement('dl.section-nav').getChildren().each(function (child) {
			switch (child.get('tag')) {
				case 'dt' :
					a = child.getElement('a');
					
					if (firstDt) {
						a.addClass('top');
						firstDt = false;
					}
					
					__addClickEvent(a, ++i);
					break;
				case 'dd' :
					child.getElements('ul li a').each(function (a) {
						__addClickEvent(a, ++i);
					});
					break;
			}
		});
	},
	
	showSubsections: function(ids) {
		var a;
		switch (ids.length) {
			case 1 :
				a = $(ids[0]);
				
				if (a == null) {
					SWFAddress.setValue(this.getId() + '/');
					this._sectController.sectionChangeComplete();
				} else {
					this._requestSubsectionOpen(a);
				}
				break;
			case 2 :
				a = $(ids[1]);
				
				if (a == null) {
					SWFAddress.setValue(this.getId() + '/');
					this._sectController.sectionChangeComplete();
				} else {
					this._requestSubsection(a);
				}
				break;
		}
	},
	
	leaving: function() {
		if (this._container.getElement('div#timelineFlash') != null) {
			this.reset();
		}
	},
	
	_requestSubsectionOpen: function(a) {
		this._openSubsection(a);
		
		this._requestContent(a.get('href'), a.get('order'));
	},
	
	_requestSubsection: function(a) {
		this._openSubsection($(createDeepLinkPathByUrl(a.get('href')).split('/').slice(-3, -2)[0]));
		
		a.getParent().addClass('active');
		
		this._requestContent(a.get('href'), a.get('order'));
	},
	
	_openSubsection: function(a) {
		this._resetSubsections();
		
		var dt = a.getParent();
		dt.addClass('active');
		
		if (dt.getNext() != null) {
			if (dt.getNext().get('tag') == 'dd') {
				dt.getNext().addClass('show');
			}
		}
	},
	
	_resetSubsections: function() {
		var dl = this._container.getElement('dl.section-nav');
		
		dl.getElements('dd').each(function (dd) {
			dd.removeClass('show');
		});
		
		dl.getElements('dd ul li').each(function (li) {
			li.removeClass('active');
		});
		
		dl.getElements('dt').each(function (dt) {
			dt.removeClass('active');
		});
	},
	
	_requestContent: function(path, order) {
		this._requested = order * 1;
		
		if (this._requested == this._current) {
			this._sectController.sectionChangeComplete();
			return;
		}
		
		var context = this;
		this._data = new Request.HTML({url:path});
		this._data.addEvent('onComplete', function (responseTree, responseElements, responseHTML, responseJavaScript) {
			context._requestLoaded(responseTree[0].innerHTML);
		});
		this._data.send();
	},
	
	_requestLoaded: function(responseText) {
		var subsection = new Element('div');
		subsection.addClass('subsection');
		subsection.set('html', responseText);
		
		var context = this;
		this._scroll = new Fx.Scroll(this._container.getElement('div.content'), {
			duration: 600,
			wheelStops: false
		});
		this._scroll.addEvent('onComplete', function() {
			context._requestPositioned();
		});
		
		if (this._container.getElement('div#timelineFlash') != null) {
			this._container.getElement('div#timelineFlash').set('html', '');
			this._container.getElement('div#timelineFlash').dispose();
		}
		
		if (this._requested > this._current) {
			subsection.injectInside(this._container.getElement('div.content div.contentWrapper'));
			
			this._scroll.start(0, 732);
		} else {
			subsection.injectTop(this._container.getElement('div.content div.contentWrapper'));
			
			this._container.getElement('div.content').scrollTop = 732;
			
			this._scroll.start(0, 0);
		}
		
		initContent(subsection);
	},
	
	_requestPositioned: function() {
		if (this._requested > this._current) {
			this._scroll.set(0, 0);
			this._container.getElement('div.content div.contentWrapper div.subsection').set('html', '');
			this._container.getElement('div.content div.contentWrapper div.subsection').dispose();
		} else {
			this._container.getElements('div.content div.contentWrapper div.subsection')[1].set('html', '');
			this._container.getElements('div.content div.contentWrapper div.subsection')[1].dispose();
		}
		
		this._current = this._requested;
		
		this._sectController.sectionChangeComplete();
	},
	
	reset: function() {
		if (this._current != -1) {
			this._requested = -1;
			
			this._resetSubsections();
			
			this._requestLoaded(this._defaultContent);
		} else {
			this._sectController.sectionChangeComplete();
		}
	}
});

var SectionChanger = new Class({
	Extends: Events,
	
	initialize: function() {
		this.clear();
	},
	
	requestSection: function(id) {
		if (id == this._queuedSection) {
			return;
		}
		
		if (id == this.getSection()) {
			this._queuedSection = null;
			return;
		}
		
		if (this._changingSections) {
			this._queuedSection = id;
		} else {
			this._startSectionChange(id);
		}
	},
	
	_startSectionChange: function(id) {
		this._queuedSection    = null;
		this._section          = id;
		this._changingSections = true;
		
		this.fireEvent('request', this._section, 0);
	},
	
	sectionChangeComplete: function() {
		if (!this._changingSections) {
			return;
		}
		
		this._changingSections = false;
		
		this.fireEvent('complete', this._section, 0);
		
		if (this._queuedSection != null) {
			this._startSectionChange(this._queuedSection);
		}
	},
	
	getSection: function() {
		return this._section;
	},
	
	getQueuedSection: function() {
		return this._queuedSection;
	},
	
	clear: function() {
		this._requestedSection = null;
		this._queuedSection    = null;
		this._changingSections = false;
	}
});

function showVideo(a) {
	var overlay = new Element('div');
	overlay.set('id', 'videoOverlay');
	overlay.set('html', '<a href="#">close</a><div id="qtVideo"></div>');
	
	overlay.injectAfter($('viewport'));
	
	var context = this;
	overlay.getElement('a').addEvent('click', function(e) {
		e.stop();
		
		context.hideVideo();
	});
	isIE6 = (document.all && document.getElementById) ? true : false;
	if (isIE6) {
		$('videoOverlay').addEvent('click', function(e) {
			e.stop();
			
			context.hideVideo();
		});
	}
	var so = new SWFObject(a.get('href'), 'flashContent', '480', '271', '8', '#E7DB8F');
	so.addParam('menu', 'false');
	so.addParam('wmode', 'transparent');
	so.write('qtVideo');
}

function hideVideo() {
	if ($('videoOverlay') != null) {
		$('videoOverlay').set('html', '');
		$('videoOverlay').dispose();
	}
}

function initContent(el) {
	if ($('timelineFlash')) {
		// Waits for everything to finish sliding.
		setTimeout('embedTimeline()', 1300);
	}
	
	el.getElements('a[rel=external]').each(function(a) {
		a.addEvent('click', function(e) {
			e.stop();
			
			window.open(this.get('href'));
		});
	});
	
	el.getElements('a[rel=deep-link]').each(function(a) {
		a.addEvent('click', function(e) {
			e.stop();
			
			SWFAddress.setValue(createDeepLinkPathByUrl(this.get('href')));
		});
	});
	
	el.getElements('div.video a').each(function(a) {
		a.addEvent('click', function(e) {
			e.stop();
			
			showVideo(this);
		});
	});
}

function createDeepLinkPathByUrl(url) {
	return url.split('.html').join('/').split('.asp').join('/');
}

function embedTimeline() {
	if ($('timelineFlash') != null) {
		var so = new SWFObject('flash/timeline.swf', 'timelineFlashContent', '713', '366', '8', '#E7DB8F');
		so.addParam('menu', 'false');
		so.addParam('wmode', 'transparent');
		so.addVariable('xmlPath', 'xml/timeline.xml');
		so.write('timelineFlash');
	}
}

function addSeparatorsToUl(ulEl) {
	if (!ulEl)
		return;
	
	var first = true;
	
	ulEl.getElements('li').each(function (li) {
		if (first) {
			first = false;
			return;
		}
		
		var pipe = new Element('li');
		pipe.addClass('separator');
		pipe.set('html', '&bull;');
		pipe.injectBefore(li);
	});
}
function showCompliance() {
	window.open('/compliance.html', 'compliance_pop', 'width=713,height=366,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0');
}

function showMailingList() {
	window.open('/mailinglist.asp', 'ml_pop', 'width=713,height=366,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0');
}

function showPrivacyPolicy() {
	window.open('/privacy_policy.html', 'priv_pop', 'width=713,height=366,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0');
}
function showTerms() {
	window.open('/terms.html', 'priv_pop', 'width=713,height=366,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0');
}
function showFeatured() {
	window.open('/featured.html', 'priv_pop', 'width=713,height=366,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1');
}

