var recipeData = null, subData = null, ingredientList = null,
ingredientMap = new Array();

$(document).ready(
  function() {
    path = "..";
    
    $('#delete_ingredient').live('click', deleteIngredient);

    $('.input_amount').live('keypress',
      function (event) {
        var code = (event.keyCode ? event.keyCode : event.which);
        // Allow system keys
        if ((code == 0) || (code == 8) || (code == 9)) {
          if (!isNaN($(this).val())) {
            deletePrompt($(this));
          }
          return true;
        }
        if ((code < 48 || code > 57) && code != 46) { // 46 is the code for period which is the decimal separator 
          buildPrompt($(this), "Please enter the amount in the form of a decimal");
        } else {
          if (!isNaN($(this).val())) {
            deletePrompt($(this));
          }
        }
      });
    
    $('.common_ingredient_Add').click(
      function(event) {
        event.preventDefault();
        showAddIngredient();
        $('#new_ingredient').val($(this).text());
        return false;
      });

    $('.common_ingredient_Remove').click(
      function(event) {
        event.preventDefault();
        GA.trackPageview('recipe/commoningredientremove');
        
        var ingIndex = 0;
        var currentIngredient = $(this).text().replace(/^\s+|\s+$/g, '');

        var totalMatches = $('.ingredient').length;

        //console.log('ingredientList: ' + ingredientList);
        //console.log('totalMatches: ' + totalMatches + ' ingredientList.length: ' + ingredientList.length);

        $('.yummly-recipe-ingredients-ingredient').each(
          function() {
            var matchTag = /<(?:.|\s)*?>/g;
            var currIngText = $(this).html();
            var ingredient_id = $(this).attr('id').replace('ingredient_', '');
            //console.log('ingredient_id: ' + ingredient_id);
            currIngText = currIngText.split("(")[0];
            currIngText = currIngText.replace(matchTag, "");
            currIngText = currIngText.replace(/^\s+|\s+$/g, '');
            if (currIngText == currentIngredient) {
              //console.log(currIngText + ' ' + currentIngredient + ' ingIndex: ' + ingIndex);
              var currID = $(this).parent('tr').attr('id');
              //console.log('currID: ' + currID);
              var edit_row = $('#editor-'+currID);
              var static_row = $('#'+currID);
              ingredientList.splice(currID, 1);
              edit_row.remove();
              static_row.remove();
              reindexIngredientTable();
              return false;
            }
            // only increment if the ingredient is correctly parsed out and we've never entered edit mode, or we're in edit mode and the ingredient hasn't been parsed out
            // kludge
            if ( (ingredient_id.search('ingredient') > -1) || (totalMatches == ingredientList.length)  ) {
              ingIndex++;
            }

            return true;
          });

        $('#recipe_edit').show();
        $('#recipe_edit_all').hide();
        return false;
      });    
    
      $('#servings').live('keypress', function(event) {
        var code = (event.keyCode ? event.keyCode : event.which);
        if (code == 0 || code == 8) {
          if (isInt($(this).val())) {
            deletePrompt($(this));
          }
        } else if (code == 13 || code == 9) {
            updateServings();
        } else if (code < 48 || code > 57) {
          buildPrompt($(this), "Please enter a whole number.");
        } else {
          if (isInt($(this).val())) {
            deletePrompt($(this));
          }
        }
      });
      
      $('#servings').blur(function() {
        deletePrompt($(this));
      });

      $('#recipe_save').click(function(event){
        
        event.preventDefault;
        
        $('#savedAction').attr('href', '/recipe/save');
        // first check and see if the user is authed
        var currDate = new Date();
        $.withFacebookSharing('fb-sharing-publish-edited-recipes', function() {
          // continue on to original action
          GA.trackPageview('recipe/saverecipe');
          saveRecipe();
        });

      });
      $('#recipe_add').click(showAddIngredient);      
      $('#update_servings').click(updateServings);
      $('#recipe_edit_all').click(editRecipe);
      $('#recipe_cancel').click(hideAddIngredient);
      $('#recipe_submits').click(addIngredient);

      $('#ingredients_table .yummly-recipe-ingredients-ingredient').bind("click", editIngredient);

      $("#emailForm").validationEngine({scroll:false});
      
      $('#emailRecipeButton').click(function(event){
        event.preventDefault();        
        GA.trackPageview('recipe/emailrecipe');

        var isValid = $('#emailForm').validationEngine({returnIsValid:true, scroll:false});

        //$.nui.waitStart({content:'Sending Email', object:$('#ingredients-bubble')});

        if (isValid) {
          $.getJSON(
            "/recipes/email",
            {
              username : $('#username').val(),
              recipeId : $('#recipeId').val(),
              toEmail : $('#toEmail').val(),
              fromEmail : $('#fromEmail').val(),
              fromName : $('#fromName').val(),
              personalNote : $('#personalNote').val(),
              ccChecked : ($('#ccChecked:checked').val() == 'on') ? true : false
            },
            function(json){
              if (json.success && json.success == "true") {
                $('#emailWindowDiv').hide();
                $('#emailSuccess').text("The recipe has been sent to " + json.toEmail);
                $('#emailSuccess').show();            
              } else {
                $('#emailWindowDiv').hide();
                $('#emailFailure').show();           
              }          
            }
          );
        }
      });

      $('#personalNote').keyup(function(event){
	event.preventDefault();
	limitChars('personalNote', 500, 'remainingChars');
      });

      $('#reportProblemLink').click(function(event) {
        event.preventDefault();
        $.getJSON("/login/ajaxLoggedIn", {}, function(json) {
          //alert(json.loggedIn);

          if (json.loggedIn) {
            // continue on to original action
            GA.trackPageview('recipe/reportaproblem');
            $.nui.windowOpen({title:'Report a problem', url:'/window/reportaproblem?recipe_id=' +  $('#recipe_id').val() });
          }
          else {
            // not logged in, so pop logged in modal
            //$("a.nui-window-opener").nuiWindow().load();
            $('#savedAction').attr('href', '/recipe/reportaproblem');
            $.nui.windowOpen({title:'Log In to Yummly', url:'/window/auth'});
          }
        });


      });
      var reportParam = $(document).getUrlParam("report");
      if (reportParam == 'true') {
        $.nui.windowOpen({title:'Report a problem', url:'/window/reportaproblem?recipe_id=' +  $('#recipe_id').val() });
      }
  });

