var MY_AUTHOR_LAST = 'UNKNOWN';
var MY_AUTHOR_FIRST = 'UNKNOWN';
var SEP = '::';

// one browser sniff to account for a known bug
var sUserAgent = navigator.userAgent.toLowerCase();
var isOpera = (sUserAgent.indexOf('opera')!=-1)?true:false;

var DEFAULTPOP = 'width=725,height=450,menu=1,resizable=1,status=1,scrollbars=1,dependent=true';
var MP3POP = 'width=250,height=80,menu=0,resizable=1,status=1,scrollbars=1,dependent=true';

// Initialize the package, only call this for the popup
function init(last,first) {
  MY_AUTHOR_LAST = last;
  MY_AUTHOR_FIRST = first;
  if (window.opener) {
     setupChecksForAuthor(MY_AUTHOR_LAST + ' ' + MY_AUTHOR_FIRST);
  } else {
    directHit();
  }
}

// Rewrite some stuff on a speaker "popup" page
// when it gets a direct hit (i.e. from a search engine
function directHit() {
  if (! window.opener) {
    // hide all the checkboxes
    var checkboxen = document.getElementsByName("msg");
    if (checkboxen) {
       if (checkboxen.length) {
         for (var j=0; j<checkboxen.length; j++) {
           checkboxen[j].style.display = 'none';
         }
       } else {
         checkboxen.style.display = 'none';
       }
    }
    // Hide the toggle header checkbox
    var ta = document.getElementById('toggleAll');
    if (ta) {
        ta.style.display = 'none';
    }
    // Hide the close button cuz its not a popup
    var closer = document.getElementById('closer');
    if (closer) {
       closer.style.display = 'none';
    }
    // Turn on the navigation links
    var altnav = document.getElementById('altnav');
    if (altnav) {
       altnav.style.display = 'block';
    }
  }
}

// Initialize the package from the search results pop
function initSearchResults() {
  var ids = new Array();
  var checkboxen = document.getElementsByName("msg");
  if (checkboxen) {
    if (checkboxen.length) {
      for (var j=0; j<checkboxen.length; j++) {
	ids[j] = checkboxen[j].value;
      }
    } else {
      ids[0] = checkboxen.value;
    }
  }
  if (ids && ids.length) {
    setupChecks(ids);
  }
}

// Initialize the main window
function initMain() {
  removeAll();
}
      
// Pop up a list of messages by the author
// make new popup window
function pop(oAnchor,sWindow,sProps){

  // get URL from calling link oAnchor
  var sUrl = '';
  
  if(oAnchor.getAttribute) {
    sUrl = oAnchor.getAttribute('href');
  }
  if(sUrl=='') {
    sUrl = oAnchor.href;
  }

  // if still no URL, return true and let the regular link take over
  if(sUrl=='') return true;

  return popS(sUrl,sWindow,sProps);
}
 
function popS(sUrl, sWindow, sProps) {

  // set window name ('_blank' for new window each time)
  // Use author name by default
  var sWindowName = sWindow?sWindow:sUrl;
  
  // if no window properties are defined in the function
  // call's optional parameter 'sProps'
  if(!sProps) sProps = DEFAULTPOP;
  
  // assign the popup to this variable so we can verify it exists
  var oPopup;
  if(sUrl) {
    //alert("doing open on \n" + sUrl + ",\n" + sWindowName + ",\n" + sProps);
    oPopup = window.open(sUrl,sWindowName,sProps);
  }
  
  // An Opera bug returns too early if you focus the 
  // window, so we don't focus it in that browser.
  // Only a noticable defect if a window is already open and hidden.
  if(oPopup && !isOpera) oPopup.focus();
  
  // If popup was created successfully, cancel link in calling window.
  // Acts as regular link in browser that blocks requested
  // popups or has JavaScript turned off.
  return (oPopup)?false:true;
  
}

