var tocompare_num = 0;

function toCompare(id, checkbox) {
  status = checkbox.checked;
  action = 'remove';
  if (true == status)
    action = 'add';

  if (tocompare_num == "4" && action == 'add') {
    alert('Maximum 4 terméket jelölhet ki összehasonlításra!');
    checkbox.checked = false;
    return;
  }

  $.get("/webshop/ajax/compare",
  {
    id : id,
    todo : action
  },
  function(data) {
    document.getElementById('tocompare').innerHTML = data + ' termék vár összehasonlításra';
    tocompare_num = data;
  });
}

function compareRemove(id) 
{
  action = 'remove';
  $.get("/webshop/ajax/compare",
  {
    id : id,
    todo : action
  },
  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 check_special_field(product_id, special_field_id, special_field_value)
{
  $.get("/webshop/ajax/addspecialfieldproducts",
  {
    product_id :         product_id,
    special_field_id:    special_field_id,
    special_field_value: special_field_value
  },
  function(data) {
    });
}

function addToFavourites(id)
{
  $.get("/webshop/ajax/addtofavourites",
  {
    id : id
  },
  function(data) {
    if (data == '')
      document.getElementById('addtofavourites').innerHTML = 'A terméket elmentettük a <a href="/user/favourites" style="text-decoration:underline;">kedvencei</a> közé.';
    else
      alert(data);
  });
}

function doCompare() {
  if (tocompare_num < 2) {
    alert('Minimum 2 terméket ki kell jelölni a funkció használatához!');
    return;
  }

  width = 180 + (tocompare_num * 180);
	
  window.open("/webshop/category/compare", "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';

  $.get("/webshop/ajax/searchrefine", {
    value : value,
    field : name,
    todo : action
  }, function(data) {
    document.getElementById('total_count').innerHTML = data;
    tocompare_num = data;
  });
}

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

function changeProductTab(id) {
  for (i = 1; i <= 5; 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 (obj = 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 addToCartWithPrice(id, count, reload, price, url, upsale) {
  $.get("/webshop/ajax/addtocart", {
    id : id,
    count : count,
    price : price,
    upsale : upsale
  }, function(data) {
    refreshCartSumPrice();
    if (url)
      window.location = url;
    else
      window.location.reload();
  });
}

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, price, upsale)
{
  addToCartWithPrice(id, count, true, price, false, upsale);
//	window.location.reload();
}

function removeFromCart(id, url) {
  if (!confirm('Biztosan törölni szeretné?'))
    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, product_id)
{
  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,
    price : item_price,
    count: count,
    product_id: product_id
  }, 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 productRate(user_id, product_id, value)
{
  $.post("/webshop/ajax/productrate", {
    user_id: user_id,
    product_id: product_id,
    value: value
  }, function(data) {
    if (data == '') // minden OK
    {
      //			window.location = '/webshop/order/step2';
      /*            if (url)
                window.location = url; */
      //	alert('Sikeres regisztráció');
      document.getElementById('user_rating').style.display='none';
    }
    else
    {
      alert (data);
    }
  });
}

function register(url) 
{
  var error_text = 'ok';
  var fields = new Array('familyname', 'firstname', 'username', 'email', 'phone',
    'password', 'repassword', 'billingname', 'zip', 'city', 'country',
    '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öltse ki valamennyi 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; 
  }

  doRegister(url);

/*    $.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 adhat meg.');
            return false;
        }
        doRegister(url);
    }); */
//	$('#registration').submit();
//	return false;
}

function update() {
  var error_text = 'ok';
  var fields = new Array('familyname', 'firstname', 'username', 'email', 'phone',
    'billingname', 'zip', 'billingaddress', 'city');
  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öltse ki valamennyi 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') && document.getElementById('password').value != document.getElementById('repassword').value)
  {
    error_text='A két jelszó nem egyezik!';
    alert (error_text);
    return false; 
  }
	
  doUpdate();
}

function doRegister(url)
{
  var fields = new Array('familyname', 'firstname', 'username', 'email', 'phone', 'country',
    'password', 'repassword', 'billingname','zip',
    'billingaddress','lyoness_code','firmname');
    
  if (document.getElementById('newsletter').checked) 
    newsletter = 1;
  else
    newsletter = 0;    
    
  $.post("/ajax/userregister", {
    familyname: document.getElementById('familyname').value,
    firstname: document.getElementById('firstname').value,
    username: document.getElementById('username').value,
    email: document.getElementById('email').value,
    phone: document.getElementById('phone').value,
    password: document.getElementById('password').value,
//    repassword: document.getElementById(fields[6]).value,
    billingname: document.getElementById('billingname').value,
    billingzip: document.getElementById('zip').value,
    billingaddress: document.getElementById('billingaddress').value,
    lyoness_code : document.getElementById('lyoness_code').value,
    firmname : document.getElementById('firmname').value,
    country : document.getElementById('country').value,
    city : document.getElementById('city').value,
    zip : document.getElementById('zip').value,
    newsletter: newsletter
  }, 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', 'username', 'email', 'phone',
    'password', 'repassword', 'billingname', 'zip', 'city',
    'billingaddress', 'firmname', 'lyoness_code', 'country');

  familyname = document.getElementById(fields[0]).value;
  firstname  = document.getElementById(fields[1]).value;
  username = document.getElementById(fields[2]).value;
  email = document.getElementById(fields[3]).value;
  phone = document.getElementById(fields[4]).value;
  if (document.getElementById(fields[5]))
    password = document.getElementById(fields[5]).value;
  else
    password = '';
  if (document.getElementById(fields[6]))
    repassword = document.getElementById(fields[6]).value;
  else
    repassword = '';
  billingname = document.getElementById(fields[7]).value;
  billingaddress = document.getElementById(fields[10]).value;
  city = document.getElementById('city').value;
  country = document.getElementById('country').value;
  zip = document.getElementById('zip').value;
  firmname = document.getElementById('firmname').value;
  lyoness_code = document.getElementById('lyoness_code').value;

  if (document.getElementById('newsletter').checked) 
    newsletter = 1;
  else
    newsletter = 0;

  $.post("/ajax/userupdate", {
    familyname: familyname,
    firstname: firstname,
    username: username,
    email: email,
    phone: phone,
    password: password,
    repassword: repassword,
    billingname: billingname,
    billingaddress: billingaddress,
    city : city,
    country : country,
    zip : zip,
    firmname: firmname,
    lyoness_code: lyoness_code,
    newsletter: newsletter
  }, 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álassza ki az átvétel módját!");
    return false;
  }

  if (document.getElementById('shipping_1').checked == true && document.getElementById('transporter').value == '')
  {
    alert ("Házhozszállítás esetén ki kell választania a szállítót!");
    return false;
  }

  if (document.getElementById('shipping_2').checked == true)
  {
    //document.getElementById('shop_id').value == '' || document.getElementById('shop_id').value == '0'
    shop_id = document.getElementById('shop_select').options[document.getElementById('shop_select').selectedIndex].value;
    document.getElementById('shop_id').value = shop_id;
    if (shop_id == 0)
    {
      alert ("Személyes átvétel esetén ki kell választania az üzletet, ahol szeretné a termék(ek)et átvenni!");
      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érjük, válassza ki a fizetési módot!");
    return false;
  }
    
  $('#checkoutstep2').submit();
  return true;
//	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 fogadja el a vásárlási feltételeket!");
    return
  }
  $('#checkoutstep3').submit();
}

function szemelyesAtvetel()
{
  document.getElementById('szemelyes').className = 'active';
  document.getElementById('hazhozszallitas').className = 'inactive';
  document.getElementById('hazhozszallitas_labels').className = 'inactive';
  document.getElementById('shop_select').disabled = false;
  document.getElementById('shipping_cost').value = '0';
  document.getElementById('shippingname').disabled = true;
  document.getElementById('shippingzip').disabled = true;
  document.getElementById('shippingcity').disabled = true;
  document.getElementById('shippingaddress').disabled = true;
  document.getElementById('shippingname').className = 'input_field_content_inactive';
  document.getElementById('shippingcity').className = 'input_field_content_inactive';
  document.getElementById('shippingzip').className = 'input_field_content_inactive';
  document.getElementById('shippingaddress').className = 'input_field_content_inactive';
  document.getElementById('shop_select').disabled = false;
  document.getElementById('shop_select').className = 'input_field_content';
  //    document.getElementById('shop_select').className = 'input_field_bg';
/*  document.getElementById('transporter_1').disabled = true;
  if (document.getElementById('transporter_2'))
    document.getElementById('transporter_2').disabled = true; */
  $('.transporter_select').attr('disabled', 'disabled');
}

function hazhozSzallitas()
{
  document.getElementById('szemelyes').className = 'inactive';
  document.getElementById('hazhozszallitas').className = 'active';
  document.getElementById('shop_select').disabled = true;
  document.getElementById('hazhozszallitas_labels').className = 'active';
  document.getElementById('shippingname').disabled = false;
  document.getElementById('shippingzip').disabled = false;
  document.getElementById('shippingcity').disabled = false;
  document.getElementById('shippingaddress').disabled = false;
  document.getElementById('shippingname').className = 'input_field_content';
  document.getElementById('shippingcity').className = 'input_field_content';
  document.getElementById('shippingzip').className = 'input_field_content';
  document.getElementById('shippingaddress').className = 'input_field_content';
  document.getElementById('shop_select').disabled = true;
/*  document.getElementById('transporter_1').disabled = false;
  if (document.getElementById('transporter_2'))
    document.getElementById('transporter_2').disabled = false; */
//    document.getElementById('shop_select').className = 'input_field_bg';
//  $('.transporter_select').removeAttr('disabled');
  $('.transporter_select').attr('disabled', false);
}

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 adnia az email címét!');
    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ímére elküldtük az új jelszó megadásához szükséges linket.';
    }
  });
	
}

function couponRequest (id)
{
  if (id)
  {
    name = document.getElementById('coupon_name'+id).value;
    email = document.getElementById('coupon_email'+id).value;
  }
  else
  {
    name = document.getElementById('coupon_name').value;
    email = document.getElementById('coupon_email').value;
  }
  
  if (name == "" || name == "Név" || email == "" || email == "Email cím")
  {
    alert('A kuponok megszerzéséhez ki kell tölteni valamennyi 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ímére.');
  });
}


