var column_class    = 'column';
var cell_class      = 'cell';
var expanded_class  = 'expanded';
var load_class      = 'load';

var STATE_NORMAL      = 1;
var STATE_EXPANDED    = 2;
var STATE_COLAPED     = 3;

var TYPE_CENTRAL      = 1;
var TYPE_TOP          = 2;
var TYPE_BOTTOM       = 3;

var WIDTH_NORMAL         = 202;
var HEIGHT_NORMAL        = 202;

var WIDTH_COLAPSED       = 704;
var HEIGHT_COLLAPSED     = 55;
var HEIGHT_COLLAPSED_TOP = 109;

var WIDTH_EXPANDED       = 704 + WIDTH_NORMAL;
var HEIGHT_EXPANDED      = 498 ;


var INTER_STEP        = 10;
var UP_CLELL_STEP     = 8;
var DW_CLELL_STEP     = 8;
var WIDTH_CLELL_STEP  = 8;
var HEIGHT_CLELL_STEP = 8;

var ANIM_DURATION = "fast";
var MIN_SCREEN_WIDTH = 1024;
var EXPAND_IN_PROGRES = false;
var HEIGHT_MENU = 77;

var IGNORE_CELLS = [
  'start',

];
var interval;
var slideSwitchInterval;
var slideEnabled = true;

//******************************************************************************
Array.prototype.exists = function(search){
  for (var i=0; i<this.length; i++)
    if (this[i] == search) return true;

  return false;
}
//******************************************************************************

function get_cell_type( cell ){
  if( typeof( $( cell ).prev()[0] ) == 'undefined' ){
    return TYPE_TOP;
  } else if ( typeof( $( cell ).next()[0] ) == 'undefined' ) {
    return TYPE_BOTTOM;
  } else {
    return TYPE_CENTRAL;
  }
}
//******************************************************************************

function get_cell_state( cell ){
  var width = cell.parentNode.clientWidth;
  var height = cell.clientHeight;
  if( ( width == WIDTH_NORMAL ) && ( height == HEIGHT_NORMAL ) ){
    return STATE_NORMAL;
  } else if( ( width == WIDTH_COLAPSED ) && ( height == HEIGHT_COLLAPSED ) ){
    return STATE_COLAPED;
  } else if ( ( width == WIDTH_EXPANDED ) && ( height == HEIGHT_EXPANDED ) ){
    return STATE_EXPANDED;
  }
}
//******************************************************************************
function load_full_content( cell ){
  var jcell = $( cell );

  var preload_url = jcell.find( '.content .full-cont' ).attr( 'iconv:preload' );
  var url = jcell.find( '.content' ).attr( 'iconv:full' );
  if( typeof(preload_url) != 'undefined' ){
    if( preload_url.length > 0 ){
      var url = preload_url;
      jcell.find( '.content .full-cont' ).attr( 'iconv:preload', '' );
    }
  }
  if ( !url ) return false;
  $.ajax({
    type: "get",
    url:  url,
    dataType:'html',
    success: function( msg ){
      jcell.find('.content .digest-cont').css( 'display', 'none' );
      jcell.find('.content .full-cont').css('display', '').html( msg ).attr( 'iconv:loaded', 'true');
    }
  });
}

