function change_input(obj, defer_update) 
{

	var fieldname = obj.id.replace(/_t_.*/, "");
	var changed = obj.id.replace(/.*_t_/, "");
	var bot_txt = $("#"+fieldname+"_t_bot").val();
	var top_txt = $("#"+fieldname+"_t_top").val();
	
	//scrub input fields for numeric 
	top_txt = top_txt.match(/\$?(\d*,?)*\d*\.?\d*/)[0];
	bot_txt = bot_txt.match(/\$?(\d*,?)*\d*\.?\d*/)[0];
	
	var type = eval(fieldname+"_type");

	
	if(type == 'enum')
	{
		var vals = eval(fieldname+"_vals");
		
		var values = [ indexToPercentage(top_txt, vals),
					   indexToPercentage(bot_txt, vals)];
	}
	else
	{
		//numeric
		var min = eval(fieldname+"_min");
		var rng = eval(fieldname+"_rng");

		var values = [ rangedValToPercentage(top_txt, min, rng, 2), 
				   rangedValToPercentage(bot_txt, min, rng, 2)];

	}
	
	//error check inputs.
	if(values[0] > 100)	{ values[0] = 100;}
	if(values[1] > 100)	{ values[1] = 100;}
	
	if(values[0] < 0)	{ values[0] = 0;}
	if(values[1] < 0)	{ values[1] = 0;}

	if(values[0] > values[1]) // would create negative range.
	{
		if(changed == 'top')
		{
			//change top to equal bot
			values[0] = values[1];
		}
		else
		{
			//change bot to equal top;
			values[1] = values[0];
		}
	}
	
	if(changed == 'top')
	{
		idx = 0;
	}
	else
	{
		idx = 1;
	}
	
	var updatedValue = "";
	var precision;
	if(type == "numeric")
	{
		//if(fieldname == "price_hs")
		if(fieldname.indexOf("price", 0) > -1)
		{
			precision = 0;
		}
		//else if(fieldname == "carat")
		else if(fieldname.indexOf("carat", 0) > -1)
		{
			precision = 2;
		}
		else if(fieldname.indexOf("calc_percent_off_rap", 0) > -1 )
		{
			precision = 1;
		}
		else if(fieldname.indexOf("table", 0) > -1 )
		{
			precision = 1;
		}
		else if(fieldname.indexOf("depth", 0) > -1 )
		{
			precision = 1;
		}
		
	
		updatedValue = number_format(percentageToRangedVal(values[idx], min, rng, precision),precision, ".",","); 
		//if(fieldname == "price_hs")
		if(fieldname.indexOf("price", 0) > -1)
		{
			updatedValue = "$"+updatedValue;
		}
		else if ( fieldname.indexOf("calc_percent_off_rap", 0) > -1 )
		{
			updatedValue = updatedValue+"%";
		}
		else if ( fieldname.indexOf("table", 0) > -1 )
		{
			updatedValue = updatedValue+"%";
		}
		else if ( fieldname.indexOf("depth", 0) > -1 )
		{
			updatedValue = updatedValue+"%";
		}
	}
	else
	{
		updatedValue = percentageToIndex(values[idx], vals);
	}

	$("#"+obj.id).val( updatedValue );

	$("#"+fieldname+"_slider").sliderMoveTo(values);
	if(defer_update != true)
	{
		get_diamonds();
	}
}

function set_reset()
{
	if(saveSearch == 1)
	{
//		$("span#reset").html("").hide("fast");
		var links = "<a href='#' id='reset_fields'>Reset Search Fields</a>&nbsp;&nbsp;<a href='#' id='link_to'>Link to this search</a>&nbsp;&nbsp;";
		$("span#reset").html(links).show("fast");
		
		//reset
		$("a#reset_fields").click(function(){
			$("div.slider").sliderMoveTo([0,100]).each(function(){reset_slider(this);});
			
			$("div.options div input").each(function(n){
				if(n==0)
				{
					$(this).attr("checked", "checked");
				}
				else
				{
					$(this).attr("checked", "");
				}
			});
			var options_name = $("div.options").parent().attr("id").replace(/_options/, "");
			options_checked(options_name);
			get_diamonds();
		});
		
		//linkto
		$("a#link_to").click(function(){
			//remove a#link_to and replace with text box.
			var link_to = save_state_url();
			var save_box = "<div class='save'><div class='close_button'></div><div>Copy this to paste in email</div><div><input type='text' id='link' value='"+link_to+"' size='32' /></div></div>";
			$("a#link_to").after(save_box);
			//$("a#link_to").after("<input type='text' id='link' value='"+link_to+"' />");
			$("a#link_to").remove();
			$("input#link").select();
			$("div.save div.close_button").click(function(){$("div.save").hide(); set_reset();});
		});
	}
}

