/**
 * Copyright (c) 2011 Sonic Electronix.
 * Duplication or modification is prohibited.
 */

function warranty_toggle(warranty_opt_id, checked)
{
	var opt = $('warranty_opt' + warranty_opt_id);
	var btn = $('warranty_opt_btn' + warranty_opt_id);

	// Option doesn't exist
	if(!opt || !btn)
	{
		return false;
	}
	
	// Activate the hidden warranty ID holder
	$('selected_warranty_id').removeAttribute('disabled');

	// Make checked
	if(checked)
	{
		opt.setAttribute('checked', 'checked');
		
		// For IE6
		if(typeof opt.checked != 'undefined')
		{
			opt.checked = true;
		}
		
		btn.innerHTML = 'Undo';
		addClass(btn, 'undo');
		$('selected_warranty_id').value = opt.value;
	}
	// Make unchecked
	else
	{
		opt.removeAttribute('checked');
		
		// For IE6
		if(typeof opt.checked != 'undefined')
		{
			opt.checked = false;
		}
		
		btn.innerHTML = 'Add';
		removeClass(btn, 'undo');
		$('selected_warranty_id').value = '';
	}
	
	return true;
};

function warranty_hide_total()
{
	var total_after_warranty = $('total_after_warranty');
	if(total_after_warranty !== null)
	{
		$('total_after_warranty').style.display = 'none';
	}
};

function warranty_show_total(warranty_opt_id)
{
	var total_after_warranty = $('total_after_warranty');
	if(total_after_warranty !== null)
	{
		// Get matching warranty price elem
		var price_elem = $('price_with_warranty' + warranty_opt_id);
	
		// Warranty has a price
		if(typeof price_elem != 'undefined')
		{
			// Update total
			var total;
			for(var i=0; i<total_after_warranty.childNodes.length; ++i)
			{
				if(hasClass(total_after_warranty.childNodes[i], 'price'))
				{
					total = total_after_warranty.childNodes[i];
					break;
				}
			}
			total = total.getElementsByTagName('span');
			total = total[0];
			total.innerHTML = price_elem.value;
	
			// Show total
			$('total_after_warranty').style.display = 'block';
		}
	}
};

function warranty_btn_click(warranty_opt_id)
{
	// Matching warranty option is already checked
	if((typeof $('warranty_opt' + warranty_opt_id).getAttribute('checked') == 'string'
	|| typeof $('warranty_opt' + warranty_opt_id).getAttribute('checked') == 'boolean')
	&& $('warranty_opt' + warranty_opt_id).getAttribute('checked'))
	{
		// Uncheck this warranty
		warranty_toggle(warranty_opt_id, false);
		
		// Hide total
		warranty_hide_total();
	}
	// Matching opt is unchecked
	else
	{
		// Check this warranty
		warranty_toggle(warranty_opt_id, true);
	
		// For each possible warranty
		for(var i=0; i<100; ++i)
		{
			// Not this warranty
			if(i != warranty_opt_id)
			{
				// Uncheck it and abort if we're done
				if(!warranty_toggle(i, false))
				{
					break;
				}
			}
		}
		
		// Show total
		warranty_show_total(warranty_opt_id);
	}
	
	// track click for search log
	track_click();
	
	// Cancel click
	return false;
};

function reset_shipping_form()
{
	// Trash the zip cookie
	document.cookie = $('zip_cookie_name').value + '=;path=;domain=;expires=Thu, 01-Jan-1970 00:00:01 GMT';

	// Hide free shipping indicator, shipping notes, and some shipping links
	$('free_shipping_indicator').style.display = 'none';
	$('shipping_notes').style.display = 'none';
	$('shipping_link_view_options').style.display = 'none';
	$('shipping_link_change_zip').style.display = 'none';

	// Show the calculator and links
	$('shipping_info_header').style.display = 'block';
	$('shipping_calc').style.display = 'block';
	$('shipping_links').style.display = 'block';
	$('shipping_link_outside_us').style.display = 'block';
	
	// Enable submit button
	$('shipping_calc_submit').disabled = false;
	
	// Cancel click
	return false;
};

function calculate_shipping_link_click()
{
	// Hide the button
	$('shipping_calc_link').style.display = 'none';
	
	// track click for search log
	track_click();
	
	// Reset shipping form
	reset_shipping_form();
	
	// Cancel click
	return false;
};

