/**
 * @author jreyes
 */

if (typeof(MyOpenSpace) === "undefined") MyOpenSpace = { };

MyOpenSpace.View = {};

MyOpenSpace.View.Field = {
    /**
     * The canvas.
     * @memberOf MyOpenSpace.View.Field
     */
    CANVAS:"canvas",
    /**
     * The left column on a profile page.
     * @memberOf MyOpenSpace.View.Field
     */
    PROFILE_LEFT:"profile.left",
    /**
     * The right column on a profile page.
     * @memberOf MyOpenSpace.View.Field
     */
    PROFILE_RIGHT:"profile.right",
    /**
     * Used for passing into requestNavigateTo
     * @memberOf MyOpenSpace.View.Field
     * @internal
     */
    PROFILE:"profile",
    /**
     * The home page.
     * @memberOf MyOpenSpace.View.Field
     */
    HOME:"home",
    /**
     * The default view.
     * @memberOf MyOpenSpace.View.Field
     */
    DEFAULT:"canvas"
};

MyOpenSpace.Message = function(body, opt_params) {
  this.fields_ = opt_params || {};
  this.fields_[MyOpenSpace.Message.Field.BODY] = body;
};

MyOpenSpace.Message.Field = {
  /**
   * The title of the message, specified as an opensocial.Message.Type.
   * @member opensocial.Message.Field
   */
  TYPE : 'type',

  /**
   * The title of the message. HTML attributes are allowed and are
   * sanitized by the container.
   * @member opensocial.Message.Field
   */
  TITLE : 'title',

  /**
   * The main text of the message. HTML attributes are allowed and are
   * sanitized by the container.
   * @member opensocial.Message.Field
   */
  BODY : 'body'
};


/**
 * Gets the message data that's associated with the specified key.
 *
 * @param {String} key The key to get data for;
 *   see the <a href="opensocial.Message.Field.html">Field</a> class
 * for possible values
 * @return {String} The data
 * @member opensocial.Message
 */
MyOpenSpace.Message.prototype.getField = function(key) {
  return this.fields_[key];
};


/**
 * Sets data for this message associated with the given key.
 *
 * @param {String} key The key to set data for
 * @param {String} data The data to set
 */
MyOpenSpace.Message.prototype.setField = function(key, data) {
  return this.fields_[key] = data;
};


MyOpenSpace.PostTo = {};

/**
 * Enumerates the targets for PostTo
 * @static
 * @class
 * @internal
 * @name MyOpenSpace.PostTo.Targets
 */
MyOpenSpace.PostTo.Targets = {
    /**
     * A user's profile, the specific section is specified on the Post To UI
     * @memberOf MyOpenSpace.PostTo.Targets
     */
    PROFILE:"PROFILE",
    
    /**
     * A message to another user's inbox
     * @memberOf MyOpenSpace.PostTo.Targets
     */
    SEND_MESSAGE:"SEND_MESSAGE",
    
    /**
     * A user's comments
     * @memberOf MyOpenSpace.PostTo.Targets
     */
    COMMENTS:"COMMENTS",
    
    /**
     * A user's bulletins
     * @memberOf MyOpenSpace.PostTo.Targets
     */
    BULLETINS:"BULLETINS",
    
    /**
     * A user's blog
     * @memberOf MyOpenSpace.PostTo.Targets
     */
    BLOG:"BLOG",

    /**
     * Request to share an app with another user
     * @memberOf MyOpenSpace.PostTo.Targets
     */
    SHARE_APP:"SHARE_APP"

};

MyOpenSpace.PostTo.Result = {
    /**
     * An error occurred in postTo request
     * @memberOf MyOpenSpace.PostTo.Result
     */
	ERROR: -1,
	
    /**
     * User pressed cancel before completion
     * @memberOf MyOpenSpace.PostTo.Result
     */
	CANCELLED: 0,
	
    /**
     * Successful postTo request completed
     * @memberOf MyOpenSpace.PostTo.Result
     */
	SUCCESS: 1
};

MyOpenSpace.MySpaceContainer = function() {
    
    gadgets.util.getUrlParameters().views = gadgets.util.getUrlParameters().opensocial_surface;//HACK ALERT
    var config = {};
    var supported_views = {};
    supported_views["default"] = new gadgets.views.View(MyOpenSpace.View.Field.DEFAULT, true);
    supported_views[MyOpenSpace.View.Field.CANVAS] = new gadgets.views.View(MyOpenSpace.View.Field.CANVAS, true);
    
    config["views"] = supported_views;
    gadgets.config.init(config);

    this.osMode_ = gadgets.views.getCurrentView();
    var uriFragment = window.location.hash;
    if (uriFragment && uriFragment.length >= 0) {
        uriFragment = uriFragment.substring(1,uriFragment.length);
        if(uriFragment.indexOf("&") >= 0){
            uriFragment = uriFragment.substring(0, uriFragment.indexOf("&"));
        }
    }
	
    this.params_ = {};
    
    var urlParams = gadgets.util.getUrlParameters();
	
	if (urlParams &&  urlParams.opensocial_token){
		this.params_["osToken"] = urlParams.opensocial_token;
	}
	
	if (urlParams &&  urlParams.opensocial_owner_id){
		this.params_["ownerid"] = urlParams.opensocial_owner_id;
	}
	
	if (urlParams &&  urlParams.appid){
		this.params_["appid"] = urlParams.appid;
	}
	
    if (urlParams && urlParams.ptoString) {
        this.params_["supportedPostToTargets"] = urlParams.ptoString.split(",");
    }
	else{
		this.params_["supportedPostToTargets"] = ["COMMENTS","BLOG","BULLETINS","PROFILE","SEND_MESSAGE","SHARE_APP"];
	}
	
	this.params_["remoteRelay"] = "http://profile.myspace.com/Modules/Applications/Pages/ifpc_relay.aspx";
}
MyOpenSpace.MySpaceContainer.container_ = new MyOpenSpace.MySpaceContainer();

