var doc = document;
var root_http = 'http://www.terko.cz/';

function redirect(url) {
	window.location = url;
}

// zobrazeni/skryti selectboxu pro misto akce se znamkou
function akce_change() {
  var akce = doc.getElementById('akce');
  var akce_slozka = doc.getElementById('akce_slozka');
  var akce_presunout_str = doc.getElementById('akce_presunout_str'); 
    
  if (akce.value == 'smazat') {
    if (akce_slozka) { 
      akce_slozka.style.display = 'none';
      akce_slozka.disabled = true;
    }
    if (akce_presunout_str) { 
      akce_presunout_str.style.display = 'none';
    }         
  } else if (akce.value == 'presunout') {  
    if (akce_slozka) { 
      akce_slozka.style.display = '';
      akce_slozka.disabled = false;
    }
    if (akce_presunout_str) { 
      akce_presunout_str.style.display = '';
    }          
  }
}

function akce_potvrzeni(hlaska) {  
  if (doc.getElementById('akce').value == 'presunout' || doc.getElementById('akce').value == 'smazat') {
    return confirm(hlaska);
  }
}

function zaskrtnout_vse(pocet_polozek, id_name) {
  for (i=1; i<=pocet_polozek; i++) {
    if (doc.getElementById(id_name+i)) {
      doc.getElementById(id_name+i).checked = true;
    } 
  }
}

function odskrtnout_vse(pocet_polozek, id_name) {
  for (i=1; i<=pocet_polozek; i++) { 
    if (doc.getElementById(id_name+i)) {
      doc.getElementById(id_name+i).checked = false;
    } 
  }
}

function popup(page, name) {
  var args = 'width=820,height=600,scrollbars=yes,status=yes,resizable=1,location=no,left=30,top=30';
  if (!name) {
	name = 'prirazeni_polozek';  
  }
  popup_window = window.open(page,name,args);
  if (window.focus) {
	popup_window.focus();
  }
}

function kalendar(opener_id, mesic, rok) {
  var args = 'scrollbars=yes,status=no,resizable=1,location=no,width=280,height=150,top=100,left=200';
  if (mesic && rok) {
    rok_mesic = 'rok='+rok+'&mesic='+mesic+'&';
  } else {
    rok_mesic = '';
  }
  var page = 'http://www.smscz.cz/zemedelske-stroje/modules/kalendar.php?'+rok_mesic+'opener_id='+opener_id;
  window.open(page,'_blank',args);
}  

function show_hide(elem_id) {
  if (doc.getElementById(elem_id).style.display == 'none') {
    doc.getElementById(elem_id).style.display = '';
  } else {
    doc.getElementById(elem_id).style.display = 'none';
  }
}  

function enabled_disabled(elem_id) {
  if (doc.getElementById(elem_id).disabled == true) {
    doc.getElementById(elem_id).disabled = false;
  } else {
    doc.getElementById(elem_id).disabled = true;
  }
}

function enable(elem_id) {
  if (doc.getElementById(elem_id)) {
    doc.getElementById(elem_id).disabled = false;
  }
}

function disable(elem_id) {
  if (doc.getElementById(elem_id)) {
    doc.getElementById(elem_id).disabled = true;
  }
}   

function show(elem_id) {
  if (doc.getElementById(elem_id)) {
    doc.getElementById(elem_id).style.display = '';
  }
}  

function hide(elem_id) {
  if (doc.getElementById(elem_id)) {	
    doc.getElementById(elem_id).style.display = 'none';
  }
}  

function is_checked(elem_id) {
  if (doc.getElementById(elem_id)) {
	return doc.getElementById(elem_id).checked;
  } else {
	return false;  
  }
}   

function check(elem_id) {
  if (doc.getElementById(elem_id)) {
	doc.getElementById(elem_id).checked = true;
  }
}   

function uncheck(elem_id) {
  if (doc.getElementById(elem_id)) {
	doc.getElementById(elem_id).checked = false;
  }
}   

