/*
 * JQuery document ready
 */
$(document).ready(function(){

    $('a.productOrder').html('');
    $('form.shoppingcart .button').html('');
    $('input.toRegistration').val('');
    $('input.toConfirm').val('');
    $('input.toOrder').val('');

	if ($('.headercontent').length > 1)
	{
		$('#headercycler').addClass('cyclerstyles');

		$('#headercycler').cycle(
		{
			timeout: 5000, // milliseconds between slide transitions (0 to disable auto advance)
			speed: 2000, // speed of the transition (any valid fx speed value)
			next: null, // id of element to use as click trigger for next slide
			prev: null, // id of element to use as click trigger for previous slide
			before: null, // transition callback (scope set to element to be shown)
			after: null, // transition callback (scope set to element that was shown)
			height: 'auto', // container height
			sync: 1, // true if in/out transitions should occur simultaneously
			fit: 0, // force slides to fit container
			pause: 0, // true to enable "pause on hover"
			delay: 0, // additional delay (in ms) for first transition (hint: can be negative)
			slideExpr: null // expression for selecting slides (if something other than all children is required)
		});
	}

	// Add a lightbox for some pictures
	$('.lightbox')
		.lightBox({
			imageLoading:	'/gfx/lightbox-ico-loading.gif',
			imageBtnClose :	'/gfx/lightbox-btn-close.gif',
			imageBtnPrev:	'/gfx/lightbox-btn-prev.gif',
			imageBtnNext:	'/gfx/lightbox-btn-next.gif',
			imageBlank :	'/gfx/lightbox-blank.gif'
		})
		.click(function(){
			$('#lightbox-container-image-data-box').addClass('no_box_sizing');
		});

	// Show video's in a colorbox
	$('a.video').addClass('cboxelement').colorbox({
		width:			'720px',
		height:			'408px',
		iframe:			true,
		opacity:		0.5
	});

	// Show 360 tour in a colorbox
	$('img.tour').each(function(){

		// Set some vars
		var sTour 		= $(this).attr('alt').replace(' ','').toLowerCase();
		var sTitle		= $(this).attr('title');
		var sStyle 		= $(this).attr('style');
		var $parent 	= $(this).parent();

		// Remove the img style, gets added to container
		$(this).removeAttr('style');

		// Create the container, append the image
		$dummy = $('<div />')
					.attr('style', sStyle)
					.css('text-align', 'center')
					.append($(this));

		// Inject the container
		$parent.prepend($dummy);

		// Add a link and click function to the image
		$(this)
			.after('<br /><a href="/tour/'+sTour+'/tourviewer_'+sTour+'.html" class="tour" title="'+sTitle+'" rel="">360&deg; film van onze winkel</a>')
			.click(function(){
				$(this).siblings('a.tour').click();
			})
			.css('cursor', 'pointer');

		// Add the colorbox
		$(this).siblings('a.tour').addClass('cboxelement').colorbox({
			width:			'545px',
			height:			'550px',
			iframe:			true,
			opacity:		0.5
		});

	});

	$("form.shoppingcart td.amount input").keyup(function()
	{
		var $input = $(this);
		$input.val($input.val().replace(/\D/g , ''));

		if ($input.val() == '')
		{
			return false;
		}
		else if ($input.val() == 0)
	    {
	        var $tr = $(this).parent().parent();
    		removeItem($tr);
	    }

		var aProduct =  $input.parents('tr:first').attr('id').replace('prod_','').split('_');

		$.getJSON(
			"/ajax/changeCart.php",
			{
				action:			'changeAmount',
				product_id: 	aProduct.shift(),
				amount:			$input.val(),
				price_id:       aProduct.pop()
			},
			function(json)
			{
				changeShoppingCartContent(json);
			}
		);
	});

	$("form.shoppingcart tbody td.remove").click(function()
	{
		$tr = $(this).parent();

		removeItem($tr);
	});

	function removeItem($tr)
	{
		var aProduct = $tr.attr('id').replace('prod_','').split('_');

	    $.getJSON(
			"/ajax/changeCart.php",
			{
				action:			'removeProduct',
				product_id: 	aProduct.shift(),
				price_id: 	    aProduct.pop()
			},
			function(json)
			{
				$tr.fadeOut('slow', function()
				{
					$tr.remove();
				});
				changeShoppingCartContent(json);
			}
		);
	}

	$("form[action$='/winkelwagen/naarBetalen']").submit(function()
	{
        if (!$("input[name$='conditions']").is(':checked'))
        {
            $("p.conditions").css('color', '#B44746');
            $("p.conditions").css('padding', '0.5em');
            $("p.conditions").css('border', '2px solid #B44746');
            return false;
        }
        else
        {
            return true;
        }
	});

	__tomorow = new Date();
	__tomorow.setDate(__tomorow.getDate()+1);
	if ($(".datepicker").length > 0)
	{
		__disabledDays =  new getDisabledDays()

		$(".datepicker").datepicker(
		{

			regional:			'nl',
			firstDay:			1,
			minDate:			__tomorow,
			maxDate:            '+1y',
			beforeShowDay:  	noSundayOrHolidays,
			showAnim:			'fadeIn'
		});
	}

    var bSubmit = false;

    var tableInloggen = $('table.registration:first');
    var tableRegistration = $('table.registration:nth(1)');

    $("form[name$='shoppingcartInloggen']").validate();
    $("form[name$='shoppingcartRegistration']").validate();

	$("form[name$='registrationButtons']").submit(function(e)
	{
        e.preventDefault();
	    if (winkelwagenRegToggle == 'inloggen' || winkelwagenRegToggle == 'onthouden')
	    {
	        $("form[name$='shoppingcartInloggen']").submit();
	    }
	    else
        {
            $("form[name$='shoppingcartRegistration']").submit();
        }
	});

	$("form[name$='shoppingcartInloggen']").submit(function(e) {
	    if (bSubmit)
	    {
	        return true;
	    }
	    else
        {
            e.preventDefault();
        }

	    var sEmail  = $(this).find('input:nth(1)').val();
    	var sPassword = $(this).find('input:nth(2)').val();

	    if ($(this).valid())
	    {
	        $.getJSON(
                '/ajax/findshopUser.php',
                {
                    action: 'findCustomer',
                    email:  sEmail,
                    password: sPassword
                },
                function(json)
                {
                    if (typeof(json.error) == 'string')
                    {
                        $('div.inloggen').find('p:nth(1)').html('<label for="inloggenPassword">Mijn wachtwoord</label><em>*</em><input id="inloggenPassword" class="required error" name="findCustomer[wachtwoord]" value="" type="password"><label class="error" generated="true" for="inloggenPassword">Uw gegevens konden niet gevonden worden.</label>');
                        return false;
                    }
                    else
                    {
                        $("input[name$='customer[number]']").val(json.id);
                        bSubmit = true;
                        $("form[action$='/winkelwagen/naarControle']").submit();
                    }
                }
            );
	    }
	    else
	    {
	        return false;
	    }
	});

    if (winkelwagenRegToggle == null)
    {
        if ($('div.inloggen').css('display') == 'block')
        {
            var winkelwagenRegToggle = 'inloggen';
        }
        else
        {
            var winkelwagenRegToggle = 'registreren';
        }

        if ($('input#inloggenEmail').attr('type') == 'hidden')
        {
            winkelwagenRegToggle = 'onthouden';
        }
    }

    var divInloggen = $('div.inloggen');
    var divRegistration = $('div.registration');
    var nieuweKlant = $('a#nieuweKlant');
    var spanToggle = $('span#toggle');
    var inputNewCustomer = $('input#newCustomer');

    $('a#nieuweKlant').toggle(function() {
        divInloggen.slideUp('slow');
        divRegistration.slideDown('slow');
        nieuweKlant.html('Ik was al eens klant');
        spanToggle.html('(inlogformulier schuift open)');
        inputNewCustomer.val('true');
        winkelwagenRegToggle = 'registreren';
    }, function() {
        divInloggen.slideDown('slow');
        divRegistration.slideUp('slow');
        nieuweKlant.html('Ik ben een nieuwe klant');
        spanToggle.html('(registratieformulier schuift open)');
        inputNewCustomer.val('false');
        winkelwagenRegToggle = 'inloggen';
    });

    if ($('div.inloggen').css('display') != 'block')
    {
        $('a#nieuweKlant').trigger('click');
    }

    /* Gegevens aanpassing in 'controle' */

    $('table.registration').find('a#editCustomer').click(function(e){
        e.preventDefault();
        var table = $('table.registration');
        table.find('span').css('display', 'none');
        table.find('input').css('display', 'inline');
        table.find('em').css('display', 'inline');
        table.find('a').css('display', 'inline');
        $(this).css('display', 'none');
    });

    $('table.registration').find('a#saveCustomer').click(function(e){
        e.preventDefault();

        var table = $('table.registration');

        if (validateUserForm(table))
        {
            $.post(
    			"/ajax/saveshopUser.php",
    			{
    				action:			'saveshopUser',
    				name: 	        table.find('input[name *= \'name\']').val(),
    				address: 	    table.find('input[name *= \'address\']').val(),
    				zipcode: 	    table.find('input[name *= \'zipcode\']').val(),
    				city: 	        table.find('input[name *= \'city\']').val(),
    				telephone: 	    table.find('input[name *= \'telephone\']').val()
    			},
    			function(json)
    			{
                    if (json == 'success')
                    {
                        $('#customerName').html(table.find('input[name *= \'name\']').val());
                        $('#customerAddress').html(table.find('input[name *= \'address\']').val());
                        $('#customerZipcode').html(table.find('input[name *= \'zipcode\']').val());
                        $('#customerCity').html(table.find('input[name *= \'city\']').val());
                        $('#customerTelephone').html(table.find('input[name *= \'telephone\']').val());

                        table.find('a').css('display', 'none');
                        $('a#editCustomer').css('display', 'inline');
                        table.find('span').css('display', 'inline');
                        table.find('input').css('display', 'none');
                        table.find('em').css('display', 'none');
                    }
                    else
                    {
                        alert('Opslaan mislukt! Uw sessie is incorrect of verlopen.');
                    }
    			},
    			"json"
    	    );
	    }
    });

    $('table.registration').find('a#cancelCustomer').click(function(e){
        e.preventDefault();
        var table = $('table.registration');
        table.find('a').css('display', 'none');
        $('a#editCustomer').css('display', 'inline');
        table.find('span').css('display', 'inline');
        table.find('input').css('display', 'none');
        table.find('em').css('display', 'none');
    });

    $("a[rel^='prettyPhoto']").prettyPhoto();

    $('p.submit a').click(function(e) {
        e.preventDefault();
        $('p#busy').show();
        $('#ideal').submit();
    });

    $('input#inloggenDeliverydate').change(function(e) {
        $('input#registrationDeliverydate').val($(this).val());
    });

    $('input#registrationDeliverydate').change(function(e) {
        $('input#inloggenDeliverydate').val($(this).val());
    });

    $('p#sendPassword a').click(function(e) {
        e.preventDefault();

        var email = $('input#inloggenEmail').val();

        if (email.length > 0)
        {
            $.post(
    			"/ajax/mailPassword.php",
    			{
    				email: 	    email
    			},
    			function(json)
    			{
                    if (json == 'success')
                    {
                        $('p#sendPassword a').css('display', 'none');
                        $('p#sendPassword span:nth(1)').html('');
                        $('p#sendPassword span:first').html('<br />Er is een nieuw wachtwoord verstuurd naar: ' + email);
                    }
                    else if (json == 'mailing failed')
                    {
                        $('p#sendPassword span:nth(1)').html('<br />Het versturen van een e-mail naar ' + email + ' is niet gelukt.');
                    }
                    else
                    {
                        $('p#sendPassword span:nth(1)').html('<br />Er is geen gebruiker met het e-mailadres: ' + email);
                    }
    			},
    			"json"
    	    );
        }
        else
        {
            $('div.inloggen').find('p:first').html('<label for="inloggenEmail">Mijn e-mailadres</label><em>*</em><input id="inloggenEmail" class="required email error" name="findCustomer[email]" value="" type="text"><label class="error" generated="true" for="inloggenEmail">Dit is een verplicht veld.</label>');
        }
    });
});

