
/**
 *  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.submitFrndIdsForm = 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();	
  }
  
  alert("in submit frnd id form");
   var link1 = [link, "&appId=",getAppId()].join('');
   gadgets.io.makeRequest(link1,inviteStatus,params);
}

function inviteStatus(obj){
   document.getElementById("invite_status").innerHTML = obj.text;
}


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);
}

//Show list of friends to send invitation to
Cinemas.sendInvite = function (appName) {
  
      var params = [];
  
	  //Title of the Invitation Message
	  params[opensocial.Message.Field.TITLE]= "Send fan mail, frown, wink and more at " + appName;
	  params[opensocial.Message.Field.TYPE] = opensocial.Message.Type.EMAIL; 
	  
	  //Body with application link URL
	  var lnk =createAppLink();
	  var body= "Express your emotions towards " + appName + " with colorful icons. Love, be amused, applaud, yawn, get excited and more...  ";
	  body = body + lnk; 
	  var message = opensocial.newMessage(body, params);
	  
	  //send invitation message
	  opensocial.requestSendMessage("OWNER_FRIENDS", message,handlesendmsg);
	  
	  //Handlemessage will redirect to canvas
}

//Show list of friends to send invitation to
Cinemas.sendExpInvite = function (appName) {
  
      var params = [];
  
	  //Title of the Invitation Message
	  params[opensocial.Message.Field.TITLE]= "Express for your favorite movies, celebs, music, sports";
	  params[opensocial.Message.Field.TYPE] = opensocial.Message.Type.EMAIL; 
	  
	  //Body with application link URL
	  var lnk =createAppLink();
	  var body= "Express your emotions towards your favorite music, movies, artists, celebrities with colorful icons. Love, be amused, applaud, yawn, get excited and more...  ";
	  body = body + lnk; 
	  var message = opensocial.newMessage(body, params);
	  
	  //send invitation message
	  opensocial.requestSendMessage("OWNER_FRIENDS", message,handleExpsendmsg);
	  
	  //Handlemessage will redirect to canvas
}

//This should be fully implemented after requestShareApp is added to Orkut
//Currently it is not.
function inviteFriends(pagnum)
{
    //Do nothing.
}


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;
		}
	}
}

var notify_title;
var notify_msg;
var _app_cr_name;
// Notify friends about an expression
Cinemas.forwardToFriends = function (title, msg, corner_name, user_name ) {
	var params = {};
	
	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 = user_name + " wrote on " + corner_name + "\n" + msg + "\n";
	html += "To find more go to " + 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, onForwardNotification);
}

// Sends Notification / Private Message to user friends
Cinemas.sendNotification = function (donate_url, corner_name, container) {
	// Set the DOM element to be reloaded after sending notification
	ctr = container;
	
	var params = {};
	
	params[opensocial.Message.Field.TITLE] = "Create colorful expressions for "+corner_name;
    params[opensocial.Message.Field.TYPE] = opensocial.Message.Type.PRIVATE_MESSAGE;
	
	// Body of the private message
	app_url = createAppCanvasLink();
	html = "Love, smile, frown, wink, shower petals at "+ corner_name +". using colorful expressions.\n";
	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);
}

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('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){}
   }
   
   // Update Profile data of user on first visit to index into persistence.
   var u_prof_data = document.getElementById('profile_view');
   if(u_prof_data)
   {
       //Store the Profile view content to Persistent data
	   try{
	     processProfData();
	   }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();
}

// Callback for send notification
function onForwardNotification(resp) {
  hidn_div = document.getElementById('_notify_fwd');
  
  if (!resp.hadError()) {
  	if( hidn_div != null )
       hidn_div.style.display = "block";
  } else {
    if( hidn_div != null )
    {
	    msg = "There was a problem: " + resp.getErrorMessage();
		document.getElementById('_notify_fwd').innerHTML = "Try again later!"
		document.getElementById('_notify_fwd').style.display = "block";
    }
  }
}


// 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();
	document.getElementById(ctr).innerHTML = "Ask Friends to Help";
	document.getElementById('request_failed').style.display = "block";
	window.setTimeout("fadeOutMsg()", 5000);
  }
}

function fadeOutMsg() {
  document.getElementById('request_failed').style.display = "none;";
}

function playVideo(url, container){
  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 = 3;
     
	 params = {
	    "max"  :  fTotal,
		"filter" : "hasApp"
	 };

     var req = opensocial.newDataRequest();
	 var spec = opensocial.newIdSpec({"userId" : "OWNER", "groupId" : "FRIENDS"});
     req.add(req.newFetchPeopleRequest(spec, params), 'viewerFriends');
     
	 if( fTotal != 3)
	   req.send(handleShowFriends);
	 else
	   req.send(handleFriendsOnMydesk);
}

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 = 3;
		
        total_friends = viewerFriends.getTotalSize();
        html = new Array();
	
        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+'&fb_user_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('friends').innerHTML = html.join('');
     }
	 else {
	   document.getElementById('friends').innerHTML = '<span style="font-size:12px;font-family:Arial;color:#0F8DBC;">Invite Your friends to install application.</span>';
	 }
	 
	 gadgets.window.adjustHeight();
}

function handleFriendsOnMydesk(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 = 3;
		
        total_friends = viewerFriends.getTotalSize();
        html = new Array();
	
        html.push('<div style="float:left;width:35px;">&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:120px;">');
              html.push('<div style="height:79px;width:79px;border:1px #ccc solid;">');
			  
			  if(frnd_prof_url)
			  {
			    fr_u = frnd_prof_url+'&fb_user_id='+person.getId();
				cn = 'main_container';
			    html.push('<a href="javascript:void(0)" onclick="Cinemas.fetchGETRequest(\''+fr_u+'\',null,\''+cn+'\')">');
			  }
			  
			  html.push('<img style="width:75px;height:75px;border:2px solid #FFFFFF;" src="'+person.getField(opensocial.Person.Field.THUMBNAIL_URL)+'"/>');
			  
			  if(frnd_prof_url)
			    html.push('</a>');
			  
			  html.push('</div>');
		      html.push('<div align="left" style="font:bold 12px Arial;color:#0F8DBC;width:90px;overflow:hidden;" >'+person.getDisplayName()+'</div>');
		      html.push('</div>');
            
			  if(counter % per_line == 0) {
			     html.push('<div style="clear:both;"></div>');
			  }
			
			});
        html.push('<div style="clear:both;"></div>');
        document.getElementById('friends').innerHTML = html.join('');
     }
	 else {
	   document.getElementById('friends').innerHTML = '<span style="font-size:12px;font-family:Arial;color:#0F8DBC;">Invite Your friends to install application.</span>';
	 }
	 
	 gadgets.window.adjustHeight();
}

function postDonateFeed()
{
	var cimgdiv = document.getElementById('_corner_pic')
	var cimg = cimgdiv.getElementsByTagName('img')  //use src attribute
    
    var cnameinput = document.getElementById('_corner_name'); ///use innerhtml
    actTitle = " loves " + cnameinput.value;
    
    
    actMsg = '<a href="/Application.aspx?appId=' +getAppId() + '">I love  ' + cnameinput.value + '. Find my gifts and expressions for ' + cnameinput.value;
    
    var actBody = new Array();
    actBody.push('<div style="font-size:12px;color:#02679C;">');
	    actBody.push('<div style="float:left;padding:1px 5px;">');
			 actBody.push('<a href="/Application.aspx?appId='+getAppId()+'">');
			 actBody.push('<img src="'+ cimg.src + '" border="0" style="width:72px;height:72px;"/>');
			 actBody.push('</a>');
		actBody.push('</div>');
		
		actBody.push('<div style="float:left;padding:1px 5px;">');
			 actBody.push('<div style="padding-top:10px;overflow:hidden;color:#000000">');
			 actBody.push('<span style="color:#02679C;">' + '<a href="/Application.aspx?appId=' +getAppId() + '">I love ' + cnameinput.value + '.</a></span>');
			 actBody.push('  Find my expressions and gifts for ' + cnameinput.value + ', and for other fans of ' + cnameinput.value );
			 actBody.push('</div>');
		actBody.push('</div>');
	actBody.push('<div style="clear:both;"></div>')
	actBody.push('</div>');
	
	postActivity(actTitle,actBody.join(''));
	document.getElementById("exhort_div").innerHTML = "Broadcast sent";
}

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;">');
	
	// Activity Feed first image ( icon of the corresponding activity such as video/photo/gift)
	var actMsgpart1 = new Array();
	// Activity feed second image if present(image of a user/person)
	var actMsgpart2 = new Array();
	// Activity feed Message part of the feed
	var actMsgpart3 = new Array();
	actMsgpart3.push('<div style="float:left;padding:1px 5px;width:300px;">');
	actMsgpart3.push('<div style="padding-top:10px;overflow:hidden;">');
	 
	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" ) {  // append the image of the action that resulted the feed
		 if (activities[i].value && activities[i].value != "" ) {
			 actMsgpart1.push('<div style="float:left;padding:1px 5px;">');
			 actMsgpart1.push('<a href="/Application.aspx?appId='+getAppId()+'">');
			 actMsgpart1.push('<img src="'+activities[i].value+'" border="0" style="width:72px;height:68px;"/>');
			 actMsgpart1.push('</a>');
			 actMsgpart1.push('</div>');
		 }
	  }
	  else if( activities[i].id == "cr_act_img1" ) { // append the image on which the feed is generated
		 if (activities[i].value && activities[i].value != "" ) {
			 actMsgpart2.push('<div style="float:left;padding:1px 5px;">');
			 actMsgpart2.push('<a href="/Application.aspx?appId='+getAppId()+'">');
			 actMsgpart2.push('<img src="'+activities[i].value+'" border="0" style="width:72px;height:68px;"/>');
			 actMsgpart2.push('</a>');
			 actMsgpart2.push('</div>');
		 }
	  }
	  else if( activities[i].id == "cr_act_desc" ) { // append text message into the feed
		 actMsgpart3.push('<span style="color:#02679C;">'+activities[i].value+'</span>')
	  }
	  else if( activities[i].id == "cr_act_desc1" ) {
		 actMsgpart3.push('<br/><br/><a href="/Application.aspx?appId='+getAppId()+'">');
		 actMsgpart3.push('<span style="color:#02679C;">'+activities[i].value+'</span></a>')
	  }
	  else if( activities[i].id == "cr_act_type" ) {
		 
	  }
	}
	actMsgpart3.push('</div>');
	actMsgpart3.push('</div>');
	
	// Combine all the feed message parts into the activity body
	actBody.push(actMsgpart1.join(''));
	actBody.push(actMsgpart2.join(''));
	actBody.push(actMsgpart3.join(''));
	
	actBody.push('<div style="clear:both;"></div>')
	actBody.push('</div>');
	
	// Create an activity feed with corresponding title, and body
	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_addF8Ractors_search_form(url)
{
	var postdata = {
		    ctype : document.getElementById('ctype').value,
		    search_query : document.getElementById('search_query').value
    };  
    
    Cinemas.makeSubmitForm(url,'main_container',postdata);
}

// Returns application's install URL on Orkut, Friendster
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("");
	}
}

// Returns application's Canvas URl on orkut, Friendster
function createAppCanvasLink(){
   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"], 
				 "/Main#Application.aspx?appId=",
				 app_id].join("");
	}
}

// Callback for openapps send invite - single corner apps
function handlesendmsg(resp){
  if(!resp.hadError()){
	  resp_data = resp.getData();
	  idslist = resp_data["recipientIds"];

      var postdata = {
			    ids : idslist
	    };  
	  
	  var url = "http://www.corners.in/orkutapps/postinvitefriends"
	  Cinemas.submitFrndIdsForm(url,'main_container',postdata);
	  
	  var url2 = "http://www.corners.in/orkutapps/index";
      Cinemas.fetchGETRequest(url2,null,'main_container');
              
  }
}

// Callback for the send invite on Expressions app
function handleExpsendmsg(resp){
  if(!resp.hadError()){
	  resp_data = resp.getData();
	  idslist = resp_data["recipientIds"];

      var postdata = {
			    ids : idslist
	    };  
	  
	  var url = "http://www.corners.in/socialapps_expressions/postinvitefriends"
	  Cinemas.submitFrndIdsForm(url,'main_container',postdata);
	  
	  var url2 = "http://www.corners.in/socialapps_expressions/indexnew";
      Cinemas.fetchGETRequest(url2,null,'main_container');
              
  }
}

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;
	}
}

/** 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;
	}
}

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
		return gadgets.util.getUrlParameters()["gadgetId"];
}

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("");
	}
}

/**
 * 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);
}

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';
}

/*** PROFILE PERSISTENCE ***/
//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.title1 = null;
    this._profile.title2 = null;
    this._profile.title3 = null;

    this._profile.hits1 = 1;
    this._profile.hits2 = 1;
    this._profile.hits3 = 1;
	
	this._profile.crnrimgurl = null;
    this._profile.rhtrctxt = null;
	this._profile.cornername = null;

    this._profile.next = 1;
};
 
