//mapbox plugin
/* jQuery Map Plugin
 * Version 0.5.1
 * Author Abel Mohler
 * Developed for Kukio July 2009
 * Released with the MIT License: http://www.opensource.org/licenses/mit-license.php
 */
(function(a){a.fn.mapbox=function(c,i){var e={zoom:true,pan:true,defaultLayer:0,layerSplit:4,mapContent:".mapcontent",defaultX:null,defaultY:null,callBefore:function(n,m,l,k){},callAfter:function(n,m,l,k){},beforeZoom:function(n,m,l,k){},afterZoom:function(n,m,l,k){},mousewheel:false};if(typeof i=="function"){c.callAfter=i}var d;if(typeof c=="string"){d=c}c=a.extend(e,c||{});a(this).css({overflow:"hidden",position:"relative"});function h(o){if(!c.zoom){return}if(o===0){return}else{o=o||1}var s=a(this).find(">div"),C=s.length-1,A=a(this).find(".current-map-layer");if(typeof c.beforeZoom=="function"){c.beforeZoom(A[0],this.xPos,this.yPos,this)}var B=this.visible,G=B;B+=(o/c.layerSplit);if(B<0){B=0}if(B>C){B=C}G=Math.ceil(B);this.visible=B;var y=A.width(),u=A.height();var k=((a(this).width()/2)+this.xPos)/y,x=((a(this).height()/2)+this.yPos)/u;if(c.layerSplit>1&&G>0){var l=B-(G-1),w=s.eq(G)[0].defaultWidth,v=s.eq(G)[0].defaultHeight,r=s.eq(G-1).width(),q=s.eq(G-1).height();var p=w-r,n=v-q,m=r+(p*l),D=q+(n*l);s.eq(G).width(m).find(".map-layer-mask").width(m).height(D);s.eq(G).height(D).find(c.mapContent).width(m).height(D)}var z=(s.eq(G).width()*k)-(a(this).width()/2),t=(s.eq(G).height()*x)-(a(this).height()/2);z=0-z;t=0-t;var F=a(this).width()-s.eq(G).width(),E=a(this).height()-s.eq(G).height();if(z>0){z=0}if(t>0){t=0}if(z<F){z=F}if(t<E){t=E}this.xPos=0-z;this.yPos=0-t;s.removeClass("current-map-layer").hide();s.eq(G).css({left:z+"px",top:t+"px",display:"block"}).addClass("current-map-layer");if(typeof c.afterZoom=="function"){c.afterZoom(s.eq(G)[0],this.xPos,this.yPos,this)}}function j(t,s,o){o=o||a(this).find(".current-map-layer");var m=0,l=0,p=a(this).width(),q=a(this).height(),u=a(o).width(),k=a(o).height();if(p<u){m=p-u}if(q<k){l=q-k}var n=0-(this.xPos+t),r=0-(this.yPos+s);n=(n>0)?0:n;n=(n<m)?m:n;r=(r>0)?0:r;r=(r<l)?l:r;this.xPos=0-n;this.yPos=0-r;a(o).css({left:n+"px",top:r+"px"})}function g(k,o,l){l=l||a(this).find(".current-map-layer");k=0-k;o=0-o;var n=0-(a(l).width()-a(this).width());var m=0-(a(l).height()-a(this).height());if(k>0){k=0}if(o>0){o=0}if(k<n){k=n}if(o<m){o=m}this.xPos=0-k;this.yPos=0-o;a(l).css({left:k+"px",top:o+"px"})}function f(k){k=k.replace(/px/,"");k=0-k;return k}var b={zoom:function(k){k=k||1;h.call(this,k)},back:function(k){k=k||1;h.call(this,0-k)},left:function(k){k=k||10;j.call(this,0-k,0)},right:function(k){k=k||10;j.call(this,k,0)},up:function(k){k=k||10;j.call(this,0,0-k)},down:function(k){k=k||10;j.call(this,0,k)},center:function(l){l=l||{x:a(this).find(".current-map-layer").width()/2,y:a(this).find(".current-map-layer").height()/2};var k=a(this).find(".current-map-layer");var n=l.x-(a(this).width()/2),m=l.y-(a(this).height()/2);g.call(this,n,m,k[0])},zoomTo:function(l){var k=Math.round((l-this.visible)/(1/this.layerSplit));h.call(this,k)}};return this.each(function(){if(typeof d=="string"){var u=b[d];c.layerSplit=this.layerSplit||c.layerSplit;u.call(this,i)}else{this.visible=c.defaultLayer,this.layerSplit=c.layerSplit;var t=this,o=a(this).find(">div"),s=a(this).height(),q=a(this).width(),p=false,r=true;o.css({position:"absolute"}).eq(c.defaultLayer).css({display:"block",left:"",top:""}).addClass("current-map-layer").find(c.mapContent).css({position:"absolute",left:"0",top:"0",height:s+"px",width:"100%"});o.each(function(){this.defaultWidth=a(this).width();this.defaultHeight=a(this).height();a(this).find(c.mapContent).css({position:"absolute",top:"0",left:"0"});if(a(this).find(c.mapContent).length>0){a(this).find(">img").css({width:"100%",position:"absolute",left:"0",top:"0"}).after('<div class="map-layer-mask"></div>')}});a(this).find(".map-layer-mask").css({position:"absolute",left:"0",top:"0",background:"white",opacity:"0",filter:"alpha(opacity=0)"});if(c.defaultLayer>0){o.eq(c.defaultLayer).find(".map-layer-mask").width(o.eq(c.defaultLayer).width()).height(o.eq(c.defaultLayer).height());o.eq(c.defaultLayer).find(c.mapContent).width(o.eq(c.defaultLayer).width()).height(o.eq(c.defaultLayer).height())}a(this).find(">div:not(.current-map-layer)").hide();if(c.defaultX==null){c.defaultX=Math.floor((q/2)-(a(this).find(".current-map-layer").width()/2));if(c.defaultX>0){c.defaultX=0}}if(c.defaultY==null){c.defaultY=Math.floor((s/2)-(a(this).find(".current-map-layer").height()/2));if(c.defaultY>0){c.defaultY=0}}this.xPos=0-c.defaultX;this.yPos=0-c.defaultY;this.layerSplit=c.layerSplit;var n=c.defaultX;var m=c.defaultY;var l;var k;a(this).find(".current-map-layer").css({left:c.defaultX+"px",top:c.defaultY+"px"});a(this).mousedown(function(){var w=a(this).find(".current-map-layer");var v=w[0].style.left,z=w[0].style.top;v=f(v);z=f(z);c.callBefore(w,v,z,t);p=true;r=true;return false});a(document).mouseup(function(){var w=a(t).find(".current-map-layer");var v=w[0].style.left,z=w[0].style.top;v=f(v);z=f(z);c.callAfter(w,v,z,t);p=false;return false});a(document).mousemove(function(A){var x=a(t).find(".current-map-layer");if(p&&c.pan){if(r){l=A.clientX;k=A.clientY;n=x[0].style.left.replace(/px/,"");m=x[0].style.top.replace(/px/,"");r=false}var z=0,y=0;if(q<x.width()){z=q-x.width()}if(s<x.height()){y=s-x.height()}var w=n-(l-A.clientX);w=(w>0)?0:w;w=(w<z)?z:w;var v=m-(k-A.clientY);v=(v>0)?0:v;v=(v<y)?y:v;x.css({left:w+"px",top:v+"px"});t.xPos=f(x[0].style.left);t.yPos=f(x[0].style.top)}});if(c.mousewheel&&typeof a.fn.mousewheel!="undefined"){a(t).mousewheel(function(v,w){h.call(this,w);return false})}a(window).load(function(){o.each(function(){var v=a(this).find("img")[0];if(typeof v=="object"){a("<img>").attr("src",v.src)}})})}})}})(jQuery);

