var gadgets = gadgets || {};
gadgets.JSON = function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'

 },
        s = {
            'boolean': function (x) {
                return String(x);
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x =  _proxy_jslib_handle(x, 'replace', '', 1, 0)(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c =  _proxy_jslib_handle(m, (b), 0, 0);
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                             _proxy_jslib_handle(Math.floor(c / 16), 'toString', '', 1, 0)(16) +
                             _proxy_jslib_handle((c % 16), 'toString', '', 1, 0)(16);
                    });
                }
                return '"' + x + '"';
            },
            object: function (x) {
                if (x) {
                    var a = [], b, f, i, l, v;
                    if (x instanceof Array) {
                        a[0] = '[';
                        l = x.length;
                        for (i = 0; i < l; i += 1) {
                            v =  _proxy_jslib_handle(x, (i), 0, 0);
                            f =  _proxy_jslib_handle(s, (typeof v), 0, 0);
                            if (f) {
                                v = f(v);
                                if (typeof v == 'string') {
                                    if (b) {
                                         _proxy_jslib_assign('', a, (a.length), '=', ( ','));
                                    }
                                     _proxy_jslib_assign('', a, (a.length), '=', ( v));
                                    b = true;
                                }
                            }
                        }
                         _proxy_jslib_assign('', a, (a.length), '=', ( ']'));
                    } else if (typeof x.hasOwnProperty === 'function') {
                        a[0] = '{';
                        for (i in x) {
                            if (x.hasOwnProperty(i)) {
                                v =  _proxy_jslib_handle(x, (i), 0, 0);
                                f =  _proxy_jslib_handle(s, (typeof v), 0, 0);
                                if (f) {
                                    v = f(v);
                                    if (typeof v == 'string') {
                                        if (b) {
                                             _proxy_jslib_assign('', a, (a.length), '=', ( ','));
                                        }
                                        a.push(s.string(i), ':', v);
                                        b = true;
                                    }
                                }
                            }
                        }
                         _proxy_jslib_assign('', a, (a.length), '=', ( '}'));
                    } else {
                        return;
                    }
                    return a.join('');
                }
                return 'null';
            }
        };
    return {
        copyright: '(c)2005 JSON.org',
        license: 'http://www.JSON.org/license.html',
/*
    Stringify a JavaScript value, producing a JSON text.
*/
        stringify: function (v) {
            var f =  _proxy_jslib_handle(s, (typeof v), 0, 0);
            if (f) {
                v = f(v);
                if (typeof v == 'string') {
                    return v;
                }
            }
            return null;
        },
/*
    Parse a JSON text, producing a JavaScript value.
    It returns false if there is a syntax error.
*/
        parse: function (text) {
            try {
                return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                         _proxy_jslib_handle(text, 'replace', '', 1, 0)(/"(\\.|[^"\\])*"/g, ''))) &&
                    eval(_proxy_jslib_proxify_js(('(' + text + ')'), 0, 0) );
            } catch (e) {
                return false;
            }
        }
    };
}();

//IFPC
var gadgets = gadgets || {};

/**
 * IFrame pool
 */
gadgets.IFramePool_ = function() {
  this.pool_ = [];
};

/**
 * Returns a newly created IFRAME with the locked state as specified
 * @param {Boolean} locked whether the created IFRAME is locked by default
 * @returns {HTMLElement} the created IFRAME element
 * @private
 */
gadgets.IFramePool_.prototype.createIFrame_ = function(locked) {
  var div = document.createElement("DIV");

  // MSIE will reliably trigger an IFRAME onload event if the onload is defined
  // inlined but not if it is defined via JS with element.onload = func;
  // We create it within a DIV but eventually is moved directly into doc.body.
   _proxy_jslib_assign('', div, 'innerHTML', '=', ( "<iframe onload='this.pool_locked=false'></iframe>"));

  var iframe =  _proxy_jslib_handle(div, 'getElementsByTagName', '', 1, 0)("IFRAME")[0];
  iframe.style.visibility = 'hidden';
  iframe.style.width = iframe.style.height = '0px';
  iframe.style.border = '0px';
  iframe.style.position = 'absolute';

  iframe.pool_locked = locked;
   _proxy_jslib_assign('', this.pool_, (this.pool_.length), '=', ( iframe));

  // The div was only used to create the iframe. Now we disown and remove it.
  div.removeChild(iframe);
  div = null;
  return iframe;
};

/**
 * Retrieves an available IFrame and sets the URL to 'url'
 * @param {String} url The URL the IFrame is pointed to
 */
