/**
 *  This function gets all the relevant data of a product to prepare the form
 *  for use. It also creates all relevant Javascript UI/UX events for the form's
 *  functionality.
 */
function createOrderFormInit(product_id) {

  // Initialize jQuery UI datepicker
  $('form#create_order_form input#purchase_date').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true
  });

  /**
   *  Catch click events on the Regular / Backtest orders tab
   */
  $('div#modalBoxTopLink a#backtest_order_btn').click(function(){
    toggleBacktesting(true);
  });
  $('div#modalBoxTopLink a#regular_order_btn').click(function(){
    toggleBacktesting(false);
  });

  /**
   *  Catch change event on portfolio selection
   */
  $('form#create_order_form select#portfolio').change(function(){
    // Ask for Portfolio name if product is going to be added to a new
    // portfolio
    if ($('form#create_order_form select#portfolio').val() == 0) {
      $('form#create_order_form #create_new_portfolio').show('slow');
      $("#TB_ajaxContent").height(390);

    // Else, hide the form and delete the entered form name
    } else {
      $('form#create_order_form span#create_new_portfolio').hide();
      $('form#create_order_form input#new_portfolio_name').val('');
      $("#TB_ajaxContent").height(370);
    }
  });

  /**
   *  Automatically update total price when purchase quantity changes
   */
  $('form#create_order_form input#purchase_quantity').keyup (function(){
    // RegEx to test for integers
    var objRegExp  = /(^\d\d*$)/;

    // If it's a valid integer
    if(objRegExp.test(
      $('form#create_order_form input#purchase_quantity').val())
    ){
      // Hide error message
      $('form#create_order_form span#purchase_quantity_error').hide();
      // Update total price
      updateTotalPrice();
    } else {
      // Not an integer, but do not throw errors for an empty string
      if ($('form#create_order_form input#purchase_quantity').val()!=''){
        $('form#create_order_form span#purchase_quantity_error').show();
      } else {
        $('form#create_order_form span#purchase_quantity_error').hide();
      }
    }
  });

  /**
   *  Update the form to use data from the inception
   */
  $('form$create_order_form input#since_inception_btn').click(function(){
    getProductPrice(product_id, 'inception', '');
  });

  /**
   *  If the date changes, update the form to get the closest previous price to
   *  the new date
   */
  $('form$create_order_form input#purchase_date').change(function(){
    getProductPrice(
      product_id,
      'date',
      $('form$create_order_form input#purchase_date').val()
    );
  });

  /**
   *  Validate and submit the form
   *
   *  @todo Get design on success / failure modal
   */
  $('#place_order_btn').unbind('click', submitCreateOrderForm)
      .click(submitCreateOrderForm);

  /*
   * Modal Cancel Button
   */
  $('#modal_cancel_btn').click(function() {
    tb_remove();
  });

}

/**
 *  Check for login and pop up modal
 */
function addToPortfolioModalByPortfolioID(portfolio_id) {
  var product_id = 1;
  createOrderFormInit();

  check_login(function(){
    product_id = $('form#create_order_form input#product_id').val();

    // Open up modal with @param title
    openThickboxTitleDelayed("Add to Portfolio",
      "#TB_inline?height=375&width=450&inlineId=create_order_form_wrapper", 250
    );
    
    $("div#TB_ajaxContent").css("background-color","#eff3f4");
    setTimeout('$("div#TB_ajaxContent").css("background-color","#eff3f4");', 280);

    // Get user portfolios and insert into select dropdown
    $.ajax({
      url:      SITE_URL + 'ajax/orders/getPortfolios',
      data:     {},
      dataType: "json",
      async:    false,

      success: function(json){
        // Create dropdown list from id and description
        var insert = '';
        for(i=0; i<json.payload.portfolios.length; i++){
          prod_id = json.payload.portfolios[i].portfolio_id;
          prod_desc = json.payload.portfolios[i].portfolio_description;
          insert += '<option value="'+prod_id+'"';

          // If the current portfolio is mark last used from the backend, make it
          // the default value
        if (prod_id == portfolio_id)
            insert += ' selected="selected";'
          insert += '>'+prod_desc+'</option>';
        }

        // Adddefault options as well as user's portfolios
        insert =  '<option value="-1">-----Please select-----</option>'+
                  insert +
                  '<option value="0">Create new portfolio</option>';

        // Insert it into the element
        $('form#create_order_form select#portfolio').html(insert);
      }
    });

    // Hide all error messages
    $('form#create_order_form span#create_new_portfolio').hide();
    $('form#create_order_form span#backtest_message').hide();

    $('div#orderform_loading').hide();
    $('form#create_order_form').show();

  });
}

