// faked in urchinTracker to work with new GA
function urchinTracker(path) {
	pageTracker._trackPageview(path);
}

var newwindow = '';
function popRest() {
	if (!newwindow.closed && newwindow.location) {
		newwindow.location.href = url;
	}
	else {
		newwindow=window.open('/changerestaurant'+(window.location.href.indexOf('search') != -1 ? "?search" : ""),'console','height=250,width=400');
		if (!newwindow.opener) newwindow.opener = self;
	}
	if (window.focus) {newwindow.focus()}
	//return false;
}

function preloadImg() {
	// base url, [image1name [, image2name...]]
	if (document.images) {
		var url = arguments[0];
		var cached = new Array();
		for ( var i=1; i < arguments.length; i++) {
			cached[i-1] = new Image();
			cached[i-1].src = url + arguments[i];
		}
	}
}

function TabSet(name) {
	this.name = name;
	this.currentTab = "init";

	TabSet.prototype.setTab = function (newtab) {
		if (this.currentTab != newtab) {
			this.unsetTab.call(this);
			newtab.className = "focused";

			contentarea = document.getElementById(newtab.id + "content");
			Effect.toggle(contentarea, 'blind', {duration:.5, queue: 'end', afterFinish: function() {
//				contentarea.style.display = "block";
			} } );

			this.currentTab = newtab;
		} else { this.unsetTab.call(this); }
	}

	TabSet.prototype.unsetTab = function() {
		if (this.currentTab != "init") {
			this.currentTab.className = "";

			contentarea = document.getElementById(this.currentTab.id + "content");
			Effect.toggle(contentarea, 'blind', {duration:.5, queue: 'end', afterFinish: function() {
//				contentarea.style.display = "none";
			} } );

			this.currentTab = "init";
		}
	}
}

function togglebar(button, tabset) {
	var bar = document.getElementById('bar');

	if (tabset.currentTab == "init") { // tabset isn't open
		if (bar.style.display == "none") {
			button.innerHTML = "HIDE";
			new Effect.Opacity(button, {duration:0.0, from:0.4, to:1, afterFinish: function() {
//				button.style.opacity = "1";
			} } );

			Effect.toggle(bar, 'blind', {duration:.5, afterFinish: function() {
//				bar.style.display = "block";
			} } );
		} else {
			Effect.toggle(bar, 'blind', {duration:.5, afterFinish: function() {
//				bar.style.display = "none";
				button.innerHTML = "SHOW";

				new Effect.Opacity(button, {duration:0.5, from:1.0, to:0.4, afterFinish: function() {
//					button.style.opacity = ".4";
				} } );
			} } );
		}
	} else {
		tabset.unsetTab();
	}
}

function ajaxSubmit(button, formID) {
	button.disabled = "disabled";

	// TODO: Handle with AJAX...
		// Success: (JS) Close add comments infotab, open comments infotab, display new comment with slightly different color BG
		// Fail: (JS) Display error

	// TODO: (PHP) Render data harmless for output
	// TODO: (PHP) Render data harmless for SQL
	// TODO: (PHP) Insert comment into database
	document.getElementById('formID').submit();
}

function periodictest(max) {
	if ($('passMsg').innerHTML.indexOf("Checking your") != -1 && max > 0) {
		$('passMsg').innerHTML += '.';
		setTimeout('periodictest('+(max-1)+');', 375);
	} else if ( max == 0) {
		$('passMsg').innerHTML = 'Password checking failed. Please try again.';
	}
}

function resetinput(element) {
	element.style.opacity = "1";
	element.style.cursor = "pointer";
	if (element.attachEvent) {
		element.onclick = function () { resetPassword(this); return false; }
	} else {
		element.setAttribute('onclick', 'resetPassword(this); return false;');
	}
}

function resetPassword(element)
{
	element.style.opacity = ".5";
	element.style.cursor = "default";
	element.setAttribute('onclick', 'return false;');
	if (element.attachEvent) { element.onclick = function () { return false; } }

	new Effect.Opacity('passMsg', {duration: .5, from: 1.0, to:0.0,
		afterFinish: function() {
			$('passMsg').innerHTML = "Checking your email address";
			periodictest(10);
			new Effect.Opacity('passMsg', {duration: .5, from: 0.0, to:1.0,
				afterFinish: function () {

					new Ajax.Request('/app/ajax/passwordReset', {
						method: 'post',
						parameters: 'email='+$('email').value,
						onSuccess: function(transport) {
							new Effect.Opacity('passMsg',
								{
								duration: 1,
								from: 1.0,
								to: 0.0,
								afterFinish: function() {
										$('passMsg').innerHTML = transport.responseText;
										new Effect.Opacity('passMsg', {duration: 1, from: 0.0, to:1.0});
									}
								});
							}
						});
				}
			});
		}
	});

}

