/**
 * @copyright  Copyright (c) 2007 August Ash Inc. (http://www.augustash.com)
 * @version    $Id: aailib.js 30 2008-04-02 17:56:43Z dficker $
 */

/**
 * Prepare Links - using jQuery
 * 
 * Checks the document, when ready, for all link nodes with a class
 * name "external" and opens them in a new window when clicked.
 */
$(document).ready(function(){
	$("a").filter(".external").click(function (){
		var NewWindow = new OpenWindow($(this).attr("href"));
		return NewWindow.open();
	})
    .end();
});

/**
 * OpenWindow Class
 * 
 * Creates an OpenWindow object that allows you to define the URL, 
 * window name, and features for firing a pop-up window.
 * 
 * @param {String} href
 */
function OpenWindow(href)
{
	// Set default values
	var _href     = href;
	var _name     = "external";
	var _features = "";
	
	function __construct() {
		// Define methods		
		this.getHref     = function() { return _href; }
		this.setHref     = function(href) { _href = href; }
		this.getName     = function() { return _name; }
		this.setName     = function(name) { _href = name; }
		this.getFeatures = function() { return _features; }
		this.setFeatures = function(features) { _features = features; }
		
		this.open = function() {
			window.open(_href, _name, _features);
			return false;
		}
	};
	
	return new __construct();
}

/**
 * Son of Suckerfish Drop Down Menu
 * http://www.htmldog.com/
 */
// $(document).ready(function(){
//  var sfEls = $("ul#nav li");
//  for (var i = 0; i < sfEls.length; i++) {
//    $(sfEls[i]).mouseover(function(){
//      $(this).addClass("sfhover");
//    });
//    $(sfEls[i]).mouseout(function(){
//      $(this).removeClass("sfhover");
//    });
//  }
// });

/**
 * Old School Method for Suckerfish Drop Down Menu
 * Needed for IE6 flickering issues 
 */

sfHover = function() {
	if (!document.getElementById("nav")) return false;
	var sfEls = document.getElementById("nav").getElementsByTagName("li");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}

if (window.attachEvent) window.attachEvent("onload", sfHover);


/**
 * Prepare Links - using jQuery
 * 
 * Checks the document, when ready, for all link nodes with a class
 * name "popup" and opens them in a new window when clicked.
 */
$(document).ready(function() {
	$("a").filter(".popup").click(function () {
	    var width = 700;
        var height = 600;
        var win_left = (screen.width-width)/2;
        var win_top = (screen.height-height)/2;
    
		var NewWindow = new OpenWindow($(this).attr("href"));
		NewWindow.setFeatures('width='+width+',height='+height+',top='+win_top+',left='+win_left+',toolbar=no,directories=no,status=no,scrollbars=yes,resizable=yes');
		
		return NewWindow.open();
	})
    .end();
});


/*	Stripe Admin Index Tables
------------------------------------------------------------------------ */
$(document).ready(function() {
    $("table.adminLister:not(#quote_results) tbody tr:odd").addClass("odd");
    // $("table.adminLister:not(#quote_results) tbody tr:even").addClass("altRow");
});


