loadFlag=false;

function init(whichpage) {
	initDHTMLAPI();
	loadFlag=true;

	switch(whichpage) {
		case "home__page":
			initSlidingBoxes();
			$$('.homeimg').each(function(s) {
				s.setStyle ({
					visibility:'visible'
				});
			});
			setTimeout('startSlideshow(4000)',3000);
		break;
		case "about_cx_client_list_page":
			beginTestiAnim();
		break;
		case "about_cx_factory_page":
			initFactoryScroller();
		break;
		case "press_media_download_page":
			if (getObject('media') != null) {
				document.media.media_uname.focus();
			}
			if (getObject('mediaCol1') != null) {
				fixMediaCols();
			}
		break;
		case "contact__page":
			initSlidingSections();
		break;
		case "project_gallery_installations_page":
			initSlidingSections();
			initHoverLinks();
		break;
		case "project_gallery_press_page":
		case "products_featured_products_page":
		case "project_gallery_custom_design_page":
			initHoverLinks();
		break;
		case "checkout__page":
			if ($('region') != undefined) {
				$('region', 'bill_region').invoke('observe', 'change', function(e) {
					menu = e.element().id;
					stateMenu = menu == 'region' ? 'state' : 'bill_state';
					switch ($(menu).options[$(menu).selectedIndex].text) {
						case "USA":
						case "Canada":
							switchStateDropdown(menu);
//							$(stateMenu).enable();
						break;
						case "Puerto Rico":
							$(stateMenu).selectedIndex = 0;
							$(stateMenu).disable();
						break;
					}
					updateTotal(menu);
				});
				
				Event.observe($('state'), 'change', function(){
					updateTotal();
				});
			}
		break;
	}


	preload_images(
		'images/nav/top_about_cx_on.png',
		'images/nav/about_our_story_on.png',
		'images/nav/about_inspiration_on.png',
		'images/nav/about_factory_on.png',
		'images/nav/about_client_list_on.png',
		'images/nav/top_products_on.png',
		'images/nav/products_featured_products_on.png',
		'images/nav/products_collections_on.png',
		'images/nav/products_fixture_types_on.png',
		'images/nav/top_project_gallery_on.png',
		'images/nav/project_gallery_installations_on.png',
		'images/nav/project_gallery_custom_design_on.png',
		'images/nav/project_gallery_press_on.png',
		'images/nav/project_gallery_cx_blog_on.png',
		'images/nav/top_ordering_info_on.png',
		'images/nav/ordering_info_retailers_on.png',
		'images/nav/ordering_info_faq_list_on.png',
		'images/nav/ordering_info_glossary_on.png',
		'images/nav/top_cx_blog_on.png',
		'images/nav/products_featured_products_new_products_on.png',
		'images/nav/products_featured_products_sale_items_on.png',
		'images/nav/products_featured_products_recent_projects_on.png',
		'images/nav/products_collections_Scavo_on.png',
		'images/nav/products_collections_Milk_White_on.png',
		'images/nav/products_collections_Cristallo_on.png',
		'images/nav/products_fixture_types_single_pendants_on.png',
		'images/nav/products_fixture_types_chandeliers_on.png',
		'images/nav/products_fixture_types_wall_fixtures_on.png',
		'images/nav/products_fixture_types_semi_flush_ceiling_on.png',
		'images/nav/products_fixture_types_table_on.png',
		'images/nav/ordering_info_retailers_domestic_on.png',
		'images/nav/ordering_info_retailers_international_on.png',
		'images/nav/ordering_info_retailers_inquiries_on.png',
		'images/nav/ordering_info_faq_list_general_info_on.png',
		'images/nav/ordering_info_faq_list_mounting_hardware_on.png',
		'images/nav/ordering_info_faq_list_electrical_on.png',
		'images/nav/ordering_info_faq_list_ordering_info_on.png'
	);
		
}

var preloaded = new Array();
function preload_images() {
    for (var i = 0; i < arguments.length; i++){
        preloaded[i] = document.createElement('img');
        preloaded[i].setAttribute('src',arguments[i]);
    };
};

