var slideshowObj;
var colLBottom, colRRight, minH, minW, maincolPaddingY;
var slideW = 670;

Event.observe(window, 'load', function() {
	switch (document.body.id) {
		case 'projects_page' :
		case 'exhibitions_page' :
			$$('#project_links li span').each(function(s) {
				Event.observe(s, 'click', proj_link);
				if (s.hasClassName('here')) {
					getLinkObj(s.up().id);
				}
			});
		break;
	}
	
	//fade in hidden items
	$$('.showMe').each(function(s) {
		s.appear({ afterFinish: resizeListener, duration:2.0, delay:1.0 });
	});


	//activate fancybox
	$$('.newsimg').each(function(s) {
		Event.observe(s, 'click', getFancyGallery);
	});

	colLBottom = $('col_L').getStyle('bottom');
	colLBottom = parseInt(colLBottom.substr(0,colLBottom.length-2));
	
	colRRight = $('col_R').getStyle('right');
	colRRight = parseInt(colRRight.substr(0,colRRight.length-2));
	
	minH = document.body.getStyle('minHeight');
	minH = parseInt(minH.substr(0,minH.length-2));

	minW = document.body.getStyle('minWidth');
	minW = parseInt(minW.substr(0,minW.length-2));

	maincolPaddingY = $('maincol').getStyle('paddingTop');
	maincolPaddingY = parseInt(maincolPaddingY.substr(0,maincolPaddingY.length-2));

	resizeListener();
	Event.observe(window, 'resize', resizeListener);
	
	if ($('homelink') != null) {
		Event.observe($('homelink'), 'click', function() {
			document.cookie = "isFirstView=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/";
		});
	}

	Event.observe($('email'), 'click', showPane);
});

//when leaving page, store the current time in seconds so we can compare the leaving time to the landing time (in parc_lib.inc) and determine whether to show the darker static.
Event.observe(window, 'beforeunload', function() {
	if (get_cookie('isFirstView') != undefined) {//if it's undefined, it's because the homelink was clicked
		d = new Date();
		document.cookie = "isFirstView=" + (Date.parse(d)/1000) + ';path=/';
	}
});

function resizeListener() {
	minTop = minH - $('col_L').getHeight() - colLBottom;
	minLeft = minW - $('col_R').getWidth() - colRRight;
	if (document.viewport.getHeight() < minH) {
		$('col_L').setStyle({
			position:'absolute',
			top:minTop + 'px',
			bottom:'auto'
		});
	} else {
		$('col_L').setStyle({
			position:'fixed',
			top:'auto',
			bottom:colLBottom + 'px'
		});
	}
	if (document.viewport.getWidth() < minW) {
		$('col_R').setStyle({
			position:'absolute',
			left:minLeft + 'px',
			right:'auto'
		});
	} else {
		$('col_R').setStyle({
			position:'fixed',
			left:'auto',
			right:colRRight + 'px'
		});
	}

	//stretch main column top to bottom
	if (document.body.id == 'news_page' || document.body.id == 'about_page' || document.body.id == 'missing_page' || document.body.id == 'archive_page') {
		var body = document.body, html = document.documentElement;
		var bodyheight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
		$('maincol').setStyle({
			height:(bodyheight - maincolPaddingY) + 'px'
		});
	}
}

function getLinkObj(id) {
	params = {
		action: 'getLinkObj',
		id: id,
		proj: location.href
	}
	new Ajax.Request('includes/parc_ajax.php', {
		parameters: params,
		onComplete: function(r) {
			l = r.responseJSON;
			switch (l.ltype) {
				case 'slides':
					if (typeof slideshowObj != "undefined") {
						$('slidenext').stopObserving('click', slideshowObj.scrollslide);
						$('slideprev').stopObserving('click', slideshowObj.scrollslide);
					}
					slideshowObj = new parc_slideshow();
					slideshowObj.initProjSlides(l);
				break;
				case 'pdf':
					if (/dev/.test(location.pathname)) {
						devpath = '/dev/';
					} else {
						devpath = '/';
					}
					location.href = 'http://' + location.host + devpath + 'includes/download.php?type=pdf&key=' + l.lkey;
				break;
				case 'text':
					textpaneObj = new parc_textpane();
					textpaneObj.initTextpane(l);
				break;
			}
		}
	});
}

function getFancyGallery(id) {
	if (typeof(id) == 'object') {
		id = id.element().id;
	}
	params = {
		action: 'getFancyGallery',
		id: id
	}
	new Ajax.Request('includes/parc_ajax.php', {
		parameters: params,
		onComplete: function(r) {
			l = r.responseJSON;
			jQuery.fancybox(l,
			{
				titlePosition:'over',
				titleFormat:fancyTitleFormat
			});
		}
	});
}

function showMore() {
	if ($('readmorediv') == undefined || $('readmorediv').down().hasClassName('here')) {
		return;
	}
	params = {
		action: 'getMoreText',
		proj: location.href
	}
	new Ajax.Request('includes/parc_ajax.php', {
		parameters: params,
		onComplete: function(r) {
			l = r.responseJSON;
			l.ltext = l.remainder;
			textpaneObj = new parc_textpane();
			textpaneObj.initTextpane(l);
			$('readmorediv').down().className = 'here';
		}
	});
	resetLinks();
}

function resetLinks() {
	$$('#project_links li span').each(function(s) {
		s.className = '';
	});
	if ($('readmorediv') != undefined) {
		$('readmorediv').down().className = '';
	}
}

function proj_link(e) {
	if (e.element().className == 'here') { return; }
	getLinkObj(e.element().up().id);
	resetLinks();
	e.element().className = 'here';
}