CProfile.prototype = {
    _profile:{
        imgurl1:null,
        imgurl2:null,
        imgurl3:null,
        title1:null,
        title2:null,
        title3:null,
        hits1:1,
        hits2:1,
        hits3:1,
		crnrimgurl:null,
		rhtrctxt:null,
		cornername:null,
        next:1
    },
    getImgurl1:function(){
        return this._profile.imgurl1;
    },
   getImgurl2:function(){
        return this._profile.imgurl2;
    },
   getImgurl3:function(){
        return this._profile.imgurl3;
    },
   getTitle1:function(){
        return this._profile.title1;
    },
   getTitle2:function(){
        return this._profile.title2;
    },
   getTitle3:function(){
        return this._profile.title3;
    },
   getHits1:function(){
        return this._profile.hits1;
    },
   getHits2:function(){
        return this._profile.hits2;
    },
   getHits3:function(){
        return this._profile.hits3;
    },
   getCrnrimgurl:function(){
		return this._profile.crnrimgurl;
   },
   getRhtrctxt:function(){
		return this._profile.rhtrctxt;
   },
   getCornername:function(){
		return this._profile.cornername;
   },
   setImgurl1:function(url){
        this._profile.imgurl1 = url;
   },
  setImgurl2:function(url){
        this._profile.imgurl2 = url;
   },
  setImgurl3:function(url){
        this._profile.imgurl3 = url;
   },
  setTitle1:function(titl){
       this._profile.title1 = titl;
  },
  setTitle2:function(titl){
       this._profile.title2 = titl;
  },
 setTitle3:function(titl){
       this._profile.title3 = titl;
  },
  setHits1:function(hitz){
      this._profile.hits1 = hitz;
  },
  setHits2:function(hitz){
      this._profile.hits2 = hitz;
  },
  setHits3:function(hitz){
      this._profile.hits3 = hitz;
  },
  setCrnrimgurl:function(url){
	  this._profile.crnrimgurl = url;
  },
  setRhtrctxt:function(txt){
	  this._profile.rhtrctxt = txt;
  },
  setCornername:function(name){
	  this._profile.cornername = name;
  },
 getNext:function(){
        return this._profile.next;
  },
 setNext:function(nxt){
        this._profile.next = nxt;
  },
    setVideo1:function(url, titl, hits, update) {
        this._profile.imgurl1 = url;
        this._profile.title1 = titl;
        this._profile.hits1 = hits;
        this._profile.next = 2;
        if(update){
            this._updateProfile();
        }
    },
    setVideo2:function(url, titl, hits, update){
        this._profile.imgurl2 = url;
        this._profile.title2 = titl;
        this._profile.hits2 = hits;
        this._profile.next = 1;
        if(update){
            this._updateProfile();
        }
    },
	setCornerdetails:function(corner_icon,rtrc_txt, corner_name){
		this._profile.crnrimgurl = corner_icon;
		this._profile.rhtrctxt = rtrc_txt;
		this._profile.cornername = corner_name;
	},
    _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();
    }
};