/* Toggle display of featured quote rows / TableSorter Plugin
--------------------------------------------------------------- */
$(document).ready(function() {
  // set vars
  var featured_quotes     = $("table#quote_results tbody tr.featured");
  var regular_quotes      = $("table#quote_results tbody tr:not(.featured)");
  var featuredQuotes_tab  = $("a#featuredQuotes");
  var allQuotes_tab       = $("a#allQuotes");
  var sortable_columns    = $("table#quote_results th.sort");

  // hide the non-featured quotes by default
  $(regular_quotes).hide();
    
  $("table#quote_results").tablesorter({
    // disable sorting of specific columns (counting starts at 0)
    headers: {
      0: { sorter: false },
      3: { sorter: false },
      6: { sorter: false }
    },
    sortList: [[5,0]],      // sort by premium ASC
    widgets: ['zebra']
  });
  
  $(allQuotes_tab).click(function(){
    // remove the selected class from the Featured quotes tab
    $(featuredQuotes_tab).removeClass('selected');
    $(featuredQuotes_tab).parent('li').removeClass('selected');
    // add the selected class to this All Quotes tab
    $(this).parent('li').addClass('selected');
    $(this).addClass('selected');
    // show all quote rows
    $(regular_quotes).show();
    // stripe the visible rows
    $("table#quote_results tbody tr").removeClass("odd");
    $("table#quote_results tbody tr:visible:odd").addClass("odd");
  });

  $(featuredQuotes_tab).click(function(){
    // remove the selected class from the All Quotes tab
    $(allQuotes_tab).removeClass('selected');
    $(allQuotes_tab).parent('li').removeClass('selected');
    // add the selected class to this Featured Quotes tab
    $(this).parent('li').addClass('selected');
    $(this).addClass('selected');
    // show all quote rows
    $(regular_quotes).hide();
    // stripe the visible rows
    $("table#quote_results tbody tr").removeClass("odd");
    $("table#quote_results tbody tr:visible:odd").addClass("odd");
  });
});

/*	Hide div.orientation when clicked
------------------------------------------------------------------------ */
$(document).ready(function() {
  $("div.orientation_show").hide();
  $("div.orientation a.close").click(function () {
    // Animate hide
    $('div.orientation').slideUp('fast');
    $('div.orientation_show').slideDown('fast');
  });

  $("div.orientation_show a.orientation_help").click(function () {
    // Animate hide
    $('div.orientation_show').slideUp('fast');
    $('div.orientation').slideDown('fast');
  });
});

/*	Hide flashes
------------------------------------------------------------------------ */
$(document).ready(function() {
  $("div.flash a.close_flash").click(function () {
    // Animate hide
    $('div.flash').fadeOut(1000);
  });
});

/*	Form Helper Bubbles
------------------------------------------------------------------------ */
$(document).ready(function () {
  $('.formHelper').each(function () {
    // options
    var distance = 10;
    var time = 250;
    var hideDelay = 500;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;
    
    var trigger = $('.trigger', this);
    var popup = $('.popup', this).css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).mouseover(function () {
      // stops the hide event if we move from the trigger to the popup element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        beingShown = true;

        // reset position of popup box
        popup.css({
          top: 0,
          left: 33,
          display: 'block' // brings the popup back in to view
        })

        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          top: '-=' + distance + 'px',
          opacity: .75
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
      }
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      
      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the popup entirely after the effect (opacity alone doesn't do the job)
          popup.css('display', 'none');
        });
      }, hideDelay);
    });
  });
});


/*	Toggle display of security question choices between default 
    drop down box and creating your own
------------------------------------------------------------------------ */
$(document).ready(function() {
  var mySecurityQuestion = $('input.my_security_q');
  var myAnswerFormRow = $('input#security_secret_answer').parent('div.formRow');
  var chooseSecurityQuestion = $('select.security_q_select').parent('div.formRow');
  
  // hide the parent div.formRow of mySecurityQuestion
  mySecurityQuestion.parent('div.formRow').hide();
  
  // add toggle links to security question choices and custom question
  chooseSecurityQuestion.children('div.formHelper').after('<a class="toggle_secret_q" href="#" title="Create My Own Security Question">Create My Own Security Question</a>');
  mySecurityQuestion.parent('div.formRow').children('div.formHelper').after('<a class="toggle_my_secret_q" href="#" title="Choose from the default set">Choose From the Default Set</a>');
  
  $('a.toggle_secret_q:visible').click(function() {
    if ($('select.security_q_select').parent('div.formRow:visible')) {
      chooseSecurityQuestion.hide();
      mySecurityQuestion.parent('div.formRow').slideDown();
    }
  });

  $('a.toggle_my_secret_q:visible').click(function() {
    if ($('select.security_q_select').parent('div.formRow:visible')) {
      // clear the form field and toggle the select box
      mySecurityQuestion.val('');
      mySecurityQuestion.parent('div.formRow').hide();
      chooseSecurityQuestion.slideDown();
    }
  });
});


