$.ajaxSetup({ cache: false});
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend( jQuery.easing, {
  def: "easeOutCirc",
    swing: function (x, t, b, c, d) {
        //alert(jQuery.easing.default);
        return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
    },
    easeInCirc: function (x, t, b, c, d) {
        return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
    },
    easeOutCirc: function (x, t, b, c, d) {
        return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
    }
});

// delay execution of function for a specified time
var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

/* Sets appropriate timer, content and styling to display notification messages. */
var note_timeout;
var notify = function(message){
  clearTimeout(note_timeout);
  var notification = $("#notification");
  notification.html(message).slideDown(350);
  note_timeout = setTimeout(function(){ notification.slideUp(350); }, 18 * 1000);
};

function show_comments() {
    $("#order-form .product .icon").live('click', function(e){
        tr_id = $(this).parents("tr").attr('id').replace('row-', '');
        var expand = $(this).parents("tbody").find("textarea[name=" + tr_id + "-comment]").parent();
        if(expand.css("display")!="block"){
          expand.slideDown(250, function(){
            // .focus().select() not working in IE6
            // $(this).find("textarea");
          });
        }else{
          expand.slideUp();
        }
        return false;
      });
}

var submit_order = function(url) {alert('')
    $('form#order-form').attr('action', url);
    $('form#order-form').submit();
}

/*
  Any form action (keyup) triggers (and resets) a timer that saves the form with ajax
*/

var save_timeout;
var save = function(target){
    /* No input for a whole second when this point is reached.
       We serialize the form and post it. Reply is the form html snippet (w.
       management form and table rows). */
    var form = $("#order-form");
      notify("update screen");
    $.post(form.attr("action"), form.serialize(), function(data, statusText) {      
        var response = $(data);     
        order_form = $("#order-form");
        total_forms_id = "id_form-TOTAL_FORMS";
        initial_forms_id = "id_form-INITIAL_FORMS";
    
        $("#" + total_forms_id).val( response.find("#" + total_forms_id).val() );
        $("#" + initial_forms_id).val(response.find("#" + initial_forms_id).val() );
        order_form.find("tfoot .price").html( response.find("tfoot .price").html() );
        
        response.find("tbody tr.row").each(function(i){         
            var response_row = $(this);         
            resp_row_id = response_row.attr('id').replace('row-', '');

            response_errors = response.find("tbody tr.errors[id=row-errors-" + resp_row_id + "]").find(".errorlist");
            
            target_row = order_form.find("tr#row-" + resp_row_id);
            target_errors_cont = order_form.find("tbody tr.errors[id=row-errors-" + resp_row_id + "]");
            
            target_row.find("td.product").attr('class', response_row.find("td.product").attr('class')); // Syncronise css classes
            target_row.find("td.amount").attr('class', response_row.find("td.amount").attr('class')); // Syncronise css classes
            
            target_row.find("td.item_price").html(response_row.find("td.item_price").html());
            target_row.find("td.special_product").html(response_row.find("td.special_product").html());
            target_row.find("td.total").html(response_row.find("td.total").html());
        
            target_errors_cont.find(".errorlist").remove(); // Remove errors
            if(response_errors.size()) {
                target_errors_cont.find('td').html(response_errors); // And insert them again
            };
            
            target_add_row = order_form.find("tr.product_config_additonal_products[id=row-additonal_products-" + resp_row_id + "]");            
            resp_add_row = response.find("tr.product_config_additonal_products[id=row-additonal_products-" + resp_row_id + "]");
            
            resp_add_row.find("tr.additional_item_row").each(function(i){
                var response_add_item_row = $(this);
                
                tr = target_add_row.find('tr#' + response_add_item_row.attr('id'));
                
                tr.find("td.add_prod_total").html(response_add_item_row.find("td.add_prod_total").html());
                tr.find("td.unit_price").html(response_add_item_row.find("td.unit_price").html());
                tr.find("td.add_prod_amount").html(response_add_item_row.find("td.add_prod_amount").html());
            });
        });
    notify("screen updated");
    });
};

/*
Abstract of common pattern.
GET returns confirmation message, POST performs the action.
*/

var confirm_action = function(resource, success, error, gets, posts){
  if(!gets){ var gets={}; }
  if(!posts){ var posts={}; }
  $.get(resource, gets, function(response){
    var c = confirm(response);
    if(c){
      $.post(resource, posts, function(response){
        if(response['success']){
          success(response);
        }else{
          if(error){
            error(response);
          }else{
            alert(response['message']);
          }
        }
      }, "json");
    }else{
      return false;
    }
  });
}

