$(function () {
  $('#search_buttons td#drug_name_box p, #search2_buttons #orig_name_box, #search2_buttons #drug_name_box, #simple_search #drug_name_disp_a').click(function () {
    $('#search_buttons #drug_name_disp, #drug_name_disp_a, #orig_name_disp, #simple_search #drug_name_disp_a, #simple_search #dosage_name_a').hide();
    pane = 'drugs';
    $('#dosage_name p').html('&nbsp;');
    $('#search_buttons #drug_list div').css('visibility', '').html('&nbsp;');
    if(!thera_drug_id) {
      $('#drug_name').show();
      drugSearch(true);
    } else {
      theraSearch(thera_drug_id);
    }
  });

  $('#category #category_box').click(function () {
    $('#category_id').change();
  });

  $('#search_buttons td#dosage_name p, #dosage_name_box, #simple_search #dosage_name_a').click(function () {
    if(pane == 'forms') {
      $('#dosage_name p').html('&nbsp;').css('cursor', '');
      $('#dosage_name_a').hide();
      $('#drug_list div').css('visibility', '');
      $('#search2_buttons #drug_list, #category #drug_list, #simple_search #drug_list').fadeIn();
      dosageSearch();
    }
  });
});

var pane = 'drugs';
var drugSearchTimer;
function drugSearch(now) {
  if(pane == 'drugs') {
    clearTimeout(drugSearchTimer);
    drugSearchTimer = setTimeout(loadDrugs, now ? 0 : 500);
    $('#simple_search #drug_list').fadeIn('slow');
    $('#search_buttons #drug_list, #search_buttons #drug_name_box').css('background-color', '#d4f0f7');
    $('#search_buttons #drug_list').css('border', '1px solid black').css('border-top', 'none');
    $('#search_buttons #drug_name_box').css('border', '1px solid black').css('border-bottom', 'none');
    $('#search_buttons #dosage_name').css('background-color', '').css('border', 'none').css('border-bottom', '1px solid black');
    $('#search2_buttons #dosage_name_box, #category #dosage_name_box').css('background-color', '').css('border-bottom', '2px outset black');
    $('#search2_buttons #drug_name_disp, #category #drug_name_disp, #dosage_name_disp').html('&nbsp;');
    $("input[@name='orig_drug_name'], input[@name='drug_form_id']").val('');
    $('#search2_buttons #orig_name_box, #category #category_box').css('background-color', '#eaf1c1').css('border-bottom', '2px solid #eaf1c1');
    if(document.getElementById('search2_buttons') || document.getElementById('category')) { //causes an error if the offset doesn't exist in the math below
      $('#drug_list').fadeIn().width($('#drug_name_box').offset().left + $('#drug_name_box').outerWidth(true)/2 - $('#orig_name_box, #category_box').offset().left).css('left', $('#orig_name_box, #category_box').offset().left - $('#search2_buttons #input table, #category #input table').offset().left + 'px');
    }
//     $("input[@name='price']").attr("disabled", true);
//     $("input[@name='therapeutic']").attr("disabled", true);
  }
}

function dosageSearch(drug_name, drug_id) {
  clearTimeout(drugSearchTimer);
  pane = 'forms';
  $('#dosage_name_disp').html('&nbsp;');
  $('#search_buttons #drug_name').hide();
  if(drug_name) {
    $('#search_buttons #drug_name_disp, #orig_name_disp, #simple_search #drug_name_disp').html(escapeHTML(whiteSpace(drug_name))).effect('highlight', {color : '#c0d422'}, 'slow');
    $("input[@name='orig_drug_name']").val(drug_name);
  }
  if(!thera_drug_id) {
    $('#drug_name').hide();
    $('#orig_name_disp').show();
  }
  $('#search_buttons #drug_name_disp, #search_buttons #drug_name_disp_a, #simple_search #drug_name_disp, #simple_search #drug_name_disp_a').show();
  $('#search_buttons #drug_list, #search_buttons #dosage_name').css('background-color', '#eaf1c1');
  $('#search_buttons #drug_list').css('border', '1px solid black').css('border-top', 'none');
  $('#search_buttons #dosage_name').css('border', '1px solid black').css('border-bottom', 'none');
  $('#search_buttons #drug_name_box').css('background-color', '').css('border', 'none').css('border-bottom', '1px solid black');
//   $("input[@name='price']").attr("disabled", true);
//   $("input[@name='therapeutic']").attr("disabled", true);

  $('#search_buttons #drug_list div').css('border-top', 'none');
  $('#search_buttons #drug_list span, #simple_search #drug_list span').html('');
  $('#progress').html('Loading... <IMG src="images/throbber.gif" alt="">');
  if(drug_id) {
    $('#search_buttons #drug_list div').html('&nbsp;');
    $.ajax({
      url : 'getforms.php/' + drug_id,
      type : 'get',
      dataType : 'json',
      error : function(XMLHttpRequest, textStatus) {
        $('#progress').html('<P>Request failed: ' + textStatus + '. You can retry.<\/P>').append(XMLHttpRequest.responseText);
      },
      success : function(data, textStatus) {
        $('#progress').html('&nbsp;');
        dosageToList(data);
      }
    });
  }
}

