var SCROLL_OBJ_ID = 0, SCROLL_DIR = 1, SCROLL_SHIFT = 2;//, SCROLL_ANIMATION = 3;
var scrollInfo = Array();

function getScrollInfo( obj ) {
  for( i in scrollInfo )
    if( scrollInfo[i][SCROLL_OBJ_ID] == obj.attr('id') )
      return scrollInfo[i];
  return -1;
}

/* ---=== PORTFOLIO ATTRIBUTES ===--- */
function getScrollSpeed( obj, scrollTo ) {
  var offset = scrollTo + obj.offset().left;//obj.attr('scrollLeft');
  if( offset < 0 )
    offset = -offset;
//alert(Math.ceil(offset/1000*scrollSpeed));
  return Math.ceil(offset/1000*scrollSpeed);
}

function getScrollWidth( obj ) {
  return obj.attr('scrollWidth');
}

/* ---=== PORTFOLIO SCROLLING ===--- */
function getLiLeft( obj, pos, shift ) {
  var left = 0;
  var lastWidth = 0;
  
  $('#'+ obj.attr('id') +' li').each(function(index){
    if( index >= pos )
      return false;

    lastWidth = $(this).width();
    if( isIE() )
      lastWidth += marginLeft;
    left += lastWidth;
  });
  
  //return left - (obj.parent().width()/2);
  left = left - (obj.parent().width()/2) + (lastWidth/2) + getScrollInfo(obj)[SCROLL_SHIFT]/2;
  if( isIE() )
    left = left - marginFirstLast/2 + marginLeft;
  if( left < 0 )
    left = 0;
  return left;
  //return left - (obj.parent().width()/2) + (lastWidth/2) + getScrollInfo(obj)[SCROLL_SHIFT]/2;// - marginFirstLast/2;
  
}


function getFirstVisibleLiPos( obj ) {
  var left = 0;
  if( isIE() )
    left += marginFirstLast/2;
  var pos = 0;
  var w;

  if( obj.position().left >= 0 )
    return 0;
  
  var scrollLeft = -obj.position().left;  //alert(scrollLeft);

  $('#'+ obj.attr('id') +' li').each( function(index){
    w = $(this).width();
    if( isIE() )
      w += marginLeft;
    
    if( left+w > scrollLeft ) {
      return false;
    }
    
    left += w;
    pos++;
  });
  
  return pos;
}

// Returns pos of LI, that is most centered on the screen.
function getCenterLiPos( obj ) {
  var center = -obj.position().left + (obj.parent().width()/2) + ($('#' + obj.attr('id') + ' li').width()/2);
  var left = 0;
  var pos = 0;

  $('#'+ obj.attr('id') +' li').each(function(index){
    left += $(this).width();

    if( left+($(this).width()/2) >= center ) {
      return false;
    }
    pos++;
  });
  
  return pos;
}

/*function scrollAnimate( obj, pos, speed ) {
  if( pos > getMaxScroll(obj) )
    left = getMaxScroll(obj);

  if( speed == null || speed == 0 ) {
    obj.css({ 'left' : -pos });     // Invert pos to scroll properly.
    return;
  }
}*/

function getMaxScroll( obj ) {
  return getScrollWidth(obj) - obj.parent().width();
}

function scrollToLi( obj, pos, speed ) {
  scrollStop( obj );
  
  //pos = 3;
  var left = getLiLeft(obj, pos);     //pr(pos + '  ' + left);
  
  /*if( speed == null || speed == 0 ) {
    scroll( obj, left, 0 );
    return;
  }
  
  if( speed == 'auto' )
    speed = getScrollSpeed(obj, left);*/
  
  //getScrollInfo(obj)[SCROLL_ANIMATION] = true;
  scroll( obj, left, speed );
  //obj.animate({scrollLeft: left}, speed, 'linear' );  //swing

  //loadVisibleImages();
}

function getCurrentLi( obj ) {
}

function scrollToFirm( id, speed ) {
  var pos = 0;
  
  $('#firm-list li a').each( function(index){
    if( this.id == 'firm_'+id ) {
      scrollToLi( $('#firm-list'), pos, speed );
      return false;
    }
    pos++;
  });
}

