var ttt1;
var ttt2;
var ttt3;
var ttt4;
var ttt5;
var ttt6;
var ttt7;
var ttt8;
var ttt9;

var nav="home";
var mWidth = 500;
var basedir ="../v7/wp-content/themes/pp/";
var ww, wh, sw, sh, ws;
var wrapTop = new Array();
var logoImg;
var context;
var tr,tg,tb;
var nr, ng, nb;


var t =0;
var iLoaded=0;
var wwOld=0;
var loadingCount=0;
var navOver = false;
var expandDir = 0;//1=expanding, -1=collapsing
var thumbFade = 0.1;
//json
var project="";
var pageTitle="";
var mx=1000;
var my=0;

var colorList = new Array();
var colorStopList = new Array();

//bgCanvas
var t2=0;
var g;
var pList = new Array();

//subvision
var subvisionList=new Array();
var subvisionIndex = 0;
var subvisionLen = 0;


$(document).ready(function(){
	us();
	$.address.change(function(event) {
		var strList = event.value.split("/");
		//alert(strList+"/"+strList.length);
		if(strList.length<2){//if no deeplink
			//$.address.value(lang+"/projects/3");
			return false;
		}
		if(strList.length==2){
			
			if(strList[1]!='project'){
				clearDetail(true);
			}
			$('.subvision_link').removeClass('current');
			
			$.address.title("pill & pillow");
		}
		if(strList[1]=='project'){
			var startT = 0;
			if(project !=""){
				clearDetail(false);
				//startT = 2000;
			}
			project = strList[2];
			
			ttt7 = setTimeout("open_project();",startT);
			ttt5 = setTimeout('get_J_project();',startT+1000);
			
			$('.subvision_link').removeClass('current');
			$('.subvision_link[project="'+project+'"]').addClass('current');
			
			$.address.title("pill & pillow");
		}
	});

	$(window).scroll(function () {  
		checkScroll();
	});
	$(window).resize(function() {
		us();
		if(ww<wwOld){
			expandDir = 1;
			if(ww < mWidth){
				checkResize();
			}else{
				aboutToCheckResize();
			}
		}else{
			expandDir = -1;
			if(ww < mWidth){
				checkResize();
			}else{
				aboutToCheckResize();
			}
		}
		//checkResize();
	});
	$(document,'body').mousemove(function (event) {
		mx = event.pageX;  
		my = event.pageY;

		if(ww> mWidth){
			if(mx < 180){
				if(!navOver){
					checkMove2();
					navOver = true;
				}
			}else{
				if(navOver){
					checkMove2();
					navOver = false;
				}
			}
		}
		//checkMove();
	});
	checkResize();
	
		
	$('img').load(function(){
		imgLoaded();	
	});
	//imgLoaded();
	//bgCanvas
	var c_canvas = document.getElementById("bgCanvas");
	g = c_canvas.getContext("2d");
	for(var i=0; i<10; i++){
		var pt = new Object();
		pt.x = Math.random()*800;
		pt.y = Math.random()*5000;
		pList[i] = pt;
	}
	var my_gradient = g.createLinearGradient(0, 0, 0, 600);
	
	my_gradient.addColorStop(0, "#FFF");
	my_gradient.addColorStop(1, "#CFCFCF");
	g.fillStyle = my_gradient;
	g.fillRect(0, 0, 800,600);
	
	
	//bird
	var canvas = document.getElementById("canvas_logo");
    context = canvas.getContext("2d");

	context.strokeStyle = "#000000";
	context.fillStyle = "#FF0066";
	context.beginPath();
	context.arc(36,36,36,0,Math.PI*2,true);
	context.closePath();
	context.stroke();
	context.fill();

 	$('#sb_wrapper').css('position','fixed');
 
    logoImg = new Image();
    logoImg.onload = function(){	
    //255 251 84
		context.drawImage(logoImg, 36-15, 36-15);
	
    };
  	
    logoImg.src = basedir+"assets/pp_logo2.png";
    tr = Math.floor(Math.random()*255);
    tb = Math.floor(Math.random()*255);
    tg = Math.floor(Math.random()*255);
    nr = tr; 
    nb = tb; 
    ng = tg;
    
    colorList.push( rgb2Hex(tr,tg,tb));
    colorStopList.push(1);
    
    ttt1 = setInterval("update();",50);
    
    //subvision
    updateSubvision();  
    
    //work hl
    $('.work_thumb').css('width','300px');
    $('.hl_thumb').css('width','230px');
   	$('.box').show();
   	$('.box').css('left','38px');
   	$('._btn').hide();
   	
   	$('.work_thumb').hover(function(){
   		var __type = $(this).attr('_type');
   		var _project = $(this).attr('project');
   		if ( _project!= project ){
   			if(ww> mWidth && project==""){
   				$('.work_thumb[project="'+_project+'"]').find('.box').fadeIn(100);
   			}
   			if(ww> mWidth && project!=""){
   				$('.work_thumb[project="'+_project+'"]').css("opacity",0.4);
   				$('.work_thumb[project="'+_project+'"]').find('.box').fadeIn(100);
   			}
   			$('.subvision').find('a[_type="'+__type+'"]').addClass('current');
   		}
   	},
   	function(){
   		var __type = $(this).attr('_type');
   		var _project = $(this).attr('project');
   		if ( _project!= project ){
   			if(ww> mWidth && project==""){
   				$('.work_thumb[project="'+_project+'"]').find('.box').fadeOut(100);
   			} 
   			if(ww> mWidth && project!=""){
   				$('.work_thumb[project="'+_project+'"]').css("opacity",thumbFade);
   				$('.work_thumb[project="'+_project+'"]').find('.box').fadeOut(100);
   			} 
   			$('.subvision').find('a[project!="'+project+'"]').removeClass('current');
   		}
   	
   		
   	});//end of hover

	
	$('.hl_thumb').hover(function(){
		if ( $(this).attr('project')!= project ){
			if(ww> mWidth){
				$(this).find('.box').fadeOut(100);
			} 

		}
	},
	function(){
		if ( $(this).attr('project')!= project ){
			if(ww> mWidth){
				$(this).find('.box').fadeIn(100);
			}
		}
			
		
	});//end of hover

   	//label
   	$('.label').click(function(){
   		
   		var scrollTo = wrapTop[ $('.label').index($(this))]-30;
   		var scrollDur = 800;
   		$('html, body').animate({scrollTop: scrollTo}, scrollDur);
   		
   	});
   	
   	//bg
   	$('#bg').css('position','fixed');
   	
   	//sb_block vision
   	
   	$('.sb_block.vision').delay(1500).animate({opacity:1},500);
   	$('.sb_block.subvision').delay(2000).animate({opacity:1},500);
   	/*var text = $('.sb_block.vision').text();
   	$('.sb_block.vision').attr('_text',text);
   	$('.sb_block.vision').attr('_textIndex',0);
   	
   	
   	text = text.substring(0,5);
   	$('.sb_block.vision').text(text);
   	*/
   	
   	// json
   	
   	$('.work_thumb').each(function(index){
   		var href = $(this).attr('permalink');
   		var hrefSplit = href.split('/');
   		$(this).attr('project', hrefSplit[hrefSplit.length-2]);
   		$(this).click(function(){
   			if(ww > mWidth){
	   			
	   				var _p = $(this).attr('project');
	   				document.location.href = "#/project/"+_p;
	   			
 			}
   		});  
   	});
   	
   	$('.hl_thumb').each(function(index){

   		$(this).click(function(){
   			var href = $(this).attr('permalink');
   			var target = $(this).attr('target');
   			if(ww > mWidth){
	   			
		   			if(target =="_blank"){
		   				window.open(href);
		   			}else{
		   				document.location.href = href;
		   			}
	   			
   			}
   		});  
   	});
 	
   
	// incase image is buffer
	ttt3 = setInterval('imgLoaded();',1000);

});


