function regExpEscape(text){
  if( !arguments.callee.sRE ){
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}
/*
function jsAddToCart(){

	$('.js_add_to_cart').click(function(){
							
		pattern = new RegExp('^(' + regExpEscape(host) + (window.languageIdentifier ? ('\\/' + languageIdentifier) : '') + ')\\/(.+)\\/([^\\/]+)$');
		var productName = $(this).attr('href').match(pattern);
		productName = productName[2];				

		$.ajax({
			url: 'ajax.php',
			data: (window.languageIdentifier ? ('lang=' + languageIdentifier + '&') : '') + 'ajax=add_to_cart&product=' + productName,
			dataType: 'html',
			cache: false,	
			success: function(data, textStatus){				
									
				$('.js_cart').replaceWith(data);	
				
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){}
		});
		
		return false;		
				
	});

}

function jsAddToWishList(){

	$('.js_add_to_wishlist').click(function(){
	
		pattern = new RegExp('^(' + regExpEscape(host) + (window.languageIdentifier ? ('\\/' + languageIdentifier) : '') + ')\\/(.+)\\/([^\\/]+)$');
		var productName = $(this).attr('href').match(pattern);
		productName = productName[2];
				
	
		$.ajax({
			url: 'ajax.php',
			data: (window.languageIdentifier ? ('lang=' + languageIdentifier + '&') : '') + 'ajax=add_to_wishlist&product=' + productName,
			dataType: 'html',
			cache: false,	
			success: function(data, textStatus){				
									
				$('.js_wishlist').replaceWith(data);	
				
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){}
		});
		
		return false;	
				
	});
}
*/
(function($) {
	$.fn.imagePreview = function() {
		if (!this.length) { return this; }
				
		var xOffset = 20;
		var yOffset = 10;
		var loadingImg = new Image();
		loadingImg.src = host + '/skn/' + skin + '/img/loading.gif';
		var img;
		var tempImg;
		
		this.each(function() {
			
			$(this).hover(function(e){
				img = loadingImg;
				$("body").append("<p id='preview'><img src='"+ img.src +"' /></p>");								 
				$("#preview")
					.css("top",(e.pageY - img.height - yOffset) + "px")
					.css("left",(e.pageX - img.width - xOffset) + "px")
					.fadeIn("fast");
				tempImg = new Image();
				tempImg.onload = function(){
					img = tempImg;
					$("#preview img").attr('src', img.src);
					$("#preview")
						.css("top",(e.pageY - img.height - yOffset) + "px")
						.css("left",(e.pageX - img.width - xOffset) + "px");
				};
				tempImg.src = $(this).attr('rel');
		    },
			function(){
				$("#preview").remove();
		    });	
			$(this).mousemove(function(e){
				if (typeof(img) !== 'undefined') {// makes this work in ie
					$("#preview")
						.css("top",(e.pageY - img.height - yOffset) + "px")
						.css("left",(e.pageX - img.width - xOffset) + "px");
				}
			});
			
		});

		return this;
	};
})(jQuery);
function blockOffset(elem){
	var eOffset = elem.offset();
	var top = eOffset.top;
	var left = eOffset.left;
	var bottom = top + elem.outerHeight();
	var right = left + elem.outerWidth();
	
	return {top : top, left : left, bottom : bottom, right : right};
}
function isScrolledIntoView(top, right, bottom, left, elem){	
	elem = blockOffset($(elem));
	
	if (
		elem.top < bottom
		&& elem.right > left
		&& elem.bottom > top
		&& elem.left < right
	) return true;
	return false;
}
(function($){
	$.fn.imgLoad = function(container){
		if (!this.length) { return this; }
		
		container = blockOffset($(container));
		
		this.each(function(){
			if ($(this).attr('rel') && isScrolledIntoView(container.top, container.right, container.bottom, container.left, $(this))) {
				$(this).attr('src', $(this).attr('rel'));
				$(this).removeAttr('rel');				
			}
		});
	}
})(jQuery);
function extendCart(){
	var height = parseInt($('.addToCart .top').height());
	height += 16;
	$('.addToCart').animate({'height': height + 'px'});
	$('.prodp').animate({'margin-top': height + 53 + 'px'});
	$('.js_cartControl').html('<span>[-Restrange]</span>');
}
function collapseCart(){
	$('.addToCart').animate({'height': '45px'});
	$('.prodp').animate({'margin-top': '98px'});
	$('.js_cartControl').html('<span>[+ADAUGA IN COS]</span> pentru comanda online');
}
function scrollPrev(){
	if ($('#js_scroll:animated').length) return;
	var _marginLeft = parseInt($('#js_scroll').css('margin-left').substring(0, $('#js_scroll').css('margin-left').length - 2));
	if (_marginLeft < 0) $('#js_scroll').animate({marginLeft: _marginLeft + 190}, "normal", scrollPrevLoad);
	else $('#js_scroll').animate({marginLeft: -jsScrollWidth + 190}, "normal", scrollPrevLoad);
}
function scrollNext(){
	if ($('#js_scroll:animated').length) return;
	var _marginLeft = parseInt($('#js_scroll').css('margin-left').substring(0, $('#js_scroll').css('margin-left').length - 2));
	if (_marginLeft <= -jsScrollWidth + 190) $('#js_scroll').animate({marginLeft: 0}, "normal", scrollNextLoad);
	else $('#js_scroll').animate({marginLeft: _marginLeft - 190}, "normal", scrollNextLoad);
}
function scrollPrevLoad(){
	var _marginLeft = parseInt($('#js_scroll').css('margin-left').substring(0, $('#js_scroll').css('margin-left').length - 2));
	var col = Math.abs(_marginLeft / 190) - 1;
	if (col < 0) col = jsScrollMaxCol - 1;
	$('#js_scroll .scrollCol').eq(col).find('.js_imgLoad').each(function(){
		if ($(this).attr('rel')) {
			$(this).attr('src', $(this).attr('rel'));
			$(this).removeAttr('rel');
		}
	});
}
function scrollNextLoad(){
	var _marginLeft = parseInt($('#js_scroll').css('margin-left').substring(0, $('#js_scroll').css('margin-left').length - 2));
	var col = Math.abs(_marginLeft / 190) + 1;
	if (col >= jsScrollMaxCol) col = 0;
	$('#js_scroll .scrollCol').eq(col).find('.js_imgLoad').each(function(){
		if ($(this).attr('rel')) {
			$(this).attr('src', $(this).attr('rel'));
			$(this).removeAttr('rel');
		}
	});
}
$(document).ready(function(){
	//jsAddToCart();
	//jsAddToWishList();	
	$('.hide_onload').hide();
	$('.submit_onchange').change(function(){
		$(this).parents().filter('form').submit();
	});
	$('.submit_onclick').click(function(){
		$(this).parents().filter('form').submit();
	});
	
	$('.js_news').each(function(){
		$(this).click(function(){
			if ($(this).parents('blockquote').find('p').css('height') == 'auto') {
				$(this).parents('blockquote').find('p').css('height', '30px');
				$(this).parents('blockquote').children('span').show();
				$(this).parents('blockquote').children('a').text('[+Extinde]');
			}
			else {
				var domElem = $(this).parents('blockquote').get();
				$('.news blockquote').not(domElem).each(function(){
					$(this).find('p').css('height', '30px');
					$(this).children('span').show();
					$(this).children('a').text('[+Extinde]');
				});
				$(this).parents('blockquote').find('p').css('height', 'auto');
				$(this).parents('blockquote').children('span').hide();
				$(this).parents('blockquote').children('a').text('[-Restrange]');
			}
			return false;
		});
	});

	$('.drop_shadow').each(function(){
		$(this).append('<span>' + $(this).text() + '</span>');
	});
	$('.js_imgPreview').imagePreview();
	
	$('.header_m ul li a').prepend('<img src="' + host + '/skn/' + skin + '/img/bull.png" alt="" />');
	$('.header_m ul li:first a img').css('margin-left', '0');

	jsScrollWidth = $('#js_scroll .scrollCol').length * 190;
	jsScrollMaxCol = jsScrollWidth / 190;
	$('#js_scroll').width(jsScrollWidth);
	$('.js_prev').click(function(){
		clearInterval(jsScrollInterval);
		scrollPrev();
		return false;
	});
	$('.js_next').click(function(){
		clearInterval(jsScrollInterval);
		scrollNext();
		return false;
	});
	jsScrollInterval = setInterval(scrollNext, 5000);
	$('#js_scroll_container .js_imgLoad').imgLoad("#js_scroll_container");
	scrollPrevLoad();
	scrollNextLoad();
	
	if ($('.prodp a').length) {
		$('.prodp a').attr('rel', 'fancybox');
		$('.prodp a').fancybox({'autoScale': false, 'showCloseButton': false, 'showNavArrows': false, 'cyclic': true, 'titlePosition': 'over', 'titleFormat': function(title, currentArray, currentIndex, currentOpts){
			var text = '';
			if (currentArray.length > 1) {
				text += '<a style="float: left;" href="javascript: $.fancybox.prev()" title="Inapoi">Inapoi</a>';
				text += '<a style="float: right;" href="javascript: $.fancybox.next()" title="Inainte">Inainte</a>';
			}
			text += '<p style="margin-top: 0;text-align: center;"><a href="javascript: $.fancybox.close()" title="Inchide">INCHIDE</a></p>';
			if (title && title.length) text += '<h1>' + title + '</h1>';
			var desc = $('.prodp img').eq(0).attr('alt');
			if (desc.length) text += '<p>' + desc + '</p>';
			if ($('.js_price').length) text += '<p style="margin-bottom: 0;font-weight: bold;">Pret: ' + $('.js_price').contents().get(0).data + '</p>';
			return  '<div>' + text + '</div>';
		}});
	}
	
	$('.js_cartControl').click(function(){
		if ($('.addToCart').height() == 45) extendCart();
		else collapseCart();
		return false;
	});
	
	$('input[name=company_details]').change(function(){
		if ($(this).val() == 1) $('.js_company').slideDown();
		else $('.js_company').slideUp();
	});
	
	$('.sort_table').attr('cellspacing', '0');
	
	$('.sort_table th, .sort_table td').each(function(){
		if ($(this).html() == '') $(this).html('&nbsp;');
	});
	
	$('.fproduct .js_imgLoad').imgLoad(".fproduct");
	var fproductScroll = true;
	var fproductBrakeScroll = false;
	$('.fproduct').scroll(function(){
		if (fproductScroll) {
			$('.fproduct .js_imgLoad').imgLoad(".fproduct");
			setTimeout(function(){
				if (fproductBrakeScroll) {
					$('.fproduct .js_imgLoad').imgLoad(".fproduct");
					fproductBrakeScroll = false;
				}
				fproductScroll = true;
			}, 300)
			fproductScroll = false;
		}
		else {
			if (!fproductBrakeScroll) fproductBrakeScroll = true;
		}
	});

});