var editInPlaceSettings = {
  start_form: '<tr id="editor-#{id}" class="yummly-recipe-ingredients-edit"><td class="yummly-recipe-ingredients-amount">',
  select_option_form: '<option #{onclick} value="#{option_value}" #{selected}>#{option_text}</option>',
  stop_form: '</td></tr>',
  start_first_column: '<div class="yummly-label">Amount</div><input type="text" id="amount-#{id}" class="input_amount" size="3" value="#{amount}"/><select id="unit-#{id}" style="width:6em;">',
  start_second_column: '</select></td><td class="yummly-recipe-ingredients-ingredient"><div class="yummly-label">Ingredient</div><select id="ingredient-#{id}" style="width:6em;">',
  stop_second_column: '</select> (<input type="text" id="remaining-#{id}" class="remaining" size="10" value="#{remaining}" />) ' +
    '<button class="nui-button delete_ingredient" id="delete_ingredient" title="Remove Ingredient"><span class="nui-icon nui-icon-subtract"></span></a>'
};


function deleteIngredient(){
  GA.trackPageview('recipe/deleteingredient');
  var edit_row = $(this).parents('tr:first');
  var ingredient_id = edit_row.attr('id').replace('editor-','').toLowerCase();
  var static_row = $('#'+ingredient_id);

  ingredientList.splice(ingredient_id, 1);
  edit_row.remove();

  static_row.remove();
  reindexIngredientTable();
}

function reindexIngredientTable() {

  $('#ingredients_table tr[class!=yummly-recipe-ingredients-edit]').each(function(i, currTR) {
                                                    //console.log($(this));
                                                    $(this).attr('id', i);
                                                    //console.log($(this));
                                                  });

  $('#ingredients_table tr[class=yummly-recipe-ingredients-edit]').each(function(i, currTR) {
                                                   //console.log($(this));
                                                   $(this).attr('id', 'editor-'+i);
                                                   //console.log($(this));
                                                 });

}

