var timeout_info = false;
var lclick = '';

check_cart = function() {
	var przbe = $("#sel_p").val();
	var size = $("#sel_r").val();


	var errnum = 0;
	if ($('#rprzb').length > 0) {
		if (przbe == null || przbe.length < 1) {
			$('#rprzbc').show();

			$('#rprzbc').addClass('eerr');
			$('#rprzbc').html(_lang['choose_przb']['txt']);
			errnum++;
		}
		else {
			$('#rprzbc').removeClass('eerr');
			$('#rprzbc').html('');
			$('#rprzbc').hide();
		}
	}

	if ($('#rroz').length > 0) {
		if (size == null || size.length < 1 && przbe != 'bez-przebicia') {
			$('#rrozc').show();
			$('#rrozc').addClass('eerr');
			$('#rrozc').html(_lang['choose_size']['txt']);
			errnum++;
		}
		else {
			$('#rrozc').removeClass('eerr');
			$('#rrozc').html('');
			$('#rrozc').hide();
		}
	}

	if (errnum > 0) {
		show_info('cart_invalid_data');
		return false;
	}
	else {
		return true;
	}
}

toggle_cat = function(cat_id) {

	if ( $('#sub' + cat_id).css('display') == 'none' ) {
		$('.catalog .level1').hide('normal');
		$('#sub' + cat_id).show('normal');

		return false;
	}


}


o_type = function(v){
	if (v == 1) {
		$('#customer-details').hide();
	}
	else {
		$('#customer-details').show();
	}

	for (i = 1; i < 4; i++) {
    if (i == v) {
      $('#otypeli' + i).addClass('actlie');
      $('#otypeli' + i).removeClass('nohov');
    }
    else {
      $('#otypeli' + i).removeClass('actlie');
      $('#otypeli' + i).addClass('nohov');
    }
  }
  $('#otp').val(v);
}

select_delivery = function(v) {
	$('#delivery').html('+ ' + v);

}

select_dv = function(id) {
$('#payment_option1').show();
$('#payment_option2').show();
$('#payment_option3').show();

	if (id == 2) {
	 $('#payment_option3').hide();
	 $('#pym2').click();
	}


	if (id == 3) {
	 $('#payment_option1').hide();
	 $('#payment_option2').hide();
	 $('#pym3').click();
	}


	if (id == 1) {
	 $('#payment_option3').hide();
	 $('#pym1').click();
  }

	if (id == 5) {
	 $('#payment_option1').hide();
	 $('#payment_option2').hide();
	 $('#pym3').click();
	}

}

select_active = function(cur_selected, classc) {
	$('.' + classc).removeClass('act');
	$('#' + cur_selected).addClass('act');
}

add_cart_product = function(product_id, price, price_wc) {

	var przbe = $("#sel_p").val();
	var size = $("#sel_r").val();
	var num = parseInt($('#product_num').val());
	show_info('please_wait');

	if (check_cart() == true){
		$.ajax({
			type: "POST",
			url: _BASE_URL + "koszyk/dodaj/",
			data: "product_id=" + product_id + "&product_num=" + num + "&product_size=" + size + "&product_przb=" + przbe,
			dataType: 'json',
			success: function(msg) {

				if (parseInt(msg.success) == 1) {
					update_cart_items(msg.other.cart_items);
					update_cart_value(msg.other.cart_value);
					document.location.href = _BASE_URL + 'koszyk';
				}
				else {
					show_info('k2');
				}
			},
			error: function() {
				//show_info('o1');
			}
		});
	}
	return false;
}

sort_item = function(item_name) {
	show_info('please_wait');
		$.ajax({
			type: "POST",
			url: _BASE_URL + "operacje/sortowanie/",
			data: "sort_item=" + item_name,
			dataType: 'json',
			success: function(msg) {
				document.location.reload();
			}
		});
	return false;
}

