﻿vlvjs = {
  'api' : {}
};

/**
 * 
 * @param {Object} callback
 * @param {Object} infos
 */
vlvjs.api.loadSketch = function(callback, infos)
{
  jQuery.ajax({
     url: heap.urlmap.jsonapi+'/vlvapi/loadSketch',
     data: { parameters: JSON.stringify(infos) }, 
     success: callback
     });
};

/**
 * 
 * @param {Object} callback
 * @param {Object} infos
 */
vlvjs.api.searchSketch = function(callback, infos)
{
   jQuery.ajax({
     url: heap.urlmap.jsonapi+'/vlvapi/searchSketch',
     data: { parameters: JSON.stringify(infos) }, 
     success: callback
     }); 
};

/**
 * 
 * @param {Object} callback
 * @param {Object} infos
 */
vlvjs.api.listSketch = function(callback, infos)
{
   jQuery.ajax({
     url: heap.urlmap.jsonapi+'/vlvapi/pager',
     data: { parameters: JSON.stringify(infos) }, 
     success: callback
     }); 
};

/**
 * 
 * @param {Object} callback
 * @param {Object} infos
 */
vlvjs.api.voteForSketch = function(callback, infos)
{
   jQuery.ajax({
     url: heap.urlmap.jsonapi+'/vlvapi/voteForSketch',
     data: { parameters: JSON.stringify(infos) }, 
     success: callback
     }); 
};

/**
 * 
 * @param {Object} callback
 * @param {Object} infos
 */
vlvjs.api.login = function(callback, infos)
{
   jQuery.ajax({
     url: heap.urlmap.jsonapi+'/vlvapi/login',
     data: { parameters: JSON.stringify(infos) }, 
     success: callback
     }); 
};

/**
 * 
 * @param {Object} callback
 * @param {Object} infos
 */
vlvjs.api.renderConnectBox = function(callback, infos)
{
   jQuery.ajax({
     url: heap.urlmap.jsonapi+'/vlvapi/renderConnectBox',
     data: { parameters: JSON.stringify(infos) }, 
     success: callback
     }); 
};
/**

 * 
 * @param {Object} callback
 * @param {Object} infos
 */
vlvjs.api.sendAbuseEmail = function(callback, infos)
{
   jQuery.ajax({
     url: heap.urlmap.jsonapi+'/vlvapi/sendAbuseEmail',
     data: { parameters: JSON.stringify(infos) }, 
     success: callback
     }); 
};

VLVPlayer = {};
VLVPlayerPresentation = {};
VLVFabrique = {};
VLVobj = {};
VLVDefiSemaine = {};
VLVPlayers = new Array();

VLVFabrique.swfbridge = { initialized: false, logged: "false", flash_container_id: 'fabrique_flash', flash_id: 'fabrique_swf' };
VLVDefiSemaine.swfbridge = { initialized: false, logged: "false", flash_container_id: 'defi_swf_container', flash_id: 'defi_swf' };

VLVobj.randnum = Math.round(Math.random()*100000000000);
        
VLVobj.vote = { initiated: false, locked : false };
VLVobj.vote.reinit = function(item){
  if(item)
  {
    var round_value = Math.round(parseFloat(item.value));
    for(var i=0; i<5; i++)
    {
      var curr_rater = $('#sketch_infos #votepanel a').eq(i);
      var curr_rater_span = curr_rater.find('span');
      curr_rater.attr('href', '#'+item.id);
      
      if(round_value > i)
        curr_rater_span.removeClass('off').addClass('on').addClass('active');
      else
        curr_rater_span.removeClass('on').removeClass('active').addClass('off');
        
    }
  }
  else
  {
    $('.votable a').find("span:not(.active)").removeClass("on").addClass("off");
    $('.votable a').find("span.active").removeClass("off").addClass("on");
  }
  VLVobj.vote.locked = false;
  return false;
};


VLVPlayerPresentation.writeVideo = function(swf_id, swf_inject_id, class_link)
{
  if( (!$('#'+swf_inject_id+' embed').length) && (!$('#'+swf_inject_id+' object').length) )
  {
    var curr_player = VLVPlayers[swf_id];    
    player_flashvars = curr_player.player_flashvars;
    player_params = curr_player.player_params;
    player_attributes = curr_player.player_attributes;
    
    curr_player.swfobj = new SWFObject(player_flashvars.src, player_attributes.name, player_flashvars.width, player_flashvars.height , "10.0.22"); 
    curr_player.swfobj.addParam("wmode", player_params.wmode); 
    curr_player.swfobj.addParam("allowFullScreen", "true");
    curr_player.swfobj.addParam("allowscriptaccess", "always");
    for (var fvar in player_flashvars) {
      curr_player.swfobj.addVariable( fvar, player_flashvars[fvar]); 
    };
    try{
      curr_player.swfobj.write(swf_inject_id);  
    }
    catch(e){
      $('a.'+class_link).eq(0).trigger('click');
    }
  }
};

