// Global holds reference to selected element
var selectedObj;
// Globals hold location of click relative to element
var offsetX, offsetY;

//write weight range to form
var minWeight;
var maxWeight;
function drawWeights() {
  var count=1;
  for (i=minWeight;i<=maxWeight+.05;i+=0.05) {
	if (count>6) {break}
	var elem="w"+count;
	var n=document.getElementById(elem);
	val=parseInt(i*100)/100;
	res=""+val;
	if (res.indexOf('.')==-1) {res+="."};
	while (res.length-res.indexOf('.')<3) {res+="0"};
	n.innerHTML=res;
	count++;
  }
}



//show or hide search form
function showHide(id) {
  n=document.getElementById(id);
  if (n.style.display!="inline") {
    n.style.display="inline";
  } else {
    n.style.display="none";
  }
}

function stripquotes(a) {
  for (i=0;i<a.length;i++) {
    a[i]=a[i].replace(/^\'|\'$/g,"");
  }
  return a;
}
function setPreLimits() {
  if (preLimit["color"]) {
	parts=preLimit["color"].split(/ OR /i);
	parts=stripquotes(parts);
	setValues('A','B',colorMap,parts[0],parts[parts.length-1]);
  }
  if (preLimit["clarity"]) {
	preLimit["clarity"]=preLimit["clarity"].replace(/[\'\"]/g,'');
	parts=preLimit["clarity"].split(/ OR /i);
	parts=stripquotes(parts);
	setValues('C','D',clarityMap,parts[0],parts[parts.length-1]);
  }

  if (preLimit["quality"]) {
	preLimit["quality"]=preLimit["quality"].replace(/[\'\"]/g,'');
	parts=preLimit["quality"].split(/ OR /i);
	parts=stripquotes(parts);
	if ((parts[0]=="super ideal") || (parts[0]=="signature princess")) {parts[0]="ideal"};
	if ((preLimit["shape"]!="round")&&(preLimit["shape"]!="princess")) {parts[0]="very good"};
	setValues('E','F',qualityMap,parts[0],parts[parts.length-1]);
  }

  if (preLimit["weightgroup"]) {
    parts=preLimit["weightgroup"].split(/-/);
	parts=stripquotes(parts);
	minWeight=parseFloat(parts[0]);
	maxWeight=parseFloat(parts[1]);
//	drawWeights();


	  if (preLimit["weight"]) {
		var tmp=preLimit["weight"].replace(/^between /i,"");
		parts=tmp.split(/ and /i);
		min=""+Math.round((parts[0]-minWeight)*100)/100;
		max=""+Math.round((parts[1]-minWeight)*100)/100;
		setValues('G','H',weightMap,min,max);
	  }
  }
  
  if (preLimit["total"]) {
	var tmp=preLimit["total"].replace(/^between /i,"");
	parts=tmp.split(/ and /i);
	setValues('I','J',priceMap,parts[0],parts[1]);
  }



  setVals();
}

function setValues(x,y,list,xval,yval) {
  // the reverse of getValueList
  // this function takes the initial min and max values
  // and sets the sliders and limits accordingly
  n1=document.getElementById('img'+x+'Wrap');
  n2=document.getElementById('img'+y+'Wrap');
  var last;
  for (i=0;i<list.length;i++) {
    var parts=list[i].split('|');
	var pos=parseInt(parts[0]);
	var val=""+parts[1];
    if (isNaN(parseFloat(val))) {
		if (val.toLowerCase()==xval.toLowerCase()) {
		  n1.style.left=Math.floor((last+pos)/2)+"px";
		}
	} else {
		if (parseFloat(val)==parseFloat(xval)) {
		  n1.style.left=Math.floor((last+pos)/2)+"px";
		}
	}
	last=pos;
  }

  for (i=list.length-1;i>0;i--) {
    var parts=list[i].split('|');
	var pos=parseInt(parts[0]);
	var val=parts[1];
    if (isNaN(parseFloat(val))) {
		if (val.toLowerCase()==yval.toLowerCase()) {
		  n2.style.left=Math.floor((last+pos)/2)+"px";
		}
	} else {
		if (parseFloat(val)==parseFloat(yval)) {
		  n2.style.left=Math.floor((last+pos)/2)+"px";
		}
	}
	last=pos;
  }
}


function getValueList(x,y,list,type,modifier) {
  // x and y are the letter portion of the draggable elements.
  // list is the array which contains the position of each value
  // type is either "values" or "range"
  
  var min,max,minPos,maxPos,last,n1,n2,val;
  n1=document.getElementById('img'+x+'Wrap');
  n2=document.getElementById('img'+y+'Wrap');
  minPos=parseInt(n1.style.left);
  maxPos=parseInt(n2.style.left);
  var parts=list[0].split('|');
  last=parseInt(parts[0]);
  //get min value and set position.
  for (i=0;i<list.length;i++) {
    var parts=list[i].split('|');
	var pos=parseInt(parts[0]);
	if ((minPos<pos)||(i>=list.length-2)) {
      n1.style.left=Math.floor((last+pos)/2)+"px";
	  limits[n2.id][0]=Math.floor((last+pos)/2)+9;
      min=i;
	  break;
	}
	last=pos;
  }

  //get max value and set position.
  var parts=list[list.length-1].split('|');
  last=parseInt(parts[0]);
  for (i=list.length-1;i>0;i--) {
    var parts=list[i].split('|');
	var pos=parseInt(parts[0]);
	if ((maxPos>pos)||(i<=min)) {
      n2.style.left=Math.floor((last+pos)/2)+"px";
  	  limits[n1.id][1]=Math.floor((last+pos)/2)-9;
	  if ((x=='I')&&(limits[n1.id][1]>392)) {limits[n1.id][1]=392};
      max=i;
	  break;
	}
	last=pos;
  }

  
  if (type=="values") {
	var resultList=new Array();
	for (i=min;i<=max;i++) {
      var parts=list[i].split('|');
	  resultList.push("'"+parts[1]+"'");
	}
    return resultList.join(' OR ');
  } else {
	if (isNaN(parseFloat(modifier))) {modifier=0};
    var p1=list[min].split('|');
	var minVal=parseFloat(p1[1])+modifier;
    var p2=list[max].split('|');
	var maxVal=parseFloat(p2[1])+modifier;
	return "between "+minVal+" and "+maxVal;
  }

}

//set values onMouseUp
function setVals() {
  f=document.searchForm;
  f.elements['loose.color'].value=getValueList('A','B',colorMap,'values');
  f.elements['loose.clarity'].value=getValueList('C','D',clarityMap,'values');
  val=getValueList('E','F',qualityMap,'values');
  val=val.replace(/\'Ideal\'/i,"'Super Ideal' OR 'Signature Princess'");
  f.elements['loose.cutquality'].value=val;

//  f.elements['loose.weight'].value=getValueList('G','H',weightMap,'range',minWeight);
  f.elements['loose.total'].value=getValueList('I','J',priceMap,'range');
}


// Set global reference to element being engaged and dragged
var limits=new Array();
addLimit('A',0,300);
addLimit('B',10,300);
addLimit('C',0,413);
addLimit('D',10,413);
addLimit('E',0,413);
addLimit('F',10,413);
addLimit('G',0,413);
addLimit('H',10,413);
addLimit('I',0,485);
addLimit('J',10,527);

function addPricePos(v) {
  pricePos[pricePos.length]=v;
}
function getPricePos(v) {
  for (i=1;i<pricePos.length;i++) {
    if (pricePos[i]>v) {return i-1};
  }
}

function setLimit(id,val) {
  if (id=="imgAWrap") {limits["imgBWrap"][0]=val+9};
  if (id=="imgBWrap") {limits["imgAWrap"][1]=val-9};
  if (id=="imgCWrap") {limits["imgDWrap"][0]=val+9};
  if (id=="imgDWrap") {limits["imgCWrap"][1]=val-9};
  if (id=="imgEWrap") {limits["imgFWrap"][0]=val+9};
  if (id=="imgFWrap") {limits["imgEWrap"][1]=val-9};
  if (id=="imgGWrap") {limits["imgHWrap"][0]=val+9};
  if (id=="imgHWrap") {limits["imgGWrap"][1]=val-9};
  if (id=="imgIWrap") {limits["imgJWrap"][0]=val+9};
  if (id=="imgJWrap") {limits["imgIWrap"][1]=val-9};
}

function addLimit(letter,min,max) {
	lim="img"+letter+"Wrap";
	limits[lim]=new Array();
	limits[lim][0]=min;
	limits[lim][1]=max;
}

function setSelectedElem(evt) {
    var target = (evt.target) ? evt.target : evt.srcElement;
    var spanID = (target.name && target.src) ? target.name + "Wrap" : "";
    if (spanID) {
        if (document.layers) {
            selectedObj = document.layers[spanID];
        } else if (document.all) {
            selectedObj = document.all(spanID);
        } else if (document.getElementById) {
            selectedObj = document.getElementById(spanID);
        }
        setZIndex(selectedObj, 100);
        return;
    }
    selectedObj = null;
    return;
}

// Drag an element
function dragIt(evt) {
    evt = (evt) ? evt : event;

    if (selectedObj) {
        window.status=evt.clientX+" "+offsetX+" "+limits[selectedObj.id][0];
        if ((evt.pageX)&&(evt.pageX-offsetX>limits[selectedObj.id][0])&&
			(evt.pageX-offsetX<limits[selectedObj.id][1])) {
				shiftTo(selectedObj, (evt.pageX - offsetX), (evt.pageY - offsetY));
        } else if ((  evt.clientX || evt.clientY)
					&&(evt.clientX-offsetX>limits[selectedObj.id][0])
					&&(evt.clientX-offsetX<limits[selectedObj.id][1])
					) {
            shiftTo(selectedObj, (evt.clientX - offsetX), parseInt(selectedObj.style.top));
        } 
		evt.cancelBubble = true;
        return false;
    }
}
// Turn selected element on
function engage(evt) {
    evt = (evt) ? evt : event;
    setSelectedElem(evt);
    if (selectedObj) {
        if (evt.pageX) {
            offsetX = evt.pageX - ((selectedObj.offsetLeft) ? 
                     selectedObj.offsetLeft : selectedObj.left);
        } else if (evt.offsetX || evt.offsetY) {
            offsetX = evt.offsetX - ((evt.offsetX < -2) ? 
                      0 : document.body.scrollLeft);
			nleft=selectedObj.parentNode.parentNode.offsetLeft;
			offsetX+=nleft;
        } else if (evt.clientX) {
            offsetX = evt.clientX - ((selectedObj.offsetLeft) ? 
                      selectedObj.offsetLeft : 0);
            offsetY = evt.clientY - ((selectedObj.offsetTop) ? 
                      selectedObj.offsetTop : 0);
        }
        return false;
    }
}
// Turn selected element off
function release(evt) {
    if (selectedObj) {
		var result;
		evt = (evt) ? evt : event;
        if (evt.pageX) {
			result=evt.pageX-offsetX;
		} else if (evt.clientX) {
			result=evt.clientX-offsetX;
		}
		
		setVals();
        setLimit(selectedObj.id,result);

        setZIndex(selectedObj, 0);
        selectedObj = null;

	}
}

// Set event capture for Navigator 4
function setNSEventCapture() {
    document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
}
// Assign event handlers used by both Navigator and IE
function init() {
	if (document.layers) {
        setNSEventCapture();
    }
    document.onmousedown = engage;
    document.onmousemove = dragIt;
    document.onmouseup = release;
	setPreLimits();
//    if (preLimit["total"]) {showHide('searchform')}; //to leave slider div open
	checkCmpBoxes();
}

var weightOffset=1;

var colorMap=new Array();
colorMap.push('-19|begin');
colorMap.push('9|D');
colorMap.push('39|E');
colorMap.push('73|F');
colorMap.push('105|G');
colorMap.push('135|H');
colorMap.push('161|I');
colorMap.push('196|J');
colorMap.push('226|K');
colorMap.push('259|L');
colorMap.push('290|M');
colorMap.push('321|end');

var clarityMap=new Array();
clarityMap.push('-30|begin');
clarityMap.push('24|IF');
clarityMap.push('88|VVS1');
clarityMap.push('147|VVS2');
clarityMap.push('198|VS1');
clarityMap.push('251|VS2');
clarityMap.push('298|SI1');
clarityMap.push('345|SI2');
clarityMap.push('390|I1');
clarityMap.push('435|end');

var qualityMap=new Array();
qualityMap.push('-70|begin');
qualityMap.push('63|Ideal');
qualityMap.push('157|Very Good');
qualityMap.push('247|Good');
qualityMap.push('337|end');

var priceMap=new Array();
priceMap.push('-1|begin');
priceMap.push('36|0');
priceMap.push('63|1000');
priceMap.push('91|2000');
priceMap.push('119|3000');
priceMap.push('147|4000');
priceMap.push('175|5000');
priceMap.push('203|6000');
priceMap.push('230|7000');
priceMap.push('258|8000');
priceMap.push('286|9000');
priceMap.push('318|10000');
priceMap.push('367|15000');
priceMap.push('418|20000');
priceMap.push('476|999000');
priceMap.push('526|end');

var weightMap=new Array();
weightMap.push('-40|begin');
weightMap.push('18|0');
weightMap.push('94|.05');
weightMap.push('169|.10');
weightMap.push('244|.15');
weightMap.push('319|.20');
weightMap.push('394|.25');
weightMap.push('472|end');

//*************************************************************//

function addRemove(box) {
  if (box.checked) {
	  addToList(box.name);
  } else {
	  removeFromList(box.name);
  }
}

function addToList(val) {
  cookieVal=getCookie("sd_compare");
  if (!cookieVal) {cookieVal=""};
  parts=cookieVal.split('\|');
  alreadyThere=0;
  for (i=0;i<parts.length;i++) {
    if (parts[i]==val) {alreadyThere=1}
  }
  if (alreadyThere) {return};
  parts[parts.length]=val;
  newVal=parts.join('|');
  setCookie("sd_compare",newVal,1);
}

function removeFromList(val) {
  cookieVal=getCookie("sd_compare");
  parts=cookieVal.split('\|');
  alreadyThere=0;
  newList=new Array();
  for (i=0;i<parts.length;i++) {
    if (parts[i]!=val) {newList[newList.length]=val}
  }
  newVal=newList.join('|');
  setCookie("sd_compare",newVal,1);
}


function setCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
	endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function getCookie (name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
		return getCookieVal (j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return null;
}

function compare() {
  val=getCookie("sd_compare");
  setCookie("sd_compare","",0);
  parts=val.split('\|');
  for (i=0;i<parts.length;i++) {
    parts[i]=parts[i].replace(/^cmp_/,'');
	parts[i]='%27'+parts[i]+'%27';
  }
  newVal=parts.join('%20or%20');
  layout=document.nav._layout.value;
  location='/cgi-bin/webdata_pro.pl?_cgifunction=Search&_layout='+layout+'&loose.code='+newVal+'&hideSlider=1';
}

function checkCmpBoxes() {
  f=document.forms['cmpForm'];
  val=(getCookie("sd_compare"))?getCookie("sd_compare"):"";
  for (i=0;i<f.elements.length;i++) {
	boxName=f.elements[i].name;
	if (boxName.indexOf('cmp_')==0) {
		f.elements[i].checked=false;
		parts=val.split('\|');
		for (j=0;j<parts.length;j++) {
			if (f.elements[i].name==parts[j]) {f.elements[i].checked=true};
		}
	}
  }
}

function stripOr(val) {
  val=val.replace(/ OR /ig,', ');
  val=val.replace(/\'/g,'');
  return val;
}