
var loc = document.location + ""
var alpha="abcdefghijklmnopqrstuvwxyz"
var panelPosition = 0
var colCount = 1
var catTimer
var lastPanel
var panelOpening = 0
var panelTimer
var ddTimer
var scrollPages
var previewLoading=0
var previewTimer
var basketTimer
var jumping = 0
var subPanelTimer
var quickTimer
var lastPid
var quickLoading = 0
//hide lists - these are used to populate the category slide-down panel



function findPos(obj) {
	//find coordinates of a DIV
	var badBrowser = (/MSIE ((5\.5)|6|7|8)/.test(navigator.userAgent) && navigator.platform == "Win32");
	if (badBrowser) {
		var altPos = jQuery("#"+$(obj).id).offset()
		return [altPos.left, altPos.top]
	}

	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}

	return [curleft,curtop];
}


function columnify(element) {

	if(!$(element)) {
		return;
	}
	var master = $(element).select('li').toArray()
	var list = $(element).down('ul')

	var oldtop = element.style.top
	//element.style.top="-9999px"
	element.show()

	var myWidth = 125 //list.getWidth()+40
	var myHeight = $(element).getHeight()

	var output ="<ul>"
	for(var x=0;x<9;x++) {
		output = output + "<li>" + master[x].innerHTML + "</li>"
	}
	output = output + "</ul><ul>"
	var cc = 10
	for(var x=9;x<master.length;x++) {
		output = output + "<li>" + master[x].innerHTML + "</li>"
		cc--
		if(cc==0) {
			cc = 10
			output = output + "</ul>"
			if(x<master.length) {
				output = output + "<ul>"
			}
		}

	}
	output = output + "</ul>"
	element.update(output)
	if(1==2) {
	element.down('.wrapper').update(output)
	element.down('.wrapper').style.height=(myHeight-30)+"px"
	element.down('.wrapper').style.width=(myWidth*($(element).select('ul').length+1))+"px"
	}
	element.style.top=oldtop
	element.hide()

}


function TH_SubscribeNews(){
	var email = $("subscribeEmail").value.trim();
	if(email.trim()!="" && email != "enter your email address"){
		//sitescripts.js
		var retVal = SubscribeNews(email,-1);
		if(retVal){
			alert("Subscribed!");
		}
	}
}

function subscribeEmailFocus(){
    $("subscribeEmail").value = '';
	$("subscribeEmail").style.color = '#474747'; //put hardcoded, didn't work with add/remove class
}

function subscribeEmailBlur(){
	if($('subscribeEmail').value.trim()=='') {
		$("subscribeEmail").style.color = '#d0d0d0';
		$('subscribeEmail').value='enter your email address';
	}
}

function searchFocus() {
	//change appearance of search box on focus
	if($('searchField').value=='Search for a product') {
		$('searchField').value='';
	}
	$('searchField').removeClassName('searchInactive');
	$('searchField').addClassName('searchActive');
}


function emailFocus() {
    //change appearance of search box on focus
    if($('emailField').value=='Email Address') {
        $('emailField').value='';
    }
    $('emailField').removeClassName('emailInactive');
    $('emailField').addClassName('emailActive');
	$('emailField').style.color = '#000000';
}

function emailBlur(){
    if($('emailField').value=='') {
        $('emailField').value='Email Address';
		$('emailField').style.color = '#ADADAD';
    }
}

function searchBlur(){
	//change appearance of search box on blur
	if($('searchField').value.trim()=='') {
		$('searchField').value='Search for a product';
	}
}

function subPanelShow(evt) {
	$('menu').select('.subMenu').each(function(element) {
		element.hide()
	})

	clearTimeout(subPanelTimer)
	element = Event.element(evt);
	new Effect.Appear($(element).up().next('.subMenu'),{duration:0.2})
}

function subPanelOut(evt) {
	var element = Event.element(evt);
	element.removeClassName('open');
	element.up().removeClassName('open');
	subPanelTimer = window.setTimeout(function() {subPanelHide()},400)
}

function subPanelHide() {
	$('menu').select('ul li div.subMenu').each(function(element) {
		if(!element.hasClassName('open')) {
			element.hide()
		}
	})
}

function showPanel(panelName,element) {

	//display category panel

	// this re-writes the HTML of the long list of categories
	// into 8-item chunks so they fit nicely in the panel


	//hide mini cart if open
	if($('miniCart')) {
		if($('miniCart').visible()) {
			$('miniCart').hide()
			if($('miniCartShadow')) {
				$('miniCartShadow').hide()
			}
		}
	}

	$('subCategory').hide()

	clearTimeout(catTimer)
	if(panelOpening) {
		return;
	}

	$('menu').select('.active').each(function(element) {
		element.removeClassName('active')
	})
	$(element).addClassName('active')


	// if the panel is already open, close it and exit
	if($('navPanel').visible()&&lastPanel==panelName) {
		new Effect.BlindUp('navPanel',{duration:.4})
		if($('navPanelShadow')) {
			new Effect.BlindUp('navPanelShadow',{duration:.4})
		}
		return;
	}


	//start to build the panel
	var panelTitle = $(element).innerHTML.toLowerCase()
	panelOpening= 1
	panelPosition = 0
	colCount = 1
	var linksPerCol = 6
	var linkCount = 1

	$('panelTitle').innerHTML = panelTitle
	$('listHolder').innerHTML = ""
	$('catRight').innerHTML="view more"
	$('catLeft').innerHTML="go back"
	$('catLeft').hide()
	$('catRight').hide()
	$('listHolder').style.left="0px"



	var buildList
	// buildlist is the temporary element used to hold the HTML until it is
	// ready to be inserted into the DOM. It's faster this way.
	var menuName = "menu"


	var myPos = findPos($(menuName))
	$('navPanel').style.top = myPos[1]+$(menuName).getHeight()-10+'px'
	$('navPanel').style.left = myPos[0]+80+'px'

	//if the shadow doesn't exist, build it
	//if(!$('navPanelShadow')) {
		//$(document.body).insert(new Element('div',{id:'navPanelShadow',style:'display:none',className:'navPanelShadow'}))
	//}
	//$('navPanelShadow').style.top = $('navPanel').style.top
	//$('navPanelShadow').style.left = $('navPanel').style.left

	//reformat this into columns
	var listLength = $(panelName).select('li').toArray().length
	var catLinks = $(panelName).select('li').each(function(element) {
		//like lists of 8 items
		if(linkCount==1) {
			buildList="<ul>"
		}
		buildList = buildList + "<li>"+element.innerHTML+"</li>"
		linkCount++
		if(linkCount==8) {
			$('listHolder').insert(buildList+"</ul>")
			linkCount=1
			colCount++
		}
	})
	//output remaining links
	if(linkCount>1) {
		$('listHolder').insert(buildList+"</ul>")
	}



	//add alpha index if more than two pages
	var thisURL
	if(colCount>6) {
		if(!$('panelIndex')) {
			var tempIndex = new Element('div',{className:'panelIndex',id:'panelIndex'}).update("<span class='red'>jump to:</span> ")
			for(x=0;x<alpha.length;x++) {
				tempIndex.insert(new Element('a',{href:'javascript:panelJump("'+alpha.substr(x,1)+'")'}).update(alpha.substr(x,1)))
			}
			$('navPanel').insert(tempIndex)
		}
		else {
			$('panelIndex').show()
		}
	}
	else {
		if($('panelIndex')) {
			$('panelIndex').hide()
		}
	}


	//add page button if wider than three columns
	if(colCount>3) {
		$('catRight').show()
	}
	lastPanel = panelName
	if(!$('navPanel').visible()) {
		new Effect.BlindDown('navPanel',{duration:.4,afterFinish:function(){panelOpening=0;truncateItems()}})
		//new Effect.BlindDown('navPanelShadow',{duration:.4})
	}
	else {
		panelOpening=0
	}



}

function truncateItems() {
	//fix two-line items on navigation panel so they don't wrap to two lines
return;
	var myHeight
	var maxHeight = 17
	var limit = 50
	var attempts = 0

	$('listHolder').select('li').each(function(element) {
		//console.log("-"+element.getHeight()>maxHeight&&attempts<limit)
		while (element.getHeight()>maxHeight&&attempts<limit)  {
			var prodName = element.down().innerHTML.replace("&hellip;","")
			var prodNameArr = prodName.split(" ")
			var newName = ""
			for(var x=0;x<prodNameArr.length-2;x++) {
				newName = newName + prodNameArr[x]+" "
			}
			element.down().update(newName + prodNameArr[x]+"&hellip;")
			attempts++
		}
		if(attempts>0) {
			//we can add events for tooltip on the truncated items here

			//var myTip = new Element('div',{style:'display:none',className:'prodTip'}).update(origName)
			//$(document.body).insert(myTip)
			//$(element).observe('mouseover',prodShowTip.curry(myTip))
			//myTip.observe('mouseout',function(){this.hide();$('prodTipShadow').hide()})
		}
	})

}


function loadList(listName) {
	$('pageList').innerHTML="<ul>"+$(listName)+"</ul>"
}


