/*******************************
*   NPOINTS functions
********************************/

function NPoints(map, params){
	var me = this;
	this.map = null;
	this.modified = true;
	this.list_id = null;
	this.settings = {
		print: false,
		max_points: 30
	};
	this.mgrsettings = {
		trackMarkers: true
	};
	this.points = new Array();
	this._event_click = null;
	this.default_point = {
		title: 'Название точки...',
		text: 'Описание точки...'
	};

	this.constructor = function(map, params){
		if(typeof(map) == 'undefined'){
			alert('bad Npoints map!');
			return false;
		}
		if(typeof(params) == 'object'){
			if(typeof(params.print) != 'undefined' ){
				this.settings.print = params.print; 
			}
			if(typeof(params.max_points) != 'undefined' ){
				this.settings.max_points = params.max_points; 
			}
		}
		this.map = map;
		if(this.settings.print !== true){
			this.refreshControls();
			this.registerEvents();
		}

		this.baseIcon = new GIcon();
		this.baseIcon.shadow = "/_img/modules/map_google/shadow50.png";
		this.baseIcon.image = "/_img/modules/map_google/marker.png";
		this.baseIcon.iconSize = new GSize(20, 34);
		this.baseIcon.shadowSize = new GSize(37, 34);
		this.baseIcon.iconAnchor = new GPoint(9, 34);
		this.baseIcon.infoWindowAnchor = new GPoint(9, 2);
		this.baseIcon.infoShadowAnchor = new GPoint(18, 25);
	};
	
	this.refreshControls = function(){
		if( this._event_click == null ){
			$('#pcmd_start_putting').show();
			$('#pcmd_stop_putting').hide();
		}else{
			$('#pcmd_start_putting').hide();
			$('#pcmd_stop_putting').show();
		}
		if( this.points.length>0 && this.modified ){
			$('#pcmd_save').show();
		}else{
			$('#pcmd_save').hide();
		}
		if(this.points.length>0){
			$('#pcmd_show_all').show();
		}
		this.map.closeInfoWindow();
	};
	
	this.registerEvents = function(){
		$('#pcmd_show_all').bind('click', {obj: this}, function(e){return e.data.obj.btnShowAllClick(e);});
		$('#pcmd_start_putting').bind('click', {obj: this}, function(e){return e.data.obj.btnStartPuttingClick(e);});
		$('#pcmd_stop_putting').bind('click', {obj: this}, function(e){return e.data.obj.btnEndPuttingClick(e);});
		$('#pcmd_save').bind('click', {obj: this}, function(e){return e.data.obj.btnSaveClick(e);});
	};
	
	this.btnShowAllClick = function(e){
		var bnd = new GLatLngBounds();
		for(i = 0; i<this.points.length; i++){
			bnd.extend(this.points[i].marker.getLatLng());
		}
		this.map.getBoundsZoomLevel(bnd);
		this.map.setCenter(bnd.getCenter(), this.map.getBoundsZoomLevel(bnd));
	};

	this.btnStartPuttingClick = function(e){
		this.startPutting();
	};

	this.btnEndPuttingClick = function(e){
		this.endPutting();
	};

	this.btnSaveClick = function(){
		if(this.modified){
			this.savePoints();
			this.refreshControls();
		}
	};

	this.savePoints = function(){
		var params = 'action=points_save&' + this.getSerializedData();
		$.ajax({
			type: "POST",
			url: '?',
			data: params,
			dataType: "json",
			success: this.savePoints_callback
		});
	};

	this.savePoints_callback = function(response){
		if( typeof(response.res) == 'object' && response.res.error == 0 && response.res.id != '' ){
			me.list_id = response.res.id;
			me.endPutting();
			me.modified = false;
			//me.refreshList();
			me.refreshControls();
		}else{
			alert('При сохранении возникла ошибка. Попробуйте сохранить позже.');
		}
	};

	this.loadPoints = function(code){
		var params = 'action=points_load&id=' + code;
		$.ajax({
			type: "POST",
			url: '?',
			data: params,
			dataType: "json",
			success: this.loadPoints_callback
		});
	};

	this.loadPoints_callback = function(response){
		if( typeof(response.res) == 'object' && response.res.error == 0 && response.res.id != '' ){
			me.list_id = response.res.id;
			for(i = 0; i<me.points.length; i++){
				me.points[i].remove();
			}
			for(i=0; i<response.res.points.length; i++){
				var settings = {
					title: response.res.points[i].title,
					text: response.res.points[i].text
				}; 
				me.createPoint(new GLatLng(response.res.points[i].x, response.res.points[i].y), settings);
			}
			me.modified = false;
			if(me.settings.print !== true){
				me.refreshList();
				me.refreshControls();
			}else{
				me.print_refreshList();
			}
		}else{
			alert('При загрузке точек возникла ошибка. Попробуйте позже.');
		}
	};

	this.startPutting = function(){
		this.endPutting();
		this._event_click = GEvent.bind(this.map, 'click', this, this.clickOnMap);
		this.refreshControls();
	};
	
	this.endPutting = function(){
		if(typeof(this._event_click) != 'undefined' && this._event_click != null){
			GEvent.removeListener(this._event_click);
			this._event_click = null;
		}
		this.refreshControls();
	};
	
	this.clickOnMap = function(overley, latlng){
		if(overley == null){
			if(this.settings.max_points<=this.points.length){
				alert('Вы можете отметить на карте только '+this.settings.max_points+' точек.');
				return false;
			}
			this.modified = true;
			this.createPoint(latlng);
			this.refreshList();
			this.refreshControls();
			this.points[this.points.length-1].click();
		}
	};

	this.createPoint = function(point){
		var settings = {};
		if(typeof(arguments[1]) == 'object'){ settings = arguments[1];}
		this.points[this.points.length] = new NPoint(point, {
			index: this.points.length,
			title: (typeof(settings.title)!='undefined'?settings.title:this.default_point.title),
			text: (typeof(settings.text)!='undefined'?settings.text:this.default_point.text)
		}, this);
	};
	
	this.deletePoint = function(i){
		if(i<this.points.length){
			this.points.splice(i, 1);
			this.modified = true;
			for(i = 0; i<this.points.length; i++){
				this.points[i].index = i;
				this.points[i].createMarker();
			}
			if(this.settings.print !== true){
				this.refreshList();
				this.refreshControls();
			}
		}
	};
	
	this.clickPoint = function(i){
		if(i<this.points.length){
			this.points[i].click();
		}
	};
	
	this.refreshList = function(){
		$('#points_list').html('');
		for(i = 0; i<this.points.length; i++){
			var temp = '<li id="pl_item_'+i+'" class="plitem">'
			+ '<span class="title">' + this.points[i].title.escape_quotes().escape_tags() + '</span><br />'
			+ '<span class="delete">удалить</span>'
			+ '</li>';
			$('#points_list').append(temp);
			$('#pl_item_'+i+' .title').bind('click', {obj: this, i: i}, function(e){return e.data.obj.clickPoint(e.data.i);});
			$('#pl_item_'+i+' .delete').bind('click', {obj: this, i: i}, function(e){return e.data.obj.points[e.data.i].remove();});
		}
	};
	
	this.refreshPoint = function(i){
		if(i<this.points.length){
			$('#pl_item_'+i+' .title').html(this.points[i].title.escape_quotes().escape_tags());
		}
	};
	
	this.getLetteredIcon = function(letter){
		var letteredIcon = new GIcon(this.baseIcon);
		letteredIcon.image = "/_img/modules/map_google/marker"+letter+".png";
		return letteredIcon;
	};

	this.print_refreshList = function(){
		if(this.points.length==0){
			$('#print_points_area').hide();
			return false;
		}
		$('#print_points_list').html('');
		for(i = 0; i<this.points.length; i++){
			var temp = '<li class="plitem">'
			+ '<span class="title">' + this.points[i].title.escape_quotes().escape_tags() + '</span><br />'
			+ '<span class="text">' + this.points[i].text.escape_quotes().escape_tags() + '</span><br />'
			+ '</li>';
			$('#print_points_list').append(temp);
		}
		$('#print_points_area').show();
	};
	
	/**
	 * Return serializedData
	 * @return string
	 */
	this.getSerializedData = function(){
		var str = '';
		var temp = '';
		for(i = 0; i<this.points.length; i++){
			temp = '' + this.points[i].title;
			str += '&title['+i+']=' + temp.escape_amp();
			temp = '' + this.points[i].text;
			str += '&text['+i+']=' + temp.escape_amp();
			temp = '' + this.points[i].point.lat();
			str += '&lat['+i+']=' + temp.escape_amp();
			temp = '' + this.points[i].point.lng();
			str += '&lng['+i+']=' + temp.escape_amp();
		}
		return str;
	};
	
	/**
	 * Return points list identificator
	 * @return string
	 */
	this.getId = function(){
		if(this.list_id != '' ){
			return this.list_id;
		}else{
			return '';
		}
	};
	
	this.constructor(map, params);
}// end of NPoints



