///////////////////
// ACCOUNT LOGIN/REGISTER/CONFIRM/VERIFY


function logIn(){
	$('_login')._password.value=SHA1($('_login').password.value);
	$('_login').password.value='';
	notify('verifying log-in',10000);
	$('_login').request({
		onSuccess:function(a){
			$('_log_load').update(a.responseText);
		}
	})
	return false;
}
function register(x,y){
	x = $(x)
	if(!y)var y = x.up();
	if(x.password.value!=x.repass.value){
		x.password.value='';
		x.repass.value='';
		x.password.focus();
		return notify('Password Mismatch! Please Re-enter your passwords in the Registration form',10000);
	}
	x._password.value=SHA1(x.password.value);
	x.repass.value='';
	x.password.value='';
	load(x,y,'Initializing Registration','appear')
	return false;
}
function logPass(){
	$('_password')._password.value=SHA1($('_password').password.value);
	$('_password').password.value='';
	notify('Re-AuthoriZing Account',10000);
	$('_password').request({
		onSuccess:function(a){
			$('_log_load').update(a.responseText);
		}
	})
	return false;
}
function logSuccess(){
	Account.id = true;
	jsonAccount();
	$('_login').hide();
	$('_register').hide();
	$('_register_tab').hide();
	$('_password').hide();
	$('_logout').show();
	peopleLoad();
	}
function logSwitch(element) {
	new Effect.ScrollTo('_login',{ duration: .5,afterFinish: function (){
		tabOpen('_login');
		$('_login').reset();
		$('_login').email.focus();
		$('_password').hide();
		
		}})
	}
function logConfirm(){
	var p = prompt('Your session has timed out. Please re-enter your password:');
	if(p=='')return false;
	p = md5(p);
	new Ajax.Request('/accounts/confirm',{
		method: 'get',
		parameters:'password='+p,
		onSuccess:function(it){
			$('_logs').update(it.responseText);
			}
		})
	}

function logOut(){
	new Ajax.Request('/accounts/logout',{
		onSuccess:function(){
			window.location.reload(true);
			
			}
		})
	}

////////////////////\\/////////
//////// TALK LEVEL
function speak(x,y){
	if(Account.id){
		load(x,y);
		x.reset();
		return false;
	}
	notify('You must be logged in to do that!')
	logSwitch();
	
	return false;
	
	
}



//////////////////////////
/// PROJECT LEVEL CORE ///

var meta;
var metaTime;
function metaClear(){
	clearTimeout(metaTime);
	$$('#_directory ._meta').each(function(x){x.hide()});
}
function metaStart(x){
	meta=x;
	metaTime = setTimeout('meta.appear({duration:.3})',500);
}


function jsonAccount(){ new Ajax.Request('/json/account',{ onSuccess:function(a){ Account = a.responseJSON; } } ); }
function jsonPublication(x){ new Ajax.Request('/json/publiction/'+x,{ onSuccess:function(a){ Publication = a.responseJSON; } } ); }
function jsonPage(x){ new Ajax.Request('/json/page/'+x,{ onSuccess:function(a){ Page = a.responseJSON; } } ); }

function peopleLoad(){
	load('/entities/people',$('_people'));
	load('/entities/people_speak',$('_people_speak'));
	$('_people').onclick=function (){
		$('_people_select').toggle();
	}
}
function personSelect(x){
	$('_person').update($(x).firstChild.nodeValue);
	load(x);
	$('_people_select').hide();
	return false;
}


function person(){
if(!A.id)notify('You must be logged in to do that!')
}

var notifyTime=null;
function notify(x,y){ // handles notifications
	clearTimeout(notifyTime);
	var a = $('_notify')
	if(!y)y=3000;
	if(x){
		a.update(x);
		a.show();
		setTimeout("$('_notify').update().hide()",y);
	} else {
		a.update();
		a.hide();
	}
	return false;
}

