/*
 * socialize custom settings
 */
var conf=
{
	//APIKey: '2_Is_70CUXajvd4vWdRD48vTJob7CntMUdpjguHktLqx7Hi-EkE8UnUvTQUYRDTZ3W' // for www.test.loc
	APIKey: sKey
	,enabledProviders: 'facebook'
	,lang: lang
}
var invite = 
{
	title: 'invite test text'
	,text: 'you are invited'
	,name: 'autosahora'
	,actionText: 'join now'
	,actionURL: 'http://www.autosahora.com/en/research/compare/my-account'
}
var login_params=
{
	showTermsLink: 'false'
	,hideGigyaLink: 'true'
	,height: '55'
	,width: '100'
	,containerID: 'socializeDiv'
	,UIConfig: '<config><body><controls><snbuttons buttonsize="45"></snbuttons></controls><background frame-color="Transparent" background-color=\"#effeff\"></background></body></config>'
	,useFacebookConnect: 'true'
	,invite: invite
}
var login_mini_params=
{
	showTermsLink: 'false'
	,hideGigyaLink: 'true'
	,height: '30'
	,width: '30'
	,containerID: 'socializeDiv_mini'
	,UIConfig: '<config><body><controls><snbuttons buttonsize="25"></snbuttons></controls><background frame-color="Transparent" background-color=\"#bcc4c9\"></background></body></config>'
	,useFacebookConnect: 'true'
	,invite: invite
}
var fs_params=
{
	hideGigyaLink: 'true'
	,showEditLink: 'false'
	,height: '360'
	,width: '400'
	,useFacebookConnect: 'true'
}
var connect_params=
{
	showTermsLink: 'false'
	,hideGigyaLink: 'true'
	,height: '60'
	,width: '100'
	,containerID: 'componentDiv'
	,UIConfig: '<config><body><background frame-color="Transparent" background-color=\"#effeff\"></background></body></config>'
	,useFacebookConnect: 'true'
}

/*
 * socialize custom functions
 */

function onLoginHandler(eventObj){
	logConsole(eventObj);
	
	cmSocialUser=new Object();
	// fields we want
	cmSocialUser.uid 	= eventObj.UID;
	cmSocialUser.fname 	= eventObj.user.firstName;
	cmSocialUser.lname 	= eventObj.user.lastName;
	cmSocialUser.email	= eventObj.user.email;
	cmSocialUser.profile_zip		= eventObj.user.zip;
	cmSocialUser.profile_gender		= parseProfileResponse(eventObj.user.gender,'gender');
	cmSocialUser.profile_birth_year	= eventObj.user.birthYear;
	cmSocialUser.profile_socialize_id	= eventObj.UID;
	
	// check whether we have this uid already,
	// if we don't then send them through the reg process
	var socUser = userExists(cmSocialUser.uid);
	if (socUser!=0){
		// log them in, they've already reg'd
		loginUser(cmSocialUser,socUser);
	} else if (cmSocialUser.email) {
		// push through full reg
		regUser(cmSocialUser,null);
	} else {
		// we at least need their email
		regPrompt(cmSocialUser);
	}

	logConsole(cmSocialUser);
}

function showSocializeOpts(eventObj){
	logConsole(eventObj);

	if(eventObj.loggedIn){
		jQueryCM('#friendSelectorLink').show();	
	} else {
		jQueryCM('#friendSelectorLink').hide();
		socializeConnect();
	}
}

function onLogoutHandler(eventObj) {  
	if (cmDebug){ alert('logged out'); }
}

// register a new user
function regUser(cmSocialUser, e){
	if(e){
		// plug the new stuff in to the form
		cmSocialUser.email = e;
		jQueryCM('#email').val(e);
	}
	// iterate through the fields we have and set them on screen
	jQueryCM.each(cmSocialUser, function(key, val) {
	  jQueryCM('#'+key).val(val);
    });
	setRanPass('pwd','pwd_confirm'); // generate and set random passwords
	
	if (cmDebug){ alert('[we have everything we need, register ' + cmSocialUser.email + ']'); }
	jQueryCM('#cmRegistration').submit();
	return true;
}

// login existing social user
function loginUser(cmSocialUser, socUser){
	//cmSoc
	if (cmDebug){ alert('login this existing user via social'); }
	
	jQueryCM.ajax({
		dataType:       'jsonp',
        success:        confirmLogin,
        type:           'get',
		data:			'login=1&username='+ socUser +'&pwd=cmSoc',
        url:            cmWebRoot+'/ws_user.php',
        clearForm:      true,
        timeout:        3000
    });
	
	return true;
}

function confirmLogin(){
	if (cmDebug){ alert('user authenticated via social'); }
	cmSetUser();
}

function regPrompt(cmSocialUser){
	if (cmDebug){ alert('We need their email address to complete registration'); }

	// iterate through the fields we have and set them on screen
	jQueryCM.each(cmSocialUser, function(key, val) {
	  jQueryCM('#'+key).val(val);
    });
	setRanPass('pwd','pwd_confirm'); // generate and set random passwords
	
	// prompt them to complete what's missing & required
	jQueryCM('#cmRegistration fieldset, #cmRegistration #socializeOpt, #cmRegistration .cmButtons').hide();
	jQueryCM('#socializeFeedback').html('<h2>Almost Done!</h2><p>In order to complete your registration we\'ll need your email address, please enter below:</p>');
	jQueryCM('#socializeReq').show();
	jQueryCM('#req-email').addClass('required');	
}

// check if a user exists
function userExists(uid){
	var exists = jQueryCM.ajax({
	  url: "/cmcore/user_exists.php?sid="+uid,
	  async: false
	});
	
	return exists.responseText;
}

/*
 * basic socialize calls
 */
function socializeLogout(){
   gigya.services.socialize.logout(conf);
}
 
/*
 * utilities
 */ 
function logConsole(eventObj) {
	// log to firefox console
	if(typeof(console) == 'object'){
		console.log(eventObj);
	}
}

function parseProfileResponse(v,k){
	if(k=='gender'){
		if(v=='m'){return 'Male'}else{return 'Female'};
	}
}

function setId(){
	var id = String(document.cookie.match(/PHPSESSID=[^;]+/));	
	id = id.replace(/PHPSESSID=/i,"");
	
}

function setRanPass(a,b){
	chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  	pass = "";
  	for(x=0;x<10;x++)
  	{
    	i = Math.floor(Math.random() * 62);
    	pass += chars.charAt(i);
  	}
	// temp
	pass = 'cmSoc';
  	if (cmDebug){ alert('Password set to ' + pass); }
	jQueryCM('#'+a).val(pass);
	jQueryCM('#'+b).val(pass);
}