//variables//
var stageMode 		= 0;
var signupMode 		= 0;
var articleMode 	= 0;
var newcolMode 		= 0;
var userMode		= 0;
var uploadMedia 	= new Array();
var editMedia;
var gridArr 		= new Array();
var gidSpacing 		= 5;
var gridWidth		= 200;
var gridHeight 		= 200;
var mainDiv			= new Array(10,10);
var displayList		= new Array();
var divWidths 		= new Array();
var divHeights 		= new Array();
var stageLength		= 60;
var startOffsetY = 5
var startOffsetX = 7
var stageDirection
var assignment		=0;
var rollArray		= new Array();	
var divs
var sizes
var aboutMode		= 0;



var PaginationClass = new Class({

	initialize: function(el, max) {
		this.element = $(el);
		this.max = max;

		this.historyKey = this.element.id + '-page';
		this.history = HistoryManager.register(
			this.historyKey,
			[1],
			function(values) {
				this.to(parseInt(values[0]));
			}.bind(this),
			function(values) {
				return [this.historyKey, '(', values[0], ')'].join('');
			}.bind(this),
			this.historyKey + '\\((\\d+)\\)');
	},

	by: function(dir) {
		this.to(this.page + dir);
	},

	to: function(page) {
		page = Math.max(Math.min(this.max, page), 1);
		this.page = page;
		this.element.setHTML('Page ', this.page);
		this.history.setValue(0, this.page);
	}

});



window.addEvent('domready', function() {
	//var pagi = new PaginationClass('products', 10);
	
   if (login==true){
   $('signIn').set('html', 'sign out');
   $('signUp').setStyle('visibility', 'hidden');
   }
   
   	$('volgende').addEvent('click', function(){
   	
	});
	
	$('signUp').addEvent('click', function(e){
		e.stop();
		swapSignup();
	});
	$('keywords1').addEvent('change', function(e){
		//alert('l');
		keyChange();
	});
	
	$('signupForm').addEvent('submit', function(e){
		e.stop();
		SignUp();
	});
	$('loginForm').addEvent('submit', function(e){
		e.stop();
		SignIn();
		
	});
	$('submit').addEvent('click', function(e){
		e.stop();
		SignUp();
	});
	
	$('signIn').addEvent('click', function(e){
		e.stop();
		SignIn();
		
	});
	
	if (goTo=='NULL'){
		setStage();
	}else{
		showArticle(goTo)
	}
	
		checkTV();
	
	
	buildGrid(gridWidth, gridHeight)
	
	
});
/*
var myInterval = window.setInterval(function (a,b) {
	if(login==true){
	
		
	}
  myNumber++;
},20000);
*/
function checkTV(){
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		//alert (json.content[2]);
		$('broadcastName').set('html', json.content[1]);
		if (json.content[2]==1){
			$('wdwtv').setStyle('visibility', 'visible');
			var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
				$('tvCanvasInner').set('html', json.tv);
			}}).get({'wdwtv': '1'});	
		}
	}}).get({'broadcastStatus': '1'});
	
	
}
function tvClose(){
	$('wdwtv').setStyle('visibility', 'hidden');
}
function search(){
var zoekterm = $('searchfield').value;
$('article').set('html', 'loading...');
	userMode = 1;
	articleMode = 0;
	assignment = 0
	swapStageOut();
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('article').set('html', json.content);
		//alert (json.content);
}}).get({'showSearch': zoekterm});	

}
function about_Morality(){
var about1="Morality is the year-long leitmotiv of Witte de With. It incorporates a changing constellation of five exhibitions, a discursive web platform, film program, performance cycle, symposium and book. Morality is one of those inflammatory topics, often evoked as being in crisis, about which everybody and every society has an opinion. From the playground to the battlefield, it shapes both thinking and behaviour. This project looks at morality as a total concept through the filter of different art forms. It does not seek to label art or individual artists as being \"moral\" (or indeed \"immoral\". Nevertheless, some of the works presented at Witte de With tackle moral issues head-on. Others provide a more oblique commentary on morally-charged situations. And others present an amoral subjectivity. ";
var about2="As a multifaceted program, Morality seeks to create a space for discussion in our increasingly polarized and moralistic world. <br/>For more information about the program, contributors, contact information and opening hours, please visit the <u><a href=\"http://www.wdw.nl/index.php\" target=\"_blank\">Witte de With website</a></u>.<br/><br/><img src=\"img/sponsors.jpg\">";
$('about1').set('html',about1);
$('about2').set('html',about2);
$('about_title').set('html','<b>About Morality</b>');
}
function about_Web(){
var about1="For Morality, Witte de With's education department has produced this innovative, web platform as an extraordinary tool for engaging our audiences in discussions and debate. Given the multiple and complex intersections between education and the theme, Morality promises to open up an unprecedented and exciting space for a wider and even more amorphous public than usually addressed by contemporary art. This web platform is vital for the production and expansion of the different levels of discourse that Morality intends to provoke. Alongside contributions from Witte de With's staff and invited guests, the audience is encouraged to bring content into the project (through texts, images, video) and to react to other contributions. ";
var about2="The web platform also presents developments and results of education projects as well as artistic processes and discussions prior to the performance cycle, film program and symposium, with the intention to stimulate an intense interaction with our audiences. <br/><br/>For more information, questions or remarks please contact <u><a href=\"mailto:morality@wdw.nl\">morality@wdw.nl</a></u>.";
$('about1').set('html',about1);
$('about2').set('html',about2);
$('about_title').set('html','<b>About the web platform</b>');
}
function about_Terms(){
var about1="These terms govern our relationship with users and others who interact with the Morality web platform. By using or accessing this web platform, you agree to these terms. We do our best to keep the web platform safe, but we need your help to do so. Your privacy is very important to us. We will not share any personal contact details with others. You choose what information you put in your profile, including contact and personal information, pictures, interests, etc. Do not share your password or any other login information. Do not bully, intimidate, or harass any user. Do not do anything unlawful, misleading, malicious, or discriminatory. In short: we respect other people's rights, and expect you to do the same. ";
var about2="We can remove any content or information you post on this web platform if we believe that it violates our terms. We can disable your account if we deem it to be necessary.";
$('about1').set('html',about1);
$('about2').set('html',about2);
$('about_title').set('html','<b>Terms</b>');
}
function about_How(){
var about1=	"The web platform explores the potential of engaging directly with our visitors, and aims at integrating a range of levels and forms of engagement for a diversity of audiences, from discourse to simple observation. That is why five categories of users are distinguished based on their level of engagement:<br/><br/>";
about1+="1. Observers. The activity of visitors browsing the web platform is visualized in an interactive graph by the amount of clicks on specific contributions. ";
about1+="<br/><br/>2. The observed. The web platform continuously filters the feeds of Twitter users worldwide on specific keywords. Although they are unaware of Morality, they still contribute to the project. ";
var about2="3. Participants. Everybody can register, respond to the question of the week, do assignments, create and edit content, comment and take part in discussions. Just log in and join.";
about2+="<br/><br/>4. Guest contributors. Artists, curators, educators, writers, teachers, students are invited by Witte de With to contribute to the web platform, related in the form of projects specially created for Morality.";
about2+="<br/><br/>5. Witte de With. The institution produces projects and programs related to Morality. Every staff member can make his or her projects and related content visible to the audience in a variety of ways, this includes educational projects, lectures, artistic processes, performances, discussions and interviews.";

$('about1').set('html',about1);
$('about2').set('html',about2);
$('about_title').set('html','<b>How it works</b>');
}
function about_Colophon(){
var about1="Witte de With staff<br/>director: Nicolaus Schafhausen<br/>adjunct director: Paul van Gennip<br/>curators: Juan Gaitan, Zo&euml; Gray, Renske Janssen<br/>project coordinator: Ariadne Urlus <br/>education project curator: Belinda Hak<br/>communication, curatorial assistant: Anne-Claire Schmitz<br/>publications: Monika Szewczyk <br/>assistant curator: Eva Huttenlauch<br/>secretary: Ang&ecirc;lique Barendregt, Gerda Brust, Anna Sch&ouml;ning <br/>interns: Justa van den Bulk, Amira Gad, Marijke Goeting, Hessel de Ronde<br/>reception: Erik Visser, Erwin Nederhoff, Hedwig Homoet <br/>technicians: G&eacute; Beckman, Line Kramer <br/><br/>";
var about2="Morality web platform<br/>";
about2+="concept: Marijke Goeting, Belinda Hak, Richard Vijgen<br/>";
about2+="design and programming: <u><a href=\"http://www.richardvijgen.net\" target=\"_blank\">Richard Vijgen</a></u><br/>";
about2+="<br/><span class=\"small\">";
about2+="Press can contact <u><a href=\"mailto:morality@wdw.nl\">morality@wdw.nl</a></u>.<br/>";
about2+="<br/>Witte de With is supported by the City of Rotterdam and the Dutch Ministry of Culture.";
about2+="Witte de With is member of the Comit&eacute; van Roosendaal, a network connecting contemporary art institutes in Northwestern Europe.";
about2+="</span>";

$('about1').set('html',about1);
$('about2').set('html',about2);
$('about_title').set('html','<b>Colophon</b>');
}

