window.fbAsyncInit = function() {
  FB.init({
    appId  : '27f3bf7bb8aeeacd335399ee10face69',
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml  : true  // parse XFBML
  });
};

(function() {
  var e = document.createElement('script');
  e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
  e.async = true;
  document.getElementById('fb-root').appendChild(e);
}());

if($("#radioSet1, #radioSet2, #radioSet3, #radioSet4").length)
{
	$("#radioSet1, #radioSet2, #radioSet3, #radioSet4").buttonset();
}

$("#evaluateProfessor").click(function(e){
	
	e.preventDefault();
	
	if(! $(this).hasClass('active') )
	{
		openRate();
	}
	else
	{
		closeRate();
	}
});

$("#evaluate input[name='johnDoe']").change(function() {
	$("fieldset.johnDoeTerms").fadeIn("fast",function(){});
});

$("#evaluateAjax input[name='johnDoe']").change(function() {
	$("fieldset.johnDoeTerms").fadeIn("fast",function(){});
});

$(".commentBox input[name='johnDoe']").change(function() {
	$("div.johnDoeTerms").fadeIn("fast",function(){});
});

$(".searchBox").keypress(function(e){
	if(e.keyCode == 13){
		e.preventDefault();
		window.location = "http://www.notaso.com/search/" + $("#tags").val();
	}
});
$("#searchsubmit").click(function(e){

	e.preventDefault();
	
	window.location = "http://www.notaso.com/search/" + $("#tags").val();
})

if(window.location.hash == '#rate'){openRate();}

function openRate()
{
	$("#evaluateProfessor").addClass("active");
	$("#intro").children("div").css("height", "300px");
	$('#create').show();
}

function closeRate()
{
	$("#evaluateProfessor").removeClass("active");
	$("#intro").children("div").css("height", "40px");
	$('#create').hide();
}

// $("#facebook_signin").click(function(e) {
// 	e.preventDefault();
// 	FB.getLoginStatus(function(response) {
// 		if (response.status === 'connected') {
// 		// the user is logged in and connected to your
// 		// app, and response.authResponse supplies
// 		// the user's ID, a valid access token, a signed
// 		// request, and the time the access token
// 		// and signed request each expire
// 		var uid = response.authResponse.userID;
// 		var accessToken = response.authResponse.accessToken;
// 		createUpdateUser();
// 		} else if (response.status === 'not_authorized') {
// 			//the user is logged in to Facebook,
// 			//but not connected to the app
// 			FB.login(function(response) {
// 				if (response.authResponse) {
// 					createUpdateUser();
// 				} else {
// 					alert('Debes hacer click en “Allow” para poder usar el sistema. Trata de nuevo.');
// 				}
// 			}, {scope: 'email,publish_stream,user_birthday,user_location,sms,offline_access'});
// 		} else {
// 		// the user isn't even logged in to Facebook.
// 			alert('Not logged in');
// 		}
// 	});
// });

$("#facebook_invite").click(function(e){
    e.preventDefault();
    
    var share = {
      method: 'stream.share',
      u: 'http://www.notaso.com/'
    };

    FB.ui(share, function(response) { console.log(response); });
    
});
function createUpdateUser() {
    FB.api({
			method: 'fql.query',
			query: "SELECT uid, first_name, middle_name, last_name, birthday_date, pic_square, sex, email FROM user WHERE uid='"+FB.getSession().uid+"'"
		},
		function(d) {
            $.ajax({
                type: 'post',
                url:'http://www.notaso.com/auth/createUpdateUser',
                data: {'uid':d[0]['uid'], 'first_name':d[0]['first_name'], 'middle_name':d[0]['middle_name'], 'last_name':d[0]['last_name'], 'birthday_date':d[0]['birthday_date'], 'pic_square':d[0]['pic_square'], 'sex':d[0]['sex'], 'email':d[0]['email']},
                success: function(msg) {
                    // console.log(d);
                    location.reload(true);
                },
                error: function(msg) {
                    // console.log(msg);
                    alert('Error. Please try again.');
                }
            });  
		});
}

$("#facebook_logout").click(function(e) {
	e.preventDefault();
	FB.getLoginStatus(function(response) {
	if (response.status === 'connected') {
	// the user is logged in and connected to your
	// app, and response.authResponse supplies
	// the user's ID, a valid access token, a signed
	// request, and the time the access token 
	// and signed request each expire
	var uid = response.authResponse.userID;
	var accessToken = response.authResponse.accessToken;
		FB.logout(function(response) {
        // alert('Logging you out...');
		location.reload(true);
	});
	} else if (response.status === 'not_authorized') {
	// the user is logged in to Facebook, 
	//but not connected to the app
	} else {
	// the user isn't even logged in to Facebook.
	}
	});
});

