var focus_changing = false;

// Focus into field f, display message s and return false
function focus_alert(s, f) {
	if (!focus_changing) {
		focus_changing = true;
		f.focus();
		alert(s);
		focus_changing = false;
	}
	return false;
}

function focus_confirm_url(s, url, f) {
	if (!focus_changing) {
		focus_changing = true;
        if (confirm(s)) {
            location.href = url;
        }
		focus_changing = false;
	}
    return false;
}

// Check fields in the form
// s is warning message, f is pointer to <form>, next arguments are names of mandatory fields
// example of use: <form onSubmit="return form_correct('Fill-in all marked fields!', this, 'name', 'password');">
function form_correct(s, f) {
	// non-emptiness of selected fields
	fields_loop:
	for (var i=2; i < arguments.length; i++) {
		if (f[arguments[i]].length && !f[arguments[i]].options) {
			for (var j=0; j < f[arguments[i]].length; j++) {
				if (f[arguments[i]][j].checked) {
					continue fields_loop;
				}
			}
			return focus_alert(s, f[arguments[i]][0]);
		} else if (f[arguments[i]].type == 'radio' || f[arguments[i]].type == 'checkbox' ? !f[arguments[i]].checked : !f[arguments[i]].value) {
			return focus_alert(s, f[arguments[i]]);
		}
	}

	// correctness of each field
	for (var i=0; i < f.elements.length; i++) {
		if (f.elements[i].onblur && !f.elements[i].onblur()) {
			return false;
		}
	}
	
	return true;
}

function form_correct_message(s, f, fields) {
	var field = '';
	for (var key in fields) {
		if (!f[key].value) {
			s += '\n' + fields[key];
			if (!field) {
				field = key;
			}
		}
	}
	if (field) {
		return focus_alert(s, f[field]);
	}
	
	for (var i=0; i < f.elements.length; i++) {
		if (f.elements[i].onblur && !f.elements[i].onblur()) {
			return false;
		}
	}
	
	return true;
}

// Check if field matches ereg
// example of use: <input onBlur="return ereg_correct('Enter a date!', this, /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/);">
function ereg_correct(s, f, regexp) {
	if (f.value == '' || regexp.test(f.value)) {
		return true;
	}
	return focus_alert(s, f);
}

// Check if there is a number in the field
// s is warning message, f is input field, boolean negative allows negative values, d1 is number of digits before decimal point, optional d2 is maximum count of digits after decimal point (empty - none, d1 - unlimited)
// example of use: <input onBlur="return number_correct('Enter a possitive number!', this, false, 5);">
function number_correct(s, f, negative, d1, d2) {
	f.value = f.value.replace(',', '.');
	return ereg_correct(s, f, new RegExp('^'+ (negative ? '-?' : '') +'[0-9]{0,'+ (d1 ? d1 : '') +'}'+ (d2 ? '([.][0-9]{1,'+ d2 +'})?' : '') +'$'));
}

// Check if there is an e-mail in the field, simplified!
// example of use: <input onBlur="return email_correct('Enter an e-mail!', this);">
function email_correct(s, f) {
	return ereg_correct(s, f, /^[^ @]+@[^ @]+\.[^ @]+$/);
}

// Check if there is a URL in the field, simplified!
// example of use: <input onBlur="return email_correct('Enter a URL!', this);">
function url_correct(s, f) {
	return ereg_correct(s, f, /^https?:\/\/[^ \/]+\.[^ ]+/);
}

// Check if the checkbox is checked
// example of use: <form onSubmit="return checkbox_correct('You have to agree!', this['agree']);">
function checkbox_correct(s, f) {
	if (!f.checked) {
		return focus_alert(s, f);
	}
}

// Check if the field has valid lengths, parameters from valid_length1 are possible lengths
// example of use: <input onBlur="return length_correct('Enter 8 or 10 characters!', this, 8, 10);">
function length_correct(s, f, valid_length1) {
	for (var i=2; i < arguments.length; i++) {
		if (f.value.length == arguments[i]) {
			return true;
		}
	}
	return focus_alert(s, f);
}