function keyChange(){
	
	var pullVal = $('keywords1').value;
	
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
			
		$('pull2').set('html',json.result);
	}}).get({'changeKey': pullVal});	
}
/////////////////////////////////////////STAGE/////////////////////////////////////////
function buildGrid(gWidth, gHeight){
trace (gHeight);
	var row = 0;
	var collumn = 0;
	gridArr.push(new Array())
	for (i=0; i<(gWidth*gHeight); i++){
	gridArr[row].push(0)
	
	if (collumn==gWidth){
		gridArr.push(new Array())
		row++;
		collumn = 0;
	}
	collumn++
	}
	trace (gridArr.length)
}

function scanPos(divWidth, divHeight){

	//trace(divWidth);
	var scanLine 	=  new Array();
	var scanning 	= 1;
	var scanRow 	= 3;
	trace (scanRow);
	var scanCol 	= 0	
	
	var min			= 2000
	var resultLine
	var move		= 0
	var result 
	if (displayList.length>0){
	scanCol = 50;
	}
	
	if (displayList.length==1){
		scanCol = 0;
	}
	if (displayList.length==0){
		
		result = new Array(startOffsetY, startOffsetX)
		draw();
		return result;
	}
	doCounter = 0
	do
	{
	
	if (gridArr[mainDiv[0]+scanRow][mainDiv[1]+scanCol]==0){
	
		if (checkOverlay(mainDiv[0]+scanRow, mainDiv[1]+scanCol, divWidth, divHeight)==0){
		//ER IS GEEN OVERLAY	
			scanLine.push(new Array(scanRow, scanCol));
			scanCol = 0;
			scanRow++;
			if (scanRow==stageLength){
			//alert (scanRow)
					scanning =0
				for (k=0; k<scanLine.length; k++){
					var curVal;
					if(k == stageLength	-1)
					{
					
					curVal = (scanLine[k][1]+1)
					
					}else{
					curVal = scanLine[k][1];
					}
					if (curVal<min){
					min = scanLine[k][1];
					resultLine = k
					}
				}
				for (l=0; l<scanLine.length; l++){
					if (scanLine[l][1]==min){
						if (l<resultLine)resultLine=l;
					}
				}
				//STOP SCANNING
				scanning = 0;
				result = new Array(scanLine[resultLine][0]+mainDiv[0], scanLine[resultLine][1]+mainDiv[1])
				draw();
				trace ('counter'+doCounter)
				return result;
			}
		}else{
		//OVERLAY IS TRUE
		scanCol = 0;
		scanRow++;
		
		}
	}
	scanCol++;
	if (doCounter>25000){
	scanning = 0;
	//alert('error')
	}
	doCounter++
	}
	while (scanning>0)
	
	function draw(){
	//trace ('draw')
	//write to matrix//
		var writeCol	= 0;
		var writeRow	= 0;
		//alert(divWidth*divHeight)
		for (j=0; j<(divWidth*divHeight); j++){
			gridArr[result[0]+writeRow][result[1]+writeCol] = 1;
			
			writeCol++;
			if (writeCol==(divWidth)){
				writeCol = 0;
				writeRow++;
			}
		}
	//end write to matrix//
	
	}
}

function checkOverlay(t, l, w, h){

//return 0;
	//trace ('checking '+t+' '+l+' '+w+' '+h);
	var overCol=0;
	var overRow=0;
	var overlap = 0;
	
	if (t+h>gridHeight){
			//trace ('overflow hoogte')
			overlap = 1;
			return overlap;
		}else if (l+w>gridWidth){
			//trace ('overflow breedte'+l+' '+w)
			overlap = 1;
			return overlap;
		}
	
	
	for (a=0; a<(w*h); a++){
		
		if(gridArr[t+overRow][l+overCol]==1){
		overlap = 1;
		return overlap;
		}
		
		if (overCol==w){
		overCol = 0;
		overRow++;
		}
		overCol++;
		}
		return overlap;
	
}