function load(x,y,z,e){ // handles submissions of forms, and ajax loads
	if(!$(x)){
		to(x,y,z,e);
	} else if($(x).tagName.toLowerCase()=='form'){
		return go(x,y,z,e);
	} else if($(x).tagName.toLowerCase()=='a') {
		to(x.href,y,z,e);
	} 
	
	return false;
}

function go(x,y,z,e){
	if(!z)z='Loading...'
	notify(z,10000);
	$(x).request({
		onSuccess:function(a){
			notify('Complete',400); // cancel notify
			$(y).update(a.responseText);	
			if(!$(y).visible()){
				if(e)y[e]({duration:.2});
				else $(y).show();
			}
		}
	});
	return false;
}

function to(x,y,z,e){
	if(!z)z='Loading...'
	notify(z,10000);
	new Ajax.Request(x,{
		onSuccess:function(a){
			notify('OK...',400); // cancel notify
			$(y).update(a.responseText);
			if(!$(y).visible()){
				if(e)y[e]({duration:.2});
				else $(y).show();
			}	
		}		
	})
	return false;
}


function coreShow(x){
	$('_project').hide();
	$('_stuff').hide();
	$('_editor').hide();
	if(x)$(x).appear({duration:.2});
	else $('_project').appear({duration:.2});

}

function tab(x,y,z,sh,hd){ // x is the selected tab (this), y is the element to open and z is the parent node in which tabs are kept
	x = $(x);
	y = $(y);
	z = $(z);
	if(!z)z = x.up();// if not z, get the parent element of the x tab
	if(!x.hasClassName('_tab'))var t = x.tagName.toLowerCase()
	else var t = '._tab'
	var a = $(z).select(t);
	if(x.hasClassName('_selected')){
		a.each(function(b){ b.removeClassName('_selected'); })
		if(y){
			if(hd)y[hd]({duration:0.3});
			else y.hide();
		}
		x.addClassName('_closed')
		return false;
	} else if(x.hasClassName('_closed')){
		a.each(function(b){ b.removeClassName('_selected'); })
		if(y){
			if(sh)y[sh]({duration:0.3});
			else y.show();
		}
		x.removeClassName('_closed')
		x.addClassName('_selected')
		
		return false;
	}
	a.each(function(b){ b.removeClassName('_selected'); })
	x.addClassName('_selected')
	//y.hide();
	if(y){
		if(x.href||x.action)load(x,y,null,sh); // fill it with the tab uri if there is one
		else {
			if(sh)y[sh]({duration:0.3});
			else y.show();
		}
	}
	return false;
}


//////////////////////////
/// STUFF  HANDLING!!! ///


/////////
//// following gets the panel of forms for making changes from stuff
function stuffPanel(x,y){
	$$('._panel').each(function(m) { 
		if(!m.hidden){
		m.remove()
		}
	});
	var x = $(x).up(); //get the tab list div
	x.insert({ 'after':'<div class="_panel"></div>' })
	load(y,x.next(),'Loading...')

	}


function stuff(x){ // x the stuff identity
	if(!Account.id)return notify('You have to be logged in for that.');
	
	if($('_stuff').visible()){
		coreShow();
	} else {
		coreShow('_stuff');
		
	}
	tab('_stuff_tab'); // toggle stuff tab
	

	if(x||$('_stuff_tabs').select('._tab._selected').length==0)return stuffLoad(x)
	

}



function stuffLoad(x){
	if(!x){  // get the right stuff...
		if($('_stuff_tabs').select('._tab._selected').length>0)x = $('_stuff_tabs').select('._tab._selected')[0].id.replace(/_stuff_tab/i,'').replace(/_/i,'');
		else if($('_stuff_tabs').select('._tab').length>0)x = $('_stuff_tabs').select('._tab')[0].id.replace(/_stuff_tab/i,'').replace(/_/i,'');
	}
	
	$('_stuff_load').select('._loader').each(function(b){ b.hide(); })
	
	//tabOpen('_stuff')
	var a = $('_'+x+'_stuff');  // get the stuff_load div that holds this stuff
	if(!a){  // if it doesn't exist, create it, and load it with stuff...
		$('_stuff_load').insert('<div id="_'+x+'_stuff'+'" style="display:none;" class="_loader"></div>')
		progress('_'+x+'_stuff');
	} else {
		clearTimeout(stuffload)
		$('_'+x+'_stuff_tab').addClassName('_closed');
	}
	return tab('_'+x+'_stuff_tab','_'+x+'_stuff','_stuff_tabs');

}
	