/**
 * 
 * @param
 */
VLVPlayer.on_tab_clicked = function(params)
{
  //alert('VLVPlayer.on_tab_clicked : params = '+params.toSource());
  if(params)
    cslug = params;
  else
    return false;
    
  vlvjs.api.loadSketch(function(response){
    if(response.data)
    {
      var item = response.data;
      if(item.title)
        $('#sketch_infos .title').html(item.title);
      if(item._meta && item._meta['views'])
        $('#sketch_infos .viewed .viewed_count').html(item._meta['views']);
      else
        $('#sketch_infos .viewed .viewed_count').html("0");
      if(item._user && item._user[0] && item._user[0].username)
        $('#sketch_infos .username').html(item._user[0].username);
      if(item._time_created)
      {
        var dateY = item._time_created.substr(0,4);
        var datem = parseInt(item._time_created.substr(5,2));
        if(item._time_created.substr(5,1) == '0')
          datem = parseInt(item._time_created.substr(6,1));
          
        var dated = item._time_created.substr(8,2);
        var arrayMonths_fr = ['JANVIER', 'FÉVRIER', 'MARS', 'AVRIL', 'MAI', 'JUIN', 'JUILLET', 'AOÛT', 'SEPTEMBRE', 'OCTOBRE', 'NOVEMBRE', 'DÉCEMBRE'];
        $('#sketch_infos .date').html(dated+' '+arrayMonths_fr[datem]+' '+dateY); 
      }
    }
    return false;
  },{slug: cslug});  
  
};


/**
 * 
 * @param none
 */
VLVFabrique.on_needhelp_clicked = function()
{
  if(!VLVobj.initFlash(VLVFabrique)){
    //alert("VLVobj.initFlash(VLVFabrique) not defined"); return;
  }
  else {
    $('a.fabrique_helper').trigger('click');    
  }
  
  return false;
};

/**
 * 
 * @param none
 */
VLVFabrique.show_video_tutorial = function()
{
  if(!VLVobj.initFlash(VLVFabrique)){
    //alert("VLVobj.initFlash(VLVFabrique) not defined"); return;
  }
  else {
    $('a.fabrique_helper_video').trigger('click');    
  }
  
  return false;
};

/**
 * 
 * @param none
 */
VLVFabrique.showConnectPannel = function()
{
  if(!VLVobj.initFlash(VLVFabrique)){
    //alert("VLVobj.initFlash(VLVFabrique) not defined"); return;
  }
  else {
    $('a.already_member').trigger('click');
  }
   
  return false;
};

/**
 * 
 * @param none
 */
VLVDefiSemaine.voirVideo = function()
{
  if(!VLVobj.initFlash(VLVDefiSemaine)){
    alert("VLVobj.initFlash(VLVDefiSemaine) not defined"); return;
  }
  else {
    $('a.defi_link_video_prec').trigger('click');
  }   
  return false;
};

/**
 * Write SWFObject to DOM and initialize connection with it
 * @param none
 */
VLVobj.initFlash  = function(obj)
{
  if (!obj.swfbridge.initialized) {
    try{
        obj.swfobj.write(obj.swfbridge.flash_container_id);
        obj.swfbridge.initialized = true;
    }
    catch(e){
        //alert("exception caught : "+e);
        return false;
    }
  }
  if (!obj.swfobj || !obj.swfobj.tagName) {
    try{
        var name = obj.swfbridge.flash_id;
        var isIE = jQuery.browser.msie;
        //window[name] = document.forms[1].mosaic;

        if(obj.swfobj = (isIE) ? window[name] : document[name]){
          return true;
        } else return false;
    }
    catch(e){
      alert("exception caught : "+e);
      return false;
    }
  } else return true;

};

/**
*
* astral scripts
*
**/


var si_site_name = 'sri.vrak';
var si_ord = Math.round(Math.random()*100000000000);
function SIWriteAdvert(si_zone, si_tile_id, si_size) {
 
  try {
    var dcopt_val = '';
    if (si_tile_id == 1) {
      dcopt_val='dcopt=ist;'
    }
    document.write("<sc"+"ript type=\"text/jav"+"ascript\" src=\"http://ad.double"+"click.net/adj/"+si_site_name+"/"+si_zone+";"+dcopt_val+"tile="+si_tile_id+";sz="+si_size+";ord="+si_ord+"?\"></scr"+"ipt>");
  } catch (e) {
    alert('error');
    return;
  }
   /**/
};