function addIngredient() {
  GA.trackPageview('recipe/addingredient');
  
  var ingredient_name = $('#as-values-ingredients-include').val().replace(',','') || null;
  var quantity = $('#new_amount').val() || null;
  var other = null;
  var unit = $('#new_unit') || null;
  var unit_name = $( "#new_unit option:selected" ).text() || null;

  if ($('#new_remaining').val() && $('#new_remaining').val() != 'Optional Details') {
    other = $('#new_remaining').val();
  }

  if(ingredient_name.length < 1) {
    //        console.log('name too short');
    $('#ingredient-label').html('Ingredient: <span class="error">(Please enter an ingredient name.)</span>');
  }
  else {
    // make sure ingredient is in ingredient dropdown for now
    var isValidIngredient = false;
    for (var i = 0 ; i < buckets['ingredient'].length ; i++) {
      if (buckets['ingredient'][i].term == ingredient_name) {
        isValidIngredient = true;
        break;
      }
    }

    if (isValidIngredient) {
      //    Fill our spot with a stub structure
      ingredientList[ingredientList.length] = {
        "alternatives":[
          {
            "ingredient" : {
              "term" : ingredient_name
            },
            "quantity": quantity,
            "remainder": other,
            "unit" : {
              "id" : unit.val(),
              "name" : unit_name
            },
            alternativeKind : "primary"
          }
        ],
        "id": ""
      };

      var form = "<tr style='display:none;' id='"+(ingredientList.length-1)+"' class='"+(((ingredientList.length-1)%2)?"even":"odd")+" display'><td class='yummly-recipe-ingredients-amount'>"+quantity+" " + unit.text() +
        "</td><td class='yummly-recipe-ingredients-ingredient'>"+ingredient_name + "("+other+")</td></tr>";
      $('#ingredients_table tr:last').after(form);
      //        console.log('hiding ingredient');
      //hideAddIngredient();
      //        console.log($('#'+(ingredientList.length-1)));
      $('#'+(ingredientList.length-1)).editMode(ingredientList.length-1);
      $('#ingredient-label').html('Ingredient: ');
    }
    else {
      $('#ingredient-label').html('Ingredient: <span class="error">(Please select an ingredient from the list. Enter at least 3 letters to see available ingredients.)</span>');
    }
  }
  $.nui.windowClose('.nui-window-frame-content');
  return false;
}

function showAddIngredient() {
  GA.trackPageview('recipe/showaddingredient');

  $.nui.waitStart({content:'Loading...', object:$('#ingredients-bubble')});
  
  if (recipeData == null || subData == null) {
    loadRecipeStructure(addIngredientLoaded);
  } else {
    $.nui.waitStop();
    addIngredientLoaded();
  }
}

var addIngredientLoaded = function () {
    $('#recipe_edit').show();
    $.nui.windowOpen({
      onOpen: function() {
      },
      title:'Add Ingredient',
      url:'/window/addingredient'
    });      
};


function hideAddIngredient() {

  var waitElem = $('.yummly-layout');
  GA.trackPageview('recipe/hideaddingredient');
  $.nui.waitStart({content:'Cancelling Edit Mode...', object:$(waitElem)});
  window.location.reload(true);
}

// Enter a custom ingredient name, currently an ugly js prompt
function enterCustom(e) {
  var input = window.prompt("Please enter the alternative ingredient's name:","");
  if (input)
  {
    $(e).parent().append($("<option></option>").attr("selected","selected").attr("value",'custom|'+input.toLowerCase()).text(input));
  }
}

// Handles the saving part of the recipe
function insertRecipe() {
  // Set the parent id
  $.nui.waitStart({content:'Saving recipe...', object:$('.yummly-body')});
  $.getJSON('/user/ajaxgetuser', function(data){

              if (! recipeData['baseRecipeId']) {
                recipeData['baseRecipeId'] = recipeData['id'];
              }
              

              var recipeString = $.toJSON(recipeData);

              data = {
                recipe : recipeString
              };
              if(recipeData['creatingUser'])
              {
                data['supercede'] = recipeData['id'];
              }

              $.ajax({
                       type: 'POST',
                       data:  data,
                       url:'/recipeAPI/insert',
                       contentType: "application/x-www-form-urlencoded; charset=utf-8",
                       success: function(data) {
                         confirmExit(false);
                         
                         var name = data.id;
                         
                         if (data.urls)
                           name = data.urls[0].urlName;
                         
                         window.location = "/recipe/"+name;
                       },
                       dataType: 'json'
                     });

            });

}

