<?php
//
//  Comic Calendar Generator
//  -------------------
//  - Author: Steve H <http://comiccms.com/>
//  - License: GPL 3 <http://www.gnu.org/copyleft/gpl.html>
//  - Created: April 2009
//  - Updated: April 2009
//
//  Designed for ComicCMS 0.1.9b <http://comiccms.com/>
//
class pl_comiccalendar extends ComicCMS {
    var $id = 'comiccalendar';
    var $version = '0.1';
    var $forversion = array('0.1.9alpha7','0.1.9b','0.2RC1','0.2');
    var $template = true;
    
    var $lang = array(
        '_lang'=>'en',
        'en'=>array(
            '_title'=>'Comic Calendar',
            '_desc'=>'Creates monthly calendar pages with comic links on them',
            '_author'=>'Steve H',
            
            'mainpage'=>'This plugin creates a calendar table for your comic site, it can only link to one comic per day so is best suited for use on sites with one or less comic per day. To use it place {{plugin:comiccalendar}} anywhere in your templates. By default if put anywhere {{comic}} variables are available it will show the month that comic was added, otherwise it will show the calendar page of the most recent month a comic was added. ',
            
            'usagetitle'=>'Other Usage',
            'usagemanual'=>'<strong>To show a manual month:</strong> Give the plugin the argument of a 4 digit year, followed by a dot and then a 2 digit month. e.g: {{plugin:comiccalendar|2009.04}} will display April 2009.',
            'usagearchive'=>'<strong>To show all months:</strong> Use {{plugin:comiccalendar|archive}}',
            'usagecurrent'=>'<strong>To show the most recent month:</strong> Use {{plugin:comiccalendar|current}}',
            
            'csstitle'=>'Styling the calendar',
            'cssexplain'=>'You can edit the HTML the calendar uses through the edit plugin page, however that is quite advanced and usually unnecessary. If you want to style the calendar then copy the following CSS onto the end of your CSS template page and edit the styles to your liking.',
            
            'montitle'=>'Starting the calendar on Sunday',
            'monexplain'=>'Want to have the calendar weekdays start on Sunday instead of Monday? Can do. Go to the edit plugin page and untick the "Start week on Monday" checkbox. You will also need to edit the "Head Template" there to reflect this change. Move the <span style="font-size:80%; color:#282;">&lt;th for="col" title="Sunday"&gt;S&lt;/th&gt;</span> from just before the second &lt;/tr&gt; to just after the second &lt;tr&gt;',
            
            'startmon'=>'Start week on Monday (otherwise Sunday)',
            
            'head'=>'Head Template',
            'padding'=>'Padding Template',
            'rowdivide'=>'Row-divide Template',
            'daycomic'=>'Day Template (with a comic - use any {{comic_*}} variables)',
            'dayblank'=>'Day Template (without a comic - use {{date_*}} variables)',
            'foot'=>'Foot Template',
            
            'archivepre'=>'In archive mode - before each calendar',
            'archivepost'=>'In archive mode - after each calendar',
            
            'delete'=>'Be sure to erase all mention of {{plugin:comiccalendar}} from your templates before deleting.',
        ),
    );
    
    
    