function scrollStop( obj ) {
  getScrollInfo(obj)[SCROLL_DIR] = '';
  obj.stop();
}

function scroll( obj, direction, speed ) {
  if( getScrollInfo(obj)[SCROLL_DIR] == direction )
    return;

  var scrollTo;
  
  // Check if we can scroll.
  if( obj.width() < obj.parent().width() )
    return;
    
    
  if( direction == 'left' ) {
    scrollTo = 0;
  } else if( direction == 'right' ) {
    scrollTo = getMaxScroll(obj);   //getScrollWidth(obj) - obj.parent().width();//getScrollWidth(obj) - obj.width();
  } else {
    scrollTo = direction;
    
    /*if( scrollTo < 0 )
      return;*/
      
    if( scrollTo > getMaxScroll(obj) )
      scrollTo = getMaxScroll(obj);
    /*else if( scrollTo < 0 )
      scrollTo = 0;*/
  }
   
//alert(scrollTo + '  ' + obj.position().left);
//scrollTo += 5000;
  // Return if we have nothing to do;
  //if( obj.attr('id') == 'firm-list' ) {
    /*if( scrollTo == obj.attr('scrollLeft') )
      return;*/
  //}
  
  getScrollInfo(obj)[SCROLL_DIR] = direction;
    
  scrollStop( obj );
  if( obj.attr('id') == 'firm-list' )
    scrollStop( $('#portfolio-list') );
    //alert( obj.attr('id') + '  ' + $('#firm-list').is(':animated') );
  if( obj.attr('id')=='portfolio-list' && ($('#firm-list').is(':animated')) )
    return;

  if( speed == null ) {
    speed = getScrollSpeed( obj, scrollTo );
  } else if( speed == 0 ) {
    obj.css({ 'left' : -scrollTo });     // Invert pos to scroll properly.
    return;
  } else {   // 'auto'
    speed = getScrollSpeed( obj, scrollTo );
  }

  obj.animate({'left': -scrollTo}, speed, 'linear', function(){
    /*if( obj.attr('id') == 'firm-list' )
      if( scrollTo==0 )
        scrollToLi( $('#portfolio-list'), 0, 'auto' );
      else
        scrollToLi( $('#portfolio-list'), $('#portfolio-list li').length, 'auto' );*/
  } );
}

function mmove( e ) {

  //$('#portfolio-list').animate({'scrollLeft': 1000}, 10000, 'linear' );
  //$('#portfolio-list').scrollTo( 10, 10 );
  //$('#portfolio-list').animate({ scrollLeft: '1000px'}, 'slow' );
  //alert( $('#portfolio-list').css('top') );
  //return;
  
  var parent = $(this);
  var obj = parent.find('ul.scroll');
  var p = parent.offset();
  var w = parent.width();
  var x = e.pageX - p.left;
  
  if( x <= scrollActive)
    scroll( obj, 'left' );
  else if( x >= w-scrollActive )
    scroll( obj, 'right' );
  else
    scrollStop( obj );
}

/* ---=== INIT, RESIZING ===--- */
$(window).load( function() {
  //$('ul.scroll').mousemove( mmove );
  $('ul.scroll').parent().mousemove( mmove );
  $('ul.scroll').mouseleave( function() { scrollStop($(this)) } );
  
  $('ul.scroll').each( function(index) {
    var arr = Array();
    arr[SCROLL_OBJ_ID] = $(this).attr('id');
    arr[SCROLL_DIR] = '';
    if( $(this).attr('id') == 'portfolio-list' )
      arr[SCROLL_SHIFT] = marginFirstLast/2 + marginLeft/2;
    else
      arr[SCROLL_SHIFT] = 0;
    //arr[SCROLL_ANIMATION] = false;
    
    scrollInfo.push( arr );
  });
})


/* ---=== IMAGES POSTLOADING ===--- */
var postloadImages = Array();

function getNextPostLoadImagePos() {
  var pos = -1;
  var firstVisible = getFirstVisibleLiPos($('#portfolio-list'));
  var found = false;  // Did we find img with pos >= first ?
  var i;

  for( i=firstVisible; i<postloadImages.length; ++i )
    if( postloadImages[i] != null )
      return i;

  for( i=0; i<firstVisible && i<postloadImages.length; ++i )
    if( postloadImages[i] != null )
      return i;

  return -1;
      
  /*$('img.postload').each( function() {                         //alert($(this).attr('id'));
    //pos = parseInt( $(this).attr('id').split('_')[1] );
    
    if( pos >= firstVisible )
      return false;
  });
  
  return pos;*/
}