function updateSubvision(){
	us();
	
	subvisionList[0] = ["We create, design, develop, plan, consult and reinvent digital experiences in various media. We specialize in what we do and we are easy to work with.",""];
   	subvisionList[1] = ["Ideas in various medium including ",""];
   	$('.work_thumb:not(.detail)').each(function(i){
   		subvisionList[1][0] += "<a class='subvision_link' href='#/project/"+$(this).attr('project')+"' _type='"+$(this).attr('_type')+"' project='"+$(this).attr('project')+"'>"+$(this).attr('_type')+"</a><font>, </font>";
   	});
   	subvisionList[1][0] += ".";

   	
   	subvisionList[2] = ["Some of our projects since 2004. Our clients include JOYCE, Po Lin Monastery, MTR, The University of Hong Kong, City University of Hong Kong, School of Creative Media, Wieden+Kennedy... ",""];
   	subvisionList[3] = ["More than awards, we won clients' trust and satisfaction. We provide what is truely helpful to our clients.",""];
   	subvisionList[4] = ["We are a small and compact team of multi-talented people, and we are independent.",""];
   	subvisionList[5] = ["We are a small and compact team of multi-talented people, and we are independent.",""];

	
	$('.sb_block.subvision').after('<div id="temp_subvision" class="sb_block subvision"></div>');
	var _div = $('#temp_subvision');
	_div.css('opacity',1);
	for(var i=0;i<subvisionList.length;i++){
		_div.html(subvisionList[i][0]);
		//not so univeral for works only
		var _divTop = _div.offset().top;
		var truncated = false;
		_div.children().each(function(i){
			var pos = $(this).offset().top-_divTop;
			var maxH = wh-180-160;
			if(pos > maxH){
				$(this).addClass('to_delete');
				truncated = true;
			}
		});
		_div.find('.to_delete').remove();
		if(truncated){
			_div.append("...");
		}
		subvisionList[i][0] = _div.html();
		//
		subvisionList[i][1] = _div.text();
	}
	_div.remove();

}

