
/**
 *  Fetch Request(Normal) from cinemas application
 */
function Cinemas(){
  var container = null;
}

var ctr;
// user's persistence data
var viewerPdata = {};
var total_friends;
var v_profile_url;
var viewr_id;
var isOVSame;
var viewerInstallApp;
Cinemas.fetchGETRequest = function (url,opt_params,container){
  showSpinner();
  ctr = container;
  var params = {};
  params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
  var qm = url.indexOf('?');
  if(qm >=0)
  {
  	var link = url+"&us_id="+u_id.toString();
  }
  else
  {
  	var link = url+"?us_id="+u_id.toString();	
  }
  var link1 = [link, "&appId=",getAppId()].join('');
  gadgets.io.makeRequest(link1,respGET,params)
  
}

Cinemas.makeSubmitForm = function (url,container,postdata){
  showSpinner();
  ctr = container;
  var params = {};
  
  params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
  params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(postdata);
  
  var qm = url.indexOf('?');
  if(qm >=0)
  {
  	var link = url+"&us_id="+u_id.toString();
  }
  else
  {
  	var link = url+"?us_id="+u_id.toString();	
  }
   var link1 = [link, "&appId=",getAppId()].join('');
  gadgets.io.makeRequest(link1,respGET,params);
}

Cinemas.sendInvite = function (appName) {
  var params = [];
  
  //Title of the Invitation Message
  params[opensocial.Message.Field.TITLE]=appName +" on Orkut!!";
  
  //Body with application link URL
  var body=createAppLink();
  var message = opensocial.newMessage(body, params);
  
  //send invitation message
  opensocial.requestSendMessage(opensocial.DataRequest.Group.OWNER_FRIENDS, message,handlesendmsg);
}

// Sends Notification / Private Message to user friends
Cinemas.sendNotification = function (donate_url, container, msg_div_id, title_div_id) {
	// Set the DOM element to be reloaded after sending notification
	ctr = container;
	
	var params = {};
	var title_div = document.getElementById(title_div_id);
	var msg_div = document.getElementById(msg_div_id);
	if(title_div)
		var title = title_div.innerHTML;	
	else
		var title = " ";
	if(msg_div)
		var msg = msg_div.innerHTML;	
	else
		var msg = " ";
	params[opensocial.Message.Field.TITLE] = title;
    params[opensocial.Message.Field.TYPE] = opensocial.Message.Type.PRIVATE_MESSAGE;
	
	// Body of the private message
	app_url = createAppCanvasLink();
	html = msg;
	html += app_url;
	
	var body = html;
	var message = opensocial.newMessage(body, params);
	
	var idspec = opensocial.newIdSpec({
	               "userId" : "OWNER", 
				   "groupId" : "FRIENDS" 
				  });
	// Recipients - Owner friends
	var recipient = "OWNER_FRIENDS";
	
	// Send private message
	opensocial.requestSendMessage(recipient, message, onSendNotification);
}

/**
 * Iterate through form elements and create a JSON formatted parameters.
 * Submit formdata to the remote server using postRequest of the Opensocial
 */
function submitFormData(myForm, url) {
		elements = myForm.elements;
		
		var params = {};		
		
		for(i = 0; i < elements.length; i++ ) {
		  if( elements[i].type == "radio" && elements[i].checked == true) {
		    params[elements[i].name] = gadgets.util.escapeString(elements[i].value);
		  }
		  else if( elements[i].type == "checkbox" && elements[i].checked == true ){
		    params[elements[i].name] = gadgets.util.escapeString(elements[i].value);
		  }
		  else if( elements[i].type == "text" || elements[i].type == "textarea" || elements[i].type == "hidden" ) {
		    params[elements[i].name] = gadgets.util.escapeString(elements[i].value);
		  }
		  else if( elements[i].type == "select-one" ) {
		    params[elements[i].name] = gadgets.util.escapeString(elements[i].value);
		  }
		  else if( elements[i].type == "select-multiple" ) {
		    var selected = new Array();
			for( j= 0; j < elements[i].length; j++ ) {
			  if( elements[i].options[j].selected )
			    selected.push(gadgets.util.escapeString(elements[i].options[j].value));
			}
			params[elements[i].name] = selected;
		  }
		  else if( elements[i].type == "file") {
		  }
		}
		
		Cinemas.makeSubmitForm(url,'main_container',params);
}

