/*
  	One program in that packed thing is:
	Masked Input plugin for jQuery
	Copyright (c) 2007-2009 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) 
	Version: 1.2.2 (03/09/2009 22:39:06)
*/
var timestampBasketAdd = -1;
var timeStampAnimation = -1;
var krok = 1;
var position = -1;
var sposob_wysylki = readCookie("sposob_wysylki") ? readCookie("sposob_wysylki") : "online";
var sposob_zaplaty = readCookie("sposob_zaplaty") ? readCookie("sposob_zaplaty") : "dotpay";
var przesylkaGratis = false;
var loggedInVersion = false;
var prePrice = "";
$("document").ready(function() {
   if ((window.location.href).indexOf("sklep-online") == -1)
	init();
});
document.onkeydown = tabingItems;
function init() {
	
    watchMovieAnimation();
    create_basket();//
    shopping_add_button();
    insert_existing_items();
    addBasket();
    tooltip();
    removingAnimations();
    opacityForThumbs();
    loginForm();
	input_change($("#opis_kursu"));
		
	if (window.XMLHttpRequest) 
	$(window).scroll(function(evt) {
		setVideoToMiddle('#film');
		setPanelLoginAdmin('#panelAdministracyjnyContainer');
	});
	
	ieFixes();

	ajax_loader();
}
function watchMovieAnimation() {
    $("#thumbVideoContainer img").css("opacity", 0.6);
    $("#thumbVideoContainer img").hover(function() {
        $(this).css("opacity", 1.0)
    }, function() {
        $(this).css("opacity", 0.6)
    })
}

function create_basket() {
    var basketObj = $('<div id="basket_container"><a id="zamowienie_header" title="Przejdź do zamówienia" class="tooltip" href="#"><div class="basket_headers"><img width="16" height="16"  id="basket_icon_small" src="images/basket_icon_small.gif"/><span class="small_basket_header">Koszyk:</span><div class="price_header">Cena:</div></div></a><table class="produkty_w_koszyku"><tr class="produkt"><td class="productNames"><a href="#" class="sendmessage tooltip" rel="nofollow" title="&lt;b>Dostawa online jest całkowicie bezpłatna&lt;/b>. &lt;br />&lt;br />Zamów kursy w wersji pudełkowej (DVD) za łączną wartość przekraczającą &lt;b>75 zł&lt;/b>, a przesyłka będzie &lt;b>GRATIS&lt;/b>! :-) Naciśnij na &lt;b>dostawę&lt;/b>, aby uzyskać szczegółowe informacje."><img width="12" height="12" class="tick_products" src="images/mail_tick.gif" /><span class="nazwa">Dostawa</span></a></td><td><div class="priceOfProduct">0 zł</div></td></tr></table><div class="fullPriceField"> Razem: <span class="fullPrice">0 zł</span></div><div id="zamowienie" class="tooltip" rel="nofollow" title="Przejdź do zamówienia">Zamówienie</div></div>');
    $("#top_background").prepend(basketObj);
    $("#zamowienie, #zamowienie_header").click(function() {
        showMessage("order");
        return false;
    });
    $(".sendmessage").click(function() {
        showMessage("sending");
        return false;
    })
}

function shopping_add_button() {
    hoverSrcEffect(".add_kurs", "images/dodaj_do_koszyka_hover.gif", "images/dodaj_do_koszyka.gif")
}

function addBasket() {
    $("[class^='AB'], [class^='add_kurs'], [class^='AL']").click(function(e) {
		
		var courseType;
		var pojLekcja = false;
		$("#opis_kursu input").each(function() //checking what the type of course is
		{
			if ($(this)[0].checked)
				courseType = $(this).attr("value");	
		});
		
		if ($(this).attr("class").indexOf("AL") > -1)
		{
			courseType = "online";
			pojLekcja = true;
		}		
		
			
       	if (($("#basket_container .productNames")[0].innerHTML).indexOf(courseType) < 0) //we can have only one version of course online | DVD, it's enough to check the first one, because next one is for sure the good one
		{	
			initBox("lib/error_message/only_one_version_at_time.html", true);
			return;
		}
	   	var productId;
	    if (!pojLekcja)
	    	productId = parseInt($(this).attr("class").slice($(this).attr("class").indexOf("AB") + ("AB").length, $(this).attr("class").lastIndexOf(" ")));
		else
			productId = parseInt($(this).attr("class").slice($(this).attr("class").indexOf("AL") + ("AL").length, $(this).attr("class").lastIndexOf(" ")));
			
		
		if (courseType == "online") 
		{
			sposob_wysylki = "online";
			createCookie("sposob_wysylki", sposob_wysylki, 30);
		}
		else 
		{
			if (sposob_wysylki == "online") 
			{
				sposob_wysylki = "priorytet_polecony";
				createCookie("sposob_wysylki", sposob_wysylki, 30);
			}
		}
		
        if (timestampBasketAdd == -1) 
            timestampBasketAdd = e.timeStamp;
        else timestampBasketAdd = e.timeStamp - timestampBasketAdd;
        if (timestampBasketAdd > 1500) 
        {
            var basket = $("#basket_container");
            basket.show(400);
			if (!pojLekcja)
			{
	            var coursePhoto = $(".zdjecie_kursu");
	            var courseClone = $(".zdjecie_kursu").clone(true);
			}
			else
			{
	            var coursePhoto = $(".AL"+productId);				
	            var courseClone = $(".AL"+productId).clone(true);
			}
            $(window).scrollTop(0);
            courseClone.css("position", "absolute").css("top", coursePhoto.position().top + "px").css("left", coursePhoto.position().left + "px").css("z-index", 999);
            courseClone.prependTo("body");
            courseClone.animate(
            {
                "top": basket.position().top + "px",
                "left": basket.position().left + "px",
                "opacity": 0
            }, 500, function() {
                courseClone.remove();
                addItemToBasket(productId, courseType, pojLekcja);
            });
            basket.scrollTop(0)
        }
        timestampBasketAdd = e.timeStamp;
        return false
    })
}

function removeBasket() {
    $("#basket_container").hide(400, function() {
        $("tr[class*='rm']", this).remove();
    })
}

function removingAnimations() {
    $("#basket_container .produkt:not(.produkt:last), #basket_container_b .produkt:not(.produkt:last)").unbind("hover");
    $("#basket_container .produkt:not(.produkt:last), #basket_container_b .produkt:not(.produkt:last)").hover(function() {
        $(".tick_products", $(this)).attr("src", function() {
            return "images/remove_product.gif"
        })
    }, function() {
        $(".tick_products", $(this)).attr("src", function() {
            return "images/tick.gif"
        })
    })
}

function addItemToBasket(productId, courseType, pojLekcja) {
	var myObject;
		
    if ($("#messageWindow").length) 
    {
        $("#messageWindow").hide().remove()
    }
	
    $.ajax(
    {
        url: "lib/getproduct.php",
        type: 'POST',
        async: false,
        cache: false,
        data: 
        {
            "productId": productId,
			"courseType": courseType,
			"pojLekcja": pojLekcja
        },
        timeout: 10000,
        success: function(myJSONtext) {
            if (myJSONtext) 
               myObject = eval('(' + myJSONtext + ')');
            if (myObject) 
            {
                var cena = myObject[0]['cena'];
                var skrocona_nazwa = myObject[0]['nazwa_skrocona'];
                var insertedId = myObject[0]['insertedId'];
                var nazwa_strony = myObject[0]['nazwa_strony'];				
				var lekcja = myObject[0]['lekcja'];
				if (!lekcja) 
					var obj = $("<tr class='produkt rm" + insertedId + "'><td class='productNames'><img width='12' height='12' class='tick_products tooltip rm" + insertedId + "' src='images/tick.gif' title='Usuń Kurs " + skrocona_nazwa + " z koszyka' /><span class='nazwa'><a href='" + nazwa_strony + "' class='tooltip' title='Kliknij by przejść na stronę opisu kursu " + skrocona_nazwa + "'>" + skrocona_nazwa + "</a></span></td><td><div class='priceOfProduct'>" + cena + " zł</div></td></tr>");
				else 
				{	
					var labelId = myObject[0]['labelId'];
					var obj = $("<tr class='produkt rm" + insertedId + "'><td class='productNames'><img width='12' height='12' class='tick_products tooltip rm" + insertedId + "' src='images/tick.gif' title='Usuń Kurs " + skrocona_nazwa + " z koszyka' /><span class='nazwa'><a href='" + nazwa_strony + "#AL" + labelId + "' class='tooltip' title='Kliknij by przejść na stronę opisu kursu " + skrocona_nazwa + "'>" + skrocona_nazwa + "</a></span></td><td><div class='priceOfProduct'>" + cena + " zł</div></td></tr>");
				}				
                
                $(".priceOfProduct", obj).addClass("PC" + cena);
                obj.css("opacity", 0);
                $(".produkty_w_koszyku").prepend(obj);
                $("img.rm" + insertedId).click(function() {
                    removeItemFromBasket(insertedId)
                });
                obj.animate(
                {
                    "opacity": 1.0
                }, 400, function() {
                    setPrice(countPrice());
                   	removingAnimations();
                    tooltip(obj);
                    if ((75 - countPrice() + 6) > 0) 
                        przesylkaGratis = false
					
					createCookie("anything_in_basket", 1, 30);
                })
            }
        }
    })
}

function countPrice(upust_count) {
    upust = readCookie("upust") ? readCookie("upust") : 0;
    if (upust) 
        $("#basket_container .priceOfProduct:not(#basket_container .priceOfProduct:last), #basket_container_b .priceOfProduct:not(#basket_container_b .priceOfProduct:last), #basket_container_c .priceOfProduct:not(#basket_container_c .priceOfProduct:last)").each(function() {
            preProductPrice = parseFloat(($(this).attr("class")).substr(($(this).attr("class")).indexOf("PC") + 2));
            newPrice = preProductPrice - parseFloat(upust * preProductPrice);
            $(this).text(newPrice.toFixed(2) + " zł")
        });
    suma = 0;
    $("#basket_container .priceOfProduct:not(.priceOfProduct:last)").each(function() {
        suma += parseFloat(($(this).text()))
    });
    koszt_wysylki = "";
	if (sposob_wysylki == 'online') 
		koszt_wysylki = 0;
    else if (sposob_wysylki == 'priorytet_polecony') 
        koszt_wysylki = 6;
    else if (sposob_wysylki == 'priorytet_polecony_pobranie') 
        koszt_wysylki = 13.5;
    else if (sposob_wysylki == 'odbior_osobisty') 
        koszt_wysylki = 0;
    else if (sposob_wysylki == 'kurierUPS') 
        koszt_wysylki = 25;
    prePrice = (suma / parseFloat((1 - upust)));
    if (suma > 75 && sposob_wysylki == 'priorytet_polecony') 
    {
        $("#basket_container .priceOfProduct:last, #basket_container_b .priceOfProduct:last, #basket_container_c .priceOfProduct:last").text("GRATIS!");
        przesylkaGratis = true
    }
    else 
    {
        if (suma > 75) 
        {
            przesylkaGratis = true
        }
        $("#basket_container .priceOfProduct:last, #basket_container_b .priceOfProduct:last, #basket_container_c .priceOfProduct:last").text(koszt_wysylki + " zł");
        suma += koszt_wysylki;
        prePrice += koszt_wysylki
    }
    return suma.toFixed(2)
}

function setPrice(price) {
    $(".fullPrice").each(function() {
        $(this).text(price + " zł");
        upust = readCookie("upust") ? readCookie("upust") : 0;
        if (upust) 
        {
            $(this).html("Przed: <strike>" + prePrice.toFixed(2) + " </strike> zł<br />Po: " + price + " zł")
        }
    });
    return price
}

