
$(document).ready(function() {
  $.initTwitterMessaging();

  // bind to keywords field
  $('.yummly-search-text').live(
    'keypress',
    function(event) {

      var code = (event.keyCode ? event.keyCode : event.which);
      if (code == 13) {
        event.preventDefault();
        var currQ = $(this).val();
        // need a new value on each request so the href actually refreshes
        var userPrefs = $('#user_foodfinder_prefs').val();

        var newurl;
        if (userPrefs) {
          newurl = window.location.protocol + "//" + window.location.host
            + '/recipes/#q=' + currQ
            + userPrefs;
        } else {
          newurl = window.location.protocol + "//" + window.location.host
            + '/recipes/#q=' + currQ;
        }

        window.location.href = newurl;
      }
    });

  $('.yummly-search-button').live('click', function(event) {
    event.preventDefault();
    var currQ = $('#q', $(this).parent()).val();
    // need a new value on each request so the href actually refreshes
    var userPrefs = $('#user_foodfinder_prefs').val();

    var newurl;
    if (userPrefs) {
      newurl = window.location.protocol + "//" + window.location.host
        + '/recipes/#q=' + currQ
        + userPrefs;
    } else {
      newurl = window.location.protocol + "//" + window.location.host
        + '/recipes/#q=' + currQ;
    }

    window.location.href = newurl;
  });
  //
  $("#twitter").tweet( {
    avatar_size : 32,
    count : 5,
    query : $("#twitterSearch").text(),
    loading_text : "searching twitter..."
  });

  path = "../..";

  // run contact form when any contact link is clicked
  $(".rblink").live('click', function(event) {
    event.preventDefault();

    $('#savedAction').attr('href', $(this).attr('href'));
    $('#savedAction').attr('rel', $(this).attr('id'));
    // first check and see if the user is authed
    var currDate = new Date();
    $.getJSON("/login/ajaxLoggedIn", {}, function(json) {
      // alert(json.loggedIn);

      if (json.loggedIn) {
        // continue on to original action
        $.handleYummlyAction();
      } else {
        // not logged in, so pop logged in modal
        // $("a.nui-window-opener").nuiWindow().load();
        $.nui.windowOpen( {
          title : 'Log In to Yummly',
          url : '/window/auth'
        });
      }

    });
    return false;
  });

  $("#loginsubmit").click(function(event) {
    event.preventDefault();
    // if form is valid, determine if this is login or registration
    if ($("#loginForm").valid()) {
      var username = $("input#email").val();
      var password = $("input#password").val();
      var loginType = $("input[name='actiontype']:checked").val();

      // it's a login, so login and then continue to the original action
      if (loginType == 'login') {
        $.loginUser(username, password);
      } else if (loginType == 'reg') {
        // it's a registration, so register, then login, then continue to
        // the original action
        $.postJSON("/register/ajaxRegister", {
          username : username,
          password : password,
          emailAddress : username
        }, function(json) {
          if (typeof json.error != 'undefined') {
            $("#errors").text(
              'Registration unsuccessful. Please try again.');
          } else if (typeof json.success != 'undefined' && json.success) {
            $.loginUser(username, password);
          }
        });
      }

    }
  });

  // only need force for IE6
  $("#backgroundPopup").css( {
    "height" : document.documentElement.clientHeight
  });

  $('#homepageFormButton').click(
    function(event) {
      event.preventDefault();
      var allowedIngredient = $('#allowedIngredient').val();
      var excludedIngredient = $('#excludedIngredient').val();
      var allowedDiet = $('#allowedDiet').val();
      location.href = 'search/index/?q=#allowedIngredient='
        + allowedIngredient + '&excludedIngredient=' + excludedIngredient
        + '&allowedDiet=' + allowedDiet;
    });

  // selector to kill enter events on form fields
  $('.yummly-form-field').live('keydown', function(event) {
    var code = (event.keyCode ? event.keyCode : event.which);
    if (code == 13) {
      return false;
    }
  });

});

