var hndlSearchResults = function(page, only, q)
{	
	if(!q) {
		var q	= $('searchInput').value;
	}
			
	var Container	= $('search_tab');
	var url			= '/map/search/content/?q=' + encodeURIComponent(q) + '&page=' + page;
	Container.update('Загрузка...');
	
	//window.location	= url;
	
	new Ajax.Request(url, {
		method		: 'GET',
		onSuccess	: function(req) {			
			Container.update(req.responseText);			
		}
	});

	Map.clear();
	
	Tabs.changeTab('search');
}

var TabController	= Class.create({
	
	EVENT_TYPES: [
	              'tabchange'
	],
	
	initialize : function()
	{	
		var me	= this;
		$A($('mapTabsNavigation').getElementsByTagName('a')).each(function(a){		
			$(a).observe('click', me.changeTab.bind(me, $(a.parentNode).identify().split('_')[0]));
		});
		
		this.events = new OpenLayers.Events(
			this, 
            $('mapTabsNavigation'), 
            this.EVENT_TYPES, 
            true, 
            {}
		);
	},
	
	changeTab : function(tab)
	{		
		$A($('mapTabsNavigation').getElementsByTagName('div')).each(function(div){		
			var div	= $(div);
			if(div.identify().include(tab)) {
				div.addClassName('active');
			}
			else {
				div.removeClassName('active');
			}		
		});

		$A($('mapTabsContainer').childNodes).each(function(li){		
			if(li.tagName && li.tagName.toLowerCase() == 'li') {
				var li	= $(li);
				if(li.identify().include(tab)) {
					li.removeClassName('hidden');			
				}
				else {
					li.addClassName('hidden');	
				}
			}		
		});
	}
});
/*
var hndlChangeTab	= function(tab)
{	
	$A($('mapTabsNavigation').getElementsByTagName('div')).each(function(div){		
		var div	= $(div);
		if(div.identify().include(tab)) {
			div.addClassName('active');
		}
		else {
			div.removeClassName('active');
		}		
	});

	$A($('mapTabsContainer').childNodes).each(function(li){		
		if(li.tagName && li.tagName.toLowerCase() == 'li') {
			var li	= $(li);
			if(li.identify().include(tab)) {
				li.removeClassName('hidden');			
			}
			else {
				li.addClassName('hidden');	
			}
		}		
	});
}
*/
var hndlToggleMapSize	= function()
{
	var Main		= $('main');
	var Img			= $('hideButton');
	var w			= 309; //col width
	Main.setStyle({width:Main.getWidth()}); //IE fix
	
	if(Main.maximized) {
		var newWidth	= Main.getWidth() - w + 'px';
		Img.src			= '/public/images/maximize.gif';
		Img.title		= 'Свернуть';
	}
	else {
		var newWidth	= Main.getWidth() + w + 'px';
		Img.src			= '/public/images/minimize.gif';
		Img.title		= 'Развернуть';
	}
	Main.maximized	= !Main.maximized;
	
	new Effect.Morph(Main, {
		style		: 'width:' + newWidth,
		duration	: 0.3
	});		
}

var hndlSetSize	= function()
{
	var h				= $(document.body).getHeight();
	var defaultHeight	= 255; //css value
		
	$('main').setStyle({height:(h - $('header').getHeight() + 'px')});
	$('catalogueMain').setStyle({height:getCatalogueHeight(true) + 'px'});
	$('search_tab').setStyle({height:getCatalogueHeight(false) + 'px'});
	$('marker_tab').setStyle({height:getCatalogueHeight(false) + 'px'});
	
	var catalogueList	= $('catalogueList');
	if(catalogueList.fullView) {
		catalogueList.setStyle({height:getCatalogueHeight() + 'px'});
	}
	else {
		catalogueList.setStyle({height:defaultHeight + 'px'});
	}
}

var hndlCatalogueToggle = function()
{	
	var catalogueList	= $('catalogueList');
	var defaultHeight	= 255; //css value
	
	if(catalogueList.fullView) {
		var over		= 'hidden';
		var newHeight	= defaultHeight;
		
		catalogueList.scrollTop	= 0;		
	}
	else {
		var over		= 'auto';
		var newHeight	= getCatalogueHeight(true);
	}
	
	catalogueList.setStyle({		
		'overflow'	: over
	});
	
	new Effect.Morph(catalogueList, {
		style		: 'height:' + newHeight + 'px;',
		duration	: 0.3
	});
	
	catalogueList.fullView	= !catalogueList.fullView;
}

var getCatalogueHeight	= function(withGrafica)
{
	var paddingTop		= 49; //tab navigation
	var graficaHeight	= 0;
	
	if(withGrafica) {
		graficaHeight	= 52; //height + padding		
	}
	
	
	return $('main').getHeight() - paddingTop - graficaHeight;
}