function clear_all_radios() {
  var radios = doc.getElementsByTagName('input');
  
  for (var i = 0; i < radios.length; i++) {
	  if (radios[i].type == 'radio') {
		  radios[i].checked = false;
		  radios[i].disabled = false;
	  }
  }
}  

function clear_balik_na_postu() {
	hide('balik_na_postu');
	set_html('balik_na_postu', '<a href="javascript:popup(\''+root_http+'modules/naPostu/index.php\');">vyberte poštu</a><br />');
}

function get_value(elem_id) {
  if (doc.getElementById(elem_id)) {
	return doc.getElementById(elem_id).value;
  } else {
	return false;  
  }
}

function set_value(elem_id, elem_value) {
  if (doc.getElementById(elem_id)) {
	doc.getElementById(elem_id).value = elem_value;
  }
}

function set_html(elem_id, value) {
	if (doc.getElementById(elem_id)) {
		doc.getElementById(elem_id).innerHTML = value;
	}
}

function get_html(elem_id) {
	if (doc.getElementById(elem_id)) {
		return doc.getElementById(elem_id).innerHTML;
	}
}

function check_max_length(event, input, max_length) {
  var key = event.which;  

  if(key >= 33 || key == 13) {  
    return (input.value.length <= max_length);
  } else {
    return true;
  }
}      

function save_parametr(hodnota_akce, hodnota_id) {
  doc.getElementById('hodnota_akce').value = hodnota_akce;
  doc.getElementById('hodnota_id').value = hodnota_id; 
  doc.getElementById('form').submit();
}

function onchange_varianta(varianta_id, produkt_id) {
  if (varianta_id == 'null') { 
    document.getElementById('produkt_kod').innerHTML = '---'; 
    get_produkt_cena(produkt_id); 
  } else { 
	get_varianta_cena(varianta_id); 
	get_produkt_kod(varianta_id); }
}

/* AJAX */
function get_polozka_html(page, polozka_id, input, close) {
  var text = '';
  var url = root_http+'ajax/get_polozka_html.php';
	var pars = 'page='+page+'&polozka_id='+polozka_id;
	var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onComplete: function(originalRequest){
  	var text = originalRequest.responseText;
  	opener.document.getElementById(input).innerHTML = text;
  	if (close) {
  	  self.close();
  	}
  }} );
}

function prirad_polozky(page, pocet_polozek, polozka_id, sloupec_id, tabulka) {
  var polozky2_id = '';
  for (var i = 1; i <= pocet_polozek; i++) {
    if (doc.getElementById('polozka'+i).checked == true) {
      polozky2_id += '-'+doc.getElementById('polozka'+i).value;
    }
  }
  if (polozky2_id != '') {
    polozky2_id = polozky2_id.substr(1);
    var url = root_http+'ajax/priradit_polozky.php';
  	var pars = 'page='+page+'&polozky2_id='+polozky2_id+'&polozka_id='+polozka_id+'&sloupec_id='+sloupec_id+'&tabulka='+tabulka;
  	//alert(url+'?'+pars);
  	var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onComplete: function(originalRequest){
  	window.location.reload();
  	opener.location.reload();
    }} );
  }
}  

function prirad_hlavni_sekce(pocet_polozek, tabulka, slozka, umisteni) {
  var polozka_name = 'polozka';
  if (slozka) {
    polozka_name = 'slozka';
  }

  var polozky_id = '';
  for (var i = 1; i <= pocet_polozek; i++) {
    if (doc.getElementById(polozka_name+i).checked == true) {
      polozky_id += '-'+doc.getElementById(polozka_name+i).value;
    }
  }
  if (polozky_id != '') {
    polozky_id = polozky_id.substr(1);
    var url = root_http+'ajax/priradit_hlavni_sekce.php';
  	var pars = 'polozky_id='+polozky_id+'&tabulka='+tabulka+'&umisteni='+umisteni;
  	
  	var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onComplete: function(originalRequest){
  	window.location.reload();
  	opener.location.reload();
    }} );
  }
} 

