function randOrd(){
	return (Math.round(Math.random())-0.5); 
}

function arrowToggle(t) {
	var toggler = t;
	if(toggler.hasClassName('on')) {
		toggler.removeClassName('on');
		toggler.addClassName('off');
	}else{
		toggler.removeClassName('off');
		toggler.addClassName('on');
	}
	toggler.siblings().each(function(sib) {
		if(sib.hasClassName('toggleable')) {
			sib.toggle();
		}
	});
	if(toggler.hasClassName('view-comments')){
		if(slideshowRunning==true) { 
			slideshowRunning = false;
		}	else if (slideshowRunning==false) {
			slideshowRunning = true;
		}
		adjustPageHeightForRightColumn();
	}
}

function zoomIn(button, newWidth, newHeight) {
	button.siblings().each(function(sib) {
		if(sib.hasClassName('zoom-window')) {
			var preZoomWidth = sib.firstChild.width
			if(preZoomWidth <= 535) {
				//new Effect.Scale(sib.firstChild, 200, {scaleFromCenter: true, duration: .3});
				var preZoomHeight = sib.firstChild.height
				var newX = (preZoomWidth - newWidth)/2
				var newY = (preZoomHeight - newHeight)/2
				sib.firstChild.morph('width:' + newWidth + 'px; height:' + newHeight + 'px;', {duration: 0.3});
				new Effect.Move(sib.firstChild, { x: newX, y: newY, mode: 'absolute', duration: .3});
				sib.firstChild.drag = new Draggable(sib.firstChild, {ghosting: false});
				sib.addClassName('move-cursor');
				zoomed++;
			}
		}
	});
}

function zoomOut(button, originalWidth, originalHeight) {
	button.siblings().each(function(sib) {
		if(sib.hasClassName('zoom-window')) {
			var preZoomWidth = sib.firstChild.width
			if(preZoomWidth > 535){
				//new Effect.Scale(sib.firstChild, 50, {scaleFromCenter: true, duration: .3});
				sib.firstChild.morph('width:' + originalWidth + 'px; height:' + originalHeight + 'px;', {duration: 0.3});
				new Effect.Move(sib.firstChild, { x: 0, y: 0, mode: 'absolute', duration: .3});
				zoomed--;
				sib.firstChild.drag.destroy();		
				sib.removeClassName('move-cursor');
			}
		}
	});
	
}

function proceduralDrag(){
	new Draggable('box-grid-procedural',{
	  snap: function(x,y) {
	    return[
	      x<100 ? (x > 0 ? x : 0 ) : 100,
	      y<50 ? (y > 0 ? y : 0) : 50];
	  },
	  revert:true
	});
}

function observeToggles() {
	$$('.toggler').each(function (t){
		t.stopObserving('click');
		t.observe('click', function() { arrowToggle(t) });
	});
}

function observeZooms() {
	$$('.zoom-in-button').each(function(button){
		button.stopObserving('click');
		button.observe('click', function() { zoomIn(button) });
	});
	$$('.zoom-out-button').each(function(button){
		button.stopObserving('click');
		button.observe('click', function() { zoomOut(button) });
	});
}

function observeHovers() {
	$$('.project').each(function(proj){
//		project.stopObserving('mouseover');
		proj.observe('mouseover', function(p) { 
			proj.down('.project-infos').appear({duration:0});
		});
		proj.observe('mouseout', function(p) { 
			proj.down('.project-infos').hide();
		});
	});
}
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 updateGreenWindowLocation(usingParams,x,y,window) {
	if((!disableUpdateGreenWindowLocation) && (windowOpen==1)){
		var offset = Element.positionedOffset($('green-window'))
		var newValue = offset.left + 'x' + offset.top + 'x' + windowOpen
		createCookie('announcement', newValue, 20);
		//$('green-window-content').insert(document.cookie);
	} else {
		if(usingParams){
			var newValue = x + 'x' + y + 'x' + window;
			createCookie('announcement', newValue, 20)
		}
		disableUpdateGreenWindowLocation = false;
	}
}

