Jaml.register('order_confirmation', function(container) {
  div({id: 'order_confirmation_wrap_' + container.order.restaurant.data._id},
    div(Jaml.render('order_summary', container)),
    div(Jaml.render('signup_login', container)),
    div({cls: 'clear'})
  );
});

Jaml.register('signup_login', function(container) {
  if(container.user && container.user.data && container.user.data.success) {
    div(Jaml.render('logged_in_customer_details', container));
    div(Jaml.render('billing_details', container.order));
  } else {
    var e = (container && container.user && container.user.data && container.user.data.email) ? container.user.data.email : '';
    form({name: 'login', cls: 'signup_login', method: 'get', action: ''},
      h3(span("2"), "Sign in"),
      h4("What is your email address?"),
      div({cls: 'email_wrap'}, 
        label(
          "My email address is: ",
          input({type: 'email', name: 'email', cls: 'email', value: e})
        )
      ),
      h4("Do you have an e-resistible.co.uk password?"),
      div({cls: 'have_password'}, 
        label(
          input({type: 'radio', name: 'have_password', value: 'new', checked: 'checked'}),
          "No, I am a new customer"
        )
      ),
      div({cls: 'have_password'}, 
        label(
          input({type: 'radio', name: 'have_password', value: 'old'}),
          "Yes, I have a password: "
        ),
        input({type: 'password', name: 'password', cls: 'password', disabled: 'disabled'})
      ),
      div({cls: 'signup_login_error', style: 'display: none;'}),
      input({type: 'submit', cls: 'sign_in_sec sign_in_secure', value: 'Sign in using our secure server'}),
      a({cls: 'forgot_pass', href: '#'}, "Forgot your password? Click here")
    );
  }
});

Jaml.register('forgot_pass', function(container) {
  var e = (container && container.user && container.user.data && container.user.data.email) ? container.user.data.email : '';
  form({name: 'signup', cls: 'signup_login', method: 'get', action: ''},
    h3(span("2"), "Send password reminder"),
    h4("What is your email address?"),
    div({cls: 'email_wrap'}, 
      label(
        "My email address is: ",
        input({type: 'email', name: 'forgot_pass_email', cls: 'email', value: e})
      )
    ),
    div({cls: 'signup_login_error', style: 'display: none;'}),
    a({cls: 'sign_in_sec send_pass_reminder', href: '#'}, "Email me a password reminder"),
    " or ",
    a({cls: 'signup_to_login', href: '#'}, "go back to login screen")
  );
});

Jaml.register('forgot_pass_thanks', function(container) {
  var e = (container && container.user && container.user.data && container.user.data.email) ? container.user.data.email : '';
  div({cls: 'signup_login'},
    h3(span("2"), "Send password reminder"),
    h4("Your password has been sent"),
    div({cls: 'email_wrap'}, "Your password has been sent to " + e + "."),
    div({cls: 'email_wrap', style: 'margin-top: 10px;'}, 
      "Please check your email, then ",
      a({cls: 'signup_to_login', href: '#'}, "go back to the login screen")
    )
  );
});

Jaml.register('signup', function(container) {
  form({name: 'signup', cls: 'signup_login'},
    h3(span("2"), "Register for e-resistible.co.uk"),
    div({cls: 'row'}, 
      label("First Name: "),
      input({type: 'text', name: 'first_name'})
    ),
    div({cls: 'row'}, 
      label("Last Name: "),
      input({type: 'text', name: 'last_name'})
    ),
    div({cls: 'row'}, 
      label("E-mail Address: "),
      input({type: 'email', name: 'email', value: container.user.data.email || ''})
    ),
    div({cls: 'row'}, 
      label("Re-enter E-mail Address: "),
      input({type: 'email', name: 'email_confirmation'})
    ),
    div({cls: 'row'}, 
      label("Choose a Password: "),
      input({type: 'password', name: 'password'})
    ),
    div({cls: 'row'}, 
      label("Re-enter Password: "),
      input({type: 'password', name: 'password_confirmation'})
    ),
    div({cls: 'signup_login_error', style: 'display: none;'}),
    input({type: 'submit', cls: 'sign_in_sec sign_up_secure', value: "Create a new account"}),
    " or ",
    a({cls: 'signup_to_login', href: '#'}, "go back to login screen")
  );
});

