﻿$(document).ready(function() {
  initBinding();
  
  $(".PrintButton").click(function(){
    var link = $(this).children(".PrintButtonContent").children("a").attr("href");
    if(link != null)
    {
      //alert("link="+link);
      location.href = link;
    }
  });
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Dashboard
  ///////////////////////////////////////////////////////////////////////////////////////////////////  
  $(".EditWeddingDetails").click(function(){
    $(this).parent().next().slideToggle();
  });
  
  $("#dashboarddatepicker").datepicker({ showOn: 'button', buttonImage: '/test/tools/Images/Calendar.png', buttonImageOnly: true, dateFormat: 'D d M yy' });
  $("#dashboarddatepicker").change(function() {
    var datestring = $(this).attr("value");
    $("#WeddingDate").html(datestring);
  });
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Todo
  ///////////////////////////////////////////////////////////////////////////////////////////////////

  $(".TodoArrow").click(function() {
    $(this).next().slideToggle();
    $(this).toggleClass("TodoArrowOpen");
    return false;
  });

  $(".AddTodo").click(function() {
    if (!$(this).hasClass("open")) {
      $("#AddTodoForm").children("form").clone(true).prependTo($(this).next().children(".TodoList"));
      $(this).next().show(); //show ActiveTodos panel
      //initBinding();      
    }
    else {
      $(this).next("div").children(".TodoList").children(".TodoForm").remove();
    }
    $(this).toggleClass("open")
    return false;
  });

  $(".TodoAssignedToFilter").change(function() {
    $(this).parents("form").submit();
  });

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Schedule
  ///////////////////////////////////////////////////////////////////////////////////////////////////

  $(".FormChangePost").change(function() {
    var form = $(this).parents("form");
    var action = form.attr("action");
    var serializedForm = form.serialize();
    $.post(action, serializedForm,
      function(data) {
        //alert("data = [" + data + "]");
        if (data == "Success") {
          $("#ErrorMessage").empty();
        }
        else {
          $("#ErrorMessage").text(data);
        }
      }
    );
  })

  $(".AddEventCatOk").click(function() {
    var me = $(this);
    var form = $(this).parents("form");
    var action = form.attr("action");
    var serializedForm = form.serialize();
    $.post(action, serializedForm,
                function(data) {
                  form.parent().append(data);
                  form.children("input").attr("value", "");
                  form.toggleClass("FormHide");
                  initBinding();
                }
        );
    return false;
  });
});