/**
 *  Check for login and pop up modal
 */
function addToPortfolioModal(product_id) {

  createOrderFormInit(product_id);

  $('form#create_order_form input#product_id').val(product_id);

  callback = function(){
    product_id = $('form#create_order_form input#product_id').val();

    // Open up modal with @param title
    openThickboxTitleDelayed("Add to Portfolio",
      "#TB_inline?height=375&width=450&inlineId=create_order_form_wrapper", 250
    );
    
    $("div#TB_ajaxContent").css("background-color","#eff3f4");
    setTimeout('$("div#TB_ajaxContent").css("background-color","#eff3f4");', 280);

    // Get product information and insert into form
    $.ajax({
      url:      SITE_URL + 'ajax/orders/getProduct',
      data:     {'product_id': product_id},
      dataType: "json",
      async:    false,

      success:  function(json){
        // Update form values
        $('form#create_order_form input#product_name').val(
          json.payload.product.product_description
        );
        
        // Set Product links (Confirmation Modal)
        var view_this_product = SITE_URL + 'group/'
                                + json.payload.product.group_uri + '/'
                                + json.payload.product.product_uri;
        
        $("a#view_this_product").attr("href", view_this_product);

      }
    });

    // Get user portfolios and insert into select dropdown
    $.ajax({
      url:      SITE_URL + 'ajax/orders/getPortfolios',
      data:     {},
      dataType: "json",
      async:    false,

      success: function(json){
        // Create dropdown list from id and description
        var insert = '';
        for(i=0; i<json.payload.portfolios.length; i++){
          prod_id = json.payload.portfolios[i].portfolio_id;
          prod_desc = json.payload.portfolios[i].portfolio_description;
          insert += '<option value="'+prod_id+'"';

          // If the current portfolio is mark last used from the backend, make it
          // the default value
          if (json.payload.portfolios[i].portfolio_last_used)
            insert += ' selected="selected";'
          insert += '>'+prod_desc+'</option>';
        }

        // Adddefault options as well as user's portfolios
        insert =  '<option value="-1">-----Please select-----</option>'+
                  insert +
                  '<option value="0">Create new portfolio</option>';

        // Insert it into the element
        $('form#create_order_form select#portfolio').html(insert);
        
      }
    });

    // Get most recent product price
    getProductPrice(product_id, 'inception', '');

    // Hide all error messages
    $('form#create_order_form span#create_new_portfolio').hide();
    $('form#create_order_form span#backtest_message').hide();

    $('div#orderform_loading').hide();
    $('form#create_order_form').show();

  }

  check_login(callback);
}

/**
 *  This function toggles between backtesting / regular orders by changing
 *  styling and a hidden value in the form
 */
function toggleBacktesting(backtesting){
  if (backtesting) {
    $('form#create_order_form input#backtesting').val('true');
    $('div#modalBoxTopLink a#regular_order_btn').removeClass('btn_greyON');
    $('div#modalBoxTopLink a#regular_order_btn').addClass('btn_greyOFF');
    $('div#modalBoxTopLink a#backtest_order_btn').removeClass('btn_greyOFF');
    $('div#modalBoxTopLink a#backtest_order_btn').addClass('btn_greyON');
    $('p.order_description').html('Backtested orders are hypothetical investments for the pupose of testing allocation in investment markets or managers.');
  } else {
    $('form#create_order_form input#backtesting').val('false');
    $('div#modalBoxTopLink a#backtest_order_btn').removeClass('btn_greyON');
    $('div#modalBoxTopLink a#backtest_order_btn').addClass('btn_greyOFF');
    $('div#modalBoxTopLink a#regular_order_btn').removeClass('btn_greyOFF');
    $('div#modalBoxTopLink a#regular_order_btn').addClass('btn_greyON');
    $('p.order_description').html('Actual orders are paper trades placed in real-time on investment markets or managers.');
  }
}