function removeItemFromBasket(which) {
    $.ajax(
    {
        url: "lib/removeproduct.php",
        type: 'POST',
        async: false,
        cache: false,
        data: 
        {
            "productId": which
        },
        timeout: 10000,
        success: function() {
            $("tr.rm" + which).animate(
            {
                "opacity": 0
            }, 200, function() {
                $("tr.rm" + which).unbind("hover").unbind("mousemove").remove();
                tooltip(undefined, true);
                setPrice(countPrice());
                if ((75 - countPrice() + 6) > 0) 
                    przesylkaGratis = false;
                if (!($("#basket_container .produkt:not(.produkt:last)").length)) 
                {
                    removeBasket();
					removeCookie("anything_in_basket");
                    if ($("#messageWindow").length) 
                    {
                        $("#messageWindow").hide(500).remove()
                    }
                }
            })
        }
    })
}

function insert_existing_items() {
	if (readCookie("anything_in_basket")) 
	{
		var myObject;
		$.ajax(
		{
			url: "lib/get_existing_items.php",
			type: 'POST',
			async: false,
			cache: false,
			data: 
			{
				"action": "getExistingItems"
			},
			timeout: 10000,
			success: function(myJSONtext) {
			
				if (myJSONtext) //TU SIE PRZYPATRZ
					myObject = eval('(' + myJSONtext + ')');
				if (myObject) 
				{
					for (var i = 0; i < myObject.length; i++) 
					{
						var cena = myObject[i]['cena'];
						var skrocona_nazwa = myObject[i]['nazwa_skrocona'];
						var insertedId = myObject[i]['insertedId'];
						var nazwa_strony = myObject[i]['nazwa_strony'];
						var lekcja = myObject[i]['lekcja'];
						if (!lekcja) 
							var obj = $("<tr class='produkt rm" + insertedId + "'><td class='productNames'><img class='tick_products tooltip rm" + insertedId + "' src='images/tick.gif' title='Usuń " + skrocona_nazwa + " z koszyka' /><span class='nazwa'><a href='" + nazwa_strony + "' class='tooltip' title='Kliknij by przejść na stronę opisu kursu " + skrocona_nazwa + "'>" + skrocona_nazwa + "</a></span></td><td><div class='priceOfProduct PC" + cena + " '>" + cena + " zł</div></td></tr>");
						else 
						{
							var labelId = myObject[i]['labelId'];
							var obj = $("<tr class='produkt rm" + insertedId + "'><td class='productNames'><img class='tick_products tooltip rm" + insertedId + "' src='images/tick.gif' title='Usuń " + skrocona_nazwa + " z koszyka' /><span class='nazwa'><a href='" + nazwa_strony + "#AL" + labelId + "' class='tooltip' title='Kliknij by przejść na stronę opisu kursu " + skrocona_nazwa + "'>" + skrocona_nazwa + "</a></span></td><td><div class='priceOfProduct PC" + cena + " '>" + cena + " zł</div></td></tr>");
						}
						$(".produkty_w_koszyku").prepend(obj);
					}
					setPrice(countPrice());
					$("#basket_container").show(100, function() {
						removingAnimations();
						$("img[class*='rm']").click(function() {
							var fullClassName = $(this).attr("class");
							var idToRemove = parseInt(fullClassName.substring(fullClassName.indexOf("rm") + ("rm").length));
							removeItemFromBasket(idToRemove);
						});
					})
				}
			}
		});
	}
}

function tooltip(which, assign) {
    if (assign) 
    {
        $("#tooltip").remove()
    }
    else 
    {
        xOffset = 30;
        yOffset = 20;
        $(".tooltip", which).hover(function(e) {
			if( $("#tooltip")) //important by workowalo dobrze ;) 
			$("#tooltip").remove();
			
            $("body").append("<p id='tooltip'>" + this.title + "</p>");
            $("#tooltip").css("top", (e.pageY - xOffset) + "px").css("left", (e.pageX + yOffset) + "px").fadeIn("fast");
            this.t = this.title;
            this.title = ""
        }, function() {
            this.title = this.t;
            $("#tooltip").remove();
        });
        $(".tooltip", which).mousemove(function(e) {
            $("#tooltip").css("top", (e.pageY - xOffset) + "px").css("left", (e.pageX + yOffset) + "px")
        })
    }
}

function updateTooltip(searchPattern, newTitle) {
    xOffset = 30;
    yOffset = 20;
    if (newTitle) 
    {
        $(searchPattern).unbind();
    }
	$("#tooltip").remove();
    $(searchPattern).hover(function(e) {
        if (newTitle) 
            this.title = newTitle;
        $("body").append("<p id='tooltip'>" + this.title + "</p>");
        $("#tooltip").css("top", (e.pageY - xOffset) + "px").css("left", (e.pageX + yOffset) + "px").fadeIn("fast");
        this.t = this.title;
        this.title = ""
    }, function() {
        this.title = this.t;
        $("#tooltip").remove()
    });
    $(searchPattern).mousemove(function(e) {
        $("#tooltip").css("top", (e.pageY - xOffset) + "px").css("left", (e.pageX + yOffset) + "px")
    })
}

function opacityForThumbs() {
    $(".obrazek").hover(function() {
        $(this).css("opacity", 1.0)
    }, function() {
        $(this).css("opacity", 0.6)
    })
}