function stuffReLoad(){
	var a  = $('_stuff_tabs').select('._tab._selected')[0];	
	$(a.id.replace(/_tab/i,'')).remove();
	a.removeClassName('_selected')
	a.onclick();
	}


var stuffload

function progress(x){  // runs until x__stuff is not empty .. after update from load

	var a = $('_stuff_status').down();
	if($(x).empty()){
		a.firstChild.nodeValue = "* "+a.firstChild.nodeValue
		stuffload = setTimeout('progress("'+x+'")',5);
		if(a.firstChild.nodeValue.length>200)a.firstChild.nodeValue='reload';
	} else {
		clearTimeout(stuffload)
		a.firstChild.nodeValue='reload';
	}

}


var SelectElement;
function selector(x,y,z){ // select load, element to load, elament to fill
	$$('_selector').each(function (x){ x.update().hide() })
	if(!z)z = $(x).next();
	SelectElement = y;
	z.show();
	load(x,$(z),'Select...','appear');
	return false;
}
function selectOne(x,y){ // x is the element selected, y is _selector element;

	if(SelectElement)SelectElement.value=$(x).down().value;
	$(SelectElement).next().firstChild.nodeValue=$(x).firstChild.nodeValue;
	y.update().hide();
}


function centerWindow(element) {
     if($(element) != null) {
          if(typeof window.innerHeight != 'undefined') {
               $(element).style.top = Math.round(document.viewport.getScrollOffsets().top +  ((window.innerHeight - $(element).getHeight()))/4)+'px';
               $(element).style.left =  Math.round(document.viewport.getScrollOffsets().left + ((window.innerWidth - $(element).getWidth()))/4)+'px';
          } else {
               $(element).style.top =  Math.round(document.body.scrollTop + (($$('body')[0].clientHeight - $(element).getHeight()))/4)+'px';
               $(element).style.left = Math.round(document.body.scrollLeft +  (($$('body')[0].clientWidth - $(element).getWidth()))/4)+'px';
          }
     }
}

//////////////////////////
/// MAP ///


function GMapLoad() {
google.load("maps", "2", {"callback" : Gmap});
}

function Gmap(){
	var map = new google.maps.Map2(document.getElementById("map"));
	new Ajax.Request('?action=stuff&switch=get_lat_lon_json',{
			onSuccess:function(it){
				var a =it.responseJSON
				if(!a.latitude)var a = google.loader.ClientLocation
				if(a.latitude) { 
					var center = new google.maps.LatLng(a.latitude,a.longitude)
					map.setCenter(center,13); 
					$('account_lat').value=a.latitude
					$('account_lon').value=a.longitude
					} else { 
					var center = new google.maps.LatLng('38.563','-121.76')
					map.setCenter(center,10);
					$('account_lat').value=a.latitude
					$('account_lon').value=a.longitude
					}
				
				map.addControl(new GMapTypeControl());
				map.addControl(new GSmallMapControl());
				
				var marker = new GMarker(center, {draggable: true});
				GEvent.addListener(marker, "dragend", function() {
					var point = marker.getPoint();
					
					$('account_lat').value=point.lat()
					$('account_lon').value=point.lng()
					});
				map.addOverlay(marker);
						
				
				
				}
			
				
			})
	
	}



//////////////////////////
/// EDITOR  HANDLING!!! ///

function editor(x,y){
	tab('_editor_tab');
	if($('_editor').visible()){
		coreShow();
		return false;
	}
	coreShow('_editor');
	
	return editorLoad(x,y)
}
function editorLoad(x,y){
	if(!x)x='basic_page';
	load('/editors/'+x+'/'+y,'_editor_load');
	return false;
}








