var tocompare_num = 0;

function toCompare(checkbox, cikkcsop, id, sid) {
	
	var action = $j(checkbox).attr('checked') ? 'add' : 'remove';
	
	if (tocompare_num == "4" && action == 'add') {
		alert('Maximum 4 terméket jelölhetsz ki összehasonlításra!');
		checkbox.checked = false;
		return;
	}
	
	$j.ajax({
		url: "/modul/cikkcsoport_tocompare.php",
		type: 'POST',
		data: ({
			todo: action,
			group: cikkcsop,
			id: id,
			sid: sid
		}),
		success: function(data) {
			//document.getElementById('tocompare').innerHTML = data + ' termék vár összehasonlításra';
			tocompare_num = data;
		}
	});
}

function compareRemove(cikkcsop, id, sid) 
{
	action = 'remove';
	$.ajax({
		url: "/modul/cikkcsoport_tocompare.php",
		type: 'POST',
		data: ({
			todo : action,
			group: cikkcsop,
			id : id,
			sid: sid
		}),
		success: function(data) {
			//document.getElementById('tocompare').innerHTML = data + ' termék vár összehasonlításra';
			tocompare_num = data;
			if (data == 0)
			{
				window.close();
			}
			else
			{
				window.location.reload();
			}
			window.opener.location.reload();
		}
	});
}

function addToFavourites(id, sid)
{
	$.ajax({
		url: "/modul/cikk_kedvenc.php",
		type: 'POST',
		data: ({
			action: 'add',
			id: id,
			sid: sid
		}),
		success: function(data) {
			if (data == '')
				$j('#addtofavourites').html('A terméket elmentettük a <a href="/kedvenceim" style="text-decoration:underline;">kedvenceid</a> közé.');
			else
				alert(data);
		}
	});
}

function delFromFavourites(id, sid)
{
	$.ajax({
		url: "/modul/cikk_kedvenc.php",
		type: 'POST',
		data: ({
			action: 'del',
			id: id,
			sid: sid
		}),
		success: function(data) {
			if (data == '')
				$j('#favourite_'+id).remove();
			else
				alert(data);
		}
	});
}

function doCompare(cikkcsop, sid) {
	if (tocompare_num < 2) {
		alert('Minimum 2 terméket ki kell jelölnöd a funkció használatához!');
		return;
	}
	
	width = 180 + (tocompare_num * 180);
	
	window.open("/modul/cikk_osszehasonlitas.php?group="+cikkcsop+"&sid="+sid, "mywindow",
		"menubar=1,resizable=1,scrollbars=1,width="+width+",height=700");
	
// $("a[rel=compare]").fancybox().trigger('click');	
}

/*
function searchRefine(checkbox) {
	name = checkbox.name;
	value = checkbox.value;
	
	action = 'remove';
	if (true == checkbox.checked)
		action = 'add';
	
	$j.get("/webshop/ajax/searchrefine", {
		value : value,
		field : name,
		todo : action
	}, function(data) {
		document.getElementById('total_count').innerHTML = data;
		tocompare_num = data;
	});
}
*/

function searchRefine(checkbox, cikkcsop, sid) {
	name = checkbox.name;
	value = checkbox.value;
	
	action = 'remove';
	if (true == checkbox.checked)
		action = 'add';
	
	$j('#total_count').load("/modul/cikkcsoport_szukites.php", {
		todo: action,
		group: cikkcsop,
		field: name,
		value: value,
		sid: sid
	});
}

function clearFilter(cikkcsop, sid) {
	$j('.left_box').find(':checkbox').attr('checked', false);
	$j('#total_count').load("/modul/cikkcsoport_szukites.php", {
		todo: 'clear',
		group: cikkcsop,
		sid: sid
	});
}

function doFilter ()
{
	window.location.reload();
}

function changeProductTab(id, count) {
    for (i = 1; i <= count; i++) {
        if (i != id) {
            if (document.getElementById('producttab_' + i))
                document.getElementById('producttab_' + i).style.display = 'none';
            if (document.getElementById('li_producttab_' + i))
                document.getElementById('li_producttab_' + i).className = '';
        }
    }
    document.getElementById('producttab_' + id).style.display = 'block';
    document.getElementById('li_producttab_' + id).className = 'active';
}