// Open image window
function img_open(filename, w, h, title) {
	var wnd = window.open('', '', (w && h ? 'width=' + w + ',height=' + h : 'width=300,height=300'));
	if (!wnd) {
		return false;
	}
	wnd.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml">\n');
	if (title) {
		wnd.document.write('<head>\n<title>' + title + '</title>\n</head>\n');
	}
	wnd.document.write('\n<body style="margin: 0;">\n\n');
	wnd.document.write('<img src="' + filename + '"' + (w && h ? ' width="' + w + '" height="' + h + '"' : '') + ' alt="' + (title ? title : '') + '" style="margin: 0;" />');
	wnd.document.write('\n</body>\n</html>\n');
	return true;
}

/** odeslání XMLHttp požadavku
* @param function obsluha funkce zajišťující obsluhu při změně stavu požadavku, dostane parametr s XMLHttp objektem
* @param string method GET|POST|...
* @param string url URL požadavku
* @param string [content] tělo zprávy
* @param array [headers] pole předaných hlaviček ve tvaru { 'hlavička': 'obsah' }
* @return bool true v případě úspěchu, false jinak
*/
function send_xmlhttprequest(obsluha, method, url, content, headers) {
    var xmlhttp = (window.XMLHttpRequest ? new XMLHttpRequest : (window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : false));
    if (!xmlhttp) {
        return false;
    }
    xmlhttp.open(method, url);
    xmlhttp.onreadystatechange = function() {
        obsluha(xmlhttp);
    };
    if (headers) {
        for (var key in headers) {
            xmlhttp.setRequestHeader(key, headers[key]);
        }
    }
    xmlhttp.send(content);
    return true;
}

function naseptavac_click(field_id, id, text) {
	document.getElementById(field_id).value = text;
	if (document.getElementById('mesto').value != id) {
		document.getElementById('mesto').value = id;
		document.getElementById('mesto').onchange();
	}
	document.getElementById('mesto-naseptavac').style.display = 'none';
	return true;
}