function showMessage(whatmessage) {
    if ($("#panelTop").length) 
        panelAdministracyjnyProcedure("hide");
    if (krok == 3) 
    {
        if (whatmessage == 'acceptOrder') 
        {
            var messageWindow = $("#messageWindow");
            if (messageWindow.length && $("#addressInfo", messageWindow).length == 0) 
            {
                $("#formDataOrder, #methodOfOrder, #odbior_osobisty_info, #invoiceForm, #methodOfPayment", messageWindow).remove();
                $("#tooltip").hide();
                $(".header_b", messageWindow).text("Potwierdzenie zamówienia (Krok 3)");
                $(".current_krok", messageWindow).removeClass("current_krok");
                $(".krok:eq(2)", messageWindow).addClass("current_krok");
                $(".progressBar:eq(2)").attr("src", "images/step_bar_1.gif");
                $(".arrow_right").hide(1000);
                updateTooltip(".arrow_left", "Popraw dane. Przejdź do kroku 2");
                hoverSrcEffect(".arrow_left", "images/arrow_left_hover.gif", "images/arrow_left.gif");
                $(".arrow_left").click(function() {
                    krok = 2;
                    $("#tooltip").remove();
                    showMessage("krok2")
                });
                var imie = readCookie("imie") ? readCookie("imie") : "";
                var nazwisko = readCookie("nazwisko") ? readCookie("nazwisko") : "";
                var miasto = readCookie("imie") ? readCookie("miasto") : "";
                var kod_pocztowy = readCookie("kod_pocztowy") ? readCookie("kod_pocztowy") : "";
                var ulica = readCookie("ulica") ? readCookie("ulica") : "";
                var wojewodztwo = readCookie("wojewodztwo") ? readCookie("wojewodztwo") : "";
                var email = readCookie("email") ? readCookie("email") : "";
                var telefon_kontaktowy = readCookie("telefon") ? readCookie("telefon") : "";
                if (telefon_kontaktowy) 
                    additionalInfo = $("<div id='additionalInfo'>Twój e-mail: <b>" + email + "</b>, nr telefonu kontaktowego: <b>" + telefon_kontaktowy + "</b></div>");
                else additionalInfo = $("<div id='additionalInfo'>Twój e-mail: <b>" + email + "</b></div>");
                messageWindow.append(additionalInfo);
				
				if (sposob_wysylki == "online" || sposob_wysylki == "odbior_osobisty")			
					addressInfo = $("<table id='addressInfo'><caption>Twoje dane:</caption><tr><td><b>" + imie + " " + nazwisko + "</b></td></tr><tr><td>" + email + " </td></tr></table>");
				else
					addressInfo = $("<table id='addressInfo'><caption>Adres do wysyłki:</caption><tr><td><b>" + imie + " " + nazwisko + "</b></td></tr><tr><td>" + kod_pocztowy + " " + miasto + "</td></tr><tr><td>ul. " + ulica + "</td></tr><tr><td>woj.: " + wojewodztwo + "</td></tr></table>");
                
				
                messageWindow.append(addressInfo);
                if (readCookie("invoiceChecked") == "true") 
                {
                    var nazwaFirmyFaktura = readCookie("nazwaFirmyFaktura") ? readCookie("nazwaFirmyFaktura") : "";
                    var miastoFaktura = readCookie("miastoFaktura") ? readCookie("miastoFaktura") : (readCookie("imie") ? readCookie("miasto") : "");
                    var kod_pocztowyFaktura = readCookie("kod_pocztowyFaktura") ? readCookie("kod_pocztowyFaktura") : (readCookie("kod_pocztowy") ? readCookie("kod_pocztowy") : "");
                    var ulicaFaktura = readCookie("ulicaFaktura") ? readCookie("ulicaFaktura") : (readCookie("ulica") ? readCookie("ulica") : "");
                    var NIPFaktura = readCookie("NIPFaktura") ? readCookie("NIPFaktura") : "";
                    addressInfo = $("<table id='invoiceInfo'><caption>Faktura VAT na dane:</caption><tr><td><b>" + nazwaFirmyFaktura + "</b></td></tr><tr><td>" + kod_pocztowyFaktura + " " + miastoFaktura + "</td></tr><tr><td>ul. " + ulicaFaktura + "</td></tr><tr><td>NIP: " + NIPFaktura + "</td></tr></table>");
                    messageWindow.append(addressInfo)
                }
                var basket = procedureOrder("krok3");
                var obj = "";
                for (var i = 0; i < basket.length; i++) 
                {
                    obj += "<tr class=\"produkt\"><td class\"productNames\"><img src=\"images/tick.gif\" class=\"tick_products\"><span class=\"nazwa\">" + basket[i]['nazwa'] + "</span></td><td><div class=\"priceOfProduct PC" + basket[i]['cena'] + "\">" + basket[i]['cena'] + " zł</div></td></tr>"
                }
                var third_basket = $('<div id="basket_container_c"><div class="basket_headers"><span class="small_basket_header">Zamawiane produkty:</span><div class="price_header">Cena:</div></div><table class="produkty_w_koszyku">' + obj + '<tr class="produkt"><td class="productNames"><img class="tick_products" src="images/mail_tick.gif" /><span class="nazwa">Dostawa</span></td><td><div class="priceOfProduct">6 zł</div></td></tr></table><div class="fullPriceField" > Razem: <span class="fullPrice">0 zł</span></div></div>');
                third_basket.hide();
                messageWindow.append(third_basket);
                var total_price = setPrice(countPrice());
                third_basket.show(400);
                var commentsFromCustomer = readCookie("commentFromCustomer") ? readCookie("commentFromCustomer") : "";
                var commentFromCustomer = $("<form id='commentFromCustomer'><span class='formLabel'>Twoje uwagi do zamówienia: </span><div><textarea>" + commentsFromCustomer + "</textarea></div></form>");
                messageWindow.append(commentFromCustomer);
                commentFromCustomer.change(function() {
                    createCookie("commentFromCustomer", $("textarea", this).val(), 30)
                });
				if (sposob_zaplaty == "dotpay" && sposob_wysylki != "odbior_osobisty" && sposob_wysylki != "priorytet_polecony_pobranie")
					buttonOrderValue = "Płacąc przez DotPay";
				else
					buttonOrderValue = "";
					
                var submitOrder = $('<form><input type="submit" id="submitOrder" value="Złóż Zamówienie '+buttonOrderValue+'"></form>');
                messageWindow.append(submitOrder);
                $(submitOrder).click(function() {
                    preloadImage("images/ajax-loader.gif", 100, 100);
		
						if (sposob_zaplaty == "dotpay" && sposob_wysylki != "odbior_osobisty" && sposob_wysylki != "priorytet_polecony_pobranie") 
						{
							$.ajax(
							{
								url: "lib/create_order_dotpay.php",
								type: 'POST',
								async: false,
								cache: false,
								data: 
								{
									"action": "create_order_dotpay",
									"imie": imie,
									"nazwisko": nazwisko,
									"sposob_wysylki": sposob_wysylki,
									"miasto": miasto,
									"kod_pocztowy": kod_pocztowy,
									"ulica": ulica,
									"wojewodztwo": wojewodztwo,
									"telefon_kontaktowy": telefon_kontaktowy,
									"email": email,
									"nazwaFirmyFaktura": nazwaFirmyFaktura,
									"miastoFaktura": miastoFaktura,
									"kod_pocztowyFaktura": kod_pocztowyFaktura,
									"ulicaFaktura": ulicaFaktura,
									"NIPFaktura": NIPFaktura,
									"invoiceChecked": readCookie("invoiceChecked"),
									"commentFromCustomer": $("textarea", commentFromCustomer).val(),
									"kontoChecked": readCookie("kontoChecked"),
									"newsletterChecked": readCookie("newsletterChecked"),
									"loggedInVersion": (loggedInVersion ? 1 : 0),
									"kod_rabatowy": readCookie("kod_rabatowy")
								
								},
								timeout: 30000,
								beforeSend: function() {
									$("body").prepend("<div id='loading'><img src='images/ajax-loader.gif' alt='wczytuję' /><div>");
									var loader = $("#loading");
									loader.css("opacity", 0.9);
									loader.css("top", ($(window).height() - loader.height()) / 3 + "px").css("left", ($(window).width() - loader.width() - parseInt(loader.css("padding-left")) - parseInt(loader.css("padding-right"))) / 2 + "px")
								},
								success: function(myJSONtext) 
								{
									
									$("#loading").hide();
									var myObject = "";
									
								    if (myJSONtext) 
            							myObject = eval('(' + myJSONtext + ')');
											
									removeCookie("upust");
									removeCookie("kod_rabatowy")
									 							
									post_to_url("https://ssl.dotpay.pl/", {
										"id": 45271,
										"kwota": countPrice(),
										"waluta": "PLN",
										"opis": "Za zamówienie nr "+myObject['id_zamowienia'],
										"przelewyonline": 1,
										"URL": "http://videokurs.pl/platnosci-dotpay/powrot.php", //uzupelnic
										"typ": 3,
										"imie": imie,
										"nazwisko": nazwisko,
										"email": email,
										"ulica": ulica,
										"miasto": miasto,
										"kod": kod_pocztowy,
										"telefon_kontaktowy": telefon_kontaktowy,
										"p_info": "#B;videokurs.pl=B;",
										"control": myObject['control']										
									});
												
									
								},
								error: function() {
									$("#loading").hide();
									alert("Wystąpił jakiś błąd, bardzo prosimy o kontakt w sprawie zamówienia na eskoal@bochnia.pl")
								}
							});							
								
							
						}
						else 
						{
							
							$.ajax(
							{
								url: "lib/create_order.php",
								type: 'POST',
								async: false,
								cache: false,
								data: 
								{
									"action": "create_order",
									"imie": imie,
									"nazwisko": nazwisko,
									"sposob_wysylki": sposob_wysylki,
									"miasto": miasto,
									"kod_pocztowy": kod_pocztowy,
									"ulica": ulica,
									"wojewodztwo": wojewodztwo,
									"telefon_kontaktowy": telefon_kontaktowy,
									"email": email,
									"nazwaFirmyFaktura": nazwaFirmyFaktura,
									"miastoFaktura": miastoFaktura,
									"kod_pocztowyFaktura": kod_pocztowyFaktura,
									"ulicaFaktura": ulicaFaktura,
									"NIPFaktura": NIPFaktura,
									"invoiceChecked": readCookie("invoiceChecked"),
									"commentFromCustomer": $("textarea", commentFromCustomer).val(),
									"kontoChecked": readCookie("kontoChecked"),
									"newsletterChecked": readCookie("newsletterChecked"),
									"loggedInVersion": (loggedInVersion ? 1 : 0),
									"kod_rabatowy": readCookie("kod_rabatowy")
								},
								timeout: 30000,
								beforeSend: function() {
									
									$("body").prepend("<div id='loading'><img src='images/ajax-loader.gif' alt='wczytuję' /><div>");
									var loader = $("#loading");
									loader.css("opacity", 0.9);
									loader.css("top", ($(window).height() - loader.height()) / 3 + "px").css("left", ($(window).width() - loader.width() - parseInt(loader.css("padding-left")) - parseInt(loader.css("padding-right"))) / 2 + "px")
								},
								success: function(nrZamowienia) {
									$("#loading").hide(500);
									errorMessageBox("Zamówienie złożone poprawnie", false, 400, 100);
									$("#addressInfo").remove();
									$("#additionalInfo").remove();
									$("#invoiceInfo").remove();
									$("#basket_container_c").remove();
									$("#commentFromCustomer").remove();
									$("#submitOrder").remove();
									$(".arrow_left").remove();
									$("#kod_rabatowy").remove();
									total_price = setPrice(countPrice());
									removeCookie("upust");
									removeCookie("kod_rabatowy");
									removeBasket();
									$(".header_b").text("Informacje po złożeniu zamówienia");
									var stringInfoAfterOrder = "<div class='infoOrder' style='margin-top: 30px;'>Dziękujemy za złożenie zamówienia.</div>";
									if (sposob_wysylki == "priorytet_polecony" || sposob_wysylki == "kurierUPS" || sposob_wysylki == "online") 
									{
										stringInfoAfterOrder += "<div class='infoOrder'>Proszę wysłać do nas przelew bankowy na kwotę <b>" + total_price + " zł.</b></div>";
										stringInfoAfterOrder += "<div class='infoOrder'>Numer rachunku: <b>ESKOAL 32-700 Bochnia ul. Proszowska 92, Nr. Rachunku: 50 1020 5558 1111 1670 2330 0087</b></div>";
										stringInfoAfterOrder += "<div class='infoOrder'>bank: INTELIGO</div>";
										stringInfoAfterOrder += "<div class='infoOrder'>Prosimy nie zapomnieć wstawić swojego numeru zamówienia, to jest <b>" + nrZamowienia + "</b> w tytule przelewu bankowego. </div>"
									}
									else if (sposob_wysylki == "priorytet_polecony_pobranie") 
									{
										stringInfoAfterOrder += "<div class='infoOrder'>Twoje zamówienie zostanie wysłane w najbliższy dzień roboczy o ok. godz 13-stej, o czym zostaną Państwo powiadomieni drogą e-mail. Kwota, którą pobierze listonosz: <b>" + total_price + " zł </b></div>"
									}
									else if (sposob_wysylki == "odbior_osobisty") 
									{
										stringInfoAfterOrder += "<div id='odbior_osobisty_info'>Zapraszamy do odbioru kursów na ul. Proszowską 92 w Bochni. Warto zadzwonić i sprawdzić, czy sklep jest otwarty w godzinach, w których mają Państwo zamiar odebrać kursy. <br />Telefon kontaktowy:  668 489 016. E-mail: <a href='mailto:eskoal@bochnia.pl'>eskoal@bochnia.pl</a></div>"
									}
								
									stringInfoAfterOrder += "<div class='infoOrder'>Został do Ciebie wysłany mail z informacjami dotyczącymi zamówienia. </div>";
									stringInfoAfterOrder += "<div class='infoOrder'>Jeśli masz jakieś pytania lub potrzebujesz więcej informacji prosimy o kontakt: <a href='mailto:eskoal@bochnia.pl'>eskoal@bochnia.pl</a> lub telefonicznie: 606 192 567</div>";
									stringInfoAfterOrder += "<center><div class='infoOrder'><img src='images/tick_big.png' alt='Everything is OK' /></div></center>";
									if (readCookie("kontoChecked") == "true") 
										stringInfoAfterOrder += "<div class='infoOrder'>Twoje dane konta z hasłem zostały wysłane na podany przez Ciebie e-mail.</div>";
									var infoAfterOrder = $(stringInfoAfterOrder);
									infoAfterOrder.hide();
									messageWindow.append(infoAfterOrder);
									infoAfterOrder.show(1000);
									$("#content_container_panel").load("lib/moje_zamowienia.php", 
									{
										"action": "moje_zamowienia"
									})
									
								},
								error: function() {
									$("#loading").hide();
									alert("Wystąpił jakiś błąd, bardzo prosimy o kontakt w sprawie zamówienia na eskoal@bochnia.pl")
								}
							});
						}
                    return false
                })
            }
        }
    }
    else if (krok == 1) 
    {
		
        if ($("#messageWindow").length) 
        {
            $("#messageWindow").hide().remove()
        }
        $("body").prepend("<div id='messageWindow'> </div>");
        var messageWindow = $("#messageWindow");
        messageWindow.hide();
        var xOffset = 0;
        var yOffset = 0;
        messageWindow.prepend($("<img id='closeButton' src='images/close_message.gif' class='tooltip' title='Zamknij ramkę' />"));
        hoverSrcEffect("#closeButton", "images/close_message_hover.gif", "images/close_message.gif");
        $("#closeButton").click(function() {
            messageWindow.hide(200, function() {
                position = -1;
                messageWindow.remove();
                krok = 1
            })
        });
		
        var message = "";
        if (whatmessage == "sending") 
		{
			messageWindow.css("height", 400);
			message = procedureSending();
		}
		else if (whatmessage == "order") 
			message = procedureOrder();
        messageWindow.append(message);
        if (whatmessage == "order") 
        {
			
            setPrice(countPrice());
            removingAnimations();
            $("#basket_container_b img[class*='rm']").click(function() {
                var fullClassName = $(this).attr("class");
                var idToRemove = parseInt(fullClassName.substring(fullClassName.indexOf("rm") + ("rm").length));
                removeItemFromBasket(idToRemove)
            });
            if ((75 - countPrice() + 6) < 0) 
                $(".freeShipmentMessage").hide();
            else $(".freeShipmentMessage").show();
            $(".sendmessage").click(function() {
                $("#tooltip").remove();
                showMessage("sending");
                return false
            });
            hoverSrcEffect(".arrow_right", "images/arrow_right_hover.gif", "images/arrow_right.gif");
            $(".arrow_right").click(function() {
                krok = 2;
                showMessage("krok1");
                $(".arrow_right").unbind("click")
            })
        }
        messageWindow.css("top", ($(window).height() - $("#messageWindow").height()) / 3 + "px").css("left", ($(window).width() - $("#messageWindow").width()) / 2 + "px").show(200, function() {
            tooltip(messageWindow)
        })
		
		
    }
    else if (krok == 2) 
    {
        if ($("#messageWindow").length) 
        {
            var messageWindow = $("#messageWindow");
            messageWindow.animate(
            {
                "height": 700,
                "top": "30px"
            }, 600, function() {
                updateTooltip(".arrow_right", "Przejdź do kroku 3");
                var totalPrice = countPrice();
                hoverSrcEffect(".arrow_right", "images/arrow_right_hover.gif", "images/arrow_right.gif");
                $(".arrow_right", messageWindow).show().click(function(e) {
                    if (timeStampAnimation == -1 || (e.timeStamp - timeStampAnimation) > 1500) 
                    {
                        if (!loggedInVersion) 
                            if (checkEmailInDatabase() && readCookie("poprawka") != "prawda") 
                            {
								initBox("lib/error_message/account_already_exists.html", true);
								
                                //alert("")
                            }
                        if (isAllFilled()) 
                        {
                            if (readCookie("regulaminChecked") == "true") 
                            {
                                krok = 3;
                                $("#tooltip").remove();
                                showMessage("acceptOrder")
                            }
                            else 
                            {
                                errorMessageBox("Prosimy o akceptację regulaminu", true)
                            }
                        }
                    }
                    timeStampAnimation = e.timeStamp
                });
				
				//metody dostawy
				if (sposob_wysylki != "online") 
				{
					headerSposobDostawy = "Wybierz sposób dostawy:";
					sposobyDostawy = "<div class='input_shop_shipment tooltip' title='Możesz osobiście odebrać zamówione kursy przy ulicy Proszowskiej 92 w Bochni.'>  <input name='sposob_wysylki' type='radio' value='odbior_osobisty' id='A3' /><span><label for='A3'>Odbiór osobisty: <span class='koszt_wysylki'>0 zł</span></label></span></div><div class='input_shop_shipment tooltip' title='Przy wybraniu tej opcji należność wpłaca się na podane przez nas konto, które otrzymasz po złożeniu zamówienia.'><input name='sposob_wysylki' type='radio' value='priorytet_polecony' id='A1' /><span><label for='A1'>Priorytet / polecony: <span class='koszt_wysylki' id='koszt_priorytet_polecony'>6 zł</span></label></span></div><div class='input_shop_shipment tooltip' title='Wybierając tą opcję zapłacisz za zamówione kursy przy odbiorze swojemu listonoszowi.'>  <input name='sposob_wysylki' type='radio' value='priorytet_polecony_pobranie' id='A2' /><span><label for='A2'>Priorytet / polecony za pobraniem: <span class='koszt_wysylki' id='koszt_za_pobraniem'>13,5 zł</span></label></span></div><div class='input_shop_shipment tooltip' title='Jeżeli bardzo Ci zależy na czasie, to możesz wybrać przesyłkę kurierską. Korzystamy z usług kurierskich firmy UPS. Wysyłka kurierska realizowana jest po wpłacie należnośći na konto, które otrzymasz po złożeniu zamówienia.'>  <input name='sposob_wysylki' type='radio' value='kurierUPS' id='A4' /><span><label for='A4'>Kurier UPS: <span class='koszt_wysylki'>25 zł</span></label></span>";
				}
				else 
				{
					sposobyDostawy = "<div class='input_shop_shipment tooltip' title='&lt;b>Dostawa &quot;online&quot; jest całkowicie bezpłatna&lt;/b>. &lt;br /> &lt;br /> Przy wybraniu tej opcji będziesz mieć dostęp do plików zakupionego kursu przez 1 rok w wersji online + dodatkowo możliwość ściągnięcia plików na dysk przez 7 pierwszych dni od daty realizacji zamówienia.  &lt;br /> &lt;br />Zezwalamy na nagranie dla &lt;u>własnego użytku&lt;/u> jednej kopi zapasowej płyty ze ściągniętymi plikami.  &lt;br /> &lt;br />Z reguły transakcje &lt;b>za pośrednictwem DotPay&lt;/b> są realizowane &lt;b>w ciągu kilku minut, czasem kilku sekund&lt;/b>, jednak operatorzy rezerwują sobie czas do 24 godzin, dlatego transakcja może trwać dłużej. &lt;br /> &lt;br />Przy wybraniu opcji &lt;b>bezpośredniego przelewu&lt;/b> na nasze konto (w 2 kroku zamówienia) dostęp do materiałów następuje po odnotowaniu wpłaty na konto lub po przesłaniu dowodu wpłaty.'>  <input name='sposob_wysylki' type='radio' value='online' id='A3' /><span><label for='A3'>Online (elektroniczny): <span class='koszt_wysylki'>0 zł</span></label></span></div>";
					headerSposobDostawy = "Sposób dostawy:";
				}
                var methodOfOrder = $("<form id='methodOfOrder'><div id='infoAboutPrice' class='tooltip' title='Kwota zamówienia wraz z przesyłką'><span><b>Aktualna kwota zamówienia:</b></span><span class='fullPrice'> " + totalPrice + " zł</span></div><div><div class='formHeader'>"+headerSposobDostawy+"</div> " + sposobyDostawy+" </div></form>");
                methodOfOrder.css("opacity", 0);
                messageWindow.append(methodOfOrder);

												
                $("input[value=" + sposob_wysylki + "]", messageWindow).attr("checked", function() {
                    return "checked"
                });
                countPrice();
                if (przesylkaGratis) 
                    $("#koszt_priorytet_polecony").text("GRATIS");
                tooltip("#methodOfOrder");
				
                methodOfOrder.animate(
                {
                    "opacity": 1.0
                }, 600, function() {
                    ieRenderFix($(this));
                    $(".input_shop_shipment").hover(function() {
                        $(this).css("opacity", 0.7);
                        ieRenderFix($(this))
                    }, function() {
                        $(this).css("opacity", 1.0);
                        ieRenderFix($(this))
                    });
	                $(".input_shop_shipment input").click(function() {
		                    sposob_wysylki = $(this).attr("value");
		                    createCookie("sposob_wysylki", sposob_wysylki, 30);
		                    setPrice(countPrice());
		                    if ((sposob_wysylki == "priorytet_polecony" || sposob_wysylki == "kurierUPS" || sposob_wysylki == "priorytet_polecony_pobranie")) 
		                    {
		                        $("#input_miasto, #input_kod_pocztowy, #input_ulica, #input_telefon_kontaktowy, #input_wojewodztwo").show(200, function() {
		                            ieRenderFix($(this))
		                        });
		                        formAddressProcedure($("#formDataOrder"));
		                        $("#headerAboutOrder").text("Podaj dane do wysyłki:");
		                        if ($("#odbior_osobisty_info").length) 
		                        {
		                            $("#odbior_osobisty_info").hide(300, function() {
		                                $(this).remove()
		                            });
		                            if (!jQuery.browser.msie) 
		                                messageWindow.animate(
		                                {
		                                    "height": (parseInt(messageWindow.css("height")) - parseInt($("#odbior_osobisty_info").css("height"))) + "px"
		                                }, 100)
		                        }
		                    }
		                    else if (sposob_wysylki == "odbior_osobisty") 		                 
		                        odbiorOsobistyProcedure(messageWindow);
		                 
							if (sposob_wysylki == "priorytet_polecony_pobranie" || sposob_wysylki == "odbior_osobisty")
								$("#methodOfPayment").hide(400);
							else
								$("#methodOfPayment").show(400);
	                	})
           		 });
				
				
				//sposoby platnosci
				headerSposobPlatnosci = "Sposób płatności: ";	
				if (sposob_wysylki == "online") 
				{
					infoPrzelew = "Wybierając opcję &lt;b>przelew bankowy&lt;/b>, otrzymasz na podany przez Ciebie e-mail nr konta na który należy przelać należność. Po odnotowaniu wpłaty Twoje zamówione kursy / lekcje online zostaną aktywowane w panelu Klienta.";
					dotPayInfo = "Wybierając opcję płatności &lt;b>DotPay&lt;/b> Twoje zamówienie zostanie zrealizowane &lt;b>automatycznie&lt;/b>. &lt;br />&lt;br />W większości sytuacji &lt;b>otrzymasz dostęp&lt;/b> do zamówionych produktów &lt;b>w przeciągu paru minut, sekund.&lt;/b>";
				}
				else 
				{
					infoPrzelew = "Wybierając opcję &lt;b>przelew bankowy&lt;/b>, otrzymasz na podany przez Ciebie e-mail nr konta na który należy przelać należność. Przesyłka zostanie wysłana po odnotowaniu wpłaty na konto.";
					dotPayInfo = "Wybierając opcję płatności &lt;b>DotPay&lt;/b> Twoje zamówienie zostanie prawdopodobnie zrealizowane szybciej, ponieważ otrzymamy natychmiast potwierdzenie wpłaty co umożliwi nam wysyłkę nawet tego samego dnia - pod warunkiem, że zamówienie zostanie złożone przed godz. 10-tą.";
				}
				sposobyPlatnosci = "<div class='input_shop_payment tooltip' title='"+dotPayInfo+"'>  <input name='sposob_platnosci' type='radio' value='dotpay' id='P1' /><span><label for='P1' style='vertical-align: -150%;'><img width='160' height='83' src='images/dotpay_b3_160x83.gif' /> </label></span></div> <div class='input_shop_payment tooltip' title='"+infoPrzelew+"'>  <input name='sposob_platnosci' type='radio' value='przelew_bankowy' id='P2' /><span><label for='P2'>Przelew Bankowy (przedpłata) </label></span></div>";
        
		
			    var methodOfPayment = $("<form id='methodOfPayment'><div><div class='formHeader'>"+headerSposobPlatnosci+"</div>" + sposobyPlatnosci+" </div></form>");
				
                methodOfPayment.css("opacity", 0);
                messageWindow.append(methodOfPayment);
				
				tooltip("#methodOfPayment");
									
				$("input[value=" + sposob_zaplaty + "]", messageWindow).attr("checked", function() {
	           		 return "checked";
	        		});
                methodOfPayment.animate(
                {
                    "opacity": 1.0
                }, 600, function() {
					if($.browser.msie)
					{
						$img = $("label img", methodOfPayment);
				 
						$img.click(function(e) 
						{
							$("#" + $(this).parent().attr("for"))
								.change()
								.click();
						});
					}				
                    ieRenderFix($(this));
                    $(".input_shop_payment").hover(function() {
                        $(this).css("opacity", 0.7);
                        ieRenderFix($(this))
                    }, function() {
                        $(this).css("opacity", 1.0);
                        ieRenderFix($(this))
                    });
					 $(".input_shop_payment input").click(function() {
		                    sposob_zaplaty = $(this).attr("value");
		                    createCookie("sposob_zaplaty", sposob_zaplaty, 30);
		               
	                	});

				});
			  	
                var imie = readCookie("imie") ? readCookie("imie") : "";
                var nazwisko = readCookie("nazwisko") ? readCookie("nazwisko") : "";
                var miasto = readCookie("imie") ? readCookie("miasto") : "";
                var kod_pocztowy = readCookie("kod_pocztowy") ? readCookie("kod_pocztowy") : "";
                var ulica = readCookie("ulica") ? readCookie("ulica") : "";
                var wojewodztwo = readCookie("wojewodztwo") ? readCookie("wojewodztwo") : "";
                var email = readCookie("email") ? readCookie("email") : "";
                var telefon_kontaktowy = readCookie("telefon") ? readCookie("telefon") : "";
                var nazwaFirmyFaktura = readCookie("nazwaFirmyFaktura") ? readCookie("nazwaFirmyFaktura") : "";
                var nazwiskoFaktura = readCookie("nazwiskoFaktura") ? readCookie("nazwiskoFaktura") : (readCookie("nazwisko") ? readCookie("nazwisko") : "");
                var miastoFaktura = readCookie("miastoFaktura") ? readCookie("miastoFaktura") : (readCookie("miasto") ? readCookie("miasto") : "");
                var kod_pocztowyFaktura = readCookie("kod_pocztowyFaktura") ? readCookie("kod_pocztowyFaktura") : (readCookie("kod_pocztowy") ? readCookie("kod_pocztowy") : "");
                var ulicaFaktura = readCookie("ulicaFaktura") ? readCookie("ulicaFaktura") : (readCookie("ulica") ? readCookie("ulica") : "");
                var wojewodztwoFaktura = readCookie("wojewodztwoFaktura") ? readCookie("wojewodztwoFaktura") : (readCookie("wojewodztwo") ? readCookie("wojewodztwo") : "");
                var NIPFaktura = readCookie("NIPFaktura") ? readCookie("NIPFaktura") : "";
                var invoiceChecked = readCookie("invoiceChecked") ? readCookie("invoiceChecked") : "";

				if (sposob_wysylki != "online") 
				{
					var headerDaneWysylki = "Podaj dane do wysyłki:";
					var daneZamowienie = "<div class='input_shop' id='input_imie'><span>Imię:</span> <input class='requiredField' name='imie' type='text' maxlength='40' value='" + imie + "' /></div><div class='input_shop' id='input_nazwisko'><span>Nazwisko:</span> <input class='requiredField' name='nazwisko' type='text' maxlength='40' value='" + nazwisko + "' /></div><div class='input_shop' id='input_miasto'><span>Miasto:</span> <input class='requiredField' name='miasto' type='text' maxlength='40' value='" + miasto + "' /></div><div class='input_shop' id='input_kod_pocztowy'><span>Kod-pocztowy:</span><input class='requiredField' name='kod_pocztowy' type='text' maxlength='6' value='" + kod_pocztowy + "'/></div><div class='input_shop' id='input_ulica'><span>Ulica:</span><input class='requiredField' name='ulica' type='text' maxlength='80' value='" + ulica + "'/></div><div class='input_shop' id='input_wojewodztwo'><span>Województwo:</span><input class='requiredField' name='wojewodztwo' type='text' maxlength='40' value='" + wojewodztwo + "'/></div><div class='input_shop' id='input_email'><span>E-mail:</span><input class='requiredField' name='email' type='text' maxlength='40' value='" + email + "'/></div><div class='input_shop' id='input_telefon_kontaktowy'><span>Nr telefonu:</span><input name='telefon' type='text' maxlength='25' value='" + telefon_kontaktowy + "'/></div><div id='dataInvoiceForm'><div class='formHeader'>Podaj dane do Faktury VAT:</div><div class='input_shop'><span>Nazwa Firmy: </span><input class='requiredField' name='nazwaFirmyFaktura' type='text' maxlength='80' value='" + nazwaFirmyFaktura + "' /></div><div class='input_shop'><span>Miasto: </span> <input class='requiredField' name='miastoFaktura' type='text' maxlength='40' value='" + miastoFaktura + "' /></div><div class='input_shop' id='input_kod_pocztowy_faktura'><span>Kod-pocztowy: </span><input class='requiredField' name='kod_pocztowyFaktura' type='text' maxlength='6' value='" + kod_pocztowyFaktura + "'/></div><div class='input_shop'><span>Ulica: </span><input class='requiredField' name='ulicaFaktura' type='text' maxlength='80' value='" + ulicaFaktura + "'/></div><div class='input_shop' id='input_NIPFaktura'><span>NIP: </span><input class='requiredField' name='NIPFaktura' type='text' maxlength='13' value='" + NIPFaktura + "'/></div>";
				}
				else
				{
					var headerDaneWysylki = "Podaj niezbędne dane do zamówienia";
					daneZamowienie = "<div class='input_shop' id='input_imie'><span>Imię:</span> <input class='requiredField' name='imie' type='text' maxlength='40' value='" + imie + "' /></div><div class='input_shop' id='input_nazwisko'><span>Nazwisko:</span> <input class='requiredField' name='nazwisko' type='text' maxlength='40' value='" + nazwisko + "' /></div><div class='input_shop' id='input_email'><span>E-mail:</span><input class='requiredField' name='email' type='text' maxlength='40' value='" + email + "'/></div><div id='dataInvoiceForm'><div class='formHeader'>Podaj dane do Faktury VAT:</div><div class='input_shop'><span>Nazwa Firmy: </span><input class='requiredField' name='nazwaFirmyFaktura' type='text' maxlength='80' value='" + nazwaFirmyFaktura + "' /></div><div class='input_shop'><span>Miasto: </span> <input class='requiredField' name='miastoFaktura' type='text' maxlength='40' value='" + miastoFaktura + "' /></div><div class='input_shop' id='input_kod_pocztowy_faktura'><span>Kod-pocztowy: </span><input class='requiredField' name='kod_pocztowyFaktura' type='text' maxlength='6' value='" + kod_pocztowyFaktura + "'/></div><div class='input_shop'><span>Ulica: </span><input class='requiredField' name='ulicaFaktura' type='text' maxlength='80' value='" + ulicaFaktura + "'/></div><div class='input_shop' id='input_NIPFaktura'><span>NIP: </span><input class='requiredField' name='NIPFaktura' type='text' maxlength='13' value='" + NIPFaktura + "'/></div>";
				} 

				var formAddress = $("<form id='formDataOrder'><div><div class='formHeader' id='headerAboutOrder'>" + headerDaneWysylki + "</div> "+daneZamowienie+" </div></form>");
                formAddress.css("opacity", 0).hide();
                messageWindow.append(formAddress);
                $("#input_kod_pocztowy input").mask("99-999");
                $("#input_NIPFaktura input").mask("999-999-99-99");
                $("#input_kod_pocztowy_faktura input").mask("99-999");
                $("#dataInvoiceForm", messageWindow).hide();
                formAddressProcedure(formAddress);
				
				if (sposob_wysylki == "online")
					konto = "&lt;b>Przy zamówieniu online, konto jest wymagane, abyś mógł ściągnąć i oglądać swoje pliki online&lt;/b>.&lt;br />&lt;br />";
				else
					konto = "";
				
                if (sposob_wysylki == "odbior_osobisty") 
                    odbiorOsobistyProcedure(messageWindow);
				if (sposob_wysylki == "online" || sposob_wysylki == "priorytet_polecony_pobranie")
					$("#methodOfPayment").hide();
					
                if (!loggedInVersion) 
                    invoiceMessage = $('<form id="invoiceForm"><input type="checkbox" name="acceptation" value="konto" id="konto" /> <label class="tooltip" title="'+konto+'Konto umożliwi Ci śledzenie zamówień oraz możliwość otrzymania specjalnych rabatów dla stałych Klientów. Na podany przez Ciebie e-mail zostanie wysłane hasło do stworzonego konta. Po zalogowaniu się będzie można zmienić hasło." for="konto">Stwórz konto na podane przeze mnie dane</label><br /><input type="checkbox" name="acceptation" value="FVAT" id="FVAT" /> <label for="FVAT">Czy wystawić Fakturę VAT?</label> <br /><div id="regulaminDiv"><input type="checkbox" name="acceptation" value="regulamin" id="regulamin" /> <label for="regulamin">Zgadzam się i akceptuję warunki Regulaminu </label> <span class="regulaminAction">(czytaj)</span></div><input type="checkbox" name="acceptation" value="newsletter" id="newsletter" /> <label for="newsletter">Zapisz mnie do Newslettera zgodnie z </label> <span class="zasadyPrywatnosciAction">zasadami prywatnosci</span></form>');
                else invoiceMessage = $('<form id="invoiceForm"><input type="checkbox" name="acceptation" value="FVAT" id="FVAT" /> <label for="FVAT">Czy wystawić Fakturę VAT?</label> <br /><div id="regulaminDiv"><input type="checkbox" name="acceptation" value="regulamin" id="regulamin" /> <label for="regulamin">Zgadzam się i akceptuję warunki Regulaminu </label> <span class="regulaminAction">(czytaj)</span></div></form>');
                
				if (sposob_wysylki == "online")
				{
					createCookie("kontoChecked", true, 30);
					$("#konto",invoiceMessage).attr("disabled", "disabled");
				}
				if (sposob_wysylki == "priorytet_polecony_pobranie" || sposob_wysylki == "odbior_osobisty")
					$("#methodOfPayment").hide();
				else
					$("#methodOfPayment").show();
					
				messageWindow.append(invoiceMessage);
                tooltip(invoiceMessage);
                $("#invoiceForm").css("opacity", 0);
                $("#invoiceForm").animate(
                {
                    "opacity": 1.0
                }, 500, function() {
                    ieRenderFix($("#invoiceForm"));
                    if (readCookie("invoiceChecked") == "true") 
                    {
                        $("#FVAT", $(this)).attr("checked", function() {
                            return "checked"
                        });
                        $("#dataInvoiceForm", messageWindow).show(300)
                    }
                    if (readCookie("regulaminChecked") == "true") 
                    {
                        $("#regulamin", $(this)).attr("checked", function() {
                            return "checked"
                        })
                    }
                    if (!loggedInVersion) 
                        if (readCookie("newsletterChecked") == "true") 
                        {
                            $("#newsletter", $(this)).attr("checked", function() {
                                return "checked"
                            })
                        }
                    if (!loggedInVersion) 
                        if (readCookie("kontoChecked") == "true") 
                        {
                            $("#konto", $(this)).attr("checked", function() {
                                return "checked";
                            })
                        }
                });
                $(".regulaminAction").click(function() {
                    initBox("regulamin.html")
                });
                $(".zasadyPrywatnosciAction").click(function() {
                    initBox("zasady_prywatnosci.html")
                });
                $("#regulamin").click(function() {
                    createCookie("regulaminChecked", $(this).attr("checked"), 30)
                });
                if (!loggedInVersion) 
                    $("#newsletter").click(function() {
                        createCookie("newsletterChecked", $(this).attr("checked"), 30)
                    });
                if (!loggedInVersion) 
                    $("#konto").click(function() {
                        createCookie("kontoChecked", $(this).attr("checked"), 30)
                    });
                $("#FVAT").click(function() {
                    if ($(this).attr("checked")) 
                    {
                        $("#dataInvoiceForm", messageWindow).show(500);
                        $("#formDataOrder").height(250)
                    }
                    else 
                    {
                        $("#dataInvoiceForm", messageWindow).hide(500)
						$("#formDataOrder").height("auto");
                    }
				
                    createCookie("invoiceChecked", $(this).attr("checked"), 30)
                });								

                if (!jQuery.browser.msie) 
                {
                    $("#formDataOrder").height("auto")
                }
                messageWindow.height("auto")
				if (invoiceChecked == "true" && (sposob_wysylki == "online" || sposob_wysylki == "odbior_osobisty")) 
					$("#formDataOrder").height(200);
		
					
				
            });
			
			$(".header_b", messageWindow).text("Sposób dostawy oraz dane do wysyłki (Krok 2)");
		
			
            $(".current_krok", messageWindow).removeClass("current_krok");
            $(".krok:eq(1)", messageWindow).addClass("current_krok");
            $(".progressBar:eq(1)").attr("src", "images/step_bar_1.gif");
            if (whatmessage == "krok1") 
            {
                $("#basket_container_b", messageWindow).remove();
                $("#tooltip").hide();
                var leftArrow = $("<span class='indicatorForTooltip'><img src='images/arrow_left.gif' class='tooltip arrow_left' title='Przejdź do kroku 1' /></span>");
                $("#messageWindow").append(leftArrow);
                leftArrow.css("opacity", 0);
                leftArrow.animate(
                {
                    "opacity": 1.0
                }, 2000);
                hoverSrcEffect(".arrow_left", "images/arrow_left_hover.gif", "images/arrow_left.gif");
                $(".arrow_left").click(function() {
                    krok = 1;
                    $("#tooltip").remove();
                    showMessage("order")
                });
                tooltip($(".indicatorForTooltip"))
            }
            else if (whatmessage == "krok2") 
            {
                $(".progressBar:eq(2)").attr("src", "images/step_bar_2.gif");
                updateTooltip(".arrow_left", "Przejdź do kroku 1");
                hoverSrcEffect(".arrow_left", "images/arrow_left_hover.gif", "images/arrow_left.gif");
                $(".arrow_left").click(function() {
                    krok = 1;
                    $("#tooltip").remove();
                    showMessage("order")
                });
                $("#addressInfo").remove();
                $("#additionalInfo").remove();
                $("#invoiceInfo").remove();
                $("#basket_container_c").remove();
                $("#commentFromCustomer").remove();
                $("#submitOrder").remove()
            }

        }
        else 
        {
            krok = 1;
            showMessage(whatmessage)
        }
    }
}

