// Required by all javascript calls
var MINHost = 'http://myinboxnews.com';
//MINHost = '';

var MIN = {
  host     : MINHost,
  codebase : MINHost + '/javascripts',
  base_url : MINHost + '/api',
  referral_string : '',
  make_call : function(path, params, callback, callback_params) {
    var vname, params_strings = [], url, i, callback_param;
    callback_params = callback_params || [];
    params = params || {};
    
    url = this.base_url + path;
    for (vname in params) { params_strings.push(vname + '='  + params[vname]); }
    params_strings.push('callback' + '=' + callback);
    for (i=0; callback_param = callback_params[i]; i++) { params_strings.push("callback_args[]=" + callback_param);}
    url = url + '?' + params_strings.join('&');
    document.write('<script type="text/javascript" defer="defer" src="'+ url + '"><'+'/script>');
  },
  lists : {},
  videos : {},
  
  generate_id : function(length) {
    length = length || 50;
    var r_str = "0123456789";
    r_str += "abcdefghijklmnopqrstuvwxyz";
    r_str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    var ret_str = '';
    for (var i=0; i < length; i++) { ret_str += r_str.charAt(this.random_number(0, r_str.length - 1)); }
    return ret_str;
  },
  
  random_number : function(lbound, ubound) {
    return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
  },
  
  get : function(name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp( "[\\?&]"+name+"=([^&#]*)" );
    var results = regex.exec( window.location.href );
    return results ? results[1] : '';
  },
  
  show_video : function(id, small_player, id_list, opts) {
    
    if (id == 'horoscopes') {
      window.open(MINHost + '/option/horoscopes');
      return false;
    }
    
    opts = opts || {};
    jQuery.facebox.settings.opacity = .5;
    jQuery.facebox.settings.unloadMethods = [
      function() { jQuery('#facebox .body .content').html('');},
    ];
    jQuery.facebox.settings.closeImage = MIN.host + '/images/facebox/closelabel.gif';
    jQuery.facebox.settings.loadingImage = MIN.host + '/images/facebox/loading.gif';
    if(small_player) {
      jQuery.facebox('<iframe id="min_player_frame" src="' + MIN.host + '/videos/' + id + '?embedded=true&auto_start=true&referral_string=' + MIN.referral_string + '" width="640" height="480"></iframe>');
    } else {
      jQuery.facebox.settings.faceboxHtml('<div id="facebox" class="bigfacebox" style="display:none;"> \
          <div class="popup"> \
            <table> \
              <tbody> \
                <tr> \
                  <td class="body"> \
                    <div class="content" style="width: 910px; 615px;"> \
                    </div> \
                  </td> \
                </tr> \
              </tbody> \
            </table> \
          </div> \
        </div>');
      jQuery.facebox('<div id="min_video_player">You need javascript and flash to view this video</div>');
      var flashvars = { id : id, embedded : true, referral_string : MIN.referral_string, category_ids : id_list, auto_start : true, show_videos : opts.show_videos, show_horoscopes : opts.show_horoscopes };
      
      var htmlvars = { allowfullscreen : true, bgcolor : '#000000', allowscriptaccess : 'always' };
      swfobject.embedSWF(
        MINHost + '/flash/video_player_big.swf?v=1.52',
        'min_video_player',
        910,
        615,
        "9.0.0",
        "/flash/expressInstall.swf",
        flashvars,
        htmlvars
      );
    }
  },
  
  close_video : function() {
    jQuery(document).trigger('close.facebox');
  },
  
  email_video : function(id) {
    var subject = 'Watch this video on My Inbox News';
    var body_message = "Hello, \n \
I thought you would enjoy this video. Watch it by clicking on the following link: \n \
\n \
http://myinboxnews.com/videos/" + id + " \n \
__________________________________________________________________________________________________ \n \
I love receiving My Inbox News!  You should sign up. \n \
They send you short video clips - funny, positive, informative and very entertaining. \n \
Please sign up for your FREE email.  You can opt-out at any time - no risk. They also give you rewards! \n \
Click the link below and sign up \n \
http://myinboxnews.com/users/new";
    var mailto_link = 'mailto:?subject='+subject+'&body='+body_message.replace(/[\r\n]/g, '%0A');
    var win = window.open(mailto_link,'emailWindow');
    if (win && win.open &&!win.closed) { win.close(); }
    
  }
};