function setStage(id){

		rollArray = []
		stageLength		= 55;
		if (stageMode==0){
			kind= 'stage'
		}else{
			if (userMode==1){
				kind = 'user'
			}
			if (articleMode == 1){
				kind = 'article'
			}
		}
		
	
		var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		
			$('stage').set('html', json.content);
			
			divs = json.div
			sizes = json.size
			
			makeStage(kind, divs, sizes)
			
		}}).get({'stage': kind, 'id':id});	
		
	
}
function makeStage(kind, divs, sizes){

var breedte=0;

	if (stageMode == 0){
	
			///RESET STAGE//
				displayList=[];
				gridArr=[];
				buildGrid(gridWidth, gridHeight)
				
				
				for (i=0; i<divs.length; i++){
				
				
					
					if (sizes[i][0]){
					divWidth		= Math.floor(sizes[i][0]/5)
					divHeight		= Math.floor(sizes[i][1]/5)
					$(divs[i]).setStyle('width', divWidth*5);
					$(divs[i]).setStyle('height', divHeight*5);
					//infoTop = 0-(divHeight*5)
					//$('info_'+divs[i]).setStyle('margin-top', infoTop); 
					}else{
					
					size = $(divs[i]).getSize();
					trace ('a'+sizes[i][0])
					divWidth		= Math.floor(size.x/5)
					divHeight		= Math.floor(size.y/5)
					}
					coords = scanPos(divWidth, divHeight);
					if (coords[1]+divWidth>breedte)breedte = coords[1]+divWidth;
					y = (Math.random()*500)+150;
					x = Math.random()*800
					$(divs[i]).setStyle('top', (coords[0]*5)+195);
					$(divs[i]).setStyle('left', coords[1]*5);
					
					rollArray.push($(divs[i]));
					div = $(divs[i]);
					displayList.push(div);
					rollArray.push(new Array($(divs[i]).id,0))
					
				}
				if (stageMode==0){
				
					twitterWidth = $('twitter').getStyle('width').toInt();
					$('stageWrapper').setStyle('left', (((950-(breedte*5))+twitterWidth)-(startOffsetX*5))/2);
					
					$('question').setStyle('left', 285);
					$('question').setStyle('top', 194);
					
					wrapperLeft = $('stageWrapper').getStyle('left').toInt();
					
					$('twitter').setStyle('top', 230);//
					$('twitter').setStyle('left', ((wrapperLeft-twitterWidth)+(startOffsetX*5)));//
					//INITIALIZE TWITTER SERVICE
					
					var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
						//alert ('clb'+json.length)
						var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
						if (IE6==true){
							(function(){  
							//twit(json.query, json.length, 0)
							}).delay(1000);	
						}else{
						twit(json.query, json.length, 0)
						}
					}}).get({'twitterData': 's'});		
					
					
						}else{
					}
				}else{
				
				//IF STAGEMODE IS ARTICLE
					
						
					displayList=[];
					gridArr=[];
					buildGrid(100, gridHeight)
					
					breedte = 0
					for (i=0; i<divs.length; i++){
						
						if (sizes[i][0]){
						divWidth		= Math.floor(sizes[i][0]/5)
						divHeight		= Math.floor(sizes[i][1]/5)
						$(divs[i]).setStyle('width', divWidth*5);
						$(divs[i]).setStyle('height', divHeight*5);
						}else{
						size = $(divs[i]).getSize();
						trace ('a'+sizes[i][0])
						divWidth		= Math.floor(size.x/5)
						divHeight		= Math.floor(size.y/5)
						}
						
						coords = scanPos(divWidth, divHeight);
						if (coords[1]+divWidth>breedte)breedte = coords[1]+divWidth;
						y = (Math.random()*500)+150;
						x = Math.random()*800
						$(divs[i]).setStyle('top', (coords[0]*5)+190);
						$(divs[i]).setStyle('left', coords[1]*5);
						if ((coords[1]*5)+(divWidth*5)> breedte)breedte = (coords[1]*5)+(divWidth*5);
						div = $(divs[i]);
						displayList.push(div);
						rollArray.push($(divs[i]));
					
						rollArray.push(new Array($(divs[i]).id,0))
						
					}
					
					$('stage').setStyle('visibility', 'visible');
					$('stageWrapper').setStyle('left',295-breedte);
					//$('question').setStyle('left',0);
					//$('question').setStyle('top',100);
					
				}
				
}
function twit(query, lengthe, state){

if (state == 0){
	aantal = 5;
	align = 'right'
}else{
	aantal = 12;
	align = 'left'
	
}

loc= 'http://search.twitter.com/search.json';
	var myTwitterRequest = new Request.JSONP({
	url: loc,
	data: {
		q:'\"'+query+'\"',
		count: '4',
		rrp: '4'
	},
	noCache: true,
	onComplete: function(myTweets) {
	
	browsertest = myTweets.results.length
	
	if (browsertest>0){
		twitterOutput="";
		for (j=0; j<aantal; j++){
				
				var tweet = myTweets.results[j]
				var twt = tweet.text;
				var rg = new RegExp(query,'i');
				var start = twt.search(rg)
				var str = twt.substring(start).split(' ');
				var output='';
				if (str.length<lengthe)lengte = str.length
				else lengte = lengthe
				
				for (i=0; i<lengte; i++){
				output+=str[i]+' ';
				}
				// DATE
				
				var made = new Date();
				made.parse(tweet.created_at);
				var today = new Date();
				var difference = made.diff(today, 'minute');
			
				twitterOutput+="<div class=\"twitWrap\" style=\"float: "+align+";\"><div class=\"stretch\"><div class=\"twitW\" style=\"float: "+align+";\"><span class = \"twitText\">\"" + output+"...\"</span></div></div><div class=\"stretch\"><div class=\"twitW\" style=\"float: "+align+";\"><span class=\"twitter_date\">"+difference+" minutes ago from <a href=\"\http://www.twitter.com/"+tweet.from_user+" \"target=\"_blank\"><i>"+tweet.from_user+"</i></a></span></div></div></div><br>";
			};
			
				$('insideTwitter').set('html', twitterOutput);
			
			
			
		}else{
			
			var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
				tweets = json.result
				echo = '';
				for (i=0; i<5; i++){
					var twt = tweets[i][0];
					//var rg = new RegExp(query,'i');
					//var start = twt.search(rg)
					//var str = twt.substring(start).split(' ');
					//var output='';
					//if (str.length<lengthe)lengte = str.length
					//else lengte = lengthe
					
					//for (j=0; j<lengte; j++){
						//output+=str[j]+' ';
					//}
					echo+= twt+'<br/>';
				}
				$('insideTwitter').set('html', echo);
			}}).get({'twitterString':query, 'lengte':lengthe});
		}
		}

		}).send();

}

