var currentBacket = 1;
var totalBackets;
var isSwitching = false;
var isViewingProduct = false;
var isViewingNotepad = false;

$(document).ready(function()
{
	// Get count total backets
	totalBackets = $('.backets').length;

	// Move first backet to focus
	setTimeout("moveBacketToFocus("+currentBacket+", 'first')", 500);
	
	// Set click functions
	
	$('#btn_next').click(function(){
		if(!isSwitching && !isViewingProduct)
		{
			moveBacketToFocus(currentBacket+1, 'next');
		}
	});

	$('#btn_previous').click(function(){
		if(!isSwitching && !isViewingProduct)
		{
			moveBacketToFocus(currentBacket-1, 'previous');
		}
	});
	
	$('#btn_close').click(function()
	{
		hideDetailView();
	});
	
	// Update small notepad
	updateSmallNotepad();
	
	// Move next and previous buttons
	moveNextButton();
	movePreviousButton();
});

// Weight format

function weightFormat(textObj)
{
	var newValue = textObj.value;
	var decAmount = "";
  	var dolAmount = "";
   	var decFlag = false;
   	var aChar = "";
   
   	// ignore all but digits and decimal points.
   	for(i=0; i < newValue.length; i++) {
   	   	aChar = newValue.substring(i,i+1);
   	   	if(aChar >= "0" && aChar <= "9") {
   	    	if(decFlag) {
				decAmount = "" + decAmount + aChar;
			}
   	      	else {
   	      		dolAmount = "" + dolAmount + aChar;
   	      	}
   	   	}
   	   	if(aChar == ",") {
   	      	if(decFlag) {
   	         	dolAmount = "";
   	         	break;
   	      	}
   	    	decFlag=true;
   		}
   	}
   	
   	// Ensure that at least a zero appears for the dollar amount.

   	if(dolAmount == "") {
    	dolAmount = "0";
   	}
   	// Strip leading zeros.
   	if(dolAmount.length > 1) {
    	while(dolAmount.length > 1 && dolAmount.substring(0,1) == "0") {
       		dolAmount = dolAmount.substring(1,dolAmount.length);
    	}
   	}
   
   	// Round the decimal amount.
   	if(decAmount.length > 2) {
    	if(decAmount.substring(2,3) > "4") {
       		decAmount = parseInt(decAmount.substring(0,2)) + 1;
       		if(decAmount < 10) {
          		decAmount = "0" + decAmount;
       		}
       		else {
       			decAmount = "" + decAmount;
       		}
    	}
    	else {
       		decAmount = decAmount.substring(0,2);
    	}
    	if (decAmount == 100) {
       		decAmount = "00";
       		dolAmount = parseInt(dolAmount) + 1;
    	}
   	}
   
   	// Pad right side of decAmount
   	if(decAmount.length == 1) {
      	decAmount = decAmount + "0";
   	}
   	if(decAmount.length == 0) {
      	decAmount = decAmount + "00";
   	}
    
    // Check for negative values and reset textObj
   	textObj.value = dolAmount + "," + decAmount;
}


function updateSmallNotepad()
{
	$.ajax({ url: 'requests.php', data: {request: 'numberItemsCart'}, type: 'post', success: function(output)
	{
		$('#notepad_small span').html('<h4><a href="#" id="watch_notepad" onclick="showNotepad()">Bekijken</a></h4><h4 style="clear: left;"><a href="#" onclick="logout()">Uitloggen</a></h4>');
	
		if(output == 'not_logged_in')
		{
			$('#notepad_small p').html('U bent niet ingelogd. Klik <a href="#" onclick="login()">hier</a> om in te loggen.<br />Nog geen account? <a href="#" onclick="register()">Meld</a> u nu aan.');
			
			$('#notepad_small span').html('');
		}
		else if(output > 0)
		{
			$('#notepad_small p').html('U heeft '+output+' product(en) in uw winkelmand.');
		}
		else
		{
			$('#notepad_small p').html('U heeft geen producten in uw winkelmand.');
		}
    }});
}

function minProduct(klant_id, product_id)
{
	$.ajax({url: 'requests.php', data: {request: 'minProduct', artikelid: product_id, klantid: klant_id}, type: 'post', success: function(output)
	{
		if(output == 'success')
		{
			updateSmallNotepad();
			reloadNotepad();
		}
		else
		{
			alert(output);
		}
	}});
}

/*

function plusProduct(klant_id, product_id, _aantalkg)
{
	$.ajax({url: 'requests.php', data: {request: 'plusProduct', artikelid: product_id, klantid: klant_id, aantalkg: _aantalkg}, type: 'post', success: function(output)
	{
		if(output == 'success')
		{
			updateSmallNotepad();
			reloadNotepad();
		}
		else
		{
			alert(output);
		}
	}});
}

*/