document.write('<link rel="stylesheet" href="' + MIN.host + '/stylesheets/facebox.css"/>');
document.write('<script type="text/javascript" src="'+ MIN.codebase + '/jquery-1.2.6.pack.js"></script>'  );
document.write('<script type="text/javascript" src="'+ MIN.codebase + '/jquery.facebox.js"></script>'  );
document.write('<script type="text/javascript" src="'+ MIN.codebase + '/jquery.url.js"></script>'  );
document.write('<script type="text/javascript" src="'+ MIN.codebase + '/swfobject.js"></script>'  );



function MINVideo(id) {
  this.id = id;
  MIN.videos[id] = this;
  MIN.make_call('/videos/' + id + '.js', {}, "MIN.videos['" + id +"'].process" );
}

MINVideo.prototype = {
  process : function(data)  {
    var v; for (v in data) { this[v] = data[v]; }
    this.finished = true;
  },
  
  replace_ids : function(obj)  {
    this.replace_info = obj;
    this.timer = setInterval('MIN.videos['+this.id+'].do_replace()', 100);
  },
  
  do_replace : function() {
    if (this.finished) {
      clearInterval(this.timer);
      for (v in this.replace_info) { document.getElementById(v).innerHTML = this[this.replace_info[v]]; }
    }
  }
}


function MINList(container_id, video_box_id, id_list) {
  this.container_id = container_id;
  this.video_box_id = video_box_id;
  if (!(id_list instanceof Array)) {id_list = [id_list]}
  this.id_list = id_list;
  this.id = MIN.generate_id();
  MIN.lists[this.id] = this;
  this.video_lists = {};
  this.popup = false;
  this.limit = false;
}

MINList.prototype = {
  small_player : false,
  
  embed : function() {
    var opts = this.limit ? {limit : this.limit} : {};
    jQuery(document).bind('reveal.facebox', function() { if (!/MSIE 6/i.test(navigator.userAgent)) { $('#facebox').css('position', 'fixed'); } });
    for (i=0; id = this.id_list[i]; i++) {
      MIN.make_call('/categories/' + id + '/videos.js', opts, "MIN.lists['"+ this.id + "'].process");
    }
  },
  
  sort_videos : function (v1, v2) {
    if (v1.air_date < v2.air_date) { return 1; }
    else if (v1.air_date > v2.air_date) { return -1; }
    return 0;
  },
  
  process : function(cat_id, video_data) {
    var vl,i, i2, l, v, all_videos = [], video, master_video_box, video_box, video_container;
    this.video_lists[cat_id] = video_data;
    for (i=0; vl = this.id_list[i]; i++) { if (!this.video_lists[vl]) return; } // Have not yet retreived all the data.
    for (l in this.video_lists) { l = this.video_lists[l]; for (var i2=0; v = l[i2]; i2++) { all_videos.push(v); } }
    all_videos = all_videos.sort(this.sort_videos);
    
    
    master_video_box = document.getElementById(this.video_box_id);
    video_container = document.getElementById(this.container_id);
    
    var child;
    for (i=0; video = all_videos[i]; i++) {
      video_box = document.createElement('div');
      video_box.className = 'min_video';
      video_box.innerHTML = master_video_box.innerHTML;
      for (i2=0; child = video_box.childNodes[i2]; i2++) {
        if (child.nodeType != 1) { continue; }
        switch(child.className) {
          case 'min_screencap':
            child.innerHTML = '<img src="'+ video.thumbnail + '" alt=""/>';
            break;
          
          case 'min_video_name':
            child.innerHTML = video.name;
            break;
          
          case 'min_date_featuring':
            child.innerHTML = video.featuring == '' || video.featuring == null ? video.air_date : 'with ' + video.featuring +', ' + video.air_date;
            break;
          
          case 'min_video_summary':
            child.innerHTML = video.summary;
            break;
        }
        if (this.popup) {
          child.innerHTML = '<a href="#" onclick="MIN.show_video(' + video.id + ', ' + this.small_player + ', \'' + this.id_list.join(',') + '\', { show_videos : \'' + this.show_videos + '\', show_horoscopes : \'' + (this.show_horoscopes || '') + '\'}); return false;">' + child.innerHTML + '</a>';
        } else { child.innerHTML = '<a href="' + this.video_url.replace('#{id}', video.id) + '">' + child.innerHTML + '</a>'; }
      }
      video_container.appendChild(video_box);
    }
    var br = document.createElement("br");
    br.style.display = 'block';
    br.style.clear = 'both';
    br.style.height = '1px';
    br.style.lineHeight = '1px';
    video_container.appendChild(br);
    var as = jQuery.url.param('auto_start');
    if (this.popup && as) { MIN.show_video(as == 'latest' ? all_videos[0].id : parseInt(as), false, this.id_list.join(',')); }
  }
  
};