function panelJump(letter) {
	//jump to correct column using alpha index
	//$('searchField').value = (letter)

	if(panelOpening==1) {
		return
	}
	panelOpening=1
	thisLetter = letter.toUpperCase()
	var found = 0
	var colCount = 1
	var foundLink


	//match the letter to the first character of the LI items
	$('listHolder').select('ul').each(function(element) {
		element.select('li').each(function(element) {
			thisLink = element.down(0).innerHTML
			if(thisLink.substr(0,1).toUpperCase()==thisLetter&&!found) {
				foundLink = element.down(0)
				found=colCount-1
			}
		})
		colCount++
	})

	if(found==0) {
		//go to previous letter
		for(x=1;x<alpha.length;x++) {
			if(alpha.substr(x,1).toUpperCase()==thisLetter) {
				panelOpening=0
				panelJump(alpha.substr(x-1,1))

				return
			}
		}
	}
	var curPos = parseInt($('listHolder').style.left.replace('px',''))
	//var newPos = -1*(found*200)+curPos
	if(found>colCount-4) {
		found = colCount-4
	}
	var newPos = -200*found
	if(letter=='A') {
		newPos = 0
	}
	//$('searchField').value = (found+", "+newPos+", "+curPos+":"+letter)
	new Effect.Move('listHolder',{mode:'absolute',x:newPos,fps:30,duration:.3,queue:'end',afterFinish:function(){panelOpening=0}})
	panelPosition=-1*found

	$('catRight').hide()
	$('catLeft').hide()
	if(newPos<0) {
		$('catRight').show()
		$('catLeft').show()
	}
	else {
		$('catRight').show()
	}

}


function panelScroll(direction) {
	return
	//this is the auto-scroll on the mouseover for the panel nav buttons
	if(direction==0) {
		clearTimeout(panelTimer)
	}
	else {
		panelTimer=window.setTimeout("panelMove("+direction+");panelScroll("+direction+");",1000)

	}
}

function panelMove(element,direction) {
	//animate categories nav pane


	clearTimeout(panelTimer)
	var wrapper = $(element).up('.subMenu')
	var navLeft = wrapper.down('.navLeft')
	var navRight = wrapper.down('.navRight')
	colMove = 166 //wrapper.down('ul').getWidth()
	var colCount = wrapper.select('ul').toArray()
	var colCount = colCount.length
	target = wrapper.down('.navPanel')
	$(navLeft).hide()

	var myPos = parseInt(target.getStyle('marginLeft').replace("px",""))
	if(direction==-1) {
		myPos = myPos - colMove
	}
	if(direction==1) {
		myPos = myPos + colMove
	}
	new Effect.Morph(target,{style:'margin-left:'+myPos+'px',duration:0.1})

	//change view more button state
	if(myPos<1) {
		$(navLeft).show()
		$(navRight).show()
	}
	

	if(myPos==0) {
		$(navLeft).hide()
		$(navRight).show()
		return;
	}
	
	// 2011.10.04 changed from -2 to -4 to show all categories under SubMenu "byBrand"
	if(wrapper.getWidth()+myPos<(colMove*-4)) {
		$(navRight).hide()
		$(navLeft).show()
	}


}

function closeCat() {

	//close categories nav panel
	if(panelOpening) {
		return;
	}
	//panelOpening=1

	catTimer= window.setTimeout(function() {
		if($('navPanelShadow')) {
			new Effect.BlindUp('navPanelShadow',{duration:.3})
		}
		if(!$('catLeft')) {
			return;
		}

		$('catRight').hide()
		$('menu').select('.active').each(function(element) {
			element.removeClassName('active')
		})
		new Effect.BlindUp('navPanel',{duration:.3,afterFinish:function(){panelOpening=0;}})
	},400)

}

function closeMiniCart() {
	//close the mini cart
	clearTimeout(basketTimer)
	new Effect.BlindUp('miniCartShadow',{duration:.1})
	new Effect.BlindUp('miniCart',{duration:.1})
	//$('miniCart').hide()
	//$('miniCartShadow').hide()
}

function miniCart() {
	//display mini cart
	if(jumping) {
		//animation is still running, come back later
		window.setTimeout("miniCart()",100)
		return
	}
	if($('navPanel').visible()) {
		$('navPanel').hide()
		if(!$('navPanelShadow')) {
			$('navPanelShadow').hide()
		}
	}
	if($('miniCart').visible()) {
		return;
	}

	if(!$('miniCartShadow')) {
		$(document.body).insert(new Element('div',{id:'miniCartShadow',style:'display:none',className:'miniCartShadow'}))
	}


	var myPos = findPos($('cartItems'))
	//$('searchField').value = myPos[0]+","+myPos[1]
	//$('searchField').value=myPos[1]
	$('miniCart').style.top = myPos[1]+18+'px'
	$('miniCart').style.left = myPos[0]+'px'
	$('miniCartShadow').style.top = $('miniCart').style.top
	$('miniCartShadow').style.left = $('miniCart').style.left
	$('miniCartShadow').style.height=$('miniCart').getHeight()+13+'px'

	new Effect.BlindDown('miniCartShadow',{duration:.3})
	new Effect.BlindDown('miniCart',{duration:.3})
	basketTimer = window.setTimeout("closeMiniCart()",6000)
}


function ddControl(evt) {
	//drop-down control renderer
	if(!$('ddHolder')) {
		$(document.body).insert(new Element('div',{id:'ddHolder',className:'ddItems'}))
		$(document.body).insert(new Element('div',{id:'ddShadow',className:'ddShadow'}))
	}
	var element = Event.element(evt);
	var myParent = element.id
	var ddLimit=10
	var ddCount=1
	var addMore = 0
	//assign temp list box
	var myList = $('ddHolder')

	//get current list
	myList.innerHTML = element.next().innerHTML

	//find position of myParent
	var myPos=findPos(element)


	//position the list box
	myList.style.top = myPos[1]+18+'px'
	myList.style.left = myPos[0]+'px'
	$('ddShadow').style.top = myPos[1]+18+'px'
	$('ddShadow').style.left = myPos[0]+'px'




	listLength = myList.select('li').toArray().length
	if(listLength>ddLimit) {
		//if this is a long list, build the slider instead
		$('ddHolder').stopObserving('mouseout',ddHideTimer)
		initSlider(listLength,myParent)
	}
	else {
		myList.style.width = $(myParent).getWidth()+'px'
		myList.style.overflowX = 'visible'
		myList.show()
		$('ddShadow').style.width = myList.getWidth()+3+'px'
		$('ddShadow').style.height = myList.getHeight()+1+'px'
		$('ddShadow').show()
		$('ddHolder').observe('mouseout',ddHideTimer)
		myList.select('li').each(function(element) {
			element.observe('mouseover',ddHover)
			element.observe('mouseout',ddHover)
			element.addClassName(myParent)
		})
	}

}

function ddHover(evt) {
	// mouseover event for the drop-down generator
	clearTimeout(ddTimer)

	var element = Event.element(evt);

	//if this is the anchor tag, change the outer LI tag.
	if(!element.down()) {
		element = element.up()
	}
	if(element.hasClassName('ddHover')) {
		element.removeClassName('ddHover')
	}
	else {
		element.addClassName('ddHover')
	}
}

function ddClear(evt) {
	// hide the drop-down

	clearTimeout(ddTimer)
}

function ddClick(evt) {
	//click event for the drop-down

	var element = Event.element(evt);
	if(element.down()) {
		element.click()
		return;
	}
	var myClass = $(element).classNames().toArray()
	//alert(myClass[0])
	$(myClass[0]).innerHTML = element.innerHTML
	$('ddShadow').hide()
	$('ddHolder').hide()

}

function ddHideTimer(evt) {
	//hide the drop-down

	var element = Event.element(evt);
	if(element.hasClassName('noClose')) {
		return
	}
	ddTimer=window.setTimeout("ddHide(0)",300)
}

function ddHide(evt) {
	$('ddShadow').hide()
	$('ddHolder').hide()

}




function initSlider(listLength,myParent) {
	// if the drop-down is long you can replace it with a slider control using this function

	clearTimeout(ddTimer)
	scrollPages = listLength
	var myPos=findPos($(myParent))
	var startValue = $(myParent).innerHTML/listLength
	var myList = $('ddHolder')
	var fudgeOffset=1

	// curse you, internet explorer!
	if(document.all) {
		fudgeOffset=-39
	}


	myList.style.width = '78px'

	$('ddShadow').style.width = '80px'
	$('ddShadow').style.height = '230px'

	myList.style.top = myPos[1]+18+'px'
	myList.style.left = myPos[0]+fudgeOffset+'px'


	$('ddShadow').style.top = myPos[1]+19+'px'
	$('ddShadow').style.left = myPos[0]+2+'px'


	myList.show()

	$('ddShadow').show()

	//build the HTML for the slider
	var panel = '<div class="scrollSlider" id="pageSlider">'
	panel = panel + "page <div id='pageStart' class='pageStart'>1</div> <div id='pageEnd' class='pageEnd'></div>"
	panel = panel + '<div id="pageTrack" class="scrollTrack noClose">'
	panel = panel + '<div id="pageHandle" class="scrollButton noClose"><div class="scrollIndicator noClose" id="pageIndicator">1</div></div>'
	panel = panel + '</div></div>'
	$('ddHolder').innerHTML=panel
	$('ddHolder').show()
	$('pageEnd').innerHTML = listLength
	$('pageIndicator').innerHTML = $(myParent).innerHTML

	//intialize the slider control
	new Control.Slider('pageHandle', 'pageTrack', {
		axis: 'vertical',
		onSlide: slideUpdate,
		onChange: slideSelect,
		sliderValue:startValue
	});


	//hook up the slider vents
	$('ddHolder').observe('mouseout',ddHideTimer)
	$('pageSlider').observe('mouseout',ddHideTimer)
	$('pageSlider').observe('mouseover',function(){$('pageSlider').stopObserving('mouseout',ddHideTimer)})
	$('pageTrack').observe('mouseover',ddClear)
	$('pageTrack').observe('mouseout',ddClear)
}

function slideUpdate(v) {
	//update page selection indicator beside the slider control
	var selPage = (parseInt(v*scrollPages))
	if(selPage<1) {
		selPage = 1
	}
	$('pageIndicator').innerHTML = selPage
}