window.AA	= {};
AA.MarkerController	= Class.create({
	initialize : function(contaier, map, vector, marker)
	{
		this.container			= $(contaier);
		this.map				= map;
		this.vectorLayer		= vector;
		this.markerLayer		= marker;
		this.controls			= [];
		this.urlInputText		= $('textUrl');
		this.urlInputTextArea	= $('textareaUrl');
		this.MarkerMessage		= $('newMarkerMessage');

		this.permalink	= null;
		var me			= this;
		$A(this.map.controls).each(function(e){
			if(e.CLASS_NAME == 'OpenLayers.Control.AAPermalink') {					
				me.permalink	= e;
			}			
		});

		var me	= this;

		this.urlInputText.observe('click', this.urlInputText.activate.bind());
		
		if(this.urlInputTextArea) {
			this.urlInputTextArea.observe('click', this.urlInputTextArea.activate.bind());
		}		

		this.MarkerMessage.observe('keyup', this._setUrls.bind(this));
	},

	addControl : function(type, control)
	{
		var options	= {
			'map'				: this.map,
			buttonContainer		: 'buttonContainer',
			controlsContainer	: 'controlsContainer'
		};

		if(type == 'marker') {
		}
		else {
			options.layer	= this.vectorLayer;
		}

		control.setOptions(options);
		control.events.on({            
	        'activate'		: this._deactivateAllControls.bind(this),
	        'statechange'	: this._setUrls.bind(this)					
		});
		
		this.controls.push(control);
	},

	run : function()
	{
		var first	= null;
		$A(this.controls).each(function(e){
			e.build();

			if(!first) {
				first	= e;
			}
		});

		first.activate();
	},

	_deactivateAllControls : function()
	{
		$A(this.controls).each(function(e){
			e.deactivate();
		});
	},

	_setUrls : function()
	{
		var me	= this;
		$A(this.controls).each(function(control){
			if(control.isActive()) {					
				var link	= OpenLayers.Util.getParameterString(me.permalink.createParams(null, null, null, true));
				if(control.MapControl && control.MapControl.layer.features[0]) {
					link	+= '&feature=' + control.MapControl.layer.features[0].geometry.toString();
				}

				$H(control.drawControlOptions).each(function(e){
					link	+= '&' + e.key + '=' + e.value;
				});					
				link	+= '&message=' + encodeURI(me.MarkerMessage.value);
				
				var iframeLink	= 'http://autoatlas.kz/marker/view/?' + link;
				var siteLink	= 'http://autoatlas.kz/?' + link;

				me.urlInputText.value		= siteLink;
				if(me.urlInputTextArea) {
					me.urlInputTextArea.value	= iframeLink;
				}
				
			}
		});			
	}
});

