var gigyaConf = {
	enabledProviders:'facebook,google,yahoo' //control the list of providers and their order in the login ui here
};
var gigyaConfFbOnly = {
	enabledProviders:'facebook' //control the list of providers and their order in the login ui here FACEBOOK ONLY
};

var gigyaConfFacebookOnly = {
	enabledProviders:'facebook' //control the list of providers and their order in the login ui here
};

var shareURL="";
var custMsg="";

//params for social registration ui
var socialSignupParams = {
	enabledProviders:'google,yahoo'
	,showTermsLink: 'false' //hide Gigya terms link
	,hideGigya: 'true' //hide Gigya logo
	,lastLoginIndication:'none' //none = do not display last login border
	,width: 107 //social signup ui width
	,height: 32 //social signup ui height
	,containerID: 'socialSignupDiv' //HTML div id in which to display social signup ui
	,UIConfig: '<config><body><controls><snbuttons buttonsize="32"></snbuttons></controls><background background-color="Transparent"></background></body></config>' //ui settings
	,autoDetectUserProviders: '' //empty = do not detect Facebook Connect
	,facepilePosition: 'none' //none = hide Facebook facepile
	,cid: 'registration'
	,context: 'signup' //variable to know if the gigya login is from the signup or login ui
	,pendingRegistration: 'true' //flag to timeout gigya profile creation is user cancels registration process
};

//params for social login ui
var socialLoginParams = {
	showTermsLink: 'false' //hide Gigya terms link
	,hideGigya: 'true' //hide Gigya logo
	,lastLoginIndication:'border' //border = green border; star = star overlay on icons; none = do not display last login border
	,width: 26 //social login ui width
	,height: 26 //social login ui height
	,containerID: 'socialLoginDiv' //HTML div id in which to display social login ui
	,UIConfig: '<config><body><controls><snbuttons buttonsize="25"></snbuttons></controls><background background-color="Transparent"></background></body></config>' //ui settings
	,autoDetectUserProviders: '' //empty = do not detect Facebook Connect
	,facepilePosition: 'none' //none = hide Facebook facepile
	,cid: 'login'
	,context: 'login' //variable to know if the gigya login is from the signup or login ui
};

//params for social login modal ui
var socialLoginModalParams = {
	showTermsLink: 'false' //hide Gigya terms link
	,hideGigya: 'true' //hide Gigya logo
	,lastLoginIndication:'none' //border = green border; star = star overlay on icons; none = do not display last login border
	,width: 180 //social login ui width
	,height: 240 //social login ui height
	,containerID: 'socialLoginModalDiv' //HTML div id in which to display social login ui
	,UIConfig: '<config><body><controls><snbuttons buttonsize="50"></snbuttons></controls><background background-color="Transparent"></background></body></config>' //ui settings
	,buttonsStyle: 'fullLogo'
	,autoDetectUserProviders: '' //empty = do not detect Facebook Connect
	,facepilePosition: 'none' //none = hide Facebook facepile
	,cid: 'login modal'
	,context:'login' //variable to know if the gigya login is from the signup or login ui
};

//triggered when gigya login event fires
function onGigyaAuthHandler(response) {
	//response.eventName
	//response.source
	//response.user
	//response.UIDSignature
	//response.signatureTimestamp
	//response.UID
	//response.provider

	//determine which user flow scenario
	if("signup" == response.context) { //social registration buttons
		if(response.user.isSiteUID) { //existing user
			//
			// add code here if you want to display a message to the user, e.g.
			// alert(response.user.email+" is an existing user");
			//
			log_event("home-index.php-gigya-social-signup-"+response.provider+"-existing-user-"+response.user.email);
			//since user already exists, continue w/ regular social login
			socialLoginHandler(response);
		} else { //new user
			log_event("home-index.php-gigya-social-signup-"+response.provider);
			socialSignupHandler(response);
		}
	} else { //social login buttons
		//console.log(response);
		if(response.user.isSiteUID) { //existing user
			log_event("home-index.php-gigya-social-login-"+response.provider);
			socialLoginHandler(response);
		} else { //link accounts path
			log_event("home-index.php or login.php gigya social login. Provider: '" + response.provider + "'. Unrecognized user: '" + response.user.email + "'.");
			//populate hidden input fields
			$("#link-guid").val(response.UID);
			$("#link-timestamp").val(response.signatureTimestamp);
			$("#link-signature").val(response.UIDSignature);
			$("#link-provider").val(response.user.loginProvider);
			
			//display user's profile image
			if(null != response.user.thumbnailURL & "" != response.user.thumbnailURL){
				//$("#profile-img").attr("src",response.user.thumbnailURL);
				$("#profile-img").css({background:'url(' + response.user.thumbnailURL + ') no-repeat 0 0 transparent'});
			} else {
				//$("#profile-img").hide();
			}
			
			//Pre-populate email address
			$("#form_login_link").val(response.user.email);
			
			//display user's first name
			if(null != response.user.firstName && "" != response.user.nickname) {
				$(".social-username").text(response.user.nickname);
			}
			
			////stuff variables into existing registation form in case user clicks on signup link
			populateSignupForm(response);

			$.colorbox({
				inline:true,
				fixed:true,
				opacity:0,
				scrolling:false,
				href: "#gigya-link-accnt-modal"
			}, function(){
				//Callback if needed
			});
		}
	}
}