Jaml.register('logged_in_customer_details', function(container){
  var user = container.user;
  var order = container.order;
  
  var logged_in = (user.data && user.data.success);
  var address = (logged_in && user.data.addresses) ? user.data.addresses[0] : {};
  
  if(!order.data.customer_name && user.data.first_name) order.data.customer_name = user.customer_name();
  if(!order.data.phone) order.data.phone = user.data.phone;
  if(user.data.addresses && user.data.addresses[0]) {
    if(!order.data.address_1) order.data.address_1 = user.data.addresses[0].address_1;
    if(!order.data.address_2) order.data.address_2 = user.data.addresses[0].address_2;
    if(!order.data.town) order.data.town = user.data.addresses[0].town;
    if(!order.data.postcode) order.data.postcode = user.data.addresses[0].postcode;
  }
  
  var deliv_chk_fields = {type: 'radio', name: 'method', value: 'deliver', cls: 'delivery_method'};
  if(order.for_delivery()) deliv_chk_fields.checked = 'checked';
  var colec_chk_fields = {type: 'radio', name: 'method', value: 'collect', cls: 'delivery_method'};
  if(!order.for_delivery()) colec_chk_fields.checked = 'checked';
  
  div({cls: 'customer_details'},
    h3(span("2"), "Delivery or Collection?"),
    div({cls: 'row_method'}, 
      label(
        input(deliv_chk_fields), "Deliver"
      ),
      span({cls: 'for_delivery', style: order.for_delivery() ? '' : 'display: none;'},
        " at ",
        select({id:'select-' + order.restaurant.data._id, name: 'requested_deliv_time'},
          Jaml.render('delivery_time_options', {restaurant: order.restaurant, interval: 15})
        )
      )
    ),
    order.restaurant.data.allows_collections ? div({cls: 'row_method'}, 
      label(input(colec_chk_fields), "I will collect"),
      span({cls: 'for_collection', style: order.for_delivery() ? 'display: none;' : ''},
        " at",
        select({id:'select-' + order.restaurant.data._id, name: 'requested_colec_time'},
          Jaml.render('delivery_time_options', {restaurant: order.restaurant, interval: 10})
        )
      )
    ) : '',
    div({cls: 'row_col customer_name_phone'},
      (order.data.customer_name && order.data.phone) ? Jaml.render('customer_name_phone', order) : Jaml.render('customer_name_phone_edit', order)
    ),
    div({cls: 'customer_address', id: 'delivery_address_' + order.restaurant.data._id, style: order.for_delivery() ? '' : 'display: none;'},
      (order.data.address_1 && order.data.town && order.data.postcode) ? Jaml.render('customer_address', order) : Jaml.render('customer_address_edit', order)
    ),
    Jaml.render('delivery_instructions')
  )
});

Jaml.register('customer_name_phone', function(order){
  div({cls: 'sm_row'}, span({cls: 'lft'}, "Full Name "), order.data.customer_name);
  div({cls: 'sm_row'}, 
    span({cls: 'lft'}, "Mobile # "), order.data.phone || '&nbsp;',
    a({href:'#', cls: 'edit_user_details'}, 'edit')
  )
});

Jaml.register('customer_name_phone_edit', function(order){
  div({cls: 'row'},
    label("Full Name"),
    input({type: 'text', cls: 'txt customer_name', name: 'customer_name', value: order.data.customer_name || ''})
  );
  div({cls: 'row'},
    label("Mobile #"),
    input({type: 'tel', cls: 'txt customer_phone', name: 'phone', value: order.data.phone || ''})
  )    
});

