// JavaScript Document
$(window).resize(redrawHolder);

function redrawHolder() {
	var windowHeight = (window.innerHeight || document.documentElement.clientHeight) / 2;
	var height = $("#container").height()/2+30;
	$("#container").css("top",(windowHeight-height));
	var curPage = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
	curPage = curPage.replace(".asp","");
	if (curPage == "furniture") { //check to see if q is passed - compress JS errors (collectionItemsArray is not defined error)
		rebuildPaging();	
	}
	resetScrollers();
}

function rebuildPaging() {
	
	$("div").remove(".collectionItem");
	$("div").remove(".collectionRow");

	var holderWidth = $("#collectionHolder").width();
	var itemWidth = 200+55;
	var itemsOnAPage = Math.floor(holderWidth / itemWidth)*2; //two rows
	var pages = Math.ceil(collectionItemsArray.length / itemsOnAPage);

	pageItems = collectionItemsArray.slice((itemsOnAPage*(currentPage-1)),(itemsOnAPage*currentPage));
		
	for (var i = 0; i < itemsOnAPage; i++) {
		if (i == 0 || i == Math.ceil(itemsOnAPage/2)) {
			newRow = document.createElement("div");
			newRow.className = "collectionRow";
			$(newRow).insertBefore('#collectionLoading');
		}
		$(newRow).append(pageItems[i])
	}
	
	//go to itemsOnOnePage / 2 and then break onto new line
	if ($('#collectionPaging').find("ul")) {
		$('#collectionPaging').find("ul").remove();
	}
	if (pages > 1) {
		$('#pagesText').show();
		pagingUL = document.getElementById("collectionPaging").appendChild(document.createElement("UL"))
		for (i = 1; i <= pages; i++) {
			pagingLI = pagingUL.appendChild(document.createElement("LI"));
			if (i == currentPage) pagingLI.className = "active";
			pagingAnchor = pagingLI.appendChild(document.createElement("A"));
			pagingAnchor.innerHTML = i;
			if (document.all) {
				pagingAnchor.href = "javascript:void(0);slideToPage(this,"+i+")";
			} else {
				pagingAnchor.href = "javascript:void(0);";
				pagingAnchor.setAttribute("onclick","slideToPage(this,"+i+")")
			}
		} 
	} else {
		$('#pagesText').hide();
	}
}

function slideToPage(aEl,pageID) {
	$('#collectionLoading').fadeIn("slow", function() {
		pages = $(aEl).parent().siblings()
		currentPage = pageID;
		rebuildPaging();
		for(var i = 0; i < pages.length; i++) {
			if (pages[i].nodeName == "LI") {
				if ($(pages[i]).attr("class") == "active") currentPage = parseInt($(pages[i]).find("a").html());
				$(pages[i]).removeClass("active");
			}
		}
		$(aEl).parent().addClass("active");
		setTimeout("collectionsFadeOut()",500);
	});
}

function resetScrollers() 
{
	if (typeof $('.scrollContainer').children()[0] !== "undefined") {
		ocontainer = $('div.scrollContainer');
		ocontent = $('div.scrollContent');
		$('.scrollIndicator').html('<img src="/images/layout/scrollup.gif" alt="" border="0" />');
		containerSize = jQuery.iUtil.getSize(ocontainer.get(0));
		containerPosition = jQuery.iUtil.getPosition(ocontainer.get(0));
		containerInner = jQuery.iUtil.getClient(ocontainer.get(0));
		
		contentSize = jQuery.iUtil.getSize(ocontent.get(0));
		
		$('div.scrollScroller')
			//.css('top', containerPosition.y + 'px')
			//.css('left', containerPosition.x + containerSize.wb + 'px')
			.css('height', containerSize.hb + 'px');
		
		spaceToScroll = contentSize.hb - containerInner.h;
		
		$('div.scrollIndicator')
			.css('height', containerInner.h * containerSize.hb / contentSize.hb + 'px')
		
		$('.scrollScroller').Slider(
			{
				accept : '.scrollIndicator',
				onSlide : function( cordx, cordy, x , y)
				{
					ocontent
						.css('top', - spaceToScroll * cordy / 100 + 'px');
				}
			}
		);
	}
}

function navHover(imgEl) {
	imgEl.src = imgEl.src.replace(".gif","_h.gif");
}

function navOut(imgEl) {
	imgEl.src = imgEl.src.replace("_h.gif",".gif");
}

function openSubNav(liEl) {
	var subNav = $(liEl).children().filter("ul");
	$(subNav).toggle();
}
function closeCollectionSubNav() {
	$('#collectionsSubNav').hide();
}
function closeSpecsSubNav(collectionLiEl) {
	$('#specificationsSubNav').hide();
	$(collectionLiEl).children().filter("ul").show();
}
function toggleProductDetails() {
	var width = parseInt($('.productDetails').css("width"));
	if (width <= 0) {
		$('.productDetails').animate({ style: 'width:200px'  }, 1000, function() {
			document.getElementById("productDescTogImg").src = "/images/layout/productDescCollapse.gif";
			$('.scrollScroller').fadeIn(500);
		});
	} else {
		$('.productDetails').animate({ style: 'width:0px' }, 1000, function() {
			document.getElementById("productDescTogImg").src = "/images/layout/productDescExpand.gif";
			$('.scrollScroller').fadeOut(500);
		});
	}
}
function toggleProductSizes(imgObj) {
	$('#productSizes').BlindToggleVertically(700, 'easeout');
	if (imgObj.src.indexOf("sizesOpen") > -1) imgObj.src = "/images/layout/sizesClosed.gif"
	else imgObj.src = "/images/layout/sizesOpen.gif"
}

