
/**
 *  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);
}

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;
		}
	}
}

// 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] = "Meet me at "+corner_name;
    params[opensocial.Message.Field.TYPE] = opensocial.Message.Type.PRIVATE_MESSAGE;
	
	// Body of the private message
	app_url = createAppCanvasLink();
	html = "Smile, Hug, Love, Flirt, Poke and more.. at "+ corner_name +". to be the biggest fan.\n";
	html += app_url;
	
	var body = html;
	var message = opensocial.newMessage(body, params);
	
	
	// 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 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[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 req = opensocial.newDataRequest();
     req.add(req.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, 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();
}

// Shows three friends on mydesk
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.getField(opensocial.Person.Field.NAME).getField(opensocial.Name.Field.GIVEN_NAME)+'</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();
}

//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 postDonateFeed()
{
	var cimgdiv = document.getElementById('_corner_pic')
	var cimg = cimgdiv.getElementsByTagName('img')  //use src attribute
	var cornericon = document.getElementById('_corner_icon');
    
    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="'+ cornericon.value + '" 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 = "Feed posted";
}

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;">');
		 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_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("");
	}
}

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;
	}
}

/** 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';
}

/***
 *
 */
function generateProfContent(ownerPData) {
		html = new Array(); 
		
		html.push('<div style="padding:5px 8px;float:left;background-color:#EEEEEE;">')	  
		
		html.push('<div style="font-weight:bold;">My Favorites</div>');
		
		html.push('<div id="prof_vdos" style="padding:5px 20px;">');
			  
		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="'+gadgets.util.unescapeString(ownerPData['prof_img_url1'])+'" />');
			  
		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;">'+gadgets.util.unescapeString(ownerPData['prof_vdo_title1'])+'</span>');
			  
		html.push('</a></div>');
		html.push('<div align="left">');
			  
		html.push('<span class="resource_label">Views : '+gadgets.util.unescapeString(ownerPData['prof_vdo_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="'+gadgets.util.unescapeString(ownerPData['prof_img_url2'])+'" />');
			  
		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;">'+gadgets.util.unescapeString(ownerPData['prof_vdo_title2'])+'</span>');
			  
		html.push('</a></div>');
		html.push('<div align="left">');
			  
		html.push('<span class="resource_label">Views : '+gadgets.util.unescapeString(ownerPData['prof_vdo_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 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 ;}
				 
			 for(i = 1; i <= count; i++ ){
			   cont1 = 'prof_img_url'+i;
			   cont2 = 'prof_vdo_title'+i;
			   cont3 = 'prof_vdo_hits'+i;
				    
			   cont_val1 = document.getElementById(cont1).value;
			   cont_val2 = document.getElementById(cont2).value;
			   cont_val3 = document.getElementById(cont3).value;
			 
			   preq.add(preq.newUpdatePersonAppDataRequest("VIEWER",cont1, cont_val1));
			   preq.add(preq.newUpdatePersonAppDataRequest("VIEWER",cont2, cont_val2));
			   preq.add(preq.newUpdatePersonAppDataRequest("VIEWER",cont3, cont_val3));
			 }
			 
			 preq.add(preq.newUpdatePersonAppDataRequest("VIEWER", "vdo_to_updte", 1));
			 preq.send(function (){});
		}
		else {
		     count = 1;
		     owner_prof_data = ["vdo_to_updte"]
			 preq.add(preq.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER),'owner');
			 preq.add(preq.newFetchPersonAppDataRequest(opensocial.DataRequest.PersonId.OWNER,owner_prof_data),'owner_data');
			 
			 preq.send(handleProcessProfData);
		}
}
			
function handleProcessProfData(pro_resp) {
		owner = pro_resp.get('owner').getData();
		prof_data = pro_resp.get('owner_data').getData();
		
		vdo_index = 1;
		if(prof_data) {
		   prof_vdo_to_update = prof_data[owner.getId()];
		   if( prof_vdo_to_update)
		      vdo_index = prof_vdo_to_update["vdo_to_updte"];
		}
		cont1 = 'prof_img_url'+vdo_index;
		cont2 = 'prof_vdo_title'+vdo_index;
		cont3 = 'prof_vdo_hits'+vdo_index;
				
		cont_val1 = document.getElementById('prof_img_url1').value;
		cont_val2 = document.getElementById('prof_vdo_title1').value;
		cont_val3 = document.getElementById('prof_vdo_hits1').value;
		
		var preq = opensocial.newDataRequest();
		
		preq.add(preq.newUpdatePersonAppDataRequest("VIEWER",cont1, cont_val1));
		preq.add(preq.newUpdatePersonAppDataRequest("VIEWER",cont2, cont_val2));
		preq.add(preq.newUpdatePersonAppDataRequest("VIEWER",cont3, cont_val3));
		
		if( vdo_index == 1)
		  nxt_vdo = 2;
		else
		  nxt_vdo = 1;
		
		preq.add(preq.newUpdatePersonAppDataRequest("VIEWER", "vdo_to_updte", nxt_vdo.toString()));
		preq.send(function (){});
}

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 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.parentNode.parentNode.style.border = '1px #92AF09 solid';

    	if( allow_multiples == '0' )
    	{
    	    document.getElementById('step2').style.display = 'none';
    	}
    	else
    	{
    	    document.getElementById('step2').style.display = 'block';
    	    
    	    var iscore = parseInt(score);
        	var iunits = parseInt(units);
        	var can_buy = 1;
        	
        	if( iunits > 0 && iscore > 0 && (iscore >= iunits) )
        	   can_buy = parseInt(iscore/iunits);
        	else
        	   can_buy = 0;
        	
        	var purch_adv = "";
            if( can_buy > 0 )
        	   purch_adv = "<span id='canbuy' name='canbuy'>(Upto " + can_buy + " " + measure + " )</span>";
        	else
        	   purch_adv = "<span id='canbuy' name='canbuy'>(You do not have sufficient fan-coins)</span>";
        	
        	
        	//Set purchase_advise span's inner html
        	document.getElementById('purchase_advise').innerHTML = purch_adv;
    	}
    	
    	hidninpt.value = emoticon_id;
    	
  }

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;
 }

var temp_url;
function updatePicture(url,opt_params,container) {
	if(typeof sn_owner !="undefined")
	{	
		var thumburl = sn_owner.getField(opensocial.Person.Field.THUMBNAIL_URL);
		var postdata = {
				thumb_url :  thumburl				
		};
		Cinemas.makeSubmitForm(url,container,postdata);
		hideSpinner();
	}
	else
	{
		temp_url = url;
                  	ctr = container;
                  	var req = opensocial.newDataRequest();
		req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER),'owner');	
		req.send(callback_updatePicture);
	}	
}

function callback_updatePicture(respObj)
{
	var owner = respObj.get('owner').getData();
	if(owner && temp_url )
	{
		var thumburl = owner.getField(opensocial.Person.Field.THUMBNAIL_URL);
		var postdata = {
				thumb_url :  thumburl				
		};
		Cinemas.makeSubmitForm(temp_url,ctr,postdata);
		temp_url = null;
	}
	hideSpinner();		
}


  // 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";
  }