Jaml.register('customer_address', function(order){
  if(order.data.address_1) div({cls: 'sm_row'}, span({cls: 'lft'}, "Deliver to:"),  order.data.address_1 || '&nbsp;');
  if(order.data.address_2) div({cls: 'sm_row'}, span({cls: 'lft'}, "&nbsp;"),  order.data.address_2 || '&nbsp;');
  if(order.data.town) div({cls: 'sm_row'}, span({cls: 'lft'}, "&nbsp;"),  order.data.town || '');
  if(order.data.postcode) div({cls: 'sm_row'}, span({cls: 'lft'}, "&nbsp;"), order.data.postcode, a({href:'#', cls: 'edit_user_address'}, 'edit'));
});

Jaml.register('customer_address_edit', function(order){

  div({cls: 'row'},
    label("Address"),
    input({type: 'text', cls: 'txt address_1', name: 'address_1', value: order.data.address_1 || ''})
  );
  div({cls: 'row'},
    label("&nbsp;"),
    input({type: 'text', cls: 'txt address_2', name: 'address_2', value: order.data.address_2 || ''})
  );
  div({cls: 'row'},
    label("Town"),
    input({type: 'text', cls: 'txt address_2', name: 'town', value: order.data.town || ''})
  );
  div({cls: 'row'},
    label("Postcode"),
    input({type: 'text', cls: 'txt postcode', name: 'postcode', value: order.data.postcode || ''})
  );

})

Jaml.register('order_method', function(order){
  div({cls: 'method'},
    // only show deliver method if allowed
    (function() {
      if (order.restaurant.data.can_deliver) {
        var chk_atr = {type: 'radio', name: 'method', value: 'deliver', cls: 'delivery_method'};
        if(order.for_delivery()) chk_atr.checked = "checked";
        return label({cls: 'deliver'}, 
          input(chk_atr), "Deliver"
        );
      };
    })(),
    
    // only show "or" if both deliveries and collections are allowed
    (order.restaurant.data.allows_collections && order.restaurant.data.can_deliver) ? "or" : "",
    
    // only show collection method if allowed
    (function() {
      if (order.restaurant.data.allows_collections) {
        var chk_atr = {type: 'radio', name: 'method', value: 'collect', cls: 'delivery_method'};
        if(!order.for_delivery()) chk_atr.checked = "checked";
        return label({cls: 'collect'}, 
          input(chk_atr), "I will collect"
        );
      };
    })()
  )
});

Jaml.register('delivery_time_options', function(data) {
  _.each(data.restaurant.opening_times(data.interval), function(date) {
    option({value: date}, date);
  });
})

Jaml.register('delivery_instructions', function(){
  div({cls: 'row'},
    "Extra delivery instructions",
    textarea({cls: 'delivery_instructions', name: 'delivery_instructions'})
  );
});

