/* ---- Put your site specific functions in here --- */


function space_price(n){
	var x = 0;
	var res = '';
	
	for (var i=n.length-1; i>=0; i--){
		
		if (x % 3 == 0 && x>0)
			res = ' ' + res;
		res= n.substr(i, 1) + res;
		x++;
	}
	return res;
}

function price_format(n){
	// afronden op twee cijfers achter de komma
	n = Math.round(n*100)/100;
	
	if (n <=0) { 
		return '-'; 
	}
	
	var tmp = new String(n);
	
	
	// splitsen op een punt
	var expl = tmp.split(/\./);
	var test;
	// controleer of er een punt in voorkwam
	if (expl.length==2){
		if (expl[1].length<2){
			for (var i=expl[1].length; i<2; i++){
				expl[1]+='0';
			}
		}
		return space_price(expl[0]) + ',' + expl[1];
	}
	else{
		return space_price(expl[0]) + ',00';
	}
}

function detailfoto (fotoFlip) {
	for (i = 1; i <= 10; i++) {
		if (document.getElementById('fotoklein_' + i)) {
			if (i == fotoFlip) {
				document.getElementById('fotoklein_' + i).className = 'select';
				document.getElementById('fotogroot_' + i).className = 'toon-img';
			}	else {
				document.getElementById('fotoklein_' + i).className = '';
				document.getElementById('fotogroot_' + i).className = 'verberg-img';
			}
		}
	}	
}

function getSubCategories(){
    Event.observe('category', 'change', function() {
        if ($F('category') != 0) {
	        var url = "ajax/getSubcategories.php";
	        var pars = "parent_id="+$F('category');
	        
	        new Ajax.Request(url, {method:'get', parameters:pars, onComplete:function(originalRequest){
	            var data = eval('('+originalRequest.responseText+')');
	            var error = data.error;
	            var subcategories = data.subcategories;
	            
	            if (error != ''){
	                //error
	                alert(error);
	            } else {
	                //clear the box wich cities can be chosen from
	                $('subcategory').options.length=0;
	                
	                //show the cities
	                for (i=0;i<subcategories.length;i++){
	                    subcategory = subcategories[i];
	                    var option = document.createElement('option');
	                    option.value = subcategory.id;
	                    option.innerHTML = subcategory.text;
	                    $('subcategory').appendChild(option);
	                }
	            }
	        }
	        });
	    } else {
	    	$('subcategory').options.length=0;
            var option = document.createElement('option');
            option.value = 0;
            option.innerHTML = '-- kies eerst een Rubriek --';
            $('subcategory').appendChild(option);
	    }
        return false;
        
        
    });
}