//// NNNEDS major REWREITES!!!!





function closeIt(x,y,z){
	$(x).remove();
	var a = z || '_selected';	
	if(y)y.removeClassName(a)
	}

function minimize(x,y,z){
	x.remove();
	var a = z || '_selected';	
	if(y)y.removeClassName(a)
	}

function stuffAble(x){
	if(x.checked){
		$(x.parentNode).getElementsBySelector('input').each(function(it){it.enable()})
		} else {
		$(x.parentNode).getElementsBySelector('input').each(function(it){it.disable()})
		}
	$(x).enable()
	}


function gear(x){
	if(x)$(x).update('<img class="_gear" src="gear1.gif" />');
	}



////////////////////// DIRECTORY STUFF!!!!!!!!!
////////////////////// DIRECTORY STUFF!!!!!!!!!
////////////////////// DIRECTORY STUFF!!!!!!!!!
////////////////////// DIRECTORY STUFF!!!!!!!!!
////////////////////// DIRECTORY STUFF!!!!!!!!!


function direct(){
	if($('_directory').visible()){ hideDir(); } else { showDir(); }
}
	
function hideDir(){
	$('_directory').fade({duration:.3});
	$('_directory_x').removeClassName('_s');
	$('_directory_x').down().firstChild.nodeValue='menu';
//	$('_page_box').style['margin'+D.pageMargin]=0;
}
function showDir(){
	$('_directory').appear({duration:.3});
	$('_directory_x').addClassName('_s');
	$('_directory_x').down().firstChild.nodeValue='hide';
//	$('_page_box').style['margin'+D.pageMargin]=D.width+D.unit;
}

var t1; // timeout for scrolling directory
var t2; // timeout for the scrolling navigation


function scrollDirectory(){ 
	//if(!Settings.bigMenuScrolls)return;
	var projH = $('_publication').getHeight(); // height of page/project
	var scrollOff = document.viewport.getScrollOffsets()[1] // scroll offset of viewport
	if(scrollOff>projH)return false; // if offset of viewport is greater than project height, do nothing
	var dirH = $('_directory_hold').getHeight();  // current height of directory
	var dirOff = $('_directory_hold').positionedOffset()[1]; // offset of directory
	if(scrollOff<dirH&&dirOff==OriginalOff)return false;
	
	var Offset=0;  // offset
	var SubOff=0;  // offset
	var SubOff = $$('#_directory_load a._s')[0].positionedOffset()[1]
	
	
	
	var DistOff = scrollOff-dirOff; // the difference between scroll offset and directory offset

	if(DistOff<0){  // the directory is below the page... move it up
		Offset=scrollOff-SubOff;
		if(scrollOff<OriginalOff+(dirH/2)) { Offset=OriginalOff }
		else if(DistOff+dirH>0)return;
		
		
	} else if( scrollOff>dirH+dirOff ) { // else if scroll offset is greater than direcory offset plus height
		if(projH-scrollOff<=dirH)Offset=projH-dirH; // if projectpage minus scroll height is less or equal directory height, then subtract difference 
		else Offset=scrollOff-SubOff; 
	} else {
		return;
	}
	
		
	scrollAction(Offset,'_directory_hold')
	
}

function scrollNav(){ // Scrolls Top Navigation buttons after a delay
	//if(!Settings.bigMenuScrolls)return;
	var projH = $('_publication').getHeight(); // height of publication
	var scrollOff = document.viewport.getScrollOffsets()[1] // scroll offset of viewport
	if(scrollOff>projH)return false; // if offset of viewport is greater than publication height, do nothing
	
	var Offset=0;  // offset
	Offset=scrollOff; 
	
	if(scrollOff<OriginalOff)Offset=OriginalOff;

	scrollAction(Offset,'_nav_top_hold')
}

