<?php
class GMapCities extends DataObject {

    public static $db = array(
        'Title' => 'Text',
        'Locale' => 'Varchar(16)',
        'Active' => 'Boolean'
    );

     public static $has_one = array(
        'GMapPage' => 'GMapPage'
    );


    //Set our defaults
    public static $defaults = array(
        'Title' => 'New City',
        'Active' => true
    );


    public function getCMSFields_forPopup() {
        $current_locale = Translatable::get_current_locale();
        return new FieldSet(
                        new TextField('Title', 'City'),
                        new HiddenField('Locale', 'Locale', $current_locale),
                        new CheckboxField('Active', 'Active?', true)

        );
    }

//    /**
//	 * When the item is saved then do so
//	 */
//	public function onBeforeWrite() {
//		parent::onBeforeWrite();
//		$this->Locale = Translatable::get_current_locale();
//	}

//    public function countPoints() {
//        $points = $this->AllPoints();
//        if($points) {
//            return $points->Count();
//        }
//        return 0;
//    }

    public function PointsMoreThan($counter=2) {
        return ($this->AllPoints() &&  $this->AllPoints()->Count() > $counter);
    }

    public function Point() {
        $points = $this->AllPoints();
        if($points) {
            return $points->First();
        }
        return false;
    }

    public function AllPoints() {

        return DataObject::get('GMapData', "Active='1' AND GMapCityID='".$this->ID."'");
    }


}
class GMapData extends DataObject {

    public static $db = array(
        'Address' => 'Varchar(255)',
        'Lat' => 'Varchar(10)',
        'Long' => 'Varchar(10)',
        'InfoBlock' => 'HTMLText',
        'GMapCityID' => 'Int',
        'Active' => 'Boolean',
        'Locale' => 'Varchar(16)'
    );

    public static $has_one = array(
        'GMapPage' => 'GMapPage'
    );


    //Set our defaults
    public static $defaults = array(
        'Active' => true
    );


    public function getCMSFields_forPopup() {
     $current_locale = Translatable::get_current_locale();

        return new FieldSet(
                        new TextField('Address', 'Address'),
                        new TextField('Lat', 'Latitude'),
                        new TextField('Long', 'Longitude'),
                        new SimpleTinyMCEField('InfoBlock', 'Info block'),
                        new DropdownField('GMapCityID', 'City', $this->getCitiesOptions()),
                        new CheckboxField('Active', 'Active?', true),
                        new HiddenField('Locale', 'Locale', $current_locale),
                        new LiteralField('Literal','<br /><br />')
        );
    }

    /**
	 * When the item is saved then do so
	 */
	public function onBeforeWrite() {
		parent::onBeforeWrite();
		//$this->Locale = Translatable::get_current_locale();
        $this->InfoBlock = strip_tags($this->InfoBlock, '<strong><em><b><i><br/><br><ul><li><ol><a>');


	}

	public function getCityByString(){
		if(!empty($this->Address)){
			preg_match('/[^ ]*$/', $this->Address, $result);
			return isset($result[0])
			       ? $result[0] : null;
		}

		return null;
	}

    public function getCitiesOptions() {

         $pageID = 0;
         if($this->GMapPageID) {
             $page = DataObject::get_by_id('GMapPage', $this->GMapPageID);
             if($page) $pageID = $page->ID;
         }
        if($Items = DataObject::get('GMapCities', "Active='1' AND GMapPageID='".$pageID."'")) {
            return $Items->map('ID', 'Title', _t('GMapPage.SELECT', 'Please Select'));
        } else {
            return array('No Objects found');
        }
    }



}

class GMapPage extends Page {

    static $has_many = array (
        'GMapData' => 'GMapData',
    );

    public function getCMSFields() {
        $fields = parent::getCMSFields();

        $fields->addFieldToTab("Root.Content.Cities", new DataObjectManager(
                $this,
                'GMapCities',
                'GMapCities',
                array(
                    'Title' => 'City',
                    'Active' => 'Active?'),
                'getCMSFields_forPopup'
        ));
        $fields->addFieldToTab("Root.Content.MapData", new DataObjectManager(
                $this,
                'GMapData',
                'GMapData',
                array(
                    'Address' => 'Address',
                    'Lat' => 'Latitude',
                    'Long' => 'Longitude',
                    'Active' => 'Active?'),
                'getCMSFields_forPopup'
        ));

        return $fields;
    }

    public function MapRecords() {
        return GMapData::get('GMapData', "Active='1'", 'SortOrder ASC');
    }

    public function MapCities() {
        return DataObject::get('GMapCities', "Active='1' AND GMapPageID='".$this->ID."'");
    }

}

class GMapPage_Controller extends Page_Controller {

    public function init() {
        parent::init();
        $mapRecords = $this->GMapData();
        $coords = 'coords = [';
        $num_items = count($mapRecords);
        $i = 1;
        if($mapRecords) {
            foreach($mapRecords as $rec) {
                $coords .= "{RecID:\"$rec->ID\", RecLat:\"$rec->Lat\", RecLong:\"$rec->Long\"}";
                if ($i ++ < $num_items)
                    $coords .= ",";
            }
        }
        $coords .= ']';

        $this->coords = $coords;
        // Requirements::javascriptTemplate(MODULE_CONTACT_DIR . '/javascript/gmap.js', array('coords' => $coords));

    }

    public function coords() {
        return $this->coords;
    }

}
