
var user_id         = null;
var user_login      = null;
var user_lat        = null;
var user_lon        = null;
var user_role       = null;
var current_session = null;


function getArgs() {
	var args = new Object();
	var query = location.search.substring(1);
	var pairs = query.split(",");
	for(var i= 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=');
		if (pos == -1) continue;
		var argname = pairs[i].substring(0,pos);
		var value = pairs[i].substring(pos+1);
		args[argname] = unescape(value);
	}
	return args;
}


function get_cookie(name) {
	var allcookies = document.cookie;
  
	var pos = allcookies.indexOf(name+'=');
	if (pos != -1) {
		var start = pos+name.length+1;
		var end = allcookies.indexOf(';', start);
		if (end == -1) { end = allcookies.length }
		var value = allcookies.substring(start, end);
		return unescape(value);
	} else {
		return null;
	}
}


function parse_user_cookie(str) {
	var parts = str.split('&');
	user_id    = parts[0];
	user_login = parts[1];
	var re = /\+/g;
	user_login = user_login.replace(re, ' ');
	user_lat   = parts[2];
	user_lon   = parts[3];
	user_role  = parts[4];
}


function test_cookie() {
	document.cookie = "test=OK;%20path=/index.html";
  return ( get_cookie( "test" ) == "OK");
}


function request_cookie() {
	// check that the browser accepts cookies
	if (test_cookie() == false) { return; }
	
	// if accepts cookie, request a new one
	new Ajax.Request('/account/update_cookie', 
											{
												method: 'post',
												asynchronous: true,
												onComplete: function(request) {
													var user_str = get_cookie('user');
													if ((user_str != null) && (user_str != '')) {
														parse_user_cookie(user_str);
													}
												}
											});
}

var user_str = get_cookie('user');

if ((user_str != null) && (user_str != '')) {
	// existing cookie
	parse_user_cookie(user_str);
	if (user_lat == '') { request_cookie(); }	 // old cookie, no loc data.  skips if 'fail'
} else {
	// no cookie
	request_cookie();
}


var tabs = [];

function clear_tabs() {
	for (i=0; i < tabs.length; ++i) {
		$(tabs[i]).className = null;
	}
}

function click_tab(id) {
	clear_tabs();
	$(id).className = 'current';
}

function notify_clear() {
	$('notices').innerHTML ='';
}

function notify_user(type, message) {
	$('notices').innerHTML = '<div class="'+type+'" onclick="Element.hide(\''+type+'\');" id="'+type+'" >'+message+'</div>';
}

// ****** STATE MACHINE *********

var page_state    = 'UNDEFINED';
var page_mode     = 'UNDEF';

function View(state, box_id, mode, has_tab, open_setup, close_cleanup) {
	this.state         = state;
	this.box_id        = box_id;
	this.mode          = mode;
	this.has_tab       = has_tab;
	this.open_setup    = open_setup;
	this.close_cleanup = close_cleanup;
}

View.prototype.open = function(from_state) {
	Element.show(this.box_id);
	if(this.has_tab == true) { click_tab('tab_'+this.state); }
}

View.prototype.close = function(to_state) {
	Element.hide(this.box_id);
}

var views = {};

function register_view(view) {
	views[view.state] = view;
}

function load_states(states) {
	for(var i=0; i < states.length; ++i) {
		var open_setup    = (states[i][3] == null ? function () {} : states[i][3] );
		var close_cleanup = (states[i][4] == null ? function () {} : states[i][4] );
		register_view( new View(states[i][0], 'box_'+states[i][0].toLowerCase(), states[i][1], states[i][2], open_setup, close_cleanup ) );
	}
}

function transition_to(to_state) {
   var from_state = page_state;
	 if ( to_state == from_state ){ return true; }
//Logger.debug("transitioning page from "+from_state+" to "+to_state);

	var from_view = views[from_state];
	var to_view   = views[to_state];
	from_view.close(to_state);
	from_view.close_cleanup(to_state);
	Element.show('tab_bar_'+to_view.mode);
	if (from_view.mode != to_view.mode) {
		Element.hide('tab_bar_'+from_view.mode);
	}
	to_view.open_setup(from_state);
	to_view.open(from_state);
	
   page_state = to_state;
   page_mode  = to_view.mode;
   notify_clear();
  
//Logger.debug('done transitioning');
   return true;
}

var rememberMap = 0;

function changeMap(n){
	for(var i = 0; i < bestof_maps_data.length; i++){
		$('bestof_'+i).style.background='#111';
	}
	$('bestof_'+n).style.background='#444444';
	show_widescreen_map( bestof_maps_data[n] );
	rememberMap = n;
}

function showBox(){
	Element.show('overlay_login');
	center('dual_box');
	return false;
}
function showBox1(){
	Element.show('overlay_login');
	center('dual_box1');
	return false;
}
function showBox2(){
	Element.show('overlay_login');
	center('dual_box2');
	return false;
}
function hideBox(){
	Element.hide('dual_box');
	Element.hide('dual_box1');
	Element.hide('overlay_login');
	Element.hide('results_form');
	Element.show('initial_form');
	return false;
}
function hideBox1(){
	Element.hide('dual_box');
	Element.hide('dual_box1');
	Element.hide('dual_box2');
	Element.hide('overlay_login');
	Element.hide('results_form');
	Element.show('initial_form');
	return false;
}

function showMessageBox(){
	Element.show('overlay_message');
	center('message_box');
	return false;
}

function hideMessageBox(){
	Element.hide('message_box');
	Element.hide('overlay_message');
	return false;
}

function showLoginLogout(){
	if ((user_login != null) && (user_login != '')) {
		new Insertion.Top('user_status', '<div id=\"loginlogout\">User: <a href="/users/show/'+user_id+'">'+user_login+'</a>&nbsp;&nbsp;|&nbsp<a href="/account/logout">Sign Out</a>&nbsp;&nbsp;|&nbsp<a href="/account/edit">Settings</a></div>');
	} else {
		new Insertion.Top('user_status', "<div id=\"loginlogout\"><a href=\"\" onclick=\"showBox(); return false;\">Log In</a></div>");
	}
}

function center(element){
    try{
    	element = document.getElementById(element);
    }catch(e){
        return;
    }

    var my_width  = 0;
    var my_height = 0;

    if ( typeof( window.innerWidth ) == 'number' ){
        my_width  = window.innerWidth;
        my_height = window.innerHeight;
    }else if ( document.documentElement && 
			 ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ){
        my_width  = document.documentElement.clientWidth;
        my_height = document.documentElement.clientHeight;
    }
    else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ){
        my_width  = document.body.clientWidth;
        my_height = document.body.clientHeight;
    }

    element.style.position = 'absolute';
    element.style.zIndex   = 99;

    var scrollY = 0;

    if ( document.documentElement && document.documentElement.scrollTop ){
        scrollY = document.documentElement.scrollTop;
    }else if ( document.body && document.body.scrollTop ){
        scrollY = document.body.scrollTop;
    }else if ( window.pageYOffset ){
        scrollY = window.pageYOffset;
    }else if ( window.scrollY ){
        scrollY = window.scrollY;
    }

    var elementDimensions = Element.getDimensions(element);

    var setX = ( my_width  - elementDimensions.width  ) / 2;
    var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;

    setX = ( setX < 0 ) ? 0 : setX;
    setY = ( setY < 0 ) ? 0 : setY;

    element.style.left = setX + "px";
    element.style.top  = setY + "px";

    element.style.display  = 'block';
}

