/**

	This script will be run on every page. It depends on:
	* Utitlities.js
	* XBElem.js
	* InputSanitizer.js

**/

var g_OpenJobApplicationsCount = 0;

addEventHandler("load", window_load, window);

function window_load(e)
{
    /*just add the pop up for the lodge virtual tour on the home page here because I don't want to bother creating a seperate js file just for that
    */
    var lodgeImg = document.getElementById("lodgeImg");
    if(lodgeImg)
    {
        addEventHandler("click",popUpTour,lodgeImg);
    }


	var inputs = document.getElementsByTagName("input");
	var textareas = document.getElementsByTagName("textarea");
	
	//
	//Hook up keypressed events for all textbox inputs
	//
	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]);
			
			if (inputs[i].id.indexOf("tbSearch") > -1)
			{
				var xbSearch = new XBElem(inputs[i]);
				xbSearch.tieToButton(inputs[i].parentNode.getElementsByTagName("a")[0]);
			}
		}
	}
	 
	//
	//Hook up onChange events for all textarea inputs
	//
	for (var i = 0;i<textareas.length;i++)
	{//alert(textareas[i].id);
		//check the input as it goes in
		addEventHandler("change", sanitizeOnChange, textareas[i]);
		
		//hook up the length-checker for the Contact Us message textbox
		if (textareas[i].id == "ctl00_SitePlaceHolder_tbMessage")
		{
			addEventHandler("keypress", ContactMessage_keypress, textareas[i]);
			addEventHandler("change", ContactMessage_change, textareas[i]);
		}
	}
	
	//
	//Loop through all the divs hooking up events as we find the appropriate controls
	//
	var divs = document.getElementsByTagName("div");
	
	//
	//	Hook up the image centering javascript
	//
	/*Product List Items need a hack for IE now that we have the images in a containing div to resolve
	resizing issues*/
	var ProductList = document.getElementById("ProductList");
	if(ProductList != null)
	{
		var spans = ProductList.getElementsByTagName("span");
		for (var i = 0;i<spans.length;i++)
		{
			if (spans[i].className.indexOf("prodImgContainer") >= 0)
			{
				//find the image.
				var imgTag = spans[i].getElementsByTagName("img")[0];
				if(imgTag)
				{
					addEventHandler("click",bubbleUpToParentAnchor,imgTag);
					centerInParent(imgTag);
				}
			}
		}
	}
	
}//window_load
function popUpTour(e)
{
    var path = "Lodge/LodgeTourPopUp.aspx";
     window.open(path, "tour", "directories=no,location=no,menubar=no,toolbar=no,width=500px,height=770px,scrollbars=no,resizable=no");
}
function featurePopUp(e)
{

    var tgt = e.srcElement || e.target; 
    var targetURL="";
    if(tgt.nodeName=="A")
    {
        targetURL=tgt.href;
    }
    else
    {    
        targetURL=tgt.parentNode.href;
    }
    window.open(targetURL, "help", "directories=no,location=no,menubar=no,toolbar=no,width=370px,height=560px,scrollbars=no,resizable=no");
    cancelEventDefault(e);
}
//Called on EVERY keypress event for EVERY text input
function sanitize(e)
{
	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;
	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);
	}
}

//
//		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_SitePlaceHolder_imgProductImage");
    //targImg.src=path_str;
    targImg.src = tgt.src.replace(/tiny/, "medium");
    
    var hdn=document.getElementById("ctl00$SitePlaceHolder$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;
//	//extract the cart contents control's ID from the sender
//	var id = src.id.replace("custvalQuantity", "gvCartItems");
//	//get the rows of the table
//	var rows = document.getElementById(id).rows;
//	//count the zero-quantity elements
//	var iArrayIndex = 0;
//	var zeroIndexes = new Array();
//	for (var i = 1;i<rows.length;i++)//init i at 1 to skip the header
//	{
//		if (rows[i].cells[2].getElementsByTagName("input")[0].value == 0)
//		{
//			zeroIndexes[iArrayIndex++] = i;
//		}
//	}

//	//alert user if any zero-count items were found
//	if (zeroIndexes.length > 0)
//	{
//		if (confirm("You have items with a quantity of zero, would you like these to be deleted?"))
//		{
//			//delete the rows with zero-quantity items
//			//for (var index in zeroIndexes)
//			for (var i = zeroIndexes.length-1;i>=0;i--)
//			{
//				//this is the row we will delete
//				var theRow = document.getElementById(id).rows[zeroIndexes[i]];
////				var inputs = theRow.getElementsByTagName("input");
////				var theCheckbox = inputs[inputs.length-1];
////				if (!theCheckbox.checked)
////					theCheckbox.click();
//				
//				//findthe validator for this row's incrementer control
//				var oldID = theRow.getElementsByTagName("input")[0].id;
//				var newID = oldID.replace(oldID.match(/[^_]+$/), "compIncrementer");
//				
//				//disable the validator for the incrementer control in the row we're gonna delete
//				ValidatorEnable(document.getElementById(newID), false);
//				
//				//Check the 'delete' check box
//				var row = document.getElementById(id).rows[zeroIndexes[i]];
//				row.cells[row.cells.length-1].getElementsByTagName("input")[0].checked = true;
//				//document.getElementById(id).deleteRow(zeroIndexes[i]);
//			}
//			args.IsValid = true;
//		}
//		else
//		{
//			args.IsValid = false;
//		}
//	}
}



//
//		BRAND AND TYPE FILTERS
//
/////////////////////////////////
/*
//moved to genericCheckList.js
function selectAll(e)
{
	var tgt = e.srcElement || e.target;
	
	//get at the UL parent
	var ul = tgt.parentElement.parentElement;
	try
	{
		//select all its input controls
		var inputs = ul.getElementsByTagName("input");
		for (var i = 0;i<inputs.length;i++)
		{
			inputs[i].checked = true;
		}
	}
	catch (e)
	{
		//
	}
	finally
	{
		XBElem.prototype.cancelEventDefault(e);
	}

}

function deselectAll(e)
{
	var tgt = e.srcElement || e.target;
	
	//get at the UL parent
	var ul = tgt.parentElement.parentElement;
	try
	{
		//select all its input controls
		var inputs = ul.getElementsByTagName("input");
		for (var i = 0;i<inputs.length;i++)
		{
			inputs[i].checked = false;
		}
	}
	catch (e)
	{
		//
	}
	finally
	{
		XBElem.prototype.cancelEventDefault(e);
	}
}*/



//
//		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.");
	}
}