
var loader =  "<img src='/themes/frontend/blackdiamond/images/loading.gif' id='loader' />"

jQuery(document).ready(function ($) {
  $('.dynamic').show();
  $('.pdp #details').css('height', '507px');
  // need to override the above in cases in which the not-for-sale panel requires some more space
  $('.nfs').parent().parent().css('height', '');
  $('.pdp #details .content').css('height', '200px');

  try {
    $('#retail_partners form button.submit').click(function () {
      try {
        loadPdpDealers();
      } catch (err) {
        //if (window.console) { window.console.log(err) }
        // return false;
      }
      return false;
    });
    $('#retail_partners form').submit(function () {
      try {
        loadPdpDealers();
        return false;
      } catch (err) {
        //if (window.console) { window.console.log(err) }
        // return false;
      }
      return false;
    });
    $('#retail_partners #result #change_loc').live('click', function () {
      $('#retail_partners form').show();
      $('#retail_partners #result').remove();
      $('#retail_partners').css('padding-bottom', '0px');
    })
    // add colors
    if ($("#add #colors").size() > 0) {
      $("#add #colors a").each(function (index) {
        if ($(this).attr("rel") != null) {
          var colors = $(this).attr("rel").split(":");
          for (var i = 0; i < colors.length; i++) { //if the color is an integer this adds the # for hex color val
            if (isHex(colors[i])) {
              colors[i] = "#" + colors[i];
            } else {
              colors[i];
            }
          }
          if (colors.length == 1) {
            $(this).addClass("swatch").parent().css({ width: '22px', height: '22px', backgroundColor: colors[0] });
          } else if (colors.length == 2) {
            $(this).addClass("swatch").parent().css({ width: '12px', height: '22px', backgroundColor: colors[0], borderRight: "solid 10px " + colors[1] });
          } else if (colors.length == 3) {
            $(this).addClass("swatch").parent().css({ width: '17px', height: '17px', backgroundColor: colors[0], borderRight: "solid 5px " + colors[1], borderBottom: "solid 5px " + colors[2] });
          }
        };
        $(this).click(function () {
          $(".swatch").each(function () {
            $(this).removeClass("activeSwatch");
          });
          if ($(this).hasClass("swatch")) {
            $(this).addClass("activeSwatch");
          };
        });
      });
    };
    // check if any items are sold out and rewrite any options
    // this only works for items with a dropdown and without colors
    // for products with colors and sizes, the cascadeConfiguration method handles it
    var store_enabled = ($('#add .submit').length > 0);
    if (document.getElementById('configurables')) {
      var configurables = document.getElementById('configurables').value.split(',');
      for (i = 0; i <= configurables.length - 1; i++) {
        if (configurables[i] != 'bd_color' && document.getElementById('setup_' + configurables[i])) {
          var dropdown = document.getElementById('setup_' + configurables[i]);
          dd_size = dropdown.options.length;
          var newtext = Array(dd_size);
          var newval = Array(dd_size);
          for (ii = 0; ii <= dd_size - 1; ii++) {
            newtext[ii] = dropdown.options[ii].text;
            newval[ii] = dropdown.options[ii].value;
            if (newtext[ii].indexOf('UNAVAILABLE') == -1 && store_enabled && $('#stock_by_combo_' + newval[ii]) && $('#stock_by_combo_' + newval[ii]).val() == '0') {
              newtext[ii] += " *UNAVAILABLE*";
            }
          }
          clearMapped('setup_' + configurables[i]);
          for (ii = 1; ii < dd_size; ii++) {
            dropdown.options[ii] = new Option(newtext[ii], newval[ii]);
          }
        }
      }
    }
  } catch (err) {
    if (window.console) { window.console.log(err) }
    //return false;
  }

  prepSDR();
});

function isHex(s) {
	return (s.toString().search(/^-?[0-9a-fA-F]+$/) == 0);
}

function configureProduct(obj) {
	if (obj.options[obj.selectedIndex].value.length >= 1) {
		var real_attribute_id = obj.id.replace('setup_', '');
		// Set the hidden input to store the value
		if (document.getElementById(real_attribute_id)) {
			var chosen_value = obj.options[obj.selectedIndex].value;
			document.getElementById(real_attribute_id).value = chosen_value;
			cascadeConfiguration(real_attribute_id, chosen_value);
		}
	}
}

// this function is called once upon page load by forcing a click on a predetermined color swatch
// and that in turn sets up the markup for the color swatches and size dropdown
// I can't find what is forcing the click but if you figure it out please update this comment!
function configureColor(obj, real_attribute_id, value) {
	// assume the color is out of stock until you find a size of that color that is in stock
	var is_in_stock = false;
	$('input[id^=stock_by_combo_' + value + ']').each(function() {
		if ($(this).val() == 1) {
			is_in_stock = true;
		}
	});
	var store_enabled = ($('#add .submit').length > 0);
	if (store_enabled && !is_in_stock && obj.title.indexOf('UNAVAILABLE') == -1) {
		obj.title += ' <span class="sold-out">*UNAVAILABLE*</span>';
	}
	if (document.getElementById(real_attribute_id)) {
		// there is a hidden field with an ID that is auto-generated based on an attribute name
		// the field lives within a div with an id of "hidden_config_setup"
		// the value of this field will be set here and then referred to while generating the markup for the size/type dropdown
		document.getElementById(real_attribute_id).value = value;
	}
	cascadeConfiguration(real_attribute_id, value);
	// there is one label to show the currently selected color name - updated here
	document.getElementById('color_swatch_name').title = obj.title;
	document.getElementById('color_swatch_name').innerHTML = obj.title;
}