// Kick off the file download referenced
// in the specified <a> tag in an accessible
// degradable way
function getaudio(oAnchor) {
   return true;
}
function pop_getaudio(oAnchor) {
  
  // get URL from calling link oAnchor
  var sUrl = '';
  
  if(oAnchor.getAttribute) {
    sUrl = oAnchor.getAttribute('href');
  }
  if(sUrl=='') {
    sUrl = oAnchor.href;
  }

  // if still no URL, return true and let the regular link take over
  if(sUrl=='') {
    alert('Unable to download file');
    return false;
  }

   // assign the popup to this variable so we can verify it exists
  var oPopup = window.open('audiopop.html','MP3Download',MP3POP);
  
  // An Opera bug returns too early if you focus the 
  // window, so we don't focus it in that browser.
  // Only a noticable defect if a window is already open and hidden.
  if(oPopup && !isOpera) oPopup.focus();
  
  // Set url into audio popup and let it do its thing
  oPopup.fnslot = sUrl;
  oPopup.setTimeout('restuff("'+sUrl+'")',500);
  return false;
}

function removeAll() {
  var sel = document.getElementById("msgs");
  if (sel) {
    sel.options.length = 0;
  }
  updateVisible();
}


// Remove an array of messages from the order
function removeMessages(id) {
  var sel = document.getElementById("msgs");
  if (sel) {
    for (var i=0; i<id.length; i++) {
      var sz = sel.options.length;
      
      for (var j=0; j<sz; j++ ){ 
	if (sel.options[j].value == id[i]) {
	  sel.options[j].text = sel.options[sz-1].text;
	  sel.options[j].value = sel.options[sz-1].value;
	  sel.options.length = sz-1;
	  break;
	}
      }
    }
    updateVisible();
  }
}

// Remove a message from the order
function removeMessage(id) {
  var sel = document.getElementById("msgs");
  var sz = sel.options.length;
  if (sel) {
    for (var i=0; i<sz; i++ ){ 
      if (sel.options[i].value == id) {
	sel.options[i].text = sel.options[sz-1].text;
	sel.options[i].value = sel.options[sz-1].value;
	sel.options.length = sz-1;
	break;
      }
    }
    updateVisible();
  }
}

// Add an array of messges to the order
function addMessages(id,author,title) {
  var sel = document.getElementById("msgs");
  if (sel) {
    for (var i=0; i<id.length; i++) {
      var sz = sel.options.length;
      sel.options.length = sz + 1;
      sel.options[sz].value = id[i];
      sel.options[sz].text = id[i] + SEP + author[i] + SEP + title[i];
    }
    updateVisible();
  }
}

// Add a message to the order       
function addMessage(id, author, title) {
  var sel = document.getElementById("msgs");
  if (sel) {
    var sz = sel.options.length;
    sel.options.length = sz + 1;
    sel.options[sz].value = id;
    sel.options[sz].text = id + SEP + author + SEP + title;
    //sel.options.sort();
    updateVisible();
  }
}

// Update the user visible text of what is ordered
function updateVisible() {
  var sel = document.getElementById('msgs');
  var msg = "";
  if (sel) {
    for (var i=0; i<sel.options.length; i++) {
      sel.options[i].selected = true;
      msg += "   " + sel.options[i].text + "\n";
    }
  }
  msg = msg.replace(/::/g,'   ');

  if (msg == '') {
    msg = 'Nothing';
  } else {
    msg = '<pre>' + msg + '</pre>';
  }
  var el = document.getElementById('orderlist');
  if (el) {
    el.innerHTML = msg;
  } else {
    //alert("hmmm. no orderList");
  }

  updateCounters();
}

// Update message and disk counters
function updateCounters() {

  var sel = document.getElementById('msgs');
  var ctr = document.getElementById('counter');
  
  if (sel && ctr) {
    ctr.value = sel.options.length;
  }
}