function slideSelect(v) {
	//jump to page seleted by the slider
	var linkPath=''
	var selected = parseInt(v*scrollPages)
	if(selected<1) {
		selected = 1
	}
	if(selected+''==$('jupmpToPage').innerHTML) {
		return
	}

	$('jupmpToPage').innerHTML = selected
	$('jupmpToPage').next().select('a').each(function(element) {
		if(selected==element.innerHTML) {
			linkPath = element.href
		}
	})
	//$('searchField').value = linkPath
	$('ddShadow').hide()
	$('ddHolder').hide()
	document.location =linkPath
	//$('pageIndicator').innerHTML = 'selected: ' + (parseInt(v*scrollPages))
}


function prodShowTip() {
	// tolltip for long product names that are truncated.

	var myTip = arguments[0]
	var element = Event.element(arguments[1]);
	if(myTip.visible()) {
		return;
	}
	myPos = findPos(element)
	//alert(myPos[0]+", "+myPos[1])
	myTip.style.top = myPos[1]+'px'
	myTip.style.left = myPos[0]-30+'px'
	$('prodTipShadow').style.top=myPos[1]+5+'px'
	$('prodTipShadow').style.left=myPos[0]-23+'px'
	$('prodTipShadow').style.width = myTip.getWidth()+'px'
	$('prodTipShadow').style.height = myTip.getHeight()+'px'
	new Effect.Appear($('prodTipShadow'),{duration:.5})
	new Effect.Appear(myTip,{duration:.5})
	//myTip.show()

}


function leftLess(element) {
	//collapse left menu list
	var maxLeftList = 11
	var thisItem = 1
	var thisList = $(element).up()
	thisList.select('li').each(function(element) {
		if(thisItem>maxLeftList) {
			element.addClassName('hidden')
		}
		thisItem++
	})
	$(element).replace("<a href='javascript:;//' onclick='leftMore(this)'><strong>"+(thisItem-maxLeftList-1)+" more</strong></a>")
}

function leftMore(element) {
	//expand left menu list
	var myParent = $(element).up()
	var myHeight = myParent.getHeight()

	myParent.select('li').each(function(element) {
		element.removeClassName('hidden')
	})
	var newHeight = myParent.getHeight()
	myParent.addClassName('overflow')
	myParent.style.height = myHeight+'px'
	new Effect.Morph(myParent,{style:'height:'+newHeight+'px',fps:60,duration:.5,afterFinish:function(){myParent.style.height='';myParent.removeClassName('overflow')}})
	$(element).replace("<a href='javascript:;//' onclick='leftLess(this)'><strong>Collapse list</strong></a>")


}

function boxMore(element) {
	//expand left menu list
	var myParent = $(element).up()
	var myHeight = myParent.getHeight()

	myParent.select('li').each(function(element) {
		element.removeClassName('hidden')
	})
	var newHeight = myParent.getHeight()
	myParent.addClassName('overflow')
	myParent.style.height = myHeight+'px'
	new Effect.Morph(myParent,{style:'height:'+newHeight+'px',fps:60,duration:.5,afterFinish:function(){myParent.style.height='';myParent.removeClassName('overflow')}})
	$(element).replace("<a class='red' href='javascript:;//' onclick='boxLess(this)'>...collapse list</a>")

}

function boxLess(element) {
	//collapse left menu list
	var maxLeftList = 10
	var thisItem = 1
	var thisList = $(element).up()
	thisList.select('li').each(function(element) {
		if(thisItem>maxLeftList) {
			element.addClassName('hidden')
		}
		thisItem++
	})
	$(element).replace("<a class='topLink' href='javascript:;//' onclick='leftMore(this)'>View "+(thisItem-maxLeftList-1)+" similar products...</a>")
}


function customerServiceFormVal(element){

	if(document.csForm.cs_subjectList.selectedIndex != 0) {
		document.csForm.cs_other.value = document.csForm.cs_other.value + " "
	}
	document.csForm.cs_subject.value = document.csForm.cs_subjectList[document.csForm.cs_subjectList.selectedIndex].value + ' ' + document.csForm.cs_other.value;
	valForm(element)
	//document.csForm.cs_button.disabled = true;
	//document.csForm.cs_button.value = '- Sending Your Message -';
	//document.csForm.submit();
}

var minarray = new Array('min6');

function valForm(btn) {
	// this is a general-putpose form validation script
	// any form element with a class name of "req" will be checked
	// any invalid fields will be highlighted using the "formError" class

	thisform = $(btn).up('form')

	var firstElement = ''
	var formOK = 1
	$(thisform).select('.req').each(function(element) {
		if(element.selectedIndex) {
				//this is a select statement
				if(element.selectedIndex<1) {
					element.addClassName('formError')
					formOK = 0
					if(firstElement=='') {
						firstElement = element
					}
				}
				else {
					element.removeClassName('formError')
				}
			}
			else {
				//this is a text box
				if(element.value=="") {
					element.addClassName('formError')
					formOK = 0
					if(firstElement=='') {
						firstElement = element
					}
				}
				else {
					element.removeClassName('formError')
				}
			}
	})
	if(formOK) {

		var reqlen = 0;
		for (i=0; i<=minarray.length; i++)
		{
			$(thisform).select('.'+minarray[i]).each(function(element) {
				if(!element.selectedIndex) {
					//this is a text box
					reqlen = parseFloat(minarray[i].substring(minarray[i].length-1));
					if(element.value.length < reqlen || element.value.indexOf(" ")>-1) {
						element.addClassName('formError')
						formOK = 0
						if(firstElement=='') {
							firstElement = element
						}
					}
					else {
						element.removeClassName('formError')
					}
				}
			})

			if (formOK == 0)
			{
				var minlen = reqlen;
				break;
			}
		}

		if (formOK != 0)
		{
			//check first and last name
			$(thisform).select('.valname').each(function(element) {
				if(!element.selectedIndex) {
					//this is a text box
					if(validateName(element.value) == false) {
						element.addClassName('formError')
						formOK = 0
						if(firstElement=='') {
							firstElement = element
						}
					}
					else {
						element.removeClassName('formError')
					}
				}
			})
			if (formOK == 0)
			{
				new Effect.ScrollTo(firstElement,{duration:.6,offset:-240});
				showDialog(firstElement,'Invalid character found',"closeDialog()","");
				return false;
			}

			//check email
			$(thisform).select('.valemail').each(function(element) {
				if(!element.selectedIndex) {
					//this is a text box
					if(validateemail(element.value) == false) {
						element.addClassName('formError')
						formOK = 0
						if(firstElement=='') {
							firstElement = element
						}
					}
					else {
						element.removeClassName('formError')
					}
				}
			})

			if (formOK != 0)
			{
				if (thisform.action != '')
				{
					thisform.submit();
				}
				return true;
			}
			else
			{
				new Effect.ScrollTo(firstElement,{duration:.6,offset:-240});
				showDialog(firstElement,'Invalid email address',"closeDialog()","");
				return false;
			}
		}
		else
		{
			new Effect.ScrollTo(firstElement,{duration:.6,offset:-240});
			showDialog(firstElement,'This field requires a minimum of ' + minlen + ' characters<br />(no spaces)',"closeDialog()","");
			return false;
		}

	}
	else {
		new Effect.ScrollTo(firstElement,{duration:.6,offset:-240});
		showDialog(firstElement,'Please complete all required fields',"closeDialog()","");
		return false;
	}

}

function buttonEffect(btn) {
	return;
	if($(btn).hasClassName('buttonOver')) {
		$(btn).removeClassName('buttonOver')
		$(btn).down().removeClassName('buttonTextOver')
	}
	else {
		$(btn).addClassName('buttonOver')
		$(btn).down().addClassName('buttonTextOver')
	}
}

function showTip(element,thumb) {
	//this is the product mouse-over mini viewer for the basket pages.

	//if the image is still loading, quit
	if(previewLoading==1) {
		return
	}
	if(!$('prodThumb')) {
		$(document.body).insert(new Element('div',{id:'prodThumb',className:'prodThumb',style:'display:none'}))
	}

	if(thumb=='') {
		hideTip()
		return
	}

	previewLoading=1
	clearTimeout(previewTimer)
	$('prodThumb').stopObserving('mouseout',hideTip)
	$('prodThumb').innerHTML = "<img src='"+thumb+"'>"
	myPos = findPos($(element))
	myWidth = $(element).getWidth()
	$('prodThumb').style.top=myPos[1]-50+'px'
	$('prodThumb').style.left=myPos[0]+myWidth+'px'
	$('prodThumb').observe('mouseout',hideTip)
	$('prodThumb').observe('mouseover',tipTimer)
	new Effect.Appear('prodThumb',{duration:.5,beforeStart:function(){previewTimer = window.setTimeout("hideTip()",2000)},afterFinish:function(){previewLoading=0;}})

}

function hideTip() {
	// hide the mini product viewer

	$('prodThumb').hide()
}

function tipTimer() {
	clearTimeout(previewTimer)
}


//form buttons


function sch_MiniBasket(){
	//populate and open the mini basket


	if($('miniCart').visible()) {
		closeMiniCart();


		return;
	}



	new Ajax.Request('/ajax/ajaxShowMiniBasket.taf',
	{
		onSuccess: function(transport) {
			$('ajaxcartresponse').innerHTML = transport.responseText;
			$('miniCart').innerHTML = $('miniCartWrapper').innerHTML;

			var basketerror = $('basketerror');
			if (basketerror != null)
			{
				$('addtocartmsg').innerHTML = "";
				alert(basketerror.innerHTML);
			}
			else
			{

				//open it
				miniCart();
			}
		}
	});

	if($('miniCart').innerHTML!=''){

		miniCart();
		return;
	}


}