function initBinding()
{
  $(".datepicker").datepicker({ dateFormat: "d/m/yy" });

  $(".GreenBarArrow").unbind('click');
  $(".GreenBarArrow").click(function() {
    $(this).next().slideToggle({height:"toggle", opacity:"toggle"});
    $(this).toggleClass("GreenBarArrowOpen");
    return false;
  });
///////////////////////////////////////////////////////////////////////////////////////////////////
// Budget Planner
///////////////////////////////////////////////////////////////////////////////////////////////////  
  $(".SupplierCost").Watermark("$Quoted");
  $(".SupplierNotes").Watermark("Notes");
  
  $(".BudgetItemArrow").unbind('click');  
  $(".BudgetItemArrow").click(function() {
      $(this).next().slideToggle();
      $(this).toggleClass("BudgetItemArrowOpen");
      return false;
  });
  
  //this is used for adding BudgetCategories, BudgetItems and BudgetItemSuppliers
  $(".BudgetAddFormSubmit").unbind('click');  
  $(".BudgetAddFormSubmit").click(function() {
    var me = $(this);
    var form = $(this).parents("form");
    var action = form.attr("action");
    var serializedForm = form.serialize();
    $.post(action, serializedForm,
      function(data) {
        form.parent().append(data);
        me.prev().attr("value", "");
        me.parent().toggleClass("FormHide");
        initBinding();
      }
    );
    return false;
  });
  
  $(".Cash").unbind('change');
  $(".Cash").change(function() {
    alert("cash");
    var val = $(this).attr("value");
    if(val.charAt(0) != '$')
      $(this).attr("value", "$"+val);
  });
  
  $(".BudgetItemAmount").unbind('change');
  $(".BudgetItemAmount").change(function() {
    var me = $(this);
    var form = $(this).parents("form");
    var action = form.attr("action");
    var serializedForm = form.serialize();
    //alert("sForm = ["+serializedForm+"]")
    //removes the $ and , from input strings
    serializedForm = serializedForm.replace(/%24/g, "");
    serializedForm = serializedForm.replace(/%2C/g, "");
    //alert("sForm = ["+serializedForm+"]")
    
    //replaces the stupid $ text is entered to please Luke
    var val = $(this).attr("value");
    if(val.charAt(0) != '$')
      $(this).attr("value", "$"+val);
    
    $.post(action, serializedForm,
      function(data) {
        //alert("data = " + data);
        UpdateBudgetPlannerTotals(me, data);
      }
    );
  });
  
  $(".BudgetInputChange").unbind('change');
  $(".BudgetInputChange").change(function() {
    var BudgetItemBudgetInput = $(this).parents(".greyBoxContent").children("form").children(".BIABudget");
    var form = $(this).parents("form");
    var action = form.attr("action");
    var serializedForm = form.serialize();
    
    //removes the $ and , from cost input string
    serializedForm = serializedForm.replace(/%24/, "");
    serializedForm = serializedForm.replace(/%2C/, "");
    
    //replaces the stupid $ text is entered to please Luke
    if($(this).hasClass("SupplierCost")){
      var val = $(this).attr("value");
      if(val.charAt(0) != '$')
        $(this).attr("value", "$"+val);
    }
    
    $.post(action, serializedForm,
      function(data) {
        //alert("data = " + data);
        UpdateBudgetPlannerTotals(BudgetItemBudgetInput, data);
      }
    );
  });
  
  $(".BudgetInputClick").unbind('click');
  $(".BudgetInputClick").click(function() {
    var BudgetItemBudgetInput = $(this).parents(".greyBoxContent").children("form").children(".BIABudget");
    var form = $(this).parents("form");
    var action = form.attr("action");
    var serializedForm = form.serialize();
    
    //removes the $ and , from cost input string
    serializedForm = serializedForm.replace(/%24/, "");
    serializedForm = serializedForm.replace(/%2C/, "");
    
    $.post(action, serializedForm,
      function(data) {
        //alert("data = " + data);
        UpdateBudgetPlannerTotals(BudgetItemBudgetInput, data);
      }
    );
  });
  
  $(".BudgetCategoryDelete").unbind('click');
  $(".BudgetCategoryDelete").click(function() {
    var item = $(this);
    jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
      if (r) {
        $.post(item.attr("href"),
          function(data) {
            item.parents(".BudgetGroup").remove();
            UpdateBudgetPlannerTotals(item, data); 
            //I've chucked item in here but doesn't really matter because on the totals up the top will be updated
            // Catagory and BudgetItem are irelivant because they are being delete.
          }
        );
      }
    });
    return false;
  });
  
  $(".BudgetItemDelete").unbind('click');
  $(".BudgetItemDelete").click(function() {
    var item = $(this);
    var BudgetItemBudgetInput = $(this).parent().children("div").children(".greyBoxContent").children("form").children(".BIABudget");
    jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
      if (r) {
        $.post(item.attr("href"),
          function(data) {
            //alert("data={"+data+"}");
            UpdateBudgetPlannerTotals(BudgetItemBudgetInput, data);             
            item.parent().remove();
          }
        );
      }
    });
    return false;
  });
  
  $(".BudgetItemSupplierDelete").unbind('click');
  $(".BudgetItemSupplierDelete").click(function() {
    var item = $(this);
    var BudgetItemBudgetInput = $(this).parents(".greyBoxContent").children("form").children(".BIABudget");
    jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
      if (r) {
        $.post(item.attr("href"),
          function(data) {
            //alert("data={"+data+"}");
            UpdateBudgetPlannerTotals(BudgetItemBudgetInput, data);             
            item.parents(".BudgetItemSupplier").remove();
          }
        );
      }
    });
    return false;
  });  