function search2(form_name, drug_form_id, prices, theras) {
  if(document.getElementById('error_no_price') && !prices) {
    alert('This drug/dosage is not eligible for the giveaway.');
    return;
  }
  delayBlink_drugList_stop();
  $('#dosage_name p, #dosage_name_disp').html(escapeHTML(whiteSpace(form_name))).effect('highlight', {color : '#009fc3'}, 'slow').css('cursor', 'pointer');
  $('#search_buttons #dosage_name_a, #simple_search #dosage_name_a').show();
  $('#search_buttons #drug_list div').css('visibility', 'hidden');
  $('#search_buttons #drug_list, #search_buttons #drug_name_box, #search_buttons #dosage_name').css('background-color', '').css('border', 'none');
  $('#search_buttons #drug_list div').css('border-top', 'none');
  $('#search_buttons #drug_list span, #simple_search #drug_list span').html('');
  $('#search2_buttons #dosage_name_box, #category #dosage_name_box').css('background-color', '').css('border-bottom', '2px outset black');
  $('#search2_buttons #drug_list, #category #drug_list, #simple_search #drug_list').fadeOut();
  $("input[@name='drug_form_id']").val(drug_form_id);
//   $("input[@name='price']").attr("disabled", !prices);
//   $("input[@name='therapeutic']").attr("disabled", !theras);
  if(document.getElementById('search2_buttons') || document.getElementById('category')) {
    setQtys([]); //important because of a race condition: the results load before the price list is populated, so clear it, and then let it load in the background
    newFormId(drug_form_id);
    $.ajax({
      url : 'getform.php/' + encodeURIComponent(drug_form_id) + '/' + (thera_drug_id ? '1' : '0') + '/' + $('#location').val() + (loc_point ? '/' + (map_type == 'bing' ? loc_point.Latitude : loc_point.lat()) + '/' + (map_type == 'bing' ? loc_point.Longitude : loc_point.lng()) : ''),
      type : 'get',
      dataType : 'json',
      success : function(data, textStatus) {
        setQtys(data.qtys);
      }
    });
  }
}

function loadDrugs() {
  $('#search_buttons #drug_list div').css('border-top', 'none');
  $('#search_buttons #drug_list span, #simple_search #drug_list span').html('');
  if($('#drug_name').val().length < 2) {
    $('#drug_list div').html('Enter at least the first 2 characters of the drug name.');
  } else {
    $('#progress').html('Loading... <IMG src="images/throbber.gif" alt="">');
    $.ajax({
      url : 'getdrug.php/' + encodeURIComponent($('#drug_name').val()),
      type : 'get',
      dataType : 'json',
      error : function(XMLHttpRequest, textStatus) {
        $('#progress').html('<P>Request failed: ' + textStatus + '. You can retry.<\/P>').append(XMLHttpRequest.responseText);
      },
      success : function(data, textStatus) {
        $('#progress').html('&nbsp;');
        drugsToList(data);
      }
    });
  }
}

