//===================================utils dump=============================
/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
	 for(var item in arr) {
	  var value = arr[item];

	  if(typeof(value) == 'object') { //If it is an array,
	   dumped_text += level_padding + "'" + item + "' ...\n";
	   dumped_text += dump(value,level+1);
	  } else {
	   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
	  }
	 }
	} else { //Stings/Chars/Numbers etc.
	 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

//==============================

function set_center(id) {
	try {
		var obj_w = $(id).offsetWidth;
		var obj_h = $(id).offsetHeight;
		var win_w = window.innerWidth;
		var win_h = window.innerHeight;

		var offset_left = (win_w - obj_w) / 2;
		var offset_top = Math.max(((win_h - obj_h) / 2), 0);

		$(id).setStyle({
			left: offset_left,
			top: offset_top
		});
	}
	catch(e){

		 alert('Невозможно выполнить скрипт. \nИбо:\n' + e);
	}
}
//==============================

function select_img_dialog(target) {

	new Ajax.Updater('dialog_popup', '/post.php?module=media&action=img_select_popup&field_name='+target,{
			onSuccess: function(transport){
				$('dialog_popup_main').show();
			}
		});

	//$('dialog_popup').innerHTML = '1111';

}

//для совместимости с holydays, events, etc. Исправить когда-нибудь
function select_img_dialog_old(target) {

	new Ajax.Updater('dialog_popup', '/post.php?module=media&action=img_select_popup_old&field_name='+target,{
			onSuccess: function(transport){
				$('dialog_popup_main').show();
			}
		});

	//$('dialog_popup').innerHTML = '1111';

}

function select_img_dialog_filter(target,tag) {

	new Ajax.Updater('dialog_popup','/post.php?module=media&action=img_select_popup&field_name='+target+'&tag='+tag,
		{
			onSuccess: function(transport){
				$('dialog_popup_main').show();
			}
		});
}

function flv_show_dialog(filename, preview) {


	$('dialog_popup').innerHTML="<div id='flv_preview'></div>";

	var s1 = new SWFObject("swf/player.swf","ply","328","200","9","#FFFFFF");
		s1.addParam("allowfullscreen","true");
		s1.addParam("allowscriptaccess","always");
		s1.addParam("flashvars","file=http://visit.lh/get.php?filename=" + filename + "&image=http://visit.lh/get.php?filename=/flv/" + preview );

		s1.write("flv_preview");
	$('dialog_popup_main').show();
}
function img_show_dialog(filename) {
	$('dialog_popup').update('<img onclick="dialog_close();" src="get.php?filename='+filename+'">');
	$('dialog_popup_main').show();

	set_center('dialog_popup_main');
}

function dialog_close() {

	$('dialog_popup_main').hide();
}

var __position, __name;

function init () {
	map = new YMaps.Map(document.getElementById("YMapsID"));

	map.addControl(new YMaps.Zoom());

//	map.addControl(new GoBigMap());


	var geocoder = new YMaps.Geocoder(__position);
				   YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
					   if (this.length()) {
						map.setBounds(this.get(0).getBounds());
						var geoPoint=this.get(0).getGeoPoint();
						map.setCenter(geoPoint, 13);

						map.addOverlay(this.get(0));
						this.get(0).setBalloonContent(__name);
						this.get(0).openBalloon();

	}
	});
}

function init () {
	map = new YMaps.Map(document.getElementById("YMapsID"));

	map.addControl(new YMaps.Zoom());

	map.addControl(new GoBigMap());


	var geocoder = new YMaps.Geocoder(__position);
				   YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
					   if (this.length()) {
						map.setBounds(this.get(0).getBounds());
						var geoPoint=this.get(0).getGeoPoint();
						map.setCenter(geoPoint, 13);

						map.addOverlay(this.get(0));
						this.get(0).setBalloonContent(__name);
						this.get(0).openBalloon();

	}
	});
}


function show_map_dialog(position, name) {
	$('dialog_popup').innerHTML = '<div id="YMapsID" style="width:700px;height:500px;margin-top:18px;"></div>';
	__position = position;
	__name = name;

	$('dialog_popup_main').setStyle({
		width: '700px',
		height: '520px',
		left: Math.max(Math.floor(document.viewport.getWidth()/2 - 350), 0) + 'px',
		top: Math.max(Math.floor(document.viewport.getScrollOffsets().top + document.viewport.getHeight()/2 - 250) , 0) + 'px'
	});
	$('dialog_popup_main').show();

	YMaps.load(init);

}

