/*
 * The facebook_onload statement is printed out in the PHP. If the user's logged in
 * status has changed since the last page load, then refresh the page to pick up
 * the change.
 *
 * This helps enforce the concept of "single sign on", so that if a user is signed into
 * Facebook when they visit your site, they will be automatically logged in -
 * without any need to click the login button.
 *
 * @param already_logged_into_facebook  reports whether the server thinks the user
 *                                      is logged in, based on their cookies
 *
 */
 
function facebook_onload(already_logged_into_facebook) {
  // user state is either: has a session, or does not.
  // if the state has changed, detect that and reload.
 
  FB.ensureInit(function() {
	  
      FB.Facebook.get_sessionState().waitUntilReady(function(session) {
		  
          var is_now_logged_into_facebook = session ? true : false;
			//alert("current logged in status"+is_now_logged_into_facebook);
          // if the new state is the same as the old (i.e., nothing changed)
          // then do nothing
          if (is_now_logged_into_facebook == already_logged_into_facebook) {
            return;
          }

          // otherwise, refresh to pick up the state change
          //refresh_page();
		  if(is_now_logged_into_facebook)
		  {
			 
		 // update_user_box();
		 //alert("Now redirect me on my home page");
		// refresh_account_page();
		  }
        });
    });
}

/*
 * Our <fb:login-button> specifies this function in its onlogin attribute,
 * which is triggered after the user authenticates the app in the Connect
 * dialog and the Facebook session has been set in the cookies.
 */
function facebook_onlogin_ready() {
  // In this app, we redirect the user back to index.php. The server will read
  // the cookie and see that the user is logged in, and will deliver a new page
  // with content appropriate for a logged-in user.
  //
  // However, a more complex app could use this function to do AJAX calls
  // and/or in-place replacement of page contents to avoid a full page refresh.
  refresh_page();
}

/*
 * Do a page refresh after login state changes.
 * This is the easiest but not the only way to pick up changes.
 * If you have a small amount of Facebook-specific content on a large page,
 * then you could change it in Javascript without refresh.
 */
function refresh_page() {
  window.location = 'index.php';
}

/*
 * Prompts the user to grant a permission to the application.
 */
function facebook_prompt_permission(permission) {
  FB.ensureInit(function() {
    FB.Connect.showPermissionDialog(permission);
  });
}

/*
 * Show the feed form. This would be typically called in response to the
 * onclick handler of a "Publish" button, or in the onload event after
 * the user submits a form with info that should be published.
 *
 */
function facebook_publish_feed_story(form_bundle_id, template_data) {
  // Load the feed form
  FB.ensureInit(function() {
          FB.Connect.showFeedDialog(form_bundle_id, template_data);
          //FB.Connect.showFeedDialog(form_bundle_id, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);

      // hide the "Loading feed story ..." div
      ge('feed_loading').style.visibility = "hidden";
  });
}

/*
 * If a user is not connected, then the checkbox that says "Publish To Facebook"
 * is hidden in the "add run" form.
 *
 * This function detects whether the user is logged into facebook but just
 * not connected, and shows the checkbox if that's true.
 */
function facebook_show_feed_checkbox() {
  FB.ensureInit(function() {
      FB.Connect.get_status().waitUntilReady(function(status) {
		  
          if (status != FB.ConnectState.userNotLoggedIn) {
            // If the user is currently logged into Facebook, but has not
            // authorized the app, then go ahead and show them the feed dialog + upsell
            checkbox = ge('publish_fb_checkbox');
            if (checkbox) {
              checkbox.style.visibility = "visible";
            }
          }
        });
    });
}


