﻿/*
 * Common JS
 * Provides universal event handling and shared functionality.
 *
 */

// Default ready handler
// @$: (jQuery) Object
jQuery(function($) {
    // Include clear plugin if not already present
    if(typeof $.fn.clear === "undefined") {
        // This is the object to clear
        $.fn.clear = function(who, not, when, what) {
            var that = this;
                
            // Bind to each selector
            $(who).each(function(i,e) {
                // Default to click
                e = (e === "document") ? document : e;
                $(e).bind((when || "click"), function(evt) {
                    if(typeof what === "function")
                        what.call(that, evt);
                    else
                        that.hide();
                });
            });
     
            // Prevent the object from closing
            $(not).bind(when || "click", function(evt) {
                evt.stopPropagation();
            });
            
            return that;
        }
    }
    // Emulate jQuery 1.4.2 delegate method
    if(typeof $.fn.delegate === "undefined") {
        $.fn.delegate = function(_target, _type, _callback) {
            var $root = this.bind(_type, function(evt) {
                var $this = $(evt.target),
                    $this = ($this.filter(_target).length) ? $this :
                        $this.parents().filter(_target);
                        
                if($root.find($this).length) {
                    if($this.length) {
                        return _callback.call($this[0], evt);
                    }
                }
                
                return false;
            });
        };
    }
    // Emulate jQuery 1.4 last method
    if(typeof $.fn.last === "undefined") {
        $.fn.last = function() {
            return this.eq(-1);
        }
    }
    
    // Attach to jQuery prototype
    // Context: (jQuery) Object of what the plugin is being run on
    // Returns: (jQuery) Object of what the plugin is being run on
    $.fn.toggleValue = function() {
         // Chainability
         // Context: (jQuery) Object iteration plugin will be run on.
         return this.each(function $each() {            
            // Caching iterative element
            var $element = $(this),
               // Caching DOMElement
               element = this,
               // Default value
               defaultValue = element.defaultValue;
               
            // Should only be applied to <INPUT> types
            if($element.is("input[type=text]")) {
               // Set the default value if nonexistant
               element.defaultValue = (defaultValue.length) ? defaultValue : element.value;
               
               // On focus hide the value if matches the default value
               $element.bind("focus", function() {
                  // Clear the textbox
                  if(this.value === this.defaultValue) {
                     this.value = "";
                  }
               });
               
               // On blur set to default if value is empty
               $element.bind("blur", function() {
                  // Fill the textbox
                  if(!this.value.length) {
                     this.value = this.defaultValue;
                  }
               });
            }
        });
        
    };
    
    // Dropdown effect in primary navigation
    var $primary_nav = $("#primary-nav ul > li");
    // Toggle menu hover
    $primary_nav.hover(function() {
        $(this).find("ul").show();
    }, function() { 
        $(this).find("ul").hide();
    });
    
    // Dropdown effect for Call Center Hours
    $("a.call-center").bind("click", function() {
        $("div.call-center").show();
    });
    
    $("div.call-center").clear("body, div.call-center img.close", "a.call-center, div.call-center");

    // Hover effect on text for various buttons throughout the entire site
    $('.btn-quote input, .btn-learn input').hover(function() {
        $(this).addClass('hover');
    }, function() {
        $(this).removeClass('hover');
    });
	
	
	//New JavaScript additions for HFPP quote support
	
	function cloneBeneficiary() {
		var clone = $("#beneficiary1").clone();
		var count = $(".beneficiary").length + 1;
		clone.appendTo("#beneficiaries");
		clone.find("h3").html("Beneficiary " + count);
		clone.find(".share").val("").calcShare();
	}
	
	jQuery.fn.calcShare = function() {
		this.bind("change", function() {
			var value = 0
			$(".share").each(function() {value += parseInt(this.value || 0)})
			$("#totalallocatedshare").html(value + "%");
		})
	}
	
	var caller = $();
	
	$("form").submit(function() {
		$('.errors').removeClass('hidden')
		return false;
	})
	$(document).keyup(function(e) {
		if (e.keyCode == 27) {
			$(".tooltip,.tooltipiframe").remove();
			$('#mask, .window').hide();
			caller.focus();
			caller = $();
		}
	})
	
	$("a,input,select,textarea,button").focus(function(e) {
		if ($(this).parents("#modal").length == 0 && caller.get(0) != this) {
			if (!$(this).hasClass("skip")) $("#dialog a:first").focus()
			else $("#dialog a:last").focus()
		}
	});

	$(".optional").val("optional").focus(function() {
		if (this.value == "optional") {
			$(this).removeClass("optional");
			this.value = ""
		}
	})
	
	$("select").keyup(function() {
		//trigger on change w/ keyboard
		this.blur();
		this.focus();
	})
	
	$(".share").val("").calcShare()
	$(".tip").live("click", function(e) {
		caller = $(this)
		$(".tooltip,.tooltipiframe").remove();
		e.preventDefault();
		var pos = $(this).offset()
		pos.top -= 10
		pos.left += 6
		
		var tooltip = $('<div class="tooltip" role="dialog"><a class="closer" href="#" aria-label="Close" aria-describedby="descriptionClose"></a><div class="tooltip-inner"></div></div>')
		var iframe = $('<iframe class="tooltipiframe" frameborder="0" src="javascript:;"></iframe>')
		iframe.appendTo(document.body)
		tooltip.appendTo(document.body)
		tooltip.css({left: pos.left, top: pos.top})
		tooltip.find(".tooltip-inner").html(this.rel)
		tooltip.find(".closer").click(function(e) {
			e.preventDefault();
			tooltip.remove();
			iframe.remove();
			caller.focus();
			caller = $();
		})
		tooltip.find("a:first").focus();
		iframe.css({height: tooltip.height() + 14, width: tooltip.width(), left: pos.left, top: pos.top - 10})
	});
	
	$(".tip").parent().prev().find("label")
		.mouseover(function() {$(this).css("text-decoration", "underline")})
		.mouseout(function() {$(this).css("text-decoration", "none")})
	
	$(".expanderlink").click(function(e) {
		e.preventDefault();
		var sib = $(this).next('div');
		
		if (sib.hasClass('hidden')) {
			$(this).html('<span class="expandertext">Less detail</span> <span class="expander">[–]</span>');
			sib.removeClass('hidden');
		} else {
			$(this).html('<span class="expandertext">More detail</span> <span class="expander">[+]</span>');
			sib.addClass('hidden');
		}
	});
	
	$("#removefromplan").click(function(e) {
		$('[name=policy]').attr('disabled', false);
		$(this).addClass('hidden').next().removeClass('hidden').find('a').focus();
		return false;
	})
	
	$("#addtoplan").click(function(e) {
		$('[name=policy]').attr('disabled', true);
		var dailybenefit = $('[name=policy]:checked').val().split(",")
		$(this).parent().addClass('hidden').prev().removeClass('hidden').focus();
		$("#dailybenefit").get(0).innerHTML = ("Daily Benefit " + dailybenefit[0])
		$("#dailybenefitvalue").get(0).innerHTML = (dailybenefit[1])
		return false;
	})
	
	//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		$('#mask, .window').hide();
		caller.focus();
		caller = $();
	});  

	$('.window .closelink').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();

		$('#mask, .window').hide();
		caller.focus();
		caller = $();
	});  	
	 
	$(".applytoplan").click(function(e) {
		e.preventDefault();
		$(this).addClass("hidden").next(".removeplan").removeClass("hidden").focus()
	})
	$(".removeplan").click(function(e) {
		e.preventDefault();
		$(this).addClass("hidden").prev(".applytoplan").removeClass("hidden").find("a").focus()
	})	
	
});

	//modal
	var showmodal = function(elem, link){
		caller = $(link)
		var id = '#dialog';
		$('#modalcontent').html($('#'+elem)); 
		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	 
		//Set height and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		 
		//transition effect    
		$('#mask').fadeIn(0);   
		$('#mask').fadeTo("slow",0.8); 
	 
		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();
			   
		//Set the popup window to center
		$(id).css('top', Math.max(winH/2-$(id).height()/2, 20));
		$(id).css('left', winW/2-$(id).width()/2);
		
		setTimeout(function() {$(id + " a:first").focus();},0)
		//transition effect
		$(id).fadeIn(0);
	};
