// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
Array.prototype.index = function(val) {
  for(var i = 0, l = this.length; i < l; i++) {
    if(this[i] == val) return i;
  }
  return null;
}

Array.prototype.include = function(val) {
  return this.index(val) !== null;
}


function flip_tag(tag_id) {
	if($(tag_id).hasClassName("active_tag")) {
		$(tag_id).removeClassName("active_tag");
		$(tag_id).addClassName("tag");
	} else {
		$(tag_id).removeClassName("tag");
		$(tag_id).addClassName("active_tag");
	}
}

function check_reset(form_field, preset) {
	if ($F(form_field) == preset) {
		$(form_field).value = '';
	}
}

function check_preset(form_field, preset) {
	if ($F(form_field) == '') {
		$(form_field).value = preset;
	}
}

function show_overpane(id) {
	overlay = $('gc-overlay')
	theheight = $$('html')[0].getHeight();
	if (overlay.getHeight < theheight) {
		overlay.setStyle("height: " + theheight + "px;");
	}
	overlay.show();
	new Effect.BlindDown(id, {duration: 0.4});
}

function hide_overpane(id) {
	new Effect.BlindUp(id, {queue:"end", duration: 0.4});
	new Effect.Fade('gc-overlay',{queue:"end", duration: 0.2});
}

function show_options_for(id) {
	$$('.active').each(function(n){
		n.hide();
		n.removeClassName("active");
	});
	
	$$('.active_tab')[0].removeClassName('active_tab');
	$("tab_"+id).addClassName('active_tab');
	new_active = $("options_"+id)
	new_active.show();
	new_active.addClassName('active');
	new_active_swatch = $("swatches_"+id);
	new_active_swatch.show();
	new_active_swatch.addClassName('active');
}

function old_change_tab(id) {
	$$('#tabnav a').each(function(n){
		n.removeClassName("active");
	});
	$$('#tab_content div.tab_content').each(function(n){
		n.addClassName("hidden_content")
	});
	$("iplink_" + id).addClassName("active")
	$("ip_"+ id).removeClassName("hidden_content")
}

function change_tab(id,morph) {
	var morph = (morph == null) ? true : morph;
	//search for the tab with the class active	
	if ($$('#admin_tabs .active').length > 0) { //admin kludge thanks to Paul getting something wrong
		active_tab = $$('#admin_tabs .active')[0];
		//mark the old tab and tab_content as hidden
		active_tab.removeClassName("active");
	} else if ($$('#tabnav .active').length > 0) {
		active_tab = $$('#tabnav .active')[0];
		//mark the old tab and tab_content as hidden
		active_tab.removeClassName("active");
	}
	//search for the new tab
	new_tab = $("iplink_"+ id);
	new_tab.addClassName("active");
	//search for the tab_content with the class active_content
	if ($$("#tab_content div.active_content").length > 0) {
		active_content = $$("#tab_content div.active_content")[0]
		//tell it to fade out
		new Effect.Fade(active_content, { duration: 0.2, queue: 'end' });
		active_content.removeClassName('active_content');
	}
	//search for the new tab_content
	new_content = $("ip_" + id);
	
	if(morph==true) {
		//get the height of the new content and morph the tab to be that tall
		theheight = new_content.getHeight();
		new Effect.Morph('tab_height', {
		  style: "height: " + theheight + "px;", // CSS Properties
		  duration: 0.3, // Core Effect properties,
		  queue: "end"
		});
	}
	
	//tell it to fade up at the end of the queue
	new Effect.Appear(new_content, { queue: 'end', duration: 0.2 });

	//mark the new tab and tab_content as active
	new_content.addClassName('active_content');
}

function init_set_tab_height() {
	active_content = $$("#tab_content div.active_content")[0]
	theheight = active_content.getHeight();
	$("tab_height").setStyle("height: " + theheight + "px;");
} 

function stored_incase() {
	
	
}

function tabs_complete(id) {
	$("ip_" + id).addClassName("active");
}

function load_areas(selected, toupdate) {
	new Ajax.Request('/freight_areas/?id='+selected, {
	asynchronous:true, method:'get', evalScripts:true, onLoading:function(request){Element.show('ship_spinner')}
			}); return false;
}

function update_freight(selected) {
	new Ajax.Request('/addresses/set_freight_area/?id='+selected, {
	asynchronous:true, method:'get', evalScripts:true, onComplete:function(request){Element.hide('freight_area_spinner')}, onLoading:function(request){Element.show('freight_area_spinner')}
			}); return false;
}