function addToCart(id, count, reload) {
    $.get("/webshop/ajax/addtocart", {
        id : id,
        count : count
    }, function(data) {
        refreshCartSumPrice();
        if (document.getElementById('header_cart'))
        {
            /*			if (reload == true)
				window.location.reload();
			else
				obj.innerHTML = data + ' tétel'; */
            window.location = '/webshop/cart';
        }
        else
        {
        //    window.opener.location.reload();
        //			window.opener.getElementById('header_cart').innerHTML = data + ' tétel';
        }
    });
}

function addToCartWithRelateds (id, count)
{	
    if (document.related_form)
    {
        fields = document.related_form.related;
		
        for (i = 0; i < fields.length; i++)
        {
            if (fields[i].checked == true)
            {
                addToCart(fields[i].value, count);
            }
        }
    }
    addToCart(id, count);
}


function addToCartAtStep3(id, count)
{
    addToCart(id, count, true);
//	window.location.reload();
}

function removeFromCart(id, url) {
    if (!confirm('Biztosan törölni szeretnéd?'))
        return;
    $.get("/webshop/ajax/removefromcart", {
        id : id
    }, function(data) {
        document.getElementById('header_cart').innerHTML = data + ' tétel';
        document.getElementById('cart_item_' + id).style.display = 'none';
        refreshCartSumPrice();
        if (url)
            window.location = url;
    });
}

function changeCartItemCount(id, url, item_price) 
{
    obj = document.getElementById('count_' + id);
    count = obj.options[obj.selectedIndex].value;
    item_obj = document.getElementById('item_sum_' + id);
    item_obj.innerHTML = FormatNumberBy3(count * item_price, ",", ".");
	
    $.post("/webshop/ajax/changeitemcountincart", {
        id : id,
        count: count
    }, function(data) {
        refreshCartSumPrice();
        if (url)
            window.location = url;
    });
}


function refreshCartSumPrice() {
    $.get("/webshop/ajax/getcartumprice", {}, function(data) {
        obj = document.getElementById('cart_sum_price');
        if (obj)
            obj.innerHTML = data;
    });
}

function register(url) 
{
    var error_text = 'ok';
    var fields = new Array('familyname', 'firstname', 'email', 'phone',
        'password', 'repassword', 'billingname', 'billingzip',
        'billingaddress');
    var email = document.getElementById('email').value;
    var emailfilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    for (a = 0; a < fields.length; a++) {
        if (document.getElementById(fields[a]).value == '') {
            error_text = 'Kérjük, tölts ki minden mezőt!';
            alert(error_text);
            return false;
        }
    }
    if (!emailfilter.test(email)) {
        error_text = 'Nem megfelelő az email cím formátuma!';
        alert(error_text);
        return false;
    }
	
    if (document.getElementById('password').value != document.getElementById('repassword').value)
    {
        error_text='A két jelszó nem egyezik!';
        alert (error_text);
        return false; 
    }

    $.post("/ajax/zipvalid", {
        zip: document.getElementById('billingzip').value
    }, function(data) {
        if (data == '')
        {
            alert ('Csak létező, magyarországi, négy számjegyből álló irányítószámot adhatsz meg.');
            return false;
        }
        doRegister(url);
    });
//	$('#registration').submit();
//	return false;
}

function update() {
    var error_text = 'ok';
    var fields = new Array('familyname', 'firstname', 'email', 'phone',
        'billingname', 'billingzip', 'billingaddress');
    var email = document.getElementById('email').value;
    var emailfilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    for (a = 0; a < fields.length; a++) {
        if (document.getElementById(fields[a]).value == '') {
            error_text = 'Kérjük, tölts ki minden mezőt!';
            alert(error_text);
            return false;
        }
    }
    if (!emailfilter.test(email)) {
        error_text = 'Nem megfelelő az email cím formátuma!';
        alert(error_text);
        return false;
    }
	
    if (document.getElementById('password').value != document.getElementById('repassword').value)
    {
        error_text='A két jelszó nem egyezik!';
        alert (error_text);
        return false; 
    }
	
    $.post("/ajax/zipvalid", {
        zip: document.getElementById('billingzip').value
    }, function(data) {
        if (data == '')
        {
            alert ('Csak létező, magyarországi, négy számjegyből álló irányítószámot adhatsz meg.');
            return false;
        }
        doUpdate();
    });
}

