/**
 * @author Jan Cinert <jan.cinert@gmail.com>
 * @require mootools.js, SimpleTabs.js
 */

var SearchForm = new Class({

	Implements: [Events, Options],
	
	options: {
	  propertyClassName: 'main_class',
	  brokerClassName: 'broker_main_class',
	  transactionName: 'transaction',
	  regionName: 'region',
	  cityName: 'city',
	  priceName: 'price',
	  subclassName: 'class',
	  areaName: 'total_area',
	  ownershipName: 'free_item_vlastnictvi',
	  constructionName: 'free_item_konstrukce',
	  parcelTypeName: 'class',
	  buildingTypeName: 'class',
	  noLimit:   'Bez limitu',
	  imagePath: '',
	  tabPrefix: ''
	  
	},

	initialize: function(element, options){
		this.setOptions(options);
		this.element = $(element);
		this.tabs = [];
		this.footer = [];
		this.propertyClasses = [];
		this.transactionTypes = [];
		this.ownershipTypes = [];
		this.constructionTypes = [];
		this.parcelTypes = [];
		this.buildingTypes = [];
		this.subClasses = [];
		this.regions = [];
		this.cities = [];
		this.sliders = [];
		this.regionSelect = [];
		this.sliderInputs = {};
		this.tabsRenderOptions = {};
		this.trans = {};
	},
	
	setPropertyClasses: function( classes ) {
	  this.propertyClasses = classes;
	},
	
	setTransactionTypes: function( items ) {
	  this.transactionTypes = items;
	},
	
	setOwnershipTypes: function( items ) {
	  this.ownershipTypes = items;
	},
	
	setConstructionTypes: function( items ) {
	  this.constructionTypes = items;
	},
	
	setParcelTypes: function( items ) {
	  this.parcelTypes = items;
	},
	
	setBuildingTypes: function( items ) {
	  this.buildingTypes = items;
	},
	
	setSubClasses: function( items ) {
	  this.subClasses = items;
	},
	
	setRegions: function( items ) {
	  this.regions = items;
	},
	
	setCities: function( items ) {
	  this.cities = items;
	},
	
	setTrans: function( trans ) {
	  this.trans = trans;
	  this.options.noLimit = this.translate( 'Bez limitu' );
	},
	
	translate: function( Value ) {
	  return $defined( this.trans[Value] ) ? this.trans[Value] : Value;
	},
	
	loadHPScheme: function() {
	  this.addTab( 'Nemovitosti' );
	  var group = this.addGroup( { title: this.translate( 'výběr typu nemovitosti' ) } );
	  this.addItem( { type: 'propertyClasses' }, group );
	  group = this.addGroup( { title: this.translate( 'výběr kraje' ) } );
	  this.addItem( { type: 'regions', labels: { submit: 'Odeslat', submitClass: 'nemovitosti' } }, group );
	  
	  this.addTab( 'Developerské projekty' );
	  group = this.addGroup( { title: this.translate( 'výběr kraje' ) } );
	  this.addItem( { type: 'regions', labels: { submit: 'Odeslat', submitClass: 'projekty' } }, group );
	  
	  this.addTab( 'Kanceláře' );
	  group = this.addGroup( { title: this.translate( 'výběr kraje' ) } );
	  this.addItem( { type: 'regions', labels: { submit: 'Odeslat', submitClass: 'kancelare' } }, group );
	  
	  this.addTab( 'Makléři' );
	  group = this.addGroup( { title: this.translate( 'výběr kraje' ) } );
	  this.addItem( { type: 'regions', name: 'broker_region', labels: { submit: 'Odeslat', submitClass: 'makleri' } }, group );
	  
	  this.tabsRenderOptions.show = 0;
	},
	
	loadDefaultScheme: function() {
	  
	  	    
	  this.addTab( 'Dev. projekty' );
	  group = this.addGroup( { title: this.translate( 'výběr kraje' ) } );
	  this.addItem( { type: 'region' }, group );
	  group = this.addGroup( { title: this.translate( 'výběr města' ) } );
	  this.addItem( { type: 'cities' }, group );
	  group = this.addGroup();
	  this.addItem( { type: 'inputs', items: [ { label: this.translate( 'Obsahuje text: (např. ulici)' ), name: 'fulltext' } ] }, group );
	  group = this.addGroup( { addition: '-footer' } );
	  this.addItem( { type: 'submit', 'label' : 'Odeslat', addition : '-projekty'}, group );
	  
	
	  this.addTab( 'Nemovitosti' );
	  var group = this.addGroup( { title: this.translate( 'výběr typu nemovitosti' ) } );
	  this.addItem( { type: 'propertyClasses' }, group );
	  group = this.addGroup( { title: this.translate( 'výběr kraje' ) } );
	  this.addItem( { type: 'region' }, group );
	  group = this.addGroup( { title: this.translate( 'výběr města' ) } );
	  this.addItem( { type: 'cities' }, group );
	  group = this.addGroup( { title: this.translate( 'typ transakce' ), propertyClasses: [1, 2, 3, 4, 5, 6, 7, 9] } );
	  this.addItem( { type: 'transactionTypes' }, group );
	  group = this.addGroup( { title: this.translate( 'cena a velikost' ), propertyClasses: [1, 2, 3, 4, 5, 6, 7, 9] } );
	  
	  this.addItem( { 
	    type: 'price', 
	    steps: [ [1000, 1000], [2000, 2000], [3000, 3000], [5000, 5000], [7500, 7500], [10000, 10000], [15000, 15000], [20000, 20000], [30000, 30000], [100000, 100000], [300000, 300000], [500000, 500000], [1000000, 1000000], [1500000, 1500000], [2000000, 2000000], [3000000, 3000000], [5000000, 5000000], [10000000, 10000000] ], 
	    label: this.translate( 'Cena:' ), 
	    labelFormat: '{min} - {max}', 
	    valueFormat: this.translate( '{value} Kč' ) }, 
	    group );
	  var steps = [];
	  this.subClasses[1].each( function( item ) {
	    steps.push( [ item.value, item.label ] );
	  });
	  this.addItem( { 
	    type: 'subclass', 
	    steps: steps, 
	    label: this.translate( 'Dispozice:' ), 
	    labelFormat: '{min} - {max}', 
	    valueFormat: '{value}', 
	    propertyClasses: [1] }, 
	    group );
	  this.addItem( { 
	    type: 'area', 
	    steps: [ [30, 30], [40, 40], [50, 50], [60, 60], [70, 70], [80, 80], [100, 100], [120, 120], [150, 150], [200, 200], [300, 300], [500, 500] ], 
	    label: this.translate( 'Velikost:' ), 
	    labelFormat: '{min} - {max}', 
	    valueFormat: '{value} m2', 
	    propertyClasses: [1, 2, 3] }, 
	    group );
	  this.addItem( { 
	    type: 'area', 
	    steps: [ [100, 100], [250, 250], [500, 500], [750, 750], [1000, 1000], [1250, 1250], [1500, 1500], [2000, 2000], [3000, 3000], [5000, 5000], [8000, 8000], [10000, 10000], [30000, 30000], [50000, 50000] ], 
	    label: this.translate( 'Výměra:' ), 
	    labelFormat: '{min} - {max}', 
	    valueFormat: '{value} m2', 
	    propertyClasses: [6] }, 
	    group );
	  this.addItem( { 
	    type: 'area', 
	    steps: [ [100, 100], [200, 200], [300, 300], [500, 500], [750, 750], [1000, 1000], [1250, 1250],[1500, 1500], [2000, 2000], [3000, 3000], [5000, 5000], [8000, 8000], [10000, 10000] ], 
	    label: this.translate( 'Velikost:' ), 
	    labelFormat: '{min} - {max}', 
	    valueFormat: '{value} m2', 
	    propertyClasses: [5] }, 
	    group );
	  this.addItem( { 
	    type: 'area', 
	    steps: [ [100, 100], [500, 500], [1000, 1000] ], 
	    label: this.translate( 'Velikost:' ), 
	    labelFormat: '{min} - {max}', 
	    valueFormat: '{value} m2', 
	    propertyClasses: [7] }, 
	    group );
	  group = this.addGroup( { title: this.translate( 'vlastnictví' ), propertyClasses: [1] } );  
	  this.addItem( { type: 'ownershipTypes' }, group );
	  group = this.addGroup( { title: this.translate( 'konstrukce' ), propertyClasses: [1] } );  
	  this.addItem( { type: 'constructionTypes' }, group );
	  
	  group = this.addGroup( { title: this.translate( 'druh parcely' ), propertyClasses: [6] } );  
	  this.addItem( { type: 'parcelTypes' }, group );
	  group = this.addGroup( { title: this.translate( 'typ prostor/budovy' ), propertyClasses: [5] } );  
	  this.addItem( { type: 'buildingTypes' }, group );
	  
	  group = this.addGroup();
	  this.addItem( { type: 'inputs', items: [ { label: this.translate( 'Obsahuje text: (např. ulici)' ), name: 'fulltext' } ] }, group );
	  //this.addItem( { type: 'exact_price', labels: { title: 'Přesná cena:', from: 'od', to: 'do' } }, group );
      group = this.addGroup( { addition: '-footer' } );
	  this.addItem( { type: 'submit', 'label' : 'Odeslat', addition : '-nemovitosti'}, group );
	  
	  this.addTab( 'Kanceláře' );
	  group = this.addGroup( { title: this.translate( 'výběr kraje:' ) } );
	  this.addItem( { type: 'region' }, group );
	  group = this.addGroup( { title: this.translate( 'výběr města:' ) } );
	  this.addItem( { type: 'cities' }, group );
	  group = this.addGroup( { title: '' } );
	  this.addItem( { type: 'inputs', items: [ { label: this.translate( 'Obsahuje text: (např. ulici)' ), name: 'fulltext' } ] }, group );
      group = this.addGroup( { addition: '-footer' } );
	  this.addItem( { type: 'submit', 'label' : 'Odeslat', addition : '-kancelare'}, group );
	  
	  this.addTab( 'Makléři' );
	  group = this.addGroup( { title: this.translate( 'hledat dle typu transakce:' ) } );
	  this.addItem( { type: 'transactionTypes', name: 'broker_transaction' }, group );
	  var group = this.addGroup( { title: this.translate( 'zaměření:' ) } );
	  this.addItem( { type: 'propertyClasses', name: this.options.brokerClassName, renderType: 'checkbox' }, group );
	  group = this.addGroup( { title: this.translate( 'lokality:' ) } );
	  this.addItem( { type: 'region', name: 'broker_region' }, group );
	  group = this.addGroup( { title: this.translate( 'výběr města:' ) } );
	  this.addItem( { type: 'cities' }, group );
	  group = this.addGroup( { title: this.translate( 'vyhledat konkrétního makléře:' ) } );
	  this.addItem( { type: 'inputs', items: [ { label: this.translate( 'Příjmení:' ), name: 'fulltext' } ] }, group );
	  group = this.addGroup( { addition: '-footer' } );
	  this.addItem( { type: 'submit', 'label' : 'Odeslat', addition : '-makleri'}, group );

	// this.footer.push( { type: 'submit', 'label' : 'Odeslat'} );
	  
	  this.tabsRenderOptions.show = 1;
	},
	
	addTab: function( text, title ) {
	  text = this.translate( text );
	  this.tabs.push( { text: text, title: text, groups: [] } );
	  return this.tabs.getLast();
	},
	
	addGroup: function( group, tab ) {
	  if( !$defined( tab ) ) tab = this.tabs.getLast();

	  tab.groups.push( $merge( { title: '', items: [], propertyTypes: null }, group ) );
	  return tab.groups.getLast();
	},
	
	addItem: function( item, group ) {
	  group.items.push( $merge( { title: '' }, item ) );
	},
	
	getTab: function( index ) {
	  return this.tabs[index];
	},
	
	getValues: function() {
	  var result = {};
	  this.element.getElements('input, textarea, select').each( function( el ) {
	    if( !this._isElementVisible( el ) ) {
	      return;
	    }
	    if (!el.name || el.disabled) return;
	    var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
				return opt.value;
			}) : (['radio', 'checkbox'].contains( el.type ) && !el.checked) ? null : el.value;
			$splat(value).each(function(val){
				if (typeof val != 'undefined') {
				  if( $defined( result[el.name] ) ) {
    			  if( $type( result[el.name] ) == 'array' ) {
    			    result[el.name].push( val );
    			  }
    			  else {
    			    result[el.name] = [result[el.name], val];
    			  }
    			}
    			else {
    			  result[el.name] = val;
    			}
				}
			});

			
	  }, this);
	  //console.log(result);
	  return result
	},
	
	getValuesAsArray: function() {
	  var result = [];
	  this.element.getElements('input, textarea, select').each( function( el ) {
	    if( ( el.get( 'type' ) == 'hidden' && !el.value ) || ( el.get( 'type' ) != 'hidden' && !this._isElementVisible( el ) ) ) {
	      return;
	    }

	    if (!el.name || el.disabled) return;
	    var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
				return opt.value;
			}) : (['radio', 'checkbox'].contains( el.type ) && !el.checked) ? null : el.value;
			$splat(value).each(function(val){
				if (typeof val != 'undefined') {
				  result.push( [ el.name, val ] );
				}
			
		  });
	  }, this);

	  return result;
	},
	
	toQueryString: function( data ) {
	  var queryString = [];
		data.each( function(value){
		  var result;
		  result = value[0] + '=' + encodeURIComponent(value[1]);
		  if (value[1] != undefined) queryString.push(result);
		});

		return queryString.join('&');
	},
	
	collectValues: function() {
	  var result = {};
	  this.element.getElements('input, textarea, select').each( function( el ) {
	    if (!el.name || el.disabled) return;
	    var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
				return opt.value;
			}) : (['radio', 'checkbox'].contains( el.type ) && !el.checked) ? null : el.value;
			if( !$defined( result[el.name]  ) ) {
			  result[el.name] = [];
			}
			result[el.name].push( value );
			
	  });

	  return result
	},
	
	
	_isElementVisible: function( el ) {
	  
	  var parent = el.getParent();
	  while( $defined( parent ) ) {
	    if( parent.getStyle( 'display' ) == 'none' ) {
	      return false;
	    }
	    parent = parent.getParent();
	  }
	  
	  return true;
	},
	
	_collectElements: function( content ) {
	  var result = {};
	  content = $pick( content, this.element );
	  content.getElements('input, textarea, select').each( function( el ) {
	    if (!el.name || el.disabled) return;
	    
			if( !$defined( result[el.name]  ) ) {
			  result[el.name] = [];
			}
			result[el.name].push( el );
	  });
	  
	  return result
	},
	
	_fireBubblingEvent: function( el, name, args ) {
	  while( $defined( el ) ) {
	    el.fireEvent( name, args );
	    if( $defined( args[0] ) && args[0].cancel == true ) {
	      break;
	    }
	    el = el.getParent();
	    //console.log(el);
	  }
	},
	
	bindValues: function( data, content ) {
	  
	  var elements = this._collectElements( content );

	  for( var i in elements ) {
	    for( var j = 0, length = elements[i].length; j < length; j++ ) {
	      var el = elements[i][j];
	      if( !$defined( data[i] ) ) data[i] = [];
	      if( $type( data[i] ) != 'array' ) data[i] = [ data[i] ];

	      var ev = { changedContent: null, target: el };
	      if( ['radio', 'checkbox'].contains( el.type ) ) {
	        var newValue = data[i].contains( el.get('value') );
	        if( el.checked != newValue ) {
	          el.checked = newValue;
	          this._fireBubblingEvent( el, 'change', [ev] );
	        }

	      }
	      else if( el.tagName.toLowerCase() == 'select' ) {
	        if( !$defined( data[i][j] ) ) data[i][j] = [];
	        $A(el.options).each( function( option ) {
	          option.selected = data[i][j].contains( option.value );
	        });
	        this._fireBubblingEvent( el, 'change', [ev] );
	        if( $defined( ev.changedContent ) ) {
	          this.bindValues( data, ev.changedContent );
	        }
	        
	      }
	      else {

	        if( !$defined( data[i][j] ) ) data[i][j] = null;
	        el.set( 'value', data[i][j] );

	        el.fireEvent( 'change', [ev] );

	      }
	    }
	  }
	  
      
	},
	
	build: function( values, selectedTab ) {

	  this.isBuild = false;
	  this.element.setStyle( 'visibility', 'hidden' );
	  this.element.empty();
	  this.element.addEvent( 'change', this.onCheckableInputChange.bindWithEvent( this ) );
	  this.element.addEvent( 'click', this.onCheckableInputChange.bindWithEvent( this ) );
	  this.element.addEvent( 'keydown', function( ev ){ if( ev.key == 'enter' ) { ev.stop(); this.submit(); } }.bindWithEvent( this ) );


	  var thisObj = this;
	  var options = $merge( this.tabsRenderOptions, {
	    buildToggleMarkup: function( text, title ) { return thisObj._TabsBuildToggleMarkup.apply( thisObj, [text, title, this] ) },
	    buildMenuMarkup: function() { return new Element( 'div', { id: 'sidebar_tabframe' } ) },
	    buildWrapperMarkup: function() { return new Element( 'div', { id: 'sidebar_content' } ) }
	  } );
	  

	  this.tabsRender = new SimpleTabs( this.element, options );
	 
	  this.tabs.each( function(item) { this.renderTab(item); }, this );
	  this.renderFooter();
	  if( $defined( values ) ) {
	     this.tabs.each( function(item, i) { this.bindValues( values, this.tabsRender.tabs[i].container ); }, this );
	  }
	  this.tabsRender.select( $pick( selectedTab, options.show ) );

	  this.isBuilt = true;
	  (function() {
	    this.element.setStyle( 'visibility', 'visible' );
	    this.fireEvent( 'afterBuild', [{}], 0 );
	    this.fireEvent( 'afterBuildLast', [{}], 0 );
	  }).delay( 20, this );
	  
    
	},
	
	refresh: function() {
	  var values = this.collectValues();
	  var selected = this.tabsRender.selected;
	  this.build( values, selected );
	},
	
	submit: function() {
		
		this.element.getElements('input').each( function( el ) {
	    if( ( el.get( 'type' ) == 'hidden' ) ) {
	      el.set( 'value', '' );
	    }
		});
    this.sliders.each( function( s ) {
	    if( this._isElementVisible( s.element ) ) {
	      s.updateInputs();
	    }
	  }, this);

	  var data = this.getValuesAsArray();

	  this.fireEvent( 'submit', [data, this] );
	},
	
	addNamePrefix: function( data, prefix ) {
	  var result = {};
	  var re = /([^\[]+)(.*)/;
	  if( $type( data ) == 'object' ) {
  	  for( var i in data ) {
  	    var match = re.exec( i );
  	    
  	    result[prefix + '[' + match[1] + ']' + match[2]] = data[i];
  	  }
	  }
	  else {
	    var result = [];
	    data.each( function( item ) {
	      var match = re.exec( item[0] );
	      result.push( [ prefix + '[' + match[1] + ']' + match[2], item[1] ] );
	    });
	  }

	  return result;
	},
	
	renderTab: function( tab ) {
	  var content = new Element( 'div' );
	  this.tabsRender.addTab( tab.text, tab.title, content );
        
	  tab.groups.each( function( item ) {
	    
	    if( !$defined( item.addition ) ) {
	        item.addition = ''
	    } 
	        var classic = 'group' + item.addition;
	    
	    
	    var group = new Element( 'div', { 'class': classic} );
	    var inner = new Element( 'div', { 'class': 'inner' } );
	    if( $defined( item.propertyClasses ) ) {
	      group.addClass( 'propertyClassAware' );
	      item.propertyClasses.each( function( item2 ) { group.addClass(  'propertyClass' + item2) } );
	    }
	    if( item.title ) group.grab( new Element( 'div', { text: item.title, 'class': 'groupTitle' } ) );	
	    group.grab(inner);
	    content.grab( group );
	    item.items.each( function( item2 ) {  
	        if( !$defined( item2.addition ) ) {
	        item2.addition = ''
	    } 
	      var innerItem = new Element( 'div', { 'class': 'inner-item inner-item-' + item2.type + item2.addition } );
	      inner.grab(innerItem);
	      if( $defined( item2.propertyClasses ) ) {
  	      innerItem.addClass( 'propertyClassAware' );
  	      item2.propertyClasses.each( function( item3 ) { innerItem.addClass(  'propertyClass' + item3 ) } );
  	    }
  	    
	      this['render_' + item2.type](innerItem, item2, tab);
	    }, this);

	    this['render_line'](group);
	  }, this);


	},
	
	render_transactionTypes: function( content, item, tab ) {
	  this._render_radio_list( 'transactionType', $pick( item.name, this.options.transactionName ), this.transactionTypes, content, tab );
	},
	
	render_ownershipTypes: function( content, item, tab ) {
	  this._render_radio_list( 'ownershipType', this.options.ownershipName, this.ownershipTypes, content, tab );
	},
	
	render_constructionTypes: function( content, item, tab ) {
	  this._render_radio_list( 'constructionType', this.options.constructionName, this.constructionTypes, content, tab );
	},
	
	render_parcelTypes: function( content ) {
	  this._render_checkbox_list( 'parcelType', this.options.parcelTypeName, this.subClasses[6], content );
	},
	
	render_buildingTypes: function( content ) {
	  this._render_checkbox_list( 'buildingType', this.options.buildingTypeName, this.subClasses[5], content );
	},
	
	render_propertyClasses: function( content, item, tab ) {
	  var parent = this.tabsRender.tabs[this.tabs.indexOf( tab )].container;
	  var name = $pick( item.name, this.options.propertyClassName );
    var func = this.onPropertyClassChange.bindWithEvent( this, [parent, name] );
	
    content.addEvent( 'change', func );
    content.addEvent( 'click', func );
    this.addEvent( 'afterBuildLast', func );
	  if( $pick( item.renderType, 'radio' ) == 'radio' ) {
	    this._render_radio_list( 'propertyClass', name, this.propertyClasses, content, tab );
	  }
	  else {
	    this._render_checkbox_list( 'propertyClass', name, this.propertyClasses, content, tab );
	  }
	},
	
	_render_radio_list: function( _class, name, list, content, tab, callback ) {
	  var tabIndex = this.tabs.indexOf( tab );
	
	  list.each( function( item ) {
	    var div = new Element( 'div', { 'class': _class } );
	    var id = name + tabIndex + item.value;
	    var input = new Element( 'input', { type: 'radio', name: name, id: id, value: item.value } );
	    if( $defined( callback ) ) {
	      callback.apply( this, [div, input, label] );
	    }
	    var label = new Element( 'label', { 'for': id, text: item.label } );
	    content.grab( div.grab( input ).grab( label ) );
	   
	  }, this);
	},
	
	_render_checkbox_list: function( _class, name, list, content, tab, callback ) {	  
	  var tabIndex = this.tabs.indexOf( tab );
	  
	  list.each( function( item ) {
	    var div = new Element( 'div', { 'class': _class } );
	    var id = name + tabIndex + item.value;
	    var input = new Element( 'input', { type: 'checkbox', name: name + '[]', id: id, value: item.value } );
	    if( $defined( callback ) ) {
	      callback.apply( this, [div, input, label] );
	    }
	    var label = new Element( 'label', { 'for': id, text: item.label } );
	    content.grab( div.grab( input ).grab( label ) );
	   
	  }, this);
	},
	
	onCheckableInputChange: function( ev ) {
	  var el = ev.target;

	  if( (['radio', 'checkbox'].contains( el.type )) ) {
	    $$('input[name="'+el.name+'"]').each( function( el2 ) { if( el2.checked ) el2.getParent().addClass( 'input-checked' ); else el2.getParent().removeClass( 'input-checked' ) } );
	    
	  }
	},

	onPropertyClassChange: function( ev, parent, name ) {
	  if( this.isBuilt ) {

  	  var item = parent.getElements( 'input[name="'+name+'"]:checked' )[0];
  	  var value = $defined( item ) ? item.get('value') : null;
  	  parent.getElements( '.propertyClassAware' ).each( function( item ) { item.setStyle( 'display', 'none' ) } );
  	  parent.getElements( '.propertyClass' + value ).each( function( item ) { item.setStyle( 'display', 'block' ) } );
	  }
	  else {
	    this.addEvent( 'afterBuildLast', this.onPropertyClassChange.bindWithEvent( this, [parent, name] ) );
	  }
	},
	
	onSliderInputsChange: function( ev, slider ) {
	  if( this.isBuilt ) {
	    slider.updateFromInputs();
	  }
	  else {
	    this.addEvent( 'afterBuild', this.onSliderInputsChange.bindWithEvent( this, [slider] ) );
	  }
	},
	
	render_region: function( content, item, tab ) {
	  var tabIndex = this.tabs.indexOf( tab );

	  this.regionSelect[tabIndex] = new Element( 'select', { name: $pick( item.name, this.options.regionName ), id: this.options.regionName + tabIndex } );
	  select = new updateableSelect( this.regionSelect[tabIndex] );
	  select.buildOptions( this.regions );
    content.grab( this.regionSelect[tabIndex] );
	},
	
	render_cities: function( content, item, tab ) {
	  var tabIndex = this.tabs.indexOf( tab );
	
	  this.regionSelect[tabIndex].addEvent( 'change', this._updateCities.bindWithEvent( this, [content, tab] ) );
	  this.regionSelect[tabIndex].fireEvent( 'change', [{}] );
	},
	
	render_price: function( content, item ) {
    this._buildSlider( this.options.priceName, item.label, item.steps, item.labelFormat, item.valueFormat, content );
	},
	render_subclass: function( content, item ) {
    this._buildSlider( this.options.subclassName, item.label, item.steps, item.labelFormat, item.valueFormat, content );
	},
	render_area: function( content, item ) {
    this._buildSlider( this.options.areaName, item.label, item.steps, item.labelFormat, item.valueFormat, content );
	},
	
	render_inputs: function( content, item, tab ) {
	  var tabIndex = this.tabs.indexOf( tab );
	  
	  item.items.each( function( item ) {
	    var div = new Element( 'div', { 'class': 'input' } );
	    var input = new Element( 'input', { type: 'text', name: item.name, id: item.name + tabIndex, value: '' } );
	    var label = new Element( 'label', { 'for': item.name + tabIndex, text: item.label } );
	    content.grab( div.grab( label ).grab( input ) );
	  }, this);
	},
	
	render_exact_price: function( content, item ) {
    var div = new Element( 'div', { text: item.labels.title } );
    var input = new Element( 'input', { type: 'text', name: 'exact_price[from]', id: 'exact_pricefrom', value: '' } );
    var label = new Element( 'label', { 'for': 'exact_pricefrom', text: item.labels.from } );
    content.grab( div ).grab( label ).grab( input );
	  var input = new Element( 'input', { type: 'text', name: 'exact_price[to]', id: 'exact_priceto', value: '' } );
    var label = new Element( 'label', { 'for': 'exact_priceto', text: item.labels.to } );
    content.grab( label ).grab( input );
	},
	
	render_regions: function( content, item, tab ) {

	
	  var tabIndex = this.tabs.indexOf( tab );
	
	  var map = new Regions( content, { imagePath: this.options.imagePath, mapName: 'regiony_map' + tabIndex } );
	  map.addEvent( 'click', function(region) { this.regionSelect[tabIndex].set('value', region ); this.submit() }.bind( this ) );
	  map.build();
	  this.render_region( content, item, tab );
	  this.regionSelect[tabIndex].addEvent( 'change', function( ev ) { map.setRegion( this.regionSelect[tabIndex].get('value') ) }.bind( this ) );
	 if( !$defined( item.labels.submitClass ) ) { item.labels.submitClass = '' };
	  var submit = new Element( 'button', { type: 'submit', 'text': item.labels.submit, 'class': item.labels.submitClass } );
	  submit.addEvent( 'click', this.submit.bind(this) );
	  content.grab( submit );
	},
	
	render_line: function( content ) {
	  content.grab( new Element( 'div', { text: '', 'class': 'line' } ) );
	},
	
	render_submit: function( content, item ) {
	  var submit = new Element( 'button', { type: 'submit', 'text': item.label } );
	  submit.addEvent( 'click', this.submit.bind( this ) );
	  content.grab( submit );
	},
	
	renderFooter: function() {
	  var footer = new Element( 'div', { 'id': 'search-form-footer' } );
	  this.footer.each( function( item ) {
	    this['render_' + item.type](footer, item);
	  }, this);
	  this.element.grab( footer );
	},
	
	_buildSlider: function( id, label, steps, labelFormat, valueFormat, content ) {

	  if( $defined( this.sliderInputs[id] ) ) {
	    var fromInput = this.sliderInputs[id].fromInput;
	    var toInput = this.sliderInputs[id].toInput;
	    id = id + ++this.sliderInputs[id].count;
	  }
	  else {
  	  var fromInput = new Element( 'input', { name: id + '[from]', type: 'hidden' } );
  	  var toInput = new Element( 'input', { name: id + '[to]', type: 'hidden' } );
  	  content.grab( fromInput ).grab( toInput );
  	  this.sliderInputs[id] = { fromInput: fromInput, toInput: toInput, count: 0 };
	  }
	  
	  var div = new Element( 'div', { 'class': 'slidercontainer' } );
	  div.grab( new Element( 'div', { id: id + 'label', 'class': 'slidervalue' } ) );
	  div.grab( new Element( 'div', { text: label, 'class': 'sliderlabel' } ) );
	  content.grab( div );
	  var slider = new YAHOO.LOCAL.Slider( { id: id, content: div, steps: steps, noLimit: this.options.noLimit, labelFormat: labelFormat, valueFormat: valueFormat, imagePath: this.options.imagePath } );
	  

	  
    [ fromInput, toInput ].each( function( input ) {
	    input.addEvent( 'change', this.onSliderInputsChange.bindWithEvent( this, [slider] ) );
	  }, this);
	  
    slider.fromInput = fromInput;
    slider.toInput = toInput;
    this.sliders.push( slider );
	},
	
	_updateCities: function( ev, content, tab ) {
	  ev.changedContent = content;
	  ev.cancel = true;
	  content.empty();
	  var count = 0;
	  var tabsIndex = this.tabs.indexOf( tab );
	  var cities = this.cities[this.regionSelect[tabsIndex].get('value')];
	  for( var key in cities ) {
	    count++;
	    var item = cities[key];
	    var div = new Element( 'div', { 'class': 'city' } );
	    var id = this.options.cityName + tabsIndex + key;
	    var input = new Element( 'input', { type: 'checkbox', name: this.options.cityName + '[]', id: id, value: item } );
	    var label = new Element( 'label', { 'for': id, text: item } );
	    content.grab( div.grab( input ).grab( label ) );
	   
	  };

    content.getParent().getParent().setStyle( 'display', count > 0 ? 'block' : 'none' );
	},
	
	
	_TabsBuildToggleMarkup: function( text, title, tabsObj ) {
	  return new Element('div', { 'id': 'tab_' + this.options.tabPrefix + tabsObj.tabs.length, 'class': 'sidebar_tab' }).grab(new Element('a', {
				href: '#',
				title: title
			}).grab(
				new Element('span', {html: text})
			));
	}


});