function reload_secondary(master_product_id, primary_option_id, sequence_number) {
	var secondary_option_id = ""
	if ($("swatch_group")) {
		var options = $("swatch_group").getElementsByTagName('INPUT');
		$A(options).each(function(elm) {
	    	if(elm.checked) { secondary_option_id = elm.id }
		});
	}
		
	if(secondary_option_id != '') {
		secondary_option_id = secondary_option_id.split('_')
		secondary_option_id = secondary_option_id.pop();
	}
	new Ajax.Request('/sec_option_show/?id='+master_product_id+'&primary_option_id='+primary_option_id+"&sequence_number="+sequence_number+"&secondary_option_id="+secondary_option_id, {
	asynchronous:true, method:'get', evalScripts:true, onSuccess: function(transport) { $('secondary_option').update(transport.responseText); FancyForm.start(); }, onLoading:function(request){Element.show('sec_option_spinner')}
			}); return false;
}


function toggleStockTabs(element) {
	Element.hide('stock_in');
	Element.hide('stock_out');
	Element.hide('stock_adjust');
	Element.show(element);
}

function isNumberKey(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		return false;
	} else {
		return true;
	}
}

function moveAndShowPanel(id) {
	var id = (id == null) ? '' : id;
	movePanel(id);
	Effect.toggle("add_panel"+id, "appear", { duration: 0.2 })
	inputs = $$("#add_panel"+id+" input");
	//window.alert(inputs.length);
	for(a=0; a < inputs.length; a++) {
		if(inputs[a].type == "text") {
			//Field.activate(inputs[a])
			theinput = inputs[a];
			setTimeout("Field.activate(theinput)",500);
			break;
		}
	}
}

function movePanel(id) {
	xy = $("plus_button"+id).cumulativeOffset();
	thetop = xy[1] + 30;
	theleft = xy[0] - 15;
	$('add_panel'+id).setStyle({
	  top: thetop + 'px',
	  left: theleft + 'px'
	});
}

function change_order_by(index, field, form) {
	window.location.href = ("/categories/order_by?order_by=" + field[index].value + "&return_to="+location.href);
}

function change_per_page(index, field, form) {
	window.location.href = ("/categories/per_page/" + field[index].value+ "?return_to="+location.href);
}

// AJAX Pagination

function ajaxPaginate() {
  // the element in which we will observe all clicks and capture
  // ones originating from pagination links
  var container = $('ajax_pagination')

  if (container) {
    var img = new Image
    img.src = '/images/interface/spinner.gif'

    function createSpinner() {
		window.alert("Creating spinner");
      new Element('img', { src: img.src, 'class': 'spinner' })
    }

    container.observe('click', function(e) {
      var el = e.element()
      if (el.match('.pagination a')) {
        el.up('.pagination').insert(createSpinner())
        new Ajax.Request(el.href, { method: 'get' })
        e.stop()
      }
    })
  }
}

function doSwatchChange(the_id) {
	$("main_image").src = "/product_images/"+ the_id + ".jpg";
	$("zoom_link").href = "/product_images/large/"+ the_id + ".jpg";
	$("main_image_link").href = "/product_images/large/"+ the_id + ".jpg";
}

function gray_forms() {
	$$("#gray_watch input").each(function(n){
		n.observe('focus', function(event){
		thefield = Event.element(event)
		thefield.removeClassName('greyout');
		if(thefield.value == "0.00") {
			thefield.value = '';
		}
	});
		
		n.observe('blur', function(event){
			thefield = Event.element(event)
			if (thefield.value == '0.00' || thefield.value == '') {
				thefield.value = '0.00'
		 		thefield.addClassName('greyout');
			}
		});
	});
}

function change_stores(new_url) {
	window.location = new_url;
}

function option_add() {
	setTimeout("movePanel('')", 500);
}

function country_check(country_array, country) {
	if(!country_array.include(country)) {
		$('country_warning').show();
	} else {
		$('country_warning').hide();
	}
	
}

function replace_address(address_id, add_type) {
	new Ajax.Request('/addresses/'+address_id+'?add_type='+add_type, {
	asynchronous:true, method:'get', evalScripts:true, onLoading:function(request){Element.show('address_spinner')}
			}); return false;
}