Coordinate_X_InImage = 0;
Coordinate_Y_InImage = 0;
magnify = new Array(0); // initialized in setBlocks()
if (typeof(window['photoImgElementId']) == "undefined" ) { photoImgElementId = "photocolorpicker_img"; }

function windowOnLoadHandler_paint() {
	if(document.addEventListener) {
		document.getElementById(photoImgElementId).addEventListener("mousemove", TrackCoordinatesInImage, false);
	} else if(window.event) {
	  document.getElementById(photoImgElementId).onmousemove = TrackCoordinatesInImage;
	}
}
	
function searchcolorrgb() { // called by button "search nearest colors", loads the results from the server into a div
  var r = document.getElementById('redBox').value;
  var g = document.getElementById('greenBox').value;
  var b = document.getElementById('blueBox').value;
	var div = document.getElementById('paintresults');
	div.innerHTML = 'Searching for color' + 
	                '<br><img src="/js/thickbox/images/loadingAnimation.gif">' + 
									'<div style="height:2000px"></div>';
  loadFragmentInToElement('paintresults','/paint.php?searchrgb&r='+r+'&g='+g+'&b='+b);
}

function searchcolorhsv() { // called by button "search nearest colors", loads the results from the server into a div
  var h = document.getElementById('hueBox').value;
  var s = document.getElementById('saturationBox').value;
  var v = document.getElementById('valueBox').value;
	var div = document.getElementById('paintresults');
	div.innerHTML = 'Searching for color' + 
	                '<br><img src="/js/thickbox/images/loadingAnimation.gif">' + 
									'<div style="height:2000px"></div>';
  
	loadFragmentInToElement('paintresults','/paint.php?searchhsv&h='+h+'&s='+s+'&v='+v);
}

var firstColorSearch = true; // smooth scroll to results after the first search
function searchcoloroptimized() { // called by button "search nearest colors", loads the results from the server into a div
	var h = document.getElementById('hueBox').value;
  var s = document.getElementById('saturationBox').value;
  var v = document.getElementById('valueBox').value;
  var r = document.getElementById('redBox').value;
  var g = document.getElementById('greenBox').value;
  var b = document.getElementById('blueBox').value;	
	var div = document.getElementById('paintresults');
	div.innerHTML = 'Searching for color...' + 
	                '<br><img src="/js/thickbox/images/loadingAnimation.gif">' + 
									'<div style="height:2000px"></div>';

	var formElements = '';
	for(i=0; i<document.formsearch.elements.length; i++) {
    formElements = formElements + '&' + document.formsearch.elements[i].name + '=' + escape(document.formsearch.elements[i].checked);
	}
	if (firstColorSearch) {
    firstColorSearch = false;	
	  loadFragmentInToElement('paintresults','/paint.php?searchoptimized&h='+h+'&s='+s+'&v='+v+'&r='+r+'&g='+g+'&b='+b+formElements, true);
	}
  else {
	  loadFragmentInToElement('paintresults','/paint.php?searchoptimized&h='+h+'&s='+s+'&v='+v+'&r='+r+'&g='+g+'&b='+b+formElements, false);
  }
}

var firstChartSearch = true; // smooth scroll to results after the first search
function showchart() {
	var div = document.getElementById('paintresults');
	div.innerHTML = 'Loading paint chart...' + 
	                '<br><img src="/js/thickbox/images/loadingAnimation.gif">' + 
									'<div style="height:2000px"></div>';

	var formElements = '';
	var value;
	for(i=0; i<document.formsearch.elements.length; i++) {
	  var element = document.formsearch.elements[i];
		if (element.type=='checkbox') {
		  value = element.checked;
		}
		else if (element.type=='radio') {
		  if (element.checked == true) {
			  value = element.value;
			}
			else continue; // skip unchecked radio buttons, because all buttons in the same group have the same name.
		}
    else {
      value = element.value;
    }		
    formElements = formElements + '&' + document.formsearch.elements[i].name + '=' + escape(value);
	}
	if (firstChartSearch) {
    firstChartSearch = false;	
	  loadFragmentInToElement('paintresults','/paint.php?showchart&'+formElements, true);
	}
  else {
	  loadFragmentInToElement('paintresults','/paint.php?showchart&'+formElements, false);
  }
}

function toHex(N) { // 8 bit number to a hex string
	if (N==null) return "00";
	N=parseInt(N); if (N==0 || isNaN(N)) return "00";
	N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
	return "0123456789ABCDEF".charAt((N-N%16)/16)
			 + "0123456789ABCDEF".charAt(N%16);
}

function RGBtoHex(R,G,B) { // 3 * 8 bit numbers to a hex string of 6 characters
  return toHex(R)+toHex(G)+toHex(B)
}