function validateUserForm(table)
{
    var bError = false;

    var nameTh = table.find('input[name *= \'name\']').parent().parent().find('th:first');
    var addressTh = table.find('input[name *= \'address\']').parent().parent().find('th:first');
    var zipcodeTh = table.find('input[name *= \'zipcode\']').parent().parent().find('th:first');
    var cityTh = table.find('input[name *= \'city\']').parent().parent().find('th:first');
    var telephoneTh = table.find('input[name *= \'telephone\']').parent().parent().find('th:first');
    var emailTh = table.find('input[name *= \'email\']').parent().parent().find('th:first');

    if (table.find('input[name *= \'name\']').val().length === 0)
    {
        nameTh.css('color', '#B44746');
        bError = true;
    }
    else
    {
        nameTh.css('color', '');
    }

    if (table.find('input[name *= \'address\']').val().length === 0)
    {
        addressTh.css('color', '#B44746');
        bError = true;
    }
    else
    {
        addressTh.css('color', '');
    }

    if (table.find('input[name *= \'zipcode\']').val().length === 0)
    {
        zipcodeTh.css('color', '#B44746');
        bError = true;
    }
    else if (table.find('input[name *= \'zipcode\']').val().length > 7)
    {
        zipcodeTh.css('color', '#B44746');
        bError = true;
    }
    else
    {
        zipcodeTh.css('color', '');
    }

    if (table.find('input[name *= \'city\']').val().length === 0)
    {
        cityTh.css('color', '#B44746');
        bError = true;
    }
    else
    {
        cityTh.css('color', '');
    }

    if (table.find('input[name *= \'telephone\']').val().length === 0)
    {
        telephoneTh.css('color', '#B44746');
        bError = true;
    }
    else
    {
        telephoneTh.css('color', '');
    }

    if (bError)
    {
        return false;
    }
    else
    {
        return true;
    }
}