function isAllFilled() {
    var allFilled = true;
    var stringForInvoice = ":not(#dataInvoiceForm .requiredField)";
	
    if ($("#FVAT").attr("checked")) 
        stringForInvoice = "";
	
	var whatToCheck  = "";
		
	if (sposob_wysylki == "online" || sposob_wysylki == "odbior_osobisty")
	{
		if ($("#FVAT").attr("checked")) 
		  stringForInvoice = ", #dataInvoiceForm .requiredField";
		else
		  stringForInvoice = "";	
		
		whatToCheck = ".requiredField[name='imie'], .requiredField[name='nazwisko'], .requiredField[name='email']" + stringForInvoice;	  
	}
	else
		whatToCheck = ".requiredField" + stringForInvoice;
	
	
    $(whatToCheck).each(function() {
        if ($(this).val() == "") 
        {
			
            requiredInputDiv = $(this).parent("div[class='input_shop']");
            showErrorMessageForm(requiredInputDiv, "Pole wymagane", this);
            var preOpacity = $("span", requiredInputDiv).css("opacity");
            $("span", requiredInputDiv).animate(
            {
                "opacity": 0.4
            }, 1000, function() {
                $(this).animate(
                {
                    "opacity": preOpacity
                }, 1000, function() {
                    ieRenderFix($(this));
                })
            });
            allFilled = false;
        }
    });
	
    if (!(/^[a-z][\w\.-]*\w@([\w-]+\.)/i.test($("#input_email input").attr("value"))) && $("#input_email input").attr("value") != "") 
    {
        showErrorMessageForm($("#input_email"), "Niepoprawny E-mail", $("#input_email"));
		
        allFilled = false;
		
    }
	if (sposob_wysylki != "online" && sposob_wysylki != "odbior_osobisty")
	    if (!(/^\d\d-?\d\d\d$/.test($("#input_kod_pocztowy input").attr("value"))) && $("#input_kod_pocztowy input").attr("value") != "") 
	    {
	        showErrorMessageForm($("#input_kod_pocztowy"), "Format 00-000", $("#input_kod_pocztowy"));
	        allFilled = false;
	    }
    if (!(/^\d\d\d-?\d\d\d-?\d\d-?\d\d$/.test($("#input_NIPFaktura input").attr("value"))) && $("#input_NIPFaktura input").attr("value") != "") 
    {
        showErrorMessageForm($("#input_NIPFaktura"), "000-000-00-00", $("#input_NIPFaktura"));
        allFilled = false;
    }
    return allFilled;
}