function removeReservedWine(resWineId, elem)
{
	var tr = elem.parentNode.parentNode.parentNode.parentNode;
	var table = tr.parentNode.parentNode;

	var confirmstring = "Are you sure you want to remove this wine?";
	if (table.getElementsByTagName('tbody')[0].getElementsByTagName('tr').length == 1) {
		var redirectme = true;
		confirmstring = "Removing this wine selection from your reservation will cancel your reservation. " + confirmstring;
	}

	if(confirm(confirmstring)) {
		new Ajax.Request('/app/ajax/removeWineSelection', {
			method: 'post',
			parameters: 'resWineId='+resWineId+'&restWineId='+$('sizeSelect'+resWineId).value,
			onSuccess: function (response) {
				if (response.responseText == "1") {
					if (redirectme) {
						window.location.href = "/browse/";
					} else {
						var num = parseInt(document.getElementById('reservation_qty').firstChild.nodeValue.substring(1, document.getElementById('reservation_qty').firstChild.nodeValue.length-1)) - 1;
						var qtystring = (num == 1 ? "("+num+" wine)" : "("+num+" wines)");
						document.getElementById('reservation_qty').firstChild.nodeValue = qtystring;
						new Effect.Fade(tr, {duration:1});
					}
				} else {
					window.location.href = "/browse/";
				}

			}
		});
	}
}

function updateReservedWine(resWineId, WineId, elem)
{
	var tr = elem.parentNode.parentNode.parentNode.parentNode;
	new Ajax.Request('/app/ajax/updateWineSelection', {
		method: 'post',
		parameters: 'WineId='+WineId+'&restWineId='+$('sizeSelect'+resWineId).value+'&qty='+$('qtySelect'+resWineId).value,
		onSuccess: function (response) {
			if (response.responseText == "1") {
				new Effect.Highlight(tr, {startcolor: '#E3DFD8', endcolor: '#FFFFFF', restorecolor: '#FFFFFF', duration:.5, afterFinish: function () {
					new Effect.Highlight(tr, {startcolor: '#FFFFFF', endcolor: '#E3DFD8', restorecolor: '#E3DFD8', duration:.5});
				}});
			} else {
				window.location.reload();
			}
		}
	});
}

function changeQuantity(resWineId, wineId)
{
	var availableCount = bottles[$('sizeSelect'+resWineId).value];
	var c = 1;
	var HTML = '';
	while(c <= availableCount && c < 6)
	{
		HTML = HTML+'<option value="'+c+'">'+c+'</option>';
		c++;
	}
	$('qtySelect'+resWineId).innerHTML = HTML;
}

function toggleNeedRes()
{
	if($('unreserved').className == 'closed')
	{
		$('unreserved').className = '';
		$('unreservedDate').className = '';
		$('reserved').className = 'closed';
	}
	else
	{
		$('unreserved').className = 'closed';
		$('unreservedDate').className = 'closed';
	}
}
var firstTogRes = false;
function toggleRes()
{
	if($('reserved').className == 'closed' || !firstTogRes)
	{
		$('reserved').className = '';
		$('unreserved').className = 'closed';
		$('unreservedDate').className = 'closed';
		firstTogRes = true;
	}
	else
	{
		$('reserved').className = 'closed';
	}
}

function enableDate()
{
	$('getReservation').className = 'disabled';
	$('openTable').attributes['onclick'].value = 'return false;';
	$('continue').attributes['onclick'].value = 'return false;';

	$('reservationDate').className = '';

	if ($('submit2').attachEvent) {
		$('submit2').onclick = function() { submitDateTime(2); return false; }
	} else {
		$('submit2').attributes['onclick'].value = 'submitDateTime(2); return false;';
	}

}

function submitDateTime(num)
{
	$('dateTimeForm'+num).submit();
}