/*	Toggle Display of File Upload Fields if there are more 
    than one File Uploads
------------------------------------------------------------------------ */
$(document).ready(function() {
  // do something
  var attachmentFields = $('input.fileUploadMultiple');
  var attachmentFormRows = attachmentFields.parent('div.formRow');
  var addAttachmentLink = $('fieldset div.addMoreAttachments a.addAttachment');
  
  attachmentFormRows.hide();
  addAttachmentLink.click(function () {
    attachmentFormRows.toggle('750');
    addAttachmentLink.text('View Attachments');
  });
});

/*	Hide My Application Link field if user chooses BlueCross BlueShield 
    as their carrier    reason: BCBS has 2 links for applications
------------------------------------------------------------------------ */
$(document).ready(function () {
  // set the vars
  var my_app_link         = $('input.my_app_link');
  var my_app_link_row     = $(my_app_link).parent('div.formRow');
  var carrier_select_box  = $('select#license_number_carrier_id');
  var carrier_options     = $('select#license_number_carrier_id option:gt(1)');
  var carrier_bcbs        = $('select#license_number_carrier_id option[value="1"]');
  var carrier_selected    = $('select#license_number_carrier_id option:selected');
  
  
  // EDIT VIEW
  // test if the selected carrier is BCBS and if true then hide the my_app_link_row
  if ($('select#license_number_carrier_id option:selected').text() == 'BlueCross BlueShield') {
    $(my_app_link_row).hide();
  }

	if ($.browser.msie) {
		// IE doesn't recognize option.click so we'll use the change function
		$(carrier_select_box).change(function () {
			var str = "";
			$('select#license_number_carrier_id option:selected').each(function () {
  		  str += $(this).text();    	
      	if (str == 'BlueCross BlueShield') {
      	  $(my_app_link_row).hide();
      	} else {
      	  $(my_app_link_row).show();
      	}
			})
			.trigger('change');
		});
	} else {
    $(carrier_options).click(function () {
      $(my_app_link_row).show();
    });
  
    $(carrier_bcbs).click(function () {
      $(my_app_link_row).hide();
    });
  }
});


/*	Limit the # of plans selected to compare
    http://www.slideshare.net/gueste8d8bc/growing-jquery (slide 8)
------------------------------------------------------------------------ */
$(document).ready(function () {
  // set vars
  var max_amount  = 5;
  var checkboxes  = $('table#quote_results input:checkbox');
  
  $(checkboxes).click(function () {
    if (checkboxes.filter(":checked").length <= max_amount) {
        $(this).is(':checked') = true;
    } else {
      this.checked = false;
      alert('You can only compare '+ max_amount +' plans at a time. Please choose the '+ max_amount +' plans you wish to compare from the results listed.');
    }
  });  
});

/*	Display Loading Progress when rates import button is clicked
------------------------------------------------------------------------ */
$(document).ready(function () {
  // set vars
  var import_btn = $('input.btn_import');
  
  $(import_btn).click(function () {
    if ($('div.loading_progress:hidden')) {
      $('div.loading_progress').fadeIn('slow');
    } else {
      $('div.loading_progress').fadeOut();
    }
  });
});

/*	Show/hide the modal dialogue box
------------------------------------------------------------------------ */
$(document).ready(function() {
  $("input#getQuoteSubmit").click(function() {
    $("div#simpleModal").fadeIn();
  });
});

/* Toggle Sorting Arrows
------------------------------------------------------------------------ */
$(document).ready(function() {
  var url = window.location.href;
  if (url.substr(-4) == 'desc') {
    $("th.sort a").addClass('sortMe');
  } else if (url.substr(-3) == 'asc') {
    $("th.sort a").removeClass('sortMe');
  }
});


/*	Add class .selected 
------------------------------------------------------------------------ */
$(document).ready(function() {
  // add class...
  var selected_tab = $("ul.subnav a.tabs-selected");
  selected_tab.parent("li").addClass('selected')
});


