﻿/************************************************************
*
*  TL Master.js
*
*  Do not modify this file.  Website specific JS should be in Site.js or in a page-specific JS file.
*  
************************************************************/
$(document).ready(
          function()
          {
			window_load();
		  }
		);

var signatureBoxes = new Array();
var continueButton;
var completedCheckbox;
var dataEnrolled;
var btnSubmitCompletedPackage = null;
var inputs = new Array();
var dataDeclined;
var rblDirectDepositEnrollmentRadioButtons = new Array();




function clearMe(e)
{
    var target = e.srcElement || e.target;
    if(!target.isChanged)
    {
       target.value="";
    }
    else
    
    target.isChanged=true;
    
}
function window_load()
{
	inputs = document.getElementsByTagName("input");
	var textareas = document.getElementsByTagName("textarea");
	var images = document.getElementsByTagName("img");
	//
	//Hook up keypressed events for all textbox inputs
	//
	var targetTxt=document.getElementById("ctl00_sendPageControl_tbTargetAddress");
	
	if(targetTxt)
	{
	    targetTxt.isChanged=false;
	    addEventHandler("focus",clearMe,targetTxt);
	}
	for (var i = 0;i<inputs.length;i++)
	{
		if (inputs[i].type == "text")
		{
			//check the input as it goes in
			addEventHandler("keypress", sanitize, inputs[i]);
			
			//and check the input as it goes out
			addEventHandler("change", sanitizeOnChange, inputs[i]);
		}
	}
	
	//
	//Hook up onChange events for all textarea inputs
	//
	for (var i = 0;i<textareas.length;i++)
	{
		addEventHandler("change", sanitizeOnChange, textareas[i]);
	}
	addEventHandler("keypress",noPostBack,window);
    
    
    /*NEEDS TO BE EVALUATED.  THIS APPEARS TO BE GARBAGE THAT SHOULD NEVER HAVE
    MADE ITS WAY INTO MASTER.JS BUT BEEN IN SITE.JS FOR A SPECIFIC PROJECT ONLY
    for(var i=0; i<inputs.length;i++)
    {
        var id = inputs[i].id;
        id = id.toLowerCase();
        if(id.indexOf("signature")>=0)
        {
            signatureBoxes.push(inputs[i]);
            addEventHandler("click",validateSignaturesGlobalFunc,inputs[i]);
        }
        else if((id.indexOf("insertbutton")>=0)||(id.indexOf("updatebutton")>=0))
        {
            continueButton = inputs[i];
        }
        else if (id.indexOf("btnsubmitcompletedpackage") >= 0 && btnSubmitCompletedPackage == null)
        {
            btnSubmitCompletedPackage = inputs[i];
        }
        else if (id.indexOf("dataenrolled") >= 0)
        {
            dataEnrolled = inputs[i];
            addEventHandler("click", dataEnrolled_Checked, inputs[i]);
        }
        else if (id.indexOf("datadeclined") >= 0)
        {
            dataDeclined = inputs[i];
            addEventHandler("click", dataDeclined_Checked, inputs[i]);
        }
    }
    validateSignaturesGlobalFunc(null);
    dataEnrolled_Checked(null);
    //END OF FIRST CHUNK OF GARBAGE CODE*/
    
    //
    //  Hook up onBlur event on any required text inputs that are not covered by masks.
    //
    /*ALSO APPEARS TO BE STUFF THAT SHOULD HAVE BEEN IN SITE.JS FOR A SPECIFIC PROJECT NOT IN MASTER.JS
    THAT GETS REUSED ON OUR TEMPLATES
    for (var i = 0; i < inputs.length; ++i)
    {
        var currentId = inputs[i].id;
        currentId = currentId.toLowerCase();
        if (currentId.indexOf("required") >= 0)
        {
            addEventHandler("blur", CheckRequiredTextInput, inputs[i]);
        }
    }*/
	
	
     //hook up any anchor tags with the css class popUp
     var anchors = document.getElementsByTagName("a");
     
     for(var i=0; i<anchors.length; i++)
     {
        var className= anchors[i].className;
       
        if(className)
        {
            if(className.indexOf("popUp")>=0)
            {
                
                addEventHandler("click",popUpLink,anchors[i]);
            }
        }
     }
     
     for (var i = 0; i < images.length; ++i)
     {
        id = images[i].id;
        id = id.toLowerCase();
        if (id.indexOf("imgcompletecheckbox") >= 0)
        {
            completedCheckbox = images[i];
            addEventHandler("click", imgCompleteCheckbox_Clicked, completedCheckbox);
            break;
        }
     }
     
    // call the site window onLoad function if it exists
    if (typeof Site_Window_Load == 'function')
    {
        Site_Window_Load();
    }
    // call the page-specific window onLoad function if it exists
    if (typeof Page_Window_Load == 'function')
    {
        Page_Window_Load();
    }
	 
}//window_load
function popUpLink(e)
{
     var tgt = e.srcElement || e.target;
     
     window.open(tgt.href,'pop up','');
     cancelEventDefault(e);
}

