/*
	We're going to mindfuck people, we're going to use persistance of vision POV. 
	Because our brains are so smart, we can see the image that was previously there for a few seconds.
	it then fades away, just like looking into the sun.. you'll get those sun spots remaining in your eye.
																																					- edge-u-paul-mi-kay-tion
																																					
	i have closure: var that = this

    FYI - Copyright Paul Adams 2011 paul-misterg @ chaos-studio.com

*/




function pic_sil(target, location) {
	this.fps = 12;
	/* leave me alone! */
	this.intervalv = 1000 / this.fps;
	this.pleasestop = 0;
	this.target = target;
	this.location = location;
	this.toload = 0;
	this.loaded = 0;

	this.hero = new Image();
	this.current = -1;
	this.imagebank = [];
	
	this.timer = null;
	
	this.p = $(target)[0].getContext("2d");
	this.pw = $(target).width();
	this.ph = $(target).height();
	
	
	this.init = function () {

		if (!$(this.target).length || $(this.target).css('display') == "none") {return 'Target Does not exist';}
		var that = this; //closure support!!
     $(".audio").jPlayer("destroy");
		$.getJSON(this.location+'data.json', function(data) {
			
			/* initialize what we need */
			var images = [];
			/* load the hero image */
	
	
			that.hero.src = that.location+data.Hero;
			$('.playerbar p').replaceWith('<p>'+data.Date+'<br />'+data.Tag+'</p>'); //should be the only external access
			
			/* draw the hero image */
			var mp3 = that.location+data.mp3;
      var ogg = that.location+data.ogg;

        $(".audio").jPlayer({
          ready: function (event) {
            $(this).jPlayer("setMedia", {
              mp3: mp3,
              oga: ogg

            });
          },
          swfPath: "/js",
          supplied: "mp3, oga",
          wmode: "window",
          loop: "true"
        });
      
			/* load the data */
			$.each(data.Sequence, function(key, val) {

				that.loadinggroup();
				
				images[val.id] = new Image();
				images[val.id].src = that.location + val.name;

				images[val.id].onload = function() {

					/* this is the list of images we've loaded so far, in order of load */
					that.playable(val.id, images[val.id], val.time, {w: images[val.id].width, h:images[val.id].height});
				};
				images[val.id].onerror = function() {
          that.loaded++;
        };
		
			});
		});	 
	
			
		
	}
  //is there a reason why i kept this externalized?
  /*
	this.black = function() {
		picsil.p.shadowColor='rgba(0, 0, 0, 0)';
		picsil.p.globalAlpha = 1;
		picsil.p.fillStyle = "#000";
		picsil.p.fillRect  (0,0, picsil.pw, picsil.ph);
	}
  */
 	this.black = function() {
		this.p.shadowColor='rgba(0, 0, 0, 0)';
		this.p.globalAlpha = 1;
		this.p.fillStyle = "#000";
		this.p.fillRect  (0,0, this.pw, this.ph);
	}
	this.playable = function(position,image,delay, details) {
		if (delay == 0) {delay = this.intervalv;} 
		//we can record how to play now.
		this.imagebank.push({'pos': position, 'link': image, 'delay': delay, 'details':details});
		this.loaded++;
		//draw the updated status over hero
		this.loading();
	}
	this.reorder = function() {
		/*execute this before playing*/
		var clean1 = new Array();
		var clean2 = new Array();
		
		$.each(this.imagebank, function(key, val) {
			if (val !== undefined) {
				clean1[val.pos] = {'pos': val.pos, 'link': val.link, 'delay': val.delay, 'details':val.details};
			}
		});
		
		$.each(clean1, function(key, val) {
				if (val !== undefined) {
					clean2.push({'pos': val.pos, 'link': val.link, 'delay': val.delay, 'details':val.details});
				}
		});
		
		this.imagebank = clean2;
		
	}
	this.loading = function() {
		this.p.drawImage(this.hero, 0, 0);
		this.p.fillStyle    = '#CCC';
		this.p.textBaseline = 'top';
		this.p.font         = 'bold 14px sans-serif';
		this.p.fillText('LOADING: '+ parseFloat(Math.round(100/this.toload * this.loaded)) +'%', this.pw/2-50, this.ph/2-20);
		if (parseFloat(Math.round(100/this.toload * this.loaded)) == 100) {
			this.current = 0;
			this.start();
		}
	}
	this.next = function(){
		if(this.current < this.imagebank.length-1) {
			this.current++;
		} else {
			this.current = 0;
		}
    this.background();

		var info = this.imagebank[this.current]['details'];

    if ((info.w != this.pw) || (info.h != this.ph)) {
       var nW = 0;
       var nH = 0;
       var x = 0;
       var y = 0;
       
      if (info.w > this.pw) {
        //too wide
        nW = this.pw;
        nH = (info.h/info.w) * this.pw;
        //offset position
        y = (this.ph - nH) / 2;
      } else if (info.h > this.ph) {
        //too tall
        nW = (info.w/info.h) * this.ph;
        nH = this.ph;
        //offset position
        x = (this.pw - nW) /2;
      }
     // drawImage(image, dx, dy, dw, dh)
      this.p.drawImage(this.imagebank[this.current]['link'], x, y, nW, nH);
		} else {
			this.p.drawImage(this.imagebank[this.current]['link'], 0, 0);
		}


//    this.p.drawImage(this.imagebank[this.current]['link'], 0, 0);
	}

	this.previous = function() {
		if(this.current > 0) {
			this.current--;
		} else {
			this.current = this.imagebank.length-1;
		}
    this.background();
		this.p.drawImage(this.imagebank[this.current]['link'], 0, 0);
	}
  this.background = function() {
    this.p.shadowColor='rgba(0, 0, 0, 0)';
		this.p.globalAlpha = 1;
		this.p.fillStyle = "#000";
		this.p.fillRect  (0,0, this.pw, this.ph);
  }
	this.start = function() {
    $(".audio").jPlayer("play");
		var that = this;
		//need to reorder our images first as the load could have gone out of whack/or we injected more.
		this.reorder();
		//
		this.p.drawImage(this.imagebank[this.current]['link'], 0, 0);
		// no way to test if an event is bound, so we blindly unset it first.
		$(this.target).unbind('click');$(this.target).click(function () {clearTimeout(that.timer);that.pause();});
		$(document).unbind('keydown');$(document).keydown(function (evnt) {that.onKeyDown(evnt);});
		clearTimeout(this.timer);
		this.timer = setTimeout( function() {that.play();}, this.imagebank[this.current]['delay']);
    
	}
	this.play = function() {
		var that = this;
		this.next();

		if (this.pleasestop !== 1) {
			this.timer = setTimeout( function() {that.play();}, this.imagebank[this.current]['delay']);
		} else {
     $(".audio").jPlayer("pause"); 
			this.black();
		}
	}
	this.pause = function() {

		var that = this;
    $(".audio").jPlayer("pause"); 
		$(document).unbind('keydown');
		$(this.target).unbind('click');$(this.target).click(function () {clearTimeout(that.timer);that.start();});
		//call interface
		this.ui();
	
	}
	
	///
	this.ui = function() {
		this.p.shadowColor='rgba(0, 0, 0, 0)';
		this.p.globalAlpha = 0.6;
		this.p.fillStyle = "#FFF";
		this.p.fillRect  (0,0, this.pw, this.ph);
		
		this.p.shadowOffsetX = 2;
		this.p.shadowOffsetY = 2;
		this.p.shadowBlur    = 4;
		this.p.shadowColor   = 'rgba(0, 0, 0, 0.5)';
		
		this.p.globalAlpha = 0.6;
		this.p.beginPath();
		this.p.arc(this.pw/2, this.ph/2, 60, 0, Math.PI * 2, false);
		this.p.closePath();
		this.p.fillStyle = "#000";
		this.p.fill();   
		
		this.p.beginPath();
		var ox = this.pw/2-15;
		var oy = this.ph/2-55;
		this.p.lineTo(ox+45, oy+55);
		this.p.lineTo(ox+0, oy+100);
		this.p.lineTo(ox+0, oy+10);
		this.p.closePath();
		
		this.p.fillStyle = "#000";
		this.p.fill();   
		this.p.globalAlpha = 1;
		this.p.shadowColor='rgba(0, 0, 0, 0)';
	}
	this.loadinggroup = function() {
		this.toload++;
	}
	this.onKeyDown = function(evnt) {
		var that = this;
		if (evnt.keyCode == 39) {
			clearTimeout(this.timer);
			this.timer = setTimeout( function() {that.play();}, 2000);
			this.next();
		} else if (evnt.keyCode == 37)  {
			clearTimeout(this.timer);
			this.timer = setTimeout( function() {that.play();}, 2000);
			this.previous();
		}
	}
}