function getImgPixelColor(oImg, x, y)  {  // pixel of image under the mouse cursor as a hex color string
 // try
 {
    if (!oImg) {
		  alert('oImg=null');
			return;
		}
//  	var oCanvasImg = new Image();
//		oCanvasImg.src = oImg.src;

		var oCanvas = document.createElement("canvas");
		if (!oCanvas.getContext) {
		  alert('failed to create canvas element (experimental HTML 5).');
			return;
		}
		var oCtx = oCanvas.getContext("2d");
		if (!oCtx.getImageData) {
		  alert('getImageData failed');
			return;
		}
		var fResolution = 1;
		var iWidth = Math.round(parseInt(oImg.offsetWidth) * fResolution);
		var iHeight = Math.round(parseInt(oImg.offsetHeight) * fResolution);
		oCanvas.width = iWidth;
		oCanvas.height = iHeight;
		oCanvas.style.display = "none";
		oCanvas.style.width = iWidth;
		oCanvas.style.height = iHeight;
		oCtx.drawImage(oImg, 0, 0, iWidth, iHeight);
		
		var oImgData = oCtx.getImageData(0, 0, iWidth, iHeight).data;  // This only works if the source image is local (from this website)

		var sumR = 0; // add the Red value of each pixel in the magnification grid. This is used to calculate the average color of all used magnified pixels
		var sumG = 0; // same for Green
		var sumB = 0; // same for Blue
		var sumPixels = 0; // amount of pixels used to calculate the average color
		var	iOffset = 0; // index in oImgData
		var	iRed = 0; // red value of image pixel
		var	iGreen = 0;
		var	iBlue = 0;
		
 		var dx = -Math.floor(magnify.length / 2);    // magnification starts this amount of pixels left of X
		var dy = -Math.floor(magnify[0].length / 2); // magnification starts this amount of pixels above Y
		// copy pixel values to the the 'magnification' grid
		for ( iy=0; iy<magnify.length; ++iy ){  // loop through magnification rectangle
	    for (var ix=0; ix<magnify[iy].length; ++ix ){ // loop through magnification rectangle
			  magnify[iy][ix] = ''; 
				
				mx = x + dx + ix; // current pixelX near X in the magnification area
				my = y + dy + iy; // current pixelY near Y in the magnification area
				if ( (mx >= 0) &&
				     (my >= 0) &&
						 (mx < iWidth) &&
						 (my < iHeight) ) {
					iOffset = (my*iWidth + mx) * 4;
					iRed = oImgData[iOffset];
					iGreen = oImgData[iOffset + 1];
					iBlue = oImgData[iOffset + 2];
					magnify[iy][ix] = '#' + RGBtoHex(iRed, iGreen, iBlue);
					
					sumPixels++;
					sumR = sumR + iRed;
					sumG = sumG + iGreen;
					sumB = sumB + iBlue;
				} 
			}
		}
		updateBlocks();
		
		if (sumPixels > 0) {
		  iRed   = Math.floor(sumR / sumPixels);
		  iGreen = Math.floor(sumG / sumPixels);
		  iBlue  = Math.floor(sumB / sumPixels);

		  var hexcolor = '#' + RGBtoHex(iRed, iGreen, iBlue);
		
		  return hexcolor; 
		}
    else alert('no result');		
	}
//  catch(err) {
//    alert('javascript error: ' + err.description);
//  }	
}

function selectColorFromImage(x, y) {	
	var img = document.getElementById(photoImgElementId);
	if (!img) {
	  alert('img element not found: ' + photoImgElementId);
	}
  var hexcolor = getImgPixelColor(img, x, y);
	if ((!hexcolor) || (hexcolor == null)) {
	  alert('Failed to read the pixel color from the image at coordinate (' + x + ', ' + y + '). This feature might not work in your web browser. If you use Firefox or Opera then you can find matching paints by clicking on a color in this image.');
	}
	else {
	  document.getElementById('hexBox').value = hexcolor;
	  hexBoxChanged();
	}	
}

function TrackCoordinatesInImage(evt){
  Coordinate_X_InImage = Coordinate_Y_InImage = 0;
  if(window.event && !window.opera && typeof event.offsetX == "number") {
    // IE 5+
		Coordinate_X_InImage = event.offsetX;
		Coordinate_Y_InImage = event.offsetY;
  } 
	else if(document.addEventListener && evt && typeof evt.pageX == "number"){
		// Mozilla-based browsers
		var Element = evt.target;
		var CalculatedTotalOffsetLeft, CalculatedTotalOffsetTop;
		CalculatedTotalOffsetLeft = CalculatedTotalOffsetTop = 0;
		while (Element.offsetParent) {
	  	CalculatedTotalOffsetLeft += Element.offsetLeft ;
	  	CalculatedTotalOffsetTop += Element.offsetTop ;
		  Element = Element.offsetParent ;
    }
    Coordinate_X_InImage = evt.pageX - CalculatedTotalOffsetLeft ;
    Coordinate_Y_InImage = evt.pageY - CalculatedTotalOffsetTop ;
  }
  document.getElementById('coord').innerHTML = "("+Coordinate_X_InImage+", "+Coordinate_Y_InImage+")";
}

// array to store mouse click coordinates
//var coords=new Array();

function storepoint(x,y){  // triggered by mouse click on image
// alert(x+', '+y);
  selectColorFromImage(x, y);
}

function photoReplaced() {  // initialize new image
  windowOnLoadHandler_paint();
	setBlocks();
}

