window.pageset_btn_hide=0;
var $pageset_head_nav=$('.pageset-head-nav'),
    $page_iframe=$('.page-iframe'),
    $btn_common_modal=$('.btn-pageset-common-modal'),
    pageset_modal={
        nav:'.pageset-nav-modal',
        img:'.pageset-img-modal',
        editor:'.pageset-editor-modal',
        block_config:'.pageset-block-config-modal',
        other_config:'.pageset-other-config-modal',
    };
window.mid_btn_position={};
// 可视化iframe部分
$page_iframe.load(function() {
    var $page_iframe_contents=$(this).contents(),
        page_iframe_window=$(this).prop('contentWindow'),
        page_iframe_document=page_iframe_window.document;
    // 添加文字编辑按钮和区块设置组件
    //  console.log(page_iframe_window);
    var pageset_html='<link rel="stylesheet" type="text/css" href="tpl/static/css/page_iframe.css">'
        +'<div class="pageeditor-btn">'
        +'<span class="pageeditor-remark" hidden data-url="" data-rows="3"></span>'
        +'<button class="btn btn-floating btn-success btn-xs p-0 pageeditor-editor"><i style="left: -2px;" class="icon wb-pencil" aria-hidden="true"></i></button>'
        +'</div>';
    $page_iframe_contents.find("html").append(pageset_html);
    $page_iframe_contents.pageinfo(page_iframe_window,page_iframe_document);// 页面输出值的标签处理
    if($('meta[name="generator"]',page_iframe_document).length && $('meta[name="generator"]',page_iframe_document).attr('content').indexOf('MetInfo')>=0){
        var new_url=page_iframe_window.location.href;
        // 更新iframe的动态url信息
        $page_iframe.attr({'data-dynamic':new_url});
        // 更新预览按钮链接
        new_url=new_url.replace('&pageset=1','').replace('?pageset=1','');
        $('.pageset-view').attr({href:new_url});
    }
    // 鼠标经过区块显示区块边界
    $(page_iframe_document).on('mouseover','*',function(e){

        var $block=$(e.target).closest("[m-id]"),
            index=$page_iframe_contents.find('[m-id]').index($block),
            $pageset_btns=$page_iframe_contents.find('html>.pageset-btns'),
            $pageset_btn=$pageset_btns.find('.pageset-btn[data-mid="'+$block.attr('m-id')+'"][data-index="'+index+'"]');
        //   alert('.pageset-btn[data-mid="'+$block.attr('m-id')+'"][data-index="'+index+'"]')
        $page_iframe_contents.find('[m-id]').removeClass('set-active');
        $block.addClass('set-active');
        $block.attr('m-id') && blocksetBtnPosition($block,$pageset_btn,index,page_iframe_window,$page_iframe_contents);
        pageset_btn_hide && $pageset_btn.is(':hidden') && $pageset_btns.find('.pageset-btn').hide() && $pageset_btn.show();
    });
    // 弹出区块内容框
    $page_iframe_contents.on('click','.pageset-btn .pageset-content',function(event) {
        var mid=$(this).attr('data-mid'),
            type=$(this).attr('data-type')||null,
            index=$(this).attr('data-index');

        if(type=='myads'){
            var url='admincp.php?c='+type+'&wei='+mid;
        }else if(type=='product'){
            var url='admincp.php?c='+type+'&tid=2';
        }else if(type=='article'){
            var url='admincp.php?c='+type+'&tid=1';
        }else if(type=='photo'){
            var url='admincp.php?c='+type+'&tid=3';
        }else if(type=='download'){
            var url='admincp.php?c='+type+'&tid=4';
        }else if(type=='hr'){
            var url='admincp.php?c='+type+'&tid=5';
        }else if(type=='about'){
            var url='admincp.php?c=about&a=edit&catid=26&id=3';
        }else if(type=='htmllabel'){
            var url='admincp.php?c=htmllabel&a=edit&id='+mid+'&page=1';
        }else {
            var url='admincp.php?c='+type;
        }
        layer.open({
            type: 2,
            title: '可视化编辑',
            shadeClose: true,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['893px', '600px'],
            content: url,
            end: function(){
                parent.location.reload();
            }
        });
    });

    // 文字、图片编辑
    var $pageeditor_btn=$page_iframe_contents.find('.pageeditor-btn'),
        $pageeditor_editor=$pageeditor_btn.find('.pageeditor-editor'),
        $pageeditor_remark=$pageeditor_btn.find('.pageeditor-remark');
    // 鼠标经过可编辑文字、图片显示编辑按钮
    $(page_iframe_document).on('mouseover','.editable-click,img[met-id],.met-icon',function(e){
        if($pageeditor_btn.find('.editable-container').length) return false;
        var obj=target='';
        if($(e.target).prop('tagName')=='IMG'){
            obj=target='img';
        }else if($(e.target).hasClass('editable-click_content')){
            obj='.met-icon';
            target='icon';
        }else{
            obj='.editable-click';
        }
        // alert(obj);
        var $self=$(e.target).closest(obj);
        if($self.parents('[m-type]').attr('m-type')=='displayimgs'){
            return false;
        }
        if(obj=='img' && typeof $self.attr('met-id')=='undefined'){
            return false;
        }
        if($self.parents('.met-editor').length){
            $self=$self.parents('[met-id]:eq(0)');
            obj='.met-editor';
            target='editor';
        }
        if($self.hasClass('met-editor')){
            obj='.met-editor';
            target='editor';
        }
        if($(e.target).parents('[met-id]:eq(0)').attr('met-table')=='column' && $(e.target).parents('[met-id]:eq(0)').attr('met-field')=='content'){
            $self=$(e.target).parents('[met-id][met-table="column"][met-field="content"]:eq(0)');
            obj='[met-id][met-table="column"][met-field="content"]';
            target='editor';
        }
        if($(e.target).attr('met-table')=='column' && $(e.target).attr('met-field')=='content'){
            $self=$(e.target);
            obj='[met-id][met-table="column"][met-field="content"]';
            target='editor';
        }

        var left=$self.offset().left,
            top=$self.offset().top,
            position_fixed=$self.css('position')=='fixed'?true:false;
         $self.parents().each(function(index, el) {
            if($(el).css('position')=='fixed'){
                position_fixed=true;
                return false;
            }
        });
        if(position_fixed){
            top-=$page_iframe_contents.scrollTop();
            var position='fixed';
        }else{
            var position='';
        }
        var type=$(this).attr('met-type');
        var id=$(this).attr('met-id');
        var content=$(this).attr('met-content');
        if(obj=='img') top+=$self.outerHeight()/2-10;
        $pageeditor_btn.css({left:left+$self.outerWidth()/2,top:top,position:position});
        typeof $.fn.editable=='function' && $pageeditor_remark.editable('hide');
        $pageeditor_editor.show().attr({'data-obj':obj,'data-type':type,'data-id':id,'data-content':content,'data-index':$page_iframe_contents.find(obj).index($self)});
        $btn_common_modal.attr({'data-target':(target?(target=='icon'?'.met-icon-modal':'.pageset-'+target+'-modal'):'')});
        $('.editable-click,img,.met-icon',page_iframe_document).removeClass('set');
        $self.addClass('set');
    });
    // 鼠标移出设置元素，隐藏设置元素外边框
    $(page_iframe_document).on('mouseout','.editable-click,img[met-id],.met-icon',function(e){

        if($pageeditor_btn.find('.editable-container').length){
            return false;
        }
        var obj='';
        if($(e.target).prop('tagName')=='IMG'){
            obj='img';
        }else if($(e.target).hasClass('met-icon')){
            obj='.met-icon';
        }else{
            obj='.editable-click';
        }
        var $self=$(e.target).closest(obj);
        //   $pageeditor_editor.hide().attr({'data-obj':obj,'data-index':$page_iframe_contents.find(obj).index($self)});
        if(!$(e.target).parents('.met-editor').length)
        {
            $self.removeClass('set');
        }
    })
    // 鼠标移到编辑按钮，显示对应的设置元素的外边框
    $pageeditor_editor.hover(function(event) {
        $($(this).attr('data-obj'),page_iframe_document).eq($(this).attr('data-index')).addClass('set');
    },function(){
        $($(this).attr('data-obj'),page_iframe_document).eq($(this).attr('data-index')).removeClass('set');
    });
    // 编辑按钮点击显示输入框
    $pageeditor_editor.click(function(event) {
        // 计算输入框样式尺寸
        var type=$(this).attr('data-type');
        var id =$(this).attr('data-id');
        var content=$(this).attr('data-content');
        console.log(type);
        console.log(id);
      //  return false;
        if($(this).attr('data-obj')=='img'){
             var url='admincp.php?c=ui_set&a=save_img&type='+type+'&id='+id;
                layer.open({
                    type: 2,
                    title: '图片修改',
                    shadeClose: true,
                    shade: false,
                    maxmin: true, //开启最大化最小化按钮
                    area: ['580', '250'],
                    content: url,
                    end: function(){
                        parent.location.reload();
                    }
                });
        }else{
            if(content=='1'){
                if(type=='setting'){
                    var url='admincp.php?c='+type+'&a='+id;
                }else if(type=='article'){
                    var url='admincp.php?c='+type+'&tid=1&a=edit&id='+id;
                }else if(type=='download'){
                    var url='admincp.php?c='+type+'&tid=4&a=edit&id='+id;
                }else if(type=='photo'){
                    var url='admincp.php?c='+type+'&tid=3&a=edit&id='+id;
                }else if(type=='hr'){
                    var url='admincp.php?c='+type+'&tid=5&a=edit&id='+id;
                }else {
                    var url='admincp.php?c='+type+'&tid=2&a=edit&id='+id;
                }
                layer.open({
                    type: 2,
                    title: '可视化编辑',
                    shadeClose: true,
                    shade: false,
                    maxmin: true, //开启最大化最小化按钮
                    area: ['893px', '600px'],
                    content: url,
                    end: function(){
                        parent.location.reload();
                    }
                });
            }else {
                $.ajax({
                    url: "admincp.php?c=ui_set&a=gat_name",
                    type: "post",
                    data:{type:type,id:id},
                    dataType: "json",
                    success: function (data) {
                        if(data.response=='1'){
                            layer.prompt({title: '在线编辑', formType: 0,value:data.name}, function(text, index){
                                $.ajax({
                                    url: "admincp.php?c=ui_set&a=save_name",
                                    type: "post",
                                    data:{type:type,id:id,text:text},
                                    dataType: "json",
                                    success: function (data) {
                                        if(data.response=='1'){
                                            layer.msg(data.result);
                                            setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                                layer.close(index);
                                                window.location.reload();//页面刷新
                                            },2000);
                                        }else {
                                            layer.msg(data.result);
                                        }
                                        //  window.location.href = "index.php";
                                    },
                                    error: function (e) {
                                        //  window.location.href = "index.php";
                                    }
                                });
                                return false;
                            });
                        }else {
                            layer.msg(data.result);
                        }

                        //  window.location.href = "index.php";
                    },
                    error: function (e) {
                        //  window.location.href = "index.php";
                    }
                });
            }
        }
    });
    // 非可编辑文字区域，隐藏输入框和文字编辑按钮
    $page_iframe_contents.find("body").mouseover(function(e) {
        if(!($(e.target).closest(".editable-click").length || $pageeditor_btn.find('.editable-container').length || $(e.target).closest(".pageeditor-btn").length)){
            // $pageeditor_remark.editable('hide');
            $pageeditor_editor.hide();
        }
    });
});