function logoOver(){
$('logoImg').src = "img/wdw_over.gif";
}
function logoOut(){
$('logoImg').src = "img/wdw.gif";
}


function rollOver(div, width, height,type){

for (i=0; i<rollArray.length; i++){
	if (rollArray[i][0]==div)rollArray[i][1] = 1;
	
}
(function(){  
		for (i=0; i<rollArray.length; i++){
			if (rollArray[i][0]==div)
			if (rollArray[i][1]==1){
				if (type=='main')scale = 250/width;
				if (type=='side')scale = 250/width;
				hoogte = alertSize();
				var top = Math.floor($(''+div).getStyle('top').toInt());
				var left = Math.floor($(''+div).getStyle('left').toInt());
				
				if(top-((height*scale)-height)<180){
					newTop = top
					newLeft = left
					stageDirection = div;
				}else{
					Math.floor(newTop = top-((height*scale)-height));
					Math.floor(newLeft = left-((width*scale)-width));
				}
				//alert ($('img_'+div));
				
				newHeight = height*scale;
				newWidth = width*scale
				if (type=='side'){
					if (newHeight>250)newHeight = 250;
				}
				
				$('info_'+div).setStyle('margin-top', 0-(height*scale));
				$('info_'+div).setStyle('visibility', 'visible');
				$(''+div).setStyle('width', newWidth);
				$(''+div).setStyle('height', newHeight);
				$(''+div).setStyle('top', newTop);
				$(''+div).setStyle('left', newLeft);
				$(''+div).setStyle('background-color', '#FFFFFF');
				$(''+div).setStyle('z-index', 100);
				$('img_'+div).setStyle('width', width*scale);
				$('img_'+div).setStyle('height', height*scale);
				
				//$('mouseOver').setStyle('visibility', 'visible');
				//$('mouseOver').setStyle('width', width*scale);
				//$('mouseOver').setStyle('height', height*scale);
				//$('mouseOver').setStyle('top', newTop);
				//$('mouseOver').setStyle('left', newLeft+178);
				//$('mouseOver').setStyle('background-color', '#000000');
				//$('mouseOver').setStyle('z-index', 120);
				size = new Array(width*scale, height*scale)
				sizes[i] = size
				//sizes[i][1] = height*scale
			//	alert(sizes[i][0])
				
				displayList=[];
				gridArr=[];
				buildGrid(gridWidth, gridHeight)
				//alert()
				//makeStage('stage', divs, sizes)
			}
		}
		
			
}).delay(300);			
	

	
	
	
}
function rollOut(div, width, height){
for (i=0; i<rollArray.length; i++){
	if (rollArray[i][0]==div)rollArray[i][1] = 0;
}
(function(){  

	scale = 250/width;
	var top = $(''+div).getStyle('top').toInt();
	var hoogte = $(''+div).getStyle('height').toInt();
	var left = $(''+div).getStyle('left').toInt();
	var breedte = $(''+div).getStyle('width').toInt();
	
	
	if (div==stageDirection){
		origY = 0
		origX = 0
	}else{
		Math.floor(origY = hoogte-height);
		Math.floor(origX = breedte-width);
	}
	trace ('orig'+origY);
	if (origY<0){
	}else{
	//$('mouseOver').setStyle('visibility', 'hidden');
	$('info_'+div).setStyle('visibility', 'hidden');
	$(''+div).setStyle('width', width);
	$(''+div).setStyle('height', height);
	$(''+div).setStyle('top', top+origY);
	$(''+div).setStyle('left', left+origX);
	$(''+div).setStyle('z-index', 0);
	$('img_'+div).setStyle('width', width);
	$('img_'+div).setStyle('height', height);
	
	}
	
	}).delay(300);	
}


function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return (myHeight);
}

////////////////////////////////////////INPUT OUTPUT///////////////////////////////////


function showUser2(name){
	$('article').set('html', 'loading...');
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('article').set('html', json.content);
		//alert (json.content)
	}}).get({'showUser2':name, 'username':name});	
}
function showUser3(name){
	
	$('article').set('html', 'loading...');
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('article').set('html', json.content);
	}}).get({'showUser3':name, 'username':name});	
}
function showUser4(name){
	$('article').set('html', 'loading...');
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		
		
	}}).get({'showUser4':name, 'username':name});	
}
function showUser5(name){
	$('article').set('html', 'loading...');
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('article').set('html', json.content);
	}}).get({'showUser5':name, 'username':name});	
}


function user1(){
	tvClose();
	stageMode = 0;
	$('stage').setStyle('width', 950);
	$('content').setStyle('visibility', 'hidden');
	$('stage').setStyle('visibility', 'visible');
	userMode = 1;
	articleMode = 0;
	assignment = 0
	//swapStageOut();
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('stage').set('html', json.content);
		displayList=[];
		gridArr=[];
		buildGrid(gridWidth, gridHeight)
		divs = json.div
		sizes = json.size
		stageLength		= 45;
		breedte = 0;
		for (i=0; i<divs.length; i++){
			if (sizes[i][0]){
			divWidth		= Math.floor(sizes[i][0]/5)
			divHeight		= Math.floor(sizes[i][1]/5)
			$(divs[i]).setStyle('width', divWidth*5);
			$(divs[i]).setStyle('height', divHeight*5);
			
			}else{
			//alert()
			}
			coords = scanPos(divWidth, divHeight);
			$(divs[i]).setStyle('top', (coords[0]*5)+170);
			$(divs[i]).setStyle('left', coords[1]*5);
			//alert(coords[1]*5)
			div = $(divs[i]);
			displayList.push(div);
			if ((coords[1]*5)+divWidth> breedte)breedte = (coords[1]*5)+divWidth;
		}
		$('stageWrapper').setStyle('left',(950-breedte)/2);
		$('visHeader').setStyle('top', '195px');
		$('visHeader').setStyle('left', '320px');
		
		stageMode = 0;
		$('stage').setStyle('width', 950);
		$('content').setStyle('visibility', 'hidden');
	}}).get({'user1': 's'});	
}
function user2(){
	tvClose();
	$('article').set('html', 'loading...');
	userMode = 1;
	articleMode = 0;
	assignment = 0
	swapStageOut();
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('article').set('html', json.content);
		//alert (json.content);
	}}).get({'user2': 's'});	
}
function user3(){
	tvClose();
	$('article').set('html', 'loading...');
	userMode = 1;
	articleMode = 0;
	assignment = 0
	swapStageOut();
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('article').set('html', json.content);
	}}).get({'user3': 's'});	
}
function user4(){
	tvClose();
	$('article').set('html', 'loading...');
	userMode = 1;
	articleMode = 0;
	assignment = 0
	swapStageOut();
			
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('article').set('html', json.content);
		var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
			twit(json.query, json.length, 1)
		}}).get({'twitterData': 's'});
	}}).get({'user4': 's'});	
}
function user5(){
	tvClose();
	$('article').set('html', 'loading...');
	userMode = 1;
	articleMode = 0;
	assignment = 0
	swapStageOut();
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('article').set('html', json.content);
		//$('stage').setStyle('width', 0);
		//$('stage').setStyle('visibility', 'visible');
		//$('stage').set('html', json.kalender);
		
		//alert(json.calendar);
	}}).get({'user5': 's'});	
}