function showErrorMessageForm(div, infoToShow, loopObj) {
    errorMessage = $("<div class='requiredFieldInfo'>" + infoToShow + "</div>");
    div.append(errorMessage);
    errorMessage.css("top", $(loopObj).position().top).css("opacity", 0);
    errorMessage.animate(
    {
        "opacity": 0.9
    }, 1000, function() {
        $(this).animate(
        {
            "opacity": 0
        }, 5000, function() {
            $(this).remove()
        })
    })
}

function odbiorOsobistyProcedure(messageWindow) {
    ieRenderFix(messageWindow);
    if (!$("#odbior_osobisty_info").length) 
    {
        messageWindow.append(("<div id='odbior_osobisty_info'>Po zaakceptowaniu zamówienia zapraszamy do odbioru kursów na ul. Proszowską 92 w Bochni. Warto zadzwonić i sprawdzić, czy sklep jest otwarty w godzinach, w których mają Państwo zamiar odebrać kursy. <br />Telefon kontaktowy:  668 489 016. E-mail: <a href='mailto:eskoal@bochnia.pl'>eskoal@bochnia.pl</a></div>"));
        if (!jQuery.browser.msie) 
        {
            $("#input_miasto, #input_kod_pocztowy, #input_ulica, #input_telefon_kontaktowy, #input_wojewodztwo").hide(200, function() {
                if (readCookie("invoiceChecked") == "true") 
                    $("#formDataOrder").height(250);
                else $("#formDataOrder").height("auto")
            })
        }
        else $("#input_miasto, #input_kod_pocztowy, #input_ulica, #input_telefon_kontaktowy, #input_wojewodztwo").hide(200, function() {
            ieRenderFix($("#input_miasto, #input_kod_pocztowy, #input_ulica, #input_telefon_kontaktowy, #input_wojewodztwo"))
        });
        $("#headerAboutOrder").text("Podaj dane do odbioru:");
        $("#odbior_osobisty_info").hide().show(400, function() {
            if (!jQuery.browser.msie) 
                messageWindow.animate(
                {
                    "height": (parseInt(messageWindow.css("height")) + parseInt($("#odbior_osobisty_info").css("height"))) + "px"
                }, 100)
        });
		
		
    }
}