Jaml.register('card_fields', function(order) {
  var payment_type_cash_chk = {type: 'radio', name: 'payment_type', value: 'cash'};
  if(order.data.payment_type == 'cash') payment_type_cash_chk.checked = 'checked';
  var payment_type_card_chk = {type: 'radio', name: 'payment_type', value: 'card'};
  if(order.data.payment_type == 'card') payment_type_card_chk.checked = 'checked';
  var payment_type_rept_chk = {type: 'radio', name: 'payment_type', value: 'card'};
  if(order.data.payment_type == 'repeat') payment_type_rept_chk.checked = 'checked';
  
  // div({cls: 'row', style: 'font-weight: bold; color: red;'},
  //   "CARD PAYMENTS CURRENTLY OFFLINE"
  // );
  
  if(order.restaurant.data.accepts_cash) {
    div({cls: 'row payment_type pay_with_cash'}, label(input(payment_type_cash_chk), "Pay cash on delivery"));    
  }
  
  if(order.restaurant.data.accepts_card) {
    if(order.data.repeat_card) {
      div({cls: 'row payment_type pay_with_repeat'}, label(input(payment_type_rept_chk), "Pay with " + order.data.repeat_card.card))
      div({cls: 'row payment_type pay_with_card'}, label(input(payment_type_card_chk), "Pay with another card"))
    } else {
      div({cls: 'row payment_type pay_with_card'}, label(input(payment_type_card_chk), "Pay with a credit / debit card"))
    }
    div({cls: 'card_fields', style: order.data.payment_type == 'card' ? '' : 'display: none'},  
    
      div({cls: 'row'},
        label("Type"),
        select({name: 'card_type'},
          option("VISA"),
          option("MasterCard"),
          option("Switch"),
          option("Maestro"),
          option("Solo")
        )
      ),
      div({cls: 'row'},
        label("Card #"),
        input({type: 'text', cls: 'txt card_number', name: 'card_number', autocomplete: 'off'})
      ),
      div({cls: 'row card_start', style: 'display: none'},
        label("Start"),
        select({name: 'card_start_month'},
          option({value: '01'}, "1 - Jan"),
          option({value: '02'}, "2 - Feb"),
          option({value: '03'}, "3 - Mar"),
          option({value: '04'}, "4 - Apr"),
          option({value: '05'}, "5 - May"),
          option({value: '06'}, "6 - Jun"),
          option({value: '07'}, "7 - Jul"),
          option({value: '08'}, "8 - Aug"),
          option({value: '09'}, "9 - Sep"),
          option({value: '10'}, "10 - Oct"),
          option({value: '11'}, "11 - Nov"),
          option({value: '12'}, "12 - Dec")
        ),
        select({name: 'card_start_year'},
          option({value: '04'}, "2004"),
          option({value: '05'}, "2005"),
          option({value: '06'}, "2006"),
          option({value: '07'}, "2007"),
          option({value: '08'}, "2008"),
          option({value: '09'}, "2009"),
          option({value: '10'}, "2010")
        )
      ),
      div({cls: 'row'},
        label("Expires"),
        select({name: 'card_expires_month'},
          option({value: '01'}, "1 - Jan"),
          option({value: '02'}, "2 - Feb"),
          option({value: '03'}, "3 - Mar"),
          option({value: '04'}, "4 - Apr"),
          option({value: '05'}, "5 - May"),
          option({value: '06'}, "6 - Jun"),
          option({value: '07'}, "7 - Jul"),
          option({value: '08'}, "8 - Aug"),
          option({value: '09'}, "9 - Sep"),
          option({value: '10'}, "10 - Oct"),
          option({value: '11'}, "11 - Nov"),
          option({value: '12'}, "12 - Dec")
        ),
        select({name: 'card_expires_year'},
          option({value: '10'}, "2010"),
          option({value: '11'}, "2011"),
          option({value: '12'}, "2012"),
          option({value: '13'}, "2013"),
          option({value: '14'}, "2014"),
          option({value: '15'}, "2015"),
          option({value: '16'}, "2016"),
          option({value: '17'}, "2017"),
          option({value: '18'}, "2018"),
          option({value: '19'}, "2019"),
          option({value: '20'}, "2020")
        )
      ),
      div({cls: 'row'},
        label("CCV #"),
        input({type: 'text', cls: 'txt ccv', name: 'card_ccv', autocomplete: 'off'}),
        a({href: '#', cls: 'what_ccv'}, "What's this?")
      ),
      div({cls: 'ccv_help', id: 'ccv_help_' + order.restaurant.data._id, style: 'display:none'}, "CCV is the last 3 digits on the back of your card"),
      div({cls: 'row issue', style: 'display: none;'},
        label("Issue #"),
        input({type: 'text', cls: 'txt ccv', name: 'issue', autocomplete: 'off'})
      ),
      div({cls: 'row card_addr_same', id: 'billing_address_' + order.restaurant.data._id + '_lnk'},
        "My card and delivery address are the same",
        input({type: 'checkbox', name: 'billing_delivery_same', id: 'delivery_address_checkbox_' + order.restaurant.data._id, cls: 'diff_billing_address', checked: 'checked'})
      ),
      div({cls: 'billing_address', id: 'billing_address_' + order.restaurant.data._id, style: 'display:none'},
        div({cls: 'sep'},
          span("Enter your billing / card address")
        ),
        div({cls: 'row'},
          label("Address"),
          input({type: 'text', cls: 'txt', name: 'bill_address_1'})
        ),
        div({cls: 'row'},
          label("Town"),
          input({type: 'text', cls: 'txt', name: 'bill_town'})
        ),
        div({cls: 'row'},
          label("Postcode"),
          input({type: 'text', cls: 'txt postcode', name: 'bill_postcode'})
        )    
      )
    );
  
    div({cls: 'row card_addr_same note_card_fee', style: order.pay_online() ? '' : 'display: none'},
      "<b>Please note</b>: 50p card fee"
    );
  }
})

