//therendstudio

/*
description options
 default - makes a section the default one
 open(url) - the link opens external url in a frame
 blank - force the external link to open in a new window instead of in a frame
 thumbnails - the gallery has thumbnails
 arrows - the gallery has arrows
 centered - the text section is center aligned
 composite - the text section is composite of several text/image sections
 hide-stripe - non active images are hidden and active ones don't scroll in
 center-images - center the active image into view (must have hide-stripe)
*/
//
_mc_options = new Hash({
	email_content : "Hi,\nTake a gander at this image from Michael Clinard,\n{0}\nRegards,",
	behave_ipod : Browser.Platform.ipod,
	iphone : navigator.platform == 'iPhone' || navigator.platform == 'iPod',
	site_url : 'http://michaelclinard.com',	//To be used for the emailed urls
	res_base_url : 'cms/data_cms/',
	local_base_url : 'cms/data_cms/',
	mailer_url : 'mail_to.php',
	scrolling_threshold : 150,
	email_box_fillet_offset : 40,
	scrolling_interval : 30	//ms
});
_mc_sectionDefault = null;
_mc_sectionCurrent = null;
_mc_fxScrollPictures = null;
_mc_fxScrollThumbnails = null;
function mc_Init(options){
	inter_precacheImg('images/arrows.jpg');
	inter_precacheImg('images/progress-circ.gif');
	_mc_options.extend(options);
	if(_mc_options.behave_ipod)
		$(document.body).getParent().addClass('ipod');
	if(_mc_options.iphone)
		$(document.body).getParent().addClass('iphone');

	//Get xml
	new Request({
		url : _mc_options.local_base_url + 'infoFull.xml',
		noCache : true,
		method : 'get',
		isSuccess : function(){return _inter_request_is_success(this.xhr)}
	})
		.addEvent('success',function(responseText, responseXML){
			_mc_parse_infoxml(responseXML.documentElement);
		})
		.addEvent('failure',function(xhr){
			alert("There was an error with the info.xml ajax call: " + (xhr.status ? xhr.statusText : 'Unknown'));
		})
		.send();
	_mc_fxScrollPictures = new Fx.Scroll($('pictures'));
	_mc_fxScrollThumbnails = new Fx.Scroll($('thumbnails'));
	new mc_Scroller('thumbnails',{area : 300,velocity : 0.08,fps : 30}).start();	//Mouse hover scroll
	$$('#menu','#thumbnails','#pictures')
		//.nonDraggable();
	$('arrow-left')
		.nonDraggable()
		.addEvent('click',function(){
				var elActiveImg = $('pictures').getElement('.img-box.active img');
				if(!elActiveImg) return;
				var indCur = elActiveImg.retrieve('index');
				if(!indCur)
					_mc_activateImage($('pictures').getElements('img').length-1);
				else
					_mc_activateImage(indCur-1);
			});
	$('arrow-right')
		.nonDraggable()
		.addEvent('click',function(){
				var elActiveImg = $('pictures').getElement('.img-box.active img');
				if(!elActiveImg) return;
				var indCur = elActiveImg.retrieve('index');
				_mc_activateImage((indCur + 1) % $('pictures').getElements('img').length);
			});
	$('embed').addEvent('load',function(){
		if(this.src)
			this.fade('in');
	});
	window.addEvent('resize',_mc_win_resize);
}
function _mc_navigate(nav){
	nav = nav.split('/');
	section = nav.shift();

	newSection = __mc_sections[section];
	if(newSection === _mc_sectionCurrent && nav.length){	//Image url
		//Section already built
		_mc_activateImage(nav[0]);
		return;
	}
	_mc_sectionCurrent = newSection;
	if(!$defined(newSection))
		if(_mc_sectionDefault)
			throw new inter_History.excNavReplace(_mc_sectionDefault);
		else{
			alert("There is no default section defined");
			return;
		}
	$$('#menu div').removeClass('active');
	$$('#menu .nav-'+section).addClass('active');
	$('pictures').empty();
	$('thumbnails').empty();
	$('content').set('class',newSection.type);
	$('embed').fade('hide').set('src',null);
	switch(newSection.type){
		case 'portfolio':	//pf
			$('pictures').fade('hide').adopt(
					newSection.pictures.map(function(picture,ind){
							return new Element('DIV',{'class' : 'img-box'})
								.adopt(
									new Element("IMG",{src : picture.src,width : picture.iw, height : picture.ih,alt : picture.galName+" :: "+picture.label, title: picture.label})
										.store('width',picture.iw)
										.store('height',picture.ih)
										.store('index',ind)
										.addEvent('click',function(){
												if(!this.getParent().hasClass('active')){
													if(!$$('#pictures .img-box.email').length)	//No email box opened
														inter_History.navigate(section+'/'+this.retrieve('index'));
												}else if($('content').hasClass('hide-stripe'))	//advance
													$('arrow-right').fireEvent('click');
										}),
									new Element("DIV",{'class' : 'cmd'})
										.grab(new Element("button",{text : 'email','class' : 'email'})
											.nonDraggable()
											.addEvent('click',function(){	//Activate email box
												if(this.getParent('.img-box').hasClass('email')) return;
												var canvas;
												var ebox;
												this.getParent('.img-box')
													.addClass('email')
														.mask()
														.get('mask')
															.element
																.grab(
																	ebox = new Element("DIV",{'class' : 'email-box'})
																		.adopt(
																			canvas = new Element("CANVAS"),
																			new Element("DIV",{'class' : 'email-controls'})
																				.adopt(
																					new Element("DIV",{'class' : 'email-title',text : 'share this image'}),
																					new Element("INPUT",{type : 'text','class' : 'name',title : 'your name'}).addEvent('focus',function(){if(this.hasClass('error'))this.removeClass('error').value = '';}),
																					new Element("INPUT",{type : 'text','class' : 'emailfrom',title : 'your email'}).addEvent('focus',function(){if(this.hasClass('error'))this.removeClass('error').value = '';}),
																					new Element("INPUT",{type : 'text','class' : 'emailto',title : 'email to'}).addEvent('focus',function(){if(this.hasClass('error'))this.removeClass('error').value = '';}),
																					new Element("INPUT",{type : 'text','class' : 'subject',title : 'subject'}).addEvent('focus',function(){if(this.hasClass('error'))this.removeClass('error').value = '';}),
																					new Element("TEXTAREA").store('url',_mc_options.site_url + '#' + section + '/' + ind).set('value',_mc_options.email_content.substitute([_mc_options.site_url + '#' + section + '/' + ind])).addEvent('focus',function(){if(this.hasClass('error'))this.removeClass('error').value = _mc_options.email_content.substitute([_mc_options.site_url + '#' + section + '/' + ind]);}),
																					new Element("DIV",{'class' : 'email-buttons'})
																						.adopt(
																							new Element("BUTTON",{text : 'forget it',id : 'forget-it'})
																								.nonDraggable()
																								.addEvent('click',function(e){
																										e && e.stop();
																										this.getParent('.mask').getPrevious('.img-box').removeClass('email').unmask();
																										this.getParent('.email-box').destroy();
																									}),
																							new Element("BUTTON",{text : 'send it',id : 'send-it'})
																								.nonDraggable()
																								.addEvent('click',_mc_sendmail)
																						)
																				)
																			)
																).getElements('input').each(function(input){
																	new OverText(input);	//Set prompts
																});
												_mc_win_resize();	//Scale the ebox
												if(!canvas || !canvas.getContext){
													ebox.setStyle('background-color','#FFFFFF');
													return;
												}
												var ctx = canvas.getContext('2d');
												canvas.width = canvas.getSize().x;
												canvas.height = canvas.getSize().y;
												ctx.fillStyle = "rgb(255,255,255)";
												ctx.beginPath();
												ctx.moveTo(_mc_options.email_box_fillet_offset,0);  
												ctx.lineTo(canvas.width - _mc_options.email_box_fillet_offset,0);  
												ctx.lineTo(canvas.width,_mc_options.email_box_fillet_offset);  
												ctx.lineTo(canvas.width,canvas.height - _mc_options.email_box_fillet_offset);  
												ctx.lineTo(canvas.width - _mc_options.email_box_fillet_offset,canvas.height);
												ctx.lineTo(_mc_options.email_box_fillet_offset,canvas.height);
												ctx.lineTo(0,canvas.height - _mc_options.email_box_fillet_offset);
												ctx.lineTo(0,_mc_options.email_box_fillet_offset);
												ctx.fill();
											}))
										.appendText(' / ')
										.grab(new Element("button",{text : 'pdf'})
												.nonDraggable()
												.addEvent('click',(function(pdfsrc){
													return function(e){
														e.stop();
														window.open(pdfsrc,'pdf');
													};
												})(picture.pdf))
										),
									new Element("DIV",{'class' : 'title',text : picture.label})
								);
						}),
					new Element("DIV",{'class' : 'padding'})
				).fade('in');
			_mc_fxScrollPictures.set(0,0);
			if(newSection.withThumbnails)
				$('thumbnails').adopt(
						newSection.pictures.map(function(picture,ind){
							return new Element("IMG",{src : picture.tnsrc,width : picture.tw, height : picture.th, title: picture.label, alt: picture.galName+" :: "+picture.label})
								.addEvent('click',(function(section,ind){
									return function(){
    									//GA Tracking for each thumbnail clicked - anw
//    									console.log(section+picture.tnsrc.substring(picture.tnsrc.lastIndexOf('/')));
									    _gaq.push(['_trackPageview', section+picture.tnsrc.substring(picture.tnsrc.lastIndexOf('/'))]);									
										if(this.getParent().hasClass('active')) return;
										inter_History.navigate(section+'/'+ind);
									};
								})(section,ind));
						})
					).scrollTo(0,0);
			$('content')
				.addClass(newSection.hideStripe ? 'hide-stripe' : '')
				.addClass(newSection.centerImages ? 'center-images' : '')
				.addClass(newSection.withThumbnails ? 'thumbnails' : '')
				.addClass(newSection.withArrows ? 'arrows' : '');
			if(nav.length)	//Image url
				_mc_activateImage(nav[0]);
			else
				_mc_activateImage(0);
			_mc_win_resize();
			break;
		case 'text' :	//text
			$('text')[['addClass','removeClass'][+!newSection.centered]]('centered');
			$('text')
				.fade('hide')
				.set('html',newSection.content)
				.fade('in');
			break;
		case 'external':
			$('embed').src = newSection.url;
			//$('embed').setStyle('top',newSection.offset + 'px');
			_mc_win_resize();
			break;
		default:			//Not loaded yet
			break;
	}
}
__mc_sections = {};
function _mc_parse_infoxml(root){
	var thumbnails = [];
	var sections = $$A(root.selectNodes('/*/section[@status="1"]'));
	for(var si=0;si < sections.length;si++){
		var link = null;
		var elSection = sections[si];
		var name = elSection.getAttribute('name');
		var description = elSection.getAttribute('description').toLowerCase();
		if(!_mc_sectionDefault || description.test(/\bdefault\b/))	//Make the first section default initially
			_mc_sectionDefault = name.toNav();
		var type = elSection.getAttribute('type');
		var openURL = description.match(/\bopen\(([^)]+)\)(?:\s|$)/);	//\b doesn't match next to ')'
		if(openURL && openURL.length == 2){	//Just redirect
			openURL = openURL[1];
			type = 'external';
		}
		switch(type){
			case 'portfolio':
				//Portfolio
				var portfolio = {
					pictures : [],
					type : 'portfolio',
					withThumbnails : description.test(/\bthumbnails\b/),
					hideStripe : description.test(/\bhide-stripe\b/),
					centerImages : description.test(/\bhide-stripe\b/) && description.test(/\bcenter-images\b/),
					withArrows : description.test(/\barrows\b/)
				};
				var content = elSection.selectNodes('content[@status="1"]');
				for(var i=0;i < content.length;i++){
					var elContent = content[i];
					var picture = {
						label : elContent.getAttribute('caption'),
						galName: name,
						src : _mc_options.res_base_url + name + '/images/' + escape(elContent.getAttribute('name')),
						iw : elContent.getAttribute('iw'),
						ih : elContent.getAttribute('ih'),
						tnsrc : _mc_options.res_base_url + name + '/thumbnails/' + escape(elContent.getAttribute('thmbname')),
						tw : elContent.getAttribute('tw'),
						th : elContent.getAttribute('th'),
						pdf : _mc_options.res_base_url + name + '/pdf/' + escape(elContent.getAttribute('name').split('.').slice(0,-1).join('.')) + '.pdf'
					};
					thumbnails.push(picture.tnsrc);
					portfolio.pictures.push(picture);
				};
			__mc_sections[name.toNav()] = portfolio;
                myname=name.toNav();	
			    //GA Tracking for each menu item clicked - anw						                
       				link = new Element("DIV",{text : name, title: name+" photo gallery"}).addEvent('click',(function(nav){
       					return function(){ 
       						//console.log("clicked: " + nav);
       						_gaq.push(['_trackPageview', '/Navigation/'+nav]);
       						inter_History.navigate(nav);
       					};
       				})(name.toNav()));

				break;
			case 'text':
			//Text section
				var section = {
					type : 'text',
					centered : description.test(/\bcentered\b/)
				};
				if(description.test(/\bcomposite\b/)){
					section.content = '';
					var paragraphs = $$A(elSection.selectNodes('section[@status="1"]'));
					while(paragraphs.length){
						var elParagraph = paragraphs.shift();
						switch(elParagraph.getAttribute('type')){
							case 'portfolio':
								var images = $$A(elParagraph.selectNodes('content[@status="1"]'));
								while(images.length){
									var elImage = images.shift();
									section.content += '<img src="{0}" width={1} height={2} alt=""/>'.substitute([
									_mc_options.res_base_url + escape(elSection.getAttribute('name')) + '/' + escape(elParagraph.getAttribute('name')) + '/images/' + escape(elImage.getAttribute('name')),
									elImage.getAttribute('iw'),
									elImage.getAttribute('ih')]);
								}
								break;
							case 'text':
								section.content += "<p>" + (elParagraph.textContent || elParagraph.text) + "</p>";
								break;
						}
					}
				}else	//plain text section
					section.content = elSection.textContent || elSection.text;
				__mc_sections[name.toNav()] = section;

				break;
			case 'external':
				if(_mc_options.behave_ipod || description.test(/\bblank\b/))	//Open externally
					link = new Element("DIV",{text : name})
//						.addEvent('click',function(){window.open(openURL,openURL.toNav());});
						.addEvent('click',function(){window.location=openURL;}); //open in the same window (anw)
				else{
					//var offset = description.match(/\bframe-offset:(-?\d+)/);
					__mc_sections[name.toNav()] = {
											type : 'external',
											//offset : offset ? offset[1] : 0,
											 url : openURL
											};
				}
				break;
		}
		if(!link)
			link = new Element("DIV",{text : name})
				.addEvent('click',(function(nav){return function(){
				//GA Event Tracking for each menu item that's not a gallery - anw
//				console.log(nav);
                _gaq.push(["_trackPageview", "/Navigation/" + nav]);				
				inter_History.navigate(nav);};})(name.toNav()));
// anw - hide sub pages (while testing)
        if(name.toNav().indexOf("_sub_")<0)
    		$('menu').grab(link.set('class','nav-'+name.toNav()));
	}
	new inter_ImgLoadingQueue(thumbnails,{iq_max_loading_requests : 6}).start();	//preload the thumbnails
	inter_History.initialize(_mc_navigate);