function init_desired_delivery_date(date_input) {
    date_input.datepicker({
        dateFormat: "dd-mm-yy", 
        minDate: "+1d",
        showOn: "button", 
        buttonImageOnly: true, 
        buttonImage: "/media/images/icon_calendar.gif"
    });

    date_input.keyup(function(e) {
        var code_format = {109: ["-", "dd-mm-yy"], 111: ["/", "dd/mm/yy"], 
            191: ["/", "dd/mm/yy"], 190: [".", "dd.mm.yy"]};
        if (e.keyCode in code_format && 
            date_input.val().indexOf(code_format[e.keyCode][0]) == -1) {
            date_input.val(date_input.val() + code_format[e.keyCode][0])
                .datepicker("option", "dateFormat", code_format[e.keyCode][1]);
        }
    });
};


function show_my_room_popup(profile_url) {
    $.get(profile_url, {}, function(response) {
        $.modal(response, {
            onShow: function(dialog){
                profile_popup_on_show(); 
            },
            onClose: function(dialog) {
                profile_popup_on_close(dialog);
                check_messages_count();
            },
            minWidth : 870,
            minHeight : 570
        });
     });
    return false;
};

function feedback_dialog(where_url) {
    $.get(where_url, {}, function(response){
        $.modal(response, {
            onShow: function(dialog) {
                return;
            }
        });
    });
    return false;
}
function send_feedback () {
    var form = $('#feedback-form');
    $.post(form.attr("action"), form.serialize(), function(response, status) {
        if (response != 'SUCCESS') {
            $('.modalData').html(response);
        } else {
            $.modal.close();
        }
    });
}

function init_find_address_feature(config) {
    if (config == undefined) {
        config = {
            'zip_code': '#id_zip_code',
            'city': '#id_city',
            'street': '#id_address',
            'country': '#id_country'
        }
    }
    if (config['zip_code'] != undefined) {
        var find_address_url = '/shop/find_address/';
        $(config['zip_code']).autocomplete(find_address_url, {
            width: 300,
            formatItem: function(item) {
                var data = $.evalJSON(item);
                return data['zip_code'] + 
                    (data['city'] != undefined ? ' ' + data['city'] : '') + 
                    (data['street'] != undefined ? ' ' + data['street'] : '') + 
                    (data['country'] != undefined ? ' ' + data['country'] : '') + '\n';
            },
            formatResult: function(item) {
                var data = $.evalJSON(item);
                return data['zip_code'];
            }
        }).result(function(event, item) {
            var data = $.evalJSON(item);
            $(config['city']).val(data['city']);
            // $(config['street']).val(data['street']);
            $(config['country']).val(data['country']);
            if (config['resultCallback'] != undefined) config['resultCallback']($(config['zip_code']));
        });
    }
    if (config['city'] != undefined) {
        $(config['city']).autocomplete(find_address_url, {
            width: 300,
            extraParams: {by: 'city'},
            formatItem: function(item) {
                var data = $.evalJSON(item);
                return data['zip_code'] + ' ' + data['city'] + 
                    (data['street'] != undefined ? ' ' + data['street'] : '') + 
                    (data['country'] != undefined ? ' ' + data['country'] : '') + '\n';
            },
            formatResult: function(item) {
                var data = $.evalJSON(item);
                return data['city'];
            }
        }).result(function(event, item) {
            var data = $.evalJSON(item);
            $(config['zip_code']).val(data['zip_code']);
            // $(config['street']).val(data['street']);
            $(config['country']).val(data['country']);
            if (config['resultCallback'] != undefined) config['resultCallback']($(config['city']));
        });
    }
};

//Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
};


/* Order project functionality */
function init_order_project() {
    // all functionality implemented inside popup template
    init_order_project_inside_popup();
}