// Reset field border from the error condition
// Not sure how to specify without repeating info
// from the css file
function resetBorder(fld) {
  fld.style.border = "1px solid #26a";
}


// Format and submit the message 
function submitOrder() {
  var f = document.getElementById('orderForm');

  if (!f) {
    alert("Hmmm. That did not work out too well. \n" +
	  "Sorry, but your browser seems incompatible \n" +
          "with our order system at the moment.");
    return;
  }

  if (f.name.value == '' || f.name.value.length < 4) {
    f.name.style.border = "1px solid red";
    alert('Please fill in your name.');
    return;
  }

  if (f.email.value == '' || f.email.value.indexOf('@') == -1 || f.email.value.length < 6) {
    f.email.style.border = "1px solid red";
    alert('Please fill in your email address.');
    return;
  }

  if (f.email.value.indexOf('@voicesforchrist.org') > -1) {
    f.email.style.border = "1px solid red";
    f.email.value = '';
    alert('Please fill in your email address.');
    return;
  }

  if (f.address1.value == '' ||
      f.address2.value == '' ||
      f.address3.value == '' ||
      f.address1.value.length < 4 ||
      f.address2.value.length < 2 ||
      f.address3.value.length < 2) {
    if (f.address1.value == '' || f.address1.value.length < 4)
       f.address1.style.border = "1px solid red";
    if (f.address2.value == '' || f.address2.value.length < 2)
       f.address2.style.border = "1px solid red";
    if (f.address3.value == '' || f.address4.value.length < 2)
       f.address3.style.border = "1px solid red";
    alert('We need your address in order to ship the media to you');
    return;
  }

  if (f.address1.value.indexOf('http://') > -1 ||
      f.address2.value.indexOf('http://') > -1 ||
      f.address3.value.indexOf('http://') > -1 ||
      f.address4.value.indexOf('http://') > -1 ||
      f.address5.value.indexOf('http://') > -1 ||
      f.email.value.indexOf('http://') > -1 ||
      f.name.value.indexOf('http://') > -1) {
      f.address1.value = '';
      f.address2.value = '';
      f.address3.value = '';
      f.address4.value = '';
      f.address5.value = '';
      f.name.value = '';
      f.email.value = '';
      removeAll();
      return;
  }

  if (f.address4.value == '' || f.address4.value.length < 2)
  {
    f.address4.style.border = "1px solid red";
    alert('We need the country in order to ship the media to you');
    return;
  }

  if ((f.address4.value == 'US' || f.address4.value == 'USA' || 
       f.address4.value == 'us' || f.address4.value == 'usa' || 
       f.address4.value == 'u.s.' || f.address4.value == 'u.s.a.' || 
       f.address4.value == 'U.S.' || f.address4.value == 'U.S.A.') &&
       f.address5.value == '' || f.address5.value.length < 5) {
    f.address5.style.border = "1px solid red";
    alert('We need the Zip Code for US addresses please');
    return;
  }
  
  if (f.counter.value == '' || f.counter.value == '0') {
    alert('You didnt select any messages');
    return;
  }

  var msg = document.getElementById('orderlist').innerHTML;
  msg = msg.replace(/<\/?pre>/img,'');
  msg = msg.replace(/<span class="?date"?>/img,' ');
  msg = msg.replace(/<span class="?searchword"?>/img,'');
  msg = msg.replace(/<\/span>/img,'');
  msg = msg.replace(/&nbsp;/img,'');
  f.details.value = msg;
  f.submit();

}

// Collect already ordered GROUP-ID numbers for 
// specified author for sending to the popup
// Input author name, return array of ids
function getSelectedFor(author) {
  var sel = document.getElementById('msgs');
  var msg = new Array();
  var i = 0;
  if (sel) {
    for (var i=0; i<sel.options.length; i++) {
      var txt = sel.options[i].text;
      if (txt.indexOf(SEP + author + SEP) > -1) {
	msg[i] = sel.options[i].value;
      }
    }
  }
  return msg;
}

