/*
	Site:		Space Matrix
	File:		/js/script.js
	Author:		vinay@artminister.com
	Version:	24-12-2010
	Usage : With jQuery

*/

SpaceMatrix = new Object;
var loader ='<p style="text-align:center; height:300px; line-height:400px"><img src="/images/ajax-loader_white.gif" class="loadingImage" alt="Loading" /></p>',
    loader_plain = '<p style="text-align:center; padding:10px 0;"><img src="/images/ajax-loader_white.gif" class="loadingImage" alt="Loading" /></p>',
    body_class=jQuery("body").attr("class"),
    gridloader='<p style="text-align:center; height:300px; line-height:400px"><img src="/images/ajax-loader-'+body_class+'.gif" class="loadingImage" alt="Loading" /></p>';
    

// Show Entry Popup on the Right Grid

SpaceMatrix.UI={
  GridPopup:{
    load:function(e,element){
      var _self =element;
      jQuery('.accordionList a').removeClass('active'); 
      jQuery(_self).addClass('active');      
      
      if(!$('aside').find('#DetailPopup').length)  $('aside').append('<div id="DetailPopup"><a href="#" id="CloseButton">Close</a><div class="innerPadding">'+gridloader+'</div></div>').find('.innerPadding').end().find('#DetailPopup').hide().fadeTo(200,1);
      SpaceMatrix.UI.GridPopup.scrollbar(_self.href);
      e.preventDefault();
      
      $(document).keyup(function(e){
        if(e.keyCode=='27'){
          e.preventDefault();
          SpaceMatrix.UI.GridPopup.close();
        }
      });
      
      jQuery('#DetailPopup #CloseButton').live('click',function(event){
        SpaceMatrix.UI.GridPopup.close();
        event.preventDefault();
      });
      
    },
    scrollbar:function(href){
      var container =  $('aside').find('#DetailPopup > .innerPadding');
      var _scrollpane =container.jScrollPane().data('jsp');
      $('aside').find("#DetailPopup").fadeTo(500,1);
      _scrollpane.getContentPane().load(href,function(){
        _scrollpane.reinitialise();
      });      
    },
    close:function(){
      if(jQuery('#DetailPopup').length) jQuery('#DetailPopup').fadeOut(function(){jQuery(this).remove();});
    }
  },
  Search:{
    load:function(e){
      e.preventDefault();
      jQuery('.accordionList a').removeClass('active'); 
      jQuery(this).addClass('active');
      $('#SearchResult').html('<li>'+loader_plain+'</li>').load(this.href);
    },    
    form:function(e){
      var _this = this;
      $('#SearchResult').html('<li>'+loader_plain+'</li>');
      var keyword_lenth = jQuery(this).find('#keywords').val().length;
      if(keyword_lenth<3) {
        $('#SearchResult').html('<li>Search term must be atleast 3 characters in length</li>')
      }else{
        $.post(_this.action, jQuery(this).serialize(), function(data) {
          $('#SearchResult').html(data);
        });
      }
      
      e.preventDefault();
    }
  },
  Popup:{
    open:function(e,element){
      e.preventDefault();
      if(!$('#FullPopup').length) {
          $('section').append('<div id="FullPopup">'+loader+'</div>').find('#FullPopup').hide().fadeTo(200,1);
      }else{        
        $('section').find('#FullPopup').html(loader);
      }
      $.get(element.href,function(data){  
        var container = $('section').find('#FullPopup');      
        container.html(data);
        container.find('.scrollpane').jScrollPane()
        container.fadeTo(200,1);
      });
      
      jQuery('#CloseButton').live('click',function(event){
        SpaceMatrix.UI.Popup.close();
        event.preventDefault();
      });
      
      // Escape Key
      
      $(document).keyup(function(e){
        if(e.keyCode=='27'){
          e.preventDefault();
          SpaceMatrix.UI.Popup.close();
        }
      });
      
    },
    close:function(){
      if(jQuery('#FullPopup').length) jQuery('#FullPopup').fadeOut(function(){jQuery(this).remove();});
    }
  },
  
  Gallery:{
    setup:function(){
      SpaceMatrix.UI.Gallery.load(jQuery('#Thumbs li:first a').attr("href"));      
      jQuery('#Thumbs li:first').addClass("active");
      jQuery('#Thumbs > li > a').live('click',function(e){
        var _this = this;
        jQuery(_this).parent().addClass('active').siblings().removeClass("active");
        jQuery('#ProjectImage').html('<img src="'+_this.href+'" alt="" />');
        e.preventDefault();
      });
      
      // Setup Slideshow
      var galleryInterval = setInterval( "SpaceMatrix.UI.Gallery.slideshow();", 5000 );
      
    },
    load:function(href){
      jQuery('#ProjectImage').find('img')
      
      //.fadeOut().attr("src",href).fadeIn();
    },
    slideshow:function(){
      var $active = $('#Thumbs li.active');
      if ( $active.length == 0 ) $active = $('#Thumbs li:last');
      var $next =  $active.next().length ? $active.next() : $('#Thumbs li:first');
      $active.addClass('last-active');      
      $next.addClass('active');
      SpaceMatrix.UI.Gallery.load($next.find('a').attr("href"));
      $active.removeClass('active last-active');
    }
    
  },
  
  Gridbuilder:{
    init:function(element){
      var random = new Array();
      var _this = element;
      var slideshowImages = jQuery(_this).children('li').size();      
      random = picks(6,slideshowImages);
      
      jQuery.map(random,function(n,i){
        jQuery(_this).find('li').eq(n-1).find('span').css("left",-140);
      });
      
      // Pick some more random numbers and start sliding
      setTimeout(function(){SpaceMatrix.UI.Gridbuilder.slide(_this,slideshowImages)},2000);
      setInterval(function(){
        SpaceMatrix.UI.Gridbuilder.slide(_this,slideshowImages);
      },2000);
      
    },
    slide:function(element,slideshowImages){
      var _this = element;
      random = picks(1,slideshowImages);
      jQuery.map(random,function(n,i){
        
        jQuery(_this).find('li').eq(n-1).find('span').filter(function(){
          return jQuery(this).css("left")=="0px";
        }).animate({
          left:"-=140"
        },500);
        
        jQuery(_this).find('li').eq(n-1).find('span').filter(function(){
          return jQuery(this).css("left")=="-140px" && (jQuery(this).children('a').size()>1);
        }).animate({
          left:"-=140"
        },500);
        
        jQuery(_this).find('li').eq(n-1).find('span').filter(function(){
          return (jQuery(this).css("left")=="-140px") && (jQuery(this).children('a').size()<2);
        }).animate({
          left:"0"
        },500);
        
        jQuery(_this).find('li').eq(n-1).find('span').filter(function(){
          return jQuery(this).css("left")=="-280px";
        }).animate({
          left:"0"
        },500);
        
      });
          
    }
  },
  newGrid:{
    startSlideshow:function(){
      if (slideshowImages.length < 6) return;
    	var i			= 0,
    		j			= 0;
    	listItems	= $('#Grids li');
    	while (j < 6) {
    		var randomIndex	= Math.floor (Math.random () * 9);
    		if(!$.inArray(randomIndex, currentLi) > -1) {
    			j ++;
    			currentLi.push (randomIndex);
    		}
    	}
    	//console.log(currentLi);    	
    	while (i < 6) {
    		var randomIndex	= Math.floor (Math.random () * slideshowImages.length);
    		if(!($.inArray(randomIndex, currentImg) > -1)) {
    			
    			var img = '<a href='+slideshowImages[randomIndex].href+' style="opacity:0" class="'+slideshowImages[randomIndex].classname+'"><img src='+slideshowImages[randomIndex].src+' width="140" height="140" /></a>';
    			//console.log(listItems[currentLi[i]]);
    			listItems.eq(currentLi[i]).empty().html(img);
    			listItems.eq(currentLi[i]).find('a').animate({
    			  opacity:1
    			},500);
    			//console.log(i);
    			i ++;
    			currentImg.push (randomIndex);
    		}
    	}
    	//	Start: Interval to perform fade in/out every 4 seconds

    	setInterval(function(){
    	  slideNext();
  	  },2000);
  	  
  	  function slideNext () {
      	//	Get next image

      	var randomImgIndex	= Math.floor (Math.random () * slideshowImages.length);
      	while ($.inArray(randomImgIndex, currentImg) > -1) {
      	  randomImgIndex	= Math.floor (Math.random () * slideshowImages.length);
      	}
      	
      	currentImg.shift();
      	currentImg.push (randomImgIndex);
      	
      	//console.log('currentli'+currentLi);
      	var randomLiIndex	= Math.floor (Math.random () * 9);
      	while ($.inArray(randomLiIndex, currentLi) > -1){
      		randomLiIndex	= Math.floor (Math.random () * 9);

      	}
      	currentLi.push (randomLiIndex);
      	//console.log('currentlipush'+currentLi);
      	
      	//	Remove an image

      	listItems.eq(currentLi.shift()).find('a,img').eq(0).animate({
      	  opacity:0
      	},500).remove();

      	//	Add an image
        //console.log(slideshowImages[randomIndex].classname);
      	var img = '<a href='+slideshowImages[randomImgIndex].href+' class="'+slideshowImages[randomImgIndex].classname+'" style="opacity:0"><img src='+slideshowImages[randomImgIndex].src+' width="140" style="opacity:0" height="140" /></a>';
  			//console.log(listItems[currentLi[i]]);
  			//console.log('img'+img);
  			listItems.eq(randomLiIndex).empty().html(img);
  			listItems.eq(randomLiIndex).find('a,img').animate({
  			  opacity:1
  			},500);
  			//console.log('liindex'+randomLiIndex);
      	
      	
      }
      
    	
    // End of slideshow	
    }
    
  }
}