function deleteCollection(artID){
	var answer = confirm("Are you sure you want to delete this entire collection?")
	if (answer){
		var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
			collectionList();
			setStage()
		}}).get({'deleteCollection': artID});	
	}
	else{
		
	}

}
function deleteMedia(id, stamp){
	var answer = confirm("Are you sure you want to delete this?")
	if (answer){
		var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('newForm').set('html', json.content);
			editCollection(stamp)
		}}).get({'deleteMedia': id});	
	}
	else{
		
	}
	
}
function updateText(id){

	var text = $('newCol').colTextarea.value
	text = text.replace(/'/gi, '&rsquo;');
	/*
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('col_insert').set('html', '&nbsp;');
	}}).get({'editSave': id, 'content':text});
	*/
	new Request.JSON({
  				url: 'php/ajax.edit.php',
  				data: {
				'editSave': id, 
				'content': text
				},
  				method: 'post',
  				onSuccess: function(json){
  				
   					$('col_insert').set('html', '&nbsp;');
   				
  				}
	}).send();
	
	
	
}
function updateVideo(id){
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('col_insert').set('html', '&nbsp;');
	}}).get({'editSave': id, 'content':$('newCol').youtube.value});
}

function textEdit(id, artID){
$('captions').set('html','');
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
	
		text = '<textarea name=\"colTextarea\" id=\"colTextarea\" cols=\"9\" rows=\"5\">'+json.result+'</textarea><br/><div class=\"button_small\"><a href=\"javascript:updateText('+id+')\">update</a></div>';
		
		$('col_insert').set('html', text);
	
	}}).get({'textEdit': id});	
	
}
function videoEdit(id, artID){
$('captions').set('html','');
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		video = 'insert a youtube tag<br/><input name=\"youtube\" type=\"text\" value=\"'+json.result+'\" class=\"form_veld\" size=\"30\" width=\"30\" /><div class=\"button_small\"><a href=\"javascript:updateVideo('+id+')\">update</a></div>';
		$('col_insert').set('html', video);
	
	}}).get({'textEdit': id});	
	
}

function editCollection(id){
	//
	scroll(0,0);
	$('captions').set('html','');
	var jsonRequest = new Request.JSON({url: "php/j_interface.php", onSuccess: function(json){
		$('newForm').set('html', json.content);
		uploadMedia = json.media;
		//alert (uploadMedia);
		editMedia = json.media.length;
		$('pull1').addEvent('change', function(e){
		e.stop();
		keyChange();
	});
		$('newCol').addEvent('submit', function(e){
		e.stop();
		submitUpdate();
	});
	}}).get({'updateForm': id});	
}


function uploadImage(){
	$('postImage').set('send', {onComplete: function(response) { 
			//alert ('response= '+response);
		}});

	$('imageUpload').send();

}

function linkUpdate() {
		if (!swf.uploading) return;
		var size = Swiff.Uploader.formatUnit(swf.size, 'b');
		link.set('html', '<span class="small">' + swf.percentLoaded + '% of ' + size + '</span>');
}


function addContent(type){
	$('captions').set('html','');
	if (type=='image'){
	
	
	
		//img = '<form action=\"php/image.upload.php\" id=\"postImage\" method=\"post\" onsubmit=\"return AIM.submit(this, {\'onStart\' : startCallback, \'onComplete\' : completeCallback})\">';
		
		//img+= '<br/><input type=\"file\" name=\"form[file]\" /><br/>';
		//img+= '<input name=\"description\" type=\"text\" class=\"form_veld\" size=\"24\" width=\"24\" /><br/><br/><div class=\"button_small\"><a href=\"javascript:uploadImage()\">upload</a></div><br/><br/>';
		//img+= '<input type=\"submit\" vaule=\"d\"></form>';
		//alert (img);
		
		img = '<div id=\"demo-portrait\">';
		img+= '<a href=\"#\" id=\"select-0\" title=\"Please upload only images, maximal 2 Mb filesize!\">upload new image</a><div id=\"wait\" style=\"\"></div></div>';
		
		
		
		$('col_insert').set('html', img);
		
		var link = $('select-0');
		var linkIdle = link.get('html');
		
		var swf = new Swiff.Uploader({
			path: 'php/Swiff.Uploader.swf',
			url: 'php/script.php',
			verbose: true,
			queued: false,
			multiple: false,
			target: link,
			instantStart: true,
			typeFilter: {
				'Images (*.jpg, *.jpeg, *.gif, *.png, *.pdf)': '*.jpg; *.jpeg; *.gif; *.png; *.pdf'
			},
			fileSizeMax: 10 * 1024 * 1024,
			onSelectSuccess: function(files) {
				$('wait').set('html', '<img src=\"img/load.gif\">');
				if (Browser.Platform.linux) window.alert('Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');
				log.alert('Starting Upload', 'Uploading <em>' + files[0].name + '</em> (' + Swiff.Uploader.formatUnit(files[0].size, 'b') + ')');
				this.setEnabled(false);
				
			},
			onSelectFail: function(files) {
				alert('Please select an image smaller than 2 Mb.');
			},
			appendCookieData: true,
			onQueue: linkUpdate,
			onFileComplete:function(file){
				// We *don't* save the uploaded images, we only take the md5 value and create a monsterid ;)
				if (file.response.error) {
					alert('Failed Upload', 'Uploading <em>' + this.fileList[0].name + '</em> failed, please try again. (Error: #' + this.fileList[0].response.code + ' ' + this.fileList[0].response.error + ')');
				}else{
					var md5 = JSON.decode(file.response.text, true).hash; // secure decode
					var soort = JSON.decode(file.response.text, true).soort;
					var naam = JSON.decode(file.response.text, true).naam;
					//alert(naam);
					//alert (md5)
					uploadMedia.push(new Array(soort,md5,naam));
					
					//
					updatePreview();
					$('col_insert').set('html', 'click the above buttons to add more content');
					}
				file.remove();
				this.setEnabled(true);
				},
				onComplete: function() {
					link.set('html', linkIdle);
				}
		});
		
		$('select-0').addEvents({
			click: function() {
				return false;
				
				
			},
			mouseenter: function() {
				this.addClass('hover');
				swf.reposition();
			},
			mouseleave: function() {
				this.removeClass('hover');
				this.blur();
			},
			mousedown: function() {
				this.focus();
			}
		});
		
		
		
		$('postImage').addEvent('submit', function(e){
		e.stop();
	});
		
	}else if (type=='text'){
		text = '<textarea name=\"colTextarea\" id=\"colTextarea\" cols=\"9\" rows=\"5\"></textarea><br/><div class=\"button_small\"><a href=\"javascript:submitText()\">add</a>';
		$('col_insert').set('html', '</div><span class=\"small\">to add a link type the full adress including http://</span>'+text);
	}else if (type=='video'){
		video = "<span class=\"small\">insert a youtube url</span><br/><input name=\"youtube\" type=\"text\" class=\"form_veld\" size=\"30\" width=\"30\" /><div class=\"button_small\"><a href=\"javascript:submitVideo()\">add</a></div>";
		$('col_insert').set('html', video);
	}
}
function showHelp(){
window.open("youhelp.html","add youtube","menubar=no,width=430,height=360,toolbar=no");
}
function calendar(){
window.open("calendar.html","add youtube","menubar=no,width=800,height=600,toolbar=no");
}
function submitCaption(listPosition){
var caption = $('captionForm').captionInput.value;
uploadMedia[listPosition][2]=caption;
$('captions').set('html','');
//alert (uploadMedia);
}