var naseptavac_timeout;
function naseptavac(field, url, div) {
	document.getElementById('mesto').value = '';
	div.style.display = 'none';
	if (!field.value || field.value.length < 2) {
		document.getElementById('mesto').onchange();
	} else {
		send_xmlhttprequest(function (xmlhttp) {
			if (xmlhttp.readyState == 4 && xmlhttp.responseXML.documentElement.getAttribute('dotaz') == field.value) {
				var s = '';
				var mesta = xmlhttp.responseXML.getElementsByTagName('mesto');
				for (var i=0; i < mesta.length; i++) {
					//~ s += '<a href="#' + mesta[i].firstChild.data + '" onclick="return !naseptavac_click(\'' + field.id + '\', ' + mesta[i].getAttribute('id') + ', \'' + mesta[i].firstChild.data.replace(/'/g, "\\'") + '\');">' + mesta[i].firstChild.data.replace(new RegExp(field.value.replace(/[[\\^$*+?.(|{]/g, '\\$&'), 'i'), '<b>$&</b>') + '</a>' + (field.id == 'mesto_text' ? ' (' + mesta[i].getAttribute('stat') + ')' : '') + '<br />\n';
					s += '<a href="' + mesta[i].getAttribute('url') + '">' + mesta[i].firstChild.data.replace(new RegExp(field.value.replace(/[[\\^$*+?.(|{]/g, '\\$&'), 'i'), '<b>$&</b>') + '</a>' + (field.id == 'mesto_text' ? ' (' + mesta[i].getAttribute('stat') + ')' : '') + '<br />\n';
				}
				div.innerHTML = s;
				div.style.display = 'block';
				if (mesta.length == 1) {
					document.getElementById('mesto').value = mesta[0].getAttribute('id');
				}
				document.getElementById('mesto').onchange();
			}
		}, 'GET', url + encodeURIComponent(field.value));
	}
}

function toggle_on_off(f, a, hide_text) {
	f.style.display = (f.style.display == 'none' ? '' : 'none');
	if (a) {
		if (f.style.display == 'none') {
			a.innerHTML = a.hide_text;
		} else {
			a.hide_text = a.innerHTML;
			a.innerHTML = hide_text;
		}
	}
	return true;
}

function pocet_hotelu(f) {
    
    if(document.getElementById('pocet-hotelu') != null)
    {        
        $('#availcheck').attr('checked', 'checked');
        
        if (document.getElementById('show-button')) {
		    document.getElementById('show-button').className = 'inline-button';
	    }
	    var parametry = '';
	    var inputs = f.getElementsByTagName('select');
	    for (var i=0; i < inputs.length; i++) {
		    if (inputs[i].name && inputs[i].value) {
			    parametry += '&' + inputs[i].name + '=' + encodeURIComponent(inputs[i].value);
		    }
	    }
	    inputs = f.getElementsByTagName('input');
	    for (var i=0; i < inputs.length; i++) {
		    if (inputs[i].name && (inputs[i].checked || (inputs[i].type != 'checkbox' && inputs[i].value))) {
			    parametry += '&' + inputs[i].name + '=' + encodeURIComponent(inputs[i].value);
		    }
	    }
	    send_xmlhttprequest(function (xmlhttp) {
		    if (xmlhttp.readyState == 4) {
			    document.getElementById('pocet-hotelu').innerHTML = xmlhttp.responseText;
		    }
	    }, 'GET', '/xml/search-count.php?' + parametry.substr(1));
    }
}

function date_change(f) {
	f['availcheck'].checked = true;
	if (f['checkin_year_month'].selectedIndex == 0 && f['checkin_day'].value < (new Date()).getDate()) {
		f['checkin_year_month'].selectedIndex = 1;
	}
	if (f['checkout_year_month'].selectedIndex < f['checkin_year_month'].selectedIndex || (f['checkout_year_month'].selectedIndex == f['checkin_year_month'].selectedIndex && f['checkout_day'].selectedIndex <= f['checkin_day'].selectedIndex)) {
		f['checkout_day'].value = ((new Date(f['checkin_year_month'].value.substr(0, 4), f['checkin_year_month'].value.substr(5, 2), 0)).getDate() > f['checkin_day'].value ? 1 + 1*f['checkin_day'].value : 1);
		f['checkout_year_month'].selectedIndex = f['checkin_year_month'].selectedIndex + (f['checkout_day'].value == 1 ? 1 : 0);
	}
	pocet_hotelu(f);
}

function foto_active(a, text) {
	document.getElementById('foto_big').src = a.href;
	document.getElementById('foto_big-text').innerHTML = text;
	var lis = a.parentNode.parentNode.parentNode.getElementsByTagName('li');
	for (var i=0; i < lis.length; i++) {
		lis[i].className = '';
	}
	a.parentNode.className = 'active';
	return true;
}

function show_big(obr,popisek,styl) {
    if (popisek) popisek=popisek.replace(/%/g,"%25").replace(/&/g,"%26").replace(/\+/g,"¤")
    else popisek=""
    if (!styl && styl!=0) styl=""
    if (obr.substring(0,7)!="http://") {
        from=""+self.location;
        if (obr.substring(0,1)!="/")
            obr=from.substring(0,from.lastIndexOf("/")+1)+obr;
        else
            obr=from.substring(0,from.indexOf("/",8))+obr;
    }
    window.open("/showbig.inc.php?obr="+obr+"&styl="+styl+"&popisek="+popisek,"show_big","toolbar=no,scrollbars=no,location=no,status=no,width=520,height=420,resizable=yes,menubar=no,directories=no")
}