function doRegister(url)
{
    var fields = new Array('familyname', 'firstname', 'email', 'phone',
        'password', 'repassword', 'billingname', 'billingzip',
        'billingaddress');
    $.post("/ajax/userregister", {
        familyname: document.getElementById(fields[0]).value,
        firstname: document.getElementById(fields[1]).value,
        email: document.getElementById(fields[2]).value,
        phone: document.getElementById(fields[3]).value,
        password: document.getElementById(fields[4]).value,
        repassword: document.getElementById(fields[5]).value,
        billingname: document.getElementById(fields[6]).value,
        billingzip: document.getElementById(fields[7]).value,
        billingaddress: document.getElementById(fields[8]).value,
        city : document.getElementById('city').value,
        zip : document.getElementById('zip').value
    }, function(data) {
        if (data == '') // minden OK
        {
            //			window.location = '/webshop/order/step2';
            if (url)
                window.location = url;
        //	alert('Sikeres regisztráció');
        }
        else
        {
            alert (data);
        }
    });
}

function doUpdate()
{
    var fields = new Array('familyname', 'firstname', 'email', 'phone',
        'password', 'repassword', 'billingname', 'billingzip',
        'billingaddress');
    $.post("/ajax/userupdate", {
        familyname: document.getElementById(fields[0]).value,
        firstname: document.getElementById(fields[1]).value,
        email: document.getElementById(fields[2]).value,
        phone: document.getElementById(fields[3]).value,
        password: document.getElementById(fields[4]).value,
        repassword: document.getElementById(fields[5]).value,
        billingname: document.getElementById(fields[6]).value,
        billingzip: document.getElementById(fields[7]).value,
        billingaddress: document.getElementById(fields[8]).value,
        city : document.getElementById('city').value,
        zip : document.getElementById('zip').value
    }, function(data) {
        if (data == '') // minden OK
        {
            window.location = '/webshop/order/step2/';
        }
        else
        {
            alert (data);
        }
    });
}

function checkoutstep2(){

    if (document.getElementById('shipping_1').checked == false &&
        document.getElementById('shipping_2').checked == false)
        {
        alert ("Kérünk, válaszd ki az átvétel módját!");
        return false;
    }
	
    if (document.getElementById('pay_1').checked == false && 
        document.getElementById('pay_2').checked == false &&
        document.getElementById('pay_3').checked == false &&
        document.getElementById('pay_4').checked == false)
        {
        alert ("Kérünk, válaszd ki a fizetési módot!");
        return false;
    }
    
    if (document.getElementById('shipping_2').checked == true && 
        (document.getElementById('shop_id').value == '' || document.getElementById('shop_id').value == '0'))
        {
        alert ("Személyes átvétel esetén ki kell választanod az üzletet, ahol szeretnéd a termék(ek)et átvenni!");
        return false;
    }
    
    $('#checkoutstep2').submit();
//	window.location = '/webshop/order/step3';
}

function filterShopSelect(town)
{
    $.get("/webshop/ajax/getshopselect", {
        town: town
    }, function(data) {
        obj = document.getElementById('shop_select');
        if (obj)
            obj.innerHTML = data;
    });
}

function setShop(shop_id)
{
    obj = document.getElementById('shop_id');
    if (obj)
        obj.value = shop_id;
}

function order_check()
{
    if (document.getElementById('accept').checked == false)
    {
        alert ("Kérünk, a megrendeléshez fogadd el a vásárlási feltételeket!");
        return
    }
    $('#checkoutstep3').submit();
}

function forgottenPassword()
{
    email = document.getElementById('login_email').value;
    if (email == "" || email == "Email cím")
    {
        alert('Az elfelejtett jelszó visszaállításához meg kell adnod az email címedet!');
        return;
    }

    $.post("/ajax/forgottenpassword", {
        email: email
    }, function(data) {
        if (data != "")
        {
            alert(data);
            return;
        }
        else
        {
            //alert ('Új jelszó beállításához kérlek ellenőrizd az email fiókodat és kövesd a leírtakat!');
            document.getElementById('message').innerHTML = 'Email címedre elküldtük az új jelszó megadásához szükséges linket.';
        }
    });
	
}

function newsletterSubscribe ()
{
    name = document.getElementById('newsletter_name').value;
    email = document.getElementById('newsletter_email').value;
	
    if (name == "" || name == "Neved" || email == "" || email == "Email címed")
    {
        alert('A feliratkozáshoz ki kell töltened mindegyik mezőt!');
        return;
    }

    $.post("/ajax/newslettersubscribe", {
        name: name,
        email: email
    }, function(data) {
        obj = document.getElementById('newsletter_form');
        if (data != "")
        {
            alert(data);
            return;
        }
        if (obj)
            obj.innerHTML = 'Hírlevélfeliratkozás sikeres.';
    });
}