function clearDetail(isEnd){//end of animatin, no follow up
	if(project!=""){
		if(isEnd){
			var afterTo = $('div[project="'+project+'"]');
			scrollToMe(afterTo,500,-30);
			
			//var scrollTo = afterTo.offset().top-30;
			//var scrollDur = 500;
			//$('html, body').delay(500).animate({scrollTop: scrollTo}, scrollDur);
		}
	}
	if(isEnd){
	$('.work_thumb').each(function(i){
		if($(this).isOnScreen()){
			$(this).animate({opacity:1}, 500);
		}else{
			$(this).css('opacity',1);
			$(this).css('z-index',1);
		}
		$(this).find('.box').hide();
	});
	}
	
	//clear detail
	project = '';
	$('._thumb.detail').stop(true).animate({opacity:0}, 500, function(){
		$(this).remove();
	});
	if(isEnd){
		expandDir = -1;
		ttt4 = setTimeout('checkResize();',600);
	}
}

function aboutToCheckResize(){
	clearTimeout(ttt2);
	ttt2 = setTimeout("readyToCheckResize();",300);
}

function readyToCheckResize(){
	clearTimeout(ttt2);
	checkResize();
}

function imgLoaded(){
	
	var loadedTotal = 0;
	
	$('img').each(function(index){
		//if($(this).attr('ow') !="" &&  $(this).attr('ow') !=0){
		if($(this).attr('ow') == null || $(this).attr('ow') == undefined  ){
			loadedTotal++;
			$(this).attr('style','');
					
			var imgW = Number(nopx($(this).css('width')));
			var imgH = Number(nopx($(this).css('height')));
			
			if(imgW != 0 && imgH !=0){
				$(this).attr('ow', imgW);
				$(this).attr('oh', imgH );
				//iLoaded++;
				//$('.l_highlight').attr("hhh", iLoaded);
				if($(this).parent().hasClass('_thumb')){
										
					// what height to show the "roll"
					var cutTop = 216;
					if($(this).parent().hasClass('hl_thumb')){
						cutTop = imgW*20;
					}	
					if($(this).parent().hasClass('work_thumb')){
						cutTop = imgW*20;
					}
					
					//
					var cutTop2 = cutTop + 20;
					$(this).parent().attr('cutTop',cutTop);
					$(this).parent().attr('cutTop2',cutTop2);
					
					$(this).parent().attr('ow', imgW);
					$(this).parent().attr('oh', imgH);
					//
					if($(this).parent().hasClass('detail')){

						$(this).parent().attr('tType', 'l');//thumbnail type, l=landscape
						$(this).parent().attr('nh', imgH);
						$(this).parent().find('.box').css('height', imgH+'px');
						$(this).parent().css('height',imgH+'px');
						
					}else{
						
						$(this).parent().attr('tType', 'l');//thumbnail type, l=landscape
						$(this).parent().attr('nh', imgH);
						$(this).parent().find('.box').css('height', imgH+'px');
						$(this).parent().css('height',imgH+'px');
							
						if($(this).parent().hasClass('work_thumb')){
							$(this).parent().find('.box').hide();
						}
							
						
						//$(this).hide();
					}
					
				}
			}
		}
	});
	if(loadedTotal == $('img').length){
		clearInterval(ttt3);
		$('body').css('overflow-y','scroll');
	}
	checkResize();
}
function draw(){
	us();
	clearCanvas();
		t2 ++;
	
		$('._thumb').each(function(index){
			var pt = $(this).offset();
			
			g.beginPath();
			g.strokeStyle="#342";
			g.moveTo((pt.left+40)/ww*800 , (pt.top-ws)/wh*600 );
			g.lineTo(400,400);
			g.stroke();
			g.closePath();
			
			g.beginPath();
			g.strokeStyle="#413";
			g.moveTo((pt.left+40)/ww*800 , (pt.top-ws+Number($(this).attr('nh')) )/wh*600 );
			g.lineTo(400,400);
			g.stroke();
			g.closePath();
			
		});
		
		
		
		/*g.fillStyle = "#F60";
		g.beginPath();
	
		g.moveTo(pList[4].x, pList[4].y);
		for(var i=0; i<10; i++){
			var j = 2+i+0.1;
			var dx = 50*Math.cos(t2*0.01*j+j);
			var dy = 50*Math.sin(t2*0.01*j+j);
			g.lineTo(pList[i].x+dx, pList[i].y+dy -ws*0.8 );
		}
		g.fill();
		g.closePath();
		*/
		
		//g.stroke();
		//g.fillRect(20,20,30,30);
}
function clearCanvas() 
{
    g.fillStyle = "#222";
    //g.fillRect(0, 0, $('#bg').width(), $('#bg').height());
    g.fillRect(0, 0, 800,600);
}
function update(){
	t+= 0.1;
	
//var ifChange = Math.random()>0.996;
	//if(ifChange){
	//	tr = Math.floor(Math.random()*255);
	//	tb = Math.floor(Math.random()*255);
	//	tg = Math.floor(Math.random()*255);	
	//}

	nr = nr*0.9 + tr*0.1;
	ng = ng*0.8 + tg*0.2;
	nb = nb*0.85 + tb*0.15;

	rCol = rgb2Hex(nr,ng,nb);


	//if(ifChange){
		$('.sb_block').css('borderTopColor',"#"+rCol);
		//$('a').css('color',"#FFFFFF");
		//$('a:hover').css('color',"#"+rCol);
	//}

	//var gc = (255-(nr+ng+nb)/3)*0.5;
	
	//var rColN2 = Math.floor(gc)*256*256+Math.floor(gc)*256+Math.floor(gc);
	//var rCol2 = rColN2.toString(16); 
	//$('#bg').css('background-color',"#"+rCol2);


	context.clearRect(0,0,72,80);	
	
	if(ww>mWidth){
		//var my_gradient = context.createLinearGradient(0, 0, mx*0.1, my*0.1);
		//var my_gradient = context.createLinearGradient(0, 0, 36+36*Math.sin(t*0.2), 72);
		var my_gradient = context.createLinearGradient(0, 0, 110, 110);
		
		my_gradient.addColorStop(0, "#"+colorList[0]);
		for(var i=0; i<colorList.length;i++){
			var tStop = (i+1)/colorList.length*0.5;
			//tStop += 0.05*Math.sin(t*0.3 + i%7);
			//tStop = Math.max(Math.min(tStop,1),0);
			colorStopList[i] = colorStopList[i]*0.9 + tStop*0.1;
			my_gradient.addColorStop( colorStopList[i], "#"+colorList[i]);
		}
		context.fillStyle = my_gradient;
		
	
		context.beginPath();
		context.arc(36,38,36,0,Math.PI*2,true);
		
		//context.Stroke();
		context.fill();
		context.closePath();


		context.beginPath();
		context.strokeStyle = 'rgba(255,255,255,0.5)';
		var aOff = t*0.1;
		context.arc(36,37,36,0+aOff,Math.PI+aOff,true);		
		context.stroke();
		context.closePath();
		
		//context.beginPath();
		//context.strokeStyle = 'rgba(0,0,0,0.5)';
		//context.arc(36,39,36,Math.PI,0,true);		
		//context.stroke();
		
		context.closePath();		
		
	}else{
		context.fillStyle = "#"+rCol;
		context.beginPath();
		context.arc(36,38,36,0,Math.PI*2,true);
		
		//context.Stroke();
		context.fill();
		context.closePath();
	}
    context.drawImage(logoImg, 36-15, 38-15);
	
	if(mx<180){
		
	}
	
	//

	
}
function update_textefx(){
	//subvision
	var oldLen = subvisionLen;
	var subT = subvisionList[subvisionIndex][1];
	//subvisionLen = Math.min(subvisionLen+7, subvisionList[subvisionIndex].length+1 );
	subvisionLen = Math.min(subvisionLen*0.95 + (subT.length+3)*0.05, subT.length+1 );
	subT = subT.substring(0,subvisionLen);
	if(oldLen != subvisionLen){
		$('.sb_block.subvision').text(subT);
	}else{
		$('.sb_block.subvision').html(subvisionList[subvisionIndex][0]);
		clearInterval(ttt9);
	}
}
function checkMove(){
	checkScroll();
}
function checkMove2(){
	checkScroll2();
}
function checkScroll(){
	us();	
	
	if(ww> mWidth){
		if(mx>180){			
			$('.label').each(function(i){
				if(ws< wrapTop[i]-30){
					$(this).css('position','absolute');
					if($(this).hasClass("intro")){
						$(this).animate({top:wrapTop[i]+'px'}, 500, "easeInOutCubic");
						$(this).removeClass("intro");
					}else{
						$(this).css('top', wrapTop[i]+'px');
					}
				}
				if(ws>= wrapTop[i]-30 && ws< wrapTop[i+1]-250-36){
					$(this).css('position','fixed');
					if($(this).hasClass("intro")){
						$(this).animate({top:'30px'}, 500, "easeInOutCubic");
						$(this).removeClass("intro");
					}else{
						$(this).css('top', '30px');
					}
					
				}
				if(ws> wrapTop[i+1]-250-36){
					$(this).css('position','absolute');
					if($(this).hasClass("intro")){
						$(this).animate({top:wrapTop[i+1]-250+'px'}, 500, "easeInOutCubic");
						$(this).removeClass("intro");
					}else{
						$(this).css('top', wrapTop[i+1]-250+'px');
					}
				}
				$(this).find('.label_arrow').show();
			});
			
		}else{
			var startY = 30;
			$('.label').each(function(i){
				if(ws>= wrapTop[i]-30 && ws< wrapTop[i+1]-250-36){
					$(this).find('.label_arrow').show();
				}else{
					$(this).find('.label_arrow').hide();
				}
			
				$(this).css('position','fixed');
				$(this).css('top', startY+'px');
				startY += nopx($(this).css('height'))+10;
			});
		}
		// subvision
		$('.label').each(function(i){
			if(ws>= wrapTop[i]-30 && ws< wrapTop[i+1]-250-36){
				if(subvisionIndex != i){
					subvisionIndex = i;
					subvisionLen = 0;
					clearInterval(ttt9);
					ttt9 = setInterval("update_textefx();",10);
				}
				//$('.sb_block.subvision').text(subvisionList[i]);
			}
			
		});
		
	}else{
		$('.label').each(function(index){
			$(this).find('.label_arrow').show();
			$(this).css('position','absolute');
			$(this).css('top',wrapTop[index]-50+'px');
		});
	}

}
function checkScroll2(){
	us();	
	
	if(ww> mWidth){
		if(mx>180){	
			$('.label').each(function(i){
				if($(this).css('position')=="fixed"){

				}
		
				if(ws< wrapTop[i]-30){
					var _y = $(this).offset().top;
					
					$(this).css('position','absolute');
					$(this).css('top', _y +'px');
					
					//$(this).css('top', wrapTop[i]+'px');
					$(this).stop(true).animate({top:wrapTop[i]+"px"}, 500, "easeInOutCubic");
				}
				if(ws>= wrapTop[i]-30 && ws< wrapTop[i+1]-250-36){
					$(this).css('position','fixed');
					//$(this).css('top', '30px');
					$(this).stop(true).animate({top:30+"px"}, 500, "easeInOutCubic");
				}
				if(ws> wrapTop[i+1]-250-36){
					var _y = $(this).offset().top;
					$(this).css('position','absolute');
					$(this).css('top', _y +'px');
					
					//$(this).css('top', wrapTop[i+1]-250+'px');
					$(this).stop(true).animate({top:wrapTop[i+1]-250+"px"}, 500, "easeInOutCubic");
				}
				$(this).find('.label_arrow').show();
			});
			
		}else{
			var startY = 30;
			$('.label').each(function(i){
				if(ws>= wrapTop[i]-30 && ws< wrapTop[i+1]-250-36){
					$(this).find('.label_arrow').show();
				}else{
					$(this).find('.label_arrow').hide();
				}
				
				var _y = $(this).offset().top;
				
				$(this).css('position','fixed');
				$(this).css('top', _y-ws+'px');
				
				$(this).stop(true).animate({top:startY+'px'},500+i*50,"easeInOutCubic");
				startY += nopx($(this).css('height'))+10;
			});
		}
	}else{
		$('.label').each(function(index){
			$(this).find('.label_arrow').show();
			$(this).css('position','absolute');
			$(this).css('top',wrapTop[index]-50+'px');
		});
	}
}
function checkResize(){
	us();

	updateSubvision();
		
	var wrapX = '23px';
	if(ww <= mWidth){
		$('#logo').attr('style', "");
		$('#logo').css('position','absolute');
		$('#logo').css('top',70+"px");
		$('#logo').css('left',ww/2-36+"px");
		
		$('#sb_wrapper').attr('style', "");
		$('#sb_wrapper').css('position','absolute');
		$('#sb_wrapper').css('top',70+72+70+"px");
		$('#sb_wrapper').css('right',23+"px");
		$('#sb_wrapper').css('width',ww-23-23+"px");
				
		$('.p_fixed, .p_portrait').css('max-width','300px');
		$('.col_projectlist').css('max-width','300px');
	}else{
		$('#logo').attr('style', "");
		$('#logo').css('position','fixed');
		$('#logo').css('bottom',30+"px");
		$('#logo').css('right',40+"px");
		//
		$('#sb_wrapper').attr('style', "");
		$('#sb_wrapper').css('position','fixed');
		$('#sb_wrapper').css('top',28+"px");
		$('#sb_wrapper').css('right',15+"px");
		$('#sb_wrapper').css('width',125+"px");
		
		$('.p_fixed, .p_portrait').css('max-width','500px');
		$('.col_projectlist').css('width','300px');
		wrapX = '180px';
	}
	$('.wrap').css('left',wrapX);
	
	/////////////// highlight
	
	var startY = 30;
	if(ww <= mWidth){
		startY = 500;
	}
	var startX = 40;
	wrapTop[0] = startY;
	$('.wrap_highlight').css('top',startY+'px');
	
	
	//////////////////////////////////////////////////////////////////////////////////
	//work
	//////////////////////////////////////////////////////////////////////////////////
	$('.wrap_highlight').css('top',startY+'px');
	
	var wrapH = positionThumb('.hl_thumb',230, startY);
	
	startY += wrapH+150;
	wrapTop[1] = startY;
	//////////////////////////////////////////////////////////////////////////////////
	//work
	//////////////////////////////////////////////////////////////////////////////////
	$('.wrap_work').css('top',startY+'px');
	
	var wrapH = positionThumb('.work_thumb',300, startY);
	
	startY += wrapH+150;
	wrapTop[2] = startY;
	
	//project list
	var ii=0;
	var lastStartChar = "_";
	var plMax = ($('.all_projectlist').find('p').length);
	var colMax = Math.ceil(plMax/3);
	$('.all_projectlist').find('p').each(function(i){
		var iii = Math.floor(ii/colMax);
		var startChar =  $(this).html().substring(0,1).toUpperCase();
		if(startChar != lastStartChar){
			//$('.col_projectlist').eq(iii).append('<p>'+startChar+'</p>');
			//lastStartChar = startChar;
			//ii +=1;
		}
		$('.col_projectlist').eq(iii).append( $(this));
		//$('.col_projectlist').eq(ii).append( $('<br/>'));
		ii +=1;
	});
	$('.all_projectlist').remove();
	
	
	$('.wrap_projectlist').css('top',startY+'px');
	wrapH = nopx($('.wrap_projectlist').css('height'));
	startY += wrapH+150;
	wrapTop[3] = startY;
	//awards
	$('.wrap_awards').css('top',startY+'px');
	wrapH = nopx($('.wrap_awards').css('height'));
	startY += wrapH+150;
	wrapTop[4] = startY;
	//director
	$('.wrap_director').css('top',startY+'px');	
	wrapH = nopx($('.wrap_director').css('height'));
	startY += wrapH+150;
	wrapTop[5] = startY;
	//contact
	$('.wrap_contact').css('top',startY+'px');
	wrapH = nopx($('.wrap_contact').css('height'));	
	startY += wrapH+150;
	wrapTop[6] = startY;
	//
	wwOld = ww;
	//
	checkScroll();
}

