$().ready(function(){
	$.ajax({
		type:'get',
		dataType:'html',
		url:'/ajax/'+Config.language+'/shop/loadcart/',
		success:function(response){
			if(response){
					$('#js-shop-total').html(response).show();
					//$('#js-quick-basket').show();
			}
		}
	});
	
	$('.js-shop-order').live('click',function(){
		var self = $(this);
		rel = $(this).attr('rel');
		form = $('#js-form-order').serialize();
		
		self.addClass('disabled');
		self.parent().find('img.loader').show();
		
		$.ajax({
			type:'post',
			dataType:'json',
			data : form,
			url:'/ajax/'+Config.language+'/shop/buy/',
			success:function(response){
				if(response.success){
					if(response.shop.total){
						$('#js-quick-basket').hide();
						$('#js-quick-basket').html(response.shop.basket);
						$('#js-quick-basket').fadeIn();
						
						
						$('#lightsout').show();
						$('#dialogs').html(response.shop.message).show();
						
						self.parent().find('img.loader').hide();
						self.removeClass('disabled');
						
						/*$('#js-quick-message').addClass('hidden');
						$('#js-quick-message').hide();
						$('#js-quick-message').html(response.shop.message);
						$('#js-quick-message').removeClass('hidden');
						$('#js-quick-message').fadeIn();*/

					}

					highlight('#js-shop-ordered-'+rel);
					//$('#js-shop-order-success-'+rel).show();
					//setTimeout('$("#js-quick-message").fadeOut(1800);', 5000);
				}
			}
		});
		return false;
	});

	//edit parameters in cart
	$('.js-edit-options').live('click',function(){
		$(this).parent().hide();
		$(this).parent().parent().find('.js-parameters').show();
		return false;
	});

	$('#NodePriceId').live('change', function(){
		nodepriceid = $(this).val();
		productid = $(this).attr('rel');
		$.ajax({
            'type':'post',
            'url':'/ajax/'+Config.language+'/shop/checknodeprice',
            data: "id="+$(this).val(),
            'success':function(response){
            	$('#NodePriceId-'+productid).val(nodepriceid);
				$('.price em span').html(response);
            }
		});
	});

	$('.js-shop-amount-minus').live('click',function(){
		rel = $(this).attr('rel');
		amount = changeValue(rel, -1);
		changePrice(rel, amount);
        $.ajax({
            'type':'post',
            'url':'/ajax/'+Config.language+'/shop/amount_minus',
            data: "id="+rel,
            'success':function(response){

            }
        });
	});

	$('.js-shop-amount-plus').live('click',function(){
		rel = $(this).attr('rel');
		amount = changeValue(rel, 1);
		changePrice(rel, amount);
        $.ajax({
                'type':'post',
                'url':'/ajax/'+Config.language+'/shop/amount_plus',
                data: "id="+rel,
                'success':function(response){

                }
        });
	});

	$('.js-shop-amount-change').live('submit',function(){
		data = $(this).serialize();
		//alert(data);
        $.ajax({
                'type':'post',
                'url':'/ajax/'+Config.language+'/shop/amount_change',
                'data': data,
                'success':function(json){
                	updateBasket('full');
                }
        });
	});
	
	
	$('.quantity .js-shop-amount-more input').live('blur', function(){
		val = $(this).val();
		//node_id =  rel van andere selectbox
		node_id = $(this).closest('.quantity').find('.js-shop-amount-default').attr('rel');
		//console.log(node_id);
		//node_id = $('.js-shop-amount-default').attr('rel');
		saveAmount(val,node_id);
	});

	$('.quantity .js-shop-amount-on-change').live('change',function(){
		val = $(this).val();
		if(val=='other'){
			$(this).closest('.quantity').find('.js-shop-amount-more').show();
			$(this).closest('.quantity').find('.js-shop-amount-default').hide();
		}
		else{
			rel = $(this).attr('rel');
			saveAmount(val,rel)
		}
	});

	$('#js-shop-delevery-copy').click(function(){
		if($(this).is(':checked')){
			$('#js-shop-delevery-data').show();
		}else{
			$('#js-shop-delevery-data').hide();
		}
	});

	$('.quantity .js-shop-save-amount-other').live('click',function(){
		val = $(this).closest('.js-shop-amount-more').find('input').val();
		//node_id =  rel van andere selectbox
		node_id = $(this).closest('.quantity').find('.js-shop-amount-default').attr('rel');
		saveAmount(val,node_id);
	});

	$('.js-cart-delete').live('click',function(){
		id = this.rel;
		del(id, 0);
	});

	$('.js-cart-delete-gift').live('click',function(){
		id = this.rel;
		id = id.replace('g-','');
		del(id, 1);
	});


	$('.js-delivery').live('change', function(){
		changeDelivery($('.js-delivery').val());
	});


	$('.js-gift').live('click',function(){
		$('.js-gift').removeClass('active');
		$(this).addClass('active');
		$('#js-amount-other').hide();
		$('#NodePricePrice').val();
		$('#NodePriceId').val($(this).attr('rel'));
	});

	$('.js-gift-other').live('click',function(){
		$('#NodePriceId').val($(this).attr('rel'));
		$('#js-amount-other').show();
	});


	$('#js-giftcode').keydown(function(event) {
  		if (event.keyCode == '13') {
			$('.js-check-gift').trigger('click');
			return false;
  		}
	});

	$('.js-check-gift').live('click', function(){
		checkGift('#js-giftcode');
		return false;
	});

	$('.js-gift-edit').live('click',function(){
		loadDialog($(this).attr('href'));
		return false;
	});

	$('.js-delivery-type input').live('click',function(){
		if($(this).val()==1){
			$('.js-send-email').show();
		}
		else{
			$('.js-send-email').hide();
		}
	});

	$('.js-send-email input').live('click',function(){
		if($(this).val()==1){
			$('.js-delivery-email').show();
		}
		else{
			$('.js-delivery_email').hide();
		}
	});



	
	$("input[name='data[NodePriceGift][delivery_type]']").live('click',function(){
		if($(this).val() == '1'){
			$('.js-send-email').show();
			$('.js-send-email').removeClass('hidden');
			if($('#NodePriceGiftDeliverySendEmail1').is(':checked')){
				$('.js-delivery-email').show();
				$('.js-delivery-email').removeClass('hidden');
			} else {
				$('.js-delivery-email').hide();
				$('.js-delivery-email').addClass('hidden');
			}
		} else {
			$('.js-send-email').hide();
			$('.js-send-email').addClass('hidden');
		}	
	});
	
	$("input[name='data[NodePriceGift][delivery_send_email]']").live('click',function(){
		if($(this).val() == '1'){
			$('.js-delivery-email').show();
			$('.js-delivery-email').removeClass('hidden');
			
		} else {
			$('.js-delivery-email').hide();
			$('.js-delivery-email').addClass('hidden');
		}	
	});

	$('.js-gift').live('click',function(){
		$('.js-gift').removeClass('active');
		$(this).addClass('active');
		$('#js-amount-other').hide();
		$('#NodePricePrice').val();
		$('#NodePriceId').val($(this).attr('rel'));
	});

	$('.js-gift-other').live('click',function(){
		$('#NodePriceId').val($(this).attr('rel'));
		$('#js-amount-other').show();
	});


	$('#js-giftcode').keydown(function(event) {
  		if (event.keyCode == '13') {
			$('.js-check-gift').trigger('click');
			return false;
  		}
	});

	$('.js-check-gift').live('click', function(){
		checkGift('#js-giftcode');
		return false;
	});

	$('.js-gift-edit').live('click',function(){
		loadDialog($(this).attr('href'));
		return false;
	});

	
	$('.js-shop-amount-order').live('change',function(){
		if(this.value=='other'){
			$('.js-shop-amount-default').hide();
			$('.js-shop-amount-more').show();
		}
		else{
			$('.js-shop-amount-more').hide();
			$('.js-shop-amount-default').show();
		}
	});

});

