var setting = new Array(8);
setting['minClosetHeight'] = 50; // minimal allowed closet height
setting['maxClosetHeight'] = 263; // maximal allowed closet height
setting['minClosetWidth'] = 120; // minimal allowed closet width
setting['maxClosetWidth'] = 500; // maximal allowed closet width
setting['minDoorWidth'] = 60; // minimal allowed door width
setting['maxDoorWidth'] = 100; // maximal allowed door width
setting['maxDoorAmount'] = 6; // maximal allowed door amount
setting['profileWidth'] = 3; // width of profile (cm/px)

var values = new Array(12);
values['ClosetHeight'] = 0; // current closet height
values['ClosetWidth'] = 0; // current closet width
values['DoorHeight'] = 0; // current closet height
values['DoorWidth'] = 0; // current closet width
values['AmountOfDoors'] = 0; // current amount of doors
values['ProfileColorId'] = 0; // current profile id
values['ProfilesColorCode'] = 0; // current selected color code
values['SelectedDoorIndex'] = null; // current selected door
values['SelectedMaterialGroup'] = 1; // current selected material group
values['maxDoorsAmount']; // maximal allowed doors calculated by the closet width
values['minDoorsAmount']; // minimal allowed doors calculated by the closet width
values['TotalPrice'] = 0; // current total price
values['DecorativeStrips'] = 0;
var Doors = new Array(); // array with door materials

$(document).ready(function(){
	
	init_page1Events();
	
});

function init_page1Events() {
	$('#closet').hide();
	// start with input height
	$("#ClosetHeight").focus();
	
	// set default values
	values['ProfileColorId'] = $("#create-closet-profile .radio input:checked").attr("value"); // current profile id
	values['ProfilesColorCode'] = profileColors[values['ProfileColorId']]; // current selected color code
	
	/* STEP 1: select sizes */
	
	// when the user update the sizes
	$("#ClosetWidth").focus(function () {
		$('#create-closet-amount ul li').hide();
		$('#create-closet-amount').hide();
		$("#create-closet-next").hide();
		$('ul#closet li').remove();
		values['AmountOfDoors'] = 0; // reset amount of doors
	});
	
	// validate input values
	$("#start").click(function () {
		var valid = new Array(2);
		
		// validate both values
		$.each( ['ClosetHeight', 'ClosetWidth'], function(key, name){
			values[name] = parseInt($('#'+name).val(), 10);
			
			if (isNaN(values[name])) {
				values[name] = '';
			}
			// false value
			if (values[name] > setting['max'+name] || values[name] < setting['min'+name]){
	    		valid[name] = false;
	    		$('#'+name).addClass('error');
	    		if (name == 'ClosetHeight'){
	    			var msg = 'De hoogte van de kast kan alleen tussen '+setting['minClosetHeight']+' en '+setting['maxClosetHeight']+' zijn.';
	    		}
	    		else{
	    			var msg = 'De breedte van de kast kan alleen tussen '+setting['minClosetWidth']+' en '+setting['maxClosetWidth']+' zijn.';
	    		}
	    		setFlash(msg);
	    	}
	    	// valid value
	    	else{
	    		valid[name] = true;
	    		$('#'+name).removeClass('error');
	    	}
		});
		
		// show x line when width is valid
		if (valid['ClosetWidth']) {
    		$('#x-line').animate({width: values['ClosetWidth']+'px'}, {"duration": 600,	queue: false, "easing": "easeOutBack"});
    		$('#x-line p').html(values['ClosetWidth']+'cm breed');
		}
		
		// if height and width are valid show the selection of door amounts
    	if (valid['ClosetHeight'] && valid['ClosetWidth'] ){
    		// calculate doors that could be used
    		var amounts = calculateDoorAmounts(values['ClosetWidth'], setting['maxDoorWidth'], setting['minDoorWidth'], setting['maxDoorAmount'], setting['profileWidth']);
    		values['maxDoorsAmount'] = amounts['max'];
    		values['minDoorsAmount'] = amounts['min'];
    		// show doors selections box
    		$("#create-closet-amount").fadeIn('slow');
    		// show doors selections
    		showSelectiondoors(amounts['min'], amounts['max']);
    	}
    	return false;
	});
	
	/* STEP 2: select amount of doors */
	
	$("#create-closet-amount ul li a").click(function(){
		// get amount
		var targetAmountOfDoors = $(this).attr('alt');
		// calculate width of doors
		values['DoorWidth'] = calculateDoorWidth(values['ClosetWidth'], targetAmountOfDoors, setting['profileWidth']);
		values['DoorHeight'] = calculateDoorHeight(values['ClosetHeight'], setting['profileWidth']);
		// hide intro text
		$('.block').hide();
		$('#closet').show();
		
		// display doors or edit them
		showDoors(targetAmountOfDoors, values['AmountOfDoors'], values['DoorWidth'], values['DoorHeight'], values['ClosetHeight']);
		// display next button
		$("#create-closet-next").fadeIn('slow');
		return false;
	});
	
	/* STEP 3: go to page two */
	
	$("#create-closet-next .submit input").click(function(){
		// display profile selections
		$("#create-closet-profile").show();
		// display material selections
		$("#create-closet-material").show();
		// slide setting box
		$('#create-closet-left #steps-wrapper').animate(
			{
				marginTop: '-400px'
			}, 
			{ 
				"duration": 600,
				queue: false,
				"easing": "easeOutBack",
				complete: init_page2Events()
			}
		);
		return false;
	});
}

