// Contributors 
// Ilkka Huotari at http://www.editsite.net
// Mathieu 'p01' HENRI at http://www.p01.org/
// http://seky.nahory.net/2005/04/rounded-corners/
// Steven Wittens at http://www.acko.net/anti-aliased-nifty-corners
// Original Nifty Corners by Alessandro Fulciniti at http://pro.html.it/esempio/nifty/
function NiftyCheck() {
  if(!document.getElementById || !document.createElement) {
    return false;
  }
  var b = navigator.userAgent.toLowerCase();
  if (b.indexOf("msie 5") > 0 && b.indexOf("opera") == -1) {
    return false;
  }
  return true;
}

function Rounded(className, sizex, sizey, sizex_b, sizey_b) {
	var bk;
	if (!NiftyCheck()) return;
	if (typeof(sizex_b) == 'undefined')
		sizex_b = sizex;
	if (typeof(sizey_b) == 'undefined')
		sizey_b = sizey;
	var v = getElements(className);
	var l = v.length;
	for (var i = 0; i < l; i++) {
		color = get_current_style(v[i],"background-color","transparent");
		bk = get_current_style(v[i].parentNode,"background-color","transparent");
		AddRounded(v[i], bk, color, sizex, sizey, true);
		AddRounded(v[i], bk, color, sizex_b, sizey_b, false);
	}
}

Math.sqr = function (x) {
  return x*x;
};

function Blend(a, b, alpha) {

  var ca = Array(
    parseInt('0x' + a.substring(1, 3)), 
    parseInt('0x' + a.substring(3, 5)), 
    parseInt('0x' + a.substring(5, 7))
  );
  var cb = Array(
    parseInt('0x' + b.substring(1, 3)), 
    parseInt('0x' + b.substring(3, 5)), 
    parseInt('0x' + b.substring(5, 7))
  );
  return '#' + ('0'+Math.round(ca[0] + (cb[0] - ca[0])*alpha).toString(16)).slice(-2).toString(16)
             + ('0'+Math.round(ca[1] + (cb[1] - ca[1])*alpha).toString(16)).slice(-2).toString(16)
             + ('0'+Math.round(ca[2] + (cb[2] - ca[2])*alpha).toString(16)).slice(-2).toString(16);

  return '#' + ('0'+Math.round(ca[0] + (cb[0] - ca[0])*alpha).toString(16)).slice(-2).toString(16)
             + ('0'+Math.round(ca[1] + (cb[1] - ca[1])*alpha).toString(16)).slice(-2).toString(16)
             + ('0'+Math.round(ca[2] + (cb[2] - ca[2])*alpha).toString(16)).slice(-2).toString(16);
}

