/**
* @Descript: 前台-插入图片
*/
;(function ( $, window, document, undefined ) {
$.fn.extend({
rangeInsert: function(myValue,t){
var $t=$(this)[0];

if (document.selection) {//ie
this.focus();
var sel = document.selection.createRange();
sel.text = myValue;
this.focus();
sel.moveStart ('character', -l);
var wee = sel.text.length;
if(arguments.length == 2){
var l = $t.value.length;
sel.moveEnd("character", wee+t );
t<=0?sel.moveStart("character",wee-2*t-myValue.length):sel.moveStart("character",wee-t-myValue.length);

sel.select();
}
} else if ($t.selectionStart || $t.selectionStart == '0') {
var startPos = $t.selectionStart;
var endPos = $t.selectionEnd;
var scrollTop = $t.scrollTop;
$t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
this.focus();
$t.selectionStart = startPos + myValue.length;
$t.selectionEnd = startPos + myValue.length;
$t.scrollTop = scrollTop;
if(arguments.length == 2){
$t.setSelectionRange(startPos-t,$t.selectionEnd+t);
this.focus();
}
}
else {
this.value += myValue;
this.focus();
}
}
});

})(jQuery, window ,document);

var ATTACH_CONFIG = {
ifopen : '1',
uploadUrl : "/bbs-upload-dorun?_json=1",//上传地址
attachnum : parseInt('3'),
list : {},
postData : {csrf_token : GV.TOKEN,uid : GV.U_ID,fid:fid},
filetype : {'jpg' : '2048','png' : '2048','gif' : '2048','bmp' : '2048'}
}


var photo_temp = $('\
<div id="J_photo_pop" style="z-index:11;position:absolute;" class="core_menu pop_show_mini edit_menu">\
<div class="core_arrow_top" style="left:0;"><em></em><span></span></div><a href="#" id="J_photo_close" class="pop_close">关闭</a>\
<div id="J_photo_menu">\
<div class="hd">\
<ul class="cc">\
<li class="J_upload_tab current" data-show="J_upload" ><a href="">本地上传</a></li>\
<li data-show="J_network"><a href="">网络图片</a></li>\
</ul>\
</div>\
</div>\
<div  id="J_photo_pl">\
<div id="J_upload" class="J_tab_content J_upload_tab">\
<div class="edit_menu_cont">\
<div class="edit_uping">\
<span class="num">还可上传<em id="J_num2"></em>个</span>\
<span id="J_buttonPlaceHolder2" ></span>\
</div>\
<div class="eidt_uphoto">\
<ul class="cc" id="J_photo_list">\
</ul>\
</div>\
</div>\
<div class="edit_menu_bot">\
<button type="button" class="btn edit_btn_cancel">取消</button><!--点击编辑可编辑图片效果-->\
<span class="tips_icon" style="margin-left:7px" >上传图片后，点击图片插入帖子显示</span>\
</div>\
</div>\
<div class="edit_menu_cont J_tab_content" style="display:none;" id="J_network">\
<div class="edit_online_photo">\
<em>图片地址：</em><input name="" type="text" id="J_input_net_photo" class="input" value="" placeholder="http://">\
</div>\
<div class="tac mb10"><button type="button" class="btn btn_submit" id="J_insert_net_photo">插入图片</button></div>\
</div>\
</div>\
</div>\
</div>');  



//上传图片
var file_list = ATTACH_CONFIG.list;
var photo_list_ul = photo_temp.find('#J_photo_list');//没有添加进document时只能用find
var allowFileCount = ATTACH_CONFIG.attachnum,html = [];