function changeColor(which) {
	productimg.src = 'images/products/medium/' + which + '.jpg';
}

function hidePane() {
	$('jb_overlay').remove();
	$('paneHolder').remove();
}

function createOverlay() {
	var arrayPageSize = getPageSize();
	document.body.appendChild(
		Builder.node('div',{id:'jb_overlay'})
	);
	$('jb_overlay').observe('click', (function(event) { hidePane(); }));
	getObject("jb_overlay").position = 'absolute';
	getObject("jb_overlay").top = '0px';
	getObject("jb_overlay").left = '0px';
	getObject("jb_overlay").height = (arrayPageSize[1] + 'px');
	getObject("jb_overlay").width = '100%';
	getObject("jb_overlay").backgroundColor = '#000';
	setOpacity(getRawObject('jb_overlay'), 50);
	getObject("jb_overlay").zIndex = 122;
}

function fillPane(theHTML) {
	getRawObject('pane').innerHTML = theHTML;
}

function fixMediaCols() {//jesus. I wish I could figure out the CSS for this, but no.
	colH = getRawObject('col2').offsetHeight - (getRawObject('breadcrumb').offsetHeight + getRawObject('mdIntro').offsetHeight + 22) + 'px';
	getObject("mediaCol2").height = colH;
}

function fixHomeCols() {
	colMax = 0;
	for (i=1;i<=5;i++) {
		colMax = Math.max(colMax,getRawObject('homebox_content' + i).offsetHeight);
	}
	for (i=1;i<=5;i++) {
		getObject("homebox_content" + i).height = colMax + 'px';
	}
}

function productDropdown(which, path) {
	if (which.value == 0) {
		location.href = path;
	} else {
		location.href = path + '/cat' + which.value;
	}
}

function inspirePane(key) {
	if (!loadFlag) { return; }
	if (getObject('pane') == null) {
		createOverlay();
		document.body.appendChild(
			Builder.node('div',{id:'paneHolder'},
				Builder.node('div', {id:'pane'})
			)
		);
	$('paneHolder').observe('click', (function(event) { hidePane(); }));
		getObject('pane').top = (f_scrollTop() + 54) + 'px';
	}
	theURL = 'includes/inspire_pane.php?key=' + key;
	makeHttpRequest(theURL, 'fillPane', false);
}

function inspireImgs() {
	if (!inspireImgs.arguments.length || !loadFlag) {
		return;
	}
	var c=0;
	for (i=1;i<=allImgs;i++) {
		if (i == inspireImgs.arguments[c]) {
			c++;
		} else {
			setOpacity(getRawObject('image' + i), 50);
		}
	}
}

function inspireImgs_off() {
	if (!loadFlag) { return; }
	for (i=1;i<=allImgs;i++) {
		setOpacity(getRawObject('image' + i), 100);
	}
}

function inspireTags() {
	if (!inspireTags.arguments.length || !loadFlag) {
		return;
	}
	var c=0;
	for (i=1;i<=allTags;i++) {
		if (i == inspireTags.arguments[c]) {
			c++;
		} else {
			setOpacity(getRawObject('tag' + i), 50);
		}
	}
}

function inspireTags_off() {
	if (!loadFlag) { return; }
	for (i=1;i<=allTags;i++) {
		setOpacity(getRawObject('tag' + i), 100);
	}
}

function showMountLength(min, max, iid) {
	if (typeof iid == "undefined") {//from product detail page
		mountselect = document.cartform.mounting;
		lengthdiv = getRawObject('orderlength');
		selectname = "plength";
		nullval = '<option value="">overall length</option>';
		deselect = '';
	} else { //from cart
		mountselect = document.cartform["mounting[" + iid + "]"];
		lengthdiv = getRawObject('length' + iid);
		selectname = "length[" + iid + "]";
		nullval = '';
		deselect = 'N/A<input type="hidden" name="length[' + iid + ']" value="" />';
	}
	if (mountselect.options[mountselect.selectedIndex].innerHTML == 'stem') {
		theHTML = '<select name="' + selectname + '">';
		theHTML += nullval;
		for (i=min;i<=max;i++) {
			theHTML += '<option value="' + i + '">' + i + '"</option>';
		}
		theHTML += '</select>';
		lengthdiv.innerHTML = theHTML;	
	} else {
		lengthdiv.innerHTML = deselect;
	}
}