function newsletterSubscribe (id, category)
{  
  if (typeof category == "undefined") {
    category = 0;
  }
  
  if (id)
  {
    name = document.getElementById('newsletter_name'+id).value;
    email = document.getElementById('newsletter_email'+id).value;
  }
  else
  {
    name = document.getElementById('newsletter_name').value;
    email = document.getElementById('newsletter_email').value;
  }
    
  if (name == "" || name == "Név" || email == "" || email == "Email cím")
  {
    alert('A regisztrációhoz ki kell tölteni valamennyi mezőt!');
    return;
  }

  $.post("/ajax/newslettersubscribe", {
    name: name,
    email: email,
    category: category
  }, 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('Hírlevél feliratkozás sikeres!');
  });
}

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('Kuponkód elutasítva\n\nLehetséges okok:\n1. A vásárlási érték nem éri el a kuponon megadott minimumot.\n2. Nincs a kosárban olyan termék, amire ez a kód vonatkozik.\n3. Helytelen kód (kérjük, pontosan másolja be).\n4. Lejárt a kupon érvényességi ideje (ellenőrizze a kuponon).\n5. Technikai probléma (Ha ez áll fenn, akkor elnézését kérjük, és feltétlenül forduljon az Ügyfélszolgálathoz)');
    else
    {
      obj = document.getElementById('coupon_validate_form');
      if (obj)
        obj.innerHTML = '<div style="margin-top:5px;padding:2px;">' + data + '</div>';
    }
			
  //	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');
  var email = document.getElementById('contact_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 = 'Valamennyi mező 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;
  }
	
  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
  });
}

function onlyNumbers(e)
{
  var keynum
  var keychar
  var numcheck

  if(window.event) // IE
  {
    keynum = e.keyCode
  }
  else if(e.which) // Netscape/Firefox/Opera
  {
    keynum = e.which
  }

  keychar = String.fromCharCode(keynum);
  numcheck = /\d/;
  return (numcheck.test(keychar)||keynum==8||keynum==9||(keynum>95&&keynum<106));
}