/**
 *  Function to make an AJAX request to get the product price on date of product
 *  inception, today's price, or the price of a historical date
 */
function getProductPrice(product_id, type, date) {

  // Prepare data string to get the product price
  if (type=='inception' ||type=='recent') {
    data = {'product_id':product_id, 'type':type};
  } else if(type=='date') {
    data = {'product_id':product_id, 'type':type, 'date':date};
  } else {
    data = {'product_id':product_id};
  }

  $.ajax({
    url:      SITE_URL + 'ajax/orders/getProductPrices',
    data:     data,
    dataType: "json",
    async:    false,

    success:  function(json){
      prices = json.payload.product_prices;

      // Update date / pricing / backtesting data in the form
      $('form#create_order_form #purchase_date').val(prices[0].date);
      $('form#create_order_form #purchase_price').val(prices[0].price);
      $('form#create_order_form a#purchase_price_a').html(prices[0].price);
      $('form#create_order_form input#backtesting').val(prices[0].backtest);

      toggleBacktesting(prices[0].backtest);

      updateTotalPrice();
      
      // Set Product links (Confirmation Modal)
      var view_this_product = SITE_URL + 'group/'
                              + json.payload.group_uri + '/'
                              + json.payload.product_uri;
      
      $("a#view_this_product").attr("href", view_this_product);
    }
  });
}

/**
 *  Updates the total price of the current order
 *
 *  Product quantity * product total
 */
function updateTotalPrice() {
  $('form#create_order_form input#total_price').val(
    '$ ' +
    ( $('form#create_order_form input#purchase_quantity').val() *
    $('form#create_order_form input#purchase_price').val() )
  );
}

/**
 * Process create order form when user click on PLACE ORDRE button
 * - calls validCrateOrderForm for simple validation
 * - invoke AJAX call to process order form
 * @return
 */
var submit_create_order_form = true;

function submitCreateOrderForm() {
      if (validCreateOrderForm() && submit_create_order_form == true ) {
        
        submit_create_order_form = false;
        $("div.data_processing > span").html("Creating order...").parent().show();
        
        form_data = $('form#create_order_form').serialize();
        $.ajax({
          type: "POST",
          url:      SITE_URL+"ajax/orders/postNewOrder",
          data:     form_data,
          dataType: "json",
          success:  function(json){
                      if(!json.success) {
                        // If the submit was not submit...
                        $("div.data_processing").hide();
                        alert('error');
                        submit_create_order_form = true;
                      }
                      else {                       
                        // Reset the form
                        $('form#create_order_form')[0].reset();
                        $("div.data_processing").hide();
                        
                        var view_your_portfolio_order = SITE_URL + 'portfolio/'
                            + json.payload.user_uri + '/'
                            + json.payload.portfolio_uri;
        
                        $("a#view_your_portfolio_order")
                          .attr("href", view_your_portfolio_order);
   
                        submit_create_order_form = true;
                        
                        openThickboxTitleDelayed("Add to Portfolio",
                          "#TB_inline?height=225&width=450&inlineId=create_order_confirmation_wrapper", 250
                        );
                        setTimeout('$("div#TB_ajaxContent").css("background-color","#eff3f4");', 280);
                      }
                    }
          
        });
        
        
      }
}

/**
 * Process create portfolio form when user submit the form
 * - calls validCreatePortfolioForm for simple validation
 * - invoke AJAX call to process order form
 * @return
 */