/***
 *
 */
function generateProfContent(prfile) {
		html = new Array(); 
		
		html.push('<div style="padding:5px 8px;float:left;background-color:#EEEEEE;">')	  
		
		if( prfile.crnrimgurl && prfile.cornername) {
			html.push('<div style="font-family:Arial;">'); 
			html.push('<div style="float:left;" >');
			html.push('<img src="'+prfile.crnrimgurl+'" border="0" style="width:60px;height:60px" />');
			html.push('</div>');
			html.push('<div style="float:left;padding-left:8px;">');
			html.push('<div style="font-size:11px;width:256px;text-align:justify;">');
			if(prfile.rhtrctxt)
			  html.push(prfile.rhtrctxt);
			else
			  html.push('Find exclusive videos, pictures and raves on '+prfile.cornername+'. Earn fan points.');
			html.push('</div>');
			html.push('<div style="font-size:4px;">&nbsp;</div><div align="center">');
			html.push('<a href="javascript:Cinemas.goToCanvasView(false,false);">');
			html.push('<img border="0" style="width: 119px; height: 16px;" src="http://www.corners.in/images/earn_fan_coins.gif"/></a></div>');
			html.push('</div>');
			html.push('<div style="clear:both;"></div>');
			html.push('</div>');
			html.push('<div style="font-size:5px;">&nbsp;</div>');
		}
		
		html.push('<div style="font-weight:bold;">My Favorites</div>');
		
		html.push('<div id="prof_vdos" style="padding:5px 5px;">');
			  
		html.push('<div style="float:left;">');
			  
		html.push('<div align="left" class="vdo_img_div"><a href="javascript:Cinemas.goToCanvasView(false,false);">');
			  
		html.push('<img border="0" src="'+prfile.imgurl1+'" style="width:120px;height:90px;"/>');
			  
		html.push('</a></div>');
		html.push('<div align="left" class="mover_underline"><a href="javascript:Cinemas.goToCanvasView(false,false);" class="blue_color_link">');
			  
		html.push('<span style="font-weight:bold;">'+prfile.title1+'</span>');
			  
		html.push('</a></div>');
		html.push('<div align="left">');
			  
		html.push('<span class="resource_label">Views : '+prfile.hits1+'</span>');
			  
		html.push('</div>');			  
			  
		html.push('</div>');
		  
		html.push('<div style="float:left;width:60px;">&nbsp;</div>')
			  
		html.push('<div style="float:left;">');
			  
		html.push('<div align="left" class="vdo_img_div"><a href="javascript:Cinemas.goToCanvasView(false,false);">');
			  
		html.push('<img border="0" src="'+prfile.imgurl2+'" style="width:120px;height:90px;"/>');
			  
		html.push('</a></div>');
		html.push('<div align="left" class="mover_underline"><a href="javascript:Cinemas.goToCanvasView(false,false);" class="blue_color_link">');
			  
		html.push('<span style="font-weight:bold;">'+prfile.title2+'</span>');
			  
		html.push('</a></div>');
		html.push('<div align="left">');
			  
		html.push('<span class="resource_label">Views : '+prfile.hits2+'</span>');
			  
		html.push('</div>');			  
			  
		html.push('</div>');
			  
		html.push('<div style="clear:both;"></div>');
			  
		html.push('</div>');
		
		html.push('</div>');
		html.push('<div style="clear:both;"></div>');
		
		return html.join('');
}