function NPoint(point, params, mgr){	
	this.mgr = null;
	this.point = null;
	this.index = '';
	this.title = '';
	this.text = '';
	this.marker = null;
	this._event_dragend = null;
	this._event_click = null;
	this._event_save = null;
	this._event_delete = null;
	this.btnSave = null;
	this.btnDelete = null;

	this.constructor = function(point, params, mgr){
		this.point = point;
		if(typeof(mgr) != 'undefined'){
			this.mgr = mgr;
		}
		if(typeof(params) == 'object'){
			if(typeof(params.index) != 'undefined'){
				this.index = params.index;
			}
			if(typeof(params.title) != 'undefined'){
				this.title = params.title;
			}
			if(typeof(params.text) != 'undefined'){
				this.text = params.text;
			}
		}
		this.createMarker();
	}
	
	this.createMarker = function(){
		if(this.marker != null){
			this.mgr.map.removeOverlay(this.marker);
		}
		this.marker = new GMarker(this.point, {title: this.title, draggable:(this.mgr.settings.print==true?false:true), icon:this.mgr.getLetteredIcon(this.index+1)});
		if(this.mgr.settings.print !== true){
			this.regEventClick();
		}
		this.mgr.map.addOverlay(this.marker);
	};
	
	this.regEventClick = function(){
		this.unregEventClick();
		this._event_click = GEvent.bind(this.marker, 'click', this, this.click);
		this._event_dragend = GEvent.bind(this.marker, 'dragend', this, this.dragend);
	};
	
	this.unregEventClick = function(){
		if(typeof(this._event_click) != 'undefined' && this._event_click != null){
			GEvent.removeListener(this._event_click);
		}
		if(typeof(this._event_dragend) != 'undefined' && this._event_dragend != null){
			GEvent.removeListener(this._event_dragend);
		}
		$('#mkr_save_'+this.index).unbind('click');
		$('#mkr_delete_'+this.index).unbind('click');
	};
	
	this.dragend = function(){
		this.marker.closeInfoWindow();
		this.point = this.marker.getLatLng();
		this.mgr.modified = true;
		this.mgr.refreshControls();
	};
	
	this.click = function(){
		if(this.mgr != null && this.mgr.modified){
			this.showEdit();
		}else{
			this.showView();
		}
	};
	
	this.showEdit = function(){
		$('#mkr_save_'+this.index).unbind('click');
		$('#mkr_delete_'+this.index).unbind('click');
		var html = '<div class="pinfo_edit">'
		+ '<div class="caption">Введите название точки и ее описание...</div>'
		+ '<input type="text" class="title" id="mkr_title_'+this.index+'" value="'+this.title.escape_quotes()+'" />'
		+ '<textarea class="text" id="mkr_text_'+this.index+'">'+this.text.escape_tags()+'</textarea>'
		+ '<div class="controls">'
		+ '<input type="button" id="mkr_save_'+this.index+'" class="save" value="Сохранить" />'
		+ '<input type="button" id="mkr_delete_'+this.index+'" class="delete" value="Удалить" />'
		+ '</div>';
		+ '</div>';
		this.marker.openInfoWindowHtml(html);
		$('#mkr_save_'+this.index).bind('click', {obj: this}, function(e){e.data.obj.savePoint();});
		$('#mkr_delete_'+this.index).bind('click', {obj: this}, function(e){e.data.obj.deletePoint();});
	};
	
	this.showView = function(){
		var html = '<div class="pinfo_view">'
		+ '<div class="title">'+this.title.escape_tags()+'</div>'
		+ '<div class="text">'+this.text.escape_tags()+'</div>'
		+ '<div class="controls">'
		+ '<span id="mkr_edit_'+this.index+'" class="edit">изменить</span>'
		+ '&nbsp;&nbsp;'
		+ '<span id="mkr_delete_'+this.index+'" class="delete">удалить</span>'
		+ '</div>';
		+ '</div>';
		this.marker.openInfoWindowHtml(html);
		$('#mkr_edit_'+this.index).bind('click', {obj: this}, function(e){e.data.obj.mgr.modified = true; e.data.obj.marker.closeInfoWindow(); e.data.obj.mgr.refreshControls(); e.data.obj.click();});
		$('#mkr_delete_'+this.index).bind('click', {obj: this}, function(e){e.data.obj.mgr.modified = true; e.data.obj.marker.closeInfoWindow(); e.data.obj.remove();});
	};
	
	this.savePoint = function(){
		if( this.mgr == null || !this.mgr.modified ){
			return false;
		}
		
		var title = $('#mkr_title_'+this.index).get(0).value;
		var text = $('#mkr_text_'+this.index).get(0).value;
		if(title == '' || title == this.mgr.default_point.title){
			alert('Введите название точки.');
			return false;
		}
		this.title = title;
		this.text = text;
		this.marker.closeInfoWindow();
		this.mgr.refreshPoint(this.index);
		this.mgr.modified = true;
		this.createMarker();
		return true;		
	};
	
	this.deletePoint = function(){
		if( this.mgr == null || !this.mgr.modified ){
			return false;
		}
		
		this.mgr.modified = true;
		this.remove();
	};
	
	this.remove = function(){
		this.unregEventClick();
		this.mgr.map.removeOverlay(this.marker);
		this.mgr.deletePoint(this.index);
	};
	
	this.constructor(point, params, mgr);
}
