(function($) {
	/**
	 * plug-in for the inputs focus event
	 */
	$.fn.takeInputFocus = function() {
		this.each(function() {
			var me = new Object({
				value: $(this).attr('title')
				, name: $(this).attr('name').replace(/\$/g, "_")
            });

            if (me.value && me.value != "")
            {
			    if ($(this).parent().find('#fake_'+ me.name).length == 0)
				    $(this).parent().append('<div class="fake" id="fake_'+ me.name +'">'+ me.value +'</div>');

			    var fake = $('#fake_'+ me.name);
			
			    $(this).val('');
			    $(this).focus(function(){
				    fake.hide();
			    });
			    $(this).blur(function(){
				    if ($(this).val() == '')
					    fake.show();
			    });
			    fake.click(function() { fake.hide(); $('#'+ me.name).focus(); });
			}
		});
	};
	/**
	 * plug-in for highlight the product
	 */
	$.fn.takeProductHover = function() {
		this.each(function() {
			var parent = $(this).parent();
			$(this).hover(
				function(){
					parent.addClass('hover');
				},
				function(){
					parent.removeClass('hover');
				}
			);
		});
	};
})(jQuery);

function sendOrder(){
	if (termekek > 0){
		showShadow();
		$('#orderForm').ajaxSubmit({
			url: 'action/order.php'
			, target:'#mainContent'
			, success: function() {
				hideShadow();
		    }
		});
	}else{
		alert('Az Ön kosara jelenleg üres!');
	}
}

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

function SetButtons() {
    var first = $('#ctl00_RightContent_ProductsOnSale1_inpFirst').val();
    var last = $('#ctl00_RightContent_ProductsOnSale1_inpLast').val();
    var total = $('#ctl00_RightContent_ProductsOnSale1_inpTotal').val();

    if (total <= 4) {
        $("#bLeftDiv").parent().remove();
    }
    else {
        $("#bLeftDiv").parent().show();
    }
}

function ProductPrev() {
    var first = $('#ctl00_RightContent_ProductsOnSale1_inpFirst').val();
    var last = $('#ctl00_RightContent_ProductsOnSale1_inpLast').val();
    var total = $('#ctl00_RightContent_ProductsOnSale1_inpTotal').val();

    if (1 < first) {
        first--;
        last--;

        $('#ctl00_RightContent_ProductsOnSale1_inpFirst').val(first);
        $('#ctl00_RightContent_ProductsOnSale1_inpLast').val(last);

        SetButtons();
        ProductScroll();
    }
}

function ProductNext() {
    var first = $('#ctl00_RightContent_ProductsOnSale1_inpFirst').val();
    var last = $('#ctl00_RightContent_ProductsOnSale1_inpLast').val();
    var total = $('#ctl00_RightContent_ProductsOnSale1_inpTotal').val();

    if (last < total) {
        first++;
        last++;

        $('#ctl00_RightContent_ProductsOnSale1_inpFirst').val(first);
        $('#ctl00_RightContent_ProductsOnSale1_inpLast').val(last);

        SetButtons();
        ProductScroll();
    }
}

function ProductScroll() {
    var first = $('#ctl00_RightContent_ProductsOnSale1_inpFirst').val();
    var last = $('#ctl00_RightContent_ProductsOnSale1_inpLast').val();

    var language = $('#ctl00_RightContent_ProductsOnSale1_inpLanguageId').val();
    var defaultLang = $('#ctl00_RightContent_ProductsOnSale1_inpDefaultLangId').val();
    $.post("/Ajax/ProductScroll.aspx", { language: language, defaultLang: defaultLang, first: first, last: last },
        function (res) {
            if (res != "") {
                $("#ctl00_RightContent_ProductsOnSale1_productsContainer").html(res);
            }
        }
    );
}

function MISelected(menuItem) {
    var subDiv = $('#' + $(menuItem).attr('id') + '_sub');
    if (subDiv.html() == null)
        return;

    if (subDiv.css('display') == 'none')
        subDiv.css('display', 'block');
    else
        subDiv.css('display', 'none');
}

function cbReseller_Click(cb) {
    if ($(cb).is(":checked")) {
        $(".hide").show();
    }
    else {
        $(".hide").hide();
    }
}

function cbSameAsInvoice_Click(checkbox) {
    console.log("ok");
    if ($(checkbox).is(":checked")) {
        $('#tblShipmentAddress').hide();
    }
    else {
        $('#tblShipmentAddress').show();
    }
}

function rbType_Click(obj, targetObj) {
    if ($(obj).val() == 1) {
        $("#" + targetObj).show();
    }
    else {
        $("#" + targetObj).hide();
    }
}

function refreshCaptcha_Click() {
    var targetObj = "img[src^='/Captcha.aspx']";
    $(targetObj).attr("src", "/Captcha.aspx?r=" + Math.floor(Math.random() * 1001));
    $(targetObj).attr("class", "valami");
    return false;
}

function RegAddressChange() {
    var id = $('#ctl00_RightContent_ddlAddressList').val();

    if (id > 0) {
        $.post('/Ajax/RegAddress.aspx', { addressId: id },
            function (res) {
                if (res != '') {
                    var arr = JSON.parse(res);

                    $('#ctl00_RightContent_tbName').val(arr.name);
                    $('#ctl00_RightContent_ddlCountry').val(arr.countryId);
                    $('#ctl00_RightContent_tbZip').val(arr.zip);
                    $('#ctl00_RightContent_tbCity').val(arr.city);
                    $('#ctl00_RightContent_tbAddress').val(arr.address);
                    $('#ctl00_RightContebt_tbBankAccount').val(arr.bankAccount);
                    $('#ctl00_RightContent_tbTaxNumber').val(arr.taxNumber);
                    $('#ctl00_RightContent_tbEUTaxNumber').val(arr.EUTaxNumber);
                    $('#ct100_RightContent_ddlAddressList').val(arr.addressId);
                }
            }
        );
    }
    else {
        $('#ctl00_RightContent_tblInvoice input:text').val('');
    }
}