$.displayLoginDialog = function() {
  $.nui.windowOpen({
    title:'Log in/Register with Yummly',
    url:'/window/auth',
    onClose : function() {
      $.validationEngine.closePrompt('.formError',true);
    }
  });
};

$.postJSON = function(url, data, callback) {
  $.post(url, data, callback, "json");
};

$.callAuthProtected = function(callback, title) {
  if (title == null)
    title = 'Log In';

  var loginUrl = '/window/auth';

  $.getJSON("/login/ajaxLoggedIn", {}, function(json) {
    // alert(json.loggedIn);
    if (json.loggedIn) {
      callback();
    } else {
      $.setSavedAction(function() {
        $.nui.windowClose('.nui-window-frame-content');

        callback();
      });
      $.nui.windowOpen( {
        title : title,
        url : loginUrl
      });
    }
  });
};

$.setSavedAction = function(f) {
  $.__savedAction = f;
};

$.clearSavedAction = function() {
  $.__savedAction = null;
};

$.handleYummlyAction = function() {
  try {
    var closure = $.__savedAction;

    if (closure != null) {
      $.__savedAction = null;
      closure();
    } else {
      var currentLink = $('#savedAction').attr('href');
      if (typeof currentLink == "undefined") {
        currentLink = '';
        GA.trackPageview('/action/undefined');
      } else {
        GA.trackPageview(currentLink);
      }

      if (currentLink.search('user/addrecipetobox') > -1) {
        $.addToRecipeBox($('#savedAction').attr('rel'));
      } else if (currentLink.search('user/addrecipeimage') > -1) {
        $.showRecipeImageUpload();
      } else if (currentLink.search('user/vote') > -1) {
        $.handleVote();
      } else if (currentLink.search('user/removefavoriterecipe') > -1) {
        $.removeFavoriteRecipe($('#savedAction').attr('rel'));
      } else if (currentLink.search('profile/adduser') > -1) {
        $.handleFollowLink($('#savedAction').attr('followLink'));
      } else if (currentLink.search('user/removerecipeimage') > -1) {
        $.removeRecipeImage($('#savedAction').attr('href'));
      } else if (currentLink.search('recipe/save') > -1) {
        saveRecipe();
      } else if (currentLink.search('recipe/reportaproblem') > -1) {
        $.handleOpenReportWindow();
      } else if (currentLink == '') {
        window.location.reload(true);
      } else {
        // the link isn't blank, but it doesn't have a specific handler, so
        // redirect
        location.href = currentLink;
      }
    }
  } catch (e) {
    alert(e);
  }
};

$.addToRecipeBox = function(recipeIDStr) {
  var recipeArr = recipeIDStr.split('_');
  var recipeID = recipeArr[1];

  // $('#gotobox').html('Adding recipe...');
  $.nui.waitStart( {
    content : 'Adding to Favorites...',
    object : $('.yummly-body')
  });
  $
    .postJSON(
      "/user/ajaxaddrecipetobox",
      {
        recipeid : recipeID
      },
      function(json) {

        $.nui.windowClose('.nui-window-frame-content');

        if (typeof json.error != 'undefined') {
          $('#favoritebox_' + recipeID).html('Error adding recipe');
        } else if (typeof json.success != 'undefined' && json.success) {
          $('#activeFavoriteSpan_' + recipeID)
            .html(
              '<button type="button" class="nui-button rblink nui-active" icon="heart" id="' + recipeIDStr + '" title="A Favorite" href="/user/removefavoriterecipe"><span class="nui-icon nui-icon-heart"></span> Favorite</button>');
          // $('#gotobox').html('In Recipe Box');
        }
        if (window.justLoggedIn) {
          window.justLoggedIn = false;
          window.location.reload(true);
        } else {
          $.nui.waitStop();
        }
      });
};