function productDetailOrder(which) {
	if (parseInt(which.quant.value) != which.quant.value) {
		alert("The quantity must be a number.");
		which.quant.focus();
		return false;
	}
	if (which.quant.value <= 0) {
		alert("The quantity must be  greater than zero.");
		which.quant.focus();
		return false;
	}
	if (which.color.type != 'hidden' && !which.color.value) {
		alert("You must choose a color.");
		which.color.focus();
		return false;
	}
	if (which.finish.type != 'hidden' && !which.finish.value) {
		alert("You must choose a hardware option.");
		which.finish.focus();
		return false;
	}
	if (which.mounting.type != 'hidden' && !which.mounting.value) {
		alert("You must choose a mounting option.");
		which.mounting.focus();
		return false;
	}
	if (which.mounting.value == 3 && !which.plength.value) {
		alert("You must choose a length.");
		which.plength.focus();
		return false;
	}
	return true;
}

function editDiffusers(which, width) {
	if (!loadFlag) { return; }
	document.cartform['diffclean[' + which + ']'].value = 'n';
	theURL = 'includes/cart_diffuser_chooser.php?ch=' + which;
	CSSclass = 'diffuserpane' + width;
	cx_popdiffPane(theURL, CSSclass);
}

function cx_popdiffPane(theURL, CSSclass, callback) {
	if (!loadFlag) { return; }
	if (typeof(callback) == 'undefined') {
		callback = 'ad_fillPane';
	}
	if (getObject('pane') == null) {
		createOverlay();
		document.body.appendChild(
			Builder.node('div',{id:'paneHolder'},
				Builder.node('div', {id:'pane'})
			)
		);
		getObject('pane').top = (f_scrollTop() + 54) + 'px';
	}
	$('pane').className = CSSclass;
	makeHttpRequest(theURL, callback, false);
}

function hideDropdowns() {
	obj = document.getElementById('cartform');
	for (i=0; i<obj.elements.length; i++) {
		if (obj.elements[i].name && obj.elements[i].type == 'select-one') {
			unsetDisplay(obj.elements[i]);
		}
	}
}

function showDropdowns() {
	obj = document.getElementById('cartform');
	for (i=0; i<obj.elements.length; i++) {
		if (obj.elements[i].name && obj.elements[i].type == 'select-one') {
			setDisplay(obj.elements[i]);
		}
	}
}


function selectDiff(diffnum,iid,diffinc) {
	var my_diff = diffstyle[iid][diffnum];
	var my_col = diffcol[iid][diffnum];
	my_diff += diffinc;
	if (my_diff == diffs[iid].length) {
		my_diff = 0;
	}
	if (my_diff < 0) {
		my_diff = diffs[iid].length - 1;
	}
	diffstyle[iid][diffnum] = my_diff;
	newImg = alldiff[iid][diffs[iid][my_diff]][colors[iid][my_col]];
	changeImages('diffimg' + diffnum,'images/products/chandelier_diffusers/' + newImg + '.jpg');
	diffName = diffnames[iid][my_diff];
	getRawObject('diffname' + diffnum).innerHTML = diffName;
}

function selectDiffcol(diffnum,iid,my_col) {
	var my_diff = diffstyle[iid][diffnum];
	diffcol[iid][diffnum] = my_col;
	newImg = alldiff[iid][diffs[iid][my_diff]][colors[iid][my_col]];
	changeImages('diffimg' + diffnum,'images/products/chandelier_diffusers/' + newImg + '.jpg');
	
	getRawObject('diffcolorname' + diffnum).innerHTML = diffcolnames[iid][my_col];
}