Cinemas.goToCanvasView = function (isO_V_same,viewrInstallApp){
    //var canvas_view = new gadgets.views.View("canvas");
    //gadgets.views.requestNavigateTo(canvas_view);
    if(isOVSame == true) //Owner and Viewer same
	{
		var canvas_view = new gadgets.views.View("canvas");
		gadgets.views.requestNavigateTo(canvas_view);
	}
	else // Owner and Viewer different
	{
		if(!viewerInstallApp){ // Viewer has not installed the app
			app_id = getAppId();
			url = createAppLink();
			window.top.location = url;
		}
		else { // Viewer already installed the app
			app_id = getAppId();
			viewer_UID = getOUid(v_profile_url);
			url = getAppCanvasUrl();
			window.top.location = url;
		}
	}
}

Cinemas.fetchPOSTRequest = function(url,container){
  showSpinner();
  ctr = container;
  var params = {};
  var postdata = {
       us_id : u_id.toString(),
	   appId : getAppId().toString(),
	   friend_list : friendsList
  };
  
  params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
  params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(postdata);
  
  gadgets.io.makeRequest(link1,respGET,params)
}

Cinemas.showVideo = function (url, container){
  gadgets.flash.embedFlash(url, container, {
      swf_version: 6,
      id: "flashid",
      width: 280,
      height: 250
    });
}

function respGET(obj){
   document.getElementById(ctr).innerHTML = obj.text;
   
   var vdo = document.getElementById('vdo_url')
   if(vdo)
   {
     try{
       playVideo(vdo.value, 'videoP');
	 }catch(e){}
   }
  
   var friends = document.getElementById('_grp_friends');
   if(friends)
   {
     try{
       showFriends();
	 }catch(e){}
   }
   
   //Check if the div id="corners123" exists
   //If it does process it. 
   //After processing, replace that div with empty string in dom.
   //so that if another action is going to insert the same div, then there will not be a conflict.
   var cinemas_update = document.getElementById('corner123');
   if(cinemas_update)
   {
     try{
       processReturnData(cinemas_update);
     }catch(e){}
   }
   
   // Post Updates to user friends on the activity of user
   // Updates are posted for - adding video/photo as favorite, writing review.
   var post_update = document.getElementById('post_activity');
   if(post_update) {
      try {
	     postAnUpdate(post_update);
	  }catch(e){}
   }
   
   hideSpinner();
   
   gadgets.window.adjustHeight();
}

function playVideo(url, container){
  vdo_ebd_flsh = document.getElementById('vdo_ebd_flsh')
  if(vdo_ebd_flsh) {
	  // Handles Yupp TV videos
	  emb = '<embed width="100%" height="100%" wmode="transparent" type="application/x-shockwave-flash" flashvars="'+vdo_ebd_flsh.value+'" src="'+url+' />';
	  document.getElementById(container).innerHTML = emb;
  }
  else {
	  gadgets.flash.embedFlash(url, container, {
	      swf_version: 6,
	      id: "flashid",
	      wmode: "transparent",
	      width: 300,
	      height: 250
	    });
  }
}