register_type = function(el, i) {
	if (el.checked == true && i == 1) {
		$('#dperson').show('normal');
		$('#dcompany').hide('normal');
	}
	if (el.checked == true && i == 2) {
		$('#dperson').hide('normal');
		$('#dcompany').show('normal');
	}

}

sign = function() {

	$('#panel-unauthorized').animate({
		 height: 0, easing: 'swing', opacity: 0
	}, 400, "linear", function(){ $('#panel-unauthorized').hide();

		$('#sign-area').show();
	$('#sign-area').animate({
		height: 120, easing: 'swing', opacity: 100
	}, 700, "linear", function(){} );
	} );



	return false;
}

waddress_toggle = function(e) {
	if (e.checked) {
		$('#waddress').hide('normal');
	}
	else {
		$('#waddress').show('normal');
	}
}

sign_action = function() {
	show_info('please_wait');
	var email = $('#signmail').val();
	var password = $('#signpassword').val();

	if (email.match(/([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4})/gi) && password.length > 3) {
		$.ajax({
			type: "POST",
			url: _BASE_URL + "konto/logowanie_json/",
			data: {'email': email, 'password': password},
			dataType: 'json',
			success: function(msg) {

				if (msg.success == 1) {
					document.location.reload();
				}
				else {
					show_info('sign_invalid');
				}
			}
		});
	}
	else {
		show_info('sign_invalid');
	}
	return false;
}

sign_action_in = function() {
	show_info('please_wait');
	var email = $('#signmail_in').val();
	var password = $('#signpassword_in').val();

	if (email.match(/([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4})/gi) && password.length > 3) {
		$.ajax({
			type: "POST",
			url: _BASE_URL + "konto/logowanie_json/",
			data: {'email': email, 'password': password},
			dataType: 'json',
			success: function(msg) {

				if (msg.success == 1) {
					document.location.reload();
				}
				else {
					show_info('sign_invalid');
				}
			}
		});
	}
	else {
		show_info('sign_invalid');
	}
	return false;
}

reload_cart = function() {
	document.location.href = _BASE_URL + 'koszyk';
}

cart_change_amount = function(element, item_id) {
	if (parseInt($(element).val()) > 0) {
		show_info('please_wait');

		$.ajax({
			type: "POST",
			url: _BASE_URL + "koszyk/zmien_ilosc/",
			data: "item_id=" + item_id + '&item_amount=' + $(element).val(),
			dataType: 'json',
			success: function(msg) {

				if (msg.success == 1) {
					//$('#cart_row' + item_id).hide();


					update_cart_items(msg.other.cart_items);
					update_cart_value(msg.other.cart_value);

					setTimeout(reload_cart, 3000);
					show_info('cart_change_amount_ok');
					if (msg.other.cart_item) {

						$('#itemtotal'+msg.other.cart_item).html(msg.other.cart_item_value);
					}
				}
				else {
					show_info('k2');
				}
			}
		});
	}
	return false;
}

remove_cart_item = function(item_id) {
	show_info('please_wait');
	$.ajax({
		type: "POST",
		url: _BASE_URL + "koszyk/usun/",
		data: "item_id=" + item_id,
		dataType: 'json',
		success: function(msg) {

			if (msg.success == 1) {
				//$('#cart_row' + item_id).hide();

				$('#cart_row' + item_id+ '').animate({
				       opacity: 0
				    }, 900, "linear", function(){ $('#cart_row' + item_id+ '').hide(); } );

				update_cart_items(msg.other.cart_items);
				update_cart_value(msg.other.cart_value);

				if (msg.other.cart_items == 0) {
					$('#ccart').html('<div class=kom>Koszyk jest pusty.</div>');
				}
				//document.location.href = _BASE_URL + 'koszyk';
				show_info('cart_delete_product_ok');
			}
			else {
				show_info('k2');
			}
		}
	});
	return false;
}

// Show CSS information layer
show_info = function(info_id) {
	clearTimeout(timeout_info);

	$('#einfo').html(_lang[info_id]['txt']);
	$('#einfo').animate({
	       opacity: 1, top: 70
	    }, 300, "linear", function(){ timeout_info = setTimeout(hide_info, 3000); } );
}

