// Timeline management
function showTimeline(id) {
  new Ajax.Updater('timelineDisplay', '/timelines/show/' + id, { 
    onSuccess: function(request) { 
      var f = $$('.timelineBox'); 
      for (var i=0; i<f.length; i++) {
        if (f[i].id == 'timeline' + id) {
          f[i].className = "timelineBox activeTimeline";
        } else {
          f[i].className = "timelineBox";
        }
      }
    } 
  });
}

function addTimelineStep(element) {
  var newRow   = element.insertRow(-1);
  var newCell1 = newRow.insertCell(0);
  var newCell2 = newRow.insertCell(1);
  newCell1.innerHTML = '<input id="timeline[steps][][0]" name="timeline[steps][][0]" type="text" />';
  newCell2.innerHTML = '<input id="timeline[steps][][1]" name="timeline[steps][][1]" type="text" />';
}

// AIG plan
function toggleDisabilityEntry() {
  var toggled = $('aig_plan_disability_rider_units').checked;
  if (toggled) {
    $('aig_plan_disability_rider_occupation').disabled = false;
    $('aig_plan_disability_rider_type').disabled = false;
  } else {
    $('aig_plan_disability_rider_occupation').disabled = true;
    $('aig_plan_disability_rider_type').disabled = true;
  }
}

// Critcare plan
function setUpChildren(max, current) {
  var child_list = $('critcare_plan[child_coverage_units]');
  while (child_list.length > 0)
    child_list.remove(child_list.length - 1);
  (max + 1).times(function (index) { 
    var opt = document.createElement('option');
    if (index == 0)
      opt.text = "None";
    else
      opt.text = '$' + (5 * (index + 1)) + ',000';
    opt.value = index;
    if (index == current)
      opt.selected = "selected";
    Try.these(
      function() { child_list.add(opt, null) },
      function() { child_list.add(opt) }
    );
  });
}

// Norvax family setup

function checkNorvaxFamilyEnableds() {
  var chks = $$('.chkchild');
  var full = true;
  chks.each(function(box, index) {
    if (! box.checked)
      full = false;
  });
  if (full) {
    addNorvaxChild(chks.length);
  }
}

function addNorvaxChild(length) {
  new Ajax.Request('/norvax_plan/child_row',
      {
        method: 'get',
        parameters: 'which=' + length,
        onComplete: function(request) {
          new Insertion.Before('eff_date_row', request.responseText);
        }
      });
}

// Quote-saving things

function notifyQuoteSaved()
{
  $('quote_saved').innerHTML = "<strong>Your Quote Has Been Saved</strong><br />\n" +
                               "We'll give you a call or an email to follow up with you shortly.\n" +
                               "In the meantime, feel free to give us a call at 800.259.0455.";
  $('quote_saved').show();
  new Effect.Highlight('quote_saved');
}

// External stuff

if (window.addEventListener)
{
	window.addEventListener("load", fixLayout, false);
	window.addEventListener("resize", fixLayout, false);
}
function fixLayout()
{
	var d = document.getElementById("pagewidth");
	if (d)
	{
		d.style.minHeight = document.documentElement.clientHeight + "px";
	}
}

/**** Definitions ****/
defn_cache = {};

function updateDefinitions(request)
{
  var defns = eval("(" + request.responseText + ")");
  var elements = $$('.takesDefs');
  var i = 0;
  for (var idx=0; idx<elements.length; idx++) {
    var element = elements[idx];
    var subject = element.innerHTML;
    for (word in defns) {
      i += 1;
      subject = subject.replace(eval('/\\b('+word+')\\b/i'), '<a href="javascript:;" class="info" onmouseover="loadDefn(this)" name="defn_' + defns[word] + '">' +
                                                             '<span id="defn_tag_' + i + '">Loading...</span>$1</a>');
    }
    element.innerHTML = subject;
  }
}

function loadDefn(anchor)
{
  span = anchor.firstChild;
  defn = anchor.name.substr(5);
  anchor.onmouseover = null;
  if (defn_cache[defn]) {
    span.innerHTML = defn_cache[defn]
  } else {
    new Ajax.Updater(span.id, '/definition/meaning/' + defn, {
      onSuccess: function(request) { defn_cache[defn] = request.responseText }
    });
  }
}