///////////////////////////////////////////////////////////////////////////////////////////////////
// Todos
///////////////////////////////////////////////////////////////////////////////////////////////////
  $(".TodoEdit").unbind('click');
  $(".TodoEdit").click(function() {
    //$(this).prev().prev().after("<img src='/Images/loading.gif'/>");
    //$(this).prev().prev().toggle();
    var root = $("#toolsRoot").text();
    //alert("root="+root);
    var id = $(this).attr("id");
    var todo = $(this).parents(".Todo");
    //alert("Getting it now id="+id);

    $.get(root + "/Todo/Edit/" + id,
    function(data) {
        //alert("Sweet!");
        todo.after(data);
        todo.toggle();
        initBinding();
        return false;
    });
    return false;
  });
  
  $(".TodoEditCancel").unbind('click');
  $(".TodoEditCancel").click(function(){
    //resets the checkbox and removes spinner/loader img
    //$(this).parents(".TodoForm").prev().children('input[type="checkbox"]').remove();
    //$(this).parents(".TodoForm").prev().children("img").remove();
    
    $(this).parents(".TodoForm").prev().toggle();
    $(this).parents(".TodoForm").remove();
    return false;
  });
  
  $(".TodoFormSubmit").unbind('click');
  $(".TodoFormSubmit").click(function(){
		var form = $(this).parents("form");
		var action = form.attr("action");
		var serializedForm = form.serialize();
    
    $.ajax(
    {
      type: "POST",
      url: action,
      data: serializedForm,
      dataType: "html",
      success: function(result)
      {
        var domElement = $(result);
        if(domElement.filter("div.Todo").length > 0){ 
          if(form.filter('form[action*="Create"]').length > 0){
            form.parents(".TodoList").prepend(domElement);
            form.remove();             
          }
          else{
            form.replaceWith(domElement);
          }
        }
        else {
          form.replaceWith(domElement); 
        }
        initBinding();
      }
    });
    return false;
  });
  
  $(".TodoFormCancel").unbind('click');
  $(".TodoFormCancel").click(function() {
      $(this).parents(".ActiveTodos").prev().removeClass("open");
      $(this).parents(".TodoForm").remove();
      return false;
  });
  
  $(".TodoCheckBox").unbind('click');
  $(".TodoCheckBox").click(function() {
      var root = $("#toolsRoot").text();
      var todo;
      //check whether its a form or a todo
      if ($(this).hasClass("TodoCheckBoxForm"))
          todo = $(this).parents(".TodoForm");
      else
          todo = $(this).parents(".Todo");
          
      if (todo.hasClass("done")) {
          var activeList = todo.parents(".CompletedTodos").prev().children(".TodoList");
          var todoID = todo.attr("id");
          $.post(root + "/Todo/ToggleTodoCompleted/", { id: todoID },
            function(data) {
                todo.remove();
                activeList.append(data);
                initBinding();
            }
        );
      }
      else {
          var doneList = todo.parents(".ActiveTodos").next();
          var todoID = todo.attr("id");
          if (todoID != 0) {
              $.post(root + "/Todo/ToggleTodoCompleted/", { id: todoID },
                function(data) {
                    todo.remove();
                    doneList.append(data);
                    initBinding();
                }
            );
          }
          else {
              todo.parents(".ActiveTodos").prev().removeClass("open");
              todo.remove();
          }
      }
  });
 
  $(".TodoDelete").unbind('click');
  $(".TodoDelete").click(function() {
      //alert("delete it");
      var item = $(this);
      var todoForm = $(this).parents("form");
      var todoID = todoForm.attr("id");
      if (todoID != 0) {
          //alert("exists");
          jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
            if (r) {
              $.post(item.attr("href"),
                function(data) {
                  if (data == "success") {
                      todoForm.remove();
                  }
                }
              );
            }
          });
      }
      else {
          //alert("new");
          todoForm.parents(".ActiveTodos").prev().removeClass("open");
          todoForm.remove();
      }
  });