function load_map_geo(position, name, route_anchor) {

	map = new YMaps.Map(document.getElementById("YMapsID"));

	map.setCenter(YMaps.GeoPoint.fromString(position),12);
	//map.enableScrollZoom();

	map.addControl(new YMaps.ToolBar());
	map.addControl(new YMaps.Zoom());

	/*var router = new YMaps.Router([new YMaps.GeoPoint(30.658509,59.758331),
	new YMaps.GeoPoint(30.594306,59.735429)]

	);*/
	/*var router = new YMaps.Router([new YMaps.GeoPoint(37.658509,55.758331),
							   new YMaps.GeoPoint(37.594306,55.735429)]);*/

	/*	YMaps.Events.observe(router, router.Events.Success, function() {
			router.getWayPoint(0).setIconContent('Точка отправления');
			router.getWayPoint(1).setIconContent('Точка прибытия');
				  map.addOverlay(router);
		});*/
	//map.addOverlay(router);

   //map.addOverlay(new YMaps.Placemark(YMaps.GeoPoint.fromString(position)));

	var placemark = new YMaps.Placemark(YMaps.GeoPoint.fromString(position));


	map.addOverlay(placemark);

	placemark.setBalloonContent(name);
	placemark.openBalloon();

	//if (route_anchor) {

	//}

}

function load_map_into(position, name) {
	__position = 'Санкт-Петербург,'+position;	//todo: get geocode and fiiiiiix this shit for the justice
	__name = name;

	var geocoder = new YMaps.Geocoder(__position);
				   YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
					   if (this.length()) {
						map.setBounds(this.get(0).getBounds());
						var geoPoint=this.get(0).getGeoPoint();
						map.setCenter(geoPoint, 13);

						map.addOverlay(this.get(0));
						this.get(0).setBalloonContent(__name);
						this.get(0).openBalloon();

	}
	});
}
//--------------------------------------

	function catalog_category_edit(id) {
		$('label_'+id).hide();
		$('categorys_edit_gen_'+id).hide();
		$('edit_category_'+id).show();
		$('categorys_edit_etc_'+id).show();
	}

	function categorys_edit_cancel(id) {
		$('label_'+id).show();
		$('categorys_edit_gen_'+id).show();
		$('edit_category_'+id).hide();
		$('categorys_edit_etc_'+id).hide();
	}

//--------------------------------------

	function ubase_category_edit(id) {
		$('label_'+id).hide();
		$('categorys_edit_gen_'+id).hide();
		$('edit_category_'+id).show();
		$('edit_type_'+id).show();
		$('edit_categoryid_'+id).show();
		$('categorys_edit_etc_'+id).show();
	}

	function ubase_edit_cancel(id) {
		$('label_'+id).show();
		$('categorys_edit_gen_'+id).show();
		$('edit_category_'+id).hide();
		$('edit_categoryid_'+id).hide();
		$('edit_type_'+id).hide();
		$('categorys_edit_etc_'+id).hide();
	}


//--------------------------------------
/*
function xmpp_show() {

	new Ajax.Request('/get.php?mode=xmpp',{
			onSuccess: function(transport){
				$('chat_main').update(transport.responseText);

				$('chat_window').show();

				xmpp_init();
			}
		});
}
*/

function chat_init() {
	if($('chat_window')){
		new Ajax.Request('/post.php?module=xmpp&action=set_chat_opened',{
			onSuccess: function(transport){
				$('chat_main').innerHTML = '';
				xmpp_reply_check();
				$('chat_window').show();
				$('chat_input').focus();
				$('chat_input').scrollTo();
			}
		});
	}else{
		alert('Нет окна чата');
	}
}

function chat_uninit(){
	new Ajax.Request('/post.php?module=xmpp&action=set_chat_closed',{
		onSuccess: function(transport){
			if(document.xmpp_counter){
				document.xmpp_counter = null;
				$('chat_window').hide();
			}
		}
	});
}

function xmpp_reply_check() {
//	$('xmpp_status').innerHTML='updating...';
	xmpp_reload();
	$('chat_main').scrollTop = 1000000;
	document.xmpp_counter = setTimeout('xmpp_reply_check()', 10000);
}

