/*
iksi.1.0.js
March 2009
By Jurriaan Topper
Iksi / iksi.tv
*/

		var img;

(function($){	
	
	$(document).ready(function() {
		

		// load background (background.js)
		$.ajax({
			url: "/files/backgroundimage.php",
			cache: false,
			success: function(html){
				$("#front").image(html,function(){
					$('#front > img').attr('src', html);	
					$('#front > img').fillimage();
					// ten second delay
					setInterval("slide()", 30000);        
				});
			}
		});

		// window onresize function
	 	$(window).bind("resize", function(){
	   		$("#back > img").resizenow(); 
	   		$("#front > img").resizenow();
				//positionContent();	
	 	});

	});

	//Resize image on ready or resize
	$.fn.fillimage = function() {
			$(this).fadeIn(300);
			//$(this).css("display","block");
			$(this).resizenow();
			//$('#feed > p').html(imagewidth+" - "+imageheight);			
	};
	
	//Adjust image size
	$.fn.resizenow = function() {
		return this.each(function() {
		var imagewidth = img.width; //$(this).width();
		var imageheight = img.height; //$(this).height();
		
		//$('#feed > p').html(imagewidth+" - "+imageheight);
		var width = $(window).width();
		var height = $(window).height();		
		var w = width;
  		var h = width * (imageheight / imagewidth);
  		var x = 0;
  		var y = (height - h) / 10;
  	
  		if (h < height) { // y < 0
  			h = height;
  			w = height * (imagewidth / imageheight);
  			y = 0;
  			x = (width - w) / 2;
  		}

		// set everything
  		$(this).css("marginTop",y);
  		$(this).css("marginLeft",x);
  		$(this).attr("width",w);
    	$(this).attr("height",h);
		});
		
	};
	
	$.fn.image = function(src, f){ 	
	   return this.each(function(){ 
	     img = new Image(); 
	     img.onload = f;
	     img.src = src; 
	     //this.appendChild(i);
		 //$(this).html("<img src=\""+src+"\" />");
		 // set this somewhere else:
		 //var set = "#"+this.id+" > img";
		 //$(set).attr('src', src);
	   }); 
	}
	
	
})(jQuery);

function slide() {
	// check above one
	if ($('#front').css("zIndex") == 2) {
		$('#back > img').css("display","none");	
		
		$.ajax({
       		url: "/files/backgroundimage.php",
       		cache: false,
       		success: function(html){
            	$("#back").image(html,function(){
              		//alert("image loaded");
					$('#back > img').attr('src', html);	
					$('#back > img').fillimage();				
					$('#front').css("zIndex",1);
            	});
     		}
   		});		
			
	} else {
		$('#front > img').css("display","none");
		
		$.ajax({
       		url: "/files/backgroundimage.php",
       		cache: false,
       		success: function(html){
            	$("#front").image(html,function(){
              		//alert("image loaded");
					$('#front > img').attr('src', html);	
					$('#front > img').fillimage();				
					$('#front').css("zIndex",2);
            	});
     		}
   		});
		
	}
}
