var conf = {
	APIKey: '2_847XhCe0zygxwG2Cnki_Jk--UI5FuxDzU5ZQUqr4NIMtMDfYYhu12nOOcfkPyqKI',
	enabledProviders: 'facebook,twitter,google'
}
var login_params = {
	showTermsLink: 'false',
	height: 230,
	width: 310,
	buttonsStyle: 'fullLogo',
	autoDetectUserProviders: '',
	facepilePosition: 'none',
	hideGigyaLink: true //,redirectURL: "{/literal}http://{$smarty.server.SERVER_NAME}{$smarty.server.REQUEST_URI}{literal}",
}
function social() {
	this.cookieDomain = '.syfy.com'; // take this out or set it static later
	this.facebook();
	this.twitter();
	jqN('.login').live('click', function() {
		gigya.services.socialize.showLoginUI(conf, login_params);
	});
	jqN('.logout').live('click', function() {
		gigya.services.socialize.logout(conf, {
			callback: this.gigyaLogout
		});
	});
	jqN('.deleteemail').live('click', function() {
		socialConnect.deleteEmail();
	});
	jqN('#emailModal button').live('click', function() {
		var valid = validateEmail();
		if (valid === false) {} else {
			socialConnect.email = jqN('.email').val();
			socialConnect.gigyaLogin(socialConnect.u);
		}
		return false;
	});
	gigya.services.socialize.addEventHandlers(conf, {
		onLogin: this.gigyaLogin,
		onLogout: this.gigyaLogout
	});
	gigya.services.socialize.getUserInfo(conf, {
		callback: this.checkLoggedIn
	});
}
social.prototype.checkLoggedIn = function(r) {


	if (r.errorCode === 0) {
		if (r.UID) {
			socialConnect.syfyuid = r.UID;
			socialConnect.nickname = r.user.nickname;
			socialConnect.photoURL = r.user.photoURL;
			jqN.cookie('syfyuid', r.UID, {
				path: '/',
				domain: ".syfy.com",
				secure: false
			});
			if (typeof rewards_init == 'function' && !socialConnect.reload) rewards_init();

		} else {
			if (jqN.cookie('syfyuid')) {
				this.syfyuid = jqN.cookie('syfyuid');
			} else {
				uid = 'anon_' + jqN.md5(Math.random());
				jqN.cookie('syfyuid', uid, {
					path: '/',
					domain: ".syfy.com",
					secure: false
				});
				this.syfyuid = uid;
			}
			socialConnect = this;
			
			if (typeof rewards_init == 'function' && !socialConnect.reload) rewards_init();
		}
			if(socialConnect.reload == true){
				window.location.reload(true);
			}

	} else {
		console.log('Error :' + r.errorMessage);
	}
	
}
social.prototype.deleteEmail = function(r) {
	var params = {
		settings: "email",
		group: 'syfySettings'
	};
	gigya.services.socialize.delUserSettings(conf, params);
}

