document.observe("dom:loaded", function() {
  if( window.location.hash == "#action_image_upload" ){
    Modalbox.show($('action_image_form'), {title: 'Submit your action shot!', width: 450});
  }
});

// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function decrement_character_count( src, dest ) {
    var dest = $(dest);
    var src = $(src);
    dest.innerHTML = src.maxLength - src.value.length;
}

// Methods for default expanding navigation
function setupNavigation( container_id ) {
  var container = $(container_id);
  
  if( ! container ) {
    return false;
  }
  
  $$('#' + container_id + ' > .nav_element a').each(function(arg) {
    if( arg.readAttribute('href') == '#' ) {
      arg.onclick = navigationElementClicked;
    }
  });
  
}

function navigationElementClicked( event ) {
  var target = Event.element(event);
  target.parentNode.toggleClassName('active');
  return false;
}

function buttonRemoteLoading( element ) {
  var button = $(element);
  button.writeAttribute('oldText', button.readAttribute('value') );
  button.value = "Please wait";
  button.disabled = true;
}

function buttonRemoteDone( element ) {
  var button = $(element);
  button.value = button.readAttribute('oldText');
  button.writeAttribute("oldText", '');
  button.disabled = false;
}

function adminCollapsibleToggle( ele, target ) {
  var ele = $(ele);
  var target = $(target);

  // if( target.style.display == 'none' ) {
  //   window.location.hash = ele.name;
  // }
  // 

  Effect.toggle(target, 'appear',{});
}

function ship_to_billing_clicked() {
  var disabled = document.information_form.ship_to_billing_address.checked;
  if( document.information_form['shipping_address_id'] ) {
    if( disabled ) {
      document.information_form['shipping_address_id'].value = "";
      document.information_form['shipping_address_id'].disabled = true;
    } else {
      document.information_form['shipping_address_id'].disabled = false;
    }
  }
	['first_name', 'last_name', 'line2', 'line3', 'city', 'province', 'postal_code', 'country_id'].each(function(field){
    if( disabled ) {
      document.information_form['shipping_address['+field+']'].value = document.information_form['billing_address['+field+']'].value;
    }
    document.information_form['shipping_address['+field+']'].disabled = disabled;
  });
}

function ship_to_billing_update(ele){
	to_update = $(ele.id.replace('billing','shipping'));
	to_update.value = ele.value;
}

function set_card_type(number){
  var logo = undefined;
  // remove spaces and hyphens
  cc_number = number.replace(/[ -]/g,"");
  // initially the card type is unknown
  cardtype = '';
  // define card names and their matching patterns
  ccArray = {"visa" : "^4[0-9]{12}(?:[0-9]{3})?$",
  "mastercard" : "^5[1-5][0-9]{14}$",
  "discover" : "^6011[0-9]{12}$",
  "amex" : "^3[47][0-9]{13}$"};
  
  // identify the card type
  for (key in ccArray) {
    regex = new RegExp(ccArray[key]);
    if (regex.test(cc_number)) {
      cardtype = key;
      break;
    }
  }

  //Now that we have the cardtype make it set type automatically
  logos=new Array();
  logos=document.getElementsByName("credit_card_img");
  for(i=0;i < logos.length;i++){    
    logos[i].style.opacity="1.0";
  }
  cardTypeId=document.getElementById("credit_card[credit_card_type_id]");
  cardTypeId.value=0; 
  switch(cardtype){
    case "visa":        
      for(i=0;i < logos.length;i++){
        if(logos[i].id == "1")logo=logos[i];
      }
      break;
    case "mastercard":
      for(i=0;i < logos.length;i++){
        if(logos[i].id == "2")logo=logos[i];
      }
      break;
    case "discover":
      for(i=0;i < logos.length;i++){
        if(logos[i].id == "3")logo=logos[i];
      }
      break;
    case "amex":
      for(i=0;i < logos.length;i++){
        if(logos[i].id == "4")logo=logos[i];
      }
      break;
    default:
      logo = undefined;
      break;
  }
  for(i=0;i < logos.length;i++){        
    if(logos[i] != logo){       
      logos[i].style.opacity="0.15";
    }else{
      logos[i].style.opacity="1.0"; 
      cardTypeId=document.getElementById("credit_card[credit_card_type_id]");
      cardTypeId.value=logo.id;           
    }
  }
}

function disableAfterSubmit( ele ) {
  var btn = ele.getInputs("submit")[0];
  btn.disabled = true;
}

function optionMapping() {
  var mapping = new Array();;
  $$('.product-option select').each(function(select) {
    mapping[mapping.length] = select.name +"=" + $F(select);
  });
  
  return mapping.join("&");
}

function updateProductSkuDetails(url_path, short_availability, auth_token) {
  new Ajax.Request(url_path, {asynchronous:true, evalScripts:true,
    parameters: "short_availability="+short_availability+"&authenticity_token="+auth_token+"&" + optionMapping()
  });
}

function updateProductSkuDetailResult( sku, price, stock_message, image_path ) {
  if( $('product-sku') ) {
    Element.update('product-sku', sku );
  }
  
  if( $('product-price') ) {
    Element.update('product-price', price);
  }
  
  if( $('stock-message') ) {
    Element.update('stock-message', stock_message);
  }  
  updateDetailImage(image_path);
}

function updateDetailImage( image_path ) {
  if( $('detail-image') && image_path != '' ) {
    $('detail-image').src = image_path;
  }  
}

function updateZoomLink( image_path ) {
	if( $$('.zoom-link') && image_path != '' ) {
		$$('.zoom-link').each(function(e) {
			e.href = image_path;
		});
	}
}

