/*******************************************************/
/********** BEHAVIOUR CODE FOR ATTACHING JSCRIPT *******/
/**********  TO HTML WITH SPECIAL FUNCTIONALITY	********/
/*******************************************************/
//Examples:	<IMG src="images/test.jpg" class="rolloverImage"/>
//		<A href="/some/test/page.htm" class="siteNavigationLink">Click Me</A>

var isIE = (/MSIE/.test(navigator.userAgent));

var websiteRules = {
	'IMG.rolloverImage': function(image){
		image.onmouseover = function(){turnImageOn(image);};
		image.onmouseout = function(){turnImageOff(image);};				
	},
	
	'IMG.galleryImage': function(image){
		var titleNode = '';
		try{	
			titleNode = image.parentNode.nextSibling;
			(titleNode.nodeName == '#text') ? titleNode = titleNode.nextSibling : '';
		}catch(e){}
		
		image.onclick = function(){document.getElementById('galleryLargeImage').src = image.src.replace('sm', 'lg');};
		
		image.onmouseover = function(){
							try{showtrail(image.src.replace('sm', 'lg'),titleNode.innerHTML);}catch(e){}
							image.style.borderColor = '#33CCFF';};
		image.onmouseout = function(){
							try{hidetrail();}catch(e){}
							image.style.borderColor = '#FFFFFF';};
	},
		
	
	'#formSubmissionControl': function(control){control.onclick = function(){document.getElementById('mainForm').submit();};},
	
	'#bannerSwapImage': function(image){image.src = image.src.replace('00', '0' + ((new Date()).getMinutes() % 6) );},
	
	'#homePageFeatureImage': function(image){image.src = image.src.replace('00', '0' + ((new Date()).getMinutes() % 6) );},
	
	'#sideNavigationSpacer': function(spacer){
		var accumulatedHeight = parseInt(document.getElementById('sideNavigationEndCap').offsetHeight) - (isIE?17:0);
				
		if(document.getElementById('introductoryNavigationSection') != null){
			accumulatedHeight += parseInt(document.getElementById('introductoryNavigationSection').offsetHeight);
			document.getElementById('stoneNavigationContainer').style.top = parseInt(document.getElementById('introductoryNavigationSection').offsetHeight) + 'px';
		}
		
		if(parseInt(document.getElementById('pageMainBody').offsetHeight) > accumulatedHeight){
			spacer.style.height = (parseInt(document.getElementById('pageMainBody').offsetHeight) - accumulatedHeight) + 'px';
		}
	},
	
	'.sideNavigationItem': function(navItem){
		var children = navItem.getElementsByTagName('DIV');
		var controller = null;
		var subNav = null;
		for(var i = 0; i < children.length; i++){
			if(children[i].className == 'sideNavigationController'){
				controller = children[i];	
			}else if(children[i].className == 'sideSubNavigation'){
				subNav = children[i];
			}
			if(controller != null && subNav != null){break;}
		}
		
		if(controller != null && subNav != null){
			controller.onclick = function(){
								var allSubNavigations = document.getElementsByClassName('sideSubNavigation');	
								for(var i = 0; i < allSubNavigations.length; i++){
									if(allSubNavigations[i] != subNav){allSubNavigations[i].style.display = 'none';}
								}
								subNav.style.display = (subNav.style.display=='block')?'none':'block';
							};
		}		
	},
	
	'.selection': function(selection){
		selection.onmouseover = function(){selection.className = 'selectionHover';};
		selection.onmouseout = function(){selection.className = 'selection';};
		selection.onclick = function(){
								var selectionChildren = selection.getElementsByTagName('DIV');	
								for(var i = 0; i < selectionChildren.length; i++){
									if(selectionChildren[i].className == 'stone'){
										document.getElementById('stoneImage').src = 'images/granite/compare/g-' + selectionChildren[i].id + '.jpg';
										document.getElementById('stoneTitle').innerHTML = (isIE)?selectionChildren[i].innerText:selectionChildren[i].textContent;	
									}else if(selectionChildren[i].className == 'cabinet'){
										document.getElementById('cabinetImage').src = 'images/granite/compare/c-' + selectionChildren[i].id + '.jpg';
										document.getElementById('cabinetTitle').innerHTML = (isIE)?selectionChildren[i].innerText:selectionChildren[i].textContent;
									}		
								}			
							};
	},
	
	
	
	'.individualSampleContainer': function(container){
		container.onclick = function(){document.getSubElementsByClassName(document.getElementById('largeSampleContainer'), 'title')[0].innerHTML = document.getSubElementsByClassName(container, 'title')[0].innerHTML;}
	}
};