function minimizeGreenWindow() {
	$('green-window-bg').toggle();
	
	if(windowOpen == 1){
		$('green-window').removeClassName('open');
		$('green-window').addClassName('closed');
		windowOpen = parseInt(windowOpen) * -1;
		updateGreenWindowLocation();
		disableUpdateGreenWindowLocation = true;
		//calculate left distance by getting fixed-page width and subtracting right distance from it
		distanceRight = parseInt($('buttons-fixed-page').getStyle('width')) - 241 + ieAdjust//=width of green window + 15px
		
		//new Effect.Move('green-window', { x: distanceRight, y: -9, duration: 0.3, mode: 'absolute' });
		//$('green-window').setStyle('left:auto;right;40px;');
		new Effect.Morph('green-window', {
		  style: 'left:' + distanceRight + 'px;top:-9px;margin-top:0;margin-left:0;', // CSS Properties
		  duration: 0.3 // Core Effect properties
		});
		
	} else if(windowOpen == -1){
		var pos = readCookie('announcement')
		xY = pos.split('x')
		x_pos = parseInt(xY[0]) 
		y_pos = parseInt(xY[1])
		$('green-window').removeClassName('closed');
		$('green-window').addClassName('open');
		new Effect.Move('green-window', { x: x_pos, y: y_pos, duration: 0.3, mode: 'absolute' });
		windowOpen = parseInt(windowOpen) * -1;
		disableUpdateGreenWindowLocation = true;
		updateGreenWindowLocation(true,x_pos,y_pos,windowOpen);
	}
}
function writeCookie(name, value_as_a_string) {
	var nameEQ = name + "=";
	var eq = document.cookie.indexOf(nameEQ) + nameEQ.length
	var afterEQ = document.cookie.substring(eq, document.cookie.length)
	var semiColPosition = afterEQ.indexOf(';')
	if (semiColPosition == -1) {
		var updatedCookie = document.cookie.substring(0, eq) + value_as_a_string + ';'
	} else {
		var afterVal = afterEQ.substring(semiColPosition, afterEQ.length)
		var updatedCookie = document.cookie.substring(0, eq) + value_as_a_string + afterVal
	}
	updatedCookie = updatedCookie + '; path=/'
	deleteCookie(name)
	document.cookie = updatedCookie
}

function deleteCookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function checkActiveMenus(sectionWithHash){
	$$('.menu', '#admin-menu-bar').each(function(menu){
		menu.select('a').each(function(a){
			var hashLocationInHref = a.href.indexOf('#');
			if((a.href == window.location) || (a.href.substr(hashLocationInHref) == sectionWithHash)) { 
				a.addClassName('active') 
			} else if(a.hasClassName('active')){
				a.removeClassName('active')
			}
		});
	});
}

function annonces(){	
	var announcements = $('green-window').select('.annonce')
	announcements.each( function(a) {
		if (a.getStyle('display') == "block") {
			var thisObj = this;
			var moveTo = announcements.indexOf(a) + 1
			if (moveTo >= announcements.size()) moveTo = 0
			Effect.Fade( a, {duration:.2, queue: 'front'})
			var nextElem = announcements[moveTo]
			var nextText = announcements[moveTo].innerHTML
			Effect.Appear( nextElem, {duration:.2, queue: 'end'} )
			idArray = nextElem.id.split('_')
			ticInterval = parseInt(idArray[3])
		  nextTic = setTimeout(function() { thisObj.annonces(); }, ticInterval);	
		}
	})
}

function ticker(){
	var notes = $('project-notes').select('.note')
	notes.each( function(note) {
		if (note.getStyle('display') == "block") {
			var thisObj = this;
			idArray = note.id.split('_')
			noteTicInterval = parseInt(idArray[3])
		  nextTic = setTimeout(function() { thisObj.tickNote(); }, noteTicInterval);	
		}
	})
}

function tickNote(){
	var notes = $('project-notes').select('.note')
	notes.each( function(note) {
		if (note.getStyle('display') == "block") {
			var thisObj = this;
			var moveTo = notes.indexOf(note) + 1
			if (moveTo >= notes.size()) moveTo = 0
			Effect.Fade( note, {duration:.2, queue: 'front'})
			var nextElem = notes[moveTo]
			var nextText = notes[moveTo].innerHTML
			Effect.Appear( nextElem, {duration:.2, queue: 'end'} )
			idArray = nextElem.id.split('_')
			noteTicInterval = parseInt(idArray[3])
		  nextTic = setTimeout(function() { thisObj.tickNote(); }, noteTicInterval);	
		}
	})
	
}
function typingNotes(){
	n=-1;
	
	var notes = $('project-notes').select('.note')
	notes.each( function(note) {
		if (note.getStyle('display') == "block") {
			var thisObj = this;
			var moveTo = notes.indexOf(note) + 1
			if (moveTo >= notes.size()) moveTo = 0
			note.hide()
			var nextElem = notes[moveTo]
			var nextText = notes[moveTo].innerHTML
			Effect.Appear( nextElem, {duration:0} )
			var divId = 'note-typeout'
			idArray = nextElem.id.split('_')
			ticInterval = parseInt(idArray[3])
			noteTmr = setInterval(function() { thisObj.typ(divId, nextText); }, 50);
		  nextNoteTick = setTimeout(function() { thisObj.typingNotes(); }, ticInterval);	
		}
	})
}