gadgets.IFramePool_.prototype.iframe = function(url) {
    
  // Reject weird urls
  if (!url.match(/^http[s]?:\/\//)) {
    return;
  }
  
  // We wrap this code in a setTimeout call to avoid tying the UI up too much
  // with a series of repeated IFRAME creation calls.

  var ifp = this;
   _proxy_jslib_handle(window, 'setTimeout', '', 1, 0)(function() {
    var iframe = null;

    // For MSIE, delete any iframes that are no longer being used. MSIE cannnot
    // re-use the IFRAME because it will 'click' when we set the SRC.
    // Other browsers scan the pool for a free iframe to re-use.
    for (var i = ifp.pool_.length - 1; i >= 0; i--) {
      var ifr =  _proxy_jslib_handle(ifp.pool_, (i), 0, 0);
      if (ifr && !ifr.pool_locked) {
        ifr.parentNode.removeChild(ifr);
        if (window.ActiveXObject) {  // MSIE
          ifr = null;
           _proxy_jslib_assign('', ifp.pool_, (i), '=', ( null));
          ifp.pool_.splice(i,1);  // Remove it from the array
        } else {
          ifr.pool_locked = true;
          iframe = ifr;
          break;
        }
      }
    }

    // If no iframe was found to re-use we create a new one
    iframe = iframe ? iframe : ifp.createIFrame_(true);
     _proxy_jslib_assign('', iframe, 'src', '=', ( url));
    // We append to the body after setting the src otherwise MSIE will 'click'
     _proxy_jslib_handle(document, 'body', '', 0, 0).appendChild(iframe);
  }, 0);
  
};

/**
 * Clears the pool and re-initializes it to empty
 */
gadgets.IFramePool_.prototype.clear = function() {
  for (var i = 0; i < this.pool_.length; i++) {
     _proxy_jslib_handle(this.pool_, (i), 0, 0).onload = null;
     _proxy_jslib_assign('', this.pool_, (i), '=', ( null));
  }
  this.pool_.length = 0;
  this.pool_ = new (Array)();
};

/**
 * Inter-frame procedure call
 */
gadgets.IFPC_ = function() {

var CALLBACK_ID_PREFIX_ = "cbid";
var CALLBACK_SERVICE_NAME_ = "ifpc_callback";
var iframe_pool_ = new (gadgets.IFramePool_)();
var packet_store_ = {};
var services_ = {};
var callbacks_ = {};
var callback_counter_ = 0;
var call_counter_ = 0;

/**
 * Registers a new service and associates it with 'handler'
 * @param {String} name the id to used to identify this service when calling
 * @param {Function} handler function to handle incoming requests
 */
function registerService(name, handler) {
   _proxy_jslib_assign('', services_, (name), '=', ( handler));
}

/**
 * Unregisters a registered service
 * @param {String} name the id used to identify the service when calling
 */
function unregisterService(name) {
   _proxy_jslib_assign('delete', (services_), (name), '');
}

/**
 * dispatches the call
 * @param {String} iframe_id iframe ID to use for this request
 * @param {String} service_name service name
 * @param {Array} args_list array of arguments expected by this service
 * @param {String} remote_relay_url remote relay URL of the relay HTML page
 * @param {Function} callback callback function if a response is expected
 *        (can be null if no callback expected)
 * @param {String} local_relay_url local relay URL of the relay HTML page
 *        (can be null if callback is also null)
 */
function call(iframe_id,
              service_name,
              args_list,
              remote_relay_url,
              callback,
              local_relay_url,
              opt_shouldThrowError) {
  // We prepend some other arguments that the processRequest
  // method is expecting and will shift off in reverse order
  // once all the packets have been received
  // First make a local copy of args_list
  
  args_list = args_list.slice(0);
  args_list.unshift(registerCallback_(callback));
  args_list.unshift(local_relay_url);
  args_list.unshift(service_name);
  args_list.unshift(iframe_id);

  // Figure out how much URL space is available for actual data.
  // MSIE puts a limit of 4095 total chars including the # data.
  // Other browsers have limits at least as large as 4095.
  var max_data_len = 4095 - remote_relay_url.length;
  // Because we encodeArgs twice we need to leave room for escape chars
  max_data_len = parseInt(max_data_len / 3, 10);

  if (typeof opt_shouldThrowError == "undefined") {
    opt_shouldThrowError = true;
  }

  // Format of each packet is:
  // #iframe_id&callId&num_packets&packet_num&block_of_data
  var data = encodeArgs_(args_list);
  var num_packets = parseInt(data.length / max_data_len, 10);
  if (data.length % max_data_len > 0) {
    num_packets += 1;
  }
  
  for (var i = 0; i < num_packets; i++) {
    var data_slice = data.substr(i*max_data_len, max_data_len);
    var packet = [iframe_id, call_counter_, num_packets, i,
                  data_slice, opt_shouldThrowError];
    iframe_pool_.iframe(
      remote_relay_url + "#" + encodeArgs_(packet));
  }
  call_counter_++;
  
}

/**
 * Clears internal state.
 * Should be called from an unload handler to avoid memory leaks.
 */
function clear() {
  services_ = {};
  callbacks_ = {};
  iframe_pool_.clear();
}

/**
 * Relays a request either from container to gadget, from gadget to container,
 * or from gadget to gadget.
 * @param {String} argsString encoded parameters
 */
function relayRequest(argsString) {
    
  // Extract the iframe-id.
  var iframeId = decodeArgs_(argsString)[0];
  
  // Need to find the destination window to pass the request on to.
  // We are in an IFPC relay iframe within the source window.
  var win = null;
  // If container-to-gadget communication, the window corresponding to
  // 'iframeId' will be our sibling, ie. a child of the container page,
  // and this child is the window we need.
  try {
    win =  _proxy_jslib_handle( _proxy_jslib_handle( _proxy_jslib_handle(window, 'parent', '', 0, 0), 'frames', '', 0, 0), (iframeId), 0, 0);
  } catch (e) {
    // Doesn't look like container-to-gadget communication.
    // Just leave 'win' unset.
  }
  // If gadget-to-gadget communication, the window corresponding to
  // 'iframeId' will be a sibling of our outer page, and this is the
  // window we need.
  try {
    if (!win &&  _proxy_jslib_handle( _proxy_jslib_handle( _proxy_jslib_handle( _proxy_jslib_handle(window, 'parent', '', 0, 0), 'parent', '', 0, 0), 'frames', '', 0, 0), (iframeId), 0, 0) !=  _proxy_jslib_handle(window, 'parent', '', 0, 0)) {
      win =  _proxy_jslib_handle( _proxy_jslib_handle( _proxy_jslib_handle( _proxy_jslib_handle(window, 'parent', '', 0, 0), 'parent', '', 0, 0), 'frames', '', 0, 0), (iframeId), 0, 0);
    }
  } catch (e) {
    // Doesn't look like gadget-to-gadget communication.
    // Just leave 'win' unset.
  }
  if (!win) {
    // Wasn't container-to-gadget nor gadget-to-gadget communication.
    // If gadget-to-container communication, 'iframeId' will be our grandparent.
    win =  _proxy_jslib_handle( _proxy_jslib_handle(window, 'parent', '', 0, 0), 'parent', '', 0, 0);
  }
  // Now that 'win' is set appropriately, pass on the request.
  // Obscure Firefox bug sometimes causes an exception when xmlhttp is
  // utilized in an IFPC handler. Wrapping our handleRequest calls
  // with a setTimeout in the target window's scope prevents this
  // exception.
  // See this Mozilla bug for more info:
  // https://bugzilla.mozilla.org/show_bug.cgi?id=249843
  // Also see this blogged account of the bug:
  // http://the-stickman.com/web-development/javascript/iframes-xmlhttprequest-bug-in-firefox
  var fn = function() {
             win.gadgets.IFPC_.handleRequest(argsString);
           };

  if (window.ActiveXObject) { // MSIE
    // call the relay synchronously in IE
    // this is required because the iframe (and its relay closure)
    // may otherwise be deleted/invalidated before this call is made
    fn();
  } else {
    // all other browsers call with timeout, particularly FF. See
    // above comment regarding FF bug for why it's done this way
    
    //win.setTimeout(fn, 0);
    //BUGBUG: workaround the workaround since execution doesn't return to the timeout function
    //once the callstack "crosses back" to the x.myspace.com subdomain
    fn();
  }
}

/**
 * Internal function that processes the request
 * @param {String} packet encoded parameters
 */
function handleRequest(packet) {

  var packet = decodeArgs_(packet);

  var iframeId = packet.shift();
  var callId = packet.shift();
  var numPackets = packet.shift();
  var packetNum = packet.shift();
  var data = packet.shift();
  var shouldThrowError = packet.shift();
  // If you see fit to add a parameter here, don't.
  // If you must, be sure to add it to the END of the list!
  // If you don't, lots of problems will occur in situations where
  // IFPC versions mismatch, because ordered arguments will no longer
  // match up, causing all manner of breakages and odd behavior.

  // We store incoming packets in the packet_store object.
  // The key is the iframeId + the unique callId.
  // The value is an array to hold all the packets for the request.
  // The elements in the array are a 2-element array: packetNum and data.
  // When all packets are received, we sort based on the packetNum and then
  // re-create the original data block before passing to the Service Handler.
  var key = iframeId + "_" + callId;
  if (! _proxy_jslib_handle(packet_store_, (key), 0, 0))  _proxy_jslib_assign('', packet_store_, (key), '=', ( []));
   _proxy_jslib_handle(packet_store_, (key), 0, 0).push([packetNum, data]);

  if ( _proxy_jslib_handle(packet_store_, (key), 0, 0).length == numPackets) {
    // All packets have been received
     _proxy_jslib_handle(packet_store_, (key), 0, 0).sort(function(a,b) {
      return parseInt(a[0], 10) - parseInt(b[0], 10);
    });

    data = "";
    for (var i = 0; i < numPackets; i++) {
      data +=  _proxy_jslib_handle( _proxy_jslib_handle(packet_store_, (key), 0, 0), (i), 0, 0)[1];
    }
    // Clear this entry from the packet_store
     _proxy_jslib_assign('', packet_store_, (key), '=', ( null));

    var args = decodeArgs_(data);

    var iframeId = args.shift();
    var serviceName = args.shift();
    var remote_relay_url = args.shift();
    var callbackId = args.shift();

    var handler = getServiceHandler_(serviceName);
     
    var opt_callback = null;
    if(isCallbackIdWellFormed_(callbackId)) {
        opt_callback = function() { 
            var argsArray = new (Array)();
            if(arguments != null && arguments.length > 0){
				for(var n=0; n < arguments.length; n++){
					argsArray.push( _proxy_jslib_handle(arguments, (n), 0, 0));
				}
            }
            handleCallback_(callbackId, iframeId, remote_relay_url, argsArray);
        }
        args.push(opt_callback);
    }
    
    if (handler) {
      var args_list_result = handler.apply(null, args);
      handleCallback_(callbackId, iframeId, remote_relay_url, args_list_result);      
    } else if (shouldThrowError) {
      throw new (Error)("Service " + serviceName + " not registered.");
    }
  }
}

/**
 * Handles a callback
 */
function handleCallback_(callbackId, iframeId, remote_relay_url, args_list_result) {
    if (args_list_result instanceof Array && isCallbackIdWellFormed_(callbackId)) {
        args_list_result.unshift(callbackId);
        call(iframeId,
                   CALLBACK_SERVICE_NAME_,
                   args_list_result,
                   remote_relay_url,
                   null,   // no callback from the callback
                   "");    // no callback, no relay needed
     }
}

/**
 * Returns the service handler given a specific service name
 * @param {String} name service name
 * @returns {Function} service
 * @private
 */
function getServiceHandler_(name) {
  if(services_.hasOwnProperty(name)) {
    return  _proxy_jslib_handle(services_, (name), 0, 0);
  } else {
    return null;
  }
}

/**
 * Registers a new callback
 * @param {Function} callback callback function
 * @returns {String} a callback ID to use with call()
 * @private
 */
function registerCallback_(callback) {
  var callbackId = "";
  if (callback && typeof callback == "function") {
    callbackId = getNewCallbackId_();
     _proxy_jslib_assign('', callbacks_, (callbackId), '=', ( callback));
  }
  return callbackId;
}

/**
 * Unregisters an existing callback
 * @param {String} callback_id callback ID
 */
function unregisterCallback_(callback_id) {
  if (callbacks_.hasOwnProperty(callback_id)) {
     _proxy_jslib_assign('', callbacks_, (callback_id), '=', ( null));
  }
}

/**
 * Returns the callback given a specific callback id
 * @param {String} callback_id callback ID
 * @returns {Function|null} callback function
 * @private
 */
function getCallback_(callback_id) {
  if (callback_id &&
      callbacks_.hasOwnProperty(callback_id)) {
    return  _proxy_jslib_handle(callbacks_, (callback_id), 0, 0);
  }
  return null;
}

/**
 * Gets a new callback ID
 * @returns {String} a callback ID string
 * @private
 */
function getNewCallbackId_() {
  return CALLBACK_ID_PREFIX_ + (callback_counter_++);
}

/**
 * Return the decoded arguments a a list. First element is the service name.
 * @param {String} argsString Encoded argument string
 * @returns {Array} decoded argument list
 * @private
 */
function decodeArgs_(argsString) {
  var args = argsString.split('&');
  for(var i = 0; i < args.length; i++) {
    var arg = decodeURIComponent( _proxy_jslib_handle(args, (i), 0, 0));
    try {
      arg = gadgets.JSON.parse(arg);
    } catch (e) {
      // unexpected, but ok - treat as a string
    }
     _proxy_jslib_assign('', args, (i), '=', ( arg));
  }
  return args;
}

/**
 * Determines whether a callbackId is well-formed.
 * @param {String} callbackId callback ID
 * @returns {Boolean} whether the callbackId is well-formed
 * @private
 */
function isCallbackIdWellFormed_(callbackId) {
  return (callbackId+"").indexOf(CALLBACK_ID_PREFIX_) == 0;
}

/**
 * Private handler for the built-in callback service
 * @param {String} callbackId callback ID
 * @private
 */
function callbackServiceHandler_(callbackId) {
  var callback = getCallback_(callbackId);
  if (callback) {
    var args = [];
    for (var i = 1; i < arguments.length; i++) {
       _proxy_jslib_assign('', args, (args.length), '=', (  _proxy_jslib_handle(arguments, (i), 0, 0)));  // append the extra arguments
    }
    callback.apply(null, args);

    // Once the callback is triggered, we remove it.
    unregisterCallback_(callbackId);
  } else {
    throw new (Error)("Invalid callbackId");
  }
}

/**
 * Return the encoded argument string.
 * @param {Array} args list of arguments to encode
 * @returns {String} encoded argument string
 * @private
 */
function encodeArgs_(args) {
  var argsEscaped = [];
  for(var i = 0; i < args.length; i++) {
    var arg = gadgets.JSON.stringify( _proxy_jslib_handle(args, (i), 0, 0));
    argsEscaped.push(encodeURIComponent(arg));
  }
  return argsEscaped.join('&');
}

// Register the built-in callback handler
registerService(CALLBACK_SERVICE_NAME_, callbackServiceHandler_);

// Public methods
return {
  registerService: registerService,
  unregisterService: unregisterService,
  call: call,
  clear: clear,
  relayRequest: relayRequest,
  processRequest: relayRequest,
  handleRequest: handleRequest

};

}();

// Alias for legacy code
var _IFPC = gadgets.IFPC_;

//AppsCore
Type.registerNamespace('MySpace.Web.Services.Apps');
MySpace.Web.Services.Apps.Apps = function() {
    MySpace.Web.Services.Apps.Apps.initializeBase(this);
    this._timeout = 0;
    this._userContext = null;
    this._succeeded = null;
    this._failed = null;
}
MySpace.Web.Services.Apps.Apps.prototype = {
    MoveAppUp: function(token, surfaceId, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'MoveAppUp', false, { token: token, surfaceId: surfaceId }, succeededCallback, failedCallback, userContext);
    },
    MoveAppDown: function(token, surfaceId, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'MoveAppDown', false, { token: token, surfaceId: surfaceId }, succeededCallback, failedCallback, userContext);
    },
    UninstallApplication: function(token, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'UninstallApplication', false, { token: token }, succeededCallback, failedCallback, userContext);
    },
    UninstallApplicationEx: function(token, callbackParams, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'UninstallApplicationEx', false, { token: token, callbackParams: callbackParams }, succeededCallback, failedCallback, userContext);
    },
    RevokeApplicationToken: function(applID, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'RevokeApplicationToken', false, { applID: applID }, succeededCallback, failedCallback, userContext);
    },
    GetAddAppFooterText: function(appid, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'GetAddAppFooterText', false, { appid: appid }, succeededCallback, failedCallback, userContext);
    },
    InstallApplication: function(token, permissions, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'InstallApplication', false, { token: token, permissions: permissions }, succeededCallback, failedCallback, userContext);
    },
    InstallApplicationEx: function(token, permissions, callbackParams, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'InstallApplicationEx', false, { token: token, permissions: permissions, callbackParams: callbackParams }, succeededCallback, failedCallback, userContext);
    },
    UpdateApplicationSettings: function(appid, setpermissions, unsetpermissions, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'UpdateApplicationSettings', false, { appid: appid, setpermissions: setpermissions, unsetpermissions: unsetpermissions }, succeededCallback, failedCallback, userContext);
    },
    GetApplicationPermissionsString: function(appid, unsetpermissions, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'GetApplicationPermissionsString', false, { appid: appid, unsetpermissions: unsetpermissions }, succeededCallback, failedCallback, userContext);
    },
    BlockApplication: function(token, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'BlockApplication', false, { token: token }, succeededCallback, failedCallback, userContext);
    },
    UnblockApplication: function(token, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'UnblockApplication', false, { token: token }, succeededCallback, failedCallback, userContext);
    },
    SetUserPreferences: function(appId, userPreferenceKeys, userPreferenceValues, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'SetUserPreferences', false, { appId: appId, userPreferenceKeys: userPreferenceKeys, userPreferenceValues: userPreferenceValues }, succeededCallback, failedCallback, userContext);
    },
    IsAppInstallable: function(appId, viewerId, succeededCallback, failedCallback, userContext) {
        return this._invoke(MySpace.Web.Services.Apps.Apps.get_path(), 'IsAppInstallable', false, { appId: appId, viewerId: viewerId }, succeededCallback, failedCallback, userContext);
    } 
}
MySpace.Web.Services.Apps.Apps.registerClass('MySpace.Web.Services.Apps.Apps', Sys.Net.WebServiceProxy);
MySpace.Web.Services.Apps.Apps._staticInstance = new (MySpace.Web.Services.Apps.Apps)();
MySpace.Web.Services.Apps.Apps.set_path = function(value) { MySpace.Web.Services.Apps.Apps._staticInstance._path =  _proxy_jslib_handle(null, 'value', value, 0, 0); }
MySpace.Web.Services.Apps.Apps.get_path = function() { return MySpace.Web.Services.Apps.Apps._staticInstance._path; }
MySpace.Web.Services.Apps.Apps.set_timeout = function(value) { MySpace.Web.Services.Apps.Apps._staticInstance._timeout =  _proxy_jslib_handle(null, 'value', value, 0, 0); }
MySpace.Web.Services.Apps.Apps.get_timeout = function() { return MySpace.Web.Services.Apps.Apps._staticInstance._timeout; }
MySpace.Web.Services.Apps.Apps.set_defaultUserContext = function(value) { MySpace.Web.Services.Apps.Apps._staticInstance._userContext =  _proxy_jslib_handle(null, 'value', value, 0, 0); }
MySpace.Web.Services.Apps.Apps.get_defaultUserContext = function() { return MySpace.Web.Services.Apps.Apps._staticInstance._userContext; }
MySpace.Web.Services.Apps.Apps.set_defaultSucceededCallback = function(value) { MySpace.Web.Services.Apps.Apps._staticInstance._succeeded =  _proxy_jslib_handle(null, 'value', value, 0, 0); }
MySpace.Web.Services.Apps.Apps.get_defaultSucceededCallback = function() { return MySpace.Web.Services.Apps.Apps._staticInstance._succeeded; }
MySpace.Web.Services.Apps.Apps.set_defaultFailedCallback = function(value) { MySpace.Web.Services.Apps.Apps._staticInstance._failed =  _proxy_jslib_handle(null, 'value', value, 0, 0); }
MySpace.Web.Services.Apps.Apps.get_defaultFailedCallback = function() { return MySpace.Web.Services.Apps.Apps._staticInstance._failed; }
MySpace.Web.Services.Apps.Apps.set_path("/Services/Apps/apps.asmx");
MySpace.Web.Services.Apps.Apps.MoveAppUp = function(token, surfaceId, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.MoveAppUp(token, surfaceId, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.MoveAppDown = function(token, surfaceId, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.MoveAppDown(token, surfaceId, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.UninstallApplication = function(token, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.UninstallApplication(token, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.UninstallApplicationEx = function(token, callbackParams, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.UninstallApplicationEx(token, callbackParams, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.RevokeApplicationToken = function(applID, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.RevokeApplicationToken(applID, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.GetAddAppFooterText = function(appid, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.GetAddAppFooterText(appid, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.InstallApplication = function(token, permissions, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.InstallApplication(token, permissions, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.InstallApplicationEx = function(token, permissions, callbackParams, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.InstallApplicationEx(token, permissions, callbackParams, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.UpdateApplicationSettings = function(appid, setpermissions, unsetpermissions, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.UpdateApplicationSettings(appid, setpermissions, unsetpermissions, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.GetApplicationPermissionsString = function(appid, unsetpermissions, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.GetApplicationPermissionsString(appid, unsetpermissions, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.BlockApplication = function(token, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.BlockApplication(token, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.UnblockApplication = function(token, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.UnblockApplication(token, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.SetUserPreferences = function(appId, userPreferenceKeys, userPreferenceValues, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.SetUserPreferences(appId, userPreferenceKeys, userPreferenceValues, onSuccess, onFailed, userContext); }
MySpace.Web.Services.Apps.Apps.IsAppInstallable = function(appId, viewerId, onSuccess, onFailed, userContext) { MySpace.Web.Services.Apps.Apps._staticInstance.IsAppInstallable(appId, viewerId, onSuccess, onFailed, userContext); }
var gtc = Sys.Net.WebServiceProxy._generateTypedConstructor;
if (typeof (MySpace.Web.Services.Apps.AppsReturn) === 'undefined') {
    MySpace.Web.Services.Apps.AppsReturn = gtc("MySpace.Web.Services.Apps.AppsReturn");
    MySpace.Web.Services.Apps.AppsReturn.registerClass('MySpace.Web.Services.Apps.AppsReturn');
}

Type.registerNamespace("MySpace");
Type.registerNamespace("MySpace.Apps");

MySpace.Apps.executeUrl = function(url) {
    if(url == null || url.length == 0) {
        return;
    }
    
	var img = new (Image)();
     _proxy_jslib_assign('', img, 'src', '=', ( url));
}

MySpace.Apps.executeInstallCallback = function(installCallbackUrl) {
    MySpace.Apps.executeUrl(installCallbackUrl);
}

MySpace.Apps.executeUninstallCallback = function(uninstallCallbackUrl) {
    MySpace.Apps.executeUrl(uninstallCallbackUrl);
}

MySpace.Apps.getFIMAdvParameter = function() {
   var re = "[\\?&]adv=([^&#]*)";
    var regexp = new (RegExp)(re);
    var matches = regexp.exec(  _proxy_jslib_handle( _proxy_jslib_handle(window, 'location', '', 0, 0), 'href', '', 0, 0) );
    if(matches == null) {
        return null;
    }
    else {
        return matches[1];
    }    
}

MySpace.Apps.makeFIMAdvCallback = function(primaryAdvId, secondaryAdvId) {
    var advCallbackUrl = "http://conv.opt.fimserve.com/conv/" + primaryAdvId + "/?rnd=" + Math.floor(Math.random()*9999999+1);
    if(FIM_advAppId) {
        advCallbackUrl +="&offid=" + secondaryAdvId + "-" + FIM_advAppId;
    }
    MySpace.Apps.executeUrl(advCallbackUrl);
}

MySpace.Apps.tryFIMAdvCallback = function() {
	var queryAdvId = MySpace.Apps.getFIMAdvParameter();
	if(queryAdvId) {
        if(FIM_baseAdvId) {
            MySpace.Apps.makeFIMAdvCallback(FIM_baseAdvId, queryAdvId);
        }
        else {
            MySpace.Apps.makeFIMAdvCallback(queryAdvId, queryAdvId);        
        }
	}
    else if(FIM_baseAdvId) {
        MySpace.Apps.makeFIMAdvCallback(FIM_baseAdvId, 0);            
    }
	else {
        return false;
	}
    return true;
}

MySpace.Apps.tryInstallCallback = function() {
    if(Applications_InstallCallbackUrl != null) 
    {
        MySpace.Apps.executeInstallCallback(Applications_InstallCallbackUrl);
    }
}

MySpace.Apps.uninstallApplication = function(token, uninstallSuccessHandler, uninstallFailureHandler) {
    MySpace.Web.Services.Apps.Apps.UninstallApplication(token,
    function(args) {
        if(typeof(args) == "object") {
            if(args.status == 0) {
                MySpace.Apps.executeUninstallCallback(args.callbackUrl);
                 _proxy_jslib_handle(null, 'setTimeout', setTimeout, 1, 0)(uninstallSuccessHandler, 2 * 1000);
            }
            else {
                uninstallFailureHandler();
            }
        }
        else {
            uninstallSuccessHandler();
        }
    },
    function(args) {
        uninstallFailureHandler(); 
    });
}

Type.registerNamespace('MySpace.Apps.JSONP');

MySpace.Apps.JSONP.timeoutIds = {};
MySpace.Apps.JSONP.request = function(paddingFunction, url, onTimeout, timeoutMilliseconds) {
    var timeout_id = paddingFunction;    
    var t =  _proxy_jslib_handle(null, 'setTimeout', setTimeout, 1, 0)(onTimeout, timeoutMilliseconds);
     _proxy_jslib_assign('', MySpace.Apps.JSONP.timeoutIds, (timeout_id), '=', ( t));
    
    var scriptElement = document.createElement("script");
     _proxy_jslib_handle(scriptElement, 'setAttribute', '', 1, 0)("type", "text/javascript");
    
    var jsonpParam = "?";
    if(url.indexOf("?") > 0) {
        jsonpParam = "&";
    }
    jsonpParam += "jsonp=clearTimeout(MySpace.Apps.JSONP.timeoutIds[\"" + timeout_id + "\"]);" + paddingFunction;
    
     _proxy_jslib_handle(scriptElement, 'setAttribute', '', 1, 0)("src", url + jsonpParam);    
     _proxy_jslib_handle(document, 'getElementsByTagName', '', 1, 0)("head")[0].appendChild(scriptElement);
}

MySpace.Apps.JSONP.context = {};
MySpace.Apps.JSONP.setContext = function(key, value) {
     _proxy_jslib_assign('', MySpace.Apps.JSONP.context, (key), '=', (  _proxy_jslib_handle(null, 'value', value, 0, 0)));
}

MySpace.Apps.JSONP.getContext = function(key) {
    if(MySpace.Apps.JSONP.context.hasOwnProperty(key)) {
        return  _proxy_jslib_handle(MySpace.Apps.JSONP.context, (key), 0, 0);
    }
    return null;
}

Type.registerNamespace("MySpace");
Type.registerNamespace("MySpace.UI");

MySpace.UI.AppsPopup = function() {throw "Cannot instantiate static class.";} 
MySpace.UI.AppsPopup._contentHolders = {};
MySpace.UI.AppsPopup.create=function(content, title, callback) {
    var temp=document.createElement("div");
     _proxy_jslib_assign('', temp, 'innerHTML', '=', ("<div class='appspopup_wrapper' style='z-index:1000001;left:0px;width:100%;display:none;visibility:hidden;'><div class='appspopup_box'><a></a><div class='appspopup_title'></div><div class='appspopup_content'></div><div class='appspopup_buttons'></div></div></div>"));
    var popup = $create(MySpace.UI._Popup,{title:title, content: _proxy_jslib_handle(null, 'content', content, 0, 0), callback:callback},null,null,temp.firstChild);
	return popup;
}

MySpace.UI.AppsPopup.createAddAppV2=function(content, title, close, footer, callback) {
    var temp=document.createElement("div");
     _proxy_jslib_assign('', temp, 'innerHTML', '=', ("<div class='addapp_popup_wrapper' style='z-index:1000001;left:0px;width:100%;display:none;visibility:hidden;'><div class='addapp_popup_box'><a class='addapp_popup_x'><div id='addappv2_close_x' style='float: left; margin-right: 4px; height: 17px;'>" +  _proxy_jslib_handle(null, 'close', close, 0, 0) + "</div><img id='addappv2_close_x' src='http://x.myspace.com/modules/applications/static/img/addappv2_close_icon.gif' /></a><div class='addapp_popup_title'></div><div class='addapp_popup_content'></div><div class='addapp_popup_buttons'><span style='margin-right: 10px;'>" + footer + "</span></div></div></div>"));
    var popup = $create(MySpace.UI._Popup,{title:title, content: _proxy_jslib_handle(null, 'content', content, 0, 0), callback:callback},null,null,temp.firstChild);
	return popup;
}

MySpace.UI.AppsPopup.inlinePermissions = function(appid, precontent, postcontent, title, callback) {
    var innerContent = "";
    var appidString =  _proxy_jslib_handle(appid, 'toString', '', 1, 0)();
    if(MySpace.UI.AppsPopup._contentHolders.hasOwnProperty(appidString)){
        innerContent =  _proxy_jslib_handle(MySpace.UI.AppsPopup._contentHolders, (appidString), 0, 0);
    }
    else {
        var inlineContentElement = $get('userapplication_permission_settings_' + appidString);
        innerContent =  _proxy_jslib_assign('', MySpace.UI.AppsPopup._contentHolders, (appidString), '=', (  _proxy_jslib_handle(inlineContentElement, 'innerHTML', '', 0, 0)));
        inlineContentElement.parentNode.removeChild(inlineContentElement);
    }    
    var content = precontent + innerContent + postcontent;
    return MySpace.UI.AppsPopup.create( _proxy_jslib_handle(null, 'content', content, 0, 0), title);       
}
MySpace.UI.AppsPopup.ajaxPermissions = function(appid, precontent, postcontent, title, handler) {
    return MySpace.UI.AppsPopup.ajaxPermissionsEx(appid, precontent, postcontent, title, handler, null, null);
}
MySpace.UI.AppsPopup.ajaxPermissionsEx = function(appid, precontent, postcontent, title, handler, category, permission) {
    if(typeof(category) == undefined) {
        category = null;
    }
    if(typeof(permission) == undefined) {
        permission = null;
    }
    
    var appidString =  _proxy_jslib_handle(appid, 'toString', '', 1, 0)();
    
    var requestParams = "appid="+appidString+"&checkuser=true";
    if(category != null) {
        requestParams +="&cat=" + escape(category);
    }
    if(permission != null) {
        requestParams +="&perm=" + escape(permission);
    }
    
    MySpace.WebRequest.invoke("/Modules/Applications/Pages/AppPermissions.aspx", false, requestParams, _onComplete, _onFail, null, 0);

    function _onComplete(response, eventArgs) {
	    var tempDiv = document.createElement('div');
	     _proxy_jslib_assign('', tempDiv, 'innerHTML', '=', ( response));
		var innerContent =  _proxy_jslib_assign('', MySpace.UI.AppsPopup._contentHolders, (appidString), '=', (  _proxy_jslib_handle($get('userapplication_permission_settings_' +  _proxy_jslib_handle(appid, 'toString', '', 1, 0)(), tempDiv), 'innerHTML', '', 0, 0)));
	    var content = precontent + innerContent + postcontent;
	    var p = MySpace.UI.AppsPopup.create( _proxy_jslib_handle(null, 'content', content, 0, 0), title);
	    handler(true, p);
	}
	function _onFail() {
	    handler(false, null);
	}
    return;
}

MySpace.UI.AppsPopup.getPermissions = function(sender, isset) {
    var installPermissions = new (Array)();
    var temps =  _proxy_jslib_handle(sender._box, 'getElementsByTagName', '', 1, 0)('input');
    for(i = 0; i < temps.length; i++) {
        if(Sys.UI.DomElement.containsCssClass( _proxy_jslib_handle(temps, (i), 0, 0), 'userAppPermission')

 &&  _proxy_jslib_handle(temps, (i), 0, 0).checked == isset) {
            installPermissions.push( _proxy_jslib_handle( _proxy_jslib_handle(temps, (i), 0, 0), 'value', '', 0, 0));
        }
    }
    return installPermissions;
}
MySpace.UI.AppsPopup.getSelectedPermissions = function(sender) {
    return MySpace.UI.AppsPopup.getPermissions(sender, true);
}
MySpace.UI.AppsPopup.getUnselectedPermissions = function(sender) {
    return MySpace.UI.AppsPopup.getPermissions(sender, false);
}

MySpace.UI.AppsPopup.ajaxBlockConfirmation = function(appid, title, handler) { 
    var appidString =  _proxy_jslib_handle(appid, 'toString', '', 1, 0)();   
    var requestParams = "appid=" + appidString;    
    
    MySpace.WebRequest.invoke("/Modules/Applications/Pages/BlockApplication.aspx", false, requestParams, _onComplete, _onFail, null, 0);

    function _onComplete(response, eventArgs) {
	    var content = response;
		var p = MySpace.UI.AppsPopup.create( _proxy_jslib_handle(null, 'content', content, 0, 0), title);
	    handler(true, p);
	}
	function _onFail() {
	    handler(false, null);
	}
    return;
}

MySpace.UI.AppsPopup.ajaxAddApp = function(appid, title, handler) { 
	var useLegacyAddApp = MySpace.Application.keyDisabled("Applications_EnableV2AddAppPopup");
	var appidString =  _proxy_jslib_handle(appid, 'toString', '', 1, 0)();   
    var requestParams = "appid=" + appidString + "&cat=2"; 
	var p;
	
	var loaderText = "<center style='margin-top: 25px; margin-bottom: 25px;'>" + MySpaceRes.AppManagement.AppsPopup_Loading + "<br /><img style='margin-top: 15px;' src='/modules/common/static/img/fhloadercircles.gif' /></center>";
	
	var	addAppHandler = function(result) {	
	
		var footer = result;
    
		if(useLegacyAddApp)
		{
			p = MySpace.UI.AppsPopup.create(loaderText, title);
			p.add_button(MySpaceRes.ProfileDisplay.AppInstallPopupButtonInstall);
	        p.add_button(MySpaceRes.ProfileDisplay.AppInstallPopupButtonCancel, true).isCancel = true;
	        p.show(handler);
			
			MySpace.WebRequest.invoke("/Modules/Applications/Pages/AddApp.aspx", false, requestParams, _onComplete, _onFail, null, 0);
		}
		else
		{
			p = MySpace.UI.AppsPopup.createAddAppV2(loaderText, MySpaceRes.AppManagement.AppsPopupV2AddApp, MySpaceRes.AppManagement.AppsPopupV2Close, footer);
			p.add_button(MySpaceRes.ProfileDisplay.AppInstallPopupButtonInstall);
		    p.show(handler);
		    
		    MySpace.WebRequest.invoke("/Modules/Applications/Pages/AddAppV2.aspx", false, requestParams, _onComplete, _onFail, null, 0);     
		}
		
		function _onComplete(response, eventArgs) {
	        
			var content = response;			
			p.set_content( _proxy_jslib_handle(null, 'content', content, 0, 0));		
			
			MySpace.UI.AppsPopup.checkForHideAddButton();				
						
			$create(MySpace.UI._Popup, null, null, null, p._element);
		}
			
		function _onFail() {}
			
		MySpace.UI.AppsPopup.checkForHideAddButton();
	}
	
	MySpace.Web.Services.Apps.Apps.GetAddAppFooterText(appid, addAppHandler);
           
    return;
}

MySpace.UI.AppsPopup.checkForHideAddButton = function() {
	var hideButton =  _proxy_jslib_handle(document, 'getElementById', '', 1, 0)('hideAddAppButton');
	
	if (hideButton != null) {
		var button =  _proxy_jslib_handle(document, 'getElementsByTagName', '', 1, 0)('input');
		for (var x = 0; x < button.length; x++) {
			if ( _proxy_jslib_handle( _proxy_jslib_handle(button, (x), 0, 0), 'value', '', 0, 0) == MySpaceRes.ProfileDisplay.AppInstallPopupButtonInstall) {
				 _proxy_jslib_handle(button, (x), 0, 0).style.display = 'none';
			}
		}
	}
}



function getElementsByClassName(classname, node) {
    if (!node) node =  _proxy_jslib_handle(document, 'getElementsByTagName', '', 1, 0)("body")[0];
    var a = [];
    var re = new (RegExp)('\\b' + classname + '\\b');
    var els =  _proxy_jslib_handle(node, 'getElementsByTagName', '', 1, 0)("*");
    for (var i = 0, j = els.length; i < j; i++)
    if (re.test( _proxy_jslib_handle(els, (i), 0, 0).className)) a.push( _proxy_jslib_handle(els, (i), 0, 0));
    return a;
}



MySpace.UI.AppsPopup.ajaxPreferences = function(appid, title, handler) {
    var appidString =  _proxy_jslib_handle(appid, 'toString', '', 1, 0)();
    var requestParams = "appid=" + appidString;

    var p = MySpace.UI.AppsPopup.create(MySpaceRes.AppManagement.AppsPopup_Loading, title);
    p.add_button(MySpaceRes.AppManagement.UserAppPref_SaveButton);
    p.add_button(MySpaceRes.AppManagement.UserAppPref_CancelButton, true).isCancel = true;
    p.show(
        function(sender, args) {
            if (args.target.isCancel) {
                sender.set_content("");
                if (typeof opt_callback === "function") {
                    opt_callback(null);
                }
                return;
            }

            var preferenceKeys = [];
            var preferenceValues = [];


            var prefNodes = getElementsByClassName("preferenceDefinition");
            for (var x = 0; x < prefNodes.length; x++) {
                preferenceKeys.push( _proxy_jslib_handle(prefNodes, (x), 0, 0).name);
                if ( _proxy_jslib_handle(prefNodes, (x), 0, 0).type == "checkbox") {
                    preferenceValues.push( _proxy_jslib_handle(prefNodes, (x), 0, 0).checked);
                }
                else
                    preferenceValues.push( _proxy_jslib_handle( _proxy_jslib_handle(prefNodes, (x), 0, 0), 'value', '', 0, 0));
            }

            prefList = getElementsByClassName("preferenceListText")[0];
            if (prefList) {
                preferenceKeys.push(prefList.name);
                var prefListValues = getElementsByClassName("preferenceListItem");
                var listValue = "";
                for (var x = 0; x < prefListValues.length; x++) {
                    listValue = listValue +  _proxy_jslib_handle( _proxy_jslib_handle(prefListValues, (x), 0, 0), 'innerHTML', '', 0, 0).substr(0,  _proxy_jslib_handle( _proxy_jslib_handle(prefListValues, (x), 0, 0), 'innerHTML', '', 0, 0).indexOf("<")) + "|";
                }

                listValue = listValue.substr(0, listValue.length - 1);
                preferenceValues.push(listValue);
            }

            alert("keys:" + preferenceKeys);
            alert("vals:" + preferenceValues);
            sender.set_content("");

            MySpace.Web.Services.Apps.Apps.SetUserPreferences(appid, preferenceKeys, preferenceValues,
            function(ret) {
                switch (ret.status) {
                    case 0:
                        if (typeof opt_callback === "function") {
                            opt_callback(null);
                        }
                        return;
                    default: // todo: do something different on error
                        if (typeof opt_callback === "function") {
                            opt_callback(null);
                        }
                        return;
                }
            },
            function(ret) {
                if (typeof opt_callback === "function") {
                    opt_callback(null);
                }
            });

        });

    MySpace.WebRequest.invoke("/Modules/Applications/Pages/UserAppPreferences.aspx", false, requestParams, _onComplete, _onFail, null, 0);

    function _onComplete(response, eventArgs) {
        var content = response;
        p.set_content( _proxy_jslib_handle(null, 'content', content, 0, 0));
        $create(MySpace.UI.AppPreferenceContainer,
            { rootElement: p._element },
            null, null, p._element);
        handler(true, p);
    }
    function _onFail() {
        handler(false, null);
    }
    return;
}

MySpace.UI.AppsPopup.registerClass('MySpace.UI.AppsPopup');

MySpace.UI.AppPreferenceContainer = function(element) {
    MySpace.UI.AppPreferenceContainer.initializeBase(this, [element]);
}; 
MySpace.UI.AppPreferenceContainer.prototype = {
    _rootElement: null,
    
    get_rootElement : function() { return this._rootElement; },
	set_rootElement : function(value) { this._rootElement =  _proxy_jslib_handle(null, 'value', value, 0, 0); },

    initialize: function() {
        var elements =  _proxy_jslib_handle(this._rootElement, 'getElementsByTagName', '', 1, 0)("form")
        for(var i = 0; i < elements.length; i++) {
            if( Sys.UI.DomElement.containsCssClass( _proxy_jslib_handle(elements, (i), 0, 0), "preferenceList")) {
                 var idStr = "apppreflist_" + i;
                  _proxy_jslib_handle(elements, (i), 0, 0).id = idStr;
                 $create(MySpace.UI.AppPreferenceList, 
		            {rootElement:  _proxy_jslib_handle(elements, (i), 0, 0)},
		            null,null, $get(idStr));
            }
        }
    }
}
MySpace.UI.AppPreferenceContainer.registerClass('MySpace.UI.AppPreferenceContainer', Sys.UI.Control);

MySpace.UI.AppPreferenceList = function(element) {
    MySpace.UI.AppPreferenceList.initializeBase(this, [element]);
}; 
MySpace.UI.AppPreferenceList.prototype = {
    _rootElement : null,
    _textInputElement: null,
    
    get_rootElement : function() { return this._rootElement; },
	set_rootElement : function(value) { this._rootElement =  _proxy_jslib_handle(null, 'value', value, 0, 0); },  
    
    initialize: function() {
        var subInputElements =  _proxy_jslib_handle(this._rootElement, 'getElementsByTagName', '', 1, 0)("input");
        for(var j = 0; j < subInputElements.length; j++) {
            if(Sys.UI.DomElement.containsCssClass( _proxy_jslib_handle(subInputElements, (j), 0, 0), "preferenceListText")) {
                this._textInputElement =  _proxy_jslib_handle(subInputElements, (j), 0, 0);
            }
            else if(Sys.UI.DomElement.containsCssClass( _proxy_jslib_handle(subInputElements, (j), 0, 0), "preferenceListButton")) {
                
                $addHandler( _proxy_jslib_handle(subInputElements, (j), 0, 0), "click", 
                Function.createDelegate (this, 
                    function (sender) {
                        if( _proxy_jslib_handle(this._textInputElement, 'value', '', 0, 0) != "") {
                            var elements =  _proxy_jslib_handle(sender.target.parentNode, 'getElementsByTagName', '', 1, 0)("span");
                            var preferenceListValues = null;
                            for(var i = 0; i < elements.length; i++) {
                                if(Sys.UI.DomElement.containsCssClass( _proxy_jslib_handle(elements, (i), 0, 0), "preferenceListValues")) {
                                    preferenceListValues =  _proxy_jslib_handle(elements, (i), 0, 0);
                                    break;
                                }
                            }
                            var span = document.createElement("span");
                            span.className = "preferenceListItem";
                            span.appendChild(document.createTextNode( _proxy_jslib_handle(this._textInputElement, 'value', '', 0, 0)));
                             _proxy_jslib_assign('', this._textInputElement, 'value', '=', ( ""));
                            var anchor = document.createElement("a");
                            anchor.className = "preferenceListItemRemove";
                             _proxy_jslib_assign('', anchor, 'innerHTML', '=', ( "X"));
                            $addHandler(anchor, "click", function (sender) { sender.target.parentNode.parentNode.removeChild(sender.target.parentNode); });
                            span.appendChild(anchor);
                            preferenceListValues.appendChild(span);
                            preferenceListValues.appendChild(document.createElement("wbr"));
                        }
                    }));
                break;
            }
        }
        var subListItems =  _proxy_jslib_handle(this._rootElement, 'getElementsByTagName', '', 1, 0)("span");                
        for(var k = 0; k < subListItems.length; k++) {
            if(Sys.UI.DomElement.containsCssClass( _proxy_jslib_handle(subListItems, (k), 0, 0), "preferenceListItem")) {
               var listItemAnchors =  _proxy_jslib_handle( _proxy_jslib_handle(subListItems, (k), 0, 0), 'getElementsByTagName', '', 1, 0)("a");
               for(var l = 0; l < listItemAnchors.length; l++) {
                    if(Sys.UI.DomElement.containsCssClass( _proxy_jslib_handle(listItemAnchors, (l), 0, 0), "preferenceListItemRemove")) {
                        $addHandler( _proxy_jslib_handle(listItemAnchors, (l), 0, 0), "click", function (sender) { sender.target.parentNode.parentNode.removeChild(sender.target.parentNode); });
                        break;
                    }
               }              
            }
        }
    }
}
MySpace.UI.AppPreferenceList.registerClass('MySpace.UI.AppPreferenceList', Sys.UI.Control);
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


MySpace.UI.AppsPopup.ajaxBlockConfirmation = function(appid, title, handler) {
    var appidString =  _proxy_jslib_handle(appid, 'toString', '', 1, 0)();
    var requestParams = "appid=" + appidString;

    MySpace.WebRequest.invoke("/Modules/Applications/Pages/BlockApplication.aspx", false, requestParams, _onComplete, _onFail, null, 0);

    function _onComplete(response, eventArgs) {
        var content = response;
        var p = MySpace.UI.AppsPopup.create( _proxy_jslib_handle(null, 'content', content, 0, 0), title);
        handler(true, p);
    }
    function _onFail() {
        handler(false, null);
    }
    return;
}



Type.registerNamespace('MySpace.MDP');
Type.registerNamespace('MySpace.MDP.Apps');
Type.registerNamespace('MySpace.MDP.Util');

MySpace.MDP.Util.isArray = function(a) {
    if(a == null) {
        return false;
    }
    return a.constructor == (new (Array)).constructor;
}

MySpace.MDP.Apps.API_RESOURCE_TIMEOUT = 3*1000; // in millis
MySpace.MDP.Apps.LIST_APPS_RESOURCE = "/Tests/Apps/TestAppsResources.aspx";
MySpace.MDP.Apps.setListAppsResource = function(resource) {
    MySpace.MDP.Apps.LIST_APPS_RESOURCE = resource;
}

/*********************************
 * Apps Cache 
 * todo: put timestamp on cache
 *********************************/
MySpace.MDP.Apps.AppCache = function() {
    MySpace.MDP.Apps.AppCache.initializeBase(this);
    this._initialized = false;
    this._cache = {};
    this._apps = null;
    this._viewerInfo = null;
}

MySpace.MDP.Apps.AppCache.prototype = {
    clear: function() {
        this._cache = {};
        this._initialized = false;
    },
    populate: function(apps) {
        this.clear();
        // normalize the array
        if(!MySpace.MDP.Util.isArray(apps) && MySpace.MDP.Util.isArray(apps.userInstalledApplications)) {
            if(apps.hasOwnProperty("viewer")) 
                this._viewerInfo = apps.viewer;
            apps = apps.userInstalledApplications;
        }
        // couldn't find apps
        if(apps == null) {
            apps = [];
        }    
        // set cache
        this._apps = apps;
        for(var i in apps) {
             _proxy_jslib_assign('', this._cache, ( _proxy_jslib_handle(apps, (i), 0, 0).id), '=', (  _proxy_jslib_handle(apps, (i), 0, 0)));
        }
        this._initialized = true;
        return apps;
    },
    getApp: function(appId) {
        return  _proxy_jslib_handle(this._cache, (appId), 0, 0);
    },
    getApps: function() {
        return this._apps;
    },
    getViewerInfo: function() {
        return this._viewerInfo;
    },
    isInitialized: function() {
        return this._initialized;
    }
};

MySpace.MDP.Apps.AppCache.registerClass('MySpace.MDP.Apps.AppCache');

mdpAppCache = new (MySpace.MDP.Apps.AppCache)();

/**************************
 * Callback proxy
 **************************/
MySpace.MDP.Apps.CallbackProxy = function(callbackProxyId, successCallback, errorCallback) {
    MySpace.MDP.Apps.AppCache.initializeBase(this);
    this.callbackProxyId = callbackProxyId;
    this.successCallback = successCallback;
    this.errorCallback = errorCallback;
}

MySpace.MDP.Apps.CallbackProxy.prototype = {
    invokeCallback: function(jsonData) {
        var arg = mdpAppCache.populate(jsonData);
        this.successCallback(arg);
         _proxy_jslib_assign('delete', (MySpace.MDP.Apps.callbackProxies), (this.callbackProxyId), '');
    }
};

MySpace.MDP.Apps.callbackProxies = {};

/***********************
 * Apps Resources
 * todo: timestamp? timeout length?
 ***********************/
MySpace.MDP.Apps.listApps = function(token, timestamp, surface, successCallback, errorCallback) {
    if(mdpAppCache.isInitialized()) {
        successCallback(mdpAppCache.getApps());
        return;
    }

    // make the jsonp request
    var listAppsUri = MySpace.MDP.Apps.LIST_APPS_RESOURCE;
    var jsonpParam = "?";
    if(listAppsUri.indexOf("?") > 0) {
        jsonpParam = "&";
    }
    if(token != null && token != "") { 
        listAppsUri += jsonpParam + "token=" + token;
        jsonpParam = "&";
    }
    if(timestamp != null && timestamp != "") {
        listAppsUri += jsonpParam + "timestamp=" + timestamp;
    }
    var jsonpTimeoutCallback = errorCallback;
    if(typeof(errorCallback) == "function") {
        jsonpTimeoutCallback = errorCallback.name + "();";
    }
    var timeout = MySpace.MDP.Apps.API_RESOURCE_TIMEOUT;
    var callbackProxyId = surface + timestamp;
     _proxy_jslib_assign('', MySpace.MDP.Apps.callbackProxies, (callbackProxyId), '=', ( new (MySpace.MDP.Apps.CallbackProxy)(callbackProxyId, successCallback, errorCallback, 47)));
    var jsonpCallback = "MySpace.MDP.Apps.callbackProxies['"+ callbackProxyId +"'].invokeCallback";
    MySpace.Apps.JSONP.request(jsonpCallback, listAppsUri, jsonpTimeoutCallback, timeout);    
}

MySpace.MDP.Apps.getAppFromCache = function(appId, successCallback) {
    if(mdpAppCache.getApp(appId) != null) {
        // todo: check timestamp, etc on app cache
        var app = mdpAppCache.getApp(appId);
        successCallback(app);
        return true;
    }
    return false;
}

MySpace.MDP.Apps.getViewerInfoFromCache = function(appId, successCallback) {
    if(mdpAppCache.getViewerInfo() != null) {
        
        var viewerInfo = mdpAppCache.getViewerInfo();
        //if surface is canvas, Check global permissions
        
        //then check the app permissions based on the appid

        successCallback(viewerInfo);
        return true;
    }
    return false;
}

MySpace.MDP.Apps.getApp = function(appId, token, timestamp, surface, successCallback, errorCallback) {
    if(MySpace.MDP.Apps.getAppFromCache(appId, successCallback)){
        return;
    }
    // fetch from server    
    function __listAppsCallback(apps) {
        // at this point, cache should be populated
        if(!MySpace.MDP.Apps.getAppFromCache(appId, successCallback)){
            errorCallback();            
        }
    }
    MySpace.MDP.Apps.listApps(token, timestamp, surface, __listAppsCallback, errorCallback);
}

MySpace.MDP.Apps.getViewerInfo = function(appId, token, timestamp, successCallback, errorCallback) {
    if(MySpace.MDP.Apps.getViewerInfoFromCache(appId, successCallback)) {
        return;
    }
    
    function __listAppsCallback(apps) {
        if(!MySpace.MDP.Apps.getViewerInfoFromCache(appId, successCallback)) {
            errorCallback();
        }
    }
    MySpace.MDP.Apps.listApps(token, timestamp, ifpc_current_surface, __listAppsCallback, errorCallback);   
}

MySpace.MDP.Apps.generateAppMarkup = function(app, surface) {
    if(!MySpace.Application.keyDisabled("Applications_ShowAfterLoadUHP") && app.panelType.toLowerCase() != "flash") {
        var height = 0; 
        var width = 0;
        if(app.hasOwnProperty("height")) height = app.height; 
        else if(app.hasOwnProperty("h")) height = app.h;
        if(app.hasOwnProperty("width")) width = app.width; 
        else if(app.hasOwnProperty("w")) width = app.w;
        return '<div class="mdp_app_placeholder" style="height: ' + height + 'px; width: ' + width + 'px;"></div>';
    }
    else {
        return MySpace.MDP.Apps.generateAppMarkupInternal(app, surface);   
    }
}

MySpace.MDP.Apps.generateAppMarkupInternal = function(app, surface) {
	
	if(surface.indexOf("profile") > -1)
		surface = "profile";
    
	var id = "apppanel_" + app.id + "_" + surface;
    var appcode = null;
    if(app.hasOwnProperty("innerHTML")) {
        //appcontent.innerHTML = app.innerHTML;    
        appcode =  _proxy_jslib_handle(app, 'innerHTML', '', 0, 0);
    }
    else {        
        var id = "apppanel_" + app.id + "_home";
        var panel;
        if(app.panelType.toLowerCase() == "opensocial") {
            panel = document.createElement("iframe");
            panel.id = id;
            panel.name = id;
            panel.allowtransparency = "true";
            panel.frameborder = 0;
            panel.height = app.height;
            panel.width = app.width;
             _proxy_jslib_assign('', panel, 'src', '=', ( app.iframeUrl));
            panel.scrolling = "no";

        }
        else if(app.panelType.toLowerCase() == "flash") {
            var panel = document.createElement("object");
            panel.id = id;
            panel.allowscriptaccess = "never";
            panel.allownetworking = "all";
            panel.type = "application/x-shockwave-flash";
            panel.data = app.flashUrl;
            panel.height = app.height;
            panel.width = app.width;
            
            var paramMovie = document.createElement("param");
            paramMovie.name = "movie";
             _proxy_jslib_assign('', paramMovie, 'value', '=', ( app.flashUrl));
            panel.appendChild(paramMovie);
            
            var paramFlashVars = document.createElement("param");
            paramFlashVars.name = "FlashVars";
             _proxy_jslib_assign('', paramFlashVars, 'value', '=', ( "")); //app.flashVars;
            panel.appendChild(paramFlashVars);
            
            var paramQuality = document.createElement("param");
            paramQuality.name = "quality";
             _proxy_jslib_assign('', paramQuality, 'value', '=', ( "high"));
            panel.appendChild(paramQuality);
            
            var paramWMode = document.createElement("param");
            paramWMode.name = "wmode";
             _proxy_jslib_assign('', paramWMode, 'value', '=', ( "transparent"));
            panel.appendChild(paramWMode);                
        }
        //appcontent.appendChild(panel);
        var fake = document.createElement("div");
        fake.appendChild(panel);
        appcode =  _proxy_jslib_handle(fake, 'innerHTML', '', 0, 0);
    }
    return appcode;
}

MySpace.MDP.Apps.loadApp = function(appid, surface, placeholder) {
    //check the class of the placeholder to see if it is
    if(placeholder && placeholder.className == "mdp_app_placeholder") {
         _proxy_jslib_assign('', placeholder, 'innerHTML', '=', ( '<div style="background: transparent url(/Modules/Common/Static/img/loadercircles.gif) no-repeat; margin: 10px; padding: 3px 0 0 28px; height: 30px;">App loading...</div>'));   
        MySpace.MDP.Apps.getApp(appid, "", "", surface, 
            function(app) {
                var fake = document.createElement("div");
                 _proxy_jslib_assign('', fake, 'innerHTML', '=', ( MySpace.MDP.Apps.generateAppMarkupInternal(app, surface)));    
            
                var appContent = fake.firstChild;
                appContent.style.display = "none";
                placeholder.appendChild(appContent);
                
                 _proxy_jslib_assign('', MySpace.MDP.Apps.loadAppPlaceholders, (appid + surface), '=', ( placeholder));           
            }, 
            function() {
                 _proxy_jslib_assign('', placeholder, 'innerHTML', '=', ( '<div style="margin: 10px; padding: 3px 0 0 3px; height: 30px;">Error loading app.</div>'));
            })

 }
}

MySpace.MDP.Apps.loadAppPlaceholders = {};
MySpace.MDP.Apps.appLoadedCallback = function(appid, surface) {
    var key = appid + surface;
    if(MySpace.MDP.Apps.loadAppPlaceholders.hasOwnProperty(key)) {
        var placeholder =  _proxy_jslib_handle(MySpace.MDP.Apps.loadAppPlaceholders, (key), 0, 0);
        placeholder.removeChild(placeholder.firstChild);
        placeholder.firstChild.style.display = "block";
        if(placeholder.className == "mdp_app_placeholder") {
            placeholder.style.height = "auto"; 
            placeholder.style.width = "auto";
        }
    }
} 

//AppsServices
function ifpc_widget_resize(iframeId, verticalHeight) {
    if(verticalHeight <= 1 && verticalHeight > 0 && "canvas" === ifpc_current_surface){
        var a= _proxy_jslib_handle(document, 'body', '', 0, 0).scrollHeight;//scrolled content
        var b=document.documentElement.clientHeight;//no scroll
        var c=document.documentElement.scrollHeight;//ie7 friendly
        a = ((a>c)?a:c);
        //291 is height of header  + nav link + app title + footer
        //291 shows a scroll bar in IE, 295 doesn't
        //TODO:this won't work if the user has text magnified or if another language breaks text onto two lines
        verticalHeight = Math.floor((((a>b)?a:b) - 295) * verticalHeight);
    }
    else if (verticalHeight < 1) verticalHeight = 0;//< 1 for when a fraction is given, but not on canvas
    else{
        switch(ifpc_current_surface) {
            case "canvas":
                max_widget_height = 1000000;
                break;
            default:
                max_widget_height = 1000;
                break;                                        
        }
        if (verticalHeight > max_widget_height) verticalHeight = max_widget_height;
    }

    var iFrame =  _proxy_jslib_handle(document, 'getElementById', '', 1, 0)(iframeId);
    
    iFrame.style.height = verticalHeight;
    iFrame.height = verticalHeight;
}
_IFPC.registerService('resizeWidget', ifpc_widget_resize);

function ifpc_widget_requestNavigateTo(appId, ownerId, surface, params, sourcePanel) {
    ifpc_widget_requestNavigateToEx(appId, ownerId, surface, params, sourcePanel, false, false)

}

function ifpc_widget_requestNavigateToEx(appId, ownerId, surface, params, sourcePanel, isNewInstall, getParams) {
    //encode params accordingly
    var encodedParams = encodeURIComponent(gadgets.JSON.stringify(params));            

    var target = null;
    //navigate to the url
    switch(surface) {
        case "canvas":
            target = ifpc_canvas_urltemplate;
            break;
        case "profile":
            target = ifpc_profile_urltemplate;
            break; 
        case "home":
            target = ifpc_home_urltemplate;
            break;    
    }
    
    if(target != null) {
        if(-1 === ifpc_ownerid){
            if(MySpace && MySpace.ClientContext && MySpace.ClientContext.DisplayFriendId){
                ifpc_ownerid = MySpace.ClientContext.DisplayFriendId;
            }
        }
    
        target =  _proxy_jslib_handle(target, 'replace', '', 1, 0)("{0}", appId);
        target =  _proxy_jslib_handle(target, 'replace', '', 1, 0)("{1}", ifpc_ownerid);
        target =  _proxy_jslib_handle(target, 'replace', '', 1, 0)("{2}", encodedParams);
        if(isNewInstall) {
            target += "&newinstall=1";
        }
        if(getParams) {
            target += "&" + getParams;
        }
         _proxy_jslib_assign('',  _proxy_jslib_handle(null, 'top', top, 0, 0), 'location', '=', ( target));
    }
}
_IFPC.registerService('requestNavigateTo', ifpc_widget_requestNavigateTo);

function ifpc_widget_requestPermission(appId, permissions, reason, opt_callback) {
    if(permissions instanceof Array && permissions.length > 0) { 
        MySpace.UI.AppsPopup.ajaxPermissionsEx(appId, reason, "", MySpaceRes.AppManagement.RequestPermissionHeader, 
            function(status, p) {
                if(p){
                    p.add_button(MySpaceRes.AppManagement.RequestPermissionUpdate); //adds the update button
                    p.add_button(MySpaceRes.AppManagement.RequestPermissionCancel, true).isCancel = true;
                    p.show(
                        function(sender, args) {
                            if(args.target.isCancel) {
                                if(typeof opt_callback === "function") {
                                    opt_callback(null);
                                }
                                return;
                            }
                            var selectedPermissions = MySpace.UI.AppsPopup.getSelectedPermissions(sender);
                            var unselectedPermissions = MySpace.UI.AppsPopup.getUnselectedPermissions(sender);
                            var permissionState = {};
                            for(var i=0; i<selectedPermissions.length; i++) {
                                 _proxy_jslib_assign('', permissionState, ( _proxy_jslib_handle(selectedPermissions, (i), 0, 0)), '=', ( true));
                            }
                            for(var i=0; i<unselectedPermissions.length; i++) {
                                 _proxy_jslib_assign('', permissionState, ( _proxy_jslib_handle(unselectedPermissions, (i), 0, 0)), '=', ( false));
                            }
                            MySpace.Web.Services.Apps.Apps.UpdateApplicationSettings(appId,
                                selectedPermissions, unselectedPermissions,
                                function(ret) {
                                    switch(ret.status) {
                                        case 0:
                                            if(typeof opt_callback === "function") {
                                                opt_callback(permissionState);
                                            }
                                            return;
                                        default:
                                            if(typeof opt_callback === "function") {
                                                opt_callback(null);
                                            }
                                            return;
                                    }
                                },
                                function(ret) {
                                    if(typeof opt_callback === "function") {
                                        opt_callback(null);
                                    }
                                });                                   
                        }    
                    );
                }//end if(p)
            }
            , null, permissions[0]  

 ); 
    }
}
_IFPC.registerService('requestPermission', ifpc_widget_requestPermission);

var ifpc_widget_postTo_data = {};
var ifpc_widget_iframe_popup = null;
function ifpc_widget_postTo(os_token, post_type, subject, content, opt_recipientId, opt_recipientImage, opt_recipientName, opt_recipientProfile, opt_callback) {
    ifpc_widget_postTo_data.os_token = os_token;
    ifpc_widget_postTo_data.post_type = post_type;
    ifpc_widget_postTo_data.subject = subject;
     _proxy_jslib_assign('', ifpc_widget_postTo_data, 'content', '=', (  _proxy_jslib_handle(null, 'content', content, 0, 0)));
    ifpc_widget_postTo_data.opt_recipientId = opt_recipientId;
    ifpc_widget_postTo_data.opt_recipientImage = opt_recipientImage;
    ifpc_widget_postTo_data.opt_recipientName = opt_recipientName;
    ifpc_widget_postTo_data.opt_recipientProfile = opt_recipientProfile;
    ifpc_widget_postTo_data.callback = opt_callback;
    
    var target_supported = false;
    for(var i = 0; i < ifpc_supported_postto_targets.length; i++){
        if( _proxy_jslib_handle(ifpc_supported_postto_targets, (i), 0, 0) === post_type){
            target_supported = true;
            break;
        }
    }
    
    if(target_supported){
        var url = "/Modules/MDPPostTo/Pages/MDPPostTo.aspx?opensocial_token=" + os_token + "&p=MDPPostTo", style = "appspopup_pt_";
        switch (post_type){
            case "PROFILE":
                url += "Profile";
                style += "pro";
                break;
            case "SEND_MESSAGE":
                url += "SendMessage";
                style += "send";
                break;
            case "COMMENTS":
                url += "Comment";
                style += "comm";
                break;
            case "BULLETINS":
                url += "Bulletin";
                style += "bull";
                break;
            case "BLOG":
                url += "Blog";
                style += "blog";
                break;
            case "SHARE_APP":
                url += "AppInvite";
                style += "appinvite";
                break;
        }
        
        if("appspopup_pt_" !== style){
            var div =  _proxy_jslib_handle(document, 'getElementById', '', 1, 0)("post_to_container");
            if(div){
                var iframe =  _proxy_jslib_handle(document, 'getElementById', '', 1, 0)("post_to_iframe");
                if(iframe && style !== iframe.className){
                    div.parentNode.removeChild(div);
                    //div = null;
                    ifpc_widget_iframe_popup = new (MySpace.UI.IframePopup)("post_to_container","","post_to_iframe",url,"appspopup_box appspopup_box_pt",style);
                }
            }
            else{
                ifpc_widget_iframe_popup = new (MySpace.UI.IframePopup)("post_to_container","","post_to_iframe",url,"appspopup_box appspopup_box_pt",style);
            }
            ifpc_widget_iframe_popup.show();
            
            if( _proxy_jslib_handle(document, 'getElementById', '', 1, 0)("post_to_container")){
                 _proxy_jslib_handle(document, 'getElementById', '', 1, 0)("post_to_container").style.position = "absolute";
                
                var vertScroll = 0;
                if( _proxy_jslib_handle(document, 'body', '', 0, 0) && ( _proxy_jslib_handle(document, 'body', '', 0, 0).scrollLeft ||  _proxy_jslib_handle(document, 'body', '', 0, 0).scrollTop)){
                    vertScroll =  _proxy_jslib_handle(document, 'body', '', 0, 0).scrollTop;
                }
                else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)){
                    vertScroll = document.documentElement.scrollTop;
                }
                 _proxy_jslib_assign('',  _proxy_jslib_handle(document, 'getElementById', '', 1, 0)("post_to_container").style, 'top', '=', ( 125 + vertScroll + "px"));
            }
        }
    }
}
_IFPC.registerService('postTo', ifpc_widget_postTo);


function ifpc_widget_requestLocale() {
    return [ifpc_locale.country, ifpc_locale.lang];
}
_IFPC.registerService('requestLocale', ifpc_widget_requestLocale);
_IFPC.registerService('requestShowApp', MySpace.MDP.Apps.appLoadedCallback);

function ifpc_widget_requestUserBasicInfo(userId, appId, opt_callback) {
    if(userId == 'VIEWER') {
        MySpace.MDP.Apps.getViewerInfo(appId, "", "", opt_callback, function() {});
        return;
    }
    opt_callback(null);
}
_IFPC.registerService('parentPageBasicInfoRequest', ifpc_widget_requestUserBasicInfo);
 ;
_proxy_jslib_flush_write_buffers() ;