function addCaption(listPosition){
	$('col_insert').set('html', '<br/>');
	
	var output="<div class=\"span-2\">add caption</div><div class=\"span-6 last\">";
	if(uploadMedia[listPosition][0]=="img"){
	output+="<form id=\"captionForm\"><input name=\"captionInput\" id=\"captionInput\" type=\"text\" class=\"form_veld\" size=\"30\" width=\"30\" /></form>";
	}else{
	output+="<form id=\"captionForm\"><input name=\"captionInput\" id=\"captionInput\" type=\"text\" class=\"form_veld\" size=\"30\" width=\"30\" value=\""+uploadMedia[listPosition][2]+"\"/></form>";
	}
	output+="<br/><div class=\"button_small\"><a href=\"javascript:submitCaption("+listPosition+")\">add caption</a></div><br/><br/>";
	if(uploadMedia[listPosition][0]=="img"){
		output+="<img src=\"php/phpThumb.php?src=/content/img/"+uploadMedia[listPosition][1]+".jpg&w=150&h=150\">";
	}else{
		output+="<img src=\"img/pdf.gif\">";
	}
	output+="</div>";
	$('captions').set('html',output);
}
function editCaption(listPosition, caption){
	$('col_insert').set('html', '<br/>');
	var output="<div class=\"span-2\">add caption</div><div class=\"span-6 last\">";
	output+="<form id=\"captionForm\"><input name=\"captionInput\" id=\"captionInput\" type=\"text\" class=\"form_veld\" size=\"30\" width=\"30\" value=\""+caption+"\"/></form>";
	output+="<br/><div class=\"button_small\"><a href=\"javascript:submitCaption("+listPosition+")\">add caption</a></div><br/><br/>";
	if(uploadMedia[listPosition][0]=="img"){
	output+="<img src=\"php/phpThumb.php?src=/content/img/"+uploadMedia[listPosition][1]+".jpg&w=150&h=150\"></div>";
	}else{
	output+="<img src=\"img/pdf.gif\">";
	}
	$('captions').set('html',output);
}
function updatePreview(){
//alert('test')
	output="";
	for (i=0; i<uploadMedia.length; i++){
		if(uploadMedia[i][0]=="img"){
			output+="<div class=\"media_item\" style=\"background-image:url('content/thumb/"+uploadMedia[i][1]+".jpg'); background-repeat:no-repeat;\"><a href=\"javascript:addCaption("+i+")\"><img src=\"img/add_caption.gif\"></a></div>";
		}
		if(uploadMedia[i][0]=="text"){
			output+="<div class=\"media_item\" style=\"background-image:url('img/text.gif'); background-repeat:no-repeat\"></div>";
		}
		if(uploadMedia[i][0]=="video"){
			output+="<div class=\"media_item\" style=\"background-image:url('content/thumb/"+uploadMedia[i][1]+".jpg'); background-repeat:no-repeat\"><img src=\"img/youtube.gif\"></div>";
		}
		if(uploadMedia[i][0]=="pdf"){
			output+="<div class=\"media_item\" style=\"background-image:url('img/pdf.gif'); background-repeat:no-repeat\"><a href=\"javascript:addCaption("+i+")\"><img src=\"img/add_caption.gif\"></a></div>";
		}
	}
	/*
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
						//alert ('feedback');
						$('media_list').set('html', output);
						$('wait').set('html', '');
						
	}}).get({'mediaGallery': JSON.encode(uploadMedia)});
	*/
	$('media_list').set('html', output);
						$('wait').set('html', '');
}
function submitVideo(){
	video = $('newCol').youtube.value;
	uploadMedia.push(new Array('video',video));
	updatePreview();
	$('col_insert').set('html', 'click the above buttons to add more content');
}
function submitText(){
	text = $('newCol').colTextarea.value;
	text = text.replace(/'/gi, '&rsquo;');
	uploadMedia.push(new Array('text',text));
	$('col_insert').set('html', 'click the above buttons to add more content');
	updatePreview();
	
}
function collectionForm(update){
	$('captions').set('html','');
	uploadMedia = [];
	var jsonRequest = new Request.JSON({url: "php/j_interface.php", onSuccess: function(json){
		$('newForm').set('html', json.content);
		//alert (json.content);
		
		$('keywords1').addEvent('change', function(e){
		e.stop();
		
		keyChange();
		});
		$('newCol').addEvent('submit', function(e){
		e.stop();
		submitTitle();
		
	});
	}}).get({'newForm': 'set'});	
}
function AssignmentForm(title){
	newCollection()
	uploadMedia = [];
	var jsonRequest = new Request.JSON({url: "php/j_interface.php", onSuccess: function(json){
		$('newForm').set('html', json.content);
		$('newCol').addEvent('submit', function(e){
		e.stop();
		submitTitle();
	});
	}}).get({'newAssignmentForm': 'set', 'naam':title});	
}
function commentVis(id, titel){
	newCollection()
	uploadMedia = [];
	var jsonRequest = new Request.JSON({url: "php/j_interface.php", onSuccess: function(json){
		$('newForm').set('html', json.content);
		
		$('newCol').addEvent('submit', function(e){
		e.stop();
		
		submitTitle();
	});
	}}).get({'newCommentForm': 'set', 'naam':titel, 'id':id});	
}
function collectionList(){
	var jsonRequest = new Request.JSON({url: "php/j_interface.php", onSuccess: function(json){
		$('collections').set('html', json.content);
	}}).get({'updateList': 'set'});	
}
function updateNewView(){
$('collectionView').set('html','test');
}
function submitUpdate(stamp){

	title = $('newCol').col_title.value;
	media = uploadMedia;
	
	key1 = $('newCol').keywords1.value;
	key2 = $('newCol').keywords2.value;
	personal = $('newCol').personal.value;
	if (title==''){
	alert ('please give your collection a title');
	}else{
		if (media.length<1){
			alert ('your collection is empty, please add something');
		}else{
			if (key1=='null' && key2=='null'){
			alert ('please select two keywords from the pulldown menu.');
			}else if (key1=='null' || key2=='null'){
			alert ('please select two keywords from the pulldown menu.');
			}else{
				/*
				var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
					if (json.content=='error'){
						 alert('You have been signed out, please sign in again to upload content.');
					 	signOut();
					}else{
					collectionForm();
					collectionList();
					setStage();
					//alert (json.content)
					}
				}}).get({'editCollection': JSON.encode(uploadMedia), 'title':title, 'key1':key1, 'key2':key2, 'offset':editMedia, 'stamp':stamp});
				*/
				//alert (uploadMedia);
				new Request.JSON({
  				url: 'php/ajax.update.php',
  				data: {
				'collection': JSON.encode(uploadMedia), 
				'title': title,
				'key1':key1,
				'key2':key2,
				'offset':editMedia,
				'stamp':stamp,
				'personal':personal
				},
  				method: 'post',
  				onSuccess: function(json){
  					if (json.content=='error'){
						 alert('You have been signed out, please sign in again to upload content.');
					 	signOut();
					}else{
					collectionForm();
					collectionList();
					setStage();
					//alert (json.debug)
					}
   					
   				
  				}
	}).send();
				
			}
		}
	}
}
function submitTitle(){
	
	title = $('newCol').col_title.value;
	media = uploadMedia;
	key1 = $('newCol').keywords1.value;
	key2 = $('newCol').keywords2.value;
	personal = $('newCol').personal.value;
	
	if (title==''){
	alert ('please give your collection a title');
	}else{
		if (media.length<1){
			alert ('your collection is empty, please add something');
		}else{
			if (key1=='null' && key2=='null'){
			alert ('please select two keywords from the pulldown menu.');
			}else if (key1=='null' || key2=='null'){
			alert ('please select two keywords from the pulldown menu.');
			}else{
				/*
				var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
					collectionForm();
					collectionList();
					setStage();
					if (json.comment=='error'){
					 alert('You have been signed out, please sign in again to upload content.');
					 signOut();
					}else{
					if (key1=='comment'){
						var comment = 'visual comment '+json.content
						var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
						updateComments(key2)	
						$('commentForm').commentarea.value="";
						
						}}).get({'submitComment': comment, 'articleID': key2});
					}
				};
					
				}}).get({'submitCollection': JSON.encode(uploadMedia), 'title':title, 'key1':key1, 'key2':key2});
				*/
				
				new Request.JSON({
  				url: 'php/ajax.post.php',
  				data: {
				'collection': JSON.encode(uploadMedia), 
				'title': title,
				'key1':key1,
				'key2':key2,
				'personal':personal
  				},
  				method: 'post',
  				onSuccess: function(json){
   				//alert(res.content);
   					collectionForm();
					collectionList();
					setStage();
					if (json.comment=='error'){
					 alert('You have been signed out, please sign in again to upload content.');
					 signOut();
					}else{
					if (key1=='comment'){
						var comment = 'visual comment '+json.content
						var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
						updateComments(key2)	
						$('commentForm').commentarea.value="";
						$('captions').set('html','');
						}}).get({'submitComment': comment, 'articleID': key2});
					}
					}
   				
  				}
				}).send();
			}
		}
	}
	
	
}
function newCollection(){
	//$('collections').setStyle('visibility', 'visible');
	collectionForm()
	
	swapNewcol();
}
function viewImage(image, caption){
	$('imgHolder').set('html', '<img src=\"content/img/'+image+'\">');
	$('captionHolder').set('html', caption);
	
}
function viewVideo(tag){
	$('imgHolder').set('html', '&nbsp;<object width=\"455\" height=\"255\"><param name=\"movie\" value=\"http://www.youtube.com/v/'+tag+'&hl=en&fs=1&autoplay=1\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://www.youtube.com/v/'+tag+'&hl=en&fs=1&autoplay=1\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"455\" height=\"255\"></embed></object>');
	$('captionHolder').set('html', '');
	}