function save_state_url()
{
	var base_url = "http://www.hooverandstrong.com/diamond-search/?";
	var parameters = "init=1";
	//options
	var options_name = $("div.options").parent().attr("id").replace(/_options/, "");
	if(options_name != "")
	{
		var options_val = eval( options_name + "_c_vals");
		parameters = parameters + "&" + options_name + "=" + options_val[0].replace(/ /g, "+");
	}
	//enums
	//numerics
	$("div.slider").each(function(){save_state(this);});
	parameters = parameters + slider_save_state;
	
	return base_url + parameters;
}
var slider_save_state = "";
function save_state(obj)
{
	var name = obj.id.replace(/_slider/, "");
	var tt = $("#"+name+"_t_top").val();
	var tb = $("#"+name+"_t_bot").val();
	if ( name.indexOf("price", 0) > -1
			|| name.indexOf("calc_percent_off_rap", 0) > -1 || name.indexOf("depth", 0) > -1 || name.indexOf("table", 0) > -1 )
	{
		tt = strip_formatting(tt);
		tb = strip_formatting(tb);
	}
	var this_slider = "&" + name + "[max]=" + tt + "&" + name + "[min]=" + tb;
	
	
	slider_save_state = slider_save_state + this_slider;
}

function change_sort(obj)
{	
	var fieldname = obj.id.replace(/_header/, "");
	if(sort.col != fieldname)
	{
		clear_sort();
		$(obj).addClass("headerSortDown");
		sort.col = fieldname;
		sort.dir = "ASC";
	}
	else
	{
		$(obj).toggleClass("headerSortDown");
		$(obj).toggleClass("headerSortUp");
		sort.col = fieldname;
		if(sort.dir == "ASC")
		{
			sort.dir = "DESC";
		}
		else
		{
			sort.dir = "ASC";
		}
	}
	get_diamonds();
}
function clear_sort()
{
	$("th.header").removeClass('headerSortUp').removeClass('headerSortDown');
}

function handle_scroll(obj)
{
	var scrollPct = (obj.scrollTop) / (obj.scrollHeight - obj.offsetHeight);
	
	if(scrollPct > 0.55 && !loading)
	{
		get_diamonds(true);
		e_log("loading more ... ");
		loading = true;
	}
	else if(scrollPct > 0.85)
	{
		get_diamonds(true);
		e_log("loading!");
		loading= true;
	}
}
function do_popup(r)
{
	if(popup_id == r)
	{
		if(!r.id)
		{
			r = document.getElementById(r);
		}

		var id = r.id.replace(/_row/, "");

		var offset = r.rowIndex * ($(r).height()) + 30;
	
	//	if($.browser.msie){	s = $("div.scrollable").get(0); }
	//	else{ s = $("table#example tbody").get(0); }
		var scrollTop = $("div.scrollable").get(0).scrollTop || $("table#example tbody").get(0).scrollTop;
		
		$("#popup").html("<div style='padding: 105px 65px;'><img width='32' height='32' src='loading.gif' /></div>");
	//	$("#popup").parent().css("top", offset - s.scrollTop);
		$("#popup").parent().css("top", offset - scrollTop);
		//lose ajax param at release, will improve performance to allow browser to cache the popup
		$.get("/diamond-search/get_diamonds.php", {popup: 1, did: id,  ajax: new Date().getTime()}, function(data){
			$("#popup").html(data);
		});
		$("#popup").parent().parent().show();
		$("#popup").parent().ifixpng();
	}
}
function clear_popup(r)
{
	$("#popup").parent().parent().hide();
}

function do_stripes(hover)
{
	$(".stripeMe tbody tr").addClass("odd");
	if(hover == true)
	{
		$(".stripeMe tbody tr").mouseover(function() {$(this).addClass("over");}).mouseout(function() {$(this).removeClass("over");});
	}
	$(".stripeMe tbody tr:even").removeClass("odd").addClass("even");
	
}
var temp = "";
function options_checked(name)
{
	temp = "";
	$("#"+name+"_options input[type='checkbox']").each(function(){
		if( $(this).attr("checked"))
		{
			if(temp != "")
			{
				temp += ", ";
			}
			temp += $(this).val();
		}
	});
	
	vals = eval( name+"_c_vals = [ temp ]");
}

function reset_slider(obj)
{
	var type = eval(obj.id.replace(/_slider/, "_type"));
	if(type == 'enum')
	{
		enum_reset(obj);
	}
	else
	{//type==numeric
		numeric_reset(obj);
	}
}

function enum_reset(obj)
{
	var name = obj.id.replace(/_slider/,"");
	var tt = name + "_t_top";
	var tb = name + "_t_bot";
	var vals = eval(name+"_vals");
	$("#"+tt).val(percentageToIndex(0, vals));//max
	$("#"+tb).val(percentageToIndex(100, vals));//min
}
function enum_slide(ui, vals)
{
	var nVal = ui.slider.curValue;
	var sTxt = ui.handle.id.replace(/_h_/,"_t_");
	var pos = ui.handle.id.replace(/.*h_/, "");
		
	var oppVal;
	if(pos == "top")
	{
		oppVal = ui.values[1];//bottom value
	}
	if(pos == "bot")
	{
		oppVal = ui.values[0];//top value
	}
	
	var newIndex = myRound(percentageToIndex(nVal, vals), 0);
	
	if( nVal == oppVal)
	{
		if(pos == "top")
		{
			//move handle and index up one.
			newIndex = newIndex + 1; 
		}
		else
		{
			//move handle and index down one.
			newIndex = newIndex - 1;
		}
	}
	$("#"+sTxt).val(newIndex);
	
	if( nVal == oppVal)
	{
		change_input(document.getElementById(sTxt));
	}
}

