//cookie functions
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


//ask user before proceeding
function askFirst(text, url)
{
	var answer = confirm (text);
	
	if (answer)
		window.location=url;
}

//for the add wine page
var oldname;
function updateWineName()
{	
	//get vars
	var winery = $F('f_winery');
	var variety = $F('f_variety');
	var currentname = $F('f_name');
	
	//our guess
	var nameguess;
	if(winery && variety)
		nameguess = winery + ' ' + variety;
	else if(winery)
		nameguess = winery;
	else if(variety)
		nameguess = variety;
	else
		nameguess = '';
		
	if(currentname == oldname || !currentname)
	{	//user hasn't adjusted the name yet. update it
		$('f_name').value = nameguess;
	}
	else
	{	//user updated the name already. leave it alone
	}
	
	oldname = nameguess;	
}

//hides all child elements
function hideChildren(e)
{
	e = $(e);
	
	if(e)
	{
		//hide the children
		for(child in e.childNodes)
		{
			hideChildren(e.childNodes[child]);
		}
	
		//hide this one
		if(e.style)
			e.style.display='none';
	}
}

//shows all child elements
function showChildren(e)
{
	e = $(e);
	
	if(e)
	{	
		//hide the children
		for(child in e.childNodes)
		{
			showChildren(e.childNodes[child]);
		}
	
		//hide this one
		if(e.style)
			e.style.display='';
	}
}

//ui functions
function showCentered(obj)
{	
	$(obj).style.left = (document.documentElement.clientWidth / 2 - parseInt($(obj).style.width) / 2) + 'px';		
	Element.show(obj);
}

function showWineryForm()
{
	Element.hide('winery_website');
	Effect.Appear('winery_form');
}

function hideWineryForm()
{
	Element.hide('winery_form');
	Effect.Appear('winery_website');
}

function toggleContent(target, opened, closed)
{
	//find target
	var root = target;
	var eSwitch = $('switch_' + target);
	var target = $('content_' + target);
	
	//todo: add code to handle images for opened and closed
		
	//hide/show
	if (target.style.display == 'none')
	{
		eSwitch.innerHTML = opened;
		target.show();
		createCookie('SuperWineSearch_toggle_'+root,'hide',30);				
	}
	else
	{
		eSwitch.innerHTML = closed;
		target.hide();
		createCookie('SuperWineSearch_toggle_'+root,'show',30);								
	}		
}

function ifEnter(e, btn)
{
	if (window.event && window.event.keyCode == 13)
		$(btn).click();
	else if(e && e.which == 13)
		$(btn).click();
	else
		return true;
}