function scrollAction(a,b,c){
	new Effect.Fade(b, { duration: .1, afterFinish: function () {
		new Effect.Move(b, { x: 0, y:a, mode: 'absolute',duration:.1, afterFinish: function () {
			new Effect.Appear(b, { duration: .3 });
		}});
	} });
}

var OriginalOff
function directory(){ // main directory handler
	OriginalOff = $('_directory_hold').positionedOffset()[1];
	Event.observe(window,'keydown', function (e){ 
		var code;
		if (!e) var e = window.event;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		if(code==37){ Last(); }
		if(code==39){ Next(); }
		 });
	Event.observe(window, 'scroll', function() { 
		if(t1)clearTimeout(t1); 
		t1 = setTimeout('scrollDirectory()',1000);// Scrolls the Directory when the page scrolls, after a delay
		if(t2)clearTimeout(t2); 
		t2 = setTimeout('scrollNav()',500);
		
		})
	//load($('_direct_form'),'_directory_load');
	Dir.load();
}

Dir = new Object;

Dir.load = function (){
	$$('#_directory_load ._publication').each(function(x){
		x.onmouseover=function (){ metaStart( x.down()); }
		x.onmouseout=function (){ metaClear(); }
		
		})
	$$('#_directory_load ._publication a').each(function(x){
		x.onclick=function(){return false;}
		x.onmousedown=function(){
			page(this);
			Dir.navigate(this);
			collectPublication($(this).up().next());
			}
		})
	
	//Dir.select();
	Dir.toggle();

// load first ...
	if(Project.page_id)return;
	if($$('#_directory_load ._publication._s').length>0){
		$$('#_directory_load ._publication._s')[0].down().onmousedown();
	} else {
		$$('#_directory_load ._publication a')[0].onmousedown();
	}
}
//Dir.collect = function (){}


function collectPublication(x){
	if((x)&&x.hasClassName('_o')){
		x.next().addClassName('_s');
		if(Dir.col(x.next())){
			if(!x.next().visible()){
				x.next().blindDown({
					duration:.3,
					afterFinish: collectNavigate
					})
			} else {
				collectNavigate()
			}
		}
	}
}

function collectNavigate(){
	var a;
	if($$('#_directory_load ._publication._s a ._title').length==0){
		a = $$('#_directory_load ._collection._s a._first');
		if(!a.length>0)a = $$('#_directory_load ._collection._s a');
	}
	Dir.navigate(a[0])
	
}

Dir.collect = function (){
	
	
	
	$$('#_directory_load ._collection a').each(function(x){
		x.onclick=function(){return false;}
		x.onmousedown=function(){
			page(this);
			collectPage($(this).up().next());
			Dir.navigate(this);
			}
		})
	
	//Dir.toggle();
	
}

function collectPage(x){
	if((x)&&x.hasClassName('_o')){
		if(!x.next().visible()){
			x.next().blindDown({duration:.3})	
		}
	}
}

Dir.toggle = function (){
	
	$$('#_directory_load ._o').each(function(x){
		x.onmousedown=function(){
			if(Dir.col($(this).next())){	
				if(!$(this).next().visible())$(this).next().blindDown({duration:.3})
				else $(this).next().blindUp({duration:.3})
				
				}
			}
			//alert(x.previous().down().next())		
		
		})
}

Dir.col = function (a,b){
	if(a.down().hasClassName('_collect')){

		notify('Collecting Pages...',10000);
		new Ajax.Request(a.down().href,{
		onSuccess:function(m){
			notify('Pages Loaded',500); // cancel notify
			a.update(m.responseText);
			a.blindDown({
				duration:.3,
				afterFinish: collectNavigate

			
			});
			
		}		
	})
	return false;
	}
	return true;
}




Dir.select=function(){
	var g = $$('#_directory_load a._s')[0];
	if(g.length==0)g =  $$('#_directory_load a')[0];
	Dir.navigate(g)
}


