/* ############################################# */
/* #  WocaDirect                               # */
/* # ......................................... # */
/* #  RUBIX MEDIA LLC                          # */
/* #  @pgold - 7 JUN 2009                      # */
/* ############################################# */


var GLOBAL_THIS = (function(){return this;})();

// Initialize globals
var page_init = function() {
//	updateCartCount.init();
	sidebarContent.init();
	productThumbs.init();
	externalLauncher.init();               // External links
}
jQuery(document).ready(page_init);


var productThumbs = {
	init: function() {
		var imgContainer = jQuery('.single_product_display .imagecol')[0];
		if (!imgContainer) return;

		var sv = document.createElement('div');
		sv.className = "swatchViewer";
		for (var i=0; i<imgContainer.childNodes.length; i++) {
			sv.appendChild(imgContainer.childNodes[i]);
		}
		imgContainer.appendChild(sv);

		var firstThumb = jQuery('.single_product_display .imagecol a.preview_link:first')[0];
		jQuery(firstThumb).wrap('<div class="viewPane"></div>');
		productThumbs.viewPane   = firstThumb.parentNode;
		productThumbs.viewAnchor = jQuery('a',productThumbs.viewPane)[0];
		productThumbs.viewImg    = jQuery('img',productThumbs.viewAnchor)[0];

		var prodViews  = productThumbs.prodViews();
		var colorViews = productThumbs.colorViews();

		if (prodViews)  sv.appendChild(prodViews);
		if (colorViews) sv.appendChild(colorViews);

		// fix page height as needed
		var prodPageContainer = jQuery('div.single_product_display div.textcol')[0];
		var imageCol = jQuery('div.single_product_display div.textcol div.imagecol')[0];
		if (prodPageContainer.offsetHeight < imageCol.offsetHeight) {

			prodPageContainer.style.height = imageCol.offsetHeight + "px";
		}

		productThumbs.setCurrent(jQuery('.swatchViewer .thumbs li')[0]);
	},
	prodViews: function() {
		var imgSet = jQuery('.single_product_display .imagecol a.preview_link img');
		if (!imgSet) return;

		return productThumbs.constructThumbSet(imgSet,"productThumbs","Product Views");
	},
	colorViews: function() {
		// get select box containing color variants
		var variation_labels = jQuery('.wpsc_variation_forms label');
		for (var i=0; i<variation_labels.length; i++) {
			var lbl = (jQuery(variation_labels[i]).html()).toLowerCase();
			if ( lbl.match('oil colors') || lbl.match('color')) {
				var label_for = jQuery(variation_labels[i]).attr('for');
				productThumbs.colorSelect = document.getElementById(label_for);
				break;
			}
		}
		if (!productThumbs.colorSelect) return;

		// get list of color names
		productThumbs.colorList = new Array;
		jQuery('option',productThumbs.colorSelect).each(function (i) {
			var colorName = (jQuery(this).text());
			productThumbs.colorList.push(colorName);
		});
		if (!productThumbs.colorList) return;

		// get img references
		var imgSet = new Array;
		for (var i=0; i<productThumbs.colorList.length; i++) {
			var img = document.createElement('img');
			var fileStr = ((productThumbs.colorList[i]).toLowerCase());
			fileStr = fileStr.replace( new RegExp( "\\b[ ]+", "gi" ), "_" );
			img.src = '/wp-content/themes/woca/images/products/colors/thumbnails/color_'+fileStr+'.jpg';
			img.alt = productThumbs.colorList[i];
			imgSet.push(img);
		}

		return productThumbs.constructThumbSet(imgSet,"colorThumbs","Swatches");
	},
	constructThumbSet: function(imgSet, thumbClass, title) {
		if (!imgSet.length > 0) return;
		if (!title) title="";

		var container = document.createElement('div');
		container.className = "thumbsContainer "+thumbClass;

		var thumbs = document.createElement('ul');
		thumbs.className = "thumbs"

		jQuery(container).html('<h6>'+title+' ('+imgSet.length+')</h6>');
		for (var i=0; i<imgSet.length; i++) {
			var img = jQuery(imgSet[i]).clone()[0];
			jQuery(img).removeClass('product_image');

			var tn = document.createElement('li');
			var anchor = document.createElement('a');
			anchor.href = img.src.replace("thumbnails/","");
			anchor.rel = title.replace( new RegExp( "\\b[ ]+", "gi" ), "_" );
			jQuery(anchor).bind('click',productThumbs.thumbClick);
			if (thumbClass=="colorThumbs") {
				jQuery(tn).hover(productThumbs.thumbHover,productThumbs.thumbHoverOut);
			}

			productThumbs.viewAnchor = jQuery('a',productThumbs.viewPane)[0];
			anchor.title = productThumbs.viewAnchor.title + ' - Color: ' + img.alt;

			anchor.appendChild(img);
			tn.appendChild(anchor);
			tn.anchor = anchor;
			anchor.tn = tn;
			thumbs.appendChild(tn);
			container.appendChild(thumbs);
		}
		return container;
	},
	thumbHover: function(e) {
		rbx_cmn.kill_event(e);
		var targetImg = (e.target.tagName=='IMG') ? e.target : jQuery(e.target).find('IMG')[0];
		productThumbs.setColorName(targetImg.alt);
	},
	thumbHoverOut: function(e) {
		rbx_cmn.kill_event(e);
		var targetImg = (e.target.tagName=='IMG') ? e.target : jQuery(e.target).find('IMG')[0];
		productThumbs.setColorName('');
	},
	thumbClick: function(e) {
		rbx_cmn.kill_event(e);
		var targetAnchor = e.target.parentNode;
		var targetImg = e.target;

		productThumbs.viewAnchor = jQuery('a',productThumbs.viewPane)[0];
		productThumbs.viewImg    = jQuery('img',productThumbs.viewAnchor)[0];

		if (!targetAnchor) {
			alert('targetAnchor: '+targetAnchor+', e.target: '+e.target);
		}
		productThumbs.viewAnchor.rel = targetAnchor.rel;
		productThumbs.viewAnchor.href = targetAnchor.href;
		productThumbs.viewAnchor.title = productThumbs.viewAnchor.title + " - Color: " + targetImg.alt;

		productThumbs.viewImg.src = targetImg.src;
		productThumbs.viewImg.alt = targetImg.alt;

		var thumbHdr = jQuery('.colorThumbs h6 span')[0];
		if (thumbHdr) {
			jQuery(thumbHdr).text('');
		}

		if (productThumbs.viewAnchor.rel == "Swatches") {
			var colorName = productThumbs.viewImg.alt;
			var options = jQuery('option',productThumbs.colorSelect);
			for (var i=0; i<options.length; i++) {
				if (jQuery(options[i]).text() == colorName) {
					productThumbs.colorSelect.selectedIndex = i;
					if (productThumbs.colorSelect.onchange) {
						productThumbs.colorSelect.onchange();
					} else if(jQuery(productThumbs.colorSelect).change) {
						jQuery(productThumbs.colorSelect).change();
					}
					break;
				}
			}
			productThumbs.setColorName(colorName);
			thumbHdr.selectedName = jQuery(thumbHdr).text();
		}

		productThumbs.setCurrent(targetAnchor.parentNode);
	},
	setColorName: function(colorName) {
		var thumbHdr = jQuery('.colorThumbs h6 span')[0];
		if (thumbHdr) {
			if (colorName == '') {
				thumbHdr.selectedName = (thumbHdr.selectedName) ? thumbHdr.selectedName : '';
				jQuery(thumbHdr).text(thumbHdr.selectedName);
			} else {
				jQuery(thumbHdr).text(': '+colorName);
			}
		} else {
			jQuery('.colorThumbs h6')[0].innerHTML += '<span>: '+colorName+'</span>';
		}
	},
	setCurrent: function(current) {
		jQuery('.swatchViewer .thumbs li').each(function(i) {
			jQuery(this).removeClass("current");
		});
		jQuery(current).addClass("current");
	}
};