function updateDiffs(iid) {
	colstr = '';
	diffstr = '';
	for (i=0;i<diffcol[iid].length;i++) {
		colstr = colstr + colors[iid][diffcol[iid][i]] + ',';
		diffstr = diffstr + diffs[iid][diffstyle[iid][i]] + ',';
	}
	theURL = 'includes/diff_update.php?iid=' + iid + '&col=' + colstr + '&diff=' + diffstr;
	makeHttpRequest(theURL, 'void', false);
	document.cartform["color[" + iid + "]"].value = colstr.substr(0,colstr.length-1);
	hideDiffPane();
}

function hideDiffPane() {
	hidePane();
	if (navigator.userAgent.indexOf('MSIE') != -1) {//MSIE needs its dropdowns hidden, because it's retarded as usual.
		showDropdowns();
	}
}

function colorNameOn(which,leftpos) {
	margin = 38 * leftpos - 77;
	getRawObject('colorname').innerHTML = which;
	getObject('colorname').marginLeft = margin + 'px';
}

function colorNameOff() {
	getRawObject('colorname').innerHTML = '';
}

function diffusersChosen() {
	re = /diffclean/;
	obj = document.getElementById('cartform');
	for (i=0; i<obj.elements.length; i++) {
		if (re.exec(obj.elements[i].name) && obj.elements[i].type == 'hidden') {
			if (obj.elements[i].value == 'y') {
				alert("Please choose the diffusers for your chandelier before checking out.");
				return false;
			}
		}
	}
return true;
}

function changeFlag() {
	changeImages('bt_updatecart','images/buttons/updatecart_on.gif');
}

//Factory scroll

function initFactoryScroller() {
	if (getRawObject('thumbSCContainer') != null) {
		getObject('thumbSCContainer').visibility='visible';
		initLeft = 0;
		lPos = 0;
		scrollImgWidth = 162;
		scrollContainerWidth = 648;
		thumbScroll = new jb_scroller('thumb', scrollContainerWidth, 176, 460, initLeft, 0); // id, width, height, speed, initLeft, initTop
		thumbScroll.load();
		
	}
}

function scrollFactoryImg(dir) {
	lPos += scrollImgWidth * dir;
	thumbScroll.smoothScrollTo(lPos,0,.4);
	holderW = parseInt((getObject("thumbSCContent").width).slice(0,-2));
	if (lPos <= 0) {
		unsetDisplay('img_arrow_left');
		setDisplay('img_arrow_right');
	} else if (lPos >= holderW - (scrollImgWidth * 4)) {
		unsetDisplay('img_arrow_right');
		setDisplay('img_arrow_left');
	} else {
		setDisplay('img_arrow_left');
		setDisplay('img_arrow_right');
	}
}


function startSlideshow(delay) {
	end_frame = 1;
	while ($('slide' + end_frame) != undefined) {
		end_frame++;
	}
	end_frame--;
	setTimeout(switchSlides(1, end_frame, delay), 1);
}
						
function switchSlides(frame, end_frame, delay) {
	return (function() {
		if (frame < end_frame) {
			Effect.Fade('slide' + frame);
			frame++;
		} else {
			frame = 1;
			Effect.Appear('slide' + frame, {
				afterFinish: function() {
					for (i=2;i<=end_frame;i++) {
						$('slide' + i).setStyle({
							display:'block',
							opacity:1.0
						});
					}
				}
			});
		}
		setTimeout(switchSlides(frame, end_frame, delay), delay);
	})
}

