-неизвестно

 -Поиск по дневнику

Поиск сообщений в ATUM

 -Подписка по e-mail

 

 -Постоянные читатели

 -Статистика

Статистика LiveInternet.ru: показано количество хитов и посетителей
Создан: 17.02.2006
Записей:
Комментариев:
Написано: 1139


facebook Cookie

Суббота, 19 Января 2013 г. 11:04 + в цитатник
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
<!--

var is_not_publish = true;
var data = new Object(); 

var del_add_text = "Delete application";//"Удалить приложение";
var timeline_on = "Timeline On";//"Хроника включена";
var timeline_off = "Timeline Off";//"Хроника выключена";
var delete_txt = "delete";//"удалить";
//var ntv_verb = getMeta("og:type");
//var ntv_objectType = "ntv_program";
var ntv_verb = 'ntvtimeline:ntv_live';
var ntv_objectType = 'peredacha';
var postId=0; // id - новости на facebook
var postIdTimer = null; // таймер для отправки просмотренного видео
var url =  getMeta("og:url");
url = encodeURIComponent(url);
window.fbAsyncInit = function () {
  FB.init({
    appId: '398092463538505', // App ID
    status: true, // check login status
    cookie: true, // enable cookies to allow the server to access the session
    oauth: true, // enable OAuth 2.0
    xfbml: true // parse XFBML
  });
  
   //TODO возможно сюда перенести функции publish_news updateButton
   // так было в примере !?
  
  // run once with current status and whenever the status changes
  //тут вызов два раза
  FB.getLoginStatus(showUserPanel);
  FB.Event.subscribe('auth.statusChange', showUserPanel);  
};    


function fbchecker(checked){
  console.log(checked);
}

function getVerb(){
  var result = 'ntvtimeline:ntvwatch?ntvvideo';
  //  result = 'ntvtimeline:ntv_live?peredacha';
  //ntvtimeline:peredacha - ntvtimeline:ntv_live?peredacha=
  //ntvtimeline:ntv_video - ntvtimeline:ntv_watch?ntv_video=
   var type = getMeta("og:type");
   if(type.length>0){
    var verb = type.split(":");
   if(verb != null && verb[1] == 'peredacha'){
     result = 'ntvtimeline:ntv_live?peredacha';
   }
   if(verb != null && verb[1] == 'ntv_video'){
     result = 'ntvtimeline:ntv_watch?ntv_video';
   }
   if(type!=null && type =="article" ){
     result = 'news.reads?article';
   }
   
     if(type!=null && type =="video.other" ){
     result = 'video.watches?video';
   }
  
   
   }
  return result;
}
function getObjectType(){
  //var ntv_objectType = 'ntv_video'; //'peredacha''
   var result = 'ntv_video';
   var type = getMeta("og:type");
  if(type.length>0){
    var verb = type.split(":");
    if(verb != null && verb[1] == 'peredacha'){
      result = 'peredacha';
    }
    if(verb != null && verb[1] == 'ntvvideo'){
      result = 'ntvvideo';
    }
    
   if(type!=null && type =="article" ){
     result = 'article';
   }
   
   if(type!=null && type =="video.other" ){
     result = 'video';
   }
    
  }
  return result;
  
}


function clckbtnaddnews(){
  $('#btnaddnews').removeClass("add");
  $('#btnaddnews').addClass("save");
  $('#btnaddnews').html('I read this');
  $('#btnaddnews').attr('disabled', 'disabled');
}

  function publish_news(){
    var isStat = isStatus();
//    console.log(" is_not_publish = "+is_not_publish +"; isStatus =  " + isStat);
   
    if(is_not_publish && isStat){
      is_not_publish = false;
       clckbtnaddnews();
     // var ntv_verb = 'ntvtimeline:ntv_watch';
     // var ntv_objectType = 'ntv_video';
    //  var ntv_verb = 'ntvtimeline:watch_online';
    //  var ntv_objectType = 'ntv_program';
    //console.log('/me/' + ntv_verb + '?' + ntv_objectType + '=' + url);
      console.log('/me/' + getVerb() + '=' + url);
      var mbody = getMeta("og:title");
      FB.api('/me/' + getVerb() + '=' + url, 'post', {message: mbody},
        function (result) {
          postId = result.id;
          console.log(result);
          postTimer();
        // console.log('published with id = ' + result.id);
          showPopupWindow(result);
        });
    }
     clckbtnaddnews();
     btnLater();
  }
  
  