function update_user_box()
{
	//alert("now i m connected going to register your user");
	
	var user_box = document.getElementById("faceconn");
	//render_xfbml();
	//var loggedinuser="723376341";
	//alert("Connecting to facebook");
	//user_box.innerHTML = "<span>" + "<fb:profile-pic uid='loggedinuser' facebook-logo='true'></fb:profile-pic>" + "Welcome, <fb:name uid='loggedinuser' useyou='false'></fb:name>. <a onclick=\"FB.Connect.logout(function() { refresh_page(); })\" href=\"#\">Logout of Facebook</a>" + "</span>"; 

	FB.XFBML.Host.parseDomTree(); 
	document.getElementsByTagName('html')[0].style.overflow ='auto';document.getElementById('light_l').style.display='none';document.getElementById('fade').style.display='none';
	//window.location = '<?php echo $site_url?>index.php';
	//facebook_onlogin_ready();
	//
	var usr=FB.Facebook.apiClient.get_session().uid;
	//alert("connecting with facebook");
	/*FB.Facebook.apiClient.users_getInfo(usr,['name','birthday'], function(unifoo, ex){
            window.alert("User Info :"+uinfoo);
            window.alert("Exception :"+ex);
			
        });*/
		//if(!usr)
		//fb_showloading();

	FB.Facebook.apiClient.users_getInfo(usr,['first_name','last_name','name','birthday','political','sex','pic_small','pic_big','pic','current_location','hometown_location','about_me','education_history','proxied_email'],function(uni,ex)
          {
			
// do something
//alert("hi shekhar"+uni[0]['first_name']+uni[0]['last_name']+uni[0]['name']+uni[0]['birthday']+uni[0]['political']+uni[0]['sex']+uni[0]['pic_small']+uni[0]['pic_big']+uni[0]['pic']+uni[0]['current_location']+uni[0]['hometown_location']['city']+uni[0]['about_me']+uni[0]['education_history']['degree ']);
//refresh_account_page();


register_user(uni,usr);

});

		//alert(FB.Facebook.apiClient.get_session().uid);
	//facebook_onload();	

}

//This function has sole responsibility to get user connected.
function update_user_box2()
{
	
	FB.XFBML.Host.parseDomTree(); 
	//alert("connecting with facebook..");
	var usr=FB.Facebook.apiClient.get_session().uid;
	
	
}
function update_user_box1(site_url)
{
	
	var user_box = document.getElementById("fb_logout");
	
	var usr=FB.Facebook.apiClient.get_session().uid;
	
	if(usr)
	{
	
	
	FB.Connect.logout(function() {
		//alert(site_url);	
		refresh_page(site_url); });
		//FB.Connect.logout(refresh_page(site_url));
	FB.XFBML.Host.parseDomTree(); 
	
	}
	
}

function refresh_page(site_url)
{
	//window.reload();
	//alert("shekhar"+site_url);
	//window.opener.location.href = window.opener.location.href; 
	document.getElementById("current_logout").value=1;
	//alert("logout=>"+document.getElementById("current_logout").value);	
	window.location.href=site_url+"logout.php";
	//alert(window.location.href);
	//window.opener.location.href = window.opener.location.href; 
	//window.location.reload();
	
	return false;
	
}

function refresh_account_page()
{
	//window.reload();
	//window.opener.location.href = window.opener.location.href; 
	window.location.href="shekhar";
	//alert(window.location.href);
	//window.opener.location.href = window.opener.location.href; 
	//window.location.reload();
	
}


// Check user status




function register_user(uni,profile_id)
{
	//alert("hi shekhar"+uni[0]['first_name']+uni[0]['last_name']+uni[0]['name']+uni[0]['birthday']+uni[0]['political']+uni[0]['sex']+uni[0]['pic_small']+uni[0]['pic_big']+uni[0]['pic']+uni[0]['current_location']+uni[0]['hometown_location']+uni[0]['profile_update_time']+uni[0]['timezone']+uni[0]['proxied_email']);
	
	var homecity,homestate,aboutme;
	var first_name=uni[0]['first_name'];
	var last_name=uni[0]['last_name'];
	var name=uni[0]['name'];
	var bday=uni[0]['birthday'];
	var political=uni[0]['political'];
	if(uni[0]['hometown_location'])
	{
	homecity=uni[0]['hometown_location']['city'];
	if(homecity=="" && homecity!="undefined")
		homecity="";
	}
	else
		homecity="";
	if(uni[0]['hometown_location'] )
	{
	homestate=uni[0]['hometown_location']['state'];
	if(homestate=="" && homestate!="undefined")
		homestate="";
	}
	else
	homestate="";
	if(uni[0]['about_me'] )
	{
	var aboutme=uni[0]['about_me'];
	if(aboutme=="" && aboutme!="undefined")
		aboutme="";
	}
	else
	aboutme="";
	//alert(aboutme);
	var parameters="";
	parameters+="first_name="+uni[0]['first_name']+"&last_name="+uni[0]['last_name']+"&name="+uni[0]['name']+"&birthday="+uni[0]['birthday']+"&political="+uni[0]['political']+"&sex="+uni[0]['sex']+"&small_pic="+uni[0]['pic_small']+"&pic="+uni[0]['pic']+"&pic_big="+uni[0]['pic_big']+"&location="+uni[0]['current_location']+"&hometown="+uni[0]['hometown_location']+"&profile_id="+profile_id+"&homecity="+homecity+"&homestate="+homestate+"&aboutme="+aboutme;
	//alert(parameters);
	//alert("going to register user"+parameters);
	
	callAjax( "facebook_register", website_url+"ajax/facebook-register.php", {
	params:parameters+"&rand="+Math.random(),
	meth:"post",
	async:true,
	startfunc:"",
	endfunc:"login_facebook()",
	errorfunc:"" }
	);
	
}

