$(function() {
  
  // Windows
  $.fn.qtip.styles.phoneboothWindow = {
     title: {
       fontSize: '150%',
       fontWeight: 'normal',
       background: 'white',
       padding: '20px 25px 6px 25px'
     },
     padding: '0 25px 20px',
     border: {
       width: 6,
       radius: 6
     },
     tip: false,
     name: 'phonebooth'
  };
  
  // Buy Window
  $('#buy_form').submit(function() {
    // Set configurator URL in correct form field before submit
    $('#widget_url', this).val(window.location);
    
    // Set URL to redirect to upon success
    var root_url = $.url.attr('protocol') + '://' + $.url.attr('host');
    if ($.url.attr('port') != null) root_url += ':' + $.url.attr('port');
    $('#FormSubmitRedirectURL', this).val(root_url + '/configurator/buy_thanks');
  });
  $('a.buy').qtip({
    content: {
      title: {
        text: 'Ready to Talk?',
        button: 'Close'
      },
      text: ''
    },
    position: {
      target: $(document.body), // Position it via the document body...
      corner: 'center' // ...at the center of the viewport
    },
    show: {
      when: 'click', // Show it on click
      solo: true // And hide all other tooltips
    },
    hide: { when: 'unfocus' },
    style: {
     width: 550,
     name: 'phoneboothWindow'
    },
    api: {
      beforeShow: function() {
        // Fade in the modal "blanket" using the defined show speed
        $('#qtip-blanket').fadeIn(this.options.show.effect.length);
        $('#buy_form .activity').hide(); // hide spinner
        $('#buy_form button').attr('disabled', false); // enable submit button
      },
      onContentUpdate: function() {
        // Insert the form
        this.elements.content.append($('form.buy:first'));
      },
      onShow: function() {
        $('form.buy:first input.textbox:first').focus();
      },
      beforeHide: function() {
        // Fade out the modal "blanket" using the defined hide speed
        $('#qtip-blanket').fadeOut(this.options.hide.effect.length);
      }
    }
  });
  
// This code can be found in the buy_form snippet in Radiant
/* $('#buy_form').validate({
    groups: {
      name: "FirstName LastName",
      city_zip: "City PostalCode"
    },
    rules: {
      'FirstName'   : 'required',
      'LastName'    : 'required',
      'Phone'       : 'required',
      'Company'     : 'required',
      'Street'      : 'required',
      'City'        : 'required',
      'PostalCode'  : 'required',
      'Email': {
        required: true,
        email: true
      }
    },
    messages: {
      'FirstName'   : 'Your full name is required.',
      'LastName'    : 'Your full name is required.',
      'Phone'       : 'Your phone number is required.',
      'Company'     : 'Your company name is required.',
      'Street'      : 'Your street address is required.',
      'City'        : 'Your city, state, and zip are required.',
      'PostalCode'  : 'Your city, state, and zip are required.',
      'Email': {
        required: 'Your e-mail address is required.',
        email: 'Please enter a valid e-mail address.'
      }
    },
    errorPlacement: function(error, element) {
      if (element.attr("name") == "FirstName" || element.attr("name") == "LastName") {
        error.insertAfter("#LastName");
      } else if (element.attr("name") == "City" || element.attr("name") == "PostalCode") {
        error.insertAfter("#PostalCode");
      } else {
        error.insertAfter(element);
      }
    },
    submitHandler: function(form) {
      $('.activity', form).show(); // show spinner
      $('button', form).attr('disabled', true); // disable submit button
      form.submit();
    }
  });*/
  
  // Save or Share
  $('a.save').qtip({
    content: {
      title: {
        text: 'Save or Share Configuration',
        button: 'Close'
      },
      text: ''
    },
    position: {
      target: $(document.body), // Position it via the document body...
      corner: 'center' // ...at the center of the viewport
    },
    show: {
      when: 'click', // Show it on click
      solo: true // And hide all other tooltips
    },
    hide: { when: 'unfocus' },
    style: {
      width: 550,
      name: 'phoneboothWindow'
    },
    api: {
      beforeShow: function() {
        // Fade in the modal "blanket" using the defined show speed
        $('#qtip-blanket').fadeIn(this.options.show.effect.length);
        $('#save_thanks').hide(); // hide confirmation message
        $('#save_form .activity').hide(); // hide spinner
        $('#save_form button').attr('disabled', false); // enable submit button
        $('#save_form').show(); // show form
        this.updatePosition(); // reposition qtip
      },
      onContentUpdate: function() {
        // Insert the form
        this.elements.content.append($('#save_dialog'));
      },
      onShow: function() {
        $('#save_dialog input.textbox:first').focus();
      },
      beforeHide: function() {
        // Fade out the modal "blanket" using the defined hide speed
        $('#qtip-blanket').fadeOut(this.options.hide.effect.length);
      }
    }
  });
  
  $('.add_another_email').click(function() {
    var context = ('#save_form');
    var num = parseInt($('#num_friends', context).val()) + 1;
    var html = $('#friend_field_template', context).html().replace('{{x}}', num);
    $('#friend_fields', context).append(html);
    $('#num_friends', context).val(num);
  });
  
  $('#save_form').validate({
    rules: {
      email: {
        required: true,
        email: true
      },
      'friends[]': {
        required: false,
        email: true
      }
    },
    submitHandler: function(form) {
      $('.activity', form).show(); // show spinner
      $('button', form).attr('disabled', true); // disable submit button
      $('#configurator_url', form).val(window.location); // set config URL in form field
      
      $.post('/configurator/share', $(form).serialize(), function(json) {
        if (json['success'] == true) {
          $('#save_form').hide(); // hide form
          $('#save_thanks').show(); // show confirmation message
          $('a.save').qtip('api').updatePosition(); // reposition qtip
        } else {
          // an error occurred so fail gracefully
          $('button', form).attr('disabled', false); // enable submit button
          $('.activity', form).hide(); // hide spinner
        }
      }, 'json');
    }
  });
  
  // Tweet
  $('#tweet_form').submit(function() {
    $('input', this).val('I just configured a cloud phone system to save ' + Configurator.savings +
      '% over a PBX. Check out the configurator at http://phonebooth.net');
    $('a.tweet').qtip('api').hide();
  });
  $('a.tweet').qtip({
    content: {
      title: {
        text: 'Tweet your savings - and Win!',
        button: 'Close'
      },
      text: ''
    },
    position: {
      target: $(document.body), // Position it via the document body...
      corner: 'center' // ...at the center of the viewport
    },
    show: {
      when: 'click', // Show it on click
      solo: true // And hide all other tooltips
    },
    hide: { when: 'unfocus' },
    style: { 
     width: 500,
     name: 'phoneboothWindow'
    },
    api: {
      beforeShow: function() {
        // Fade in the modal "blanket" using the defined show speed
        $('#qtip-blanket').fadeIn(this.options.show.effect.length);
      },
      onContentUpdate: function() {
        // Insert the form
        this.elements.content.append($('form.tweet:first'));
      },
      beforeHide: function() {
        // Fade out the modal "blanket" using the defined hide speed
        $('#qtip-blanket').fadeOut(this.options.hide.effect.length);
      }
    }
  });
  
  $('a.print').click(function() {
    window.print();
  });
  
  // Create the modal backdrop on document load so all modal tooltips can use it
  $('<div id="qtip-blanket">')
    .css({
      position: 'absolute',
      top: $(document).scrollTop(), // Use document scrollTop so it's on-screen even if the window is scrolled
      left: 0,
      height: $(document).height(), // Span the full document height...
      width: '100%', // ...and full width
      opacity: 0.7, // Make it slightly transparent
      backgroundColor: 'black',
      zIndex: 5000  // Make sure the zIndex is below 6000 to keep it below tooltips!
    })
    .appendTo(document.body) // Append to the document body
    .hide(); // Hide it initially
  
});