$(document).ready(function()
    {  
      var img = 0; // array index
      var max_img = backgroundImages.length-1;
      var img_total = String(backgroundImages.length);
      var slideInterval = 5000; // how fast the image rotates timewise      
      
      function shuffle(array) {
            var tmp, current, top = array.length;
        
            if(top) while(--top) {
                current = Math.floor(Math.random() * (top + 1));
                tmp = array[current];
                array[current] = array[top];
                array[top] = tmp;
            }
        
            return array;
        }

      // We shuffle background images array:
      backgroundImages = shuffle(backgroundImages);
      
      function changeFontColor(color) {
	    if (color=="black") var css_color = "#000"; else var css_color = "#fff";
	    if (color=="black") var css_background = "#fff"; else var css_background = "#000";	    	    
	    $("div,p,h1,h2,h3,span,a").each(function() {
		if ($(this).text()!='') $(this).css("color", css_color);
	    });
	    $("body").css('background-color', css_background);  
      }
      
      function slideshow() {
            $('#backstretch').remove();
            $.backstretch(backgroundImages[img][0]);
	    $('#backstretch').hide();
	    changeFontColor(backgroundImages[img][1]);
            $.backstretch(backgroundImages[img][0]);    
            img++;
            if (img > max_img) {  img=0; }      
      }
      
      // Play slides
      setInterval(slideshow, slideInterval);
      // Trigger first image:
      slideshow();
 });