function sch_DisplayBasketTotals(basketquantity,basketprice){

	if(basketquantity=="") basketquantity = 0;
	if(basketprice=="") basketprice = 0.00;
	//$("basketquantity").innerHTML = basketquantity;
	$("basketprice").innerHTML = basketprice;
	/*
	$('miniCart').innerHTML = ""; //force to reload mini basket when click

	if(basketquantity==1) {
		$('basketItemsTitle').innerHTML = "item";
	}else{
		$('basketItemsTitle').innerHTML = "items";
	}*/
}


function jumpy() {
	//make the item jump off the page, into the cart.
	jumping = 1

	var basketTop = $('cartNav').viewportOffset().top
	if(basketTop<1) {
		new Effect.ScrollTo('root',{duration:.3,queue:'front'})
	}


	img = $('showimage')
	if(!$('jumpy')) {
		$(document.body).insert(new Element('div',{id:'jumpy',style:'position:absolute;display:none;border:1px solid #000000;z-index:999;'}).update(img.innerHTML))
	}
	//$('jumpy').clonePosition(img)
	$('jumpy').show()

	var myPos = findPos(img)
	x1 = myPos[0]
	y1 = myPos[1]
	var myPos = findPos($('cartNav'))
	x2 = myPos[0]+50
	y2 = myPos[1]+35

	new Effect.Curve('jumpy',{fps:60,duration:1,curve: new BezierCurve(
		x1, y1,
		x1+200, y1+200,
		x2, y2+200,
		x2, y2
	)});

	new Effect.Morph($('jumpy').down(),{duration:1,style:'height:5px;width:5px',afterFinish:function(){$('jumpy').remove();jumping=0}})
	new Effect.Fade($('jumpy'),{delay:.5,duration:.5})
	//window.setTimeout("Prod_MultiAddToBasketSC()",900)
}


function checkQTY() {
	var OK = 1
	var total = 0
	var firstElement = ''
	var inputs = 0
	$('productForm').select('input').each(function(element) {
		if(element.type=='text') {
			if(isNaN(element.value)||element.value=='')	{
				OK = 0
				element.addClassName('formError')
				firstElement=element
			}
			else {
				element.removeClassName('formError')
				total = total + parseInt(element.value)
			}
			inputs++
		}
	})


	//this pages uses a drop-down
	if($('productForm').select('select')) {
		$('productForm').select('select').each(function(element) {
			if(element.name=='Quantity') {
				OK = 1
				total = element.value
			}
		})
	}

	//2011.10.04
	//Can't add products to the cart if the product has options but there's none selected 
	if(jQuery('#productForm #pOptions ').length>0 && !jQuery('#productForm #pOptions .productOptionSelect:checked').length>0) {
		showDialog('','You will need to select an option to add this item to your cart.','closeDialog()','')
		return false;
	}


	if(OK&&total>0) {
		return true;
	}

	if(inputs==1) {
		showDialog(firstElement,'You will need to enter a quantity in order<br />to add this item to your cart.','closeDialog()','')
	}
	else {
		showDialog('','You will need to enter a quantity in order<br />to add this item to your cart.','closeDialog()','')
	}
	return false;
}


function Prod_MultiAddToBasket(){

		//style="line-height:4px;"
		$('addtocartmsg').innerHTML = '<br style="line-height:5px;"><img src="images/ajax_indicator_sm.gif" />';
		var myPos = findPos($('btnQuickAdd'))
		$('dialogCart').style.top = myPos[1]-50+'px'
		$('dialogCart').style.left = myPos[0]-150+'px'
		new Ajax.Request('/ajax/multiaddtobasket.taf',
		{
			parameters: $('productForm').serialize(true),
			onSuccess: function(transport) {
				$('ajaxcartresponse').innerHTML = transport.responseText;

				var basketerror = $('basketerror');
				if (basketerror != null)
				{
					$('addtocartmsg').innerHTML = "";
					alert(basketerror.innerHTML);
				}
				else
				{
					var cartresponse = $('addmsg').innerHTML;
					var totalprice = $('totalprice').innerHTML;
					var totalquantity = $('totalquantity').innerHTML;
					$('addtocartmsg').innerHTML = "<br style='line-height:5px;'>" + cartresponse;
					$('addtocartmsg').innerHTML = "";
					$('dialogCartMsg').innerHTML = cartresponse;
					Prod_AddOrOptionClose()

					jQuery('.dialogCart').fadeOut('medium');
					jQuery('#dialogCart').fadeIn('medium');

					$('basketquantity').innerHTML = totalquantity;
					$('basketprice').innerHTML = totalprice;
				}
			}
		});
}



function Prod_MultiAddToBasketSC(){
	// add products to basket
	//_DEBUD_MODE = true;
	clearTimeout(basketTimer)
	//initDialogCart();
	var origContent = $('addtocartmsg').previous().innerHTML



	if (checkQTY()) //ajaxproduct.js
	{

		//style="line-height:4px;"
		//$('addtocartmsg').innerHTML = '<br style="line-height:5px;"><img src="images/ajax_indicator_sm.gif" />';

		$('addtocartmsg').previous().observe('mouseout',function() {
			//$('searchField').value="###"
			$('addtocartmsg').previous().innerHTML = origContent
			$('addtocartmsg').previous().removeClassName('buttonAddToCartHover')

		})
		//$('addtocartmsg').previous().innerHTML="<div><img src='/Bus/B26/s1/siteskins/assets_1/Spinner.gif'></div>"
		jumpy()
		if(checkIE8()) {
			ajaxDelay = 600
		}
		else {
			ajaxDelay = 1
		}


		window.setTimeout(function(){
		new Ajax.Request('/ajax/multiAddToBasket.taf',
		{
			parameters: $('productForm').serialize(true),
			onSuccess: function(transport) {
				$('errorMessage').innerHTML = '';
				$('ajaxcartresponse').innerHTML = transport.responseText;
				$('addtocartmsg').previous().innerHTML=origContent;
					var cartresponse = $('addmsg').innerHTML;
					var totalprice = $('totalprice').innerHTML;
					var totalquantity = $('totalquantity').innerHTML;
					//$('basketquantity').innerHTML = '';
					//$('addtocartmsg').innerHTML = "";
					//$('miniCart').innerHTML = '';
					sch_MiniBasket();
					sch_DisplayBasketTotals(totalquantity,totalprice);

			}
		})
		},ajaxDelay)
	}
	else {
		$('overlay').hide()
	}

}


function Prod_SingleAddToBasketSC() {
	//initDialogCart();
	if(jQuery("input[name='productOptionSelect']:checked").length == 0)
	{
	   alert("Please select an option");
	   return;
	}
	if(isNaN($('BaseQuantity').value) || $('OP').selectedIndex < 1 ) {
		$('OP').addClassName('formError')
		Effect.Pulsate('OP', { pulses: 3, duration: 1.5 });
		window.setTimeout(function() {$('OP').removeClassName('formError')},2000)
		return;
	}

	// add products to basket
	//_DEBUD_MODE = true;
	clearTimeout(basketTimer)
	//initDialogCart();
	var origContent = $('addtocartmsg').previous().innerHTML
	if (checkQTY()) //ajaxproduct.js
	{
		//style="line-height:4px;"
		//$('addtocartmsg').innerHTML = '<br style="line-height:5px;"><img src="images/ajax_indicator_sm.gif" />';
		$('addtocartmsg').previous().observe('mouseout',function() {
			//$('searchField').value="###"
			$('addtocartmsg').previous().innerHTML = origContent
			$('addtocartmsg').previous().removeClassName('buttonAddToCartHover')
		})
		//$('addtocartmsg').previous().innerHTML="<div><img src='/Bus/B26/s1/siteskins/assets_1/Spinner.gif'></div>"
		jumpy()
		if(checkIE8()) {
			ajaxDelay = 600
		}
		else {
			ajaxDelay = 1
		}


		window.setTimeout(function(){
		new Ajax.Request('/ajax/multiAddToBasket.taf',
		{
			parameters: $('productForm').serialize(true),
			onSuccess: function(transport) {
				$('errorMessage').innerHTML = '';
				$('ajaxcartresponse').innerHTML = transport.responseText;
				$('addtocartmsg').previous().innerHTML=origContent
				var cartresponse = $('addmsg').innerHTML;
				var totalprice = $('totalprice').innerHTML;
				var totalquantity = $('totalquantity').innerHTML;
				//$('basketquantity').innerHTML = '';
				$('addtocartmsg').innerHTML = "";
				//$('miniCart').innerHTML = '';
				sch_MiniBasket();
				sch_DisplayBasketTotals(totalquantity,totalprice);
			}
		})
		},ajaxDelay)
	}
	else {
		$('overlay').hide()
	}
}

function printPage() {
	// this copies the main area to a hidden Iframe, then prints what's in the iframe
	if(!$('printWin')) {
		printWin = new Element('iframe',{name:'printWin',id:'printWin',src:'/Bus/B26/S1/SiteSkins/assets_1/PrintWindow.htm',style:'height:0px;width:0px;frameBorder:0'})
		$(document.body).insert(printWin)
	}
}

function postMailToFriend(){
	$('tellafriendnamereq').hide()
	$('tellafriendmsg').hide()
	$('tellafriendmsg').innerHTML = '';
	tEmail = document.sendToFriend.tEmail.value;
	yEmail = document.sendToFriend.yEmail.value;
	yName = document.sendToFriend.yName.value;
	//if (yName == '')
	//{
	//	$('tellafriendnamereq').show()
	//	return;
	//}
	friendMessage = document.sendToFriend.friendMessage.value;
	proid = document.sendToFriend.proid.value;
	if((tEmail!='') && (yEmail!='')){
		//mailToFriend = new Image();
		//mailToFriend.src= globalFilePath + 'tellAFriend.taf?tEmail=' + tEmail + '&yEmail=' + yEmail + '&yName=' + yName + '&friendMessage=' + friendMessage + '&proid=' + proid + '&' + globalUserKey;
		var url = globalFilePath + 'tellAFriend.taf?tEmail=' + tEmail + '&yEmail=' + yEmail + '&yName=' + yName + '&friendMessage=' + encodeURI(friendMessage) + '&proid=' + proid + '&' + globalUserKey;
		tellafriendAjax(url);
	}
}