// handle cart
// ..........................
var updateCartCount = {
	init: function() {
		jQuery('input.wpsc_buy_button').bind('click',updateCartCount.increment);
	},
	increment: function(e) {
		var retval = rbxAjax.call_ext_function("nzshpcrt_overall_total_price","update","updateCartCount");
	},
	update: function(data) {
		jQuery('.globalCart #hdr_cart_count').html(data);
	}
};




var sidebarContent = {
	init: function() {
		var single_additional_description = jQuery('.single_additional_description')[0];
		var sidebarComponents = jQuery('.single_additional_description .content-sidebar');
		var sidebar = jQuery('.sidebar')[0];
		if (sidebarComponents.length == 0 || !sidebar) return;
		//jQuery(single_additional_description).hide();
		for (var i=0; i<sidebarComponents.length; i++) {
			jQuery(sidebarComponents[i]).addClass("component");
		
			if (jQuery(sidebarComponents[i]).hasClass("downloads")) {
				var callout = document.createElement("div");
				jQuery(callout).addClass("callout")

				for (var n=0; n<sidebarComponents[i].childNodes.length; n++) {
					var node = sidebarComponents[i].childNodes[n];
					if (node == callout) continue;
					if (node.tagName == "H3") continue;
					if (node.innerHTML == undefined) { continue; }

					var linkhtml = (jQuery(node).html()) ? jQuery(node).html() : '';
					jQuery("<span />")
						.addClass( "download" )
						.html(linkhtml)
						.appendTo(callout);

					jQuery(node).remove();
				}
				jQuery(callout).appendTo(sidebarComponents[i]);
			}
			jQuery(sidebar).append(jQuery(sidebarComponents[i]).clone());
		}

		// remove empty text nodes -- this is suspect
		/*
		for (var i=0; i<single_additional_description.childNodes.length; i++) {
			if (!single_additional_description.childNodes[i].tagName) {
				jQuery(single_additional_description.childNodes[i]).remove();
				i--;
			}
		}
		// if we have other additional content, show the div
		if (single_additional_description.childNodes.length > 0) {
			jQuery(single_additional_description).show();
		}
		*/
	}
};




