  function getOnlyTag(tagname, root) { return(root.getElementsByTagName(tagname)[0]); }
	  
  function namedItem(nodelist, name) {
        for(var i = 0; i < nodelist.length; i++) {
            if(nodelist.item(i).name == name) return nodelist.item(i);
        }
  }

	function validate(what) {
		var regexes = new Array();
		regexes["username"] = /^[a-zA-Z0-9_. -]{2,}$/;
		regexes["email"] = /^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/; // "
		regexes["phone"] = regexes["ship_phone"] = /^[+\d]\d[\d -]{6,}$/;
		regexes["bill_zip"] = /^\d{3}( )?\d{2}$/;
		regexes["ship_zip"] = /(^\d{3}( )?\d{2}$)|(^\d{0}$)/;
		regexes["name"] = regexes["surname"] = regexes["bill_street"] = regexes["bill_city"] = regexes["adress"] /* x.x */ = regexes["subject"] = regexes["message"] = /^.{2,}$/;
		
		var validity_images = new Array();
		var validity_texts = new Array();
		validity_images["valid"] = template_url + "graphics/valid.png";
		validity_images["invalid"] = template_url + "graphics/invalid.png";
		validity_texts["valid"] = "Je vyplněno správně.";
		validity_texts["invalid"] = "Není vyplněno správně.";
		
		var value = document.getElementById(what).value;
		var img = document.getElementById(what + "_img");

		if(regexes[what].exec(value)) {
			if(img.src != validity_images["valid"]) img.src = validity_images["valid"];
			img.alt = validity_texts["valid"];
			return true;
		}
		else {
			if(img.src != validity_images["invalid"]) img.src = validity_images["invalid"];
			img.alt = validity_texts["invalid"];
			return false;
		}
	}

	function validate_password(register) {
		var password = $("#password").val();
		var password_img = $("#password_img")[0];
		if(register == true) {
			var confirmation = $("#password_change_confirmation").val();
			var confirmation_img = $("#password_change_confirmation_img")[0];
		}
		else {
			var confirmation = $("#password_confirmation").val();
			var confirmation_img = $("#password_confirmation_img")[0];
		}

		var regex = /^.{5,32}$/;
		var validity_images = new Array();
		var validity_texts = new Array();
		validity_images["valid"] = template_url + "graphics/valid.png";
		validity_images["invalid"] = template_url + "graphics/invalid.png";
		validity_texts["valid"] = "Je vyplněno správně.";
		validity_texts["invalid"] = "Není vyplněno správně.";
		
		if(regex.exec(password) || (password == "" && confirmation == "" && register == false)) {
			if(password_img.src != validity_images["valid"]) {
                password_img.src = validity_images["valid"];
                password_img.alt = validity_texts["valid"];
            }
			var valid = true;
		}
		else {
			if(password_img.src != validity_images["invalid"]) {
                password_img.src = validity_images["invalid"];
                password_img.alt = validity_texts["invalid"];
            }
			var valid = false;
		}
		
		if(password == confirmation) {
			if(confirmation_img.src != validity_images["valid"]) {
                confirmation_img.src = validity_images["valid"];
                confirmation_img.alt = validity_texts["valid"];
            }
			var identic = true;
		}
		else {
			if(confirmation_img.src != validity_images["invalid"]) {
                confirmation_img.src = validity_images["invalid"];
                confirmation_img.alt = validity_texts["invalid"];
            }
			var identic = false;
		}
		
		if(valid && identic) return true;
		else return false;
		
	}