function typ(o,m) { 
  n++; 
	if(m.substr(n - 1, 1) == "<"){
		n = m.substr(n + 1).indexOf('>') + n + 2
	}
  if(document.getElementById(o).childNodes.length == 0) { 
    document.getElementById(o).appendChild(document.createTextNode("")); 
  } 
  if(n == m.length) { 
    clearInterval(noteTmr); 
  } 
  document.getElementById(o).innerHTML = m.substr(0,n); 
} 

function clearValue(e, v){
	if(e.value == v){
		e.value = '';
	}
}

function resetForm(form){
	form.down('#comment_name').value = 'name';
	form.down('#comment_email').value = 'mail';
	form.down('#comment_text_body').value = 'comment';
}

function returnButton(){
	if($('return-button')){
		$('return-button').addClassName('loading');
	}
	steppingBack = true;
	if((customHistory.length < 1)||(customHistory.last() == '')){
		window.location = '/';
	} else {
		window.history.go(-1);
	}
}

function slideRequest(projectId){
	//$('return-button').addClassName('loading');
	window.clearTimeout( slideTimeout );
	if($('return-button')){
		$('return-button').addClassName('loading');
	}
	slideshowRunning = true;
	new Ajax.Request('/frontend/slide?project=' + projectId, {asynchronous:true, evalScripts:true, onComplete:function(request){if($('return-button')){$('return-button').removeClassName('loading')};adjustPageHeightForRightColumn();}, parameters:'authenticity_token=' + encodeURIComponent(window._token)}); 
}

function autoSlideRequest(projectId){
	if(slideshowRunning){
		slideRequest(projectId)
	}
}

function forgetSlideTimer(){
	if (slideTimeout) {
		window.clearTimeout( slideTimeout );
		nextSlide = false;
	}
}
function pageRequest(hash){
	var page = hash.substring(1, hash.length)
	ajaxPageRequest(page);
}

function ajaxPageRequest(page){
	
	var slashAt = page.indexOf('/')
	if(slashAt > 0) {
		pageArg = page.substring(0,slashAt)
		detailArg = page.substring(slashAt + 1, page.length)
		var requestUrl = '/frontend/ajax_page?page=' + encodeURIComponent(pageArg) + '&detail=' + encodeURIComponent(detailArg)
	}else {
		var requestUrl = '/frontend/ajax_page?page=' + encodeURIComponent(page)
	}
	if($('return-button')){
		$('return-button').addClassName('loading');
	}
	forgetSlideTimer();
	updateUrlHash(page);
	new Ajax.Request(requestUrl, {
		asynchronous:true, 
		evalScripts:true, 
		onComplete:function(request){
			if($('return-button')){
				$('return-button').removeClassName('loading');
			}
		}, 
		parameters:'authenticity_token=' + encodeURIComponent(window._token)
	});
}

function classifyPage(page) {
	//alert(page);
	if(page.substr(0, 7) == 'project') {
		$('body').addClassName('projects-section');
	} else {
		$('body').removeClassName('projects-section');
	}
}
function onIdleFunction(){
	$('screencover').show();
	if (slideTimeout) window.clearTimeout( slideTimeout );
}

function resetIdle(){
    window.clearTimeout( timeOut );
		//if ($('screensaver').getStyle('display') != 'none') $('screensaver').hide();
    setIdle();
}

function wakeUp(){
	resetIdle()
	if(nextSlide) setSlideTimeout(nextSlide)
	currentScreensaver++
	if(currentScreensaver >= screensaverImages.size()) currentScreensaver = 0;
	//setIdle()
	screensaverHTML = '<div id="screencover" style="display:none;"><img id="screensaver" style="" onclick="wakeUp();" src="' + screensaverImages[currentScreensaver] + '"/></div>'
	$('screencover').replace(screensaverHTML);
}