function AddRounded(el, bk, color, sizex, sizey, top) {
  if (!sizex && !sizey)
	return;
  var i, j;
  var d = document.createElement("div");
  d.style.backgroundColor = bk;
  var lastarc = 0;
  for (i = 1; i <= sizey; i++) {
    var coverage, arc2, arc3;
    // Find intersection of arc with bottom of pixel row
    arc = Math.sqrt(1.0 - Math.sqr(1.0 - i / sizey)) * sizex;
    // Calculate how many pixels are bg, fg and blended.
    var n_bg = sizex - Math.ceil(arc);
    var n_fg = Math.floor(lastarc);
    var n_aa = sizex - n_bg - n_fg;
    // Create pixel row wrapper
    var x = document.createElement("div");
    var y = d;
    x.style.margin = "0px " + n_bg + "px";
	x.style.height='1px';
	x.style.overflow='hidden';
    // Make a wrapper per anti-aliased pixel (at least one)
    for (j = 1; j <= n_aa; j++) {
      // Calculate coverage per pixel
      // (approximates circle by a line within the pixel)
      if (j == 1) {
        if (j == n_aa) {
          // Single pixel
          coverage = ((arc + lastarc) * .5) - n_fg;
        }
        else {
          // First in a run
          arc2 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j + 1) / sizex)) * sizey;
          coverage = (arc2 - (sizey - i)) * (arc - n_fg - n_aa + 1) * .5;
          // Coverage is incorrect. Why?
          coverage = 0;
        }
      }
      else if (j == n_aa) {
        // Last in a run
        arc2 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j + 1) / sizex)) * sizey;
        coverage = 1.0 - (1.0 - (arc2 - (sizey - i))) * (1.0 - (lastarc - n_fg)) * .5;
      }
      else {
        // Middle of a run
        arc3 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j) / sizex)) * sizey;
        arc2 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j + 1) / sizex)) * sizey;
        coverage = ((arc2 + arc3) * .5) - (sizey - i);
      }
      
      x.style.backgroundColor = Blend(bk, color, coverage);
	  if (top)
	      y.appendChild(x);
      else
	      y.insertBefore(x, y.firstChild);
      y = x;
      var x = document.createElement("div");
		x.style.height='1px';
		x.style.overflow='hidden';
      x.style.margin = "0px 1px";
    }
    x.style.backgroundColor = color;
    if (top)
	    y.appendChild(x);
    else
		y.insertBefore(x, y.firstChild);
    lastarc = arc;
  }
  if (top)
	  el.insertBefore(d, el.firstChild);
  else
	  el.appendChild(d);
}

function getElements(className) {
	var elements = [];
	var el = document.getElementsByTagName('DIV');  
	var regexp=new RegExp("\\b"+className+"\\b");
	for (var i = 0; i < el.length; i++) 
	{
		if (regexp.test(el[i].className)) 
			elements.push(el[i]);
	}
	return elements;
}

function get_current_style(element,property,not_accepted)
{
  var ee,i,val,apr;
  try
  {
    var cs=document.defaultView.getComputedStyle(element,'');
    val=cs.getPropertyValue(property);
  }
  catch(ee)
  {
    if(element.currentStyle)
  	{
	    apr=property.split("-");
	    for(i=1;i<apr.length;i++) apr[i]=apr[i].toUpperCase();
	    apr=apr.join("");
	    val=element.currentStyle.getAttribute(apr);
   }
  }
  if((val.indexOf("rgba") > -1 || val==not_accepted) && element.parentNode)
  {
	 if(element.parentNode != document) 
		 val=get_current_style(element.parentNode,property,not_accepted);
	 else
		 val = '#FFFFFF';
  }
  if (val.indexOf("rgb") > -1 && val.indexOf("rgba") == -1)
	  val = rgb2hex(val);
  if (val.length == 4)
	  val = '#'+val.substring(1,1)+val.substring(1,1)+val.substring(2,1)+val.substring(2,1)+val.substring(3,1)+val.substring(3,1);
  return val;
}

function rgb2hex(value)
{
	var x = 255;
	var hex = '';
	var i;
	var regexp=/([0-9]+)[, ]+([0-9]+)[, ]+([0-9]+)/;
	var array=regexp.exec(value);
	for(i=1;i<4;i++) hex += ('0'+parseInt(array[i]).toString(16)).slice(-2);
	return '#'+hex;
}

function switchMainPicture(srcObject){
	var mainPicture = document.getElementById('mainPicture').src;
	var thumbPicture = srcObject.src;
	
	mainPicture = mainPicture.replace(/200x200/,'50x50');
	thumbPicture = thumbPicture.replace(/50x50/,'200x200');
	
	document.getElementById('mainPicture').src = thumbPicture;
	srcObject.src = mainPicture;
}
function getPageSizeWithScroll(){
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
	return arrayPageSizeWithScroll;
}

