
// Set external links to open in a new window
$(document).ready(function() {
    // Hook external links
    $('a').each(function() {
        if ( (this.href.indexOf('://' + window.location.hostname) < 0 || this.rel == 'external') && this.href.indexOf('javascript:') < 0) {
            this.target = '_blank';
            $(this).addClass('external');
        }
    });
    
    // jQuery is a bit promiscuous and tries to convert any
    // li>a inside the tab container into a tab.
    // It can't mangle what it can't see...
    $('.node .tabs').each(function() {
        var $this = $(this);
        var $panels = $this.children('div');
        var panelContents = [];
        for ( var i = 0; i < $panels.length; ++i ) {
            panelContents[i] = $($panels[i]).contents().remove();
        }
        $this.tabs();
        for ( var i = 0; i < $panels.length; ++i ) {
            $($panels[i]).append(panelContents[i]);
        }
    });
    
    // Hook the ask the experts form
    if ( $('#webform-client-form-16').length > 0 ) {
        form = $('#webform-client-form-16')[0];
        form.ajaxsubmitOnComplete = function(data) {
            //console.debug(data);
            //var errors = $(this.form).find('.ajaxsubmit-message .error li').length;
            if ( !data.errors ) {
                $(this.form).find('#edit-submitted-question').attr('value', '');
                
                try {
                    pageTracker._trackPageview(Drupal.settings.jstools.basePath + 'ask-a-specialist/thank-you');
                } catch ( ex ) {}
            }
        };
        
        form.validate = function() {
            this['op'].disabled = false;
            if ( !this['submitted[name]'].value || !this['submitted[name]'].value.match(/^\w+\s\w+$/) ) {
                this['op'].disabled = true;
            }
            if ( !this['submitted[email]'].value || !this['submitted[email]'].value.match(/^[^\s]+@[^\s]+$/) ) {
                this['op'].disabled = true;
            }
            if ( !this['submitted[question]'].value || this['submitted[question]'].value.length < 15 ) {
                this['op'].disabled = true;
            }
        };
        
        setInterval(function() { form.validate(); }, 250);
    }
    
    // Hook links to the contact form
    $('body').append('<div id="contact-dialog"></div>');
    $('a[href$=/contact-us]').click(function() {
        // set the conversion page cookie
        $.cookie('lead_conversion_page', window.location.href);
        
        // open the form in a dialog
        $dlg = $('#contact-dialog');
        $dlg.html('<iframe src="' + this.href + '?iframe=1" height="99%" width="100%" frameborder="0" scrolling="auto" marginheight="0" marginwidth="0"></iframe>');
        $dlg.dialog({
            modal: true,
            autoOpen: true,
            title: '&nbsp;',
            height: 500,
            width: 520,
            draggable: true,
            resizable: false,
            overlay: {
                opacity: 0.5,
                background: '#000000'
            },
            bgiframe: true,
            close: function(event, ui) {
                $iframe = $('#contact-dialog iframe');
                if ( $iframe.length ) {
                    // submit the form if they're on the second page
                    if ( $('input#edit-submit', $iframe[0].contentDocument).length ) {
                        $form = $('form', $iframe[0].contentDocument);
                        $form.append('<input type="hidden" name="op" value="Submit"/>');
                        $form.submit();
                    }
                }
            }
        });
        return false;
    });
    
    // fix links if we're in an iframe
    $('body.in-iframe a').click(function() {
        if ( !this.target ) {
            window.top.location.href = this.href;
            return false;
        }
    });
    
    // TODO set these, where do they come from?
    //$.cookie('lead_media_source', '');
    //$.cookie('lead_search_terms_used', '');
    
    // we've got some tabs that can make the main content area change height,
    // which messes up the nifty columns spacer elements
    // this code watches the main content height and resets nifty columns
    // if it changes
    var contentHeight = 0;
    setInterval(function() {
        if ( $('#main-content').height() != contentHeight ) {
            contentHeight = $('#main-content').height();
            nfusion.updateNifty();
        }
    }, 250);
});

nfusion.updateNifty = function() {
    // remove old nifty stuff
    $('.niftyfill').remove();
    
    // build nifty stuff
    Nifty("div#sub-page-wrapper,div#sidebar-left","none same-height");
};

// =============================================================================
// Customize the ajaxsubmit behavior
// =============================================================================

/**
 * Handler for the form redirection submission.
 */
Drupal.ajaxsubmit.prototype.onsubmit = function () {
  // Remove any error messages.
  var form = this.form;
  for (var i = 0; elt = form.elements[i]; i++) {
    $(elt).removeClass('error');
  }
  $(this.target).html('');
  // Insert progressbar.
  if (form.ajaxsubmit_progress) {

    // Success: redirect to the summary.
    var submitCallback = function (progress, status, pb) {
      if (progress == 100) {
        pb.stopMonitoring();
        window.location = '';
      }
    }

    // Failure: point out error message and provide link to the summary.
    var errorCallback = function (pb) {
      var div = document.createElement('p');
      $(div)
        .addClass('error')
        .html('An unrecoverable error has occured. You can find the error message below.');
      $('#progress').children(0).before(div);
      $('#wait').css('display', 'none');
 
    }
    this.progress = new Drupal.progressBar('updateprogress', submitCallback, HTTPPost, errorCallback);
    this.progress.startMonitoring(Drupal.url(form.ajaxsubmit_progress.value, 'form_id=' + form.form_id.value), 0);
  }
  else {
    this.progress = new Drupal.progressBar('ajaxsubmitprogress');
  }
  this.progress.setProgress(-1, 'Submitting Form');
  //this.progress.element.style.width = '28em';
  //this.progress.element.style.height = '200px';
  $(this.target).append(this.progress.element);
};

/**
 * Handler for the form redirection completion.
 */
Drupal.ajaxsubmit.prototype.oncomplete = function (data) {
  // Remove progressbar
  $(this.progress.element).remove();
  this.progress = null;
  $(this.target).html(data['message']);
  if (data['errors']) {
    for (id in data['errors']) {
      // edit[foo][bar] -> foo-bar
      $('#edit-' + id.replace('][', '-').replace('_', '-')).addClass('error');
    }
  }
  // Set preview.
  if (data['preview']) {
    $(this.target).html($(this.target).html() + data['preview']);
  }
  // Redirect.
  if (data['destination']) {
    window.location = Drupal.url(data['destination']);
  }
  //Drupal.scrollTo(this.target);
  Drupal.attachBehaviors(this.target);
  
  // form-specific callbacks
  if ( this.form.ajaxsubmitOnComplete ) {
      this.form.ajaxsubmitOnComplete.call(this, data);
  }
};

/**
 * Handler for the form redirection error.
 */
Drupal.ajaxsubmit.prototype.onerror = function (error) {
  // Remove progressbar
  $(this.progress.element).remove();
  this.progress = null;
  // Go to a designated error page, if any.
  var form = this.form;
  console.debug(error);
  $(this.target).html(form.ajaxsubmit_error_message ? form.ajaxsubmit_error_message.value : 'An error occurred:<br /><br />'+ error);
  if (form.ajaxsubmit_error_redirect) {
    window.location.href = form.ajaxsubmit_error_redirect.value;
  }
};

