$(document).ready(function() {
	initAttributesOnCategories();
});

function initAttributesOnCategories() {
	var timerCatAttr = new Array();
	$('#product_list li.ajax_block_product').each(function(i) {
		var curSrc = $(this).children('.center_block').children('.product_img_link').children('img').attr('src');
		var ids = curSrc.match(/[0-9]+\-[0-9]+\-/g);
		var reg = new  RegExp("[-]+", "g");
		var id = ids[0].split(reg);
		var id_product = id[0];
		var curIdImg = id[1];

		$(this).hover(
			function() {
				var e = $(this).children('.product_hide_elements');
				/*var hideDescr = $(this).children('.center_block').children('.product_list_descr');*/
				if(timerCatAttr[i] != false) clearTimeout(timerCatAttr[i]);
				if($(this).children('.product_hide_elements').children('.attributesoncategories').html() == '') {
					$(e).children('.attributesoncategories').load(pathAttrOnCat+'ajax.php', {action: 'getCombination',id_product: id_product,id_image:curIdImg},function(response, status, xhr) {
						$(e).show();
						/*$(hideDescr).fadeIn('fast');*/
						initAttributesImageLoad($(this));
					});
				}else { $(this).children('.product_hide_elements').fadeIn('fast');/*$(hideDescr).fadeIn('fast');*/}
			},function () {
				if($(this).children('.product_hide_elements').children('.attributesoncategories').html() == '') var timerLenght = 1000;
				else  var timerLenght = 50;
				var e = $(this).children('.product_hide_elements');
				var hideDescr = $(this).children('.center_block').children('.product_list_descr');
				timerCatAttr[i] = setTimeout(function() {
					$(e).fadeOut('fast');
					/*$(hideDescr).fadeOut('fast');*/
				},timerLenght);
			});
		});
}

function initAttributesImageLoad(e) {
	/*$(e).children('.color_picker').children('a').tooltip({
	    track: true,
	    delay: 0,
	    showURL: false,
	    showBody: " - ",
	    fade: 250
	});*/
	$(e).children('.color_picker').children('a').click(function() {
		  var curid = $(this).attr('id');
		  var reg = new  RegExp("[_]+", "g");
		  var id = curid.split(reg);
		  var id_image = id[1];
		  changeCatImgProduct($(this),id_image);
	});
}

function changeCatImgProduct(e,id_image) {
	var curImg = $(e).parent(".color_picker").parent(".attributesoncategories").parent(".product_hide_elements").parent('.ajax_block_product').children('.product_img_link').children('img');
	var curSrc = $(curImg).attr("src");
	var newSrc = curSrc.replace(/([0-9]+\-)[0-9]+(\-)/g,"$1"+id_image+"$2");

	if(newSrc && newSrc != curSrc) {
		$(e).parent(".color_picker").children('.color_pick').removeClass('selected');
		$(e).addClass('selected');
		$(curImg).fadeOut("fast",function() {
			$(this).attr("src",newSrc).load(function(){
				$(this).fadeIn("fast");

			});
		});
	}
}
