$(function(){
    /* Fix height */
    $('#fix-height').height($('#column3').height() - $('#categoryListHolder').height());
    if($('#column2').height() > $('#column3').height()){
        $('#fix-height').height( $('#column2').height() - $('#categoryListHolder').height());
    }

    /* Product images */
    $(".productImages a").fancybox({
        'speedIn'   :	600,
        'speedOut'  :	200,
        'titleShow' : 	false
    });

    $(".productImages a").each(function(i){
        if(i >0){
            $(this).hide();
        }
    });

    /* Message dialogs */
    $('.message').dialog({
            draggable: false,
            width: 350,
            modal: true,
            resizable: false
    });

    /* View cart button */
    $('#column3 a:last').replaceWith('<input type="button" onclick="document.location=\'' + $('#column3 a:last').attr('href') + '\'" value="' + $('#column3 a:last').text() + '" name="btnShowCart" />');

    /* Category menu */
    $('#categoryListHolder > ul > li > a').each(function(){
        /* Add info marker */
        $(this).before('<div class="info" title="Meer informatie" onclick="goTo(\'' + $('base').attr('href') + 'service/' + $(this).text().toLowerCase() + '.html \')"></div>');
        /* Display sub menu */
        $(this).click(function(e){
            e.preventDefault();
            var $this = $(this);
            $active =  $('#categoryListHolder ul li a.active');
            $active.removeClass('active');

            $this.addClass('active');
            $('#categoryListHolder ul li ul').slideUp();
            $this.parent().find('ul').slideDown();
        });
    });

    /* Enable active option */
    $('#categoryListHolder > ul > li > ul > li.active').parent().css('display','block');

    /* Product propertys */
    $('.productPropertys select, .productInfoShort select').selectmenu(selectmenu_options);



    $('.productDescription img').wrap(function(){
       return '<a href="'+ $(this).attr('src') +'" title="'+ $(this).attr('alt') +'" class="fancybox-link"/>';
    });

    $(".productImages a, .fancybox-link").fancybox({
            'speedIn'		:	600,
            'speedOut'		:	200,
            'titleShow'		: 	false
    });

    $('.toTop').click(function(event){
        event.preventDefault();
        $('html, body').animate({scrollTop:0}, 0);
    });
});


var selectmenu_options = {
    style:'dropdown',
    change: function(){
        prod_data = $(this).attr('class');
        prod_data = prod_data.replace(' ', '');
        prod_data = prod_data.replace('first', '');
        prod_id = prod_data.replace('product_info_', '');
        updateProductInstance($(this), product_info[prod_id]);
    }
}


/**
 * Go to a given URI
 * @param {string} uri
 */
function goTo(uri){
	document.location = uri;
}

var selected_options = {};
function updateProductInstance($obj, data){
    $(".productButtons button").attr("disabled", "disabled");
    $('.itemCode, .itemPrice').css({'display': 'none'});
    $('.itemPrice-from').css({'display' : 'block'});

    // select values of the selected option
    sel_prop  = $obj.attr('name').substring(12, ($obj.attr('name').length - 1) );
    sel_value = $obj.val();

    if(sel_value !== ''){
        selected_options[sel_prop] = sel_value;
    }
    else{
        delete selected_options[sel_prop];
    }

    // get the next select
    $next_select = $obj.parent().find('select[name="' + $obj.attr('name') + '"] ~ select:eq(0)');
    if(sel_value === ''){
        // get the next select property id
        next_property = $next_select.attr('name').substring(12, ($next_select.attr('name').length - 1) );

        // clear the nex select
        $next_select.val('').selectmenu(selectmenu_options);
        if(typeof selected_options[next_property] !== 'undefined'){
            delete selected_options[next_property];
        }

        // disable all further selects
        $obj.parent().find('select[name="' + $obj.attr('name') + '"] ~ select:gt(0)').each(function(){
            // remove the option from selected items
            prop_id = $(this).attr('name').substring(12, ($(this).attr('name').length - 1) );

            if(typeof selected_options[prop_id] !== 'undefined'){
                delete selected_options[prop_id];
            }

            $(this).find('option:gt(0)').remove();
            $(this).val('')
                .attr('disabled','disabled')
                .selectmenu('destroy')
                .selectmenu(selectmenu_options);
        });

        $next_select.attr('disabled', 'disabled');
        $next_select.selectmenu('destroy').selectmenu(selectmenu_options);
    }
    else if($next_select.length !== 0){
        // get the next select property id
        next_property = $next_select.attr('name').substring(12, ($next_select.attr('name').length - 1) );

        // clear the nex select
        $next_select.val('').selectmenu(selectmenu_options);
        if(typeof selected_options[next_property] !== 'undefined'){
            delete selected_options[next_property];
        }

        // disable all further selects
        $obj.parent().find('select[name="' + $obj.attr('name') + '"] ~ select:gt(0)').each(function(){
            // remove the option from selected items
            prop_id = $(this).attr('name').substring(12, ($(this).attr('name').length - 1) );

            if(typeof selected_options[prop_id] !== 'undefined'){
                delete selected_options[prop_id];
            }

            $(this).find('option:gt(0)').remove();
            $(this).val('')
                .attr('disabled','disabled')
                .selectmenu('destroy')
                .selectmenu(selectmenu_options);
        });

        // remove all options of this select except the first (label)
        $next_select.find('option:gt(0)').remove();

        // fill the next select with values
        for(prodinst_id in data['productInstances']){
            for(property_id in data['productInstances'][prodinst_id]['property']){
                value_id = data['productInstances'][prodinst_id]['property'][property_id];
                if(typeof selected_options[property_id] !== 'undefined'){
                    if(selected_options[property_id] != value_id){
                        break;
                    }
                }

                if(property_id == next_property && $next_select.find('option[value="' + value_id + '"]').length === 0){
                    $option = $('<option value="' + value_id + '">' + data['propertyValues'][property_id][value_id] + '</option>');
                    $next_select.append($option);
                    break;
                }
            }
        }
        $next_select.attr('disabled', '');
        $next_select.selectmenu('destroy').selectmenu(selectmenu_options);
    }
    else{
         for(prodinst_id in data['productInstances']){
            for(property_id in data['productInstances'][prodinst_id]['property']){
                break_me = true;
                value_id = data['productInstances'][prodinst_id]['property'][property_id];
                if(typeof selected_options[property_id] === "undefined" || selected_options[property_id] != value_id){
                    break_me = true;
                    break;
                }
                break_me = false;
            }
            if(break_me === false){
                the_product = prodinst_id;
                break;
            }
        }

        data['current_instance'] = the_product;

        // update the price
        costs = formatPrice(data['productInstances'][the_product]['price']);

        price = currency_symbol + ' ' + roundVal(costs, 2).toString().replace('.', decimal_ceperator);

        if(typeof data['productInstances'][the_product]['discount_price'] != 'undefined'){
            price = '<span class="product-discount-price">' + price + '</span> ' + currency_symbol + ' ' + roundVal(data['productInstances'][the_product]['discount_price'], 2).toString().replace('.', decimal_ceperator);
        }

        // update product code
        if(typeof data['productInstances'][the_product]['code'] != 'undefined'){
            $('.itemCode').text(data['productInstances'][the_product]['code']);
        }

        $obj.parent().find('.itemPrice').text(currency_symbol + ' ' + roundVal(costs, 2).toString().replace('.', decimal_ceperator));

        // we are the last select so enable the buttons if I'm set!
        $(".productButtons button").attr("disabled", "");
        // display price & product code
        $('.itemCode, .itemPrice').css({'display' : 'block'});
        $('.itemPrice-from').css({'display' : 'none'});
    }
}

