<?
$item = $this->item;
$title = $item['id'] ? 'Edit Post' : 'Create Post';
$title = $this->_($title);
$method = $item['id'] ? 'put' : 'post';
$this->headTitle($title, 'SET');
$this->textDelay('breadcrumbText', $title);

if($this->form){
	$form = $this->form;
} else {
    if($item['id']) {
        $form = new Blog\Form\PostEditForm();
    } else {
        $form = new Blog\Form\PostCreateForm();
    }
}
$form->useSubFormGroup()
     ->setMethod($item['id'] ? 'put' : 'post')
     ->setView($this)
     ->setAction($this->uri('/admin/blog/'))
     ->bind($item)
     ->prepare();

$tags = isset($item['Tags']) ? $item['Tags'] : array();
?>
<div class="row">
    <form <?=$this->formAttr($form)?>>
        <?=$form->restful();?>
        <?=$form->helper('id');?>
        <div class="span10">
            <div class="slate">
                <div class="page-header">
                    <?if($item['id']):?>
                    <div class="btn-group pull-right">
                        <a href="<?=$this->uri('/pages/' . $item['urlName'])?>" class="btn"><?=$this->_('View')?></a>
                        <a href="<?=$this->uri('/admin/blog/create')?>" class="btn"><?=$this->_('Clear Cache')?></a>
                        <a href="<?=$this->uri('/admin/blog/remove/' . $item['id'], 'c', array('c' => $this->uri('/admin/blog/' . $item['id']))); ?>" class="btn"><?=$this->_('Delete')?></a>
                    </div>
                    <?endif?>
                    <h2><?=$title?></h2>
                </div>
                <fieldset class="">
                    <div class="control-group <?=$form->isError('title') ? 'error' : '';?>">
                        <?=$form->helper('title', 'label', array('class' => 'control-label'))?>
                        <div class="controls docs-input-sizes">
                            <?=$form->helper('title', array('class' => 'span9'))?>
                            <div class="help-block"><?=$form->helper('title', 'formElementErrors')?></div>
                        </div>
                    </div>

                    <div class="control-group <?=$form->isError('urlName') ? 'error' : '';?>">
                        <?=$form->helper('urlName', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <div class="input-prepend input-append">
                                <span class="add-on"><?=$this->serverUrl() . '/pages/'?></span><?=$form->helper('urlName', array('class' => 'span6'))?><span class="add-on">/</span>
                            </div>
                            <div class="help-block"><?=$this->_('No input will create a random url')?></div>
                            <div class="help-block"><?=$form->helper('urlName', 'formElementErrors')?></div>
                        </div>
                    </div>

                    <div class="control-group <?=$form->isError(array('Text', 'content')) ? 'error' : '';?>">
                        <div id="editor-left" class="controls">
                            <!--
                            <div class="btn-toolbar markdown-toolbar">
                                <div class="btn-group">
                                    <span class="btn"  data-original-title="Bold - Ctrl+B"><i class="icon-bold"></i></span>
                                    <span class="btn"  data-original-title="Italic - Ctrl+I"><i class="icon-italic"></i></span>
                                </div>
                                <div class="btn-group">
                                    <span class="btn"  data-original-title="Link - Ctrl+L"><i class="icon-link"></i></span>
                                    <span class="btn"  data-original-title="Blockquote - Ctrl+Q"><i class="icon-blockquote"></i></span>
                                    <span class="btn"  data-original-title="Code Sample - Ctrl+K"><i class="icon-code"></i></span>
                                    <span class="btn"  data-original-title="Image - Ctrl+G"><i class="icon-picture"></i></span>
                                </div>
                                <div class="btn-group">
                                    <span class="btn"  data-original-title="Numbered List - Ctrl+O"><i class="icon-list"></i></span>
                                    <span class="btn"  data-original-title="Bulleted List - Ctrl+U"><i class="icon-bullet-list"></i></span>
                                    <span class="btn"  data-original-title="Heading - Ctrl+H"><i class="icon-header"></i></span>
                                    <span class="btn"  data-original-title="Horizontal Rule - Ctrl+R"><i class="icon-hr-line"></i></span>
                                </div>
                                <div class="btn-group">
                                    <span class="btn"  data-original-title="Undo - Ctrl+Z" disabled=""><i class="icon-undo"></i></span>
                                    <span class="btn"  data-original-title="Redo - Ctrl+Y" disabled=""><i class="icon-share-alt"></i></span>
                                </div>
                                <div class="btn-group">
                                    <span class="btn fullscreen" data-original-title="Full Screen"><i class="icon-fullscreen"></i></span>
                                </div>
                            </div>
                            -->
                            <?=$form->helper(array('Text', 'content'), 'formTextarea', array('class' => 'input-block-level', 'rows' => '15',))?>
                        </div>
                        <div class="accordion">
                            <div class="accordion-group">
                                <div class="accordion-heading">
                                    <a class="accordion-toggle" data-toggle="collapse" href="#collapse-preview">
                                        Preview
                                    </a>
                                </div>
                                <div id="collapse-preview" class="accordion-body collapse">
                                    <div class="accordion-inner">
                                        <div id="markdown-preview" class="typo typocn">

                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="accordion-group">
                                <div class="accordion-heading">
                                    <a class="accordion-toggle" data-toggle="collapse" href="#collapse-preview-html">
                                        Preview Html
                                    </a>
                                </div>
                                <div id="collapse-preview-html" class="accordion-body collapse">
                                    <div class="accordion-inner">
                                        <pre id="preview-html">
                                        </pre>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="help-block"><?=$form->helper(array('Text', 'content'), 'formElementErrors')?></div>

                    </div>
                </fieldset>
            </div>
        </div><!--span10 end-->

        <div class="span5">
            <div class="slate">
                <div class="page-header">
                    <h3><?=$this->_('Post Setting')?></h3>
                </div>



                <fieldset class="form-horizontal">

                    <div class="control-group <?=$form->isError('status') ? 'error' : '';?>">
                        <?=$form->helper('status', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper('status', 'formSelect', array('class' => ''))?>
                            <div class="help-block"><?=$form->helper('status', 'formElementErrors')?></div>
                        </div>
                    </div>

                    <div class="control-group <?=$form->isError('codeType') ? 'error' : '';?>">
                        <?=$form->helper('codeType', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper('codeType', 'formRadio', array('class' => 'checkbox inline'))?>
                            <div class="help-block"><?=$form->helper('codeType', 'formElementErrors')?></div>
                        </div>
                    </div>
                    <div class="control-group <?=$form->isError('visibility') ? 'error' : '';?>">
                        <?=$form->helper('visibility', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper('visibility', 'formSelect', array('class' => ''))?>
                            <div class="help-block"><?=$form->helper('visibility', 'formElementErrors')?></div>
                        </div>
                    </div>
                    <div class="control-group <?=$form->isError('language') ? 'error' : '';?>">
                        <?=$form->helper('language', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper('language', 'formSelect', array('class' => ''))?>        
                            <div class="help-block"><?=$form->helper('language', 'formElementErrors')?></div>
                        </div>
                    </div>
                    <div class="control-group <?=$form->isError('flag') ? 'error' : '';?>">
                        <?=$form->helper('flag', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper('flag', array('class' => 'span1'))?>        
                            <div class="help-block"><?=$form->helper('flag', 'formElementErrors')?></div>
                        </div>
                    </div>
                </fieldset>
            </div>
        </div><!--span5 end-->

        <div class="span5">
            <div class="slate">
                <div class="page-header">
                    <h3><?=$this->_('Comment Setting')?></h3>
                </div>
                <fieldset class="form-horizontal">

                    <div class="control-group <?=$form->isError('commentStatus') ? 'error' : '';?>">
                        <?=$form->helper('commentStatus', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper('commentStatus', 'formSelect', array('class' => ''))?>        
                            <div class="help-block"><?=$form->helper('commentStatus', 'formElementErrors')?></div>
                        </div>
                    </div>
                    <div class="control-group <?=$form->isError('postPassword') ? 'error' : '';?>">
                        <?=$form->helper('postPassword', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper('postPassword', array('class' => ''))?>        
                            <div class="help-block"><?=$form->helper('postPassword', 'formElementErrors')?></div>
                        </div>
                    </div>
                    <div class="control-group <?=$form->isError('commentType') ? 'error' : '';?>">
                        <?=$form->helper('commentType', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper('commentType', 'formSelect', array('class' => ''))?>        
                            <div class="help-block"><?=$form->helper('commentType', 'formElementErrors')?></div>
                        </div>
                    </div>
                </fieldset>
            </div>
        </div><!--span5 end-->

        <div class="span5">
            <div class="slate">
                <div class="page-header">
                    <h3><?=$this->_('Category And Tags')?></h3>
                </div>
                <fieldset class="form-horizontal">
                    <div class="control-group <?//=$form->isError(array('CategoryPost', 'category_id')) ? 'error' : '';?>">
                        <?//=$form->helper(array('CategoryPost', 'category_id'), 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?//=$form->helper(array('CategoryPost', 'category_id'), 'formSelect', array(
                              //  'value_options' => $this->action('Blog\Api\Controller\CategoryController', 'selectAction'),
                            //), array('replace' => false, 'i18n' => false))?>
                            <?//=$form->helper(array('CategoryPost', 'post_id'), 'formHidden', array(
                              //  'value' => $item['id']
                            //))?>    
                            <div class="help-block"><?//=$form->helper(array('CategoryPost', 'category_id'), 'formElementErrors')?></div>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">Tags</label>
                        <div class="controls">
                            <?$tagForm = $form->get('Tags')->get('0');?>
                            <?=$tagForm->helper('tagName', array('id' => 'tagging', 'class' => 'input-block-level', 'value' => $this->tagging($tags)->toNameString()))?> 
                        </div>
                    </div>
                </fieldset>
            </div>
        </div><!--span5 end-->
       
        <?if($this->hasModule('File')):?>
        <div class="span5">
            <div class="slate">
                <div class="page-header">
                    <h2><?=$this->_('Connect Images')?></h2>
                </div>
                <div class="well">
                    <?if($item['PostCover']):?>
                    <img id="post-image" src="<?=$this->thumb($item['PostCover'][0]['Thumb'], array('h_250'))?>" alt="" />
                    <?else:?>
                    <img id="post-image" src="http://placehold.it/260x180" alt="" />
                    <?endif?>
                    <?=$form->helper(array('FileConnect', 'file_id'), 'formHidden')?>
                </div>
                <a id="connect-image" href="<?=$this->uri('/api/file/')?>" class="btn"><?=$this->_('Select Image')?></a>
            </div>
        </div><!--span5 end-->
        <?endif?>

        <div class="span10">
            <div class="slate">
                <div class="page-header">
                    <h3><?=$this->_('SEO Setting')?></h3>
                </div>
                <fieldset class="">
                    <div class="control-group <?=$form->isError(array('Text', 'metaKeywords')) ? 'error' : '';?>">
                        <?=$form->helper(array('Text', 'metaKeywords'), 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper(array('Text', 'metaKeywords'), array('class' => 'span9'))?>        
                            <div class="help-block"><?=$form->helper(array('Text', 'metaKeywords'), 'formElementErrors')?></div>
                        </div>
                    </div>
                    <div class="control-group <?=$form->isError(array('Text', 'metaDescription')) ? 'error' : '';?>">
                        <?=$form->helper(array('Text', 'metaDescription'), 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper(array('Text', 'metaDescription'), 'formTextarea', array('class' => 'span9'))?>        
                            <div class="help-block"><?=$form->helper(array('Text', 'metaDescription'), 'formElementErrors')?></div>
                        </div>
                    </div>
                </fieldset>
            </div>
        </div><!--span10 end-->

        <div class="span10 listing-buttons">
            <button id="save-draft" class="btn btn-info btn-large"><?=$this->_('Save As Draft')?></button>
            <button id="save-publish" class="btn btn-success btn-large"><?=$this->_('Save')?></button>
        </div>
    </form>
</div>


<script>
eva.ready(function(){
      
    eva.callback.connect = function(item, parentWindow){
        $("#file-form-fileconnectform-file-id").val(item.attr("data-connect-id"));
        var data = $.parseJSON(item.attr('data-connect-json'));
        $("#post-image").attr("src", data.Thumb);
        $.fn.colorbox.close();
    }
    eva.loadcss(eva.s('/lib/js/jquery/colorbox/colorbox.css'));
    eva.loader(eva.s('/lib/js/jquery/colorbox/jquery.colorbox.js'), function(){
        $("#connect-image").colorbox({
            iframe:true,
                width:"80%",
                height:"80%"
        });
    });

	eva.loadcss(eva.s('/lib/js/jquery/jquery.select2/select2.css'));
	eva.loader(eva.s('/lib/js/jquery/jquery.select2/select2.js'), function(){
            $('#tagging').select2({
                    tags : <?=$this->json($this->tagging($tags)->toNameArray())?>
            });
	});

    $("#save-draft").on('click', function(){
        $("#blog-form-posteditform-status").val('draft');
    });

    var editor = $("#blog-form-textform-content");
    var editorPreview = $("#markdown-preview");
    var editorPreviewHtml = $("#preview-html");

    var editorMd;
    var mdInited = false;
    var initMd = function(_editor){
        if(true === mdInited) {
            return;
        }
        eva.loadcss(eva.s(['/lib/js/codemirror/lib/codemirror.css', '/lib/js/codemirror/theme/ambiance.css']));
        eva.loader(eva.s(['/lib/js/codemirror/lib/codemirror.js', '/lib/js/codemirror/mode/xml/xml.js', '/lib/js/codemirror/mode/markdown/markdown.js', '/lib/js/showdown/showdown.js', '/lib/js/js-markdown-extra/js-markdown-extra.js']), function(){
            mdInited = true;
            builtMdEditor(_editor);
        });
    }
    var builtMdEditor = function(_editor){
        if(!mdInited){
            initMd(_editor); 
            return;
        }
        editorMd = CodeMirror.fromTextArea(_editor[0], {
            "mode":"markdown",
                "theme":"ambiance",
                "lineNumbers":true,
                "lineWrapping":true,
                onChange : function(cm){
                        //var html = Markdown(cm.getValue());
                        //editorPreview.html(html);
                }
        });	
    }


    $("#collapse-preview").on('show', function () {
         var html = Markdown(editorMd.getValue());
         editorPreview.html(html);
    });

    $("#collapse-preview-html").on('show', function () {
            function htmlencode(s){  
                    var div = document.createElement('div');  
                    div.appendChild(document.createTextNode(s));  
                    return div.innerHTML;  
            }  
            $("#preview-html").html(htmlencode(editorPreview.html()));
    });



    var removeMdEditor = function(){
            if(!editorMd){
                    return;
            }
            editorMd.toTextArea();
    }


    var editorHtml;
    var htmlInited = false;
    var initHtml = function(_editor){
            if(true === htmlInited) {
                    return;
            }
            eva.loader(eva.s(["/lib/js/tiny_mce/jquery.tinymce.js"]), function(){
                    htmlInited = true;
                    builtHtmlEditor(_editor);
            });
    }
    var builtHtmlEditor = function(_editor){
            if(!htmlInited){
                    initHtml(_editor); 
                    return;
            }

			var mceGlobelConfig = {
				mode : "textareas",
				theme : "advanced",
				plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

				// Theme options
				theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
				theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
				theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
				theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : true,
				
				remove_linebreaks : false,
				extended_valid_elements : "pre[cols|rows|disabled|name|readonly|class]",
				script_url : eva.s('/lib/js/tiny_mce/tiny_mce.js'),
				
				content_css: eva.s("/lib/css/typo/typo.min.css"),
				spellchecker_rpc_url : eva.s('/lib/js/tiny_mce/plugins/spellchecker/rpc.php')
			};

            var mceconfig = mceGlobelConfig;
            editorHtml = _editor.tinymce(mceconfig);
    }

    var removeHtmlEditor = function(_editor){
            if(!editorHtml){
                return;
            }
            tinyMCE.execCommand('mceToggleEditor', false, _editor.attr('id'));
    }

    var switchEditor = function(){
            var codeType = $("input[name='codeType']:checked").val();
            if(codeType == 'markdown'){
                    removeHtmlEditor(editor);
                    builtMdEditor(editor); 
            } else if(codeType == 'html'){
                    removeMdEditor(editor);
                    builtHtmlEditor(editor);
            } else {
                    removeHtmlEditor(editor);
                    removeMdEditor(editor);
            }
    }
    switchEditor();
    $("input[name='codeType']").on("change", function(){
            if(confirm('Content will be changed, are you sure ?')){
                switchEditor(); 
            }
    });
});
</script>