function drugsToList(data) {
  if(data.length == 0) {
    var drugs = '<P>No results found.<\/P><P>Tip: For best results enter just the first few letters of the name.<\/P>';
  } else {
    var drugs = '<UL>';
    for(var i = 0; i<data.length; i++) {
      drugs += '<LI><A HREF="?drug_id=' + data[i].drug_id + '" onClick="dosageSearch(\'' + escapeJS(data[i].name) + '\', \'' + data[i].drug_id + '\'); return false;">' + escapeHTML(data[i].name) + '<\/A>';
    }
    drugs += '<\/UL>';
    $('#search_buttons #drug_list div').css('border-top', '1px solid #cccccc');
    $('#drug_list span').html(thera_drug_id ? 'Select your alternative below' : 'Select your medication below');
  }
  delayBlink_drugList();
  $('#drug_list div').html(drugs);
}

function dosageToList(data) {
  $('#search2_buttons #drug_name_disp, #category #drug_name_disp').html(escapeHTML(whiteSpace(data.name))).effect('highlight', {color : '#c0d422'}, 'slow');
  $('#search2_buttons #dosage_name_box, #category #dosage_name_box').css('background-color', '#eaf1c1').css('border-bottom', '2px solid #eaf1c1');
  $('#search2_buttons #orig_name_box, #category #category_box').css('background-color', '').css('border-bottom', '2px outset black');
  if(document.getElementById('search2_buttons') || document.getElementById('category')) {  //causes an error if the offset doesn't exist in the math below
    $('#drug_list').width($('#location_box').offset().left + $('#location_box').outerWidth(true)/2 - $('#dosage_name_box').offset().left).css('left', $('#dosage_name_box').offset().left - $('#search2_buttons #input table, #category #input table').offset().left + 'px');
  }
  if(data.forms.length == 0) {
    var forms = '<P>No dosages found.<\/P>';
  } else {
    var forms = '<UL>';
    for(var i = 0; i<data.forms.length; i++) {
      forms += '<LI><A HREF="search2.php?drug_form_id=' + data.forms[i].drug_form_id + '" onClick="search2(\'' +  escapeJS(data.forms[i].strength + ' ' + data.forms[i].form) + '\', \'' + data.forms[i].drug_form_id + '\', ' + data.forms[i].prices + ', ' + data.forms[i].thera + '); return false;">' + escapeHTML(data.forms[i].strength + ' ' + data.forms[i].form) + '<\/A> ' + (data.forms[i].prices && data.forms[i].thera ? '<IMG src="images/yes_prices.png" alt="[Has Discount Prices &amp; Therapeutic Alternatives]" title="Has Discount Prices &amp; Therapeutic Alternatives">' : (data.forms[i].prices ? '<IMG src="images/yes_prices.png" alt="[Has Discount Prices]" title="Has Discount Prices">' : '<IMG src="images/no_prices.png" alt="[No Discount Prices]" title="No Discount Prices">') + ' ' + (data.forms[i].thera ? '<IMG src="images/yes_therapeutics.png" alt="[Has Discount Therapeutic Alternatives]" title="Has Discount Therapeutic Alternatives">' : '<IMG src="images/no_therapeutics.png" alt="[No Discount Therapeutic Alternatives]" title="No Discount Therapeutic Alternatives">')) + (data.coupon && !data.forms[i].prices ? ' <IMG src="images/yes_coupon.png" alt="[Has Brand Coupon]" title="Brand Coupon Available">' : '');
    }
    forms += '<\/UL>';
    $('#search_buttons #drug_list div').css('border-top', '1px solid #cccccc');
    $('#drug_list span').html('Select your dosage below');
  }
  delayBlink_drugList();
  $('#drug_list div, #category #dosage_list div').html(forms);
}

