function findPos(obj) {
	var curleft = curtop = 0;
	if ( obj && obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

var nr_ie = 0;
var c_width = 0;
var c_height = 0;
var isOnCat = 0;



$(function()
{
	check_buynow();
	$("#searchForm1").submit(function(){
			var t = $("#searchText1");
			if( t.val() == "" ){
				alert("Introduceti cuvantul cautat");
				t.focus();
				return false;
			};
		});
	$("#prodlist250").click(function(){
		var t = jQuery(this);
		if( t.hasClass("h") ){
			isOnCat = 0;
			hideMyCats(250);
		}
		else{
			showMyCats(250);
		}
		return false;
	});
	$("#prodlist271").click(function(){
		var t = jQuery(this);
		if( t.hasClass("h") ){
			isOnCat = 0;
			hideMyCats(271);
		}
		else{
			showMyCats(271);
		}
		return false;
	});
	$("#prodlist266").click(function(){
		var t = jQuery(this);
		if( t.hasClass("h") ){
			isOnCat = 0;
			hideMyCats(266);
		}
		else{
			showMyCats(266);
		}
		return false;
	});
	$("#prodlist249").click(function(){
		var t = jQuery(this);
		if( t.hasClass("h") ){
			isOnCat = 0;
			hideMyCats(249);
		}
		else{
			showMyCats(249);
		}
		return false;
	});
	$("#prodlist252").click(function(){
		var t = jQuery(this);
		if( t.hasClass("h") ){
			isOnCat = 0;
			hideMyCats(252);
		}
		else{
			showMyCats(252);
		}
		return false;
	});
	$("#prodlist249").hover(
		function(){
			//do nothing...
		},
		function(){
			setTimeout("hideMyCats(249)", 500);
		}
	);
	$("#prodlist252").hover(
		function(){
			//do nothing...
		},
		function(){
			setTimeout("hideMyCats(252)", 500);
		}
	);
	$("#prodlist266").hover(
		function(){
			//do nothing...
		},
		function(){
			setTimeout("hideMyCats(266)", 500);
		}
	);
	$("#prodlist271").hover(
		function(){
			//do nothing...
		},
		function(){
			setTimeout("hideMyCats(271)", 500);
		}
	);
	$("#prodlist250").hover(
		function(){
			//do nothing...
		},
		function(){
			setTimeout("hideMyCats(250)", 500);
		}
	);
	//$("#lista").css("opacity", "0");
	$("#lista250").hover(
		function(){
			isOnCat = 1;
		},
		function(){
			isOnCat = 0;
			hideMyCatsT();
			setTimeout("hideMyCats(250)", 500);
		}
	);
	$("#lista252").hover(
		function(){
			isOnCat = 1;
		},
		function(){
			isOnCat = 0;
			hideMyCatsT();
			setTimeout("hideMyCats(252)", 500);
		}
	);
	$("#lista271").hover(
		function(){
			isOnCat = 1;
		},
		function(){
			isOnCat = 0;
			hideMyCatsT();
			setTimeout("hideMyCats(271)", 500);
		}
	);
	$("#lista266").hover(
		function(){
			isOnCat = 1;
		},
		function(){
			isOnCat = 0;
			hideMyCatsT();
			setTimeout("hideMyCats(266)", 500);
		}
	);
	$("#lista249").hover(
		function(){
			isOnCat = 1;
		},
		function(){
			isOnCat = 0;
			hideMyCatsT();
			setTimeout("hideMyCats(249)", 500);
		}
	);

	if (document.getElementById('cartBtnRecomandari')) {
		cartSlider();
	}

	//fancy
	$("a#custom_1").fancybox({
		'itemLoadCallback': getGroupItems
	});



	$("a#activate_custom_1").click(function(){
		$("a#custom_1").click();
		return false;
	});
	$("a#custom_friend").fancybox({
	 'frameWidth': 500,
	 'frameHeight': 310,
	 'zoomSpeedOut': 100
	 });

	 $(".sharelinks a.share").click(function(){

		 if ($(this).hasClass("emailfr")){
			$("a#custom_friend").click();
			return false;
		 }else{
			 if ($(this).hasClass("yahoo")){
				var name=prompt("Introduceti id-ul prietenului:","");
				if (name!=null && name!=""){
						var thishref=$(this).attr("rel");
						$(this).attr("href","ymsgr:sendIM?"+name+"&m="+thishref);
				  }else{alert("Id-ul prietenullui este obligatoriu!");return false;}
			 }
		 }
	 });

	 fltCursor();
	 checkoutInit();
	 iconZoom();
	 mesajPersonlizatInit();
});

function cartSlider() {

	var speed = 100;
	var secondSpeed = 30;

	var scrollStepsPx = 1;
	var scrollStepsPxSecondSpeed = 10;


	var timer = null;
	var allowTimer = null;

	var sliderValue = 0;
	var dir = 1;
	var visibleWidth = 734;
	var maxSteps = 674;
	var scrollLeft = 0;


	var btn = $('#cartBtnRecomandari');

	var theSlider = null;
	var scroller = null;
	var crtBboxP = null;
	var	mover = null;

	var lis = null;
	var maxScroll = null;
	var raport = null;

	var init = false;
	function doInit() {
		theSlider = $('#cartSlider');
		scroller = $('#crtBboxPwr');
		crtBboxP = $('#crtBboxP');

		lis = $('li', scroller);
		maxScroll = lis.outerWidth() * lis.length - visibleWidth;

		raport = maxSteps / maxScroll;

		$('#crtBboxP').hover(stopTimer, startTimer);
		$('#cntCartSlider .arr').hover(arrow_mouseover, arrow_mouseout);
		theSlider.slider({
			slide: slider_slide,
			change: slider_slide
		});
		mover = $('.ui-slider-handle', theSlider);
		init = true;
	}

	function btnClicked() {
		if (!init) {
			doInit();
		}
		if (crtBboxP.hasClass('n')) {
			startTimer();
			crtBboxP.removeClass('n');
			$('#cartBoxReduceri .btn').addClass('btnV');
		}
		else {
			stopTimer();
			crtBboxP.addClass('n');
			$('#cartBoxReduceri .btn').removeClass('btnV');
		}
		return false;
	}
	function stopTimer() {
		clearTimeout(timer);
		allowTimer = false;
	}
	function startTimer() {
		allowTimer = true;
		timer = setTimeout(timer_slide, speed);
	}
	function arrow_mouseover() {
		if ($(this).hasClass('arrL')) {
			dir = -1;
		}
		else {
			dir = 1;
		}
		allowTimer = true;
		//console.log('over');
		arrow_ismouseover();
	}

	function arrow_ismouseover() {
		if (allowTimer) {
			scrollLeft += dir * scrollStepsPxSecondSpeed;
			if (scrollLeft <= 0) {
				dir = 1;
				if (scrollLeft < 0) {
					scrollLeft = 0;
				}
			}
			else if (scrollLeft >= maxScroll) {
				dir = -1;
				if (scrollLeft > maxScroll) {
					scrollLeft = maxScroll;
				}
			}
			moveScroller(scrollLeft, true);
			if (scrollLeft != 0 && scrollLeft != maxScroll) {
				timer = setTimeout(arrow_ismouseover, secondSpeed);
			}
		}
	}


	function arrow_mouseout() {
		stopTimer();

	}

	function timer_slide() {
		if (allowTimer) {
			scrollLeft += dir * scrollStepsPx;
			if (scrollLeft <= 0) {
				dir = 1;
				if (scrollLeft < 0) {
					scrollLeft = 0;
				}
			}
			else if (scrollLeft >= maxScroll) {
				dir = -1;
				if (scrollLeft > maxScroll) {
					scrollLeft = maxScroll;
				}
			}
			moveScroller(scrollLeft, true);
			timer = setTimeout(timer_slide, speed);
		}
	}
	function moveScroller(value, isTimerCallBack) {
		scrollLeft = value;
		scroller.scrollLeft(value);
		if (isTimerCallBack) {
			mover.css('left', (scrollLeft * raport) + 'px');
		}
	}
	function slider_slide(event, ui) {
		moveScroller(maxScroll * ui.value / 100, false);
	}

	$('#cartBtnRecomandari').click(btnClicked);
}

function fltCursor(){
	var containerLeft = $('.fltDbg');
	if (containerLeft.length < 1) {
		return false;
	}

	var containerLeft = containerLeft.position();
	containerLeft = containerLeft.left;

	var undePunCursor = $('.fltDbgUl');
	var cursorDefault = undePunCursor.css('backgroundPosition');
	var tmp_left = 0;

	var timer = null;
	var def = $('.fltAs');
	if (def.length < 1) {
		def = false;
	}

	$('.fltShowA').click(function (){
		$('.fltShow').addClass('fltIsH');
		$('.fltBox').removeClass('fltIsH');
		return false;
	});
	$('.fltXa').click(function (){
		$('.fltBox').addClass('fltIsH');
		$('.fltShow').removeClass('fltIsH');
		return false;
	});

	$('.fltA').hover(
		function() {
			clearTimeout(timer);
			// console.log('in');
			tmp_left = jQuery(this).position().left - containerLeft - 3;
			//tmp_left = tmp_left.left - containerLeft - 3;
			if (def) {
				def.removeClass('fltAs');
			}
			undePunCursor.css('background-position', tmp_left + 'px 0px');
		},
		function() {
			timer = setTimeout(setCursorToDefault, 100);
		}
	);
	function setCursorToDefault() {
		if (def) {
			def.addClass('fltAs');
		}
		undePunCursor.css('background-position', cursorDefault);
	}
}
function iconZoom() {
	var elements = jQuery('.btnZ');
	if (elements.length < 1) {
		return false;
	}

	var zr  = {
		'productid': false,
		'onpicture': false,
		'rel': false,
		'elem': null,
		'wrapper': false,
		'src': false
	};

	var ie6 = (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7);

	var cfg = {
		'url': xcart_web_dir + "/getZoomImage.php?id=",
		'hideTimeout': 200,
		'waitForImage': 200,
		'imgSomePad': 40,
		'wrapperID': 'iconZoomWr',
		'ie6IframeID': 'iconZifrSF'
	};

	function btnZMouseOver() {
		doZoom(this);
	}
	function btnZMouseOut() {
		startHideZoom();
	}
	function btnZClicked() {
		zr.rel = jQuery(this).attr('rel');
		zrWrapperClicked();
		return false;
	}

	function doZoom(el) {
		var elem = jQuery(el);
		var id = elem.attr('rel');
		zr.productid = id.substr(id.indexOf('_')+1);
		zr.rel = id;
		zr.elem = elem;
		jQuery.get(cfg.url + zr.productid, zoomReceived);
	}
	function startHideZoom() {
		setTimeout(checkToHideZoom, cfg.hideTimeout);
	}
	function zoomReceived(data) {
		//console.log(data);
		zr.src = data;
		waitForImageToLoad();
	}
	function waitForImageToLoad() {
		var img = new Image();
		img.src = zr.src;
		if (img.width == 0 || img.height == 0) {
			setTimeout(waitForImageToLoad, zr.waitForImage);
		}
		else {
			var elem = zr.elem;
			if (!elem) {
				return false;
			}
			var fereastra = jQuery(window);
			var elemPos = elem.offset();
			var pos = {
				'l_x': fereastra.width(),
				'l_y': fereastra.height(),
				'scroll_x': fereastra.scrollLeft(),
				'scroll_y': fereastra.scrollTop(),
				'x': elemPos.left,
				'y': elemPos.top
			};
			//console.log(img.width, img.height);

			// daca nu-l pot afisa la dreapta
			if ((pos.x - pos.scroll_x) + img.width + 40 > pos.l_x) {
				// in dau la stanga
				pos.x = pos.x - img.width + 10;
				//console.log('stanga 1 : ', pos.x);
				//dar sa nu-l dam prea la stanga
				if (pos.x < pos.scroll_x) {
					pos.x = pos.scroll_x;
					//console.log('stanga 2: ', pos.x);
				}
			}
			// daca nu-l pot afisa jos
			if ((pos.y - pos.scroll_y) + img.height + 40 > pos.l_y) {
				// il dau sus
				pos.y = pos.y - img.height + 10;
				//console.log('sus 1: ', pos.y);
				// dar sa nu-l dam prea sus
				if (pos.y < pos.scroll_y) {
					pos.y = pos.scroll_y;
					//console.log('sus 2: ', pos.y);
				}
			}
			// ok, acum in pos.x si pos.y avem coordonante unde tre'sa punem obiectul.
			var text = "<img src='" + img.src + "' alt='' />";
			if (ie6) {
				text = "<iframe id='" + cfg.ie6IframeID + "' src='" + xcart_web_dir + "/empty.html' style='width: " + (img.width+10) + "px; height: " + (img.height+10) + "px;'></iframe>" + text;
			}
			//console.log(pos.x, pos.y, text);
			showTheZoom(pos.x, pos.y, text);
		}
	}

	function showTheZoom(left, top, text, img_w, img_h) {
		//console.log(left, top, text);
		if (!zr.wrapper) {
			zr.wrapper = jQuery('<div id="' + cfg.wrapperID + '" class="v" style="left: ' + left + 'px; top: ' + top + 'px">' + text + '</div>');
			zr.wrapper.appendTo('body');
		}
		else {
			zr.wrapper.html(text).css({'left': left +'px', 'top': top + 'px'}).addClass('v');
		}
		zr.wrapper.hover(markOnPicture, hideZoom).click(zrWrapperClicked);
	}
	function markOnPicture() {
		zr.onpicture = true;
	}
	function zrWrapperClicked() {
		var h = null;
		if (document.getElementById(zr.rel)) {
			h = document.getElementById(zr.rel).href;
		}
		else {
			h = jQuery('.' + zr.rel).attr('href');
		}
		if (!h) {
			return false;
		}
		window.location = h;
		return false;
	}

	function checkToHideZoom() {
		if (!zr.onpicture) {
			hideZoom();
		}
	}
	function hideZoom() {
		zr.productid = false;
		zr.onpicture = false;
		zr.elem = null;
		if (zr.wrapper) {
			zr.wrapper.removeClass('v');
		}
	}

	elements.hover(btnZMouseOver, startHideZoom).click(btnZClicked);
}


/* mesaj_personalizat */
function mesajPersonlizatInit() {
	if (!document.getElementById('cartDorescMesaj')) {
		return false;
	}
	var cartDorescMesaj = jQuery('#cartDorescMesaj');
	var cartImsg = (cartDorescMesaj.attr('checked') ? true : false);
	var cartMsg = '';

	function checkboxClicked() {
		var checked = (cartDorescMesaj.attr('checked') ? true : false);
		if (checked){
			var elem = jQuery('#cartMesajPersonalizat');
			elem.removeAttr('disabled').removeClass('disabled').val(' ').val(cartMsg);
			jQuery('#cartMesajPersonalizatLayer').addClass('none');
		}
		else{
			if (cartImsg){
				window.location = "cart.php?mode=del_mesaj";
			}
			var elem = jQuery('#cartMesajPersonalizat');
			cartMsg = elem.val();
			elem.val('').attr('disabled', 'disabled').addClass('disabled');
			jQuery('#cartMesajPersonalizatLayer').removeClass('none');
		}
	}
	function layerClicked() {
		cartDorescMesaj.attr('checked', 'checked');
		checkboxClicked();
		jQuery('#cartMesajPersonalizat').focus();
	}

	cartDorescMesaj.click(checkboxClicked);
	jQuery("#cartMesajPersonalizatLayer").click(layerClicked);
}
/* mesaj_personalizat*/


var detailedimageList = new Array;
function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function rebuidDetailedImages( foritem , value)
{
	//alert(imageList[0]['url']);
	//return;
	imageList = new Array();
	//console.log(foritem + " si " + value );
	//console.log(detailedimageList.length );


	var qq = 0;
	for( var i = 0 ; i < detailedimageList.length; i++)
	{

		if (detailedimageList[i]['option'] == foritem )
		{
			if (detailedimageList[i]['valueop'] == value )
			{

				imageList[qq] = new Array();
				imageList[qq]['url'] = detailedimageList[i]['tmbn_url'];
				imageList[qq]['title'] = ''+detailedimageList[i]['alt'];
				qq++;
			}
		}
	}
	if (imageList.length == 0)
	{
		//console.log("image list este gol ... Il umplu");
		//console.log(detailedimageList.length);
		for( var i = 0 ; i < detailedimageList.length; i++)
		{
			imageList[i] = new Array();
			imageList[i]['url'] = detailedimageList[i]['tmbn_url'];
			//console.log(detailedimageList[i]['tmbn_url']);
			imageList[i]['title'] = ''+detailedimageList[i]['alt'];
			//console.log(detailedimageList[i]['title']);
		}
	}

}

 function getGroupItems(opts) {
		 jQuery.each(imageList, function(i, val) {
		 opts.itemArray.push(val);
		 });
}

function hideMyCatsT(){
}

function hideMyCats(cat){
	if( isOnCat == 1 ) return ;

	if ($.browser.msie)
		{
			if ($.browser.version.number > 6)
				{
					$("#lista"+cat).stop().animate({"opacity": "0"}, 500, function(){  $("#lista"+cat).css("display", "none"); });
				}
				else
				{
					$("#lista"+cat).css("display", "none");
				}
		}
		else {$("#lista"+cat).stop().animate({"opacity": "0"}, 500, function(){  $("#lista"+cat).css("display", "none"); });}
	$("#prodlist"+cat).removeClass("h");
	isOnCat = 0;
}
function showMyCats(cat){

	if ($.browser.msie)
		{
			if ($.browser.version.number > 6)
				{
					$("#lista"+cat).stop().css("display", "block").animate({"opacity": 1}, 500);
				}
				else
				{
					$("#lista"+cat).css("display", "block");
				}
		}
		else {$("#lista"+cat).stop().css("display", "block").animate({"opacity": 1}, 500);}




	$("#prodlist"+cat).addClass("h");
}

jQuery.fn.newsletter = function(){
return this.each(function (){
	 var t = jQuery(this);
	 t.submit(function(){
		 if( checkEmailAddress( document.getElementById( $("#"+t.attr("id")+ " input[name='newsemail']:first" ).attr("id") ), 'Y' ) == false ){
			 return false;
		 }
	 });
});
}

jQuery.fn.hint = function () {
  return this.each(function (){
    /* get jQuery version of 'this'*/
    var t = jQuery(this);
    /* get it once since it won't change*/
    var title = t.attr('alt');
    /* only apply logic if the element has the attribute*/
    if (title) {
      /* on blur, set value to title attr if text is blank*/
      t.blur(function (){
        if ($.trim(t.val()) == '') {
          t.val(title);
        }
      });
      /* on focus, set value to blank if current value */
      /* matches title attr*/
      t.focus(function (){
        if (t.val() == title) {
          t.val('');
        }
      });

      /* clear the pre-defined text when form is submitted*/
      t.parents('form:first()').submit(function(){
          if (t.val() == title) {
              t.val('');
          }
      });

      /* now change all inputs to title */
      t.blur();
    }
  });
}

$(function()
{
	$('input:text').hint();

	$("#newsletteremail").submit(function(){
		var t = $("#searchEmail");
		if( t.val() == "" ){
			alert("Introduceti o adresa de email");
			t.focus();
			return false;
		};
	});
	$("#searchForm2").submit(function(){
		var t = $("#searchText2");
		if( t.val() == "" ){
			alert("Introduceti cuvantul cautat");
			t.focus();
			return false;
		};
		window.location = $("#searchForm2").attr("action") + "?q=" + t.val();
		return false;
	});
	$("#arataToate").click(function(){
		var t = jQuery(this);
		if( t.hasClass("h") ){
			isOnCat = 0;
			hideMyCats();
		}
		else{
			showMyCats();
		}
		return false;
	});
	$("#arataToate").hover(
		function(){
			//do nothing...
		},
		function(){
			setTimeout("hideMyCats()", 500);
		}
	);
	
	if ( $.browser.msie ){
		$('input:checkbox').css('border', 'none');
		$('input:radio').css('border', 'none');
	}
	 var optiuni = {
        resizeLgImages:     true,
        displayNav:         true,
        handleUnsupported:  'remove',
        keysClose:          ['c', 27] // c or esc
    };

	

});

function changeSortType(x)
{
//var x = document.getElementById("selectSortType");
var unde = x.options[x.selectedIndex].value;
window.location = xcart_web_dir + "/" + unde;
}

function gabi_repair_bug_variant_avail()
{
	//alert("intru in functie: " + parseInt(document.getElementById('product_avail_txt').innerHTML) );
	if( document.getElementById('product_avail') )
	{
		if( parseInt(document.getElementById('product_avail').options[0].value) >= min_avail ) doIsAvailable();
		else doNotAvailable('', 1);
	}
}
function checkAvail()
{
	gabi_repair_bug_variant_avail();
	
}
function doNotAvailable(variantid, pSnAB)
{
	//alert("Nu e disponibil");

	var i = "indisponibil";
	if (variantid) {
		var h = xcart_web_dir + "/stock_notify.php?productid=" + $("h2#titluprodus").attr("rel") + "&variantid=" + variantid;
	}
	else{
		var h = xcart_web_dir + "/stock_notify.php?productid=" + $("h2#titluprodus").attr("rel");
	}
	var elem = $("#product2Cos");
	var ismyavail = elem.attr('rel');
	if(pSnAB == 1){
		if (ismyavail == 'disponibil' )
		elem.removeClass("pcc").addClass("pccbacks").html("<b>CERE ALERTA STOC</b>").attr("href", h).attr("title","CERE ALERTA STOC").attr("rel","indisponibil");
	}
	else{
		elem.addClass(i).html("CERE ALERTA STOC");
	}

	var notVisible = "notVisible";

	//document.getElementById('txt_produs_avail').setAttribute("class", "txt_produs_avail_not_ok");
	//document.getElementById('txt_produs_avail').setAttribute("className", "txt_produs_avail_not_ok"); // for ie

	$("#product_avvail").removeClass("ch_avail");
	$("#product_avvail").addClass("ch_unavail");
	$("#product_avvail").html(txt_out_of_stock);
	//functions defined in myScripts.js
	clearAllElem(document.getElementById("product_avail"));
	var elem = document.createElement('option');
	elem.value = "0";
	elem.text = txt_out_of_stock;//defined by xcart
	addSelectElem(document.getElementById("product_avail"), elem);


	return true;
}

function check_buynow(){
	
	$('.buywith').click(function(){
		if ($(this).is(':checked')){
			var product_price = $("#product_price").html();
			product_price = product_price.substr(0,((product_price.length)-4));
			var tosum = $("#"+$(this).attr("id")+"_price").attr("value"); 
			product_price = parseFloat(parseFloat(product_price) + parseFloat(tosum)) ;
			$("#product_price").html(product_price.toFixed(2) + " Lei"); 
		}
		else{
			var product_price = $("#product_price").html();
			product_price = product_price.substr(0,((product_price.length)-4));
			var tosum = $("#"+$(this).attr("id")+"_price").attr("value"); 
			product_price = parseFloat(parseFloat(product_price) - parseFloat(tosum)) ;
			$("#product_price").html(product_price.toFixed(2) + " Lei"); 
		}
	});
	/*
	$('.buywith').each(
		$(this).click(function(){
			if ($(this).is(':checked')){
				alert("acum");
				var product_price = $("#product_price").html();
				product_price = product_price.substr(0,(product_price.length-4));
				var tosum = $("#"+$(this).attr("id")+"_price").attr("value"); 
				product_price = parseFloat(product_price + parseFloat(tosum)) ;
				$("#product_price").html(product_price + " Lei"); 
			}
		});
		function(){
			if ($(this).is(':checked'))
			{
				$(this).click();
			}
		}	
	);
	*/
}

function doIsAvailable()
{
	//alert("E disponibil");
	var notVisible = "notVisible";
	$("#product_avvail").removeClass("ch_unavail");
	$("#product_avvail").addClass("ch_avail");
	$("#product_avvail").html(is_in_stoc);

	var ismyavail = $('#product2Cos').attr('rel');
	if (ismyavail == 'indisponibil' )
	{
		//alert("trec pe indisponibil");
		var elem = $("#product2Cos");
		var h = "javascript: if(FormValidation()) document.orderform.submit();";
		elem.removeClass("pccbacks").addClass("pcc").html("<b>PUNE IN COSUL DE CUMPARATURI</b>").attr("href", h).attr("title","PUNE IN COSUL DE CUMPARATURI").attr("rel","disponibil");

	}
	else{
		//alert('las asa');
	}

	return true;
}

function stockNotifyAvailButton(avail, variantid){
	// we love jQuery
	if (avail > 0) {
		doIsAvailable();
	}
	else{
		doNotAvailable(variantid, 1);
	}
}



function clearAllElem(select)
{
select.options.length = 0;
}
function addSelectElem(select, elem)
{
try
{
select.add(elem,null);
}
catch (ex)
{
select.add(elem);
}
}


// functii pentru checkout
function checkoutInit() {
	if (!document.getElementById('cpForm')) {
		return false;
	}

	var isLoginCallback = false;
	var unameTimer = false;
	var aMlivrBusy = false;

	function fieldIsRequired(field) {
		if ('undefined' == typeof(requiredFields)) {
			return false;
		}
		var n = requiredFields.length;
		var i;
		for (i = 0; i < n; i++) {
			// fuck ie
			if (!requiredFields[i] || !requiredFields[i][0]) {
				continue;
			}
			if (field == requiredFields[i][0]) {
				return true;
			}
		}
		return false;
	}

	// TODO -> in fiecare callback sa vedem daca a expirat ceva (sessionid)

	function loginCallback(data, status) {
		//console.log('in login callback', data);
		var root = jQuery(data);
		if (root.length < 1) {
			_animStopLogin();
			return false;
		}
		var error = $('error', root);
		if (error.length >= 1) {
			// avem o eroare
			var text = error.text();
			//console.log(text);
			if (text.search("forgot_password") >= 0) {
				window.location = xcart_web_dir + 'help.php?section=Password_Recovery';
			}
			else if (text.search("disabled") >= 0) {
				window.location = xcart_web_dir + '/error_message.php?disabled';
			}
			else {
				_animStopLogin();
				alert(cpError.err_invalid_login);
			}
			return false;
		}
		// toate bune...

		isLoginCallback = true;

		//
		// sa afisam formular de logout
		//
		$('#coBoxLoginNote').remove();

		// TODO -> preia textul via ajax

		var textForLogout = '<b>' + $('user_data firstname', root).text() + ' ' + $('user_data lastname', root).text() +  '</b> este logat!&nbsp;<input type="button" id="cpLoginButton" class="sbm out" value="IESIRE" />';
		$('#checkoutLoginBox').html(textForLogout);
		_liveLoginBox();

		// sa ascundem user / pass .. chiar o scoatem
		$('#registrationSection').remove();


		//
		// sa prelucram user_data + newslists
		//
		$('user_data > *', root).each(function (){
			//console.log(this.tagName);
			/*
			if (this.tagName != 'ship2firmaI') {
				return true;
			}
			//*/
			//console.log('l-am gasit');
			var t = jQuery(this);
			var elem = jQuery('#' + this.tagName);
			var tagType = elem.attr('tagName');

			if ('INPUT' == tagType) {
				var type = elem.attr('type');
				var val = t.text();
				if ('checkbox' == type) {
					var checked = elem.attr('checked');
					// sa vedem daca tre'sa facem click pe elem;
					// TODO -> vezi daca se poate optimiza aici
					if (!checked && val == 'Y') {
						elem.attr('checked', 'checked').click().attr('checked', 'checked');
					}
					else if (checked && val != 'Y') {
						elem.removeAttr('checked').click().removeAttr('checked');
					}

				}
				else {
					elem.val(t.text());
				}
			}
			else if ('SELECT' == tagType) {
				elem.val(t.text());
			}
			else {
				elem.html(t.text());
			}
			//return false;
		});

		//
		// shipping
		//
		shippingCallback(data, status);

		//
		// payments
		//
		_redisplayPaymentsCallback(data, status);

		isLoginCallback = false;
		_animStopLogin();
	}
	function shippingCallback(data, status) {
		aMlivrBusy = false;
		var root = jQuery(data);

		if (root.length < 1) {
			return false;
		}
		var hasMark = $('no_shipping', root).length;
		if (hasMark > 0) {
			$('#checkoutShippingWait, #checkoutShippingDisplay').css('display', 'none');
			$('#checkoutShippingMessage, #checkoutShippingError').css('display', '');
			return false;
		}

		hasMark = $('free_shipping', root).length;

		$('#checkoutShippingMessage, #checkoutShippingWait, #checkoutShippingError').css('display', 'none');
		$('#checkoutShippingDisplay').html($('shipping_box', root).text()).css('display', '');
		_liveCpSm();

		// caci daca avem isLoginCallback, vom ajunge in changePaymentCallback

		if (!isLoginCallback) {
			_redisplayCartCallback(data, status);
			_animStopCartBox();
		}
		aMlivrBusy = false;
	}
	function changeShippingCallback(data, status) {
		_redisplayCartCallback(data, status);
		_animStopCartBox();
	}
	function changePaymentCallback(data, status) {
		//console.log('intru in changePaymentCallback');
		var root = jQuery(data);
		if (root.length < 1) {
			return false;
		}
		var mark = $('payment_changed_error', root);
		if (mark.length > 0) {
			// stim ca acum avem doar not_found
			// TODO
			alert(cpError.lbl_co_err_payment);
			return;
		}
		_redisplayCartCallback(data, status);
		if (!isLoginCallback) {
			_animStopCartBox();
		}
	}
	function checkUsernameCallback(data, status) {
		_animStopCheckUsername();
		var root = jQuery(data);
		if (root.length != 1) {
			return false;
		}
		root = $('user_ok', root);
		// weepee
		if (root.length >= 1) {
			_showPasswordArea();
			$('#checkoutUsernameUsed').css('display', 'none');
			return;
		}
		$('#checkoutUsernameUsed').css('display', 'block');
	}
	function unsetCouponCallback(data, status) {
		//console.log('am intrat in unsetCouponCallback');
		_redisplayCartCallback(data, status);
		_animStopCartBox();
	}
	function cartContentCallback(data, status) {
		var root = jQuery(data);

		root = jQuery('cart_content', root);

		if (root.length < 1) {
			return false;
		}
		$('#cpScContent').html(root.text());
	}

	function _redisplayCartCallback(data, status) {
		//console.log('am intrat in _redisplayCartCallback');
		// TODO -> vezi direct jQuery(data).children('...')
		var root = jQuery(data);

		// please remember that ckuck norris hates ie :D
		if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7) {
			root = jQuery('cart_box', root);
			if (root.length > 1) {
				root = jQuery(root.get(root.length-1));
			}
		}
		else {
			root = jQuery('cart_box:last', root);
		}
		if (root.length < 1) {
			//console.log('in _redisplayCartCallback nu am cart_box')
			return false;
		}
		if (root.length > 1) {
			root = jQuery(root.get(root.length-1));
		}
		//alert(root.text());
		//alert('4');
		//console.log('voi pune in #checkoutOneTotals: ' + root.text());
		$('#checkoutOneTotals').html(root.text());
		//alert('5');
		_liveCartBox();
		//alert('6');
	}
	function _redisplayPaymentsCallback(data, status) {
		//console.log('intru in _redisplayPaymentsCallback');
		// caci se poate ajunge aici doar via login
		_redisplayCartCallback(data, status);

		var root = jQuery(data);
		var mark = $('payments_not_changed', root);
		if (mark.length >= 1) {
			return false;
		}
		mark = $('no_payments', root);
		if (mark.length >= 1) {
			// TODO -> alert daca e cazul.
			$('#checkoutOneTotals').html('');
			return false;
		}
		if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7) {
			mark = jQuery('payments_box', root);
			if (mark.length > 1) {
				mark = jQuery(mark.get(mark.length-1));
			}
		}
		else {
			mark = jQuery('payments_box:last', root);
		}
		if (mark.length == 1) {
			$('#cpPayments').html(mark.text());
			_livePayments();
		}
	}
	function checkUsername() {
		//console.log('nu uita sa verifici uname si sa arati campul de parola');
		var uname = jQuery.trim($('#uname').val());
		if ('' == uname) {
			_validateMarkWithError('uname');
			return false;
		}
		// TODO -> validari lungime

		_animStartCheckUsername();
		$.get('cart.php?mode=checkout&on=checkout', {
				'request': 'check_uname',
				'c_uname': uname

			}, checkUsernameCallback);
	}
	function _showPasswordArea() {
		$('#passwd1display, #passwd2display, #membershipdisplay').css('display', '');
		$('#passwd1, #passwd2').change(_inputTextChanged);
	}
	function cartBoxDisplay(data) {
		var root = jQuery(data);
		if (root.length != 1) {
			return false;
		}
		var cart = $('cart_box', root);
		if (cart.length < 1) {
			return false;
		}
		$('#checkoutOneTotals').html(cart.text());
		_liveCartBox();
	}
	function _liveLoginBox() {
		$('#cpLoginButton').click(function () {
			var b = jQuery(this);
			if (b.hasClass('out')) {
				window.location = xcart_web_dir + '/include/login.php?mode=logout';
			}
			else {
				//console.log('#cpLoginButton clicked to login');
				var errU = cpIsEmptyField('checkoutUser');
				var errP = cpIsEmptyField('checkoutPass')
				if (errU || errP) {
					var msg = '';
					if (errU) {
						msg += substitute(lbl_required_field_is_empty, 'field', cpError.fields['username']) + '\n';
					}
					if (errP) {
						msg += substitute(lbl_required_field_is_empty, 'field', cpError.fields['password']) + '\n';
					}
					alert(msg);
					if (!errU) {
						$('#checkoutPass').focus();
					}
					else {
						$('#checkoutUser').focus();
					}
					return false;
				}
				_animStartLogin();
				$.get('cart.php?mode=checkout&on=checkout', {
					'request': 'login',
					'username': jQuery.trim($('#checkoutUser').attr('value')),
					'password': jQuery.trim($('#checkoutPass').attr('value'))

				}, loginCallback);
			}
			return false;
		});
	}
	function _liveCpSm() {
		$('.cpSm').click(function() {
			_animStartCartBox();
			$.get('cart.php?mode=checkout&on=checkout', {
				'request': 'change_shipping',
				'shippingid': $(this).attr('value')

			}, changeShippingCallback);
		});
	}
	function _liveCartBox() {
		$('.cpScupon').click(function (){
			var cupon = jQuery(this).attr('id').substr(6);
			_animStartCartBox();
			$.get('cart.php?mode=checkout&on=checkout', {
					'request': 'unset_coupon',
					'cupon': cupon

				}, unsetCouponCallback);
			return false;
		});
		$('.cpVeziC').click(function (){
			showBoxCart();
			return false;
		});
		// TODO -> cpVeziC
	}
	function _livePayments() {
		$('.cpChP').click(function() {
			var t = jQuery(this);
			var value = t.attr('rel');
			$('#cpForm').attr('action', xcart_web_dir + '/payment/' + value);
			value = t.attr('value');
			_showPaymentDiv(value);
			//_animStartCartBox();
			$.get('cart.php?mode=checkout&on=checkout', {
				'request': 'change_payment',
				'paymentid': value
			}, changePaymentCallback);
		});
	}

	function _showPaymentDiv(id) {
		// TODO -> vezi ce faci cu clasele alea..
		$('#cpTrToHide, .cppdiv').removeClass('cpTpShow');

		if (!document.getElementById('template_div' + id)) {
			return false;
		}
		$('#cpTrToHide, #template_div' + id).addClass('cpTpShow');
		//$('#template_' + id).css('display', 'table');
	}

	function showBoxCart() {
		_modalStartTestBrowser();
		$('#cpModalBackground, #cpModalWindow, #cpShowCart').addClass('show');
		$.get('cart.php?mode=checkout&on=checkout', {
				'request': 'cartContent'

			}, cartContentCallback);
		_windowResize();
	}
	function hideBoxCart() {
		$('#cpModalBackground, #cpModalWindow, #cpShowCart').removeClass('show');
		_modalEndTestBrowser();
	}
	function showBoxTerms() {
		_modalStartTestBrowser();
		$('#cpModalBackground, #cpModalWindow, #cpShowTerms').addClass('show');
		_windowResize();
	}
	function hideBoxTerms() {
		$('#cpModalBackground, #cpModalWindow, #cpShowTerms').removeClass('show');
		_modalEndTestBrowser();
	}

	function formSubmit() {
		if (validateForm()) {
			$('#checkoutOrderSubmitted').css('display', '');
			$('#checkoutOrderButton').css('display', 'none');
			document.getElementById('cpForm').submit();
		}
		return false;
	}
	function validateForm() {
		var errorMsg = '';
		var errorSomeFields = false;
		var errorRegistration = false;
		var errorPassCheck = false;
		var errorUsername = false;
		var errorShipping = false;
		var errorPayment = false;
		var errorAgree = false;
		var tmp = false;
		var i;

		// hai sa vedem daca e logat
		var isLogged = $('#registrationSection').length < 1 ? true : false;

		// datele formularului
		if ('undefined' != typeof(requiredFields)) {
			n = requiredFields.length;
			var field = null;
			for (i = 0; i < n; i++) {
				// fuck ie
				if (!requiredFields[i] || !requiredFields[i][0]) {
					continue;
				}
				field = requiredFields[i][0];
				if ('' == $('#' + field).val()) {
					if ((field == 'uname' || field == 'passwd1' || field == 'passwd2') && !isLogged) {
						errorRegistration = true;
					}
					errorSomeFields = true;
					_validateMarkWithError(field, false);
				}
			}
		}

		// TODO -
		// password match

		// TODO username ok ? vezi checkUsernameCallback

		// shipping
		tmp = parseInt($('#checkoutShippingDisplay input[name=shippingid]:checked').val());
		if (isNaN(tmp) || tmp < 1) {
			errorShipping = true;
			//alert('error shipping: ' + tmp);
		}

		// payment
		tmp = parseInt($('#paymentOptions input[name=paymentid]:checked').val());
		if (isNaN(tmp) || tmp < 1) {
			//alert('error payment: ' + tmp);
			errorPayment = true;
		}

		// agree to terms
		if ($('#agree_to_terms:checked').length < 1) {
			errorAgree = true;
		}

		if (errorSomeFields) {
			errorMsg += '&bull; ' + cpError.errorSomeFields + '<br />';
		}
		if (errorRegistration) {
			errorMsg += '&bull; ' + cpError.errorRegistration + '<br />';
		}
		if (errorPassCheck) {
			errorMsg += '&bull; ' + cpError.errorPassMatch + '<br />';
		}
		if (errorUsername) {
			errorMsg += '&bull ' + cpError.errorUsername + '<br />';
		}
		if (errorShipping) {
			errorMsg += '&bull; ' + cpError.errorShipping + '<br />';
		}
		if (errorPayment) {
			errorMsg += '&bull; ' + cpError.errorPayment + '<br />';
		}
		if (errorAgree) {
			errorMsg += '&bull; ' + cpError.errorAgree + '<br />';
		}
		if (errorMsg == '') {
			return true;
		}

		$('#checkoutErrorDescription').html(errorMsg);
		$('#checkoutErrorDisplay').css('display', '');
		window.location = '#root';
		return false;
	}
	function _validateMarkWithError(field, focusIt) {
		$('#img_' + field).html('<img alt="" src="' + images_dir + '/checkout_one_error_x.gif" />');
		if (focusIt) {
			$('#' + field).addClass('cpMIr').focus();
		}
		else {
			$('#' + field).addClass('cpMIr');
		}
		//console.log('va trebui sa marchez ' + field + 'ca fiind cu eroare');
	}
	function calculateShippings(doNotAlert){
		if (aMlivrBusy) {
			return false;
		}
		var reqFields = ['state', 'country', 'conty', 'zipcode', 'city'];
		var prefix = 'b_';
		var shipTo = 'b';
		if ($('#ship2diff').attr('checked')) {
			prefix = 's_';
			shipTo = 's';
		}

		var n = reqFields.length;
		var i;
		var f = '';
		var v = '';

		var values = new Array();
		//console.log(reqFields, n);

		var isError = '';

		for (i = 0; i < n; i++) {
			f = prefix + reqFields[i];
			v = $(('#' + f)).val();
			//console.log(v + ' ' + f + ' ' + reqFields[i] + ' ' + i);
			if ('' == v && ('city' == reqFields[i] || fieldIsRequired(f))) {
				aMlivrBusy = false;
				_shippingShowButtonToCalculate();
				if (!doNotAlert) {
					_validateMarkWithError(f, true);
					alert(substitute(lbl_required_field_is_empty, 'field', cpError.fields[reqFields[i]]));

				}
				return false;
			}
		}

		_animStartCalculateShipping();

		$.get('cart.php?mode=checkout&on=checkout', {
				'request': 'shipping',
				'shipTo': shipTo,
				'state': $('#' + prefix + 'state').val(),
				'country': $('#' + prefix + 'country').val(),
				'conty': $('#' + prefix + 'conty').val(),
				'zipcode': $('#' + prefix + 'zipcode').val(),
				'city': $('#' + prefix + 'city').val()

			}, shippingCallback);
		return false;
	}
	function _shippingShowButtonToCalculate() {
		$('#checkoutShippingWait, #checkoutShippingDisplay, #checkoutShippingError').css('display', 'none');
		$('#checkoutShippingMessage').css('display', '');
	}

	function _animStartCalculateShipping() {
		$('#checkoutShippingWait').css('display', '');
	}
	function _animStopCalculateShipping() {
		$('#checkoutShippingWait').css('display', 'none');
	}

	function _animStartCartBox() {
		$('#checkoutOneTotals').css('display', 'none');
		$('#checkoutTotalsWait').css('display', '');
	}
	function _animStopCartBox() {
		$('#checkoutOneTotals').css('display', '');
		$('#checkoutTotalsWait').css('display', 'none');
	}

	function _animStartCheckUsername() {
		$('#checkoutUsernameWait').css('display', '');
	}
	function _animStopCheckUsername() {
		$('#checkoutUsernameWait').css('display', 'none');
	}

	function _animStartLogin(){
		_modalStartTestBrowser();
		$('#cpModalBackground, #cpModalWindow, #cpWaitLogin').addClass('show');
		_windowResize();
	}
	function _animStopLogin(){
		$('#cpModalBackground, #cpModalWindow, #cpWaitLogin').removeClass('show');
		_modalEndTestBrowser();
	}

	function _modalStartTestBrowser() {
		if ($.browser.msie && parseInt($.browser.version) < 7) {
			$('select').addClass('cpShide');
		}
	}
	function _modalEndTestBrowser() {
		if ($.browser.msie && parseInt($.browser.version) < 7) {
			$('select').removeClass('cpShide');
		}
	}

	function _windowResize() {
		// todo -> foloseste jQuery
		var top;
		var left;
		if (document.documentElement.scrollTop < 1) {
			left = document.body.scrollLeft;
			top  = document.body.scrollTop;
		}
		else {
			left = document.documentElement.scrollLeft;
			top  = document.documentElement.scrollTop;
		}
		var div = document.getElementById('cpModalWindow');
		var windowHeight = _getWindowHeight();
		//alert(top + ' ' + div.offsetHeight + ' ' + windowHeight);
		div.style.left = Math.max((left+(_getWindowWidth()-div.offsetWidth)/2),0)+'px';
		div.style.top  = Math.max((top+(_getWindowHeight()-div.offsetHeight)/2),0)+'px';
		$('#cpModalBackground').css('height', (document.getElementsByTagName('body')[0].offsetHeight-50) + 'px');
	}
	function _getWindowWidth(){
		var width=document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth || document.body && document.body.parentNode && document.body.parentNode.clientWidth || 0;
		return width;
	}
	function _getWindowHeight() {
		if(window.innerHeight) return window.innerHeight;
		else return document.documentElement.clientHeight;
	}

	$('.cpMhide').click(function (){
		var t = jQuery(this);
		if (t.hasClass('cart')) {
			hideBoxCart();
		}
		else if (t.hasClass('terms')) {
			hideBoxTerms();
		}
		return false;
	});
	$('.show_box').click(function (){
		var t = jQuery(this);
		var showBox = t.attr('checked');
		if (showBox) {
			$("#" + t.attr('id') + '_s_box' ).css('display', '');
		}
		else {
			$("#" + t.attr('id') + '_s_box' ).css('display', 'none');
		}
	});
	$('#uname').keyup(function (){
		clearTimeout(unameTimer);
		unameTimer = setTimeout(checkUsername, 1000);
	});
	$('#aMlivr').click(function () {
		calculateShippings(false);
		return false;
	});
	$('#ship2diff').click(function () {
		if (isLoginCallback) {
			return false;
		}
		_shippingShowButtonToCalculate();
	});
	$('#b_state, #b_country, #b_conty, #b_zipcode, #b_city, #s_state, #s_country, #s_conty, #s_zipcode, #s_city').change(function () {
		if (isLoginCallback) {
			return false;
		}
		calculateShippings(true);
	});
	$('#cpSbm').click(function () {
		formSubmit();
		return false;
	});
	$('.cpVeziT').click(function (){
		showBoxTerms();
		return false;
	});
	$('.cpBterms').click(function (){
		hideBoxTerms();
		if (jQuery(this).hasClass('yes')) {
			$('#agree_to_terms').attr('checked', 'checked');
		}
		else {
			$('#agree_to_terms').removeAttr('checked');
		}
		return false;
	});

	function _inputTextChanged() {
		if (isLoginCallback) {
			return false;
		}
		var t = jQuery(this);
		if (jQuery.trim(t.val()) != '') {
			t.removeClass('cpMIr');
			$('#img_' + t.attr('id')).html('');
		}
	}
	$('.coInnerBoxDoSpLeft table tr td input[type=text]').change(_inputTextChanged);

	function _liveTextInputs(unbindFirst) {
	}

	function cpIsEmptyField(id, value) {
		var elem = $("#" + id);
		if (elem.length != 1) {
			return true;
		}
		var val = jQuery.trim(elem.attr('value'));
		if (val == '' || val == elem.attr('alt')) {
			return true;
		}
		return false;
	}

	_liveTextInputs(false);

	_liveLoginBox();
	_liveCpSm();
	_liveCartBox();
	_livePayments();
}

// sfarsit functii ptr checkout