function showFriends() {
     var params = {};
     
     if(document.getElementById('_f_see_all'))
	   fTotal = 100
	 else
	   fTotal = 4;
	   
     params[opensocial.DataRequest.PeopleRequestFields.MAX] = fTotal;
     params[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.HAS_APP;
     params[opensocial.DataRequest.PeopleRequestFields.SORT_ORDER] = opensocial.DataRequest.SortOrder.NAME;
	 
	 var specs = opensocial.newIdSpec({ "userId" : "OWNER", "groupId" : "FRIENDS" });

     var req = opensocial.newDataRequest();
     req.add(req.newFetchPeopleRequest(specs, params), 'viewerFriends');
     req.send(handleShowFriends);
}

function handleShowFriends(resp) {
     if (!resp.hadError()) { // always verify whether your request was successful
        var viewerFriends = resp.get('viewerFriends').getData(); 
        
		var frnd_prof_url;
		if(document.getElementById('frnd_prof_url'))
		  frnd_prof_url = document.getElementById('frnd_prof_url').value;
		
		counter = 0;
		if(document.getElementById('_f_see_all'))
	      per_line = 6;
	    else
	      per_line = 2;
		
        total_friends = viewerFriends.getTotalSize();
        html = new Array();
	
        fCtr = 0;
        html.push('<div style="float:left;width:15px;">&nbsp;</div>');
        viewerFriends.each( // each() method is used to iterate through every object in collection
            function(person) {
              
			  counter += 1;
			  
			  html.push('<div style="float:left;width:83px;">');
              html.push('<div class="fbphoto">');
			  
			  if(frnd_prof_url)
			  {
			    fr_u = frnd_prof_url+'?id='+person.getId();
				cn = 'main_container';
			    html.push('<a href="javascript:void(0)" onclick="Cinemas.fetchGETRequest(\''+fr_u+'\',null,\''+cn+'\')">');
			  }
			  
			  html.push('<img class="fbimage" src="'+person.getField(opensocial.Person.Field.THUMBNAIL_URL)+'" border="0"/>');
			  
			  if(frnd_prof_url)
			    html.push('</a>');
			  
			  html.push('</div>');
		      html.push('<div align="left" style="font:bold 12px Arial;color:#0F8DBC;" >'+person.getDisplayName()+'</div>');
		      html.push('</div>');
            
			  if(counter % per_line == 0) {
			     html.push('<div style="clear:both;"></div>');
				 html.push('<div style="float:left;width:15px;">&nbsp;</div>');
			  }
			
            });
        html.push('<div style="clear:both;"></div>');
        document.getElementById('_grp_friends').innerHTML = html.join('');
     }
	 
	 gadgets.window.adjustHeight();
}

//Initialize persistence data for user
function initializePData(friends){
    var preq = opensocial.newDataRequest();

    preq.add(preq.newUpdatePersonAppDataRequest("VIEWER", "moviesCtr", 0));
    preq.add(preq.newUpdatePersonAppDataRequest("VIEWER", "actorsCtr", 0));
    preq.add(preq.newUpdatePersonAppDataRequest("VIEWER", "frndsOnApp", friends));

    preq.send(function (){});
}

function updatePesistenceData(movies, actors){
    var preq = opensocial.newDataRequest();
    
    if(viewerPdata['moviesCtr'] != movies)
      preq.add(preq.newUpdatePersonAppDataRequest("VIEWER", "moviesCtr", movies));
    if(viewerPdata['actorsCtr'] != actors)
      preq.add(preq.newUpdatePersonAppDataRequest("VIEWER", "actorsCtr", actors));
    if(viewerPdata['frndsOnApp'] != total_friends)
      preq.add(preq.newUpdatePersonAppDataRequest("VIEWER", "frndsOnApp", total_friends));
    
    preq.send(function (){});
}

function startCreatingActivity() {
   // Post Updates to user friends on the activity of user
   // Updates are posted for - adding video/photo as favorite, writing review.
   var post_update = document.getElementById('post_activity1');
   if(post_update) {
      try {
	     postAnUpdate(post_update);
	  }catch(e){}
   }
}

function postAnUpdate(act_div) {
	var activities = act_div.getElementsByTagName("input");
	var actTitle;
	var actBody = new Array();
	actBody.push('<div style="font-size:12px;color:#02679C;">');
	for(var i = 0; i < activities.length; i++ ) {
	  if( activities[i].id == "cr_act_title" ) {
	     actTitle = activities[i].value;
	  }
	  else if( activities[i].id == "cr_act_img" ) {
	     if (activities[i].value && activities[i].value != "" ) {
			 actBody.push('<div style="float:left;padding:1px 5px;">');
			 actBody.push('<a href="/Application.aspx?appId='+getAppId()+'">');
			 actBody.push('<img src="'+activities[i].value+'" border="0" style="width:72px;height:68px;"/>');
			 actBody.push('</a>');
			 actBody.push('</div>');
		 }
	  }
	  else if( activities[i].id == "cr_act_desc" ) {
	     actBody.push('<div style="float:left;padding:1px 5px;width:365px;">');
		 actBody.push('<div style="padding-top:10px;overflow:hidden;">');
		 actBody.push('<span style="color:#02679C;">'+activities[i].value+'</span>')
		 actBody.push('</div>');
		 actBody.push('</div>');
	  }
	  else if( activities[i].id == "cr_act_type" ) {
	     
	  }
	}
	actBody.push('<div style="clear:both;"></div>')
	actBody.push('</div>');
	postActivity(actTitle,actBody.join(''));
}

function postActivity(title,message){
    var params = {};
    params[opensocial.Activity.Field.TITLE] = title;
	params[opensocial.Activity.Field.BODY] = message;
    var activity = opensocial.newActivity(params);
    opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function() {});
}