function tr_over(t) { t.className += " hover"; }
function tr_out(t) { t.className = t.className.replace(/hover/g, ''); }


  function add_onload(f)
  {
      var oldhandler = window.onload;
      window.onload = function()
      {
          f();
          
          if(typeof(oldhandler) != "undefined" && oldhandler) {
              window.onload = oldhandler;
              window.onload();
          }
      }
  }

  function menu_fold()
  {
      var cats = $('#catnav')[0];
      var lis = cats.getElementsByTagName('li');
      for(var i = 0; i < lis.length; i++) {
          var uls = lis[i].getElementsByTagName('ul');
          if(lis[i].className.indexOf('sub') == -1 && uls[0]) {
              uls[0].style.display = "none";
          }
      }
  }
  function menu_click(t, e)
  {
      var uls = t.getElementsByTagName('ul');
      if(uls[0]) {
          uls[0].style.display = (uls[0].style.display == "none" ? "" : "none");
      }
      t.className = (t.className == "sub" ? "" : "sub");
      e.cancelBubble = true;
      e.stopPropagation();
  }
	function showText(){
		document.getElementById("text").style.display = 'block';
		document.getElementById("show").style.display = 'none';
		document.getElementById("hide").style.display = 'block';
	}
	function hideText(){
		document.getElementById("text").style.display = 'none';
		document.getElementById("show").style.display = 'block';
		document.getElementById("hide").style.display = 'none';
	}

  function ajax(url, method, data, succ, fail) {
  	method = method.toUpperCase();
	if(method == 'GET' || method == 'POST') {
		if(window.ActiveXObject) httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
		else httpRequest = new XMLHttpRequest();

		httpRequest.onreadystatechange = function() {
			if(httpRequest.readyState == 4) {
				if(httpRequest.status == 200) succ();
				else fail();
			}
		};

		if(data) {
			params = new Array();
			for(paramname in data) params.push(escape(paramname) + '=' + escape(data[paramname]));
			params = params.join('&');
		}
		else params = null;

		httpRequest.open(method, url, true);
		if(method == 'POST') {
			httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpRequest.setRequestHeader("Content-length", params.length);
			httpRequest.setRequestHeader("Connection", "close");
		}
		httpRequest.send(params);
	}
  }

  function updatecartpanelitem(itemname, xml) {
  	  var tag = getOnlyTag(itemname, xml);
  	  $('#cart_panel_' + itemname).text(tag.textContent == undefined ? tag.text : tag.textContent);
  }
  
  function addtocart(succ, id) {
  	  var xml = httpRequest.responseXML.documentElement;
  	  updatecartpanelitem('itemcount', xml);
  	  updatecartpanelitem('totalprice', xml);
  	  
  	  var elem = $('#addtocart_result' + (id ? '_' + id : ''))[0];
	  var istr = elem.tagName.toLowerCase() == 'tr';
  	  elem.style.display = (istr ? 'table-row' : 'block');
  	  if(istr) elem = elem.getElementsByTagName('td')[0];
  	  elem.style.textAlign = "center";
	  var suf = (id && id.length == 1 ? 'y' : 'a');
	  var nesuf = (id && id.length == 1 ? 'y' : 'u')
  	  elem.innerHTML = (succ ? "Položk" + suf + " byl" + suf + " přidán" + suf + ".<br /><a href='" + BASE_URL + "kosik'>Zobrazit košík »</a>" : "Položk" + nesuf + " se nepodařilo přidat do košíku.");
	  
  }
  
  function addtocart_all(cl, url, t) {
	var cls = $('#related_group_container_' + cl).find('div.dp_box');
	var i = 0;
	var q = 0;
	cls.each(function(k, e) {
		var pid;
		var vid;
		var inp = $(this).find('input');
		$(inp[0].className.split(' ')).each(function(k, v) {
			if(m = v.match(/^product_id_(\d+)$/)) pid = m[1];
		});
		vid = inp[0].id.match(new RegExp('^related_quantity_(\\d+)$'))[1];
		q += inp[0].value;

		ajax(url, 'POST', {product_id: pid, variant_id: vid, quantity: inp[0].value}, function() { addtocart(true, cl); }, function() { addtocart(false, cl); }  );
	});
	return(false);
  }

  function session_keepalive()
  {
      var im = new Image();
      im.src = "{{BASE_URL}}keep-alive";
  }

  function watchdog_control()
  {
      var text = "";
      re = /^[^.]+(\.[^.]+)*@([^.]+[.])+[a-z]{2,3}$/;
      if (namedItem(document.getElementsByTagName('input'), 'email_addres').value.search(re) != 0)
         text = "{{ERROR_MESSAGE_EMPTY_MAIL}}";
      var count = 0;
      if(document.getElementsByName('event[a]')[0].checked)
         count++;
      
      var radios = document.getElementsByName('event[b]');
      for(var i = 0; i < radios.length; i++)
         if (radios[i].checked == true)
            count++;

      if (count == 0)
         text += "{{ERROR_MESSAGE_NO_EVENTS}}";
         
      if (text == "")
         document.forms.watchdog_form.submit();
      else
         alert(text);
  }

  function contact_form_validateall() {
      var error = "";
      
      if(!validate("name")) error += "Invalidní jméno.\n";
      if(email.value && !validate("email")) error += "Invalidní email.\n";
      if(phone.value && !validate("phone")) error += "Invalidní telefon.\n";
      if(adress.value && !validate("adress")) /* x.x */ error += "Invalidní adresa.\n";
      if(!email.value && !phone.value && !adress.value /* x.x */) error += "Není vyplněn ani jeden kontaktní údaj.\n";
      if(!validate("subject")) error += "Invalidní předmět.\n";
      if(!validate("message")) error += "Invalidní zpráva.";
      
      if(error != "") {
         alert(error);
         return false;
      }
      else return true;
   }

var product_listing_loader = (function() {
    var xhr = null;
    this.load = function(method, data, callback)
    {
        if(xhr && xhr.abort) xhr.abort();
        
        $('#cl_products').html("<center><img src='" + template_url + "graphics/working.gif' /></center>");
        var fn = (method == 'GET' ? $.get : $.post);
        xhr = fn(location.href, data, function(res) {
            var rscript = /<script(.|\s)*?\/script>/gi;
            $('#cl_products').html($("<div />").append(res.replace(rscript, "")).find('#cl_products2'));
            xhr = null;
            product_listing_controls_init();
            if(callback) callback();
        });
    }
    return this;
})();