function prepareImagesPostLoad() {
  // Find images that shouldn't be postloaded.
  var center = getCenterLiPos( $('#portfolio-list') );
  if( portfolioId != -1 )
    center = portfolioId;

  var near = Math.floor($('#portfolio-list').parent().width() / $('#portfolio-list li').width() / 2) + 1;
  var firstVisible = center - near;
  var lastVisible = center + near;//alert( center + '   ' + near + '  ' + firstVisible + '  ' + lastVisible);

/*var last = Math.ceil(firstVisible + $('#portfolio-list').parent().width() / $('#portfolio-list li').width()) + 1;
  alert( firstVisible + '  ' + lastVisible + '  ' + getFirstVisibleLiPos($('#portfolio-list')) + '  ' + last );*/
    
  loadImages( firstVisible, lastVisible );

  // Remove 'postload' class from images, that shouldn't be postloaded.  Prepare postload images.
  var pos = 0;
  $('img.postload').each( function() {//alert($(this).attr('id') );
    //var pos = parseInt( $(this).attr('id').split('_')[1] );
    
    if( pos>=firstVisible && pos<=lastVisible ) {
      postloadImages[pos] = null;
      $(this).removeClass( 'postload' );
    } else {
      postloadImages[pos] = Array( $(this).attr('id'), $(this).attr('src') );
      $(this).attr( 'src', placeholderSrc );
    }
    
    pos++;
  });

  // Prepare postload images.
/*  $('img.postload').each( function() {
      var pos = parseInt( $(this).attr('id').split('_')[1] );
      
      if( pos<firstVisible || pos>lastVisible ) {
        postloadImages[pos] = Array( $(this).attr('id'), $(this).attr('src') );
        $(this).attr( 'src', placeholderSrc );
      }
  });*/
}


function loadNextPostLoadImage() {
  // Load next 'postload' image.
  var pos = getNextPostLoadImagePos();
  if( pos != -1 )
    loadImage( pos );
}

var imagesPostloaded=0;
function loadImagesPostLoad() {
  $('img.postload').load( function() {
    // IE6  (limit of max 15 images at once)
    imagesPostloaded++;
    if( isOldIE() && imagesPostloaded >= 10 ) {
      imagesPostloaded = 0;
      setTimeout( "loadNextPostLoadImage()", 1 )
      return;
    }
       
    // Remove 'postload' class, load next image.
    $(this).removeClass( 'postload' );

    //setTimeout("loadNextPostLoadImage();", 2000 );
    loadNextPostLoadImage();
  });
  
  $('img.postload').error( function() {
    $(this).removeClass( 'postload' );
    loadNextPostLoadImage();
  });
  
  // Load 3 images at the same time.
  for( var i=0; i<1; ++i )
    loadNextPostLoadImage();
}


function loadImage( id ) {
  if( id<0 || id>=postloadImages.length || postloadImages[id]==null )
    return;

  var src = postloadImages[id][1];
  var imgId = postloadImages[id][0];
  
  if( src != null ) {
    //$('#'+imgId).attr({ 'src' : src });

    postloadImages[id] = null;
    $('#'+imgId).attr( 'src', src );
  }
}

function loadImages( first, last ) {
  for( i=first; i<=last; i++ )
    loadImage( i );
}

/*function loadVisibleImages() {
  var ul = document.getElementById('portfolio-list');alert(ul.scrollLeft);
  var id = Math.ceil((ul.scrollLeft+$('#portfolio-list').width()/2) / liWidth );
  //var id = parseInt($('#pitem_'+portfolioId+' a img').attr('id').split('_')[1]); alert(id);
  if( id == -1 )
    id = 0;
  var left = getLiLeft( $('#portfolio-list'), id );
  
  var near = Math.floor($('#portfolio-list').width() / liWidth / 2) + 2;
  loadImages( id-near, id+near );
}
*/