//handle the social registration path
function socialSignupHandler(response) {
	//response.user
	//response.UIDSignature
	//response.signatureTimestamp
	//response.UID
	//response.provider
	
	//stuff variables into existing registation form
	populateSignupForm(response);
	
	//fire registration form submit
//	$("#ajaxregisteration").submit();
	$("#submit-signup").click();
	
}

//populate social variables into existing registation form
function populateSignupForm(response) {
	$("#email-field").val(response.user.email);
	$("#social-signup").val(response.user.loginProvider);
	$("#gigya-uid").val(response.UID);
	$("#gigya-timestamp").val(response.signatureTimestamp);
	$("#gigya-signature").val(response.UIDSignature);
	$("#gigya-nickname").val(response.user.nickname);
	$("#gigya-city").val(response.user.city);
	$("#gigya-state").val(response.user.state);
}

//handle the social login path
function socialLoginHandler(response) {
	//response.user
	//response.UIDSignature
	//response.signatureTimestamp
	//response.UID
	//response.provider
	
	//dynamically create a form and submit for social login
	submitValues("/l/loginsocial.php",{
		"gigya-uid": response.UID
		,"gigya-timestamp":response.signatureTimestamp
		,"gigya-signature":response.UIDSignature
		,"gigya-provider":response.user.loginProvider
	});
}

//initial registration using facebook
function socialFacebookSignup() {
	gigya.services.socialize.login(gigyaConf,{
		provider:'facebook'
		,pendingRegistration:'true'
		,cid:'registration'
		,context:'signup'
	});
}

//dynamically create a form object w/ given params
function submitValues(url, params) {
	var form = [ '<form method="POST" action="', url, '">' ];

	for(var key in params) {
		form.push('<input type="hidden" name="', key, '" value="', params[key], '"/>');
	}
	form.push('</form>');

	$(form.join('')).appendTo('body')[0].submit();
}

//default params for share ui
var socialShareParams = {
	userAction: null
	,showEmailButton: true
	,showMoreButton: false
	,cid: ''
	,context: null
	,operationMode: 'multiSelect'
	,enabledProviders: 'facebook,twitter,google,yahoo'
	,showSuccessMessage: true
	,grayedOutScreenOpacity: 0 //0-(20)-100
	,initialView: 'share' //share, more, email
	,shortURLs: 'always' //always, whenRequired, never
//	,shareTimeout: 30 //seconds (integer)
	,showTooltips: false
	,dontSendEmail: true
	,emailBody: "this is the email body"
	,emailProviders: 'google,yahoo'
	,onLoad: function(response) {
//		log_event(response.source+"."+response.eventName+"-on-"+response.context.cid);
	}
	,onError: function(response) {
		log_event(response.source+"."+response.eventName+"-on-"+response.context.cid+"-("+response.errorCode+")-"+response.errorMessage);		
	}
	,onClose: function(response) {
		log_event(response.source+"."+response.eventName+"-on-"+response.context.cid);
	}
	,onSendDone: function(response) {
		postShareHandler(response);
	}
};

function showSocialShare(o) {
	//retrieve sharing url
	shareURL = o.linkUrl;
	custMsg = o.usrMsg;
	//user action object for share
	var act = new gigya.services.socialize.UserAction();
	act.setUserMessage(o.usrMsg);   // Setting the default user message
	act.setTitle(o.title);  // Setting the Title
	act.setLinkBack(o.linkUrl);  // Setting the Link Back
	act.setDescription(o.desc);   // Setting Description
	act.addActionLink(o.actLinkLabel, o.actLinkUrl);  // Adding Action Link
	// Adding a Media (image)
	act.addMediaItem( { type: 'image', src: o.imgSrc, href: o.imgHref });

	//user action object for twitter
	var tact = new gigya.services.socialize.UserAction();
	tact.setUserMessage(o.twitter);   // Setting the default user message
	tact.setTitle("");  // Setting the Title
	tact.setLinkBack(o.linkUrl);  // Setting the Link Back	
	tact.setDescription("");   // Setting Description
	tact.addActionLink(o.actLinkLabel, o.actLinkUrl);  // Adding Action Link
	tact.addMediaItem( { type: 'image', src: o.imgSrc, href: o.imgHref });
	
	var params = $.extend(true, {}, socialShareParams);
	params.emailBody = o.body;
	params.userAction = act;
	params.twitterUserAction = tact;
	params.cid = o.context;
	params.context = {
			cid:o.context
			,subject:o.title
			,body:o.usrMsg+"<br/><br/>"+o.body
	};
	
	gigya.services.socialize.showShareUI(gigyaConf,params);
	
}