function init_page2Events() {
	// show order button
	$('#orderButton').fadeIn('slow');
	// show decorative strips
	$('#decorative_strips').fadeIn('slow');
	// show doorTools
	showDoorTools(values['AmountOfDoors'], values['minDoorsAmount'], values['maxDoorsAmount']);
	// select first door
	values['SelectedDoorIndex'] = 0;
	// get material and materialgroup
	var material_id = Doors[values['SelectedDoorIndex']];
	var materialgroup_id = getMaterialgroupId(material_id);
	values['SelectedMaterialGroup'] = materialgroup_id;
	showMaterials(materialgroup_id);
	selectMaterial(material_id);
	
	// place arrow above first door
	showDoorSelector(values['DoorWidth'], values['SelectedDoorIndex'], setting['profileWidth']);
	
	/* STEP 4: select a profile */
	
	// show preview box
	//$('#create-closet-profile #displayProfilePhotos').fadeIn('fast');
	setTimeout("showPreviewPhoto()", 1000);
	
	// selecting a profile
	$("#create-closet-profile .radio input").click(function () {
		// get color_id
		values['ProfileColorId'] = $(this).attr("value");
		// get color code fron array
		values['ProfilesColorCode'] = profileColors[values['ProfileColorId']];
		// set new border color
		$('ul#closet li').css('borderColor', values['ProfilesColorCode']);
		
		showPreviewPhoto(webroot+'img/profiles/'+values['ProfileColorId']+'.jpg');
	});
	
	$("a.fancybox").fancybox();
	
	$("#create-closet-profile #displayPreviewPhotos .close").click(function () {
		$('#create-closet-profile #displayPreviewPhotos').fadeOut('fast');
		return false;
	});
	
	/* STEP 5: door actions */
    
    // delete or add one door
    $('ul#doorTools li a').click(function(){
    	if ($(this).attr('class') == 'active'){
	    	// get amount
	    	var tool_id = $(this).parents('li').attr('id');
	    	if (tool_id == 'delete-door'){
	    		// delete selected door
	    		values['AmountOfDoors']--;
	    		removeSelectedDoor(values['SelectedDoorIndex']);
	    		// update arrow
	    		if (values['SelectedDoorIndex'] == values['AmountOfDoors']){
	    			values['SelectedDoorIndex']--;
	    		}
	    		// select material
	    		var door_index = values['SelectedDoorIndex'];
	    		var material_id = Doors[door_index];
				var materialgroup_id = getMaterialgroupId(material_id);
				var doorWidth = values['DoorWidth'];
				if (values['SelectedMaterialGroup'] !== materialgroup_id) {
					values['SelectedMaterialGroup'] = materialgroup_id;
					showMaterials(materialgroup_id);
				}
				setTimeout("selectMaterial("+material_id+")", 500);
	    	}
	    	else{
	    		addDoor(values['AmountOfDoors'], values['DoorWidth'], values['DoorHeight'], values['ClosetHeight']);
	    		values['AmountOfDoors']++;
	    	}
	    	var doorWidth = calculateDoorWidth(values['ClosetWidth'], values['AmountOfDoors'], setting['profileWidth']);
	    	updateDoorWidths(doorWidth);
	    	values['DoorWidth'] = doorWidth;
	    	showDoorSelector(values['DoorWidth'], values['SelectedDoorIndex'], setting['profileWidth']);
	    	showDoorTools(values['AmountOfDoors'], values['minDoorsAmount'], values['maxDoorsAmount']);
		}
		return false;
    });
    
    
    // select door
    $("ul#closet li a").live("click", function(){
		var door_index = $("ul#closet li a").index(this);
		var material_id = Doors[door_index];
		var doorWidth = values['DoorWidth'];
		values['SelectedDoorIndex'] = door_index;
		var materialgroup_id = getMaterialgroupId(material_id);
		
		if (values['SelectedMaterialGroup'] !== materialgroup_id && materialgroup_id != null) {
			values['SelectedMaterialGroup'] = materialgroup_id;
			showMaterials(materialgroup_id);
		}
		setTimeout("selectMaterial("+material_id+")", 500);
		showDoorSelector(doorWidth, door_index, setting['profileWidth']);
		
		return false;
    });
    
    // select material
    $('ul.material-list li a').click(function(){
    	var material_id = getId($(this).attr('id'));
    	var door_index = values['SelectedDoorIndex'];
    	
    	if (Doors[door_index] != material_id) {
    		Doors[door_index] = material_id;
    		updateTotalPrice(Doors, values['ClosetWidth'], values['ClosetHeight']);
    		selectMaterial(material_id);
    		showDoorMaterial(door_index, material_id, values['DoorWidth'], values['DoorHeight']);
    	}
    	
    	return false;
    });
    
    // select material group
    $('ul.material-names li a').click(function(){
    	var materialgroup_id = getId($(this).attr('id'));
    	values['SelectedMaterialGroup'] = materialgroup_id;
    	showMaterials(materialgroup_id);
    	return false;
    });
    
    // insert decorative strips
    $('#decorative_strips input').keyup(function(){
    	var val = $(this).val();
    	var amount = 0;
    	if (val != ''){
	    	var amount = parseInt(val);
	    	if (isNaN(amount)){
	    		amount = 0;
	    	}
	    	$(this).val(amount);
	    }
	    values['DecorativeStrips'] = amount;
	    updateTotalPrice(Doors, values['ClosetWidth'], values['ClosetHeight'], values['DecorativeStrips']);
    });
    
    // order closet
    $('#orderButton a').click(function(){
    	var validate = true;
    	for (var i=0; i < Doors.length; i++) {
    		if (Doors[i] == null){
    			i = Doors.length;
    			validate = false;
    		}
    	};
    	if (validate == false) {
    		// set flash
			setFlash('U heeft nog niet bij elke deur een materiaal gekozen.');
			return false;
    	}
    	else{
    		return saveAndSubmit(Doors, values['ClosetHeight'], values['ClosetWidth'], values['DoorHeight'], values['DoorWidth'], values['AmountOfDoors'], values['ProfileColorId'], setting['profileWidth'], values['TotalPrice'], values['DecorativeStrips']);
    	}
    });
    
}