function checkForm(_frmEl,_checkType) 
{
	elOk = true;
	checkType = "";
	switch (_checkType)
	{
		case 0://submit form
			//get all form objects and evaluate all their onblur functions if any
			//submit form if all objects validate
			var elements = _frmEl.elements;
			for (var i = 0; i < elements.length; i++) {
				validationType = elements[i].getAttribute("onblur")
				if (validationType) { // if not null
					validationType = parseInt(validationType.split(",")[1]);
					checkForm(elements[i],validationType);
				}
			}
			if (elOk) return true
			else return false;
		break
		
		case 1://check not null
			checkType = "cannot be empty."
			if(_frmEl.value == "") elOk = false;
		break
		
		case 2://check is valid email
			checkType = "must be a valid email address."
			atPos = _frmEl.value.indexOf("@")
			dotPos = _frmEl.value.lastIndexOf(".")
			//check @ and a . exists and that the dot is at least one char after the @ sign
			if ((atPos < 1) || (dotPos - atPos < 2)) elOk = false;
			//**TODO ** check for invalid chars
		break
		
		case 3://check is numeric
			checkType = "must be a valid number."
			var validNum = /^-?\d+$/
			//if (_frmEl.value != validNum) elOk = false;
			if (!(validNum.test(_frmEl.value))) elOk = false;
		break
		
		case 4://check is checked
			checkType = ""
			if(_frmEl.checked == false) elOk = false;
		break
		
		default://else check not null
			checkType = "cannot be empty."
			if(_frmEl.value == "") elOk = false;
	}
	$(_frmEl).parent().find(".formError").remove(); // remove any prior alerts for this before potentially showing another err msg
													// for the same form object
	if (!(elOk)) { //form element didn't validate, show error msg
		//if (!frmEdited && document.getElementById("errorHolder") && initBySubmit) clearError()
		showValidationError(_frmEl,checkType);
	}
}

function showValidationError(_frmEl,errText) {
	alrtErr = _frmEl.parentNode.appendChild(document.createElement("div"));
	alrtErr.innerHTML = _frmEl.id.replace(/_/g,"&nbsp;") + " " + errText;
	alrtErr.className = "formError";
	$(alrtErr).fadeIn(500);
}

function showFurniture(collectionID) {
	var newAlert = new customAlert({ });
	newAlert.dataSource({ url: "/getFurniture.asp", data:"cid="+collectionID, container: newAlert });
	return false;
}

function showGoogleMap(divObj) {
	if (divObj.innerHTML.indexOf("Show") > -1) {
		divObj.innerHTML = "Hide Location Map";
		$('#googleMap').animate({ style: 'width:300px'  }, 1000, function(){
			//$('#googleMap').fadeIn(500);
		});
	} else { divObj.innerHTML = "Show Location Map";
		$('#googleMap').animate({ style: 'width:0px'  }, 1000, function(){
			$('#googleMap').fadeOut(500);
		});
	}
}

function productZoom(show) {
	if (show) {
		$('#productZoom').show();
		$('#productZoomClose').show();
	} else {
		$('#productZoom').hide();
		$('#productZoomClose').hide();
	}
}

function iframeLoader(page)
{
	var newWindow = window.open(page,'PFCollections','height=600,width=700,scrollbars=yes');
}

function getElementsByClassName(oElm, strTagName, strClassName)
{
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/-/g, "\-");
	//var oRegExp = new RegExp("(^|\s)" + strClassName + "(\s|$)");
	var oRegExp = new RegExp("\\b" + strClassName + "\\b");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

var ImageHover = {
	options 	: { 
		images : new Array() 
	},
	init		: function( options )
	{
		iterator = 0;
		currentPage = ImageHover.getPage( window.location );
		jQuery( options.imgClass )
		.each(
			function()
			{
				originalSrc = jQuery( this ).attr("src");
				linkTo = ImageHover.getPage( jQuery( this ).parent().attr("href") );
				
				if ( linkTo !== currentPage )
				{	// if not on current page
					if ( originalSrc.indexOf( options.imgHoverSuffix ) < 0 )
					{	// if the image currently is not in its hover or active state, perform js binding and image preloading
						newSrc =  originalSrc.replace( options.imgSuffix , options.imgHoverSuffix);
						newImage = new Image();
						newImage.src = newSrc;
						ImageHover.options.images.push( new Array(originalSrc, newImage) ); //store the preloaded image in the array
						jQuery( this )
							.bind("mouseover", {arrayEl: iterator }, function(event)
							{
								jQuery( this ).attr( "src", ImageHover.options.images[event.data.arrayEl][1].src );
							})
							.bind("mouseout", {arrayEl: iterator }, function(event)
							{
								jQuery( this ).attr( "src", ImageHover.options.images[event.data.arrayEl][0] );
							})
						iterator++;
					}
				}
				else
				{	//change url to be in active state
					jQuery( this ).attr("src", originalSrc.replace( options.imgSuffix , options.imgActive ) );
				}
			}
		);
	},
	getPage		: function( parsePage )
	{
		_currentPage = String(parsePage).split("/");
		_currentPage = _currentPage[_currentPage.length-1];
		_currentPage = String(_currentPage).split(".")[0];
		return String(_currentPage);
	}
}