function showContent ( cell_name, url ){
  var suffix = url.replace( /\//g, ',' );
  window.location.hash = cell_name + suffix;
}

function restore_digest_content( jcell ){
  jcell.find('.content .digest-cont').css( 'display', '' );
  jcell.find('.content .full-cont').css( 'display', 'none' );
  jcell.find('.content .cp').css( 'display', 'none' );
}



function showFullContentEvent( url ){
  showContent( 'events', url );
}


function url_handler() {
  var reqURL = window.location.hash;

  if( reqURL.length > 0 ){
    var sections=reqURL.split( ',' );
    var cell_name = sections[0].replace( /#/, '' );

    if( sections.length > 1 ) {
      preload_url = '/';
      for( var sIndx = 1; sIndx < sections.length; sIndx++ ) {
        preload_url += sections[ sIndx ]
        if( sIndx < (sections.length - 1 )) {
          preload_url += '/';
        }
      }
      $( '.cell[name=' + cell_name + '] .content .full-cont' ).attr( 'iconv:preload', preload_url );
    }

    center_window( $( '.cell[name=' + cell_name + ']' )[0] );
  }
}

function slideSwitch() {
  if( slideEnabled ) {
    var $visible = $('div.project-small.visible');
    var $last = $('div.project-small:last');

    if( $visible[0] == $last[0] ){
      var $next = $('div.project-small:first');
    } else {
      var $next = $visible.next();
    }

    $visible.fadeOut( 'fast', function () {
      $visible.removeClass( 'visible' );
      $next.addClass( 'visible' );
      $next.fadeIn( 'fast' );
    });
  }
}

function onHashChanged(){
  var sections = window.location.hash.split( ',' );
  if( sections.length > 0 ){
    var preload_url = '/';
    for( var sIndx = 1; sIndx < sections.length; sIndx++ ) {
      preload_url += sections[ sIndx ]
      if( sIndx < (sections.length - 1 )) {
        preload_url += '/';
      }
    }
    var cell_name = sections[0].replace( /#/, '' );

    var dest_cell =  $( '.cell[name=' + cell_name + ']' );
    var expanded_cell = $( '.' + expanded_class );
    if( dest_cell.length == 1 ){
      //--------
      if ( get_cell_state ( dest_cell[0] ) != STATE_EXPANDED ) {
        if( ! EXPAND_IN_PROGRES  ){
          EXPAND_IN_PROGRES = true;
          if( sections.length > 1 ) {
            dest_cell( '.content .full-cont' ).attr( 'iconv:preload', preload_url );
          }
          collapse_cell( dest_cell[0], center_window );
        }
      } else {
        if( sections.length <= 1 ) {
          preload_url = dest_cell.find( '.content' ).attr( 'iconv:full' );
        }
        dest_cell.find( 'div.content div.full-cont' ).load( preload_url );
      }
      //---------
    }
  }
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
//******************************************************************************
function center_window( cell_exp ){
  var pos = $( cell_exp ).position();
  pos.left = cell_exp.offsetLeft - ( $( window ).width() / 2 ) ;
  pos.top  = cell_exp.offsetTop  - ( $( window ).height() / 2 );
  $.scrollTo( pos  , 400,{onAfter:function(){
    if( IGNORE_CELLS.exists( $( cell_exp ).attr( 'name' ) ) ) {
		  //$( cell_exp ).find('div.layer-top').css('margin-top','22px');
      EXPAND_IN_PROGRES = false;
      return false;
    }
    window.clearInterval( interval );
    var cell_type = get_cell_type ( cell_exp );
    if ( cell_type != TYPE_BOTTOM ) {
      expand_cell( cell_exp )
      $.scrollTo(
        { top : $(cell_exp).position().top - HEIGHT_MENU - (HEIGHT_NORMAL ) - 16 , left : $(cell_exp).position().left - ( ( $( window ).width() - WIDTH_EXPANDED ) /2 ) },
        {'duration' : ANIM_DURATION }
      );
    } else {
      EXPAND_IN_PROGRES = false;
    }
  }});
}

function expand_cell ( cell ) {
  var jcell     = $( cell );
  var down      = jcell.next();
  var up        = jcell.prev();
  var cell_type = get_cell_type ( cell );

  // изменить размер соседих ячеек до свенутого
  down
  .add( up )
  .find( ".content .digest-cont *" )
  .not( "h1, h1>img" )
  .css( { 'display' : 'none' } )
  .end()
  .end()
  .animate( { 'height' : ( cell_type == TYPE_CENTRAL ) ? HEIGHT_COLLAPSED - 1 : HEIGHT_COLLAPSED_TOP  }, { 'duration' : ANIM_DURATION } );

  // изменить размер текущей ячейки до состояния развернутого
  jcell
  .parent()
  .animate( { 'width' : WIDTH_EXPANDED }, { 'duration' : ANIM_DURATION } )
  .end()
  .animate( { 'height' : HEIGHT_EXPANDED, 'duration' : ANIM_DURATION  }, function (){
    jcell.addClass( expanded_class );
    EXPAND_IN_PROGRES = false;
    load_full_content( cell );
    jcell.find( '.content .cp' ).css( 'display', 'block' );
    slideEnabled = false;
  });
}
function collapse_cell( cell_exp, callback ){
  var jcell = $( '.' + expanded_class );
  var down  = jcell.next();
  var up    = jcell.prev();

  if( jcell.length == 0 ) {
    center_window( cell_exp );
    return false;
  }

  jcell.find('.content .full-cont').find('*').hide();

  down
  .add( up )
  .find( ".content .digest-cont *:not(h1)")
  .css( {'display': ''} )
  .end()
  .animate( { 'height': HEIGHT_NORMAL}, {'duration' : ANIM_DURATION });

  jcell
  .parent()
  .animate( {'width': WIDTH_NORMAL}, {'duration' : ANIM_DURATION })
  .end()
  .animate( {'height': HEIGHT_NORMAL, 'duration' : ANIM_DURATION }, function (){
    $( this ).removeClass( expanded_class );
    if( typeof( callback ) == 'function' ){
      //console.info( callback );
      callback( cell_exp );
    }
    //center_window( cell_exp );
    restore_digest_content( jcell );
    slideEnabled = true;
  })
  .find( '.full-cont' )
  .empty();
}

//******************************************************************************
//******************************************************************************
//******************************************************************************
$( document ).ready( function (){
  hashListener.init();
  url_handler();
  hashListener.onHashChanged = onHashChanged;
  $( '#menu a').bind( "click", function () {

    $( '#menu a.active' ).removeClass( 'active' );
    $( this ).addClass( 'active' );

    obj = $( '.cell[name=' + $(this).attr('href').replace(/^#/,'') + ']' )[0];

    if ( get_cell_state ( obj ) != STATE_EXPANDED ) {
      if( ! EXPAND_IN_PROGRES  ){
        EXPAND_IN_PROGRES = true;
        window.location.hash = $( obj ).attr( 'name' );
        collapse_cell( obj, center_window  );
      }
    }
    return false;
  });

  $( '.' + cell_class ).bind( "click", function(  ) {
    if ( get_cell_state ( this ) != STATE_EXPANDED ) {
      if( ! EXPAND_IN_PROGRES  ){
        EXPAND_IN_PROGRES = true;
        window.location.hash = $( this ).attr( 'name' );
        $( '#menu a.active' ).removeClass( 'active' );
        $( '#menu a#' + $( this ).attr( 'name' ) ).addClass( 'active' );
        collapse_cell( this, center_window  );
      }
    }
  });



  $( '.cp .close' ).bind( "click", function () {
    var cell = $( this ).parent().parent().parent().parent()[0];
    collapse_cell( cell );
    $( '#menu a.active' ).removeClass( 'active' );
  });

  $( '.cp .refresh' ).bind( "click", function () {
    var cell = $( this ).parent().parent().parent().parent()[0];
    load_full_content( cell );
  });


  slideSwitchInterval = setInterval( "slideSwitch()", 5000 );


});

//********************************************************************
/*function getContentFull(source1,result1){
   var taregtdiv = "#"+result1;
   $.ajaxSetup({
      url: source1,
      cache:false,
      timeout: 3000,
      type: "GET",
      dataType:'html',
      success: function(html){
        $(taregtdiv).html(html);
      },
      cache: false
    });
    $.ajax({cache: false});
}*/