/* --------------- */
/* -- FUNCTIONS -- */
/* --------------- */

var previewPhotoTimer;
function hidePreviewPhoto() {
	clearTimeout(previewPhotoTimer);
	$('#create-closet-profile #displayPreviewPhotos').fadeOut('fast');
}
function showPreviewPhoto(img) {
	clearTimeout(previewPhotoTimer);
	if (img != undefined){
		// change pop-up profile photo
		$('#create-closet-profile #displayPreviewPhotos img').attr('src', ''+img);
	}
	// show preview box
	$('#create-closet-profile #displayPreviewPhotos').fadeIn('fast');
	previewPhotoTimer = setTimeout("hidePreviewPhoto()", 3000);
}


// calculate door amount
function calculateDoorAmounts(closetWidth, maxDoorWidth, minDoorWidth, maxDoorAmount, profileWidth) {
	var amount = new Array(2);
	// closet width min start profile
	closetWidth = closetWidth; // - profileWidth
	maxDoorWidth = maxDoorWidth; // + profileWidth
	minDoorWidth = minDoorWidth; // + profileWidth
	
	amount['max'] = Math.floor(closetWidth / minDoorWidth); // max amount of doors
	if (amount['max'] > maxDoorAmount) {
		amount['max'] = maxDoorAmount;
	}
	amount['min'] = Math.ceil(closetWidth / maxDoorWidth); // min amount of doors
	return amount;
}

function calculateDoorWidth(closetWidth, amount, profileWidth) {
	// closet width min start profile
	closetWidth = closetWidth - profileWidth - (amount * profileWidth);
	var doorWidth = Math.round(closetWidth / amount);
	return doorWidth;
}
function calculateDoorHeight(closetHeight, profileWidth) {
	var doorHeight = closetHeight - (2 * profileWidth);
	return doorHeight;
}
function calculateDecorativeStripsPrice(amount) {
	return parseFloat(amount * 22.50);
}

