var targ;
window.onload=function(){
	document.onmouseup=stopDrag;
	dv=document.getElementsByTagName('div');
	for(var i=0; i < dv.length; i++){
		if(dv[i].className=='drag'){
			dv[i].onmousedown=actDrag;
			dv[i].onmouseup=stopDrag;
			dv[i].style.position="absolute";
			dv[i].style.cursor="pointer";
		}
	}
};

function actDrag(e){
	e= e || window.event;
	x1=e.clientX;
	y1=e.clientY;
	targ=e.target?e.target:e.srcElement;
	targ.onmousemove=startDrag;
	document.onmousemove=startDrag;
	coordX=targ.offsetLeft-x1;
	coordY=targ.offsetTop-y1;
}

function startDrag(e){
	if (targ) {
		e= e || window.event;
		targ.style.left=coordX+e.clientX+'px';
		targ.style.top=coordY+e.clientY+'px';
	}
}
function stopDrag(e){
	if (targ) {
		targ.onmousemove=null;
		document.onmousemove=null;
	}
}

Date.prototype.between = function(start, end) {
	if ( !(start instanceof Date))
		if ((start = getDate(start))==false)
			return false;
	if ( !(end instanceof Date))
		if ((end = getDate(end))==false)
			return false;
	var t = this.getTime();
	return start.getTime() <= t && t <= end.getTime();
}
Date.prototype.addDay = function() {
	this.setDate(this.getDate()+1);
}
Date.prototype.addDays = function(nrOfDays) {
	this.setDate(this.getDate() + parseInt(nrOfDays));
}
Date.prototype.getDayDifference = function(date) {
	var diff = this.getTime() - date.getTime();
	return Math.round(diff / ( 1000 * 24 * 3600));
}

function isDateCorrect(date) {
	return (date instanceof Date && !isNaN(date.getTime())) ? true : false;
}


/***** PHP2JS FCE */
function is_numeric( mixed_var ) { return (mixed_var === '') ? false : !isNaN(mixed_var * 1); }

function number_format( number, decimals, dec_point, thousands_sep ) {
	var n = number, prec = decimals;
	n = !isFinite(+n) ? 0 : +n;
	prec = !isFinite(+prec) ? 0 : Math.abs(prec);
	var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
	var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
	var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec);
	var abs = Math.abs(n).toFixed(prec);
	var _, i;
	if (abs >= 1000) {
		_ = abs.split(/\D/);
		i = _[0].length % 3 || 3;
		_[0] = s.slice(0,i + (n < 0)) + _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
		s = _.join(dec);
	} else {
		s = s.replace('.', dec);
	}
	return s;
}

/***** POMOCNE FCE */
function gebi(id) { return document.getElementById(id); }

function getComboValue(comboId) {
	var combo = gebi(comboId); 
	if (!combo || typeof(combo)=='undefined')
		return false;
	return combo.options[combo.selectedIndex].value;
}
function getComboText(comboId) {
	var combo = gebi(comboId); 
	if (!combo || typeof(combo)=='undefined')
		return false;
	return combo.options[combo.selectedIndex].text;
}
function setComboValue(comboId, value) {
	var combo = gebi(comboId); 
	if (!combo || typeof(combo)=='undefined')
		return false;
	for (i=0; i<combo.options.length; i++) {
		if (combo.options[i].value==value) {
			combo.selectedIndex = i;
			return;
		}
	}
}

function fillLeadingZeros(number, length) {
	numberLength = number.toString().length;
	if (numberLength>length)
		return number;
	for (var i=0; i<(length-numberLength); i++)
		number = '0' + number;
	return number;
}

/**
 * @desc z retezce Y-m-d vytvori datum
 * @param {string} date
 * @return {Date object}
 */
function getDate(date) {
	if (/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(date)==false)
		return false;
	var dateParts = date.split('-');
	return new Date(dateParts[0], dateParts[1]-1, dateParts[2]);
}