//scrollTo plugin
/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

//selectBoxes plugin
/*
 *
 * Copyright (c) 2006-2008 Sam Collett (http://www.texotela.co.uk)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 2.2.4
 * Demo: http://www.texotela.co.uk/code/jquery/select/
 *
 * $LastChangedDate: 2008-06-17 17:27:25 +0100 (Tue, 17 Jun 2008) $
 * $Rev: 5727 $
 *
 */
;(function(h){h.fn.addOption=function(){var j=function(a,f,c,g){var d=document.createElement("option");d.value=f,d.text=c;var b=a.options;var e=b.length;if(!a.cache){a.cache={};for(var i=0;i<e;i++){a.cache[b[i].value]=i}}if(typeof a.cache[f]=="undefined")a.cache[f]=e;a.options[a.cache[f]]=d;if(g){d.selected=true}};var k=arguments;if(k.length==0)return this;var l=true;var m=false;var n,o,p;if(typeof(k[0])=="object"){m=true;n=k[0]}if(k.length>=2){if(typeof(k[1])=="boolean")l=k[1];else if(typeof(k[2])=="boolean")l=k[2];if(!m){o=k[0];p=k[1]}}this.each(function(){if(this.nodeName.toLowerCase()!="select")return;if(m){for(var a in n){j(this,a,n[a],l)}}else{j(this,o,p,l)}});return this};h.fn.ajaxAddOption=function(c,g,d,b,e){if(typeof(c)!="string")return this;if(typeof(g)!="object")g={};if(typeof(d)!="boolean")d=true;this.each(function(){var f=this;h.getJSON(c,g,function(a){h(f).addOption(a,d);if(typeof b=="function"){if(typeof e=="object"){b.apply(f,e)}else{b.call(f)}}})});return this};h.fn.removeOption=function(){var d=arguments;if(d.length==0)return this;var b=typeof(d[0]);var e,i;if(b=="string"||b=="object"||b=="function"){e=d[0];if(e.constructor==Array){var j=e.length;for(var k=0;k<j;k++){this.removeOption(e[k],d[1])}return this}}else if(b=="number")i=d[0];else return this;this.each(function(){if(this.nodeName.toLowerCase()!="select")return;if(this.cache)this.cache=null;var a=false;var f=this.options;if(!!e){var c=f.length;for(var g=c-1;g>=0;g--){if(e.constructor==RegExp){if(f[g].value.match(e)){a=true}}else if(f[g].value==e){a=true}if(a&&d[1]===true)a=f[g].selected;if(a){f[g]=null}a=false}}else{if(d[1]===true){a=f[i].selected}else{a=true}if(a){this.remove(i)}}});return this};h.fn.sortOptions=function(e){var i=h(this).selectedValues();var j=typeof(e)=="undefined"?true:!!e;this.each(function(){if(this.nodeName.toLowerCase()!="select")return;var c=this.options;var g=c.length;var d=[];for(var b=0;b<g;b++){d[b]={v:c[b].value,t:c[b].text}}d.sort(function(a,f){o1t=a.t.toLowerCase(),o2t=f.t.toLowerCase();if(o1t==o2t)return 0;if(j){return o1t<o2t?-1:1}else{return o1t>o2t?-1:1}});for(var b=0;b<g;b++){c[b].text=d[b].t;c[b].value=d[b].v}}).selectOptions(i,true);return this};h.fn.selectOptions=function(g,d){var b=g;var e=typeof(g);if(e=="object"&&b.constructor==Array){var i=this;h.each(b,function(){i.selectOptions(this,d)})};var j=d||false;if(e!="string"&&e!="function"&&e!="object")return this;this.each(function(){if(this.nodeName.toLowerCase()!="select")return this;var a=this.options;var f=a.length;for(var c=0;c<f;c++){if(b.constructor==RegExp){if(a[c].value.match(b)){a[c].selected=true}else if(j){a[c].selected=false}}else{if(a[c].value==b){a[c].selected=true}else if(j){a[c].selected=false}}}});return this};h.fn.copyOptions=function(g,d){var b=d||"selected";if(h(g).size()==0)return this;this.each(function(){if(this.nodeName.toLowerCase()!="select")return this;var a=this.options;var f=a.length;for(var c=0;c<f;c++){if(b=="all"||(b=="selected"&&a[c].selected)){h(g).addOption(a[c].value,a[c].text)}}});return this};h.fn.containsOption=function(g,d){var b=false;var e=g;var i=typeof(e);var j=typeof(d);if(i!="string"&&i!="function"&&i!="object")return j=="function"?this:b;this.each(function(){if(this.nodeName.toLowerCase()!="select")return this;if(b&&j!="function")return false;var a=this.options;var f=a.length;for(var c=0;c<f;c++){if(e.constructor==RegExp){if(a[c].value.match(e)){b=true;if(j=="function")d.call(a[c],c)}}else{if(a[c].value==e){b=true;if(j=="function")d.call(a[c],c)}}}});return j=="function"?this:b};h.fn.selectedValues=function(){var a=[];this.selectedOptions().each(function(){a[a.length]=this.value});return a};h.fn.selectedTexts=function(){var a=[];this.selectedOptions().each(function(){a[a.length]=this.text});return a};h.fn.selectedOptions=function(){return this.find("option:selected")}})(jQuery);

