// JavaScript Document
/*
	This document is used as part of the integration effort of the Open Graph and Facebook API to handle the events of 
	the 'like' button & login/logout button.

*/
				/*Do not change this section*/
				var FB=null;
				var FBappId = '127468840616839';
	            window.fbAsyncInit = function() {
	                FB.init({appId: FBappId, status: true, cookie: true, xfbml: true});
	 
	                /* All the events registered */
	                FB.Event.subscribe('auth.login', function(response) {
	                    // do something with response
	                    login();
	                });
	                FB.Event.subscribe('auth.logout', function(response) {
	                    // do something with response
	                    logout();
	                });
	 
	                FB.getLoginStatus(function(response) {
	                    if (response.session) {
	                        // logged in and connected user, someone you know
	                        checkZeeklerSession();
							checkFBLoginDataCookie();
	                    }
	                });
	            };
	            (function() {
	                var e = document.createElement('script');
	                e.type = 'text/javascript';
	                e.src = document.location.protocol +
	                    '//connect.facebook.net/en_US/all.js';
	                e.async = true;
					var el2 = document.getElementById('fb-root');
					if (el2) {
						el2.appendChild(e);
					}
	            }());
	 			/* 
					This function is fired after the user has logged in to facebook
					The facebook api can invoke a fql query and obtain fields that 
					are available and not restricted by the user via their profile
					
					tip: Use the FB.getSession().uid as the primary field to identify
						 the users logging in from Facebook if they are going to also
						 be registered users. If the uid doesn't exist, then register 
						 the user, otherwise, validate the user, store the available a
						 information and proceed as a validated registered user.
				*/
	            function login(){
	                /*FB.api('/me', function(response) { */
					var el = document.getElementById('fb-profile-info');
					if (el) {
	                    el.style.display = "block";
					}
					el = document.getElementById('fb-login-button');
					if (el) {
						el.style.display = "none";
					}
	               /* });*/
				   
					queryFBDataByUID(FB.getSession().uid);
					
				 	setTimeout('CheckForAccount(' + FB.getSession().uid + ')', 300);
	            }
				
	            function logout(){
					var docel = document.getElementById('fb-profile-info');
					if (docel) {
	                	docel.style.display = "none";
					}
					
					var el = document.getElementById('fb-login-button');
					if (el)
						el.style.display = "block";
					
					//remove the values in the divs for the profile
					el = document.getElementById('fb-profile-picture');
					if (el)
						el.innerHTML="";
						
					el = document.getElementById('fb-fullname');
					if (el)
						el.innerHTML = "";
					
	            }
				
				
				function CheckForAccount(userID) {
					options = {
					
						onComplete: function(val) {
							EvaluateCheckResults(val.responseText);
						},
						onFailure: function() {
							alert("request to Zeekler server for login failed");
						},
						method: 'get'
					};
					new Ajax.Request('/login_fb.asp?ProvidedID=' + userID + '&jstimerval=' + (new Date()).getTime(),
					options);
				}
				
				function EvaluateCheckResults(response) {
				
					var resp = eval('(' + response + ')');
					if (resp) {
						if (resp.result) {
							if (resp.result == 1) {
								//alert("success response");
								if (resp.exists == 1) {
									
									document.cookie = "sessionid=" + resp.sessionid + "; expires=" + (new Date(2020,12,31)).toGMTString() + "; path=/; domain=zeekler.com;";
									window.top.location = 'https://www.zeekler.com/login.asp';
								} else {
									window.top.location = 'https://www.zeekler.com/connect_fb.asp';
								}
								
								
							} else {
								alert("The Facebook data failed validation, please re-login with facebook.");
							}
						}
					}
				
				}
				
				function checkFBLoginDataCookie()
				{
					var fbRespCookieVal = get_cookieg("fb_response");
					if(fbRespCookieVal!= null)
					{
						//parse through the fb_response and get the information for the profile info
						//var arrFBResp = fbRespCookieVal.split("|");
						//document.getElementById('fb-profile-picture').innerHTML = '<img src="' + arrFBResp[5] + "' alt='" + arrFBResp[4] + "'>";
						//document.getElementById('fb-fullname').innerHTML = 
						//"Welcome " + arrFBResp[1] + '<br/> <img onclick="FB.logout()" style="cursor: pointer;"' +	'src="https://s-static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif"><br/>';
						//document.getElementById("fb-profile-info").style.display="block";
					}
					else
					{
						queryFBDataByUID(FB.getSession().uid);
					//alert("missing custom facebook cookie");
					}
				
				}
				
				function checkZeeklerSession()
				{
					var zeeklersession = get_cookieg("sessionid");
					if (zeeklersession)
					{
						if (zeeklersession.length == 0) 
						{
							login();
						}
						// Else codepath ->  Continue, no need to re-log-in.
					}
					else
					{
						login();
					}
				}
				
				function get_cookieg ( cookie_name )
				{
					 var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
					 if ( results )
						return ( unescape ( results[2] ) );
					  else
						return null;
				}
				
				function queryFBDataByUID(UID) 
				{
				
				 try {
					FB.api(
							{
							  method: 'fql.query',
							  query: 'SELECT name,first_name,middle_name,last_name,pic_square,email,birthday,current_location,username FROM user WHERE uid='+ UID
							},
							function(response) {
								if(response!=null)
								{
									var fb_response = "";
									var delimiter ="|";
									var currentLocResp="";
									var firstname = response[0].first_name != "" ? response[0].first_name : " ";
									var middlename = response[0].middle_name != "" ? response[0].middle_name : " ";
									var lastname = response[0].last_name != "" ? response[0].last_name : " ";
									var name = response[0].name != "" ? response[0].name : " ";
									var pic_square = response[0].pic_square != "" ? response[0].pic_square : " ";
									var email = response[0].email != "" ? response[0].email : " ";	
									var birthday = response[0].birthday != "" ? response[0].birthday : " ";
									
									var lcity;
									var lstate;
									var lzip;
									var lcountry;
									var username;
									
									if(response[0].current_location)
									{
										lcity = response[0].current_location.city != "" ? response[0].current_location.city : " ";
										lstate = response[0].current_location.state != "" ? response[0].current_location.state : " ";
										lzip = response[0].current_location.zip != "" ? response[0].current_location.zip : " ";
										lcountry = response[0].current_location.country != "" ? response[0].current_location.country :" ";
									}
									else
									{
										lcity = " ";
										lstate = " ";
										lzip = " ";
										lcountry = " ";
									}
									
									if (response[0].username)
										username=response[0].username != "" ? response[0].username : " ";
									else
										username=" ";
									
									fb_response+=FB.getSession().uid;
										fb_response+=delimiter;
									fb_response+=firstname.replace("|","");
										fb_response+=delimiter;
									fb_response+=middlename.replace("|","");
										fb_response+=delimiter;
									fb_response+=lastname.replace("|","");
										fb_response+=delimiter;
									fb_response+=name.replace("|","");
										fb_response+=delimiter;
									fb_response+=pic_square.replace("|","");
										fb_response+=delimiter;
									fb_response+=email.replace("|","");	
										fb_response+=delimiter;
									fb_response+=birthday.replace("|","");
										fb_response+=delimiter;
									fb_response+=lcity.replace("|","");
										fb_response+=delimiter;
									fb_response+=lstate.replace("|","");
										fb_response+=delimiter;
									fb_response+=lzip.replace("|","");
										fb_response+=delimiter;
									fb_response+=lcountry.replace("|","");
//									alert("Location?" + response[0].current_location);									
								   
									
										fb_response+=delimiter;
									fb_response+=username.replace("|","");
									
									//alert(fb_response);
									//set cookie with the values from the response
									var expiredate = new Date();
									var expiredays = 1;
									expiredate.setTime((expiredate.getTime()+(expiredays*24*60*60*1000)));
									document.cookie="fb_response="+ fb_response +";expires=" + expiredate.toGMTString() + "; path=/; domain=zeekler.com;";
									
								}
								else
								{
									document.getElementById('fb-profile-info').style.display="none";
									alert("There was an error completing your log into Facebook, please try again later");
								}
							
							});
					} catch(e) { alert("facebook data query failed");}
				}
				
				function checkFBLogin()
				 {
					 var fbRespCookieVal = get_cookie("fb_response");
				 	if(fbRespCookieVal!= null)
					{
						
						//parse through the fb_response and get the information for the profile info
						fbRespCookieVal = fbRespCookieVal.replace("([\"<>;])","");
						//Remove potential for cookie poisoning.
						
						var arrFBResp = fbRespCookieVal.split("|");
						
						var el = document.getElementById('fb-profile-picture');
						if (el) 
							el.innerHTML = '<img src="' + arrFBResp[5] + '" alt="' + arrFBResp[4] + '">';
						el = document.getElementById('fb-fullname');
						if (el)
							el.innerHTML = 	'Welcome ' + arrFBResp[1] + '<br/> <img onclick="FB.logout()" style="cursor: pointer;"' +	'src="https://s-static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif"><br/>';
						
						el = document.getElementById("fb-profile-info");
						if (el)
							el.style.display="block";
					}
					else
					{
						//alert("missing custom facebook cookie");
					}
					
				 }
				 function get_cookie ( cookie_name )
				 {
					 var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
					 if ( results )
						return ( unescape ( results[2] ) );
					  else
						return null;
				}