function saveRecipe(event) {

  $('#ingredients_table tr.yummly-recipe-ingredients-edit').saveEdit();

  insertRecipe();
}

function fieldChanged(event){
  $(event.target).data('dirty', true);
}

//
// editMode; hides the tr and replaces it with the proper form to fill in edited data
// if single id is passed in, only create form for single ingredient
//
$.fn.editMode = function(singleID) {
  //console.log("Editmode called: " + singleID);

  var isSingleIngredientEdit = false;
  if (typeof singleID != "object" && typeof singleID != 'undefined') {
    isSingleIngredientEdit = true;
  }

  if(!isSingleIngredientEdit) {
    // Remove old ones still stuck somewhere
    $('#ingredients_table tr.yummly-recipe-ingredients-edit').remove();

    $('#ingredients_table').unbind("click", editRecipe);
    $('#recipe_edit').show();
    $('#recipe_edit_all').hide();
  } else {
    $('#ingredients_table tr[id='+singleID+']').unbind("click", editRecipe);
  }

  try {
    this.each(function() {
                var id = this.id;
                if (!isSingleIngredientEdit || (isSingleIngredientEdit && id == singleID)) {
                  // We're logged in properly
                  var ingredient_term = ingredientList[id];
                  if (typeof ingredient_term != 'undefined') {

                    form = setupTemplate( editInPlaceSettings.start_form, {
                                            id : this.id
                                          } );

                    // Find the quantity/remainder required
                    var amount = ingredientList[id].alternatives[0].quantity || "";
                    var remainder = ingredientList[id].alternatives[0].remainder || "";

                    var unit;
                    //console.log('check1');
                    try {
                      unit = ingredientList[id].alternatives[0].unit.id || "";
                    }
                    catch (e) {
                      unit = "";
                    }
                    //console.log('check2');

                    form += setupTemplate( editInPlaceSettings.start_first_column, {
                                             id     : this.id,
                                             amount : amount
                                           } );

                    //        //console.log('editmode' , id);

                    // Loop through the units
                    $.each(buckets['unit'], function(j, ob) {
                             selected = '';
                             if( ob.id == unit ) {
                               selected = 'selected="selected"';
                             }

                             form += setupTemplate( editInPlaceSettings.select_option_form, {
                                                      option_value: ob.id,
                                                      option_text       : ob.searchValue,
                                                      selected  : selected,
                                                      onclick     : ""
                                                    } );
                           });

                    form += setupTemplate( editInPlaceSettings.start_second_column, {
                                             id            : id,
                                             amount  : amount
                                           } );

                    var list;
                    // TODO: Prefill with existing value
                    // Loop to fill the select with our substitutes
                    if(subData[ingredientList[this.id].alternatives[0].id])
                    {
                      list = subData[ingredientList[this.id].alternatives[0].id];
                    } else {
                      //console.log("Nothing found, id: " + ingredientList[this.id].alternatives[0].alternative.id);
                      list= [{
                               term : ingredientList[this.id].alternatives[0].ingredient.term,
                               id : ingredientList[this.id].alternatives[0].ingredient.id
                             }, {
                               term : "Other",
                               id : ""
                             }];
                    }

                    $.each(list, function(j, ob) {
                             if( ob.term == ingredient_term )
                               selected = 'selected="selected"';
                             else
                               selected = '';

                             if( ob.term == 'Other' && ob.id == '')
                               onclick = 'onclick="enterCustom(this); return false;"';
                             else
                               onclick = "";

                             form += setupTemplate( editInPlaceSettings.select_option_form, {
                                                      option_value: ob.term,
                                                      option_text       : ob.term,
                                                      selected  : selected,
                                                      onclick     : onclick
                                                    } );

                           });

                    form += setupTemplate( editInPlaceSettings.stop_second_column, {
                                             remaining: remainder,
                                             id : this.id
                                           } );

                    form += setupTemplate( editInPlaceSettings.stop_form, {  } );

                    $( this ).after( form );
                  }
                }

              });
  }
  catch(e) {
    //alert(e);
  }

  $('#recipe_edit').fadeIn(500);
  $('#recipe_edit_all').hide();

  //console.log(isSingleIngredientEdit);
  if(isSingleIngredientEdit) {
    
    $('#ingredients_table tr[id='+singleID+']').hide();
    $('#editor-'+singleID).show();
    //console.log('showing');
    $('#save-'+singleID).click(saveSingle);
    $('#cancel-'+singleID).click(cancelSingle);
    
  } else {

    // Hide the unwanted old version and show the new one
    $('#ingredients_table tr.display').fadeOut(200);
    $('#ingredients_table tr.yummly-recipe-ingredients-edit').fadeIn(500);

  }

  $('#ingredients_table input, #ingredients_table select').bind("change", fieldChanged);

  return this;
}; // function editMode