function processReturnData(update_div){
    var activities =  update_div.getElementsByTagName("input");
    var removeDiv = 0;
    for(var i=0; i < activities.length; i++){
       if(activities[i].id == "activity"){
           postActivity(activities[i].value,"");
	   }
       else if(activities[i].id == "delete_div"){
           removeDiv = 1;
       }
	   else if(activities[i].id == "intProfileDirty"){
	       var preq = opensocial.newDataRequest();
		   preq.add(preq.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER,"intProfileDirty",1));
		   preq.add(preq.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER,"strProfileView",null));
		   preq.send(function (){});
	   }
    }
	
    if(removeDiv == 1)
    {
      parent = update_div.parentNode
      parent.removeChild(update_div);
    }
}

function submit_review_form(url)
{
	if(validateTitle('review_title', 'response_review_title') == true){
		var postdata = {
			    review_id : document.getElementById('review_id').value,
			    review_title : gadgets.util.escapeString(document.getElementById('review_title').value),
			    post_area : gadgets.util.escapeString(document.getElementById('post_area').value)
	    };  
	    
	    Cinemas.makeSubmitForm(url,'main_container',postdata);
	}
	else
	{
		hideSpinner();
		return false;
	}
}

function submit_new_review_form(url)
{
	if((validateTitle('review_title', 'review_editor_error') == true) && (validateTitle('review_blurb', 'review_editor_error') == true)){
		
			var postdata = {
			    review_title : gadgets.util.escapeString(document.getElementById('review_title').value),
			    post_area : gadgets.util.escapeString(document.getElementById('review_blurb').value)
	    	};  
	    
	    	Cinemas.makeSubmitForm(url,'main_container',postdata);
	}
	else
	{
			hideSpinner();
			window.setTimeout("hide_msg('review_editor_error')", 4000);
			return false;
	}
}

function hide_msg()
{
	for(var i=0;i<arguments.length;i++)
	{
		var field = document.getElementById(arguments[i]);
		if(field)
			field.style.display = "none";
	}
}

function reviews_show_editor_inline(elem)
{
	toggle(document.getElementById(elem));
}

function toggle()
{
	for(var i=0;i<arguments.length;i++)
	{
		var element=arguments[i];
		if(element.style.display == "")
			element.style.display = 'none'
		element.style.display=element.style.display=='block'?'none':'block';
	}
	return false;
}

function submit_mymovies_search_form(url)
{
	var postdata = {
		    ctype : document.getElementById('ctype').value,
		    movie_name : document.getElementById('movie_name').value
    };  
    
    Cinemas.makeSubmitForm(url,'main_container',postdata);
}

