var contentImages = {}

Site = {



  init: function()
  {
    Site.initContentComments()
    Site.initVote()
    galleryRotator.init()
    Site.initGallery()
  },

  initGallery: function()
  {
    $( '.fancybox' ).fancybox();
  },

  initVote : function()
  {
    $( '#vote-plus' ).click(
      function ()
      {
        Site.vote( this.rel, 1 )
        return false;
      }
    )
    $( '#vote-minus' ).click(
      function ()
      {
        Site.vote( this.rel, -1 )
        return false;
      }
    )
  },

  vote: function( contentId, modifier )
  {
    $.ajax( {
      url: '/~/content/vote/',
      data: {contentId: contentId, modifier: modifier},
      success: Site.voteSuccess,
      error: Site.voteError,
      timeout: Site.voteError,
      cache: false,
      dataType: 'json'
    } )
  },

  voteSuccess: function( responseData )
  {
    if ( responseData.success )
    {
      Site.reportMessage( 'Ваш голос успешно засчитан' )
      $( '#content-rating' ).html( responseData.newVoteCount )
    }
    else if ( responseData.message )
    {
      Site.reportError( responseData.message )
    }
    else
    {
      Site.reportError( 'Ошибка! Ваш голос не засчитан' )
    }
  },

  voteError: function( response )
  {
    Site.reportError(
      'Ошибка связи с сервером, сервер ответил некорректно или не во время' +
        'обратитесь к администрации при повторении этой ошибки. ' +
        'Ответ сервера: ' + response.responseText
    )
  },

  reportMessage: function( message )
  {
    $.fancybox( '<div style="color: #0a0; margin: 10px;">' + message + '</div>' );
      setTimeout( function() {$.fancybox.close()}, 2000 )
  },

  reportError: function( message )
  {
    $.fancybox( '<div style="color: #f00; margin: 10px;">' + message + '</div>' );
      setTimeout( function() {$.fancybox.close()}, 2000 )
  },

  initContentComments: function()
  {
    $( '.content-comment-adder' ).click(
      function ()
      {
        Site.addContentComment( this.id.substr( 22 ) )
        return false;
      }
    )
  },


  addContentComment: function( contentId )
  {
    $( '.comment-form-place' ).html( Site.getCommentForm( contentId ) )
    $( '.comment-form-place' ).toggle()
  },


  getCommentForm: function( elementId )
  {
    formAction = '/content/' + elementId + '/add-comment/';

    html = '';
    html += '<div style="text-align: left">';
    html += '<form action="' + formAction + '?redirect=" method="post">'
    html += '<p>'
    html += '<label style="margin: 0 0 3px 0; display: block;">Ваше имя</label>'
    html += '<input name="author_name" style="width: 450px;"/>'
    html += '</p>'
    html += '<p>'
    html += '<label style="margin: 0 0 3px 0; display: block;">Ваш комментарий</label>'
    html += '<textarea style="width: 450px; height: 300px;" name="text"></textarea>'
    html += '<br /><br />'
    html += '<input type="submit" value="&nbsp;&nbsp;&nbsp;Добавить комментарий&nbsp;&nbsp;&nbsp;" style="padding: 5px; margin-bottom: 5px" />'
    html += '</div>'

    return html
  },

  showVideo: function( encodedFlv, encodedImgUrl, SwfObjectPath, duration, targetBlockId )
  {
    if( typeof( targetBlockId ) == 'undefined' )
    {
      targetBlockId = 'video-player';
    }

    SWFObject = new SWFObject(
      SwfObjectPath + 'flvplayer316.swf', 'player', '400', '320', '9'
    );

		SWFObject.addParam("allowfullscreen","true");
		SWFObject.addParam("allowscriptaccess","always");
    
    SWFObject.addParam(
      'flashvars',
      'file=' + Site.base64_decode( encodedFlv ) + '&image=' +
         Site.base64_decode( encodedImgUrl ) +
         '&autostart=true&streamscript=lighttpd&showstop=true&duration=' + duration
    );
      
    SWFObject.write( targetBlockId );
  },

  showVideoRed  : function( encodedFlv, encodedImgUrl, SwfObjectPath, duration, targetBlockId )
  {
    if( typeof( targetBlockId ) == 'undefined' )
    {
      targetBlockId = 'video-player';
    }

    SWFObject = new SWFObject(
      SwfObjectPath + 'player_32.swf', "redtubeplayer", "584", "468", "9.0.124.0", "#000000"
    );

		SWFObject.addParam("allowfullscreen","true");
		SWFObject.addParam("allowscriptaccess","always");
    SWFObject.addParam("autostart", "true");
    SWFObject.addParam(
      'flashvars',
      Site.base64_decode( encodedFlv )
    );
    SWFObject.write( targetBlockId );
  },

  base64_decode: function  (data) {

    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];

    if (!data) {
        return data;
    }

    data += '';

    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');
    dec = Site.utf8_decode(dec);

    return dec;
  },
  utf8_decode: function  ( str_data ) {
    
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;

    str_data += '';

    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
  }

}