function showWindowDiv(titel, functionName){
	document.getElementById('windowTitle').innerHTML = titel;
	document.getElementById('windowContent').innerHTML = eval(functionName);
	document.getElementById('windowOverlay').style.display = 'block';
	
	if( window.innerHeight && window.scrollMaxY ){ // Firefox {
		pageWidth = window.innerWidth + window.scrollMaxX;
		pageHeight = window.innerHeight + window.scrollMaxY;
	}
	else if( document.body.scrollHeight > document.body.offsetHeight ) // all but Explorer Mac
	{
		pageWidth = document.body.scrollWidth;
		pageHeight = document.body.scrollHeight;
	}
	else // works in Explorer 6 Strict, Mozilla (not FF) and Safari
	{ 
			pageWidth = document.body.offsetWidth + document.body.offsetLeft; 
			pageHeight = document.body.offsetHeight + document.body.offsetTop; 
	}
	
	document.getElementById('windowOverlay').style.height = pageHeight+'px';
	document.getElementById('windowDiv').style.display = 'block';
	return true;
}
function closeWindowDiv(){
	document.getElementById('windowOverlay').style.display = 'none';
	document.getElementById('windowDiv').style.display = 'none';
}

$(document).ready(function()
{
	$('#reviewLink').click(function(){
		if(formDiv != true) {
			formDiv = true;
			$('<div></div>').attr('id','window').appendTo('#formDiv').hide();
			$('<form></form>').attr('method','post').attr('action','').attr('id','reviewForm').appendTo('#window');
			$('<label></label>').attr('for', 'naam').html('Naam: ').appendTo('#reviewForm');
			$('<input>').attr('type','text').attr('name','naam').attr('value','').appendTo('#reviewForm');
			$('<br>').appendTo('#reviewForm');
			$('<label></label>').attr('for', 'email').html('E-mail: ').appendTo('#reviewForm');
			$('<input>').attr('type','text').attr('name','email').attr('value','').appendTo('#reviewForm');
			$('<br>').appendTo('#reviewForm');
			$('<label></label>').attr('for', 'score').html('Score: ').appendTo('#reviewForm');
			$('<select></select>').attr('name','score').attr('id', 'scoreSelect').appendTo('#reviewForm');
			
			for (i=1; i <= 10; i++) {
				$('<option></option>').attr('value',i).html(i).appendTo('#scoreSelect');
			}
			
			$('<br>').appendTo('#reviewForm');
			$('<label></label>').attr('for', 'comment').html('Review: ').appendTo('#reviewForm');
			$('<br>').appendTo('#reviewForm');
			$('<textarea></textarea>').attr('name', 'comment').attr('id', 'comment').appendTo('#reviewForm');
			$('<br>').appendTo('#reviewForm');
			$('<input>').attr('type', 'submit').attr('name', 'sendReview').attr('id', 'sendReview').attr('value', 'Versturen').attr('style', 'clear:both;').appendTo('#reviewForm');
			$('<input>').attr('type', 'button').attr('name', 'cancel').attr('id', 'cancelWindow').attr('value','Annuleren').appendTo('#reviewForm');
			$('#window').slideDown();
		}
		return false;
	});
	
	$('#usedLink').click(function(){
		if(formDiv != true) {
			formDiv = true;
			$('<div></div>').attr('id','window').appendTo('#formDiv').hide();
			$('<form></form>').attr('method','post').attr('action','').attr('id','usedForm').appendTo('#window');
			$('<label></label>').attr('for', 'naam').html('Naam: ').appendTo('#usedForm');
			$('<input>').attr('type','text').attr('name','naam').attr('value','').appendTo('#usedForm');
			$('<br>').appendTo('#usedForm');
			$('<label></label>').attr('for', 'email').html('E-mail: ').appendTo('#usedForm');
			$('<input>').attr('type','text').attr('name','email').attr('value','').appendTo('#usedForm');
			$('<br>').appendTo('#usedForm');
			$('<label></label>').attr('for', 'postcode').html('Postcode: ').appendTo('#usedForm');
			$('<input>').attr('type','text').attr('name','postcode').attr('value','').appendTo('#usedForm');
			$('<br>').appendTo('#usedForm');
			$('<label></label>').attr('for', 'woonplaats').html('Woonplaats: ').appendTo('#usedForm');
			$('<input>').attr('type','text').attr('name','woonplaats').attr('value','').appendTo('#usedForm');
			$('<br>').appendTo('#usedForm');
			$('<label></label>').attr('for', 'vraagprijs').html('Vraagprijs: ').appendTo('#usedForm');
			$('<input>').attr('type','text').attr('name','vraagprijs').attr('value','').appendTo('#usedForm');
			$('<br>').appendTo('#usedForm');
			$('<input>').attr('type', 'submit').attr('name', 'sendSale').attr('id', 'sendSale').attr('value', 'Versturen').attr('style', 'clear:both;').appendTo('#usedForm');
			$('<input>').attr('type', 'button').attr('name', 'cancel').attr('id', 'cancelWindow').attr('value','Annuleren').appendTo('#usedForm');
			$('#window').slideDown();
		}
		return false;
	});
	
	$('#shopLink').click(function(){
		if(formDiv != true) {
			formDiv = true;
			$('<div></div>').attr('id','window').appendTo('#formDiv').hide();
			$('<form></form>').attr('method','post').attr('action','').attr('id','shopForm').appendTo('#window');
			$('<label></label>').attr('for', 'url').html('URL: ').appendTo('#shopForm');
			$('<input>').attr('type','text').attr('name','url').attr('value','').appendTo('#shopForm');
			$('<br>').appendTo('#shopForm');
			$('<label></label>').attr('for', 'email').html('E-mail: ').appendTo('#shopForm');
			$('<input>').attr('type','text').attr('name','email').attr('value','').appendTo('#shopForm');
			$('<br>').appendTo('#shopForm');
			$('<input>').attr('type', 'submit').attr('name', 'sendShopAdd').attr('id', 'sendShopAdd').attr('value', 'Versturen').attr('style', 'clear:both;').appendTo('#shopForm');
			$('<input>').attr('type', 'button').attr('name', 'cancel').attr('id', 'cancelWindow').attr('value','Annuleren').appendTo('#shopForm');
			$('#window').slideDown();
		}
		return false;
	});
	
	$('#cancelWindow').live('click', function(){
		$('#formDiv div').slideUp();
		formDiv = false;
		return false;
	});
	
    $('#addSpec').click(function(){
    	uniqueValue = Math.floor(new Date().getTime() + Math.random());
    	$('<div></div>').attr('id', 'block' + uniqueValue).appendTo('#specsBlock');
    	$('<span></span>').html('Label: ').appendTo('#block' + uniqueValue);
    	$('<input>').attr('type', 'text').attr('name', 'label[' + uniqueValue + ']').attr('id', 'datatype[' + uniqueValue + ']').appendTo('#block' + uniqueValue);
    	$('<span></span>').html('Datatype: ').appendTo('#block' + uniqueValue);
    	$('<select></select>').attr('name', 'datatype[' + uniqueValue + ']').attr('id', uniqueValue).attr('class','setSpec').appendTo('#block' + uniqueValue);
    	$('<option></option>').attr('value','').html('Kies een type').appendTo('#' + uniqueValue);
    	$('<option></option>').attr('value','range').html('Van-tot').appendTo('#' + uniqueValue);
    	$('<option></option>').attr('value','unitvalue').html('Eenheid').appendTo('#' + uniqueValue);
    	$('<option></option>').attr('value','boolean').html('Waar / niet waar').appendTo('#' + uniqueValue);
    	$('<option></option>').attr('value','static').html('Text').appendTo('#' + uniqueValue);
    	$('<option></option>').attr('value','numeric').html('Numeriek').appendTo('#' + uniqueValue);
    	$('<div></div>').attr('id', 'spec' + uniqueValue).appendTo('#block' + uniqueValue);
    	return false;
    });
    
    $('.setSpec').live('click', function(){
    	fieldType = this.value;
    	fieldId = this.id;
    	specContent = '';
    	$('#spec' + fieldId).empty();
    	switch (fieldType)
    	{
			case 'range':
				$('<span></span>').html('Van').appendTo('#spec' + fieldId);
				$('<input>').attr('type', 'text').attr('name', 'rangeValFrom[' + fieldId + ']').attr('id', 'rangeValFrom[' + fieldId + ']').appendTo('#spec' + fieldId);
				$('<span></span>').html('Tot').appendTo('#spec' + fieldId);
				$('<input>').attr('type', 'text').attr('name', 'rangeValTo[' + fieldId + ']').attr('id', 'rangeValTo[' + fieldId + ']').appendTo('#spec' + fieldId);
				$('<span></span>').html('Eenheid').appendTo('#spec' + fieldId);
				$('<select></select>').attr('name', 'unitType[' + fieldId + ']').attr('id', 'unitType' + fieldId).appendTo('#spec' + fieldId);
				
				$.getJSON('/spec/units', function(data) {
					$.each(data, function(i,unit){
						$('<option></option>').attr('value', unit['unitId']).html(unit['unitName']).appendTo('#unitType' + fieldId);
					});
				});
				break;
			case 'unitvalue':
				$('<span></span>').html('Numerieke waarde').appendTo('#spec' + fieldId);
				$('<input>').attr('type', 'text').attr('name', 'unitVal[' + fieldId + ']').attr('id', 'unitVal[' + fieldId + ']').appendTo('#spec' + fieldId);
				$('<select></select>').attr('name', 'unitType[' + fieldId + ']').attr('id', 'unitType' + fieldId).appendTo('#spec' + fieldId);
				
				$.getJSON('/spec/units', function(data) {
					$.each(data, function(i,unit){
						$('<option></option>').attr('value', unit['unitId']).html(unit['unitName']).appendTo('#unitType' + fieldId);
					});
				});
				break;
			case 'boolean':
				$('<input>').attr('type', 'radio').attr('name', 'boolVal[' + fieldId + ']').attr('id', 'boolVal[' + fieldId + ']').attr('value', '1').appendTo('#spec' + fieldId);
				$('<span></span>').html('Ja').appendTo('#spec' + fieldId);
				$('<input>').attr('type', 'radio').attr('name', 'boolVal[' + fieldId + ']').attr('id', 'boolVal[' + fieldId + ']').attr('value', '0').appendTo('#spec' + fieldId);
				$('<span></span>').html('Nee').appendTo('#spec' + fieldId);
				break;
			case 'static':
				$('<span></span>').html('Text waarde: ').appendTo('#spec' + fieldId);
				$('<input>').attr('type', 'text').attr('name', 'staticVal[' + fieldId + ']').attr('id', 'staticVal[' + fieldId + ']').attr('value', '').appendTo('#spec' + fieldId);
				break;
			case 'numeric':
				$('<span></span>').html('Numerieke waarde: ').appendTo('#spec' + fieldId);
				$('<input>').attr('type', 'text').attr('name', 'numVal[' + fieldId + ']').attr('id', 'numVal[' + fieldId + ']').attr('value', '').appendTo('#spec' + fieldId);
				break;
		
			default:
				break;
    	}
		$('<br>').appendTo('#spec' + fieldId);
		$('<span></span>').html('Commentaar: ').appendTo('#spec' + fieldId);
		$('<input>').attr('type', 'text').attr('name', 'comment[' + fieldId + ']').attr('id', 'comment[' + fieldId + ']').attr('value', '').appendTo('#spec' + fieldId);
    	return false;
    });
    
    $('#deleteSpec').live('click', function(self){
    	var specId = $(this).attr('rel');
    	$('#block' + specId).remove();
    });
    
});
