/* ****************************************** 
 
  TITLE:        NBC_USER_FACEBOOK.JS
  VERSION:      1.53
  LAST UPDATED: 09/16/2009 
  UPDATED BY:  Viktoriya Eremeeva
  CONTENTS:

 @release 2009-09-17 - vicky

******************************************  */

var NBC = (typeof NBC=="object") ? NBC : {};

NBC.FbUser = function() {
  var private = {
    // title: "Report: School Shootings Help Prepare Students For Being Shot In Real World"
  };

  
  var public = {
    getTitle: function() {
      return private.title;
    },

    loggedIn: function(apiKey) {
      //Create an ApiClient object, passing app's api key and
      //a site relative url to xd_receiver.htm
      // getAllCookies
  
      var cookiesArray = new Array(5);
      cookiesArray[apiKey] = readCookie(apiKey);
      var facebkId =  cookiesArray[apiKey];
     // alert(cookiesArray[apiKey]);
      cookiesArray[apiKey+'_expires'] = readCookie(apiKey+'_expires');
      cookiesArray[apiKey+'_session_key'] = readCookie(apiKey+'_session_key');
      cookiesArray[apiKey+'_ss'] = readCookie(apiKey+'_ss');
      cookiesArray[apiKey+'_user'] = readCookie(apiKey+'_user');
      //cookiesArray['base_domain_'+apiKey] = getCookie('base_domain_'+apiKey);
     // cookiesArray['fbsetting_'+apiKey] = getCookie('fbsetting_'+apiKey);

      var channel_path= '/includes/xd_receiver.htm';
      FB_RequireFeatures(["Api"], function(){
          // Create an ApiClient object, passing app's API key and 
          // a site relative URL to xd_receiver.htm 
          FB.Facebook.init(apiKey, channel_path); 
          var api = FB.Facebook.apiClient; 
          var uid = FB.Facebook.apiClient.get_session().uid;
         // alert("uid "+uid);
          api.requireLogin(function(exception){ 
        
              function getInfo(result,exception) {
                 // alert(result);
                 // alert(result.length);
                  if ((result) && (result.length)) {
                   FB.FBDebug.dump(result,'The info');
              
                    // alert("result[0].uid "+result[0].uid);
                
                   // alert(result[0].first_name);
                   user.setValues({facebookId:result[0].uid});
                   //alert(result[0].uid);
                   //user.setValues({picUrl:result[0].pic_small_with_logo});
                   user.setValues({picUrl:""});
                   
                   if (cookiesArray[apiKey]) { 
                      handleResponse(result, cookiesArray);
                   }
                   else {
                       alert("cookies not defined.");
                       statusMsg("Error with Facebook Login. Please refresh the page and try again.", true);
                   }
                  }
                  else {
                   statusMsg("Error with Facebook Login. Please refresh the page and try again.", true);
                  }
                 }
              
              var myinfo='last_name,first_name,sex,birthday,current_location,hometown_location,work_history,pic_small_with_logo,uid';
              

               api.users_getInfo(FB.Facebook.apiClient.get_session().uid, myinfo, getInfo);
              
              }); 
      });     
 
    }  
  }

  return public;
}(); 
  
