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) {
	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));
}

/***** GOOGLE MAPS */
// http://gmaps-samples.googlecode.com/svn/trunk/spreadsheetsmapwizard/exampleoutput.htm
function closeMap() {
	document.getElementById('map_container').style.display = 'none';
}
	
var google_map;
var google_marker;
function showHotelOnMap(object) {
	if (!(object.lat || object.lng))
		return false;
	gebi('map_container').style.display='';
	centerObject('map_container');
  var latlng = new google.maps.LatLng(object.lat, object.lng);
  var myOptions = {
  	zoom: 14,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	if (!google_map)
  	google_map = new google.maps.Map(gebi("google_map"), myOptions);
  if (!google_marker) {
  	google_marker = new google.maps.Marker({
  		position: latlng, 
    	map: google_map,
    	title: object.title
		});
  } else {
  	google_marker.set_position(latlng);
  	google_marker.set_title(object.title);
  }
  google_map.set_center(latlng);
}


/***** 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" }

/***** 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+1].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_rates) && !isEmpty(g_curr_rates[currInId]) && !isEmpty(g_curr_rates[currOutId]))
		return price * g_curr_rates[currInId]['act0013sell_____']/g_curr_rates[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 testReservationForm() {
	// 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;
	for (var i=0; i<g_services_ids.length; i++) {
		var inp = gebi('service-'+g_services_ids[i]);
		if (typeof inp!='undefined' && inp.value>0) {
			services_filled = true;
			break;
		}
	}
	if (services_filled)
		return true;
	else {
		alert(g_txt['fill-rooms']);
		return false; 
	}
}

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 onChangeTerm(arrivalChanged) {
	if (arrivalChanged)
		correctDeparture();
	changeNrOfNights();
	changePrices();
	changeTotalPrice();
}

function onChangeNrOfNights() {
	changeDepartureByNights(); 
	changePrices();	
	changeTotalPrice();
}

function writeM() {
	document.write('<a href="' + 'm' + 'a' + 'i' + 'l' + 't' + 'o:booking' + '@' + 'hotele.cz">' + 'booking' + '@' + 'hotele.cz' + '</a>');	
}