$(document).ready(function(){
	$.getJSON('/load', function(data) {		

		$.each(data, function(key, val) {
			if (val.Published != "false" && val.Published != false) {
				$('.items').append('<li onclick="watchthatmonkey(\'/images/picsils/'+val.Location+'\');"><img src="/images/picsils/'+val.Location+'/'+val.Hero+'" /><p>'+val.Date+'<br />'+val.Tag+'</p><div class="playover"></div></li>');
			}
		});
	});
  
  
  $(".infotext").hover(
    function () {
      $('.infotext p').fadeOut('slow', 0, function() {
        $(this).text('Hold Down Your Arrow Keys For Rapid Playback').fadeIn('slow');
      });
    },
    function () {
      $('.infotext p').fadeOut('slow', 0, function() {
        $(this).text('Play the Pics Using Your Arrow Keys').fadeIn('slow');
      });
    }
  );
  $('#nowshowing').jScrollTouch({'ease': 0, 'displayScrollBar':true});
});


/* youtube - youku sh1t */

function onYouTubePlayerReady(playerid) {
  /* simple hack by paul -_- chaos-studio.com 
   * for loading content based on blockability 
   */
    $('#youku').remove();
    $('#alternate').remove();
}

function load_youtube( ) {
  var params = {allowScriptAccess: "always"}; 
  var atts = {id: "youtube"}; 
  swfobject.embedSWF("http://www.youtube.com/e/asDwJgq_zZE?enablejsapi=1&playerapiid=youtube&autoplay=1", "youtube", "640", "360", "8", null, null, params, atts);

}