function xmpp_reload(){
	new Ajax.Request('/post.php?module=xmpp&action=xmpp_get_reply',{
		onSuccess: function(transport){
//			$('xmpp_status').innerHTML='reply get, ok';
			$('chat_main').update(transport.responseText);
			$('chat_main').scrollTop = 1000000;
		}
	});
}

function xmpp_send(msg) {
	$('chat_input').value = '';
	if(!msg){
		return true;
	}
//	sleep(1);
	new Ajax.Request('/post.php?module=xmpp&action=xmpp_send&msg='+msg,{
			onSuccess: function(transport){
//				Stamp = new Date();
//				var Mins = Stamp.getMinutes();

//				if (Mins < 10) {
//					Mins = "0" + Mins;
//				}

//				$('xmpp_status').innerHTML='отправлено в '+Stamp.getHours()+':'+Mins;
				$('chat_input').focus();

				xmpp_reload();

			}
		});

}

function show_signin_form(){

	$('signin_form').show();
}


function proc_thmb_crop(picture_id){

	var _offset = $('thmb_box').positionedOffset();
	var x = _offset["left"];
	var y = _offset["top"];
	var w = $('thmb_box').getWidth();
	var h = $('thmb_box').getHeight();

//	var rounded = $('rounded').checked;

//	alert(x);
//	alert(y);
//	+'&rounded='+rounded
	document.location.href = '/post.php?module=media&action=proc_thmb_crop&x='+x+'&y='+y+'&w='+w+'&h='+h+'&id='+picture_id;
}


//======================================================
//				Перенесено из guide.tpl. Вынести в map.js
//======================================================

var map = null;
var categorys_geo_map = new Array();

	function init_big_map() {
		map = new YMaps.Map(document.getElementById("YMapsID"));
		//map.enableScrollZoom();
		map.setCenter(new YMaps.GeoPoint(30.31,59.93), 11);

		map.addControl(new YMaps.ToolBar());
		map.addControl(new YMaps.Zoom());


	}

function mark_tour_places(tour_id) {
	//map = new YMaps.Map(document.getElementById("YMapsID"));

		new Ajax.Request('/get.php?mode=map&type=mark_tour&tour_id='+tour_id,
		{
			onSuccess: function(transport){
			try {

					var data = eval('(' + transport.responseText + ')');
					var l = data.length;
					for (i = 0; i < l; i++)
					{
						mark_point(data[i]["geocode"],data[i]["object_id"],'places',data[i]["category_id"] );	//fast variant is fst
					}
				}
				catch(e){
					alert('Невозможно выполнить mark_tour_places. \nИбо:\n' + e);
				}
			}
		});
}


function SimpleOverlay (geoPoint, name, link, _cid, _type) {
	var map, _this = this, offset = new YMaps.Point(-10, -29);

	this.onAddToMap = function (pMap, parentContainer) {
		map = pMap;
		parentContainer.appendChild(getElement(_cid,_type));
		this.onMapUpdate();
	};

	this.onRemoveFromMap = function () {
		if (getElement().parentNode) {
			getElement().parentNode.removeChild(getElement());
		}
	};

	this.onMapUpdate = function () {
		var position = map.converter.coordinatesToMapPixels(geoPoint).moveBy(offset);
		getElement().style.left = position.x + 'px';
		getElement().style.top = position.y + 'px';
	};

	this.openBalloon = function () {
		link.className = "active";
		getElement().style.display = "none";

		if (name) {
			//при открытии баллона загружаем его содержимое вовнутрь из базы
			new Ajax.Request('/get.php?mode=map&type='+_type+'&object_id='+name,
			{
				onSuccess: function(transport){
					map.openBalloon(geoPoint, transport.responseText, {onClose: function () {
						link.className = getElement().style.display = "";
					}});
				}
			});
		}else{
			alert('no name detected');
		}
	}

	function getElement (_cid, _type) {
		var element = document.createElement('div');
		element.className = 'overlay_'+_type+'_'+_cid;

		element.onclick = function () {
			_this.openBalloon();
		}
		return (getElement = function () {return element})();
	}
}

function createOverlay (_res, _cid, content, _type) {

		var link = document.createElement('a');

		var newOverlay = new SimpleOverlay(_res.getGeoPoint(), content, link, _cid, _type);

		return newOverlay;
	}