function submitCreatePortfolioForm() {
    if (validCreatePortfolioForm()) {
        
        setDataProcessing('data_processing', 'Creating portfolio...');
        
        $.ajax({
          type:     "POST",
          url:      SITE_URL+"ajax/portfolios/createPortfolio",
          data:     $("form#createPortfolioForm").serialize(),
          dataType: "json",
          success:  function(json){
                      if(json.success) {
                        self.parent.tb_remove();
                        $("div.data_processing").hide();
                        
                        // Set created portfolio links (Confirmation Modal)
                        var view_your_portfolio = SITE_URL + 'portfolio/'
                                                + json.payload.user_uri + '/'
                                                + json.payload.portfolio_uri;
                        
                        $("a#view_your_portfolio").attr("href", view_your_portfolio);
                        
                        openThickboxTitleDelayed("Create a Portfolio",
                          "#TB_inline?height=230&width=450&inlineId=create_portfolio_success_wrapper", 250
                        );
                        setTimeout('$("div#TB_ajaxContent").css("background-color","#eff3f4");', 280);
                        $('form#createPortfolioForm')[0].reset();
                      }
                    }
          
        });
      }
}

/**
 *  Validates the create order form and populates any error messages / styles
 */
function validCreateOrderForm(){
  var valid = true;

  // Error styling to be applied to invalid items
  var error_style = {'border':'1px solid red', 'padding':'2px'};

  // Make sure a portfolio is selected
  if ($('form#create_order_form select#portfolio').val() == - 1) {
    $('form#create_order_form select#portfolio').css(error_style);
    valid = false;

  // Or if they choose to create a portfolio, make sure a portfolio name is
  // entered
  } else if ($('form#create_order_form select#portfolio').val() == 0 &&
    $('form#create_order_form input#new_portfolio_name').val() == ''
  ) {
    $('form#create_order_form input#new_portfolio_name').css(error_style);
    valid = false;
  }

  // Make sure there is a valid purchase_quantity
  if ($('form#create_order_form input#purchase_quantity').val()=='' ||
    $('form#create_order_form input#purchase_quantity').val() <= 0
  ){
    $('form#create_order_form input#purchase_quantity').css(error_style);
    valid = false;
  }

  // Make sure that purchase_date is not emptyp
  if ($('form#create_order_form input#purchase_date').val()=='') {
    $('form#create_order_form input#purchase_quantity').css(error_style);
    valid = false;
  }

  return valid;
}

/*
 * Follow a portfolio
 */
function followPortfolio(portfolio_name, portfolio_id, user_id){
  check_login(function() {
    var requestURL = SITE_URL+"ajax/portfolios/followPortfolio"+"/"+portfolio_id;

    // Make sure user_id is provided before concat
    if(user_id != null) requestURL += "/"+user_id;

    $.get(requestURL, function(data){
      if(data=='Success') {

        // Get the button ID
        var buttonID = 'portfolio'+portfolio_id;

        // Replace Follow button with Unfollow button
        $('#'+buttonID).replaceWith(
          "<input id="+buttonID+
          " type=\"submit\" value=\"Unfollow\" class=\"search_btn\" onclick=\"unFollowPortfolio('"
          +portfolio_name+"', "+portfolio_id+")\"/>"
        );

      }
      // Remove the alert per design
      // else alert("We are unable to process your request at the moment. Please try again shortly.");
    });
  });
}

/*
 * Unfollow a portfolio
 */
function unFollowPortfolio(portfolio_name, portfolio_id, user_id){

  var requestURL = SITE_URL+"ajax/portfolios/unfollowPortfolio"+"/"+portfolio_id;

  // Make sure user_id is provided before concat
  if(user_id != null) requestURL += "/"+user_id;

  $.get(requestURL, function(data){
    if(data=='Success') {

      // Get the button ID
      var buttonID = 'portfolio'+portfolio_id;

      // Replace Follow button with Unfollow button
      $('#'+buttonID).replaceWith(
        "<input id="+buttonID+
        " type=\"submit\" value=\"Follow\" class=\"search_btn\" onclick=\"followPortfolio('"
        +portfolio_name+"', "+portfolio_id+")\"/>"
      );
    }
    // Remove the alert per design
    // else alert("We are unable to process your request at the moment. Please try again shortly.");
  });
}

/*
 * Unfollow a portfolio
 */
