// JavaScript Document for product detail page(s), this should be included after jquery.product.js

// Function: openMap(); Takes in nothing and displays the alternate MAP pricing description window
function openMap(){
	window.open('/call_for_pricing.html','call_for_pricing','toolbar=no,status=no,scrollbars=auto,location=no,menubar=no,directories=no,resizable=1,width=300,height=300,top=0');
	return false;
}

// Function: showCompare will show the side-by-side comparison if available
function showCompare(){
	/* determine if we have any additional content to show on initial page load */
	if( document.getElementById('compare_and_save') ){
		$('#tblProductContent').hide();
		/*$('#content_placeholder').html( $('#breadcrumb').html()+document.getElementById('compare_and_save').innerHTML );*/
		document.getElementById('content_placeholder').innerHTML = $('#breadcrumb').html()+$('#compare_and_save').html();
	}
}
// Function: hideCompare will hide the side-by-side comparison if available
function hideCompare(){
	$('#content_placeholder').hide();
	$('#tblProductContent').show();
}

function changeTab( currentTab ){
	// Create an arrary with each of our available divs to toggle
	possibleNames = 'details,specsheet,buying_guides,msds,warranty,nutrition'.split(',');
	// Clean up our input
	currentTab = currentTab.replace(/img/i,'');
	// Now look over each index from our array
	for( index in possibleNames ){
		// Create a local var for this index location
		currPos = possibleNames[index];
		// First check to see if we are on the current tab
		if( currPos == currentTab ){
			// Switch color to yellow (active) and show our content
			strDisplay = 'block';
			strColor = 'tan';
		}
		else{
			// Switch color to gray (in-active) and hide our content
			strDisplay = 'none';
			strColor = 'grey';
		}
		// Now perform our work with our values
		divObj = document.getElementById(currPos);
		buttonObj = document.getElementById(currPos+'btn');
		if( divObj && buttonObj ){
			// Element exist, continue
			divObj.style.display = strDisplay;
			buttonObj.className = strColor+'_button';
		}
	}
}