function initProfileVideo(profile, num, prof_ps)
{
    var video = null;
    if( num == 1 )
    {
	    if(prof_ps) {
		  url   = prof_ps.imgurl1;
		  title = prof_ps.title1;
		  hits  = prof_ps.hits1;
		}
		else {
		  url   = document.getElementById("prof_img_url1").value;
		  title = document.getElementById("prof_vdo_title1").value;
		  hits  = document.getElementById("prof_vdo_hits1").value;
		}
    	profile.setVideo1(url, title, hits);
    }
    else
    {
        if(prof_ps) {
		  url   = prof_ps.imgurl2;
		  title = prof_ps.title2;
		  hits  = prof_ps.hits2;
		}
		else {
		  url   = document.getElementById("prof_img_url2").value;
		  title = document.getElementById("prof_vdo_title2").value;
		  hits  = document.getElementById("prof_vdo_hits2").value;
		}
    	profile.setVideo2(url, title, hits);
    }
    
    return video;
}

function setFavProfileVideo(profile, num) {
	
	url = document.getElementById("prof_img_url1").value;
	title = document.getElementById("prof_vdo_title1").value;
	hits = document.getElementById("prof_vdo_hits1").value;
	
	if( num == 1 ) {
		profile.setVideo1(url, title, hits);
	}
	else {
		profile.setVideo2(url, title, hits);
	}
}

