$(function(){
	// add info labels
	$('.productInfoShort img').each(function(){
		$(this).parent().append('<div class="productMoreInfoLabel"></div>');
	});
	
	// display product info over image
	$('.productInfoShort .productMoreInfoLabel').mouseover(function(){
		$(this).parent().parent().find('.productInfoHolder').css('display', 'block');
	});
		
	$('.productInfoHolder').mouseleave(function(){
		$(this).css('display', 'none');
	});

	$('#categoryListHolder div').each(function(){
		$(this).find('ul li:last').addClass('last');
	});
	
	$('#categorie_images div').bind('mouseover',function(){
		$(this).find('.title').css('background-image','url(inc/img/cat_title_hover.png)');
	}).bind('mouseout', function(){
		$(this).find('.title').css('background-image','url(inc/img/cat_title.png)');
	});
	
	// set subcategorys
	i = 0;
	$('[id^="subcat"]').each(function(){
		if ($(this).hasClass('displ-block')){			
			if (i === 1) {
				$(this).addClass('redrow');
			}
			else {
				if (i !== 0) {
					myClass = ((i % 2) === 0) ? 'odd' : 'even';
					// display the row and add the class
					$(this).addClass(myClass);
				}
			}
			i++;
		}	
	});
	

	// align text in main category titles
	$('#subcat0 ul li a .title').each(function(){	
		padding = Math.round((40 - $(this).height()) /2)-1;
		add = (padding%2 === 1) ? 0 : 1;
		$(this).css({
			paddingTop: padding + 'px',
			paddingBottom: ((padding+add)+1) + 'px'
		});
	});
	
	// set the subcategory's
	$('#categoryListHolder div').each(function(i){		
		$(this).find('a').bind('click', function(e){
			// reset links for this row
			$(this).parent().parent().find('li').each(function(){ 
				// if this link is active
				if($(this).hasClass('active')){
					// deactivate link
					$(this).removeClass('active'); 
					// get the id
					id = $(this).parent().parent().attr('id').substr(6);
					// deactivate all siblings
					$('#subcat'+id+' ~ div').css('display','none').removeClass().find('li.active').removeClass('active');
				}				
			});						
			
			// find the id of the link
			id = $(this).attr('id').substr(4);
			// if there is a subrow
			if($('#subcat'+id).length !== 0){
				if($(this).parents('#subcat0').length === 1){					
					$('#subcat'+id).addClass('redrow');
				}
				// activate the row				
				$(this).parent().addClass('active');
				// prevent the default action			
				e.preventDefault();
				// collect all rows
				nr = 0;
				$('#categoryListHolder div').each(function(i){
					if($(this).hasClass('odd') || $(this).hasClass('even')){
						nr++;
					}
				});

				// check if we are a odd or even row
				newClass = (nr%2 === 0) ? 'odd' : 'even';
				// display the row and add the class
				$('#subcat'+id).css('display','block').addClass(newClass);
			}	
			$('#ProductContent').hide();
		});
	});
	
	// remove aanbiedingen tab
	$('#categoryListHolder [title="Aanbiedingen"]').parent().remove();
	
	$(".productImages a").fancybox({
		'speedIn'		:	600, 
		'speedOut'		:	200,
		'titleShow'		: 	false
	});
	
	$(".productImages a").each(function(i){
		if(i >0){
			$(this).hide();
		}
	});
        
        /*
        $('.productInfoShort.c250, .productInfoFull.c250, .productInfoShort.c251, .productInfoFull.c251, .productInfoShort.c252, .productInfoFull.c252').each(function(){
	   $(this).find('.productImgHolder, .productImages').append('<div class="productOutletSale"></div>');
	});
        
	// add label to products in outlet
	$('.productInfoShort.c255, .productInfoFull.c255, .productInfoShort.c264, .productInfoFull.c264, .productInfoShort.c265, .productInfoFull.c265, .productInfoShort.c266, .productInfoFull.c266').each(function(){
	   $(this).find('.productImgHolder, .productImages').append('<div class="productOutletDiscount"></div>');
	});
        */
       $('[class*="discount-"]').each(function(){
           discount = 0;
           classes = $(this).attr('class').split(' ');

           for(clas in classes){
         
               if(classes[clas].indexOf('discount-') === 0){
                   discount = classes[clas].substr(9);
               }
           }
		$div = '<div class="productOutletDiscount"><img src="inc/img/discount-'+ discount +'.gif" alt="'+ discount +' procent korting" /></div>';

        $(this).find('.productImgHolder, .productImages').append($div);
	});
	
	$('.message').dialog({
		draggable: false,
		width: 350,
		modal: true,
		resizable: false		
	});
        
        $('.productPropertys select:not(.hidden), .productInfoShort select:not(.hidden)').selectmenu({ 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]);
            }  
        }); 
        
    /* Set the images in product overvieuws*/
    $('.productImgHolder').each(function(){setImageAsBackground($(this))});

    $('.productImages').each(function(){setImageAsBackground2($(this))});
});

/**
 * 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'});
    $('.productInfoFull .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
        $('.productInfoFull .itemCode, .productInfoFull .itemPrice').css({'display' : 'block'});
        $('.itemPrice-from').css({'display' : 'none'});
    }
    return true;
}

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 updateCartRow(edt){
	var row 	= $(edt).parent().parent();
	var val 	= $(edt).val();
	var costs 	= $(row).find('.rowCosts').text();

	// strip price indicator
	costs =  costs.substr(2).replace(' ','').replace(decimal_ceperator, '.');

	// transform value to float
	costs = parseFloat(costs);

	$(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 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 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));
    });
}

function setImageAsBackground($obj){
    $img = $obj.find('img:first');
    if($img){
        $obj.css({
            'background-image' : 'url('+$img.attr('src')+')',
            'background-position' : 'center',
            'background-color' : 'white',
            'background-repeat' : 'no-repeat'
        });

        $img.remove();
    }
}

function setImageAsBackground2($obj){
    $img = $obj.find('img:first');
    if($img){
        $obj.prepend('<div class="productImgHolder"></div>');
        $obj.find('.productImgHolder').css({
            'background-image' : 'url('+$img.attr('src')+')',
            'background-position' : 'center',
            'background-color' : 'white',
            'background-repeat' : 'no-repeat',
            'width' : 400,
            'height' : 400,
            'cursor':'pointer'
        }).click(function(){$img.parent().click()});

        $img.hide();
    }
}