hide_info = function() {
	$('#einfo').animate({
	       opacity: 0, top: -20
	    }, 200, "linear", function(){ } );
}

update_cart_items = function(items_num) {
	$('#ecart-num-items').html(parseInt(items_num) + ' elementów');
}

update_cart_value = function(value) {
	$('#ecart-value').html(value + ' zł');
	$('.cart-value-order').html(value);
}

// Event onLoad page
$(document).ready(function(){
/*
	$.NiceJForms.build({
		imagesPath: _BASE_URL + 'static/images/form/'
	});
*/
	if (_FLASH_INFO != 0) {
		show_info(_FLASH_INFO);
	}


	update_cart_items(_CART_ITEMS);


	if (_CART_VALUE) {
		update_cart_value(_CART_VALUE);
	}
	if ($('#email').length > 0) if ( $('#email').val().length == 0) $('#email').defaultvalue("np.: jan@kowalski.pl");
	if ($('#phone').length > 0) if ($('#phone').val().length == 0) $('#phone').defaultvalue("np.: 600123456");
	if ($('#post_code').length > 0) if ($('#post_code').val().length == 0) $('#post_code').defaultvalue("np.: 00-000");
	if ($('#wpost_code').length > 0) if ($('#wpost_code').val().length == 0) $('#wpost_code').defaultvalue("np.: 00-000");
	if ($('#company_nip').length > 0) if ($('#company_nip').val().length == 0) $('#company_nip').defaultvalue("np.: 679-000-00-00");

	h1replace();
	h2replace();
	$('a.help-ico').tooltip({
		track: false,
	    showURL: false,

	    bodyHandler: function() {
	        return '';
	    },
	    extraClass: "help-tip",

	    fixPNG: true
	});


	$("img").pngfix({
		sizingMethod: "scale"
	});

	$('.articles .art-more').click(function () {

		$('.article-more').hide('sexy');
		$('.art-less').show('sexy');
	 if ($(this).hasClass('art-title')) {
		$('#'+$(this).parent().attr('id')+' .article-more').show('sexy');
		$('#'+$(this).parent().attr('id')+' .art-less').hide('sexy');
	 } else {

		$('#'+$(this).parent().parent().parent().attr('id')+' .article-more').show('sexy');
		$('#'+$(this).parent().parent().parent().attr('id')+' .art-less').hide('sexy');
   }

		return false
	});

  if ($('#kdinfo').length > 0) {
		var soq = new SWFObject(_BASE_URL + "static/swf/kdinfo.swf", "mymovie", "655", "29", "8", "#FFFFFF");
		soq.addParam("quality", "high");
		soq.addParam("wmode", "transparent");

		soq.write("kdinfo");
	}

	if (document.location.href.match('#art')) {
    e = document.location.href.split('#ar');
		$('#ar'+e[1]+' .article-more').show('sexy');
		$('#ar'+e[1]+' .art-less').hide('sexy');
  }

	$('#h-type li').each(function () {
		var cls = $(this).attr('class')
		var t = $(this)
		$('<img />').attr('id', cls).addClass('h-preview').attr('src', '/static/images/przebicia/'+cls+'.gif').appendTo('#h-preview')
		$(this).click(function () {
			$('#h-preview').css({background: 'none'})
			$('#h-type li input').removeAttr('checked')
			$('#h-type li').removeClass('current-prev')
			$(t).addClass('current-prev')
			$('input', t).attr('checked', 'checked')
			$('#h-preview .current-prev').animate({left: -135}).removeClass('current-prev')
			$('#'+cls).animate({left: 10}).addClass('current-prev')
			selr($('input', t).attr('rel'))
			selp($('input', t).val())
		})
	})

});