function copyOldProfileVideo(profile, num, prof_ps) {
	if( num == 1 )
	{
		url = prof_ps.imgurl1;
		title = prof_ps.title1;
		hits = prof_ps.hits1;
	}
	else {
		url = prof_ps.imgurl2;
		title = prof_ps.title2;
		hits = prof_ps.hits2;
	}
	
	if( num == 1 ) {
		profile.setVideo1(url, title, hits);
	}
	else {
		profile.setVideo2(url, title, hits);
	}
}

function saveProfCrnrdetails(profile, prof_ps) {
	_crnrimgurl = document.getElementById("corner_icon").value;
	_cornername = document.getElementById("corner_name").value;
	
	rtrc_txt = document.getElementById("rhetoric_text");
	if(rtrc_txt && rtrc_txt.value != "")
	  _rhtrctxt = rtrc_txt.value;
	else if(prof_ps)
	  _rhtrctxt = prof_ps.rhtrctxt;
	else
	  _rhtrctxt = null;
	
	profile.setCornerdetails(_crnrimgurl, _rhtrctxt, _cornername);
}

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 = 2 ;}
				 
			 var profile = new CProfile();
			 initProfileVideo(profile, 1);
			 initProfileVideo(profile, 2);
			 saveProfCrnrdetails(profile);
			 
			 profile._updateProfile(); //Will call newUpdatePersonAppDataRequest
		}
		else {
		     //Retrieve the profile data, and update the next video
		     var preq = opensocial.newDataRequest();
		     
		     prof_data = ["profile"]
			 preq.add(preq.newFetchPersonRequest(opensocial.IdSpec.PersonId.OWNER),'owner');
			 preq.add(preq.newFetchPersonAppDataRequest(getOwrIdSpec(),prof_data),'profile_data');
			 
			 preq.send(handleProcessProfData);
		}
}
			