var updateableSelect = new Class({
 
	Implements: Options,
 
	options: {
		defaultOption:null
	},
 
	initialize: function(el, options) {
		this.setOptions(options);
		this.el = $(el);
	},
 
	buildOptions: function(optionList, selected) {
		$A(optionList).each(function(option) {
			try {
				this.el.add(new Option(option.title, option.value), null);
			} catch(ex) {
				this.el.add(new Option(option.title, option.value));
			}
			if(selected && selected == option.value) {
				this.el.selectedIndex = this.el.length-1;
			}
		}.bind(this));
	},
 
	resetOptions: function(setDefault) {
		for(var i = this.el.length-1; i>=0; i--) {
			this.el.options[i] = null;
		}
		if(setDefault) {
			this.buildOptions([this.options.defaultOption], this.options.defaultOption.value);
		}
	},
 
	resetSelection: function() {
		this.el.selectedIndex = null;
	}
});


	(function () {
    YAHOO.namespace('LOCAL');
    
    YAHOO.LOCAL.Slider = function(options) {
 
      var options =  $merge( { steps: null, valueFormat: '{value}', labelFormat: '{min} to {max}', noLimit: 'No limit', id: '', content: null, initVals: [0, 138], range: 138, iTickSize: null, imagePath: '' }, options );
      if( $defined( options.steps ) ) {
        options.iTickSize = ( options.range / ( options.steps.length + 1 ) );
        var range = Math.round ( ( options.steps.length + 1 ) * options.iTickSize ) + 1;
        if( range > options.range ) {
          options.range = range;
        }

        options.initVals[1] = options.range;
      }

      var bg = new Element( 'div', { 'class': 'slider_bg', id: options.id + 'slide' } );
      var minthumb = new Element( 'div', { 'class': 'slider_min_thumb' } );
      minthumb.grab( new Element( 'img', { src: options.imagePath + '/slider/grabwidget.gif' } ) );
      var maxthumb = new Element( 'div', { 'class': 'slider_max_thumb' } );
      maxthumb.grab( new Element( 'img', { src: options.imagePath + '/slider/grabwidget.gif' } ) );
      var highlight = new Element( 'span', { 'class': 'slider_highlight' } );
      bg.grab( highlight ).grab( minthumb ).grab( maxthumb );
      options.content.grab( bg );
      var slider = YAHOO.widget.Slider.getHorizDualSlider(
            bg,
            minthumb,
            maxthumb,
            options.range,
            options.iTickSize,
            options.initVals
            );
            
      slider.element = bg;
      slider.options = options;
            
      var Dom = YAHOO.util.Dom;
      YAHOO.lang.augmentObject(slider, {

          _highlight : Dom.get( highlight ),
          _label : slider.options.id + 'label',


          updateHighlight : function () {
              var delta = this.maxVal - this.minVal;

              if (this.activeSlider === this.minSlider) {
                  // If the min thumb moved, move the highlight's left edge
                  Dom.setStyle(this._highlight,'left', (this.minVal + 12) + 'px');
              }
              // Adjust the width of the highlight to match inner boundary
              Dom.setStyle(this._highlight,'width', Math.max(delta - 12,0) + 'px');
          },
          
          updateInputs : function() {
            var values = this.getComputedValues();
            this.fromInput.set( 'value', values[0] );
            this.toInput.set( 'value', values[1] );
          },
          
          updateFromInputs : function() {
           

            var min, max;
          
            var from = this.fromInput.get( 'value' );
            var to =this.toInput.get( 'value' );
            
            if( $defined( this.options.steps ) ) {
              min = this.stepByValue( from );
              if( min == -1 ) {
                min = 0;
              }
              else {
                min = this.stepToValue( min );
              }
              max = this.stepByValue( to );
              if( max == -1 ) {
                max =  this.options.range;
              }
              else {
                max = this.stepToValue( max );
              }
              
            }
            else {
              min = from;
              max = to;
            }

            this.setValues.apply( this, [ min, max ] );
          },
          
          punctuated : function (n){
            if( $type( n ) != 'number' ) return n;

            var s=(''+n).split('.');
            s[0]=s[0].split('').reverse().join('').match(/\d{1,3}/gi).join('.').split('').reverse().join('');
            
            return(s.join('.'));
          },
          
          getComputedValues : function( formatted ) {
            var min, max;
            if( $defined( this.options.steps ) ) {

              
              range = this.options.steps.length;
              minSteps = this.valueToStep( this.minVal );
              maxSteps = this.valueToStep( this.maxVal );

              if( [-1, range].contains( minSteps ) ) {
                min = [0, 0];
              }
              else {
                min = this.options.steps[minSteps];
              }
              if( [-1, range].contains( maxSteps ) ) {
                max = [0, 0];
              }
              else {
                max = this.options.steps[maxSteps];
              }
            }
            else {
              min = this.minVal;
              max = this.options.range == max ? 0 : this.maxVal;
            }
            
            if( formatted == true ) {
              min = this.options.valueFormat.substitute( { 'value' : this.punctuated( min[1] ) } );
              max = max[0] ? this.options.valueFormat.substitute( { 'value' : this.punctuated( max[1] ) } ) : this.options.noLimit;
            }
            else {
              min = min[0];
              max = max[0];
            }
            
            return [min, max];
          },
          
          valueToStep : function( value ) {
            return Math.round( value / this.options.iTickSize ) - 1;
          },
          
          stepToValue : function( step ) {
            return Math.round( ( step + 1 ) * this.options.iTickSize );
          },
          
          stepByValue: function( value ) {
            for( var i = 0; i < this.options.steps.length; i++ ) {
              if( this.options.steps[i][0] == value ) {
                return i;
              }
            }
            return -1;
          },
          
          updateLabel : function() {
            var values = this.getComputedValues( true );
            
            $(this._label).set( 'text', this.options.labelFormat.substitute( { min: values[0], max: values[1] } ) );
          }
      },true);

      // Attach the highlight method to the slider's change event
      slider.subscribe('change',slider.updateHighlight,slider,true);
      slider.subscribe('change',slider.updateLabel,slider,true);
      
      slider.minRange = -14;
      slider.setValues.apply( slider, options.initVals );
      
      //slider.updateInputs();
      //slider.updateLabel();
      
      return slider;
    };
    YAHOO.LOCAL.DottedSlider = function(id, content, initVals) {
      
      var options =  $merge( { id: '', content: null, initVals: null, range: 110, iTickSize: 22 }, options );
      var slider = new YAHOO.LOCAL.Slider( options );
      
      slider.element.addClass( 'dotted_slider' );
           
      return slider;
    };


})();


