var lightsOn = true;

var cx, cy, shadow, textShadow, templatePath;

function toggleLights(){
	if(lightsOn) switchLightsOff();
	else switchLightsOn();
}

function switchLightsOff(){
	$('body').append('<div id="spot"><div id="light">&nbsp;</div></div>');
	initSpotlight();
	$(window).resize(initSpotlight);
      	if(document.getElementById('frame-top')) normalmap('frame-top', templatePath+'images/frame_top.jpg', templatePath+'images/nrm/frame_top.jpg', 1, 1);
	if(document.getElementById('frame-left')) normalmap('frame-left', templatePath+'images/frame_left.jpg', templatePath+'images/nrm/frame_left.jpg', 1, 1);
	if(document.getElementById('frame-right')) normalmap('frame-right', templatePath+'images/frame_right.jpg', templatePath+'images/nrm/frame_right.jpg', 1, 1);
	if(document.getElementById('frame-bottom')) normalmap('frame-bottom', templatePath+'images/frame_bottom.jpg', templatePath+'images/nrm/frame_bottom.jpg', 1, 1);
	$(document).mousemove(updateSpotlight);
	$('#light-switch .status').text('on');
	lightsOn = false;
}

function switchLightsOn(){
	$(document).unbind('mousemove');
	$(window).unbind('resize',initSpotlight);
	$('#spot').remove();
	$('.shadow').removeAttr('style');
	$('.text-shadow').removeAttr('style');
	if(document.getElementById('frame-top')) clearCanvas('frame-top');
	if(document.getElementById('frame-left')) clearCanvas('frame-left');
	if(document.getElementById('frame-right')) clearCanvas('frame-right');
	if(document.getElementById('frame-bottom')) clearCanvas('frame-bottom');
	$('#light-switch .status').text('off');
	lightsOn = true;
}

function checkBrowser(){
	if(!navigator.userAgent.toLowerCase().match(/(iphone|ipod|ipad)/) && (jQuery.browser.webkit || jQuery.browser.mozilla))
		return true;
	return false;
}

function initSpotlight(){
	shadow = $('.shadow');
	textShadow = $('.text-shadow');
	spot = $('#light');		
	$('#spot').css('height',$(document).height()+'px');
	cx = Math.ceil($(document).width() / 2);
	cy = Math.ceil($(document).height() / 2);
}

function updateSpotlight(e){
	var dx, dy, sx, sy, blur;
	var s = shadow;
	var ts = textShadow;
	dx = e.pageX - cx;
	dy = e.pageY - cy;
	if(s || ts){
		sx = -dx * 0.04;
		sy = -dy * 0.04;
		blur  =  (Math.abs(sx) + Math.abs(sy)) * 2 + 20;
		if(s){
			s.css('boxShadow',sx+'px '+sy+'px '+blur+'px #000');
			s.css('MozBoxShadow',sx+'px '+sy+'px '+blur+'px #000');
			s.css('WebkitBoxShadow',sx+'px '+sy+'px '+blur+'px #000');
		}
		if(ts){
			ts.css('textShadow',(sx/2.5)+'px '+(sy/2.5)+'px '+(blur/10)+'px #000');
		}
	}
	spot.css('backgroundPosition' ,(dx-cx) + 'px ' + (dy-cy) + 'px');
}

function embedVideo(video) {
    if(isNaN(video) && video.html){
		document.getElementById('frame-center').innerHTML = unescape(video.html);
		//document.getElementById('vimeoplayer').api_setVolume(0);
   } else {
	if(!checkBrowser() ){
		$('#frame-center').html('<iframe src="http://player.vimeo.com/video/'+video+'?title=0&byline=0&portrait=0&color=ffffff&autoplay=0&width=648&height=349" width="648" height="349" frameborder="0"></iframe>');
	}else{
		var url = 'http://vimeo.com/api/oembed.json?url=' + encodeURIComponent('http://vimeo.com/'+video) + '&callback=embedVideo&title=0&byline=0&portrait=0&color=ffffff&autoplay=0&iframe=false&width=648&height=349&wmode=transparent';
		var js = document.createElement('script');
		js.setAttribute('type', 'text/javascript');
		js.setAttribute('src', url);
		document.getElementsByTagName('head').item(0).appendChild(js);
	}
    }
}


