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);
}

function cvc_correct(s, f) {
    if($('input[name=kredit_karta_cislo]').val() == '') {
        return true;
    }
    var rg = /^[0]*$/
    if(rg.test(f.value)) {
        return focus_alert(s, f);
    }
    
    return ereg_correct(s, f, /^[0-9 ]*$/);
}

// 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, /^[^ @]+@[^ @]+\.[^ @]+$/);
    return ereg_correct(s, f, /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/);
}

// 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, checkAvailable) {
    if(typeof checkAvailable == 'undefined') {
        checkAvailable = true;
    }

    
    if(document.getElementById('pocet-hotelu') != null)
    {        
        //zobrazime loader
        document.getElementById('pocet-hotelu').innerHTML = '<img src="/images/animace-load-bila.gif" width="32" height="32" alt="Loader" />';

        if(checkAvailable) {
            $('#availcheck').attr('checked', 'checked');
        }
        
	    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;
                if (document.getElementById('show-button')) {
                document.getElementById('show-button').className = 'inline-button';
                }
		    }
	    }, '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) {
	var elm = $(a).clone();
        var hr = elm.attr('href');
        var re = /hotel-([\d]+)/;
        hr = hr.replace(re, "hotel-$1_b");
        elm.attr('href', hr);
        
    $('#foto_big').parent().attr('href', elm.attr('href'));
    $('#foto_big').parent().attr('title', text);
    $('a.lbox-inactive').removeClass('lbox-inactive').addClass('lbox');
    $(a).next().children('a').removeClass('lbox').addClass('lbox-inactive');
    
    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';
    
    resizeImage();
    activateLightBox();
    
	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")
}

/**
*
*  Javascript sprintf
*  http://www.webtoolkit.info/
*
* sprintf("Decimal %+05d, Float %07.2f, String '%-10.4s', Hexadecimal %05X", 123, 123, 'abcdefg', 123123);
*
* %% – Returns a percent sign
* %b – Binary number
* %c – The character according to the ASCII value
* %d – Signed decimal number
* %f – Floating-point number
* %o – Octal number
* %s – String
* %x – Hexadecimal number (lowercase letters)
* %X – Hexadecimal number (uppercase letters)
*
* Additional format values. These are placed between the % and the letter (example %.2f):
* + (Forces both + and – in front of numbers. By default, only negative numbers are marked)
* – (Left-justifies the variable value)
* 0 zero will be used for padding the results to the right string size
* [0-9] (Specifies the minimum width held of to the variable value)
* .[0-9] (Specifies the number of decimal digits or maximum string length)
*
**/

sprintfWrapper = {

	init : function () {

		if (typeof arguments == "undefined") { return null; }
		if (arguments.length < 1) { return null; }
		if (typeof arguments[0] != "string") { return null; }
		if (typeof RegExp == "undefined") { return null; }

		var string = arguments[0];
		var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
		var matches = new Array();
		var strings = new Array();
		var convCount = 0;
		var stringPosStart = 0;
		var stringPosEnd = 0;
		var matchPosEnd = 0;
		var newString = '';
		var match = null;

		while (match = exp.exec(string)) {
			if (match[9]) { convCount += 1; }

			stringPosStart = matchPosEnd;
			stringPosEnd = exp.lastIndex - match[0].length;
			strings[strings.length] = string.substring(stringPosStart, stringPosEnd);

			matchPosEnd = exp.lastIndex;
			matches[matches.length] = {
				match: match[0],
				left: match[3] ? true : false,
				sign: match[4] || '',
				pad: match[5] || ' ',
				min: match[6] || 0,
				precision: match[8],
				code: match[9] || '%',
				negative: parseInt(arguments[convCount]) < 0 ? true : false,
				argument: String(arguments[convCount])
			};
		}
		strings[strings.length] = string.substring(matchPosEnd);

		if (matches.length == 0) { return string; }
		if ((arguments.length - 1) < convCount) { return null; }

		var code = null;
		var match = null;
		var i = null;

		for (i=0; i<matches.length; i++) {

			if (matches[i].code == '%') { substitution = '%' }
			else if (matches[i].code == 'b') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'c') {
				matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'd') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'f') {
				matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'o') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 's') {
				matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'x') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'X') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
			}
			else {
				substitution = matches[i].match;
			}

			newString += strings[i];
			newString += substitution;

		}
		newString += strings[i];

		return newString;

	},

	convert : function(match, nosign){
		if (nosign) {
			match.sign = '';
		} else {
			match.sign = match.negative ? '-' : match.sign;
		}
		var l = match.min - match.argument.length + 1 - match.sign.length;
		var pad = new Array(l < 0 ? 0 : l).join(match.pad);
		if (!match.left) {
			if (match.pad == "0" || nosign) {
				return match.sign + pad + match.argument;
			} else {
				return pad + match.sign + match.argument;
			}
		} else {
			if (match.pad == "0" || nosign) {
				return match.sign + match.argument + pad.replace(/0/g, ' ');
			} else {
				return match.sign + match.argument + pad;
			}
		}
	}
}

sprintf = sprintfWrapper.init;