<?
$item = $this->item;
$title = $item['id'] ? 'Edit Group' : 'Create Group';
$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 Group\Form\GroupEditForm();
    } else {
        $form = new Group\Form\GroupCreateForm();
    }
}
$form->useSubFormGroup()
     ->setMethod($item['id'] ? 'put' : 'post')
     ->setView($this)
     ->setAction($this->uri('/admin/group/'))
     ->bind($item)
     ->prepare();

$tags = isset($item['Tags']) ? $item['Tags'] : array();
?>

<input id="flash-messenger" type="hidden" value="<?=is_array($this->flashMessenger) ? implode(',', $this->flashMessenger) : ''?>" />
<div id="group-create-succeed" class="alert alert-success hide">
    <a href="#" data-dismiss="alert" class="close">x</a>
    <h4 class="alert-heading"><?=$this->_('New Group Created')?></h4>
</div>

<div id="group-edit-succeed" class="alert alert-success hide">
    <a href="#" data-dismiss="alert" class="close">x</a>
    <h4 class="alert-heading"><?=$this->_('Group Edit Succeed')?></h4>
</div>

<div id="group-edit-failed" class="alert alert-error hide">
    <a href="#" data-dismiss="alert" class="close">x</a>
    <h4 class="alert-heading"><?=$this->_('Group Edit Failed')?></h4>
</div>



<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('/group/' . $item['groupKey'])?>" class="btn"><?=$this->_('View')?></a>
                        <a href="<?=$this->uri('/admin/group/create')?>" class="btn"><?=$this->_('Clear Cache')?></a>
                        <a href="<?=$this->uri('/admin/group/remove/' . $item['id'], 'c', array('c' => $this->uri('/admin/group/' . $item['id']))); ?>" class="btn"><?=$this->_('Delete')?></a>
                    </div>
                    <?endif?>
                    <h2><?=$title?></h2>
                </div>
                <fieldset class="">
                    <div class="control-group <?=$form->isError('groupName') ? 'error' : '';?>">
                        <?=$form->helper('groupName', 'label', array('class' => 'control-label'))?>
                        <div class="controls docs-input-sizes">
                            <?=$form->helper('groupName', array('class' => 'span9'))?>
                            <div class="help-block"><?=$form->helper('groupName', 'formElementErrors')?></div>
                        </div>
                    </div>

                    <div class="control-group <?=$form->isError('groupKey') ? 'error' : '';?>">
                        <?=$form->helper('groupKey', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <div class="input-prepend input-append">
                                <span class="add-on"><?=$this->serverUrl() . '/group/'?></span><?=$form->helper('groupKey', 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('groupKey', 'formElementErrors')?></div>
                        </div>
                    </div>

                    <div class="control-group <?=$form->isError(array('Text', 'content')) ? 'error' : '';?>">
                        <div id="editor-left" class="controls">
                            <?=$form->helper(array('Text', 'content'), 'formTextarea', array('class' => 'span9', 'rows' => '15',))?>
                        </div>
                        <div id="editor-right" class="markdown-preview"></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->_('Group 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('summary') ? 'error' : '';?>">
                        <?=$form->helper('summary', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper('summary', array('class' => 'span3'))?>        
                            <div class="help-block"><?=$form->helper('summary', 'formElementErrors')?></div>
                        </div>
                    </div>

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

                    <div class="control-group <?=$form->isError('memberEnable') ? 'error' : '';?>">
                        <?=$form->helper('memberEnable', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper('memberEnable', 'formSelect', array('class' => ''))?>        
                            <div class="help-block"><?=$form->helper('memberEnable', '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->_('Tags')?></h3>
                </div>

                <fieldset class="form-horizontal">
                    <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--> 

        <div class="span10">
            <div class="slate">
                <div class="page-header">
                    <h3><?=$this->_('Categories')?></h3>
                </div>
                <?foreach($form->get('CategoryGroup') as $subForm):?>
                <?$cate = $subForm->getCategory();if(!$cate){continue;}?>
                <fieldset class="form-horizontal">
                    <div class="control-group <?=$subForm->isError('category_id') ? 'error' : '';?> span3">
                        <?=$subForm->helper('category_id', 'label', array(
                            'class' => 'control-label',
                            'label' => $cate['categoryName'],
                        ))?>
                        <div class="controls">
                            <?=$subForm->helper('category_id', 'formCheckbox', array(
                                'class' => '',
                                'checkedValue' => $cate['id'],
                                'checked' => $subForm->get('group_id')->getValue() ? true : false
                            ))?>
                            <div class="help-block"><?=$subForm->helper('category_id', 'formElementErrors')?></div>
                        </div>
                    </div>
                </fieldset>
                <?endforeach?>
            </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['File']):?>
                    <img id="post-image" src="<?=$this->thumb($item['File'][0]['Thumb'], array('h_250'))?>" alt="" />
                    <?else:?>
                    <img id="post-image" src="http://placehold.it/260x180" alt="" />
                    <?endif?>
                    <?=$form->helper(array('GroupFile', '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 listing-buttons">
            <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){
        $("#group-form-groupfileform-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 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']), 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(){
                }
        });	
    }
    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);
            }
    }
    switchEditor();
    $("input[name='codeType']").on("change", function(){
            if(confirm('Content will be changed, are you sure ?')){
                switchEditor(); 
            }
    });
});
</script>