function addProductToCart(continuShopping, data){
        // check if we have only one product instance to add
        if(typeof data['current_instance'] === 'undefined' || data['current_instance'] === null){
            data['current_instance'] = product_info[data['product_id']]['instance_id'];
        }

	$('body').append('<form name="frmAddToCart" id="frmAddToCart" method="post" action="">'+
                            '<input type="hidden" name="action"             value="addToCart" />'+
                            '<input type="hidden" name="continuShopping"    value="'+continuShopping+'" />'+
                            '<input type="hidden" name="product_id"         value="'+data['product_id']+'" />'+
                            '<input type="hidden" name="instance_id"        value="'+data['current_instance']+'" />'+
                        '</form>');

	$('#frmAddToCart').submit();
}

function formatPrice(price){
	// strip price indicator
	costs =  price.replace(thousands_sep,'').replace(decimal_ceperator, '.').replace(currency_symbol, '').replace(' ','');
	// transform value to float
	costs = parseFloat(costs);
	// return the price string
	return costs;
}

function updateCartRow(edt){
	var row 	= $(edt).parent().parent();
	var val 	= $(edt).val();

	costs = formatPrice($(row).find('.rowCosts').text());
	$(row).find('.rowTotal').text(currency_symbol + ' ' + roundVal((val * costs),2).toString().replace('.',decimal_ceperator));

	updateCartTotal();
}

function updateCartTotal(){
	var amount = 0;
	var totalprice = 0;

	// for each cartRow
	$('.cartRow').each(function(){
		amount_tmp = parseFloat($(this).find('.amount').val());
		costs = $(this).find('.rowTotal').text();
		costs =  parseFloat(costs.substr(2).replace(' ',''));
		// add amount
		amount += amount_tmp;
		// add totalprice
		totalprice += costs;
	});

	total_ex = totalprice;
	total_inc =	total_ex * 1.19;
	btw = total_inc - total_ex;

	// update subtotal_ex
	$('.subtotal_ex .total').text(amount);
	$('.subtotal_ex .price').text(currency_symbol + ' ' + roundVal(total_ex,2).toString().replace('.',decimal_ceperator));

	$('.btw .price').text(currency_symbol + ' ' + roundVal(btw,2).toString().replace('.',decimal_ceperator));

	$('.subtotal_inc .price').text(currency_symbol + ' ' + roundVal(total_inc,2).toString().replace('.',decimal_ceperator));

}

/**
 * Round a value
 * @param {float} val
 * @param {int} decimals
 */
function roundVal(val, decimals){
	pow =  Math.pow(10,decimals);
	new_val = Math.round(val*pow)/pow;
	return new_val.toFixed(decimals);
}


function changeFieldToPassword(field){
	 $(field)
      .after('<input type="password" id="'+$(field).attr('id')+'" name="'+$(field).attr('name')+'" value="" />')
      .remove();
    $('input:password[name="'+$(field).attr('name')+'"]').focus();
}

function formatBrandsPage(){
    $('[id^="brand"]').each(function(){
        id = $(this).attr('id').substr(6);
        title = $(this).find('span:last').text();
        img = $(this).find('img:first');
        $(this).find('p').remove();
        a = '<a href="merken/' + id + '/' + encodeURIComponent(title) + '.html" title="' + title + '"></a>';
        $(this).prepend($(a).append(img)).find('span').html($(a).append(title));
    });
}