function cancelSingle(event){
  event.stopImmediatePropagation();
  GA.trackPageview('recipe/cancelsingleedit');
  $(this).parents('tr').eq(0).saveEdit(true);
}

function saveSingle(event) {
  event.stopImmediatePropagation();
  GA.trackPageview('recipe/savesingleedit');
  $(this).parents('tr').eq(0).saveEdit();
}

function isDirty(o){
  return o.data('dirty') == true;
}

// SaveEdit, save the data filled in for each row iff cancel is undefined or false
// @param cancel    if true, do not save, just restore view
$.fn.saveEdit = function(cancel) {
  // TODO: show JS 'in progress thing'
  this.each(function(){
              var id = this.id.replace('editor-','');

              var new_remainder = $("#remaining-" + id);
              var new_amount = $("#amount-" + id);
              var new_unit = $("#unit-"+id);
              var new_unit_name = $( "#unit-" + id + " option:selected" ).text();
              var new_ingredient = $( "#ingredient-" + id );
              var new_ingredient_name = $( "#ingredient-" + id + " option:selected" ).text();

              // Update the know ingredient
              var current_ingredient = ingredientList[id].alternatives[0];

              if(!cancel) {
                // Set the new values and clean out the id only in case something changed
                if(isDirty(new_remainder)) {
                  //console.log("remainder is dirty");
                  current_ingredient.remainder = new_remainder.val();
                  delete(current_ingredient['id']);
                }
                if(isDirty(new_amount)) {
                  current_ingredient.quantity = new_amount.val();
                  delete(current_ingredient['id']);
                }
                if(isDirty(new_unit)) {
                  current_ingredient.unit = {
                    "id": new_unit.val(),
                    "name": new_unit_name
                  };
                  delete(current_ingredient['id']);
                }
                if(isDirty(new_ingredient)) {
                  // Set ingredient stuff
                  if(new_ingredient.val().indexOf('custom|') == 0)
                  {
                    //custom entered value
                    delete(current_ingredient.ingredient['id']);
                    current_ingredient.ingredient.term = new_ingredient.val().substr(7);
                  } else {
                    current_ingredient.ingredient.id = new_ingredient.val();
                    current_ingredient.ingredient.term = new_ingredient_name;
                  }
                  delete(current_ingredient['id']);
                }
              } // end !cancel

              var quantityHTML = '';
              var currNumerator = '';
              var currDenominator = '';
              var wholeAmount = '';
              if (current_ingredient.quantity != '' && current_ingredient.quantity != null) {
                var fract = current_ingredient.quantity.toString().split(".");
                wholeAmount = fract[0];
                if (wholeAmount == '0') {
                  wholeAmount = '';
                }
                if (fract.length > 1) {
                  var currFract = "." + fract[1];
                  var formattedQuantity = decfrac(currFract);
                  currNumerator = formattedQuantity.split("/")[0];
                  currDenominator = formattedQuantity.split("/")[1];
                  quantityHTML = wholeAmount + '<span class="fraction"><span class="numerator">'+currNumerator+'</span><span class="denominator">'+currDenominator+'</span></span>';
                }
                else {
                  quantityHTML = wholeAmount;
                }
              }


              var html =  '<td class="yummly-recipe-ingredients-amount">'+quantityHTML + ' ' + new_unit_name + '</td>'+
                '<td class="yummly-recipe-ingredients-ingredient"><b>' + new_ingredient_name + '</b>';
              if(current_ingredient.remainder != undefined && current_ingredient.remainder != "")
                html += ' (' + current_ingredient.remainder + ')';
              html += '</td>';
              $( '#'+id ).html( html );
            });

  $('#ingredients_table tr.yummly-recipe-ingredients-edit').fadeOut(200).remove();
  $('#ingredients_table tr.display').fadeIn(500);

  $('#ingredients_table .yummly-recipe-ingredients-ingredient').bind("click", editIngredient);

  return this;
}; // _saveEdit


