var USER = null;
var MODAL_SHOWN_REASON;
var UPSELL_OPTION_SELECTED = null;
var SPREADLY_DISABLED = true;

// Function to do HTTP POST for a particular URL with response in JSON.
$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};

// Function to do HTTP GET for a particular URL with response in JSON.
$.getJSON = function(url, data, callback) {
	$.get(url, data, callback, "json");
};

// From: http://blog.mastykarz.nl/jquery-random-filter/
jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
{
    random: function(a, i, m, r) {
        if (i == 0) {
            jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
        };
        return i == jQuery.jQueryRandom;
    }
});

// Adds callback for DOM ready
$(document).ready(commonDomReady);

// Function to call when the DOM is ready for manipulation.
function commonDomReady() {
  $.ajaxSetup({ cache: false });  
  getUser();    
  setupModalDialogs();
  initialize();
  preFetchImages();
  
  if (location.pathname == '/avatar') {
    $("#headerLinksContainer").hide();      
  }
}

function preFetchImages() {
  var img = new Image();
  img.src = "/static/img/upsell/select_plan_small.png";
}

// Function to get basic performance stats for the current user.
function getUser() {
  $.getJSON("/users/get_current_user", {}, userLoaded);
}

// Callback for when the state for the current user is loaded.
function userLoaded(json) {
  USER = json;
}

function initialize() {
  if (USER == null) {
    setTimeout("initialize()", 500);
  }
  else {
    setupUpsell();
    showStartupModalDialog();    
    
    if (location.pathname == '/play') {
      setupHeader();
      setupPractice();
    }
    else {
      setupLandingPage();
    }
    
    trackPageview();
  }
}

function setupLandingPage() {
  if (USER.points > 0) {
    $("#try_button").attr('id', "try_signed_in");
  }
}

// Function to set up the onclick handlers for the links at the top-right and
// to set up the app in case this is an anonymous user.
function setupHeader() {
  if (typeof(USER) == "object") {  
    if (USER.email) {
    	$(".email").val(USER.email);
    }
    
    if (USER.username == null) {
      $("#settingsSignoutSpan").hide();
      $("#saveProgressSigninSpan").show();      
      $("#membership-package-options").hide();
      $("#buyNowContainer").show();
    }
    else {
      $('.fullName').html(USER.firstname + ' ' + USER.lastname);
    	$("#firstname").val(USER.firstname);
    	$("#lastname").val(USER.lastname);

    	$(".username").val(USER.username);
      
      $("#settingsSignoutSpan").show();
      $("#saveProgressSigninSpan").hide();
      $("#membership-package-options").show();
      $("#buyNowContainer").hide();      
    } 
    
    $("#headerLinksAnonymous").hide();      
    $("#headerLinksSignedIn").show();
  }
  else {
    $("#headerLinksSignedIn").hide();
    $("#headerLinksAnonymous").show();      
  }
}

function setupModalDialogs() {
  $('#progressLink').click(showProgress)
  $('#feedbackLink').click(showFeedback);
  $('#settingsLink').click(showSettings);
  $('#saveProgressLink').click(showSaveProgress);
  $('#signUpLink').click(showSaveProgress);  
  $('#saveProgressClose').click(saveProgressClose);
  $('#signoutLink').click(signoutClick);  
  $('.upsellRejection').click(upsellRejectionClick);
  $('.selectPlanButton a').click(upsellOptionButtonClick);
  $('.breadCrumbSelectPlan').click(breadCrumbSelectPlanClick);
  $('#settingsLink').click(showSettings);
  $('#buyNowLink').click(buyNowLinkClick);
  $(".buy_now_button").click(buyNowTopButtonClick);
  $(".buy_now_button_tall").click(buyNowBottomButtonClick);
  $('#pricingLink').click(pricingLinkClick);
  $('#classroomLink').click(classroomLinkClick);
  $("#sendChallengeEmail").click(sendChallengeEmailClick);
  
  $(".jqmWindow").jqm({modal: false,
                       onShow: onModalOpen,
                       onHide: onModalClose});
}