function change_zip_form_submit()
{
	if(this.zip.value.length != 5)
	{
		alert('Your zip code must be exactly 5 digits long.');
	}
	else
	{
		// Disable submit button
		$('shipping_calc_submit').disabled = true;
		
		jQuery.ajax({
			cache: false,
			data: {
				action: 'get_charges',
				product_id: $('product_id').value,
				zip: this.zip.value
			},
			dataType: 'json',
			type: 'GET',
			url: 'viewitem_shipping_quote_multivariate.php',
			success: function(response)
			{
				// Hide calculator
				$('shipping_calc').style.display = 'none';
	
				// Success
				if(typeof response.error == 'undefined' && typeof response.force_view_options == 'undefined')
				{
					// Init shipping notes
					var shipping_notes = '';
					
					// Free shipping
					if(typeof response.free != 'undefined' && response.free)
					{
						if(typeof response.method_name == 'undefined')
						{
							response.method_name = 'Shipping';
						}
					
						// Show free indicator
						$('free_shipping_indicator').style.display = 'block';
						shipping_notes += '<p>'
							+ response.method_name
							+ (typeof response.destination != 'undefined' ? ' to ' + response.destination : '')
							+ ': FREE!</p>';
							
						// Hide shipping info header
						$('shipping_info_header').style.display = 'none';
					}
					// Paid shipping
					else
					{
						// Hide free indicator
						$('free_shipping_indicator').style.display = 'none';
						shipping_notes += '<p>'
							+ response.method_name
							+ (typeof response.destination != 'undefined' ? ' to ' + response.destination : '')
							+ ': $' + response.cost + '</p>';
	
						// Show shipping info header
						$('shipping_info_header').style.display = 'block';
					}
					
					// ETT available
					if(typeof response.time_in_transit != 'undefined')
					{
						shipping_notes += '<p><abbr title="Estimated">Est.</abbr> time in transit: ' + response.time_in_transit + '</p>';
					}
					
					// Hide "outside US?" link
					$('shipping_link_outside_us').style.display = 'none';
					
					// Show links
					$('shipping_links').style.display = 'block';
					$('shipping_link_view_options').style.display = 'block';
					$('shipping_link_change_zip').style.display = 'block';
				
					// Show shipping notes
					$('shipping_notes').innerHTML = shipping_notes;
					$('shipping_notes').style.display = 'block';
				}
				// Error
				else
				{
					// Hide shipping info header
					$('shipping_info_header').style.display = 'block';
	
					if(typeof response.force_view_options != 'undefined' && response.force_view_options)
					{
						$('shipping_links').style.display = 'block';
						$('shipping_notes').innerHTML = '<p>Please click the "view all" link below.</p>';
						$('shipping_notes').style.display = 'block';
						$('shipping_link_view_options').style.display = 'block';
						$('shipping_link_change_zip').style.display = 'block';
						$('shipping_link_outside_us').style.display = 'none';
					}
				
					if(typeof response.error != 'undefined')
					{
						alert(response.error);
					}
				}
			}
		});
	}
	
	// Cancel submit
	return false;
};

function zip_input_focus()
{
	if(this.value == 'Enter ZIP code')
	{
		this.value = '';
		removeClass(this, 'init');
	}
};

function zip_input_blur()
{
	if(this.value == '')
	{
		this.value = 'Enter ZIP code';
		addClass(this, 'init');
	}
};

function show_stock_tooltip(text, caller)
{
	document.getElementById('stock_tooltip_div').innerHTML = text;
	
	caller_y_position = get_position_y(caller);
	page_bottom = get_scroll_offset() + get_viewport_height();
	top_position = caller_y_position + 20;
	bottom_position = top_position + document.getElementById('stock_tooltip_div').offsetHeight;
	
	if (bottom_position > page_bottom)
	{
		top_position -= (bottom_position - page_bottom);
	}
	
	left_position = (get_position_x(caller) + 100 );
		
	document.getElementById('stock_tooltip_div').style.top = top_position + 'px';
	document.getElementById('stock_tooltip_div').style.visibility = 'visible';
	document.getElementById('stock_tooltip_div').style.left = left_position + 'px';
}

function hide_stock_tooltip()
{
	document.getElementById('stock_tooltip_div').style.visibility = 'hidden';
}