function setIdle(){
	timeOut = window.setTimeout( "onIdleFunction()", idleTime );
}

function insertScreensaver(){
	$('page').insert({'before': screensaverHTML});
}

function monitorUrl(check){
	if(savedHash != window.location.hash){
		pageRequest(window.location.hash);
	  $('page-inner').hide();
	}
	savedHash = window.location.hash
}

function updateUrlHash(value){
	window.location.hash = value;
	if(savedHash != value){
		if(steppingBack){
			customHistory.pop();
			steppingBack = false;
		} else {
			customHistory.push( savedHash );
		}
	}
	savedHash = window.location.hash;
}

function setSlideTimeout(projectId){
	window.clearTimeout(slideTimeout)
	slideTimeout = window.setTimeout( 'autoSlideRequest(' + projectId + ')', slideTimeoutTime );
}

function addVisitedLinkClasses(){
	$('page').select('a').each( function(aTag){
		aTagHashAt = aTag.href.indexOf('#')
		aTagHash = aTag.href.substr(aTagHashAt)
		visitedPages.each( function(visitedPage){
			if(aTagHash == visitedPage){
				aTag.addClassName('visited');
			}
		});
	});
}

function updateVisitedPages() {
	var location = window.location.hash;
	if(visitedPages.indexOf( location ) == -1){
		readVisitedPagesCookie();
		visitedPages.push(window.location.hash);
		createCookie('visitedPages', escape(visitedPages.toJSON()), 20);
	}else{}
}

function readVisitedPagesCookie() {
	visitedPagesJSON = unescape(readCookie('visitedPages'));
	visitedPages = visitedPagesJSON.evalJSON();
}

function adjustPageHeightForRightColumn() {
	if($('right-column')){
		var pageShouldBeAtLeast = parseInt($('right-column').getStyle('height'));
		var pageHeight = parseInt($('inhalt').getStyle('height'));
		$('inhalt').setStyle('min-height:' + pageShouldBeAtLeast + 'px;');
	}
	$('footer').setStyle('display:block;');
}

function initializeMap() {
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map_canvas"));

	var alexsLatLng = new GLatLng(40.7450, -73.9944);
																	
    map.setCenter(alexsLatLng, 15);
    map.setUIToDefault();
    map.addOverlay(new GMarker(alexsLatLng));

  }
}

var load_columns_images_in_order = function(){
	var columns = $$('.projects-thumb-column');
	var longest_length = 0;
	var columns_projects = [];
	columns.each(function(elem) {
		var column_projects = elem.select('.project');
		columns_projects.push( column_projects );
		var curr_length = column_projects.length;
		if(curr_length > longest_length) { longest_length = curr_length; }
	});
	
	for( var project_i=0; project_i<longest_length; project_i++ ){
		columns_projects.each( function(column_projects) {
			if( column_projects[project_i] ){
				
				column_projects[project_i].select('img').each( function(project_image) {
					
					if (project_image.readAttribute('data-src')){
						project_image.writeAttribute('src', project_image.readAttribute('data-src'));
					}
				});
			}
		});
	}
	
};

var zoomed=1;
var tmr = -1;
var n=-1; 
var timeOut = '';
var idling = false;
var customHistory = new Array();
var steppingBack = false;
var slideTimeout = '';
var disableUpdateGreenWindowLocation = false;
var ieAdjust = 0;

Event.observe(window, 'load', function() {
	
	adjustPageHeightForRightColumn();
	observeToggles();
	checkActiveMenus();
	setIdle();
	setInterval("monitorUrl()", 700);
	
	readVisitedPagesCookie();
	addVisitedLinkClasses();
	
	if (showingScreensaver){
		Event.observe(document.body, 'mousemove', resetIdle, true);
		insertScreensaver();
	}
	
	elem = document.getElementById('green-window')
	var greenWindowDrag = new Draggable('green-window', { starteffect : false,
																												endeffect   : false
																											});	
	annonces(); 

	if (elem.addEventListener) {
    elem.addEventListener("mouseup", function() { updateGreenWindowLocation(); }, false);
  } else {
    elem.attachEvent("onmouseup", function() { updateGreenWindowLocation(); });
		
		//hacky way to add an extra few pixels to positioning of stickit button...
		ieAdjust = -15;
  }
	
	//observeHovers();
	
	
});