$( function() {Site.init()} )

galleryRotator = new function()
{
  this.timeout = 0
  this.currentContentId = 0
  this.currentImageNumber = 0
  this.images = {}
  this.vaitingContentId = 0

  this.init = function()
  {
    $( '.rotation' ).mouseover( galleryRotator.startRotate )
    $( '.rotation' ).mouseout( galleryRotator.endRotate )
  }

  this.setImages = function( contentId, imageArray )
  {
    galleryRotator.images[ contentId ] = imageArray;
  }
    
  this.startRotate = function( contentId )
  {
    if ( !parseInt( contentId ) )
    {
      contentId = this.id.substr( 14 )
    }

    if ( galleryRotator.vaitingContentId != 0 && galleryRotator.vaitingContentId != contentId )
    {
      return ;
    }

    if ( typeof( galleryRotator.images[ contentId ] ) == 'undefined' )
    {
      galleryRotator.vaitingContentId = contentId
      $.ajax(
        {
          url: '/~/content-image-list/' + contentId,
          dataType: 'json',
          success: galleryRotator.startRotate_listLoaded,
          error: function ( r ) {alert( r.responseText )}
        }
      );
    }
    else
    {
      galleryRotator.currentContentId = contentId
      galleryRotator.currentImageNumber ++;
      galleryRotator.makeRotation();
      galleryRotator.timeout = setInterval(  'galleryRotator.makeRotation()', 500 )
    }
  }

  this.startRotate_listLoaded = function( data )
  {
    if ( galleryRotator.vaitingContentId != data.contentId )
    {
      return ;
    }
    
    galleryRotator.vaitingContentId = 0
    galleryRotator.images[ data.contentId ] = data.imageList;
    galleryRotator.startRotate( data.contentId )
  }
  
  this.endRotate = function()
  {
    galleryRotator.currentImageNumber = 0
    galleryRotator.makeRotation();
    galleryRotator.currentContentId = 0
    clearInterval( galleryRotator.timeout );
    
    galleryRotator.vaitingContentId = 0
  }

  this.makeRotation = function()
  {
    contentId = galleryRotator.currentContentId
    if (
        typeof( galleryRotator.images[ contentId ] ) != 'undefined'
    )
    {
      if(
        typeof ( galleryRotator.images[ contentId ][ galleryRotator.currentImageNumber ] ) == 'undefined' &&
          galleryRotator.currentImageNumber != 0
      )
      {
        galleryRotator.currentImageNumber = 0
      }

      if ( typeof ( galleryRotator.images[ contentId ][ galleryRotator.currentImageNumber ] ) != 'undefined' )
      {
        $( '#image-content-' + galleryRotator.currentContentId ).attr(
          'src',
          galleryRotator.images[ contentId ][ galleryRotator.currentImageNumber ]
        )
      }

      galleryRotator.currentImageNumber ++
    }
  }
  
}

similarScroller = new function()
{
  this.positionCurrent = 0
  this.positionMaximum = 0

  this.init = function()
  {
    $( '.similar-next a' ).click( function() {similarScroller.nextClick();return false;} )
    $( '.similar-prev a' ).click( function() {similarScroller.prevClick();return false;} )
  }
  this.prevClick = function()
  {
    if( similarScroller.positionCurrent - 3 > 0 )
    {
      similarScroller.positionCurrent -= 3
    }
    else if( similarScroller.positionCurrent == 0 )
    {
      similarScroller.positionCurrent = similarScroller.positionMaximum - 3
    }
    else
    {
      similarScroller.positionCurrent = 0
    }
    similarScroller.animateToNewPosition()
  }

  this.nextClick = function()
  {
    if( similarScroller.positionCurrent + 3 < similarScroller.positionMaximum )
    {
      similarScroller.positionCurrent += 3
    }
    else
    {
      similarScroller.positionCurrent = 0
    }
    similarScroller.animateToNewPosition()
  }

  this.animateToNewPosition = function()
  {
    $( '#similar-inner' ).animate( {
      left: -1 * similarScroller.positionCurrent * 165
    } )
  }

  this.setPositionMaximum = function( position )
  {
    similarScroller.positionMaximum = position;
  }

}

