!function ($) {
    $.fn.checkListLength = function (param){
        _defaultSettings = {
            onlyOne: null,
        };
        _set = $.extend(_defaultSettings, param);
        $this = this;
        $li = this.children('li');
        $dropzone = $('#dropzone');
        if(($li.length - _set.onlyOne) == 0) {
		    $('#dropzone').fadeIn(300);
		} else {
		    $('#dropzone').fadeOut(300);
		};
		$('#file-list').nanoScroller({ scrollTop: 0, iOSNativeScrolling: true });
    }
}(window.jQuery);
$(function () {
    'use strict';
    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        maxFileSize: 5000000,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png|pdf|doc|docx|ppt|pptx|xls|xlsx)$/i,
        dropZone: $('#dropzone'),
        headers:{
            'X-CSRF-Token': $('meta[name="csrf-token"]').attr("content")
        }
    }).bind('fileuploadstop', function (e, data) {
    	window.location.reload();
    });
});
$(document).ready(function(){
	var insertBtn = $("#insert_btn"),
		deleteBtn = $("#delete_btn"),
		url = null;
	
	var showPreview = function(elem){
		var type = $("#ext_" + elem.val()).val(),
			imgexp = new RegExp(/(\.|\/)(gif|jpe?g|png)$/i),
			otherexp = new RegExp(/(\.|\/)(pdf|doc|docx|ppt|pptx|xls|xlsx)$/i)
			img = $("<img />"),
			preview = $( ".preview-area" );
		preview.text("Preview is loading...");
		if( imgexp.test(type) ){
			var url = $("#url_" + elem.val()).val();
			img.attr("src",url).load(function(){
				var ratio = this.width / this.height,
					targetWidth = targetHeight = 200;
				if( ratio < 1 ){
					targetWidth = targetHeight * ratio;
				}else{
					targetHeight = targetWidth / ratio;
				}
				img.height(targetHeight).width(targetWidth);
				preview.html(img);
			})
		}else if( otherexp.test(type) ) {
			var t = type.replace(".",""),
				url = "/assets/ft-icons/" + t + "/" + t + "-128_32.png";
			img.attr('src', url).load(function(){
				preview.html(img);
			});
		}else{
			preview.html("Preview not available.");
		}
	}

	$("#asset_sort_list").on(clickEvent,"input[type=checkbox]",function(){
		if($("#asset_sort_list input[type=checkbox]:checked").length == 1){
			url = window.location.protocol + "//" + window.location.host + $("#url_" + $("input[type=checkbox]:checked").val()).val();
			insertBtn.show();
			showPreview($("input[type=checkbox]:checked"))
		}else{
			insertBtn.hide();
			url = null;
			$( ".preview-area" ).empty();
		}
		if($("#asset_sort_list input[type=checkbox]:checked").length)
			deleteBtn.show();
		else
			deleteBtn.hide();
	})
	insertBtn.bind(clickEvent,function(){
		var alt_text = $("#"+language+"_desc_"+$("input[type=checkbox]:checked").val()).val();
		alt_text = (alt_text ? alt_text : "This is an image");
		if(url){
			window.opener.CKEDITOR.tools.callFunction( funcNum, url, function() {
			    var element,
			        dialog = this.getDialog();
			    if ( dialog.getName() == 'image' ) {
			        element = dialog.getContentElement( 'info', 'txtAlt' );
			        if ( element )
			            element.setValue( alt_text );
			    }
			});
			window.close();
		}
	})
	deleteBtn.bind( clickEvent,function(){
		var items_to_delete = [],
			type = getUrlParam("type");
		$("input[type=checkbox]:checked").each(function(){
			items_to_delete.push($(this).val());
		})
		$.post("/admin/assets/delete_files",{"files":items_to_delete,"type":type},function(){
			deleteBtn.hide();
		})
	})
	var currentEdit = null;
	$(document).on("ajax:success","form[data-remote=true]",function(evt, data, xhr){
		if(currentEdit){
			currentEdit.replaceWith($(data));
			$("#editform").modal("hide");
		}
	})

	$("#asset_sort_list").on(clickEvent,".editform",function(){
		currentEdit = $(this).parent().parent();
		$.get($(this).attr("href"),function(data){
			$("#editform").html(data).modal("show");
		})
		return false;
	})

	$("#editform").on("hidden",function(){
		currentEdit = null;
	})

	function getUrlParam( paramName ) {
	    var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' ) ;
	    var match = window.location.search.match(reParam) ;

	    return ( match && match.length > 1 ) ? match[ 1 ] : null ;
	}
	var funcNum = getUrlParam( 'CKEditorFuncNum' ),
		t = getUrlParam('CKEditor').split("_"),
		language = t[t.length-1];

	language = (language == "tw" ? "zh_tw" : language); 

})