function numeric_reset(obj)
{
	var name = obj.id.replace(/_slider/, "");
	var f = name;
	var tt = name+"_t_top";
	var tb = name+"_t_bot";
	var p = 0;
	var m = eval(name+"_min");
	var r = eval(name+"_rng");
	
	if(f.indexOf("price", 0) > -1) { p = 0;} 
	else if(f.indexOf("carat", 0) > -1) {p = 2;}
	else if(f.indexOf("calc_", 0) > -1 ) { p = 1; }
	else if(f.indexOf("depth", 0) > -1 ) { p = 1; }
	else if(f.indexOf("table", 0) > -1 ) { p = 1; }

	if(f.indexOf("price", 0) > -1)
	{
		$("#"+tt).val("$"+number_format(percentageToRangedVal(0, m, r, p), p, ".",","));
		$("#"+tb).val("$"+number_format(percentageToRangedVal(100, m, r, p), p, ".",","));
	}
	else if(f.indexOf("calc_percent_off_rap", 0) > -1)
	{
		$("#"+tt).val(number_format(percentageToRangedVal(0, m, r, p), p, ".",",") + "%" );
		$("#"+tb).val(number_format(percentageToRangedVal(100, m, r, p), p, ".",",") + "%" );
	}
	else if(f.indexOf("table", 0) > -1)
	{
		$("#"+tt).val(number_format(percentageToRangedVal(0, m, r, p), p, ".",",") + "%" );
		$("#"+tb).val(number_format(percentageToRangedVal(100, m, r, p), p, ".",",") + "%" );
	}
	else if(f.indexOf("depth", 0) > -1)
	{
		$("#"+tt).val(number_format(percentageToRangedVal(0, m, r, p), p, ".",",") + "%" );
		$("#"+tb).val(number_format(percentageToRangedVal(100, m, r, p), p, ".",",") + "%" );
	}
	else
	{
		$("#"+tt).val(percentageToRangedVal(0, m, r, p));
		$("#"+tb).val(percentageToRangedVal(100, m, r, p));
	}
	
}
function numeric_slide(ui, rMin, rRng, formatType)
{
	var nVal = ui.slider.curValue;
	var sTxt = ui.handle.id.replace(/_h_/, "_t_") ;
	var precision;
	
	if(formatType == "price")
	{
		precision = 0;
	}
	else if(formatType == "carat")
	{
		precision = 2;
	}
	else if(formatType == "percent")
	{
		precision = 1;
	}
	
	var updatedValue = percentageToRangedVal(nVal, rMin, rRng, precision); 
	if(formatType == "price")
	{
		updatedValue = "$"+number_format(updatedValue, precision, ".",",");
	}
	else if(formatType == "percent")
	{
		updatedValue = number_format(updatedValue, precision, ".", ",") + "%";
	}
	$("#"+sTxt).val( updatedValue );
}
  

function e_log(msg)
{
	$("#logbox").append(msg+"<br />");
}

function strip_formatting(str)
{
	var t = typeof str
	if(t == "string")
	{
		var tmp = str.replace(/\$/, "");
		return tmp.replace(/,/g, "");
	}
}

function percentageToIndex(percentVal, valArray)
{
	return ((100-percentVal) / 100) * (valArray.length);
}
function indexToPercentage(index, valArray)
{
	return 100 - (100 * (index / valArray.length));
}

function percentageToRangedVal(percentVal, minimum, range, precision)
{
	return myRound( Math.exp( ((100-percentVal) * range / 100) + minimum), precision);
}
function rangedValToPercentage(rangeVal, minimum, range, precision)
{
	var rangeVal = strip_formatting(rangeVal);
	return 100 - (100*(Math.log(rangeVal) - minimum) / range);
}
function myRound(val, decimals)
{
	var fac = Math.pow(10, decimals);
	return  Math.round(val * fac) / fac;
}
function myMax(a, b)
{
	if(a < b)
	{
		return a;
	}
	else
	{
		return b;
	}
}
  /* Made by Mathias Bynens <http://mathiasbynens.be/> */
function number_format(a,b,c,d){a=Math.round(a*Math.pow(10,b))/Math.pow(10,b);e=a+'';f=e.split('.');if(!f[0]){f[0]='0'}if(!f[1]){f[1]=''}if(f[1].length<b){g=f[1];for(i=f[1].length+1;i<=b;i++){g+='0'}f[1]=g}if(d!=''&&f[0].length>3){h=f[0];f[0]='';for(j=3;j<h.length;j+=3){i=h.slice(h.length-j,h.length-j+3);f[0]=d+i+f[0]+''}j=h.substr(0,(h.length%3==0)?3:(h.length%3));f[0]=j+f[0]}c=(b<=0)?'':c;return f[0]+c+f[1]}