function editIngredient() {
  GA.trackPageview('recipe/editingredient');
  var edit_row = $(this).parent();
  //console.log(edit_row.attr('id') + ' - id');
  //edit_row.html('');
  editRecipe(edit_row.attr('id'));
}


function editRecipe(singleID) {
  var nextAction = 'user/editrecipe';
  if (typeof singleID == 'string' && singleID != '') {
    $('#curr_ingredient_index').val(singleID);
    var nextAction = 'user/editrecipeingredient';
  }
  
  GA.trackPageview(nextAction);

  confirmExit(true);

  if (ingredientList != null) {
    editRecipeLoaded(singleID);
  } else {
    $.nui.waitStart({content:'Loading...', object:$('#ingredients-bubble')});
    loadRecipeStructure(editRecipeLoaded, singleID);
  }
  
}

var editRecipeLoaded = function(singleID) {
  $('#ingredients_table tr.display').editMode(singleID);
  $.nui.windowClose('.nui-window-frame-content');
};

function loadRecipeStructure(callback, callback_params) {
  //$.nui.waitStart({content:'Loading...', object:$('#ingredients-bubble')}); 
  
  $.ajax({
    type: 'GET',
    async: true,
    contentType: "application/json; charset=utf-8",
    scriptCharset: "utf-8",
    url:'/recipeAPI/getById?id='+id,
    success: function(data) {
      recipeData = data;
      // Store the ingredients in a usable fashion
      ingredientList = recipeData.ingredientLines;
      // set up a reference map of ingredient positions to ingredient ids
      for (var i = 0 ; i < ingredientList.length ; i++) {
        ingredientMap[i] = ingredientList[i].id;
      }
      loadSubstitutes(callback, callback_params);
    },
    dataType: 'json'
  });    
}

function loadSubstitutes (callback, callback_params) {
  $.ajax({
    type: 'GET',
    async: true,
    url:'/recipeAPI/substitutes/'+id,
    success: function(data) {
      subData = data;
      $.nui.waitStop();
      if (callback_params == undefined) {
        callback();
      } else {
        callback(callback_params);
      }
    },
    dataType: 'json'
  }); 
}

function confirmExit(on) {
  on = false; // TODO: Remove, confirmation is annoying during dev
  window.onbeforeunload = on ? function (evt) {
    var message = 'You have entered new data on this page.  If you navigate away from this page without first saving your data, the changes will be lost.';
    if (typeof evt == 'undefined') {
      evt = window.event;
    }
    if (evt) {
      evt.returnValue = message;
    }
    return message;
  } : null;
}

function setupTemplate( template, values ) {
  var replace = function( str, match ) {
    return typeof values[match] === "string" || typeof values[match] === 'number' ? values[match] : str;
  };
  return template.replace( /#\{([^{}]*)}/g, replace );
}

function isInt(x) { 
  var y=parseInt(x); 
  if (isNaN(y)) return false; 
  return x==y && x.toString()==y.toString(); 
} 

function updateServings() {
  if (isInt($('#servings').val()) && $('#servings').val() > 0) {
    deletePrompt($('#servings'));

    $.nui.waitStart({content:'Updating recipe...', object:$('#ingredients-bubble')});

    window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + "?servings=" + $('#servings').val();
  } else {
    buildPrompt($('#servings'), "Please enter a whole number greater than zero.");          
  }

}

function limitChars(textid, limit, infodiv) {
  var text = $('#'+textid).val(); 
  var textlength = text.length;
  if(textlength > limit) {
    $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
    $('#'+textid).val(text.substr(0,limit));
    return false;
  } else {
    $('#' + infodiv).html((limit - textlength) +' characters remaining');
    return true;
  }
}

