function changeSortType(x){
	window.location = xcart_web_dir + "/" + x.options[x.selectedIndex].value;
}
function checkAvail(){
	//alert("intru in functia checkAvail");
	//console.log('din checkAvail');
	if( document.getElementById('product_avail') )
	{
		if( parseInt(document.getElementById('product_avail').options[0].value) >= min_avail ) doIsAvailable();
		else {
			doNotAvailable(0, 0);
		}
	}
}
function doNotAvailable(variantid, pSnAB){
	//alert("Nu e disponibil");
	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

	var i = "indisponibil";
	if (variantid) {
		var h = xcart_web_dir + "/stock_notify.php?productid=" + $("h1.title").attr("id").substr(5) + "&variantid=" + variantid;
	}
	else{
		var h = xcart_web_dir + "/stock_notify.php?productid=" + $("h1.title").attr("id").substr(5);
	}
	$("#txt_produs_avail").addClass(i);
	$("#txt_produs_avail").html("Produs indisponibil");

	var elem = $("#product2Cos");

	if(pSnAB == 1){
		elem.addClass(i).html("Cere produsul in stoc").attr("href", h);
	}
	else{
		elem.addClass(i).html("Cere produsul in stoc");
	}

	//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 doIsAvailable(){
	//alert("E disponibil");
	var i = "indisponibil";
	$("#txt_produs_avail").removeClass(i);
	$("#txt_produs_avail").html("Produs disponibil in stoc");
	$("#product2Cos").removeClass(i).html("Adauga la cosul tau").attr("href", "#ADAUGA LA COSUL TAU");
	return true;
}

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

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

function productInit(){
	if( $("#product2Cos").length != 1){
		return;
	}

	$("#product2Cos").click(function(){
		if ($(this).hasClass("indisponibil")) {
			return true;
		}
		if (FormValidation()) {
			document.orderform.submit();
		}
		return false;
	});
	$(".maresteImaginea").click(function(){
		$("#cntPoze a:first").click();
		return false;
	});
	$("#veziEticheta").click(function(){
		$("#cntPozeE a:first").click();
		return false;
	});

	tb_init('a.thickbox');
	// preload image
	imgLoader = new Image();
	imgLoader.src = tb_pathToImage;
}
function cartInit(){
	$(".sCq").change(function(){
		$("#cartForm").submit();
	});
	$("#shippingChanger").change(function(){
		$("#theShippingId").val(jQuery(this).val());
		$("#cartForm").submit();
	});
	$('.wpPrC').each(function (){
		var w = jQuery(this);
		var h = $('.p', w).height();
		if (h > 51) {
			var pT = (h-30)/2;
			$('.pret', w).css({'height': (h-pT)+'px', 'padding-top': pT+'px'});
			h = (h - 51) / 2;
			$('.poza, .cantitate, .sterge', w).css('margin-top', h + 'px');
		}
	});
	$('.eOpt').click(function() {
		window.open(jQuery(this).attr('href'),'POptions','width=400,height=350,toolbar=no,status=no,scrollbars=yes,resizable=no,menubar=no,location=no,direction=no');
		return false;
	});
}

function menuPinit(){
	var selectedClass = "";
	var inClass = "";
	var timer = null;

	function casutaTimer() {
		//console.log('in casutaTimer ' + inClass + ", " + selectedClass );
		if (selectedClass == "" || (inClass == selectedClass)) {
			//console.log(' nu fac nimic in casutaTimer');
			return false;
		}
		hideClass(selectedClass);
	}
	function hideClass(cls){
		$("#menus div." + cls).css("display", "none");
	}
	function markHideClasses(){
		inClass = selectedClass = "";
	}

	$("#meniuP li a").hover(
		function() {
			clearTimeout(timer);
			var cls = $(this).parents("li").attr("class");
			if(inClass) {
				hideClass(inClass);
			}
			if(selectedClass){
				hideClass(selectedClass);
			}
			markHideClasses();
			selectedClass = cls;
			$("#menus div." + selectedClass).css("display", "block");

			//console.log(selectedClass + ' menu in');
		},
		function() {
			// $("#menus div." + selectedClass).css("display", "none");
			//console.log(selectedClass + ' menu out');
			timer = setTimeout(function(){casutaTimer();}, 100);
		}
	);
	$("#menus div.casuta").hover(
		function(){
			inClass = $(this).attr("class");
			inClass = inClass.substr(7);
			//console.log(inClass + ' casuta in');
		},
		function(){
			hideClass(inClass);
			markHideClasses();
			//console.log(inClass + ' casuta out');
		}
	);
}

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();
    }
  });
}

// 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('alt');
			$('#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-10) + '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


$(function(){
	$(".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;}
			 }
		 }
	 });
	productInit();
	menuPinit();
	checkoutInit();
	$('input:text').hint();
});