var countries = null;
var cities = {};
var cities_by_country = {};
var hotels = {};

String.prototype.translit = function () {
    var text   = this;
    var ru_str = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя';
    var en_str = [
    'A','B','V','G','D','E','Jo','Zh','Z','I','Y','K','L','M','N','O','P','R','S','T','U','F',
    'Kh','Ts','Ch','Sh','Shch','','Y','','E','Yu','Ya',
    'a','b','v','g','d','e','jo','zh','z','i','y','k','l','m','n','o','p','r','s','t','u','f',
    'kh','ts','ch','sh','shch','\'','y','','e','yu','ya'];

    for(var i = 0, out = [], count = text.length; i < count; i++) {
        var s = text.charAt(i), n = ru_str.indexOf(s);
        out[out.length] = (n >= 0) ? en_str[n] : s;
    }
    return out.join('');
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

$.fn.scrollTo = function () {
	$('html, body').animate({scrollTop:$(this).offset().top}, 500);
}

$.fn.outer = function(s) {
	return (s) ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
}

String.prototype.unserialize = function() {
	var res = {};
	$.each(this.split('&'),function(i, item) {
		var val = item.split('=');
		res[val[0]] = val[1] ? val[1] : null;
	});
	return res;
}

function loadHotel(id, callback) {
	$.ajax({
		url : '/constructor/hotel/'+id,
		timeout : 10000,
		beforeSend : function() {
		},
		success : function(data) {
			hotels[id] = eval('('+data+')');
			callback();
		}
	});
}

function getHotel(id) {
	if (!hotels[id]) {
		$.ajax({
			async : false,
			url : '/constructor/hotel/'+id,
			timeout : 10000,
			beforeSend : function() {
			},
			success : function(data) {
				hotels[id] = eval('('+data+')');
			}
		});
	}

	return hotels[id];
}

function loadCities(id, callback) {
	$.ajax({
		url : '/constructor/cities/'+id,
		timeout : 100000,
		beforeSend : function() {
			//$('#loading').show();
		},
		success : function(data) {
			//$('#loading').hide();
			var _cities = eval('('+data+')');
			var cityId;
			for (var i=0;i<_cities.length;i++) {
				cityId = _cities[i].id;
				if (!cities[cityId]) cities[cityId] = _cities[i];
			}
			cities_by_country[id] = _cities;
			callback(id);
		}
	});
}

function getCity(id) {
	if (!cities[id]) {
		$.ajax({
			async : false,
			url : '/constructor/city/'+id,
			timeout : 10000,
			beforeSend : function() {
			},
			success : function(data) {
				cities[id] = eval('('+data+')');
				if (!cities_by_country[cities[id].countryId]) cities_by_country[cities[id].countryId] = {};
				cities_by_country[cities[id].countryId][id] = cities[id];
			}
		});
	}
	
	return cities[id];
}

function loadCountries(callback) {
	$.ajax({
		url : '/constructor/countries',
		timeout : 10000,
		beforeSend : function() {
			//$('#loading').show();
		},
		success : function(data) {
			//$('#loading').hide();
			countries = eval('('+data+')');
			callback();
		}
	});
}

function getRandomInt(min, max)
{
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

var Popup = function(id, width, height, closeCallback) {
	this.id = id;
	this.popup = $('#'+id);
	
	if (width) $(this.popup).width(width);
	if (height) $(this.popup).height(height);
	
	var _this = this;
	this.popup.find('a[rel=closelink]').unbind().click(function () {
		if (closeCallback) {
			closeCallback(_this.popup);
		} else {
			_this.close();
		}
		
		return false;
	}).show();
	
	this.popup.find('div[rel=message-body]').html(''); // reset content
	
	this.setTitle = function(title) {
		this.popup.find('h1').text(title);
	}
	
	this.setContent = function(html) {
		$(this.popup).html(html);
	}
	
	this.getContent = function() {
		return $(this.popup).html();
	}
	
	this.show = function(notCenter) {
		if($.browser.msie || $.browser.opera) {
			$(this.popup).appendTo('body'); // need for right centering
			
			// remove rocon artifact in ie
			if($.browser.msie) {
				$(this.popup).find('span.rocon').remove();
			}
			
			// update rocon
			rocon.process(document.getElementById(this.id));
		}
		
		var scrollTop = 0;
		if ($.browser.webkit) {
			scrollTop = $('body').scrollTop();
		} else {
			scrollTop = $('html, body').scrollTop();
		}
				
		if (notCenter) {
			$(this.popup).css({
				'top': scrollTop
			});
		} else {
			var top = scrollTop+(($(window).height()-$(this.popup).height())/2);
			
			if (scrollTop > top) {
				top = scrollTop;
			}
			// center popup
			$(this.popup).css({
				'top': top
			});
		}
		
		$(this.popup).show();
		
		// blanking
		if(!$("body").find("#TB_overlay").is("div")) /* если фон уже добавлен не добавляем повторно */
		{
			if(!$.browser.msie) /* если браузер не ИЕ фоном будет div */
			$("body").append("<div id='TB_overlay'></div>");
			else /* иначе добавляем iframe */
			$("body").append("<div id='TB_overlay'><iframe scrolling='no' frameborder='0' style='position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter:alpha(opacity=0)'></iframe></div>");
		}
	}
	
	this.hideCloseLink = function() {
		this.popup.find('a[rel=closelink]').hide();
	}
	
	this.showCloseLink = function() {
		this.popup.find('a[rel=closelink]').show();
	}
	this.showCloseLink(); // default is visible
	
	this.hide = function() {
		this.popup.hide();
	}
	
	this.close = function() {
		this.hide();
		$('#TB_overlay').remove();
	}
}

//stub for date
function dateAdd(date, days) {
	var d = new Date(date);
	d.setDate(d.getDate() + days);
	return d;
}