var thera_drug_id = false;
function theraSearch() {
  if(!thera_drug_id) {
    thera_drug_id = $("input[@name='drug_form_id']").val();
    $('#therapeutic_title span').html(escapeHTML($("input[@name='orig_drug_name']").val()));
  }
  if(thera_drug_id) {
    $('#message #generic_message').hide();
    $('#message #therapeutic_message').show();
    $('#therapeutic_title').show()
    $('#drug_list').fadeIn().width($('#drug_name_box').offset().left + $('#drug_name_box').outerWidth(true)/2 - $('#orig_name_box, #category_box').offset().left).css('left', $('#orig_name_box, #category_box').offset().left - $('#search2_buttons #input table, #category #input table').offset().left + 'px');
    $('#orig_name_box, #category_box').css('background-color', '#eaf1c1').css('border-bottom', '2px solid #eaf1c1');
    $('#dosage_name_box').css('background-color', '').css('border-bottom', '2px outset black');
    $('#drug_name, #orig_name_disp, #category_id').hide();
    $('#drug_name_disp, #dosage_name_disp, #dosage_list div').html('&nbsp;');
    $('#orig_name_box h3, #category_box h3').html('Therapeutic Alternative:');
    clearMarkers();
    $('#pharmacies').html('<P>Therapeutic search: select your drug and dosage from the therapeutic alternatives list.<\/P><HR><H6>Legend:<\/H6><P style="font-size: 75%;"><IMG src="images/yes_prices.png" alt="[Has Discount Prices]" title="Has Discount Prices"> available on a discount drug program<BR><IMG src="images/no_prices.png" alt="[No Discount Prices]" title="No Discount Prices"> not available on a discount drug program (nationwide)<BR><IMG src="images/yes_therapeutics.png" alt="[Has Discount Therapeutic Alternatives]" title="Has Discount Therapeutic Alternatives"> therapeutic alternatives available on a discount drug program<BR><IMG src="images/no_therapeutics.png" alt="[No Discount Therapeutic Alternatives]" title="No Discount Therapeutic Alternatives"> no therapeutic alternatives available on a discount drug program<\/P><HR>');

    $('#progress').html('Loading... <IMG src="images/throbber.gif" alt="">');
    $.ajax({
      url : 'getdrug.php/' + encodeURIComponent(thera_drug_id) + '/t',
      type : 'get',
      dataType : 'json',
      error : function(XMLHttpRequest, textStatus) {
        $('#progress').html('<P>Request failed: ' + textStatus + '. You can retry.<\/P>').append(XMLHttpRequest.responseText);
      },
      success : function(data, textStatus) {
        $('#progress').html('&nbsp;');
        drugsToList(data);
      }
    });
  }
}

function theraSearchStop() {
  thera_drug_id = false;
  $('#message #generic_message').show();
  $('#message #therapeutic_message').hide();
  $('#therapeutic_title').hide()
  $('#orig_name_box h3').html('Original Drug Name:');
  $('#category_box h3').html('Drug Category:');
  $('#drug_name, #category_id').show();
  if(document.getElementById('category'))
    getCat();
  else
    drugSearch();
}

function getCat() {
  $('#drug_name_disp, #dosage_name_disp').html('&nbsp;');
  $("input[@name='orig_drug_name'], input[@name='drug_form_id']").val('');
  $('#category_box').css('background-color', '#eaf1c1').css('border-bottom', '2px solid #eaf1c1');
  $('#drug_list').fadeIn().width($('#drug_name_box').offset().left + $('#drug_name_box').outerWidth(true)/2 - $('#category_box').offset().left).css('left', $('#category_box').offset().left - $('#category #input table').offset().left + 'px');
//   $("input[@name='price']").attr("disabled", true);
//   $("input[@name='therapeutic']").attr("disabled", true);
  if($('#category_id').val() !== '') {
    $('#progress').css('color', '').html('Loading... <IMG src="images/throbber.gif" alt="">');
    $.ajax({
      url : 'getcat.php/' + encodeURIComponent($('#category_id').val()),
      type : 'get',
      dataType : 'json',
      error : function(XMLHttpRequest, textStatus) {
        $('#progress').html('Request failed: ' + textStatus + '. You can retry.').append(XMLHttpRequest.responseText);
      },
      success : function(data, textStatus) {
        $('#progress').html('&nbsp;');
        drugsToList(data);
      }
    });
  }
}

var delayTimer;
function delayBlink_drugList() {
  delayBlink_drugList_stop();
  delayTimer = setTimeout(function() {
    blink('#drug_list span');
 }, 5000);
}

function delayBlink_drugList_stop() {
  clearTimeout(delayTimer);
  blink_stop('#drug_list span');
}