function unFollowAndRemoveRow(portfolio_name, portfolio_id, user_id){

  var requestURL = SITE_URL+"ajax/portfolios/unfollowPortfolio"+"/"+portfolio_id;

  // Make sure user_id is provided before concat
  if(user_id != null) requestURL += "/"+user_id;

  $.get(requestURL, function(data){
    if(data=='Success') {

      // Get the button ID
      var buttonID = 'portfolio'+portfolio_id;
      // Get the parent table object
      table = $('#'+buttonID).parents("table");
      // Get row count
      var count = $('tr', table).length;

      // If there are 2 rows left; means Header+1row, then remove the table.
      if(count > 2 ) $('#'+buttonID).parents('tr').remove();
      else {
        $(table).remove();
      }

    }
    else alert("We are unable to process your request at the moment. Please try again shortly.");
  });
}

/*
 *  This function gets all the relevant data of a product to prepare the form
 *  for use. It also creates all relevant Javascript UI/UX events for the form's
 *  functionality.
 */
function createPortfolioFormInit(){
  $(".createPortfolioModal").click(function(){
    // Open up modal with @param title
    check_login(function() {

      openThickboxTitleDelayed("Create a Portfolio",
        "#TB_inline?height=180&width=450&inlineId=create_portfolio_form_wrapper", 250
      );
      
      setTimeout('$("div#TB_ajaxContent").css("background-color","#eff3f4");', 280);

      $("form#createPortfolioForm").unbind('submit', submitCreatePortfolioForm)
          .submit(submitCreatePortfolioForm);
    });
  });
}

/**
 *  Validates the create portfolio form and populates any
 *  error messages / styles
 */
function validCreatePortfolioForm(){
  var valid = true;

  // Error styling to be applied to invalid items
  var error_style = {'border':'1px solid red', 'padding':'2px'};

  // Make sure there is a valid purchase_quantity
  if ($('form#createPortfolioForm input#portfolio_name').val()==''){
    $('form#createPortfolioForm input#portfolio_name').css(error_style);
    valid = false;
  }

  return valid;
}

/*
 * Set loading indicator
 */
function setDataProcessing(class_name, val_text) {
  $("div."+class_name+" > span").html(val_text).parent().show();
}

/**
 *  Activate editing in Open Order table / Portfolio details
 */

var editOpenOrderInputArray;

function isDigit(val) {
  
  var reg = new RegExp('^[1-9][0-9]*$');
  return (reg.test(val));
}

function activateOpenPortfolioOrderListTable() {
  
   editOpenOrderInputArray = new Array();
  
  $('#openPortfolioOrderListForm input.numInput').each(function(){
    
    //Back up original data
    editOpenOrderInputArray.push($(this).val());
    
    //Replace commas with ''
    $(this).val($(this).val().replace(/[,]/g,''));
    
    //Activate input fields
    $(this).removeAttr('disabled');
    
    $(this).attr('class','numInput enable_edit');
    
    //Hide Edit button
    $('#openPortfolioOrderListForm input#editPortfolioBtn').hide();
    
    //Show Save & Cancel buttons
    $('#openPortfolioOrderListForm input#savePortfolioBtn').attr('disabled',false).show();
    $('#openPortfolioOrderListForm input#cancelPortfolioBtn').attr('disabled',false).show();
    
    $('#openPortfolioOrderListTable th.deleteOrderTH').hide();
    $('#openPortfolioOrderListTable td.deleteOrderTD').hide();
    
  });
}

function setOpenPortfolioOrderListDisplay() {
  
  $('#openPortfolioOrderListForm input.numInput').each(function(){
    
    //Disable input fields
    $(this).attr('disabled',true);
    $(this).css('color', '#333');
    $(this).attr('class','numInput disable_edit');
    
  });
  
  //Hide Save & Cancel buttons
  $('#openPortfolioOrderListForm input#savePortfolioBtn').hide();
  $('#openPortfolioOrderListForm input#cancelPortfolioBtn').hide();
    
  //Hide Progressing indicator
  $("#openPortfolioOrderListForm div#updateProgressing").hide();
  
  //Show Edit button
  $('#openPortfolioOrderListForm input#editPortfolioBtn').show();
  
  //Show Delete Order buttons  
  $('#openPortfolioOrderListForm th.deleteOrderTH').show();
  $('#openPortfolioOrderListForm td.deleteOrderTD').show();
  
}


