var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

if (checkIt('konqueror'))
{
	browser = "Konqueror";
	OS = "Linux";
}
else if (checkIt('safari')) browser = "Safari"
else if (checkIt('omniweb')) browser = "OmniWeb"
else if (checkIt('opera')) browser = "Opera"
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab"
else if (checkIt('msie')) browser = "Internet Explorer"
else if (!checkIt('compatible'))
{
	browser = "Mozilla"
	version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS)
{
	if (checkIt('linux')) OS = "Linux";
	else if (checkIt('x11')) OS = "Unix";
	else if (checkIt('mac')) OS = "Mac"
	else if (checkIt('win')) OS = "Windows"
	else OS = "an unknown operating system";
}

function checkIt(string)
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}
function xGetElementById(e) {
	if (typeof(e) != 'string') return e;
	if (document.getElementById) e = document.getElementById(e);
	else if (document.all) e = document.all[e];
	else if (document.layers) e = xLayer(e);
	else e = null;
	return e;
}

// setStyleById: given an element id, style property and
// value, apply the style.
// args:
//  i - element id
//  p - property
//  v - value
//
function setStyleById(element, property, value) {
	var n = $(i);
	n.style[p] = v;
}

function getStyleById(i, p) {
	var n = $(i);
	var s = eval("n.style." + p);

	// try inline
	if((s != "") && (s != null)) {
		return s;
	}

	// try currentStyle
	if(n.currentStyle) {
		var s = eval("n.currentStyle." + p);
		if((s != "") && (s != null)) {
			return s;
		}
	}

	return null;
}

function xPageY(e) {
	if (!(e=$(e))) return 0;
	if (xDef(e.pageY)) return e.pageY;
	var y = 0;
	while (e) {
		if (xDef(e.offsetTop)) y += e.offsetTop;
		e = xDef(e.offsetParent) ? e.offsetParent : null;
	}
	return y;
}

function xPageX(e) {
	if (!(e=$(e))) return 0;
	if (xDef(e.pageX)) return e.pageX;
	var x = 0;
	while (e) {
		if (xDef(e.offsetLeft)) x += e.offsetLeft;
		e = xDef(e.offsetParent) ? e.offsetParent : null;
	}
	return x;
}

function xDef() {
	for(var i=0; i<arguments.length; ++i) {
		if(typeof(arguments[i]) == 'undefined') return false;
	}
	return true;
}

function send(title, left_offset) {
	var which =$('which');
	if (which) {
		which.style.display = 'none';
	}
	var x = xPageX('send_to_friend');
	if (!left_offset || left_offset == null) {
		left_offset = 0;
	}
	x = x + left_offset;
	var y = xPageY('send_to_friend');
	var send_box = $('send_box');
	var send_box_sent = $('send_box_sent');
	var send_box_text = $('send_box_text');
	send_box_text.style.display = 'block';
	send_box_sent.style.display = 'none';
	send_box.style.position = 'absolute';
	send_box.style.top = y - 10;
	send_box.style.left = x * 1 + 30;
	new Effect.Appear(send_box); // send_box.style.display = 'block';

	// $('stf_url').value = document.location.href;
	$('stf_page_id').value = title;
}

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);
}

function showMoreRecent() {
	// new Effect.Appear('recent');
	$('recent').style.display = 'block';
	$('recent_link').style.display = 'none';
}

function showMoreRelated(start) {
	$('related_link').style.display = 'none';
	start++;
	for (i=start; i<50; i++) {
		var tr = $('related_tr_' + i);
		if (tr) {
			tr.style.display = showTableRow();
		} else {
			break;
		}
	}
}

function showMoreRelatedbm(start) {
	$('relatedbm_link').style.display = 'none';
	start++;
	for (i=start; i<50; i++) {
		var tr = $('relatedbm_tr_' + i);
		if (tr) {
			tr.style.display = showTableRow();
		} else {
			break;
		}
	}
}

function showMoreAlts() {
	$('alt').style.display = 'block';
	$('alt_link').style.display = 'none';
}

function addDesc() {
	// Effect.Fade('desc');
	var desc = $('desc');
	desc.style.display = 'none';
	new Effect.Appear('add_desc_div');
}

function i_ate_this(item_id) {
	var ate_this_when = $('ate_this_when');

	var top = xPageY('i_ate_this_btn');
	var left = xPageX('i_ate_this_btn');

	ate_this_when.style.top = top;
	ate_this_when.style.left = left;

	ate_this_when.style.position = "absolute";
	document.body.appendChild(ate_this_when);
	ate_this_when.style.display = 'block';
}