function updateBasket(type){
	$.ajax({
		'type':'get',
		'dataType':'html',
		url:'/ajax/'+Config.language+'/shop/cart/'+type+'?'+Math.floor(Math.random()*9999),
		success:function(response){
			$('#js-full-basket').parent().html(response);
		}
	});
}

function checkGift(fieldid){
	code = $(fieldid).val();
	$.ajax({
		type:'post',
		data:'code='+code,
		dataType:'json',
		url:'/ajax/'+Config.language+'/shop/check_gift/',
		success:function(json){
			$('.js-error-gift').remove();
			if(json.success==1){
				updateBasket('full');
				calculateTotals();
			}
			else{
				$(fieldid).parent().parent().append('<div class="error-message js-error-gift">'+json.message+'</div>');
			}

		}
	});
}

function del(id, gift){
	$.ajax({
		'type':'post',
		'dataType':'json',
		'url':'/ajax/'+Config.language+'/shop/delete/'+gift,
		'data':'id='+id,
		'success':function(response){
			if(response.success){
				if(gift == 1){
					id = 'g-'+id;
				}
				$('#cart-row-'+id).remove();
				if(response.shop.total == 0){
					$('#js-full-basket').html(response.message);
					$('#js-shop-total').html(response.empty);

				} else {
					$('#js-shop-total').hide();
					$('#js-shop-total').html(response.shop.total);
					$('#js-shop-total').fadeIn();
				}
				calculateTotals();
			}
		}
	});
}

function changeValue(row, change){
	val = parseInt($('#js-shop-amount-row-'+row).val());
	new_val = val + change;
	if(new_val < 1){
		new_val=1;
	}

	$('#js-shop-amount-row-'+row).val(parseInt(new_val));
	return new_val;
}

function changePrice(row, amount){
	itemprice = parseFloat($('#js-shop-item-price-'+row).html());
	rowprice = itemprice * amount;
	formatprice = formatFloat(rowprice.toFixed(2));
	$('#js-shop-item-amount-price-'+row).html(formatprice);
	highlight('#js-shop-item-amount-price-'+row);
	calculateTotals();
}