// Updates price for chosen solutions
function updatePriceSolutions(type, obj) {
	var id = (obj.name).substring(7); // price id
	
	// Retrieve old value
	var oldAmount = document.getElementById('old_amount_' + id).value;
	
	// Update old value with new value
	var amount = obj.value;
	
	// IE 6 / 7 hack
	if (obj.type == 'select-one'){
		amount = obj.options[obj.selectedIndex].text;
	}
	
	// Type check
	if (isNaN(amount)) {
		amount = 0;
	}
	

	document.getElementById('old_amount_' + id).value = amount;
	
	// Price per unit (piece, m2, etc)
	var unitPrice = document.getElementById('price_' + id).innerHTML.replace(',', '.');
	unitPrice = unitPrice.replace(/ /g,"");
		
	// Koopwoning
	if (type == 'koop') {
		
		// Update total price
		if (document.getElementById('totaal')){
			var totalPrice = document.getElementById('totaal').innerHTML;		
			totalPrice = parseFloat(removeSpaces(totalPrice).replace(',', '.'));		
			totalPrice = totalPrice - (oldAmount * unitPrice) + (amount * unitPrice);
			document.getElementById('totaal').innerHTML = price_format(totalPrice);
		}
		
		document.getElementById('totaal_' + id).innerHTML = price_format(amount * unitPrice);
		document.getElementById('totaal2_' + id).innerHTML = price_format(amount * unitPrice);
		
		// update eenmalig
		if (document.getElementById('eenmalig_totaal')){
			var eenmalig_totaal = removeSpaces(document.getElementById('eenmalig_totaal').innerHTML.replace(',', '.'));
			eenmalig_totaal = eenmalig_totaal - (oldAmount * unitPrice) + (amount * unitPrice);
			document.getElementById('eenmalig_totaal').innerHTML = price_format(eenmalig_totaal);
		}
		
		
	} else {
		
		var method = document.getElementById('method').value;
		
		var percentage_once = parseInt(document.getElementById('percentage_once_' + id).value);
		var percentage_rent = document.getElementById('percentage_rent_' + id).value;
		var percentage_months = document.getElementById('percentage_months_' + id).value;
		
		// Huurwoning
		if (method){

			// new
			var eenmalig = 0;
			var oldEenmalig = 0;
			
			var eenmalig = ((unitPrice * amount) / 100) * percentage_once;
			
			var oldEenmalig = ((unitPrice * oldAmount) / 100) * percentage_once;
			var oldVerhoging = (((unitPrice * oldAmount) / 100) * percentage_rent) / percentage_months;
			
			var oldVerhoging = document.getElementById('verhoging_once_'+ id).value.replace(',', '.') * oldAmount;
			var verhoging = (document.getElementById('verhoging_once_'+ id).value.replace(',', '.')) * amount;
			
			if (document.getElementById('eenmalig_totaal')){
				var eenmalig_totaal = removeSpaces(document.getElementById('eenmalig_totaal').innerHTML.replace(',', '.'));
			}
			
			if (document.getElementById('verhoging_totaal')){
				var verhoging_totaal = removeSpaces(document.getElementById('verhoging_totaal').innerHTML.replace(',', '.'));
			}
			
		} else {
			
			if (percentage_months == 0){
				percentage_months = 1;
			}
			
			var eenmalig = ((unitPrice * amount) / 100) * percentage_once;
			var verhoging = (((unitPrice * amount) / 100) * percentage_rent) / percentage_months;
			
			var oldEenmalig = ((unitPrice * oldAmount) / 100) * percentage_once;
			var oldVerhoging = (((unitPrice * oldAmount) / 100) * percentage_rent) / percentage_months;
			
			if (document.getElementById('eenmalig_totaal')){
				var eenmalig_totaal = removeSpaces(document.getElementById('eenmalig_totaal').innerHTML.replace(',', '.'));
			}
			var verhoging_totaal = removeSpaces(document.getElementById('verhoging_totaal').innerHTML.replace(',', '.'));
		}
		// Calculate new total prices
		
		eenmalig_totaal = eenmalig_totaal - oldEenmalig + eenmalig;
		verhoging_totaal = verhoging_totaal - oldVerhoging + verhoging;
		
		// Format prices
		eenmalig = price_format(eenmalig);
		verhoging = price_format(verhoging);
		
		eenmalig_totaal = price_format(eenmalig_totaal);
		verhoging_totaal = price_format(verhoging_totaal);
		
		// Replace HTML
		if (document.getElementById('eenmalig_' + id)){
			document.getElementById('eenmalig_' + id).innerHTML = eenmalig;
		}
		
		if (document.getElementById('verhoging_' + id)){
			document.getElementById('verhoging_' + id).innerHTML = verhoging;
		}
		
		if (document.getElementById('eenmalig_totaal')){
			document.getElementById('eenmalig_totaal').innerHTML = eenmalig_totaal;
		}
		
		if (document.getElementById('verhoging_totaal')){
			document.getElementById('verhoging_totaal').innerHTML = verhoging_totaal;
		}
		
		if (document.getElementById('totaal2_' + id)){
			document.getElementById('totaal2_' + id).innerHTML = price_format(amount * unitPrice);
		}
	}
}

function removeSpaces(string) {
	var tstring = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	tstring += splitstring[i];
	return tstring;
}

// Confirm box
function display_confirm() {
	var r=confirm("Heeft u alle aantallen correct ingevuld?");
	if (r==true) {
  		document.forms[0].submit();
  	}
}

// Fonts
function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function allCheckboxesOff(formId){
	var form = $(formId);
	if ($('next').checked){
		if (typeof form != 'undefined'){
			checkboxes = form.getInputs('checkbox');
			checkboxes.each(function(e){
				if (e.id != 'next'){ 
					e.checked = 0
				} 
			});
		}
	}
}

window.onload = function(e) {
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);


function checkBox(id) { 
	if (document.getElementById(id).checked){
		document.getElementById(id).checked = false; 
	}else {
		document.getElementById(id).checked = "checked"; 
	}
} 

