$(function() {
	var fixedToolbar = $('.toolbar:first').clone().attr('id', 'fixedToolbar');
	$('.toolbar:first').after(fixedToolbar);
	var fixedInfobar = $('.infobar:first').clone().attr('id', 'fixedInfobar');
	$('.infobar:first').after(fixedInfobar);
	
	$(window).scroll(function(){
		if ($(window).scrollTop() > 110) {
			$('#fixedToolbar').show();
			$('#fixedInfobar').show();
		} else {
			$('#fixedToolbar').hide();
			$('#fixedInfobar').hide();
		}
	});
	
	// ------------------------------------------
	// 编辑器
	// ------------------------------------------
	if ($('textarea.editor')) {
		var config = {
	        skin: '126',
	        toolbar: 'nso',
	        language: 'zh-cn',
	        filebrowserBrowseUrl : 'ckfinder/ckfinder.html',
			filebrowserImageBrowseUrl : 'ckfinder/ckfinder.html?Type=Images',
			filebrowserFlashBrowseUrl : 'ckfinder/ckfinder.html?Type=Flash',
			filebrowserUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
			filebrowserImageUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
			filebrowserFlashUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash'
	    };
	    $('textarea.editor').ckeditor(config);
	}
    
    $('.toolbar .tool_button .save_button').click(save);
    var addNewPostUri = $('#hiddenParamAddNewPostUri').html();
    $('.toolbar .tool_button .addnew_button').click(function(){window.location = addNewPostUri});
    
    // ------------------------------------------
	// Ajax表单提交
	// ------------------------------------------
    var options = { 
        //target:        '#output1',   // target element(s) to be updated with server response 
        beforeSubmit:  formSubmit,  // pre-submit callback 
        success:       saveFeeback  // post-submit callback 
 
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 
    $('#postForm').ajaxForm( options );
    
    // ------------------------------------------
	// 附件交互效果
	// ------------------------------------------
    $('#swfuploadUploadProgress').sortable({axis: 'y', containment: 'parent'});
    $('.swfuploadDeleteFileButton').live('click', deleteSwfuploadFile);
    
    // ------------------------------------------
    // Datepicker
    // ------------------------------------------
	$('.form_element_datetime input').datetimepicker({
		showSecond: true,
		timeFormat: 'hh:mm:ss',
		dateFormat: 'yy-mm-dd',
		monthNames: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'],
		dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
		timeText: '时间',
		hourText: '时',
		minuteText: '分',
		secondText: '秒',
		currentText: '当前',
		closeText: '关闭',
	});
});


// ------------------------------------------
// 表单提交
// ------------------------------------------
function save() {
	$('#postForm').submit();
	return false;
}

function formSubmit(formData, jqForm, options) { 
	$('.toolbar .tool_button .save_button').unbind('click').addClass('button_disable');
	$('.infobar .message_box').fadeIn();
    return true; 
}

function saveFeeback(responseText, statusText, xhr, $form) {
	$('.toolbar .tool_button .save_button').click(save).removeClass('button_disable');
	
	var json = $.parseJSON(responseText);
	if (json.success) {
		$('.infobar .message_box').html('保存成功。');
	    setTimeout("fadeOutMessage()", 2000);
	    
	    if (json.id != "") {
	    	$('#form-post-id-input').val(json.id);
	    	$('#form-action-input').val('update');
	    }
	} else {
		$('.infobar .message_box').html('保存失败。');
	    setTimeout("fadeOutMessage()", 5000);
	}
    
}

function fadeOutMessage()
{
	$('.infobar .message_box').fadeOut('fast', function(){$(this).html('正在保存...')});
}
// ------------------------------------------
// ------------------------------------------



// ------------------------------------------
// 删除附件
// ------------------------------------------
function deleteSwfuploadFile() {
	var wrapper = $(this).parents('.progressWrapper')
	wrapper.fadeOut();
	var json = wrapper.find('.swfuploadFileMeta input:hidden').val();
	$.getJSON('swfuploadDeleteFile.php?json='+json, function(data){
		if (data.success == true) {
			wrapper.remove();
		} else {
			wrapper.fadeIn();
		}
	});
}
// ------------------------------------------
// ------------------------------------------



// ------------------------------------------
// SWFUpload配置
// ------------------------------------------
var swfupload;
window.onload = function() {
    swfupload = new SWFUpload({
        upload_url: "swfuploadUploadFile.php",

        // File Upload Settings
        file_size_limit : "10240", // 10MB
        file_types : "*.jpg;*.png;*.gif;*.pdf;*.rar;*.avi;*.wmv;*.doc",
        file_types_description : "支持文件格式",
        file_upload_limit : "0",
        file_queue_limit : "0",

        // Event Handler Settings (all my handlers are in the Handler.js file)
        file_dialog_start_handler : fileDialogStart,
        file_queued_handler : fileQueued,
        file_queue_error_handler : fileQueueError,
        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_image_url : "swfupload/style/swfUploadAddBtn.jpg",
        button_placeholder_id : "swfuploadButtonPlaceholder",
        button_width: 70,
        button_height: 31,

        // Flash Settings
        flash_url : "swfupload/swfupload.swf",


        custom_settings : {
            progressTarget : "swfuploadUploadProgress",
            cancelButtonId : "swfuploadCancelButton"
        },

        // Debug Settings
        debug: false
    });
}