
var Video = Video || {};

Video.prerolls = [];
Video.loadPrerolls = function (set) {
  if (set) {
    url = "/prerolls/set/" + set + "/";
  } else {
    url = "/prerolls/"    
  }
  $.getJSON(url,
  function(data) {
    Video.prerolls = data;
  }); 
}
Video.getPreroll = function () {
  return Video.prerolls[Math.floor(Math.random() * Video.prerolls.length)];
}

function setupAdControl (options) {
  this.options = jQuery.extend({
    'positions': {},
    'views': null,
    'time': null,
    'sitewide': true,
    'delivery_url': 'http://ads2.ljworld.com/www/delivery/afr.php'
  }, options);

  this.original_ads = {};
  var options = this.options;
  
  // These are used if the sitewide is false
  var prerollcount = 0;
  var preroll_new_time = 0;
  var preroll_last_time = 0;
  $(document).bind('video_playing.video_tracker', function(e, percent, new_time) {
      preroll_new_time = preroll_new_time + new_time;
  });
  $(document).bind('video_start.video_tracker', function(e, video_url) {
      prerollcount = prerollcount + 1;
  });
  
  function needPreroll() {
    if (options.views) {
      if (options.sitewide) {
        debug('try site views: ' + Video.cookie.views());
        return (Video.cookie.views() == 0 || Video.cookie.views() % options.views == 0);
      } else {        
        debug('try page views: ' + prerollcount);
        return (prerollcount == 1 || prerollcount % options.views == 0);
      }
    } 
    if (options.time) {
      if (options.sitewide) {
        var new_time = Video.cookie.time()[0];
        var last_time = Video.cookie.last_time();
        debug('try site time: ' + new_time + ' / ' + last_time);
        if (Video.cookie.time()[0] == 0 || Math.floor(new_time / options.time) > Math.floor(last_time / options.time)) {
          Video.cookie.update_last_time();
          return true          
        }
      } else {
        debug('try page time: ' + preroll_new_time + ' / ' + preroll_last_time);
        var last_time = preroll_last_time;
        preroll_last_time = preroll_new_time;
        return (preroll_new_time == 0 || Math.floor(preroll_new_time / options.time) > Math.floor(last_time / options.time))
      }
    }
  }

  this.getPreroll = function() {
    var pr = {};
    if (needPreroll()) {
      debug('Preroll selected')
      pr = Video.getPreroll();
      this.setPositions(pr);
    }
    return pr;
  }
  
  insertAd = function(selector, ad) {
    $(selector).html('<iframe src="' + options.delivery_url + '?bannerid=' + ad.id + '" width="' + ad.width + '" height="' + ad.height + '"></iframe>');        
  };
  
  this.addPosition = function (identifier, selector) { 
      $(function() {    
        options[identifier] = {'selector': selector }
      });
    };
  this.setPositions = function (preroll) {
      for (position in preroll.companion_ads) {
        if (this.options.positions[position] != undefined) {
          insertAd(this.options.positions[position], preroll.companion_ads[position])
        }
      }
    };
  this.refreshAll = function () {
      for (ad in original_ads) {
        $(original_ads[ad].selector).html(original_ads[ad].original_ad);
      }
    };
}

Video.cookie = new function () {
  this.time = function () {
    return [Number(readCookie('time')), Number(readCookie('old_time'))];
  }
  this.addTime = function (time) {
    var old_time = this.time()[0];
    var new_time = old_time + time;
    createCookie('old_time', old_time, 'midnight')
    createCookie('time', new_time, 'midnight')
  }
  this.setTime = function (time) {
    createCookie('time', time, 'midnight')
  }
  this.time_passed = function (seconds) {
    var times = this.time();
    var new_time = times[0];
    var old_time = times[0];
    return (Math.floor(new_time / seconds) > Math.floor(old_time / seconds))
  }
  
  this.last_time = function () {
    return Number(readCookie('last_time'));
  }
  this.update_last_time = function () {
    var last_time = this.time()[0];
    createCookie('last_time', last_time, 'midnight')
  }

  this.views = function () {
    return Number(readCookie('views'));
  }
  this.addViews = function (views) {
    new_count = this.views() + views;
    createCookie('views', new_count, 'midnight')
  }
  this.setViews = function (views) {
    createCookie('views', views, 'midnight')
  }
  
  
  function createCookie(name,value,days) {
  	if (days) {
  	  if (days == 'midnight') {
    		var date = new Date();
    		date.setHours(23);
    		date.setMinutes(59);
    		date.setSeconds(59);
    		date.setMilliseconds(999);
    		var expires = "; expires="+date.toGMTString();  	    
  	  } else {
    		var date = new Date();
    		date.setTime(date.getTime()+(days*24*60*60*1000));
    		var expires = "; expires="+date.toGMTString();  	    
  	  }
  	}
  	else var expires = "";
  	document.cookie = name+"="+value+expires+"; path=/";
  }

  function readCookie(name) {
  	var nameEQ = name + "=";
  	var ca = document.cookie.split(';');
  	for(var i=0;i < ca.length;i++) {
  		var c = ca[i];
  		while (c.charAt(0)==' ') c = c.substring(1,c.length);
  		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  	}
  	return 0;
  }

  function eraseCookie(name) {
  	createCookie(name,"",-1);
  }
}

// Listeners
$(function (){
  $(document).bind('ad_start.video_tracker', function(e, ad) {
    event_track('prerolls', 'start',  ad.id);
  });

  $(document).bind('ad_complete.video_tracker', function(e, ad) {
    event_track('prerolls', 'complete', ad.id);
  });


  $(document).bind('video_start.video_tracker', function(e, video_url) {
    Video.cookie.addViews(1);
    event_track('videos', 'start', video_url);
    Video.current_video = video_url;
  });

  $(document).bind('video_playing.video_tracker', function(e, percent, new_time) {
    Video.cookie.addTime(new_time);
    var log_every = 60; // in seconds
    if (Video.cookie.time_passed(log_every)) {
      var rounded_time = Math.floor(Video.total_play_time / log_every) * 60
      $(document).trigger('time_passed.video_tracker', rounded_time);          
    }
    if (percent == 80) {
      $(document).trigger('video_completed.video_tracker', Video.current_video);      
    }
  });
  
  $(document).bind('time_passed.video_tracker', function(e, seconds) {
      event_track('videos', 'watch-time', 'minutes', (seconds/60));
  });

  $(document).bind('video_completed.video_tracker', function(e, video_url) {
    event_track('videos', 'complete', video_url);
  });
  
  function time_passed (seconds, previous_time, new_time) {
    return (Math.floor(new_time / seconds) > Math.floor(previous_time / seconds))
  }
  
  function event_track(category, action, label, value) {
    if (value) { txt_value = ", " + value } else { txt_value = "" };
    debug('# Tracking: ' + category + ', ' + action + ', ' + label + txt_value);
    try{
    pageTracker._trackEvent(String(category), String(action), String(label), value);
    } catch(err) {} 
  }
  
});