function show_feature_description(feature_id, caller)
{	
	feature_description = 'Invalid feature';
	feature_name ='Invalid feature';

	for (i=0; i<product_feature_definitions.length; i++)
	{
		if (product_feature_definitions[i][0] == feature_id)
		{
			feature_name = product_feature_definitions[i][1];
			feature_description = product_feature_definitions[i][2];
			break;
		}
	}
	
	//configure the element and position it properly...
	//we want to avoid having part of the div hidden, so we try to make sure
	//that it will fit in the window when we position it
	document.getElementById('feature_description_div_name').innerHTML = feature_name
	document.getElementById('feature_description_div_description').innerHTML = feature_description;
	
	caller_y_position = get_position_y(caller);
	page_bottom = get_scroll_offset() + get_viewport_height();
	top_position = caller_y_position + 20;
	bottom_position = top_position + document.getElementById('feature_description_div').offsetHeight;
	
	if (bottom_position > page_bottom)
	{
		top_position -= (bottom_position - page_bottom);
	}
		
	document.getElementById('feature_description_div').style.top = top_position + 'px';

	document.getElementById('feature_description_div').style.visibility = 'visible';
	document.getElementById('feature_description_div').style.left = (get_position_x(caller) + caller.offsetWidth * 0 + 100 - document.getElementById('feature_description_div').offsetWidth * 0 ) + 'px';
}

function hide_feature_description()
{
	document.getElementById('feature_description_div').style.visibility = 'hidden';
}

function track_click()
{
	if($('SearchClickout_query_id') != null && $('SearchClickout_clicked').value != 1)
	{
		jQuery.ajax({
				url: '/search/trackClick.php',
				data: {
					product_id: $('product_id').value,
					SearchClickout_query_id: $('SearchClickout_query_id').value
				},
				dataType: 'json',
				type: 'GET'
			});
			
		$('SearchClickout_clicked').value = 1;
	}
}

