/*
sfHover = function() {
  var sfEls = document.getElementsByTagName("LI");
  for (var i=0; i<sfEls.length; i++) {
    sfEls[i].onmouseover=function() {
      this.className+=" sfhover";
    }
    sfEls[i].onmouseout=function() {
      this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
    }
  }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
*/



function popitup(url) {
	newwindow=window.open(url,'name','width=850,height=630,resizable=1,scrollbars=1');
	if (window.focus) {newwindow.focus()}
	return false;
}


function updateProductPrice() {
  var total = determinePrice()+"";
  if (total != "0") {
    if (total == outofstock) {
      $('product_price').update(total);
    } else {
      $('product_price').update("$"+total.substring(0,total.length-2)+"."+total.substring(total.length-2));
    }
  }
}

function determinePrice() {
  var total = 0;
  if ( $('id') && $('id').options ) {
    var variant = parsePrice($('id'));
    if (variant == outofstock) {
      return variant;
    }
    total = variant;
  }
  $('product').getElementsByClassName('product_option').each(function(n){
    if (n.value && n.value != "") {
      total += parsePrice(n);
    }
  });
  return total;
}

function parsePrice(select) {
  var text = select.options[select.selectedIndex].text;
  var price = 0;
  try {
    if (text.indexOf('$') > -1) {
      price = text.gsub(/.*\$/,'');
      price = price.gsub(/\./,'');
      price *= 1;
    } else {
      price = outofstock;
    }
  } catch (err) {}
  return price;
}

function updateProductForm() {
  updateProductPrice();
  Event.observe('id','change',updateProductPrice);
  $('product').getElementsByClassName('product_option').each(function(n){
    Event.observe(n,'change',updateProductPrice);
  });
}











































function displayImage(index, parent){
 	var images = document.getElementById(parent).getElementsByTagName("div");
	for(var i = 0; i < images.length; i++) {
	  var image = images[i];
	  if (image.className != 'pimage')  { continue }
	  if(i == index-1) {
	    image.style.display="block";
	  }
	  else {
	    image.style.display="none";
	  }
	}	
}








var SectionForm = {
  toggleSettings: function() {
    Element.toggle('blog-options');
  },

  sortable: null,
  toggleSortable: function(link, category_id, container_id) {
    if($(container_id).className == 'sortable') {
      Sortable.destroy(container_id);
      $(container_id).className = '';
      link.innerHTML = 'Reorder ' + container_id;
      link.className = 'reorder';
      this.saveSortable(category_id, container_id);
    } else {
      this.sortable = Sortable.create(container_id, {handle:'handle'});
      $(container_id).className = 'sortable';
      link.className = 'reordering';
      link.innerHTML = 'Done Reordering'
    }
  },

  saveSortable: function(category_id, container_id) {
    var query = $$('#'+container_id+' li').inject([], function(qu, li) {
      qu.push('sorted_ids[]=' + li.getAttribute('id').substr(container_id.length));
      return qu;
    }).join('&')
    new Ajax.Request('/admin/categories/order/' + category_id, {asynchronous:true, evalScripts:true, parameters:query});
  }
}



function validate_send_to_friend() {
  var allgood = true;
  if ( allgood && !$('send_to_friend_name').present() ) {
    allgood = false;
    alert('enter your name!');
  }
  if ( allgood && !$('send_to_friend_email').present() ) {
    allgood = false;
    alert('enter your email!');
  }
  if ( allgood && !$('send_to_friend_friends_email').present() ) {
    allgood = false;
    alert('enter your friend\'s email!');
  }
  if ( allgood && !$('send_to_friend_message').present() ) {
    allgood = false;
    alert('enter your message!');
  }
  return allgood;
}

///////////////////////
// checkout methods
///////////////////////

function hide_totals() {
  	Element.update('total_shipping',"calculating...");
  	Element.update('total_price',"calculating...");
  	Element.update('total_tax',"calculating...");
}

function change_shipping_method() {
	hide_totals();
  var shipping_method = radio_value('checkout-form', 'cart[shipping_method_id]');  
  new Ajax.Request('/cart/update_shipping', {asynchronous:true, evalScripts:true, parameters:'shipping_method='+encodeURIComponent(shipping_method)});
}