Jaml.register('billing_details', function(order) {

  div({cls: 'billing_details'},
    h3(span("3"), "Billing information - SECURE"),
    Jaml.render('card_fields', order),

    div({cls: 'order_errors', style: 'display: none'}),
    a({cls: 'confirm_order', href: '#'}, 'Send Order to Restaurant'),
    div({cls: 'processing_order', style: 'display: none'}),
    div({cls: 'row security_logos'})
  );

});

Jaml.register('order_summary', function(container) {
  var order = container.order;
  var logged_in = container.user && container.user.data && container.user.data.success;
  
  div({cls: 'order_summary'},
    h3(span("1"), "Check your order"),
    div({cls: 'order_items'},
      Jaml.render('order_summary_item', order.order_items)
    ),
    div({cls: 'order_summary_totals'}, Jaml.render('order_summary_totals', order)),
    div({cls:'back_to_menu'}, a({href: "/" + container.order.data.restaurant_id}, "Back to menu")),
    div({style: logged_in ? '' : 'display: none'},
      div({cls:'right_links'}, a({href: '#', cls: 'special_instructions'}, "Add comments for the restaurant")),
      div({style: 'display: none', cls: 'special_instructions_wrap'},
        div({cls:'row txt_label'}, "Any comments for the restaurant?"),
        textarea({cls: 'txt comment', name: 'special_instructions', rows: '3'}, order.data.special_instructions || '')
      ),
      container.order.data.coupon_code ? '' : div({cls:'right_links'}, a({href: '#', cls: 'coupon_code_lnk'}, "Use a coupon code")),
      div({cls: 'coupon_code_wrap', style: container.order.data.coupon_code ? '' : 'display: none'},
        div({cls:'row txt_label'}, "Referrer or coupon code:"),
        div({cls: 'coupon_card_warning', style: container.order.pay_online() ? 'display: none;' : ''}, "Please note: you must pay by card for your coupon code to apply"),
        input({type: 'text', name: 'coupon_code', value: (order.data.coupon_code ? order.data.coupon_code : '')}),
        a({href:'#', cls: 'apply_coupon_code'}, 'Apply Code'),
        div({cls: 'err', style: order.data.discount_description ? '' : 'display: none;'}, order.data.discount_description || '')
      )    
    )
  );
});

Jaml.register('order_summary_totals', function(order){
  var rest_url = "/"+order.restaurant.data.food_type.toLowerCase().replace(/[^a-z]+/g, '-') + "-takeaway/" + order.restaurant.data.seo_town + "/" + order.restaurant_id
  
  div({cls: 'ar sub_total'}, span('Sub-total:'), "&pound;" + order.sub_total().toFixed(2));
  var deliv_fee = (order.delivery() == 0) ? 'FREE' : ("&pound;" + order.delivery().toFixed(2));
  div({cls: 'ar delivery_fee',style: order.for_delivery() ? '' : 'display: none;'}, span('Delivery:'), deliv_fee);    
  div({cls: 'ar discount', style: order.pay_online() ? '' : 'display: none;'}, span('Card fee:'), "&pound;" + order.card_fee().toFixed(2));    
  div({cls: 'ar card_fee', style: (order.total_discount() > 0) ? '' : 'display: none;'}, span('Discount:'), "&pound;-" + order.total_discount().toFixed(2));

  div(Jaml.render('order_summary_total', order));
});

Jaml.register('order_summary_total', function(order){ 
  div({cls: 'total'}, span('Total:'), "&pound;" + order.total().toFixed(2)); 
});