AA.MarkerController.TypePolygon	= Class.create(
{		
	buttonLabel		: 'Полигон',

	handler			: OpenLayers.Handler.Polygon,

	STATES			: ['active', 'deactive', 'draw'],

	BUTTON_CLASSES	: {
		'active'	: 'active',
		'draw'		: 'draw'
	},

	EVENT_TYPES: ['activate', 'deactivate', 'statechange'],

	controlOptions: [
		{'color':'#ff0000','transparent':0,'value':'ff0000'},
		{'color':'#0000ff','transparent':0,'value':'0000ff'},
		{'color':'#00ff00','transparent':0,'value':'00ff00'},
		{'color':'#ff0000','transparent':1,'value':'transparent'}
	],
	
	initialize : function()
	{			
		this.options	= {
			'map'				: null,
			'layer'				: null,
			'buttonContainer'	: null,
			'controlsContainer'	: null
		};

		this.state				= 'deactive';
		this.events 			= new OpenLayers.Events(this, null, this.EVENT_TYPES);
		this.drawControlOptions	= {};
	},

	setOptions : function(options)
	{
		Object.extend(this.options, options || {});			
	},

	build : function()
	{
		this.Map				= this.options.map;
		this.Layer				= this.options.layer;
		this.ButtonContainer	= $(this.options.buttonContainer);
		this.ControlsContainer	= $(this.options.controlsContainer);
		
		this._addButton();			
	},

	activate : function()
	{
		this.events.triggerEvent('activate');
		
		var me			= this;			
		this.MapControl	= new OpenLayers.Control.DrawFeature(this.Layer, this.handler);
		this.Map.addControl(this.MapControl);

		this.MapControl.events.on({            
	        'featureadded': this.stopDraw.bind(this)					
		});			

		this._addDrawControls();
		this._setState('active');
	},

	deactivate : function()
	{
		this.events.triggerEvent('deactivate');
		
		this.Map.removeControl(this.MapControl);
		this.MapControl	= null;

		this._removeDrawControls();
		this._setState('deactive');
	},

	isActive : function()
	{
		if(this.state == 'active' || this.state == 'draw') {
			return true;
		}
		else {
			return false;
		}
	},

	startDraw : function()
	{
		this.MapControl.layer.removeFeatures(this.MapControl.layer.features);
		this.MapControl.activate();
		this._setState('draw');				
	},

	stopDraw : function()
	{
		this.MapControl.deactivate();
		this._setState('active');	
	},

	getDrawOptions : function()
	{
		
	},
	
	_addButton : function()
	{
		this.Button	= new Element('span', {'class':'markerTypeButton'});
		this.Button.insert(this.buttonLabel);

		this.ButtonContainer.insert(this.Button);
		this.Button.observe('click', this._buttonClick.bind(this));
	},

	_addDrawControls : function()
	{
		
	},

	_removeDrawControls : function()
	{
	},

	_buttonClick : function()
	{
		switch(this.state) {
			case this.STATES[0]	:
					this.startDraw();
				break;
			case this.STATES[1]	:					
					this.activate();
					this.startDraw();
				break;
			case this.STATES[2]	:
					return;
				break;
		}
	},

	_setState : function(state)
	{
		this.state	= state;
		switch(this.state) {
			case this.STATES[0]	:
				this.Button.addClassName(this.BUTTON_CLASSES['active']);
				this.Button.removeClassName(this.BUTTON_CLASSES['draw']);
				break;
			case this.STATES[1]	:					
				this.Button.removeClassName(this.BUTTON_CLASSES['active']);
				this.Button.removeClassName(this.BUTTON_CLASSES['draw']);
				break;
			case this.STATES[2]	:
				this.Button.removeClassName(this.BUTTON_CLASSES['active']);
				this.Button.addClassName(this.BUTTON_CLASSES['draw']);
				break;
		}
		
		this.events.triggerEvent('statechange');			
	},

	_addDrawControls : function()
	{
		var opt	= [];
		$A(this.controlOptions).each(function(e){
			if(e.transparent) {
				var style	= 'width:20px;height:10px;border:1px solid ' + e.color + ';';
			}
			else {
				var style	= 'width:20px;height:10px;border:1px solid ' + e.color + ';background-color:' + e.color + ';';
			}			
			
			var Div	= new Element('div', {'style':style});
			opt.push({'element':Div,'value':e.value});
		});
	
		this._addRadio(opt, 'featureColor');
	},

	_addRadio : function(opt, name)
	{
		var me			= this;			
		var checkRadio	= function(value)			
		{
			me.drawControlOptions[name]	= value;			
			me.events.triggerEvent('statechange');
		}

		var radio	= null;
		$A(opt).each(function(e){
			var Label	= new Element('label');
			me.ControlsContainer.insert(Label);

			var Input	= new Element('input', {
				'type'	: 'radio',
				'value'	: e.value,
				'name'	: 'pointType'
			});
			Input.observe('click', function(){
				checkRadio(this.value);					
			});
			Label.insert(Input);
			if(!radio) {
				radio	= Input;
			}						
			Label.insert(e.element);
		});

		radio.checked = true;
		checkRadio(radio.value);
	},

	_removeDrawControls : function()
	{
		this.ControlsContainer.update('');
		this.drawControlOptions	= {};
	}

});

AA.MarkerController.TypeLine	= Class.create(AA.MarkerController.TypePolygon,
{
	buttonLabel		: 'Линия',

	handler			: OpenLayers.Handler.Path,

	controlOptions: [
			{'color':'#ff0000','transparent':0,'value':'ff0000'},
			{'color':'#0000ff','transparent':0,'value':'0000ff'},
			{'color':'#00ff00','transparent':0,'value':'00ff00'},
			{'color':'#ffb400','transparent':0,'value':'ffb400'}
		]
});

AA.MarkerController.TypePoint	= Class.create(AA.MarkerController.TypePolygon,
{
	buttonLabel			: 'Точка',

	handler				: OpenLayers.Handler.Point,
	
	pointTypes			: [
		'http://autoatlas.kz/public/images/pointer.png',
		'http://autoatlas.kz/public/images/marker/1-restaurant-black.png',
		'http://autoatlas.kz/public/images/marker/19-car-repair-black.png',
		'http://autoatlas.kz/public/images/marker/6-place-to-black.png',
		'http://autoatlas.kz/public/images/marker/24-government-black.png',
		'http://autoatlas.kz/public/images/marker/73-services-black.png',
		'http://autoatlas.kz/public/images/marker/77-torgovlya-black.png',
		'http://autoatlas.kz/public/images/marker/72-question-black.png',
		'http://autoatlas.kz/public/images/marker/47-repair-pit-black.png',
		'http://autoatlas.kz/public/images/marker/78-!-black.png'
	],

	_addDrawControls : function()
	{	
		var opt	= [];
		$A(this.pointTypes).each(function(e){
			var Img	= new Element('img', {'src' : e});
			var Div	= new Element('div');
			Div.insert(Img);
			opt.push({'element':Div,'value':e});
		});
	
		this._addRadio(opt, 'pointType');
	},
	
	addPointType : function(type, top)
	{
		if(top) {
			var newTypes	= [type];
			$A(this.pointTypes).each(function(e){
				newTypes.push(e);
			});
			this.pointTypes	= newTypes;
		}
		else {
			this.pointTypes.push(type);
		}
	}
});