// This will change the status of the currently logged in user
function changeStatus(new_status, async) {
  if (USER.status != new_status) {
    params = {
      new_status: new_status
    };
  
    jQuery.ajax({
      url: '/users/change_status',
      data: params,
      type: "POST",
      async: async
    });
  }
}
 
function onModalOpen(hash) {
  hash.w.css('opacity',1.0).show();   
  action = hash.w.attr('id');
  trackEvent("Modal", action, "Shown Due to " + MODAL_SHOWN_REASON, 1);
  scroll(0,0);
}

 
// Function to set up event tracking for modal dialog buttons
function onModalClose(hash) {
  hash.o.remove(); 
  hash.w.fadeOut("fast");
  action = hash.w.attr('id');
  trackEvent("Modal", action, "Closed After " + MODAL_SHOWN_REASON, 1);
}

// Function called when the show progress link is clicked
function showProgress() {
  MODAL_SHOWN_REASON = "Header Link";
  $("#progress").jqmShow();
  $("#reportingContent").hide();
  $("#reportingProgressMessage").show();
  $("#reportingCloseButton").blur();
  $.post("/reporting", {}, reportingDownloaded)
}

// Callback after user progress has been downloaded
function reportingDownloaded(reportingHTML) {
  $("#reportingContent").html(reportingHTML)
  $("#reportingProgressMessage").hide();
  $("#reportingContent").show();
}

function showFeedback() {
  MODAL_SHOWN_REASON = "Header Link";
  $("#feedback").jqmShow();
}

function showSettings() {
  MODAL_SHOWN_REASON = "Header Link";
  $("#settings").jqmShow();
}

function showSaveProgress() {
  MODAL_SHOWN_REASON = "Header Link";
  $("#saveProgress").jqmShow();
}

function saveProgressClose() {
  UPSELL_OPTION_SELECTED = null;
}

// Function clled when sign out link is clicked
function signoutClick(event) {
  trackEvent("Account", "Sign out", "Clicked on Header Link", 1);
  changeStatus(STATUS_OFFLINE, false);
  $.cookie('user_id', null);
  $.cookie('problem_type', null);
  if (USER.classroom) {
    location.href = USER.classroom.url_shortcut;
  } 
  else {
    location.href = '/';
  }
  return false;
}

function setupUpsell() {
  if (typeof(USER) == "object" && 
      !USER.subscribed && 
      !freeClassroomUse()) {
    $('#buyNowSpan').show();
  }
  
  if (SPREADLY_DISABLED) {
    $("#upsell .spreadly").hide();
  }
}

// Function to show the appropriate modal dialog on startup. This gets called
// again every time a modal dialog gets closed so that multiple dialogs
// show up at the beginning if necessary.
function showStartupModalDialog() {
  if (USER.subscribed && !USER.thanked_for_subscription) {
    showThankYou();
  }
  else if (USER.reset_password) {
    showResetAccount();
  }
}

function showResetAccount() {
  MODAL_SHOWN_REASON = "Reset Account";
  if (USER.username == null) {
    $("#saveProgress").jqmShow();
  }
  else {
    $("#settings").jqmShow();  
  }
}

function buyNowLinkClick() {
  MODAL_SHOWN_REASON = "Upgrade Now Header Link";
  showUpsell();
}


function buyNowTopButtonClick() {
  MODAL_SHOWN_REASON = "Learn More Top Button";
  showUpsell();
}

function buyNowBottomButtonClick() {
  MODAL_SHOWN_REASON = "Learn More Bottom Button";
  showUpsell();
}

function pricingLinkClick() {
  MODAL_SHOWN_REASON = "Pricing Header Link";
  showUpsell();
}

function classroomLinkClick() {
  MODAL_SHOWN_REASON = "Classroom Header Link";
  $("#classroomSignupPre").jqmShow();
}

function showUpsell(reason) {
  trackPageview('/upsell_shown');  
  $("#upsell").jqmShow(); 
}