// this function rewrites the size/type dropdown based on which color swatch is selected
function cascadeConfiguration(real_attribute_id, chosen_value) {
	var store_enabled = ($('#add .submit').length > 0);
	var mapped_id = 'map_' + real_attribute_id;
	// Get the option values for the next attribute
	if (document.getElementById(mapped_id) && document.getElementById(mapped_id).name != mapped_id) {
		var map = document.getElementById('map_' + real_attribute_id);
		var next_attribute = map.name.replace('map_', '');
		// Search the map for this value
		for (x = 0; x < map.options.length; x++) {
			if (map.options[x].value == chosen_value) {
				var map_ids = map.options[x].innerHTML.split(',');
				// The map has been found, now clear the jQuery select, put in mapped options and rebuild
				if (document.getElementById('options_' + next_attribute) && document.getElementById('setup_' + next_attribute)) {
					var next_options = document.getElementById('options_' + next_attribute).options;
					var next_setup = document.getElementById('setup_' + next_attribute);
					clearMapped(next_setup.id);
					next_mapped_id = document.getElementById(mapped_id).name;
					current_configuration_key = getCurrentConfigurationKey();
					// Add new options
					for (y = 0; y < next_options.length; y++) {
						for (z = 0; z < map_ids.length; z++) {
							if (map_ids[z] == next_options[y].value) {
								var option_text = next_options[y].innerHTML;
								var config_id = current_configuration_key + ',' + next_options[y].value;
								
								// Check to see if this is the second to last step (and last configurable attribute)
								if (!document.getElementById(next_mapped_id)) {
									if (document.getElementById(config_id) && document.getElementById(config_id).title.length > 0) {
										option_text = option_text + ' - ' + document.getElementById(config_id).title;
									}
								}
								if (store_enabled && $('#stock_by_combo_' + config_id.replace(',', '_')).val() == '0') {
									option_text += " *UNAVAILABLE*";
								}
								// Add the option
								next_setup.options[next_setup.options.length] = new Option(option_text, next_options[y].value);
								break;
							}
						}
					}
				}
				break;
			}
		}
	} else {
		if (document.getElementById('configurables')) {
			combined_values = getCurrentConfigurationKey();
			if (document.getElementById(combined_values)) {
				document.getElementById(combined_values).checked = true;
			}
			product = $('#add .submit').closest('.add_form').find("input[name=product_id]");
			if (product.attr('type') == 'radio') {
				product_id = $('#add .submit').closest('.add_form').find("input[name=product_id]:checked").val();
			} else {
				product_id = $('#add .submit').closest('.add_form').find("input[name=product_id]").val();
			}
			if ($('#stock_by_id_' + product_id).val() == '1') {
				// available
				enableInputs($('#qty, #add .submit'));
			} else {
				// unavailable
				disableInputs($('#qty, #add .submit'), true);
			}
		}
	}
}

function clearMapped(id) {
	var root_id = id.replace('setup_', '');
	if (document.getElementById(id)) {
		obj = document.getElementById(id);
		var choose_label = $("#" + id + " :first").text();
		// Clear the existing options
		while (obj.options.length > 0) {
			obj.removeChild(obj.options[0]);
		}
		if (obj.getAttribute('class') && obj.getAttribute('class').match('not_for_sale')) {
			// Add a new Available ... line
			var choose_label = 'Available ' + obj.title + '...';
		}
		obj.options[0] = new Option(choose_label, '');
		// Clear the selected value
		document.getElementById(root_id).value = '';
		// Check for another mapped attribute
		if (document.getElementById('map_' + root_id) && document.getElementById('map_' + root_id).name != ('map_' + root_id)) {
			next_map = document.getElementById('map_' + root_id);
			next_id = 'setup_' + next_map.name.replace('map_', '');
			clearMapped(next_id);
		} else {
			disableInputs($('#qty, #add .submit'));
		}
	}
}

function getCurrentConfigurationKey(){
	if (document.getElementById('configurables')) {
		var combined_values = new Array();
		var configurables = document.getElementById('configurables').value.split(',');
		for(x = 0; x < configurables.length; x++) {
			if (document.getElementById(configurables[x]) && document.getElementById(configurables[x]).value.length > 0) {
				combined_values[combined_values.length] = document.getElementById(configurables[x]).value;
			}
		}
		return combined_values.join(',');
	}
}

