//therendstudio
//

_sk_options = new Hash({
	behave_ipod : Browser.Platform.ipod,
	look_iphone : navigator.platform == 'iPhone' || navigator.platform == 'iPod',
	res_base_url : 'http://www.sergekerbel.com/cms/data/',
	local_base_url : 'data/',
	link_color : '#777',
	nav_transition_time : 300,
	content_time : 200,
	tnail_opacity : 0.6,
	tnail_height : 55,
	tnail_width_extra : 1,	//1px left border
	scrolling_threshold : 150,
	scrolling_interval : 30	//ms
});
function sk_Init(options){
	_sk_options.extend(options);
	if(_sk_options.behave_ipod)
		$(document.body).getParent().addClass('ipod');
	if(_sk_options.look_iphone)
		$(document.body).getParent().addClass('iphone');

	//Get xml
	new Request({
		url : _sk_options.local_base_url + 'info.xml',
		noCache : true,
		method : 'get',
		isSuccess : function(){return _inter_request_is_success(this.xhr)}
	})
		.addEvent('success',function(responseText, responseXML){
			_sk_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();
	$('preview').get('tween',{property : 'opacity', duration : _sk_options.content_time}).set(0);
	$('preview').getElements('.direction')
		.addEvent('click',function(){
			var curTnail = $('tn_slider').getElement('IMG.active');
			var nextTnail = curTnail[['getPrevious','getNext'][+this.hasClass('right')]]('img');
			if(!nextTnail)
				nextTnail = $('tn_slider')[['getLast','getFirst'][+this.hasClass('right')]]('img');
			_sk_showPreview(nextTnail);
		});
	$('text').get('tween',{property : 'opacity', duration : _sk_options.content_time}).set(0);
	_sk_initTNails();
	window.addEvent('resize',__sk_onWinResize);
}
function _sk_loadSection(section){
	newSection = __sk_infoxml.sections[section];
	if(!$defined(newSection))
		throw new inter_History.excNavReplace('women');
	$$('.menu div').removeClass('active');
	$$('.menu .nav-'+section).addClass('active');
	$('text').get('tween').start(0);
	$('preview').store('nextPicture',null).get('tween').start(0);
	$('content').set('class','').empty();
	_sk_tnails();
	switch($type(newSection)){
		case 'array':	//pf
			$('preview').get('tween').chain(function(){
				_sk_tnails(newSection);
				_sk_showPreview($$('#tn_slider img').shift());
			});
			break;
		case 'string' :	//text
			if(section == 'contact'){
				newSection += '<br/><br/><br/><a id="twitterIcon" href="http://twitter.com/#!/SergeKerbel" target="_blank"><img src="images/twitter.png" width="27" height="27"/></a>';
				newSection += '<a id="linkedInIcon" href="http://ca.linkedin.com/in/sergekerbel" target="_blank"><img src="images/linkedin.png" width="27" height="27"/></a>';
			}
			$('text').get('tween').chain(function(){
				$('content').set('class',section).set('html',newSection);
				if(__sk_infoxml.textSectionPhotos[section].length)
					$('content')
						.grab(new Element("DIV",{'class' : 'photos'})
							.adopt(
								__sk_infoxml.textSectionPhotos[section].map(function(urlPhoto){
									return new Element("IMG",{src : urlPhoto});
								})
						),'top');
				this.start(1);
			});
			break;
		default:			//Not loaded yet
			break;
	}
}
__sk_infoxml = {
	sections : {},
	textSectionPhotos : {},
	thumbnails : []
};
function _sk_parse_infoxml(root){
	var sections = $$A(root.selectNodes('/*/section[@name="PORTFOLIOS" and @status="1"]/section[@type="portfolio" and @status="1"]'));
	var firstpictures = [];
	while(sections.length){
		var elSection = sections.shift();
		var name = elSection.getAttribute('name');
		var images = $$A(elSection.selectNodes('content[@status="1"]'));
		__sk_infoxml.sections[name.toNav()] = [];
		var firstpicture = null;
		while(images.length){
			var elEntry = images.shift();
			var item = {
				src : _sk_options.res_base_url + 'PORTFOLIOS/' + name + '/images/' + elEntry.getAttribute('name'),
				tnsrc : _sk_options.res_base_url + 'PORTFOLIOS/' + name + '/thumbnails/' + elEntry.getAttribute('name'),
				tw : elEntry.getAttribute('tw'),
				outlines : !!+elEntry.getAttribute('option')
			};
			__sk_infoxml.sections[name.toNav()].push(item);
			if(firstpicture === null)
				firstpicture = item.src;
			__sk_infoxml.thumbnails.push(item.tnsrc);
		}
		if(firstpicture)
			firstpictures.push(firstpicture);
		new _sk_PFLink(name);
	}
		//text sections
	var text_sections = $$A(root.selectNodes('/*/section[@status="1" and @name!="PORTFOLIOS"]'));
	while(text_sections.length){
		var elSection = text_sections.shift();
		var name = elSection.getAttribute('name');
		if(elSection.getAttribute('description').match(/^http:/i))
			new _sk_HrefLink(name,elSection.getAttribute('description'));
		else{
			__sk_infoxml.sections[name.toNav()] = false;
			__sk_load_text_section(name,_sk_options.local_base_url + name + (elSection.getAttribute('type') == 'text' ? '/text.txt' : '/info1.txt'));
		}
		var section_photos = $$A(elSection.selectNodes('content'));
		__sk_infoxml.textSectionPhotos[name.toNav()] = section_photos.map(function(elPhoto){
				return _sk_options.res_base_url + name + '/images/' + elPhoto.getAttribute('name');
			});
	}
	new inter_ImgLoadingQueue(firstpictures,{iq_max_loading_requests : 2}).start();	//preload the first picture for each category
	new inter_ImgLoadingQueue(__sk_infoxml.thumbnails,{iq_max_loading_requests : 2}).start();
	inter_History.initialize(_sk_loadSection,'women');
}
function __sk_load_text_section(name,url){
	var xhr = new Request({
		url : url,
		link : 'cancel',
		noCache : true,
		isSuccess : function(){return _inter_request_is_success(this.xhr)}
	})
	.addEvent('success',function(responseText, responseXML){
		responseText = unescape(responseText);
		__sk_infoxml.sections[this.toNav()] = responseText
			.replace(/[\r\n][\r\n]/g,'<br/>');
		new _sk_TextLink(name);
		if(inter_History.getCurrentHash() == this.toNav())	//Currently wanted
			_sk_loadSection(this.toNav());
	}.bind(name))
	.addEvent('failure',function(xhr){
		window.console && console.log("There was an error with the "+url+"/text.txt ajax call: " + (xhr.status ? xhr.statusText : 'Unknown'));
	});
	xhr.send();
}
function _sk_tnails(content){
	if(content){
		$('tn_slider').empty();
		var width = 0;
		var images = [];
		content.each(function(item){
			width += +item.tw + _sk_options.tnail_width_extra;
			images.push(item.src);
			var img = new inter_Image(item.tnsrc,function(img,elImg){
				new Fx.Tween(elImg,{property : 'opacity',duration : _sk_options.content_time}).start(_sk_options.tnail_opacity);
			});
			img
				.toElement()
				.set('width',item.tw)
				.set('height',_sk_options.tnail_height)
				.store('picture',{src : item.src,outlines : item.outlines})
				.setStyle('opacity',0);
			$('tn_slider').grab(img);
			img.load();
		});
		$('tn_slider')
			.setStyle('width',width+'px')
			.get('tween').start(-_sk_options.tnail_height);
		new inter_ImgLoadingQueue(images,{iq_max_loading_requests : 2}).start();
	}else
		$('tn_slider')
			.scrollTo(0,0)
			.get('tween')
				.start(0)
				.chain(function(){
					this.element.empty();
				});
}
function _sk_initTNails(){
	$('tn_slider')
		.nonDraggable()
		.addEvents({
			mouseover : function(e){
				if(e.target.nodeName != 'IMG') return;
				e.target.get('tween',{property : 'opacity',duration : _sk_options.nav_transition_time}).start(1);
			},
			mouseout : function(e){
				if(e.target.nodeName != 'IMG') return;
				e.target.get('tween').start(_sk_options.tnail_opacity);
			},
			click : function(e){
				if(e.target.nodeName != 'IMG') return;
				if(e.target.hasClass('active')) return;
				_sk_showPreview(e.target);
			},
			mousemove : function(e){
				if(_sk_options.behave_ipod) return;
				this.store('scrollBy',0);
				e.stop();
			 }
		})
		.store('scrollBy',0)
		.setStyle('height',_sk_options.tnail_height+'px')
		.get('tween',{property : 'margin-top',duration : _sk_options.content_time}).set(0);

		(function(){
			var swidth = this.getScrollSize().x;
			var width = this.getSize().x;
			if(width >= swidth) return;
			var scrollBy = this.retrieve('scrollBy');
			var cscroll = this.getScroll().x;
			if(scrollBy < 0 && cscroll == 0 || scrollBy > 0 && cscroll > swidth - width) return;
			var scrolledBy = Math.round(scrollBy / 50);
			this.scrollTo(cscroll + scrolledBy,0);
			if(_sk_options.behave_ipod)
				this.store('scrollBy',scrollBy - scrolledBy);
		}).periodical(_sk_options.scrolling_interval,$('tn_slider'));
	$('tn_area')
		.addEvents({
			mouseenter : function(){
				if(_sk_options.behave_ipod) return;
				$('tn_slider').get('tween').start(-_sk_options.tnail_height);
			},
			mouseleave : function(){
				if(_sk_options.behave_ipod) return;
				$('tn_slider')
					.get('tween')
						.start(-_sk_options.tnail_height)
						.chain(function(){
							this.start(-_sk_options.tnail_height)
								.chain(function(){
									this.start(0);
								});
						});
			},
			mousemove : function(e){
				var pos = e.page.x - this.offsetLeft;
				var width = this.getSize().x;
				var scrollBy = Math.round(pos - width/2);
				if(!_sk_options.behave_ipod && Math.abs(scrollBy) < _sk_options.scrolling_threshold)
					scrollBy = 0;
				$('tn_slider').store('scrollBy',scrollBy);
			}
		});
}
function __sk_onWinResize(){
	var swidth = $('tn_slider').getScrollSize().x;
	var width = $('tn_slider').getSize().x;
	var cscroll = $('tn_slider').getScroll().x;
	if(cscroll > swidth - width)
		$('tn_slider').scrollTo(swidth - width);
}
function _sk_showPreview(elTnail){
	if(!elTnail)return;
	$('tn_slider').getElements('IMG').removeClass('active');
	elTnail.addClass('active');
	var infoPicture = elTnail.retrieve('picture');
	$('preview').store('nextPicture',infoPicture.src);
	$('preview-box').addClass('loading');
	new inter_Image(infoPicture.src,function(img,domImg){
		if($('preview').retrieve('nextPicture') != img.path) return;
		$('preview')
			.get('tween').set(0).start(0.99);	//FF image resize bug
		$('preview-box')
			.removeClass('loading')
			.empty()
			.grab(domImg);
	})
		.load()
		.toElement()
			.addClass(infoPicture.outlines ? 'outlined' : '');
}
_sk_NavLink = new Class({
	initialize : function(parent,name,nav){
		this._nav = nav;
		new Element("DIV",{text : name,'class' : 'nav-'+nav,style : {color : _sk_options.link_color}})
			.nonSelectable()
			.addEvents({
				mouseenter : function(){
					this.get('tween').start('#000');
				},
				mouseleave : function(){
					this.get('tween').start(_sk_options.link_color);
				},
				click : function(e){
					if(this._activate())
						e.target.addClass('active');
				}.bind(this)
			})
			.inject(parent)
			.get('tween',{property : 'color',duration : _sk_options.nav_transition_time}).set(_sk_options.link_opacity).element;
	},
	_activate : function(){
		inter_History.navigate(this._nav);
		return true;
	}
});
_sk_PFLink = new Class({
	Extends : _sk_NavLink,
	initialize : function(name){
		this.parent('pmenu',name,name.toNav());
	}
});
_sk_TextLink = new Class({
	Extends : _sk_NavLink,
	initialize : function(name){
		this.parent('tmenu',name,name.toNav());
	}
});
_sk_HrefLink = new Class({
	Extends : _sk_NavLink,
	initialize : function(name,href){
		this.parent('tmenu',name,name.toNav());
		this._href = href;
	},
	_activate : function(){
		window.open(this._href);
		return false;
	}
});
String.implement({
	toNav : function(){
		return this.replace(/ /g,'-').toLowerCase();
	}
});