function handleResponse(result, cookiesArray) {
    clearStatusMsg();
    $("#processing img").show();
    $("#overlay_content").css("opacity", 0.3);
    var listOfCookies=""; 
    var userLogo = result[0].pic_small_with_logo;
    for (key in cookiesArray) {
        listOfCookies += "&"+key+"="+cookiesArray[key];
    }
  
    var dataString = "action=loginFacebookUser&facebookUserId="+user.facebookId + listOfCookies;                         
	urlpost='/i/dispatcher/?h=user';
	var userExist = false; 
	var fbUserName = "";
	$.ajax({
       type: "POST",
       url: urlpost,
       data: dataString,
       dataType: "text",
       success: function(data){
		   var jsonObj1 = eval('('+data+')');
		   if (jsonObj1.ka) {
			   if (jsonObj1.ka.status == -1) {
		        processResponse(jsonObj1, result[0].uid, true, "");
		       } 
		       else {
		           fbUserName = jsonObj1.ka.username;
		            fbUserEmail = jsonObj1.ka.email;
		           // end processing    
		            $("#processing img").hide();
		            $("#overlay_content").css("opacity", 1);
		           if (jsonObj1.newFacebookUser == true) {
		               G.doPixelTracking(82, false, '', nbc.omniture.firedRegistration, 1, '', '');
		               userExist = false;
		               $("input[name='facebookUserName']").val(fbUserName);
		               user.setValues({userId:jsonObj1.ka.userId, email:fbUserEmail, token:jsonObj1.ka.TOKEN, userName: fbUserName });
		               // set omniture tracking for age, gender, postal code
		               // default values
		               showFBRegistration(result);    
		            }
		            else  {
		               var successText1 = "Thanks " + fbUserName+ ", you're now signed in.";  
		               userExist = true;
		               user.setValues({userId:jsonObj1.ka.userId, userName:fbUserName, email:fbUserEmail, token:jsonObj1.ka.TOKEN});
		               user.persist();
		               if (fbUserName.match("fb_")  || fbUserName.match("1000000")){
				         fbUserName = "Facebook User";
				       }
		               processResponse(jsonObj1, fbUserName, false, "Thanks " + fbUserName+ ", you're now signed in.");
		               // get gender, age, postal code from get profile call, store in cookie and in omniture params
		               if (jsonObj1.ka) {     
	                       var dataStr="action=getProfile&uid="+jsonObj1.ka.userId+"&token="+jsonObj1.ka.TOKEN+"&comments=n";
	                       var urlprofile="/i/dispatcher/?h=user";
	                       jQuery.ajax({
	                          type: "GET",
	                          url: urlprofile,
	                          data: dataStr,
	                          success: function(data){
	                     	  var userJsonLoad = eval("("+data+")");
	             	              if (userJsonLoad.profile.status == "-1" || typeof userJsonLoad.profile.UserProfile == "undefined") {
	             	                throw new Error ("User Profile Error: " + userJsonLoad.profile.error);
	             	              }  
	             	              var profile = userJsonLoad.profile.UserProfile;
	             	    
	             	              user.setValues({userGender: profile.gender, userAge: profile.age, zipCode: profile.postalCode}); 
	             	              user.persist();    
	             	              var ageRange = NBC_UserOverlay.convertAgeRange(parseInt(profile.age));
	             	              U.log(ageRange);
	            	              nbc.omniture.ageRange = ageRange;
	            	              nbc.omniture.userGender = NBC_UserOverlay.convertGender(profile.gender);
	            	              nbc.omniture.postalCode = profile.postalCode;
	            	              U.log(nbc.omniture.ageRange+ " "+nbc.omniture.userGender+" "+ nbc.omniture.postalCode);
	                          }
	                       });
	                     }  // get profile if user has been registered already
		            }  // new Facebook User is false - process register - popup the second screen
		       }  // if jsonObj1.ka.status = 1
		   } // if response is valid
		   else {
			   processResponse(jsonObj1, result[0].uid, true, "");
		   } // if kickapps fails
	     }
    });
}

$(document).ready(function() {
    if ($("#overlay_wrapper").hasClass("reg_fb_overlay")) {
        $("#overlay_close > a:first").click(function() {
            setTimeout("NBC_UserOverlay.hide()", 1500); 
        });
     }
});

function showFBRegistration(result) {
	//alert(result[0].first_name);
	var userName = result[0].first_name+""+result[0].last_name;
	$("#FBregDisplayName").val(userName);
	$("#overlay_wrapper").removeAttr("class");
	$("#overlay_wrapper").addClass("reg_fb_overlay");
	$("#overlay_text_header").attr("class","fb_reg_text_header");
	calcHeight("overlay_wrapper"); 
	calcWidth("overlay_wrapper");
	$("#overlay_close").addClass("fb_overlay_close").removeAttr("id");
	$(".fb_overlay_close").click(function() {
	   $("#FB_reg_wrapper").hide();
	   $("#overlay_wrapper").removeClass("reg_fb_overlay");
	   $(this).attr("id", "overlay_close").removeClass("fb_overlay_close");
	});
	// reset the form
	$("#serverMessage").text("").removeClass("invalid").removeClass("valid");  
	$(".formContent > div").removeClass("invalid").removeClass("valid");
	$("#FBregSubmit").attr("disabled", false);
	$(".reg_fb_overlay #regForm").hide();
	$(".reg_fb_overlay #loginForm").hide();
	$("#loginWithFacebook").hide();
	$("#FB_reg_wrapper").css("display","block");
	$("#overlay_wrapper").fadeIn('fast');
	$("div.fbGender").removeClass("valid"); // for IE
	$("#regFBDisplayName").focus();  
}
 
