var loggedInUser = -1;
var msGlobalViewerInfo = null;
var msGlobalAppInfo=null;
var msUserProfileBasics = new Array();
var persistUserOpinion=null;
var persistWallType=null;
var persistAssociatedId=-1;
var persistComment = null;
var friendCount = null;
var friendsName = new Array();
var friendsIds = new Array();
var recipientsArray = new Array();
var friendsObject = new Array();
var shareOpinionId = -1;
var osGlobalNotificationText = '';
var hasAppInstalled = true;
var createOpinionStatement = '';
var createOpinionId=0;

var hi5LinkPrefix = "http://www.hi5.com/friend/apps/displayAppCanvas.do?appId=3727&view-params=";
var myspaceLinkPrefix = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=103073&appParams=";
var friendsterLinkPrefix = "http://opensocial.minekey.com/ithink-fr/index.php?";

var orkutLinkPrefix = "http://www.orkut.com/Application.aspx?appId=777065918962&appParams=";


var setTimeOutValue = 3000;
var createOpinionStatement = '';
var opinionCreatorId = -1;
var currentOpinionId = null;
var justCalledUrl = null;
var currentCallBack = null;
var currentRequestType = 'GET';
var currentPostParams = null;
var totalFriendCount = 0;
var friendFlag = false;

var setTimeOutValue = 3000;


function getProcessedId(id)
{
 var retValue = id;
 var ch = retValue.substring(0, 1);
 while (ch == "0") {
     retValue = retValue.substring(1, retValue.length);
     ch = retValue.substring(0, 1);
 }
 return retValue;
}

function gotoUrl(url){
    if(getGlobalParams('container') == 'friendster')
    {
       window.location = url+getUrlAppendParams();
    }
    else
    {
       top.location = url;
    }
}
function convertAppParams(appParams){
    if(getGlobalParams('container') == 'friendster')
    {
      var paramString = '';
      for (propertyName in appParams) {
          paramString += ''+propertyName+'='+escape(appParams[propertyName])+'&';
      }
      paramString += 'lastPost=empty';
      return paramString;
    }
    else
    {
       return encodeURIComponent(gadgets.json.stringify(appParams));
    }
}
function checkAppInstalled()
{
 return hasAppInstalled;
}
function promptAppInstall()
{
	switch(getGlobalParams('container'))
	{
		case 'myspace':
	    	alert('Please install Minekey first!\n\nTo add an opinion or comment on Minekey you must first install the application.');
	    	gotoUrl("http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid=349292705");
	    	break;
	    case 'hi5':
	         alert('Please install Minekey first!\n\nTo add an opinion, Vote or comment on Minekey you must first install the application.');
	         gotoUrl("http://www.hi5.com/friend/apps/displayAppCanvas.do?appId=3727");
	    	break;
		case 'orkut':
	         alert('Please install Minekey first!\n\nTo add an opinion, Vote or comment on Minekey you must first install the application.');

	         gotoUrl("http://www.orkut.com/AppInfo.aspx?appId=777065918962");
	    	break;

	}
}

function setGlobalNotificationText(text)
{
  osGlobalNotificationText = text;
}

function getGlobalNotificationText()
{
  return osGlobalNotificationText;
}

function getViewerInfo()
{
	var req = opensocial.newDataRequest();
	req  = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
	if(getGlobalParams('container') == 'hi5')
	{
       req.add(req.newFetchPersonAppDataRequest("VIEWER",["opinion_counter"]),"counter");
	}
	req.send(onLoadViewerInfo);
}

function searchOpinion(searchDivId)
{
  var fullsearchQuery = document.getElementById(searchDivId).value;
  fullsearchQuery = fullsearchQuery.replace(/^\s+/g, '').replace(/\s+$/g, '');
  var firstterm = fullsearchQuery.split(' ');
  searchQuery = firstterm[0];
  if(searchQuery.length==0 || fullsearchQuery == 'Enter your favorite topic. Search what people are thinking.')
  {
    alert('Please enter at least one keyword to search');
    return;
  }
  var searchParams = { layout : 'search', action : 'search' , q : ''+searchQuery};
  var link = getLinkPrefix() + convertAppParams(searchParams);
  gotoUrl(link);
}

function onLoadViewerInfo(data)
{
   try
	{
	  msGlobalViewerInfo = data.get('viewer').getData();
	  if(getGlobalParams('container') == 'hi5')
      {
	      msGlobalAppInfo=data.get("counter").getData();
          msGlobalAppInfo = msGlobalAppInfo[msGlobalViewerInfo.getId()];
      }
      var userName = msGlobalViewerInfo.getDisplayName();
      if(getGlobalParams('container') == 'orkut')
      {
        msGlobalViewerInfo['getImageUrl'] = msGlobalViewerInfo.getField(opensocial.Person.Field.THUMBNAIL_URL);
        msGlobalViewerInfo['getViewerId'] = getProcessedId(msGlobalViewerInfo.getField(opensocial.Person.Field.ID));
	  }
      initPageRender();
	}
	catch(err)
	{
      hasAppInstalled = false;
	  if(getGlobalParams('container') == 'hi5')
	  {
	    hasAppInstalled = true;
	  }
	  msGlobalViewerInfo = new Object;
	  msGlobalViewerInfo['getDisplayName'] = getDummyName;
	  initPageRender();
	}
}
function getDummyName()
{
    return '';
}

var isTfdScreen = false;

function isTFD()
{
  return isTfdScreen;
}