function change_shipping_location() {
	hide_totals();
	var zip 		= $F('shipping_'+shipping_field+'_zip');
	var state 	= $F('shipping_'+shipping_field+'_state');
	var country = $F('shipping_'+shipping_field+'_country');
	var city 		= $F('shipping_'+shipping_field+'_city');
  	new Ajax.Request('/cart/update_shipping', {asynchronous:true, evalScripts:true, 		
		parameters:
			'zip='+encodeURIComponent(zip)+
			"&city="+encodeURIComponent(city)+
			"&state="+encodeURIComponent(state)+
			"&country="+encodeURIComponent(country)
	});
}

function copy_to_shipping() {
  if ( $F("sameshipping") ) {
		$("shipping_"+shipping_field+"_first_name").value = $F("billing_"+billing_field+"_first_name"); 	
		$("shipping_"+shipping_field+"_last_name").value = $F("billing_"+billing_field+"_last_name");	
		$("shipping_"+shipping_field+"_address").value = $F("billing_"+billing_field+"_address");	
		$("shipping_"+shipping_field+"_address_2").value = $F("billing_"+billing_field+"_address_2"); 	
		$("shipping_"+shipping_field+"_city").value = $F("billing_"+billing_field+"_city");	
		$("shipping_"+shipping_field+"_state").value = $F("billing_"+billing_field+"_state"); 		
		$("shipping_"+shipping_field+"_zip").value = $F("billing_"+billing_field+"_zip");
		$("shipping_"+shipping_field+"_country").value = $F("billing_"+billing_field+"_country");
		$("shipping_"+shipping_field+"_phone").value = $F("billing_"+billing_field+"_phone");
		$("shipping_"+shipping_field+"_phone_2").value = $F("billing_"+billing_field+"_phone_2");
  }
	change_shipping_location();
}

function update_state(name, prefix) {
  var state = $(prefix+"_state");
  var country = $(prefix+"_country");
  var elParent = state.parentNode;
  if (country.value == "US") {
    if (state.nodeName == "INPUT") {
     var tmp = elParent.removeChild(state);
     var sel = $('js_'+name+'_state').cloneNode(true);
     sel.setAttribute('id',prefix+"_state");
     sel.setAttribute('name',tmp.readAttribute('name'));
     sel.value = tmp.value;
     sel.oldElement = tmp;
     elParent.appendChild(sel);
    }
  } else {
    if (state.nodeName != "INPUT") {
      input = state.oldElement;
      var tmp = elParent.removeChild(state);
      elParent.appendChild(input);
    }
  }
}

function change_location(type,field) {
  field_id = type == "billing" ? billing_field : shipping_field;
  hide_totals();
  state = $(type+"_"+field_id+"_state");
  country = $(type+"_"+field_id+"_country");
  
  // if (field == 'state') {
  //   if (state.value != "") {
  //     country.value = "US";
  //   } else {
  //     country.value = "";
  //   }
  // } else {
  //   // IT or ""
  //   if (country.value != "US") {
  //     state.value = "";
  //   }
  // }
  new Ajax.Request('/cart/change_location', {asynchronous:true, evalScripts:true, 
    parameters: 
      'type=' +type +
      '&state=' +encodeURIComponent($F(type+"_"+field_id+"_state") ) +
      '&country=' +encodeURIComponent($F(type+"_"+field_id+"_country") )
    });
}


///////////////////////
// util methods
///////////////////////

function selected_radio(form, group) {
	return Form.getInputs(form,'radio', group).find(function(radio) { return radio.checked; });
}
function radio_value(form, group) {
  return selected_radio(form, group).value;
}



function addImageUpload(e) {
  var list = $('image_upload'), copyFrom = list.down();
  var newNode = copyFrom.cloneNode(true);
  var close = document.getElementsByClassName('remove-file', newNode)[0]; 
  Event.observe(close, 'click', function(e) { 
    Event.findElement(e, 'li').remove(); 
    e.preventDefault();
  });
  close.show();
  list.appendChild(newNode);
}  


function onloadcalls() {
  if ($('asset-add-file')) {
    Event.observe('asset-add-file','click',function(e) {
      addImageUpload(e);
      e.preventDefault();
    });  
  }
}

Event.observe(window, 'load', onloadcalls);