/* MAP Popup script */
this.mapPopup = function(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = -340;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.preview").hover(function(e){
		/* Determine if we have IE, if so we need to hide our dropdown */
		if( $.browser.msie ){
			parentObj = $('#item_number').parent();
			parentObj.width(parentObj.width());
			parentObj.height(parentObj.height());
			$('#item_number').hide();
		}
		
		$("#map_popup")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.show();
    },
	function(){
		$("#map_popup").hide();
		if( $.browser.msie )
			$('#item_number').show();
    });	
	$("a.preview").mousemove(function(e){
		$("#map_popup")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

$(document).ready(function() {
	/* start our map popup code */
	$('a.map1_link').Map_Tooltip( 'map1_popup' );
	$('a.map2_link').Map_Tooltip( 'map2_popup' );
	$('a.map3_link').Map_Tooltip( 'map3_popup' );
	/* try to start up our alternate content */
	showCompare();
	/* first reset this variable to make sure we don't have a problem lingering from prior page load */
	$('#product_forms').val( 0 );
	$('#companion table').hide();
	$('#companion table:first-child').show();
	// We want to do work with our ajax form submission
	if(	$().ajaxForm != null ){
		$('#companion form').ajaxForm({
			beforeSubmit: function( action, object ){
				// First trigger form validation
				if( !object.valid() ){
					return false;
				}
				else{
					object.parent().find('ul.product_add_error').remove();
				}// End custom validation invocation
				// Determine if we are the only thing submitting data at this point in time
				if( $('#product_forms').val() == 0 && $('#product_forms').val() != null ){
					// Localize our current ID to a variable
					currID = '#'+object.attr('id');
					// First setup our content for the popup
					$('#product_forms').val( currID );
					$('#added_popup li.added_product_img').html( $(currID+' li.companion_product_img').html() );
					$('#added_popup li.added_product_title').html( $(currID+' li.companion_product_title').html() );
					$('#added_popup li.added_product_item').html( '<strong>Item #:</strong> '+ $(currID+' input[name="item_number"],'+currID+' select[name="item_number"]').val() );
					$('#added_popup li.added_product_qty').html( '<strong>Quantity:</strong> '+ $(currID+' input[name="qty"],'+currID+' select[name="qty"]').val() );
					// Next we hide our dropdowns because IE6 is .. IE6
					if( jQuery.browser && jQuery.browser.msie && jQuery.browser.version <= 7 )
						$('#companion select').hide();
				}
				else{
					alert('Please wait a moment while another item is being added to your cart.');
					return false;	// Premptively abort
				}
			},
			url: '/cart_addprod.cfm',
			success: function(response_text,success) {
				// First show this "jaunt"
				$('#added_popup').show(5);
				// Next clear out out the holding variable
				$('#product_forms').val( 0 );
			}// End success function
		});// End form submission code
	}// End check to see if form validation was available
	$('#added_popup,#added_popup a.added_close_top,#added_popup a.added_close_bottom').click( function(){
		$('#added_popup').hide(5);
		// Finally we show our dropdowns again, because IE6 is .. IE6
		$('#companion select').show();
	});
	$('#companion a.companion_nav.left, #companion a.companion_nav.right').click( function(e,v){
		// Here we want to be able to hide/show the table according to the direction the user clicekd (left decrease, right increase)
		var arrClassNames = this.className.split(' ');
		if( arrClassNames.length == 2 && arrClassNames[1].match(/^left$|^right$/) != null ){
			// Localize our current class name and retrieve our current row #
			var direction = ( arrClassNames[1] == 'right' ) ? 1 : -1;
			var classPrefix = 'product_row_';
			var maxID = $('#companion table').length;
			var currentID = $('#companion table:visible').attr('id');
			if( currentID != null && currentID.match(/\d+/) ){
				// Here we want to work with grab our current integer
				currentID = currentID.match(/\d+/);
			}
			else{
				// Here we default to our first element as a safety net
				currentID = 1;
			}// End conditional for our current row
			// Check our current max ID
			if( maxID == null ){
				maxID = 1;
			}
			// First assign our current row as hidden
			$('#'+classPrefix+currentID).hide();
			// Next declare our target
			targetID = parseInt(currentID)+parseInt(direction);
			// Finally determine how we will be hiding/showing these
			if( targetID > 0 && targetID<=maxID )
				$('#'+classPrefix+targetID).show();
			else if( targetID <= 0 )
				$('#'+classPrefix+maxID).show();
			else
				$('#'+classPrefix+'1').show();
		}// End array length match and expected data check
	});
	/* override the li events */
	$('div#moreImages li').hover( function(eventObj){
		// Localize current image as jQuery element
		var jQElement = $(this);
		var jQImage = $(this).find('img');
		var srcImage = jQImage.attr('name');
		// Mouse over, first assign all borders to "no color"
		jQElement.parent().find('li').css('borderColor','white');
		// Determine if we have a valid image to use
		if(		srcImage != null
		 	&&	srcImage.length > 0 ){
			// Now assign this specific result our high-lighted color
			jQImage.css('borderColor','#004b91');
			// Next see our current image is actually the first image( or not )
			$('div.vertical_ruler,div.horizontal_ruler').css('visibility',(jQImage.attr('id').match(/_1$/) != null )?'visible':'hidden');
			// Next see if our current iamge is our 
			$('#largeimage').attr('src',srcImage);
		}// End condition to update preview image
	}, function(){
		/* Mouse out, assign all borders to "no color */
		$('div#moreImages li').css('borderColor','white');
	});
	/* start our thumbnail support by pre-loading each image now */
	jQuery.each( $('div#moreImages li img'), function(){
		// load image into js memory
		var imageObj = new Image();
		imageObj.src = $(this).attr('name');
	});
	// Determine if we have our imagePreview and slimbox around
	if( $().imgPreview != null && $().slimbox != null ){
		// Match on our user submitted photos
		$('dl.user_photo_list a').imgPreview({
			containerID: 'userImagePreview',
			imgCSS: {
				// Limit preview size:
				height: 200
			},
			// When image has loaded:
			onLoad: function(){
				// Animate image
				$(this).parent().animate({opacity:1}, 300);
			},
			// When container is shown:
			onShow: function(link){
				// Update text
				$('<div class="text">' + $(link).next().text() + '</div>').appendTo(this);
			},
			// When container hides: 
			onHide: function(link){
				// Remove temporary title/description
				$('div.text', this).remove();
			},
			srcAttr: 'src'
		}).slimbox( {
				overlayOpacity: 0.6,
				easing: "easeOutElastic",
				captionAnimationDuration: 1,
				counterText: "Image {x} of {y}",
				closeKeys: [27, 70],
				nextKeys: [39, 83]	  
			}, function(el){
			// linkMapper function will determine how to get our current image metrics
			return [el.href, $(el).next().text()];
		});// End preview image style over-ride
	}// End slimbox/image check
});