function submit_save_apps_settings_form(url)
{
    profile_u = document.getElementById("profile_to_allusers");
    profile_value = "1"
    if(!profile_u.checked)
    {
        profile_value = "0"
    }
    
    scrap_read_no = document.getElementById("scrap_read_no");
    scrap_read_value = "1"
    if(scrap_read_no.checked)
    {
        scrap_read_value = "0"
    }
    
    scrap_write_all = document.getElementById("scrap_write_all");
    scrap_write_value = "1"
    if(!scrap_write_all.checked)
    {
        scrap_write_value = "0"
    }
    
    notification = document.getElementById("notification");
    if(notification.checked)
    {
        var postdata = {
			    profile : profile_value,
			    notification: "on",
			    scrap_read : scrap_read_value,
			    scrap_write: scrap_write_value
	    };
    }
	else
	{
		var postdata = {
			    profile : profile_value,
			    scrap_read : scrap_read_value,
			    scrap_write: scrap_write_value
	    };
	}      
    
    Cinemas.makeSubmitForm(url,'main_container',postdata);
        
}

function submit_myactors_search_form(url)
{
	var postdata = {
		    ctype : document.getElementById('ctype').value,
		    actor_name : document.getElementById('actor_name').value
    };  
    
    Cinemas.makeSubmitForm(url,'main_container',postdata);
}

function submit_vote_form(url)
{
	var tt = validateVote()
	if(tt == true)
	{
		var postdata = {
			    group_id : document.getElementById('group_id').value,
			    group_title : document.getElementById('group_title').value,
			    group_no	: document.getElementById('group_no').value,
				noms		: document.getElementById('updatevote').value,
				vote_comment : document.getElementById('vote_comment').value
	    };  
	    
	    Cinemas.makeSubmitForm(url,'main_container',postdata);
	}    
}

function updateVote(corner_id)
{
	updatevote = document.getElementById('updatevote');
	if(updatevote != null)
	{
		document.getElementById('updatevote').value = corner_id;
		document.getElementById('error_msg').style.display = "none";
	}
}

function validateVote()
{
        vote = document.getElementById('updatevote');
        if( vote != null && vote.value != null && vote.value != "" && vote.value != " " ) 
        {
            return true;
        }    
        else
        {
            document.getElementById('error_msg').style.display = "block";
            return false;
        }    
}

function submit_addF8Ractors_search_form(url)
{
	var postdata = {
		    ctype : document.getElementById('ctype').value,
		    search_query : document.getElementById('search_query').value
    };  
    
    Cinemas.makeSubmitForm(url,'main_container',postdata);
}

function createAppLink(){
   app_id = getAppId();
   if(gadgets.util.getUrlParameters()["parent"].match(/friendster/) != null){
	   return [ "http://www.friendster.com/widget_add.php?api_key=",
				 gadgets.util.getUrlParameters()["appName"],"&src=canvas"].join("");
	}
	else{
	   return [ gadgets.util.getUrlParameters()["parent"], 
				 "/AppInfo.aspx?appId=",
				 app_id].join("");
	}
}

function handlesendmsg(resp){
  if(resp.hadError()){
	  html = new Array();
	  html.push('<div>Your Message has been successfully send</div>');
  }
}

function submit_new_topic_form(url)
{
	if(validateTitle('topic_title', 'response_topic_title') == true && validateTitle('post_area', 'response_post_area') == true){
		var postdata = {
			    forum_id : document.getElementById('forum_id').value,
			    topic_title : gadgets.util.escapeString(document.getElementById('topic_title').value),
			    post_area : gadgets.util.escapeString(document.getElementById('post_area').value)
	    };  
	    
	    Cinemas.makeSubmitForm(url,'main_container',postdata);
	}
	else
	{
		hideSpinner();
		return false;
	}

}

function submit_new_topic_post_form(url)
{
	if(validateTitle('post_area', 'response_post_area') == true){
		var postdata = {
		    hidden_topic_id : document.getElementById('hidden_topic_id').value,
		    hidden_post_area : gadgets.util.escapeString(document.getElementById('hidden_post_area').value),
		    post_subject : gadgets.util.escapeString(document.getElementById('post_subject').value),
		    post_area : gadgets.util.escapeString(document.getElementById('post_area').value)
		};  
	    
		Cinemas.makeSubmitForm(url,'main_container',postdata); 
	}
	else
	{
       	hideSpinner();
		return false;
	}

}