function submitWines(loggedin, url)
{
	if(!loggedin && !flashlogin) {
		var h = $('wineSelectionContent').offsetHeight-37;
		var w = $('wineSelectionContent').offsetWidth-68;
		$('blind').style.height = h+'px';
		$('blind').style.width = w+'px';

		$('blind').style.zIndex = 10;
		$('popup').style.zIndex = 100;

		$('blind').style.display = "block";
		$('popup').style.display = "block";

		if (h < $('blind').offsetTop) {
			var selects = document.getElementsByTagName('select');
			for (var i = 0; i < selects.length; i++) {
				selects[i].style.display = "none";
			}
			$('blind').style.marginTop = '-'+h+'px';
			$('popup').style.marginTop = h - $('popup').offsetTop - ($('popup').offsetHeight/2) + 60 +'px';
		}
	} else {
		window.location.href=url;
	}
}

function closeloginpop () {
	$('popup').style.display = 'none';
	$('blind').style.display = 'none';
	$('popup').style.zIndex = -100;
	$('blind').style.zIndex = -10;

	var selects = document.getElementsByTagName('select');
	for (var i = 0; i < selects.length; i++) {
		selects[i].style.display = "inline";
	}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function setRests()
{
	var city = $('citySelect').value;
	var HTML = '';
	for (var rest in rests[city])
	{
		HTML += '<option value="'+rest+'">'+rests[city][rest]+'</option>';
	}
	if(HTML == '')
		HTML += '<option value="">No restaurants in this city</option>';
	$('restSelect').innerHTML = HTML;
}

function toggleResHistory(elem)
{
	var li = elem.parentNode;
	if(li.className == 'closed')
	{
		li.className = '';
	}
	else
	{
		li.className = 'closed';
	}
}

function togglePastRes(elem)
{
	var li = elem.parentNode;
	if(li.className == 'open')
	{
		li.className = '';
	}
	else
	{
		li.className = 'open';
	}
}

function cancelReservation(resID, elem)
{
	if(confirm("Are you sure you want to cancel this reservation?"))
	{
		var ul = elem.parentNode.parentNode.parentNode;
		if(ul.nodeName != 'ul') { ul = ul.parentNode; }
		var removeme = ul.parentNode.parentNode.parentNode;

		new Ajax.Request('/app/ajax/cancelRes', {
			method: 'post',
			parameters: 'resID='+resID,
			onSuccess: function (response) {
				if (response.responseText) {
					if (ul.parentNode.getElementsByTagName('form').length == 1) {
						new Effect.Fade(removeme, {duration:1, afterFinish: function () {
							var myparent = removeme.parentNode;
							myparent.removeChild(removeme);

								if (myparent.getElementsByTagName('li').length == 0) { window.location.href = "/?p=search"; }

							for (var i = 0; i < myparent.getElementsByTagName('li').length; i++) {
								if (myparent.getElementsByTagName('li')[i].className == "closed") {
									myparent.getElementsByTagName('li')[i].className = "";
								}
							}
						}
						});
					} else {
						new Effect.Fade(ul, {duration:1, afterFinish: function () {
							var resconf = ul.parentNode;
							resconf.removeChild(ul);
							if (resconf.getElementsByTagName('ul').length == 0) {
								var containerli = resconf.parentNode.parentNode;
								var myparent = containerli.parentNode;
								myparent.removechild(containerli);

								if (myparent.getElementsByTagName('li').length == 0) { window.location.href = "/?p=search"; }

								for (var i = 0; i < myparent.getElementsByTagName('li').length; i++) {
									if (myparent.getElementsByTagName('li')[i].className == "closed") {
										myparent.getElementsByTagName('li')[i].className = "";
									}
								}
							}
						}
						});
					}
				} else {
					alert("You may not cancel this reservation online. Please contact the restaurant.");
				}
			}
		});
	}
}

function editReservation(resID, restID, cityID)
{
	new Ajax.Request('/app/ajax/setReservationID', {
		method: 'post',
		parameters: 'resID='+resID+'&restID='+restID+'&cityID='+cityID,
		onSuccess: function () {
			return true;
		}
	});
}

function togglepasswords() {
	var login = $('login_form');
	var forgot = $('pass_form');
	if (login.style.display == 'none') {
		$('username').value = $('email').value
	} else {
		$('email').value = $('username').value
	}
	$('password').value = "";
	$('remember').style.visibility = "hidden";
	Effect.toggle(login, 'blind');
	Effect.toggle(forgot, 'blind', {afterFinish: function () { $('remember').style.visibility = 'visible'; } });
}


function opensend(element) {
	Effect.toggle('opensend', 'blind', {duration: .3});
	if (element.className.indexOf('disabled') == -1) {
		element.className += ' disabled';
	} else {
		element.className = 'sendtofriend';
	}
}

function sendemails() {
	opensend($('sendtofriendlink'));
	new Ajax.Request('/app/ajax/sendtofriend', {
		method: 'post',
		parameters: 'emails=' + $('emails').value + '&resID=' + $('reservationid').value,
		onSuccess: function () {
			$('emails').value = '';
		}
	});
}

var togglelockout = new Array();
var actqueue = false;

function enqueueopen(element) {
	actqueue = function () { openme(element); };
}

function runopenqueue() {
	if (actqueue) { actqueue(); }
	setTimeout('runopenqueue();', 300);
}

function openme(element) {
	var liarray = element.parentNode.getElementsByTagName('li');
	for (var i = 0; i < liarray.length; i++) {
		if (liarray[i] == element) {
			elementindex = i;
		}
	}
	var ptag = element.getElementsByTagName('p')[0];
	var h3tag = element.getElementsByTagName('h3')[0];
	if (ptag && ptag.style.display == 'none' && !togglelockout[elementindex]) {
		togglelockout[elementindex] = true;
		new Effect.Parallel( [
			Effect.BlindDown(ptag, { sync:true, duration: .2 } ),
			new Effect.Highlight(element, { sync:true, duration: .2, startcolor: '#F3ECE3', endcolor: '#FFFFFF', restorecolor: '#FFFFFF' } )
		], {beforeStart: function () { h3tag.style.backgroundImage = 'none'; },
			afterFinish: function() {
				togglelockout[elementindex] = false;
				for (var i = 0; i < liarray.length; i++) {
					if (liarray[i] != element) {
						closeme(liarray[i], i);
					}
				}
			}, duration: .2, transition:Effect.Transitions.sinoidal, queue: 'end'});
	}
}

function closeme(element, elementindex) {
	var ptag = element.getElementsByTagName('p')[0];
	var h3tag = element.getElementsByTagName('h3')[0];
	if (ptag && ptag.style.display != 'none' && !togglelockout[elementindex]) {
		togglelockout[elementindex] = true;
		new Effect.Parallel( [
			Effect.BlindUp(ptag, { sync:true, duration: .2 } ),
			new Effect.Highlight(element, { sync:true, duration: .2, startcolor: '#FFFFFF', endcolor: '#F3ECE3', restorecolor: '#F3ECE3' } )
		], {beforeStart: function () { h3tag.style.backgroundImage = ''; },
			afterFinish: function() { togglelockout[elementindex] = false; }, duration: .2, transition:Effect.Transitions.sinoidal, queue: 'end'});
	}
}

function notespopup(infoobject, element) {
	if ($('popup')) { $('popup').parentNode.removeChild($('popup')); }

	var bottom = 0;
	var left = 0;
	var right = 0;
	var width = 0;
	var pieces = { winename: false, imageheader: false, bar: {}, bodycopy: {} };

	for (var x in infoobject) {
		switch (x) {
			// Positioning
			case "relativeto": bottom = findPos($(infoobject[x]))[1] + $(infoobject[x]).getDimensions().height; break;
			case "relativetoinside": bottom = findPos($(infoobject[x]))[1]; break;
			case "offset": bottom += infoobject[x]; break;

			case "left": left = findPos($(infoobject[x]))[0]; break;
			case "leftoffset": left += infoobject[x]; break;

			case "right": right = findPos($(infoobject[x]))[0]; break;
			case "rightoffset": right -= infoobject[x]; break;

			case "width": width = infoobject[x]; break;

			// Adding of elements
			case "winename":
				var temp = document.createElement('h3');
				temp.appendChild(document.createTextNode(infoobject[x]));
				pieces[x] = temp;
			break;
			case "imageheader":
				switch(infoobject[x]) {
					case "reservationupdate":
						var temp = document.createElement('h3');
						var headerimg = new Image();
							headerimg.src = "/_images/reservation/reservationupdate.gif";
							headerimg.setAttribute("alt", "Reservation Update. One or more of the bottles of wine you have selected is no longer available. If you choose to continue, your reservation will be updated accordingly.");

						temp.appendChild(headerimg);
					break;
				}
				pieces[x] = temp;
			break;
			case "headertext":
				var temp = document.createElement('h1');
				switch (infoobject[x]) {/*
					case "Producer Notes":
						var headerimg = new Image();
							headerimg.src = "/_images/search/winedetail/wdtitle_producernotes.gif";
							headerimg.setAttribute("alt", infoobject[x]);
						temp.appendChild(headerimg);
					break;
					case "Robert Parker":
						var headerimg = new Image();
							headerimg.src = "/_images/search/winedetail/wdtitle_robertparker.gif";
							headerimg.setAttribute("alt", infoobject[x]);
						temp.appendChild(headerimg);
					break;
					case "Wine Spectator":
						var headerimg = new Image();
							headerimg.src = "/_images/search/winedetail/wdtitle_winespectator.gif";
							headerimg.setAttribute("alt", infoobject[x]);
						temp.appendChild(headerimg);
					break;*/
					default:
						temp.appendChild(document.createTextNode(infoobject[x]));
					break;
				}
				pieces.bar[x] = temp;
			break;
			case "headerlink":
				switch (infoobject[x]) {
					case "Continue Editing Reservation":
						var anchor = document.createElement('a');
							anchor.setAttribute('href', '#');
							anchor.className = "continueediting";
							if (anchor.attachEvent) {
								anchor.onclick = function () { this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false; }
							} else {
								anchor.setAttribute('onclick', 'this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false;');
							}
							anchor.appendChild(document.createTextNode(infoobject[x]));
					break;
				}
				pieces.bar[x] = anchor;
			break;
			case "rating":
				var temp = document.createElement('h2');
				if (infoobject.maturity) { temp.className = 'first'; }
				var header = document.createElement('b');
					header.appendChild(document.createTextNode('Rating:'));

				temp.appendChild(header);
				temp.appendChild(document.createTextNode(' ' + infoobject[x]));
				pieces.bar[x] = temp;
			break;
			case "maturity":
				var temp = document.createElement('h2');
				var header = document.createElement('b');
					header.appendChild(document.createTextNode('Maturity:'));

				temp.appendChild(header);
				temp.appendChild(document.createTextNode(' ' + infoobject[x]));
				pieces.bar[x] = temp;
			break;
			case "bodycopy":
				var paragraphs = infoobject[x].split("<br/>");
				for (var i=0; i<paragraphs.length; i++) {
					var temp = document.createElement('p');
					if (infoobject.headertext && infoobject.headertext != "Producer Notes") {
						var boldsec = document.createElement('b');
							// only show the header once
							if (i == 0) {
								boldsec.appendChild(document.createTextNode('Tasting Notes:'));
							}
						temp.appendChild(boldsec);
						temp.appendChild(document.createTextNode(' '));
					}
					temp.appendChild(document.createTextNode(paragraphs[i]));
					pieces.bodycopy[i] = temp;
				}
			break;
		}
	}

	var popupblock = document.createElement('div');
		popupblock.setAttribute('id', 'popup');
		popupblock.className = 'popup';
		popupblock.style.top = bottom+'px';
		if (width) { popupblock.style.width = width+'px'; }
		if (left) { popupblock.style.left = left+'px'; popupblock.style.marginLeft = 0+'px'; } //else { popupblock.style.left = "auto"; }
		if (right) { popupblock.style.right = right+'px'; popupblock.style.marginRight = 0+'px'; } //else { popupblock.style.right = "auto"; }

	var closelink = document.createElement('a');
		closelink.setAttribute('href', '#');
		closelink.className = 'closelink';

		if (closelink.attachEvent) {
			closelink.onclick = function () { this.parentNode.parentNode.removeChild(this.parentNode); return false; }
		} else {
			closelink.setAttribute('onclick', 'this.parentNode.parentNode.removeChild(this.parentNode); return false;');
		}
		closelink.appendChild(document.createTextNode('x'));

	popupblock.appendChild(closelink);

	var bar = document.createElement('div');
		bar.className = 'headerwrapper';
		for (var x in pieces.bar) { bar.appendChild(pieces.bar[x]) }
		pieces.bar = bar;

	var bodycopy = document.createElement('div');
		bodycopy.className = 'bodycopy';
		var append = false;
		for (var x in pieces.bodycopy) { bodycopy.appendChild(pieces.bodycopy[x]); append = true; }
		pieces.bodycopy = (append ? bodycopy : false);

	for (var x in pieces) {
		if (pieces[x].nodeType == 1) {
			popupblock.appendChild(pieces[x]);
		}
	}

	document.body.appendChild(popupblock);
}