var Regions = new Class({

	Implements: [Events, Options],
	
	options: {
	  imageWidth: 440,
	  mapName: 'regiony_map',
	  imagePath: '',
	  imageSubPath: 'map/'
	},
	
	initialize: function( element, options ) {
	  this.element = $(element);
	  this.setOptions( options );
	  this.imageWidth = 440;
	  this.region = options.region
	  this.areas = [/*
	  '183,121,178,120,177,120,174,121,171,122,171,125,172,128,171,131,171,133,172,135,175,137,177,139,176,141,176,144,176,147,179,148,182,147,185,146,189,143,193,141,195,141,198,141,200,142,203,143,205,142,207,141,207,139,208,137,210,136,212,135,212,133,213,130,212,128,211,125,209,123,207,121,205,121,202,120,200,118,196,118,193,118,191,118,187,119,184,120,183,121,183,121',
	  
'251,81,251,85,251,88,253,90,253,93,252,95,249,98,248,100,248,102,251,103,254,104,255,106,257,107,258,109,260,110,262,111,265,111,268,112,270,115,269,120,268,123,266,126,266,129,267,131,269,133,269,136,267,139,267,141,265,143,265,145,268,148,270,150,272,151,274,153,275,156,276,159,274,161,272,163,272,165,271,167,270,169,264,172,262,175,260,176,251,178,251,178,246,179,245,181,243,183,242,186,243,188,246,189,248,190,248,193,246,195,243,197,240,197,236,196,232,196,230,196,226,197,224,198,222,199,221,200,215,195,213,194,211,193,209,193,206,193,204,195,202,197,201,199,199,202,198,203,195,203,193,201,191,200,189,199,183,197,181,197,178,196,175,196,173,196,171,195,169,195,167,193,165,192,164,192,162,193,162,193,158,195,156,195,154,195,154,195,151,192,150,191,150,191,148,190,147,191,140,195,139,196,135,195,133,193,132,192,131,191,129,191,126,191,126,188,125,187,124,185,124,183,126,180,126,178,125,176,122,174,123,172,124,171,122,169,122,168,125,167,127,167,129,165,130,163,133,162,133,162,134,156,134,153,135,151,135,149,137,147,138,145,137,143,135,141,133,139,132,137,131,135,130,133,130,133,128,132,125,132,123,132,121,131,118,128,117,127,116,125,116,124,114,123,112,123,110,124,109,124,106,124,105,122,104,120,105,118,107,117,109,116,111,115,112,113,115,108,117,106,120,107,122,107,124,106,127,103,128,102,133,102,134,104,136,104,142,100,143,99,145,100,146,101,149,100,151,96,154,94,157,92,160,92,170,94,174,95,177,95,181,95,183,95,186,94,189,92,191,91,193,88,194,84,196,83,198,80,199,79,200,77,201,77,205,77,209,78,212,78,215,79,218,80,220,80,222,78,223,76,225,74,226,73,228,74,229,74,231,74,233,72,234,70,236,69,239,68,240,68,242,68,244,70,248,75,250,78,251,79,253,80,251,81',

'95,260,96,254,102,248,102,241,114,233,115,219,124,214,123,203,125,197,124,192,128,190,133,191,137,195,140,195,145,190,150,190,154,194,158,194,161,193,166,192,169,194,173,197,179,196,186,196,191,199,194,202,198,203,201,200,204,195,209,192,214,194,219,198,222,204,220,211,217,216,217,221,217,227,217,231,220,235,225,233,228,235,230,239,232,242,235,244,241,244,246,243,250,246,250,251,251,255,256,257,261,257,266,260,268,264,268,268,265,272,261,275,263,278,266,280,267,284,265,288,261,291,260,285,255,282,248,279,243,278,238,281,233,283,230,281,230,275,227,274,221,272,218,274,217,280,217,287,213,292,213,298,212,303,207,303,202,299,199,297,199,304,197,306,191,308,189,312,190,318,189,322,184,324,179,320,177,316,174,318,171,316,168,312,166,318,163,319,158,320,155,322,148,320,145,315,141,314,138,316,134,315,130,311,128,306,131,302,128,299,123,293,118,290,112,284,111,278,108,274,104,272,101,267,99,262,95,260',

'29,130,36,130,42,132,45,132,48,129,52,127,56,129,60,132,64,132,67,129,70,126,70,126,75,122,79,122,83,123,83,123,87,127,87,127,91,122,93,118,96,114,100,112,103,116,105,118,106,121,107,123,113,122,117,124,118,127,120,129,123,131,129,132,132,134,133,139,136,142,138,145,135,150,134,155,135,161,135,161,127,167,122,169,124,171,123,175,126,178,125,182,124,184,126,188,125,191,124,193,126,197,124,201,123,206,124,212,123,215,118,218,115,221,114,227,114,233,111,235,107,238,104,240,102,243,102,249,98,253,96,256,95,260,92,263,89,261,84,256,83,249,82,242,79,238,72,237,68,234,68,228,65,224,60,219,56,211,52,205,48,202,40,202,35,194,33,190,30,187,29,178,28,171,27,166,25,159,23,155,18,150,17,145,19,140,23,139,25,134,29,130',

'30,126,27,124,27,124,26,120,29,117,24,116,20,113,7,99,9,84,2,79,2,75,5,70,5,70,12,69,15,73,19,79,22,80,26,72,33,67,40,64,46,61,52,62,52,62,56,63,62,59,69,61,69,61,74,65,77,69,80,71,85,72,88,76,88,76,95,79,97,83,96,88,96,88,96,96,97,102,95,108,99,112,94,118,92,122,90,125,87,127,81,123,76,123,72,125,68,128,65,130,62,131,57,131,52,128,49,129,45,132,42,132,38,130,33,130,28,130,30,126',
	
'75,67,79,65,81,63,82,59,83,56,86,55,93,56,93,56,97,57,100,54,104,51,108,49,110,48,110,48,116,46,116,46,119,48,122,47,125,44,128,41,132,37,136,36,140,36,144,36,144,36,149,38,152,39,155,38,158,37,159,34,160,31,164,30,168,30,174,30,177,28,181,27,185,25,188,23,192,23,196,23,196,23,199,20,199,20,196,15,195,13,190,14,191,10,193,7,196,5,198,2,200,6,200,6,207,5,211,8,215,11,219,14,217,19,217,21,220,22,220,22,222,25,221,29,217,33,213,37,209,40,203,36,201,40,200,44,197,48,195,52,193,57,195,64,198,67,199,72,199,76,197,81,194,84,192,87,190,91,188,94,185,94,181,95,176,95,171,95,165,94,161,93,156,94,152,96,150,98,148,100,148,100,145,102,145,102,141,99,141,99,138,103,138,103,135,104,135,104,128,103,128,103,125,106,123,108,123,108,118,106,115,110,114,112,114,112,109,117,109,117,105,119,101,114,101,114,96,110,95,108,96,105,96,103,96,100,96,96,95,93,95,86,97,84,97,81,96,79,93,79,89,77,89,77,86,73,86,73,80,73,75,67',

'290,48,292,54,293,55,294,59,294,64,294,68,293,72,292,74,293,77,295,78,296,80,296,83,295,86,292,87,290,87,288,87,285,86,283,84,282,83,280,87,278,88,275,88,272,87,270,85,267,84,265,84,263,84,260,85,251,80,248,77,245,72,244,70,241,68,236,69,234,71,231,74,229,75,226,73,226,73,221,78,221,80,218,81,215,80,211,79,209,79,206,77,206,77,200,76,200,75,198,71,197,68,196,66,194,65,192,62,192,59,195,51,197,49,199,46,200,43,200,41,201,38,202,37,204,35,207,38,208,39,208,39,211,38,213,37,215,35,217,33,219,31,221,30,226,35,229,36,232,36,234,34,237,32,241,31,246,30,249,29,251,26,252,23,249,19,249,16,251,13,254,12,256,15,258,17,260,17,263,16,265,17,266,20,267,21,269,22,272,22,273,23,273,29,273,31,272,33,273,35,277,37,279,40,279,44,279,47,279,50,280,51,282,49,284,47,287,46,289,47,290,48',

'269,133,272,135,273,137,275,138,276,139,278,137,280,135,282,134,282,134,285,135,287,136,289,136,293,136,296,135,297,135,299,133,301,132,302,133,306,136,306,136,309,137,311,135,312,134,315,135,316,137,318,140,323,144,325,145,328,147,330,149,332,152,333,152,338,152,340,152,342,154,343,154,346,154,348,152,348,148,348,145,351,146,355,145,357,143,359,140,360,139,362,143,365,145,368,145,371,144,371,144,366,139,365,136,365,133,364,130,358,120,358,120,357,116,355,115,353,115,351,113,351,110,350,109,348,108,346,107,343,106,342,105,341,104,341,102,343,99,344,98,346,97,347,96,356,90,357,88,359,86,360,83,360,80,359,78,357,75,353,74,351,72,347,72,344,72,340,71,337,71,334,71,332,72,331,73,329,74,328,77,327,74,327,72,327,69,326,67,324,66,321,65,318,65,316,64,316,62,316,60,314,58,312,56,309,56,306,56,303,55,300,53,298,52,296,51,295,50,293,49,291,49,290,50,290,53,292,54,293,56,294,57,295,60,295,64,295,66,294,69,293,71,292,74,293,76,294,77,295,79,295,84,294,85,292,86,290,86,287,86,285,85,283,84,281,83,280,84,280,87,279,88,277,89,276,88,274,87,269,85,269,85,266,84,263,83,261,84,260,84,260,84,257,83,255,82,254,81,252,81,251,82,251,84,251,87,252,90,254,91,253,93,252,95,249,97,248,98,248,101,250,104,255,105,256,106,258,108,259,110,261,111,264,112,267,112,268,114,269,117,269,120,267,124,266,126,265,128,266,130,267,132,268,133,269,133',

'392,135,393,138,392,140,390,142,387,145,385,149,384,152,385,155,384,157,382,160,379,162,376,165,377,168,378,171,380,176,380,180,377,182,377,182,376,185,377,188,379,193,381,196,383,198,383,201,383,204,381,206,378,207,378,208,378,211,378,213,376,213,373,213,370,211,368,210,365,208,360,208,358,208,354,211,353,213,351,213,348,213,346,212,344,213,343,214,341,214,341,211,341,210,339,208,337,206,335,205,335,205,334,203,333,200,326,198,324,198,322,197,321,196,319,194,318,193,318,191,316,191,315,190,314,189,314,187,312,186,310,188,308,189,307,192,305,194,304,194,301,191,300,188,298,185,297,183,295,180,292,178,290,177,289,175,286,175,283,174,281,174,280,173,278,171,277,170,277,168,277,168,273,167,272,167,272,164,272,162,273,160,273,160,275,158,274,156,274,155,273,153,271,151,269,150,267,149,266,146,265,145,265,144,265,143,266,141,266,141,267,138,268,137,268,136,268,134,269,133,271,134,273,136,275,137,276,137,278,137,279,136,280,135,280,135,282,133,284,135,286,135,289,135,291,135,294,135,296,135,298,134,298,134,301,132,301,132,303,134,303,134,306,137,307,136,309,136,311,134,312,133,314,133,316,135,316,137,318,138,320,140,323,143,323,143,327,145,332,151,334,152,338,151,341,151,342,153,345,153,346,153,348,152,349,151,349,148,348,146,349,145,352,145,354,145,355,144,356,143,357,141,358,140,360,138,361,141,363,143,365,144,366,145,371,144,372,144,373,144,376,144,378,143,380,141,383,139,385,136,387,135,390,134,392,134,392,135',

'341,210,339,208,338,207,335,205,334,204,333,201,333,200,331,199,329,199,326,198,324,198,322,197,321,196,319,194,318,193,318,192,317,191,317,191,315,190,315,190,314,188,313,187,312,187,310,187,309,189,308,191,306,194,305,194,303,194,301,189,299,187,298,184,297,183,295,181,293,179,291,178,290,177,289,176,289,175,287,175,285,175,283,174,281,173,280,172,279,171,278,169,277,167,275,167,272,167,270,168,263,174,263,174,259,176,256,177,252,177,248,178,246,180,243,182,242,185,243,188,247,189,249,191,248,193,247,195,243,196,240,197,237,196,234,196,227,196,224,198,221,199,220,200,222,203,222,206,221,209,219,212,217,214,217,224,217,228,218,231,220,235,222,234,224,232,226,233,228,234,230,238,232,240,234,242,236,244,240,244,242,243,245,242,249,246,249,247,251,250,251,253,252,255,255,257,258,257,263,259,266,260,269,263,268,267,268,269,266,271,264,273,262,274,262,277,264,278,266,280,266,282,265,287,265,287,267,288,271,287,273,286,276,286,278,286,281,285,283,283,287,282,288,280,290,279,292,279,294,279,296,278,296,277,298,278,300,279,302,280,304,280,309,279,313,278,316,278,319,275,321,274,323,273,325,273,327,272,328,270,329,269,327,267,325,266,324,264,324,262,326,261,327,260,327,258,327,256,327,255,329,254,332,253,329,251,328,249,328,247,330,244,332,243,335,242,341,240,341,239,341,237,338,231,338,228,339,226,340,224,345,222,344,220,344,219,343,218,341,216,341,210',

'440,133,440,136,439,139,437,140,434,141,431,141,428,141,424,142,422,145,420,148,418,155,418,157,417,160,415,162,412,164,411,166,413,169,415,170,414,173,413,175,411,177,410,179,410,183,413,183,415,186,416,187,417,189,420,189,423,190,425,190,427,191,430,194,433,198,436,199,440,199,444,199,448,200,452,202,453,205,453,208,453,210,456,213,457,214,460,217,462,219,463,222,464,224,465,225,467,227,469,227,470,229,468,231,466,232,462,233,457,237,455,240,454,241,452,241,449,240,447,239,445,239,443,242,442,244,440,245,437,244,435,244,433,244,431,246,430,247,427,247,425,247,423,246,421,244,420,243,419,248,419,251,417,253,414,255,409,256,406,256,403,257,401,259,399,259,399,253,399,253,398,250,396,249,393,248,391,247,390,244,392,242,392,241,393,239,391,237,389,236,388,234,388,231,387,229,386,228,382,228,380,229,380,230,383,234,384,236,384,238,381,240,379,241,377,242,374,241,372,237,373,235,373,233,374,231,374,230,371,227,371,225,372,223,373,222,372,221,370,220,369,218,370,216,371,214,374,213,375,213,377,213,379,212,379,208,379,208,381,206,383,205,383,202,382,199,381,198,379,195,378,192,377,190,376,188,375,186,378,182,379,180,380,179,380,174,380,172,378,170,377,167,377,164,378,162,380,161,382,160,384,159,385,156,385,154,385,152,385,150,386,147,387,145,389,143,390,142,392,140,393,138,393,135,393,133,395,132,398,132,400,133,402,132,401,127,402,126,400,123,398,122,397,119,394,116,393,113,392,110,393,107,396,106,400,105,403,107,406,108,409,111,410,113,412,114,420,115,422,117,423,120,424,122,424,124,426,124,428,124,429,124,429,124,431,127,432,129,432,129,438,131,440,130,440,133',

'508,253,507,252,506,251,505,249,503,247,502,247,501,245,500,243,500,242,498,239,497,238,495,237,492,237,490,237,489,236,487,235,485,234,483,233,480,233,478,232,476,232,474,231,472,231,470,230,469,230,469,228,468,227,467,226,465,225,463,223,462,220,461,218,460,217,459,216,457,214,457,214,455,212,454,211,452,209,451,206,451,205,451,204,451,202,450,201,449,201,446,199,444,199,442,199,440,199,438,199,435,198,433,198,432,197,430,195,429,194,428,192,426,191,426,191,425,190,425,190,423,190,422,190,420,190,418,189,417,188,416,187,415,185,414,184,413,183,413,183,411,183,410,180,410,178,410,177,412,175,414,173,414,171,414,171,413,170,412,168,411,166,412,164,413,163,415,162,416,161,417,158,418,154,418,153,418,151,419,147,422,144,422,144,425,142,428,141,432,141,435,141,437,140,439,138,440,135,440,133,440,131,443,131,445,131,448,132,450,132,451,133,454,132,457,129,458,129,460,129,462,130,463,132,464,133,461,135,460,137,460,138,462,139,463,141,462,143,460,145,458,146,453,147,451,147,452,151,453,153,456,154,458,155,462,160,465,166,467,168,469,171,474,173,476,171,479,169,480,168,481,167,481,164,484,163,486,164,488,165,490,169,490,173,491,175,495,174,499,175,501,176,503,179,504,181,505,183,510,184,513,184,516,184,520,185,521,185,524,185,527,187,528,191,529,194,529,198,528,206,530,209,531,210,533,212,535,214,537,216,539,217,542,218,544,219,546,222,547,225,548,231,548,234,547,236,546,238,543,240,541,240,540,240,537,239,535,239,529,240,527,239,524,239,521,241,519,243,516,246,515,248,514,250,513,252,512,253,508,253',

'434,316,434,314,433,312,432,311,431,309,429,307,427,307,427,304,427,303,426,301,425,300,423,300,421,300,419,300,415,298,414,296,413,294,411,293,410,292,409,292,407,291,405,291,403,289,403,288,403,286,402,285,402,284,400,283,398,283,396,283,393,282,393,282,391,281,391,278,393,276,395,275,398,274,400,272,400,272,402,271,402,271,399,269,398,267,398,266,398,262,399,260,400,258,402,258,405,257,407,256,410,255,413,255,416,253,419,251,419,249,418,245,418,242,420,241,423,244,424,245,426,246,428,247,431,246,433,245,432,244,434,243,437,244,437,244,440,244,442,244,444,242,445,240,445,239,447,238,450,239,451,240,452,241,454,240,456,238,458,236,459,235,463,233,464,232,466,231,466,231,468,230,470,230,472,230,474,231,476,231,478,232,484,233,486,233,486,233,488,235,490,236,491,237,494,237,496,237,498,239,500,241,500,242,501,244,502,246,506,251,506,251,508,253,508,255,507,256,507,258,506,259,505,260,503,261,501,262,499,263,498,263,495,264,493,264,490,264,488,264,488,264,486,268,487,271,486,273,485,276,484,279,482,282,481,284,480,288,480,289,478,292,477,293,476,295,473,296,470,296,468,296,465,296,463,297,461,300,460,302,460,305,460,307,460,308,457,310,455,310,452,309,451,308,449,308,447,310,445,314,445,315,443,316,442,317,438,317,434,316',

'342,214,341,215,342,217,343,219,344,220,344,222,343,223,341,224,339,225,339,228,339,231,339,234,340,237,340,240,339,241,334,244,334,244,331,245,329,245,328,246,328,249,329,251,330,252,330,253,329,255,327,256,327,256,326,260,326,260,326,262,325,263,328,267,328,267,329,269,328,271,326,272,324,274,319,275,317,277,315,278,313,279,310,279,307,279,302,279,302,279,300,279,299,278,297,277,295,277,293,279,293,279,290,279,289,279,287,280,285,282,283,283,282,283,282,283,280,286,278,286,276,285,273,286,272,286,272,286,268,287,266,287,264,288,262,289,262,291,263,292,266,293,269,293,270,293,272,296,273,298,275,300,277,300,278,300,280,299,281,298,282,296,283,296,285,298,288,299,290,303,292,304,294,304,294,307,294,309,296,312,298,313,301,314,304,317,306,318,308,318,312,317,314,316,316,317,320,318,322,319,324,321,327,322,330,322,333,321,334,320,336,317,338,315,339,314,341,314,341,314,343,315,344,314,345,313,347,315,348,316,350,317,353,317,354,318,355,319,354,323,355,324,355,324,357,325,359,325,362,324,364,324,365,326,365,328,367,328,370,328,372,328,372,329,372,331,370,332,369,334,369,336,373,339,375,340,378,340,380,338,381,335,380,332,381,330,383,327,385,325,391,321,391,319,391,317,390,313,392,312,395,312,397,313,399,312,400,310,402,309,404,309,406,310,407,312,408,315,408,316,412,318,415,319,418,319,420,319,422,318,423,316,424,318,426,319,428,320,431,319,434,317,436,316,436,316,435,313,434,312,433,310,432,309,430,308,428,307,427,305,427,304,427,302,427,301,425,300,423,300,421,300,418,299,416,297,414,296,413,295,412,293,410,292,408,292,406,291,404,290,403,288,403,286,402,284,401,283,399,283,397,283,395,282,393,281,392,280,392,278,394,276,397,275,400,274,401,272,401,270,401,269,399,267,398,265,398,263,397,262,397,261,399,259,399,256,398,255,399,253,398,251,398,250,395,249,395,249,393,248,391,246,391,244,392,242,393,241,394,240,393,238,391,236,388,235,387,233,387,231,387,229,385,227,383,227,381,228,379,229,381,231,383,234,384,235,384,237,383,238,382,239,380,240,379,241,377,241,374,240,373,235,373,233,374,232,374,230,375,229,373,228,372,226,372,225,372,224,373,223,373,222,372,220,370,220,370,219,369,217,370,216,370,216,373,215,373,215,374,213,373,212,372,211,370,211,369,210,366,209,365,208,363,207,360,208,358,208,357,209,355,210,355,210,353,212,352,212,350,213,348,212,348,212,347,211,345,212,345,212,342,214'
*/
	  
'147,95,137,97,135,107,140,119,162,115,171,105,168,96,147,93,147,94',
	  '113,79,85,95,94,99,102,106,107,113,106,128,100,133,99,151,112,155,119,152,128,155,138,156,145,157,156,162,166,153,175,158,192,156,199,153,194,144,210,140,216,134,220,125,210,114,215,106,215,99,214,90,203,83,199,75,200,65,196,56,190,54,178,58,174,64,161,61,148,74,133,74,125,75,106,82,98,86,85,93',
	  
'101,151,100,170,91,176,91,188,82,194,76,206,86,217,89,227,104,240,105,250,115,252,122,256,127,254,136,251,149,259,154,244,161,238,172,244,176,218,185,221,186,225,198,222,204,226,208,231,214,224,210,218,216,212,212,206,202,204,199,193,189,194,181,185,176,187,172,173,177,166,174,159,166,152,157,161,151,156,141,158,136,155,129,153,122,153,119,151',
	  '22,103,18,111,11,115,20,126,23,150,30,160,40,162,55,186,65,192,67,203,74,210,81,199,83,192,91,186,92,175,100,171,100,133,109,127,110,114,104,106,93,98,85,97,82,92,77,88,70,101,63,96,48,106,45,102,37,104,33,105,21,102',
	  
'5,52,14,62,25,54,36,48,49,48,59,52,69,57,77,62,76,86,68,100,61,96,48,106,40,101,33,106,22,101,18,90,6,77,1,62,5,52',	  

'61,52,65,44,75,45,83,38,94,37,104,29,123,28,131,24,159,17,153,7,160,3,171,6,174,15,176,20,171,30,162,30,157,40,155,49,158,56,159,62,149,74,128,73,99,85,83,95,77,88,75,74,75,64,62,52',
	  '177,18,178,25,184,28,191,26,199,23,198,14,204,11,211,14,219,17,218,22,218,26,222,30,223,39,230,36,234,42,235,48,234,59,236,69,221,70,200,63,194,55,180,58,174,64,161,61,156,46,162,30,172,28,176,17',
	  
'232,38,252,45,253,52,260,52,263,60,274,56,283,59,288,64,283,72,272,82,281,89,287,96,293,106,295,115,287,112,278,117,275,123,253,108,241,106,227,108,219,109,214,104,214,90,199,80,201,63,216,68,235,68,234,39',
	  '313,106,307,120,306,128,300,129,301,146,306,158,302,170,287,167,279,171,275,168,263,159,252,150,243,155,218,132,220,124,212,113,216,105,251,106,265,119,276,121,287,114,301,114,313,106',
 '174,156,176,165,173,173,175,188,180,185,188,193,198,192,202,205,211,206,215,212,209,218,213,224,213,230,237,222,250,222,262,214,263,195,273,192,275,169,250,148,242,154,225,138,219,132,207,137,198,141,192,147,196,157,175,155',
	  '321,104,313,106,307,119,307,128,299,129,300,147,307,160,302,169,296,174,299,193,305,191,304,183,309,183,313,191,316,199,318,208,337,200,336,195,346,197,376,183,362,167,362,161,328,143,330,132,341,112,349,111,354,104,342,99,332,90,317,83,313,90,321,104',
	  '354,104,370,103,370,113,361,117,362,123,377,136,384,133,388,129,391,137,403,146,421,148,422,163,434,175,439,184,432,192,418,190,409,201,399,190,376,183,359,159,329,144,341,114,349,112,354,103',
	  '409,200,403,209,388,211,379,236,368,239,366,244,358,247,355,254,348,252,341,239,329,231,311,223,321,214,318,208,335,200,338,194,345,196,376,183,398,189,408,200',
	  '274,168,273,193,264,195,260,215,250,222,209,230,222,240,227,237,236,243,243,253,258,255,263,258,272,251,298,263,295,269,302,271,315,250,324,246,331,254,337,255,349,252,342,241,321,226,312,222,322,215,318,207,317,201,309,182,304,183,305,190,299,191,297,183,297,175,301,171,292,166,285,166,279,170,273,176,273,192'
	  
	  

	  ];
	  this.computedAreas = this.areas;
	},
	
	setRegion: function( region ) {
	  this.region = region;
	  this.image.set( 'src', this._getImagePath( region ) );
	},
	
	build: function() {
	  this._computeAreas();
	  this.image = new Element( 'img', { src: this._getImagePath( this.region ), width: this.options.imageWidth, usemap: '#'+this.options.mapName } );
	  var map = new Element( 'map', { id: this.options.mapName, name: this.options.mapName } );
	  this.computedAreas.each( function( item, key ) {
	    var region = key + 1;
	    var area = new Element( 'area', {  'shape': 'poly' } );
	    area.setAttribute( 'coords', item );
	    area.addEvent( 'click', this.onAreaClick.bindWithEvent( this, [region] ) );
	    area.addEvent( 'mouseenter', this.onAreaMouseover.bindWithEvent( this, [region] ) );
	    /*area.addEvent( 'mouseout', function( ev ) { ev.stop(); if( $defined( ev.relatedTarget ) && ev.relatedTarget.get('tag') == 'area' ) this.onAreaMouseout(ev); }.bindWithEvent(this) );
	    this.element.addEvent( 'mouseout', this.onAreaMouseout.bindWithEvent( this ) );*/
	    map.grab( area );
	  }, this);
	  this.element.addEvent( 'mouseleave', this.onAreaMouseout.bindWithEvent( this ) );
	  this.element.grab( this.image ).grab( map );

	},
	
	onAreaClick: function( event, region ) {
		event.stop();
		this.setRegion( region );
		this.fireEvent( 'click', [region] );
		//console.log(this.computedAreas[region-1]);
	},
	onAreaMouseover: function( event, region ) {
	  document.body.style.cursor = 'pointer';
		this.image.set( 'src', this._getImagePath( region ) );
		event.stop();
	},
	onAreaMouseout: function( event ) {
		this.image.set( 'src', this._getImagePath( this.region ) );
		
		document.body.style.cursor = 'auto';
		event.stop();
	},

	
	_computeAreas: function() {
	  this.computedAreas = [];
	  var ratio = this.options.imageWidth / this.imageWidth;
	  this.areas.each( function( item ) {
	    var item2 = [];
	    $each( item.split( ',' ), function( value ) {
	      item2.push( Math.round( value * ratio ) );
	    });
	    this.computedAreas.push( item2.join(',') );
	  }, this);
	  
	}, 
	
	_getImagePath: function( region ) {
	  if( $defined( region ) && region != 0 ) {
		  if ( region < 10 ) region = '0' + region;
	  }
	  else {
	    region = '00';
	  }
		return this.options.imagePath + '/' + this.options.imageSubPath + 'map_' + ( region ) + '.gif';
	}

	
});

isEmpty = function( object ) {
    for (var prop in object) {
        if (object.hasOwnProperty(prop)) return false;
    }
    return true;
};