function handleProcessProfData(pro_resp) {
		owner = pro_resp.get('owner').getData();
        var prfile = pro_resp.get("profile_data").getData()[owner.getId()].profile;
        var pro = gadgets.json.parse(gadgets.util.unescapeString(prfile));
        var profile = new CProfile();

        if( prfile )
        {
	      vdo_index = pro.next;
		  if(parseInt(vdo_index) == 1)
		     retain_index = 2;
		  else
		     retain_index = 1;
	      
		  copyOldProfileVideo(profile, retain_index,pro);
		  setFavProfileVideo(profile, parseInt(vdo_index));
		  saveProfCrnrdetails(profile, pro);
		  
	      profile._updateProfile();
        } 
}

function getVwrIdSpec()
{
      var params = {};
      params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;
      var idspec = opensocial.newIdSpec(params);
 
      return idspec;
}

function selectCorner(selobj, sel_id)
{
        //Get the parent of the selobj
        var middle_div = document.getElementById('middle_corners'); //Middle div
		var lhs_div = document.getElementById('left_featured'); //left div
		var rhs_div = document.getElementById('right_newest'); //right div
		
		var hidninpt = document.getElementById('_selected_corner');
		
        var all_images = middle_div.getElementsByTagName('img');
        for(var i=0;i<all_images.length;i++)
        {
           all_images[i].parentNode.parentNode.style.background = "#FFFFFF";
           all_images[i].parentNode.parentNode.style.color = "#000000";
        }
		
		var all_images = lhs_div.getElementsByTagName('img');
        for(var i=0;i<all_images.length;i++)
        {
           all_images[i].parentNode.parentNode.style.background = "#EFEFEF";
           all_images[i].parentNode.parentNode.style.color = "#000000";
        }
		
		var all_images = rhs_div.getElementsByTagName('img');
        for(var i=0;i<all_images.length;i++)
        {
           all_images[i].parentNode.parentNode.style.background = "#EFEFEF";
           all_images[i].parentNode.parentNode.style.color = "#000000";
        }
		
		hidninpt.value = sel_id;
        
        selobj.parentNode.parentNode.style.background = "#0F8DBC";
        selobj.parentNode.parentNode.style.color = "#FFFFFF";
		
		var more_ref = document.getElementById('more_expressions');
		if(more_ref)
		  more_ref.onclick = goToMoreExp;
}
  
  // Onclick handler for More Expressions on expressions app
  function goToMoreExp()
  {
		var hidninpt = document.getElementById('_selected_corner');
		var exp_url = document.getElementById('_more_exp_url');
		
		var _create_url = exp_url.value + "?corner_id=" + hidninpt.value;
		
		Cinemas.fetchGETRequest(_create_url, null, 'main_container');
  }
  