function addProduct(_artikelid, _aantalkg)
{
	$('#btn_toevoegen_aan_winkelmand').val('Bezig met toevoegen');
	$('#btn_toevoegen_aan_winkelmand').attr('disabled', 'true');

	$.ajax({url: 'requests.php', data: {request: 'addProduct', artikelid: _artikelid, aantalkg: _aantalkg}, type: 'post', success: function(output)
	{
		if(output == 'success')
		{
			updateSmallNotepad();
			alert('U heeft '+ _aantalkg +' kg van dit artikel aan uw winkelmand toegevoegd.');
		}
		else
		{
			alert(output);
		}
		
		$('#btn_toevoegen_aan_winkelmand').removeAttr('disabled');
		$('#btn_toevoegen_aan_winkelmand').val('Toevoegen aan winkelmand');
		
	}});
}

function showNotepad()
{
	if(!isViewingNotepad)
	{
		isViewingNotepad = true;
		showLoader();
		
		reloadNotepad();
	}
}

function reloadNotepad()
{
	$('#notepad').load('notepad_request.php', function()
	{
		// Show black overlay
		$('#overlay').slideDown();
	
		hideLoader();
		$('#notepad').animate({top: '50%'}, 500);
		showCloseButton('#btn_close_notepad');
		
		$('#btn_close_notepad').click(function()
		{
			hideNotepad();
		});
	});
}

function hideNotepad()
{
	if(isViewingNotepad)
	{
		isViewingNotepad = false;
		
		// Hide black overlay
		$('#overlay').slideUp();
	
		$('#notepad').animate({top: '-100%'}, 500, function()
		{
			$('#notepad').html('');
		});
		
		hideCloseButton('#btn_close_notepad');
	}
}

function moveBacketToFocus(number, which)
{	
	isSwitching = true;

	if(which == 'next')
	{
		var newNumber = number-1;
		$('#backet'+newNumber).animate({top: '300px'}, 150, function(){ $('#backet'+newNumber).animate({left: '-150%'}, 500); });
		
	}
	
	if(which == 'previous')
	{
		var newNumber = number+1;
		$('#backet'+newNumber).animate({top: '300px'}, 150, function(){ $('#backet'+newNumber).animate({left: '150%'}, 500); });
	}
	
	
	$('#backet'+number).animate({left: '50%'}, 500, function(){ $('#backet'+number).animate({top: '330px'}, 150, function(){ isSwitching = false; }); });
	
	currentBacket = number;
	
	showNextButton();
	showPreviousButton();
}

function showNextButton()
{
	if(currentBacket+1 <= totalBackets)
	{
		$('#btn_next').show();
	}
	else
	{
		$('#btn_next').hide();
	}
}

function moveNextButton()
{
	$('#btn_next').animate({'margin-left': '340px'}, 1000, function()
	{
		$('#btn_next').animate({'margin-left': '310px'}, 1000, function()
		{
			moveNextButton();
		});
	});
}

function showPreviousButton()
{
	if(currentBacket-1 > 0)
	{
		$('#btn_previous').show();
	}
	else
	{
		$('#btn_previous').hide();
	}
}

function movePreviousButton()
{
	$('#btn_previous').animate({'margin-left': '-370px'}, 1000, function()
	{
		$('#btn_previous').animate({'margin-left': '-340px'}, 1000, function()
		{
			movePreviousButton();
		});
	});
}

function showDetailView(product_id)
{
	if(!isViewingProduct && !isViewingNotepad)
	{
		isViewingProduct = true;
		showLoader();
	
		$('#container #product_view .content #product_container').load('product_request.php?id='+product_id, function(){
		
			hideLoader();
		
			$('#container #product_view .content').animate({height: '380px'}, 500);
			showCloseButton('#container #product_view #btn_close');
		
		});
	}
}

function hideDetailView()
{
	if(isViewingProduct && !isViewingNotepad)
	{
		isViewingProduct = false;

		$('#container #product_view .content').animate({height: '0'}, 500, function(){
		
			$('#container #product_view .content #product_container').html('');
		
		});
	
		hideCloseButton('#container #product_view #btn_close');
	}
}

function showCloseButton(id)
{
	$(id).fadeIn(500);
}

function hideCloseButton(id)
{
	$(id).fadeOut(500);
}

function showLoader()
{
	$('#loader').show();
}

function hideLoader()
{
	$('#loader').hide();
}

function checkOrder(_transactionid)
{
	if(!isViewingNotepad)
	{
		isViewingNotepad = true;
		showLoader();
		
		$.ajax({url: 'requests.php', data: {request: 'checkOrder', transactionid: _transactionid}, type: 'post', success: function(output)
		{
			// Show black overlay
			$('#overlay').slideDown();
		
			$('#notepad').html(output);
				
			hideLoader();
			$('#notepad').animate({top: '50%'}, 500);
			
			showCloseButton('#btn_close_notepad');
	
			$('#btn_close_notepad').click(function()
			{
				hideNotepad();
			});
		}});
	}
}