function formAddressProcedure(formAddress) {
    formAddress.show().animate(
    {
        "opacity": 1.0
    }, 600, function() {
        ieRenderFix($(this));
        $(".input_shop").click(function() {
            clickedField = $(this);
            var i = -1;
            $(".input_shop").each(function() {
                i++;
                if ($("span", this).text() == $("span", clickedField).text()) 
                {
                    position = i;
                    return false
                }
            });
            clickedField.css("font-weight", "bold");
            var clickedInputField = $("input", this);
            clickedInputField.focus();
            var actualBorder = clickedInputField.css("border");
            clickedInputField.css("border", "1px solid green");
            clickedInputField.blur(function() {
                $(this).css("border", actualBorder);
                clickedField.css("font-weight", "normal")
            })
        });
        $(".input_shop input").change(function() {
            createCookie($(this).attr("name"), $(this).attr("value"), 30)
        })
    })
}

function tabingItems(evt) {
    var evt = (evt) ? evt : window.event;
    if (evt.keyCode == 9) 
    {
        if (krok == 2) 
        {
            if (($(".input_shop input").length - 1) == position) 
            {
                lastGuy = $(".input_shop input:eq(" + (position) + ")");
                createCookie($(lastGuy).attr("name"), $(lastGuy).attr("value"), 30);
                borderCSS = $(".input_shop input:eq(0)").css("border");
                lastGuy.css("border", borderCSS);
                $(".input_shop:eq(" + position + ")").css("font-weight", "normal");
                position = -1
            }
            var previousGuy = $(".input_shop input:eq(" + (position) + ")");
            createCookie($(previousGuy).attr("name"), $(previousGuy).attr("value"), 30);
            var nextGuy = $(".input_shop input:eq(" + (++position) + ")");
            nextGuy.focus();
            var borderCSS = nextGuy.css("border");
            previousGuy.css("border", borderCSS);
            nextGuy.css("border", "1px solid green");
            $(".input_shop:eq(" + (position) + ")").css("font-weight", "bold");
            $(".input_shop:eq(" + (position - 1) + ")").css("font-weight", "normal");
            nextGuy.blur(function() {
                $(this).css("border", borderCSS);
                $(".input_shop").css("font-weight", "normal")
            });
            nextGuy.select();
            return false
        }
    }
}

function hoverSrcEffect(searchPattern, src1, scr2) {
    preloadImage(src1, 80, 80);
    $(searchPattern).hover(function() {
        $(this).attr("src", function() {
            return src1
        })
    }, function() {
        $(this).attr("src", function() {
            return scr2
        })
    })
}

function procedureSending() {
    return $("<img src='images/mailbox.gif' style='float: left; margin-top: 25px; margin-right: 20px;' alt='Zdjęcie Koszyka' /><div class='header' style='margin-left: 190px;'>Dostawa On-line</div><p class='textIndent'><b>Dostawa &quot;online&quot; jest całkowicie bezpłatna</b>. Po wybraniu tej opcji, będziesz mieć dostęp do plików zakupionego kursu przez 1 rok w wersji online + dodatkowo możliwość ściągnięcia plików na dysk przez 7 pierwszych dni od daty realizacji zamówienia. Zezwalamy na nagranie dla <u>własnego użytku</u> jednej kopi zapasowej płyty ze ściągniętymi plikami.</p><p class='textIndent'> Z reguły transakcje <b>za pośrednictwem DotPay</b> są realizowane <b>w ciągu kilku minut, czasem kilku sekund</b>, jednak operatorzy rezerwują sobie czas do 24 godzin, dlatego transakcja może trwać dłużej.</p><p class='textIndent'>Przy wybraniu opcji <b>bezpośredniego przelewu</b> na nasze konto (w 2 kroku zamówienia) dostęp do materiałów następuje po odnotowaniu wpłaty na konto lub po przesłaniu dowodu wpłaty.</p><div class='header' style='margin-left: 190px;'>Wysyłka wersji pudełkowej (DVD)</div><p class='textIndent'>Przesyłki są wysyłane CODZIENNIE od poniedziałku do piątku o około godz. 14-stej. Po wysłaniu, natychmiast powiadamiamy o tym i podajemy Nr Listu Przewozowego.</p><p class='textIndent'> Opłaty za wysyłkę oraz opakowanie są wliczone w koszty wysyłki. Za koszty wysyłki płacisz tylko JEDEN raz. </p><p class='textIndent'>Kursy są wysyłane w solidnych kopertach bąbelkowych.</p><div class='header' style='margin-left: 60px;'>Darmowa przesyłka</div><p class='textIndent'>Jeżeli Twoje zamówienie bez wysyłki przekroczy łączną wartość 75 zł to koszty przesyłki priorytetem poleconym na terenie Polski będą pokryte przez naszą firmę. </p>")
}

function procedureOrder(whichStep) {
	var myObject;
    $.ajax(
    {
        url: "lib/get_existing_items.php",
        type: 'POST',
        async: false,
        cache: false,
        data: 
        {
            "action": "getExistingItems"
        },
        timeout: 10000,
        success: function(myJSONtext) {
            if (myJSONtext) 
                myObject = eval('(' + myJSONtext + ')')
        }
    });
    if (myObject) 
    {
        if (whichStep == "krok3") 
            return myObject;
        var obj = "";
        $("tr.produkt:not(tr.produkt:last)").each(function() {
            obj += "<tr class=\"" + $(this).attr("class") + "\">" + $(this).html() + "</tr>"
        });
        var second_basket = new String('<div id="basket_container_b"><div class="basket_headers"><span class="small_basket_header">Koszyk:</span><div class="price_header">Cena:</div></div><table class="produkty_w_koszyku">' + obj + '<tr class="produkt"><td class="productNames"><a href="#" class="sendmessage tooltip" rel="nofollow" title="&lt;b>Dostawa online jest całkowicie bezpłatna&lt;/b>. &lt;br />&lt;br />Zamów kursy w wersji pudełkowej (DVD) za łączną wartość przekraczającą &lt;b>75 zł&lt;/b>, a przesyłka będzie &lt;b>GRATIS&lt;/b>! :-) Naciśnij na &lt;b>dostawę&lt;/b>, aby uzyskać szczegółowe informacje."><img class="tick_products" src="images/mail_tick.gif" /><span class="nazwa">Dostawa</span></a></td><td><div class="priceOfProduct">6 zł</div></td></tr></table><div class="fullPriceField"> Razem: <span class="fullPrice">0 zł</span></div></div>');
        var baskeet = $("<img src='images/basket_big.png' style='position: absolute; left: 15px; top: 10px;' alt='Zdjęcie Koszyka' /><div class='header_b' style='text-align: center; margin-bottom: 6px;'>Sprawdzenie stanu koszyka (Krok 1):</div><div><span class='stan_koszyka krok tooltip current_krok' title='Sprawdzenie stanu koszyka'>Krok 1</span><span class='dostawa_dane krok tooltip' title='Wybranie sposobu dostawy&lt;br />Podanie danych do wysyłki&lt;br />Akceptacja regulaminu'>Krok 2</span><span class='gotowe krok tooltip' title='Potwierdzenie zamówienia'>Krok 3</span></div><div id='progressBar'><center><img class='progressBar' src='images/step_bar_1.gif' alt='progress_step_bar' /><img class='progressBar' src='images/step_bar_2.gif' alt='progress_step_bar' /><img class='progressBar' src='images/step_bar_2.gif' alt='progress_step_bar' /></center></div>" + second_basket + "<div id='kod_rabatowy'><div id='messageKod'> </div><span>Kod rabatowy:</span> <input id='kod_rabatowy_value' type='text' /><input id='checkRabat' type='submit' value='Sprawdź' /></div><img src='images/arrow_right.gif' class='tooltip arrow_right' title='Przejdź do kroku 2' />");
        readCookie("kod_rabatowy") ? $("#kod_rabatowy_value", baskeet).val(readCookie("kod_rabatowy")) : "";
        readCookie("kod_rabatowy") ? $("#kod_rabatowy_value", baskeet).attr("disabled", "disabled") : "";
        $("#checkRabat", baskeet).click(function() {
            $("#messageKod").css("opacity", 0);
            var kod = $("#kod_rabatowy_value", baskeet).val();
            if (kod.length > 7) 
            {
                isValid = checkKodRabatowy(kod);
                if (isValid) 
                {
                    $("#messageKod").html("<b>Kod Prawidłowy</b>").animate(
                    {
                        "opacity": 1.0
                    }, 1000, function() {
                        $(this).animate(
                        {
                            "opacity": 0
                        }, 3000)
                    });
                    $("#kod_rabatowy_value", baskeet).attr("disabled", "disabled")
                }
                else $("#messageKod").html("<b>Nieprawidłowy kod</b>").animate(
                {
                    "opacity": 1.0
                }, 1000, function() {
                    $(this).animate(
                    {
                        "opacity": 0
                    }, 3000)
                })
            }
            else 
            {
                $("#messageKod").html("<b>Kod jest za krótki</b>").animate(
                {
                    "opacity": 1.0
                }, 1000)
            }
        });
        return baskeet
    }
    else         
        return null
}