function insertPhoto(elem, input, wrap) {
var photo_pop = $('#J_photo_pop');
if(photo_pop.length) {
if(wrap) {
//移入容器里,定位由页面写
photo_pop.appendTo(wrap);
}else{
//移入body里
photo_pop.appendTo('body');
}

if(photo_pop.is(':visible')){
photo_pop.hide();
return false;
}
photoPos(elem, photo_pop, wrap);

}else{

if(wrap) {
wrap.append(photo_temp);
}else{
$('body').append(photo_temp);
}

photo_list_ul.empty();//每次弹出窗口时清空重新填充Dom,因为会受限制上传的限制需要更新
$.each(file_list,function(i,obj) {
var name = obj.name;
var file_extension = name.substring(name.lastIndexOf('.'),name.length).toLowerCase();
//把附件中如果是图片的附件显示在图片里面
if($.inArray(file_extension,imgsArr) < 0) {
//附件里的不是图片不用显示并删除一个占位格
photo_list_ul.find('li.J_empty').eq(0).remove();
return;
}
var serverData = {aid:i,path:obj.path,thumbpath:obj.thumbpath,is_new:obj.is_new};
//请注意这个uploaded的class添加，是因为每天上传的附件限制，只有在新上传的时候才会更新当前数量，编辑附件的时候不计算
var upladedLi = $('<li class="'+ (obj.is_new ? 'uploaded' : '') +'"><div class="get">\
<img alt="已上传的" data-id="'+ serverData.aid +'" src="'+ (serverData.thumbpath || serverData.path) +'" width="78" height="98" data-path="'+ serverData.path +'"/>\
</div></li>').data('serverData',serverData);
photo_temp.find('#J_photo_list').prepend(upladedLi);
});

//更新显示上传数量
update_num();

var swfupload_root = window.GV.JS_ROOT + "util_libs/swfupload/";
Wind.js(swfupload_root + 'swfupload.js?v=' + GV.JS_VERSION, swfupload_root + 'plugins/swfupload.pluginMain.js?v=' + GV.JS_VERSION, function() {
SWFUpload.CURSOR = {//鼠标状态枚举
ARROW : -1,
HAND : -2
};
var settings = {
flash_url : swfupload_root + "Flash/swfupload.swf",
upload_url: ATTACH_CONFIG.uploadUrl,//ATTACH_CONFIG为网页中提供的上传变量
post_params: ATTACH_CONFIG.postData,
file_types : (function() {
var arr = [];
for(var i in ATTACH_CONFIG.filetype) {
if(i) {
arr.push('*.' + i);
}
}
return arr.join(';');
})(),
file_types_description : "可上传的图片类型",
debug: false,
file_dialog_start_handler : fileDialogStart,
file_queued_handler : fileQueued,
file_dialog_complete_handler : fileDialogComplete,
upload_start_handler : uploadStart,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,

// Button settings
button_width: "80",
button_height: "25",
button_cursor : SWFUpload.CURSOR.HAND,
button_image_url: swfupload_root + "button80x25.png",
button_placeholder_id: "J_buttonPlaceHolder2",
swfupload_load_failed_handler: function(){
//没有安装flash插件
$("#J_buttonPlaceHolder2").html('您还没有安装flash插件，点击<a class="b u" href="http://www.adobe.com/go/getflash" target="_blank">这里</a>安装')
}
};

swfu = new SWFUpload(settings);

});


var photo_pop = $('#J_photo_pop'),
photo_menu = $('#J_photo_menu'),
photo_pl = $('#J_photo_pl');

//定位
photoPos(elem, photo_pop, wrap);


//点击菜单
photo_menu.on('click', 'a', function(e){
e.preventDefault();
var container = photo_pl.children().eq($(this).parent().index());
$(this).parent().addClass('current').siblings().removeClass('current');
container.show().siblings().hide();
})


//插入网络图片
photo_pl.find('#J_insert_net_photo').on('click',function(e) {
e.preventDefault();
var url = $('#J_input_net_photo').val();
var asdfsd = /\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(url);
if( url.indexOf('http')!== 0 || !asdfsd) {
Wind.Util.resultTip({
error : true,
msg : '尼玛，图片地址不对啊，http在否？',
follow : $('#J_insert_net_photo')
});
return;
}
input.rangeInsert('[img]'+url+'[/img]');
$('#J_photo_pop').hide();
});
}	


//取消按钮关闭弹窗口
photo_temp.find('.edit_btn_cancel').on('click',function() {
$('#J_photo_pop').hide();
});


//上传好的图片点击插入
photo_temp.find('#J_upload').off('click').on('click', 'img', function(e) {   //off是为了防止多次点图片按钮后，插入图片为多个
e.preventDefault();
var img = this;
var src = $(img).attr('data-path');
input.rangeInsert('[img]'+src+'[/img]');
});



//点击x关闭
$('#J_photo_close').on('click', function(e){
e.preventDefault();
photo_pop.hide();
});


//点击pop外面
$(document.body).on('mousedown',function(e) {
var elem = $('.J_insert_photo');
var photo_pop = $('#J_photo_pop');
if(photo_pop.is(':visible') && e.target!=photo_pop[0] && !$(e.target).hasClass('J_insert_photo') && !$.contains(photo_pop[0],e.target)) {
photo_pop.hide();
}
});


}  //insertPhoto函数结束


//图片弹窗定位
function photoPos(elem, pop, wrap){
if(wrap) {
//容器内计算边距
pop.css({
left : elem.offset().left - wrap.offset().left - 30,
top : elem.offset().top - wrap.offset().top + elem.height() + 10
}).show();
}else{
pop.css({
left : elem.offset().left - 25,
top : elem.offset().top + elem.outerHeight() + 15
}).show();
}
}