/*** Product Search ***/
function autoCompleteSelected(ele){
	product_id = ele.id.split('-')[1];
	window.location = "/products/"+product_id;
}

function validateSearch(text) {
	text = text.toLowerCase();
  input = document.getElementById('terms').value.toLowerCase();
  if (input == "" || input == text) {
    alert("You must enter your search keywords first.");
    document.getElementById('terms').focus(); 
    return false; 
  }else{
    return true;
  }
}

function validateNewsletterSignup(text) {
	text = text.toLowerCase();
  input = document.getElementById('signup_email').value.toLowerCase();
  if (input == "" || input == text) {
    alert("You must enter your Email Address first.");
    document.getElementById('signup_email').focus(); 
    return false; 
  }else{
    return true;
  }
}

/*** Scroll DIV position ***/
//TODO: Still needs checks for the y_axis
function slide(id, width, x_axis, y_axis){
	div = document.getElementById(id);
	left_position = parseInt(div.style.left.replace('px',''));
	if( (left_position + x_axis) > 0 ){
		new Effect.Move(id,{
			x: ( (width*-1) + x_axis ), y: y_axis, mode: 'relative',
			transition: Effect.Transitions.spring
		});
	}else if( (left_position + x_axis) <= (width*-1) ){
		new Effect.Move(id,{
			x: (width + x_axis), y: y_axis, mode: 'relative',
			transition: Effect.Transitions.spring
		});
	}else{
		new Effect.Move(id,{
			x: x_axis, y: y_axis, mode: 'relative',
			transition: Effect.Transitions.spring
		});
	}
}

/*** Scroll DIV position ***/
//TODO: Still needs checks for the y_axis
function linear_slide(id, width, x_axis, y_axis){
	div = document.getElementById(id);
	left_position = parseInt(div.style.left.replace('px',''));
	if( (left_position + x_axis) > 0 ){
		new Effect.Move(id,{
			x: ( (width*-1) + x_axis ), y: y_axis, mode: 'relative',
			transition: Effect.Transitions.linear
		});
	}else if( (left_position + x_axis) <= (width*-1) ){
		new Effect.Move(id,{
			x: (width + x_axis), y: y_axis, mode: 'relative',
			transition: Effect.Transitions.linear
		});
	}else{
		new Effect.Move(id,{
			x: x_axis, y: y_axis, mode: 'relative',
			transition: Effect.Transitions.linear
		});
	}
}

function decrement_character_count( src, dest ) {
    var dest = $(dest);
    var src = $(src);
    dest.innerHTML = src.maxLength - src.value.length;
}

function random_image_display(spot_name){
	// Determine Container Element and Randomly Choose An Image
	var image_container = $(spot_name);
	var images = image_container.getElementsByTagName("Img");
	var slide_count = images.length;
	var number_to_show = Math.floor( Math.random()*slide_count );
	// If the random image has a link as the parent element display the link w/image or else just show the image
	if(images[number_to_show].parentNode.tagName=="A"){
		image_container.update(images[number_to_show].parentNode);
	}else{
		image_container.update(images[number_to_show]);
	}
}

function rotate_image_display(spot_name){
	var image_container = $(spot_name);
	var images = image_container.getElementsByTagName("Img");
	window['slide_count_'+spot_name] = images.length;
	var rotating_container = document.createElement('div');
	rotating_container.setAttribute("id","rotating_wrap_"+spot_name)
	
	for(i=0; i < window['slide_count_'+spot_name]; i++){
		new_div = document.createElement('div');
		new_div.setAttribute("id","rotate_"+spot_name+"_"+i);
		if(i>0){
			new_div.setAttribute("style","display:none;");
		}
		if(images[i].parentNode.tagName=="A"){
			new_div.appendChild(images[i].parentNode.cloneNode(true));
		}else{
			new_div.appendChild(images[i].cloneNode(true));
		}
		rotating_container.appendChild(new_div);
	}
	
	image_container.update(rotating_container);
	
	window['currently_showing_'+spot_name] = 0;
	window['delay_'+spot_name] = 8000;
	window['timer_'+spot_name] = null;
	window['timer_'+spot_name] = setTimeout("swap_rotating_image_display('"+spot_name+"',1,"+window['delay_'+spot_name]+","+window['timer_'+spot_name]+")", window['delay_'+spot_name]);
}

function swap_rotating_image_display(spot_name, id){
	if( id >= parseInt(window['slide_count_'+spot_name]) ){
    id = 0;
  }

  window['fade_'+spot_name] =  $('rotate_'+spot_name+'_'+window['currently_showing_'+spot_name]);
  window['appear_'+spot_name] =  $('rotate_'+spot_name+'_'+id);
	
  new Effect.Fade(window['fade_'+spot_name]);
  new Effect.Appear(window['appear_'+spot_name], {queue: 'end', scope: spot_name});
  window['currently_showing_'+spot_name] = id++;
	window['timer_'+spot_name] = setTimeout("swap_rotating_image_display('"+spot_name+"',"+id+")", window['delay_'+spot_name]);
}

function toggleAdminNavSection(element) {
  $(element).toggleClassName('expanded')
  $(element).nextSiblings()[0].toggleClassName('collapsed');
}

function notifyAPO( element ) {
  if( element.value == 'AP' || element.value == 'AE' || element.value == 'AA' || element.value == 'MP' ) {
    $('shipping_messages').update("Only the indicated shipping methods below will ship to an APO address.");
    $('shipping_messages').show();
  } else {
    $('shipping_messages').hide();
  }
}

function togglePlusMinus(id){
	if($(id).innerHTML=='-'){
		$(id).innerHTML='+';
	}else{
		$(id).innerHTML='-';
	}
}