function tellafriendAjax(url){
  	document.sendToFriend.bttnSendAFriend.value = "Sending...";
	document.sendToFriend.bttnSendAFriend.disabled = true;


	var xmlhttp = null;
	//var moment = new Date();
	//ts = moment.getHours() + '-' + moment.getMinutes() + '-' + moment.getSeconds() + '-' + moment.getMilliseconds();
	if (window.XMLHttpRequest){
		xmlhttp = new XMLHttpRequest();
	}else if (window.ActiveXObject){
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

	try {
		xmlhttp.open('POST',url,true);
		xmlhttp.onreadystatechange = function(){
			if(xmlhttp.readyState == 4){
				if(xmlhttp.status == 200){
					ShowDebugAjaxL(xmlhttp,url,'');
					document.sendToFriend.bttnSendAFriend.disabled = true;
      				document.sendToFriend.bttnSendAFriend.value = "Send Message";

					if(xmlhttp.responseText=='OK'){
						//alert('Your message has been sent');
						$('tellafriendmsg').innerHTML = 'Your message has been sent';
						$('tellafriendmsg').show();
					}else{
						//alert('Sorry, failed to send email');
						$('tellafriendmsg').innerHTML = 'Failed to send the message, please try again later';
						$('tellafriendmsg').show();
					}
				}
			}
		}
		xmlhttp.send('');
	}
	catch(e) {
		//alert(e)
		alert('Sorry, failed to send email.');
	}
}



//gift selector
var shopForBypass = 0
function shopFor(element) {
	var skip = false;
	var num

	clicked = $(element).id

	//show spinner
	myPos = findPos($(element))
	if(!$('loadSpinner')) {
		$(document.body).insert(new Element('div',{id:'loadSpinner',style:'position:absolute'}).update('<img src="'+imgPath+'SpinnerSmall.gif" />'))
	}
	$('loadSpinner').style.top = myPos[1]+2+'px'
	$('loadSpinner').style.left = myPos[0]+150+'px'
	$('loadSpinner').show()

	//clear second selection if first changes
	if(clicked=='SF1'&&$('SF2').selectedIndex<1) {
		$('SF2').length=1
	}


	//$('SFResponseIndicator').innerHTML="aaa<img src='/Bus/B26/s1/siteskins/assets_1/Spinner.gif'/>"
	if(document.SF.C.selectedIndex>0||shopForBypass==1) {
		var A = document.SF.A[document.SF.A.selectedIndex].value
		var B = document.SF.B[document.SF.B.selectedIndex].value
		var C = document.SF.C[document.SF.C.selectedIndex].value
		var Bt = ''
		var Ct = ''
		var Cp = ''
		var At = stripChars(document.SF.A[document.SF.A.selectedIndex].text).replace(" ","-")
			//alert(stripChars(document.SF.A[document.SF.A.selectedIndex].text));
			//alert(At);
		if(B!='') {
			Bt = stripChars(document.SF.B[document.SF.B.selectedIndex].text).replace(" ","-")
		}
		if(C!='') {
			Ct = stripChars(document.SF.C[document.SF.C.selectedIndex].text).replace(" ","-")
			Cp = Ct+"-"+C
		}

		//http://scholar.staging.moveable.com/products/Grade-5-530/Female-359/Dramatic-Play-491/
		document.location = "/products/"+At+"-"+A+"/"+Bt+"-"+B+"/"+Cp
		return
	}
	switch(clicked)
	{
		case 'SF1':
			document.SF.B.selectedIndex = 0;
			$('SF3').hide();
			num = 1
			if (document.SF.A.selectedIndex == 0)
			{
				$('SF2').hide();
				skip = true;
			}
			break;
		case 'SF2':
			num = 2
			if (document.SF.B.selectedIndex == 0)
				$('SF3').hide();
			break;
	}

	if (!skip)
	{

		var url = '/ajax/ShopFor.taf?'+$('SF').serialize()+"&num=" + num + "&now="+new Date()
		//x = prompt('',url)

		new Ajax.Updater('SFResponse', url,{evalScripts:true});
		//gid=1530&gid=1772&gid=1533
		//$('SFResponseIndicator').innerHTML="";
	}


}

function stripChars(txt) {
	return txt.replace(/[^a-zA-Z 0-9]+/g,'');

}

function shopForPopulate() {
	$('loadSpinner').hide()
	if($('SFRepsonseB')) {
		$('SF2').innerHTML = $('SFRepsonseB').innerHTML;
		//$('SF2c').innerHTML = $('SFResponseB').innerHTML;
		$('SF2').show()
		$('SFB').focus()
	}
	if($('SFRepsonseC')) {
		$('SF3').innerHTML = $('SFRepsonseC').innerHTML;
		//$('SF3c').innerHTML = $('SFRepsonseC').innerHTML;
		// if the thirs list is empty, go to the currently selected category.
		if($('SFC').length==1) {
			shopForBypass = 1
			shopFor($('SFB'))
			return;
		}
		$('SF3').show()
		$('SFC').focus()

	}

}


function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

function checkIE8() {
    var msg = "You're not using Windows Internet Explorer.";
    var ver = getInternetExplorerVersion();
    if (ver > -1) {
        if (ver >= 8.0)
            return true
        else
           return false
    }
}

function showDialog(element,msg,ok,cancel) {
	//this is the general-purpose replacement for javascript alerts


	if($(element)&&element!='') {
		//this dialog points to an element
		myPos = findPos($(element))
		$('dialog').style.top = myPos[1]-25+'px'
		//check to see if it's off the screen
		screenPos = findPos($('root'))

		if(myPos[0]+element.getWidth()+2+$('dialog').getWidth()>screenPos[0]+$('root').getWidth()) {
			$('dialog').style.left = myPos[0]+2+'px'
		}
		else {
			$('dialog').style.left = myPos[0]+element.getWidth()+2+'px'
		}
		$('dialogLeft').show()
		$(element).observe('click',stopDialog)
	}
	else {
		//this dialog is in the middle of the screen
		dOffsets = document.viewport.getScrollOffsets()
		$('overlay').style.height=$('root').getHeight()+'px'
		$('overlay').style.width=document.viewport.getWidth()+'px'
		$('dialog').style.top = dOffsets.top+250+'px'
		$('dialog').style.left = parseInt(document.viewport.getWidth()/2)-100+'px'
		$('overlay').show()
		$('dialogLeft').hide()
	}



	//hide both buttons
	$('dialogBtn1').hide()
	$('dialogBtn2').hide()
	if(ok!="") {
		$('dialogBtn1').observe('click',function(){eval("$('overlay').hide();$('dialog').hide();"+ok)})
		$('dialogBtn1').show()
	}
	if(cancel!="") {
		$('dialogBtn2').observe('click',function(){eval("$('overlay').hide();$('dialog').hide()"+cancel)})
		$('dialogBtn2').show()
	}
	$('dialogMsg').update(msg)

	new Effect.Appear('dialog',{duration:.5})
}

function closeDialog(element) {
     if (element)
	    $(element).hide();
	  else
        $('dialog').hide();
}

function stopDialog(evt) {
	//kill the click event and close the dialog
	var element = Event.element(evt);
	$(element).stopObserving('click',stopDialog)
	closeDialog()
}



function quickBillCopy(){
	document.addressForm.sameAsBilling.checked = true;
	matchBilling()
}

function matchBilling(){
	var af = document.addressForm
	af.sAddList.selectedIndex = 0;

	if(af.sameAsBilling.checked){

			af.scompany.value = af.bcompany.value;
			af.sadd1.value = af.badd1.value;
			af.sadd2.value = af.badd2.value;
			af.scity.value = af.bcity.value;
			af.szip.value = af.bzip.value;
			af.stel.value = af.btel.value;
			af.stele.value = af.btele.value;
			af.sfax.value = af.bfax.value;
			af.sfname.value = af.bfname.value;
			af.slname.value = af.blname.value;
			af.semail.value = af.bemail.value;
			//af.sstateId.selectedIndex = af.bstateId.selectedIndex;
			af.sCountryId.value = af.bCountryId.value;
			Checkout_PopulateStatesList(af.sCountryId.value,af.bstateId.value,'Shipping');

			/*if(document.addressForm.bAPO.checked == true){
				document.addressForm.sAPO.checked = true;
			}
			else{
				document.addressForm.sAPO.checked = false;
			}*/

	}
	else{
		af.scompany.value = '';
		af.sadd1.value = '';
		af.sadd2.value = '';
		af.scity.value = '';
		af.szip.value = '';
		af.stel.value = '';
		af.stele.value = '';
		af.sfax.value = '';
		af.sfname.value = '';
		af.slname.value = '';
		af.semail.value = '';
		af.sCountryId.value = '';
		Checkout_PopulateStatesList('','','Shipping');
		//document.addressForm.sAPO.checked = false;
	}
}

function validateemail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = email;
   if(reg.test(address) == false) {
      //alert('Invalid Email Address');
      return false;
   }
   else
	  return true;
}