// Collect already ordered GROUP-ID numbers for 
// specified list of message group numbers
// Send in array of ids, get back array of ids
function getSelectedOf(ids) {
  var sel = document.getElementById('msgs');
  var ordered = new Array();

  if (sel) {
    var jumble = SEP;
    for (var i=0; i<ids.length; i++) {
      jumble += ids[i] + SEP;
    }
    var j = 0;
    for (var i=0; i<sel.options.length; i++) {
      if (jumble.indexOf(SEP + sel.options[i].value + SEP) > -1) {
	ordered[j] = sel.options[i].value;
      }
    }
  }
  return ordered;
}


// Get the matching title for the specified checkbox
function getTitle(value) {
  var titleEl = document.getElementById('x' + value);
  if (! titleEl) {
    alert("No element for x" + value);
    return "";
  }
  return titleEl.innerHTML;
}
  

// Update the order 
// Called from the popup to send a 
// new check or uncheck to the main screen
function updateOrder(el) {
  var value = el.value;
  var title = getTitle(value);
  
  if (!window.opener) {
    return;
  }

  if (el.checked) {
    var fn = MY_AUTHOR_FIRST;
    var ln = MY_AUTHOR_LAST;
    // If search results author is in title: ln, fn - title
    if (ln == 'UNKNOWN') {
      var p1 = title.indexOf(',');
      var p2 = title.indexOf(' - ');
      ln = title.substring(0,p1);
      fn = title.substring(p1+2,p2);
      title = title.substring(p2+3);
    }
    window.opener.addMessage(value,ln+' '+fn,title);
  } else {
    window.opener.removeMessage(value);
  }
}

// Called in the pop-up to get enable already
// ordered checkboxes in the popup window
function setupChecksForAuthor(author) {
  if (! window.opener) {
    return;
  }
  var ids = window.opener.getSelectedFor(author);

  for (var i=0; i<ids.length; i++) {
    var el = document.getElementById(ids[i]);
    if (el) {
      el.checked = true;
    }
  }
}

// Called in the search pop-up to get enable already
// ordered checkboxes in the popup window
function setupChecks(availableids) {
  if (! window.opener) {
    return;
  }
  var ids = window.opener.getSelectedOf(availableids);

  for (var i=0; i<ids.length; i++) {
    var el = document.getElementById(ids[i]);
    if (el) {
      el.checked = true;
    }
  }
}

// Toggle all checks in popup
function toggleAllInWindow(el) {
  if (el.checked) {
    selectAll();
  } else {
    clearAll();
  }
}



// Pop up set all checks
function selectAll() {
  
  var ids = new Array();
  var authors = new Array();
  var titles = new Array();
  var idx = 0;

  var frm = document.getElementById('f');
  var f = frm.msg;
  if (f.length) {
    for (i=0; i<f.length; i++) {
      if (! f[i].checked) {
	f[i].checked = true;
	//updateOrder(f[i]);
	ids[idx] = f[i].value;
	var fn = MY_AUTHOR_FIRST;
	var ln = MY_AUTHOR_LAST;
	var title = getTitle(f[i].value);
	// If search results author is in title: ln, fn - title
	if (ln == 'UNKNOWN') {
	  var p1 = title.indexOf(',');
	  var p2 = title.indexOf(' - ');
	  ln = title.substring(0,p1);
	  fn = title.substring(p1+2,p2);
	  title = title.substring(p2+3);
	}
	authors[idx] = ln+' '+fn;
	titles[idx] = title;
	idx++;
      }
    }
  } else {
    // only one
    if (! f.checked) {
      f.checked = true;
      //updateOrder(f);
      ids[idx] = f.value;
	var fn = MY_AUTHOR_FIRST;
	var ln = MY_AUTHOR_LAST;
	var title = getTitle(f.value);
	// If search results author is in title: ln, fn - title
	if (ln == 'UNKNOWN') {
	  var p1 = title.indexOf(',');
	  var p2 = title.indexOf(' - ');
	  ln = title.substring(0,p1);
	  fn = title.substring(p1+2,p2);
	  title = title.substring(p2+3);
	}
	authors[idx] = ln+' '+fn;
	titles[idx] = title;
    }
  }
  
  if (window.opener) {
    window.opener.addMessages(ids,authors,titles);
  } else {
    alert("You have to disable your popup blocker for this site \n" +
          "to make the order form work properly. Please disable \n" +
          "it now and go back to the previous page.");
  }
}