$.removeRecipeImage = function(params) {
  // $('#gotobox').html('Adding recipe...');
  $.nui.waitStart( {
    content : 'Removing image',
    object : $('.yummly-layout-split')
  });
  $.ajax( {
    type : 'GET',
    url : params,
    async : false,
    success : function(json) {
      alert('success');
    },
    error : function(json) {
      alert('error');
    },
    complete : function(json) {
      $.nui.waitStop();
    }
  });
};

$.handleOpenReportWindow = function() {
  // something is messed up with these windows
  location.href = window.location.href + "?report=true";
}

$.removeFavoriteRecipe = function(recipeIDStr) {
  var recipeArr = recipeIDStr.split('_');
  var recipeID = recipeArr[1];

  $.nui.waitStart( {
    content : 'Removing from Favorites...',
    object : $('.yummly-body')
  });
  $
    .postJSON(
      "/user/ajaxremovefavoriterecipe",
      {
        recipeid : recipeID
      },
      function(json) {

        $.nui.windowClose('.nui-window-frame-content');

        if (typeof json.error != 'undefined') {
          $('#favoritebox_' + recipeID).html('Error removing recipe');
        } else if (typeof json.success != 'undefined' && json.success) {
          $('#activeFavoriteSpan_' + recipeID)
            .html(
              '<button type="button" class="nui-button rblink" icon="heart" id="' + recipeIDStr + '" title="Add to Favorites" href="/user/addrecipetobox"><span class="nui-icon nui-icon-heart"></span> Favorite</button>');
          // $('#gotobox').html('In Recipe Box');
        }
        $.nui.waitStop();
      });
};

$.initTwitterMessaging = function() {
  $("#tsubmit")
    .click(
      function(event) {
        event.preventDefault();

        $
          .postJSON(
            "/user/ajaxsendtwitter",
            {
              tusername : $("#tusername").val(),
              tpassword : $("#tpassword").val(),
              tmessage : $("#tmessage").val()
            },
            function(json) {
              if (typeof json.error != 'undefined') {
                $("#twitterResultMessage")
                  .text(
                    'We were unable to send your message. Please check your username and password.');
              } else if (typeof json.success != 'undefined'
                         && json.success) {
                $("#twitterResultMessage").text('Message sent.');
              }
            });

      });

  $.showRecipeImageUpload = function() {
    $("#recipeUpload").show();
  };

};

function withFacebookPermissions(perms, callback, fbRequired, permissionRequired) {
  return function() {
    // ask for a publish_stream permission before running the callback
    if (typeof FB === 'object') {
      var onLogin = function (response) {
        if (response.session && response.perms == perms) {
          callback();
        } else if (! permissionRequired) {
          callback();
        }
      };
      
      if (FB.getSession()) {
        // make sure we have the permissions
        FB.login(onLogin, {perms: perms});
      } else {
        if (! fbRequired)
          callback();
      }
    } else {
      if (! fbRequired)
        callback();
    }
  };
}

$.withFacebookSharing = function(sharingAttr, callback) {
  var fbSharingAttrs = getCurrentUserAttributes()['fb-sharing-preference'];
  if (typeof FB === 'object' && FB.getSession() && fbSharingAttrs && fbSharingAttrs[sharingAttr]) {
    // if we already have a permission, go ahead
    if (getCurrentUserFbPermissions().publish_stream) {
      $.callAuthProtected(callback);
    } else {
      // permission is missing, ask
      FB.login(
        function (response) {
          if (response.session && response.perms && response.perms.indexOf('publish_stream') >= 0) {
            getCurrentUserFbPermissions().publish_stream = true;
          } else {
            $.ajax({
              url: "/user/removeUserAttribute",
              data: {
                attribute: sharingAttr
              },
              dataType: 'json',
              type: 'POST',
              success: function(json, status, xhr) {
                fbSharingAttrs[sharingAttr] = false;
                if (typeof console == 'object') {
                  console.log("removeUserAttr returned: " + json);
                }
              },
              error: function(xhr, status, error) {
                if (typeof console == 'object') {
                  console.log("removeUserAttr threw an error: " + status + ": " + error);
                }
                
              }
            });
          }
          
          $.callAuthProtected(callback);
        },
        {perms: 'publish_stream'});
    }
  } else {
    $.callAuthProtected(callback);
  };
}