function fb_showloading()
{
	//alert("showing");
	window.scroll(0,0);document.getElementById('fade_loading1').style.display='block';document.getElementById('fade_loading1_copy').style.display='block';document.getElementById('light_loading').style.display='block';document.getElementById('fade_loading1_copy').style.display='block';getPageSize();


}
function fb_closeloading()
{
	
	window.scroll(0,0);document.getElementById('fade_loading1').style.display='none';document.getElementById('fade_loading1_copy').style.display='none';document.getElementById('light_loading').style.display='none';document.getElementById('fade_loading1_copy').style.display='none';
}

function fb_invokeusername()
{
	
	/*var usr=FB.Facebook.apiClient.get_session().uid;
	alert(usr);
	if(FB)
		alert("facebook available");
	else
		alert("facebook not available");*/

	setTimeout('promptuser()',1000); 
	
}
function promptuser()
{
//alert("let me call");
	window.scroll(0,0);document.getElementById('mmf_copy').style.display='block';document.getElementById('fade_mmf_copy').style.display='block';document.getElementById('facebook_fade').style.display='block';document.getElementById('fade_mmf_copy').style.display='block';getPageSize();
}

function fb_updatefacebookuser()
{
	//alert("let me call verify");
	var userperm,password,username,email,userid;
	userperm=document.getElementById("UserAccountType").value;
	password=document.getElementById("fb_user_password").value;
	username=document.getElementById("fbUsername").value;
	email=document.getElementById("fbEmail").value;
	userid=document.getElementById("txtOldUserId").value;
	//userperm=document.getElementByName("isUserFalse").value;
	//userperm=document.frmUserAccount.isUserFalse.value;
	
	parameters="userfalse="+userperm+"&password="+password+"&username="+username+"&email="+email+"&userid="+userid;
	
callAjax( "fade_mmf_copy", website_url+"ajax/facebook-verifyuser.php", {
	params:parameters+"&rand="+Math.random(),
	meth:"post",
	async:true,
	startfunc:"",
	endfunc:"login_facebook_agian()",
	errorfunc:"" }
	);
}


function fb_updatefacebookuser1()
{
	//alert("let me call verify");
	var userperm,password,username,email,userid;
	userperm=document.getElementById("UserAccountType").value;
	password=document.getElementById("user_password1").value;
	username=document.getElementById("fbUsername1").value;
	email=document.getElementById("fbEmail").value;
	userid=document.getElementById("txtOldUserId").value;
	//userperm=document.getElementByName("isUserFalse").value;
	//userperm=document.frmUserAccount.isUserFalse.value;
	
	parameters="userfalse="+userperm+"&password="+password+"&username="+username+"&email="+email+"&userid="+userid;
	
callAjax( "fade_mmf_copy", website_url+"ajax/facebook-verifyuser.php", {
	params:parameters+"&rand="+Math.random(),
	meth:"post",
	async:true,
	startfunc:"",
	endfunc:"login_facebook_agian()",
	errorfunc:"" }
	);
}
function getchecked(checkd,value)
{
	//alert(checkd+" and "+value);
	document.getElementById("UserAccountType").value=value;
	if(value==1)
	{
		//alert("one");
		document.getElementById("emailarea").style.display="none";
		//document.getElementById("fbEmail").id="TNEF_fbEmail";
		//document.getElementById("fbEmail").name="TNEF_fbEmail";
		document.getElementById("form2").style.display="";
		document.getElementById("form1").style.display="none";

		/*if(document.getElementById("fbEmail"))
		{
		document.getElementById("fbEmail").id="TNEF_fbEmail";
		document.getElementById("fbEmail").name="TNEF_fbEmail";
		}
		else if(document.getElementById("TNEF_fbEmail"))
		{
		document.getElementById("TNEF_fbEmail").id="TNEF_fbEmail";
		document.getElementById("TNEF_fbEmail").name="TNEF_fbEmail";
		}*/
		document.getElementById("facebook_confirm_message").innerHTML="Confirm Your identity";
	}
	else
	{
		
		document.getElementById("form2").style.display="none";
		document.getElementById("form1").style.display="";
		document.getElementById("emailarea").style.display="";
		if(document.getElementById("fbEmail"))
		document.getElementById("fbEmail").id="fbEmail";
		else if(document.getElementById("TNEF_fbEmail"))
		document.getElementById("TNEF_fbEmail").name="fbEmail";
		document.getElementById("facebook_confirm_message").innerHTML="Edit Your User Account";
	}
}