function order_actions_on_show(dialog) {
    // init_desired_delivery_date(dialog.container.find("#id_desired_delivery_date"));
    init_order_project();
    if (dialog.container.find('#order-edit').length > 0) {
        init_order_edit_form();
    };
    dialog.container.find(".cancel").click(function(e){
        $.modal.close();
        return false;
    });
    dialog.container.find(".submit").click(function(e){
        $.getJSON(
            '/shop/order/' + $('#check_date_order_id').val() + '/check-delivery-date/',
            { desired_delivery_date: $('input#id_desired_delivery_date').val() },
            function(response){
                if (response['error']) {
                    alert(response['msg']);
                    return true;
                }
                if (!response['nodata']) {
                    if (confirm(response['msg'])) {
                        $('input#id_desired_delivery_date').val(response['new_date']);
                        dialog.container.find("form").ajaxSubmit( 
                            { target: dialog.container.find("form").parent(),
                              success: function(responseText, responseXML) {
                                  if (responseText == 'ok'){
                                      window.location.reload();
                                  } else {
                                      order_actions_on_show(dialog);
                                  };
                              }
                            });
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    dialog.container.find("form").ajaxSubmit( 
                        { target: dialog.container.find("form").parent(),
                          success: function(responseText, responseXML) {
                              if (responseText == 'ok'){
                              window.location.reload();
                              } else {
                              order_actions_on_show(dialog);
                              };
                          }
                        });
                    return false;
                }
            });
    });
}

$(document).ready(function(){

    (function($) {
        var lastSelected;
        var selector = '#order-table :input[name=item]';

        $(selector).live('click', function(ev) {
            if (ev.shiftKey) {
                var checkBoxes = $(selector)

                var last = checkBoxes.index(lastSelected);
                var first = checkBoxes.index(this);

                var start = Math.min(first, last);
                var end = Math.max(first, last);

                var chk = lastSelected.checked;
                for (var i = start; i < end; i++) {
                    checkBoxes[i].checked = chk;
                }
            } else {
                lastSelected = this;
            }
        });
    })(jQuery);

  $(document).ajaxSend(function(event, xhr, settings){
    if (typeof _gaq !== "undefined" && _gaq !== null) {
      _gaq.push(['_trackPageview', settings.url]);
    }
  });

  $('#order-table :input[name=item]').live('change', function () {
      if ($('#order-table :input[name=item]:checked').length > 0) {
          $('#transfer,#transfer-copy').removeAttr('disabled');
      } else {
          $('#transfer,#transfer-copy').attr('disabled', 'disabled');
      }
  });

  var total_forms = $("#id_form-TOTAL_FORMS, #id_form-INITIAL_FORMS");

  $('#order-select-all').click(function () {
    if ($(this).is(':checked')) {
      $('#order-table :input[name=item]').attr('checked', "checked");
      $('#transfer,#transfer-copy').removeAttr('disabled');
    } else {
       $('#order-table :input[name=item]').removeAttr("checked");
       $('#transfer,#transfer-copy').attr('disabled', 'disabled');
    }
  });

  show_comments();
  $("#order-form :input[type=checkbox]").live('change', save);
  $("#order-form :input[type!=checkbox]").live('keyup', function() { delay(save, 700); });
  $("#order-form :tr.amount :input").live('click', function() {$(this).select();});

  $("#price-form select").live('change', function(){
    var options = { 
        success:    function() { 
            save();
        } 
    }; 
    $(this).parents("form").ajaxSubmit(options);
  });

  $('#account-form select').change(function () {
    var $form = $('#account-form');
    $.ajax({
        url: $form.attr('action'),
        data: $form.serialize()
    });
  });
  // product order redirect handler
  // if GET request contains "product_adding_redirect" key system
  // should automatically trying to add current active product to current active order
  // with product configuration checking
  get_url_vars = getUrlVars();
  if (get_url_vars['product_adding_redirect']) {
      sel = $('#open-order-list').children('option:selected');
      if (sel.val() != 'BLANK') {
          $(".add-to-order-submit").live("click", add_to_order_submit);
          $(".add-to-order-submit").click();
      };
  };

  /* Serialize order items, GET to check for conflict, warn on conflict,
    return and reset <select> or keep going:
    transfer to order, remove from DOM, update total price and reset <select> */
  function transfer_items(add_params) {
      add_params = typeof(add_params) != 'undefined' ? add_params : '';
      return function () {
          var that = this;
          var checked = $("#order-table input:checked");
          if(that.value&&checked.size()){
            var resource = $(that).parents("form").attr("action")+'?to_order='+that.value + add_params;
            $.post(resource+'&check_collision=1', checked.serialize(), function(response){
              if(Number(response['collision'])){
                var c = confirm(response['message']);
                if(!c){
                  that.value = "";
                  return false;
                }
              }
              var resource = $(that).parents("form").attr("action")+'?to_order=' + response['to_order'] + add_params;
              $.post(resource, checked.serialize(), function(response){
                if(response['success']){
                  if (response['remove'] == "True") {
                      total_forms.val(total_forms.val()-checked.size());
                      checked.each(function(i){
                        var tr = $(this).parents("tr");
                        tr.next().remove();
                        tr.next().next().remove();
                        tr.remove();
                      });
                  }
                  notify(response['message']);
                  $("table tfoot .price span").html(response['total']);
                }
              }, "json");
            }, "json");
            that.value = "";
          }else{
            that.value = ""; // Reset picker
          }
      }
  }
  $("#shop select#transfer").change(transfer_items());
  $("#shop select#transfer-copy").change(transfer_items('&copy=True'));

  /* Serialize order items and delete, remove from DOM, update total price */
  $("#shop input#delete").click(function(e){
    var checked = $("#order-table input:checked");
    if(checked.size()){
        var resource = $(this).parents("form").attr("action");
        confirm_action(resource, function(response) {
            to_delete = response['to_delete'].split(',');
            total_forms.val(total_forms.val() - to_delete.length); // Update formset management form
            jQuery.each(to_delete, function(i, val) {
                $("#order-table").find("tr#row-product_config_line-" + val).remove();
                $("#order-table").find("tr#row-product_config_additonal_products-" + val).remove();
                $("#order-table").find("tr#row-additonal_products-" + val).remove();
                $("#order-table").find("tr#row-errors-" + val).remove();
                $("#order-table").find("tr#row-comment-" + val).remove();
                $("#order-table").find("tr#manual-convert-"+val).remove();
                $("#order-table").find("tr#row-" + val).remove();
            });         
            $("#order-table tfoot .price span").html(response['total']);
            notify(unescape(response['message']));
        }, null, null, checked.serialize());
    }
    return false;
  });

  $(".comment-tools .show-all, .comment-tools .hide-all").click(function(){
      $('.show-all, .hide-all').toggle();
      $('#shop tr div.comment textarea')
        .filter(function() { return $(this).val() != ""; })
        .parent().slideToggle();
    return false;
  });

  /*
   * Show all not empty comments
   */
  function show_all_not_empty_comment(){
      $("#shop tr div.comment textarea").each(
      function(i){
          if ($(this).text().length > 0 && enable_show_all_not_empty_comment) {
          $(this).parent().slideDown();
          }
      }
      );

  };
  show_all_not_empty_comment();

  $(".comment-tools .hide-all").click(function(){
    $("#shop tr div.comment").slideUp();
    return false;
  });

  /* Cancel order and redirect with just setting top.location.href */
  $("#order-actions .cancel").click(function(e){
    var that = this;
    $.get(that.href, {}, function(response){
      var c = confirm(response);
      if(c){
        $.ajax({
          url: that.href,
          type: "POST",
          dataType: "json",
          // NGINX does not currently handle empty POST see discussion http://www.ruby-forum.com/topic/162976
          data: { fake: 'body' },
          complete: function(){
            document.location.href = document.location.href;
          }
        });
      }
    });
    return false;
  });

  $("#order-actions .submit").click(function(e){
    if($(".errorlist").size()) {
      $(".errorlist").each(function(i){ $(this).parents(".comment").show(); });
      alert(_('correct_form_errors'));
      return false;
    }
  });

  /* Get order HTML with GET, put in modal, activate controls and take care of
     invalid forms with a special X-DJANGO-VALID-FORM header */
  $("#order-actions .edit").click(function(e){
    var that = this;
    $.get(that.href, {}, function(response){
      $.modal(response, {
        onShow: order_actions_on_show 
      });
    });
    return false;
  });
  

  $("#order-actions .update").click(function(e){
    var that = this;
    $(that).parents("form").submit();
    return false;
  });
  
  /* Add to order */

  $(".add-to-order-submit input[name=amount]").live('keypress', function (e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which == 13) {
            e.target = null;
            add_to_order_submit(e);
            return false;
        }
        if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
            return false;
        }
    });

  $(".add-to-order-submit").live("click", add_to_order_submit);
  
  function add_to_order_submit(e){
    if ($(e.target).is('input')) {
        e.preventDefault();
        return false;
    };

    var form = $("#id_add_items_form");
    if(form.find("select").val() == "BLANK"){
      // Syncronous call to process new order form first
      form.submit();
    } else {
      // Asyncronous call because we don't need any more user interaction
      $.post(form.attr("action")+"?check_collision=1", form.serialize(), function(response, status){
        if(Number(response['collision'])){
          var c = confirm(response['message']);
          if(!c){
            return false;
          }
        };
        
        // check if product should be configurated
        check_product_config(form.children('input[name=product_id]').val(),
            function(was_configured, newitemnumber, original_item_number, product_config_line, amount) {
                if (was_configured) {
                    // change product in form
                    form.children('input[name=product_id]').val(newitemnumber);
                    // add product config line to form
                    form.append("<input style='display:none' name='product_config_line' value='" + product_config_line + "' />");
                    form.append("<input style='display:none' name='amount' value='" + amount + "' />");
                };
                // add product in standart way
                $.post(form.attr("action"), form.serialize(), function(response, status){
                    if(response['success'] && status == "success") {
                        $("#add-to-order p.status").hide().html(response['message']).show("fast");
                        // if product was configured 
                        if (was_configured) {
                            product_config_add_additional_products(response['order_item_id']);
                        };
                    } else {
                        alert('Server error. Please try again.'); // Error
                    }
                }, "json");
            });
        
      }, "json");
    };
    
    return false;
  }

  $(".add-items-to-order-submit").live("click", function(e){
    //var form = $("#id_add_items_form");
    //if(form.find("select").val() == "BLANK"){
      // Syncronous call to process new order form first
      //form.submit();
    //}else{
      // Asyncronous call because we don't need any more user interaction
      //$.post(form.attr("action"), form.serialize(), function(response, status){
      //    if(response['success'] && status=="success"){
       //     $("#add-to-order p.status").hide().html(response['message']).show("fast");
        //  }else{
        //    alert('Server error. Please try again.'); // Error
        //  }
      //  }, "json");
    //}
    alert('Not implemeted because of product configuration');
    return false;
  });

  $(".order-detail").click(function(){
    var that = this;
    $.get(this.href, {}, function(response){
      $.modal(response, {
        onShow: function(dialog){
          var next = $(that).parents("tr").next();
          var has_next = next.size();
          var prev = $(that).parents("tr").prev();
          var has_prev = prev.size();
          next_nav_link = dialog.container.find(".next");
          prev_nav_link = dialog.container.find(".prev");
          if(has_next){
            next_nav_link.click(function(e){
              $.modal.close();
              next.find(".order-detail:first").click();
              return false;
            });
          }else{
            next_nav_link.remove();
          }
          if(has_prev){
            prev_nav_link.click(function(e){
              $.modal.close();
              prev.find(".order-detail:first").click();
              return false;
            });
          }else{
            prev_nav_link.remove();
          }
        }
      });
    });
    return false;
  });

  $(".errorlist").each(function(i){
    if(!i) $(this).next("p").find("input, textarea").select().focus();
    $(this).next("p").css("background", "pink");
  });
 
  $(".copy-order-details").live('click', function () {
    var copy_url = $(this).attr('href');
    $.post(copy_url, function (data) {
      document.location.href = '/shop/admin/#' + data;
      document.location.reload();
    });
    return false;
  });
  $(".copy-order-active").live('click', function () {
    var copy_url = $(this).attr('href');
    $.post(copy_url, function (data) {
      document.location.href = '/shop/order/' + data + '/activate/';
    });
    return false;
  });
});