///////////////////////////////////////////////////////////////////////////////////////////  
//Schedule scripts
///////////////////////////////////////////////////////////////////////////////////////////

  $(".ScheduleArrow").unbind('click');  
  $(".ScheduleArrow").click(function() {
      $(this).next().slideToggle();
      $(this).toggleClass("ScheduleArrowOpen");
      return false;
  });

  $(".FormShow").unbind('click');
  $(".FormShow").click(function() {
      $(this).next().toggleClass("FormHide");
      return false;
  });

  $(".FormUnShow").unbind('click');
  $(".FormUnShow").click(function() {
      $(this).parents("form").toggleClass("FormHide");
      return false;
  });

  $(".AddEventOk").unbind('click');
  $(".AddEventOk").click(function() {
    var me = $(this);
    var form = $(this).parents("form");
    var action = form.attr("action");
    var serializedForm = form.serialize();
    $.post(action, serializedForm,
      function(data) {
        form.parents(".SchedulePanel").append(data);
        form.children("#EventName").attr("value", "");
        form.toggleClass("FormHide");
        initBinding();
      }
    );
    return false;
  });

  $(".EventTimeChangePost").unbind('focus');
  $(".EventTimeChangePost").focus(function() {
    $(this).select();
  });
   
  $(".EventTimeChangePost").unbind('change');
  $(".EventTimeChangePost").change(function() {
    //matches 1am, 12pm, 12:50am etc
    var tb = $(this);
    var reg = new RegExp("^((0?[1-9]|1[012])(:[0-5]?[0-9])?((\ )?[APap][Mm])?)$");
    var val = $(this).attr("value");
    if(val.match(reg))
    {
      var form = $(this).parents("form");
      var action = form.attr("action");
      var serializedForm = form.serialize();
      $.post(action, serializedForm);
    }
    else
    {
     jAlert("Please enter a valid time format. (12pm, 9:15am)", "TimeAlert", function(){     
      setTimeout(function () { tb.focus() }, 50);
     });
    }
  });
  
  $(".EventChangePost").unbind('change');
  $(".EventChangePost").change(function() {
    var form = $(this).parents("form");
    var action = form.attr("action");
    var serializedForm = form.serialize();
    $.post(action, serializedForm);
  });
  
  $(".ScheduleDeleteItem").unbind('click');
  $(".ScheduleDeleteItem").click(function() {
    var item = $(this);
    jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
      if (r) {
        $.post(item.attr("href"),
          function(data) {
            item.parents(".ScheduleItem").remove();
          }
        );
      }
    });

    return false;
  });
  
  $(".ScheduleDeleteCategory").unbind('click');
  $(".ScheduleDeleteCategory").click(function() {
    var item = $(this);
    jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
      if (r) {
        $.post(item.attr("href"),
          function(data) {
            item.parents(".greyBox").remove();
          }
        );
      }
    });

    return false;
  });
}


//item is the element the BudgetItem input element that was changed was changed
//for deletedFunctions I just pass in the budgeted input of the relevent BudgetItem
function UpdateBudgetPlannerTotals(item, data)
{
  var arr 
  eval("arr="+data); 
  //alert(arr[0][0]); 
  $("#TotalBudgeted").attr("value", arr[0][0]);
  $("#TotalSpent").attr("value", arr[0][1]);
  $("#TotalDue").attr("value", arr[0][2]);

  var greenbar = item.parents(".BudgetPanel").prev().children(".center");
  greenbar.children(".BCABudgeted").html(arr[1][0]);
  greenbar.children(".BCAPaid").html(arr[1][1]);
  greenbar.children(".BCADue").html(arr[1][2]);

  item.siblings(".BIABudget").attr("value", arr[2][0]);
  item.siblings(".BIAPaid").attr("value", arr[2][1]);
  item.siblings(".BIADue").attr("value", arr[2][2]);
}