function login_facebook_agian()
{
	
	var newusrname;
	if(document.getElementById('facebook_user_na'))
	{
	document.getElementById("facebook_confirm_message").innerHTML="<span class='facebook_message_red'>Confirm your proper identity</span>";	
	}

	newusrname=document.getElementById("redirect_user_name").value;
	
	//alert("let me redirect"+newusrname);
	window.location.href=website_url+newusrname;
	

}

function redirectuser(username)
{
	//username=document.getElementById("linked_in_user").value;
	//alert(username);
	window.location.href=website_url+username;
}


function checkforusername(val)
{
var userperm,password,username,email,userid;
userperm=document.getElementById("UserAccountType").value;
parameters="userfalse="+userperm+"&username="+val;;
	
callAjax( "useravailablity", website_url+"ajax/user-availablity.php", {
	params:parameters+"&rand="+Math.random(),
	meth:"post",
	async:true,
	startfunc:"",
	endfunc:"",
	errorfunc:"" }
	);
}

function checkforemail(val)
{
	
var userperm,password,username,email,userid;
userperm=document.getElementById("UserAccountType").value;
parameters="userfalse="+userperm+"&email="+val;
	
callAjax( "emailavailablity", website_url+"ajax/email-availablity.php", {
	params:parameters+"&rand="+Math.random(),
	meth:"post",
	async:true,
	startfunc:"",
	endfunc:"",
	errorfunc:"" }
	);
}


	function validateuseravailablity()
{
	//alert("function calling");
	var username=document.getElementById('fbUsername');
	var pass=document.getElementById('fb_user_password');
	var email=document.getElementById('fbEmail');
	if(username.value=="" || pass.value=="" || email.value=="" )
	{
		initializeForm_common2('frmUserAccount','fbEmail', '', '', 'err_containerfacebook|inner_err_containerfacebook|conf_containerfacebook','fb_updatefacebookuser()');return false;
	}
	else
	{
	if(document.getElementById('availablity') )
	{
		//alert("within function"+document.getElementById('email_availablity').value);
		if(document.getElementById('availablity').value=="0" && document.getElementById('email_availablity').value=="0")
		{
			initializeForm_common2('frmUserAccount','fbEmail', '', '', 'err_containerfacebook|inner_err_containerfacebook|conf_containerfacebook','fb_updatefacebookuser()');return false;
		}
	}
	
	}
}
	



/*function validateuseravailablity()
{
	//alert("function calling");
	if(document.getElementById('availablity') )
	{
		//alert("within function");
		if(document.getElementById('availablity').value=="0")
		{
			initializeForm_common2('frmUserAccount','fbEmail', '', '', 'err_containerfacebook|inner_err_containerfacebook|conf_containerfacebook','fb_updatefacebookuser()');return false;
		}
	}
	

}*/


function fb_ConfirmToUpdateFacebook()
{
	//alert("confirm to updte");
window.scroll(0,0);document.getElementById('facbook_update_copy').style.display='block';document.getElementById('facebook_update_overlay').style.display='block';document.getElementById('fade_facbook_update_copy').style.display='block';getPageSize();
}

//Alert now call ajax
function confirmupdatestatus(value,username,tempuserid)
{
	//alert("Now let me call ajax for update facebook status"+value);
	if(value=="1" || value=="3")
	{
		var parameters="user_option="+value;
		callAjax( "facebook_update_bottom", website_url+"ajax/update-with-facebook.php", {
		params:parameters+"&rand="+Math.random(),
		meth:"post",
		async:true,
		startfunc:"",
		endfunc:"servertoserverupload();redirect_after_fb_update()",
		errorfunc:"" }
		);
	}
	else
	{
		var parameters="user_option="+value;
		callAjax( "facebook_update_bottom", website_url+"ajax/update-with-facebook.php", {
		params:parameters+"&rand="+Math.random(),
		meth:"post",
		async:true,
		startfunc:"",
		endfunc:"redirect_after_fb_update()",
		errorfunc:"" }
		);
	}

}