function set_produkt_data(produkt_id) {
	get_produkt_info(produkt_id);
	get_produkt_cena(produkt_id);
	get_produkt_obrazek(produkt_id);
} 

function redirect_produkt_url(produkt_id) {
	$.ajax({
		type: "GET",
		url: root_http+'ajax/get_produkt_url.php',
		data: 'produkt_id='+produkt_id,
		success: function(text){
			redirect(text);
		}
	});
}    

function get_produkt_info(produkt_id) {
	//alert(root_http+'ajax/get_produkt_info.php?produkt_id='+produkt_id);
	$.ajax({
		type: "GET",
		url: root_http+'ajax/get_produkt_info.php',
		data: 'produkt_id='+produkt_id,
		success: function(text){
			document.getElementById('detailInfoTable').innerHTML = text;
		}
	});
}    

function get_produkt_cena(produkt_id) {
	$.ajax({
		type: "GET",
		url: root_http+'ajax/get_produkt_cena.php',
		data: 'produkt_id='+produkt_id,
		success: function(text){
			document.getElementById('detailPrice').innerHTML = text;
		}
	});
}    

function get_produkt_obrazek(produkt_id) {
	$.ajax({
		type: "GET",
		url: root_http+'ajax/get_produkt_obrazek.php',
		data: 'produkt_id='+produkt_id,
		success: function(text){
			document.getElementById('detailPic').innerHTML = text;
		}
	});
}  

function get_posta(psc) {
	$.ajax({
		type: "GET",
		url: root_http+'ajax/get_posta.php',
		data: 'psc='+psc,
		success: function(text){
			opener.document.getElementById('balik_na_postu').innerHTML = text;
		  	if (close) {
		      self.close();
		    }
		}
	});
}    

function get_kraje_option(stat_id, lng) {
  var text = '';
	var url = root_http+'ajax/get_kraje_option.php';
	var pars = 'stat_id='+stat_id+'&'+lng;
	var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onComplete: function(originalRequest){
  	var text = originalRequest.responseText;
  	document.getElementById('kraj_id_td').innerHTML = text;
  }} );
}    

function get_okresy_option(kraj_id, stat_id, lng) {
  var text = '';
	var url = root_http+'ajax/get_okresy_option.php';
	var pars = 'kraj_id='+kraj_id+'&'+'stat_id='+stat_id+'&'+lng;
	var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onComplete: function(originalRequest){
  	var text = originalRequest.responseText;
  	document.getElementById('okres_id_td').innerHTML = text;
  }} );
}    

function set_zpusoby_platby(zpusob_dopravy_id, elem_prefix) {
	var xmlhttp = (window.XMLHttpRequest ? new XMLHttpRequest : (window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : false));
	if (!xmlhttp) {
		return false;
	}
	
	if (intval(zpusob_dopravy_id)) {
		xmlhttp.open('GET', root_http+'ajax/set_zpusoby_platby.php?zpusob_dopravy_id='+zpusob_dopravy_id, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {						
				var zpusoby_platby = xmlhttp.responseXML.getElementsByTagName('zpusob_platby');
				
				var enable_elem_counter = 0;
				var enable_elem_id = '';
				
				for (var i=0; i < zpusoby_platby.length; i++) {
					var zpusob_platby_id = zpusoby_platby[i].getAttribute('id');
					var zpusob_platby_cena = zpusoby_platby[i].getAttribute('cena_platby');
					var zpusob_platby_disabled = intval(zpusoby_platby[i].getAttribute('disabled'));
					var elem_id = (elem_prefix ? elem_prefix+'_' : '')+'zpusob_platby'+zpusob_platby_id;
					
					if (zpusob_platby_disabled) {
						disable(elem_id);
					} else {
						enable(elem_id);
						
						enable_elem_counter++;
						enable_elem_id = elem_id;
					}

					set_html(elem_id+'_cena', zpusob_platby_cena);
				}
				
				if (enable_elem_counter == 1) {
					check(enable_elem_id);
				}
			}
		};
		/*f (headers) {
			for (var key in headers) {
				xmlhttp.setRequestHeader(key, headers[key]);
			}
		}*/
		//xmlhttp.send(content);
		xmlhttp.send();
		return true;
	} else {
		return false;
	}
}  

