Source: Clickbox.js

require ('./iView.js');
/**
* @param {Telll} t the telll object
* @author Monsenhor filipo at kobkob.org
* Clickbox --> init -> loadPhotolinks -> telll.getPhotolinksOfUser -> tws.readUserPhotolinks
* @constructor
*/
function Clickbox(t){
    this.t = t;
    this._init(t);
}

Clickbox.prototype = Object.create(iView.prototype);

/**
* @param t {} 
* @return bool
*/
Clickbox.prototype._init = function(t){
    if (!this.t.credentials.authKey){ throw("No authKey ... hmmm, aborting!"); }
    //this.verifyCWS(); // to have compatibility
     this.date = this.Date(0);
    // default pick photolinks from one week ago
    this.beginDate = this.Date(-7);
    var me = this;
    this.loadPhotolinks(this.beginDate, function(ps){
        me.photolinks = ps;
        me.state = "loaded";
        me.emit("loaded", me);
        t.store.clickbox = ps;
        me._showWidget(t.store);
    });
    me.state = "init";
    me.emit ("init");
    me.createPhotolink();
    return null;
}

/**
* @param data {} 
* @return bool
*/
Clickbox.prototype.verifyCWS = function(){
   // to be done ... ;) 
};
 

/**
* @param data {} 
* @return bool
*/
Clickbox.prototype._showWidget = function(data){
    var tmpl = require('./templates/clickbox.mtjs');
    var html = Mustache.render(tmpl.html, data);
    if (tmpl.css)
    $('<style id="clickbox-css">'+tmpl.css+'</style>').appendTo('head');
    $(html).appendTo('body');
    var telll = this.t;
    var me = this;
    $(".telll-clickbox-widget .close").on( "click", function( e, data ) {
	me.detach();
    });
    // The popup 
    $('<div id="popup-clickbox" class="popup"><div class="top-line rgb-bg" style="z-index: 9;"></div></div>').appendTo('body');
    $("#clickbox-widget").appendTo('#popup-clickbox').fadeIn();
    $('#popup-clickbox').css('z-index','999');
    $('html').addClass('overlay');
    this.state = "show";
    me.emit("show", me);
    return true;
};

/**
* @return null
*/
Clickbox.prototype.createPhotolink = function(){
    var me = this;
    me.t.getPhotolink( function(e,got){
        if (e) throw (e)
        else {
		// TODO: deprecate photolinkbb param
            if (got.photolinkbb){
               got.photolink = got.photolinkbb; // compatibility with demo
            }
            var rData = unescape(got.extra_data);
            try {
            var got = JSON.parse(rData); } catch(e){
            throw(e)}
            me.state = "got";
            me.emit ("got", got);
            me.updatePhotolinksList(got);
            me.showPhotolinkImage(got);
        }
    });
    me.state = "created";
    me.emit ("created");
};

/** 
 */
Clickbox.prototype.showPhotolinkImage =  function (got){
    var me = this;
    var myPl = got;
    // TODO hmmm ... it looks bad ... we need an image size manager
    try {
    var img = got.thumb.replace('_180x90','');
    } catch (err) {
    var img = "/img/transp.png";
    }
    $('<div id="photolink-image"><img class="main"/></div>').appendTo("body");
    $('#photolink-image img.main').attr('src', img);
    $('#photolink-image img.main').css({'width':'100%'});
    $('#photolink-image a').attr('href', myPl.link);
    $('#photolink-image a').attr('target', '_blank');
    $('#photolink-image').fadeIn(); 
    setTimeout(function(){
        $('#photolink-image').fadeOut("slow", function (){$('#photolink-image').detach()}); 
    }, 4000);
    me.state = "image";
    me.emit ("image",got);
       
};

/** 
 *
 * @see Telll.store.clickbox
 */
