var ml1_widgets_2012_base = 'http://widgets.mylife.truelife.com/';
//var ml1_widgets_2012_base = 'http://localhost:22234/';

try {
  var jq_ua = jQuery.browser;
  if ( jq_ua.msie && jq_ua.version.slice(0,1) == '7' ) {
    jQuery('head').append('<script type="text/javascript" src="' + ml1_widgets_2012_base + '/assets/js/json2.js"></script>');
  }
  //jQuery('head').append('<script type="text/javascript" src="' + ml1_widgets_2012_base + '/assets/js/xd_iframe_me.js"></script>');
  //jQuery('head').append('<script type="text/javascript" src="' + ml1_widgets_2012_base + '/assets/js/easyXDM.debug.js"></script>');
} catch (e) {}

(function($) {
  $.fn.ml1_widgets_sidebar = function(options) {
    options = $.extend({ }, $.fn.ml1_widgets_sidebar.defaults, options);
    var me = $(this);
    var guid = guid();
    var sso_id = 0;
    var access_token = 0;
    function guid() {
      return 'f' + (Math.random() * (1 << 30)).toString(16).replace('.', '');
    }
    function render() {
      var height = me.attr('data-height');
      if ( typeof height === 'undefined' || height === false ) {
        height = '1300';
      }
      var url = ml1_widgets_2012_base
                + "main/ml1_widgets_2012?"
                + 'guid=' + String(guid)
                + '&sso_id=' + String(sso_id)
                + '&access_token=' + String(access_token)
                + '&proxy_url=' + encodeURIComponent(String(jQuery.trim(me.attr('data-proxy-url'))))
                + '&oftheday_setting=' + encodeURIComponent(String(jQuery.trim(me.attr('data-oftheday-setting'))))
                + '&tab=' + String(me.attr('data-tab'))
                + '&tab_default=' + String(me.attr('data-tab-default'));
      if ( me.attr('data-provider') == 'iframe' ) {
        //me.empty().append('<iframe id="'+guid+'" src="'+url+'" width="225" height="' + height + '" frameborder="0" scrolling="no" style="border:none;border-bottom:2px solid #ccc;-webkit-border-radius:0 0 5px 5px;-moz-border-radius:0 0 5px 5px;border-radius:0 0 5px 5px;"></iframe>');
        me.empty().append('<iframe id="'+guid+'" src="'+url+'" width="225" height="' + height + '" frameborder="0" scrolling="no" style="border:none;-webkit-border-radius:0 0 5px 5px;-moz-border-radius:0 0 5px 5px;border-radius:0 0 5px 5px;"></iframe>');
      }
      else if ( me.attr('data-provider') == 'div' ) {
        url += "&jsoncallback=?";
        jQuery.getJSON(url, function (data) {
          me.empty().append('<div id="'+guid+'">'+htmlspecialchars_decode(jQuery.trim(data.html))+'</div>');
        });
      }
    }
    function render_with_sso() {
      //var url_check_sso = 'http://login.truelife.com/checkCentralizeCookies.php?jsoncallback=?';
      var url_check_sso = 'http://login.truelife.com/checkAuthorize.php?jsoncallback=?';
      jQuery.getJSON( url_check_sso, function (sso_data) {
        if (sso_data.jsonReturn.uid != undefined) {
          sso_id = String(sso_data.jsonReturn.uid);
          access_token = String(sso_data.jsonReturn.access_token);
        }
        render();
      });
      
      /*
      sso_id = get_cookie('c_user');
      access_token = get_cookie('access_token');
      sso_id = sso_id !== null ? sso_id : '0';
      access_token = access_token !== null ? access_token : '0';
      render();
      */
    }
    function valid_data() {
      me.empty();
      if ( typeof me.attr('data-proxy-url') == 'undefined' || me.attr('data-proxy-url') == '') {
        me.append('<p>Invalid "data-proxy-url"</p>');
        return false;
      }
      else {
        var contents = file_get_contents(urldecode(me.attr('data-proxy-url')));
        var pattern = /xd_proxy\.html/ig;
        if ( ! pattern.test(contents) ) {
          me.append('<p>Invalid "data-proxy-url"</p>');
          return false;
        }
      };
      /*
      if ( typeof me.attr('data-oftheday-setting') == 'undefined' || jQuery.trim(me.attr('data-oftheday-setting')) == '' )) {
        me.append('<p>Invalid "data-oftheday-setting"</p>');
        return false;
      };
      */
      if ( typeof me.attr('data-provider') == 'undefined' || ! ( jQuery.trim(me.attr('data-provider')) == 'iframe' || jQuery.trim(me.attr('data-provider')) == 'div' )) {
        me.append('<p>Invalid "data-provider"</p>');
        return false;
      };
      /*
      if ( typeof me.attr('data-tab-default') == 'undefined' || ! ( jQuery.trim(me.attr('data-tab-default')) == 'oftheday' || jQuery.trim(me.attr('data-tab-default')) == 'social' || jQuery.trim(me.attr('data-tab-default')) == 'stuff' || jQuery.trim(me.attr('data-tab-default')) == 'friend' || jQuery.trim(me.attr('data-tab-default')) == 'message' ) ) {
        me.append('<p>Invalid "data-tab-default"</p>');
        return false;
      };
      */
      var pattern_data_tab_default = /^oftheday|^social|^stuff|^friend|^message/ig;
      if ( typeof me.attr('data-tab-default') == 'undefined' || ! ( pattern_data_tab_default.test(jQuery.trim(me.attr('data-tab-default'))) || pattern_data_tab_default.test(jQuery.trim(me.attr('data-tab-default'))) || pattern_data_tab_default.test(jQuery.trim(me.attr('data-tab-default'))) || pattern_data_tab_default.test(jQuery.trim(me.attr('data-tab-default'))) || pattern_data_tab_default.test(jQuery.trim(me.attr('data-tab-default'))) ) ) {
        me.append('<p>Invalid "data-tab-default"</p>');
        return false;
      };
      return true;
    }
    function run() {
      if (valid_data()) { render_with_sso(); }
      else { return false; }
    }
    run();
  }
  $.fn.ml1_widgets_sidebar.defaults = {
  }
})(jQuery);