$(".btnSend").click(function(e){
	
	 e.preventDefault();
	 console.log('debug message');
	 $('form').submit();
	 // $.ajax({
	 //    type: 'post',
	 //    url:'http://www.notaso.com/professor/rate/'+$("#professor_id").val(),
		// dataType: "json",
	 //    data: {
		// 	'rating_1': $("input[name='rating_1']:checked").val(),
		// 	'rating_2': $("input[name='rating_2']:checked").val(),
		// 	'rating_3': $("input[name='rating_3']:checked").val(),
		// 	'rating_4': $("input[name='rating_4']:checked").val(),
		// 	'content': $("#commentRate").val(),
		// 	'johnDoe': $("input[name='johnDoe']").is(':checked') ? "1" : "2"
			
		// },
	 //    success: function(m){
	 //        console.log(m);
		// 	if(m.response == 'success')
		// 	{
		// 		window.location = 'http://www.notaso.com/professor/'+$("#professor_id").val();
		// 	}
		// 	else
		// 	{
		// 		alert(m.response);
		// 		$(".ajax-loader").remove();
		// 		$(".ajax.btnSend").show();
		// 		$("#johnDoeAJAX").show();
		// 	}
	 //    },
		// error: function(error){
		// 	alert(error);
		// }
	 //  });
	
	// // alert('Button Pressed');
	// if($(this).hasClass('ajax'))
	// {
	// 	$("#johnDoeAJAX").hide();
	// 	$(this).hide();
	// 	$('<img class="ajax-loader" src="http://notaso.com/assets/img/ajax-loader.gif" />').insertBefore(this);
	// 	FB.getLoginStatus(function(response){

	// 		if(!response.session)
	// 		{
	// 			//alert('No session, loggin in....');
	// 			FB.login(function(response2){
	// 				if(response2.session)
	// 				{
	// 					//alert('User logged in');
	// 					FB.api(
	// 						{
	// 							method: 'fql.query',
	// 							query: "SELECT uid, first_name, middle_name, last_name, birthday_date, pic_square, sex, email FROM user WHERE uid='"+FB.getSession().uid+"'"
	// 						},
	// 						function(d) {
	// 							// alert(d);
	// 							  $.ajax({
	// 							    type: 'post',
	// 							    url:'http://www.notaso.com/auth/createUpdateUser',
	// 							    data: {'uid':d[0]['uid'], 'first_name':d[0]['first_name'], 'middle_name':d[0]['middle_name'], 'last_name':d[0]['last_name'], 'birthday_date':d[0]['birthday_date'], 'pic_square':d[0]['pic_square'], 'sex':d[0]['sex'], 'email':d[0]['email']},
	// 							    success: function(msg){
	// 							        // console.log(d);
	// 									// alert('with ajax');
	// 									  $.ajax({
	// 									    type: 'post',
	// 									    url:'http://www.notaso.com/professor/rate/'+$("#professor_id").val(),
	// 										dataType: "json",
	// 									    data: {
	// 											'rating_1': $("input[name='rating_1']:checked").val(),
	// 											'rating_2': $("input[name='rating_2']:checked").val(),
	// 											'rating_3': $("input[name='rating_3']:checked").val(),
	// 											'rating_4': $("input[name='rating_4']:checked").val(),
	// 											'content': $("#commentRate").val(),
	// 											'johnDoe': $("input[name='johnDoe']").is(':checked') ? "1" : "2"
												
	// 										},
	// 									    success: function(m){
 //                                                // console.log(m);
	// 											if(m.response == 'success')
	// 											{
	// 												window.location = 'http://www.notaso.com/professor/'+$("#professor_id").val();
	// 											}
	// 											else
	// 											{
	// 												alert(m.response);
	// 												$(".ajax-loader").remove();
	// 												$(".ajax.btnSend").show();
	// 												$("#johnDoeAJAX").show();
	// 											}
	// 									    },
	// 										error: function(error){
	// 											alert(error);
	// 										}
	// 									  });
	// 							      }
	// 							  });	
	// 						}
	// 					);
	// 				}
	// 				else
	// 				{
	// 					// alert(response);
	// 				}

	// 			}, {perms:'email,publish_stream,user_birthday,user_location,sms,offline_access'});
	// 		}
	// 		else
	// 		{
	// 			// alert('with ajax and session');
	// 			  $.ajax({
	// 			    type: 'post',
	// 			    url:'http://www.notaso.com/professor/rate/'+$("#professor_id").val(),
	// 				dataType: "json",
	// 			    data: {
	// 					'rating_1': $("input[name='rating_1']:checked").val(),
	// 					'rating_2': $("input[name='rating_2']:checked").val(),
	// 					'rating_3': $("input[name='rating_3']:checked").val(),
	// 					'rating_4': $("input[name='rating_4']:checked").val(),
	// 					'content': $("#commentRate").val(),
	// 					'johnDoe': $("input[name='johnDoe']").is(':checked') ? "1" : "2"
	// 				},
	// 			    success: function(m){
 //                        // console.log(m);
	// 					if(m.response == 'success')
	// 					{
	// 						window.location = 'http://www.notaso.com/professor/'+$("#professor_id").val();
	// 					}
	// 					else
	// 					{
	// 						alert(m.response);
	// 						$(".ajax-loader").remove();
	// 						$(".ajax.btnSend").show();
	// 						$("#johnDoeAJAX").show();
	// 					}
	// 			    },
	// 				error: function(error){
	// 					alert(error);
	// 				}
	// 			  });
	// 		}
	// 	});
	// }
	// //Normal not ajaxy form
	// else
	// {
	// 	$(".johnDoe").hide();
	// 	$(this).hide();
	// 	$('.ajax-loader').show();
	// 	FB.getLoginStatus(function(response){

	// 		if(!response.session)
	// 		{
	// 			//alert('No session, loggin in....');
	// 			FB.login(function(response2){
	// 				if(response2.session)
	// 				{
	// 					//alert('User logged in');
	// 					FB.api(
	// 						{
	// 							method: 'fql.query',
	// 							query: "SELECT uid, first_name, middle_name, last_name, birthday_date, pic_square, sex, email FROM user WHERE uid='"+FB.getSession().uid+"'"
	// 						},
	// 						function(d) {
	// 							// console.log(d);
	// 							  $.ajax({
	// 							    type: 'post',
	// 							    url:'http://www.notaso.com/auth/createUpdateUser',
	// 							    data: {'uid':d[0]['uid'], 'first_name':d[0]['first_name'], 'middle_name':d[0]['middle_name'], 'last_name':d[0]['last_name'], 'birthday_date':d[0]['birthday_date'], 'pic_square':d[0]['pic_square'], 'sex':d[0]['sex'], 'email':d[0]['email']},
	// 							    success: function(msg){
	// 							        // alert(msg);
	// 									// console.log(d);
	// 									pageTracker._trackPageview("/virtual/professorCreated");
	// 									$("#evaluate").submit();
	// 							      }
	// 							  });	
	// 						}
	// 					);
	// 				}
	// 				else
	// 				{
	// 					alert('Debes hacer click en “Allow” para poder usar el sistema. Trata de nuevo.');
	// 				}

	// 			}, {perms:'email,publish_stream,user_birthday,user_location,sms,offline_access'});
	// 		}
	// 		else
	// 		{
	// 			//alert('There is a session...');
	// 			FB.api(
	// 				{
	// 					method: 'fql.query',
	// 					query: "SELECT uid, first_name, middle_name, last_name, birthday_date, pic_square, sex, email FROM user WHERE uid='"+FB.getSession().uid+"'"
	// 				},
	// 				function(d) {
	// 					  $.ajax({
	// 					    type: 'post',
	// 					    url:'http://www.notaso.com/auth/createUpdateUser',
	// 					    data: {'uid':d[0]['uid'], 'first_name':d[0]['first_name'], 'middle_name':d[0]['middle_name'], 'last_name':d[0]['last_name'], 'birthday_date':d[0]['birthday_date'], 'pic_square':d[0]['pic_square'], 'sex':d[0]['sex'], 'email':d[0]['email']},
	// 					    success: function(res){
	// 							// console.log(d);
	// 							pageTracker._trackPageview("/virtual/professorCreated");
	// 							$("#evaluate").submit();
	// 					      }
	// 					  });	
	// 				}
	// 			);	
	// 		}
	// 	});
	// }
  
});
$(".diggDown").click(function(e){
	e.preventDefault();
	comment_id = $(this).parents().parents().attr("id").split("-");
	
	FB.getLoginStatus(function(response){

		if(!response.session)
		{
			// alert('No session, loggin in....');
			FB.login(function(response2){
				if(response2.session)
				{
					// alert('User logged in');
					FB.api(
						{
							method: 'fql.query',
							query: "SELECT uid, first_name, middle_name, last_name, birthday_date, pic_square, sex, email FROM user WHERE uid='"+FB.getSession().uid+"'"
						},
						function(d) {
							// alert(d);
							$.ajax({
								type: 'post',
								url: 'http://www.notaso.com/comment/dig/'+comment_id[1],
								data: {
									'type': 'down'
								},
								dataType: "json",
								success: function(resp){
									if(resp.response == 'success')
									{
										location.reload();
									}
									else
									{
										alert(resp.response);
									}
								},
								error: function(error){
									alert(error);
								}
							});	
						}
					);
				}
				else
				{
					// alert('Not logged in');
				}

			}, {perms:'email,publish_stream,user_birthday,user_location,sms,offline_access'});
		}
		else
		{
			// alert('There is a session...digg!');
			$.ajax({
				type: 'post',
				url: 'http://www.notaso.com/comment/dig/'+comment_id[1],
				data: {
					'type': 'down'
				},
				dataType: "json",
				success: function(resp){
					if(resp.response == 'success')
					{
						location.reload();
					}
					else
					{
						alert(resp.response);
					}
				},
				error: function(error){
					alert(error);
				}
			});
		}
	});
	
});
$(".diggUp").click(function(e){
	e.preventDefault();
	comment_id = $(this).parents().parents().attr("id").split("-");
	
	FB.getLoginStatus(function(response){

		if(!response.session)
		{
			// alert('No session, loggin in....');
			FB.login(function(response2){
				if(response2.session)
				{
					// alert('User logged in');
					FB.api(
						{
							method: 'fql.query',
							query: "SELECT uid, first_name, middle_name, last_name, birthday_date, pic_square, sex, email FROM user WHERE uid='"+FB.getSession().uid+"'"
						},
						function(d) {
							// alert(d);
							$.ajax({
								type: 'post',
								url: 'http://www.notaso.com/comment/dig/'+comment_id[1],
								data: {
									'type': 'up'
								},
								dataType: "json",
								success: function(resp){
									if(resp.response == 'success')
									{
										location.reload();
									}
									else
									{
										alert(resp.response);
									}
								},
								error: function(error){
									alert(error);
								}
							});	
						}
					);
				}
				else
				{
					// alert('Not logged in');
				}

			}, {perms:'email,publish_stream,user_birthday,user_location,sms,offline_access'});
		}
		else
		{
			// alert('There is a session...digg!');
			$.ajax({
				type: 'post',
				url: 'http://www.notaso.com/comment/dig/'+comment_id[1],
				data: {
					'type': 'up'
				},
				dataType: "json",
				success: function(resp){
					if(resp.response == 'success')
					{
						location.reload();
					}
					else
					{
						alert(resp.response);
					}
				},
				error: function(error){
					alert(error);
				}
			});
		}
	});
	
});
//Custom Autocomplete used everywhere else
$.fn.myAutocomplete = function(opt) {
	
    var cache = {};

    this.autocomplete({
        source: function(request, response) {
            if (cache.term == request.term && cache.content) {
                response(cache.content);
            }
            if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
                var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                response($.grep(cache.content, function(value) {
                    return matcher.test(value.value)
                }));
            }
            opt.term = request.term;
			$("#tags").addClass("loader");
            $.ajax({
                url: opt.dataUrl,
                dataType: "json",
                type: "POST",
                data: opt,
                success: function(data) {
                    cache.term = request.term;
                    cache.content = data;
                    response(data);
					$("#tags").removeClass("loader");
                }
            });
        },
        minLength: 2,
		select: function(event, ui){
			if(opt.which == "home")
			{
				if(ui.item.name != 0)
				{
					$("#tags").val(ui.item.name);
					window.location = "http://www.notaso.com/professor/" + ui.item.value;
				}
				else
				window.location = ui.item.value;
				return false;
			}
			else if(opt.which == "create")
			{
				if(ui.item.value != 0)
				{
					window.location = "http://www.notaso.com/professor/" + ui.item.value + "#rate";
				}
				
				return false;
			}
		},
		focus: function(event, ui){

			if(opt.which == "home")
			{
				if(ui.item.name != 0)
				{
					$("#tags").val(ui.item.name);
				}
				
				return false;
			}
			else if(opt.which == "create")
			{					
				if(ui.item.name != 0)
				{
					// $("#tags2").val(ui.item.name);
				}
				
				return false;
			}
		}
    })
	.data("autocomplete")._renderItem = function(ul, item) {
		return $( "<li></li>" )
			.data( "item.autocomplete", item )
			.append( $( "<a></a>" ).html( item.label ) )
			.appendTo( ul );
	
    };
    return this;
}

$(document).ready(function(){
  $("#tags").focus(function(){
    $(this).css({'color':'#000'});
  });
  
  $("#tags").blur(function(){
    $(this).css({'color':'#CCC'});
  });
  
});