function photoFromUrl() { // load the image from the url. The server processes the url to make external images local, otherwise getImgPixelColor won't work
  var div = document.getElementById('photocolorpicker_div');
	var url = document.getElementById('photocolorpicker_url').value;
	if (url == '') 
	  alert('please copy a valid web address of the image into the inputbox on the left.')
	else {
//	  photocolorpicker_img = "photocolorpicker_img_" + Math.floor(Math.random() * 10000);
//		alert(photocolorpicker_img);
    loadFragmentInToElementPost('photocolorpicker_div','/paint.php', 'photo_url=' + url, null, photoReplaced);
	}
}

function select_sample_change(element) { // load a sample image, selected by the combobox
  var div = document.getElementById('photocolorpicker_div');
	var url = element.value;
  loadFragmentInToElementPost('photocolorpicker_div','/paint.php', 'photo_url=' + url, null, photoReplaced);
}

/*
function photoFromFile() {
  // test, Firefox 3.0 only
  var fileinput = document.getElementById('photocolorpicker_upload');
	alert(fileinput.files.item(0).fileName);
	alert(fileinput.files.item(0).fileSize);
	alert(fileinput.files.item(0).getAsDataURL());
	alert(fileinput.files.item(0).getAsBinary());
}
*/

function startPhotoUploadCallback() {
  var content = '<div style="vertical-align:center; text-align:center;">Uploading file...<br>';
	var fileinput = document.getElementById('photocolorpicker_upload');
	if ((fileinput.files) && (fileinput.files.item(0))) { 
	  if (fileinput.files.item(0).fileName) { content = content + 'filename: ' + fileinput.files.item(0).fileName + '<br>'; }
	  if (fileinput.files.item(0).fileSize) { content = content + 'bytes: ' + fileinput.files.item(0).fileSize + '<br>'; }
	}	
	content = content + '<img src="/js/thickbox/images/loadingAnimation.gif"></div>';
	document.getElementById('photocolorpicker_div').innerHTML = content;
  return true;
}

function completePhotoUploadCallback(response) {
	document.getElementById('photocolorpicker_div').innerHTML = response;
	photoReplaced();
}

function setBlocks() {
  var amount = document.getElementById('blocks').value;
  var blockContainer = document.getElementById('magnify');	
	var html = '';
  var y;
	var x;
	var style;

	// initialize 2D array
	magnify = new Array(); // center point under the mouse cursor is [amount div 2 + 1, amount div 2 + 1]
  for (y=0; y<amount; ++y) {
    magnify[y] = new Array();
		for ( x=0; x<amount; ++x ){
		  magnify[y][x] = '';
		}
  }
	style = 'width:' + Math.floor(80 / amount) + 'px;height:' + Math.floor(80 / amount) + 'px;';
	
	html = '<table class=magnify>';
	for ( y=0; y<magnify.length; ++y ){
    html = html + '<tr>';
		for ( x=0; x<magnify[y].length; ++x ){
		  html = html + '<td id="mag'+y+'x'+x+'" style="'+style+'"></td>';
		}
    html = html + '</tr>';
	} 
	html = html + '</table>';
	
	blockContainer.innerHTML = html;
}

function updateBlocks() {
  // set the color of the blocks
  var y;
	var x;
	var element;
	for ( y=0; y<magnify.length; ++y ){
    for ( x=0; x<magnify[y].length; ++x ){
		  element = document.getElementById('mag'+y+'x'+x);
			if (element) {
		    element.style.backgroundColor = magnify[y][x];	  
			}
		}
  } 
}


var previouszIndex = 1;
function paintResultDivMouseOverWhite(element) {
  element.style.borderColor = '#A0A0A0';
	previouszIndex = element.style.zIndex;
	element.style.zIndex = 2;
}

function paintResultDivMouseOverGray(element) {
  element.style.borderColor = '#606060';
	previouszIndex = element.style.zIndex;
	element.style.zIndex = 2;
}

function paintResultDivMouseClick(element) {
	paintResultTooltipShow(element);
}

function paintResultDivMouseOut(element) {
	element.style.borderColor = element.style.backgroundColor;
	element.style.zIndex = previouszIndex;
	paintResultTooltipHide(element);
}

function paintResultTooltipShow(paintElement) {

	var tooltip = document.getElementById('paintToolTip');
	// position the tooltip lower-right of the paint block
	
	tooltip.style.left = String(Number(paintElement.style.left.substring(0, paintElement.style.left.length - 2)) + Number(paintElement.style.width.substring(0,  paintElement.style.width.length - 2)) + 5) + 'px';
	tooltip.style.top  = String(Number(paintElement.style.top.substring(0,  paintElement.style.top.length - 2))  + Number(paintElement.style.height.substring(0, paintElement.style.height.length - 2)) + 5) + 'px';
	tooltip.style.display = 'block';
	tooltip.innerHTML = 'Loading...';
	loadFragmentInToElement(tooltip.id, '/paint/tooltip/' + paintElement.id);
}

function paintResultTooltipHide(paintElement) {
	var tooltip = document.getElementById('paintToolTip');
	tooltip.style.display = 'none';
}

function paintDetails($id) {
  window.location.href = '/paintdetails/' + $id;
}