//  $(document).ready(function(){
//  $(document).not('основной_элемент').click(function(){
//    $('элемент').slideUp(); // клик был на странице вне элемента
//  });
// 
//  $('основной_элемент').click(function(){
//    $('элемент').slideDown(); // клик был на самом основном элементе
//    return false;
//  });
//  
//});
  
    function showPopupWindow(result){
      $('#infowindow').fadeIn(4000, function (){
        
        setTimeout(function(){
          $('#infowindow').fadeOut(4000);
        },3000);
      });
    }
  
  // propname,propval, content
function getMeta(property) {
 var metas = document.getElementsByTagName('META');
 var i;
 var url;
 for (i = 0; i < metas.length; i++){
   if (metas[i].getAttribute('property') == property){
   url = metas[i].getAttribute('content');  
   return url
   break;
   }
 }
//  url = window.location.toString();
 return url;
}
  

  function showUserPanel(response) {
    
    FB.getLoginStatus(function(response) {
      
    showHelp(response.status);
    
    if (response.status === 'connected') { 
     
     document.getElementById('login-panel-on').setAttribute('style','display:block;'); 
     document.getElementById('login-panel-off').setAttribute('style','display:none;');
     loadUserInfo(response);
    }else{
     document.getElementById('setting-dialog').setAttribute('style','display:none;'); 
     document.getElementById('login-panel-on').setAttribute('style','display:none;'); 
     document.getElementById('login-panel-off').setAttribute('style','display:block;');
    
      if(response.status === 'not_authorized'){
        
      //   document.getElementById('helpcenter').style.display='';
      }
     
    }
  });
  }  
  
  
  function showHelp(resp){
 
  var fb_source = false;
  var fb_appcenter = false;
  var access_token = "0";
  //?fb_source=appcenter&fb_appcenter=1&code=AQB4cKbGiO
  var search = document.location.search.substr(1);
  var parts  = search.split("&");
  for (i=0; i<parts.length; i++) {
    var curr = parts[i].split('=');
    if(curr[0] == "fb_source" & curr[1] == "appcenter"){
      fb_source = true;
    }
    if(curr[0] == "fb_appcenter" & curr[1] == "1"){
      fb_appcenter = true;
    }
    if(curr[0] == "fb_action_ids" & curr[1] == "486575714693365"){
      fb_source = true;
      fb_appcenter = true;
    }
  }
  if(fb_source && fb_appcenter || resp === 'not_authorized'){
  
     document.getElementById('helpcenter').style.display='block';
     document.getElementById('popup_overlay').style.display='block';
     
  }
  }
 
  function btnLater(){
     document.getElementById('helpcenter').style.display='none';
     document.getElementById('popup_overlay').style.display='none';
  }


 var dx = [0,-650,-2*650,-1930, -2495 , -3130];
 var pos = 0;
  function step_left(){
    console.log('step_left');
    pos--;
    if(pos<0) pos = 0;
    var xpos = dx[pos];
    if($.browser.safari){
      $('#infolenta').animate({'background-position-x': xpos+'px'},'slow');
    }else{
      $('#infolenta').css("background-position", xpos+'px '+ '-64px');
    }

  }
  
  function step_right(){
     console.log('step_right');
    pos++;
    if(pos>(dx.length-1)) pos = 0;
    var xpos = dx[pos];
    if($.browser.safari){
      $('#infolenta').animate({'background-position-x': xpos+'px'},'slow');
    }else{
      $('#infolenta').css("background-position", xpos+'px '+ '-64px');
    }

  }
  
  function loadUserInfo(response){
    //console.log("response.authResponse = "+response.authResponse);
    if (response.authResponse) {
     FB.api('/me', function(response) {
       //console.log(response.id + " = " +response.name);
        var userPicture = document.getElementById('user-picture');
        userPicture.innerHTML = '<img src="https://graph.facebook.com/'+ response.id + '/picture">';
         var userName = document.getElementById('user-name');
         userName.innerHTML = '<a href=\"'+response.link+'\" target=\"_blank\">'+response.name+'</a>' ;
         get_timeline_status();
         setTimeout(publish_news,11000);
      });
    }
  }