    var $settings = array(
        'startmon'=>true,
        'template'=>array(
            'head'=>
'<table class="comiccalendar">
<tr class="comiccalendar_title"><th colspan="7">{{date_month:name}} {{date_year:pad}}</th></tr>
<tr class="comiccalendar_weekdays"><th for="col" title="Monday">M</th><th for="col" title="Tuesday">T</th><th for="col" title="Wednesday">W</th><th for="col" title="Thursday">T</th><th for="col" title="Friday">F</th><th for="col" title="Saturday">S</th><th for="col" title="Sunday">S</th></tr>
<tr>',
            'foot'=>'</tr></table>',
            'padding'=>'<td class="comiccalendar_pad"></td>',
            'rowdivide'=>'</tr><tr>',
            'daycomic'=>'<td class="comiccalendar_comicday"><a href="http:///?id={{comic_id}}" title="{{comic_title}}">{{comic_day:unpad}}</a></td>',
            'dayblank'=>'<td class="comiccalendar_blankday" title="No comic">{{date_day}}</td>',
            
            'archivepre'=>'<div class="comiccalendar_archivebox">',
            'archivepost'=>'</div>',
        ),
    );
    
    
    
    
    ////////////////////////////////////////////////////////////
    // Generate default form fields
    ////////////////////////////////////////////////////////////
    function fields($switch) {
        switch ($switch) {
            case 'edit':
                return array(
                    'startmon'=>array('type'=>'checkbox','title'=>$this->lang('startmon')),
                    
                    'head'=>array('type'=>'textarea','title'=>$this->lang('head'),'class'=>'resizeTextarea'),
                    'padding'=>array('type'=>'textarea','title'=>$this->lang('padding'),'class'=>'resizeTextarea','rows'=>1),
                    'rowdivide'=>array('type'=>'textarea','title'=>$this->lang('rowdivide'),'class'=>'resizeTextarea','rows'=>1),
                    'daycomic'=>array('type'=>'textarea','title'=>$this->lang('daycomic'),'class'=>'resizeTextarea','rows'=>1),
                    'dayblank'=>array('type'=>'textarea','title'=>$this->lang('dayblank'),'class'=>'resizeTextarea','rows'=>1),
                    'foot'=>array('type'=>'textarea','title'=>$this->lang('foot'),'class'=>'resizeTextarea'),
                    
                    'archivepre'=>array('type'=>'textarea','title'=>$this->lang('archivepre'),'class'=>'resizeTextarea'),
                    'archivepost'=>array('type'=>'textarea','title'=>$this->lang('archivepost'),'class'=>'resizeTextarea'),
                );
                break;
        }
    }
    
    
    function d_use($admin) {
        $admin->addline('<p>'.$this->lang('mainpage').'</p>');
        
        $admin->addline('<div id="accordian" style="width:750px; margin:30px auto;">');
        
		$admin->addline('<h2>'.$this->lang('usagetitle').'</h2>');
        $admin->addline('  <div class="accordian">');
        $admin->addline('    <p>'.$this->lang('usagemanual').'</p>');
        $admin->addline('    <p>'.$this->lang('usagearchive').'</p>');
        $admin->addline('    <p>'.$this->lang('usagecurrent').'</p>');
        $admin->addline('  </div>');
        
        $admin->addline('<h2>'.$this->lang('montitle').'</h2>');
        $admin->addline('  <div class="accordian">');
        $admin->addline('    <p>'.$this->lang('monexplain').'</p>');
        $admin->addline('  </div>');
        
        $admin->addline('<h2>'.$this->lang('csstitle').'</h2>');
        $admin->addline('  <div class="accordian">');
        $admin->addline('    <p>'.$this->lang('cssexplain').'</p>');
        $admin->addline('    <pre style="padding:2px 10px; border:solid 1px; font-size:10px;">
.comiccalendar {
    width:100%;
    border:dashed 1px;
    font-size:12px;
    text-align:center;
}
.comiccalendar_title th {
    background-color:#eee;
}
.comiccalendar_weekdays th {
    
}
.comiccalendar_pad {
    border:none 0px;
}
.comiccalendar_comicday {
    font-weight:bold;
    border:solid 1px;
}
.comiccalendar_comicday a {
    display:block;
    color:#a54;
    text-decoration:none;
}
.comiccalendar_comicday a:hover {
    background-color:#eee;
}
.comiccalendar_blankday {
    color:#888;
}
.comiccalendar_archivebox {
    float:left;
    width:180px;
    height:180px;
    padding:10px 20px;
}
</pre>');
        $admin->addline('  </div>');
        
        $admin->addjavascript('new Accordion($(\'accordian\').getElements(\'h2\'),$(\'accordian\').getElements(\'div.accordian\'), {
		opacity: 0,
		onActive: function(h) {h.setStyles({\'cursor\':\'default\',\'background-color\':\'#fff\'});},
		onBackground: function(h) {h.setStyles({\'cursor\':\'pointer\',\'background-color\':\'#eef\'});}
	});');
    }
    
    
    function d_edit($admin,$data=false) {
        $this->settings = ($data?$data:array_merge($this->settings,$this->settings['template']));
        $admin->genform($this->fields('edit'),$this->settings);
    }
    function p_edit($admin,$data) {
        if (!$admin->readform($data,$this->fields('edit'))) return false;
        
        foreach ($data as $key => $value) {
            if (isset($this->settings[$key])) $this->settings[$key] = $value;
            if (isset($this->settings['template'][$key])) $this->settings['template'][$key] = $value;
        }
        $this->save();
        return true;
    }
    
    
    function d_delete($admin,$data=false) {
        $admin->addwarning($this->lang('delete'));
        $admin->genform(array('fullremove'=>'checkbox'),array());
    }
    function p_delete($admin,$data) {
        if (!$admin->readform($data,array('fullremove'=>'checkbox'))) return false;
        
        $this->delete($data['fullremove']);
        return true;
    }
    
    
    
    
    
    
    
    
    
    function cacherebuild($extra=false,$tpl=false) {
        
        
        
        
        $comiccpu = load_cpu('comic');
        
        if (!$tpl) {
            $cache = true;
            
            // Load all comics in tpl as date based cannot guarantee cache regen on comic edit... or something like that
            import('.../lib/site/template.php');
            $tpl = new site_template;
            $tpl->get('comic','range','+0','-0');
        } else $cache = false;
        
        
        // Archive of calendars
        if ($extra=='archive') {
            $minyear = date('Y',$tpl->items['comic'][min(array_keys($tpl->items['comic']))]['timestamp']);
            $minmonth = date('m',$tpl->items['comic'][min(array_keys($tpl->items['comic']))]['timestamp']);
            
            $maxyear = date('Y',$tpl->items['comic'][max(array_keys($tpl->items['comic']))]['timestamp']);
            $maxmonth = date('m',$tpl->items['comic'][max(array_keys($tpl->items['comic']))]['timestamp']);
            
            $content = '';
            
            while ($maxyear.$maxmonth >= $minyear.$minmonth) {
                $content .= $tpl->parse($this->settings['template']['archivepre'],'date',array('timestamp'=>date('U',mktime(0,0,0,$maxmonth,1,$maxyear)))) . "\n";
                $content .= $this->cacherebuild($maxyear.'.'.$maxmonth,&$tpl);
                $content .= $tpl->parse($this->settings['template']['archivepost'],'date',array('timestamp'=>date('U',mktime(0,0,0,$maxmonth,1,$maxyear)))) . "\n";
                
                $maxmonth--;
                if ($maxmonth < 1) {
                    $maxyear--;
                    $maxmonth = 12;
                }
                if (strlen($maxmonth)==1) $maxmonth = '0'.$maxmonth;
            }
            
            $tpl->addcache($content,'pl_'.$this->id,'archive');
            
            return $content;
        }
        
        // Get year/month from input
        $good = false;
        if ($extra) {
            $year = substr($extra,0,strpos($extra,'.'));
            if (strlen($year)==4) {
                $month = substr($extra,strpos($extra,'.')+1);
                if (strlen($month)==2) $good = true;
            }
        }
        if (!$good) {
            $year = date('Y',$tpl->items['comic'][max(array_keys($tpl->items['comic']))]['timestamp']);
            $month = date('m',$tpl->items['comic'][max(array_keys($tpl->items['comic']))]['timestamp']);
        }
        
        // Get data from month
        $daysinmonth = date('t',mktime(0,0,0,$month,1,$year));
        $min = date('U',mktime(0,0,0,$month,1,$year));
        $max = date('U',mktime(23,59,59,$month,$daysinmonth,$year));
        
        // Index comics in this month (max 1 per day)
        $days = array();
        foreach ($tpl->items['comic'] as $k => $comic) {
            if ( ($comic['timestamp'] <= $max) && ($comic['timestamp'] >= $min) ) {
                $days[date('j',$comic['timestamp'])] = &$tpl->items['comic'][$k];
            }
        }
        
        
        $content = $tpl->parse($this->settings['template']['head'],'date',array('timestamp'=>date('U',mktime(0,0,0,$month,1,$year)))) . "\n";
        
        // Padding
        $w = date('w',$min);
        if ($this->settings['startmon']) {
            $w--;
            if ($w<0) $w=6;
        }
        for ($p=0;$p<$w;$p++) $content .= $this->settings['template']['padding'];
        
        // Each Day
        for ($d=1;$d<=$daysinmonth;$d++) {
            if ($w > 6) {
                $content .= $this->settings['template']['rowdivide'];
                $w=0;
            }
            $w++;
            
            $id = false;
            if (isset($days[$d])) {
                $content .= $tpl->parse($this->settings['template']['daycomic'],'comic',$days[$d]) . "\n";
            } else {
                $content .= $tpl->parse($this->settings['template']['dayblank'],'date',array('timestamp'=>date('U',mktime(0,0,0,$month,$d,$year)))) . "\n";
            }
        }
        $content .= $tpl->parse($this->settings['template']['foot'],'date',array('timestamp'=>date('U',mktime(0,0,0,$month,1,$year))));
        
        if ($cache) $tpl->addcache($content,'pl_'.$this->id,$year.'.'.$month);
        
        return $content;
    }
    
    function plugintpl($extra) {
        return '{{plugincache:comiccalendar|'.($extra?$extra:'{{comic_year:pad}}.{{comic_month:pad}}').'}}';
    }
}
?>