try{
	Behaviour.register(websiteRules);
}catch(e){
	//Happened because the behaviour script is not loaded yet
	//Attempt to register after the page finishes loading
	if(document.attachEvent){
		document.attachEvent('onload', new Function('try{Behaviour.register(websiteRules);}catch(e){}'));
	}else{
		document.addEventListener('load', new Function('try{Behaviour.register(websiteRules);}catch(e){}'), true);
	}
}
	



/*******************************************************/
/**************** DOM EXTENSION FUNCTIONS  *************/
/*******************************************************/

document.getElementsByClassName = function(className){return document.getSubElementsByClassName(document, className);}
			
document.getSubElementsByClassName = function(parentElement, className){
			var returnElements = new Array();
			var classExpression = new RegExp('\\b'+className+'\\b');
			var pageElements = parentElement.getElementsByTagName('*');

			for(var i = 0; i < pageElements.length; i++){
				var currentClassName = pageElements[i].className;
				if(classExpression.test(currentClassName)){returnElements.push(pageElements[i]);}
			}
			return returnElements;}
			
document.getElementsByName = function(name){
			var returnElements = new Array();
			var nameExpression = new RegExp('\\b'+name+'\\b');
			var pageElements = document.getElementsByTagName('*');

			for(var i = 0; i < pageElements.length; i++){
				var currentName = pageElements[i].getAttribute('name');
				if(nameExpression.test(currentName)){returnElements.push(pageElements[i]);}
			}
			return returnElements;}
			
document.deepAppendChildNode = function(destContainingNode, srcNode){
			var newNode = destContainingNode.ownerDocument.createElement(srcNode.nodeName);
			if(srcNode.selectSingleNode("text()") != null){
				newNode.text = srcNode.selectSingleNode("text()").nodeValue;}
			destContainingNode.appendChild(newNode);
			if(srcNode.childNodes.length > 0){
				for(var i = 0; i < srcNode.childNodes.length; i++){
					if(srcNode.childNodes[i].nodeName != "#text"){deepAppendChildNode(newNode, srcNode.childNodes[i]);}
				}
			}			
		}
			


/*******************************************************/
/**********   EVENT EXTENSION FUNCTIONS  ***************/
/*******************************************************/
if(!isIE){
	Event.prototype.__defineSetter__("cancelBubble", function (b) {
	if (b) this.stopPropagation();
	});

	Event.prototype.__defineSetter__("returnValue", function (b) {
	if (!b) this.preventDefault();
	});
}


/*******************************************************/
/**********   ARRAY EXTENSION FUNCTIONS  ***************/
/*******************************************************/
Array.prototype.resizeArray = function(array, removalStartIndex, itemsToRemove){
	var returnArray = new Array();
	
	//Duplicate everything before the removal index
	for(var i = 0; i < removalStartIndex; i++){returnArray[i] = array[i];}
	
	//Duplicate everything after the removal index + the removal item count
	for(var i = (removalStartIndex + itemsToRemove); i < array.length; i++){returnArray[returnArray.length] = array[i];}
	
	return returnArray;
}




/*******************************************************/
/**************  TAB PAGE CONTROLS *********************/
/*******************************************************/
function showTabPage(e){
	if(e == null){e = window.event;}
	
	var currentTab = (e.srcElement) ? e.srcElement : e.currentTarget;
	
	//The tabPageControl is always 2 elements removed from the tab
	var tabPageControl = currentTab.parentNode.parentNode;
	
	//Deselect all tabs
	for(var i = 0; i < tabPageControl.childNodes.length; i++){
		if(tabPageControl.childNodes[i].nodeType == 1){
			if(tabPageControl.childNodes[i].className == 'selectedTabPage'){
				tabPageControl.childNodes[i].className = 'tabPage';
			}
		}
	}
	
	//Select the current tab
	currentTab.parentNode.className = 'selectedTabPage';	
}




/*******************************************************/
/**************  COOKY HANDLING FUNCTIONS **************/
/*******************************************************/
function setDocumentCookie( oDoc, sName, sValue ){
    if(sName.length < 1){return;}

    if(0 < sValue.length){
        var expDate = new Date();
        expDate.setTime(expDate.getTime() + 365*24*60*60*1000);
        oDoc.cookie = ""+sName+"="+sValue+"; path=/; "+"expires="+expDate.toGMTString();                        
    }else{oDoc.cookie = sName + "=";}
}

function setNamedCookie(sName, sValue){setDocumentCookie(document,sName,sValue);}
function deleteDocumentCookie(oDoc, sName){oDoc.cookie = sName+"=";}
function deleteCookie(sName){deleteDocumentCookie(document, sName);}