function showSettingPanel(){

 document.getElementById('login-panel-on').setAttribute('style','display:none;');
 document.getElementById('setting-dialog').setAttribute('style','display:block;');
 hide();

  FB.getLoginStatus(function(response) {
    //console.log("response.authResponse = "+response.authResponse);
    if (response.authResponse) {
      FB.api('/me', function(response) {
        var userPicture = document.getElementById('user-picture1');
        userPicture.innerHTML = '<img src="https://graph.facebook.com/'+ response.id + '/picture">';
        var userName = document.getElementById('user-name1');
        userName.innerHTML = '<a href=\"'+response.link+'\" target=\"_blank\">'+response.name+'</a>' ;
      });
    }
  });


}

function hideSettingPanel(){
   document.getElementById('login-panel-on').setAttribute('style','display:block;');
   document.getElementById('setting-dialog').setAttribute('style','display:none;');
}

// Load the SDK Asynchronously

(function(d, s, id) {
 var js, fjs = d.getElementsByTagName(s)[0];
 if (d.getElementById(id)) return;
 js = d.createElement(s);js.id = id;
 js.src = "//connect.facebook.net/ru_RU/all.js#xfbml=1&appId=398092463538505";
 fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

//(function (d) {
//  var js, id = 'facebook-jssdk';
//  if (d.getElementById(id)) {
//    return;
//  }
//  js = d.createElement('script');
//  js.id = id;
//  js.async = true;
//  js.src = "//connect.facebook.net/ru_RU/all.js#xfbml=1&appId=398092463538505";
//  d.getElementsByTagName('head')[0].appendChild(js);
//} (document));



// устанавливаем cookie для того чтобы понять отключили ли мы ведение хроники или нет .
// name = timeline : value on | off
function set_cookie (name, value){
 var cookie_string = name + "=" + encodeURIComponent ( value );
    var expires = new Date();
      expires.setFullYear(expires.getFullYear() + 1);
    var path = "/";
    var domain = 'ntv.ru';
    var secure = false;
  if (expires) cookie_string += '; expires=' + expires.toGMTString();
  if (path)  cookie_string += '; path=' + path;
  if (domain) cookie_string += '; domain=' + domain;
  if (secure) cookie_string += '; secure';
 
 //console.log('set_cookie : ' + cookie_string); 
 
 document.cookie = cookie_string;
}

function get_cookie ( cookie_name ){
  
    var pattern = "(?:; )?" + cookie_name + "=([^;]*);?";
  var regexp = new RegExp(pattern);
  if (regexp.test(document.cookie)){
  return decodeURIComponent(RegExp["$1"]);
    }
  return false;
}

function isStatus(){
  if ( ! get_cookie ( "timeline" ) ){
    set_cookie ( "timeline", "on");
       return true;
   }else{
    var status = get_cookie ( "timeline" );
    if(status == 'on'){
       return true;
    }
  }
   return false;
}

function set_timeline_status(){
  // если ее нет то выслявляем в off
  var status = isStatus();
  if(status) {
    set_cookie ('timeline', 'off');
  }
  else{
    set_cookie('timeline', 'on');
    publish_news();
  }
  get_timeline_status();
}
// on | off
function get_timeline_status(){
  // если ее нет то выслявляем в off  
  if ( ! get_cookie ( "timeline" ) ){
    set_cookie ( "timeline", "on");
    //console.log("timeline = off");
  }
  
  var isStatus = false;
  var f = document.getElementById('timeline_btn');
  var el = document.getElementById('timeline-status');
  var status = get_cookie ( "timeline" );
  //console.log( "status = " +status);
  if(status == "off") {
    f.style.marginTop='52px';
    f.title = timeline_off;//'Хроника Выкл.';
    el.style.backgroundImage = 'url(/i/fb/timeline_off.gif)';
  } else
  if(status == "on"){
    f.style.marginTop='2px';
    f.title = timeline_on;//'Хроника Вкл.';
    el.style.backgroundImage = 'url(/i/fb/timeline_on.png)';
    isStatus = true;
  }
    
   
  return isStatus;
}


// delete app
function delete_ntv_app(){
  set_cookie('timeline', 'on');
  FB.getLoginStatus(function(response) {
    if (response.status === 'connected') { 
     FB.api("/me/permissions","DELETE",function(response){
     //console.log(" DELETE app : "+response); //gives true on app delete success
     document.location.reload();
    });
    }
  });
  
  
}

function all_history_show(flag){
//console.log("all_history_show == "+ flag );
var id = document.getElementById('history-list');
var el = document.getElementById('history');
if(flag){
 id.style.display="block";
 el.style.display="block";
}else{
  id.style.display="none";
  el.style.display="none";
}
}



// всплывающее окно с прочитанными новостями
<!--
function show (evt, id) {
var evt = evt || window.event;

var f = document.getElementById('history-items');
f.opacityFilter = 0;
f.className = 'popup_active';
f.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (f.opacityFilter * 100) + ');';
f.style.opacity = f.opacityFilter;
f.style.display = 'block';
f.style.top = '0';
f.style.left = '410px';
window.setTimeout('animate()', 50);
 if (evt.stopPropagation)  evt.stopPropagation();
 if (evt.cancelBubble!=null) evt.cancelBubble = true;

return false;
}

function open_history(){
  window.open("http://www.facebook.com/me/app_398092463538505", "", "");
}


function showHistory(){
   var f = document.getElementById('history-items');
     f.style.display = 'block';
     //console.log('showHistory');
}

// формат времени
function checkTime(i)
{
if (i<10)
 {
 i="0" + i;
 }
return i;
}
// является ли переменная числом
function isNum(v) {
    return typeof v === 'number' && isFinite(v);
}

// загрузка локальной истории
function load_history(evt, id){
   FB.getLoginStatus(function(response) {
    if (response.status === 'connected') { 
      console.log(getVerb());
     FB.api("/me/"+getVerb(),"GET",function(response){
     // парсим ответ
     
     if(!response.data || !response.data.length){return;}
     
     var length = response.data.length;
     if(length>0){
      for(var i=0; i<length && i<7; i++) {
      var news_id = response.data[i].id;
     // var ntv_article_id = response.data[i].data.ntv_article.id;
      var date = new Date(response.data[i].publish_time);
      var y = date.getYear()+1900;
      var m = date.getMonth();
      var d = date.getDate();
      var isNumder = false ;
      var time = "";
      isNumder = isNum(date.getHours()) && isNum(date.getMinutes());
      if(isNumder){
       var h = isNum(date.getHours()) ? checkTime(date.getHours()) : "12";
       var mi =isNum(date.getMinutes()) ? checkTime(date.getMinutes()) : "00";
       time = h +":"+mi+" ";
      }
       ntv_objectType = getObjectType();
       console.log(response.data[i]);
      if(response.data[i].data == undefined) continue;
      
      var title  = time + response.data[i].data[ntv_objectType].title;
      var url   = response.data[i].data[ntv_objectType].url;
      //data.push(news_id,title);
       if(data[news_id] == null){
       data[news_id] = title;
       //console.log( data[news_id] +" = "+ title);
       append_news(news_id , title , url);
       }
      }
      show (evt, id);
     
     
     }
    });
    }
  });
 
}


function delete_news(news_id){
   FB.getLoginStatus(function(response) {
    if (response.status === 'connected') { 
     FB.api("/"+news_id,"DELETE",function(response){
     //console.log("delete_news : " + response);
     if(response == true){
       var y = document.getElementById('id'+news_id);
       var x = document.getElementById("history-items");
       x.removeChild(y);
       // скрыть окно если в нем больше ничего нет :
       var size = $('#history-items').children().size();
       //console.log("history-items.length : " + size);
      if(size == 1){
        hide();
      }
     }
    });
    }
  });
}

// вставка новости в div истории
function append_news (news_id, title , url) {
 var el = document.createElement('div');
 el.setAttribute ('id', 'id'+news_id);
 el.setAttribute ('style','display: block; top: 0px; left: 0px;width:400px; position: relative;');
 el.setAttribute ('class','newli');
 var text = title.substring(0,55)+'...';
 text = "<a href=\""+ url+"\" class='ntv_decoration' >" + text + "</a>";
 el.innerHTML=text + "<a class='close1 ntv_decoration' href=\"javascript:delete_news('"+news_id+"') ;\"><span>"+delete_txt+"</span></a>";
 document.getElementById('history-items').appendChild(el);
}

function hide() {
var div = document.getElementById('history-items');
if (div != null) {
 div.className = 'footnote_new';
 div.style.display = 'none';
}
return false;
}

function animate() {
var f = document.getElementById('history-items');
f.opacityFilter += 0.05;
f.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (f.opacityFilter * 100) + ');';
f.style.opacity = f.opacityFilter;
if (f.opacityFilter<1) window.setTimeout('animate()', 50);
}

function getPosition(offsetTrail) {
var offsetLeft = 0;
var offsetTop = 0;
while (offsetTrail) {
 offsetLeft += offsetTrail.offsetLeft;
 offsetTop += offsetTrail.offsetTop;
 offsetTrail = offsetTrail.offsetParent;
}
return {left:offsetLeft, top:offsetTop}
}


// отсылка информации в facebook о том что мы смотрим видео
function postTimer(){
   postIdTimer = setTimeout(function run() {
    if(postId!= undefined && postId.length>1){
      console.log(postId); 
      FB.api('/'+postId, 'post', {
        expires_in : '5000'
      } ,function(response){
        resp1 = response;
        console.log(response );
        if(response.error && response.error.code==100){
          clearTimeout(postIdTimer);
          postIdTimer = null;
        }
      } );
    } 
    if(postIdTimer!=null)
      postIdTimer = setTimeout(run, 5000);
 }, 5000);

}

var fb_timer = null;

function fb_play(){
  console.log('fb_play');
   fb_timer = setTimeout(publish_news,11000);
   postTimer();
}

function fb_stop(){
   console.log('fb_stop');
  if (fb_timer!= null){
    clearTimeout(fb_timer);
    fb_timer = null;
    clearTimeout(postIdTimer);
    postIdTimer = null;
  }



$(document).ready(function () {
  
  if(true){
  document.getElementById('login-txt1').innerHTML='Share with friends in Facebook information that you have read and looked at ntv.ru';
  if(document.getElementById('login-txt2'))
    document.getElementById('login-txt2').innerHTML='Log in to start';
  
  document.getElementById('setting').setAttribute('title','Application settings');
  
  document.getElementById('history-link').setAttribute('title','The history of your activity on the site НТВ.RU');
  document.getElementById('history-link').innerHTML='your activity';
  
  document.getElementById('all_history_link').innerHTML='The whole history of activity';
  document.getElementById('all_history_link').setAttribute('title','The whole history of activity of the application on the site НТВ.RU');
  
  document.getElementById('delete_app').innerHTML='Remove the application';
  document.getElementById('delete_app').setAttribute('title','Remove the application and all the history of its activity');
  
  
  document.getElementById('x_image').setAttribute('title','Close');
  document.getElementById('history-header-txt').innerHTML='<b>History of activity:</b>';
  

}
});
//-->


* This source code was highlighted with Source Code Highlighter.
Метки:  

 

Добавить комментарий:
Текст комментария: смайлики

Проверка орфографии: (найти ошибки)

Прикрепить картинку:

 Переводить URL в ссылку
 Подписаться на комментарии
 Подписать картинку