function submitFBRegForm() {
clearStatusMsg();
    //alert("show FB reg");
$("#changedProfile").val("");
$("#FBregSubmit").attr("disabled", true);
// submit the form 
var userName = $('input[name="regFBDisplayName"]').fieldValue()[0];
//var facebookUserId = $('input[name="facebookUserId"]').fieldValue()[0];
var facebookUserId = user.facebookId;
var queryString = $("#regFacBookForm").formSerialize();
var userId = user.userId;
var useEmail = user.email;
var fbBirthday = $("#FBbirthday").val();
U.log("fbBirthday "+fbBirthday);
var arrayBirthday = fbBirthday.split("-");
var birthYearSet = arrayBirthday[0];
U.log("fb year set to "+birthYearSet);
var fbUserName = $("input[name='facebookUserName']").val();
var fbGender = $("#FB_reg_wrapper").find("input[@name='fbGender']:checked").val();
U.log("fbGender "+fbGender);
U.log("check token "+user.token);
var d = new Date();
var currYear = d.getFullYear();
var birthAgeSet = currYear - parseInt(birthYearSet);
var ageRangeSet = NBC_UserOverlay.convertAgeRange(parseInt(birthAgeSet));
 nbc.omniture.ageRange = ageRangeSet;
 nbc.omniture.userGender = NBC_UserOverlay.convertGender(fbGender);
 user.setValues({userAge: birthAgeSet, userGender: fbGender }); 
 user.persist(); 
 U.log(nbc.omniture.ageRange+ " "+nbc.omniture.userGender);
var dataString1 = "action=updateProfile&uid="+userId+"&userName="+ fbUserName+"&email="+useEmail + "&profileBirthday="+fbBirthday+"&token="+user.token+"&gender="+fbGender;
urlpost='/i/dispatcher/?h=user';
//alert(dataString1);
$.ajax({
    type: "POST",
    url: urlpost,
    data: dataString1,
    dataType: "text",
    success: function(data){
    var jsonObj3 = eval('('+data+')');
//alert("update profile "+jsonObj3.ka.status);
    if (jsonObj3.ka) {  
		if (jsonObj3.ka.status == "1") {
		    $("#changedProfile").val(jsonObj3.ka.status);
		    var newUserName = ($("#FBregDisplayName").val());
		    var dataString2 = "action=changeUserName&uid="+userId+"&userName="+ fbUserName+"&newUserName="+newUserName+ "&email="+useEmail+"&token="+user.token;
		    urlpost='/i/dispatcher/?h=user';
		    $.ajax({
		       type: "POST",
		       url: urlpost,
		       data: dataString2,
		       dataType: "text",
		       success: function(data){
			       var jsonObj2 = eval('('+data+')');
			    // alert("change user name "+jsonObj2.ka.status);
				    if ((jsonObj2.ka.status == "1") && (jsonObj3.ka.status == "1")) {
				        G.doPixelTracking(16);
				        user.setValues({userName:newUserName,token: jsonObj2.ka.token});
				        user.persist();
				       processResponse(jsonObj3, newUserName, false, "Thanks "+user.userName+", you're now registered and signed in.");
				       $("#FBregSubmit").attr("disabled", false);
				       
				    
				    }
				    else if ((jsonObj2.ka.status == "-1") && (jsonObj3.ka.status = "1")) {
                       processResponse(jsonObj2, newUserName, true, "Thanks "+user.userName+", you're now registered and signed in.");
				       $("#FBregSubmit").attr("disabled", false);
				    } 
				    else if ((jsonObj2.ka.status == "1") && (jsonObj3.ka.status = "-1")) {
				       processResponse(jsonObj3, user.userName, true, "Thanks "+user.userName+", you're now registered and signed in.");
				       $("#FBregSubmit").attr("disabled", false);
				    } 
				    else {
				       processResponse(jsonObj3, user.userName, true, "Thanks "+user.userName+", you're now registered and signed in.");
				       $("#FBregSubmit").attr("disabled", false);
				    }
		         }
		     });
	 }
	 else {
	     processResponse(jsonObj3, user.userName, true, "Thanks "+user.userName+", you're now registered and signed in.");
	     $("#FBregSubmit").attr("disabled", false);
	    }
     }
     else {
    	 processResponse(jsonObj3, user.userName, true, "Thanks "+user.userName+", you're now registered and signed in.");
	     $("#FBregSubmit").attr("disabled", false);
     }
   }
  });
}