function ate_this_other(item_id) {
	var ate_this_when = $('ate_this_when');
	ate_this_when.innerHTML = "<b>When did you eat this item?</b><br><br>\n" +
	"<form method='post' action='/users/myplate.php'>\n" +
	"<input type='hidden' name='what' value='" + item_id + "'>\n" +
	"<input type='text' name='when' id='when' value='m/d/2008' size='15'>\n" +
	"<input type='submit' name='go' value='Go'></form>";
}

function rateReview(item_review_id, which) {
	$('saveFrame').src = '/items/rate_review.php?iri=' + item_review_id + "&which=" + which;
	new Effect.Highlight('rate_text_' + item_review_id);
}

function getKeyCode(e) { // e is event object passed from function invocation
	var KeyID = (window.event) ? event.keyCode : e.keyCode;
	return KeyID;
}

function updateValue(which, unit) {
	var the_name = which.name;

	if (unit) {
		if (browser == 'Internet Explorer' && getKeyCode() < 47) {
			// do nothing
		} else {
			if (which.value.indexOf(unit) == -1 && which.value > '') {
				var the_length = which.value.length;
				which.value = which.value + unit;
				if (browser == 'Mozilla') {
					which.setSelectionRange(the_length, the_length);
				} else if (browser == 'Internet Explorer') {
					var range = which.createTextRange();
					range.moveStart('character', the_length);
					// range.moveEnd('character', the_length);
					//range.move('character', (the_length * -1));
					range.select();
				}

			}
		}
	}

	$(the_name).innerHTML = which.value;
	if ($(the_name + '_label')) {
		$(the_name + '_label').style.display = showTableRow();
	}

	// new Effect.Highlight(the_name);
	$(the_name).style.backgroundColor = 'yellow';
	setTimeout("$(" + the_name + ").style.backgroundColor='transparent';", 3000);
}

function showTableRow() {
	if (browser != "Internet Explorer") {
		return 'table-row';
	} else {
		return 'inline';;
	}
}

function servingSizer(item_id, which) {
	if (which != 'fitness' && which != 'meal') {
		var serving = $('servings' + item_id);
		var item = 'item' + item_id;
		for (x=1; x<=11; x++) {
			var td = $(item + '_' + x);
			if (td.style.borderBottomWidth == '2px') {
				td.style.borderBottomWidth = '0px';
			} else {
				td.style.borderBottomWidth = '2px';
			}
		}
	} else if (which == 'fitness') {
		var serving = $('fitness' + item_id);
	} else if (which == 'meal') {
		var serving = $('mealexpand' + item_id);
	}
	if (serving.style.display != 'none') {
		serving.style.display = 'none';
	} else {
		if (browser != "Internet Explorer") {
			serving.style.display = 'table-row';
		} else {
			serving.style.display = 'inline';
		}
		new Effect.Highlight(serving, {duration: 3.0});
	}

	if (which == 'meal') {
		var ffield =  $('meal_servings[' + item_id + ']');
		ffield.focus();
		ffield.select();
	} else if (which == 'fitness') {
		var ffield = $('minutes[' + item_id + ']');
		ffield.focus();
		ffield.select();
	} else if ($('serving_count_' + item_id)) {
		$('serving_count_' + item_id).focus();
		$('serving_count_' + item_id).select();
	} else if ($('servings[' + item_id + ']')) {
		$('servings[' + item_id + ']').focus();
		$('servings[' + item_id + ']').select();
	}
}

function meal(meal_id) {
	var meal = $('meal' + meal_id);
	// var link = $('reglink' + item_id);
	if (meal.style.display == 'none')  {
		// reg.style.display = 'block';
		// new Effect.Appear(reg);
		new Effect.BlindDown(meal, {duration: .5});
	} else {
		new Effect.Fade(meal, {duration: .5});
	}
}


function workout(workout_id) {
	var workout = $('workout' + workout_id);
	// var link = $('reglink' + item_id);
	if (workout.style.display == 'none')  {
		// reg.style.display = 'block';
		// new Effect.Appear(reg);
		new Effect.BlindDown(workout, {duration: .5});
	} else {
		new Effect.Fade(workout, {duration: .5});
	}
}

function regularly_eat(item_id) {
	var reg = $('regular' + item_id);
	var link = $('reglink' + item_id);
	if (reg.style.display == 'none')  {
		// reg.style.display = 'block';
		// new Effect.Appear(reg);
		new Effect.BlindDown(reg, {duration: .5});
	} else {
		new Effect.Fade(reg, {duration: .5});
	}
}