function changeShoppingCartContent(json)
{
	if (typeof(json) != 'object')
	{
		return false;
	}

	for (var i in json.cart)
	{
		var oProduct = json.cart[i];

		if (typeof(oProduct.id) == 'undefined')
		{
			for (var priceId in oProduct)
			{
				var oPrice = oProduct[priceId];

				var $tr = $('form.shoppingcart tr#prod_' + oPrice.id + '_' + priceId);
				$tr.children('td:nth(2)').html('&euro; ' + oPrice.price_local);
				$tr.children('td:nth(3)').html('&euro; ' + oPrice.price_total_local);
			}
		}
		else
		{
			var $tr = $('form.shoppingcart tr#prod_' + oProduct.id);
			$tr.children('td:nth(2)').html('&euro; ' + oProduct.price);
			$tr.children('td:nth(3)').html('&euro; ' + oProduct.price_total);
		}
	}

	var $totals = $('form.shoppingcart table.totals tbody');

    if (json.totals == null)
    {
        $('table.contents tbody').html('<tr><td colspan="4">Uw winkelwagen is leeg</td></tr>');
        $('table.totals').hide('slow');
        $('input.toRegistration').hide('slow');
        $('li.shoppingcartmenu').hide('slow');
    }
    else
    {
    	$totals.children('tr:nth(0)').children(':last').html('&euro; ' + json.totals.total_inc_tax);
    	$totals.children('tr:nth(1)').children(':last').html('&euro; ' + json.totals.tax);
    	$totals.children('tr:nth(2)').children(':last').html('&euro; ' + json.totals.total_ex_tax);

    	/* change totals in shopping cart button (in navigation) */
    	var $cartBtn = $('#carttotals');
    	if (json.totals.amount === 1)
    	{
    	    $cartBtn.html('<span style="font-size: 0.85em">1 product - &euro; ' + json.totals.total_inc_tax + '</span>');
    	}
    	else
        {
            $cartBtn.html('<span style="font-size: 0.85em">' + json.totals.amount + ' producten: &euro; ' + json.totals.total_inc_tax + '</span>');
        }
    }
}