function unlock_order(url) {
    $.get(url, {}, function(response) {
        if (response.ok) {
            window.location.reload();
        } else {
            alert(response['message']);
        };
    }, 'json');
};

(function(){

    var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);

    jQuery.event.special.focus = {
        setup: function() {
            var _self = this,
                handler = function(e) {
                    e = jQuery.event.fix(e);
                    e.type = 'focus';
                    if (_self === document) {
                        jQuery.event.handle.call(_self, e);
                    }
                };

            jQuery(this).data(uid1, handler);

            if (_self === document) {
                /* Must be live() */
                if (_self.addEventListener) {
                    _self.addEventListener('focus', handler, true);
                } else {
                    _self.attachEvent('onfocusin', handler);
                }
            } else {
                return false;
            }

        },
        teardown: function() {
            var handler = jQuery(this).data(uid1);
            if (this === document) {
                if (this.removeEventListener) {
                    this.removeEventListener('focus', handler, true);
                } else {
                    this.detachEvent('onfocusin', handler);
                }
            }
        }
    };

    jQuery.event.special.blur = {
        setup: function() {
            var _self = this,
                handler = function(e) {
                    e = jQuery.event.fix(e);
                    e.type = 'blur';
                    if (_self === document) {
                        jQuery.event.handle.call(_self, e);
                    }
                };

            jQuery(this).data(uid2, handler);

            if (_self === document) {
                /* Must be live() */
                if (_self.addEventListener) {
                    _self.addEventListener('blur', handler, true);
                } else {
                    _self.attachEvent('onfocusout', handler);
                }
            } else {
                return false;
            }

        },
        teardown: function() {
            var handler = jQuery(this).data(uid2);
            if (this === document) {
                if (this.removeEventListener) {
                    this.removeEventListener('blur', handler, true);
                } else {
                    this.detachEvent('onfocusout', handler);
                }
            }
        }
    };

})();