function couponRequest ()
{
    name = document.getElementById('coupon_name').value;
    email = document.getElementById('coupon_email').value;
	
    if (name == "" || name == "Neved" || email == "" || email == "Email címed")
    {
        alert('A kuponok megszerzéséhez ki kell töltened mindegyik mezőt!');
        return;
    }

    $.post("/ajax/couponrequest", {
        name: name,
        email: email
    }, function(data) {
        obj = document.getElementById('coupon_form');
        if (data != "")
        {
            alert(data);
            return;
        }
        if (obj)
            obj.innerHTML = 'A kuponokot elküldtük email címedre.';
        alert('A kuponokot elküldtük az email címedre.');
    });
}

function validateCoupon ()
{
    code = document.getElementById('coupon_code').value;
    if (code == "")
    {
        alert('Írd be ide a kuponod számát amit emailben kaptál!');
        return;
    }

    $.post("/ajax/couponvalidate", {
        code: code
    }, function(data) {
        if (data == "")
            alert('Rossz kuponkód\n\nLehetséges okok:\n1. Elírtad a kódot (Fontos, hogy pontosan úgy írd be, ahogyan megkaptad)\n2. Nem létezik ilyen kód, soha nem is létezett\n3. Lejárt az akció (Ellenőrizd a kuponon a határidőt)\n4. Nincs a kosárban olyan termék, amire ez a kód vonatkozik\n5. Technikai probléma (Ha ez áll fenn, akkor elnézésedet kérjük, és feltétlenül fordulj az Ügyfélszolgálathoz)');
        else
        {
            obj = document.getElementById('coupon_validate_form');
            if (obj)
                obj.innerHTML = 'Kuponod érvényes, a végösszegből levonunk <b> ' + data + '</b> Ft-ot';
        }
			
    //	obj.innerHTML = 'A kuponokot elküldtük e-mail címedre.';
    });
}

function doLogin(url)
{
    email = document.getElementById('login_email').value;
    password = document.getElementById('login_password').value;
    $.post("/ajax/dologin", {
        email: email,
        password: password
    }, function(data) {
        if (data != "")
        {
            alert(data);
        }
        else
        {
            //alert('Sikeres bejelentkezés');  // ez egyelőre kell valamiért...
            if (url)
                window.location = url;
            else
                window.location = '/webshop/order/step1';
        }
    });
}

function contact_submit()
{
    var error_text = 'ok';
    var fields = new Array('contact_name', 'contact_email', 'contact_message', 'contact_zip');
    var email = document.getElementById('contact_email').value;
    var emailfilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if (document.getElementById('contact_name').value == '')
    {
        error_text = 'A név kitöltése kötelező!';
        alert(error_text);
        return false;
    }

    if (!emailfilter.test(email)) {
        error_text = 'Nem megfelelő az email cím formátuma!';
        alert(error_text);
        return false;
    }

    if (document.getElementById('contact_message').value == '')
    {
        error_text = 'Az üzenet megadása kötelező!';
        alert(error_text);
        return false;
    }

    if (document.getElementById('contact_zip').value == '')
    {
        error_text = 'Az irányítószám megadása kötelező!';
        alert(error_text);
        return false;
    }
	
    $.post("/ajax/zipvalid", {
        zip: document.getElementById('contact_zip').value
    }, function(data) {
        if (data == '')
        {
            alert ('Csak létező, magyarországi, négy számjegyből álló irányítószámot adhatsz meg.');
        }
        else // minden OK
        {
            document.getElementById('contact_form').submit();
        }
    });
}

function compareDiffHighlight()
{
    sim = document.getElementsByName('similar');
    for ( var i in sim )
    {
        obj = sim[i];
        if (obj.style)
            obj.style.color = '#aaaaaa';
    }
}

function showProductPicture(img_src)
{
    document.getElementById('product_picture').src = '../_user/page/webshop/product/large/' + img_src;
}

function remName(a, b) {
    if(a.value==b) {
        a.value='';
    }
    else if(a.value=='') {
        a.value=b;
    }
    else {
        a.value=a.value;
    }
}

function chkName(a, b) {
    if(a.value=='') {
        a.value=b;
    }
    else {
        a.value=a.value;
    }
}

function refreshShippingCost(zip)
{
    $.post("/ajax/getshippingcostfromzip", {
        zip: zip
    }, function(data) {
        cost = data;
        document.getElementById('shippingcost').innerHTML = cost;
        document.getElementById('shipping_cost').value = cost;  // hidden input értéke
    });
}