function validateForm(which) {
	var f = document.forms[which.id];

	switch(which.id) {
		case ('appointmentform'):
			mandatory = {"appt_first_name": "First Name",
						"appt_last_name": "Last Name",
						"appt_phone": "Phone Number"
						};
			if (!validateFields(which, mandatory)) { return false; }

			if (!emailCheck(f.appt_email_address.value)) {
				return false;
			}

			if (f.appt_howheard.value == 0) {
				alert("Please specify how you heard of us.");
				f.appt_howheard.focus();
				return false;
			}
			
			if (f.appt_interested_in.value.length==0){
				alert("Please specify which kinds of products you're interested in.");
				f.appt_interested_in.focus();
				return false;
			}
		
			if (f.appt_date.value == 0) {
				alert("Please select a date.");
				f.appt_date.focus();
				return false;
			}
			
			if (f.appt_time.value == 0) {
				alert("Please select a time.");
				f.appt_time.focus();
				return false;
			}
			break;
		case ('mailinglistform'):
			mandatory = {"mailinglist_name_first": "First Name",
						"mailinglist_name_last": "Last Name",
						"mailinglist_phone": "Phone Number",
						"mailinglist_address": "Address"
						};
			if (!validateFields(which, mandatory)) { return false; }

			if (!emailCheck(f.mailinglist_email.value)) {
				return false;
			}

			if (f.mailinglist_howheard.value == 0) {
				alert("Please specify how you heard of us.");
				f.mailinglist_howheard.focus();
				return false;
			}
			
			if (f.mailinglist_interested_in.value.length==0){
				alert("Please specify which kinds of products you're interested in.");
				f.mailinglist_interested_in.focus();
				return false;
			}
			break;
		case ('ask_questionform'):
			mandatory = {"question_name_first": "First Name",
						"question_name_last": "Last Name"
						};
			if (!validateFields(which, mandatory)) { return false; }

			if (!emailCheck(f.question_email.value)) {
				return false;
			}

			if (f.question.value.length == 0) {
				alert("Please ask a question.");
				f.question.focus();
				return false;
			}
			break;
	}

	return true;
}

function validateFields(which, mandatory) {
	var f = document.forms[which.id];
	var str = '';
	var foc = '';
	for (var nicename in mandatory) {
		if (f[nicename].value == '') {
			str += "You must enter a " + mandatory[nicename] + ".\n";
			if (foc == '') {
				foc = nicename;
			}
		}
	}

	if (str) {
		alert(str);
		if (foc != '') {
			f[foc].focus();
		}
		return false;
	}
	return true;
}

//for animated shipping promotional box on home page. Made more complex by the fact that we've got multiple hit areas.
var questionSlider, overHead = [], overContent = [], boxIsDown = [], isSliding = [];
for (i=1;i<=6;i++) {
	overHead[i] = false;
	overContent[i] = false;
	boxIsDown[i] = false;
	isSliding[i] = false;
}
function initSlidingBoxes() {
	$$('.promobox').each(function(s) {
		box = s.id.substr(-1);
		Event.observe(s, 'mouseover', function(e){
			if (e.element().hasClassName('promobox')) {
				b = e.element().id.substr(-1);
			} else {
				b = e.element().up('.promobox').id.substr(-1);
			}
			overHead[b] = true;
			setTimeout(promoBox, 100, b);
			return false;
		});
		Event.observe(s, 'mouseout', function(e){
			if (e.element().hasClassName('promobox')) {
				b = e.element().id.substr(-1);
			} else {
				b = e.element().up('.promobox').id.substr(-1);
			}
			overHead[b] = false;
			setTimeout(promoBox, 100, b);
			return false;
		});
		$('homebox_head' + box).observe('mouseover', function(e){
			b = e.element().up().id.substr(-1);
			overHead[b] = true;
			setTimeout(promoBox, 100, b);
			return false;
		});
		$('homebox_content' + box).observe('mouseover', function(e){
			b = e.element().up().id.substr(-1);
			overContent[b] = true;
			setTimeout(promoBox, 100, b);
			return false;
		});
		$('homebox_head' + box).observe('mouseout', function(e){
			b = e.element().up().id.substr(-1);
			overHead[b] = false;
			setTimeout(promoBox, 100, b);
			return false;
		});
		$('homebox_content' + box).observe('mouseout', function(e){
			b = e.element().up().id.substr(-1);
			overContent[b] = false;
			setTimeout(promoBox, 100, b);
			return false;
		});
	});
	$('homequestions').observe('mouseover', function() {
		questionBox('show');
	} );
	$('homequestions').observe('mouseout', function() {
		questionBox('hide');
	} );
}