function preloadImage(imageName, width, height) {
    preload_image = new Image(width, height);
    preload_image.src = imageName
}

function ieRenderFix(obj) {
    if (jQuery.browser.msie) 
        obj.get(0).style.removeAttribute('filter')
}

function createCookie(name, value, days) {
    if (days) 
    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString()
    }
    else var expires = "";
    document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/"
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) 
    {
        var c = ca[i];
        while (c.charAt(0) == ' ') 
            c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) 
            return removeTags(decodeURIComponent(c.substring(nameEQ.length, c.length)))
    }
    return null
}

function removeCookie(name) {
    createCookie(name, "", -1)
}

function removeTags(objToStripTagsFrom) {
    var strInputCode = objToStripTagsFrom;
    strInputCode = strInputCode.replace(/&(lt|gt);/g, function(strMatch, p1) {
        return (p1 == "lt") ? "<" : ">"
    });
    var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
    return strTagStrippedText
}

function initBox(fileToShowInBox, heightAuto) {
    fileToShowInBox = addslashes(fileToShowInBox);
    $("body").append("<div id='box'> </div>");
    var box = $("#box");
	if (heightAuto)
	 box.css("height", "auto");
    box.css("opacity", 0.9);
    box.css("top", ($(window).height() - box.height()) / 3 + $(window).scrollTop() + "px").css("left", ($(window).width() - box.width()) / 2 + "px");
    $("#box").load(fileToShowInBox, function() {
        tooltip(box);
        box.show(500);
        $("#closeX").click(function() {
            box.hide(500, function() {
                box.remove()
            })
        })
    })
}

function errorMessageBox(message, regulamin, width, height) {
    $("body").append("<div id='errorBox'>" + message + " </div>");
    var box = $("#errorBox");
    if (width && height) 
    {
        box.width(width);
        box.height(height)
    }
    box.hide();
    box.css("opacity", 0.9);
    box.css("top", ($(window).height() - box.height()) / 3 + "px").css("left", ($(window).width() - box.width() - parseInt(box.css("padding-left")) - parseInt(box.css("padding-right"))) / 2 + "px");
    if (regulamin) 
    {
        preFontSize = parseInt($("#regulaminDiv").css("font-size"));
        $("#regulaminDiv").animate(
        {
            "font-size": preFontSize + 8
        }, 500, function() {
            $("#regulaminDiv").animate(
            {
                "font-size": preFontSize
            }, 500)
        })
    }
    box.show(300, function() {
        box.animate(
        {
            "height": parseInt(box.css("height")) + 1
        }, 3000, function() {
            box.hide(2000, function() {
                box.remove()
            })
        })
    })
}

function isLogged() {
    response = "";
    $.ajax(
    {
        url: "lib/isLogged.php",
        type: 'POST',
        async: false,
        cache: false,
        data: 
        {
            "action": "isLogged"
        },
        timeout: 10000,
        success: function(myJSONtext) {
            response = myJSONtext
        }
    });
    if (response) 
        return true;
    else         
        return false
}

function loginForm(entrance) {
	var myObject;
    if ((((readCookie("id_klienta") != null) && isLogged()) || readCookie("visitor_token") == entrance) && entrance != "log_in") 
    {
        $.ajax(
        {
            url: "lib/init_cookies_from_customer.php",
            type: 'POST',
            async: false,
            cache: false,
            data: 
            {
                "action": "init_cookies_from_customer"
            },
            timeout: 10000,
            success: function(myJSONtext) {
                if (myJSONtext) 
                    myObject = eval('(' + myJSONtext + ')');
                if (myObject) 
                {
                    for (var key in myObject) 
                    {
                        createCookie(key, myObject[key], 30);
                    }
                    loggedInVersion = true;
                }
            }
        });
        var panelAdministracyjnyContainer = $("<div id='panelAdministracyjnyContainer'><div id='innerPanelAdministracyjny'><div id='closePanel'><img width='24' height='24' src='images/close_button_control_hover.gif' /></div><div id='log_out'>Wyloguj się</div><div id='panelTop'> </div></div><img id='panelButton' width='20' height='461' src='images/panel_administracyjny.gif' /></div>");
        $("#innerPanelAdministracyjny", panelAdministracyjnyContainer).hide();
        $("#panelTop", panelAdministracyjnyContainer).load("lib/panel.php", 
        {
            "action": "panel"
        });
        $("body").prepend(panelAdministracyjnyContainer);
        panelAdministracyjnyContainer.hide();
        panelAdministracyjnyContainer.show(400);
        hoverSrcEffect("#closePanel img", "images/close_button_control.gif", "images/close_button_control_hover.gif");
        $("#closePanel img").click(function() {
            panelAdministracyjnyProcedure("hide")
			
        });
        preWidth = "45px";
        $("#panelButton").click(function() {
            if ($("#messageWindow").length) 
                $("#messageWindow").hide(200, function() {
                    position = -1;
                    $("#messageWindow").remove();
                    krok = 1
                });
            if ($("#innerPanelAdministracyjny:hidden")) 
                panelAdministracyjnyProcedure("show");
            else panelAdministracyjnyProcedure("hide")
        });
        $("#log_out").click(function() {
            $.ajax(
            {
                url: "lib/logout.php",
                type: "POST",
                async: false,
                cache: false,
                data: 
                {
                    "action": "logout"
                },
                timeout: 10000,
                success: function(myJSONtext) {
                    if (myJSONtext == readCookie("visitor_token")) 
                    {
                        removeCookie("id_klienta");
                        panelAdministracyjnyContainer.hide(400, function() {
                            loggedInVersion = false;
                            panelAdministracyjnyContainer.remove();
                            loginForm("log_in")
                        })
                    }
                }
            })
        })
    }
    else 
    {
        var loginFormContainer = $("<div id='loginFormContainer'><div id='loginForm'><div id='closePanel'><img width='24' height='24' src='images/close_button_control_hover.gif' /></div><form><div class='tooltip' title='Twój login to e-mail podany podczas zamówienia'>Login: <input id='loginLogin' type='text' /></div><div>Hasło: <input id='loginHaslo' type='password' autocomplete='off' /></div><div align='right' style='margin-top: 20px;'><input type='submit' id='logIn' value='Zaloguj się' /></div></form><span id='remind_pw' style='margin-top: 10px;' class='small_links'>Przypomnij hasło</span><br /><span class='small_links tooltip' title='Rejestracja odbywa się wyłącznie podczas zamawiania video kursów. Aby zamówić kurs wystarczy przejść na jedną ze stron z opisem i dodać kurs do koszyka.'>Zarejestruj się</span></div><img id='zalogujSieButton' width='25' height='249' src='images/zaloguj_sie.gif' alt='Zaloguj się image' class='tooltip' title='Kliknij, aby rozwinąć menu logowania się' /></div>");
        $("#remind_pw", loginFormContainer).click(remindPassword);
        $(".small_links", loginFormContainer).css(
        {
            "font-size": 10 + "px",
            "color": "teal"
        });
        $(".small_links", loginFormContainer).hover(function() {
            $(this).css(
            {
                "color": "#06376C",
                "cursor": "pointer"
            })
        }, function() {
            $(this).css(
            {
                "color": "teal"
            })
        });
        $("#loginForm", loginFormContainer).hide();
        $("#logIn", loginFormContainer).click(function() {
            $.ajax(
            {
                url: "lib/login.php",
                type: 'POST',
                async: false,
                cache: false,
                data: 
                {
                    "action": "login",
                    "loginLogin": $("#loginLogin", loginFormContainer).val(),
                    "loginHaslo": $("#loginHaslo", loginFormContainer).val()
                },
                timeout: 10000,
                success: function(myJSONtext) {
                    if (readCookie("visitor_token") == myJSONtext) 
                    {
                        loginFormContainer.hide(300, function() {
                            loginFormContainer.remove();
                            if ($("#messageWindow").length) 
                            {
                                $("#messageWindow").hide(200, function() {
                                    position = -1;
                                    $("#messageWindow").remove();
                                    krok = 1
                                })
                            }
                            loginForm(myJSONtext)
                        })
                    }
                    else 
                    {
                        alert("niepoprawny login lub hasło")
                    }
                }
            });
            return false
        });
        $("body").prepend(loginFormContainer);
        hoverSrcEffect("#closePanel img", "images/close_button_control.gif", "images/close_button_control_hover.gif");
        tooltip("#loginFormContainer");
        $("#closePanel img").css("margin-top", "-7px");
        $("#closePanel img").click(function() {
            $("#loginFormContainer").animate(
            {
                "width": 45 + "px"
            }, 500, function() {
                $("#loginForm").hide()
            })
        });
        preWidth = "45px";
        $("#zalogujSieButton").click(function() {
            $("#tooltip").hide();
            $("#loginFormContainer").animate(
            {
                "width": 300 + "px"
            }, 500, function() {
                $("#loginForm").show(500)
            })
        })
    }
}

function panelAdministracyjnyProcedure(whatToDo) {
    if (whatToDo == "show") 
        $("#panelAdministracyjnyContainer").animate(
        {
            "width": 900 + "px"
        }, 500, function() {
            $("#innerPanelAdministracyjny").show(500)
        });
    else if (whatToDo == "hide") 
        $("#panelAdministracyjnyContainer").animate(
        {
            "width": 45 + "px"
        }, 500, function() {
            $("#innerPanelAdministracyjny").hide();
        });
}