function set_cookie( name, value, exp_y, exp_m, exp_d, path, domain, secure ) {
  var cookie_string = name + "=" + escape ( value );
  if ( exp_y ) {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }
  if ( path ) {
    cookie_string += "; path=" + escape ( path );
  }
  if ( domain ) {
    cookie_string += "; domain=" + escape ( domain );
  }
  if ( secure ) {
    cookie_string += "; secure";
  }
  document.cookie = cookie_string;
}
function get_cookie( cookie_name ) {
  var results = document.cookie.match( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
  if ( results ) {
    return unescape( results[2] );
  }
  else {
    return null;
  }
}
function delete_cookie ( cookie_name ) {
  var cookie_date = new Date();
  cookie_date.setTime( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}
/*
 * MyLife Widget Function
 */
if(typeof String.prototype.format != 'function'){
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}
var ref_type = null,ref_id = null,uid = null,iframe_id = null; 
function _show_detail(t,c,u,fid,id){
  /**
   * t = type
   * c = content id
   * u = url
   * fid = iframe id
   * uid= user id
   */
  ref_type = t;
  ref_id = c;
  uid = id;
  iframe_id = fid;
  $.detail({
    url:"{0}content/jsonp/index/{1}/{2}?callback=?".format(u,t,c),
    content_id : c,
    iframe_id : fid
  });
}

function mylife_set_iframe_height(iframe_dom_id, height) {
  var iframe = document.getElementById(iframe_dom_id);
  iframe.style.height = height + 'px';
}

function mylife_window_location(url) {
  //console.log(url);
  window.location = url;
}

function mylife_open_modal_window(url) {
  
}

/*
 * General Utilities
 */

function guid() {
  return 'f' + (Math.random() * (1 << 30)).toString(16).replace('.', '');
}

function nl2br (str, is_xhtml) {
  var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
  return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

function addslashes (str) {
  return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

function urlencode (str) {
  str = (str + '').toString();
  return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
  replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

function urldecode (str) {
  return decodeURIComponent((str + '').replace(/\+/g, '%20'));
}

function str_replace (search, replace, subject, count) {
  var i = 0,
    j = 0,
    temp = '',
    repl = '',
    sl = 0,
    fl = 0,
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = r instanceof Array,
    sa = s instanceof Array;
  s = [].concat(s);
  if (count) {
    this.window[count] = 0;
  }
  for (i = 0, sl = s.length; i < sl; i++) {
    if (s[i] === '') {
      continue;
    }
    for (j = 0, fl = f.length; j < fl; j++) {
      temp = s[i] + '';
      repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
      s[i] = (temp).split(f[j]).join(repl);
      if (count && s[i] !== temp) {
        this.window[count] += (temp.length - s[i].length) / f[j].length;
      }
    }
  }
  return sa ? s : s[0];
}

function htmlspecialchars (string, quote_style, charset, double_encode) {
  var optTemp = 0,
    i = 0,
    noquotes = false;
  if (typeof quote_style === 'undefined' || quote_style === null) {
    quote_style = 2;
  }
  string = string.toString();
  if (double_encode !== false) {
    string = string.replace(/&/g, '&amp;');
  }
  string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  var OPTS = {
    'ENT_NOQUOTES': 0,
    'ENT_HTML_QUOTE_SINGLE': 1,
    'ENT_HTML_QUOTE_DOUBLE': 2,
    'ENT_COMPAT': 2,
    'ENT_QUOTES': 3,
    'ENT_IGNORE': 4
  };
  if (quote_style === 0) {
    noquotes = true;
  }
  if (typeof quote_style !== 'number') {
    quote_style = [].concat(quote_style);
    for (i = 0; i < quote_style.length; i++) {
      if (OPTS[quote_style[i]] === 0) {
        noquotes = true;
      } else if (OPTS[quote_style[i]]) {
        optTemp = optTemp | OPTS[quote_style[i]];
      }
    }
    quote_style = optTemp;
  }
  if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
    string = string.replace(/'/g, '&#039;');
  }
  if (!noquotes) {
    string = string.replace(/"/g, '&quot;');
  }
  return string;
}

function htmlspecialchars_decode (string, quote_style) {
  var optTemp = 0,
    i = 0,
    noquotes = false;
  if (typeof quote_style === 'undefined') {
    quote_style = 2;
  }
  string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
  var OPTS = {
    'ENT_NOQUOTES': 0,
    'ENT_HTML_QUOTE_SINGLE': 1,
    'ENT_HTML_QUOTE_DOUBLE': 2,
    'ENT_COMPAT': 2,
    'ENT_QUOTES': 3,
    'ENT_IGNORE': 4
  };
  if (quote_style === 0) {
    noquotes = true;
  }
  if (typeof quote_style !== 'number') {
    quote_style = [].concat(quote_style);
    for (i = 0; i < quote_style.length; i++) {
      if (OPTS[quote_style[i]] === 0) {
        noquotes = true;
      } else if (OPTS[quote_style[i]]) {
        optTemp = optTemp | OPTS[quote_style[i]];
      }
    }
    quote_style = optTemp;
  }
  if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
    string = string.replace(/&#0*39;/g, "'");
  }
  if (!noquotes) {
    string = string.replace(/&quot;/g, '"');
  }
  string = string.replace(/&amp;/g, '&');
  return string;
}

function file_get_contents (url, flags, context, offset, maxLen) {
  var tmp, headers = [],
    newTmp = [],
    k = 0,
    i = 0,
    href = '',
    pathPos = -1,
    flagNames = 0,
    content = null,
    http_stream = false;
  var func = function (value) {
    return value.substring(1) !== '';
  };
  this.php_js = this.php_js || {};
  this.php_js.ini = this.php_js.ini || {};
  var ini = this.php_js.ini;
  context = context || this.php_js.default_streams_context || null;
  if (!flags) {
    flags = 0;
  }
  var OPTS = {
    FILE_USE_INCLUDE_PATH: 1,
    FILE_TEXT: 32,
    FILE_BINARY: 64
  };
  if (typeof flags === 'number') {
    flagNames = flags;
  } else {
    flags = [].concat(flags);
    for (i = 0; i < flags.length; i++) {
      if (OPTS[flags[i]]) {
        flagNames = flagNames | OPTS[flags[i]];
      }
    }
  }
  if (flagNames & OPTS.FILE_BINARY && (flagNames & OPTS.FILE_TEXT)) {
    throw 'You cannot pass both FILE_BINARY and FILE_TEXT to file_get_contents()';
  }
  if ((flagNames & OPTS.FILE_USE_INCLUDE_PATH) && ini.include_path && ini.include_path.local_value) {
    var slash = ini.include_path.local_value.indexOf('/') !== -1 ? '/' : '\\';
    url = ini.include_path.local_value + slash + url;
  } else if (!/^(https?|file):/.test(url)) {
    href = this.window.location.href;
    pathPos = url.indexOf('/') === 0 ? href.indexOf('/', 8) - 1 : href.lastIndexOf('/');
    url = href.slice(0, pathPos + 1) + url;
  }
  if (context) {
    var http_options = context.stream_options && context.stream_options.http;
    http_stream = !! http_options;
  }
  if (!context || http_stream) {
    var req = this.window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
    if (!req) {
      throw new Error('XMLHttpRequest not supported');
    }
    var method = http_stream ? http_options.method : 'GET';
    var async = !! (context && context.stream_params && context.stream_params['phpjs.async']);
    if (ini['phpjs.ajaxBypassCache'] && ini['phpjs.ajaxBypassCache'].local_value) {
      url += (url.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
    }
    req.open(method, url, async);
    if (async) {
      var notification = context.stream_params.notification;
      if (typeof notification === 'function') {
        if (0 && req.addEventListener) {
        } else {
          req.onreadystatechange = function (aEvt) {
            var objContext = {
              responseText: req.responseText,
              responseXML: req.responseXML,
              status: req.status,
              statusText: req.statusText,
              readyState: req.readyState,
              evt: aEvt
            };
            var bytes_transferred;
            switch (req.readyState) {
            case 0:
              notification.call(objContext, 0, 0, '', 0, 0, 0);
              break;
            case 1:
              notification.call(objContext, 0, 0, '', 0, 0, 0);
              break;
            case 2:
              notification.call(objContext, 0, 0, '', 0, 0, 0);
              break;
            case 3:
              bytes_transferred = req.responseText.length * 2;
              notification.call(objContext, 7, 0, '', 0, bytes_transferred, 0);
              break;
            case 4:
              if (req.status >= 200 && req.status < 400) {
                bytes_transferred = req.responseText.length * 2;
                notification.call(objContext, 8, 0, '', req.status, bytes_transferred, 0);
              } else if (req.status === 403) {
                notification.call(objContext, 10, 2, '', req.status, 0, 0);
              } else {
                notification.call(objContext, 9, 2, '', req.status, 0, 0);
              }
              break;
            default:
              throw 'Unrecognized ready state for file_get_contents()';
            }
          }
        }
      }
    }
    if (http_stream) {
      var sendHeaders = http_options.header && http_options.header.split(/\r?\n/);
      var userAgentSent = false;
      for (i = 0; i < sendHeaders.length; i++) {
        var sendHeader = sendHeaders[i];
        var breakPos = sendHeader.search(/:\s*/);
        var sendHeaderName = sendHeader.substring(0, breakPos);
        req.setRequestHeader(sendHeaderName, sendHeader.substring(breakPos + 1));
        if (sendHeaderName === 'User-Agent') {
          userAgentSent = true;
        }
      }
      if (!userAgentSent) {
        var user_agent = http_options.user_agent || (ini.user_agent && ini.user_agent.local_value);
        if (user_agent) {
          req.setRequestHeader('User-Agent', user_agent);
        }
      }
      content = http_options.content || null;
    }
    if (flagNames & OPTS.FILE_TEXT) {
      var content_type = 'text/html';
      if (http_options && http_options['phpjs.override']) {
        content_type = http_options['phpjs.override'];
      } else {
        var encoding = (ini['unicode.stream_encoding'] && ini['unicode.stream_encoding'].local_value) || 'UTF-8';
        if (http_options && http_options.header && (/^content-type:/im).test(http_options.header)) {
          content_type = http_options.header.match(/^content-type:\s*(.*)$/im)[1];
        }
        if (!(/;\s*charset=/).test(content_type)) { // If no encoding
          content_type += '; charset=' + encoding;
        }
      }
      req.overrideMimeType(content_type);
    }
    else if (flagNames & OPTS.FILE_BINARY) {
      req.overrideMimeType('text/plain; charset=x-user-defined');
    }
    if (http_options && http_options['phpjs.sendAsBinary']) {
      req.sendAsBinary(content);
    } else {
      req.send(content);
    }
    tmp = req.getAllResponseHeaders();
    if (tmp) {
      tmp = tmp.split('\n');
      for (k = 0; k < tmp.length; k++) {
        if (func(tmp[k])) {
          newTmp.push(tmp[k]);
        }
      }
      tmp = newTmp;
      for (i = 0; i < tmp.length; i++) {
        headers[i] = tmp[i];
      }
      this.$http_response_header = headers;
    }
    if (offset || maxLen) {
      if (maxLen) {
        return req.responseText.substr(offset || 0, maxLen);
      }
      return req.responseText.substr(offset);
    }
    return req.responseText;
  }
  return false;
}

/*
 * Auto Generate Widget From Class
 */

jQuery(document).ready(function() {
  try {
    jQuery('head').append('<link href="'+ml1_widgets_2012_base+'/assets/css/ml1_widgets_style_2012.css" type="text/css" rel="stylesheet" />');
    jQuery('head').append('<script type="text/javascript" src="' + ml1_widgets_2012_base + '/assets/js/detail_slide.js"></script>');
    jQuery('div.ml1-widgets-sidebar').each(function(index) {
      jQuery(this).ml1_widgets_sidebar();
    });
    
  } catch (e) {}
});