function isEmpty(v,allowBlank) { return v===null || v===undefined || (!allowBlank ? v==="" : false); }
function isArray(v){ return v&&typeof v.length=="number"&&typeof v.splice=="function" }
function isEmptyOrFalse(v,allowBlank) { return v===null || v===undefined || v===false || (!allowBlank ? v==="" : false); }

/***** COOKIE FCE */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/***** OSTATNI FCE */
function list_pricelist_toggle_on_off(id, nr, moreMsg, hideMsg, a) {
	var TRs = gebi(id).getElementsByTagName('tr');
	if (TRs.length>nr) {
		var isOff = TRs[nr+2].style.display == 'none';
    for (var i=nr+1; i<TRs.length; i++)
			TRs[i].style.display = isOff ? '' : 'none';
		a.innerHTML = isOff ? hideMsg : moreMsg;
	}
}

function replaceQueryString(url,param,value) {
	var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
	if (url.match(re))
		return url.replace(re,'$1' + param + "=" + value + '$2');
	else if (url.indexOf("?") == -1)
		return url + '?' + param + "=" + value;
	else
		return url + '&' + param + "=" + value;
}

function changeHrefWithNewSorting(sortBy) {
/*
	var href = replaceQueryString(location.href, 'sbd', desc);
	href = replaceQueryString(href, 'page', 1);
*/
	location.href = replaceQueryString(location.href, 'sortby', sortBy);
/*	
	if (location.search!='') {
		var hrefWithoutParams = location.href.split(/\?/)[0];   
		var pairs = location.search.substring(1).split(/\&/);
		for (var i in pairs) {
			var nameVal = pairs[i].split(/\=/);
			if (nameVal[0]=='p' || nameVal[0]=='sortby')
				continue;
			getVars[unescape(nameVal[0])] = unescape(nameVal[1]);
		}
	} else
		var hrefWithoutParams = location.href;
	if (hrefWithoutParams.match(/\/p-[0-9]+$/))
		hrefWithoutParams = hrefWithoutParams.substring(0, hrefWithoutParams.lastIndexOf('/')+1);
	var vars = '';
	getVars['sortby'] = sortBy;
	var j=0;
	for (var k in getVars)
		vars += k + '=' + getVars[k];
	location.href = hrefWithoutParams + '?' + vars;
*/	
}

function recountPrice(price, currInId, currOutId) {
	if (currInId==currOutId)
		return price;
	if (!isEmpty(g_curr) && !isEmpty(g_curr[currInId]) && !isEmpty(g_curr[currOutId]))
		return price * g_curr[currInId]['act0013sell_____']/g_curr[currOutId]['act0013sell_____'];
	else
		return '';
}

function changeAllPricesByCurrency(bRewritePrice) {
	var is = document.getElementsByTagName('span');
	test = 1;
}

function focus_alert(field, msg) {
	field.focus();
	alert(msg);
	return false;
}

function testReservationArrivalDepartureDates() {
	var arrival = getArrivalDate();
	var departure = getDepartureDate();
	if (!isDateCorrect(arrival) || !isDateCorrect(departure) || arrival.getTime()>=departure.getTime())
		return false;
	arrival.setHours(23,59,59);
	departure.setHours(23,59,59);
	var today = new Date();
	if (today.getTime()>arrival.getTime() || today.getTime()>departure.getTime())
		return false;	
	return true;
}

