//predefined variables
var JOB_DETAILS_TWITTER_SID = 15003;
var PROFILE_DETAILS_TWITTER_SID = 16003;
var MY_EXAMS_TWITTER_SID = 17003;
var EXAM_TWITTER_SID = 18003;
var JOB_DETAILS_TWITTER_EVT = 'tw.job';
var PROFILE_DETAILS_TWITTER_EVT = 'tw.profile';
var MY_EXAMS_TWITTER_EVT = 'tw.test';
var EXAM_TWITTER_EVT = 'tw.test';

function utf8_encode ( argString ) {
  var string = (argString+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  var utftext = "";
  var start, end;
  var stringl = 0;
  start = end = 0;
  stringl = string.length;
  for (var n = 0; n < stringl; n++) {
    var c1 = string.charCodeAt(n);
    var enc = null;
    if (c1 < 128) {
      end++;
    } else if((c1 > 127) && (c1 < 2048)) {
      enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
    } else {
      enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
    }
    if (enc !== null) {
      if (end > start) {
        utftext += string.substring(start, end);
      }
      utftext += enc;
      start = end = n+1;
    }
  }
  if (end > start) {
    utftext += string.substring(start, string.length);
  }
  return utftext;
}
function base64_encode( data ) {
  var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];
 
  if (!data) {
    return data;
  }
  data = this.utf8_encode(data+'');
  do{
    o1 = data.charCodeAt(i++);
    o2 = data.charCodeAt(i++);
    o3 = data.charCodeAt(i++);
    bits = o1<<16 | o2<<8 | o3;
    h1 = bits>>18 & 0x3f;
    h2 = bits>>12 & 0x3f;
    h3 = bits>>6 & 0x3f;
    h4 = bits & 0x3f;
    tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  } while (i < data.length);
  enc = tmp_arr.join('');
  switch( data.length % 3 ){
    case 1:
        enc = enc.slice(0, -2) + '==';
      break;
    case 2:
        enc = enc.slice(0, -1) + '=';
      break;
  }
  return enc;
}
// Twitter object
var twitter = {
  log : 1,
  oauth_token : {key : null, secret: null},
  _window : null,
  status: null,
  timer: null,
  callback: null,
  short_url_cnt: 0,
  short_url: {},
  long_url: '',
  title: '',
  type: '',
  init: function(){
    if(twitter.is_user_logged()){
      var start = $.cookie(ODESK_COOKIE_PREFIX + 'start_twitter');
      twitter.type = $.cookie(ODESK_COOKIE_PREFIX + 'twitter_data_type');
      twitter.title = $.cookie(ODESK_COOKIE_PREFIX + 'twitter_data_title');
      twitter.long_url = $.cookie(ODESK_COOKIE_PREFIX + 'twitter_data_url');
      if (null != start){
        $.cookie(ODESK_COOKIE_PREFIX + 'start_twitter', null, {path:'/', domain: ODESK_COOKIE_DOMAIN});
        $.cookie(ODESK_COOKIE_PREFIX + 'twitter_data_type', null, {path: '/', domain: ODESK_COOKIE_DOMAIN});
        $.cookie(ODESK_COOKIE_PREFIX + 'twitter_data_title', null, {path: '/', domain: ODESK_COOKIE_DOMAIN});
        $.cookie(ODESK_COOKIE_PREFIX + 'twitter_data_url', null, {path: '/', domain: ODESK_COOKIE_DOMAIN});
        twitter.run();
      }
    }
  },
  _show_window: function(){
    if (null == this._window) {
      winbox.open('Share on Twitter',"<div></div>", null, 'twitter_share', true);
      this._window = 'twitter_share';
    } 
  },
  _close_window: function(){
    if(null != this._window) {
      winbox.close(this._window);
      this._window = null;
    }
  },
  show_invite: function(){
    this._show_window();
    winbox.body_reload(twitter._window, proc_tpl('twitter_invite_window'));
  },
  show_progress: function(){
    this._show_window();
    winbox.body_reload(twitter._window,'<div class="process">&nbsp;</div>');
  },
  show_success: function(){
    winbox.body_reload(twitter._window, proc_tpl('twitter_success_window',{text: this.success}));
    twitter.timer = setTimeout('twitter.do_close()', 3000);
  },
  show_error: function(){
    winbox.body_reload(twitter._window, proc_tpl('twitter_error_window',{text: this.error}));
    twitter.timer = setTimeout('twitter.do_close()', 3000);
  },
  show_post: function(){
    this._show_window();
    if(typeof twitter.short_url[twitter.long_url] == 'undefined'){
      twitter.callback = twitter.show_post;
      twitter.get_short_url();
      return false;
    }
    winbox.body_reload(this._window,proc_tpl('twitter_post_window', {name: twitter.user_data.screen_name, img: twitter.user_data.profile_image_url}));
    twitter.init_post_text();
  },
  get_short_url: function(){
    $.getScript('http://api.bit.ly/shorten?version=2.0.1&longUrl=' + encodeURIComponent(twitter.long_url)+'&login=' + ODESK_BITLY_LOGIN + '&apiKey=' + ODESK_BITLY_API_KEY + '&callback=twitter.parse_short_url&history=1');
  },
  parse_short_url: function(data, textStatus){
    if(data.errorCode == 0){
      twitter.short_url[twitter.long_url] = data.results[twitter.long_url].shortUrl;
      if ('function' == typeof twitter.callback)
        twitter.callback();
      return false;
    }
  },
  init_post_text: function(){
    switch(twitter.type){
      case 'exam':
          $('#post_text').val(twitter.title + twitter.short_url[twitter.long_url] + " #odesk");
        break;
      case 'profile':
          $('#post_text').val("I'm ready to work on @oDesk " + twitter.short_url[twitter.long_url] + " #odesk");
        break;
      case 'job':
          $('#post_text').val('Hiring on @oDesk for "' + twitter.title + '" ' + twitter.short_url[twitter.long_url] + " #jobs #odesk");
        break;
      default:
          $('#post_text').val('Enter tweet');
    }
    $('#post_text').change(twitter.recalculate_message).keyup(twitter.recalculate_message);
    twitter.recalculate_message();
  },
  recalculate_message: function(){
    var letters = 140 - $('#post_text').val().length; 
    $('.post span.counter').html(letters);
  },
  do_connect: function(){
    twitter.show_progress();
    $.cookie(ODESK_COOKIE_PREFIX + 'start_twitter', 1, {path:'/', domain: ODESK_COOKIE_DOMAIN});
    $.cookie(ODESK_COOKIE_PREFIX + 'twitter_data_type', twitter.type, {path: '/', domain: ODESK_COOKIE_DOMAIN});
    $.cookie(ODESK_COOKIE_PREFIX + 'twitter_data_title', twitter.title, {path: '/', domain: ODESK_COOKIE_DOMAIN});
    $.cookie(ODESK_COOKIE_PREFIX + 'twitter_data_url', twitter.long_url, {path: '/', domain: ODESK_COOKIE_DOMAIN});
    window.location = ODESK_CONSOLE_ROOT + 'extending_odesk.php?do=twitter_connect&twitter_post_redirect=' + base64_encode(window.location.href);
  },
  do_post: function(){
    this.text = $('#post_text').val();
    this.show_progress();
    var data = { status: this.text, name:'post'};
    data['do'] = 'api';
    $('body').ajaxError(twitter.ajaxError);
    $.post(ODESK_CONSOLE_ROOT + 'extending_odesk.php', data, twitter.after_post, 'json');
  },
  ajaxError: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
    twitter.error = "We're sorry. <br /> There was an error sending your tweet. <br /> Please try again later.";
    twitter.show_error();
  },
  after_post: function(data, textStatus){
    if('undefined' != typeof data.text){
      twitter.success = 'Tweet sent!';
      twitter.show_success();
    } else{
      twitter.error = "We're sorry. <br /> There was an error sending your tweet. <br /> Please try again later.";
      twitter.show_error();
    }
  },
  do_close: function(){
    twitter._close_window();
    if (twitter.timer!=null){
      clearTimeout(twitter.timer);
    }
  },
  is_user_logged: function(){
    if (null != this.oauth_token.key && null != this.oauth_token.secret){
      return true;
    }else{
      this.oauth_token.key = $.cookie(ODESK_COOKIE_PREFIX + 'oauth_token');
      this.oauth_token.secret = $.cookie(ODESK_COOKIE_PREFIX + 'oauth_token_secret');
      if(null != this.oauth_token.key && null != this.oauth_token.secret){
        return true;
      }
      return false;
    }
  },
  get_user_data: function(){
    if (twitter.user_data == null){
      var data = {status: this.text, name:'user'};
      data['do'] = 'api';
      $.post(ODESK_CONSOLE_ROOT + 'extending_odesk.php', data, twitter.parse_user_data, 'json');
    } else{
      if ('function' == typeof twitter.callback)
        twitter.callback();
    }
  },
  parse_user_data: function(data, textStatus){
    twitter.user_data = data;
    if ('function' == typeof twitter.callback){
      twitter.callback();
    }
  },
  run: function(){
    if(this.is_user_logged()){
      twitter.show_progress();
      twitter.callback = twitter.show_post;
      this.get_user_data();
    }else{
      this.show_invite();
    }
  },
  share: function(type, title, url){
    if ('undefined' != typeof type) {
      twitter.type = type;
      switch (type) {
        case 'job':
          evt.log(JOB_DETAILS_TWITTER_EVT, JOB_DETAILS_TWITTER_SID);
          break;
        case 'profile':
          evt.log(PROFILE_DETAILS_TWITTER_EVT, PROFILE_DETAILS_TWITTER_SID);
          break;
        case 'test':
        case 'exam':
          var page_url = document.location.toString();
          var sid = (page_url.match('exam_history')) ? MY_EXAMS_TWITTER_SID : EXAM_TWITTER_SID;
          var _ev = (page_url.match('exam_history')) ? MY_EXAMS_TWITTER_EVT : EXAM_TWITTER_EVT;
          evt.log(_ev, sid);
          break;
      }
    }
    if ('undefined' != typeof title)
      twitter.title = title;
    if ('undefined' != typeof url)
      twitter.long_url = url;
    twitter.run();
  }
};
$(document).ready( function(){ twitter.init();} );