function questionBox(which) {
	if (questionSlider != undefined) {
		questionSlider.cancel();
	}
	if (which == 'show') {
		questionSlider = new Effect.Move("questionbox", { x: 707, y: 268, mode: 'absolute' });
	} else {
		questionSlider = new Effect.Move("questionbox", { x: 707, y: 386, mode: 'absolute' });
	}
}
 
 function promoBox(box) {
	if (isSliding[box]) { return; }
	if (overHead[box] || overContent[box]) {
		if (!boxIsDown[box]) {
			isSliding[box] = true;
 			Effect.SlideDown("promobox" + box, {afterFinish: function(){
 				isSliding[box] = false;
 			}
 			});
 			boxIsDown[box] = true;
 		}
 	} else if (boxIsDown[box]) {
		isSliding[box] = true;
		Effect.SlideUp("promobox" + box, {afterFinish: function(){
			isSliding[box] = false;
		}
		});
		boxIsDown[box] = false;
	}
 }

//dropdown menus
//originally from http://www.makesites.cc/programming/by-makis/simple-drop-down-menu-with-prototype/
var DropDownMenu = Class.create();
var nodes = new Hash();

DropDownMenu.prototype = {

 initialize: function(menuElement) {
	menuElement.childElements().each(function(node){
		var submenu = $A(node.getElementsByTagName("ul")).first();
		var bkg = $A(node.getElementsByTagName("a")).first();
		var topnavbkg = node.select('[class="topnavbkg"]').first();
		if (submenu != undefined) {
			var subheight = submenu.getHeight();
			submenu.setStyle ({
				top:'-' + subheight + 'px'
			});
		}
		nodes.set(node.id, {
			nodeclass:node.className,
			submenu:submenu,
			bkg:bkg,
			topnavbkg:topnavbkg,
			subheight:subheight,
			mouseOverA:false,
			mouseOverUL:false
		});
		Event.observe(bkg, 'mouseover', anchorOver);
		Event.observe(bkg, 'mouseout', anchorOut);
	});
}

};

function anchorOver() {
	theNode = nodes.get(this.up().id);
	if (theNode.mouseOverA) {
		return;
	}
	theNode.mouseOverA = true;
	slideDown(this);
	if (theNode.submenu != null) {
		Event.observe(theNode.submenu, 'mouseover', listOver);
		Event.observe(theNode.submenu, 'mouseout', listOut);
	}
}

function anchorOut() {
	theNode = nodes.get(this.up().id);
	theNode.mouseOverA = false;
	slideUp(this);
}

function listOver() {
	theNode = nodes.get(this.up().id);
	if (theNode.mouseOverUL) {
		return;
	}
	theNode.mouseOverUL = true;
}

function listOut() {
	theNode = nodes.get(this.up().id);
	theNode.mouseOverUL = false;
	slideUp(this);
}

function slideDown(which) {
	theNode = nodes.get(which.up().id);
	if (theNode.submenu != null) {
		new Effect.Morph(theNode.submenu.id, {
			style: {
				top:'21px'
			},
			duration:theNode.subheight/400
		});
	}
	theNode.topnavbkg.setStyle({
		backgroundColor:'#FAFAFA'
	});
}

function slideUp(which) {
	setTimeout(function() {
	theNode = nodes.get(which.up().id);
	if (theNode.mouseOverA || theNode.mouseOverUL) {
		return;
	}
	if (theNode.submenu != null) {
		new Effect.Morph(theNode.submenu.id, {
			style: {
				top:'-' + theNode.subheight + 'px'
			},
			duration:theNode.subheight/400
		});
	}
	if (theNode.nodeclass == 'topnavmenu') {//don't revert the "you are here" links
		theNode.topnavbkg.setStyle({
			backgroundColor:'#F2F2F2'
		});
	}
	}, 100);
}


/*
if (mouseover a) {
	register overA
	if (menuisdown) {
		return
	} else {
		slidedown
		activate mouseover ul
	}
}
if (mouseover ul) {
	register overUL
}
if (mouseout a) {
	deregister overA
	slideup
}
slidedown {
	animate
}
slideup {
	if (!overA && !overUL) {
		deactivate mouseover ul
		animate
	}
}

*/