// display doors amount selection
function showSelectiondoors(cur, max) {
	if (cur <= max){
		$('#doorselection_'+cur).fadeIn(300);
		setTimeout("showSelectiondoors("+(cur+1)+", "+max+")", 500);
	}
}

// display selected doors
function showDoors(amount, currentAmount, doorWidth, doorHeight, closetHeight) {
	var i = 0;
	
	// doors to add
	if (amount > currentAmount){
		while (currentAmount < amount){
			setTimeout("addDoor("+currentAmount+", "+doorWidth+", "+doorHeight+", "+closetHeight+")", (0+(i*200)));
			currentAmount++;
			// update amount of doors.
			values['AmountOfDoors'] = currentAmount;
			i++;
		}
	}
	// doors to remove
	else{
		while (currentAmount > amount){
			removeLastDoor();
			currentAmount--;
			// update amount of doors.
			values['AmountOfDoors'] = currentAmount;
		}
	}
	
	// resize door widths
	updateDoorWidths(doorWidth);
}

// add a door
function addDoor(AmountOfDoors, doorWidth, doorHeight, closetHeight) {
	var door_index = AmountOfDoors;
	// add html
	$('ul#closet').append('<li><a><img src="'+webroot+'img/empty_door.jpg" height="'+doorHeight+'" width="'+doorWidth+'" /></a></li>');
	
	// set default material
	Doors[door_index] = null;
	// set styles
	$('ul#closet li:last').css({
		'height': doorHeight+'px',
		'width': doorWidth+'px',
		'z-index': (7-AmountOfDoors),
		'borderColor': values['ProfilesColorCode'],
		opacity: 0.0
	});
	$('ul#closet li a:last').css({
		'height': doorHeight+'px',
		'width': doorWidth+'px',
		'display': 'block',
		//'backgroundImage': 'url('+webroot+'img/materials/'+material_id+'.jpg)'
		'backgroundColor': '#ccc'
	});
	
	// animate displaying
	$('ul#closet li:last').animate(
		{
			marginLeft: '0px',
			opacity: 1.0
		}, 
		{ 
			"duration": 600,
			queue: false,
			"easing": "easeOutSine"
		}
	);
	
	// show price
	updateTotalPrice(Doors, values['ClosetWidth'], values['ClosetHeight']);
}

// remove a door
function removeLastDoor() {
	$('ul#closet li:last').remove();
	Doors.pop();
	// show price
	updateTotalPrice(Doors, values['ClosetWidth'], values['ClosetHeight']);
}
function removeSelectedDoor(door_index) {
	$('ul#closet li:eq('+door_index+')').remove();
	Doors.splice(door_index, 1);
	// show price
	updateTotalPrice(Doors, values['ClosetWidth'], values['ClosetHeight']);
}

function showDoorSelector(doorWidth, door_index, profileWidth) {
	var totalWidth = doorWidth+profileWidth;
	var arrowWidth = 18;
	var slideDistance = (door_index) * totalWidth + totalWidth/2 - arrowWidth/2 + 20 + profileWidth;
	$('#show-door-selected img').animate(
		{
			marginLeft: slideDistance+'px'
		}, 
		{ 
			"duration": 600,
			queue: false,
			"easing": "easeOutBack"
		}
	);
}

function showMaterials(materialgroup_id) {
	$('ul.material-names li a').removeClass('active');
	$('ul.material-list').hide();
	// set parent and sub group active
	var name = $('#materialnamegroup_'+materialgroup_id).attr('name');
	var ids = name.split("-");
	var parentmaterialgroup_id = ids[0];
	var childmaterialgroup_id = ids[1];
	// if the group has children
	$('#materialnamegroup_'+parentmaterialgroup_id).addClass('active');
	if (childmaterialgroup_id > 0){
		$('#childmaterialgroup_'+parentmaterialgroup_id).fadeIn('slow');
		$('#materialnamegroup_'+childmaterialgroup_id).addClass('active');
		materialgroup_id = childmaterialgroup_id;
	}
	else{
		$('.material-names.children').fadeOut('fast');
	}
	// show materials
	$('#materialgroup_'+materialgroup_id).fadeIn('slow');
	// show active material
}

function selectMaterial(material_id) {
	if (material_id != null){
		$('ul.material-list li a#material_'+material_id)
		.animate( { opacity: 0.5 }, { queue:false, duration:600 } )
		.animate( { opacity: 0.1 }, { duration:100, complete: function(){$('ul.material-list li a').removeClass('active'); $(this).addClass('active');} } )
		.animate( { opacity: 1.0 }, { duration:600 } );
	}
	else{
		$('ul.material-list li a').removeClass('active');
	}
}