function fetchNamedCookie(sName){return fetchDocumentCookie(document, sName);}
function fetchDocumentCookie(oDoc, sName){
    var sValue = "";
    var index = 0;
    
    if(oDoc.cookie){index = oDoc.cookie.indexOf(sName+"=");
    }else{index = -1;}
    
    if(index < 0){sValue = "";
    }else{
        var countbegin = (oDoc.cookie.indexOf("=", index) + 1);
        if(0 < countbegin){
            var countend = oDoc.cookie.indexOf(";", countbegin);
            if(countend < 0){countend = oDoc.cookie.length;}
            sValue = oDoc.cookie.substring(countbegin, countend);
        }else{sValue = "";}
    }
    return sValue;
}
			
			
				
/***************************************
	toggleImage
	
	Function used to swap the images of the supplied element depending on its current file name
	If it does not have "_over" in the file name, the supplied element image will be set to the same file with "_over" added to the name
	If it has "_over" in the file name, the supplied element image will be set to the the same file without the "_over" added to the name

	@image an image
***************************************/

function toggleImage(image){
	try{
		var source = new String(image.src);

		if(source.indexOf('_over') > 0){
			turnImageOff(image);
		}else if(!(source.indexOf('_over') > 0)){
			turnImageOn(image);}	
	}catch(e){
		alert('There was an error while swapping the image for an element. \n ' + e.message);}
}

function turnImageOff(image){
	try{
		var source = new String(image.src);
		if(!(source.indexOf('_over') > 0)){return;}
		var extension = new String(source.substring(source.lastIndexOf('.'), source.length));
		image.src = source.substring(0, source.indexOf('_over')) + extension;
	}catch(e){
		alert('There was an error while swapping the image for an element. \n ' + e.message);}
}

function turnImageOn(image){
	try{		
		var source = new String(image.src);
		if(source.indexOf('_over') > 0){return;}
		var extension = new String(source.substring(source.lastIndexOf('.'), source.length));
		image.src = source.substring(0, source.indexOf(extension)) + '_over' + extension;
	}catch(e){
		alert('There was an error while swapping the image for an element. \n ' + e.message);}
}








			
			
			


/*******************************************************/
/******************  DHTML SCROLL BOX ******************/
/*******************************************************/

var scrollUpInterval = 15;
var scrollDownInterval = 20;
var scrollTimer;
		
			
			/*
				Gallery item swapping functions
			*/
			
			
			

			function changeItemDetail()
			{
				//Get a reference to the source element
				var source = window.event.srcElement;

				//Get the image name and start chopping it up
				var imageName = source.src;

				//Get the image extension
				var extension = imageName.substring(imageName.lastIndexOf('.'), imageName.length);

				//Get the base portion of the image path and image name
				var imageBaseName = imageName.substring(0, imageName.lastIndexOf('_', imageName.lastIndexOf('_') - 1));

				//Get a reference to the itemDetailText and ItemDetailImage tags
				var lgText = document.all['ItemDetailText'];
				var lgImage = document.all['ItemDetailImage'];

				lgText.src = imageBaseName + '_text_lg' + extension;
				lgImage.src = imageBaseName + '_item_lg' + extension;
			}
			
			function changeItemColor(color)
			{
				//Get a reference to the item image holder
				var image = document.all['itemImageHolder'];
				
				//Get the base item name and extension
				var baseItemName = image.src.substring(0, image.src.indexOf('_') + 1);
				var extension = image.src.substring(image.src.lastIndexOf('.'));
								
				//Swap to the selected color
				image.src = baseItemName + color + extension
			}		
			
			function changeCategoryItem(itemName)
			{
				//Get a reference to the item image holder
				var image = document.all['itemImageHolder'];
				
				//Get the base item name and extension
				var baseItemName = image.src.substring(0, image.src.lastIndexOf('/') + 1);
				var extension = image.src.substring(image.src.lastIndexOf('_'));
								
				//Swap to the selected item name
				image.src = baseItemName + itemName + extension			
			}
				
			
			
			
			
			
			
			
			/*
				Scroll box functions
			*/
	
	
			function scrollUp()
			{
				var scroller = document.all('content');
				var top = (isNaN(parseInt(scroller.style.top))) ? 50 : parseInt(scroller.style.top);
				
				if(scrollTimer != undefined)
				{
					window.clearInterval(scrollTimer);
				}
				
				if(top <= 50)
				{
					scroller.style.top = top + 1;
					scrollTimer = window.setInterval("scrollUp()", scrollUpInterval);
				}
				else
				{
					scroller.style.top = 50;
				}
			}
			
			function scrollDown()
			{
				var scroller = document.all('content');
				var top = (isNaN(parseInt(scroller.style.top))) ? 50 : parseInt(scroller.style.top);
				
				if(scrollTimer != undefined)
				{
					window.clearInterval(scrollTimer);
				}
				
				if(top+scroller.clientHeight > 170)
				{
					scroller.style.top = top - 1;
					scrollTimer = window.setInterval("scrollDown()", scrollDownInterval);
				}
				else
				{
					scroller.style.top = -(scroller.clientHeight - 170);
				}
			}