social.prototype.checkEmail = function(r) {
	if (r.errorCode == 0) {
		if (typeof r.settings.email != 'undefined') {
			socialConnect.u.email = r.settings.email.current;
			socialConnect.reload=true;
			gigya.services.socialize.getUserInfo(conf, {
				callback: socialConnect.checkLoggedIn
			});					
		} else {			
			if (socialConnect.email || (socialConnect.u && socialConnect.u.user.email)) {
				if (socialConnect.email) {
					email = socialConnect.email;
				} else {
					email = socialConnect.u.user.email;
				}
				var params = {
					settings: {
						'email': {
							current: email,
							neverShare: true
						}
					},
					group: 'syfySettings'
				};
				gigya.services.socialize.setUserSettings(conf, params);
				socialConnect.u.email = socialConnect.u.user.email;
				socialConnect.reload=true;
				gigya.services.socialize.getUserInfo(conf, {
					callback: socialConnect.checkLoggedIn
				});		
			} else {
				socialConnect.emailDialog();
				socialConnect.reload=false;
			}
		}
	} else {

		console.log('Error :' + r.errorMessage);
	}
}
social.prototype.emailDialog = function() {
	socialConnect.reload = false;
	jqN.modal('<div id="emailModal" class="affinity_popup"><div class="content gradient_horizontal"><h3>Almost there!</h3><p>Great we got you logged in but we need your Email address in order to earn real world rewards. Don\'t want to give us your email? Then just close this box and you can still play. </p><form><div><label>Enter Email </label><input name="email" class="email" type="text" size="30"></div><button type="button" value="Register">Register</button></form></div></div>', {
		onClose: function(dialog) {
			jqN.modal.close(); // must call this!
				socialConnect.reload=true;
				gigya.services.socialize.getUserInfo(conf, {
					callback: socialConnect.checkLoggedIn
				});		
		},
		opacity: '90',
		zIndex: '10000',
		closeClass: 'affinityClose'
	});
}
social.prototype.gigyaLogout = function(r) {
        jqN.cookie('syfyuid', null, {
                path: '/',                                        
                domain: ".syfy.com",
                secure: false
        });
        jqN.cookie('sessionKey', null, {
                path: '/',
                domain: ".syfy.com",
                secure: false
        });

	window.location.reload(true);
}
social.prototype.gigyaLogin = function(u) {

        jqN.cookie('syfyuid', u.UID, {
                path: '/', 
                domain: ".syfy.com",
                secure: false
        });
        jqN.cookie('sessionKey', null, {
                path: '/',
                domain: ".syfy.com",
                secure: false
        });
	
	socialConnect.u = u;
	var params = {
		callback: socialConnect.checkEmail,
		settings: "email",
		group: 'syfySettings'
	};
	gigya.services.socialize.getUserSettings(conf, params);

	
}
social.prototype.facebook = function() {
	var self;
	self = this;
	FB.init({
		appId: '128815553796234',
		status: true,
		oauth: true,
		// check login status
		cookie: true,
		// enable cookies to allow the server to access the session
		xfbml: true // parse XFBML
	});
}
social.prototype.postFacebook = function(params) {
	var self;
	self = this;
	FB.ui({
		method: 'feed',
		name: params['name'],
		link: params['link'],
		picture: params['picture'],
		caption: params['caption'],
		description: params['description'],
		message: params['message']
	}, function(response) {
		if (response && response.post_id) {} else {}
	});
}
social.prototype.testFeed = function() {
	this.T.Status.search("happy").each(function(status) {
		//console.log('got a status');
	});
}
social.prototype.loginFacebook = function(params) {
	var self;
	self = this;
	FB.login(function(response) {
		if (response.session) {} else { // user cancelled login
		}
	}, {
		perms: 'read_stream,publish_stream'
	});
}
social.prototype.twitter = function() {
	var self;
	self = this;
	if (typeof twttr != 'undefined') {
		twttr.anywhere(function(T) {
			self.T = T;
		}); //END Twitter @anywhere functions
	}
}
social.prototype.postTwitter = function(params) {
	var snap;
	var self;
	self = this;
	//jqN('body').prepend('<div id="msg-popup-wrapper"></div><div id="msg-popup" class="message"><span class="msg-body"><div id="tbox"></div></span><span class="close"></span></div>');
	jqN("#msg-popup-wrapper").css("height", jqN(document).height());
	jqN("#msg-popup").css("margin-top", "30px");
	jqN("#msg-popup").css("left", (jqN(window).width() - jqN("#msg-popup").width()) / 2 + jqN(window).scrollLeft() + "px");
	jqN("#msg-popup").makeFloat({
		x: "current",
		y: "current"
	});
	jqN(".close").click(function() {
		jqN("#msg-popup-wrapper").remove();
		jqN("#msg-popup").remove();
	});
	if (this.T && this.T.isConnected()) {
		this.tweetbox(params['message']);
	} else {
		self.T.bind("authComplete", function(e, user) { // triggered when auth completed successfully
			this.tweetbox(params['message']);
		});
		this.T.signIn();
	};
}
social.prototype.tweetbox = function(text) {
	var self;
	self = this;
	this.T("#tbox").tweetBox({
		label: '<style>div#tweet-box-container div#tweet-box-header label {color:#fff;	}</style>Share your Vote!',
		height: 75,
		width: 280,
		defaultContent: text,
		onTweet: function(data) {
			self.postSuccess('Twitter')
		}
	});
	jqN('#tweet-box-container label').css('color', '#fff');
}
social.prototype.postSuccess = function(snap) {
	this.message('Thanks for sharing this to ' + snap + '');
}
social.prototype.postError = function(snap) {
	this.message('Sorry there was a problem sharing this to ' + snap + '.  Please try again.');
}
social.prototype.message = function(text) {
	jqN("#msg-popup-wrapper").remove();
	jqN("#msg-popup").remove();
	jqN('body').prepend('<div id="msg-popup-wrapper"></div><div id="msg-popup" class="message"><span class="msg-body">' + text + '</span><span class="close"></span></div>');
	jqN("#msg-popup-wrapper").css("height", jqN(document).height());
	jqN("#msg-popup").css("margin-top", "30px");
	jqN("#msg-popup").css("left", (jqN(window).width() - jqN("#msg-popup").width()) / 2 + jqN(window).scrollLeft() + "px");
	jqN("#msg-popup").makeFloat({
		x: "current",
		y: "current"
	});
	jqN(".close").click(function() {
		jqN("#msg-popup-wrapper").remove();
		jqN("#msg-popup").remove();
	});
}
var socialConnect;

function social_init() {
	socialConnect = new social();
}
jqN(document).ready(function() {
	social_init();
});

function validateEmail() {
	jqN(".error").hide();
	var hasError = false;
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	var emailaddressVal = jqN(".email").val();
	if (emailaddressVal == '') {
		jqN(".email").after('<span class="error">Please enter your email address.</span>');
		hasError = true;
	} else if (!emailReg.test(emailaddressVal)) {
		jqN(".email").after('<span class="error">Enter a valid email address.</span>');
		hasError = true;
	}
	if (hasError === true) {
		return false;
	}
}
/**
 * Concatenates the values of a variable into an easily readable string
 * by Matt Hackett [scriptnode.com]
 * @param {Object} x The variable to debug
 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
 * @param {String} sep The separator to use between [default: a single space ' ']
 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
 */


function print_r(x, max, sep, l) {
	l = l || 0;
	max = max || 10;
	sep = sep || ' ';
	if (l > max) {
		return "[WARNING: Too much recursion]\n";
	}
	var i, r = '',
		t = typeof x,
		tab = '';
	if (x === null) {
		r += "(null)\n";
	} else if (t == 'object') {
		l++;
		for (i = 0; i < l; i++) {
			tab += sep;
		}
		if (x && x.length) {
			t = 'array';
		}
		r += '(' + t + ") :\n";
		for (i in x) {
			try {
				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
			} catch (e) {
				return "[ERROR: " + e + "]\n";
			}
		}
	} else {
		if (t == 'string') {
			if (x == '') {
				x = '(empty)';
			}
		}
		r += '(' + t + ') ' + x + "\n";
	}
	return r;
}
var_dump = print_r;