function regularly_fit(fitness_id) {
	var fit = $('fitm' + fitness_id);
	var link = $('regfitlink' + fitness_id);
	if (fit.style.display == 'none')  {
		// reg.style.display = 'block';
		// new Effect.Appear(reg);
		new Effect.BlindDown(fit, {duration: .5});
	} else {
		new Effect.Fade(fit, {duration: .5});
	}
}

function tab_link(which) {
	var link = '';
	if (which == 'profile') {
		link = '/profile/';
	} else if (which == 'myplate') {
		link = '/users/myplate/';
	} else if (which == 'goals') {
		link = '/users/myinfo/';
	} else if (which == 'preferences') {
		link = '/users/preferences/';
	}

	if (link) {
		parent.location.href = link;
	}
}

function contribute_item_photo(action) {
	var i = $('item_photo_form');
	if (action == 'close') {
		new Effect.Fade(i);
	} else {
		i.style.left = xPageX('item_image') -240;
		i.style.top = xPageY('item_image') + 80;
		new Effect.Appear(i);
	}
}

function highlight_tab(tab, color) {
	tab.style.backgroundColor = color;
}

var tdpgmap = '';

function LoadMapSearch() {
	tdpgmap = new GSmapSearchControl(
	document.getElementById("mapsearch"),             // container
	center,                                           // center point
	{ showResultList : GSmapSearchControl.DEFAULT_RESULT_LIST,  // options
	onBootComplete : MapLoaded }
	);
}

function MapLoaded() {
	tdpgmap.execute(where);
}

function OnLoad() {
	// Create a search control
	var searchControl = new GSearchControl();

	// Add in a full set of searchers
	var localSearch = new GlocalSearch();

	// local search, partial
	options = new GsearcherOptions();
	options.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);

	var searchFormElement = document.getElementById("localform");
	var drawOptions = new GdrawOptions();
	drawOptions.setSearchFormRoot(searchFormElement);

	searchControl.addSearcher(localSearch, options);

	// Set the Local Search center point
	localSearch.setCenterPoint(center);

	// tell the searcher to draw itself and tell it where to attach
	searchControl.draw(document.getElementById("searchcontrol"), drawOptions);

	// execute an inital search
	searchControl.execute(where);
}

function save_address() {
	var address = $('where').value;
	center = address;
	OnLoad();
	$('saveFrame').src = '/users/save_address.php?address=' + escape(address);
}

function show_csv_export_box () {
	var export_box = $('export_csv');

	var top = xPageY('export_link');
	var left = xPageX('export_link');

	export_box.style.top = top;
	export_box.style.left = left;

	export_box.style.display = 'block';
}

function show_export_box () {
	var export_box = $('export_csv');

	var top = xPageY('export_link');
	var left = xPageX('export_link');

	export_box.style.top = top;
	export_box.style.left = left;

	var export_form = document.export_form;
	export_form.ftype[0].checked = 0;
	export_form.ftype[1].checked = 1;

	var csv = $('csv');
	var print = $('print');

	export_form.fltype[0].checked = 0;
	export_form.fltype[2].checked = 1;

	csv.style.display = 'none';
	print.style.display = 'inline';

	var days = document.print_form.print_timeframe.value;
	change_date(days);

	export_box.style.display = 'block';
}

function close_export_box () {
	var export_box = $('export_csv');

	export_box.style.display = 'none';
}

function show_hide_csv () {
	var csv = document.getElementById("csv");
	var print = document.getElementById("print");
/*
	var csv = $('csv');
	var print = $('print');

	csv.toggle();
	print.toggle();
	
	if (csv.display == 'visible') {
		$('xls_radio').selected = 'selected';
	}
*/
}

function change_date (days) {
	var date = new Date();
	if (days == null) {
		days = 30;
	}

	var start_month = document.export_form.start_Month;
	var start_day = document.export_form.start_Day;
	var start_year = document.export_form.start_Year;


	date.setDate(date.getDate() - days);

	for (var i = 0; i < start_month.length; i++) {
		if (start_month[i].value == date.getMonth() + 1) {
			start_month.selectedIndex = i;
		}
	}
	for (var i = 0; i < start_day.length; i++) {
		if (start_day[i].value == date.getDate()) {
			start_day.selectedIndex = i;
		}
	}
	for (var i = 0; i < start_year.length; i++) {
		if (start_year[i].value == date.getFullYear()) {
			start_year.selectedIndex = i;
		}
	}
}