function calculateTotals(){
	$.ajax({
		'type':'post',
		'dataType':'json',
		'url':'/ajax/'+Config.language+'/shop/prices',
		'success':function(json){
			$('#js-shop-price-subtotal').html(json.subtotal);
			$('#js-shop-price-delivery').html(json.delivery);
			$('#js-shop-price-taxes').html(json.total_taxes);
			$('#js-shop-price-total').html(json.total);
			//highlight('#js-shop-price-total');
		}
	});
}

function checkDeliveryCountry(val){
	$.ajax({
		'type':'get',
		'dataType':'json',
		'url':'/ajax/'+Config.language+'/shop/check_delivery/'+val,
		'success':function(json){
			if(json.changed){
				$('#js-notice').show();
			}
			else{
				$('#js-notice').hide();
			}
		}
	});

}


function formatFloat(str){
	tmp = str.split('.');
	return tmp[0]+','+tmp[1];
}

function highlight(domID){
	return true;
	//$(domID).animate("highlight", {'color':'#FFFFCC'}, 2000);
}

function changeDelivery(language){
	$.ajax({
		type:'post',
		data:'country='+language,
		url:'/ajax/'+Config.language+'/shop/change_delivery/',
		success:function(){calculateTotals(); return true}
	});
}


function saveAmount(amount,node_id){
	$.ajax({
        'type':'post',
        'url':'/ajax/'+Config.language+'/shop/amount_change',
        'data': 'data[Cart][amount]='+amount+'&data[Cart][node_id]='+node_id,
        'success':function(json){
        	updateBasket('full');
        	//calculateTotals();
        }
    });
}

function loadDialog(url){
	$('#lightsout').show();
	$('#dialogs').load('/ajax/'+Config.language+url, function(){
		$(this).show();
		if(!Modernizr.input.placeholder){
			$("input").each(function(){
				if($(this).val()=="" && $(this).attr("placeholder")!=""){
					$(this).val($(this).attr("placeholder"));
					$(this).focus(function(){
						if($(this).val()==$(this).attr("placeholder")) $(this).val("");
					});

					$(this).blur(function(){
						if($(this).val()=="") $(this).val($(this).attr("placeholder"));
					});
				}
			});
		}
	});
	if($.browser.msie && $.browser.version == 6){
		$( 'html, body').animate( { scrollTop: 0 }, 0 );
	}
}


/*GLOBAL - forgot password
===============================*/
$('#js-forgot-password-small').live('click',function(){
	forgot_password(false);
});

$('#js-forgot-password-full').live('click',function(){
	forgot_password(true);
});

$('#js-forgot').live('submit',function(){
	$('#js-response').hide();
	$.ajax({
		type:'post',
		dataType : 'json',
		data : $('#js-forgot').serialize(),
		url : '/ajax/'+Config.language+'/users/forgot_password',
		success : function(json){
			if(json.error){
				classname = 'error-message';
			}
			else{
				$('#js-forgot input[type!=submit]').each(function(){
					this.value = '';
				});
				classname = 'success-message';
			}

			$('#js-response').attr('class',classname);
			$('#js-response').html('');
			$('#js-response').html(json.message);
			$('#js-response').fadeIn();
		}
	});
	return false;
});

/*GLOBAL - forgot password
===============================*/
function forgot_password(full){
	$('#lightsout').show();
	$('#dialogs').load('/ajax/'+Config.language+'/users/forgot_password/'+full, function(){
		$(this).show();
		if(!Modernizr.input.placeholder){
			$("input").each(function(){
				if($(this).val()=="" && $(this).attr("placeholder")!=""){
					$(this).val($(this).attr("placeholder"));
					$(this).focus(function(){
						if($(this).val()==$(this).attr("placeholder")) $(this).val("");
					});

					$(this).blur(function(){
						if($(this).val()=="") $(this).val($(this).attr("placeholder"));
					});
				}
			});
		}
	});
	if($.browser.msie && $.browser.version == 6){
		$( 'html, body').animate( { scrollTop: 0 }, 0 );
	}
}

$('.js-form-gift-edit form').live('submit',function(){
	$.ajax({
		type:'post',
		url : '/ajax/'+Config.language+'/products/gift',
		data: $(this).serialize(),
		datatype : 'json',
		success:function(json){
			$('form .error').remove();
			if(json.success){
				$('.close').trigger('click');
				$('.dialog').html();
				updateBasket('full');
			}
			else{
				for(error in json.errors){
					errorfield = error.split('_');
					field = errorfield[0].slice(0,1).toUpperCase() + errorfield[0].slice(1) +errorfield[1].slice(0,1).toUpperCase() + errorfield[1].slice(1);
					$('#NodePriceGift'+field).parent().append('<div class="error">'+json.errors[error]+'<div>');
				}
			}
		}
	});

	return false;
});