// this is basically where the magic happens
function drawLight(canvas, ctx, normals, textureData, shiny, specularity, lx, ly, lz) {
    var sqrt = Math.sqrt;
    var pow = Math.pow;
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    var data = imgData.data;
    var i = 0;
    var ni = 0;
    var dx = 0, dy = 0, dz = 0;
    var magInv, dot, intensity, t1, t2, t3;
    for(var y = 0; y < canvas.height; y++) {
        for(var x = 0; x < canvas.width; x++) {
            // make it a bit faster by only updating the direction
            // for every other pixel
            if(shiny > 0 || (ni&1) == 0){
                // calculate the light direction vector
                dx = lx - x;
                dy = ly - y;
                dz = lz;

                // normalize it
                magInv = 1.0/sqrt(dx*dx + dy*dy + dz*dz);
                dx *= magInv;
                dy *= magInv;
                dz *= magInv;
            }
            // take the dot product of the direction and the normal
            // to get the amount of specularity
            dot = dx*normals[ni] + dy*normals[ni+1] + dz*normals[ni+2];
            // spec + ambient
            intensity = pow(dot, 20)*specularity+pow(dot, 400)*shiny + 0.5;
	    t1 = textureData[i]*intensity;
	    t2 = textureData[i+1]*intensity;
            t3 = textureData[i+2]*intensity;
	    //update all 3 channels
	    data[i] = (t1 < 0) ? 0 : ((t1 > 255) ? 254: t1);
	    data[i+1] = (t2 < 0) ? 0 : ((t2 > 255) ? 254: t2);
            data[i+2] = (t3 < 0) ? 0 : ((t3 > 255) ? 254: t3);
            i += 4;
            ni += 3;
        }
    }
    ctx.putImageData(imgData, 0, 0);
}

function normalmap(canvasId, texture, normalmap, specularity, shiny) {

    var canvas = document.getElementById(canvasId);
    if(canvas.getContext == undefined) return;

    var ctx = canvas.getContext('2d');

    var normalData = null;
    var textureData = null;

    function getDataFromImage(img) {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.clearRect(0, 0, img.width, img.height);
        ctx.drawImage(img, 0 ,0);
        return ctx.getImageData(0, 0, img.width, img.height);
    }

    function loadImage(src, callback) {
        var img = document.createElement('img');
        img.onload = callback;
        img.src = src;
        return img;
    }

    var normals = [];
    var textureData = null;
    var normalsImg = loadImage(normalmap, function() {
        var data = getDataFromImage(normalsImg).data;
        // precalculate the normals
        for(var i = 0; i < canvas.height*canvas.width*4; i+=4) {
            var nx = data[i];
            // flip the y value
            var ny = 255-data[i+1];
            var nz = data[i+2];

            // normalize
            var magInv = 1.0/Math.sqrt(nx*nx + ny*ny + nz*nz);
            nx *= magInv;
            ny *= magInv;
            nz *= magInv;

            normals.push(nx);
            normals.push(ny);
            normals.push(nz);
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        var textureImg = loadImage(texture, function() {
            textureData = getDataFromImage(textureImg).data;
            main();
        });

    });

    var z = 400;
    var offset = $(canvas).offset();
    function main() {
        $(document).mousemove(function(e) {
            drawLight(canvas, ctx, normals, textureData, shiny, specularity, e.clientX-offset.left+z/2, e.clientY-offset.top+z/2, z);
        });
    }
}

function clearCanvas(id) {
  var canvas = document.getElementById(id);
  var context = canvas.getContext('2d');
  context.clearRect(0, 0, canvas.width, canvas.height);
  var w = canvas.width;
  canvas.width = 1;
  canvas.width = w;
}


var socialItems;
function updateSocial(){
	if(socialItems.length){
		var c = $('#social');
		var i = socialItems[Math.floor(Math.random()*socialItems.length)];
		var t = i['y:published'];
		var time = $.timeago(t.year+'-'+t.month+'-'+t.day+'T'+t.hour+':'+t.minute+':'+t.second+'Z');
		var href = i.link;
		var title = i.title;
		var thumb;
		if(i['media:content'] && i['media:content']['media:thumbnail'] && i['media:content']['media:thumbnail']['url'])
			thumb = i['media:content']['media:thumbnail']['url']+'?ts='+(new Date()).getTime();
		else
			thumb = 'http://www.gravatar.com/avatar/3217b07e172e2b9b3620840aa5c40759.jpg?s=60&ts='+(new Date()).getTime();
		c.fadeOut('fast',function(){
			$('.hidden',c).removeClass('hidden');
			$('a',c).attr('href',href);
			$('.title',c).text(title);
			$('.time',c).text(time);
			$('img',c).one('load',function(){ 
				c.fadeIn('slow',function(){
					setTimeout('updateSocial()',5000);
				});
			}).attr('src',thumb);	
		});
	}
}


function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}