function getOkProfileUrl()
{
	var params = {};
	params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.PROFILE_URL];
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER,params), "req");
    req.send(handleOkProfileUrl);
}
function handleOkProfileUrl(data)
{
  try
  {
	  var owner = data.get('req').getData();
	  var profileURL  = owner.getField(opensocial.Person.Field.PROFILE_URL);
	  var regex = /uid=([^&#]+)/;
	  var result = profileURL.match(regex);
	  var userId = null;
	  if (result.length == 2)
	  {
	     var userId = result[1];
	  }
	  var opensocialId = msGlobalViewerInfo.getId();
	 // var gender = msGlobalViewerInfo.getField(opensocial.Person.Field.GENDER);
	  var imageURL =  msGlobalViewerInfo.getField(opensocial.Person.Field.THUMBNAIL_URL);
	  msGlobalViewerInfo['getProfileURL'] = profileURL;
	  msGlobalViewerInfo['getOrkutId'] = userId;
	  msGlobalViewerInfo['getImageUrl'] = imageURL;
      var userNameFull = msGlobalViewerInfo.getDisplayName();
      var userName = userNameFull.split(' ');
	  if(userId != null && imageURL != null && userName != null)
	  {
	    var wsUrl = msMinekeyWSUrl+ '&bpc=1&layout=user&action=createuser&genuserid='+userId+'&foruserid='+opensocialId+'&displayname='+userName[0]+'&imageurl='+msGlobalViewerInfo['getImageUrl']+'&profileurl='+msGlobalViewerInfo['getProfileURL'];
	    os_makeRequest(wsUrl, handleCreateUser);
	  }
  }
  catch(err)
  {
    hasAppInstalled = false;
    msGlobalViewerInfo['getDisplayName'] = getDummyName;
  }
}

function extractTFDContent(str, contenttype)
{
	var reg = new RegExp('###'+contenttype+'start###(.)*###'+contenttype+'end###');
	var opinionComplete = ''+str.match(reg);
	var opinionArray = new Array();
	opinionArray = opinionComplete.split('###');
	return opinionArray[2];
}
function myHandle(responseData)
{
	var response = responseData.data;
	if(response.length <= 5) initPageRender();
	var response = responseData.data;
	if(getGlobalParams('container') == 'hi5' && response.substring(1, 100).match('cmd=redirectinvite') != null)
	{
		  opensocial.requestShareApp(opensocial.DataRequest.Group.VIEWER_FRIENDS, opensocial.newMessage('Minekey is 10 times more fun when your friends get involved!'));
		  return;
	}
    document.getElementById('opensocial_Header').innerHTML = response;
    if(document.getElementById('os_success_msg'))
    {
	  setTimeout(function(){hide('os_success_msg')},3000);
    }
    if(response.substring(1, 100).match('cmd=redirecttfd') != null)
    {
      if(getGlobalParams('container') != 'orkut')
      {
	    getFriendsListBox();
	    isTfdScreen = true;
	  }
      if(getGlobalParams('container') == 'hi5')
      {
         try
         {
             var tfdContent = ''+response.substring(1, 500);
             var statement = ''+extractTFDContent(tfdContent, 'opinion');
             var opinionid = ''+extractTFDContent(tfdContent, 'opinionid');
             var creatorid = ''+extractTFDContent(tfdContent, 'loggeduser');
             activityUpdateThinkingFeed(opinionid,statement,creatorid);
         }catch(err){}
      }
	  if(getGlobalParams('container') == 'orkut')
      {
        isTfdScreen = false;
        try
         {
             var tfdContent = ''+response.substring(1, 500);
             var statement = ''+extractTFDContent(tfdContent, 'opinion');
             var opinionid = ''+extractTFDContent(tfdContent, 'opinionid');
             var creatorid = ''+extractTFDContent(tfdContent, 'loggeduser');
             activityUpdateThinkingFeed(opinionid,statement,creatorid);
         }
		 catch(err)
		 {
		 }
	  }

    }
    if(getGlobalParams('container') == 'orkut')
	{
	    if(response.substring(1, 100).match('cmd=nonappuser') != null)
	    {
		     try
		     {
		       getOkProfileUrl();
     		 }
     		 catch(err)
			 {
	  		    hasAppInstalled = false;
	            msGlobalViewerInfo['getDisplayName'] = getDummyName;
	         }
        }
	}
    if(getParams('layout') == 'share')
    {
      getFriendsListBox();
    }
    my_adjustHeight();
    if(!checkAppInstalled())
    {
       try
       {
          if(getGlobalParams('container') == 'myspace')
          {
            document.getElementById('os_toptabmyopinion').innerHTML = '<a target="_top" href="http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid=349292705" class="iThink_TopNavLink">install&nbsp;Minekey</a>';
		  }
		  else if(getGlobalParams('container') == 'orkut')
		  {

		    document.getElementById('os_toptabmyopinion').innerHTML = '<a target="_top" href="http://www.orkut.com/AppInfo.aspx?appId=777065918962" class="iThink_TopNavLink">install&nbsp;Minekey</a>';

		  }
       }catch(err){}
    }
}

function handleCreateUser(responseData)
{
  var response = parseData(responseData.data);
  extractCommonData(response);
  hasAppInstalled = false;
  if(response == null) return;
  var flag = response.createUserRes.success;
  if(flag == 'success')
  {
    hasAppInstalled = true;
    var userNameFull = msGlobalViewerInfo.getDisplayName();
    var userName = userName.split(' ');
  }
  else
  {
    hasAppInstalled = false;
	msGlobalViewerInfo['getDisplayName'] = getDummyName;

	document.getElementById('os_toptabmyopinion').innerHTML = '<a target="_top" href="http://www.orkut.com/AppInfo.aspx?appId=777065918962" class="iThink_TopNavLink">install&nbsp;Minekey</a>';

  }
}

function my_adjustHeight(){
  var newHeight;
  var vh = 0;
  if(getGlobalParams('container') != 'friendster')
  {
     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(getGlobalParams('container') == 'orkut' && getParams('layout') == 'createopinion')
  {
    newHeight = newHeight + 70;
  }
  if(getGlobalParams('container') == 'friendster')
  {
//    resizeIframe(950,newHeight);
  }
  else
  {
    gadgets.window.adjustHeight(newHeight);
  }
}
function initPageRender(postUrl, callBack, params)
{
  postUrl = msMinekeyWsHTMLUrl;
  var allParams = getAllAppParams();
  var flag = false;
  for (propertyName in allParams)
  {
        if(propertyName == "layout")
    	{
    	  flag = true;
		}
    	postUrl += "&" + propertyName + "=" + allParams[propertyName];
  }
  callBack = myHandle;
  if(params == null)
  {
		params = {};
  }
  params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
  params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
  params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
  gadgets.io.makeRequest(postUrl+'&timestamp='+currentTimestamp(), callBack, params) ;
}

function os_makeRequest(postUrl, callBack, params)
{
  try
  {
	if(getGlobalParams('container') == 'friendster')
	{
		my_makeRequest(postUrl+'&timestamp='+currentTimestamp(), callBack, params);
		return;
	}
    if(params == null)
	{
		params = {};
	}
    currentRequestType = 'GET';
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
    justCalledUrl = postUrl;
    currentCallBack = callBack;
	gadgets.io.makeRequest(postUrl+'&timestamp='+currentTimestamp(), callBack, params) ;
  }
  catch (err)
  {
    alert(err);
  }
}

function getLoggedInUserId()
{
	var LoggedInUserID =  -1;
	try
	{
	    if(getGlobalParams('container') == 'orkut')
	    {
	      LoggedInUserID = getProcessedId(msGlobalViewerInfo.getField(opensocial.Person.Field.ID));
		}
		else
		{
		  LoggedInUserID = msGlobalViewerInfo.getField(opensocial.Person.Field.ID);
		}

	} catch(err){}
	return LoggedInUserID ;
}
function parseData(responseObj)
{
	if(getGlobalParams('container') == 'friendster')
	{
	  return eval('(' + responseObj + ')');
	}
    if(responseObj.length < 5)
	{
	  if(currentRequestType == 'POST')
	  {
	     os_postDataRequest(justCalledUrl, currentPostParams, currentCallBack, {})
	  }
	  else
      {
         os_makeRequest(justCalledUrl, currentCallBack, {});
      }
       return null;
	}
    return gadgets.json.parse(responseObj);
}
function extractCommonData(responseObj)
{
    try
	{
		for(var i=0;i < responseObj.userBasics.length; i++)
	  	{
	    	var userObj = responseObj.userBasics[i];
			msUserProfileBasics[userObj.userid] = userObj;
		}

 	} catch(err) {}

}

function getParams(name)
{
  if(os_AllParams == null) getAllAppParams();
  if(os_AllParams == null) return null;
  return os_AllParams[name];
}

function currentTimestamp()
{
	var now = new Date();
	var ts = new Array(
	now.getFullYear().toString(),
	now.getMonth().toString(),
	now.getDay().toString(),
	now.getHours().toString(),
	now.getMinutes().toString(),
	now.getSeconds().toString())
	var i;
	var retval = '';
	for (i=0; i<ts.length; i++)
	{
		if (ts[i].length < 2) ts[i] = '0' + ts[i];
		retval += ts[i];
	}
	return (retval);
}

function getAllAppParams()
{
    var tempParams = new Array();
    var mergeParams = new Array();
    try
    {
      mergeParams = gadgets.views.getParams();
      for (propertyName in mergeParams) { tempParams[propertyName] = mergeParams[propertyName];}

    } catch(err){}
    try
    {
      mergeParams = opensocial.getEnvironment().getParams();
      for (propertyName in mergeParams) { tempParams[propertyName] = mergeParams[propertyName];}
    } catch(err){}
    try
    {
       var tempx =  gadgets.util.getUrlParameters();
       mergeParams = eval('(' + tempx.p + ')');
       for (propertyName in mergeParams) { tempParams[propertyName] = mergeParams[propertyName];}
    } catch(err){}
    if(os_AppParams != null)
    {
	    try
	    {
	       mergeParams = getOSAllAppParams();
	       for (propertyName in mergeParams) { tempParams[propertyName] = mergeParams[propertyName];}
	    } catch(err){}
	}


	if(tempParams == null)
    	return null;
	var returnParams = {};
    for (propertyName in tempParams)
    {
    	returnParams[propertyName] = tempParams[propertyName];
    }
    os_AllParams = returnParams;
	return returnParams;
}

function setGlobalOpinionId(opid)
{
  createOpinionId = opid;
}

function getGlobalParams(name)
{
  switch(name)
  {
    case 'baseLink':
    return '/myspace/index.html';
    break;
    case 'baseDir':
    return '/myspace/';
    case 'network':
    /*return 'myspace';*/
    return osGlobalNetwork;
    case 'container':
    return osGlobalContainer;
    case 'opinionid':
    return  createOpinionId;
    break;
  }
}


function removeSpecialChars(str)
{

  switch(getGlobalParams('container'))
  {
    case 'myspace':
    break;
    case 'hi5':
    	//str = str.replace(/ /g, '_');
    	str = str.replace(/\\/g, '');
    	str = str.replace(/\+/g, '');
    	//str = str.replace(/['"]/g, '`');
    	str = str.replace(/~/g, '_');
      break;
  }
  return str;
}

function removeFeedSpecialChars(str)
{
  switch(getGlobalParams('container'))
  {
    case 'myspace':
      break;
    case 'hi5':
    	str = str.replace(/["']/g, '`');
    	str = str.replace(/\\"/g, '`');
        str = str.replace(/\\'/g, "`");
        str = str.replace(/\\/g, "");
      break;
      case 'orkut':
    	str = str.replace(/["']/g, '`');
    	str = str.replace(/\\"/g, '`');
        str = str.replace(/\\'/g, "`");
        str = str.replace(/\\/g, "");
      break;
  }
  return str;
}

function msRemoveSpecialChars(str)
{
  str = str.replace(/\\"/g, '"');
  str = str.replace(/\\'/g, "'");
  str = str.replace(/`/g, '"');
  return str;
}

function setUserResponse(opinionid,userresponse,divid)
{
	if(!checkAppInstalled())
	{
		promptAppInstall();
		return;
	}
	var responseElement = document.getElementById('os_opinionresponse_'+opinionid+'_'+divid);
	responseElement.innerHTML = '<img src="'+msMinekeyImageBase+'/loader.gif" width="16" height="16"/>';
    var wsUrl = msMinekeyWSUrl+ '&layout=opinion&action=response&opinionid='+opinionid+'&userresponse='+userresponse+'&divid='+divid;
    os_makeRequest(wsUrl, handleReceiveUserResponse);
}

function handleReceiveUserResponse(responseData, url, error)
{
  var response = parseData(responseData.data);
  if(response == null) return;
  extractCommonData(response);
  var userresponseobj = response.opinionResponse.opinionresponse0;
  var feedPushedInLast24hrs = response.opinionResponse.feedPushedInLast24hrs;
  var notiPushedInLast24hrs = response.opinionResponse.notiPushedInLast24hrs;
  var id = response.opinionResponse.opinionresponse0.divid;
//re using the same variable names. Don't get confused
  opinionCreatorId=userresponseobj.creatorid;
  createOpinionStatement=userresponseobj.statement;
  createOpinionId=userresponseobj.opinionid;
  var str = '';
  if(userresponseobj.userresponse == null)
  {
	str += '<a href="#" class="iThink_actionLink">Agree</a> <span class="iThink_footerDividerText">|</span> <a href="#" class="iThink_actionLink">Disagree</a></td>';
  }
  else if(userresponseobj.userresponse ==  'agree')
  {
    str += '<span class="iThink_actionLinkAgree">Agreed</span>';
  }
  else if(userresponseobj.userresponse ==  'disagree')
  {
    str += '<span class="iThink_actionLinkDisagree">Disagreed</span>';
  }
  else if(userresponseobj.userresponse ==  'opined')
  {
    str += '<span class="iThink_generalBoldBlackText">Already Opined</span>';
  }
  else if(userresponseobj.userresponse ==  'deleted')
  {
    str += '<span class="iThink_generalBoldBlackText"> Opinion Deleted</span>';
  }
  if(getGlobalParams('container')=="hi5")
  {
		    persistUserResponse();
  }
  if((userresponseobj.userresponse ==  'agree' || userresponseobj.userresponse ==  'disagree' )&& feedPushedInLast24hrs == 'yes')
  {
	 if(getGlobalParams('container') == 'hi5')
	 {
	   activityUpdateVoteOnOpinion(userresponseobj.opinionid, userresponseobj.statement, userresponseobj.userresponse);
     }
	 else if(getGlobalParams('container') == 'myspace')
     {
	    sendMSBulletinOnOpinionResponse(userresponseobj.opinionid, userresponseobj.statement , userresponseobj.userresponse);
	 }
	 if(getGlobalParams('container') == 'orkut')
	 {
	   activityUpdateVoteOnOpinion(userresponseobj.opinionid, userresponseobj.statement, userresponseobj.userresponse);
     }
  }
  var responseElement = document.getElementById('os_opinionresponse_'+userresponseobj.opinionid+'_'+id);
  responseElement.innerHTML = str;

}

function doFollowAction(type,userid,divid)
{
  var faction = '';
  var ftype = '&ftype=people';
  var foruserid = '&foruserid='+getLoggedInUserId();
  var touserid = '&touserid='+userid;
  var id = '';
  if(divid != null)
  {
  	id = '&divid='+divid;
  }

  switch(type)
  {
    case 'set':
    faction = '&faction=set';
    break;
    case 'unset':
    faction = '&faction=unset';
    break;
  }
  var tempid = 'user_follow';
  if(divid != null)
  {
    tempid = 'user_follow'+divid;
  }

  document.getElementById(tempid).innerHTML = '<img src="'+msMinekeyImageBase+'/loader.gif" width="16" height="16"/>';

  var link = msMinekeyWSUrl+'&layout=user&action=followeract&calltype='+getGlobalParams('network')+ftype+foruserid+touserid+faction+id;
  os_makeRequest(link,handleReceivedFollowActionRequest);
}

function handleReceivedFollowActionRequest(responseData)
{
  var response = parseData(responseData.data);
  if(response == null) return;
  extractCommonData(response);
  var divid = response.followersActRes.divid;
  var id = 'user_follow';
  var tempId = '';
  if(divid != null)
  {
    id = 'user_follow'+divid;
    tempId = ',\''+divid+'\'';
  }

  if(response.followersActRes.success1 == 1)
  {
    switch(response.followersActRes.actionRequested)
    {
    case 'set':
	  if(getGlobalParams('container') == 'hi5')
	  {
	    activityUpdateFollowingAction(response.followersActRes.touser,response.followersActRes.foruser);
	    //Pankaj :: it seems that parallel calls are not working, so i moved notification function in call back of activity function.
	  }
	  if(getGlobalParams('container') == 'orkut')
	  {
	    activityUpdateFollowingAction(response.followersActRes.touser,response.followersActRes.foruser);
	    //Pankaj :: it seems that parallel calls are not working, so i moved notification function in call back of activity function.
	  }
	  if(getGlobalParams('container') == 'myspace')
	  {
	    //sendMSBulletinAutoFollow(response.followersActRes.touser,response.followersActRes.foruser);
	  }
	  document.getElementById(id).innerHTML = '<img src="'+msMinekeyImageBase+'/ithink_follow.gif" width="16" height="16"/><a href="javascript:doFollowAction(\'unset\',\''+response.followersActRes.touser+'\''+tempId+')" class="iThink_mainContentLink">unfollow</a>';
	  break;
    case 'unset':
	    document.getElementById(id).innerHTML = '<img src="'+msMinekeyImageBase+'/ithink_follow.gif" width="16" height="16"/><a href="javascript:doFollowAction(\'set\',\''+response.followersActRes.touser+'\''+tempId+')" class="iThink_mainContentLink">follow </a>';
	    //<div id="'+id+'" style="display:inline">
  	break;
    }
  }
}

function gotoOpinionWithMessage(opinionid, msg)
{
	var network = getGlobalParams('container');
	if(msg == null)
	  msg = '';
	var appParams = { calltype : ''+network,opinionid : ''+opinionid, layout : 'theopinion',action:'detail', msg : ''+msg};
	var link =  getLinkPrefix() + convertAppParams(appParams);
    gotoUrl(link);
}
function gotoUserProfileAction(userid, action, msg){
  if(action == null && action == '')
  {
     action = 'summary';
  }
  if(msg == null) msg = '';
  var network = getGlobalParams('container');
  var layout = 'userprofile';
  if(userid == getLoggedInUserId())
  {
    var layout = 'myopinion';
  }
  var appParams = { calltype : ''+network,creatorid : ''+userid, layout : ''+layout,action:action,msg : ''+msg};
  var link =  getLinkPrefix() + convertAppParams(appParams);
  gotoUrl(link);
  if(getGlobalParams('container') == 'orkut')
  {
    var link =  orkutLinkPrefix + convertAppParams(appParams);
    gotoUrl(link);
  }
}
function gotoCanvas(appParams, extraParams)
{
	var lastPageParams = getAllAppParams();
	if(appParams["layout"] == "theopinion" && lastPageParams["layout"] == "theopinion" && appParams["opinionid"] == lastPageParams["opinionid"])
	{
		appParams["lastpage"] = lastPageParams["lastpage"];
	}
	else
	{
		if(lastPageParams != null) lastPageParams["lastpage"] = null;
		if(lastPageParams["debugmode"])
		{
			appParams["debugmode"] = true;
			appParams["debuguserid"] = lastPageParams["debuguserid"];
		}
		appParams["lastpage"] = lastPageParams;
	}
	if(!(appParams["creatorid"]))
		appParams["creatorid"] = ''+getParams('creatorid');
	if(appParams["layout"]=='myopinions')
		appParams["creatorid"] = ''+getLoggedInUserId()	;

	//alert("calling = "+osGlobalNotificationText);
	if(getGlobalNotificationText())
	  appParams["osNotificationText"] = getGlobalNotificationText();
   	if(extraParams != null)
	{
      for(prop in extraParams)
      {
        appParams[prop] = extraParams[prop];
	  }
	}
	var linkPrefix = getLinkPrefix();
    var link = linkPrefix + convertAppParams(appParams);
    gotoUrl(link);
}

/* Functions below are specific to share opinion functionality and these are not generic function so don;t change them */

function doCheck(id,checkbox)
{
 var element  = document.getElementById(id);
 var network = getGlobalParams('container');
 if(network == 'friendster')
 {
   var tempId  = document.getElementById(id);
   if(checkbox == 'false')
   {
     if(tempId.checked)
     {
       tempId.checked = true;
     }
     else
     {
       tempId.checked = false;
     }
   }
   else
   {
	   if(tempId.checked != true)
	   {
	     tempId.checked=true;
	   }
	   else
	   {
	     tempId.checked=false;
	   }
   }
   return;
}
   for(i=1;i<=friendsIds.length;i++)
   {
     var tempId  = document.getElementById(i);
	 if(i != id)
     {
       if(network == 'myspace')
       {
         tempId.checked = false;
       }
     }
     else
     {
       if(checkbox == 'false')
       {
         if(tempId.checked)
         {
	       tempId.checked = true;
	     }
	     else
	     {
	       tempId.checked = false;
	     }
	   }
	   else
	   {
	     if(network == 'myspace')
	     {
	       tempId.checked=true;
		 }
		 else
		 {
		   if(tempId.checked != true)
           {
     	     tempId.checked=true;
           }
           else
           {
     	     tempId.checked=false;
           }
		 }
	   }
     }
   }
}

function checkAll()
{
  var field = document.myform.list;
  for (i = 0; i < field.length; i++)
    field[i].checked = true ;
}

function uncheckAll()
{
  var field = document.myform.list;
  for (i = 0; i < field.length; i++)
  field[i].checked = false ;
}

function getFriendsListBox() {
  var req = opensocial.newDataRequest();
  req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
   var allFriends = {};
   allFriends[opensocial.DataRequest.PeopleRequestFields.FIRST] = 0;
   allFriends[opensocial.DataRequest.PeopleRequestFields.MAX] = 200;
   if(getGlobalParams('container') == 'orkut')
   {
     allFriends[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.HAS_APP;
   }

  req.add(req.newFetchPeopleRequest('VIEWER_FRIENDS',allFriends), 'viewerFriends');
  req.send(onLoadFriends);
}

function onLoadFriends(data)
{
  var viewer = data.get('viewer').getData();
  var viewerFriends = data.get('viewerFriends').getData();
  var count = 1;
  var str = '';
  var checked = 'checked';
  if(getGlobalParams('container') == 'myspace')
  {
   checked = '';
  }
  var checkOnlyOne = 'false';
  if(getGlobalParams('container') == 'myspace')
  {
     checkOnlyOne = 'true';
  }
  viewerFriends.each(function(person) {
  friendsIds.push(person.getId());
  friendsName.push(person.getDisplayName());
  friendsObject.push(person);
	str += '<div style="margin: 5px; padding: 5px; float: left; height: 60px; width: 200px;">';
 	str += '<a href="javascript:doCheck('+count+');"><img src="'+person.getField(opensocial.Person.Field.THUMBNAIL_URL)+'" class="imageBorderGrey" style="float: left; margin-left: 5px;" border="0" height="50" width="50"></a>';
 	str += '<span onClick="javascript:doCheck('+count+',\''+checkOnlyOne+'\');"><input id = '+count+' type="checkbox" name="list" value="'+person.getId()+'"'+checked+'></span>';
 	str += '&nbsp;<a class="iThink_mainContentLink" style="cursor:pointer;" href="javascript:doCheck('+count+');">'+person.getDisplayName()+'</a>';
 	str += '</div>';
 	if(count % 3 == 0 )
 	{
 		str += '<div style="clear: both;"></div>';
 	}
 	count++;
  });
  if(count == 2)
  {
      var viewerId = getProcessedId(msGlobalViewerInfo.getField(opensocial.Person.Field.ID));
      var viewerName = msGlobalViewerInfo.getDisplayName();
      var okUserImage = msGlobalViewerInfo['getImageUrl'];
    str += '<div style="margin: 5px; padding: 5px; float: left; height: 60px; width: 200px;">';
 	str += '<a href="javascript:doCheck('+count+');"><img src="'+okUserImage+'" class="imageBorderGrey" style="float: left; margin-left: 5px;" border="0" height="50" width="50"></a>';
 	str += '<span onClick="javascript:doCheck('+count+',\''+checkOnlyOne+'\');"><input id = '+count+' type="checkbox" name="list" value="'+viewerId+'"'+checked+'></span>';
 	str += '&nbsp;<a class="iThink_mainContentLink" style="cursor:pointer;" href="javascript:doCheck('+count+');">'+viewerName+'</a>';
 	str += '</div>';
  }
  document.getElementById('friendslist').innerHTML = str;
}

function submitShareForm(opid,opstatement)
{
    document.getElementById("os_share_loading2").innerHTML = '&nbsp;&nbsp;<img src="'+msMinekeyImageBase+'loader.gif"/>';
    document.getElementById("os_share_loading1").innerHTML =   '&nbsp;&nbsp;<img src="'+msMinekeyImageBase+'loader.gif"/>';
    if(!checkAppInstalled())
	{
		promptAppInstall();
		return;
	}
	if(friendsIds.length < 1 && getGlobalParams('container') != 'friendster')
	{
	  alert('You must have atleast one friend to share opinion with!');
      gotoOpinionPageUrl(opid);
      return;
	}

	shareOpinionId = opid;
	var values = new Array();
	var maxListSize = 100;
	var recipients = new Array();
	var j = 0;
	var total = 0;
	var selectedIndex;
	if(typeof document.myform.list.length == "undefined")
	{
	  total = 1;
      values.push(friendsIds[0]);
      selectedIndex = 0;
	}
	else
	{
	  total = document.myform.list.length;
      for(var i = 0; i < total; i++)
	  {
		if(document.myform.list[i].checked == true)
		{
			values.push(document.myform.list[i].value);
			selectedIndex = i;
		}
	  }
	}
	total = values.length;
    friendCount = total;
	if(total == 0)
	{
	  alert('Please select atleast one friend to share opinion with!');
	  document.getElementById("os_share_loading2").innerHTML = '';
      document.getElementById("os_share_loading1").innerHTML =  '';
	  return;
	}
	var start = 0, end = 0;
	if(total > maxListSize)
	{
	  start = Math.ceil(total*Math.random());
	  end = (start + maxListSize)%total;
	}
	else
	{
	  start = 0;
	  end = total-1;
	}
	if(start<=end)
	{
	  for(var i = start; i <= end; i++)
	  {
	    recipients.push(values[i]);
	  }
	}
	else
	{
	  for(var i = start; i != end; i = (i+1)%total)
	  {
	    recipients.push(values[i]);
	  }
	}
	recipientsArray = recipients;
	trackOpinionSharing(opid,recipients);
 	if(getGlobalParams('container') == 'hi5')
	{
      sendNotificationOnShareOpinion(opid,opstatement,recipients);
        if(!isTFD())
        {
           setTimeout(gotoSharedOpinion,5000);
        }
	}
	else if(getGlobalParams('container') == 'myspace')
	{
      sendMSMessageOnShareOpinion(opid,opstatement,selectedIndex);
    }
    else if(getGlobalParams('container') == 'orkut')
	{
      //activityUpdateShareOpinion(opstatement,opid,friendCount,recipients);
      gotoOpinionWithMessage(opid,4);
      /*
	  if(!isTFD())
      {
        setTimeout(gotoSharedOpinion,5000);
      }
      */
    }
}

function submitInviteForm()
{
	if(!checkAppInstalled())
	{
		promptAppInstall();
		return;
	}
	var values = new Array();
	var maxListSize = 500;
	var recipients = new Array();
	var j = 0;
	var total = document.myform.list.length;
	var selectedIndex;
	for(var i = 0; i <total; i++)
	{
		if(document.myform.list[i].checked == true) {
			values.push(document.myform.list[i].value);
			selectedIndex = i;
		}
	}
    total = values.length;
    friendCount = total;
	if(total == 0)
	{
	  alert('Please select atleast one friend to share opinion with!');
	  return;
	}
	var start = 0, end = 0;
	if(total > maxListSize)
	{
	  start = Math.ceil(total*Math.random());
	  end = (start + maxListSize)%total;
	}
	else
	{
	  start = 0;
	  end = total-1;
	}
	if(start<=end)
	{
	  for(var i = start; i <= end; i++)
	  {
	    recipients.push(values[i]);
	  }
	}
	else
	{
	  for(var i = start; i != end; i = (i+1)%total)
	  {
	    recipients.push(values[i]);
	  }
	}
	recipientsArray = recipients;
 	if(getGlobalParams('container') == 'hi5')
	{
      //sendNotificationOnShareOpinion(opid,opstatement,recipients);
      // activity update function is inside handler of sendNotification and then redirect to theopinionpage
	}
	else if(getGlobalParams('container') == 'myspace')
	{
      sendMSMessageOnInvite(selectedIndex);
    }
}
function gotoSharedOpinion()
{
    if(currentOpinionId != null && currentOpinionId > 0) gotoOpinionPageUrl(currentOpinionId);
	else if(shareOpinionId != null && shareOpinionId > 0) gotoOpinionPageUrl(shareOpinionId);
	else gotoLastPage();
}

function renderNotfication(type,optional_text,functionName)
{
  if(!(functionName))
  {
    functionName = "gotoLastPage";
  }
//  alert(functionName);
  var notificationHtml = '';
  var noti_text = '';

  if(type=='share')
  {
    noti_text = 'The opinion has been shared.';
  }
  else if (type == 'autofollow')
  {
    noti_text = optional_text;
  }
  else if(type=='error')
  {
    noti_text = 'Error! Please try again later';
  }
  noti_text = getGlobalNotificationText();
  var replacement_text = '<a href="javascript:gotoLayout(\'invite\')" class="iThink_opinionTitleLinkSmall">click here</a> to invite them now.';
  noti_text = noti_text.replace("click here to invite",replacement_text);
  notificationHtml +=
    '<table width="'+(osNotificationWidth)+'" border="0" align="left" cellpadding="0" cellspacing="0">'+
    '<tr>'+
    '<td width="1" height="1" class="iThink_OrangeFill"></td>'+
    '<td width="97%" class="iThink_OrangeFill"></td>'+
    '<td width="1" class="iThink_OrangeFill"></td>'+
    '<td width="260"></td>'+
    '</tr>'+
    '<tr>'+
    '<td class="iThink_OrangeFill" width="1"></td>'+
    '<td height="50" class="iThink_lightOrangeFill" width="'+osNotificationWidth+'"><table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">'+
    '<tr>'+
    '<td><div align="center" class="iThink_generalBoldGreyText">'+noti_text+'</div></td>'+
    '</tr>'+
    '</table></td>'+
    '<td width="1" class="iThink_OrangeFill"></td>'+
    '</tr>'+
    '<tr>'+
    '<td height="1" class="iThink_OrangeFill"></td>'+
    '<td class="iThink_OrangeFill"></td>'+
    '<td class="iThink_OrangeFill"></td>'+
    '<td></td>'+
    '</tr><br/><br/>'+
    '</table>';
  document.getElementById('notification_text').innerHTML = notificationHtml;
  /*if(type!='error' && currentOpinionId != null) gotoOpinionPageUrl(currentOpinionId);
  if(type!='error')
  {
    setTimeout(functionName,3000);
  }*/
  setTimeout(hideNotificationBox,15000);
}

function hideNotificationBox()
{
  setGlobalNotificationText('');
  document.getElementById('notification_text').innerHTML = '';
}

function set_help_text(input, helptxt) {
  var inp = document.getElementById(input);
  var helptext = helptxt;
  inp.value=helptext;
  inp.style.color='gray';
}

function getpreview(content) {

  previewDiv = content+'_preview';
  element = document.getElementById(previewDiv);
  previewText = '';
  if (content == 'category') {
    previewText = document.getElementById(content).childNodes;
    index = document.getElementById(content).selectedIndex;
    previewText = previewText[index].id;
    //console.log(previewText[index].getId()+"---"+previewText[index].getName());
  } else if (content == 'comment') {
    previewText = document.getElementById(content).value;
    previewText = previewText.replace(/\s+/g,' ');
    previewText = wordwrap(previewText.substr(0,85),45,'\n',true);
    //      previewText = trimAll(previewText);
    if(previewText=="") previewText ="Your reason comes in here";
  } else if (content=="tags") {
    previewText = document.getElementById(content).value;
    var pattern = /\s*\,\s*/;
    previewText = previewText.replace(/\s+/g,',').replace(/\,+/g,',').replace(/\s*\,\s*/g,',');
    previewText = wordwrap(previewText,90,'\n',true);
    splitText = previewText.split(pattern);
    element.innerHTML='';
    for(i=0;i<splitText.length;i++) {
      if (i != (splitText.length - 1))
	splitText[i] += ', ';
      if(splitText[i] !="") {
	var ele = document.createElement('div');
	ele.innerHTML = '<a hohref class="iThink_mainContentLink">'+splitText[i]+'</a>';
	ele.style.display = 'inline';
	ele.style.paddingLeft = '3px' ;
	//ele.href = 'nohref';
	//console.log(splitText[i]);
	element.appendChild(ele);
      }
    }
    if(previewText == "") {
      var ele = document.createElement('div');
      ele.innerHTML = '<a hohref class="iThink_mainContentLink">Topic 1,</a>';
      ele.style.display = 'inline';
      ele.style.paddingLeft = '3px' ;
      element.appendChild(ele);

      ele = document.createElement('div');
      ele.innerHTML = '<a hohref class="iThink_mainContentLink">Topic 2,</a>';
      ele.style.display = 'inline';
      ele.style.paddingLeft = '3px' ;
      element.appendChild(ele);

      ele = document.createElement('div');
      ele.innerHTML = '<a hohref class="iThink_mainContentLink">More topics</a>';
      ele.style.display = 'inline';
      ele.style.paddingLeft = '3px' ;
      element.appendChild(ele);


    }
  }else if(content=="statement"){
    previewText = document.getElementById(content).value ;
    previewText = previewText.replace(/\s+/g,' ');
    previewText = '<a nohref class="iThink_mainOpinionLink">'+wordwrap(previewText,65,'\n',true)+'</a>';
//    previewText = wordwrap(previewText,65,'\n',true);
  //  alert(previewText);
    if(previewText == '<a nohref class="iThink_mainOpinionLink"></a>') {
      previewText = '<a nohref class="iThink_mainOpinionLink">Your statement comes in here</a>';
      // bebwakuf hi5 was having some issues -jonty
    }
  }
  if(content !="tags") element.innerHTML= previewText;
  //showOpinionPreview();
}

function textLimit(div, max_chars, wall_errid) {
  var contents = div.value;
  if(contents.length < max_chars) {
    document.getElementById(wall_errid).style.color='black';
    var charLeft = max_chars-contents.length;
    document.getElementById(wall_errid).innerHTML = charLeft+' characters left';
  }
  if(contents.length > max_chars) {
    document.getElementById(wall_errid).style.color='red';
    var charLeft = contents.length-max_chars;
    div.value = contents.substr(0,max_chars);
    document.getElementById(wall_errid).innerHTML = "Character limit reached.";
  }
  if (contents.length==max_chars) {
    document.getElementById(wall_errid).style.color = 'red';
    document.getElementById(wall_errid).innerHTML = "Character limit reached.";
  }
}

function validate_form(thisform)
{
alert(thisform.reportabuseComment.value.length);
with (thisform)
{

if (thisform.reportabuseComment.value.length == 0)
  {
  alert("The comment Box is empty.");
  reportabuseComment.focus();
  return false;
  }
  else
  {
  return true;
  }
}
}

function ReportAbuse()
 {
   opinionid = document.reportabuse.opinionid.value;
   abuse_type = document.reportabuse.abuse_type.value;
   foruserid = document.reportabuse.foruserid.value;
   message = document.reportabuse.reportabuseComment.value;
   message = trim(message);
   if(message != '')
   {
      message = removeSpecialChars(message);
   }
   if(message == '')
   {
     alert('Comment field can not be left blank');
   }
   else
   {
     creatorid = document.reportabuse.creatorid.value;
     if(abuse_type=='user')
	 opinionid=0;
     //comment = removeSpecialChars(message);
    var postParams = {opinionid : ''+opinionid,abuse_type: ''+abuse_type, foruserid : ''+foruserid, creatorid : ''+creatorid, message: ''+message};
    var wsUrl = msMinekeyWSUrl + '&layout=opinion&action=reportabuse';
    document.getElementById('os_posting_comment').innerHTML = '&nbsp;&nbsp;<img src="'+msMinekeyImageBase+'loader.gif"/>';
    os_postDataRequest(wsUrl, postParams, handleReportAbuse) ;
   }
}

function handleReportAbuse(responseData, url, error)
{
    var response = parseData(responseData.data);
    if(response == null) return;
    extractCommonData(response);
    var opinionid = response.reportabuse.opinionid;
    var abuse_type = response.reportabuse.abuse_type;
    var foruserid = response.reportabuse.foruserid;
    if(abuse_type =='opinion' && response.reportabuse.success)
    {
      //alert("Successfull reported for abuse");
      var network = getGlobalParams('container');
	  var appParams = { calltype : ''+network,opinionid : ''+opinionid, layout : 'theopinion',action:'detail',msg : '9'};

	  gotoCanvas(appParams);
    }
    if(abuse_type =='user' && response.reportabuse.success)
    {
      //alert("Successfull reported for abuse");
      var network = getGlobalParams('container');
	  var appParams = { calltype : ''+network,creatorid : ''+foruserid, layout : 'userprofile',action:'summary',msg : '10'};

	  gotoCanvas(appParams);
    }

}

 function ValidateCreateOpinionForm(formObj) {
   var err = 0;
   stmtmsg = "";
   tagsmsg = "";
   commentmsg = "";

   stmt = document.getElementById('statement').value;
   stmt = stmt.replace(/^\s+|\s+$/, '');
   if (stmt == "" || stmt == "Add your opinion here (required).") {
     err = 1;
     stmtmsg = "Please Enter Opinion Statement.";
   }

   tags = document.getElementById('tags').value;
   tags.replace(/^\s+|\s+$/, '');
   if (tags == "" || tags == "Add topics so that your opinions can be found easily (optional).")  tags = '';
   comment = document.getElementById('comment').value;
   comment = comment.replace(/^\s+|\s+$/, '');
   if(comment=="Adding good comments increases response to your opinion (optional).") comment = "";

   categoryid = document.getElementById('category').value;

   if (err==0)
   {
     stmt = removeSpecialChars(stmt);
     tags = removeSpecialChars(tags);
     comment = removeSpecialChars(comment);
     createOpinionStatement = stmt;
     var posturl = msMinekeyWSUrl + '&layout=opinion&action=create&';
     posturl += 'categoryid=' + ((categoryid == '') ? '1' : categoryid);
     var postParams = { opinionstatement: stmt, opiniontags: tags , opinioncomment: comment};
     document.getElementById('os_posting_comment').innerHTML = '&nbsp;&nbsp;<img src="'+msMinekeyImageBase+'loader.gif"/>';
     os_postDataRequest(posturl, postParams, handleCreatedOpinion) ;
   }
   else {
     document.getElementById('os_error_message').innerHTML = stmtmsg ;
   }
 }

function ddumpObject(obj, name, maxDepth, curDepth)
{
	if (curDepth == undefined)
		curDepth = 0;
	if (maxDepth != undefined && curDepth > maxDepth)
		return;

	var i = 0;
	for (prop in obj)
	{
		i++;
		if (typeof(obj[prop]) == "object")
		{
			if (obj[prop] && obj[prop].length != undefined)
				ddump(name + "." + prop + "=[probably array, length "
						+ obj[prop].length + "]");
			else
				ddump(name + "." + prop + "=[" + typeof(obj[prop]) + "]");
			ddumpObject(obj[prop], name + "." + prop, maxDepth, curDepth+1);
		}
		else if (typeof(obj[prop]) == "function")
		{}//ddump(name + "." + prop + "=[function]");
		else
			ddump(name + "." + prop + "=" + obj[prop]);
	}
	if (!i)
		ddump(name + " is empty");
}

function ddump(objtext)
{
	document.getElementById('os_debugblock').innerHTML += objtext + '<br/>';
}



function handleCreatedOpinion(responseData, url, error)
{
    var response = parseData(responseData.data);
    if(response == null) return;
    extractCommonData(response);
    var opinionid = response.opinionCreate.createdopinionid;
    var statement = response.opinionCreate.statement;
    if(opinionid == null || opinionid <=0)
    {
      document.getElementById('os_createopinionbutton').innerHTML = '&nbsp;&nbsp;error&nbsp;&nbsp;';
      return;
    }
//    createOpinionId = opinionid;
    setGlobalOpinionId(opinionid);

    if(getGlobalParams('container') == 'hi5')
	{
      createParallelActivityCount = 1;
      activityUpdateCreateopinion(opinionid,statement);
      activityPersist(opinionid);
      setTimeout(callOnAllParallelActivityFinish,5000);
	}
	else if(getGlobalParams('container') == 'orkut')
	{
      //createParallelActivityCount = 1;
      activityUpdateCreateopinion(opinionid,statement);
      //activityPersist(opinionid);
      setTimeout(callOnAllParallelActivityFinish,5000);
	}
	else
	{
	  var theopinionParams = { layout : 'share', action : 'share' , opinionid : ''+opinionid};
      var link = getLinkPrefix() + convertAppParams(theopinionParams);
      gotoUrl(link);
	}
}

function gotoHomePageUrl(opinionid)
{
  var opinionParams = { layout : 'opinion'};
  var link = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId="+osApplicationId+"&appParams=" + convertAppParams(opinionParams);
  gotoUrl(link);
}

function gotoOpinionPageUrl(opinionid,paramList)
{
    if(!paramList)
    {
      var theopinionParams = { calltype : getGlobalParams('network'), layout : 'theopinion', action : 'detail' , opinionid : opinionid+''};
    }
    else
    {
      var theopinionParams = paramList;
    }
  var linkPrefix = getLinkPrefix();
  var link = linkPrefix + convertAppParams(theopinionParams);
  gotoUrl(link);
}

function gotoOpinionLayout()
{
  var theopinionParams = { calltype : getGlobalParams('network'), layout : 'opinion'};
  var linkPrefix = getLinkPrefix();
  var link = linkPrefix + convertAppParams(theopinionParams);
  gotoUrl(link);
}

function getLinkPrefix(){
    if(getGlobalParams('container') == 'myspace') return myspaceLinkPrefix;
    if(getGlobalParams('container') == 'hi5') return hi5LinkPrefix;;
    if(getGlobalParams('container') == 'friendster') return friendsterLinkPrefix;
    if(getGlobalParams('container') == 'orkut') return orkutLinkPrefix;
    return friendsterLinkPrefix;
}

function gotoOpinionSharePageUrl(opinionid)
{
  if(opinionid == null || opinionid <= 0) opinionid = createOpinionId;
  var theopinionParams = { layout : 'share', action : 'share' , opinionid : ''+opinionid};
  var linkPrefix = getLinkPrefix();
  var link = linkPrefix + convertAppParams(theopinionParams);
  gotoUrl(link);
}

function os_postDataRequest(postUrl, postParams, callBack, params)
{
    justCalledUrl = postUrl;
    currentCallBack = callBack;
    currentRequestType = 'POST';
    currentPostParams = postParams;
    if(getGlobalParams('container') == 'friendster')
	{
		my_postDataRequest(postUrl+'&timestamp='+currentTimestamp(), postParams, callBack, params);
		return;
	}
	if(getParams("debugmode"))
	{
		postUrl += "&debugmode=true";
		postUrl += "&debuguserid=" + getParams("debuguserid");
	}
	if(params == null)
	{
		var params = {};
	}
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
    params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
	switch(getGlobalParams('container'))
	{
		case 'myspace':
            params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
            params[gadgets.io.RequestParameters.POST_DATA] = postParams;
            break;
        case 'hi5':
            params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
            try{
                    for (propertyName in postParams) {
                            params[propertyName] = postParams[propertyName];
                            postUrl += '&'+propertyName+'='+escape(params[propertyName])+'';
                    }
            } catch(err){}
            break;
         case 'orkut':
            params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
            params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(postParams);
            postUrl += "&gadgetViewer="+getLoggedInUserId()+"&gadgetOwner="+getLoggedInUserId();
           break;
        }
	gadgets.io.makeRequest(postUrl+'&timestamp='+currentTimestamp(), callBack, params);
}


function fetchAdminReportAbuse(actionTaken,foruserid,opinionid,creatorid)
{
 if(opinionid=='')
 	opinionid=0;
 var wsUrl = msMinekeyWSUrl+ '?layout=opinion&action=adminaction&calltype='+getGlobalParams('network')+'&opinionid='+opinionid+'&foruserid='+foruserid+'&creatorid='+creatorid+'&actionTaken='+actionTaken;
if(opinionid>0)
  {
  if(actionTaken=='delete')
 	 var answer = confirm ("Deleting will remove this opinion from Minekey and all activity connected to it permanently. Do you want to delete this opinion?")
  else
 	 var answer = confirm ("After ignoring report abuse you will not able to delete this opinion from Minekey and all activity connected to it permanently. Do you want to ignore reported abuse for this opinion?")
 }
 else
 {
 if(actionTaken=='delete')
 	var answer = confirm ("Deleting will remove this user from Minekey and all activity connected to it permanently. Do you want to delete this user?")
 else
 	var answer = confirm ("After ignoring report abuse you will not able to ban this user from Minekey and all activity connected to it permanently. Do you want to ignore reported abuse for this user?")

}
    if (!answer)
    {
      //return false;
    }
    else
    {
      os_makeRequest(wsUrl, handleAdminReportAbuse);
    }
}

function handleAdminReportAbuse(responseData, url, error)
{
  var response = parseData(responseData.data);
  if(response == null) return;
  var action = response.adminaction;
  if(action.success == false)
  {//alert("shail4")
    //document.getElementById('os_createcommentbutton').innerHTML = '&nbsp;&nbsp;error&nbsp;&nbsp;';
    //return;
  }
  else
  {//actionTaken
  	var network = getGlobalParams('container');
	if(action.type=='opinion')
	{
		if(action.actionTaken=='deleted')
			var appParams = { calltype : ''+network,creatorid : ''+action.reporteduserid, layout : 'userprofile',action:'summary',msg : '11'};
		else
			var appParams = { calltype : ''+network,creatorid : ''+action.reporteduserid, layout : 'userprofile',action:'summary',msg : '12'};

	}
	else
	{
		if(action.actionTaken=='deleted')
			var appParams = { calltype : ''+network,creatorid : ''+action.admin, layout : 'myopinion',action:'list',acttype: 'added',msg : '13'};
    	else
    		var appParams = { calltype : ''+network,creatorid : ''+action.admin, layout : 'myopinion',action:'list',acttype: 'added',msg : '14'};

	}

	gotoCanvas(appParams);

  }
}

function deleteOpinion(opinionid,foruserid)
{
 var wsUrl = msMinekeyWSUrl+ '?layout=opinion&action=delete&calltype='+getGlobalParams('network')+'&opinionid='+opinionid+'&foruserid='+foruserid;

  var answer = confirm ("Deleting will remove this opinion from Minekey and all activity connected to it permanently. Do you want to delete this opinion?")
    if (!answer)
    {

      //return false;
    }
    else
    {
      var posturl = msMinekeyWSUrl + '&layout=opinion&action=delete&';

      posturl += 'opinionid='+opinionid+'&';
      posturl += 'foruserid='+foruserid;

      var postParams = {};
      os_makeRequest(posturl, handleDeletedOpinion);
    }
}

function handleDeletedOpinion(responseData, url, error)
{
  var response = parseData(responseData.data);
  if(response == null) return;
  var opinionDeleteObj = response.deleteOpinion;
  var userid = opinionDeleteObj.userid;
  if(opinionDeleteObj.success == false)
  {
    //document.getElementById('os_createcommentbutton').innerHTML = '&nbsp;&nbsp;error&nbsp;&nbsp;';
    //return;
  }
  else
  {
  	var network = getGlobalParams('container');
	var appParams = { calltype : ''+network,creatorid : ''+userid, layout : 'myopinion',action:'list',acttype: 'added',msg : '8'};

	gotoCanvas(appParams);
  }
}


function deleteNote(walltype,wallid,postid,actionUserId,associatedid)
{
  var answer = confirm ("Deleting will remove this post from Minekey and all activity connected to it permanently. Do you want to delete this post?")
    if (!answer)
    {
    }
    else
    {
      var posturl = msMinekeyWSUrl + '&layout=wall&action=delete&';
      posturl += 'actionuserid='+actionUserId+'&';
      posturl += 'walltype='+ walltype+'&';
      posturl += 'wallid='+ wallid+'&';
      posturl += 'associatedid='+associatedid+'&';
      posturl += 'postid='+postid;
      var postParams = {};
      os_makeRequest(posturl, handleDeletedComment);
    }
}

function handleDeletedComment(responseData, url, error)
{
    var response = parseData(responseData.data);
    if(response == null) return;
    extractCommonData(response);
  var wallpostobj = response.wallPostDeleted;
  if(wallpostobj.success == false)
  {
  }
  else
  {
    var elem = 'note_'+wallpostobj.postid;
    document.getElementById(elem).innerHTML = showSuccessMsg('The post has been deleted.');
    document.getElementById(elem).style.align = 'center';
    setTimeout(function(){hide(elem)},3000);
  }
}

function createComment(walltype, wallid, associatedid, commentDivId, defaultValue)
{
	if(!checkAppInstalled())
	{
		promptAppInstall();
		return;
	}
	var posturl = msMinekeyWSUrl + '&layout=wall&action=create&';
	var content = document.getElementById(commentDivId).value.replace(/^\s+|\s+$/, '');
	content = (content == "add your comments...") ? "" : content;

	if(content == '' || wallid == '' || content == defaultValue)
	{
		 if(walltype == 'user')
		 {
		   document.getElementById('os_posting_comment').innerHTML = '<div class="generalText" style="color:red;">&nbsp;&nbsp;Please enter your note!</div>';
         }
         else
         {
           document.getElementById('os_posting_comment').innerHTML = '<div class="generalText" style="color:red;">&nbsp;&nbsp;Please enter your comments!</div>';
         }
		 return;
	}
	document.getElementById('os_posting_comment').innerHTML = '&nbsp;&nbsp;<img src="'+msMinekeyImageBase+'loader.gif"/>';
//frosty commenting out till its working fine
//	var hrefElement = document.getElementById('osNotePostLink');
    //hrefElement.innerHTML = '<a href="#" class="iThink_buttonLink"> Post</a>';

    posturl += 'associatedid='+ associatedid+'&';
    posturl += 'walltype='+ walltype+'&';
    posturl += 'wallid='+ wallid;
    var postParams = { content: content};
	os_postDataRequest(posturl, postParams, handleCreatedComment);
}

function handleCreatedComment(responseData, url, error)
{
    var response = parseData(responseData.data);
    if(response == null) return;
    extractCommonData(response);
    var wallpostobj = response.wallPostCreated;
    persistWallType=wallpostobj.walltype;
    persistAssociatedId=wallpostobj.associatedid;
    persistCreatorId=wallpostobj.creatorid;
    persistComment=wallpostobj.opstatement;
    if(persistWallType == 'opinion')
    {
      if(getGlobalParams('container') == 'hi5' && getLoggedInUserId() != wallpostobj.creatorid)
	  {
         activityUpdateCommentOnOpinion(persistAssociatedId,wallpostobj.opstatement,wallpostobj.creatorid);
         persistCommenting();
         setTimeout(gotoOpinionAfterNoti,setTimeOutValue);
	  }
	  else if(getGlobalParams('container') == 'orkut' && getLoggedInUserId() != wallpostobj.creatorid)
      {
         activityUpdateCommentOnOpinion(persistAssociatedId,wallpostobj.opstatement,wallpostobj.creatorid);
         setTimeout(gotoOpinionAfterNoti,setTimeOutValue);
	  }
	  else
	  {
	     gotoOpinionWithMessage(persistAssociatedId, 2);
	  }
    }
    else
    {
       if(getGlobalParams('container') == 'hi5' && getLoggedInUserId() != wallpostobj.associatedid)
       {
            activityUpdateCommentOnUser(wallpostobj.content,wallpostobj.associatedid);
       }
       else if(getGlobalParams('container') == 'orkut' && getLoggedInUserId() != wallpostobj.associatedid)
       {
           activityUpdateCommentOnUser(wallpostobj.content,wallpostobj.associatedid);
       }
       else
       {
          gotoUserProfileAction(wallpostobj.associatedid, 'notes',7);
       }
    }
}

function hideSuccessMsg()
{
  var element = document.getElementById('os_success_msg');
  element.style.visibility = 'hidden';
}
function hide(elementid){
  document.getElementById(elementid).style.display = 'none';
my_adjustHeight();
}
function show(elementid){
  document.getElementById(elementid).style.display = 'block';
my_adjustHeight();
}

function showSuccessMsg(msg)
{
  var str =
'<table width="400px" height="50px" border="0" align="center" cellpadding="0" cellspacing="0" style="background-color: #fdf1d7;">'+
  '<tr>'+
    '<td colspan="4" style="background-color: #EBAE7F; height:1px;"></td>'+
  '</tr>'+
  '<tr>'+
    '<td style="background-color: #EBAE7F; width:1px;"></td>'+
    '<td colspan="2">&nbsp;</td>'+
    '<td style="background-color: #EBAE7F; width:1px;"></td>'+
  '</tr>'+
  '<tr>'+
    '<td style="background-color: #EBAE7F; width:1px;"></td>'+
    '<td width="20px;"></td>'+
    '<td class="generalText" align="center" style="font-size:15px;">'+msg+'</td>'+
    '<td style="background-color: #EBAE7F; width:1px;"></td>'+
  '</tr>'+
  '<tr>'+
    '<td style="background-color: #EBAE7F; width:1px;"></td>'+
    '<td colspan="2">&nbsp;</td>'+
    '<td style="background-color: #EBAE7F; width:1px;"></td>'+
  '</tr>'+
  '<tr>'+
    '<td colspan="4" style="background-color: #EBAE7F; height:1px;"></td>'+
  '</tr>'+
'</table><br>';
return str;
}


function detectKeyAndExecute()
{
  document.onkeyup= keyup;
  function keyup(e) {
    var keyId = (window.event) ? event.keyCode : e.keyCode;
    if(keyId != 13) return;
    searchOpinion('os_search_text')
  }
}
function ChangeNoteOrder(opinionid,id)
{
var commentOrder=document.getElementById(id).value;
var paramsList = { layout : 'theopinion', action : 'detail' , opinionid : ''+opinionid, sort : commentOrder};
gotoOpinionPageUrl(opinionid,paramsList);
return false;
}


function wordwrap( str, int_width, str_break, cut ) {
    var m = int_width, b = str_break, c = cut;
    var i, j, l, s, r;

    if(m < 1) {
        return str;
    }
    for(i = -1, l = (r = str.split("\n")).length; ++i < l; r[i] += s) {
        for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : "")){
            j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
        }
    }

    return r.join("\n");
}

function followOpinion(opinionid,following, userid) {
	var posturl = msMinekeyWSUrl + '&layout=opinion&action=followeract&calltype='+getGlobalParams('network')+'&';
	posturl += 'faction='+following+"&ftype=opinion&followid="+opinionid+"&foruserid="+userid;

	document.getElementById("followLink").innerHTML='<img src="'+msMinekeyImageBase+'/loader.gif" width="16" height="16"/>';;
	var postparams = {};
	os_postDataRequest(posturl,postparams,handleFollowOpinion);


}

function handleFollowOpinion(responseData) {
   var response = parseData(responseData.data);
  if(response == null) return;
  extractCommonData(response);

 if(response.followersActRes.success1 && response.followersActRes.success2 && response.followersActRes.success3){
	 if(response.followersActRes.actionRequested=='set') {
		 document.getElementById("followLink").innerHTML ='<a href="javascript:followOpinion('+response.followersActRes.followopinionid+',\'unset\','+response.followersActRes.foruser+');" class="iThink_mainContentLink">unfollow opinion</a>';
	 } else {
		 document.getElementById("followLink").innerHTML ='<a href="javascript:followOpinion('+response.followersActRes.followopinionid+',\'set\','+response.followersActRes.foruser+');" class="iThink_mainContentLink">follow opinion</a>';
 }
 }
}

function activityPersist(opinionid) {

  var req = opensocial.newDataRequest();


  var owner = msGlobalViewerInfo;
  if(msGlobalAppInfo == null || msGlobalAppInfo === null) {
    req.add(req.newUpdatePersonAppDataRequest("OWNER","activity0",createPersistenceString("create",''+createOpinionId,createOpinionStatement,owner.getField(opensocial.Person.Field.THUMBNAIL_URL),owner.getId())));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","opinion_counter",''+1));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","top_counter",''+0));

  }else {
    var myCounter = msGlobalAppInfo["opinion_counter"];
    if(isNaN(myCounter)) {
      myCounter=''+1;
    }

    pstring = createPersistenceString("create",''+createOpinionId,createOpinionStatement,owner.getField(opensocial.Person.Field.THUMBNAIL_URL),owner.getId());
    alert("pstring="+pstring);
    req.add(req.newUpdatePersonAppDataRequest("OWNER","activity"+myCounter,createPersistenceString("create",''+createOpinionId,createOpinionStatement,owner.getField(opensocial.Person.Field.THUMBNAIL_URL),owner.getId())));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","opinion_counter",''+(myCounter+1)%3));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","top_counter",''+myCounter));
  }
  req.send(handlePersistingActivity);
}

function createPersistenceString(type,id,text,profilePic_url,profile_id) {
  var str='';
  str +='type='+type+"&&id="+id+'&&text='+ text+'&&profilepic='+profilePic_url+'&&profileid='+profile_id;
  return str;
}

function handlePersistingActivity(response) {
  createParallelActivityCount--;
  alert("activity count = "+createParallelActivityCount);
  if(createParallelActivityCount == 0)
  {
    callOnAllParallelActivityFinish();
  }
}

function callOnAllParallelActivityFinish()
{
 gotoOpinionPageUrl(getGlobalParams('opinionid'));
}

function followOpinion(opinionid,following, userid) {
	var posturl = msMinekeyWSUrl + '&layout=opinion&action=followeract&';
	posturl += 'faction='+following+"&ftype=opinion&followid="+opinionid+"&foruserid="+userid;
	document.getElementById("followLink").innerHTML='<span class="iThink_mainContentLink">updating...</span>';
	var postparams = {};
	os_postDataRequest(posturl,postparams,handleFollowOpinion);


}

function trackOpinionSharing(opinionid,receipients) {
	var posturl = msMinekeyWSUrl + '&layout=opinion&action=sharetrack&opinionid='+opinionid;
	//posturl += '&touserids=';
/*
	for(var i=0;i<receipients.length;i++){
		posturl+= receipients[i];
		if(i< receipients.length-1) {
			posturl += ',';
		}
	}
*/
	posturl += '';
	var postParams = {touserids : ''+ receipients};
	os_postDataRequest(posturl,postParams,handleTrackOpinionSharing);
}

function handleTrackOpinionSharing(response){
    if(getGlobalParams('container') == 'friendster')
	{
      gotoOpinionWithMessage(shareOpinionId,4);
    }
}

function activityPersist(opinionid) {

  var req = opensocial.newDataRequest();


  var owner = msGlobalViewerInfo;
  if(msGlobalAppInfo == null || msGlobalAppInfo === null) {
    req.add(req.newUpdatePersonAppDataRequest("OWNER","activity0",createPersistenceString("create",''+createOpinionId,createOpinionStatement,owner.getField(opensocial.Person.Field.THUMBNAIL_URL),owner.getId())));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","opinion_counter",''+1));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","top_counter",''+0));

  }else {
    var myCounter = msGlobalAppInfo["opinion_counter"];
    if(isNaN(myCounter)) {
      myCounter=''+1;
    }

    pstring = createPersistenceString("create",''+createOpinionId,createOpinionStatement,owner.getField(opensocial.Person.Field.THUMBNAIL_URL),owner.getId());
    req.add(req.newUpdatePersonAppDataRequest("OWNER","activity"+myCounter,createPersistenceString("create",''+createOpinionId,createOpinionStatement,owner.getField(opensocial.Person.Field.THUMBNAIL_URL),owner.getId())));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","opinion_counter",''+(myCounter+1)%3));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","top_counter",''+myCounter));
  }

  req.send(handlePersistingActivity);

}
function createPersistenceString(type,id,text,profilePic_url,profile_id) {
  var str='';
  str +='type='+type+"&&id="+id+'&&text='+ text+'&&profilepic='+profilePic_url+'&&profileid='+profile_id;
  return str;
}

function handlePersistingActivity(response) {
}


function persistUserResponse() {
  var req = opensocial.newDataRequest();
  if(msGlobalAppInfo == null || msGlobalAppInfo === null) {
    req.add(req.newUpdatePersonAppDataRequest("OWNER","activity0",createPersistenceString("vote",''+createOpinionId,createOpinionStatement,getUserProfileImageURL(opinionCreatorId),opinionCreatorId)));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","opinion_counter",''+1));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","top_counter",''+0));
    msGlobalAppInfo = new Object;
    msGlobalAppInfo['opinion_counter']=1;

  }else {
    var myCounter = msGlobalAppInfo["opinion_counter"];
    if(isNaN(myCounter)) {
      myCounter=''+1;
    }
    req.add(req.newUpdatePersonAppDataRequest("OWNER","activity"+myCounter,createPersistenceString("vote",''+createOpinionId,createOpinionStatement,getUserProfileImageURL(opinionCreatorId),opinionCreatorId)));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","opinion_counter",''+(myCounter+1)%3));
    req.add(req.newUpdatePersonAppDataRequest("OWNER","top_counter",''+myCounter));
    msGlobalAppInfo['opinion_counter']=(myCounter+1)%3;
  }
  req.send(handlePersistingVote);
}

function handlePersistingVote(response) {
}

function persistCommenting(){
	var req = opensocial.newDataRequest();
	var actType=null;
	switch(persistWallType) {
		case 'user': actType='commentUser';break;
		case 'opinion': actType="commentOpinion";break;
	}
	if(msGlobalAppInfo == null || msGlobalAppInfo === null) {
		req.add(req.newUpdatePersonAppDataRequest("OWNER","activity0",createPersistenceString(actType,''+persistAssociatedId,persistComment,getUserProfileImageURL(persistCreatorId),persistCreatorId)));
		req.add(req.newUpdatePersonAppDataRequest("OWNER","opinion_counter",''+1));
			req.add(req.newUpdatePersonAppDataRequest("OWNER","top_counter",''+0));

	}else {
		var myCounter = msGlobalAppInfo["opinion_counter"];
		if(isNaN(myCounter)) {
			myCounter=''+1;
		}
		req.add(req.newUpdatePersonAppDataRequest("OWNER","activity"+myCounter,createPersistenceString(actType,''+persistAssociatedId,persistComment,getUserProfileImageURL(persistCreatorId),persistCreatorId)));
		req.add(req.newUpdatePersonAppDataRequest("OWNER","opinion_counter",''+(myCounter+1)%3));
		req.add(req.newUpdatePersonAppDataRequest("OWNER","top_counter",''+myCounter));
	}

	req.send(handlePersistingComment);
}

function handlePersistingComment(response) {
}
function getUserProfileImageURL(userid) {
	return (msUserProfileBasics[userid] == null) ? '' : msUserProfileBasics[userid].imageurl;
}

function changeOpinionFilter(userid,id,layout)
{
  var addedOpinionFilter = document.getElementById(id).value;
  var paramsList = { layout : layout, action : 'list' , acttype : 'added', type : addedOpinionFilter, creatorid : userid};
  gotoUserProfilePageUrl(userid,layout,paramsList);
}

function gotoUserProfilePageUrl(userid,layout,paramList)
{
  if(!paramList)
  {
    var userprofileParams = { layout : layout, action : 'summary' , creatorid : userid};
  }
  else
  {
    var userprofileParams = paramList;
  }
  var link = getLinkPrefix() +convertAppParams(userprofileParams);
  gotoUrl(link);
}

function trim(inputString)
{
  if (typeof inputString != "string") { return inputString; }
  var retValue = inputString;
  var ch = retValue.substring(0, 1);
  while (ch == " ") {
     retValue = retValue.substring(1, retValue.length);
     ch = retValue.substring(0, 1);
  }
  ch = retValue.substring(retValue.length-1, retValue.length);
  while (ch == " ") {
     retValue = retValue.substring(0, retValue.length-1);
     ch = retValue.substring(retValue.length-1, retValue.length);
  }
  while (retValue.indexOf("  ") != -1) {
     retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
  }
  return retValue;
}

function gotoOpinionBoardWithMessage(msg)
{
	var network = getGlobalParams('container');
	if(msg == null)
	  msg = '';
	var appParams = { calltype : ''+network,layout : 'opinion', msg : ''+msg};
	var link =  getLinkPrefix() + convertAppParams(appParams);
    gotoUrl(link);
}