function updateComments(id){
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		$('comments').set('html', json.content);
	}}).get({'updateComments': id});	
	
}
function submitComment(id){
	if ($('commentForm').commentarea.value.length>0){
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		updateComments(id)	
		$('commentForm').commentarea.value="";
	}}).get({'submitComment': $('commentForm').commentarea.value, 'articleID': id});	
	}
}
function showArticle(id){
	$('article').set('html', 'loading...');
	tvClose();
	//alert (assignment);
	assignment = 0;
	userMode = 0;
	articleMode = 1;
	stageMode = 1;
	$('stage').set('html', '')	
	$('stage').setStyle('width', 316);
	$('content').setStyle('visibility', 'visible');
	setStage(id);
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(json){
		if (json.type=='assignment')assignment = 1;
		var text = json.content
		//text = text.replace(/'/gi, '&rsquo;');
		$('article').set('html', text);
		addthis.button('#atbutton', {}, {url: "http://www.wdw-morality.nl/?artID="+id, title: "Morality"});
		
	}}).get({'article': id});	
}


function SignUp(){
	
	trace ('submit');
		var email = ($('signupForm').email.value.indexOf(".") > 2) && ($('signupForm').email.value.indexOf("@") > 0)
		if ($('signupForm').username.value.length>0){
			if (email==true){
				if ($('signupForm').password.value.length>5){
					if ($('signupForm').password.value==$('signupForm').repeat_password.value){
					$('signupForm').set('send', {onComplete: function(response) { 
					if (response=='exists'){
						$('signupStatus').set('html', 'username already exists, please choose another')
					}else{
						$('welcome').set('html', response);
						swapSignup();
						login=true;
						$('signIn').set('html', 'sign out');
						$('signUp').setStyle('visibility', 'hidden');
						if (articleMode==1){
							$('commentText').setStyle('height', '0px');
							$('commentField').setStyle('height', 'auto');
						}
					}
					}});
					$('signupForm').send();
					}else{
						$('signupStatus').set('html', 'passwords do not match, please check')
					}
				}else{
					$('signupStatus').set('html', 'password has to be 6 characters or more')
				}
			}else{
				$('signupStatus').set('html', 'please provide a valid email adress')
				
			}
		}else{
			$('signupStatus').set('html', 'please choose a username')
		}
}
function SignIn(){
	var loginData = $('loginForm');
		$('loginForm').set('send', {onComplete: function(response) { 
			if (response!='false'){
				login=true;
				$('welcome').set('html', response);
				$('loginForm').login.value='username';
				$('loginForm').password.value='password';
				$('signIn').set('html', '<b>sign out</b>');
				$('signUp').setStyle('visibility', 'hidden');
				// update personal collections
				collectionList();
				// enable CommentBOX
				if (signupMode==1){
					swapSignup();
				}
				if (articleMode==1){
					if (assignment==1){
					$('assignLogin').setStyle('height', '0px');
					$('assignSubmit').setStyle('height', 'auto');
					}else{
					$('commentText').setStyle('height', '0px');
					$('commentField').setStyle('height', 'auto');
					}
				}
			}else{
				$('loginForm').login.value='';
				$('loginForm').password.value='password';
				$('loginForm').login.focus();
				trace (response);
			}
		}});
		if (login==false){
		$('loginForm').send();
		}else{
		login = false;
		//hide personal collections
		$('collections').set('html', '');
		//alert (newcolMode);
		
		if (newcolMode==1){
			swapNewcol();
		}
		$('signUp').setStyle('visibility', 'visible');
		if (articleMode==1){
			if (assignment==1){
						$('assignLogin').setStyle('height', 'auto');
						$('assignSubmit').setStyle('height', '0px');
						//assignment=0;
						//alert()
					}else{
						$('commentText').setStyle('height', 'auto');
						$('commentField').setStyle('height', '0px');
					}
		}
		killSession();
		}
}
function signOut(){
	login = false;
	$('collections').set('html', '');
	if (newcolMode==1){
		swapNewcol();
	}
	$('signUp').setStyle('visibility', 'visible');
	if (articleMode==1){
		if (assignment==1){
			$('assignLogin').setStyle('height', 'auto');
			$('assignSubmit').setStyle('height', '0px');
			//assignment=0;
			//alert()
		}else{
			$('commentText').setStyle('height', 'auto');
			$('commentField').setStyle('height', '0px');
		}
	}
	killSession();
	
}
function killSession(){
	var jsonRequest = new Request.JSON({url: "php/json.php", onSuccess: function(person){
		$('welcome').set('html', person.a);
		$('signIn').set('html', '<b>sign in</b>');
		
	}}).get({'session': 'destroy'});
}