/**
*
* Initialisations
*
**/
$(document).ready(function(){	

  $('a.already_member').lightBox({
    containerId: 'lightbox-login-hidden',
    closeClass: 'lightbox_closer-active',
    fixedNavigation:false
  });

  $('a.fabrique_helper').lightBox({
    forcedWidth: 724,
    forcedHeight: 472,
    containerId: 'lightbox-help-hidden',
    fixedNavigation:false
  });
  
  $('a.fabrique_helper_video').lightBox({
    forcedWidth: 724,
    forcedHeight: 472,
    containerId: 'lightbox-help-video-hidden',
    closeClass: 'lightbox_closer-help',
    fixedNavigation:false
  });

  $('a.lightbox-profile').lightBox({
    forcedWidth: 400,
    forcedHeight: 472,
    containerId: 'lightbox-profile-hidden',
    closeClass: 'lightbox-profile',
    fixedNavigation:false
  });
  
 
      
  $('a.defi_link_video').bind('click', function(){
    var swf_target = $(this).attr('rel');
    var swf_target_inject = 'LB'+swf_target;
    
    $(this).lightBox({
      forcedWidth: 695,
      forcedHeight: 535,
      swfContainerId: swf_target_inject,
      containerId: 'lightbox-presentation-video-hidden',
      closeClass: 'closer',
      fixedNavigation:false
    });
    window.setTimeout('VLVPlayerPresentation.writeVideo("'+swf_target+'","'+swf_target_inject+'","defi_link_video")', 1000);
    return false;
  });
  
  $('a.defi_link_video_prec').bind('click', function(){
    var swf_target = $(this).attr('rel');
    var swf_target_inject = 'LB'+swf_target;
    
    $(this).lightBox({
      forcedWidth: 695,
      forcedHeight: 535,
      swfContainerId: swf_target_inject,
      containerId: 'lightbox-presentation-videoprec-hidden',
      closeClass: 'closer',
      fixedNavigation:false
    });
    //VLVPlayerPresentation.writeVideo(swf_target);
    window.setTimeout('VLVPlayerPresentation.writeVideo("'+swf_target+'","'+swf_target_inject+'","defi_link_video_prec")', 1000);
    return false;
  });
  
  /*
  * Votes functions
  */
  $('.votable').hover(
    function () {
      VLVobj.vote.initiated = true;
    },function () {
      VLVobj.vote.initiated = false;
      VLVobj.vote.reinit();
    }
  );
  
  $('.votable a').hover(
    function () {
      if(VLVobj.vote.initiated)
      {
        var link = $(this);
        $('.votable a').find("span").removeClass("on").addClass("off");
        $('.votable a')
          .filter(function(){
            return ( parseInt(link.attr("rel")) >= parseInt($(this).attr("rel")) ); 
          })
          .find("span").removeClass("off").addClass("on");
      };
    }, 
    function () {}
  );

  $('.votable a').bind('click', function(){
    
    if(!VLVobj.vote.locked)
    {
      VLVobj.vote.locked = true;
      var video_parent_id = $(this).attr('href').substring(1);
      var video_vote = $(this).attr('rel');
      var video_atom_id = $(this).closest('.votable').children('span.hidden').attr('id').substring(4);

      vlvjs.api.voteForSketch(function(response){
        if(response)
        {
          if(response.code && (response.code == "ERR_ALREADY_VOTED"))
          {
            $('#sketch_infos .vote .msg').html(heap.labels['videos_vote_already_vote']);
            VLVobj.vote.reinit();
          }
          else if(response.data)
          {
            $('#sketch_infos .vote .msg').html(heap.labels['videos_vote_thanks']); 
            VLVobj.vote.reinit(response.data);
          }
          $('.votable').unbind();
          $('.votable a').unbind();
        }
        return false;
      },{ parent_id: video_parent_id, value: video_vote, atom_id: video_atom_id, type: 'vote', title: 'vote pour '+video_parent_id });
    }
    return false;
  });

 /*
 * login and fabrique interface events binders
 */
 
  $('#jquery-lightbox .itext').live('keydown', function(){
    $('#jquery-lightbox .error_msg').hide();
  });
  
  $('#jquery-lightbox .lightbox_closer-none').live('click', function(){
      $('#lightbox-container-close').trigger('click');
  });
  
  $('#jquery-lightbox .lightbox_closer:not(.lightbox_closer-none)').live('click', function(){
    if(!VLVobj.initFlash(VLVFabrique)){
      //alert("VLVobj.initFlash(VLVFabrique) not defined"); return false;
    }
    else{
      if($(this).hasClass('lightbox_closer-help'))
      {
        VLVFabrique.swfobj.vlv_video_tutorial_closed();
      }
      else
      {
        VLVFabrique.swfobj.vlv_userIsConnected(VLVFabrique.swfbridge.logged);
      }
    }
    $('#lightbox-container-close').trigger('click');
  });
  
  $('#jquery-lightbox .form_login_submit').live('click', function(){
  
    var cb_login = function(response)
    {
      VLVFabrique.swfbridge.logged = "false";
      if(response.data && response.data.username)
      {
       
        VLVFabrique.swfbridge.logged = "true";
        vlvjs.api.renderConnectBox(function(response){  
          if(response.data && response.data.html)
            $('#disconnect').replaceWith(response.data.html);
        }, params);
       
        if(VLVFabrique && VLVFabrique.swfobj)
        {
          // lock login to non finaliste users if in final mode
          var user_roles = response.data.roles;
          VLVFabrique.swfobj.vlv_userIsConnected(VLVFabrique.swfbridge.logged);

          if(user_roles && (user_roles.indexOf(p_role) == -1))
          {
            $('#jquery-lightbox').remove();
            $('a.lightbox_nonfinaliste').trigger('click'); 
            $('#fabrique_flash').remove();
            return false;
          }
          
        }
        $('#lightbox-container-close').trigger('click');
      }
      else
      {
        $('#jquery-lightbox .error_msg').fadeIn();
      }
      return false;
    
    };
    
    var p_username = $('#jquery-lightbox .connect_username').val();
    var p_password = $('#jquery-lightbox .connect_password').val();
    var p_role = $('#jquery-lightbox .connect_role').val();
    var params = { username: p_username, password: p_password };

    vlvjs.api.login(cb_login, params);
    return false;
  });
  
  $('#jquery-lightbox form').live('submit', function(){
    $('#jquery-lightbox .form_login_submit').trigger('click');
    return false;
  });

  /*
  * pager / sorter
  */
  $('a.abuse').live('click', function(){
    var abuse_url = $(this).attr('rel');
    var abuse_response = $(this).attr('href');
    var curr_link  = $(this);
    vlvjs.api.sendAbuseEmail(function(response){
        if(response && (response.code == 'OK'))
        {
          curr_link.fadeOut();
          $(abuse_response).fadeIn();
        }
        return false;
      },{ url: abuse_url });
    return false;
  });
  
  $('.pager ul li a').live('click', function(){   
    if(!$(this).hasClass('selected'))
    {
      $('_loader').show();
      $('#videos_paged_container ul li').fadeOut();
      
      var page_param = ($(this).attr('rel')) ? $(this).attr('rel') : 1;
      var sketchs_se = { template: 'ui/videos_container.html', paged: true };
      if(sketchs_se_row_number)
        sketchs_se.row_number = sketchs_se_row_number;
                
      sketchs_so.page = page_param;
      
      params = { searchParams: sketchs_sp, searchOptions: sketchs_so, searchExtras: sketchs_se};   
      vlvjs.api.listSketch(cb_listSketchs, params);
    }
    return false;
  });
  
  $('#sorter_top a#defis_filter').live('click', function(){  
    var is_hidden = ( $('#defis_filter_list').css('display') != 'block' );
    if(is_hidden)
      $('#defis_filter_list').fadeIn();
    else
      $('#defis_filter_list').fadeOut();
  });
  
  $('#sorter_top a.sorter_link').live('click', function(){  
    if(!$(this).hasClass('selected'))
    {  
      $('_loader').show();
      $('#sorter_top a').removeClass('selected');
      $(this).addClass('selected');
      $(".pager ul li a[rel='1']").addClass('selected');
      $('#videos_paged_container ul li').fadeOut();
      
      var sketchs_se = { template: 'ui/videos_container.html', paged: true, row_number: 4};
      if(sketchs_se_row_number)
        sketchs_se.row_number = sketchs_se_row_number;
        
      if($(this).attr('rel') != 'defis')
      {
        var sort_param = ($(this).attr('rel')) ? $(this).attr('rel') : '_time_created';
        sketchs_so.sort = sort_param;
        sketchs_so.page = 1;
      }
      else
      {
        var sort_param = '_time_created';
        //var sketchs_se = { template: 'ui/videos_container.html', paged: true };
                
        sketchs_so.sort = sort_param;
        sketchs_so.page = 1;
        sketchs_sp.atom_id = $(this).attr('href').substring(1);
      }
      params = {searchParams: sketchs_sp, searchOptions: sketchs_so, searchExtras: sketchs_se};
      vlvjs.api.listSketch(cb_listSketchs, params);
    }
    return false;
  });
  
  /*
  * caroussel
  */
  
  params = { scroll: 1, animation: 'slow', easing: 'easeInOutExpo' }; 
  $('#vrak_related #photos .photos_list').jcarousel(params);

  var params_related = { vertical: true, scroll: 1, animation: 'slow', easing: 'easeInOutExpo' };
  $('#related_carousel .videos_list ul').jcarousel(params_related);
  
  $('#defis #archives ul li a.disabled').css('opacity', 0.5);

  var isIE = jQuery.browser.msie;  
  if(isIE)
    $('#footer #astral').css('margin-top','36px');
  
   
});