function checkEmailInDatabase() {
    isEmailInDatabase = false;
    $.ajax(
    {
        url: "lib/check_email.php",
        type: 'POST',
        async: false,
        cache: false,
        data: 
        {
            "action": "check_email",
            "email": readCookie("email")
        },
        timeout: 10000,
        success: function(myJSONtext) {
            if (myJSONtext == readCookie("visitor_token")) 
                isEmailInDatabase = true;
        }
    });
    return isEmailInDatabase;
}

function remindPassword() {
    initBox("lib/remind_pw.php", true);
    return false;
}

function addslashes(str) {
    return (str + '').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
}

function checkKodRabatowy(kod) {
    isKodValid = false;
    $.ajax(
    {
        url: "lib/kod_validation.php",
        type: 'POST',
        async: false,
        cache: false,
        data: 
        {
            "action": "kod_validation",
            "kod_rabatowy": kod
        },
        timeout: 10000,
        success: function(myJSONtext) {
            if (myJSONtext != 0) 
            {
                createCookie("upust", myJSONtext, 1);
                createCookie("kod_rabatowy", kod, 1);
                isKodValid = true;
                setPrice(countPrice("upust_count"))
            }
        }
    });
    return isKodValid;
}
function input_change(fromWhere)
{
	if($.browser.msie)
	$(".course_version_img", fromWhere).css("margin-left", 36);
	
	if($.browser.msie)
	{
		$img = $("label img", fromWhere);
 
		$img.click(function(e) 
		{
			$("#" + $(this).parent().attr("for"))
				.change()
				.click();
		});
	}
	$("img:not(.current_input img)", fromWhere).css("opacity", 0.6);
	$("label, input", fromWhere).click(function(evt)
	{
		 if ($(this)[0].nodeName == "LABEL")
		 {
		 	   if(!$.browser.msie)
		 		if ($(".current_input label", fromWhere).attr("for") == $(this).attr("for")) 
				return;
				
		 }
		
		
		div = $(this).parent("div").parent("div");
		if($.browser.msie)
			div = $(this).parent("div");
			
		$("div .current_input img", fromWhere).css("opacity", 0.6);
		$("div", fromWhere).removeClass("current_input");
		
		div.addClass("current_input");
		$("div .current_input img", fromWhere).css("opacity", 1);
		
		
	});
}

function showTheFilm(lessonToPlay, width, height, title, fileURL, fileExtension)
{ 
   $.ajax(
    {
        url: "lib/make_hash.php",
        type: 'POST',
        async: false,
        cache: false,
        data: 
        {
            "action": "make_hash",
			"lessonToPlay": lessonToPlay,
			"download": 0
        },
        timeout: 10000,
        success: function(hash) {
            if (hash != 0) 
            {
		
				// insertAdjacentHTML(), insertAdjacentText() and insertAdjacentElement() 
					// for Netscape 6/Mozilla by Thor Larholm me@jscript.dk 
					// Usage: include this code segment at the beginning of your document 
					// before any other Javascript contents. 
					if (!fileExtension)
						fileExtension = "flv";		
					
					
					if(typeof HTMLElement!="undefined" && ! HTMLElement.prototype.insertAdjacentElement)
					{ 
						HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode)
							{ 
								switch (where)
								{ 
									case 'beforeBegin': 
									this.parentNode.insertBefore(parsedNode,this) ;
									break; 
									case 'afterBegin': 
									this.insertBefore(parsedNode,this.firstChild); 
									break; 
									case 'beforeEnd': 
									this.appendChild(parsedNode); 
									break; 
									case 'afterEnd': 
									if (this.nextSibling) 
										this.parentNode.insertBefore(parsedNode,this.nextSibling); 
									else this.parentNode.appendChild(parsedNode); 
										break; 
								} 
							};
					
						HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr)
						{ 
							var r = this.ownerDocument.createRange(); 
							r.setStartBefore(this); 
							var parsedHTML = r.createContextualFragment(htmlStr); 
							this.insertAdjacentElement(where,parsedHTML);
						};
					
					
						HTMLElement.prototype.insertAdjacentText = function (where,txtStr)
						{ 
							var parsedText = document.createTextNode(txtStr);
							this.insertAdjacentElement(where,parsedText) ;
						};
					}
					/* Code by armiksos */
					//setting title of the movie
					
					document.getElementById("film_title").innerHTML = title+"<a href='javascript:hideMe();'><img id='exit_movie' src='exit.png' alt='exit' /></a>";
					
				    var begin = document.getElementById("film");
					
				    //removing object if it existed
				    if (begin.getElementsByTagName("object")[0]) 
				        begin.removeChild(begin.getElementsByTagName("object")[0]);
				
				 	
				    //creating object
					var fullPath = fileURL+lessonToPlay+"HS"+hash+"."+fileExtension;
					if (!fileURL)
					fullPath = "http://films.video-courses-online.com/video-kursy/free/"+lessonToPlay+".flv";
					
					if ( ($(window).height()-height - 56) < 0)					
					{
						width = 320;
						height = 320;
					}	
								
					begin.insertAdjacentHTML("beforeEnd", " <object id='player' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' name='player' width='"+width+"' height='"+height+"'>	     <param name='movie' value='player-licensed.swf' />	     <param name='allowfullscreen' value='true' />	     <param name='allowscriptaccess' value='always' />	     <param name='flashvars' value='file="+fullPath+"' />	       	<embed				type='application/x-shockwave-flash'					id='player2'					name='player2'					src='player-licensed.swf'					width='"+width+"'					height='"+height+"'					allowscriptaccess='always'					allowfullscreen='true'					flashvars='file="+fullPath+"' /> </object>");
					 
					
				    //showing the shadow in the background	
				    document.getElementById('shadow').style.display = 'block';
				    
				    //setting the movie in the middle
				   			
			
				    var _docHeight = (document.height !== undefined) ? document.height : document.body.offsetHeight;
				    document.getElementById("shadow").style.height = _docHeight+"px";
				    document.getElementById('film').style.display = 'block';
				    document.getElementById('film').style.top = $(window).scrollTop()+15+"px";
				    document.getElementById('film').style.left = (($(window).width() - width) / 2) + "px";
    
            }
        }
    });
	
	
}
function setVideoToMiddle(video)
{
	$(video).css('top', ($(window).scrollTop()+15));
}
function setPanelLoginAdmin(panel)
{
	$(panel).css('top', ($(window).scrollTop()+20));
}
function hideMe(){
    //hiding shadow and the movie					
    document.getElementById("shadow").style.display = "none";
    document.getElementById("film").style.display = "none";
}
/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2009 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) 
	Version: 1.2.2 (03/09/2009 22:39:06)
*/
(function(a){var c=(a.browser.msie?"paste":"input")+".mask";var b=(window.orientation!=undefined);a.mask={definitions:{"9":"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"}};a.fn.extend({caret:function(e,f){if(this.length==0){return}if(typeof e=="number"){f=(typeof f=="number")?f:e;return this.each(function(){if(this.setSelectionRange){this.focus();this.setSelectionRange(e,f)}else{if(this.createTextRange){var g=this.createTextRange();g.collapse(true);g.moveEnd("character",f);g.moveStart("character",e);g.select()}}})}else{if(this[0].setSelectionRange){e=this[0].selectionStart;f=this[0].selectionEnd}else{if(document.selection&&document.selection.createRange){var d=document.selection.createRange();e=0-d.duplicate().moveStart("character",-100000);f=e+d.text.length}}return{begin:e,end:f}}},unmask:function(){return this.trigger("unmask")},mask:function(j,d){if(!j&&this.length>0){var f=a(this[0]);var g=f.data("tests");return a.map(f.data("buffer"),function(l,m){return g[m]?l:null}).join("")}d=a.extend({placeholder:"_",completed:null},d);var k=a.mask.definitions;var g=[];var e=j.length;var i=null;var h=j.length;a.each(j.split(""),function(m,l){if(l=="?"){h--;e=m}else{if(k[l]){g.push(new RegExp(k[l]));if(i==null){i=g.length-1}}else{g.push(null)}}});return this.each(function(){var r=a(this);var m=a.map(j.split(""),function(x,y){if(x!="?"){return k[x]?d.placeholder:x}});var n=false;var q=r.val();r.data("buffer",m).data("tests",g);function v(x){while(++x<=h&&!g[x]){}return x}function t(x){while(!g[x]&&--x>=0){}for(var y=x;y<h;y++){if(g[y]){m[y]=d.placeholder;var z=v(y);if(z<h&&g[y].test(m[z])){m[y]=m[z]}else{break}}}s();r.caret(Math.max(i,x))}function u(y){for(var A=y,z=d.placeholder;A<h;A++){if(g[A]){var B=v(A);var x=m[A];m[A]=z;if(B<h&&g[B].test(x)){z=x}else{break}}}}function l(y){var x=a(this).caret();var z=y.keyCode;n=(z<16||(z>16&&z<32)||(z>32&&z<41));if((x.begin-x.end)!=0&&(!n||z==8||z==46)){w(x.begin,x.end)}if(z==8||z==46||(b&&z==127)){t(x.begin+(z==46?0:-1));return false}else{if(z==27){r.val(q);r.caret(0,p());return false}}}function o(B){if(n){n=false;return(B.keyCode==8)?false:null}B=B||window.event;var C=B.charCode||B.keyCode||B.which;var z=a(this).caret();if(B.ctrlKey||B.altKey||B.metaKey){return true}else{if((C>=32&&C<=125)||C>186){var x=v(z.begin-1);if(x<h){var A=String.fromCharCode(C);if(g[x].test(A)){u(x);m[x]=A;s();var y=v(x);a(this).caret(y);if(d.completed&&y==h){d.completed.call(r)}}}}}return false}function w(x,y){for(var z=x;z<y&&z<h;z++){if(g[z]){m[z]=d.placeholder}}}function s(){return r.val(m.join("")).val()}function p(y){var z=r.val();var C=-1;for(var B=0,x=0;B<h;B++){if(g[B]){m[B]=d.placeholder;while(x++<z.length){var A=z.charAt(x-1);if(g[B].test(A)){m[B]=A;C=B;break}}if(x>z.length){break}}else{if(m[B]==z[x]&&B!=e){x++;C=B}}}if(!y&&C+1<e){r.val("");w(0,h)}else{if(y||C+1>=e){s();if(!y){r.val(r.val().substring(0,C+1))}}}return(e?B:i)}if(!r.attr("readonly")){r.one("unmask",function(){r.unbind(".mask").removeData("buffer").removeData("tests")}).bind("focus.mask",function(){q=r.val();var x=p();s();setTimeout(function(){if(x==j.length){r.caret(0,x)}else{r.caret(x)}},0)}).bind("blur.mask",function(){p();if(r.val()!=q){r.change()}}).bind("keydown.mask",l).bind("keypress.mask",o).bind(c,function(){setTimeout(function(){r.caret(p(true))},0)})}p()})}})})(jQuery);
function ieFixes()
{
	if ($.browser.msie && $.browser.version.substr(0,1) == 6)
		$(".lekcja_add_button").css("margin-left", -23);
}
function post_to_url(path, params, method) 
{
    method = method || "post"; // Set method to post by default, if not specified.

    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
    }

    document.body.appendChild(form);    
    form.submit();
}
function ajax_loader()
{
	$("body").append("<div id='loading'><img src='images/ajax-loader.gif' alt='wczytuję' /><div>");
        var loader = $("#loading");
        loader.css("opacity", 0.9);
        loader.css("top", ($(window).height() - loader.height()) / 3 + "px").css("left", ($(window).width() - loader.width() - parseInt(loader.css("padding-left")) - parseInt(loader.css("padding-right"))) / 2 + "px");
 	$("#loading").hide();
	$('#loading').ajaxStart(function() {
		
		$(this).css('top', ($(window).scrollTop()+100));
	    $(this).show();
	}).ajaxComplete(function() {
	    $(this).hide();
	});
}