function swapSignup(){
	if (aboutMode==1)about();
	var morph = new Fx.Morph('sign');
	if (signupMode==0){
    	signupMode=1;
    	$('checkbox1').setStyle('visibility', 'visible');
    	$('checkbox2').setStyle('visibility', 'visible');
    	morph.start({
			height:	'360px'
		});
    }else{
    	signupMode=0;
    	$('checkbox1').setStyle('visibility', 'hidden');
    	$('checkbox2').setStyle('visibility', 'hidden');
    	morph.start({
			height:	'0px'
		});
    }
}

function swapNewcol(){
	if (aboutMode==1)about();
	var morph = new Fx.Morph('new_collection');
	var innerHeight = $('collections').getStyle('height').toInt();
	
	var openSize = 500;
	
	//alert ('o'+openSize)
	if (newcolMode==0){
		if (innerHeight>500){
		openSize = innerHeight
		$('header').setStyle('position','absolute');
		}
    	newcolMode = 1;
    	morph.start({
			height:	openSize
		});
    }else{
    $('header').setStyle('position','fixed');
    	newcolMode = 0;
    	morph.start({
			height:	'0px'
		});
    }
}
function about(){
	if (newcolMode==1)swapNewcol();
	if (signupMode==1)swapSignup();
	var morph = new Fx.Morph('about');
	if (aboutMode==0){
    	aboutMode = 1;
    	morph.start({
			height:	'440px'
		});
    }else{
    	aboutMode = 0;
    	morph.start({
			height:	'0px'
		});
    }
}

function new_collection(){
	
	//alert ('a');
}
function swapStage(){
	if (stageMode==0){
		stageMode = 1;
		$('stage').setStyle('width', 316);
		$('content').setStyle('visibility', 'visible');
		$('stage').setStyle('visibility', 'hidden');
		setStage();
	}else{
		stageMode = 0;
		articleMode = 1;
		$('stage').setStyle('width', 950);
		$('content').setStyle('visibility', 'hidden');
		$('stage').setStyle('visibility', 'visible');
		setStage();
	}
}
function swapStageOut(){
		
		stageMode = 1;
		
		$('stage').setStyle('width', 316);
		$('content').setStyle('visibility', 'visible');
		$('stage').setStyle('visibility', 'hidden');
		setStage();
}
function swapStageIn(){
		
		
		stageMode = 0;
		$('stage').setStyle('width', 950);
		$('content').setStyle('visibility', 'hidden');
		$('stage').setStyle('visibility', 'visible');
		setStage();
}
function home(){
	if (tv!='NULL'){
		checkTV();
	}
	$('article').set('html', '');
	$('stage').set('html', 'loading...');
	swapStageIn();
	if (newcolMode==1){
		swapNewcol()
	}
	if (aboutMode==1){
		about();
	}
}
function trace(string){
	new Element('div', {'html': string}).inject($('console')); 
}