//cookie plugin
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

// make this script compatible with other frameworks
jQuery.noConflict(); 

jQuery(document).ready(function(){ 
								
	// trigger the baynote.js setCollectionNav function that gets blanked by jQuery
	setNavHighlight();
	
	// if the browser is Opera, hide the non-functional zoom button
	if (jQuery.browser.opera){
		jQuery('.control-box').css("display","none");
	}
	
	// set up some global variables
	var imgPath = '';
	var prodImgPath = '';
	var matrixOutput = '';
	var finish = '';
	var finishName = '';
	var knob = '';
	var shade = '';
	var glass = '';
	var color = '';
	var extension = '';	
	var prodImgBase = '';
	var matrixMasterHeight = 460;
	var thumbStyle = "matrixThumb";
	var loadingDiv = '<div id="loading"><img id="loadingIcon" src="http://img.houseofantiquehardware.com/flashternative/hoah_loading_H.gif" /></div>';
	var preloadDiv = '<div id="imgPreload" style="display:block;position:absolute;top:0;left:0;width:1px;height:1px;background:#000000;overflow:hidden;">&nbsp;</div>';
	var zoomState = 'full';
	var matrixVisible = ',Finishes,Glass Color,Color,Suggested Shades,Knobs,Shade Color,';
	//var matrixVisible = 'custcol_finish,custcol_glass_color,custcol_elec_color,custcol_picture_cord_color';
	jQuery('body').append(loadingDiv);
	jQuery('body').append(preloadDiv);
			
	//recast the xml file in lowercase in case it's not already
	productXML = productXML.toLowerCase();
	
	// Open the xml file
	jQuery.get(productXML,{},function(xml){				  
		
		//count how many visible matrices there are (for use in determining heights of divs)
		var matrixCount = 0;
		jQuery('matrix',xml).each(function(k) {
			matrixLabel = jQuery(this).attr("myLabel");
			matrixCartVar = jQuery(this).attr("cartVar");
			if(matrixVisible.indexOf(',' + matrixLabel + ',') > -1) {
				matrixCount++;
				//set the variables for image display based on the matrix label and the first thumbnail image found in each matrix
				switch(matrixCartVar){
					case "custcol_finish":
					jQuery('thumb',this).each(function(l) {
						if (finish == ''){
							finish = jQuery(this).attr("imDiscriptor");
						}
					});
					break;
					case "custcol_glass_color":
					jQuery('thumb',this).each(function(l) {
						if (glass == ''){
							glass = jQuery(this).attr("imDiscriptor");
						}
					});
					break;
					case "custcol_elec_color":
					jQuery('thumb',this).each(function(l) {
						if (color == ''){
							color = jQuery(this).attr("imDiscriptor");
						}
					});
					break;					
					case "custcol_wood":
					jQuery('thumb',this).each(function(l) {
						if (finish == ''){
							finish = jQuery(this).attr("imDiscriptor");
						}
					});
					break;					
					case "custcol_picture_cord_color":
					jQuery('thumb',this).each(function(l) {
						if (color == ''){
							color = jQuery(this).attr("imDiscriptor");
						}
					});					
					break;
					case "custcol_interior_knob":
					jQuery('thumb',this).each(function(l) {
						if (knob == ''){
							knob = jQuery(this).attr("imDiscriptor");
						}
					});					
					break;					
				}
			}
		});

		//set the heights of the matrixes to draw so they all fit in the panel provided
		matrixHeight = Math.floor(matrixMasterHeight / matrixCount);
		var innerMatrixHeight = matrixHeight - 16;
		
		// Build an HTML string
		myHTMLOutput = '';
	  	
		// get the setup info
		jQuery('setUps',xml).each(function(i) {
			imgPath = jQuery(this).attr("supportImsPath");
		});
				
		jQuery('product',xml).each(function(j) {
			prodTitle = jQuery(this).attr("Title");
			prodImgBase = jQuery(this).attr("itNum");
			myHTMLOutput = myHTMLOutput + "<h2>" + prodTitle + "</h2>";
			prodImgPath = jQuery(this).attr("imPath");
		});

		//if there is a default finish option set in the xml, use it.
		jQuery('defaultFinish',xml).each(function(y) {
			finish = jQuery(this).attr("imDiscriptor");
			finishName = jQuery(this).attr("Name");
		});

				
		//if a cookie has been set with the last-seen finish, use it instead
		if(jQuery.cookie(prodImgBase + "-finish")){
			finish = jQuery.cookie(prodImgBase + "-finish");
		}
		if(jQuery.cookie(prodImgBase + "-knob")){
			knob = jQuery.cookie(prodImgBase + "-knob");
		}
		if(jQuery.cookie(prodImgBase + "-glass")){
			glass = jQuery.cookie(prodImgBase + "-glass");
		}
		if(jQuery.cookie(prodImgBase + "-shade")){
			shade = jQuery.cookie(prodImgBase + "-shade");
		}
		if(jQuery.cookie(prodImgBase + "-color")){
			color = jQuery.cookie(prodImgBase + "-color");
		}
		
		// loop through the list of matrices, build a div for each, and populate it
		jQuery('matrix',xml).each(function(k) {
			finishImagePath = jQuery(this).attr("imPath");
			matrixLabel = jQuery(this).attr("myLabel");
			selectListID = jQuery(this).attr("cartVar");
			// if the matrix label is present in the 'MatrixVisible' list, draw a thumbnail panel for it. Otherwise, skip it.
			if (matrixVisible.indexOf(matrixLabel) > -1) {
				//if the page contains a select list for this matrix already, clear its options
				jQuery("#" + selectListID).removeOption(/./);
				//build the matrixes (if found)
				jQuery('thumb',this).each(function(m) {
					if(matrixLabel == "Glass Color"){
						thumbStyle = "matrixThumbGlass";
					}
					else if(matrixLabel == "Knobs"){
						thumbStyle = "matrixThumbGlass";
					}
					myLabel = jQuery(this).attr("myLabel");
					thumbImage = jQuery(this).attr("thumbImage");
					thumbDescriptor = jQuery(this).attr("imDiscriptor");
					cartCode = jQuery(this).attr("cartCode");
					myMatrix = BuildMatrix(myLabel,thumbImage,finishImagePath,thumbDescriptor,finish,prodImgPath,prodImgBase,thumbStyle,selectListID,cartCode);
					matrixOutput = matrixOutput + myMatrix;
				});
				// add a div wrapper and a title to the matrix string
				matrixOutput = '<div class="matrix" id="' + matrixLabel + '" style="overflow:hidden;"><h3>' + matrixLabel + '</h3><div id="mtx-' + selectListID + '" style="height:' + innerMatrixHeight + 'px;width:100%;overflow:auto;">' + matrixOutput + '</div></div>';
				// Update the matrix with the string of images and names
				jQuery("#productMatrix").append(matrixOutput);
				matrixOutput = "";
			}
		});
		
		//find the proper matrix thumbnail ID based on the add-to-cart select list option
		function activateMatrixItem(selectID,cartVal){
			jQuery('matrix',xml).each(function(l) {
				if(jQuery(this).attr("cartVar") == selectID){
					jQuery('thumb',this).each(function(n){
						if(jQuery(this).attr("cartCode") == cartVal){
							thisAnchorID = "#" + jQuery(this).attr("imDiscriptor");
							//scroll to the relevent thumbnail
							jQuery('#mtx-' + selectID).scrollTo(thisAnchorID);
							jQuery(thisAnchorID).click();
						}
					});
				};
			});
		};
		
		//find the proper option in the select list corresponding to a matrix thumbnail and select it
		function selectMatrixOption(selectID,matrixThumbText){
			jQuery('thumb',xml).each(function(l) {
				if(jQuery(this).attr("myLabel") == matrixThumbText){
					var thisValue = jQuery(this).attr("cartCode");
					//select the option that matches the chosen finish
					jQuery('#' + selectID).selectOptions(thisValue, true);
					//activate the onchange functions for the matrix select list
					activateSelectOnchange();
				};
			});
		}
		
		//Change the item number text based on the options selected
		function updateItemNumber(){
			
		}
		
		// Set the default product image and zoomed counterpart
		prodImageMain = prodImgPath + prodImgBase + imgExtension() + '.jpg';
		prodImageZoom = prodImgPath + prodImgBase + imgExtension() + '-lg.jpg';

		//if there are no matrixes, hide the matrix master div and expand the photo area to fill the full width of the viewer
		if(matrixCount <= 0){
			jQuery('#productMatrix').css('display','none');
			jQuery('#productPhoto').css('width',jQuery('#productContainer').css('width'));
			jQuery('#loading').css('width',jQuery('#productContainer').css('width'));
		}
		
		//dynamically create the layers to be used for mapbox zooming
		var prodHTML = "";
		prodHTML = prodHTML + '<div style="background: url(' + prodImageMain + ') top center no-repeat; width: ' + jQuery("#productPhoto").css("width") + '; height: 485px; z-order: 10;" id="productMain">';
		prodHTML = prodHTML + '<!--top level map content goes here-->';
		prodHTML = prodHTML + '</div>';
		prodHTML = prodHTML + '<div style="height: 1120px; width: 819px;">';
		prodHTML = prodHTML + '<img name="productZoom" id="productZoom" src="' + prodImageZoom + '" alt="" />';
		prodHTML = prodHTML + '<div class="mapcontent">';
		prodHTML = prodHTML + '<!--map content goes here-->';
		prodHTML = prodHTML + '</div>';
		prodHTML = prodHTML + '</div>';
		
		//write the dynamic layers to the productPhoto div
		jQuery("#productPhoto").append(prodHTML);		
		
		//set the width, height, and position of the loading blank to fit the product photo
		var photoHeight = jQuery("#productPhoto").css("height");
		var photoWidth = jQuery("#productPhoto").css("width");
		var photoPos = jQuery("#productPhoto").position();
		
		// set the width of the caption box based on whether there are matrices or not
		if(matrixCount <= 0){
			jQuery("#caption-box").css('width','444px');
		}
		else {
			jQuery("#caption-box").css('width',photoWidth);
		}
		
		//if there's a default finish name, write it to the caption box
		//this is primarily used for non-matrix items with a default finish entry
		if(finishName != ''){
			jQuery("#caption-box").html("Pictured in " + finishName );
		}

		//write the included hardware panel into the productPhoto div if found in the XML
		jQuery('extra',xml).each(function(i) {
			var incMarginL;
			if(matrixCount >= 1){
				incMarginL = '5px';
			}
			else {
				incMarginL = '20px';
			}
			var incHwPic = imgPath + jQuery(this).attr('extraIm');
			var incHwHTML = '<div id="includedHardware" style="margin-left:' + incMarginL + ';">';
			if(typeof jQuery(this).attr('extraIm') != 'undefined'){
				incHwHTML = incHwHTML + '<div id="includedHardwareTitle" style="position:absolute;top:10px;left:0;height:24px;width:300px;margin-left:10px;text-align:center;"><img id="includedHardwareTriangle" src="http://img.houseofantiquehardware.com/flashternative/IncHwTriangleUp.gif" align="absmiddle"> ' + jQuery(this).attr('extraTitle') + '</div>';
				incHwHTML = incHwHTML + '<div style="position:absolute;top:32px;left:0;height:357px;width:300px;text-align:center;margin-left:10px;"><img src="' + incHwPic + '"><br />' + jQuery(this).attr('extraCopy') + '</div>';			
				incHwHTML = incHwHTML + '</div>';							  
				jQuery("#productContainer").append(incHwHTML);
			}
			
			// animate the panel when clicked
			jQuery('#includedHardware').toggle(
				function()
				{
					jQuery('#includedHardware').animate({top: "101"}, 1000, function() {
						jQuery('#includedHardwareTriangle').attr('src','http://img.houseofantiquehardware.com/flashternative/IncHwTriangleDown.gif');
					});
				},
				function()
				{
					jQuery('#includedHardware').animate({top: "459"}, 1000, function() {
						jQuery('#includedHardwareTriangle').attr('src','http://img.houseofantiquehardware.com/flashternative/IncHwTriangleUp.gif');
					});
			});
		});
		
		//call the mapbox functions
		jQuery("#productPhoto").mapbox({ 
			mousewheel: false
		}); 
		
		// clicking the control box (zoom) link triggers the zoom function
		jQuery("#zoom").click(function() {//control panel 
			var viewport = jQuery("#productPhoto");
			//this.className is same as method to be called 
			if(this.className == "zoom" || this.className == "back") {
				if(this.className == "zoom"){
					swapZoomImage();
				}
				viewport.mapbox(this.className, 3);//step twice
				if(this.className == "zoom"){
					this.className = "back";
					zoomState = "zoomed";
					//if the image is zoomed, change the CSS cursor to 'move'
					jQuery("#productPhoto").css("cursor","move");
				}
				else{
					this.className = "zoom";
					zoomState = "full";
					jQuery("#productPhoto").css("cursor","default");
				} 
			} 
			else { 
				viewport.mapbox(this.className); 
			} 
			return false; 
		});
		
		// trigger the swap of main and zoomed product images when a finish matrix item is clicked
		jQuery("#productMatrix a").click(function() {
			var matrixItem = jQuery(this).attr("id");
			var matrixClass = jQuery(this).attr("class");
			var parentID = jQuery(this).parent().attr("id");
			parentID = parentID.split("-");
			matrixParentID = parentID[1];
			//determine which variable to update based on the matrix that was clicked
			switch(matrixParentID){
				case "custcol_finish": 
					finish = matrixItem;
					break;
				case "custcol_wood": 
					finish = matrixItem;
					break;
				case "custcol_interior_knob": 
					knob = matrixItem;
					break;
				case "custcol_glass_color": 
					glass = matrixItem;
					break;
				case "custcol_elec_color": 
					color = matrixItem;
					break;
				case "custcol_picture_cord_color": 
					color = matrixItem;
					break;
			}
			var matrixText = jQuery("#" + matrixItem).text();
			selectedThumb = matrixItem;
			//finish = matrixItem.substr(4);
			//assemble the main and zoom image strings based on the finishID
			var thisExt = imgExtension();
			prodImageMain = 'url(' + prodImgPath + prodImgBase + imgExtension() + '.jpg)';
			prodImageZoom = prodImgPath + prodImgBase + imgExtension() + '-lg.jpg';
			//swap the main and zoomed images for the new ones as built above - but only if the link clicked isn't already marked "selected" in its id
			if(matrixClass.indexOf('Selected') == -1){
				swapProdImage(prodImageMain,prodImageZoom,jQuery(this));
			}
			jQuery("#caption-box").html("Pictured in " + matrixText );
			//set a cookie with the new thumbnail option, identified by the productID
			switch(matrixParentID){
				case "custcol_finish": 
					jQuery.cookie(prodImgBase + "-finish",selectedThumb,{expires: 14});
					break;
				case "custcol_interior_knob": 
					jQuery.cookie(prodImgBase + "-knob",selectedThumb,{expires: 14});
					break;
				case "custcol_glass_color": 
					jQuery.cookie(prodImgBase + "-glass",selectedThumb,{expires: 14});
					break;
				case "custcol_elec_color": 
					jQuery.cookie(prodImgBase + "-color",selectedThumb,{expires: 14});
					break;
				case "custcol_picture_cord_color": 
					jQuery.cookie(prodImgBase + "-color",selectedThumb,{expires: 14});
					break;
			}
			//change the select list under Add to Cart to the newly chosen option
			selectMatrixOption(matrixParentID,matrixText);
			return false;
		});
		
		// product image swapper (called above) that loads new main and zoomed images, displaying the loading icon until the zoom img is done
		function swapProdImage(mainImg,zoomImg,thumbnail){
			var matrixClass = thumbnail.attr("class");
			var matrixClassSelected = matrixClass + "Selected";	
			var selectedClass = matrixClass + ' ' + matrixClassSelected;
			//get the ID of the parent matrix of this thumbnail
			var matrixID = thumbnail.parent().attr('id');
			jQuery("#productMain").css("background-image", mainImg);
			//set all the thumbnails in this matrix to the unselected class (clearing any selected items)
			jQuery("#" + matrixID + " a").attr('class',matrixClass);
			thumbnail.attr('class',matrixClassSelected);
			//if the zoomstate is "zoomed", trigger the function to swap the zoomed product image
			if(zoomState == 'zoomed'){
				swapZoomImage();
			}
		}
		
		function swapZoomImage(){
			//determine which zoom image to load based on the current full image - requires a little substring juijitsu to extract from the url src
			//oh, and IE is a pain in the backside when calling load functions on cached images, so I had to append a random string to the URL to get it to work.
			var fullImageSrc = jQuery("#productMain").css("background-image");
			zoomImg = fullImageSrc.substr(fullImageSrc.indexOf('http'));
			zoomImg = zoomImg.substr(0,zoomImg.indexOf('.jpg')) + '-lg.jpg' + '?random=' + (new Date()).getTime();
			currentImg = jQuery("#productZoom").attr("src");
			//if the requested zoom img is different from the current image, show the "loading" blank, load the zoomed image, then hide the loading blank when it's loaded
			if(zoomImg != currentImg){	
				jQuery("#loading").css("display","block");
				jQuery("#productZoom").attr("src", zoomImg).load(function() {													  
					jQuery("#loading").css("display","none");
				});  
			}
		}
		
		//on initial page load, activate the default thumbnails and select option
		if(finish != ''){
			jQuery('#' + finish).click();
			var parentID = jQuery('#' + finish).parent().attr("id");
			jQuery('#' + parentID).scrollTo('#' + finish);
		}
		if (glass != ''){
			jQuery('#' + glass).click();
			var parentID = jQuery('#' + glass).parent().attr("id");
			jQuery('#' + parentID).scrollTo('#' + glass);
		}
		if (knob != '') {
			jQuery('#' + knob).click();
			var parentID = jQuery('#' + knob).parent().attr("id");
			jQuery('#' + parentID).scrollTo('#' + knob);
		}
		if (shade != '') {
			jQuery('#' + shade).click();
			var parentID = jQuery('#' + shade).parent().attr("id");
			jQuery('#' + parentID).scrollTo('#' + shade);
		}
		if (color != '') {
			jQuery('#' + color).click();
			var parentID = jQuery('#' + color).parent().attr("id");
			jQuery('#' + parentID).scrollTo('#' + color);
		}
		
		//manually monitor the select lists in the add-to-cart area for changes that affect the visual matrices
		jQuery('#custcol_glass_color').change(function(){
			thisCartVal = jQuery('#custcol_glass_color').val();
			activateMatrixItem('custcol_glass_color',thisCartVal);
		});
		
		jQuery('#custcol_finish').change(function(){
			thisCartVal = jQuery('#custcol_finish').val();
			activateMatrixItem('custcol_finish',thisCartVal);
		});
		
		jQuery('#custcol_wood').change(function(){
			thisCartVal = jQuery('#custcol_wood').val();
			activateMatrixItem('custcol_wood',thisCartVal);
		});		

		jQuery('#custcol_interior_knob').change(function(){
			thisCartVal = jQuery('#custcol_interior_knob').val();
			activateMatrixItem('custcol_interior_knob',thisCartVal);
		});

		jQuery('#custcol_elec_color').change(function(){
			thisCartVal = jQuery('#custcol_elec_color').val();
			activateMatrixItem('custcol_elec_color',thisCartVal);
		});

		jQuery('#custcol_picture_cord_color').change(function(){
			thisCartVal = jQuery('#custcol_picture_cord_color').val();
			activateMatrixItem('custcol_picture_cord_color',thisCartVal);
		});

		//based on the visible matrixes found, figure out the order of the thumbnail variables and concatenate them into a filename extension
		function imgExtension(){
			if(matrixCount <= 1){
				if (finish != '') {
					extension = "-" + finish;
				}
				if (glass != '') {
					extension = "-" + glass;
				}
				if (knob != '') {
					extension = "-" + knob;
				}
				if (color != '') {
					extension = "-" + color;
				}
			}
			if(matrixCount == 2){
				//if there are two matrices and we find a finish and knob option, assume this is a double-matrix doorset
				if(finish != '' || knob != ''){
					extension = "-" + knob + "-" + finish;
				}
			}
			return extension;
		}
		
	});
	
	//the root function that builds the panels of thumbnails based on input from the XML matrices
	function BuildMatrix(myLabel,thumbImage,finishImagePath,thumbDescriptor,finish,prodImgPath,prodImgBase,thumbStyle,selectListID,cartCode){
		var thisThumbImg = finishImagePath + thumbImage + ".jpg";
		var swapLink = "javascript:swapProdImg('" + thumbDescriptor + "','" + prodImgPath + "','" + prodImgBase + "');";
		if(thumbDescriptor != finish){
			thisThumbStyle = thumbStyle;
		}
		else {
			thisThumbStyle = thumbStyle + 'Selected';
		}
		output = '';
		output += '<a href="#" class="' + thisThumbStyle + '" id="' + thumbDescriptor + '" style="background-image:url(' + thisThumbImg + ')">';
		output += myLabel + '</a>';
		
		//add the matrix item to its corresponding select list in the add-to-cart area
		jQuery("#" + selectListID).addOption(cartCode, myLabel);
		
		//preload the main product image by inserting a call to it in the hidden #imgPreload div
		var prodImage = '<div style="width:150px;height:150px;background-image:url(' + prodImgPath + prodImgBase + '-' + thumbDescriptor + '.jpg);">&nbsp;</div>';
		jQuery("#imgPreload").append(prodImage);
		return output;
	}
});

jQuery.noConflict();