function InvoiceAddressChange() {
    var id = $('#ctl00_RightContent_ddlInvoiceAddressList').val();

    if (id > 0) {
        $.post('/Ajax/RegAddress.aspx', { addressId: id },
            function (res) {
                if (res != '') {
                    var arr = JSON.parse(res);

                    $('#ctl00_RightContent_tbInvoiceName').val(arr.name);
                    $('#ctl00_RightContent_ddlInvoiceCountry').val(arr.countryId);
                    $('#ctl00_RightContent_tbInvoiceZip').val(arr.zip);
                    $('#ctl00_RightContent_tbInvoiceCity').val(arr.city);
                    $('#ctl00_RightContent_tbInvoiceAddress').val(arr.address);
                    $('#ctl00_RightContebt_tbInvoiceBankAccount').val(arr.bankAccount);
                    $('#ctl00_RightContent_tbInvoiceTaxNumber').val(arr.taxNumber);
                    $('#ctl00_RightContent_tbInvoiceEUTaxNumber').val(arr.EUTaxNumber);
                    $('#ct100_RightContent_ddlInvoiceAddressList').val(arr.addressId);
                }
            }
        );
    }
    else {
        $('#ctl00_RightContent_tblInvoice input:text').val('');
    }
}

function ShipmentAddressChange() {
    var id = $('#ctl00_RightContent_ddlShipmentAddressList').val();

    if (id > 0) {
        $.post('/Ajax/RegAddress.aspx', { addressId: id },
            function (res) {
                if (res != '') {
                    var arr = JSON.parse(res);

                    $('#ctl00_RightContent_tbShipmentName').val(arr.name);
                    $('#ctl00_RightContent_ddlShipmentCountry').val(arr.countryId);
                    $('#ctl00_RightContent_tbShipmentZip').val(arr.zip);
                    $('#ctl00_RightContent_tbShipmentCity').val(arr.city);
                    $('#ctl00_RightContent_tbShipmentAddress').val(arr.address);
                    $('#ct100_RightContent_ddlShipmentAddressList').val(arr.addressId);
                }
            }
        );
    }
    else {
        $('#ctl00_RightContent_tblShipmentAddress input:text').val('');
    }
}

function AddToCart(productId, quantity) {
    $.post('/Ajax/AddToCart.aspx', { productId: productId, quantity: quantity },
        function (res) {
            if (res != '') {
                if (res == 'ERROR') {
                    alert("A termék kosárba helyezése közben hiba történt!");
                }
                else {
                    $("#ctl00_cartContent").html(res);
                    alert("A terméket hozzáadtuk a kosárhoz!");
                }
            }
        }
    );
}

function keyfilter(filter, event) {
    if (!event) event = window.event;
    var c = getCharCode(event);
    if (c && !filter(c)) cancelEvent(event);
}

function getCharCode(event) {
    return typeof (event.charCode) == "undefined" ? (event.keyCode || event.which) : event.charCode;
}

function cancelEvent(event) {
    if (!event) event = window.event;
    if (event.preventDefault) event.preventDefault();
    else event.returnValue = false;
}

function keyfilter_Decimal(event) {
    keyfilter(function (c) {
        return (c >= 48 && c <= 57) || c == 13 || c == 44 || c == 46
    }, event);
}

KeyListener = {
    init: function () {
        $('div#main').bind('keypress', function (e) {
            var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
            var target = e.target.tagName.toLowerCase();
            if (key === 13 && target === 'input') {
                e.preventDefault();

                var parentFieldset = $(e.target).parents('fieldset').first();

                if (parentFieldset.length > 0) {
                    var classnames = parentFieldset.attr('class').split(' ');

                    for (var i = 0; i < classnames.length; i++) {
                        if (classnames[i].substring(0, 7) == 'submit-') {
                            var button = $('a.' + classnames[i] + ', button.' + classnames[i] + ', input.' + classnames[i], $(this)).eq(0);
                            if (button.length > 0) {
                                if (typeof (button.get(0).onclick) == 'function') {
                                    button.trigger('click');return false;;
                                } else if (button.attr('href')) {
                                    window.location = button.attr('href');
                                } else {
                                    button.trigger('click');return false;;
                                }
                            }
                            break;
                        }
                    }
                }
            }
        });
    }
};

$(document).ready(function () {
    KeyListener.init();
    $('.bRefreshCaptcha').click(function () { refreshCaptcha_Click(); return false; });
    $("div.button.gray.pointer").hover(
				function () {
				    $(this).addClass("hover");
				    $(this).removeClass("gray");
				},
				function () {
				    $(this).removeClass("hover");
				    $(this).addClass("gray");
				}
			);
    $(".button input").takeInputFocus();
    $(".highlighted-product div.img").takeProductHover();

    if ($("div.errorLogin:visible").size()) {
        var highlighted = false;
        //$(window).scroll(function () {
        if (!highlighted && isScrolledIntoView($("div.errorLogin"))) {
            $("div.errorLogin:visible").effect("highlight", {}, 2000).delay(3000).fadeOut(800);
            $("#contact table input:first").focus();
            highlighted = true;
        }
        //});
    }
});