function selectFirstCorner()
{
      var middle_div = document.getElementById('middle_corners'); 
      var all_images = middle_div.getElementsByTagName('img');
      
      all_images[0].parentNode.parentNode.style.background = "#0F8DBC";
      all_images[0].parentNode.parentNode.style.color = "#FFFFFF";
}
 

function selectEmotion(selobj, emoticon_id, score, units, allow_multiples, measure)
  {
         //Get the parent of the selobj
        var images_div = document.getElementById('images_div');
        var hidninpt = document.getElementById('hidnemotion');
        var iscore = parseInt(score);
        var iunits = parseInt(units);
        
        var all_images = images_div.getElementsByTagName('img');
        for(var i=0;i<all_images.length;i++)
        {
           all_images[i].parentNode.parentNode.style.border = "0px #FFFFFF";
        }
        
    	//selobj.border = 1;
    	selobj.parentNode.parentNode.style.border = "1px #92AF09 solid";

    	if( allow_multiples == '0' )
    	{
    	    document.getElementById('step2').style.display = "none";
    	    if( iscore < iunits )
    	    {
    	       document.getElementById('no_coins_msg').style.display = "block";
    	    }
    	    else
    	    {
    	       document.getElementById('no_coins_msg').style.display = "none";
    	    }
    	}
    	else
    	{
    	    document.getElementById('step2').style.display = "block";
    	    
        	var can_buy = 1;
        	
        	if( iunits > 0 && iscore > 0 )
        	   can_buy = parseInt(iscore/iunits);
        	   
        	if( can_buy < 1 )
        	{
        	    document.getElementById('no_coins_msg').style.display = "block";
        	}
        	else
        	{
        	    document.getElementById('no_coins_msg').style.display = "none";
        	}
        
        	var purch_adv = "<span id='canbuy' name='canbuy'>(Upto " + can_buy + " " + measure + " )</span>"
        	//Set purchase_advise span's inner html
        	document.getElementById('purchase_advise').innerHTML = purch_adv;
    	}
    	
    	hidninpt.value = emoticon_id;
    	
  }
  
  
  // Handles Premium expressions
	function selectPrmExp(parentdiv, totalExprs, exp_id)
	{   
		// hidden field that holds the selected expression value
		var hidninpt = document.getElementById('sel_emotion');
		
		var childDivs = parentdiv.getElementsByTagName("div");
		childDivs[0].style.background="url(http://www.corners.in/applications/images/bluebox.gif) no-repeat";   
			
		var whiteboxdiv = parentdiv.getElementsByTagName("div")[0];   //first child element of parent div
		var contentdiv  = whiteboxdiv.getElementsByTagName("div")[0]; // first child element of whilebax
		var coinsdiv    = contentdiv.getElementsByTagName("div")[2].getElementsByTagName("div")[1]; //second child elemnt of whitebox
		contentdiv.getElementsByTagName("div")[2].style.color = "#003399";
		coinsdiv.style.color = "#9f9f9f";
		
		//get last index from the id
		var parentid = parentdiv.getAttribute('id');
		
		var endindex = parentid.length;	
		var seldiv = parentid.slice(5,endindex);
		seldiv_no = seldiv * 1;
	   
		//this will change the background of selected div's nextSiblings.
		for(var i = seldiv_no+1; i < totalExprs+1; i++)
		{
		  bid = "badge"+i;
		  clearLastselectedExp(bid);
		}
		
		for(var i = seldiv_no-1; i >= 1; i-- )
		{
		  bid = "badge"+i;
		  clearLastselectedExp(bid);
		}
		
		hidninpt.value = exp_id;
	}
	
	// Clears last selected premium expression
	function clearLastselectedExp(sib)
	{
		var sibling = document.getElementById(sib);
	   
		whiteboxdiv = sibling.getElementsByTagName("div")[0];
		whiteboxdiv.style.background="url(http://www.corners.in/applications/images/whitebox.gif) no-repeat";
	   
		var contentdiv  = whiteboxdiv.getElementsByTagName("div")[0]; // first child element of whilebax
		var coinsdiv    = contentdiv.getElementsByTagName("div")[2].getElementsByTagName("div")[1]; //second child elemnt of whitebox
		contentdiv.getElementsByTagName("div")[2].style.color = "#000000";
		coinsdiv.style.color = "#FFFFFF";
	}

  // Disables save Expression if insufficient coins
  function selectEmotion_Disabled(selobj, total_emots, sel_id, exp_type)
  {
     //Select the emotion, but disable save button
     if(exp_type == 0) // check if the emotion is premium or not
	   selectEmotion2(selobj, sel_id);
	 else
	   selectPrmExp(selobj, total_emots, sel_id); // Selection for premium
     
     var save_enabled  = document.getElementById('enabled_save');
     var save_disabled = document.getElementById('disabled_save');    	
    	
     save_enabled.style.display = "none";
     save_disabled.style.display = "block";
     
  }

  // Selection on create_emotion2 page	
  function selectEmotion2(selobj, sel_id)
  {
        //Get the parent of the selobj
        var middle_div = document.getElementById('middle_corners'); //First div
		var hidninpt = document.getElementById('sel_emotion');
		
        var all_images = middle_div.getElementsByTagName('img');
        for(var i=0;i<all_images.length;i++)
        {
           all_images[i].parentNode.parentNode.style.background = "#FFFFFF";
		   all_images[i].parentNode.parentNode.style.color = "#000000";
        }
		
		hidninpt.value = sel_id;
        
        selobj.parentNode.parentNode.style.background = "#0F8DBC";
		selobj.parentNode.parentNode.style.color = "#FFFFFF";
    	
    	//Set the more expressions url
    	var more_ref = document.getElementById('more_expressions')
    	
    	var save_enabled  = document.getElementById('enabled_save');
    	var save_disabled = document.getElementById('disabled_save');    	
    	
    	save_enabled.style.display = "block";
    	save_disabled.style.display = "none";
    	
  }
  // Selects the first emotion
  function selectFirstEmotion()
  {
      var middle_div = document.getElementById('middle_corners'); 
      var all_images = middle_div.getElementsByTagName('img');
      all_images[0].parentNode.parentNode.style.background = "#0F8DBC";
	  all_images[0].parentNode.parentNode.style.color = "#FFFFFF";
  }
  // Updates Tab selection
  function updateTabSel(seldiv)
  {
   
	var emotion_tabs = document.getElementById("emotion_tabs");
	var tabdivs = emotion_tabs.getElementsByTagName('div');
	var len = tabdivs.length;
	for( var i=0; i < len ; i++)
	{
	    var nameAttr = tabdivs[i].getAttribute('id');
	    if( nameAttr == "normal" )
		{
		    tabdivs[i].style.background = "url(http://www.corners.in/applications/images/normalemotab.gif)";
			tabdivs[i].style.color = "FFFFFF";
		}
		if( nameAttr == "premium" )
		{
			tabdivs[i].style.background = "url(http://www.corners.in/applications/images/premiumemotab.gif)";
			tabdivs[i].style.color = "FFFFFF";
		}
	}
	
	seldiv.style.background = "url(http://www.corners.in/applications/images/emptywhitetab.gif)";
	seldiv.style.color = "#676767";
  }

function getOwrIdSpec()
{
      var params = {};
      params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.OWNER;
      var idspec = opensocial.newIdSpec(params);
 
      return idspec;
}
/*** END PROFILE PERSISTENCE ***/

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;
 }