function calcHeight(popupId)  {
    var extraTop = 170 + parseInt($("#logoFrame").height());
    var popupTop = ((screen.height-extraTop) - parseInt(document.getElementById(popupId).offsetHeight))/2;
    document.getElementById(popupId).style.top =popupTop+ "px";
  }

  function calcWidth(popupId)  {
    extraLeft = (screen.width - parseInt($("#siteContainer").width()))/2;
    var popupLeft = (screen.width - parseInt(document.getElementById(popupId).offsetWidth))/2 - extraLeft;
    document.getElementById(popupId).style.left = popupLeft+"px";
  }   
$(document).ready(function() {

  if ($("#regFacBookForm").attr("id")) {
    $("#regFacBookForm").validate({
      submitHandler: function(form) {
          // do other stuff for a valid form
         $("#processing img").show();
         $("#overlay_content").css("opacity", 0.3);
         submitFBRegForm();
      },        
      errorPlacement: function(error, element) {
        element.parent().removeClass('valid').addClass('invalid'); 
        // don't do anything for birthday
        if (element.parent().removeClass('valid').attr('class') == 'invalid') {
            U.log("field set for gender");
            if ($("#fbRegMale").is(":checked") || $("#fbRegFemale").is(":checked")) {
                element.parent().parent().removeClass('invalid').addClass('valid');
            }
            else {
                element.parent().parent().removeClass('valid').addClass('invalid');
            }
         }
        if (element.attr("name") != "fbBirthday") {
          element.parent().find('.errorText').text(error.text());
        }
      },
      success: function(label) {
        $("#" + label[0].htmlFor).parent().removeClass("invalid").addClass("valid");
        if ($("#" + label[0].htmlFor).parent().removeClass("invalid").attr("class") == "valid") {
          $("#" + label[0].htmlFor).parent().removeClass("invalid").addClass("valid");
        }
      },    
      errorClass: "invalid",
      event: "submit",
      rules: {

      userName: {
         required: true,
         nowhitespaceuserpunct: true,
         minlength: 4,
         maxlength: 20
        },
       fbBirthday: {
          required: true
        },
        fbGender: {
            required: true
        }
      },
      messages: {
           userName: {
             required: 'Please enter a username.'
           },
           fbGender: {
            required: 'Please chose a gender.'
           }
      }
    });
  }
  });
 
// custom birthday validation
$(document).ready(function() {
  $("#FBbirthMonth,#FBbirthDay,#FBbirthYear").change(function() {
   validationForBirthday();
  });
});


function validationForBirthday() {
   if (isBirthdayCompleted()) {
      $("div.FBbirthdate").removeClass("invalid").addClass("valid");
      $('input[name="fbBirthday"]').val(getFormattedBirthday());
    }
    // if user deselected a validated birthday field
    else if ($("div.FBbirthdate").hasClass("valid")) {
      // make invalid
      $("div.FBbirthdate").removeClass("valid").addClass("invalid");      
      $('input[name="fbBirthday"]').val(""); // reset
    }
}
function getFormattedBirthday() {
    // merge birth fields into a single field YYYY-MM-DD
    var birthMonth = $('select#FBbirthMonth').val(); 
    var birthDay = $('select#FBbirthDay').val();
    var birthYear = $('select#FBbirthYear').val();
    var birthday = birthYear + "-" + getZeroedValue(birthMonth) + "-" + getZeroedValue(birthDay);
    return birthday;
  }

 function isEmpty(fieldId) {
    return ($("#" + fieldId).val() === "");
  }