/* create an array of days which need to be disabled */
getDisabledDays = function ()
{
	var self = this;
	this.days = [];

	this.fetchDays = function()
	{
		$.getJSON(
			'/ajax/getHolidays.php',
			function(dates)
			{
				self.days = dates;
			}
		);
	}

	if (typeof(this.daysFetched) == 'undefined')
	{
		this.fetchDays();
		return false;
	}
	return this.days;
}


/* utility functions */
function nationalDays(date) {
	disabledDays = __disabledDays.days;

	var d = date.getDate(), m = date.getMonth(), y = date.getFullYear();
	//console.log('Checking (raw): ' + d + '-' + m + '-' + y);

	/* remember, day and month is a single value so 3 instead of 03 */

	for (i = 0; i < disabledDays.length; i++) {
		if($.inArray(y + '-' + (m+1) + '-' + d, disabledDays) != -1 || new Date() > date) {
			//console.log('bad:  ' + y + '-' + (m+1) + '-' + d + ' / ' + disabledDays[i]);
			return [false,'nope'];
		}
	}
	//console.log('good:  ' + y + '-' + (m+1) + '-' + d);
	return [true,''];
}

function noSundayOrHolidays(date) {
	var noSunday = true;

	if (date.getDay() == 0)
	{
		return false;
	}

	return noSunday ? nationalDays(date) : [noSunday ,''];
}
