$(document).ready(function(){
	loadOptions($("#pid").val(), 'property2', {property1: null}, true);

	$("#property1").change(function(){
		loadOptions($("#pid").val(), 'property2', {property1: $("#property1").val()});
	});

	$("#property2").change(function(){
		loadOptions($("#pid").val(), 'property1', {property2: $("#property2").val()});
	});

	$("#order_btn").click(function(){
		if($("#property1").val() == "" && $("#property2").val() == "") {
			alert('Selecteert u alstublieft een maat en een kleur.');
			return false;
		}
	});

	$(".nojs_warning").hide();
	$("#order_btn").show();
});

/**
 * Function to load options into select box
 * @param String propertyId Target id of select box
 * @param Array otherPropertyValues Array of properties on which the target depends
 * @return null
 */
function loadOptions(productId, propertyId, otherPropertyValues, initialize) {
	var getVariables = otherPropertyValues;

	getVariables['target']		= propertyId;
	getVariables['targetVal']	= $("#" + propertyId).val();
	getVariables['pid']			= productId;

	$.getJSON("/optionHandler.php", getVariables, function (data) {
		// Clear options
		$("#"+data['target']).removeOption(/./);
		// Add options
		$("#"+data['target']).addOption(data['options']);
		// If selected value equals null => convert to empty
		data['targetVal'] = data['targetVal'] == 'null' ? "" : data['targetVal'];
		// Select option
		if(data['toggle'] == "hide"){
			$("#"+data['target']).parent().hide();
		}else{
			$("#"+data['target']).parent().show();
		}
		if(data['targetVal'] != ''){
			$("#"+data['target']).selectOptions(data['targetVal']);
		}
		if(initialize){
			loadOptions($("#pid").val(), 'property1', {property2: $("#property2").val()});
		}
		updateItemPrice(data['pid'], data['target'], data['otherPropertyValues']);
	});
}

function updateItemPrice(productId, propertyId, otherPropertyValues) {
	var getVariables = otherPropertyValues;

	getVariables['pid']			= productId;
	getVariables[propertyId]	= $("#" + propertyId).val();

	for(var propertyId in otherPropertyValues) {
		getVariables[propertyId] = $("#" + propertyId).val();
	}

	$.getJSON("/itemPriceHandler.php", getVariables, function (data) {
		$("#itemprice").html(data['itemprice']);
		if(data['image'] != ''){
			$('#productImage').attr('src','/dynamisch/producten/'+data['image']);
		}
	});
}