h1replace = function() {
	var elements = $('.h1-flash');
	for (i = 0; i < elements.length; i++) {
		var so = new SWFObject(_BASE_URL + "static/swf/h1-flash.swf", "mymovie", "550", "50", "8", "#FFFFFF");
		so.addParam("quality", "high");
		so.addParam("wmode", "transparent");
		so.addVariable("label", elements[i].innerHTML);

		so.write(elements[i]);

	}

}


h2replace = function() {
	var elements = $('.h2-flash');
	for (i = 0; i < elements.length; i++) {
		var so = new SWFObject(_BASE_URL + "static/swf/h2-flash.swf", "mymovie", "550", "40", "8", "#FFFFFF");
		so.addParam("quality", "high");
		so.addParam("wmode", "transparent");
		so.addVariable("label", elements[i].innerHTML);

		so.write(elements[i]);

	}

}

price_format = function(num)
{
    var n = num.toString();
    var nums = n.split('.');
    var newNum = "";
    if (nums.length > 1)
    {
        var dec = nums[1].substring(0,2);
        newNum = nums[0] + "." + dec;
    }
    else
    {
    newNum = num;
    }
	return newNum;
}


price_calc = function() {
	var przb = $("#sel_p").val();
	var size = $("#sel_r").val();
	var num = parseInt($('#product_num').val());


	if ($('#rroz').length > 0) {
		elements_size = $('.lblr');
		for (i = 0; i < elements_size.length; i++) {
			csize = $(elements_size[i]).attr('rel');
			$(elements_size[i]).attr('src', _BASE_URL + 'static/images/sizes/' + csize + '.gif');

		}
		//$('#lbr'+size).attr('src', _BASE_URL + 'static/images/sizes/' + size + '-on.gif');
		$('.sxc span').removeClass('on');
		$('#lbq'+size).addClass('on');
		//$('#lbq'+size).removeClass('off');
	}

	if ($('#rprzb').length > 0) {
		elements_przb = $('.przebs');
		for (i = 0; i < elements_przb.length; i++) {
			cprz = $(elements_przb[i]).attr('rel');

			$(elements_przb[i]).attr('src', _BASE_URL + 'static/images/przeb/' + cprz + '.gif');

		}
		//$('#przbrt'+przb).attr('src', _BASE_URL + 'static/images/przeb/' + przb + '-on.gif');
		//$('#przbrt'+przb).addClass('on');
		$('.sxp span').removeClass('on');
		$('#przbrt'+przb).addClass('on');
		//$('#przbrt'+przb).removeClass('off');
	}



	if (check_cart() == true){

		if (isNaN(num)) {
			num = 1;
		}

		if (przb == 'wc' && _PRODUCT_PRICE_WC > 0) {
			$('#total_sum').html(price_format(_PRODUCT_PRICE_WC*num));
		}
		if (przb != 'wc' && _PRODUCT_PRICE > 0) {
			$('#total_sum').html(price_format(_PRODUCT_PRICE*num));
		}
	}
	return false;
}

selp = function(val) {
	$('#sel_p').val(val);
	price_calc();
}

gmail = function(pre) {
	document.location.href = 'mailto:' + pre +'@klamki-drzwiowe.pl';
	return false;
}

selr = function(val) {
	$('#sel_r').val(val);
	price_calc();
}

clickLi = function(el) {

  eval($('#'+el).attr('onclick').toString().replace('function onclick(event) {','if ($(\'#'+el+'\').checked){').replace('if (this.checked) {','').replace('}','').replace("\n", " ").replace("\n", " ").replace("\n", " ").replace("\n", " ").replace("\n", " ").replace("\n", " ").replace("\n", " "));

}

$(document).ready(function () {

	var errors = $('.error, .eerr');
	if (errors.size() > 0) {
		$('html, body').animate({scrollTop: errors.eq(0).position().top}, 2000, function () {
			errors.eq(0).addClass('pulsate')
			function pulsate() {
				$(".pulsate").
					animate({opacity: 0.2}, 1000).
					animate({opacity: 1}, 1000, pulsate);
			}
			pulsate();
		})
	}

})