function validateSignaturesGlobalFunc(e)
{
  var enableBtn;
  enableBtn=true;
  if(continueButton)
  {
      for(var i=0; i<signatureBoxes.length;i++)
      {
        var cb = signatureBoxes[i];
      
         enableBtn = enableBtn && cb.checked;
      }
      continueButton.disabled=!enableBtn;
    }
}
function noPostBack(e)
{
    if (e.keyCode != 13) {return;}
    
    var target = e.srcElement||e.target;
    //we need to allow enter on text areas.
    if(target)
    {
		var nodename=target.nodeName;
		if(nodename)
		{
			nodename=nodename.toLowerCase();
			if(nodename=="textarea")
			{
				return;
			}
		}
    }
    
    cancelEventDefault(e);
}

//Called on EVERY keypress event for EVERY text input
function sanitize(e)
{
    /*IE uses keycode on this event
    Firefox uses charcode for characters, keycode for the arrow keys etc.
    IE doesn't register a key press event for the arrow keys, but firefox uses
    the keycode 39 for the right arrow.  That matches the charcode 39 for the apostraphe
    making the arrow key throw the alert error in firefox.*/
    if(typeof e.isChar != undefined)
	{	    
	    if(e.charCode==0)
	    {
	        return;
	    }
	}
	
	var code = e.charCode || e.keyCode;
	var match = String.fromCharCode(code).match(/[<>']/);
	
	if (match)
	{
		XBElem.prototype.cancelEventDefault(e);
		alert("Invalid character. " + match[0] + " is not allowed.");
	}
}

function sanitizeOnChange(e)
{
	var tgt = e.srcElement || e.target;
	/*NOTE: THE ONLY USE FOR TEXT AREAS ON A STATIC SITE IS TO SEND COMMENTS TO THE WEBMASTER.  THERE IS
	NO DATA ACCESS SO WE ARE ALLOWING THE '*/
	var reBaddies = new RegExp("[<>]", "g");
	var match = tgt.value.match(reBaddies);
	var baddies = "";
	tgt.value = tgt.value.replace(reBaddies, "");
	
	if (match)
	{
		for (var i = 0;i<match.length;i++)
		{
			if (baddies.indexOf(match[i]) == -1)
			{
				baddies += "\n" + match[i];
			}
		}
		
		alert("The following characters are not allowed and have been removed: " + baddies);
	}
}

//ctl00_ContentPlaceHolder1_formview1_rfv_
function CheckRequiredTextInput(e)
{    
    // Get the text from the arguments sent in.
    var text = e.Value;
    
    //alert(e.srcElement.id);
    //alert(e.type);
    
//    if (TrimString(text) == "")
//    {
//        // Not valid. Print error message and focus on the text box.
//        //document.getElementById("ctl00_ContentPlaceHolder1_formview1_rfv_" + e.id)
//        //oSrc.focus();
//    }
}

var checkedImageUrl = "Images/CompleteStep.gif";
var uncheckedImageUrl = "Images/IncompleteStep.gif";
function imgCompleteCheckbox_Clicked(e)
{
    var imgSrc = completedCheckbox.src;
    imgSrc = imgSrc.toLowerCase();
    if (imgSrc.indexOf("incomplete") >= 0)
    {
        // Display the checked image.
        completedCheckbox.src = checkedImageUrl;
        btnSubmitCompletedPackage.disabled = false;
    }
    else
    {
        completedCheckbox.src = uncheckedImageUrl;
        btnSubmitCompletedPackage.disabled = true;
    }
}

function dataEnrolled_Checked(e)
{
    if (dataEnrolled != null)
    {
        var directDepositRows = document.getElementsByTagName("tr");
        for (var i = 0; i < directDepositRows.length; ++i)
        {
            if (directDepositRows[i].className == "directDepositCanHide")
            {
                if (dataEnrolled.checked)
                {
                    // Show everything.
                    directDepositRows[i].style.visibility = "visible";
//                    directDepositRows[i].style.display = "table-row";
                }
                else
                {
                    // Hide everything.
                    directDepositRows[i].style.visibility = "hidden";
//                    directDepositRows[i].style.display = "none";
                }
            }
        }
    }
}




function ValidatePage(source, args)
{
    for (var i = 0; i < Page_Validators.length; ++i)
    {
        if (Page_Validators[i].id.indexOf("custom_ValidatePage") >= 0) break;
        ValidatorValidate(Page_Validators[i]);
        if (!Page_Validators[i].isvalid)
        {
            args.IsValid = false;
            alert("Please make sure you have filled out all required information and that all dates are correct.");
            return;
        }
    }
    
    args.IsValid = true;
}

//
//		SEARCH TEXT BOX
//
/////////////////////////////////
function tbSearch_change(e)
{
	var tgt = e.srcElement || e.target;
	//the rough equivalent to the "TrimStart" function in .NET
	tgt.value = tgt.value.replace(/^\s+/, "");
}

//
//		INCREMENTER CONTROL
//
/////////////////////////////////

function incrementValue(e)
{
	changeValue(e, "+");
}

function decrementValue(e)
{
	changeValue(e, "-");
}

function changeValue(e, how)
{
	//get the event target
	var tgt = e.srcElement || e.target;
	//get the textbox whose value we're interested in
	var textBox = tgt.parentNode.previousSibling;
	
	//crawl past text nodes 'till we get to an element node
	while (textBox.nodeType == 3)
	{
		textBox = textBox.previousSibling;
	}
	if (!isNaN(textBox.value))
	{
		//turn value into a number. will throw an error if value is inappropriate
		var intValue = parseInt(textBox.value);
		
		//take the appropriate action
		if (how == "+")
		{
			++intValue;
		}
		else if (how == "-")
		{
			if (intValue > 0)
				--intValue;
		}
		else
		{
			//unrecognized change request
		}
		
		//stick the new value in the textbox
		textBox.focus();
		textBox.value = intValue;
		textBox.blur();
		
		//
		//	Special functionality for the shopping cart
		//
		var seeker = tgt;
		while (seeker.tagName != "TD")
		{
			seeker = seeker.parentNode;
			if (seeker == null) break;
		}
		if (seeker != null)
		{
			var intPrice = parseFloat(getText(seeker.nextSibling).replace(/\$/, ""));
			
			//update the total price
			//updateTotalPrice(intValue, intPrice, seeker.nextSibling.nextSibling);
		}
	}
	else
	{
		textBox.value = "0";
	}

	XBElem.prototype.cancelEventDefault(e);

}


//
//		SHOPPING CART
//
/////////////////////////////////

function Quantity_change(e)
{
	var tgt = e.srcElement || e.target;
	var qty = parseInt(tgt.value) || 0;

	if (qty <= 0)
	{
		qty = 0;
		tgt.value = "0";
	}
	
	//turn value into a number. will throw an error if value is inappropriate
	//var intQuantity = parseInt(tgt.value);
	var seeker = tgt;
	while (seeker.tagName != "TD")
	{
		seeker = seeker.parentNode;
		if (!seeker) break;
	}
	if (seeker)
	{
		var fltPrice = parseFloat(getText(seeker.nextSibling).replace(/\$/, ""));
		//updateTotalPrice(qty, fltPrice, seeker.nextSibling.nextSibling);
	}
}

function updateTotalPrice(qty, price, td)
{
	if (!isNaN(qty))
	{
		qty = parseInt(qty);
		var price = qty * price;
		setText(FormatCurrency(price), td);
	}
	else
	{
		alert("non-numeric value");
	}
	
	updateCartSubTotal(td);
}

function updateCartSubTotal(td)
{
	//get table cell's cell index
	var cellIndex = td.cellIndex;
	//for each row in the table, sum the totals at that cell index
	var table = td.parentNode.parentNode;
	var sum = 0.0;
	for (var i = 1;i<table.rows.length;i++)
	{
	    var val=getText(table.rows[i].cells[cellIndex]);
	    val=val.replace("$","");
	    val=val.replace(",","");
		sum += parseFloat(val);
	}
	
	var footerTbl=document.getElementById("cartFooterTbl");
	var changeRow=footerTbl.rows[0];
	var changeCell=changeRow.cells[1];
	setText(FormatCurrency(sum),changeCell.getElementsByTagName("em")[0]);
	//the return false has to be here so we don't do a full postback in firefox.
	//the postback was resetting the value after the user clicked the incrementer.
	return false;
}


//
//		PRODUCT LIST ITEM
//
/////////////////////////////////
function centerInParent(img)
{
	var container = img.parentNode;
	var containerHeight = 0;
	var containerWidth = 0;
	if(document.defaultView)
	{
		containerHeight = parseInt(document.defaultView.getComputedStyle(container, null).getPropertyValue("height").replace("px", ""));
		containerWidth = parseInt(document.defaultView.getComputedStyle(container, null).getPropertyValue("width").replace("px", ""));
	}
	else
	{
		containerHeight = parseInt(container.currentStyle.height.replace("px", ""));
		containerWidth = parseInt(container.currentStyle.width.replace("px", ""));
	}
	
	container.style.position = "relative";
	img.style.position = "absolute";
	
	//center vertically
	img.style.top = (containerHeight/2 - img.height/2) + "px";
	//center horizontally
	img.style.left = (containerWidth/2 - img.width/2) + "px";
}


//
//		PRODUCT DETAILS
//
/////////////////////////////////
function bubbleUpToParentAnchor( e )
{ /*Now that we have placed our productListItem images into a containing div with an overflow attribute
    Internet Explorer makes the image not clickable any more.  So we have to register a click event 
    and bubble that click event up to the parent node */
  
    if(!e.srcElement)
    {
        //The issue only happens in IE.  So we don't bother doing 
        //unneeded processing if it is Firefox.
        return;
    }
   
    var clickedObj= e.srcElement;
    var checkNode=clickedObj.parentNode;
    while((checkNode.tagName!="a")&&(checkNode.tagName!="A")&&(checkNode))
    {
        checkNode=checkNode.parentNode;
    }
    if(checkNode)
    {
        checkNode.click();
    }
    

}
//function loadProductImage(path_str)
function loadProductImage(e)
{
	var tgt = e.srcElement || e.target;
	var srcImg = tgt.getElementsByTagName("img")[0];
    var targImg=document.getElementById("ctl00_ContentPlaceHolder1_imgProductImage");
    //targImg.src=path_str;
    targImg.src = tgt.src.replace(/tiny/, "medium");
    
    var hdn=document.getElementById("ctl00$ContentPlaceHolder1$hdnPathInfo");
    if(hdn)
    {
        hdn.value=targImg.src;
    }
}


function zoomImage(e)
{
	var style = document.getElementById("ZoomWindow").style;
	if (style.display != "block")
	{
		//show & position the window
		style.display = "block";
		style.top = e.y;style.left = e.x;
		
		//load image & get image dimensions
		var img = document.getElementById("ZoomWindow").getElementsByTagName("img")[0];
		img.onload = function() {document.getElementById("ZoomWindow").style.width = this.width + "px";};
		img.src = document.getElementById("hdnZoomImage").value;
		//img.onload = sizeWindow(style);
		style.width = 0;//imgWidth
	}
	else
	{
		style.display = "none";
	}
		
	XBElem.prototype.cancelEventDefault(e);
}
function hoverViewImage(hover)
{
    if (hover)
    {
        document.getElementById('englargeText').style.display = "none"
    } 
        else
    {  
        document.getElementById('englargeText').style.display = "block"
    }
}


//
//		SHOPPING CART
//
/////////////////////////////////
function ValidateCartQuantities(src, args)
{
    args.isValid=true;
}


//
//		APPLY ONLINE
//
/////////////////////////////////


///
///	Assumes the fieldset is the first fielset element in the target's parent
///
function ShowApplicationFields(e)
{
	var tgt = e.srcElement || e.target;
	
	//Get the fieldset
	var fieldset = tgt.parentNode.getElementsByTagName("fieldset")[0];

	//Show the fielset
	fieldset.style.display = "block";
	//Hide the "show" button
	tgt.style.display = "none";
	
	//Make the "hide" button
	var hideButton = document.createElement("input");
	hideButton.type = "button";
	hideButton.className = "btnShowAppliationfields";
	hideButton.value = "- Click here to hide this job application";
	addEventHandler("click", HideApplicationFields, hideButton);
	
	//add the "hide" button
	tgt.parentNode.insertBefore(hideButton, tgt);
	
	//removeEventHandler("click", ShowApplicationFields, tgt);
	//addEventHandler("click", HideApplicationFields, tgt);

	g_OpenJobApplicationsCount++;
}

///
///	Assumes the "Show" button is the first input field in the target's parent
///
function HideApplicationFields(e)
{
	var tgt = e.srcElement || e.target;

	//Get the fieldset
	var fieldset = tgt.parentNode.getElementsByTagName("fieldset")[0];

	//Hide the fielset
	fieldset.style.display = "none";
	//show the "show" button
	tgt.nextSibling.style.display = "block";
	//remove the "hide" button.
	tgt.parentNode.removeChild(tgt);

	//removeEventHandler("click", HideApplicationFields, tgt);
	//addEventHandler("click", ShowApplicationFields, tgt);
	
	g_OpenJobApplicationsCount--;
}

function warnOfOpenApplications(e)
{
	if (g_OpenJobApplicationsCount > 1)
	{
		var bContinue = confirm("You have more than one job application open at this time.\n\nOnly the application for which you clicked the 'Submit Application' button will be sent.\n\nClick 'OK' to continue anyway, click 'Cancel' to cancel sending this application.");
		if (!bContinue)
		{
			XBElem.prototype.cancelEventDefault(e);
		}
	}
}

function keepJobApplicationOpen(appFieldsetID)
{
	document.getElementById(appFieldsetID).style.display = "block";
}



//
//		CONTACT FORM
//
/////////////////////////////////

var maxMsgLength = 4200;
function ContactMessage_keypress(e)
{
	var tgt = e.srcElement || e.target;
	if (tgt.value.length >= maxMsgLength)
	{
		alert("You have entered the maximum amount of text allowable in this field.");
		cancelEventDefault(e);
	}
}
function ContactMessage_change(e)
{
	var tgt = e.srcElement || e.target;
	var msg = tgt.value;
	if (msg.length > maxMsgLength)
	{
		msg = msg.substr(0, maxMsgLength);
		tgt.value = msg;
		alert("You have entered the maximum amount of text allowable in this field. We have shortened your message to fit.");
	}
}