function set_zpusoby_dopravy(zpusob_platby_id, elem_prefix) {
	var xmlhttp = (window.XMLHttpRequest ? new XMLHttpRequest : (window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : false));
	if (!xmlhttp) {
		return false;
	}
	
	if (intval(zpusob_platby_id)) {
		xmlhttp.open('GET', root_http+'ajax/set_zpusoby_dopravy.php?zpusob_platby_id='+zpusob_platby_id, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {						
				var zpusoby_dopravy = xmlhttp.responseXML.getElementsByTagName('zpusob_dopravy');
				
				for (var i=0; i < zpusoby_dopravy.length; i++) {
					var zpusob_dopravy_id = zpusoby_dopravy[i].getAttribute('id');
					var zpusob_dopravy_cena = zpusoby_dopravy[i].getAttribute('cena_dopravy');
					var zpusob_dopravy_disabled = intval(zpusoby_dopravy[i].getAttribute('disabled'));
					var elem_id = (elem_prefix ? elem_prefix+'_' : '')+'zpusob_dopravy'+zpusob_dopravy_id;
					
					if (zpusob_dopravy_disabled) {
						disable(elem_id);
					} else {
						enable(elem_id);
					}
					
					set_html(elem_id+'_cena', zpusob_dopravy_cena);
				}
			}
		};
		/*f (headers) {
			for (var key in headers) {
				xmlhttp.setRequestHeader(key, headers[key]);
			}
		}*/
		//xmlhttp.send(content);
		xmlhttp.send();
		return true;
	} else {
		return false;
	}
} 
/* KONEC - AJAX */


/* PRO MAPU */
function create_marker(lat_lng, title, content, icon) {
	var marker = new GMarker(lat_lng, { title: title, icon: icon });
	GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(content); });
	return marker;
}

function marker_save() {
  doc.getElementById('latitude').value = marker.getPoint().lat();
  doc.getElementById('longitude').value = marker.getPoint().lng();
  doc.getElementById('map_zoom').value = map.getZoom();
}

function unset_marker() {
  doc.getElementById('latitude').value = 0;
  doc.getElementById('longitude').value = 0;
  doc.getElementById('map_zoom').value = 0;
  var point = new GLatLng(0, 0);	
  marker.setPoint(point);      	  
	map.setCenter(point, 0);
}

function search_address(address) {
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(address, function (point) {
		if (!point) {
			alert('NENALEZENO: ' + address);
		} else {
			marker.setPoint(point);
			map.setCenter(point, 15);
			marker_save();
		}
	});
}

function search_gps(latitude, longitude) {
  latitude[2] = str_replace(",", ".", latitude[2]);
  longitude[2] = str_replace(",", ".", longitude[2]);
  
  var lat = parseInt(latitude[0]) + (parseFloat(latitude[1])/60) + (parseFloat(latitude[2])/3600);
  var lang = parseInt(longitude[0]) + (parseFloat(longitude[1])/60) + (parseFloat(longitude[2])/3600);
  
  var point = new GLatLng(lat, lang);	
  marker.setPoint(point);      	  
	map.setCenter(point, 18);
}
/* KONEC - PRO MAPU */