//	window.console && console.log(__mc_sections);
}
function _mc_activateImage(index,force){
	elImage = $('pictures').getElements('img')[index];
	if(!elImage)return;
	if(!force)
		$$('#forget-it').fireEvent('click');	//Close ebox
	$('pictures').getElements('.img-box').removeClass('active');
	elImage.getParent().addClass('active');
	_mc_fxScrollPictures.cancel();
	if(force || $('content').hasClass('hide-stripe'))
		_mc_fxScrollPictures.set(elImage.getPosition('pictures').x,0);
	else
		_mc_fxScrollPictures.start(elImage.getPosition('pictures').x,0);
	$$('#thumbnails img').removeClass('active');
	var activeTnail = $('thumbnails').getChildren('img')[index];
	//Center image if stripe is hidden
	if($('content').hasClass('center-images'))
		$('pictures').setStyle('margin-left',Math.max(0,$('content').getSize().x / 2 - elImage.getParent().getSize().x / 2));
	else
		$('pictures').setStyle('margin-left',0);
	if(activeTnail){
		activeTnail.addClass('active');
		_mc_fxScrollThumbnails.cancel().start(activeTnail.getPosition('thumbnails').x + activeTnail.getSize().x / 2 - $('thumbnails').getSize().x / 2,0);
	}
}
function _mc_win_resize(){
	$('embed').setStyles({
		width : window.getSize().x - $('embed').getStyle('left').toInt() + 'px',
		height : window.getSize().y - $('embed').getStyle('top').toInt() + 'px'
	});
	var heightPictures = $('pictures').getSize().y;
	$('pictures').getElements('.img-box').each(function(img_box){
		var img = img_box.getElement('img');
		var height = Math.min(heightPictures - 40,img.retrieve('height'));
		img.setStyle('height',height+'px');
		img_box.setStyle('width',img.retrieve('width') * height / img.retrieve('height'));
	});
	var elActiveImg = $('pictures').getElement('.img-box.active img');
	//Email box
	$$('#pictures .email-box').each(function(ebox){
		var sizeEBox = ebox.getSize();
		var hfactor = (heightPictures - 60) / sizeEBox.y;
		var wfactor = ebox.getParent('.mask').getPrevious().getSize().x / (sizeEBox.x + 40);
		var factor = Math.min(hfactor,wfactor);
		if(factor <= 1)
			ebox.setStyles({
				'-webkit-transform' : 'scale('+factor+')',
				'-o-transform' : 'scale('+factor+')',
				'-moz-transform' : 'scale('+factor+')'
			});
	});
	if(!elActiveImg) return;
	_mc_activateImage(elActiveImg.retrieve('index'),true);
}
function _mc_sendmail(){
	var ebox = $('pictures').getElement('.email-box');
	if(!ebox || ebox.hasClass('sending')) return;
	var inName = ebox.getElement('.name');
	var inEmailFrom = ebox.getElement('.emailfrom');
	var inEmailTo = ebox.getElement('.emailto');
	var inSubject = ebox.getElement('.subject');
	var inText = ebox.getElement('textarea');
	var name = inName.value.trim();
	var emailfrom = inEmailFrom.value.trim();
	var emailto = inEmailTo.value.trim();
	var subject = inSubject.value.trim();
	var text = inText.value.trim();
	if(!name.length){
		inName.focus();
		inName.addClass('error').set('value','Please enter your name').blur();
		return;
	}
	if(!emailfrom.length || !/^([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})$/i.test(emailfrom)){
		inEmailFrom.focus();
		inEmailFrom.addClass('error').set('value','Please enter your valid email').blur();
		return;
	}
	if(!emailto.length || !/^([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})$/i.test(emailto)){
		inEmailTo.focus();
		inEmailTo.addClass('error').set('value','Please enter valud destination email').blur();
		return;
	}
	if(!subject.length){
		inSubject.focus();
		inSubject.addClass('error').set('value','Please enter the subject').blur();
		return;
	}
	if(!text.length){
		inText.focus();
		inText.addClass('error').set('value','Please enter the email text').blur();
		return;
	}
	ebox.addClass('sending');
	new Request({
		url : _mc_options.mailer_url,
		noCache : true,
		link : 'cancel',
		isSuccess : function(){return _inter_request_is_success(this.xhr)}
	})
		.addEvent('success',function(responseText, responseXML){
			$$('#pictures .email-box').removeClass('sending');
			if(responseText.length)
				inText.addClass('error').set('value',"ERROR: " + responseText);
			else
				$$('#forget-it').fireEvent('click');	//Close ebox
				//inText.removeClass('error').addClass('success').set('valu3','Message sent !').fireEvent('blur');
		})
		.addEvent('failure',function(xhr){
			alert("There was an error with the mail sending ajax call: " + (xhr.status ? xhr.statusText : 'Unknown'));
		})
		.post({
			sendTo : emailto,
			theEmail : emailfrom,
			subject : subject,
			name : name,
			url : inText.retrieve('url'),
			text : text
		});
}

String.implement({
	toNav : function(){
		return this.replace(/ /g,'-').toLowerCase();
	}
});

mc_Scroller = new Class({
	Extends : Scroller,
	start: function(){
		this.listener.addEvents({
			mouseenter: this.bound.attach,
			mouseleave: this.bound.detach
		});
	},

	stop: function(){
		this.listener.removeEvents({
			mouseenter: this.bound.attach,
			mouseleave: this.bound.detach
		});
		this.detach();
		this.timer = $clear(this.timer);
	}
});