// Closure
(function($)
{
	// DOM ready
	$(function()
	{
		// Tab headers
		var $tabHeaders = $('.info_tabs .tab');
		$tabHeaders.bind({
			mouseenter: function() { tab_mouseover($(this).attr('rel')); },
			mouseleave: function() { tab_mouseout($(this).attr('rel')); },
			click: function() {
				if($(this).hasClass('wiringGuideTab'))
				{
					loadWiringGuideDiagrams($.parseJSON($('#impedances').val()), $('#num_voice_coils').val());
				}
				tab_select($(this).attr('rel'));
			}
		});
		
		// Preselected wiring guide tab
		if(window.location.search.match(/\bshow_tab=5\b/))
		{
			$tabHeaders.filter('[rel=5]').click();
		}
	});

	function loadWiringGuideDiagrams(impedances, num_voice_coils)
	{
		// Haven't already attempted loading
		if(!$('#wiringGuideDiagrams').hasClass('attemptedLoad'))
		{
			// Mark as attempted load
			$('#wiringGuideDiagrams').addClass('attemptedLoad');
		
			// Show loading
			$('#wiringGuideDiagrams').html('<img alt="Loading..." src="/images/loading.gif" />');
			
			// Get wiring diagrams
			jQuery.ajax({
				cache: true,
				data: {
					impedance: impedances,
					num_voice_coils: num_voice_coils
				},
				dataType: 'json',
				type: 'GET',
				url: '/product/getSubwooferWiringDiagrams',
				success: function(Diagrams)
				{
					// Thumbs per row
					var thumbsPerRow = 3;
					
					// Separate diagrams by number of subs
					var DiagramsByNumSubs = {};
					$.each(Diagrams, function(i, Diagram)
					{
						if(typeof DiagramsByNumSubs[Diagram.num_subs] == 'undefined')
						{
							DiagramsByNumSubs[Diagram.num_subs] = [];
						}
						DiagramsByNumSubs[Diagram.num_subs].push(Diagram);
					});
					
					// Get unique numbers of subs represented
					var numSubsGroups = [];
					for(num_subs in DiagramsByNumSubs)
					{
						numSubsGroups.push(num_subs);
					}
					
					// Sort number of subs groups ascending
					numSubsGroups.sort();
					
					// Initialize diagrams HTML
					$('#wiringGuideDiagrams').html('');
					
					// For each number of subs group
					$.each(numSubsGroups, function(tmp, num_subs)
					{
						// Get diagram group by number of subs
						var DiagramGroup = DiagramsByNumSubs[num_subs];
						
						// Start diagram table
						var $diagramTable = $('<table class="diagramTable"><tbody /></table>');
						var $diagramTableBody = $diagramTable.find('tbody');
						
						// Initialize rows and cells
						var numRows = Math.ceil(Diagrams.length / thumbsPerRow);
						for(var i=0; i<numRows; ++i)
						{
							var $row = $('<tr />');
							for(var k=0; k<thumbsPerRow; ++k)
							{
								$row.append('<td />');
							}
							
							$diagramTableBody.append($row);
						}
						
						// Get rows
						var $diagramTableRows = $diagramTableBody.find('tr');
						
						// For each diagram in the group
						$.each(DiagramGroup, function(i, Diagram)
						{
							Diagram.captionLines = getWiringDiagramThumbCaptionLines(Diagram);
							
							// Get diagram td in appropriate row and column
							var $diagram = $diagramTableRows.eq(Math.floor(i / thumbsPerRow))
								.find('td').eq(i % thumbsPerRow);
	
							// Meta
							$diagram.addClass('diagram').data('Diagram', Diagram);
							
							// Caption (skip first line, the number of subs line)
							var captionLinkLines = Diagram.captionLines.slice(1);
							switch(captionLinkLines[0])
							{
							case 'mono amp': captionLinkLines[0] = 'Mono Amp'; break;
							case '2ch amp': captionLinkLines[0] = '2 Channel Amp'; break;
							case '4ch amp': captionLinkLines[0] = '4 Channel Amp'; break;
							}
							if(typeof captionLinkLines[1] != 'undefined')
							{
								captionLinkLines[1] = captionLinkLines[1].substr(0, 1).toUpperCase() + captionLinkLines[1].substr(1);
							}
							var $captionLink = $('<a />').attr('href', Diagram.fullImageURL).html(captionLinkLines.join(' &mdash; '));
							$('<div class="caption" />').append($captionLink).appendTo($diagram);
							
							// Thumb
							$('<a class="thumb" />').attr('href', Diagram.fullImageURL).append(
								$('<img />').attr({
									alt: 'Wiring diagram for ' + Diagram.captionLines.join(', '),
									src: Diagram.thumbImageURL
								})
							).appendTo($diagram);
						});
						
						// Append number of subs title and diagram group table
						var title = num_subs + ' ' + $('#manufacturer').val() + ' ' + $('#manufacturer_sku').val()
									+ ' Subwoofer' + (num_subs != 1 ? 's' : '');
						$('#wiringGuideDiagrams').append($('<p class="groupTitle" />').text(title))
							.append($diagramTable);
					});
					
					// Bind diagram popups
					bindDiagramPopups();
				}
			});
		}
	}
	
	function bindDiagramPopups()
	{
		// Diagram click
		$('#wiringGuideDiagrams .diagramTable .diagram').click(function(event)
		{
			// Stop click
			event.preventDefault();
			
			// Initialize popup content
			var Diagram = $(this).data('Diagram');
			var $content = $('<div class="diagramPopup" />');
			
			// Title
			$content.append(
				$('<div class="title" />').text(Diagram.captionLines.join(', '))
			);
			
			// Print link
			$content.append(
				$('<a class="printLink"><span class="icon"></span><span class="text">Print this diagram</span></a>').click(function()
				{
					window.print();
					return false;
				})
			);
			
			// Image
			$content.append(
				$('<img class="image" />').attr({
					alt: 'Wiring diagram for ' + Diagram.captionLines.join(', '),
					src: Diagram.fullImageURL
				})
			);
			
			// Legend
			$content.append(
				$('<img class="legend" />').attr({
					alt: 'Wiring diagram legend',
					src: $('#cdnURL').val() + '/product/img/subwoofer_wiring/legend.jpg'
				})
			);
			
			// Disclaimer
			$content.append(
				$('<p class="disclaimer" />').text(
					'Warning: The image depicted shows the resistance change when wiring multiple subwoofer terminals.'
					+ ' Please refer to your subwoofer\'s owner\'s manual for the proper wiring of its terminals. Sonic'
					+ ' Electronix, Inc. is not responsible for damage caused to your audio system or vehicle due to improper'
					+ ' installation. Please call tech support at ' + $('#supportPhone').val() + ' if you require additional'
					+ ' assistance.'
				)
			);
			
			// Make printable copy of content
			$printable = $content.clone(false).addClass('printable');
			
			// Popup
			$.fancybox({
				content: $content,
				onComplete: function()
				{
					$printable.appendTo('body');
					$('body').addClass('showingDiagramPopup');
				},
				onCleanup: function()
				{
					$printable.remove();
					$('body').removeClass('showingDiagramPopup');
				}
			});
		});
	}
	
	function getWiringDiagramThumbCaptionLines(Diagram)
	{
		var lines = [];
		lines.push(Diagram.num_subs + ' ' + $('#manufacturer').val() + ' ' + $('#manufacturer_sku').val() + ' Subwoofer' + (Diagram.num_subs == 1 ? '' : 's'));
		lines.push((Diagram.num_amp_channels == 1 ? 'mono' : Diagram.num_amp_channels + 'ch') + ' amp');
		if(Diagram.is_bridged == '1')
		{
			lines.push('bridged');
		}
		if(Diagram.variation_sort_index !== null)
		{
			lines.push('option ' + (1 + Number(Diagram.variation_sort_index)));
		}
		
		return lines;
	}
})(jQuery);
