/*========================================================================================
  
   Allinit
  
 ========================================================================================*/
/*========================================================================================
  
   Init friendconnect
   
 ========================================================================================*/
// Set location of rpc_relay.html and canvas.html 
try {
google.friendconnect.container.setParentUrl("/");
google.friendconnect.container.initOpenSocialApi({
	site: gfc_site,
	onload: function(securityToken) { initAllData(); }
});
} catch(err) {logit("Error with FriendConnect")};
login_page = 'index.php';
map_page   = 'indexTrips.php';
/*========================================================================================
  
   initAllData - triggered on friendconnect loaded
   
 ========================================================================================*/
function initAllData() {
	logit("initAllData:"+window.timesloaded);
	/*========================================================================================
	
	 Init friendconnect
	 
	========================================================================================*/

	if (!window.timesloaded) {
		window.timesloaded = 1;
	} else {
		window.timesloaded++;
	}
	if (window.timesloaded > 1) {
		logit("Second Load");
		/*========================================================================================
		
		 on the second reload redirect to profile page
		 
		========================================================================================*/
		document.location=login_page;
		//window.top.location.href = '/profile';	
	} else {
		logit("First Load");
		/*========================================================================================
		
		 first reload : init gadgets & signinbutton
		 
		========================================================================================*/
		//
		// create signin button
		//
		var gfc_login = $("#gfc_login").length;
		if (gfc_login > 0) {
			google.friendconnect.renderSignInButton({ 'id': 'gfc_login', 'text' : 'Join Site', 'style': 'long'});
		}
		//
		// init friendconnect gadgets
		//
		/*========================================================================================
		
		 Member Gadget
		 
		========================================================================================*/
		var skin_members = {};
		skin_members['BORDER_COLOR'] = '#cccccc';
		skin_members['ENDCAP_BG_COLOR'] = '#e0ecff';
		skin_members['ENDCAP_TEXT_COLOR'] = '#333333';
		skin_members['ENDCAP_LINK_COLOR'] = '#0000cc';
		skin_members['ALTERNATE_BG_COLOR'] = '#ffffff';
		skin_members['CONTENT_BG_COLOR'] = '#ffffff';
		skin_members['CONTENT_LINK_COLOR'] = '#0000cc';
		skin_members['CONTENT_TEXT_COLOR'] = '#333333';
		skin_members['CONTENT_SECONDARY_LINK_COLOR'] = '#7777cc';
		skin_members['CONTENT_SECONDARY_TEXT_COLOR'] = '#666666';
		skin_members['CONTENT_HEADLINE_COLOR'] = '#333333';
		skin_members['NUMBER_ROWS'] = '4';
		//google.friendconnect.container.setParentUrl('/' /* location of rpc_relay.html and canvas.html */);
		try {
		google.friendconnect.container.renderMembersGadget(
		 { id: 'div-memberGadget',
		   site: gfc_site },
		  skin_members);
		} catch(err) {logit("Error with renderMembersGadget")};
		/*========================================================================================
		
		 Wall Gadget
		 
		========================================================================================*/
		skin_wall = {};
		skin_wall['BORDER_COLOR'] = '#cccccc';
		skin_wall['ENDCAP_BG_COLOR'] = '#e0ecff';
		skin_wall['ENDCAP_TEXT_COLOR'] = '#333333';
		skin_wall['ENDCAP_LINK_COLOR'] = '#0000cc';
		skin_wall['ALTERNATE_BG_COLOR'] = '#ffffff';
		skin_wall['CONTENT_BG_COLOR'] = '#ffffff';
		skin_wall['CONTENT_LINK_COLOR'] = '#0000cc';
		skin_wall['CONTENT_TEXT_COLOR'] = '#333333';
		skin_wall['CONTENT_SECONDARY_LINK_COLOR'] = '#7777cc';
		skin_wall['CONTENT_SECONDARY_TEXT_COLOR'] = '#666666';
		skin_wall['CONTENT_HEADLINE_COLOR'] = '#333333';
		skin_wall['DEFAULT_COMMENT_TEXT'] = 'Please Leave a Comment';
		skin_wall['HEADER_TEXT'] = 'Comments';
		skin_wall['POSTS_PER_PAGE'] = '5';
		//google.friendconnect.container.setParentUrl('/');
		//alert("wall gadget");
		options = { id: 'div-wallGadget',
		   site: gfc_site,
		   'view-params':{"disableMinMax":"true","scope":"SITE","features":"video,comment","startMaximized":"true"}
		 };
		try {
			google.friendconnect.container.renderWallGadget(options,skin_wall);
		} catch(err) {logit("Error with renderMembersGadget")};
		/*========================================================================================
		
		 Polls
		 
		========================================================================================*/
		/*
		google.friendconnect.container.renderOpenSocialGadget(
		 { id: 'div-polls',
		   url:'http://pollsgadget.appspot.com/polls/gadget.xml',
		   site:gfc_site});
		*/
		/*========================================================================================
		
		 Example get data
		 
		========================================================================================*/
		/*
		var req = opensocial.newDataRequest();
		req.add(req.newFetchPersonRequest("OWNER"), "owner_data");
		req.add(req.newFetchPersonRequest("VIEWER"), "viewer_data");
  	var idspec = new opensocial.IdSpec({
      'userId' : 'OWNER',
      'groupId' : 'FRIENDS'
  	});
  	req.add(req.newFetchPeopleRequest(idspec), 'site_friends');
  	req.send(onData);
  	*/
	}
}   
function onData(data) {
  if (!data.get("owner_data").hadError()) {
    var owner_data = data.get("owner_data").getData();
    logit("SITE owner:"+owner_data.getDisplayName()+'/'+owner_data.getId());
  }

  if (!data.get("site_friends").hadError()) {
    var site_friends = data.get("site_friends").getData();
    site_friends.each(function(friend) {
      logit("SITE friends:"+friend.getDisplayName());
    });
  }
  if (data.get("viewer_data").hadError()) {
  	logit("SITE viewer not logged in");
  } else {
    var viewer = data.get("viewer_data").getData();
  	logit("SITE viewer:"+viewer.getDisplayName()+'/'+viewer.getId()+'/'+viewer.getField(opensocial.Person.Field.THUMBNAIL_URL));
    //postActivity("Logged into Henks Site on:" + new Date().toString());
  }
};   	
/*========================================================================================

 Example post activity
 
========================================================================================*/
/**
 * Create the new activity and send it to the server.
 */