function mark_point (geopoint_str, content, type, id) {
	try {
		//alert (geopoint_str);
			if (geopoint_str){



				var geoResult = new YMaps.GeocoderResult(new YMaps.GeoPoint.fromString(geopoint_str));

				var overlay = createOverlay(geoResult, id, content, type);


				if (id) {

					if (!categorys_geo_map[type]) {categorys_geo_map[type] = new Array();  }

					if (!categorys_geo_map[type][id]) { categorys_geo_map[type][id] = new Array();}
					categorys_geo_map[type][id].push(overlay);
				}

				//alert(dump(overlay));

				map.addOverlay(overlay);
			}

			//map.addOverlay(new YMaps.Placemark(YMaps.GeoPoint.fromString(geopoint_str)));
		}
		catch(e){
//				alert(id);
				alert('Невозможно выполнить mark_point. \nИбо:\n' + e);

		}
}


//кнопка "на большую карту"

 function GoBigMap () {
			this.element = document.createElement("DIV");
			this.element.style.position = 'absolute';
			this.element.style.zIndex = '100';
		}

		GoBigMap.prototype = {
			onAddToMap: function (map, position) {
				this.map = map;
				this.position = position || new YMaps.ControlPosition(YMaps.ControlPosition.TOP_RIGHT, new YMaps.Size(5, 5));
				this._init();
			},

			onRemoveFromMap: function () {
				if (this.element.parentNode) {
					this.map.getContainer().removeChild(this.element);
				}
				this.map = null;
			},

		   _init: function (map) {
				var zoomInDiv = document.createElement("div"),
					_this = this;

				this._setButtonStyle(zoomInDiv);
				this.element.appendChild(zoomInDiv);

				var img = document.createElement("img");
				$(img).setAttribute("src","/i/ico/arrow_out.png");

				zoomInDiv.appendChild(img);

			   // zoomInDiv.appendChild(document.createTextNode("<img src='/i/ico/arrow_out.png'>"));

				zoomInDiv.onclick  = function () {
					document.location = '/?page=places';
				};

				this.position.apply(this.element);
				this.map.getContainer().appendChild(this.element);
			},

			_setButtonStyle: function (button) {
				style = {textDecoration: 'underline',
						 color: '#0000cc',
						 backgroundColor: 'white',
						 font: 'small Arial',
						 border: '1px solid black',
						 padding: '2px',
						 marginBottom: '3px',
						 textAlign: 'center',
						 cursor: 'pointer'};
				for (var k in style) {
					button.style[k] = style[k];
				}
			}
		}


function check_hotel_booking() {

	if ($('name').value && $('surname').value) {

			try{

				var timestamp = new Date();
				var day = parseInt($('dtIn').value);
				var mon = parseInt($('mnIn').value);


				var order_timestamp = Date.UTC(timestamp.getFullYear(),mon-1,day);

				//alert(order_timestamp);

				var diff = order_timestamp-timestamp;


				if (diff < (3600*24*1000)){
					//alert (diff/(3600*24*1000));
					alert('Пожалуйста, укажите дату заезда не раньше послезавтрашнего дня.');
					return false;
				}
				else {
					$('hotel_booking_form').submit();
				}

			}
			catch(e){
					alert('Невозможно выполнить check_hotel_booking. \nИбо:\n' + e);

			}

		//$('hotel_booking_form').submit();
	} else {
		alert('Пожалуйста, заполните все поля');
		return false;
	}
}

function check_car_booking() {

	$('car_booking_form').submit();
}

function chk_car_aviable(price_day, price_total,car_id,from,to, h_from, h_to) {

	var unlimited = $('unlimited').checked;

	var url = '/?page=booking_car_confirm&price='+price_day+'&price_total='+price_total+'&car_id='+ car_id + '&from='+from+'&to='+to+'&h_from='+h_from+'&h_to='+h_to;

	if (unlimited){
		url = url+'&unlim=1'
	}

	//чтобы работало без проверки
	document.location = url;


	new Ajax.Request('/get.php?mode=booking_car&from='+from+'&to='+to+'&model='+car_id,
		{
			onSuccess: function(transport){
			try {
					if (transport.responseText == "404"){		//если 404
						document.location = url;
					}
					else
						alert(transport.responseText);

				}
				catch(e){
					alert('Невозможно выполнить check_car_aviability. \nПричина:\n' + e);
				}
			}
		});

}