$.handleVote = function(recipeID, vote) {
  var callback = function() {
    $.postJSON("/user/handlerecipevote", {
      vote : vote,
      recipeID : recipeID
    }, function(json) {
      if (window.justLoggedIn) {
        window.justLoggedIn = false;
        window.location.reload(true);
      }
    });
  };

  $.withFacebookSharing('fb-sharing-publish-recipe-ratings', callback);
  
};

// moving some common profile code here
$.saveChangesEditProfile = function(form) {

  var zipcode = $('#zipcode').val();
  if (zipcode == 'Zip Code') {
    $('#zipcode').val('');
  }

  var isValid = $('#updateProfile').validationEngine( {
    returnIsValid : true,
    scroll : false
  });

  if (isValid) {
    var url = form.attr('action');
    var data = form.serializeArray();

    var callback = function(json) {

      if (json.success) {
        // let's just reload the page for now
        window.location.reload(true);

      }
    };

    $.postJSON(url, data, callback);
  }
};

$.logoutUser = function(username, password) {
  function logoutYummly() {
    $.ajax( {
      url : '/j_spring_security_logout',
      type : 'POST',
      data : {
        test : 1
      },
      dataType : 'text',
      timeout : 1000,
      error : function(result) {
        window.location.reload(true);
      },
      success : function(result) {
        window.location.href = '/';
      }
    });

  };
  
  if (typeof FB === 'object') {
    // do the FB logout first
    FB.getLoginStatus(function(response) {
      if (response.session) {
        FB.logout(function (response) {
          logoutYummly();
        });
      } else {
        logoutYummly();
      }
    });
  } else {
    logoutYummly();
  }
  
};

function facebookPostlogin(response) {
  // after login reload page and filter should pick up access token and create yummly session

  if (typeof response == 'undefined' || response.session) {

    $.nui.waitStart({content:'Logging In...', object:$('.nui-window-content')});
    $.postJSON("/login/ajaxcheckconnected", {test : 1}, function(json) {

      if (json.success) {
        window.justLoggedIn = true;
        _userData = json.props;
        $.handleYummlyAction();
      }
      else {
        // they have fb logged in, but aren't connected yet
        if (json.accessToken != "") {
          location.href = '/login/connect';
        }
        else {
          // chose not to log in
          $.nui.waitStop();
        }

      }

    });

  } else {
    $.nui.folderToggle(0, $('#auth'));
  }
}

$.errorOverlay = function() {
  $.nui.windowOpen( {
    title : 'An Error Has Occurred',
    url : '/window/error'
  });
};

$.ajaxSetup( {
  'beforeSend' : function(xhr) {
    try {
      if (typeof enableContentTypeOverride != 'undefined'
          && enableContentTypeOverride) {
        // xhr.setRequestHeader("Content-Type",
        // "application/x-www-form-urlencoded; charset=UTF-8");
        xhr.overrideMimeType('text/html; charset=UTF-8');
      }
    } catch (e) {

    }

  },
  "error" : function(XMLHttpRequest, textStatus, errorThrown) {
    // console.log(textStatus);
    // console.log(errorThrown);
    // $.unblockUI({ fadeOut: 400 });
    // $('#search_results').unblock();
    $.errorOverlay();
  }
});

function removeUrlParams(href) {
  var i = href.indexOf('?');

  if (i >= 0) {
    href = href.substr(0,i);
  }

  return href;
}

function logTrackingEvent(eventId, href) {
  href = removeUrlParams(href);
  
  $.postJSON("/tracking/logEvent", {
    event: eventId,
    entity: href // href is the like button's href attribute
  }, function(json) {
    if (typeof console === 'object')
      console.log(json);
  });
}