function postActivity(text) {  
  var params = {};  
  params[opensocial.Activity.Field.TITLE] = text;
  var activity = opensocial.newActivity(params); 
  opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, callback);
  logit("Activity title is: " + activity.getField(opensocial.Activity.Field.TITLE));
};        

/**
* Server calls this function to indicate whether the activity post succeeded or failed.
*/
function callback(status) {
  if (status.hadError())
  {
    logit("Error creating activity.");
  }
  else 
  {
    logit("Activity successfully created.");
  }
};
/*========================================================================================
  
   allInit - triggered on DOM ready
   
 ========================================================================================*/
function allInit() {
	logit("allInit");
	$(".vAlign").vAlign();  // vertical align login window
	DD_roundies.addRule('.round20','20px',true);
	
	$("#startmap").click(function() {
		document.location=map_page;
	})
	
	$("#login_form").submit(function() { 
		/*========================================================================================
		  
		   Validate Login-Form
		   
		 ========================================================================================*/
		logit("username:"+$('#username').val());
		if ($('#username').val() == '') {
			$('#username').focus();
	  	$("#msgbox").removeClass().addClass('messageboxerror').text('User Name empty...').fadeIn(1000);
			return false;
		}
		/*========================================================================================
		  
		   Ajax Check User & Password
		   
		 ========================================================================================*/
		//remove all the class add the messagebox classes and start fading
		$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
		//check the username exists or not from ajax
		var rem_;
		if ($('input[name="remember"]').attr("checked")) {
			rem_ = 'yes';
		} else {
			rem_ = 'no';
		}
		//alert("remember="+$('input[name="remember"]').attr("checked"));
		$.post("ajaxLogin.php",{ user_name:$('#username').val(),password:$('#password').val(),remember:rem_,rand:Math.random() },
			function(data) {
		  if(data=='yes') { //if correct login detail
		  	logit("login succesful");
		  	$("#msgbox").fadeTo(200,0.1,function() { //start fading the messagebox
					//add message and change the class of the box and start fading
					$(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1,
            function()  { 
					  //redirect to secure page
				    document.location=login_page;
			  	});
				});
		  }
		  else {
		  	logit("login NOT succesful");
		  	$("#msgbox").fadeTo(200,0.1,function() { //start fading the messagebox
				  //add message and change the class of the box and start fading
				  $(this).html('Login not Succesfull...').addClass('messageboxerror').fadeTo(900,1);
				});		
       }
    });
 		return false; //not to post the  form physically
	});
	/*
	//now call the ajax also focus move from 
	$("#password").blur(function()
	{
		$("#login_form").trigger('submit');
	});
	*/
	$("#register_form").submit(function() { 
		/*========================================================================================
		  
		   Validate Register-Form
		   
		 ========================================================================================*/
		if ($('#username').val() == '') {
			$('#username').focus();
	  	$("#msgbox").removeClass().addClass('messageboxerror').text('User Name empty...').fadeIn(1000);
			return false;
		}
		if ($('#email').val() == '') {
			$('#email').focus();
	  	$("#msgbox").removeClass().addClass('messageboxerror').text('Please enter E-mail...').fadeIn(1000);
			return false;
		}
		if ($('#password').val().length < 6) {
			$('#password').focus();
	  	$("#msgbox").removeClass().addClass('messageboxerror').text('Password minimal 6 long...').fadeIn(1000);
			return false;
		}
		if ($('#password').val() != $('#password2').val()) {
			$('#password').focus();
	  	$("#msgbox").removeClass().addClass('messageboxerror').text('Passwords not same...').fadeIn(1000);
			return false;
		}
		/*========================================================================================
		  
		   Ajax check Register-Details
		   
		 ========================================================================================*/
		//remove all the class add the messagebox classes and start fading
		$("#msgbox").removeClass().addClass('messagebox').text('Registering....').fadeIn(1000);
		//check the username exists or not from ajax

		var rem_;
		if ($('input[name="remember"]').attr("checked")) {
			rem_ = 'yes';
		} else {
			rem_ = 'no';
		}

		$.post("ajaxRegister.php",{ user_name:$('#username').val(),email:$('#email').val(),password:$('#password').val(),remember:rem_,rand:Math.random() } ,
			function(data) {
			  if(data=='yes') { //if correct login detail
			  	$("#msgbox").fadeTo(200,0.1,function() { //start fading the messagebox
						//add message and change the class of the box and start fading
						$(this).html('Registered.....').addClass('messageboxok').fadeTo(900,1,
	            function()  { 
						  //redirect to secure page
					    document.location=login_page;
				  	});
					});
			  }
			  else {
			  	if (data=='double') {
			  		$('#username').focus();
			  		msg = 'User already exists...';
			  	}
			  	else { 
			  		msg = 'Register failed...';
			  	}
			  	$("#msgbox").fadeTo(200,0.1,function() { //start fading the messagebox
					  //add message and change the class of the box and start fading
					  $(this).html(msg).addClass('messageboxerror').fadeTo(900,1);
					});		
	      }
    });
 		return false; //not to post the  form physically
	});
	$("#prlogout").click(function() {
		//var logged_in = readCookie('logged_in');
		//alert("logout:"+logged_in);
		if (logged_in == 2) {
			setCookie("hg_user_c",0);
			setCookie("logged_in",0);
			logit("signout GFC");
			// google friends connected -> check if sessions are deleted
			google.friendconnect.requestSignOut();
			document.location=login_page+'?logout';
		} else {
			setCookie("hg_user_c",0);
			setCookie("logged_in",0);
			logit("logout HG:"+login_page);
			//window.top.location.href = '/testGFC.php';
			document.location=login_page+'?logout';
		}
	});

}