// Picks Unique random numbers Thanks to felgall : http://www.codingforums.com/archive/index.php/t-4614.html

function picks(pick,tot) {
  var ary = new Array();
for (var i = 0; i < tot; i++) ary[i] = i+1;
function randOrd(){return (Math.round(Math.random())-0.5); }
ary.sort(randOrd);
return ary.slice(0,pick);
}

jQuery(document).ready(function(){

// Accordion

$('.accordionList > li ul')
  .click(function(e){
    //e.stopPropagation(); // This was causing the live events not to work.. So commented
  })
  .filter(':first').closest('li').addClass("active").end().end()
  .filter(':not(:first)')
  .hide();
  
$('.accordionList > li').click(function(){
  var selfClick = $(this).find('ul:first').is(':visible');
  if(selfClick) {
    return;
  }
  $(this)
    //.siblings('li').removeClass("active")
    .addClass("active")
    .siblings('li').removeClass("active")
    .parent()
    .find('> li ul:visible')
    //.closest('li').removeClass("active").end()
    .slideToggle(function(){
      jQuery('#DetailPopup').fadeOut(300, function() { $(this).remove(); });
      jQuery('#SearchResult > li').fadeOut('fast');
    });
  
  $(this)
    .find('ul:first')
    .stop(true, true)
    .slideToggle();
});

$('.accordionList > li > a').click(function(e){e.preventDefault(); });
$('.accordionList > li').each(function(){
  if(!jQuery(this).find('ul').length){
    jQuery(this).addClass("nochild");
  }
});



$('.list-search').each(function(){  jQuery(this).bind('click',SpaceMatrix.UI.Search.load); });
$('.link-mainPopup').live('click',function(e){   SpaceMatrix.UI.Popup.open(e,this); });
$('.list-entry').live('click',function(e){ SpaceMatrix.UI.GridPopup.load(e,this); });
$('.searchForm').each(function(){ jQuery(this).bind('submit', SpaceMatrix.UI.Search.form); })
$('#Grids').each(function(){ SpaceMatrix.UI.newGrid.startSlideshow(jQuery(this)); });


// End Ready
});