var category_listing_controls_init = function(min, max, c_min, c_max) {
$(function() {
    var last_tg = null, last_div;
    var show_attr;
    var hide_attr = function(e) {
        if($(e.target).parents().filter(last_div).size() > 0) return;
        
        last_div.hide(400);
        $(document.body).unbind('click', hide_attr);
        last_tg.bind('click', show_attr);
        last_tg = null;
    };
    show_attr = function()
    {
        if(last_tg && last_tg[0] !== this) {
            hide_attr({target: null});
        }
        last_tg = $(this);
        last_div = last_tg.siblings('div.attr_values');
          last_div.css({
              position: 'absolute',
              left: last_tg.position().left - 8,
              top: last_tg.position().top + last_tg.height() + 8,
              width: Math.max(145, last_tg.outerWidth()),
              zIndex: 40
          }).show(400);
          last_tg.unbind('click', show_attr);
          setTimeout(function() { // else it would get fired right away
              $(document.body).bind('click', hide_attr);
          }, 1);
    }
    var container = $('div.attr_container');
    container.find('div.attr_selection div.attr_name').bind('click', show_attr);

    var filter_inputs = container.find('input[name^=a_filter]');
    filter_inputs.click(function() {
        var data = filter_inputs.serializeArray();
        data[data.length] = {name: 'category_listing_a_filter', value: 1};
        data[data.length] = {name: 'ajax_call', value: 1};
        product_listing_loader.load('POST', data);
    });
    
    var diff = Math.max(1, max - min);
    var div_price = $('div.attr_price'),
        slider = div_price.find('div.slider_price'),
        area = div_price.find('div.slider_area'),
        left = div_price.find('div.slider_left'),
        right = div_price.find('div.slider_right'),
        min_price = div_price.find('div.min_price'),
        max_price = div_price.find('div.max_price');

    max_price.html(max + ',–');
    min_price.add(max_price).width(max_price.width());

    var width = slider.width() + 1,
        coef = width / diff;
    
    var price_update = function(init_controls) {
        var l = (c_min - min) * coef - 1, w = Math.max(1, (c_max - c_min) * coef - 1);
        area.css({left: l, width: w});
        min_price.html(c_min + ',–');
        max_price.html(c_max + ',–');
          left.css({left: slider.position().left + l - 19});
          right.css({left: slider.position().left + l + w + 2});
        if(init_controls) {
            left.add(right).css({top: slider.position().top - 17}).show();
        }
    }
    price_update(true);
    
    var moving;
    left.add(right)
          .mousedown(function(e) {
              moving = {mouse: e.clientX, side: left[0] === this ? 'l' : 'r'};
              moving.start = (moving.side == 'l' ? c_min : c_max);
              e.stopPropagation();
              e.preventDefault();
              return false;
          });
      $(document)
          .mousemove(function(e) {
              if(!moving) return;
              var now = {mouse: e.clientX};
              
              if(moving.side == 'l') c_min = Math.min(c_max, Math.max(min, Math.round(moving.start + (now.mouse - moving.mouse) / coef)));
              else c_max = Math.min(max, Math.max(c_min, Math.round(moving.start + (now.mouse - moving.mouse) / coef)));
              
              price_update(false);
          })
          .bind('selectstart', function(e) {
              if(!moving) return;
              e.preventDefault();
              e.stopPropagation();
              return false;
          });
          
      $(document.body).mouseup(function() {
          if(moving) {
              var data = {category_listing_price_control: 1, price_control_min: c_min, price_control_max: c_max, ajax_call: 1};
              product_listing_loader.load('POST', data);
          }
          moving = null;
      });
});
};

var product_listing_controls_init = function() {
$(function() {
    var last_tg = null, last_div;
    var show_attr;
    var hide_attr = function(e) {
        if($(e.target).parents().filter(last_div).size() > 0) return;
        
        last_div.hide(400);
        $(document.body).unbind('click', hide_attr);
        last_tg.bind('click', show_attr);
        last_tg = null;
    };
    show_attr = function()
    {
        if(last_tg && last_tg[0] !== this) {
            hide_attr({target: null});
        }
        last_tg = $(this);
        last_div = last_tg.siblings('div.popup_options');
          last_div.css({
              position: 'absolute',
              left: last_tg.position().left,
              top: last_tg.position().top + last_tg.height() + 2,
              w_idth: Math.max(135, last_tg.outerWidth()),
              float: 'left',
              zIndex: 40
          }).show(400);
          last_tg.unbind('click', show_attr);
          setTimeout(function() { // else it would get fired right away
              $(document.body).bind('click', hide_attr);
          }, 1);
    }
    $('div.sorting span.sorting_current').bind('click', show_attr);
    $('div.paging div.per_page span.per_page_current').bind('click', show_attr);
    
    $('div.sorting div.popup_options div').click(function() {
        product_listing_loader.load(
            'GET',
            {orderby: $(this).attr('rel').replace(/^sorting-/, ''), ajax_call: 1}
        );
    });
    $('div.paging div.pages a').click(function() {
        product_listing_loader.load(
            'GET',
            {page: $(this).attr('href').replace(/^.*page=([0-9]+).*$/, '$1'), ajax_call: 1}
        );
        return false;
    });
    $('div.per_page div.popup_options div').click(function() {
        product_listing_loader.load(
            'GET',
            {per_page: $(this).attr('rel'), ajax_call: 1}
        );
    });
});
};