Dir.navigate = function (g){
	$$('#_directory_load ._s').each(function(x){ x.removeClassName('_s'); })
	var a = g.up();
	g.addClassName('_s');
	a.addClassName('_s');
	if(a.next()&&a.next().hasClassName('_o'))a.next().addClassName('_s');
	while(a.id!='_directory_load'){
	
		if(a.hasClassName('_collection')){
			if(!a.visible())a.blindDown({duration:.5})
			a.previous().addClassName('_s');
			a.previous().previous().addClassName('_s');
			}
		a=a.up();
	}
	$$('#_directory_load ._collection').each(function(x){
		if(x.previous()&&!x.previous().hasClassName('_s')&&x.visible())x.blindUp({duration:.3});
	});
	
	return false;
}




function Last(){
	navigate(-1);
	}

function Next(){
	navigate(1);
	}

function navigate(z){
	if(!z)z=1;
	var i=0;
	var a =$$('#_directory_load a')
	var f=a[0];
	a.each(function(x){
		
		if(x.hasClassName('_s')){
			if(i+z<0)f=false;
			else f = a[i+z];
			
			}
		i++;
	})
	if(!f)return false;
	if(f)return f.onmousedown();

}


////////
function makeFlip(){
	$$('#_directory_load ._flip').invoke('remove');
	var a = $$('#_page .page');
	var a = $$('#_page .page');
	if(a.length==0)return;
	var i = 0
	var htm = '';
	a.each(function(x){
		if(i==0){
			x.show().addClassName('_s');
			if(x.title)var txt = x.title;
			else var txt = 'Page 1';
			$$('#_directory_load a._s')[0].insert({bottom:'<div class="_title _flip">'+txt+'</div>'});
			
		} else {
			x.hide().addClassName('_x');
			var j=i+1;
			if(x.title)var txt = x.title;
			else var txt = 'Page '+j;
			htm+='<div class="_page"><a onmousedown="Dir.navigate(this);Flip('+i+')">'+txt+'</a></div>';
		}
		i++;
	})
	$$('#_directory_load a._s')[0].up().insert({after:'<div class="_o _flip"><span>O</span></div><div class="_collection  _flip">'+htm+'</div>'})	
	//$$('#_page .page')[0].addClassName('_s').appear({duration:.3});
	//$$('#_directory_load a._s')[0].up().next().next().down().down().onmousedown();
}
function Flip(x){
	var b = $$('#_page .page._s');
	if(b.length>0)b[0].fade({duration:.3}).addClassName('_x').removeClassName('_s');
	if(!x)var a = $$('#_page .page')[0];
	else var a = $$('#_page .page')[x];
	if(!a)return false;
	//alert(x)
	a.appear({duration:.3}).addClassName('_s').removeClassName('_x');
	//a.removeClassName('_s');


}

function page(x,y){

	var url='/pages/page/';
	if(!isNaN(parseFloat(x)))url='/pages/page/'+x;
	else if(x.href)url=x.href;
	else if(x)url = x;
	if(y)url=url+'/'+y;
	//load(x,'_page');
	
	notify('Loading Page...',10000);
	$('_foot').hide();
	new Effect.ScrollTo('_account',{ duration: .3, afterFinish: function (){
		new Ajax.Request(url,{ onSuccess:function(it){
			notify('Preparing Page',3000);
			$('_page').fade({ duration: .2, afterFinish: function () {
				stylesheet(2,url.replace(/\/page\//,'/css/'));
				$('_page').update(it.responseText);
					makeFlip();
				$('_page').appear({
					duration: .3,
					afterFinish: function () {
						notify('Page Loaded',500);
						$('_foot').show();
					} 
				});
			}})
		}})
	}})
	return false;

}

function stylesheet(x,y) { // update stylesheet #x
	$$('link')[x].href=y;
}



function stylesheet_x(x,y) { // update stylesheet x
	var a =document.createElement("link")
	var b = $$('link')[x];
	a.setAttribute("rel", "stylesheet")
	a.setAttribute("type", "text/css")
	a.setAttribute("href", y)
	b.up().replaceChild(a, b);
}