function positionThumb(_class, _w, startY){
	var tw = 0;
	var th = 0;
	var padX = 40;
	var padY = 40;
	var wrapH = 0;
	var hListIndex = 0;
	var colMax = 0;
	var hList = new Array();
	var hListIndex = 0;
	var row = 0;
	startX = -40;
	var moveIndex=0;
	var moveCount = 0;
	
	for(var i=0;i<50;i++){
		hList[i]=0;
	}
	
	var itemList = new Array();
	$(_class).each(function(index){
		itemList.push($(this));
	});
	
	for(var i=0; i<itemList.length; i++){
		
		var imgW,imgH, imgH2;
		
		if( !isNaN( Number(itemList[i].attr('nh'))) ){
			
			imgW = Number(itemList[i].attr('ow'));
			imgH = Number(itemList[i].attr('nh'));
			imgH2 = Number(itemList[i].attr('oh'));
		}else{
//			alert(itemList[i].attr('ow'));
		
			imgW = _w;
			imgH = 300;
			imgH2 = 300;			
		}
		
		
		
		var box = itemList[i].find('.box');
		var _cut = itemList[i].find('._cut');
		var _btn = itemList[i].find('._btn');
		
		if(ww<= mWidth){
		// iphone?
			
			itemList[i].find('img').show();
			itemList[i].css('backgroundPosition',"-2000px 0px");
			
			var iw = ww-23-23;
			var ih = iw/imgW*imgH2;			
			
			itemList[i].find('img').css('width', iw+'px');
			itemList[i].find('img').css('height', ih+'px');
			imgW = iw;
			imgH = ih;
			
			_btn.hide();
			box.show();
			
			itemList[i].css('width', iw+'px');
			itemList[i].css('height', ih+'px');
			//
			box.css('top',imgH+'px');
			box.css('width',imgW+'px');
			box.css('height',150+'px');
			
			imgH += 150;	
			itemList[i].css('height',imgH+'px');
		
			padY = 20;
		}else{
		// regular web
			var nh = itemList[i].attr('nh');
			var ow = itemList[i].attr('ow');
		
			//itemList[i].find('img').hide();
			itemList[i].css('backgroundPosition',"40px 0px");
			
			itemList[i].css('width', _w+'px');
			itemList[i].css('height', nh+'px');
			
			box.css('top',0+'px');
			box.css('width',_w+'px');
			box.css('height',nh+'px');
			
			if(itemList[i].hasClass('work_thumb') ){
				//box.hide();
			}else{
				//box.show();
			}
			
			itemList[i].find('img').css('width', ow+'px');
			itemList[i].find('img').css('height', nh+'px');
			
			//itemList[i].find('img').css('width', imgW+'px');
			//itemList[i].find('img').css('height', imgH+'px');
		}
		
		if(row == 0){
			if(startX + imgW+padX > ww-180-180){
				row ++;
			}
		}
		
		if(row != 0){
			//find tw
			var colH = 99999;
			for(var ii=50-1;ii>=0;ii--){
				if( hList[ii] !=0){
					if(hList[ii]<= colH){
						colH = hList[ii];
						hListIndex = ii;
					}
				}
			}
		}

		th = hList[hListIndex];	
		tw = (imgW+padX ) * hListIndex -40;

		//buffer position and compare if tween needed
		
		var ox = Number(itemList[i].attr('ox'));
		var oy = Number(itemList[i].attr('oy'));
		
		itemList[i].attr('tx',tw);
		itemList[i].attr('ty',th);
		
		var nh = Number(itemList[i].attr('nh'));
		
		if(ox != tw || oy != th){
			//check if on screen		
			var onScreen1 = (itemList[i].offset().top > ws && itemList[i].offset().top+nh < ws+wh);
			var onScreen2 = (itemList[i].offset().top-oy+th > ws && itemList[i].offset().top-oy+th+nh < ws+wh);
					
			if( (onScreen1 || onScreen2) && ww>=wwOld){
				moveCount +=1;
			}		
		}
	
		
		//itemList[i].css('left', tw+'px');
		//itemList[i].css('top', th+'px');
		
		//itemList[i].find('div.toptip').css('height',imgH+"px");//if have prob, go to this later
		
		//h must be a multiplier of 60px
		//var divH = Math.ceil((imgH+padY)/20)*20;
		var divH = imgH+padY;
		
		hList[hListIndex] += divH;
		wrapH = Math.max(wrapH , hList[hListIndex]);
		
		
		//alert(nopx($(this).css('height')));
		startX += imgW + padX;
		hListIndex ++;
	}
	for(var i=0; i<itemList.length; i++){
		//if(ww> mWidth){
		
			var ox = Number(itemList[i].attr('ox'));
			var oy = Number(itemList[i].attr('oy'));
			
			var tw = Number(itemList[i].attr('tx'));
			var th = Number(itemList[i].attr('ty'));
			
			var nh = Number(itemList[i].attr('nh'));
			
			var _delay = 0;
			if(ox != tw || oy != th){
				//check if on screen

				
				var onScreen1 = (itemList[i].offset().top+nh > ws && itemList[i].offset().top < ws+wh);
				var onScreen2 = (itemList[i].offset().top-oy+th+nh > ws && itemList[i].offset().top-oy+th < ws+wh);
				if( ((onScreen1 || onScreen2) && ww>=wwOld)|| itemList[i].hasClass('intro')){
					//itemList[i].removeClass('intro');
					_delay = Math.ceil(moveIndex/2)*250;
					if(expandDir == 1){
						_delay = Math.ceil((moveCount-moveIndex)/2)*250;
					}
					itemList[i].attr('delay', _delay);
					itemList[i].stop(true).delay( _delay).animate({left:tw+"px"}, 350, "easeInOutCubic");
					itemList[i].animate({top:th+"px"}, 350, "easeInOutCubic");
					
					_delay += 350+350+50;
					
					
					moveIndex+=1;
				}else{

					itemList[i].css('left', tw+'px');
					itemList[i].css('top', th+'px');
				}
				
			}
			if(itemList[i].hasClass('scrollToMeAfterResize')){
				itemList[i].removeClass('scrollToMeAfterResize');
				scrollToMe(itemList[i],_delay,-30 +th-oy );
				
			}
			
		
			itemList[i].attr('ox', tw);
			itemList[i].attr('oy', th);
		}
	//}
	return wrapH;
}
function open_project(){
	$('.work_thumb[project!="'+project+'"]').each(function(i){
		if( $(this).isOnScreen() ){
			$(this).animate({opacity:thumbFade}, 500);
		}else{
			$(this).css('opacity',thumbFade);
		}
	});
	
	expandDir = 1;
	
	var afterTo = $('div[project="'+project+'"]');
	afterTo.css('opacity',1);
	afterTo.find('.box').show();
	afterTo.css('z-index',10);
	//
	afterTo.addClass('scrollToMeAfterResize');
	
	pageTitle = afterTo.attr("_title");
	$.address.title("pill & pillow | "+pageTitle);
	
	scrollToMe(afterTo,0,-30);
	//var scrollTo = afterTo.offset().top-30;
	//var scrollDur = 500;
	//$('html, body').delay(500).animate({scrollTop: scrollTo}, scrollDur);
	
}
function updateLoading(){
	$('#loading').css('backgroundPosition-y', loadingCount%2*20+'px');
	loadingCount++;
}
function get_J_project(){
	
	var afterTo = $('div[project="'+project+'"]');
	var startX = afterTo.css('left');
	var startY = afterTo.css('top');
	
	var isBlk = afterTo.find('.box').hasClass('blktext');
	var loadingClass = "";
	if(isBlk){
		loadingClass = "blk";
	}
	
	afterTo.find('.box').append($('<div id="loading" class="'+loadingClass+'" href="#"></div>'));
	ttt6 = setInterval("updateLoading();",200);
	
	var bgC = afterTo.find('.box').css('background-color');
	var i1 = bgC.indexOf('(');
	var bgC = bgC.substring(i1+1,bgC.length-1);
	var cStr = bgC.split(',');
	
	tr = Number(cStr[0]);
	tg = Number(cStr[1]);
	tb = Number(cStr[2]);

	//var rPos = Math.floor(Math.random()*colorList.length);
	
	//var rmv = 0;
	if(colorList.length>=2){
		colorList.shift();
		colorStopList.shift();
	}
	//colorList.splice(rPos,rmv,rgb2Hex(tr,tg,tb));
	//colorStopList.splice(rPos,rmv,colorStopList[rPos]);
	
	colorList.push( rgb2Hex(tr,tg,tb));
	colorStopList.push( 1);
	
	bgC = 'rgb(0,0,0)';
	
	$.getJSON("work/"+project+"/",
		  {
		    json: 1,
		    custom_fields: 'img,year,credit,award,colour,info,textcolour,linkurl,embed_video'
		  },
		  function(data) {
		  	  //remove loading
		  	  $('#loading').remove();
			  //
			  
			  var div_str = "";

			  //video
			  if(data.post.custom_fields.embed_video != null){
			  	$.each(data.post.custom_fields.embed_video, function(i,item){
			  		div_str += '<div class="work_thumb _thumb detail detail_video" style="left: '+startX+'; top: '+startY+'; width: 300px; background-position: 40px 0px; " tx="-40" ty="0"><div class=" box " style="left: 38px; display: block; top: 0px; width: 300px; "><p>'+item+'</p></div></div>';
			  		
			  	});
			  }

			  //img
			  $.each(data.post.custom_fields.img, function(i,item){
			  		div_str += '<div class="work_thumb _thumb detail" style="left: '+startX+'; top: '+startY+'; width: 300px; background-position: 40px 0px;" tx="-40" ty="0"><img class="load" src="http://www.pillandpillow.com/v7/media//cache/th_cd2256854e5021675d91a931e783df24_'+item+'" style="display: none; "></div>';
			  });
			  
			  //description
			  div_str += '<div class="work_thumb _thumb detail detail_text" style="left: '+startX+'; top: '+startY+'; width: 300px; background-position: 40px 0px; " tx="-40" ty="0"><div class=" box " style="left: 38px; display: block; top: 0px; width: 300px; "><p>'+data.post.custom_fields.info+'</p></div></div>';

			//year, credit, award
			div_str += '<div class="work_thumb _thumb detail detail_text" style="left: '+startX+'; top: '+startY+'; width: 300px; background-position: 40px 0px; " tx="-40" ty="0"><div class=" box " style="left: 38px; display: block; top: 0px; width: 300px; height: 240px; "><div class="sWork_misc">Year: <p>'+data.post.custom_fields.year+'</p></div>'+
				'<div class="sWork_misc">Credits: <p>'+data.post.custom_fields.credit+'</p></div>'+
				'<div class="sWork_misc detail_awards">';
			
			var awardMax = 0;
			$.each(data.post.custom_fields.award, function(i,item){
					if(i==0 && item!=""){
						div_str += 'Awards:<p>'; 
					}
					div_str += item+'<br/>';
					awardMax ++;
			});			  
			if(awardMax>=0){
				div_str += '</p>';
			}
			div_str += '</div></div></div>';


			//link
  			  div_str += '<div class="work_thumb _thumb detail detail_text" style="left: '+startX+'; top: '+startY+'; width: 300px; background-position: 40px 0px; " tx="-40" ty="0"><div class=" box " style="left: 38px; display: block; top: 0px; width: 300px; height: 240px; ">';
  			  $.each(data.post.custom_fields.linkurl, function(i,item){
  			  		div_str += '<a class="url" href="'+item+'" target="_blank">'+item+'</a>'
  			  });
  			  div_str += '</div></div>';
		  		
		  	//close
		  	div_str += '<div class="work_thumb _thumb detail detail_text" style="left: '+startX+'; top: '+startY+'; width: 300px; height:60px; background-position: 40px 0px; " tx="-40" ty="0"><div class=" box " style="left: 38px; display: block; top: 0px; width: 300px; height: 60px; "><p><a class="btn_close" href="#/"></a></p>'+  '</div></div>';	
		  	
			  
			var div_ = $(div_str);
			//div_.after(afterTo);
			//afterTo.insertAfter(div_);
			afterTo.after(div_str);
			 
			$('.detail_text').each(function(i){

				if( $(this).find('p.detail_awards').html() == "Awards: <p></p>"){
					$(this).find('p.detail_awards').remove();
				}  
			
				var str = $(this).find('.box').html();
				str=str.replace(/\n/g,"<br/>");
				$(this).find('.box').html( str ) ;
				
				var divH = Math.max(nopx($(this).find('.box').css('height')),100) +30;
				//alert(divH);
				$(this).css('height',divH+"px");
				$(this).attr('nh', divH);
				$(this).attr('oh', divH);
				$(this).attr('ow', 300);
			});
			  
			$('.detail_video').each(function(i){
			
				var divH = nopx($(this).find('object').css('height'));
				var divH2 = nopx($(this).find('iframe').css('height')); 
				divH = Math.max(divH,divH2);
				
				$(this).css('height',divH+"px");
				$(this).attr('nh', divH);
				$(this).attr('oh', divH);
				$(this).attr('ow', 300);
			});
			  
  
			$('img.load').load(function(){
				imgLoaded();	
			});
			  
			  
			  /*var div_ = $(  
			  	'<div class="work_thumb _thumb" style="left: -40px; top: 0px; width: 300px; background-position: 40px 0px; " tx="-40" ty="0"><img src="http://www.pillandpillow.com/v7/media//cache/th_cd2256854e5021675d91a931e783df24_'+data.post.custom_fields.img[0]+'" style="display: none; "></div>'
			  );*/
			  
			  //div_.appendTo($('.wrap_work'));
			  /*$.each(data.post.custom_fields.img, function(i,item){
			  		img_ = $('<img src="../media/'+item+'">');
			  		img_.appendTo($('#prj_content_wrapper').find('div#gallery'));
			  });*/
			  
			  //prj_content_init();
			  //galleryInit();
		 	  
		 	  //scroll
		 	  
		});
}
function scrollToMe(target,delay,yoff){
	var scrollTo = target.offset().top+yoff;
	var scrollDur = 500;
	$('html, body').delay(delay).animate({scrollTop:scrollTo}, scrollDur);
}

function us(){//update window size
	ww = $(window).width();
	wh = $(window).height();
	sw = screen.width;
	sh = screen.height;
	ws = $(window).scrollTop();
}
function nopx(s){
	if(s=="undefined" || s==null){
		s="0";
	}
		var i = parseInt(s.replace("px", "") );
		return Number(i);
	
}
function rgb2Hex(_r,_g,_b){
	var rColN = Math.floor(_r)*256*256+Math.floor(_g)*256+Math.floor(_b);
	var rColStr = "000000"+rColN.toString(16);
	return rColStr.substring( rColStr.length-6, rColStr.length );
}

function nl2br (str, is_xhtml) {   
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';    
	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