function openChatWindow(){
  window.open('http://198.107.63.100:8080/contactus/request_chat_form.jsp', '', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1');
}

function openPhoneWindow(){
  window.open('http://198.107.63.100:8080/contactus/callback_request_new.jsp', '', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1');
}

/** Testimonial box **/

function showTestimonial()
{
  $('t_i').src = '/system/image_uploads/' + selectedTestimonial[0] + '.jpg';
  $('t_t').innerHTML = selectedTestimonial[1];
  $('t_c').innerHTML = selectedTestimonial[2];
}

function showFact()
{
  $('f_c').innerHTML = selectedFact;
}

function preload(url, destination_id, _width, _height, loaded, vars){ // users should not pass loaded as a var
	// this function needs domLoad to work correctly
	if(!loaded){ // loaded should not be passed in by default
		domLoad(url, destination_id, _width, _height); // test that the dom is available
		return;
	}
	if(document.getElementById(destination_id) != null){
		var target_url = encodeURIComponent(url);
	  var FO = { movie:"/flash/preloader.swf", width:_width+"", height:_height+"", majorversion:"8", build:"0", wmode:"transparent", xi:"false", flashvars:("target_url="+target_url+"&extra_params="+(vars ? encodeURI(vars) : ''))};
	  UFO.create(FO, destination_id);
	}
}

function domLoad(url, id, _width, _height){
	// This function is used with preload to wait for the dom to load before trying to insert the preloader
	// arguments are passed from preload and back to preload when dom is loaded
	var _t = setInterval(function() {
		if ((document.getElementsByTagName("body")[0] != null || document.body != null) && document.getElementById(id) != null) {
			preload(url, id, _width, _height, true);
			clearInterval(_t);
		}
	}, 250);
	if (typeof document.addEventListener != "undefined") {
		document.addEventListener("DOMContentLoaded", function() {preload(url, id, _width, _height, true);  clearInterval(_t); } , null); // Gecko, Opera 9+
	}
}

function openStep(n) {
  if (el = $$('.headerStep' + n + ' .oclink')[0]) {
    Element.addClassName(el, 'opened');
    Element.removeClassName(el, 'closed');
    el.innerHTML = "&nbsp;&nbsp;&nbsp;";
  }
  [1,2,3].without(n).each(function (ni) { closeStep(ni) })
}

function closeStep(n) {
  if (el = $$('.headerStep' + n + ' .oclink')[0]) {
    Element.addClassName(el, 'closed');
    Element.removeClassName(el, 'opened');
    el.innerHTML = "&nbsp;&nbsp;&nbsp;";
  }
}

function tinymceFileBrowser(field_name, url, type, win)
{
  var cmsURL = "/image_uploads/list?tinymce=yes";
  var searchString = window.location.search;
  tinyMCE.openWindow({
    file: cmsURL + '&' + searchString + '&type=' + type,
    title: "File Browser",
    width: 420,
    height: 400,
    close_previous: "no"
  }, {
    window: win,
    input: field_name,
    resizable: "yes",
    scrollable: "yes",
    editor_idx : tinyMCE.getWindowArg("editor_id")
  });

  return false;
}

/**** Carriers ****/
carrier_cache = {};

function updateCarriers(request)
{
  var defns = eval("(" + request.responseText + ")");
  var elements = $$('.takesCarriers');
  var i = 0;
  for (var idx=0; idx<elements.length; idx++) {
    var element = elements[idx];
    var subject = element.innerHTML;
    for (word in defns) {
      i += 1;
      subject = subject.replace(eval('/\\b('+word+')\\b/i'), '<a href="javascript:;" class="info" onmouseover="loadCarrier(this)" name="defn_' + defns[word] + '">' +
                                                             '<span id="defn_tag_' + i + '">Loading...</span>$1</a>');
    }
    element.innerHTML = subject;
  }
}

function loadCarrier(anchor)
{
  span = anchor.firstChild;
  carrier = anchor.name.substr(5);
  anchor.onmouseover = null;
  if (carrier_cache[carrier]) {
    span.innerHTML = carrier_cache[carrier]
  } else {
    new Ajax.Updater(span.id, '/pages/carriers/' + carrier, {
      onSuccess: function(request) { carrier_cache[carrier] = request.responseText }
    });
  }
}

function runPlanSelector(category) {
  h = $('headerFlash');
  h.style.height = '350px';
  h.style.textAlign = "center";
  //h.style.backgroundColor = "#ACE6F2";
  var FO = { movie:"/flash/questionnaire.swf", width:"940", height:"350", majorversion:"8", wmode:"transparent",  build:"0", xi:"true", flashvars:'input_quote_type=' + category};
  UFO.create(FO, "headerFlash");
  window.scrollTo(0, 0); 
}

function openDetailWindow(id){
	window.open('compare' + id, '', 'toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=410,height=410,left = 300,top = 390');
}

function openApplyWindow(id){
	window.open('apply' + id, '', 'toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=0resizable=1,width=550,height=410,left = 300,top = 390');
}

function openPdfWindow(uri){
  window.open(uri, '', 'toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=0resizable=1,width=550,height=410,left = 300,top = 390');
}

/**** Plan selector ****/

function setUpSpecialAnchors() {
  var chatLinks = $$('a.chatLink');
  chatLinks.each(function(val) {
    val.href = "javascript:openChatWindow();";
  })
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}