function login()
{
	if(!isViewingProduct)
	{		
		isViewingProduct = true;
		showLoader();
	
		$.ajax({url: 'requests.php', data: {request: 'getLogin'}, type: 'post', success: function(output)
		{
			$('#container #product_view .content #product_container').html(output);
			hideLoader();
			
			$('#container #product_view .content').animate({height: '200px'}, 500);
			showCloseButton('#container #product_view #btn_close');
		}});
	}
}

function trim(value)
{
  value = value.replace(/^\s+/,'');
  value = value.replace(/\s+$/,'');
  
  return value;
}

function submitLogin(_gebruikersnaam, _wachtwoord)
{
	if(trim(_gebruikersnaam) == '')
	{
		alert('U heeft geen gebruikersnaam ingevoerd.');
	}
	else if(trim(_wachtwoord) == '')
	{
		alert('U heeft geen wachtwoord ingevoerd.');
	}
	else
	{
		$('#btn_login').val('Bezig met inloggen..');
		$('#btn_login').attr('disabled', 'true');
	
		$.ajax({url: 'requests.php', data: {request: 'submitLogin', gebruikersnaam: _gebruikersnaam, wachtwoord: _wachtwoord}, type: 'post', success: function(output)
		{
			if(output == 'success')
			{
				$('#btn_login').val('Ingelogd');
			
				alert('U bent succesvol ingelogd.');
				updateSmallNotepad();
				hideDetailView();
			}
			else
			{
				$('#btn_login').val('Log in!');
			
				alert(output);
			}
			
			$('#btn_login').removeAttr('disabled');
		}});
	}
}

function logout()
{
	showLoader();
	
	$.ajax({url: 'requests.php', data: {request: 'logout'}, type: 'post', success: function(output)
	{
		hideLoader();
		
		updateSmallNotepad();
	
		if(output == 'success')
		{
			alert('U bent succesvol uitgelogd.');
		}
		else
		{
			alert(output);
		}
	}});
}

function register()
{
	if(!isViewingProduct)
	{
		isViewingProduct = true;
		showLoader();
	
		$.ajax({url: 'requests.php', data: {request: 'getRegister'}, type: 'post', success: function(output)
		{
			hideLoader();
			
			if(output == 'fail')
			{
				alert('U bent al ingelogd, aanmelden is dan niet mogelijk.');
			}
			else
			{
				$('#container #product_view .content #product_container').html(output);
			}
			
			$('#container #product_view .content').animate({height: '475px'}, 500);
			showCloseButton('#container #product_view #btn_close');
		}});
	}
}

function submitRegister(_gebruikersnaam, _wachtwoord, _bedrijfsnaam, _aanhef, _voornaam, _tussenvoegsel, _achternaam, _adres, _postcode, _woonplaats, _telnummer, _email)
{
	var properties = {gebruikersnaam: _gebruikersnaam, wachtwoord: _wachtwoord, bedrijfsnaam: _bedrijfsnaam, aanhef: _aanhef, voornaam: _voornaam, tussenvoegsel: _tussenvoegsel, achternaam: _achternaam, adres: _adres, postcode: _postcode, woonplaats: _woonplaats, telnummer: _telnummer, email: _email};
	
	var legeVelden = 0;
	var naamLegeVelden = '';
	
	$.each(properties, function(key, value)
	{
		if(key != 'aanhef' && key != 'tussenvoegsel' && value == '')
		{
			if(legeVelden == 0)
			{
				naamLegeVelden = key;
			}
			else
			{
				naamLegeVelden = naamLegeVelden+', '+key;
			}
		
			legeVelden += 1;
		}
	});
	
	if(legeVelden > 0)
	{
		if(legeVelden == 1)
		{
			alert('U bent het veld '+naamLegeVelden+' vergeten in te vullen.');
		}
		else
		{
			alert('U bent de velden '+naamLegeVelden+' vergeten in te vullen.');
		}
	}
	else
	{	
		$.ajax({url: 'requests.php', data: {request: 'submitRegister', data: properties}, type: 'post', success: function(output)
		{
			if(output == 'success')
			{
				alert('U bent succesvol aangemeld, er is een e-mail naar u verstuurd waarin staat hoe u uw account kan activeren..');
				hideDetailView();
			}
			else
			{
				alert(output);
			}
		}});
	}
	
}

function activateUser(_gebruikersnaam, _sleutel)
{
	if(!isViewingProduct)
	{		
		isViewingProduct = true;
		showLoader();
	
		$.ajax({url: 'requests.php', data: {request: 'activateUser', gebruikersnaam: _gebruikersnaam, sleutel: _sleutel}, type: 'post', success: function(output)
		{
			$('#container #product_view .content #product_container').html(output);
			hideLoader();
			
			$('#container #product_view .content').animate({height: '200px'}, 500);
			showCloseButton('#container #product_view #btn_close');
		}});
	}
}