MyOpenSpace.MySpaceContainer.get = function(){
	return MyOpenSpace.MySpaceContainer.container_;
}

var _IFPC = window["_IFPC"];

MyOpenSpace.MySpaceContainer.prototype.registerParam = function(key, value) {
    this.params_[key] = value;
};

MyOpenSpace.MySpaceContainer.prototype.getParam = function(key) {
    return this.params_[key];
};


MyOpenSpace.MySpaceContainer.prototype.newMessage = function(body, opt_params) {
  return new MyOpenSpace.Message(body, opt_params);
};

MyOpenSpace.MySpaceContainer.prototype.adjustHeight = function(opt_height) {
    var newHeight = parseInt(opt_height, 10);
    var percentage = false;
    if(isNaN(newHeight)){
        var vh = gadgets.window.getViewportDimensions().height;
        var body = document.body;
        var docEl = document.documentElement;
        if (document.compatMode == 'CSS1Compat' && docEl.scrollHeight){
            newHeight = docEl.scrollHeight != vh ? docEl.scrollHeight : docEl.offsetHeight;
        }
        else{
            var sh = docEl.scrollHeight;
            var oh = docEl.offsetHeight;

            if(docEl.clientHeight != oh){
                sh = body.scrollHeight;
                oh = body.offsetHeight;
            }

            if(sh > vh){
                newHeight = sh > oh ? sh : oh;
            }
            else{
                newHeight = sh < oh ? sh : oh;
            }
            
            if(newHeight === vh &&
                    window.navigator &&
                    window.navigator.userAgent &&
                    window.navigator.userAgent.toLowerCase().indexOf("safari") >= 0){ //for safari, quite ugly...
                var newDiv = document.createElement("div");
                newDiv.innerHTML = document.body.innerHTML;
                newDiv.style.visibility = "hidden";
                newDiv.id = "_temp_____div_for_____adjustHeight";
                document.body.appendChild(newDiv);
                newHeight = document.getElementById("_temp_____div_for_____adjustHeight").offsetHeight + 15;
                newDiv.innerHTML = "";
                document.body.removeChild(newDiv);
            }
        }
    }
    else if(0 === newHeight){
        newHeight = parseFloat(opt_height);
        if(!isNaN(newHeight) && (newHeight <= 1 || newHeight > 0)) percentage = true;
    }

	var oldHeight = gadgets.window.getViewportDimensions().height;
    if (newHeight != oldHeight || percentage) {
        var p = this.params_;
        _IFPC.call(
            p.panelId,
            "resizeWidget",
            [p.panelId , newHeight],
            p.remoteRelay,
            null,
            p.localRelay,
            null); 
    }
};

MyOpenSpace.MySpaceContainer.prototype.requestNavigateTo = function(view, opt_params) {

    if (view) {
        if (0 === view.indexOf("profile.")) view = "profile";
        var p = this.params_;
        _IFPC.call(
            p.panelId,
            "requestNavigateTo",
            [p.appid, p.ownerid, view.toLowerCase(), opt_params],
            p.remoteRelay,
            null,
            p.localRelay,
            null);
    }
}


MyOpenSpace.MySpaceContainer.prototype.postTo = function(message,opt_callback, recipientId, recipientName, recipientThumbnail, recipientProfileUrl ){
    if (MyOpenSpace.View.Field.CANVAS !== gadgets.views.getCurrentView().getName()) {
		return {"errorCode":"NOT_IMPLEMENTED","errorMessage":"PostTo does not support this view, only the canvas view is supported."}; 
	}
    var target_is_supported = false;
    var supported = this.params_.supportedPostToTargets;
    
    var messageSubject = "", messageBody, messageType = MyOpenSpace.PostTo.Targets.PROFILE;
    if(null !== message && "undefined" !== typeof(message)){
        messageSubject = message.getField(MyOpenSpace.Message.Field.TITLE);
        messageBody = message.getField(MyOpenSpace.Message.Field.BODY);
        messageType = message.getField(MyOpenSpace.Message.Field.TYPE);
    }
    else{
        return {"errorCode":"BAD_REQUEST","errorMessage":"You must supply a valid Message object."}; 
    }
    
    for(var i = 0; i < supported.length; i++){
        if(supported[i] === messageType){
            target_is_supported = true;
            break;
        }
    }
    
    if (!target_is_supported) {
		return {"errorCode":"BAD_REQUEST","errorMessage":"That PostTo target is not supported."};
	}

	var token = this.params_.osToken;
	if (typeof(token) === 'undefined'){
		return {"errorCode":"BAD_REQUEST","errorMessage":"Open social token not set."};
	}
	
	var panelId = this.params_.panelId;
    _IFPC.call(
            panelId,
            "postTo",
            [token, 
				messageType, messageSubject, messageBody, 
				recipientId, recipientThumbnail,recipientName, recipientProfileUrl],
            this.params_.remoteRelay,
            opt_callback,
            this.params_.localRelay,
            null);
};
