function downloadFile(downloadPath) {
    var iFrame = document.createElement('iFrame');
    iFrame.src = downloadPath;
    iFrame.style.display = 'none';
    document.body.appendChild(iFrame);
}


function handleSponsor(request, pledgePath) {
  if ( request.status == 200 ) {
    dialog.destroy();
  } else
    document.forms.popSponsor.submit();
}

var dialog = null;
function submitPopSponsor(pledgePath) {
  new Ajax.Updater({success: 'content', failure: 'content'},
    pledgePath, {asynchronous:true, evalScripts:true, 
      onSuccess: function(request){handleSponsor(request, pledgePath)},
      onFailure: function(request){handleSponsor(request, pledgePath)},
      parameters:Form.serialize(document.forms.popSponsor)});
}

function remindMe(downloadPath, pledgePath) {
 $('spinner').show();
  downloadFile(downloadPath);
  document.forms.popSponsor.reminder.value='1';
  submitPopSponsor(pledgePath);
}

function pledge(downloadPath, pledgePath) {
  var amount = parseFloat(document.forms.popSponsor.pledge_amount.value);
  if ( document.forms.popSponsor.pledge_amount.value == '' ||
      isNaN(amount) || amount <= 0 ) {
      $('pledgeError').show();
      new Effect.Highlight('pledgeError');
    return;
  }
  $('spinner').show();
  downloadFile(downloadPath);
  submitPopSponsor(pledgePath);
}

function openSponsorDialog(pledge_window_url, downloadPath, pledgePath, pushy, external) {
  var buttons = new Array();
  var n = 0;

  if ( ! external )
    buttons[n++] = {title: 'Sponsor', className: 'ok', 
      callback: function(win) { pledge(downloadPath, pledgePath); }};

  if ( pushy && !external ) {
    buttons[n++] = {title: 'Remind me Later', className: 'remind', 
      callback: function(win) { remindMe(downloadPath, pledgePath); }};
  }
  buttons[n++] = {title: 'No', className: 'cancel', 
    callback: function(win) { win.destroy(); downloadFile(downloadPath) }};

  var title= "Sponsorship: Name your price";
  if ( external )
    title= "Sponsorship: External Link";
  dialog = new UI.Dialog({buttons: buttons,
    shadow: true,
    width: 400,
    height: 330}).setHeader(title).setContent(
      '<center><img src="/images/spinner.gif"/></center>'
      ).setAjaxContent(pledge_window_url).setZIndex(100).show(true).center();
}

function external_sponsor(downloadPath) {
    downloadFile(downloadPath);
    dialog.destroy();
    return true;
}