// 区块设置按钮定位
function    blocksetBtnPosition(obj,btns,index,windows,thisiframe){
    var self_info={};
    if(obj.css('position')=='fixed'){
        self_info.left=obj.position().left,
            self_info.top=obj.position().top,
            self_info.position='fixed';
    }else{
        self_info.left=obj.offset().left,
            self_info.top=obj.offset().top,
            self_info.position='';
    }
    self_info.width=obj.outerWidth();
    self_info.left+=self_info.width/2;
    self_info.height=obj.outerHeight();
    self_info.thiswidth=btns.outerWidth();
    var scroll=$(windows).scrollTop();
    // 区块被其它区块遮挡时设置按钮位置变换
    thisiframe.find('[m-id]').each(function(index1, el1) {
        var this_position=$(this).css('position');
        if(index1!=index && this_position=='fixed'){
            var this_h=$(this).outerHeight(),
                this_top=$(this).position().top,
                this_tops=scroll+this_top,
                other_judge=this_top<15?1:0;
            if(this_tops+this_h>self_info.top && this_tops+this_h<self_info.top+self_info.height && other_judge && $(this).outerWidth()>=self_info.width/2){
                self_info.top=this_top+this_h;
                self_info.position=this_position;
                return false;
            }
        }
    });
    $.each(mid_btn_position, function(index2, val2) {
        if(self_info.top>val2.top && self_info.top<val2.top+22 && self_info.left>val2.left-self_info.thiswidth && self_info.left<val2.left+val2.width) self_info.top=val2.top+22;
    });
    if((self_info.position=='absolute' && self_info.top+22>=$(documents).height()) || (self_info.position=='fixed' && self_info.top+22>=$(windows).height())) self_info.top-=22;
    mid_btn_position[index]={
        left:self_info.left,
        top:self_info.top,
        width:self_info.thiswidth
    };
    btns.css({position:self_info.position,left:self_info.left,top:self_info.top});
    obj.is(':visible') && btns.removeClass('hide');
}
$.fn.extend({
    // 页面内容转换为可视化信息
    pageinfo:function(windows,documents){
        // 插入各区块设置按钮
        window.mid_btn_position={};
        var $this=$(this),
            blockBtnHandle=function(obj){
                obj.addClass('set').each(function(index, el) {
                    $(this).css('position')=='static' && $(this).css({position:'relative'});
                    var index=$this.find('[m-id]').index($(this)),
                        mid=$(this).attr('m-id'),
                        type=$(this).attr('m-type'),
                        html='';
                    //  if(mid!='noset') html+='<button type="button" class="btn btn-xs btn-primary pageset-block-config" data-mid="'+mid+'" data-index="'+index+'">'+"设置"+'</button>';
                    if(type!='nocontent') html+='<button type="button" class="btn btn-xs btn-warning pageset-content" data-mid="'+mid+'" data-type="'+type+'" data-index="'+index+'">'+"内容"+'</button>';
                    html && $this.find('html>.pageset-btns').append('<div class="pageset-btn hide" data-mid="'+mid+'" data-index="'+index+'">'+html+'</div>');
                    var $pageset_btn=$this.find('.pageset-btn[data-mid="'+mid+'"][data-index="'+index+'"]');
                    blocksetBtnPosition($(this),$pageset_btn,index,windows,$this);
                });
            };
        $this.find('html').append('<div class="pageset-btns"></div>');
        setTimeout(function(){
            blockBtnHandle($this.find('[m-id][m-id!="online"]'));
            var online_btnhandle_interval=setInterval(function(){
                typeof windows.met_online_load!='undefined' && windows.met_online_load && $this.find('[m-id="online"]').is(':visible') && (clearInterval(online_btnhandle_interval),blockBtnHandle($this.find('[m-id="online"]')));

            },50);
        },500);
        // 文字内容转换可视化信息
        $('m',this).each(function() {
            var el = $(this).parent();
            if(el.prop('tagName')!='BODY' && el.prop('tagName')!='HTML'){
                if($(this).attr('met-field') == 'content' && !$(this).parents('.met-editor').attr('met-field')) el = $(this).parents('.met-editor');
                el.attr({'met-id':$(this).attr('met-id'),'met-table':$(this).attr('met-table'),'met-field':$(this).attr('met-field')}).addClass('editable-click');
                $(this).remove();
            }
        });
        // 图片内容转换可视化信息
        $('img,[data-original]',this).each(function(index, el) {
            var img_url=$(this).data('original')||$(this).data('lazy')||$(this).data('src')||$(this).attr('src');
            if(img_url && img_url.indexOf('met-id=')>=0) $(this).attr({'met-id':img_url.match(/met-id=(\w+)/)[1],'met-table':img_url.match(/met-table=(\w+)/)[1],'met-field':img_url.match(/met-field=(\w+)/)[1]});
        });
        // 图标内容转换可视化信息
        $('[class*="met-icon|"]',this).each(function(index, el) {
            var self_class=$(this).attr('class').split(' ');
            self_class=$.grep(self_class, function(n) {return $.trim(n).length > 0;});
            $.each(self_class, function(index, val) {
                if(val.indexOf('met-icon')>=0){
                    var icon_info=val.split('|');
                    $(el).addClass('met-icon').removeClass(val).attr({'met-id':icon_info[1],'met-table':icon_info[2],'met-field':icon_info[3]});
                    return false;
                }
            });
        })
        // 下拉菜单新窗口打开去除新窗口打开属性
        $('a[data-toggle="dropdown"][data-hover="dropdown"][target="_blank"]',this).removeAttr('target');
        window.pageset_btn_hide=0;
        setTimeout(function(){
            $this.find('html>.pageset-btns .pageset-btn').hide();
            pageset_btn_hide=1;
        },5000);
        // 自定义链接替换
        $('a[href][href!=""]',this).filter(function(index) {
            var href=$(this).attr('href');
            return href.indexOf('javascript:')<0;
        }).each(function(index, el) {
            var href=$(this).attr('href');
            if(href.indexOf('<m met')>=0) $(this).attr({href:href.split('<m met')[0]});
        });
    },
    contextMenu:function(menu_obj) {
        // 显示右键菜单
        if(!menu_obj) menu_obj='.met-menu';
        var $menu_obj=$(menu_obj),
            $self=$(this),
            menu_obj_width=$menu_obj.outerWidth(),
            menu_obj_height=$menu_obj.outerHeight(),
            onContextMenu=function(e){
                e.preventDefault();
                var left=e.clientX,
                    right='auto',
                    top=e.clientY+50,
                    bottom='auto';
                if(left+menu_obj_width>$(window).width()){
                    left='auto';
                    right=0;
                }
                if(top+menu_obj_height>$(window).height()){
                    top='auto';
                    bottom=0;
                }
                $menu_obj.addClass('show-menu').css({left:left,right:right,top:top,bottom:bottom});
                $self.bind('mousedown',onMouseDown);
                $self.parents('body').bind('mousedown', onMouseDown);
                $menu_obj.find('.obj-remove').attr({'data-index':$self.index($(e.target).closest($self.selector))});
            },
            onMouseDown=function(){
                $menu_obj.removeClass('show-menu');
                $self.unbind('mousedown',onMouseDown);
                $self.parents('body').unbind('mousedown', onMouseDown);
            };
        $self.bind('contextmenu',onContextMenu);
        // 右键菜单功能
        $menu_obj.find('.obj-remove').click(function(event) {
            $self.eq($(this).attr('data-index')).remove();
            onMouseDown();
        });
    }
});