/* **********************
swfupload 批量上传过程中的事件处理
********************** */
function fileDialogStart() {
/* I don't need to do anything here */
}

function fileQueued(file) {
var file_list_box = $('#J_photo_list');
//填充图片显示位置
var empty_box = $('#J_photo_list > li.J_empty:eq(0)'),
name = file.name,
file_extension = name.substring(name.lastIndexOf('.') + 1,name.length).toLowerCase();
var invalid = false,tip = '';
var allowSize = parseInt(ATTACH_CONFIG.filetype[file_extension])*1024;
var allowFileCount = parseInt(ATTACH_CONFIG.attachnum);
if(empty_box.length) {
//判断文件大小是否超过上传限制
if(allowSize && file.size > allowSize) {
tip = '大小超限制('+ allowSize/1024 +'kb)';
invalid = true;
}else if(!allowSize) {
tip = '不允许上传此类型文件';
invalid = true;
}else if(file_list_box.find('li.uploaded,li.readying').size() - file_list_box.find('li.invalid').size() > allowFileCount) {
tip = '上传数量超出限制';
invalid = true;
}else {
invalid = false;
empty_box.replaceWith('<li id="'+ file.id +'" class="readying"><div class="schedule"><em>0%</em><span style="width:0%;"></span></div></li>');
}
//如果是无效的则取消上传
if(invalid) {
swfu.cancelUpload(file.id);
empty_box.before('<li class="invalid"><div class="error" title="'+ tip +'">'+ tip +'<a href="javascript:;" class="del">删除</a></div></li>');
}
}else {
swfu.cancelUpload(file.id);
tip = '上传数量超出限制';
invalid = true;
}

}

function fileQueueError(file, errorCode, message) {
$.error(message);
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
try {
if (swfu.getStats().files_queued > 0) {
}
//选择文件完成后自动上传
swfu.startUpload();
} catch (ex)  {
$.error(ex);
}
}

function uploadStart(file) {
return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {
var file_detail = $('#'+file.id);
file_detail.removeClass('readying').addClass('uploading');
try {
var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
file_detail.find('em').text(percent + '%');//显示进度
file_detail.find('span').css('width',percent + '%');//使用宽度来显示进度条
} catch (ex) {
$.error(ex);
}
}

function uploadSuccess(file, serverData) {
try {
var file_detail = $('#'+file.id);
var json = $.parseJSON(serverData);
if(json.state !== 'success') {
var message = json.message[0];
file_detail.html('<div class="error" title="'+ message +'">'+ message +'<a href="" class="del">删除</a></div>').addClass('invalid');
return;
}
var data = json.data;
data.is_new = true;//is_new表示为新上传的，而不是编辑的
file_list[''+ data['aid']] = {name : file.name, size : file.size, path : data.path, desc : '',is_new : true, thumbpath:data.thumbpath };//图片则有缩略图
file_detail.data('serverData',data).removeClass('uploading').addClass('uploaded');
file_detail.html('<div class="get">\
<img title="'+ file.name +'" alt="上传完成" data-path="'+ data.path +'" data-id="'+ data.aid +'" src="'+ data.thumbpath +'" width="78" height="98"/>\
</div>');
$('#fastReplyForm').append('<input placeholder="请输入描述" type="hidden" name="flashatt['+ data.aid +'][desc]" class="J_file_desc"/>');


//上传成功后，点击可改描述
//更新显示可上传数量
update_num();
} catch (ex) {
$.error(ex);
}
}

function uploadComplete(file) {
try {
//如果上传完成后，还有未上传的队列，那和继续自动上传
if (swfu.getStats().files_queued === 0) {
} else {
swfu.startUpload();
}
} catch (ex) {
$.error(ex);
}
}

function uploadError(file, errorCode, message) {
$.error(message);
}

//更新显示可上传数量，并更新图片的上传占位区
function update_num () {
var new_file_count = 0;
//因为附件和图片是共用的附件机制，所以要把附件中新上传的减掉
$.each(file_list,function(i,obj) {
if(obj.is_new) {
new_file_count ++ ;
}
});
var allow_count = ATTACH_CONFIG.attachnum - new_file_count;
if(allow_count < 0) {//以防算错，界面上出现可上传数量为负数
allow_count = 0;
}
photo_temp.find('#J_num2').text(allow_count);
//需要填充图片待上传占位的数量
photo_list_ul.find('li.J_empty').remove();
var need_fill_length = allow_count - photo_list_ul.find('li.readying,li.uploading').length;
//填充占位
for(var i = 0;i < need_fill_length; i++) {
photo_list_ul.append('<li class="J_empty"><div class="no">暂无</div></li>');
}
return allow_count;
}