function str_replace (search, replace, subject, count) {
  // Replaces all occurrences of search in haystack with replace  
  // 
  // version: 1008.1718
  // discuss at: http://phpjs.org/functions/str_replace    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Gabriel Paderni
  // +   improved by: Philip Peterson
  // +   improved by: Simon Willison (http://simonwillison.net)
  // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)    // +   bugfixed by: Anton Ongson
  // +      input by: Onno Marsman
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +    tweaked by: Onno Marsman
  // +      input by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   input by: Oleg Eremeev
  // +   improved by: Brett Zamir (http://brett-zamir.me)
  // +   bugfixed by: Oleg Eremeev
  // %          note 1: The count parameter must be passed as a string in order    // %          note 1:  to find a global variable in which the result will be given
  // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
  // *     returns 1: 'Kevin.van.Zonneveld'
  // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
  // *     returns 2: 'hemmo, mars'    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
          f = [].concat(search),
          r = [].concat(replace),
          s = subject,
          ra = r instanceof Array, sa = s instanceof Array;    s = [].concat(s);
  if (count) {
      this.window[count] = 0;
  }
   for (i=0, sl=s.length; i < sl; i++) {
      if (s[i] === '') {
          continue;
      }
      for (j=0, fl=f.length; j < fl; j++) {            temp = s[i]+'';
          repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
          s[i] = (temp).split(f[j]).join(repl);
          if (count && s[i] !== temp) {
              this.window[count] += (temp.length-s[i].length)/f[j].length;}        }
  }
  return sa ? s : s[0];
}

function intval (mixed_var, base) {
    var type = typeof( mixed_var );
 
    if (type === 'boolean') {        
      return (mixed_var) ? 1 : 0;
    } else if (type === 'string') {
      tmp = parseInt(mixed_var, base || 10);
      return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
    } else if (type === 'number' && isFinite(mixed_var) ) {        
      return Math.floor(mixed_var);
    } else {
      return 0;
    }
}

function get_window_width() {
	var viewportwidth;
	
	if (typeof window.innerWidth != 'undefined')
	{
	viewportwidth = window.innerWidth;
	}
	else if (typeof document.documentElement != 'undefined'
	&& typeof document.documentElement.clientWidth !=
	'undefined' && document.documentElement.clientWidth != 0)
	{
	viewportwidth = document.documentElement.clientWidth;
	}

	// older versions of IE

	else
	{
	viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
	} 
}

function get_window_height() {
	var viewportheight;

	if (typeof window.innerHeight != 'undefined')
	{
	viewportheight = window.innerHeight;
	}
	else if (typeof document.documentElement != 'undefined'
	&& typeof document.documentElement.clientHeight !=
	'undefined' && document.documentElement.clientHeight != 0)
	{
	viewportheight = document.documentElement.clientHeight;
	}

	// older versions of IE

	else
	{
	viewportheight = document.getElementsByTagName('body')[0].clientHeight;
	}
	
	return viewportheight;
}

function update_cena_objdemo(i) {
	var cena = intval(doc.getElementById('polozka'+i+'_cena').value) * intval(doc.getElementById('polozka'+i+'_kusy').value);
	doc.getElementById('polozka'+i+'_cena_celkem').innerHTML = cena;
}

function nformat(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1))
    x1 = x1.replace(rgx, '$1' + ' ' + '$2');
  return x1 + x2;
}

function getElementsByClassName(classname, node) {
	if (!node) {
		node = document;
	}	
	if (node.getElementsByClassName) { // use native implementation if available
		return node.getElementsByClassName(classname);
	} else {
		return (function getElementsByClass(searchClass,node) {
        if ( node == null )
          node = document;
        var classElements = [],
            els = node.getElementsByTagName("*"),
            elsLen = els.length,
            pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;

        for (i = 0, j = 0; i < elsLen; i++) {
          if ( pattern.test(els[i].className) ) {
              classElements[j] = els[i];
              j++;
          }
        }
        return classElements;
    })(classname, node);
  	}
}

function change_captcha_img() {
	var imgs = getElementsByClassName('captchaImg');
	var img_src = root_http+'modules/captcha/securimage_show.php?sid=' + Math.random();	
	
	for(i = 0; i < imgs.length; i++) {
		imgs[i].src = img_src;
	}
}



