﻿var isIE6 = (navigator.appVersion.search(/MSIE 6/) != -1)? true : false; // The immortal!
var isIE = (navigator.appName.indexOf('Microsoft') != -1)? true : false; // Same shit, different cousin
var loaderOpacity = 1;
var timer;
var engine = "engine/client.php";
var gItems = [];
var gCurrentItem = 0;
var gCurrentPage = false;
var gAnim = false;
var gAnimSpeed = 50;
var gAppLocation = 'albums';

var Positron = 
{
	blocks: {}, 
	vars: {}, 
	inputData: {},
	
	compile: function(data)
	{                          	
		var re = /\[([A-Z0-9_\.]*?)\](.*?)\[\/\1\]|\[([A-Z0-9_\.]*?)=(.*?)\/\]/gi;
		var re2 = /\{([A-Z0-9_\.@#]*?)(=(.*?))?\}/gi;
		var re3 = /\[([A-Z0-9_\.]*?)\].*?\[\/\1\]|\[([A-Z0-9_\.]*?)=.*?\/\]/gi;	
		var found_block, found_var, blockName, tmp;
		
		data = data.replace(/[\r\n|\t]/gim,'');
		
		do
		{
			found_block = re.exec(data);
			
			if (found_block)
			{
				(found_block[1])? blockName = found_block[1] : blockName = found_block[3];
				
				Positron.blocks[blockName] = "";
				
					var _block = '';
					
					if(found_block[2]) 
					{
					
						do
						{
							tmp = re3.exec(found_block[2]);
							data += (tmp)?tmp[0]:"";	
						}
						while (tmp)
						
						_block = found_block[2].replace(re3,'{@$1$2}');	
					}
					else _block = found_block[4];
										
					Positron.vars[blockName] = {};
					var i = 0;
					do
					{
						found_var = re2.exec(_block);
						if (found_var)
						{
							i = i+2;
							var varName = found_var[1];
							if (Positron.vars[blockName][varName] == null)
							{
								varName = varName.split('.');
								if (varName[1]) Positron.vars[blockName][varName[1]] = {value: Positron.vars.global[varName[1]].value, location: [i-1]};
								else Positron.vars[blockName][varName] = {value: found_var[3], location: [i-1]};
							}
							else 
							{
								Positron.vars[blockName][varName].location.push(i-1);
							}
							
						}
					}
					while (found_var)
					
					if (isIE) _block = _block.replace(/\}\{/g, "} {");
					_block = _block.split(/\{|\}/);
					
					Positron.blocks[blockName] = _block;					
			}
		}
		while (found_block);
		data = undefined;
		delete this.blocks.global;
	},
	
	fromJSON: function(data)
	{
		Object.extend(Positron, eval('(' + data + ')'));
	},
	
	block: function(blockName)
	{
		var result = "", varValue, location, repeat = 1;
		var tmp = Positron.blocks[blockName].slice(0);
		(Positron.inputData[blockName]) ? repeat = Positron.inputData[blockName].length : repeat = 1;
		for (var i=0; i<repeat; i++)
		{
			for (var name in Positron.vars[blockName])
			{
				if ((typeof Positron.inputData[blockName] == "undefined") || (typeof Positron.inputData[blockName][i][name] == "undefined"))
				{
					
					varValue = (name.slice(0,1) == "@") ? Positron.block(name.substr(1)) : Positron.vars[blockName][name].value;
				}
				else varValue = Positron.inputData[blockName][i][name]; 
				
				location = Positron.vars[blockName][name].location;
				for (var i2 in location)
				{
					tmp[location[i2]] = varValue;
				}
			}
			result += tmp.join("");
		}
		tmp = "";
		return result;
	},
	
	render: function(blockName, jsonData)
	{
		if(typeof(jsonData) == 'object') this.inputData = jsonData;
		else this.inputData = eval('(' + jsonData + ')');
		
		return Positron.block(blockName);
	}
}

Element.prototype.getId = function()
{
	return this.id.split('_')[1];
}
		
window.onload = function()
{
	new Ajax.Request('template.tpl', 
	{
		method: 'post',
		onSuccess: function(req) 
		{
			Positron.compile(req.responseText);
			document.body.innerHTML = Positron.block('main');
			
			$$('.a').each(function(item)
			{
				item.observe('click', function(){makeCurrent(item)});
			});
			
			//timer = setInterval('loader()',30);
			
			if (window.location.hash = "") go('');
			setInterval(function()
			{
				if (window.location.hash != gAppLocation)
				{
					go();
				}
			}, 50);

			$('main_submenu').style.left = $('submenu_handle').cumulativeOffset().left - 200 + $('submenu_handle').getWidth() + 'px';
		}
	});
}

function getPhotoPage(pageName)
{
	var scrollerCanvas = $('scroller_canvas');
	scrollerCanvas.innerHTML = '';
	scrollerCanvas.style.width = 'auto';
	scrollerCanvas.addClassName('scroller_loader');
	$$('.scroller_nav .btn').each(Element.show)
	new Ajax.Request(engine, 
	{
		method: 'post',
		parameters: {f: 'getPhotoPage', page_name: pageName},
		onSuccess: function(req) 
		{
			var photosWidth = 340, photosCount = 0;
				
			var viewportWidth = document.viewport.getWidth();
			var viewportHeight = document.viewport.getHeight();
			scrollerCanvas.removeClassName('scroller_loader');
			var lcurl = '<div id="small_l" class="_lcurl" style="width:70px;"><div class="small_image"><img src="images/curl_l.png" alt=""/></div></div>';
			var rcurl = '<div id="small_l" class="_rcurl" style="width:70px;"><div class="small_image"><img src="images/curl_r.png" alt=""/></div></div>';
			scrollerCanvas.innerHTML = lcurl+' '+Positron.render('photo_item',req.responseText)+' '+rcurl;
			$('scroller').scrollLeft = 0;
			gCurrentItem = 0;
			gItems = $$('._photo');
			
			gItems[0].addClassName('current_item');

			//$$('.current_item .title').each(Element.hide);			
			//$$('.current_item img').observe('load', function(){$$('.current_item .title').each(Element.show);});	

			gItems.each(function(item, index)
			{
				photosWidth += item.getWidth();
				photosCount++;
				
				item.observe('mouseover', function()
				{
				//if (index != gCurrentItem) 
					item.addClassName('hover_item');
				});
				
				item.observe('mouseout', function()
				{
				//	if (index != gCurrentItem) 
					item.removeClassName('hover_item');
				});	
				
				item.observe('click', function()
				
				{
					var scrollTo = 0;
					if (gItems[gCurrentItem] && gCurrentItem != index)
					{
			//			gItems[gCurrentItem].removeClassName('current_item');
						
						if (index < gCurrentItem)
						{
							gCurrentItem = index+1;
							scrollTo = -1;
						}
						else
						{
							gCurrentItem = index-1;
							scrollTo = 1;
						}
						scrollToItem(scrollTo);
					}
					
					getBigImage(item.id.split('_')[1])
					//getBigImage(item.getId());
				});
				
			});
		
			//$('scroller').style.marginTop = Math.ceil((viewportHeight-540)/2)+'px';
			
			var firstSpacerWidth = Math.ceil((viewportWidth-gItems[0].getWidth())/2);
			var lastSpacerWidth = Math.ceil((viewportWidth-gItems[gItems.length-1].getWidth())/2);
			
			scrollerCanvas.style.width = photosWidth + 40*(photosCount)+'px';
			
		}
	});
}

function getBigImage(id)
{
	var dim = document.viewport.getDimensions();
	var photo = $('big_image');
	$('dark').setStyle({width: dim.width+'px', height: dim.height+'px', display:'block'}).setOpacity(0.5);
	
	new Ajax.Request(engine, 
	{
		method: 'post',
		parameters: {f: 'getBigImage', id: id},
		onSuccess: function(req)
		{
			photo.innerHTML = Positron.render('big_photo_item',req.responseText);
			photo.setStyle({left: (dim.width-photo.getWidth())/2+'px', top: (dim.height-photo.getHeight())/2+'px', display:'block'});
			$('wrapper').setStyle({zIndex:0});
			//alert($('desc').getWidth())
			if($('desc').getWidth()<10){$('desc').hide()}
			
			if(window.location.hash=="#publications"){$('newin').show();}else{$('newin').hide();}
			
		}
	});
}



function getAbout()
{
	var scrollerCanvas = $('scroller_canvas');
	var scrollerWidth = 0;
	var paragraphsCount = 0;
	var viewportWidth = document.viewport.getWidth();
	var viewportHeight = document.viewport.getHeight();
			
	scrollerCanvas.innerHTML = Positron.block('about');
	$$('.scroller_nav .btn').each(Element.show)
	$('scroller').scrollLeft = 0;

	
	gItems = $$('.about_paragraph');
	gItems.each(function(item)
	{
		scrollerWidth += item.getWidth();
		paragraphsCount++;		
	});
	
	var firstSpacerWidth = Math.ceil((viewportWidth-gItems[0].getWidth())/2);
	var lastSpacerWidth = Math.ceil((viewportWidth-gItems[gItems.length-1].getWidth())/2);
	
	scrollerCanvas.style.width = scrollerWidth + 40*paragraphsCount+'px';
	$('wrapper').setStyle({zIndex:100});
	//$('dark').setStyle({width: viewportWidth+'px', height: viewportHeight+'px', display:'block',zIndex:10}).setOpacity(0.12);

}


function getContact()
{
	var scrollerCanvas = $('scroller_canvas');
	var scrollerWidth = 0;
	var paragraphsCount = 0;
	var viewportWidth = document.viewport.getWidth();
	var viewportHeight = document.viewport.getHeight();
			
	scrollerCanvas.innerHTML = Positron.block('contact');
	$$('.scroller_nav .btn').each(Element.hide)
	$('scroller').scrollLeft = 0;
	
	gItems = $$('.about_paragraph');
	gItems.each(function(item)
	{
		scrollerWidth += item.getWidth();
		paragraphsCount++;		
	});
	
	var firstSpacerWidth = Math.ceil((viewportWidth-gItems[0].getWidth())/2);
	var lastSpacerWidth = Math.ceil((viewportWidth-gItems[gItems.length-1].getWidth())/2);
	
	scrollerCanvas.style.width = scrollerWidth + 10*paragraphsCount+'px';
	$('scroller_canvas').setStyle({margin:'40px auto'});
	$('wrapper').setStyle({zIndex:100});
//	$('dark').setStyle({width: viewportWidth+'px', height: viewportHeight+'px', display:'block',zIndex:10}).setOpacity(0.12);
}


function getEvents()
{
	var scrollerCanvas = $('scroller_canvas');
	var scrollerWidth = 0;
	var paragraphsCount = 0;
	var viewportWidth = document.viewport.getWidth();
	var viewportHeight = document.viewport.getHeight();
			
	scrollerCanvas.innerHTML = Positron.block('events');
	$$('.scroller_nav .btn').each(Element.hide)
	$('scroller').scrollLeft = 0;
	
	gItems = $$('.about_paragraph');
	gItems.each(function(item)
	{
		scrollerWidth += item.getWidth();
		paragraphsCount++;		
	});
	
	var firstSpacerWidth = Math.ceil((viewportWidth-gItems[0].getWidth())/2);
	var lastSpacerWidth = Math.ceil((viewportWidth-gItems[gItems.length-1].getWidth())/2);
	
	scrollerCanvas.style.width = scrollerWidth + 10*paragraphsCount+'px';
	$('scroller_canvas').setStyle({margin:'40px auto'});
	$('wrapper').setStyle({zIndex:100});
//	$('dark').setStyle({width: viewportWidth+'px', height: viewportHeight+'px', display:'block',zIndex:10}).setOpacity(0.12);
}


var doAnim = false;

function scrollToItem(direction, speed)
{
	if (gItems[gCurrentItem+direction] && !gAnim)
	{
		var viewportWidth = document.viewport.getWidth();
		var scroller = $('scroller');
		var scrollPos = scroller.scrollLeft;
		var speed = speed || gAnimSpeed; 	
		var prevItem = gItems[gCurrentItem];
		var nextItem = gItems[gCurrentItem+direction];

		prevItem.removeClassName('current_item');
		nextItem.addClassName('current_item');
			
		var scrollMargin = Math.ceil((viewportWidth-nextItem.getWidth())/2); 	
		var scrollLimit = nextItem.cumulativeOffset().left-scrollMargin;
		var gAnim = setInterval(function()
		{
			if ((direction > 0 && scrollPos+speed < scrollLimit) || (direction < 0 && scrollPos-speed > scrollLimit))
			{
				scrollPos += speed*direction;
				scroller.scrollLeft = scrollPos;		
			}
			else
			{
				scroller.scrollLeft = scrollLimit;		
						
				clearInterval(gAnim);
				gCurrentItem += direction;
				
				if (doAnim) 
				{
					var timer = setTimeout(function()
					{
						gAnim = false;
						if (doAnim) scrollToItem(direction);
					}, 500);
				}
				else gAnim = false;
			}
		}, 10);
	}
}

function stopScrolling()
{
	doAnim = false; 
}


function go(hash)
{
	if (hash) window.location.hash = hash;
	
	gAppLocation = window.location.hash;
	var get = gAppLocation.split(':');
	
	switch (get[0])
	{
		case '#about': reBg('about');getAbout(); break;
		case '#contact': getContact(); break;
		case '#events': getEvents(); break;
		case '#publications': getPhotoPage('Publications'); break;
		case '#i design': getPhotoPage('i design'); break;
		case '#accessories': getPhotoPage('accessories'); break;
		case '#clothing': getPhotoPage('clothing'); break;
		case '#one_of_a_kind': getPhotoPage('one of a kind'); break;
		case '#': $$('.scroller_nav .btn').each(Element.hide); break;
		case '': $$('.scroller_nav .btn').each(Element.hide); break;
	}

	makeCurrent($$('a[href="'+get[0]+'"]')[0]);
	
	if(get[0]!=''&&get[0]!='#'){
	reBg(get[0].substring(1)+'-1500X1050pix.jpg');
	} else {
	reBg();
	}
}

function makeCurrent(element)
{
	if (element && element != gCurrentPage)
	{
		if (gCurrentPage) gCurrentPage.removeClassName('current');
		element.addClassName('current');
		gCurrentPage = element;
	}
}

		
function reBg(filename,hei){
	
	var bg=0;
	bgs=[0,1,2,3,4,5,6];
	arr=bgs//.split('@@'); 
	var sid = Math.ceil(Math.random()*(arr.length-1));
	
			var w = document.viewport.getWidth();
			var h = document.viewport.getHeight();
			
	if(w<=810){bg=800;}
	else {if(w<=1040){bg=1024;}
		else {if(w<=1300){bg=1280;}
			else {if(w<=1460){bg=1440;}
				else {bg=1600;}
			}
		}
	}
	if(h<530){h=530;}
//	alert(h+' x '+w+': '+bg)

	if(!filename||filename==""){
	$('bg').hide();//setAttribute('src',path);	
	slideshow(1,6,7000);

//	fname=bgs[sid]+'-1500X1050pix.jpg';
//	path='images/bg/'+fname;		
	}else{
	window.clearInterval(slides)
	$$('.slide').each(function(item, index){item.hide();});
		fname=filename;
		path='images/bg/'+fname;
		$('bg').show().setAttribute('src',path);	
	}
//	if(hei){h=hei;}
	//alert(h)
//	path='images/bg/'+fname;
//	alert(path)


	//alert(sid)
}


function slideshow(start,last,interval) {
  arr=[0,1,2,3,4,5,6];
  var sid=0;

  var frame = start;  
  var nextframe = start+1; 
  
  Effect.Appear('bg1',{duration:.2,from:0.0,to:1.0});  
    slides = setInterval(function() {  
    Effect.Fade('bg'+frame,{duration:.1,from:1.0,to:0.0,afterFinish:function(){  
    $('bg'+frame).hide();  
    Effect.Appear('bg'+nextframe,{duration:.15,from:0.0,to:1.0});  
	frame = nextframe;  
	sid = Math.ceil(Math.random()*(arr.length-1));
	while(sid==nextframe){sid = Math.ceil(Math.random()*(arr.length-1));}
	nextframe = arr[sid];
//  nextframe = (frame == last) ? start : nextframe+1;
	}});  
 },interval);  
 return;  
};  


function loader()
{
	loaderOpacity -= 0.2;
	$("loader").style.opacity = loaderOpacity;
	$("loader").style.filter = 'alpha(opacity=' + loaderOpacity*100 + ')';
	if (loaderOpacity <= 0)
	{
		clearInterval(timer);
		$("loader").style.display = 'none'
	}
}




function mailMe(){
var form = $('contactform');

var nam = $(form['nam']).getValue();
var company = $(form['comp']).getValue();
var email = $(form['email']).getValue();
var message = $(form['message']).getValue();


//  var name=$('nam').value();
//  var company=$('comp').val();
//  var email=$('email').val();
//  var message=$('message').val();
//alert(email+':'+name+':'+company+':'+message);
$("fid").hide();
if(nam =="" || email ==""){
if(nam =="") {
	$(form['nam']).setStyle({border:'1px solid #DD5544'});
	$("fid").update("please enter Name and Email...").setStyle({background:'#CC1122'}).show();
	$(form['nam']).observe('change', function(){this.setStyle({border:'1px solid #333333'});$("fid").hide();});
}
if(email == ""){
	$(form['email']).setStyle({border:'1px solid #DD5544'});
	$("fid").update("please enter Name and Email...").setStyle({background:'#CC1122'}).show();
	$(form['email']).observe('change', function(){this.setStyle({border:'1px solid #333333'});$("fid").hide();});	

	}
return;	
}else {
	$("fid").update("Sending request...").setStyle({background:'#778899'}).show();
	$('but_clear').hide();	
	$('but_submit').hide();
//	alert("name:"+nam+",company:"+company+",email:"+email+",message:"+message);return;

//	return;
	new Ajax.Request('engine/sendemil.php', 
	{
		method: 'post',
		parameters: {name:nam,company:company,email:email,message:message},
		onSuccess: function(req) 
		{
			if(req.responseText=='1'){
					$('nam').replace(nam)
					$('comp').replace(company)
					$('email').replace(email)
					$('message').replace(message)

			//	clearMe();
				$("fid").update("Message is sent, Thank You.").setStyle({background:'#778899'}).show();

			} else {
				$("fid").update("Error sending. Please send me an Email").setStyle({background:'#CC1122'}).show();
				$('but_clear').show();	
				$('but_submit').show();

			}
		}		
	});

}
}

function clearMe(){
var form = $('contactform');
$(form['nam']).clear().setStyle({border:'1px solid #333333'});
$(form['comp']).clear();
$(form['email']).clear().setStyle({border:'1px solid #333333'});
$(form['message']).clear();
}