function disableInputs(obj, mark_as_sold_out) {
	$(obj).each(function(index) {
		// Don't disable type="button" for SDR
		if ($(this).attr('type') == 'submit') {
			if ($(this).hasClass('submit')) {
				if (mark_as_sold_out) {
					$(this).html('UNAVAILABLE');
				} else {
					$(this).html('BUY NOW');
				}
			}
			$(this).attr({'disabled':'disabled', 'readonly':'readonly'});
			$(this).addClass("disabled");
			$(this).bind('click', function() {
				return false;
			});
			
		} else if ($(this).attr('type') == 'button') {
			$(this).bind('click', function() {
				return false;
			});
		}
	});
}

function enableInputs(obj) {
	$(obj).each(function(index) {
		if ($(this).hasClass('submit')) {
			$(this).html('BUY NOW');
		};
		$(this).attr({'disabled':'', 'readonly':''});
		$(this).removeClass("disabled");
		$(this).bind('click', function() {
			return true;
		});
	});
}

function colorOn(obj) {
	document.getElementById('color_swatch_name').innerHTML = obj.title;
}

function colorOff(obj) {
	document.getElementById('color_swatch_name').innerHTML = document.getElementById('color_swatch_name').title;
}

function loadPdpDealers () {
  $('button.submit').after(loader);
	// jQuery('#partners #map').jmap('init')
	// var pdpdealer = jQuery('#partners #map')
	var geocoder = new GClientGeocoder();
		var address = $('#dealer_address').val() + ", " + $('#retail_partners form select[name=dealer_country_code]').val();
	try {
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					alert(address + " " + notFound + ".");
				} else {
					$('#retail_partners form input[name=lat]').val(point.y);
					$('#retail_partners form input[name=lng]').val(point.x);
					var data = $('#retail_partners form').serialize();
					var dealerUrl = $('#retail_partners form').attr("action");
					$.ajax({
					  	url: dealerUrl,
					  	type: "POST",
					  	dataType: "html",
						data: data,
						success: function( html ) {
              $('img#loader').remove();
              $('#retail_partners').css('padding-bottom', '65px');
							$('#retail_partners form').hide();
							if ($('#retail_partners #result').size() == 0) {
								$('#retail_partners form').before('<div id="result"><p>'+locationTxt + address+'<br/><span id="change_loc">('+changeTxt+')</span></p>'+html+'</div>');
							} else {
								$('#retail_partners #result').replaceWith('<div id="result"><p>'+locationTxt + address+'<br/><span id="change_loc">('+changeTxt+')</span></p>'+html+'</div>');
							}
							$('div.see_more_retail').remove();
							var dealer_search_url = dealerLocatorUrl + '?link_location=' + escape($('#dealer_address').val()) + '&link_country_code=' + escape($('#retail_partners form select[name=dealer_country_code]').val());
							$('#retail_partners form').after('<div class="see_more_retail"><a href="' + dealer_search_url +'">' + seeMoreRetail + ' &gt;&gt;</a></div>');
						},
						error: function() {
							alert("We couldn't find any locations.  Something may be broken.  Please try again later.")
						}
					});
				}
			});
	} catch (err) {
		//if (window.console) { window.console.log(err) }
		//return false;
	}
}

function prepSDR() {
	if (jQuery('#SDR_button').size() > 0) {
		jQuery('#SDR_button').each(function(){
			$(this).unbind('click');
			$(this).bind('click', function() {
				openSDR();
			});
		});
		
		var widthNum = parseInt( jQuery('#sdr_box div.tab button').css('paddingLeft').replace('px','') );
		widthNum += parseInt( jQuery('#sdr_box div.tab button').css('paddingRight').replace('px','') );
		widthNum += parseInt( jQuery('#sdr_box div.tab button').width() );
		widthNum += 21;
		jQuery('#sdr_box div.tab').css('width', widthNum+'px');
		
		// Show it so that .height() works below
		jQuery('#sdr_box div.box').show();
		
		jQuery('#sdr_box div.box span a img').each(function() {
			jQuery(this).css('marginTop', 
				Math.floor((50 - jQuery(this).height()) / 2)+'px'
			);
		});
		
		jQuery('#sdr_box div.box span a').bind('click', function(){
			jQuery('#sdr_box div.box').slideUp(500);
			jQuery('#sdr_box div.tab').fadeOut(500);
			return true;
		});
		
		jQuery('#sdr_box div.tab').hide();
		jQuery('#sdr_box div.box').hide();
	}
}

function openSDR() {
	// Something magic in this file is double binding this button. This prevents that.
	jQuery('#SDR_button').unbind('click');
	jQuery('#SDR_button').bind('click', function() {
		openSDR();
	});
	
	jQuery('#sdr_box div.tab button').unbind('click');
	jQuery('#sdr_box div.tab button').bind('click', function() {
		jQuery('#sdr_box div.box').slideUp(500);
		jQuery('#sdr_box div.tab').fadeOut(500);
		return false;
	});
	
	jQuery('#sdr_box div.box').hide();
	jQuery('#sdr_box div.tab').fadeIn(500);
	jQuery('#sdr_box div.box').slideDown(500);
	
	return false;
}