// select materialgroup by material_id
function getMaterialgroupId(material_id) {
	if ($('#material_'+material_id).parents('ul').attr('id') != undefined){
		var materialgroup_ul_id = $('#material_'+material_id).parents('ul').attr('id');
		var materialgroup_ul_ids = materialgroup_ul_id.split("_");
		var materialgroup_id = materialgroup_ul_ids[1];
	}
	else{
		var materialgroup_id = 1;
	}
	return materialgroup_id;
}

function showDoorMaterial(door_index, material_id, doorWidth, doorHeight) {
	$("ul#closet li a").stop();
	// animate displaying
	$('ul#closet li a:eq('+door_index+')')
        .animate( { opacity: 0.1 }, { queue:true, duration:100, complete: function(){
        	//$('ul#closet li a:eq('+door_index+')').css('backgroundImage', 'url('+webroot+'img/materials/'+material_id+'.jpg)');
        	$('ul#closet li a:eq('+door_index+')').html('<img src="'+webroot+'img/materials/'+material_id+'.jpg" height="'+doorHeight+'", width="'+doorWidth+'" />');
    	} } )
        .animate( { opacity: 1.0 }, { queue:true, duration:300 } );
}

function showDoorTools(amountOfDoors, minDoorsAmount, maxDoorsAmount) {
	$('li#add-door a').removeClass('active');
	$('li#delete-door a').removeClass('active');
	
	if (amountOfDoors > minDoorsAmount){
		// activate delete-door
		$('li#delete-door a').addClass('active');
	}
	if (amountOfDoors < maxDoorsAmount){
		// activate add-door
		$('li#add-door a').addClass('active');
	}
}

function updateDoorWidths(doorWidth) {
	$('ul#closet li').animate(
		{
			width: doorWidth+"px"
		},
		{ 
			"duration": 800,
			queue: false,
			"easing": "easeOutBack"
		}
	);
	$('ul#closet li a img').animate(
		{
			width: doorWidth+"px"
		},
		{ 
			"duration": 800,
			queue: false,
			"easing": "easeOutBack"
		}
	);
	
	// prepare link widths
	$('ul#closet li a').css('width', doorWidth+'px');
}

function updateTotalPrice(Doors, closetWidth, closetHeight, decorativeStrips) {
	
	var price = new Number(0);
	for (var i=0; i < Doors.length; i++) {
		var material_id = Doors[i];
		if (material_id != null){
			var material_group_id = getMaterialgroupId(material_id);
			var name = $('#materialnamegroup_'+material_group_id).attr('name');
			var arMaterialGroup = name.split("-");
			var parent_material_group_id = arMaterialGroup[0];
			var groupprice = parseFloat(materialGroupPrices[parent_material_group_id]);
			price = price + parseFloat(materialGroupPrices[parent_material_group_id]);
		}
	};
	// decorative_strips
	var decorative_strips_price = calculateDecorativeStripsPrice(decorativeStrips);
	if (decorative_strips_price > 0){
		price = price + parseFloat(decorative_strips_price);
	}
	// discount
	if (closetHeight <= 140) {
		price = price/100*75;
	}
	price = price.toFixed(2);
	values['TotalPrice'] = price;
	price = price.replace(".", ",");
	$('#price').html("&euro; "+price);
}


function saveAndSubmit(Doors, ClosetHeight, ClosetWidth, DoorHeight, DoorWidth, AmountOfDoors, ProfileColorId, ProfileWidth, totalPrice, decorativeStrips) {
	var div = '#ajaxResult';
	var action = 'cart/add';
    
    $.post(
    	webroot+action, 
    	{
    		materials: Doors.toString(),
		    height: ClosetHeight,
		    width: ClosetWidth,
		    doorheight: DoorHeight,
		    doorwidth: DoorWidth,
		    door_amount: AmountOfDoors,
		    profile_id: ProfileColorId,
		    profilewidth: ProfileWidth,
		    totalprice: totalPrice,
		    decorativestrips: decorativeStrips
    	},
  		function(data, textStatus){
  			if (textStatus == 'success') {
  				//$(div).html(data+'<br /><br />'+textStatus);
  				location.href=webroot+'mijn_schuifdeuren';
  			}
  			else{
  				$(div).html('<p>Het is niet gelukt om uw kast op te slaan. Probeer het nog eens.</p>');
  			}
  		}
	);
	return false;
}