function getZeroedValue(number) {
    if(number < 10) {
      return "0" + number;
    }
    return number;
  }

  function isBirthdayCompleted() {
    return !isEmpty("FBbirthMonth") && !isEmpty("FBbirthDay") && !isEmpty("FBbirthYear");
  }    
 
 function isGenderCompleted() {
        return $("#fbRegMale").is(":checked") || $("#fbRegFemale").is(":checked");
      }
  
 // make gender valid on click
 $(document).ready(function() {
   $("#fbRegMale,#fbRegFemale").click(function() {
     $(this).parent().parent().addClass('valid');
   });
 });
 
 function displaySuccess(text) {
        $("#reg_wrapper").hide();
        $("#login_wrapper").hide();
       // alert("in display "+text);
        statusMsg(text);
        setTimeout("NBC_UserOverlay.hide()", 1500); // hide after 1.5 secs
      }

  function processResponse(data, userName, saveInfo, successText) {
        var success = false;
        if(data == undefined) {
          statusMsg("Error! Data not returned.", true);
        } 
        else if (U.isNotNull(data.error)) {
            var errorInternalMess = data.ka.error;
            var failedFirstTime = "Your credentials cannot be authenticated";
            var nbcReplacedText = "An error has occured, please click on Sign Up again.";
            if (errorInternalMess.match(failedFirstTime)) {
                statusMsg(nbcReplacedText, true);
            }
            else {
               statusMsg(data.error, true); // internal error
            }   
        }
        else if(U.isNotNull(data.ka.error)) {
            var disabledFBUser = "has been disabled";
            var replacedDisabledUserText = "Your account has been disabled due to inactivity, a violation of the <a href='http://"+nbc.domain+"/terms'>Terms of Service</a>, or at the discretion of NBC staff.  Please <a href='http://"+nbc.domain+"/about_us'>contact us</a> if you have any questions.";
            var errUserNameExist = "Unable to process change user name";
            var errorMess = data.ka.error;
            var innErrorMess = "Invalid username: Username is already taken. Try a different one.";     
            var errProfanity = "Sorry we were not able to register you.";
                var replaceForProfanity = "Invalid username. Please try again.";
            if (errorMess.match(errUserNameExist)) {
                statusMsg(innErrorMess, true);
            }
            else if (errorMess.match(disabledFBUser)) {
                statusMsg(replacedDisabledUserText, true);
            }
             else if (errorMess.match(errProfanity)) {
                statusMsg(replaceForProfanity, true);
            } 
            else { 
                statusMsg(data.ka.error, true);
            }       
           if ($(".login_overlay").css("block") != "none") {
            $("#loginUsername").focus();
          }
        }
    
        else { // SUCCESS
          success = true;
       //   alert("in success");
     //     alert(successText);
          displaySuccess(successText);
         /* user.setValues({token:data.ka.TOKEN, userId:data.ka.userId, userName:userName, email:data.ka.email});
          user.persist(saveInfo);
          */
        }
        if (!success) {
           
        }
      }
  
  function statusMsg(text,isError) {
    //  alert("text "+text);
        if (isError) {
          $("#serverMessage").addClass("invalid").html(text);
        }
        else {
          $("#serverMessage").addClass("valid").html(text);
        }  
          $("#processing img").hide();
          $("#overlay_content").css("opacity", 1);
   } 

function hideOverlay() {
  $("#overlay_wrapper").hide(); 
}
  
function clearStatusMsg() {
    $("#serverMessage").text("").removeClass("invalid").removeClass("valid");  
  }
 
function readCookie(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i=0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
          c = c.substring(1,c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
          return c.substring(nameEQ.length,c.length);
        }
      }
      return null;
    }

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}
  
  
 $(document).ready(function() {
   var apiKey1 = $("#apiKey1").text();
   /* alert(apiKey1+ readCookie(apiKey1+'_expires')); */
});
 
 
function convertMonthToNumber(monthName) {
   var selectedMonth = 1;
   var months = new Array(12);
   months[0] = "January";
   months[1] = "February";
   months[2] = "March";
   months[3] = "April";
   months[4] = "May";
   months[5] = "June";
   months[6] = "July";
   months[7] = "August";
   months[8] = "September";
   months[9] = "October";
   months[10] = "November";
   months[11] = "December"; 
   for (i=0; i< 12; i++) {
      if ( months[i] == monthName ) {
    	  selectedMonth = i+1;
      }
   }
   U.log("selectedMonth "+selectedMonth);
   return parseInt(selectedMonth);
}
 
 
 
 
 
 