function testReservationForm() {
	// termin
	if (!testReservationArrivalDepartureDates())
		return focus_alert(gebi('d1'), g_txt['change-dates']);
	// pocet osob
	var nr_persons = parseInt(gebi('persons').value);
	if (nr_persons>0)
		gebi('persons').value = nr_persons;
	else
		return focus_alert(gebi('persons'), g_txt['fill-persons']);
	// pokoje
	var services_filled = false, chosen_rooms = null, rooms_people = 0, rooms_extras = 0;
	for (var i=0; i<g_services_ids.length; i++) {
		if (gebi('service-'+g_services_ids[i]).disabled) 
			continue;
		if ((chosen_rooms = getComboValue('service-'+g_services_ids[i]))>0) {
			if (g_rooms[g_services_ids[i]].is_extra==0) {
				rooms_people += chosen_rooms*g_rooms[g_services_ids[i]].pax;
				rooms_extras += g_rooms[g_services_ids[i]].nr_extra;
				services_filled = true;
			} else if ((g_rooms[g_services_ids[i]].is_extra&2)==2)
				rooms_people += chosen_rooms*1;
		}
	}
	if (!services_filled) {
		alert(g_txt['fill-rooms']);
		return false; 
	}
	// pocet osob <= suma osob pres pokoje ?
	if (nr_persons>rooms_people) {
		// je mozne pridat pouze pristylky
		if ((rooms_people+rooms_extras)>nr_persons)
			alert(g_txt['pax-higher-rooms-2'].replace(/{#PEOPLE_NUMBER#}/, nr_persons).replace(/{#PEOPLE_ROOMS#}/, rooms_people).replace(/{#EXTRA_BEDS#}/, nr_persons-rooms_people));
		// je nutne pridat pokoje
		else
			alert(g_txt['pax-higher-rooms'].replace(/{#PEOPLE_NUMBER#}/, nr_persons).replace(/{#PEOPLE_ROOMS#}/, rooms_people));
		return false; 
	}
	// minimalni pocet noci
	if (g_minnights>0 && g_minnights>g_nr_of_nights) {
		alert(g_txt['require-more-nights'].replace(/{#NIGHTS#}/, g_minnights));
		return false;
	}
	return true;
}

function testRequestForPriceForm() {
	// jmeno, prijmeni, telefon, email
	if (gebi('firstname').value=='') 
		return focus_alert(gebi('firstname'), g_txt['txt171'] + ': ' + g_txt['first-name']);
	if (gebi('surname').value=='') 
		return focus_alert(gebi('surname'), g_txt['txt171'] + ': ' + g_txt['txt146']);
/*
	if (gebi('tel').value=='') 
		return focus_alert(gebi('tel'), g_txt['txt171'] + ': ' + g_txt['txt147']);
*/
	if (gebi('email').value=='') 
		return focus_alert(gebi('email'), g_txt['txt171'] + ': ' + g_txt['txt55']);
	filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(gebi('email').value))
		return focus_alert(gebi('email'), g_txt['txt185']);
	// pocet osob
	var nr_persons = parseInt(gebi('persons').value);
	if (nr_persons>0)
		gebi('persons').value = nr_persons;
	else
		return focus_alert(gebi('persons'), g_txt['fill-persons']);
	// pokoje
	var services_filled = false, chosen_rooms = null, rooms_people = 0;
	for (var i=0; i<g_services_ids.length; i++) {
		if (gebi('service-'+g_services_ids[i]).disabled) 
			continue;
		if ((chosen_rooms = getComboValue('service-'+g_services_ids[i]))>0) {
			if (g_rooms[g_services_ids[i]].is_extra==0) {
				services_filled = true;
				rooms_people += chosen_rooms*g_rooms[g_services_ids[i]].pax;
			} else if ((g_rooms[g_services_ids[i]].is_extra&2)==2)
				rooms_people += chosen_rooms*1;
		}
	}
	if (!services_filled) {
		alert(g_txt['fill-rooms']);
		return false; 
	}
	// pocet osob <= suma osob pres pokoje ?
	if (nr_persons>rooms_people) {
		alert(g_txt['pax-higher-rooms'].replace(/{#PEOPLE_NUMBER#}/, nr_persons).replace(/{#PEOPLE_ROOMS#}/, rooms_people));
		return false; 
	}
	return true;
}

function centerObject(sId) {
	if (document.all) {
		var top = (window.screen.height - document.getElementById(sId).offsetHeight)/2;
		var left = (window.screen.width - document.getElementById(sId).offsetWidth)/2;
		document.getElementById(sId).style.left = (left + document.documentElement.scrollLeft) + 'px';
		document.getElementById(sId).style.top = (top + document.documentElement.scrollTop) + 'px';
	} else {
		var top = (window.innerHeight - document.getElementById(sId).offsetHeight)/2;
		var left = (window.innerWidth - document.getElementById(sId).offsetWidth)/2;
		document.getElementById(sId).style.left = (left + window.pageXOffset) + 'px';
		document.getElementById(sId).style.top = (top + window.pageYOffset) + 'px';
	}
}

function getArrivalDate() {
	var d = getComboValue('d1');
	var yearMonth = getComboValue('m1').split('-');
	return new Date(yearMonth[0], yearMonth[1]-1, d);
}
function getDepartureDate() {
	var d = getComboValue('d2');
	var yearMonth = getComboValue('m2').split('-');
	return new Date(yearMonth[0], yearMonth[1]-1, d);
}
function getArrivalMonth() { var yearMonth = getComboValue('m1').split('-'); return yearMonth[1]; }
function getArrivalYear() { var yearMonth = getComboValue('m1').split('-'); return yearMonth[0]; }
function getDepartureMonth() { var yearMonth = getComboValue('m2').split('-'); return yearMonth[1]; }
function getDepartureYear() { var yearMonth = getComboValue('m2').split('-'); return yearMonth[0]; }

function setArrivalCombo(date) {
	setComboValue('d1', date.getDate());
	setComboValue('m1', (date.getFullYear())+'-'+fillLeadingZeros(date.getMonth()+1, 2));
}
function setDepartureCombo(date) {
	setComboValue('d2', date.getDate());
	setComboValue('m2', (date.getFullYear())+'-'+fillLeadingZeros(date.getMonth()+1, 2));
}

function correctNights() {
	var nights = parseInt(gebi('nights').value);
	if (nights<0) {
		nights = -1 * nights;
		gebi('nights').value = nights;
	} else if (nights==0) {
		nights = 1;
		gebi('nights').value = nights;
	}
}
function changeDepartureByNights() {
	correctNights();
	var nights = parseInt(gebi('nights').value);
	var arrival = getArrivalDate();
	arrival.addDays(nights);
	setDepartureCombo(arrival); 
}

function changeNrOfNights() {
	var arrival = getArrivalDate();
	var departure = getDepartureDate();
	gebi('nights').value = departure.getDayDifference(arrival);
}

function correctArrival() {
	var arrival = getArrivalDate();
	var departure = getDepartureDate();
	if (arrival.getTime()<departure.getTime())
		return;
	arrival = departure;
	arrival.addDays(-gebi('nights').value);
	setArrivalCombo(arrival);
}
function correctDeparture() {
	var arrival = getArrivalDate();
	var departure = getDepartureDate();
	if (arrival.getTime()<departure.getTime())
		return;
	departure = arrival;
	departure.addDays(gebi('nights').value);
	setDepartureCombo(departure);
}

function writeM() {
	document.write('<a href="' + 'm' + 'a' + 'i' + 'l' + 't' + 'o:booking' + '@' + 'hotele.cz">' + 'booking' + '@' + 'hotele.cz' + '</a>');	
}
function writeM2(sHotel, sDomain) {
	if ((typeof sDomain == 'undefined') || sDomain=='')
		sDomain = 'hotele.cz';
	document.write('<a href="' + 'm' + 'a' + 'i' + 'l' + 't' + 'o:' + sHotel + '@' + sDomain+ '">' + sHotel + '@' + sDomain + '</a>');	
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}  

function submitMainForm(sFormAction, sMethod, bSubmit) {
	if (isEmpty(bSubmit))
		bSubmit = false;
	if (isEmpty(sMethod))
		sMethod = '';
	form = gebi('mainform');
	if (this.checkForm && this.checkForm(form)==false)
		return false;
	if (sFormAction!='')
		form.action = sFormAction;
	if (!isEmpty(gebi('_action')))
		gebi('_action').value = sMethod;
	if (bSubmit) {
		form.submit();
		return false;
	}
}

/**** PRICELIST ****/
function getPriceAndRecountedPrice(fPrice, iCurrencyId, fRecountedPrice, iRecountedCurrencyId, bForceRecount) {
	if (isEmpty(fRecountedPrice))
		fRecountedPrice = null;
	if (isEmpty(iRecountedCurrencyId))
		iRecountedCurrencyId = null;
	if (isEmpty(bForceRecount))
		bForceRecount = false;
	var sCurrencyCode = g_curr[iCurrencyId]['act0005code_____'];
  var s = number_format(fPrice, sCurrencyCode=='CZK' ? 0 : 2, '.', ' ') + '&nbsp;' + sCurrencyCode;
  if (iCurrencyId!=iRecountedCurrencyId) {
  	if (isEmpty(fRecountedPrice) && !(isEmpty(iRecountedCurrencyId)) && bForceRecount)
  		fRecountedPrice = recountPrice(fPrice, iCurrencyId, iRecountedCurrencyId);
  	if (!isEmpty(fRecountedPrice))
  		s += ' ~ ' + number_format(fRecountedPrice, 0, '', ' ') + '&nbsp;' + g_curr[iRecountedCurrencyId]['act0005code_____'];
	}
	return s;
}

// pri zmene poctu pokoju zobrazi novou cenu
function changePrice(service_id) {
	if (isEmpty(g_prices) || isEmpty(g_prices[service_id]))
		return;
	if (gebi('service-'+service_id).value=='')
		gebi('price-'+service_id).innerHTML = '';
	else {
		var iNumber = 1*gebi('service-'+service_id).value;
		if (iNumber>0) 
			gebi('price-'+service_id).innerHTML = getPriceAndRecountedPrice(iNumber * g_prices[service_id], g_currency.id, null, getComboValue('currency'), true);
		else
			gebi('price-'+service_id).innerHTML = '';
	} 
	changeTotalPrice();
}

function changeTotalPrice() {
	var fTotalPrice = 0;
	for (var i=0; i<g_services_ids.length; i++)
		fTotalPrice += gebi('service-'+g_services_ids[i]).value * g_prices[g_services_ids[i]];
	gebi('total-price').innerHTML = getPriceAndRecountedPrice(fTotalPrice, g_currency.id, null, getComboValue('currency'), true); 
	return true;
}

function showPrices() {
	var arrival = getArrivalDate();
	var departure = getDepartureDate();
	var iNumber = null, iNrOfNights = departure.getDayDifference(arrival) 
	gebi('upon-request-info').style.display = 'none';
	for (var i=0; i<g_services_ids.length; i++) {
		gebi('price-night-'+g_services_ids[i]).innerHTML = getPriceAndRecountedPrice(Math.round(g_prices[g_services_ids[i]]/iNrOfNights), g_currency.id, null, getComboValue('currency'), true);
 		if ((iNumber = gebi('service-'+g_services_ids[i]).value)>0)
			gebi('price-' + g_services_ids[i]).innerHTML = getPriceAndRecountedPrice(iNumber * g_prices[g_services_ids[i]], g_currency.id, null, getComboValue('currency'), true);
		else
			gebi('price-' + g_services_ids[i]).innerHTML = '';
	}
}

/**
* nahled obrazku: po najeti na maly obrazek se zobrazi velky
*/
function onHoverImagesPreview() {	
	xOffset = -280;
	yOffset = 25;
		
	$('a.onhoverpreview').hover(function(e) {
			this.t = this.title;
			this.title = '';	
			var c = (this.t != '') ? '<br/>' + this.t : '';
			$('body').append('<p id="onhoverpreview"><img src="'+ this.href + '" alt="Image preview" />' + c + '</p>');								 
			$('#onhoverpreview')
				.css('left',(e.pageX + xOffset) + 'px')
				.css('top',(e.pageY + yOffset) + 'px')
				.fadeIn('fast');
  	},
		function() {
			this.title = this.t;
			$('#onhoverpreview').remove();
		}
	);	
	$('a.onhoverpreview').mousemove(function(e) {
		$('#onhoverpreview')
			.css('left',(e.pageX + xOffset) + 'px')
			.css('top',(e.pageY + yOffset) + 'px');
	});			
}

