$.fn.addBasket = function(){

	$(this).click(function (){
		id = $(this).attr("id");
		id = parseInt(id.substring(5, id.length));
		if(!id){
			alert('error');
			return false;
		}
		price = parseFloat($('#price_' + id).html());
		if($(this).parent().find("img:first").attr("src") == '/images/loading.gif'){
			$(this).parent().find("img:first").remove();
		}
		loading = $('<img src="/images/loading.gif" />');
		loading.hide();
		loading.appendTo($(this).parent());
		$(this).hide("slow",function(){
			loading.show();
		});



		var el = $(this);

		$.getJSON("/" + LANG + "/basket/ajaxaddbasket/id/"+id+"/price/"+price,
		function(data){
			loading.remove();
			var origImg = $("#itemimage_" + id);

			if(!origImg.attr("src") && origImg.css('background-image') == 'none'){
				$("#basketInfoCount").html(data.counttext);
				$("#basketInfoSum").html(data.sum);
				return;
			}

			var curOffset =  origImg.offset();

			var basketOffset = $("#basket").offset();
			var img = origImg.clone().prependTo("body");
			el.show("slow");
			
			
			if($.browser.msie && parseInt($.browser.version) == 6){				
				el.css('filter',"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/main/basket_but.png', sizingMethod='scale')");
			}

			if(origImg.css('background-image') != 'none'){
				img.css({
					width:origImg.parent().css('width'),
					height:origImg.parent().css('height'),
					'background-position':'center',
					'background-repeat':'no-repeat'
				}
				);
			}

			img.css({
				left:curOffset.left + "px",
				top:curOffset.top + "px",
				position:"absolute",
				'z-index':"500"
			});

			origImg.hide();
			img.animate({
				left:basketOffset.left + "px",
				top:basketOffset.top + "px"
			},1000,'easeInExpo',function(){
				$(this).hide("slow",function(){
					$(this).remove();
					$("#basketInfoCount").html(data.counttext);
					$("#basketInfoSum").html(data.sum);
					origImg.show();
					loading.remove();
				});

			});

		}
		);



	});
}

$.fn.getDeliveryPrice= function(){
	deliveryType = $("form input[name='deliveryType']:radio:checked");
	var sum  = $("#itemsSum").val();
	sum = parseFloat(sum.substring(0, (sum.length - 2)));
	var weight = $("#totalWeight").val();
	price = parseFloat(getDeliveryPrice(deliveryType.val(),sum,weight));
	return price;
}

$.fn.setCountItem = function(count,id){
	count = parseInt(count);

	var itemSumEl = $(this).parent().parent().find(".item_totalprice:first > span");
	var totalItemsPriceEl = $("#itemsSum");
	var deliveryPriceEl = $("#deliveryPrice");

	var totalPriceEl = $("#totalPrice");
	var totalWeightEl = $("#totalWeight");
	var weight = $("#weightItem_" + id).val();
	$(itemSumEl).html('<img src="/images/loading.gif" />');
	$.getJSON("/" + LANG + "/basket/ajaxchcount/id/"+id+"/count/"+count,
	function(data){
		$("#basketInfoCount").html(data.counttext);
		$("#basketInfoSum").html(data.sum.toFixed(0));
		$(itemSumEl).html(data.itemSum.toFixed(2));
		$(totalItemsPriceEl).val(data.sum.toFixed(2) + " Ls");

		$(totalWeightEl).val(data.count * weight);
		var deliveryPrice = $(this).getDeliveryPrice();
		$(deliveryPriceEl).val(deliveryPrice.toFixed(2) + " Ls");
		$.calcTotalPrice();

	});

}

$.fn.chCountItem = function(){
	$(this).each(function (){
		$(this).change(function(){
			var count = parseInt($(this).val());
			var id = $(this).attr("id");
			id = parseInt(id.substring(10, id.length));
			if(isNaN(count)){
				count = 1;
			}

			if(count < 1){
				count = 1;
			}
			$(this).val(count);
			$(this).setCountItem(count,id);
		});
	});
}