Clickbox.prototype.updatePhotolinksList = function (got) {
    var me = this;
    var myList ="";
    this.t.store.clickbox.push(got);
    var devicePhotolinks = this.t.store.clickbox;
    this.emit("got", got);
    $('#clickbox-empty').detach();
    $('#clickbox *').detach();
    $('#clickbox').height($(window).height()-40); 
    for(var i=0; i<devicePhotolinks.length;i++){
        if (! devicePhotolinks[i] || devicePhotolinks[i].photolink === undefined){ 
            throw("Error: clickbox has a bad photolinks list ...");
            return false 
        }
        else {
            var $element     = $('<div class="photolink-list-element"></div>');
            var $controlsFrm = $('<div class="ple-controls-frame"></div>');
            var $shareBtn    = $('<div class="share telll-control"></div>');
            var $favBlueBtn  = $('<div class="favorite-blue telll-control"></div>');
            var $buyBtn      = $('<div class="buy telll-control"></div>');
            var myPl = devicePhotolinks[i];
            var $content     = $('<a target="_blank" href="'+myPl.link+'"><div class="ple-img"><img src="'+myPl.thumb+'"></div><div class="ple-info"><span class="ple-title">'+myPl.title+'</span><span class="ple-desc">'+myPl.description+'</span><span class="ple-desc">'+myPl.imdbPlot+'</span></a>');
            $element.append(
                $content,
                $controlsFrm.append($shareBtn, $favBlueBtn, $buyBtn)
            );
	    // Special share feed
	    $shareBtn.on ("click", function(){
	        FB.ui({
	            method: 'feed',
	            picture: myPl.thumb,
	            link: 'http://webapp.telll.me/cgi-bin/photolink.pl?id='+myPl.id,
	            caption: myPl.title,
	        }, function(response){
	            if (response) telllDialog("Thanks to share on Facebook!",3000);
	        });
	    });
	    $buyBtn.on ("click", function(){
                window.open(myPl.link,'_blank');  
            });
	    $favBlueBtn.on ("click", function(){
                window.open("http://webapp.telll.me/cgi-bin/photolink.pl?id="+myPl.id,'_blank');  
            });
            $('#clickbox').append($element);
        }
    }
    me.state = "list";
    me.emit ("list",got);
};

/**
* @return null
*/
Clickbox.prototype.detach = function(){
    $('.telll-clickbox-widget').detach();
    $('#popup-clickbox').detach();
    this.state = "detached";
    this.emit("detached");
};

/**
* @return null
*/
Clickbox.prototype.attach = function(){
    this._showWidget(this.t.store);
};

/**
* Return actual date plus offset
* @param offset {int} number off days
* @return {string} the time in the format YYY-MM-DD hh:mm:ss
* it must be escaped to work in tws
*/
Clickbox.prototype.Date = function(offset){
var n = new Date();
var m = new Date(n.getTime() + offset * 24 * 60 * 60 * 1000);
var dateString =
  m.getUTCFullYear() +"-"+
  ("0" + (m.getUTCMonth()+1)).slice(-2) +"-"+
  ("0" + m.getUTCDate()).slice(-2) + " " +
  ("0" + m.getUTCHours()).slice(-2) + ":" +
  ("0" + m.getUTCMinutes()).slice(-2) + ":" +
  ("0" + m.getUTCSeconds()).slice(-2);
  return dateString;
};

/**
* @param date {String} the date from
* @param cb {Function} callback
* @return null 
* the list of photolinks sent to this user since date
*/
Clickbox.prototype.loadPhotolinks = function(date, cb){
     var me = this;
     // read cookies
     var deleted = this.t.getCookie("deleted");
     this.deleted = deleted || this.deleted || [];
     // read user data
     me.t.getPhotolinksOfUser(null, escape(date), function(list){
         if (!list.length) {
               // TODO what can we do here? :P
               list = [];
         }
         if (cb){ cb(list) } 
         else{
	 throw("Fatal error: Clickbox.loadPhotolinks needs a callback, please.")}
     });
};

module.exports = {Clickbox:Clickbox};