// Pop up clear all checks
function clearAll() {
  var list = new Array();
  var idx = 0;
  var frm = document.getElementById('f');
  var f = frm.msg;
  if (f.length) {
    for (i=0; i<f.length; i++) {
      if (f[i].checked) {
	f[i].checked = false;
	list[idx++] = f[i].value;
      }
    }
  } else {
    // only one
    if (f.checked) {
      f.checked = false;
      list[idx++] = f.value;
      //updateOrder(f);
    }
  }

  if (window.opener) {
    window.opener.removeMessages(list);
  } else {
    alert("You have to disable your popup blocker for this site \n" +
          "to make the order form work properly. Please disable \n" +
          "it now and go back to the previous page.");
  }
}

// Load a BIO to the iframe in bios.html page
function loadBio(oAnchor) {
  var sUrl = '';
  
  if(oAnchor.getAttribute) {
    sUrl = oAnchor.getAttribute('href');
  }
  if(sUrl=='') {
    sUrl = oAnchor.href;
  }
  
  var spot = document.getElementById('bioFrame');
  if (spot) {
    spot.src = sUrl;
    return false;
  } else {
    return true;
  }
}

function advancedSearch(f,windowName) {
  var f1 = f.pv;
  var f2 = f.tv;
  var f3 = f.sv;
  var ok = 0;
  if (f1) ok += f1.value.length;
  if (f2) ok += f2.value.length;
  if (f3) ok += f3.value.length;
  if (ok == 0) {
     alert("Please fill in some search criteria first.");
    return false;
  }

  return search(f,windowName);
}

function show(divid) {
  var el = document.getElementById(divid);
  if (el) {
    el.style.display = 'block';
  }
}

function hide(divid) {
  var el = document.getElementById(divid);
  if (el) {
    el.style.display = 'none';
  }
}

function search(f,sWindowName) {
  
  var sProps = DEFAULTPOP;

  if ((! f) || (! f.q) || (!f.q.value) || (f.q.value == '')) {
    return false;
  }

   // assign the popup to this variable so we can verify it exists
  var oPopup = window.open('about:blank',sWindowName,sProps);
  
  // An Opera bug returns too early if you focus the 
  // window, so we don't focus it in that browser.
  // Only a noticable defect if a window is already open and hidden.
  if(oPopup && !isOpera) oPopup.focus();
  
  // Target form and submit
  if (oPopup) {
    f.target = oPopup.name;
  }
  return true;
}

// Attach the popup handler where desired
function doPopups() {
  if (!document.getElementsByTagName) return false;
  var links = document.getElementsByTagName("a");
  for (var i=0; i < links.length; i++) {
    if (links[i].className.match("popup")) {
      links[i].onclick = function() {
	var s = this.href.replace(/.*\/([^\/]+)\.html?$/,'$1');
        var opop = window.open(this.href,s,DEFAULTPOP);
        if(opop && !isOpera) opop.focus();
        return (opop)?false:true;
      }
    } else if (links[i].className.match("bpop")) { 
       links[i].onclick = function() {
         var opop = window.open(this.href);
         if(opop && !isOpera) opop.focus();
         return (opop)?false:true;
      }
    }
  }
}

// All my unobtrusive javascript init stuff
// Tie it to the page when we load
window.onload = function() {
  doPopups();
}