var parc_slideshow = function() {
S = {
	initProjSlides: function(l) {
		if ($('textpane') != undefined) {
			$('textpane').remove();
		}
		this.numImgs = l.imgs.length;
		if (this.numImgs) {
			this.slideNum = 0;
			html = '';
			for (i=0;i<this.numImgs;i++) {
				html += '<div id="slide' + i + '" class="slide" style="width:' + slideW + 'px">'
				+ '<div class="slideimgholder">'
				+ '<img src="media/projects/large/' + l.imgs[i].img + '.jpg" alt="" />'
				+ '</div>'
				+ '<div class="slidecaption">' + l.imgs[i].caption + '</div>'
				+ '</div>';
			}
			$('slidestrip').setStyle({
				width:(this.numImgs * slideW) + 'px',
				marginLeft:'0px'
			});
			$('slidestrip').innerHTML = html;
			if (this.numImgs > 1) {
				$('slidecount').innerHTML = 1 + "/" + this.numImgs;
				$('slideprev').className = '';
				$('slidenext').className = 'active';
				Event.observe($('slidenext'), 'click', this.scrollslide);
				Event.observe($('slideprev'), 'click', this.scrollslide);
				$('slidenav').show();
			} else {
				$('slidenav').hide();
			}
			$('slideshow').show();
		}
	},
	
	scrollslide: function(e) {
		nav = e.element();
		if (!nav.hasClassName('active')) {
			return;
		}
		if (nav.id == 'slideprev') {
			S.slideNum--;
			if (S.slideNum == 0) {
				$('slideprev').className = '';
			}
			$('slidenext').className = 'active';
		} else {
			S.slideNum++;
			if (S.slideNum >= S.numImgs - 1) {
				$('slidenext').className = '';
			}
			$('slideprev').className = 'active';
		}
		new Effect.Morph('slidestrip',{
			style:{
				marginLeft:(-S.slideNum * slideW) + 'px'
			},
			duration: 0.25
		});
		$('slidecount').innerHTML = (S.slideNum + 1) + "/" + S.numImgs;
	}
};
return S;
}

var parc_textpane = function() {
T = {
	initTextpane: function(l) {
		if ($('textpane') != undefined) {
			$('textpane').remove();
		}
		this.textpane = new Element('div', { 'id': 'textpane' }).update(l.ltext);
		$('maincol').insert(this.textpane);
		this.closeIt = new Element('div', { 'id': 'closeIt' }).update(new Element('span').update('close x'));
		this.textpane.insert(this.closeIt);
		Event.observe(this.closeIt, 'click', function() {
			T.removePane();
		});
	},
	
	removePane: function() {
		T.textpane.remove();
		resetLinks();
	}
};
return T;
}

function fancyTitleFormat(title, currentArray, currentIndex, currentOpts) {
	html = '<div id="fancybox-title-over">' + (currentIndex + 1) + '/' + currentArray.length + (title && title.length ? '—' + title : '' ) + '</div>';
	return html;
}


/*EMAIL FORM*/
var fadertimer;//global timer to fade panes

function showPane(which) {
	var objBody = $$('body')[0];

	objBody.appendChild(Builder.node('div',{id:'form_overlay', style:'display:none'}));

	objBody.appendChild(Builder.node('div',{id:'formholderholder', style:'display:none'}, [
		Builder.node('div',{id:'formholder'})
	]));
	Effect.Appear('form_overlay', {to:0.1});
	Effect.Appear('formholderholder');
	new Ajax.Updater('formholder', 'includes/email_share.php', {
		onComplete: function() {
			$('email_share_form').email_share_sharedlink.value = location.href;
			Event.observe('submit_link', 'click', function(event) {
				if (validateForm($('email_share_form'))) {
					$('email_share_form').request({
						onSuccess: function(t) {
							Effect.Fade('formcontainer', {
								afterFinish: function() {
									$('formcontainer').update(t.responseJSON).show();
									fadertimer = setTimeout('closeForm()',3000);
								}
							});
						}
					});
				}
			});
		}
	});
}

function closeForm() {
	clearTimeout(fadertimer);
	Effect.Fade('form_overlay', {
		from:0.1,
		duration:0.5,
		afterFinish: function() {
			$('form_overlay').remove();
		}
	});
	Effect.Fade('formholderholder', {
		duration:0.5,
		afterFinish: function() {
			$('formholderholder').remove();
		}
	});
}

function validateForm(f) {
	mandatory = {"email_share_name": "Name"
				};
	if (!this.validateFields(f, mandatory)) { return false; }

	if (!emailCheck(f.email_share_email.value)) {
		f.email_share_email.focus();
		return false;
	}
	var emails = f.email_share_friends_emails.value.split(",");
	emailFlag = false;
	emails.each(function(e) {
		e = e.replace(/^\s\s*/, '').replace(/\s\s*$/, '');//trim
		if (!emailCheck(e)) {
			f.email_share_friends_emails.focus();
			emailFlag = true;
		}
	});
	if (emailFlag) { return false; }
	return true;
}

function validateFields(which, mandatory) {
	var f = document.forms[which.id];
	var str = '';
	var foc = '';
	for (var nicename in mandatory) {
		if (f[nicename].value == '') {
			str += "You must enter a " + mandatory[nicename] + ".\n";
			if (foc == '') {
				foc = nicename;
			}
		}
	}

	if (str) {
		alert(str);
		if (foc != '') {
			f[foc].focus();
		}
		return false;
	}
	return true;
}