Jaml.register('order_summary_item', function(order_item){
  div({cls: 'item'},
    span({cls: 'price'}, "&pound;" + order_item.price().toFixed(2)),
    span({cls: 'title'}, ((order_item.data.quantity > 1 ? (order_item.data.quantity + " x ") : '') + order_item.data.title)),
    Jaml.render('order_summary_item_option', order_item.options)
  );
});

Jaml.register('order_summary_item_option', function(order_item_option){
  if(order_item_option.data.options) {
    var options = _.pluck(order_item_option.data.options, 'title').join(", ");
  } else {
    var options = order_item_option.data.title;
  };
  span({cls: 'extra'},
    (order_item_option.data.group == options) ? order_item_option.data.group : (order_item_option.data.group+": "+options)
  );
});

Jaml.register('under_err', function(str){
  div({cls: 'under_err', style: 'display: none'}, str);
});

Jaml.register('order_3d_frame', function(three_d_info) {
  iframe({id: 'three_d_frame', frameborder: '0', name: 'three_d_frame', scrolling: 'auto', style: 'width: 100%; height: 400px;', src: '/3d_loading'});
  form({method: 'POST', id: three_d_info.form_id, target: 'three_d_frame', action: three_d_info.ACSURL},
    input({type: 'hidden', name: 'PaReq', value: three_d_info.PaReq}),
    input({type: 'hidden', name: 'MD', value: three_d_info.MD}),
    input({type: 'hidden', name: 'TermUrl', value: three_d_info.TermURL})
  );
});

Jaml.register('order_thank_you', function(order){
  div({cls: 'order_thanks'},
    h1('You order to ' + order.data.restaurant + ' was a success!'),
    div('We have emailed a receipt to ' + order.data.email + '.'),
    div("Don't forget to switch on your mobile phone in case there's a problem!"),
    div({style: 'margin-top: 10px;'}, "If you would like to create a new order for this restaurant, "),
    a({href: '/'+order.data.restaurant_id+"?new_order=1"}, "click here")
  );
});

Jaml.register('order_thank_you_restaurant', function(order){
  div({cls: 'order_thanks'},
    h1('Thank you for confirming this order.'),
    div('An email has been sent to the customer informing them that their order is being processed.')
  );
});


Jaml.register('restaurant_closed', function(container) {
  div({id: 'order_confirmation_wrap_' + container.order.restaurant_id},
    div({cls: 'order_thanks'},
      h1('You order to ' + container.order.data.restaurant + ' could not be processed.'),
      div('Either the restaurant is closed, or it is unable to take orders at this time.')
    ),
    div({cls: 'clear'})
  );
  
});

Jaml.register('order_status', function(container) {
  div({id: 'order_confirmation_wrap_' + container.order.restaurant.data._id},
    div(Jaml.render('order_status_summary', container.order)),
    div(Jaml.render('order_thank_you', container.order)),
    div({cls: 'clear'})
  );
});

Jaml.register('order_confirmed_by_restaurant', function(container) {
  div({id: 'order_confirmation_wrap_' + container.order.restaurant.data._id},
    div(Jaml.render('order_status_summary', container.order)),
    div(Jaml.render('order_thank_you_restaurant', container.order)),
    div({cls: 'clear'})
  );
});


Jaml.register('order_status_summary', function(order) {
  order.skip_back_to_menu = true;

  var m = order.for_delivery() ? 'Please deliver ' : 'I will collect ';
  m = m + (order.data.requested_time.match(/asap/i) ? 'ASAP' : 'at ' + order.data.requested_time);

  div({cls: 'order_summary'},
    h3(span("1"), "Details of your order"),
    div({cls: 'detail'}, span('Name'), order.data.customer_name),
    div({cls: 'detail'}, span('Phone'), order.data.phone),
    div({cls: 'detail'}, span('Email'), order.data.email),
    div({cls: 'detail'}, m),
    div({cls: 'detail'}, order.data.payment_type.match(/card/i) ? 'I have paid online' : 'I will pay cash on delivery'),
    div({cls: 'order_items'},
      Jaml.render('order_summary_item', order.order_items)
    ),    
    Jaml.render('order_summary_totals', order)
  );
});