$.fn.incCountItem = function(){
	$(this).each(function (){
		$(this).click(function(){
			var input = $(this).parent().find("input[type=text]:first");
			var count = parseInt($(input).val());
			var id = $(input).attr("id");
			count++;
			$(input).val(count);
			id = parseInt(id.substring(10, id.length));
			$(input).setCountItem(count,id);
		});
	});
}

$.fn.descCountItem = function(){
	$(this).each(function (){
		$(this).click(function(){
			var input = $(this).parent().find("input[type=text]:first");
			var count = parseInt($(input).val());
			var id = $(input).attr("id");
			count--;
			if(count < 1){
				return;
			}
			$(input).val(count);
			id = parseInt(id.substring(10, id.length));
			$(input).setCountItem(count,id);
		});
	});
}

$.fn.changeDeliveryPrice = function(){
	$(this).change(function(){
		var type = $(this).val();
		var price = $(this).getDeliveryPrice();
		$("#deliveryPrice").val(price.toFixed(2) + " Ls");
		$.calcTotalPrice();
	});

}

jQuery.calcTotalPrice = function(){
    var sum  = $("#itemsSum").val();
    sum = parseFloat(sum.substring(0, (sum.length - 2)));
    var deliviyPrice  = $("#deliveryPrice").val();
    deliviyPrice = parseFloat(deliviyPrice.substring(0, (deliviyPrice.length - 2)));
    var discountPrice  = $("#discountPrice").val();
    if(discountPrice){
    discountPrice = parseFloat(discountPrice.substring(0, (discountPrice.length - 2)));
    }else{
       discountPrice = 0; 
    }
    $("#totalPrice").val( (sum + deliviyPrice + discountPrice).toFixed(2) + " Ls");
    
}

$.fn.chDiscountPrice = function(){

		$(this).change(function(){
			var code = $(this).val();
			var reg = /^[A-z]{3}\d{1}[A-z]{2}$/;
			if(reg.test(code)){
			    $('#discountPrice').val('-5.00 Ls');
			}else{
			    $('#discountPrice').val('0.00 Ls');
			}
			$.calcTotalPrice();
		});
}


function compareItems(id){
	var ids =[id];
	$('.compare_checkbox:checked').each(function(){
		ids.push($(this).val());
	});
	ids = array_unique(ids);
	if(ids.length >1){
		document.location.href= "/" + LANG + "/compare/items/" + ids.join(',') + '/ret/' + SELF_ENCODE_URL;
		return;
	}
	return;
}

function applyFilter(el){
	
	var form = el.form;
	var val = {};	
	$(form).find("INPUT[type='checkbox']:checked").each(function(){
		key = this.name;
		if(val[key] == undefined){
			val[key] = new Array();
		}
		val[key].push(this.value);
	});
	url = json_encode(val);	
	url = Base64.encode(url);
	document.location.href= form.action + '/filter/' + url;
}

function array_unique( array ) {   
    var key = '', tmp_arr1 = {}, tmp_arr2 = {};
    var val = '';
    tmp_arr1 = array;
    
    var __array_search = function (needle, haystack, argStrict) {
        var fkey = '';
        var strict = !!argStrict;
        for (fkey in haystack) {
            if ((strict && haystack[fkey] === needle) || (!strict && haystack[fkey] == needle) ) {
                return fkey;
            }
        }
        return false;
    }
	
    for (key in tmp_arr1) {
        val = tmp_arr1[key];
        if (false === __array_search(val, tmp_arr2)) {
            tmp_arr2[key] = val;
        }
        
        delete tmp_arr1[key];
    }
    
    var arr = [];
    for(var key in tmp_arr2){
    	arr.push(tmp_arr2[key]);
    }
    
    return arr;
}

