/*
---------------------------------------------------------
*
*	Module "Place"
*	Author: Alexander Zinchuk ( Ajaxy ) 
*	Contact e-mail: hey@ajaxy.ru
*
---------------------------------------------------------
*/

ls_Place = {
  placeId : 0,
  placeTitle : 0,
  selectedTypes : Array(),
  selectedTypesMaxLength : 0,
  Rating_current : 0,
  Rating_countVote : 0,
  Rating_userIsVote : 0,
  GMapApi : 0.0,
  GMapLat : 0.0,
  GMapLng : 0.0,
  GMapZoom : 0.0,  
  GMapInited : false, 
  catalogueCity : '',
  catalogueType : '',
  catalogueDiv : '',
  catalogueTitleLike : '',
  
  setField : function(fieldName, value) {
    $('place_'+ fieldName).value = value;
  },
  
  create_addType : function(checkbox) {
    if(this.selectedTypesMaxLength == 0) return true;
  
    var type = checkbox.id.substring(checkbox.id.lastIndexOf('_')+1);
    if(this.selectedTypes.contains(type)) {
      this.selectedTypes.erase(type);
    } else if(this.selectedTypes.length < this.selectedTypesMaxLength) {
      this.selectedTypes.push(type);
    }
    checkbox.parentNode.getElements('input[type=checkbox]').each(function(chbox) {
      chbox.disabled = chbox.checked ? false : this.selectedTypes.length >= this.selectedTypesMaxLength;
    }, this);
  },
  
  Rating_move : function(div, e) {
    e = e||window.event;
    if(!div.className) div = div.parentNode;
    div.firstChild.style.width = ((e.layerX||e.offsetX)/120*100) + '%';
    $('place_rating').innerHTML = parseInt((e.layerX||e.offsetX)*500/120);
  },

  Rating_out : function(e) {
    e = e||window.event;
    var target = e.target||e.srcElement;
    if((target.className && target.className == 'stars')) {
      return false;
    }
    $('place_rating').innerHTML = this.Rating_current;
    $('place_rating_stars').style.width = ( this.Rating_current/500*100 + '%' );
  },
  
  Rating_click : function(div, e) {
    e = e||window.event;
    if(!div.className) div = div.parentNode;
    var value = Math.round((e.layerX||e.offsetX)*500/120);
    this.Rating_userIsVote = value;
    return lsVote.vote(this.placeId, div, value, 'place');
  },

  Rating_voted : function(result) {
    this.Rating_current = Math.round(result.iRating);
    this.Rating_countVote = result.iCountVote;
    $('place_rating').innerHTML = this.Rating_current;
    $('place_rating_stars').style.width = ( this.Rating_current/500*100 + '%' );
    $('place_count_vote').innerHTML = result.iCountVote;
    this.Rating_userIsVote = true;
  },
  
  joinLeave : function(obj,idPlace) {   
	obj=$(obj);
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/place_joinLeave.php',                       
        { idPlace: idPlace },
        function(result, errors) {  
        	if (!result) {
            msgErrorBox.alert('Error','Please try again later');           
        	} else {
            if (result.bStateError) {
            	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
            } else {            	
            	msgNoticeBox.alert(result.sMsgTitle,result.sMsg);
            	if (obj)  {          		
            		if (result.bState) {            			
            			$('place_join_true').style.display = 'none';
            			$('place_join_false').style.display = 'inline';
            		} else {            			
            			$('place_join_true').style.display = 'inline';
            			$('place_join_false').style.display = 'none';
            		}
            		var divCount=$('place_user_count_'+idPlace);
            		if (divCount) {
            			divCount.set('text',result.iCountUser);
            		}
            	}
            }
          }
        },
        true
    );
  },
  
  toggleEdit : function(n, item) {
    var divs = $('place_edit_form').getChildren('div');
    divs.each(function(div) {
      div.setStyle('display', 'none');
    });
    $('placeEdit_div'+n).setStyle('display', 'block');
    var menus = $('place_edit_menu').getChildren('li');
    menus.each(function(div) {
      div.removeClass('active');
    });
	item.parentNode.addClass('active');
    if(n == 1) {  
      this.placeAddress = [$('place_country').value, $('place_city').value, $('place_address').value].erase('').clean().join(', ');  
      $('gmap_geo_address').value = this.placeAddress;  
      this.GMapInit($('gmap_canvas'), this.GMapApi, this.GMapLat, this.GMapLng, this.GMapZoom, true);  
      this.GMapPutMarker(null, true); 
    }
  },
  
  /* Catalogue */
  
  selectCity : function(input) {
    setTimeout(function() {
      if(!input.focused) {
        if(input.value != ls_Place.catalogueCity) {
          ls_Place.catalogueCity = input.value;
          if(!input.value || input.value == '*' || input.value == ls_Place.lang_cities_all) {
            input.value = ls_Place.lang_cities_all;
            ls_Place.catalogueCity = '*';
          }
          ls_Place.loadCatalogue();
        }
        input.removeClass('focused');
      }
    }, 100)
  },
  
  selectType : function(type, bySearchString) {
    types = type.split(',').map(function(v) { return v.trim(); });
    var links = $('place_types').getElements('a');
    links.each(function(link) {
      if(types.contains(link.get('text'))||types.contains(link.get('nativetext'))) {
        link.addClass('active');
      } else {
        link.removeClass('active');
      }
    });
    this.catalogueType = type == this.lang_types_all ? '*' : type;
    if(bySearchString) { // no need to load places if no location.hash params set
      return;
    }
    this.loadCatalogue();
  },
  
  loadCatalogue : function(filters, catalogueDiv) {
    catalogueDiv = $(catalogueDiv||this.catalogueDiv);
    filters = filters||{},
    filters.city = ls_Place.catalogueCity||'*';
    filters.type = ls_Place.catalogueType||'*';
    filters.sortby = ls_Place.catalogueSortBy;
    filters.titlelike = ls_Place.catalogueTitleLike;
    
    var hash = new Hash(filters);
    location.hash = hash.filter(function(v, k){ return v != '*'; }).toQueryString();
    
    catalogueDiv.getChildren()[1].setStyle('display','none');        	
    catalogueDiv.getChildren()[0].setStyle('display','block');        	
    JsHttpRequest.query(
      DIR_WEB_ROOT+'/include/ajax/place_loadCatalogue.php',                       
      filters,
      function(result, errors) {  
        if (!result) {
          msgErrorBox.alert('Error','Please try again later');           
        } else {
          if (result.bStateError) {
            msgErrorBox.alert(result.sMsgTitle,result.sMsg);
          } else {  
            catalogueDiv.getChildren()[0].setStyle('display','none');        	
            catalogueDiv.getChildren()[1].set('html', result.sText);
            catalogueDiv.getChildren()[1].setStyle('display', 'block');
          }
        }
      },
      true
    );
  },
  
  profile_EventsFilter : function(filter) {
    var menus = $('place_events_filter').getChildren('li');
    menus.each(function(div) {
      div.removeClass('active');
    });
    var active = $('place_events_filter').getFirst('li.'+filter)||$('place_events_filter').getFirst('li.all');
    active.addClass('active');
    var dates = ls_Event.parseWordsInDate(filter).split('-');
    var date = dates.map(function(date){ return ls_Event._convertDate(date, true); }).join('~');
    ls_Event.loadBill({place_id:this.placeId, date:date});
  },  
    
 /*  
  * Geo Maps init.  
  */  
  GMapInit : function(div_canvas, api, lat, lng, zoom, editMode) {  
    if(this.GMapInited) {  
      return true;  
    }  
    if(api == 'google') {  
      this.GMapInited = this.GMapInitGoogle(div_canvas, lat, lng, zoom, editMode);  
    } else if(api == 'yandex') {  
      this.GMapInited = this.GMapInitYandex(div_canvas, lat, lng, zoom, editMode);  
    }  
    this.GMapApi == api;  
    return this.GMapInited;  
  },  
    
  GMapPutMarker : function(LatLng, editMode, multiple, title, url, types) {  
    if(this.GMapApi == 'google') {  
      LatLng = LatLng || ( this.GMapMarker ? this.GMapMarker.getPosition() : this.GMap.getCenter() );  
      return this.GMapGooglePutMarker(LatLng, editMode, multiple, title, url, types);  
    } else if(this.GMapApi == 'yandex') {  
      LatLng = LatLng || ( this.GMapMarker ? this.GMapMarker.getGeoPoint() : this.GMap.getCenter() );  
      return this.GMapYandexPutMarker(LatLng, editMode, multiple, title, url, types);  
    }  
  },  
    
  GMapLatLng : function(lat, lng) {  
    return this.GMapApi == 'google' ? new google.maps.LatLng(lat, lng) : new YMaps.GeoPoint(lng, lat);  
  },  
    
  GMapInitGoogle : function(div_canvas, lat, lng, zoom, editMode) {  
    if(!google || !google.maps) {  
      return false;  
    }  
    ls_Place.GMap = new google.maps.Map(div_canvas, {  
      zoom: zoom,  
      center: new google.maps.LatLng(lat, lng),  
      mapTypeId: google.maps.MapTypeId.ROADMAP,  
      mapTypeControl : true,  
      navigationControl : true,   
      scaleControl : true,  
      scrollwheel : false  
    });  
      
    return !!ls_Place.GMap;  
  },  
    
  GMapInitYandex : function(div_canvas, lat, lng, zoom, editMode) {  
    if(!YMaps) {  
      return false;  
    }  
    ls_Place.GMap = new YMaps.Map($(div_canvas));  
    ls_Place.GMap.setCenter(new YMaps.GeoPoint(lng, lat), zoom);  
    ls_Place.GMap.setZoom(zoom);  
    ls_Place.GMap.addControl(new YMaps.TypeControl());  
    ls_Place.GMap.addControl(new YMaps.ToolBar());  
    ls_Place.GMap.addControl(new YMaps.Zoom());  
    ls_Place.GMap.addControl(new YMaps.ScaleLine());  
      
    return !!ls_Place.GMap;  
  },  
    
  GMapGooglePutMarker : function(LatLng, editMode, multiple, title, url, types) {  
    editMode = editMode||false;  
    title = title||ls_Place.placeTitle||'';  
    var shortTitle = title;  
    if(title && title.contains('@')) {  
      shortTitle = title.substring(0, title.indexOf('@')-1);  
    }  
    var html = '';  
    if(url && title) {  
      html += '<a href="'+url+'"><b>'+title+'</b></a>' + (types ? ' ('+types+')' : '') + '<br/>';  
    }  
    var geocoder_options = { bounds : ls_Place.GMap.getBounds() };  
    if(editMode && ls_Place.placeAddress && !ls_Place.GMapSet) {  
      geocoder_options.address = ls_Place.placeAddress;  
    } else {  
      geocoder_options.latLng = LatLng;  
    }  
      
    var marker = false;  
    var marker_options = {  
      map: ls_Place.GMap,  
      draggable : editMode,  
      title : shortTitle,  
      position : LatLng  
    };  
      
    var geocoder = new google.maps.Geocoder()  
    geocoder.geocode(geocoder_options, function(results, status) {  
      if (status == google.maps.GeocoderStatus.OK) {  
        if(!ls_Place.GMapSet) {  
          marker_options.position = results[0].geometry.location;  
        }  
        html += results[0].formatted_address;  
      } else if(editMode) {  
        alert('Location "'+ls_Place.placeAddress+'" not found.')  
      }  
      marker = new google.maps.Marker(marker_options);  
      if(!multiple) {  
        if(ls_Place.GMapMarker) {  
          ls_Place.GMapMarker.setOptions({visible:false});  
        }  
        ls_Place.GMap.panTo(marker_options.position);  
      }  
      var infowindow = new google.maps.InfoWindow({content:html});  
      infowindow.close();  
      google.maps.event.addListener(marker, 'click', function() {  
        infowindow.open(ls_Place.GMap,marker);  
      });  
      google.maps.event.addListener(ls_Place.GMap, 'click', function() {  
        infowindow.close();  
      });  
        
      if(editMode) {  
        $('form_gmap_lat').value = marker.getPosition().lat();  
        $('form_gmap_lng').value = marker.getPosition().lng();  
        google.maps.event.addListener(marker, 'dragend', function(m_event) {  
          infowindow.close();  
          ls_Place.GMapSet = true;  
          $('form_gmap_lat').value = m_event.latLng.lat();  
          $('form_gmap_lng').value = m_event.latLng.lng();  
          ls_Place.GMapGooglePutMarker(m_event.latLng, true);  
        }, this);  
      }  
        
      ls_Place.GMapMarker = marker;  
    });  
  
      
  },  
    
  GMapYandexPutMarker : function(LatLng, editMode, multiple, title, url, types) {  
    var findBy = editMode && ls_Place.placeAddress && !ls_Place.GMapSet ? ls_Place.placeAddress : LatLng;  
    var geocoder = new YMaps.Geocoder(findBy, {results: 1, boundedBy: ls_Place.GMap.getBounds()});  
    var marker = false;  
    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {  
      if (this.length()) {  
        marker = this.get(0); 
        if(ls_Place.GMapSet) {  
          marker.setGeoPoint(LatLng);  
        } 

      } else {  
        if(editMode) {  
          alert('Location "'+ls_Place.placeAddress+'" not found.')  
        }  
        marker = new YMaps.Placemark(LatLng);  
      }  
      marker.setOptions({draggable:editMode});  
      if(url) {  
        marker.name = '<a href="'+url+'"><b>'+title+'</b></a>' + (types ? ' ('+types+')' : '');  
        marker.text = marker.name + '<br/>' + marker.text  
      }  
      if(title||ls_Place.placeTitle) {  
        if(title && title.contains('@')) {  
          title = title.substring(0, title.indexOf('@')-1)+'</a>';  
        }  
        marker.setIconContent(title||ls_Place.placeTitle);  
      }  
        
      ls_Place.GMap.addOverlay(marker);  
        
      if(!multiple) {  
        ls_Place.GMap.removeOverlay(ls_Place.GMapMarker);  
        ls_Place.GMap.panTo(marker.getGeoPoint())  
      }  
        
      if(editMode) {  
        $('form_gmap_lat').value = marker.getGeoPoint().getLat();  
        $('form_gmap_lng').value = marker.getGeoPoint().getLng();  
        YMaps.Events.observe(marker, marker.Events.DragEnd, function(marker) {  
          ls_Place.GMapSet = true;  
          ls_Place.GMapYandexPutMarker(marker.getGeoPoint(), true);  
        }, this);  
      }  
       
      ls_Place.GMapMarker = marker;  
    }); 

  }
 
}