var socialEmailParams = {
	userAction: null
	,showEmailButton: true
	,showMoreButton: false
	,cid: ''
	,context: null
	,operationMode: 'multiSelect'
	,enabledProviders: 'facebook,twitter,google,yahoo'
	,showSuccessMessage: true
	,grayedOutScreenOpacity: 0 //0-(20)-100
	,initialView: 'email' //share, more, email
	,shortURLs: 'always' //always, whenRequired, never
//	,shareTimeout: 30 //seconds (integer)
	,showTooltips: false
	,dontSendEmail: true
	,emailBody: "this is the email body"
	,emailProviders: 'google,yahoo'
	,onLoad: function(response) {
//		log_event(response.source+"."+response.eventName+"-on-"+response.context.cid);
	}
	,onError: function(response) {
		log_event(response.source+"."+response.eventName+"-on-"+response.context.cid+"-("+response.errorCode+")-"+response.errorMessage);		
	}
	,onClose: function(response) {
		log_event(response.source+"."+response.eventName+"-on-"+response.context.cid);
	}
	,onSendDone: function(response) {
		postShareHandler(response);
	}
};

function showSocialEmail(o) {
	
	//user action object for share
	var act = new gigya.services.socialize.UserAction();
	
	act.setUserMessage(o.usrMsg);   // Setting the default user message
	act.setTitle(o.title);  // Setting the Title
	act.setLinkBack(o.linkUrl);  // Setting the Link Back
	act.setDescription(o.desc);   // Setting Description
	act.addActionLink(o.actLinkLabel, o.actLinkUrl);  // Adding Action Link
	// Adding a Media (image)
	act.addMediaItem( { type: 'image', src: o.imgSrc, href: o.imgHref });

	//user action object for twitter
	var tact = new gigya.services.socialize.UserAction();
	tact.setUserMessage(o.twitter);   // Setting the default user message
	tact.setTitle("");  // Setting the Title
	tact.setLinkBack(o.linkUrl);  // Setting the Link Back	
	tact.setDescription("");   // Setting Description
	tact.addActionLink(o.actLinkLabel, o.actLinkUrl);  // Adding Action Link
	tact.addMediaItem( { type: 'image', src: o.imgSrc, href: o.imgHref });

	var params = $.extend(true, {}, socialEmailParams);
	params.emailBody = o.body;
	params.userAction = act;
	params.twitterUserAction = tact;
	params.cid = o.context;
	params.context = {
			cid:o.context
			,subject:o.title
			,body:o.usrMsg+"<br/><br/>"+o.body
	};
	
	gigya.services.socialize.showShareUI(gigyaConf,params);
}

function getNewBodyString(response){
	var b = response.context.body;
	var c = b.split("<br/><br/>");
	c.shift();
	var t = c.join("<br/><br/>");
	var a = response.userMessage+"<br/><br/>"+t;
	//alert(a+' b= '+b+' c= '+c+' t= '+t);
	return a;
}

/**
 * @author bennytjia
 * function to parse the url to get the offer and user ID
*/
function get_ID_packet(url){
	 var raw_id = url.substring(url.lastIndexOf('/')+1, url.length);  
	 return {	
		 		offer_id:raw_id.split("u")[0],
		 		user_id:raw_id.split("u")[1]
	 		};
}

/**
 * @author bennytjia
 * refactored the function that makes POST request so
 * that sharing information can be stored to DB through server side.
*/
function postShareHandler(response) {
	var success_str;
	var error_str;
	
	if("email" == response.providers) { //use offermatic email service
		log_event(response.source+"."+response.eventName+"-on-"+response.context.cid+"-email-from-"+response.sender);
		success_str = "social-email-via-offermatic-";
		error_str = "social-email-via-offermatic-error-";
		data_packet = {
						sender:response.sender
						,recipients:response.recipients
						,subject:response.context.subject
						,body:getNewBodyString(response)
					}
	} else {
		success_str = "social-non-email-sharing-via-offermatic-";
		error_str = "social-non-email-sharing-via-offermatic-error-";
		
		data_packet = {
						offer_id:get_ID_packet(shareURL).offer_id
						,user_id:get_ID_packet(shareURL).user_id
						,recipients:response.providers //in this case, the recipient is one of either facebook/twitter
						,cust_msg:custMsg
					}
	}
	
	$.ajax({
		type: 'POST'
		,url: "index.php?module=ConsumerDashboard&action=shareOffer"
		,data: data_packet
		,success: function(data, textStatus, jqXHR) {
			log_event(success_str+textStatus+"-"+data);
			//alert($("textarea").html());
		}
		,error: function(jqXHR, textStatus, errorThrown) {
			log_event(error_str+textStatus+"-"+errorThrown);
		}
//		,dataType: 'json'
	});
	
}