function youtube_youku() {
  /* what a hack :)*/
  var originalContent = $('#box').html();
  var originalSize = $('#box').css('height');
  $('#box').html('<span class="playerbar"><p>The Amazing Adventures of Mister Goldberg</p></span> <div id="movie"><div id="youtube"></div> \
    <video id="alternate" width="640" height="380" poster="/images/ad-small.jpg" onClick="this.play();" controls>\
           \
          <source src="/mistergwuzhere/MG-Final-Cut-Web.m4v" />\
          <source src="/mistergwuzhere/MG-Final-Cut-Web.webm"  type="video/webm" />\
          <source src="/mistergwuzhere/MG-Final-Cut-Web.ogv" type="video/ogg" />\
          <source src="/mistergwuzhere/MG-Final-Cut-Web.hero.m4v" width="480" height="256" /> \
        Sorry, you are out of luck today..</video>\
</embed> \
<embed id="youku" src="http://player.youku.com/player.php/sid/XMzI3NzQwMjU2/v.swf" allowFullScreen="true" quality="high" width="640" height="360" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash"></embed> \
  </div>');
  $('#box').css('height', 500);
  htmlobject(); //remove flash, it's slow
  positioning();  
  load_youtube();
  $('#playbox').fadeTo(500, .8);
  $('#box').fadeTo(2000, 1);

  $('#box').queue(function() {
    $(this).dequeue();
  });
  
  $('#playbox, .playerbar').click(function() {
    $('#box').clearQueue();//cleanup to stop runaway

    $('#playbox').fadeOut(400);
    $('#box').fadeOut(400).html(originalContent).css('height', originalSize);
    flashHeader({stopSound: "TRUE"});//initilize flash again - stop audio.. it gets on your tits.
  });
  
flashd();

}



function flashd() {
  var playerVersion = swfobject.getFlashPlayerVersion(); 
  if (playerVersion.major == 0) {
    $('#youku').remove();
  }
  

}

	function playControl() {
		if ($('#alternate').paused == false) {
			$('#alternate').pause();
		} else {
			$('#alternate').play();
		}
	}
