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

?>

<div class="row">
    <form <?=$this->formAttr($form)?>>
        <?=$form->restful();?>
        <?=$form->helper('id');?>
        <div class="span10">
            <div class="slate">
                <?if($item['id']):?>
                <div class="btn-group pull-right">
                    <a href="<?=$this->uri('/album/' . $item['urlName'])?>" class="btn"><?=$this->_('View')?></a>
                    <a href="<?=$this->uri('/admin/album/create')?>" class="btn"><?=$this->_('Create New')?></a>
                    <a href="<?=$this->uri('/admin/album/remove/' . $item['id'], 'c', array('c' => $this->uri('/admin/album/' . $item['id']))); ?>" class="btn"><?=$this->_('Delete')?></a>
                </div>
                <ul class="nav nav-tabs">
                    <li class="active">
                    <a href="<?=$this->uri('/admin/album/' . $item['id'])?>"><?=$this->_('Album Basic Info')?></a>
                    </li>
                    <li><a href="<?=$this->uri('/admin/album/upload/' . $item['id'])?>"><?=$this->_('Upload Photo')?></a></li>
                    <li><a href="<?=$this->uri('/admin/album/image/' . $item['id'])?>"><?=$this->_('Photo Management')?></a></li>
                </ul>
                <?else:?>
                    <div class="page-headr">
                        <h2><?=$title?></h2>
                    </div>
                <?endif?>
                <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() . '/album/'?></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('description') ? 'error' : '';?>">
                        <div id="editor-left" class="controls">
                            <?=$form->helper('description', 'formTextarea', array('class' => 'span9', 'rows' => '15',))?>
                        </div>
                        <div id="editor-right" class="markdown-preview"></div>
                        <div class="help-block"><?=$form->helper('description', 'formElementErrors')?></div>

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

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



                <fieldset class="form-horizontal">

                    <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('visitPassword') ? 'error' : '';?>">
                        <?=$form->helper('visitPassword', 'label', array('class' => 'control-label'))?>
                        <div class="controls">
                            <?=$form->helper('visitPassword', array('class' => 'span3'))?>        
                            <div class="help-block"><?=$form->helper('visitPassword', 'formElementErrors')?></div>
                        </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('CategoryAlbum') 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('album_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->_('Set Cover')?></h2>
                </div>
                <div class="well">
                    <?if($item['Cover']):?>
                    <img id="post-image" src="<?=$this->thumb($item['Cover']['Thumb'], array('h_250'))?>" alt="" />
                    <?else:?>
                    <img id="post-image" src="http://placehold.it/260x180" alt="" />
                    <?endif?>
                </div>
                <a id="connect-image" href="<?=$this->uri('/admin/album/image/' . $item['id'])?>" 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%"
                    });
            });


            $("#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>