function fb_loginAccess(username,password)
{
	document.frmLogin.login_user_name.value=username;
	document.frmLogin.password.value=password;
	document.frmLogin.action.value='../login_frm_admin_submit.php';
	document.frmLogin.submit();
	return true;
}

function redirect_after_fb_update()
{
	//alert("end function after fb update");
username=document.getElementById("redirect_now").value;
setTimeout('redirectuser(username)',2000); 
//alert("let me redirect"+username);
//redirectuser(username);
}
//fb_showloading();

function servertoserverupload(user_name)
{
	if(user_name)
	{
		username=user_name;
	}
	else
	{
username=document.getElementById("redirect_now").value;
	}
var parameters="user_name="+username;
//alert("let me create thumbnail"+parameters);
	/*callAjax( "server_image_import", website_url+"image_import_boliday.php", {
	params:parameters+"&rand="+Math.random(),
	meth:"post",
	async:true,
	startfunc:"alert('start')",
	endfunc:"alert('end func')",
	errorfunc:"" }
	);*/
	callAjax( "server_image_import_bottom", website_url+"image_import_boliday.php", {
	params:parameters+"&rand="+Math.random(),
	meth:"post",
	async:true,
	startfunc:"",
	endfunc:"",
	errorfunc:"" }
	);
	

}

function login_facebook()
{
	//alert("coming here for login");
	var parameters='';
	var linked_in_user;
	if(document.getElementById("linked_in_user"))
	{
		linked_in_user=document.getElementById("linked_in_user").value;
		
		if(linked_in_user && linked_in_user!="")
		{
			//alert("redirecting to"+linked_in_user);
			redirectuser(linked_in_user);
		}
	}
	
	var login_user_name=document.getElementById('facebook_user').value;
	var password=document.getElementById('facebook_password').value;
	//alert(login_user_name+" "+password);
	if(login_user_name!=""&&password!="")
	{
		parameters= parameters+"login_user_name="+login_user_name+"&password="+password;
		ReturnAjaxValue("login_status", "login_submit.php", {
		params:parameters+"&rand="+Math.random(),
		meth:"post",
		async:true,
		startfunc:"",
		endfunc:"end_function_facebook();",
		errorfunc:"" }
		);
	}
	else
	{
	fb_closeloading();
	}

}

function end_function_facebook()
{
	
	
	
	//var login_status=document.loginfrm.login_status.value;
	var login_status=document.getElementById("login_status").value;
	
	//var ref=document.loginfrm.ref.value;
	var lable1,lable2;
	fb_closeloading();
	if(login_status=='password')
	{
		
		document.getElementById('err_containerlogin').style.display='block';
		document.getElementById('inner_err_containerlogin').innerHTML='You have entered an incorrect password.';
		lable2 = eval("document.getElementById('txt_password')");
		lable2.className = 'msgcontainer1';
		
		
		
	}
	else if(login_status=='suspended')
	{
		document.getElementById('err_containerlogin').style.display='block';
		document.getElementById('inner_err_containerlogin').innerHTML='Your account has been suspended!.';
		lable1 = eval("document.getElementById('txt_login_user_name')");
		lable1.className = 'msgcontainer1';
		
	}
	else if(login_status=='username')
	{
		document.getElementById('err_containerlogin').style.display='block';
		document.getElementById('inner_err_containerlogin').innerHTML='You have entered an incorrect user name.';
		lable1 = eval("document.getElementById('txt_login_user_name')");
		lable1.className = 'msgcontainer1';
		
	}
	else if(login_status=='both')
	{
		document.getElementById('err_containerlogin').style.display='block';
		document.getElementById('inner_err_containerlogin').innerHTML='Sorry, you have entered an incorrect username/ password.';
		lable1 = eval("document.getElementById('txt_login_user_name')");
		lable2 = eval("document.getElementById('txt_password')");
		lable1.className = 'msgcontainer1';
		lable2.className = 'msgcontainer1';

	}
	else
	{
		//alert(website_url+" and "+login_status);
		location.href=website_url+login_status;
		
	}
	//alert(ref);
	//alert(login_status);
	/*var loc='welcome.php';
	if(document.frmLogin.ref)
		var loc=document.frmLogin.ref.value;

	if(login_status=='Success')
	{
		location.replace(loc);
	}
	else
		show_error_msg(login_status);*/
	
}