function validateTitle(validateElem, msgElem)
{
        var title = document.getElementById(validateElem);
        var msg_elem = document.getElementById(msgElem);
	  if( title == null || title.value == "") 
        {
		if(msg_elem != null)
            	msg_elem.style.display = "block";    
            return false;
        }    
        else
        {
		if(msg_elem != null)
            	msg_elem.style.display = "none";
            return true;
        }    
}

function getOUid(profile_url){
    var regex = /uid=([^&#]+)/;
    var result = profile_url.match(regex);
    if (result && result.length == 2) {
      var uid = result[1];
      return uid;
    } else {
      /* there was a problem getting the UID */
      return "";
    }
}

function getAppId(){
    if(opensocial.getEnvironment().getDomain() == "friendster.com"){
		return gadgets.util.getUrlParameters()["aid"];
	}
    else if(opensocial.getEnvironment().getDomain() == "orkut.com") {
	    return gadgets.util.getUrlParameters()["gadgetId"];
	}
	else {
		var prefs = new gadgets.Prefs();
		app_id = prefs.getModuleId();
		return app_id;
	}
}

function getAppCanvasUrl(){
	app_id = getAppId();
    viewer_UID = getOUid(v_profile_url);
    if(gadgets.util.getUrlParameters()["parent"].match(/friendster/) != null){
	  return [ "http://widgets.friendster.com",
			    "/", gadgets.util.getUrlParameters()["appName"]].join("");
	}
	else
	{
	  return [ gadgets.util.getUrlParameters()["parent"],
			    "/Application.aspx?appId=", app_id, "&uid=", viewer_UID].join("");
	}
}

function getViewName(){
    return gadgets.views.getCurrentView().getName();
}

function showSpinner(){
     var spinnerDiv = document.getElementById('spinner');
	 spinnerDiv.style.display = 'block';
}

function hideSpinner(){
     var spinnerDiv = document.getElementById('spinner');
	 spinnerDiv.style.display = 'none';
}

function validateIMG() {
   returnvalue = true;
   
   chkbx   = document.getElementById('tos').getChecked();
   file    = document.getElementById('photo').getValue();
   err_div = document.getElementById('error_div');
   
   str = "";
   if( chkbx != true )
   {
      str += "Please check the TOS checkbox.";
   }
   if( file == "" || file == " " )
   {
      str += "Browse and select a photo to upload.";
   } 
   
   if(chkbx != true || file == "" || file == " ")
   {
     new Dialog(Dialog.DIALOG_POP).showMessage('TOS', str, button_confirm = "Okay");
     returnvalue = false;
   }
   else
   {
     returnvalue = true;
   }
   
   return returnvalue;
 }
 
  /** Method to Send Scrap form data **/
function submit_scrap_form(url)
   {
  if(validateTitle('scrap_msg', 'resp_scrap_msg') == true){
       var postdata = {
        scrap_msg : gadgets.util.escapeString(document.getElementById('scrap_msg').value),
        receiver_id : document.getElementById('receiver_id').value
       };
    Cinemas.makeSubmitForm(url,'main_container',postdata);
    }
   else
    {
      hideSpinner();
      return false;
    }
   }
 
// Callback for send notification
function onSendNotification(resp) {
  if (!resp.hadError()) {
    msg = "Request sent to friends";
	document.getElementById(ctr).innerHTML = msg
  } else {
    msg = "There was a problem: " + resp.getErrorMessage();
	var  ret_title = document.getElementById("ret_title");
	if(ret_title)
		document.getElementById(ctr).innerHTML = ret_title.innerHTML;
	else
		document.getElementById(ctr).innerHTML = "Bring your Friends";	
	document.getElementById('request_failed').style.display = "block";
	window.setTimeout("fadeOutMsg()", 5000);
  }
}

function fadeOutMsg() {
  document.getElementById('request_failed').style.display = "none";
}

// Returns application's Canvas URl on orkut, Friendster
function createAppCanvasLink(){
   app_id = getAppId();
   if(gadgets.util.getUrlParameters()["parent"].match(/friendster/) != null){
	   return [ "http://widgets.friendster.com/",
				 gadgets.util.getUrlParameters()["appName"]].join("");
	}
	else{
	   return [ gadgets.util.getUrlParameters()["parent"], 
				 "/Main#Application.aspx?appId=",
				 app_id].join("");
	}
}

//classes to store profile data as JSON in persistant storage
var CProfile = function(){
    this._profile.imgurl1 = null;
    this._profile.imgurl2 = null;
    this._profile.imgurl3 = null;
    this._profile.imgurl4 = null;
    this._profile.imgurl5 = null;
    this._profile.imgurl6 = null;
    this._profile.text1 = null;
    this._profile.text2 = null;
    this._profile.text3 = null;
    this._profile.text4 = null;
    this._profile.text5 = null;
    this._profile.text6 = null;
};
 
CProfile.prototype = {
    _profile:{
        imgurl1:null,
        imgurl2:null,
        imgurl3:null,
        imgurl4:null,
        imgurl5:null,
        imgurl6:null,
        text1:null,
        text2:null,
        text3:null,
        text4:null,
        text5:null,
        text6:null
    },
   getImgurl1:function(){
        return this._profile.imgurl1;
    },
   getImgurl2:function(){
        return this._profile.imgurl2;
    },
   getImgurl3:function(){
        return this._profile.imgurl3;
    },
   getImgurl4:function(){
        return this._profile.imgurl4;
    },
   getImgurl5:function(){
        return this._profile.imgurl5;
    },
   getImgurl6:function(){
        return this._profile.imgurl6;
    },
   getText1:function(){
        return this._profile.text1;
   },
   getText2:function(){
        return this._profile.text2;
   },
   getText3:function(){
        return this._profile.text3;
   },
   getText4:function(){
        return this._profile.text4;
   },
   getText5:function(){
        return this._profile.text5;
   },
   getText6:function(){
        return this._profile.text6;
   },
   setImages:function(url1, url2, url3, url4, url5, url6) {
        this._profile.imgurl1 = url1;
        this._profile.imgurl2 = url2;
        this._profile.imgurl3 = url3;
        this._profile.imgurl4 = url4;
        this._profile.imgurl5 = url5;
        this._profile.imgurl6 = url6;
    },
    setTexts:function(text1, text2, text2, text4, text5, text6) {
        this._profile.text1 = text1;
        this._profile.text2 = text2;
        this._profile.text3 = text3;
        this._profile.text4 = text4;
        this._profile.text5 = text5;
        this._profile.text6 = text6;
    },
   
    _updateProfile:function(){
          var request = opensocial.newDataRequest();
		  // Stringify the JSON object and store the escaped string on persistence for Friendster
		  prof_str = gadgets.json.stringify(this._profile);
		  
          request.add(request.newUpdatePersonAppDataRequest(opensocial.IdSpec.PersonId.VIEWER, "profile", prof_str));
          request.send();
    }
};

/***
 * METHODS - To update and load profile view content
 */
function generateProfContent(prfile) {
		html = new Array();
		
		html.push('<div style="padding:5px 8px;float:left;background-color:#EEEEEE;">');
		
		//LEFT SIDE IMAGES
		html.push('<div style="float:left;width:250px;"><div>');
		
		//First image
        html.push('<div style="float:left;width:70px;height:70px;">');
        html.push('<a href="javascript:Cinemas.goToCanvasView(false,false);">');
        html.push('<img border="0" width="70px;" height="70px;" src="' + prfile.imgurl1 + '" />');
        html.push('</a></div><div style="float:left;width:15px;">.</div>');
        
        //Second image
        html.push('<div style="float:left;width:70px;height:70px;">');
        html.push('<a href="javascript:Cinemas.goToCanvasView(false,false);">');
        html.push('<img border="0" width="70px;" height="70px;" src="' + prfile.imgurl2 + '" />');
        html.push('</a></div><div style="float:left;width:15px;">.</div>');
	
	    //Third image
        html.push('<div style="float:left;width:70px;height:70px;">');
        html.push('<a href="javascript:Cinemas.goToCanvasView(false,false);">');
        html.push('<img border="0" width="70px;" height="70px;" src="' + prfile.imgurl3 + '" />');
        html.push('</a></div><div style="clear:both;">.</div></div>');
        
        //NEXT LINE - 3 IMAGES
	    
	    html.push('<div><div style="float:left;width:70px;height:70px;">');
        html.push('<a href="javascript:Cinemas.goToCanvasView(false,false);">');
        html.push('<img border="0" width="70px;" height="70px;" src="' + prfile.imgurl4 + '" />');
        html.push('</a></div><div style="float:left;width:15px;">.</div>');
	
        //Second image
        html.push('<div style="float:left;width:70px;height:70px;">');
        html.push('<a href="javascript:Cinemas.goToCanvasView(false,false);">');
        html.push('<img border="0" width="70px;" height="70px;" src="' + prfile.imgurl5 + '" />');
        html.push('</a></div><div style="float:left;width:15px;">.</div>');
    
        //3rd image
        html.push('<div style="float:left;width:70px;height:70px;">');
        html.push('<a href="javascript:Cinemas.goToCanvasView(false,false);">');
        html.push('<img border="0" width="70px;" height="70px;" src="' + prfile.imgurl6 + '" />');
        html.push('</a></div><div style="clear:both; font-size:4px;">.</div>');
	    html.push('</div></div>');
	    
	    //END LEFT SIDE IMAGES
	    
	    //START RHS TEXT NAMES
	    html.push('<div style="float:left;width:125px;font:11px Arial;" align="left;">');
	    html.push('<div style="padding-top:10px;"><a href="javascript:Cinemas.goToCanvasView(false,false);">' + prfile.text1 + '</a></div>');
		html.push('<div style="padding-top:10px;"><a href="javascript:Cinemas.goToCanvasView(false,false);">' + prfile.text2 + '</a></div>');
		html.push('<div style="padding-top:10px;"><a href="javascript:Cinemas.goToCanvasView(false,false);">' + prfile.text3 + '</a></div>');
		html.push('<div style="padding-top:10px;"><a href="javascript:Cinemas.goToCanvasView(false,false);">' + prfile.text4 + '</a></div>');
		html.push('<div style="padding-top:10px;"><a href="javascript:Cinemas.goToCanvasView(false,false);">' + prfile.text5 + '</a></div>');
		html.push('<div style="padding-top:10px;"><a href="javascript:Cinemas.goToCanvasView(false,false);">' + prfile.text6 + '</a></div>');
	    html.push('</div><div style="clear:both;">.</div>');
	    
		return html.join('');
}
	
function processProfData() {
		var preq = opensocial.newDataRequest();
			   
		var content_count = document.getElementById('content_count');
		if( content_count) {
		     var count;
			 try {
			   count = content_count.value;
			 }catch(e){ count = 6 ;}
			 
			 icon1   = document.getElementById("corner_icon1").value;
			 icon2   = document.getElementById("corner_icon2").value;
			 icon3   = document.getElementById("corner_icon3").value;
			 icon4   = document.getElementById("corner_icon4").value;
			 icon5   = document.getElementById("corner_icon5").value;
			 icon6   = document.getElementById("corner_icon6").value;
			 
			 text1    = document.getElementById("corner_name1").value;
			 text2    = document.getElementById("corner_name2").value;
			 text3    = document.getElementById("corner_name3").value;
			 text4    = document.getElementById("corner_name4").value;
			 text5    = document.getElementById("corner_name5").value;
			 text6    = document.getElementById("corner_name6").value;
			 
			 var profile = new CProfile();
			 profile.setImages(icon1, icon2, icon3, icon4, icon5, icon6); 
			 profile.setTexts(text1, text2, text3, text4, text5, text6);
			 profile._updateProfile(); //Will call newUpdatePersonAppDataRequest
		}
}

function getVwrIdSpec()
{
      var params = {};
      params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;
      var idspec = opensocial.newIdSpec(params);
 
      return idspec;
}

function getOwrIdSpec()
{
      var params = {};
      params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.OWNER;
      var idspec = opensocial.newIdSpec(params);
 
      return idspec;
}