function updatePortfolioWeight(portfolio_id) {
  
  //Disable Save & Cancel buttons
  $("#openPortfolioOrderListForm input#savePortfolioBtn").attr('disabled',true);
  $("#openPortfolioOrderListForm input#cancelPortfolioBtn").attr('disabled',true);
  
  var update_data = true;
  
  $('#openPortfolioOrderListForm input.numInput').each(function(){
     if (isDigit($(this).val()) == false) {
      update_data = false;
    }
  });
  
  if(update_data == true) {
    
    //Show Progressing indicator
    $("#openPortfolioOrderListForm div#updateProgressing").show();
    
    //Get data from form input
    var portfolio_order_data = $("#openPortfolioOrderListForm").serialize();
    
    $.ajax({
      type: "POST",
      url: SITE_URL + 'ajax/orders/updatePortfolioWeight/'+portfolio_id,
      data: portfolio_order_data,
      dataType: "json",
      success: function(response){
                if (!response) {
                  //There is error updating data
                  alert("There is an error while updating. Please try again");
                }
                
                //Set Reloading message
                $("#openPortfolioOrderListForm div#updateProgressing span#updateMessage").html('Reloading Page...');
                window.location.reload();         
              }
    });
    
  } 
  else {
    
    alert("There is invalid input. Please correct before proceeding");
    
    //Disable Save & Cancel buttons
    $("#openPortfolioOrderListForm input#savePortfolioBtn").attr('disabled',false);
    $("#openPortfolioOrderListForm input#cancelPortfolioBtn").attr('disabled',false);
    
    //Hide Progressing indicator
    $("#openPortfolioOrderListForm div#updateProgressing").hide();
  }
  
}

function cancelEditPortfolioWeight() {
  
  var i = 0;
  
  $("#openPortfolioOrderListForm input#savePortfolioBtn").attr('disabled',true);
  $("#openPortfolioOrderListForm input#cancelPortfolioBtn").attr('disabled',true);
  
  $('#openPortfolioOrderListForm input.numInput').each(function(){
    
    //Reverse to original state
    $(this).val(editOpenOrderInputArray[i]);
    $(this).attr('size', $(this).val().length);
    i++;
    
  });
  
  //Reset to original display
  setOpenPortfolioOrderListDisplay();
      
}

function addToWatchList(obj, product_name, product_id) {
  
  //Check login before process begin
  check_login(function(){
    
    //Insert Ajax process indicator
    $(obj).html('<span><img src="'+IMAGE_V2_URL+'indicator_greenbg.gif" hspace="2" align="absmiddle"/> Please wait...</span>');
    
    //Adding product to watchlist 
    $.ajax({
      type: "POST",
      url: SITE_URL + 'ajax/orders/addToWatchlist/'+product_name+'/'+product_id,
      dataType: "json",
      success: function(response){
        if (response.success == true) {
          alert(response.message);
          $(obj).hide();
        }
        else {
          alert(response.error);
        }
            
      },
      error: function(xhr, ajaxOptions, thrownError){
        alert("There was an error while communicating with server. Please try again later.");
      }
    });
  });
  
}



$(document).ready(function() {
  
  $('#openPortfolioOrderListForm input').change(function() {
    
    //Replace commas with ''
    $(this).val($(this).val().replace(/[,]/g,''));
    
    //Check for digit [0=9] only
    if (isDigit($(this).val()) == false) {
      //Change input to red, indicates error
      $(this).css('color', 'red');
      alert('"' + $(this).val() + '" is an invalid input. Please re-enter valid number (0-9).');      
    }
    else {
      //Set valid input color
      $(this).css('color', '#333');
    }
  });
  
  $('#openPortfolioOrderListForm input.numInput').keyup(function(){
     
     var input_size = $(this).val().length;
     //Resize input box
     if( input_size > 0 ) $(this).attr('size', input_size);
  });
  
    
  

});