// EXTERNAL LINKS *****************
var externalLauncher={
	init:function(){
		externalLauncher.installListeners();
	},
	installListeners:function(){
		var anchors=document.getElementsByTagName('a');
		for(var i=0;i<anchors.length;i++){
			if(anchors[i].className.match('external')){
				jQuery(anchors[i]).bind('click',externalLauncher.eventLaunch);
			}
		}
	},
	eventLaunch:function(e){
		var target = externalLauncher.getEventTarget(e);
		while (target!=document&&!(target.href)) {
			target=target.parentNode;
		}
		window.open(target.href);
		rbx_cmn.kill_event(e);
	},
	getEventTarget:function(e){return window.event?window.event.srcElement:e?e.target:null;}
};
// ********************************






// ********************************
// rubix common utility functions
// ................................
var rbx_cmn = {
	get_ancestor_by_tag: function(obj, tag) {
		if (obj == document) return null;
		return (obj.tagName == tag) ? obj : rbx_cmn.get_ancestor_by_tag(obj.parentNode, tag);
	},
	get_ancestor_by_class: function(obj, target_class) {
		if (obj == document) return null;
		return (obj.className.match(target_class)) ? obj : rbx_cmn.get_ancestor_by_class(obj.parentNode, target_class);
	},
	get_inherited_font_size: function(obj) {
		if (obj == document) return -1;
		return ((obj.style.fontSize).length > 0) ? obj.style.fontSize : rbx_cmn.get_inherited_font_size(obj.parentNode);
	},
	kill_event: function(e) {
		if (window.event){window.event.cancelBubble=true;window.event.returnValue=false;window.event.srcElement.blur();}if(e&&e.stopPropagation&&e.preventDefault){e.stopPropagation();e.preventDefault();e.target.blur();}
	},
	is_hidden: function(obj) {
		if ((obj.style.display == "none"||obj.style.visibility=="hidden")) return true;
		return false;
	},
	rand: function(lower,upper) { return (Math.floor((upper-(lower-1))*Math.random()) + lower); }
};

// ................................
// rubix ajax methods
// ................................
var rbxAjax = {
	call_ext_function: function(targetFunction,callback,callbackScope) {
		jQuery.ajax({
			type: "GET",
			url: "/wp-content/themes/woca/functions.php",
			data: ({functionCall : targetFunction}),
			success: function(data){
				if (callbackScope)
					GLOBAL_THIS[callbackScope][callback](data);
				else
					GLOBAL_THIS[callback](data);
			}
		});
	}
};
// ********************************