var slidingSectionPos = new Hash(); //-1 hidden, 0 sliding, 1 shown

function initSlidingSections() {
	$$('.toggle').each(function(s) {
		sectionID = s.id.slice(0,-6);
		if ($(sectionID + 'holder').getStyle('display') == 'none') {
			slidingSectionPos.set(sectionID,-1);
		} else {
			slidingSectionPos.set(sectionID,1);
		}
		Event.observe(s, 'click', function(event) {
			sectionID = s.id.slice(0,-6);
			if (slidingSectionPos.get(sectionID) == 0) { return; }
			slidingSectionPos.each(function(pair) {
				if (pair.key == sectionID || pair.value == 1) {
					toggleSliders(pair.key);
				}
			});
		})
	});
}

function toggleSliders(sectionID) {
	if (slidingSectionPos.get(sectionID) == -1) {
		slidingSectionPos.set(sectionID, 0);
		$(sectionID + 'button').className = 'toggle down';
		new Effect.BlindDown(sectionID + 'holder', {
			afterFinish:function() {
				slidingSectionPos.set(sectionID, 1);
			}
		});
	} else if (slidingSectionPos.get(sectionID) == 1) {
		slidingSectionPos.set(sectionID, 0);
		$(sectionID + 'button').className = 'toggle';
		new Effect.BlindUp(sectionID + 'holder', {
		afterFinish:function() {
			slidingSectionPos.set(sectionID, -1);
		}
		});
	}
}

function initHoverLinks() {
	$$('.gridlink').each(function(s) {
		Event.observe(s, 'mouseover', function(event) {
			s.down('span').className = 'gridcaption over';
		});
		Event.observe(s, 'mouseout', function(event) {
			s.down('span').className = 'gridcaption';
		});
	});
}

function updateTotal(which) {
	if (which == 'bill_region') { return; }
	params = {
		action: 'updateTotal',
		state: $('state').getValue(),
		region: $('region').getValue(),
		sid: $('sid').getValue()
	}
	new Ajax.Request('includes/cx_ajax.php', {
		parameters: params,
		onSuccess: function(r) {
			l = r.responseJSON;
			shipping = l.subtotal * (l.shiprate/100);
			newHTML = '$' + (shipping).formatMoney(2, '.', ',');
			if ($('cell_shipping').innerHTML != newHTML) {
				$('cell_shipping').innerHTML = newHTML;
				flashCell('cell_shipping');
			}

			tax = (l.subtotal + shipping) * (l.tax/100);
			newHTML = '$' + (tax).formatMoney(2, '.', ',');
			if ($('cell_tax').innerHTML != newHTML) {
				$('cell_tax').innerHTML = newHTML;
				flashCell('cell_tax');
			}

			newHTML = '$' + (l.subtotal + shipping + tax).formatMoney(2, '.', ',');
			if ($('cell_total').innerHTML != newHTML) {
				$('cell_total').innerHTML = newHTML;
				flashCell('cell_total');
			}
		}
	});
}

function flashCell(which) {
	$(which).setStyle({
		color:'#DD2725'
	});
	new Effect.Morph(which,{
		style:{
			color:'#595959'
		},
		duration: 0.75
	});
}

function switchStateDropdown(which) {
	reg = $(which).getValue();
	stateMenu = which == 'region' ? 'state' : 'bill_state';
	params = {
		menu: stateMenu,
		action: 'switchStateDropdown',
		region: reg
	}
	new Ajax.Request('includes/cx_ajax.php', {
		parameters: params,
		onSuccess: function(r) {
			l = r.responseText;
			$(stateMenu + "holder").innerHTML = l;
			if (reg == 1) {
				$(stateMenu + '_label').innerHTML = 'state';
			} else if (reg == 2) {
				$(stateMenu + '_label').innerHTML = 'province';
			}
		}
	});
}

//http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript
Number.prototype.formatMoney = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