function validateName(name) {
   var reg = /^([^-<>'"\?])+$/;
   var theName = name;
   if(reg.test(theName) == false) {
      //alert('Invalid Email Address');
      return false;
   }
   else
	  return true;
}

var _isAddFormSubmited= false;
function valAddForm(){
	if(_isAddFormSubmited) return;
	var stop = 0;
	var focusObj ='';
	var tel = 0;
	var reff = 0;
	var af = document.addressForm
	var msg = ""
	var firstElement=''

	var formOK=1
	$('root').select('.req').each(function(element) {
		if(element.selectedIndex) {
			//this is a select statement
			if(element.selectedIndex<1) {
				element.addClassName('formError')
				formOK = 0
				if(firstElement=='') {
					firstElement = element
				}
			}
			else {
				element.removeClassName('formError')
			}
		}
		else {
			//this is a text box
			if(element.value=="") {
				element.addClassName('formError')
				formOK = 0
				if(firstElement=='') {
					firstElement = element
				}
			}
			else {
				element.removeClassName('formError')
			}
		}
	})


	if(isZipFix(af.bzip,af.bCountryId.value)==false){
	   msg = msg + ('<br />Invalid Billing Zip Code');
	   formOK = 0
	   if(firstElement=='') {
			firstElement = element
		}
	}

	if(isZipFix(af.szip,af.sCountryId.value)==false){
		msg = msg + ('<br />Invalid Shipping  Zip Code');
		formOK = 0
		if(firstElement=='') {
			firstElement = element
		}
	}

	if(validateemail(af.bemail.value)==false){
		 msg = msg + ('<br />Invalid Billing Email Address');
		 formOK = 0
		 if(firstElement=='') {
			firstElement = element
		}
	}

	if(af.semail.value != '' && validateemail(af.semail.value)==false){
		 msg = msg + ('<br />Invalid Shipping Email Address');
		 formOK = 0
		 if(firstElement=='') {
			firstElement = element
		}
	}




	if((af.bsave.checked == true) && (af.ssave.checked == true)){
			if((af.scompany.value == af.bcompany.value) &&
				(af.sadd1.value == af.badd1.value) &&
				(af.sadd2.value == af.badd2.value) &&
				(af.scity.value == af.bcity.value) &&
				(af.szip.value == af.bzip.value) &&
				(af.stel.value == af.btel.value) &&
				(af.stele.value == af.btele.value) &&
				(af.sfax.value == af.bfax.value) &&
				(af.sfname.value == af.bfname.value) &&
				(af.slname.value == af.blname.value) &&
				(af.semail.value == af.bemail.value) &&
				(af.sstateId.selectedIndex == af.bstateId.selectedIndex)){
				af.ssave.checked == false;
			}
	}

	if(formOK) {
		EnableDisableAddressFileds('billing',true);
		EnableDisableAddressFileds('shipping',true);
		$("button").disabled = true;
		_isAddFormSubmited = true;
		af.submit();
	}
	else {
		new Effect.ScrollTo(firstElement,{duration:.6})
		showDialog(firstElement,'Please complete all required fields'+msg,"closeDialog()","")
	}


}








var slidePos = 1
var slidetimer




function flipSlide() {
    clearTimeout(slidetimer)
    $('slideshow').style.backgroundImage = "url(" + $('slideshow').down('img').src + ")"
    var nextPos = slidePos + 1
    if(nextPos>homeSlides.slides.length-1) {
        nextPos = 0
    }
    $('slideshow').down('img').hide()
    //$('slideshow').down('img').src = $('slideshow').down('img').src.replace("RFHomeSlide"+slidePos,"RFHomeSlide"+nextPos)
    $('slideshow').down('img').src = assetPath + homeSlides.slides[nextPos].img
    $('slideshow').down('a').href = homeSlides.slides[nextPos].url
    new Effect.Appear($('slideshow').down('img'),{duration:.5})
    slidePos = nextPos
    slidetimer = window.setTimeout(function() {flipSlide()},6000)
}

function jumpToSlide(n) {
    clearTimeout(slidetimer)
    $('slideshow').style.backgroundImage = "url(" + $('slideshow').down('img').src + ")"
    $('slideshow').down('img').hide()
    $('slideshow').down('img').src = $('slideshow').down('img').src = assetPath + homeSlides.slides[n].img
    $('slideshow').down('a').href = homeSlides.slides[n].url
    new Effect.Appear($('slideshow').down('img'),{duration:.5})
    slidePos = n
    slidetimer = window.setTimeout(function() {flipSlide()},6000)

}



function loopScroll(element,dir) {

	if(panelOpening==1) {
		return
	}

	panelOpening=1
	var shown = 4
	var container = $(element).previous('ul')
	var panels = $(container).select('li').toArray()
	var moveWidth = panels[0].getWidth()+2

	$(container).style.width=(moveWidth*panels.length)+'px'
	var hidden = $(container).select('li.offScreen').toArray()

	if(dir==1) {
		if(shown==panels.length-hidden.length) {
			//reached the end of the list
			$(container).select('li').each(function(element) {
				element.removeClassName('offScreen')
				//element.show()
			})
			$(container).style.left="0px"
			hidden.length=0
		}
		//panels[hidden.length].hide()
		panels[hidden.length].addClassName('offScreen')

		new Effect.Move(container,{x:-1*moveWidth,duration:.3,afterFinish:function(){panelOpening=0}})

	}
	else {
		if(hidden.length==0) {
			var moveLeft = panels.length-shown

			for(x=0;x<moveLeft-1;x++) {
				panels[x].addClassName('offScreen')
			}
			$(container).style.left=-1 * moveLeft * moveWidth +'px'
			hidden.length = x+1
		}
		panels[hidden.length-1].removeClassName('offScreen')
		new Effect.Move(container,{x:moveWidth,duration:.3,afterFinish:function(){panelOpening=0}})
	}
}



// quickview

function showQuickView(element,pid) {
	if($('productForm')) {
		return;
	}
	clearTimeout(quickTimer)
	if(!$('quickview')) {
		$(document.body).insert(new Element('div',{style:'display:none;position:absolute',className:'qv',id:'quickview'}))
		$(document.body).insert(new Element('div',{id:'viewer',style:'display:none'}))
		$(document.body).insert(new Element('div',{id:'showimage',style:'display:none'}))
		$('quickview').observe('mouseover',function(){clearTimeout(quickTimer)})
	}
	else {

	}
	$('quickview').stopObserving('click',function(){openQuickView(lastPid)})
	$('quickview').observe('click',function(){openQuickView(pid)})
	var myPos = findPos($(element))
	var myHeight = $(element).getHeight()
	var myWidth = $(element).getWidth()
	$('quickview').style.top = myPos[1]+70 +'px'
	$('quickview').style.left = myPos[0]+35 +'px'
	$('quickview').show();
	$('viewer').style.top = myPos[1]+70 +'px'
	$('viewer').style.left = myPos[0]+35 +'px'
	lastPid = pid
}




function hideQuickView(element) {
	quickTimer = window.setTimeout(function(){$('quickview').hide();$('quickview').update('')},100)
}

function openQuickView(pid) {
	if(quickLoading==1) {
		return
	}
	quickLoading = 1
	var myPos = findPos($('root'))
	$('viewer').style.left = myPos[0] +325+'px'


	$('viewer').show()
	url="productPopUp.taf?pid="+lastPid+"&_UserReference="+globalUserKey+"&now="+ new Date()
	new Effect.Morph('viewer',{style:'width:600px;height:360px;',duration:.5})
	new Ajax.Request(url, {
	  onSuccess: function(response) {
    	$("viewer").update(response.responseText)
		quickLoading=0
	  }
	});



}

function Prod_AddOrOptionClose() {
	$("viewer").update('')
	$("viewer").hide()
}

function sizeHover() {

}

//function prodSizes() {
	//resize product options if there are more than shown.
	//if(!$('prodSizes')) {
	//	return;
	//}
	//var psHeight = $('prodSizes').getHeight()
	//var listHeight =  $('prodSizes').scrollHeight
	//if(psHeight<listHeight) {
//		$('pBottomLink').show()
	//}
//}

function expandPrices() {
	var myParent = $('prodSizes')
	var newHeight =  $('prodSizes').scrollHeight-25
	new Effect.Morph(myParent,{style:'height:'+newHeight+'px',fps:60,duration:.5,afterFinish:function(){}})
	$('pBottomLink').hide()
}



//initilization
function init() {

	jQuery("a[href='http://runningfree.beta.moveable.ca/myaccount/newsLists/']").addClass("displayNone")

	if($('navPanel')) {
		$('navPanel').select('.panelList').each(function(element) {
			element.hide()
		})
	}

	$('root').select('.contentPageRight').each(function(element) {
		element.insert(new Element('div',{className:'clear'}),{position:'after'})
	})

	$('root').select('.contentPageTwoColumn').each(function(element) {
		element.insert(new Element('div',{className:'clear'}),{position:'after'})
	})

	//insert mini cart
	$(document.body).insert(new Element('div',{className:'miniCart',id:'miniCart',style:'display:none'}))

	//$(document.body).insert(new Element('a',{onclick:'printPage()'}).update("PRINT"))
	$$('.prodSizes li').each(function(element) {
		$(element).observe('mouseover',function(){this.addClassName('hover')})
		$(element).observe('mouseout',function(){this.removeClassName('hover')})
	})


	columnify($('subBrandsWrapper'))


	// Event hooks

	//select all on click for code boxes
	$('root').select('.codeInput').each(function(element){
		$(element).observe('click',function(){this.select()})
	})

	//initialize drop-down controls
	$('root').select('.ddControl').each(function(element){
		$(element).observe('click',ddControl)
		//adjust width of myParent

	})
	//sub nav
	$('menu').style.zIndex="10"



	//initialize ellipsis elements, such as product name
	if($('prodPreviewHolder')||$('prodInfoRight')) {
		var prodNameMaxHeight = 40
		var myTipShadow = new Element('div',{id:'prodTipShadow',style:'display:none',className:'prodTipShadow'})
		$(document.body).insert(myTipShadow)
		$(document.body).select('.ellipsis').each(function(element) {
			var limit = 50
			var attempts = 0
			var origName = element.innerHTML

			while (element.getHeight()>prodNameMaxHeight&&attempts<limit)  {
				var prodName = element.innerHTML.replace("&hellip;","")
				var prodNameArr = prodName.split(" ")
				var newName = ""
				for(var x=0;x<prodNameArr.length-2;x++) {
					newName = newName + prodNameArr[x]+" "
				}
				element.innerHTML = newName + prodNameArr[x]+"&hellip;"
				attempts++
			}
			if(attempts>0) {
				var myTip = new Element('div',{style:'display:none',className:'prodTip'}).update(origName)
				$(document.body).insert(myTip)
				$(element).observe('mouseover',prodShowTip.curry(myTip))
				myTip.observe('mouseout',function(){this.hide();$('prodTipShadow').hide()})
			}
		})
	}


	//manage left menu
	if($('leftNav')) {
		if(!$('leftPanel')) {
			$(document.body).insert(new Element('div',{id:'leftPanel',className:'leftPanel',style:'display:none'}))
		}
		var maxLeftList = 10
		var thisItem = 1
		var thisList
		$('leftNav').select('ul').each(function(element) {
			// fix to expand "departments"
			if(element.previous('h3').innerHTML!='Departments'&&element.previous('h3').innerHTML!='More Departments'&&element.previous('h3').innerHTML!='Brand Collections') {
				thisItem = 1
				thisList = element.select('li').toArray()
				//$('searchField').value=thisList.length+", "+(maxLeftList+1)
				// id there are one more than the max, just show the extra item
				element.select('li').each(function(element) {
					if(thisItem>maxLeftList&&thisList.length!=maxLeftList+1) {
						element.addClassName('hidden')
					}
					thisItem++
				})
				if(thisItem>5&&(thisItem-maxLeftList-1)>0&&thisList.length!=maxLeftList+1) {
					element.insert("<a href='javascript:;//' onclick='leftMore(this)'><strong>"+(thisItem-maxLeftList-1)+" more</strong></a>",{position:'after'})
				}
			}
		})

	}




	//fix multi-level similar items phrases.
	if($('prodInfoRight')&&4==5) {
		var gt = ""
		if($('prodInfoRight').innerHTML.indexOf('Similar')>1) {
			var x = 0
			var phrase = ''
			var newPhrase = ''
			myList = $('prodInfoRight').select('li').toArray()
			$('prodInfoRight').select('li').each(function(element) {
				if(element.down().innerHTML.indexOf('&gt;')>1) {
					if(phrase=='') {
						phrase = myList[x-1].down().innerHTML
					}
					newPhrase = element.down().innerHTML
					element.down().innerHTML = gt + myList[x].down().innerHTML.replace(phrase,"&nbsp;")
					if(newPhrase != myList[x].down().innerHTML.replace(phrase,"&nbsp;")) {
						phrase = newPhrase
						gt = gt +"&nbsp;&nbsp;&nbsp;"
					}
					else {
						phrase = ''
						gt = ''
					}
				}
				x++
			})
		}
	}

	$("searchField").observe('focus',searchFocus);
	$("searchField").observe('blur',searchBlur);
	if($("subscribeButton")) {
		$("subscribeButton").observe('click',TH_SubscribeNews);
		$("subscribeEmail").observe('click',subscribeEmailFocus);
		$("subscribeEmail").observe('blur',subscribeEmailBlur);
	}


	//sub-nav panel


	$('menu').select('ul li .subMenu').each(function(element) {
		element.observe('mouseout',subPanelOut);

		element.observe('mouseover',function() {this.addClassName('open');clearTimeout(subPanelTimer)});
	})




	//$('menu').down('.subMenu').observe('mouseover',function() {clearTimeout(subPanelTimer)});

	//$('subCategory').select('li a').each(function(element) {
		//alert(4)
		//element.observe('mouseover',function() {clearTimeout(subPanelTimer)});
		//element.observe('mouseout',function() {subPanelOut()});
	//})

	//prodSizes()

	//restrict length of similar items list
	//manage left menu
	if($('similar')) {
		var maxLeftList = 10
		var thisItem = 1
		var thisList
		$('similar').select('ul').each(function(element) {
			// fix to expand "departments"

				thisItem = 1
				thisList = element.select('li').toArray()
				//$('searchField').value=thisList.length+", "+(maxLeftList+1)
				// id there are one more than the max, just show the extra item
				element.select('li').each(function(element) {
					if(thisItem>maxLeftList&&thisList.length!=maxLeftList+1) {
						element.addClassName('hidden')
					}
					thisItem++
				})
				if(thisItem>5&&(thisItem-maxLeftList-1)>0&&thisList.length!=maxLeftList+1) {
					element.insert("<a class='topLink' href='javascript:;//' onclick='boxMore(this)'>View "+(thisItem-maxLeftList-1)+" more similar products...</a>",{position:'after'})
				}

		})

	}


	columnify($('subAccessories'))



	if($('slideshow')) {
			var n = 0

			$('slideshow').select('li a').each(function(element) {
				element.href="javascript:jumpToSlide("+(n)+")"
				n++
				//element.observe('click',function(){jumpToSlide})
			})
			$('slideshow').down('a').href=homeSlides.slides[0].url

			slidetimer = window.setTimeout(function(){flipSlide()},6000)
	}

	if($('homePromo')) {
		var loopSize = $('homePromo').select('li').toArray()
		if(loopSize.length>4) {
			//setup loop scroller
			$('homePromo').insert(new Element('a',{id:'loopLeft',className:'scrollLeft'}))
			$('homePromo').insert(new Element('a',{id:'loopRight',className:'scrollRight'}))
			$('loopLeft').observe('click',function(){loopScroll(this,-1)})
			$('loopRight').observe('click',function(){loopScroll(this,1)})
			for(var x=0;x<4;x++) {
				$('homePromo').down('ul').insert(new Element('li').update(loopSize[x].innerHTML))
			}
		}
	}

}

function raceContinue(gotoCheckout) {
  var focusSelector;
  var stopContinue = 0;
  var is_checked = false;
  jQuery('.raceOptionsTable input:radio').each(function(){
	   if (jQuery(this).is(':checked'))
	   {
	       is_checked = true;
	   }
   });
   if ( is_checked == false )
   {
      alert('Please select a race.');
	  return;
   }

  jQuery('.raceRegInfo input').removeClass('MissingInput');
  checkField('#FirstName');
  checkField('#LastName');
  checkField('#Address');
  checkField('#City');
  checkField('#Phone');
  checkField('#Email');
  checkField('#ConfirmEmail');
  checkField('#age');
  checkField('#Zip');

	
  if (validatePhone(jQuery('#Phone').val()) == false)
  {
		jQuery('#Phone').addClass('MissingInput');;
		if (!focusSelector)
		   focusSelector = '#Phone';
		stopContinue = 1;
  }

  if (validateEmail(jQuery('#Email').val()) == false)
  {
		jQuery('#Email').addClass('MissingInput');;
		jQuery('#ConfirmEmail').addClass('MissingInput');;
		if (!focusSelector)
		   focusSelector = '#Email';
		stopContinue = 1;
  }

  if(jQuery('#Email').val().toLowerCase() != jQuery('#ConfirmEmail').val().toLowerCase()){
		jQuery('#ConfirmEmail').addClass('MissingInput');
		if (!focusSelector)
		   focusSelector = '#ConfirmEmail';
		stopContinue = 1;
  }

  var firstDynamicMissingIndex = -1;
  jQuery('.raceDynamicRequiredInput').each(function(index) {
                   if (jQuery(this).val() == '')
				   {
				     if (firstDynamicMissingIndex == -1)
					 {
					    firstDynamicMissingIndex = index;
					 }
				     stopContinue = 1;
					 jQuery(this).addClass('MissingInput');;

				   }

				});
  if (firstDynamicMissingIndex != -1)
  {
     jQuery('.raceDynamicRequiredInput').eq(firstDynamicMissingIndex).focus();
  }

  if (stopContinue === 0)
  {
	    if (jQuery('#AgreeToWaiver').attr('checked') == false)
		{
			alert('You have to agree to the waiver before signing up.');
			return;
		}
		
		jQuery('#custom').val(jQuery('#FirstName').val()+' '+jQuery('#LastName').val())
		jQuery('#DateOfBirth').val(jQuery('#Year').val()+'-'+jQuery('#Month').val()+'-'+jQuery('#Day').val()+' 00:00:00.000' );

        new Ajax.Request('/ajax/raceRegistration.taf', {
	          parameters: $('productForm').serialize(true),
	          onSuccess: function(transport) {
			      var returnObj = jQuery.trim(transport.responseText);
				  returnObj = eval('(' + returnObj + ')');
				  if (returnObj.RaceRegId && isNaN(returnObj.RaceRegId) == false)
				  {
				     document.productForm.RaceRegId.value = returnObj.RaceRegId;
					 if (returnObj.QuestionaireResponseId && isNaN(returnObj.RaceRegId))
					 {
					    ajaxErrHandler();
						return;
					 }
					 else if (returnObj.QuestionaireResponseId && isNaN(returnObj.RaceRegId) == false)
					 {
					   document.productForm.qResponseId.value = returnObj.QuestionaireResponseId;
					 }
					 Prod_MultiAddToBasketAndContinue(gotoCheckout);
				  }
				  else
				  {
				        ajaxErrHandler();

				  }
			  }
		   }
	    );
	}
	else
	{
	    jQuery(focusSelector).focus();
	}

	function checkField(selector)
	{
		if(jQuery(selector).val() == ''){
			jQuery(selector).addClass('MissingInput');
			if (!focusSelector)
			   focusSelector = selector;
			stopContinue = 1;
		}
	}

	function validateEmail(email) {
	   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	   var address = email;
	   if(reg.test(address) == false) {
		  return false;
	   }
	   else
		  return true;
   }

   function validatePhone(n) {
		 n= new String(n);
		 t= new String();
		 k= new String();

		 for (i=0;i<n.length;i++)
		 {
			 k=String("1234567890").indexOf(n.substring(i,i+1));
			 if (k!=-1){
			    t=t+n.substring(i,i+1);
		     }
		 }
		 if(t.length<10){
		    return false;
		 }
		 else{
		    return true;
		 }
  }

}
function Prod_MultiAddToBasketAndContinue(gotoCheckout){
		$('addtocartmsg').innerHTML = '<br style="line-height:5px;"><img src="images/ajax_indicator_sm.gif" />';
		var myPos = findPos($('btnQuickAdd'))
		$('dialogCart').style.top = myPos[1]-50+'px'
		$('dialogCart').style.left = myPos[0]-150+'px'
		new Ajax.Request('/ajax/multiaddtobasket.taf',
		{
			parameters: $('productForm').serialize(true),
			onSuccess: function(transport) {
				$('ajaxcartresponse').innerHTML = transport.responseText;

				var basketerror = $('basketerror');
				if (basketerror != null)
				{
					$('addtocartmsg').innerHTML = "";
					alert(basketerror.innerHTML);
				}
				else
				{
					var cartresponse = $('addmsg').innerHTML;
					var totalprice = $('totalprice').innerHTML;
					var totalquantity = $('totalquantity').innerHTML;
					$('addtocartmsg').innerHTML = "<br style='line-height:5px;'>" + cartresponse;
					$('addtocartmsg').innerHTML = "";
					$('dialogCartMsg').innerHTML = cartresponse;
					//Prod_AddOrOptionClose()

					//jQuery('.dialogCart').fadeOut('medium');
					//jQuery('#dialogCart').fadeIn('medium');
					//$('basketquantity').innerHTML = totalquantity;
					$('basketprice').innerHTML = totalprice;
					if (gotoCheckout == true)
					   goToURL('checkout','');
					else
         				goToURL('basket','');
				}
			}
		});
}

function updateRaceItemQtn(btn, rowId)
{
   jQuery("input[name='Quantity']").val(0);
   jQuery("#Quantity" + rowId).val(1);
   jQuery(btn).parents('table:first').find('td.raceStyleCol').removeClass('activeRaceRow');
   jQuery(btn).parents('tr:first').find('td.raceStyleCol').addClass('activeRaceRow');
}




function enlargerunningcustom(which,type,size){
var ie=document.all
var ns6=document.getElementById&&!document.all
if(type == 2){
	var newHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="' +size+ '" height="' +size+ '" id="MMag" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="' +which+ '" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><embed src="' +which+ '" quality="high" bgcolor="#ffffff" width="' +size+ '" height="' +size+ '" name="MMag" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>'
}
else{
	var newHTML = '<a class="lightbox" href="' +which+ '"/><img  src="' +which+ '" border="0"></a>';






	}



	if (ie||ns6){
		crossobj=document.getElementById? document.getElementById("showimage") : document.all.showimage
		crossobj.innerHTML=newHTML;
		crossobj.style.visibility="visible"
	return false
	}
	else {
		return true;
	}




}


jQuery('.productOptionSelect').attr('checked', false);

currentStatus = 'ready';

function checkandSetStatus()
{

   if (1 == 1)
   {
        var statusGood = false;
        jQuery('.productOptionSelect').each(function() { 
                           if (jQuery(this).attr('disabled') == false)
                            {
                              statusGood = true;
                              return;
                            }
                          
                     });
        if (statusGood == false)
        {
              jQuery('.dynamicStatusBtn').removeClass('btnGreen').removeClass('btnBlue').removeClass('btnOrange');
              jQuery('.dynamicStatusBtn').addClass('btnRed');
              jQuery('.btnRed .buttonAddToCart').attr('onclick', '').css('cursor', 'default');


        }

   }
   
}



function dynamicStatusRemove(element)
{
   jQuery(element).removeClass('orangeBg').removeClass('greenBg').removeClass('blueBg');
}

function dynamicStatusHover(type, index, element)
{
   jQuery(element).addClass('orangeBg');
   return;

   dynamicStatusRemove(element);
   if (currentStatus == "ready")
   { 
      jQuery(element).addClass('orangeBg');
      
   }
   else if (currentStatus == "InStock")
   {  

       jQuery(element).addClass('greenBg');     
   }
   else if (currentStatus == "OutOfStockCanBackOrder")
   {
        jQuery(element).addClass('blueBg');  
   }
}

function modifyBaseQty(){
	var loops = jQuery('#ITEMCOUNT').val();
	var i = 0;
	while (i < loops)
	{
		i++
		var checkObject = jQuery('#quantity'+i).length;
		if (checkObject != 0){
			var baseQty = jQuery('#BaseQuantity').val();
			var qty = jQuery('#quantity'+i).val();
			if((qty > 0) && (baseQty > 0)){
				jQuery('#quantity'+i).val(baseQty);
				verifyAvailableQty(i);
			}
		}

	}	
}

function verifyAvailableQty2(obj){

	var selectedVal = obj[obj.selectedIndex].value;
	var ohV = jQuery('#onHandVal').val();
	var alertMsg = '';
	if ((parseInt(ohV) < parseInt(selectedVal)) && (parseInt(ohV) > 0))
	{
		alertMsg = 'Exceeds available amount of ' + ohV + '. Your order will<BR />be held and shipped once all items are available.';
	}
	jQuery('#backorderAlert').html(alertMsg)
}

function verifyAvailableQty(i){
	var alertMsg = '';
	var qty = jQuery('#quantity'+i).val();
	var ohv = jQuery('#onHandVal'+i).val();
	var maxok = jQuery('#maxAllowed'+i).val();
	if((parseInt(ohv) < parseInt(qty)) && (parseInt(ohv) >0) && (parseInt(ohv) <= parseInt(maxok))){
		alertMsg = 'Exceeds available amount of ' + ohv + '. Your order will<BR />be held and shipped once all items are available.';
	}
	if((parseInt(ohv) < parseInt(qty)) && (parseInt(ohv) >0) && (parseInt(qty) > parseInt(maxok))){
		if(parseInt(ohv)==1){
			msgQty = 'is';
		}
		else{
			msgQty = 'are';
		}
		alertMsg = 'Only ' + ohv + ' ' + msgQty + ' available at this time';
		jQuery('#quantity'+i).val(ohv);
		jQuery('#BaseQuantity').val(ohv);

	}

	jQuery('#backorderAlert').html(alertMsg)
}

function dynamicStatusUpdate(type, index, element, StockMsg)
{  
   if (jQuery(element).attr('disabled') == true)
   {
     return;
   }
   jQuery('.dynamicStatusColor').removeClass('darkgreen').removeClass('blue');
   jQuery('.dynamicStatusBtn').removeClass('btnGreen').removeClass('btnBlue').removeClass('btnOrange');
   jQuery('.stkStatusMsgCls').removeClass('ssmBlue').removeClass('ssmGreen');
   jQuery('.quantityField').val(0); 
   jQuery('#pOptions li label').removeClass('orangeBgSteady').removeClass('greenBgSteady').removeClass('blueBgSteady');
   if (type == "InStock")
   { 
      jQuery('.dynamicStatusColor').addClass('darkgreen'); 
      jQuery('.dynamicStatusBtn').addClass('btnGreen');
	  jQuery('.stkStatusMsgCls').addClass('ssmGreen');
      currentStatus = 'InStock';
      jQuery(element).parents('li:first').find('label').addClass('greenBgSteady');
   }
   if (type == "OutOfStockCanBackOrder")
   {  
      jQuery('.dynamicStatusColor').addClass('blue'); 
      jQuery('.dynamicStatusBtn').addClass('btnBlue');
	  jQuery('.stkStatusMsgCls').addClass('ssmBlue');;
      currentStatus = 'OutOfStockCanBackOrder';
       jQuery(element).parents('li:first').find('label').addClass('blueBgSteady');     
   }
   else if (type == "OutOfStockNoBackOrder")
   {
   }
   jQuery('#stkStatusMsg').text(StockMsg)

   jQuery('#quantity'+index).val(jQuery('#BaseQuantity').val());
	verifyAvailableQty(index);
}

jQuery('#pOptions li').click(function(){
	jQuery('#pOptions li').removeClass('whoopwhoop');
	jQuery(this).addClass('whoopwhoop');
});


var optionsheight = jQuery('.prodSizes').height();

if ( optionsheight < 192)
	{

jQuery('.prodSizes').css('overflow', 'hidden');
jQuery('.prodSizes label').css('width', '322px');

};


jQuery(document).ready(function () {
	jQuery('.payPalBox').hide();
});

function paypalbox() {
	var ispaypal = jQuery('#select3').val();
	if (ispaypal == 'PayPal') {
		
		jQuery('.paymentFormUpper').hide();
		jQuery('.payPalBox').show();
		jQuery('.buttonContinueFinal').hide();
	} else {
		jQuery('.paymentFormUpper').show();
		jQuery('.payPalBox').hide();
		jQuery('.buttonContinueFinal').show();
	}
}




document.observe("dom:loaded", function() {
  init()
});






/// Please put all script additions ABOVE the init() function ///

/// Don't put anything down below. Bad, bad. ////