function createSpreadlyDialog() {
  if ($(this).children().length == 1) {
    url_params = "?return_url=" + escape(location.href) + "&user_id=" + USER.user_id;
    return_url = 'https://carrotsticks-www.appspot.com/billing/successful_purchase' + url_params;
    cancel_url = 'https://carrotsticks-www.appspot.com/billing/cancelled_purchase' + url_params;

    params = {
      'merchant_id': 'carrotsticks',
      'product_id': $(this).attr('id'),
      'paypal_custom': USER.user_id,
      'order_num': USER.user_id,
      'paypal_return_url': return_url,
      'paypal_cancel_url': cancel_url
    };
    iframe = createSpreadlyIFrame(params);  
    $(this).append(iframe);    
  }
}

function showThankYou() {
  $.postJSON("/users/thanked_for_subscription", {}, null);
  trackPageview('/successful_purchase');
  MODAL_SHOWN_REASON = "Successful Purchase";
  $("#thankYou").jqmShow();  
}

// Function to handle when a user rejects our upsell
function upsellRejectionClick(event) {
  trackPageview('/upsell_rejected');    
  $("#upsell").jqmHide();
    
  //MODAL_SHOWN_REASON = "Rejecting Upsell Shown Due to " + MODAL_SHOWN_REASON;
  //$("#upsellRejectionSurvey").jqmShow();
  //$("#upsell_rejection_survey_feedback").focus();  
}

// Function to handle a click on the buy now button
function upsellOptionButtonClick(event) {
  UPSELL_OPTION_SELECTED = $(event.target).attr('class')

  trackEvent("Modal", "upsell", "Offer Clicked (" + UPSELL_OPTION_SELECTED + ") After Shown Due to " + MODAL_SHOWN_REASON, 1);
  trackPageview('/upsell_clicked');      
  
  MODAL_SHOWN_REASON = "Click From Upsell";
  if (!USER || USER.username == null) {
    $("#upsell").jqmHide();
    $("#saveProgress").jqmShow();
  }
  else {
    upsellPlanSelected();
  }
}

function upsellPlanSelected() {
  if (SPREADLY_DISABLED) {
    redirectToPayPal();
  }
  else {
    $("#upsell").jqmHide();      
    $("#" + UPSELL_OPTION_SELECTED).each(createSpreadlyDialog);
    $("#" + UPSELL_OPTION_SELECTED).jqmShow();   
    $("#" + UPSELL_OPTION_SELECTED).removeClass('invisible'); 
  }  
}

function breadCrumbSelectPlanClick() {
  MODAL_SHOWN_REASON = "Click on Upsell Breadcrumb Banner";
  $("#" + UPSELL_OPTION_SELECTED).jqmHide();     
  $("#upsell").jqmShow();    
}

function redirectToPayPal() {
  url_params = "?return_url=" + escape(location.href) + "&user_id=" + USER.user_id;
  return_url = 'https://carrotsticks-www.appspot.com/billing/successful_purchase' + url_params;
  cancel_url = 'https://carrotsticks-www.appspot.com/billing/cancelled_purchase' + url_params;

  if (UPSELL_OPTION_SELECTED == "one_month") {
    $("#paypal_item_name").val("CarrotSticks 1-month subscription");
    $("#paypal_amount").val("3.95");    
  }
  else if (UPSELL_OPTION_SELECTED == "six_month") {
    $("#paypal_item_name").val("CarrotSticks 6-month subscription");
    $("#paypal_amount").val("19.95");
  }
  else if (UPSELL_OPTION_SELECTED == "twelve_month") {
    $("#paypal_item_name").val("CarrotSticks 12-month subscription");
    $("#paypal_amount").val("29.95");
  }

  $("#paypal_return_url").val(return_url);
  $("#paypal_cancel_url").val(cancel_url);
  $("#paypal_custom").val(USER.user_id);
  $("#paypal_form").submit();
}

function sendChallengeEmailClick(event) {
  MODAL_SHOWN_REASON = "Send Challenge Email";
  $("#opponentOffline").jqmHide();
}

function freeClassroomUse() {
  var now = new Date();
  //date is zero based so 4 = May
  if (5 == now.getMonth()) { return true; }
  return (USER.classroom && USER.classroom.in_school);
}
