/**
 * jquery.ui.plupload.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.button.js
 *	jquery.ui.progressbar.js
 *	
 * Optionally:
 *	jquery.ui.sortable.js
 */

 /* global jQuery:true */

!function(a,b,c,d,e){function g(a){return c.translate(a)||a}function h(a){a.id=a.attr("id"),a.html('<div class="plupload_wrapper"><div class="ui-widget-content plupload_container"><div class="ui-state-default ui-widget-header plupload_header"><div class="plupload_header_content"><div class="plupload_logo"> </div><div class="plupload_header_title">'+g("Select files")+'</div><div class="plupload_header_text">'+g("Add files to the upload queue and click the start button.")+'</div><div class="plupload_view_switch"><input type="radio" id="'+a.id+'_view_list" name="view_mode_'+a.id+'" checked="checked" /><label class="plupload_button" for="'+a.id+'_view_list" data-view="list">'+g("List")+'</label><input type="radio" id="'+a.id+'_view_thumbs" name="view_mode_'+a.id+'" /><label class="plupload_button"  for="'+a.id+'_view_thumbs" data-view="thumbs">'+g("Thumbs")+'</label></div></div></div><table class="plupload_filelist plupload_filelist_header ui-widget-header"><tr><td class="plupload_cell plupload_file_name">'+g("Filename")+'</td><td class="plupload_cell plupload_file_status">'+g("Status")+'</td><td class="plupload_cell plupload_file_size">'+g("Size")+'</td><td class="plupload_cell plupload_file_action">&nbsp;</td></tr></table><div class="plupload_content"><div class="plupload_droptext">'+g("Drag files here.")+'</div><ul class="plupload_filelist_content"> </ul><div class="plupload_clearer">&nbsp;</div></div><table class="plupload_filelist plupload_filelist_footer ui-widget-header"><tr><td class="plupload_cell plupload_file_name"><div class="plupload_buttons"><!-- Visible --><a class="plupload_button plupload_add">'+g("Add Files")+'</a>&nbsp;<a class="plupload_button plupload_start">'+g("Start Upload")+'</a>&nbsp;<a class="plupload_button plupload_stop plupload_hidden">'+g("Stop Upload")+'</a>&nbsp;</div><div class="plupload_started plupload_hidden"><!-- Hidden --><div class="plupload_progress plupload_right"><div class="plupload_progress_container"></div></div><div class="plupload_cell plupload_upload_status"></div><div class="plupload_clearer">&nbsp;</div></div></td><td class="plupload_file_status"><span class="plupload_total_status">0%</span></td><td class="plupload_file_size"><span class="plupload_total_file_size">0 kb</span></td><td class="plupload_file_action"></td></tr></table></div><input class="plupload_count" value="0" type="hidden"></div>')}var f={};e.widget("ui.plupload",{widgetEventPrefix:"",contents_bak:"",options:{browse_button_hover:"ui-state-hover",browse_button_active:"ui-state-active",dragdrop:!0,multiple_queues:!0,buttons:{browse:!0,start:!0,stop:!0},views:{list:!0,thumbs:!1,active:"list",remember:!0},autostart:!1,sortable:!1,rename:!1,max_file_count:0},FILE_COUNT_ERROR:-9001,_create:function(){var a=this.element.attr("id");a||(a=c.guid(),this.element.attr("id",a)),this.id=a,this.contents_bak=this.element.html(),h(this.element),this.container=e(".plupload_container",this.element).attr("id",a+"_container"),this.content=e(".plupload_content",this.element),e.fn.resizable&&this.container.resizable({handles:"s",minHeight:300}),this.filelist=e(".plupload_filelist_content",this.container).attr({id:a+"_filelist",unselectable:"on"}),this.browse_button=e(".plupload_add",this.container).attr("id",a+"_browse"),this.start_button=e(".plupload_start",this.container).attr("id",a+"_start"),this.stop_button=e(".plupload_stop",this.container).attr("id",a+"_stop"),this.thumbs_switcher=e("#"+a+"_view_thumbs"),this.list_switcher=e("#"+a+"_view_list"),e.ui.button&&(this.browse_button.button({icons:{primary:"ui-icon-circle-plus"},disabled:!0}),this.start_button.button({icons:{primary:"ui-icon-circle-arrow-e"},disabled:!0}),this.stop_button.button({icons:{primary:"ui-icon-circle-close"}}),this.list_switcher.button({text:!1,icons:{secondary:"ui-icon-grip-dotted-horizontal"}}),this.thumbs_switcher.button({text:!1,icons:{secondary:"ui-icon-image"}})),this.progressbar=e(".plupload_progress_container",this.container),e.ui.progressbar&&this.progressbar.progressbar(),this.counter=e(".plupload_count",this.element).attr({id:a+"_count",name:a+"_count"}),this._initUploader()},_initUploader:function(){var h,a=this,b=this.id,i={container:b+"_buttons",browse_button:b+"_browse"};e(".plupload_buttons",this.element).attr("id",b+"_buttons"),a.options.dragdrop&&(this.filelist.parent().attr("id",this.id+"_dropbox"),i.drop_element=this.id+"_dropbox"),h=this.uploader=f[b]=new c.Uploader(e.extend(this.options,i)),a.options.views.thumbs&&(h.settings.required_features.display_media=!0),h.bind("Error",function(b,e){var f,h="";switch(f="<strong>"+e.message+"</strong>",e.code){case c.FILE_EXTENSION_ERROR:h=d.sprintf(g("File: %s"),e.file.name);break;case c.FILE_SIZE_ERROR:h=d.sprintf(g("File: %s, size: %d, max file size: %d"),e.file.name,e.file.size,c.parseSize(a.options.max_file_size));break;case c.FILE_DUPLICATE_ERROR:h=d.sprintf(g("%s already present in the queue."),e.file.name);break;case a.FILE_COUNT_ERROR:h=d.sprintf(g("Upload element accepts only %d file(s) at a time. Extra files were stripped."),a.options.max_file_count);break;case c.IMAGE_FORMAT_ERROR:h=g("Image format either wrong or not supported.");break;case c.IMAGE_MEMORY_ERROR:h=g("Runtime ran out of available memory.");break;case c.HTTP_ERROR:h=g("Upload URL might be wrong or doesn't exist.")}f+=" <br /><i>"+h+"</i>",a._trigger("error",null,{up:b,error:e}),e.code===c.INIT_ERROR?setTimeout(function(){a.destroy()},1):a.notify("error",f)}),h.bind("PostInit",function(b){a.options.buttons.browse?a.browse_button.button("enable"):(a.browse_button.button("disable").hide(),b.disableBrowse(!0)),a.options.buttons.start||a.start_button.button("disable").hide(),a.options.buttons.stop||a.stop_button.button("disable").hide(),!a.options.unique_names&&a.options.rename&&a._enableRenaming(),a.options.dragdrop&&b.features.dragdrop&&a.filelist.parent().addClass("plupload_dropbox"),a._enableViewSwitcher(),a.start_button.click(function(b){e(this).button("option","disabled")||a.start(),b.preventDefault()}),a.stop_button.click(function(b){a.stop(),b.preventDefault()}),a._trigger("ready",null,{up:b})}),a.options.max_file_count&&(a.options.multiple_queues=!1,h.bind("FilesAdded",function(b,c){var d=c.length,e=b.files.length+d-a.options.max_file_count;e>0&&(c.splice(d-e,e),b.trigger("Error",{code:a.FILE_COUNT_ERROR,message:g("File count error.")}))})),h.init(),h.bind("FileFiltered",function(b,c){a._addFiles(c)}),h.bind("FilesAdded",function(b,c){a._trigger("selected",null,{up:b,files:c}),a.options.sortable&&e.ui.sortable&&a._enableSortingList(),a._trigger("updatelist",null,{filelist:a.filelist}),a.options.autostart&&setTimeout(function(){a.start()},10)}),h.bind("FilesRemoved",function(b,c){a._trigger("removed",null,{up:b,files:c})}),h.bind("QueueChanged StateChanged",function(){a._handleState()}),h.bind("UploadFile",function(b,c){a._handleFileStatus(c)}),h.bind("FileUploaded",function(b,c){a._handleFileStatus(c),a._trigger("uploaded",null,{up:b,file:c})}),h.bind("UploadProgress",function(b,c){a._handleFileStatus(c),a._updateTotalProgress(),a._trigger("progress",null,{up:b,file:c})}),h.bind("UploadComplete",function(b,c){a._addFormFields(),a._trigger("complete",null,{up:b,files:c})})},_setOption:function(a,b){var c=this;"buttons"==a&&"object"==typeof b&&(b=e.extend(c.options.buttons,b),b.browse?(c.browse_button.button("enable").show(),c.uploader.disableBrowse(!1)):(c.browse_button.button("disable").hide(),c.uploader.disableBrowse(!0)),b.start?c.start_button.button("enable").show():c.start_button.button("disable").hide(),b.stop?c.start_button.button("enable").show():c.stop_button.button("disable").hide()),c.uploader.settings[a]=b},start:function(){this.uploader.start(),this._trigger("start",null,{up:this.uploader})},stop:function(){this.uploader.stop(),this._trigger("stop",null,{up:this.uploader})},enable:function(){this.browse_button.button("enable"),this.uploader.disableBrowse(!1)},disable:function(){this.browse_button.button("disable"),this.uploader.disableBrowse(!0)},getFile:function(a){var b;return b="number"==typeof a?this.uploader.files[a]:this.uploader.getFile(a)},getFiles:function(){return this.uploader.files},removeFile:function(a){"string"===c.typeOf(a)&&(a=this.getFile(a)),this._removeFiles(a)},clearQueue:function(){this.uploader.splice()},getUploader:function(){return this.uploader},refresh:function(){this.uploader.refresh()},notify:function(a,b){var c=e('<div class="plupload_message"><span class="plupload_message_close ui-icon ui-icon-circle-close" title="'+g("Close")+'"></span><p><span class="ui-icon"></span>'+b+"</p></div>");c.addClass("ui-state-"+("error"===a?"error":"highlight")).find("p .ui-icon").addClass("ui-icon-"+("error"===a?"alert":"info")).end().find(".plupload_message_close").click(function(){c.remove()}).end(),e(".plupload_header",this.container).append(c)},destroy:function(){this._removeFiles([].slice.call(this.uploader.files)),this.uploader.destroy(),e(".plupload_button",this.element).unbind(),e.ui.button&&e(".plupload_add, .plupload_start, .plupload_stop",this.container).button("destroy"),e.ui.progressbar&&this.progressbar.progressbar("destroy"),e.ui.sortable&&this.options.sortable&&e("tbody",this.filelist).sortable("destroy"),this.element.empty().html(this.contents_bak),this.contents_bak="",e.Widget.prototype.destroy.apply(this)},_handleState:function(){var a=this.uploader;a.state===c.STARTED?(e(this.start_button).button("disable"),e([]).add(this.stop_button).add(".plupload_started").removeClass("plupload_hidden"),e(".plupload_upload_status",this.element).html(d.sprintf(g("Uploaded %d/%d files"),a.total.uploaded,a.files.length)),e(".plupload_header_content",this.element).addClass("plupload_header_content_bw")):a.state===c.STOPPED&&(e([]).add(this.stop_button).add(".plupload_started").addClass("plupload_hidden"),this.options.multiple_queues?e(".plupload_header_content",this.element).removeClass("plupload_header_content_bw"):(e([]).add(this.browse_button).add(this.start_button).button("disable"),a.disableBrowse()),a.files.length===a.total.uploaded+a.total.failed?this.start_button.button("disable"):this.start_button.button("enable"),this._updateTotalProgress()),0===a.total.queued?e(".ui-button-text",this.browse_button).html(g("Add Files")):e(".ui-button-text",this.browse_button).html(d.sprintf(g("%d files queued"),a.total.queued)),a.refresh()},_handleFileStatus:function(a){var d,f,b=this;if(e("#"+a.id).length){switch(a.status){case c.DONE:d="plupload_done",f="ui-icon ui-icon-circle-check";break;case c.FAILED:d="ui-state-error plupload_failed",f="ui-icon ui-icon-alert";break;case c.QUEUED:d="plupload_delete",f="ui-icon ui-icon-circle-minus";break;case c.UPLOADING:d="ui-state-highlight plupload_uploading",f="ui-icon ui-icon-circle-arrow-w";var g=e(".plupload_scroll",this.container),h=g.scrollTop(),i=g.height(),j=e("#"+a.id).position().top+e("#"+a.id).height();i<j&&g.scrollTop(h+j-i),e("#"+a.id).find(".plupload_file_percent").html(a.percent+"%").end().find(".plupload_file_progress").css("width",a.percent+"%").end().find(".plupload_file_size").html(c.formatSize(a.size))}d+=" ui-state-default plupload_file",e("#"+a.id).attr("class",d).find(".ui-icon").attr("class",f).end().filter(".plupload_delete, .plupload_done, .plupload_failed").find(".ui-icon").click(function(c){b._removeFiles(a),c.preventDefault()})}},_updateTotalProgress:function(){var a=this.uploader;this.filelist[0].scrollTop=this.filelist[0].scrollHeight,this.progressbar.progressbar("value",a.total.percent),this.element.find(".plupload_total_status").html(a.total.percent+"%").end().find(".plupload_total_file_size").html(c.formatSize(a.total.size)).end().find(".plupload_upload_status").html(d.sprintf(g("Uploaded %d/%d files"),a.total.uploaded,a.files.length))},_displayThumbs:function(){function j(a,b,c){var d;a.on(b,function(){clearTimeout(d),d=setTimeout(function(){clearTimeout(d),c()},300)})}function k(){if(!b||!c){var d=e(".plupload_file:eq(0)",a.filelist);b=d.outerWidth(!0),c=d.outerHeight(!0)}var h=a.content.width(),i=a.content.height();f=Math.floor(h/b),g=f*(Math.ceil(i/c)+1)}function l(){var b=Math.floor(a.content.scrollTop()/c)*f;h=e(".plupload_file",a.filelist).slice(b,b+g).filter(":not(.plupload_file_thumb_loaded)").get()}function m(){function b(){"thumbs"===a.view_mode&&(k(),l(),o())}e.fn.resizable&&j(a.container,"resize",b),j(a.window,"resize",b),j(a.content,"scroll",b),a.element.on("viewchanged selected",b),b()}function n(b,c){var f=new d.Image;f.onload=function(){var c=e("#"+b.id+" .plupload_file_thumb",a.filelist).html("");this.embed(c[0],{width:100,height:60,crop:!0,swf_url:d.resolveUrl(a.options.flash_swf_url),xap_url:d.resolveUrl(a.options.silverlight_xap_url)})},f.bind("embedded error",function(){e("#"+b.id,a.filelist).addClass("plupload_file_thumb_loaded"),this.destroy(),setTimeout(c,1)}),f.load(b.getSource())}function o(){"thumbs"!==a.view_mode||i||(l(),h.length&&(i=!0,n(a.getFile(e(h.shift()).attr("id")),function(){i=!1,o()})))}var b,c,f,a=this,g=0,h=[],i=!1;this.options.views.thumbs&&this.element.on("selected",function b(){a.element.off("selected",b),m()})},_addFiles:function(a){var f,b=this;f='<li class="plupload_file ui-state-default" id="%id%"><div class="plupload_file_thumb"><div class="plupload_file_dummy ui-widget-content"><span class="ui-state-disabled">%ext%</span></div></div><div class="plupload_file_name" title="%name%"><span class="plupload_file_namespan">%name%</span></div><div class="plupload_file_action"><div class="ui-icon"> </div></div><div class="plupload_file_size">%size% </div><div class="plupload_file_status"><div class="plupload_file_progress ui-widget-header" style="width: 0%"> </div><span class="plupload_file_percent">%percent% </span></div><div class="plupload_file_fields"> </div></li>',"array"!==c.typeOf(a)&&(a=[a]),e.each(a,function(a,e){var g=d.Mime.getFileExtension(e.name)||"none";b.filelist.append(f.replace(/%(\w+)%/g,function(a,b){return"size"===b?c.formatSize(e.size):"ext"===b?g:e[b]||""})),b._handleFileStatus(e)})},_removeFiles:function(a){var b=this,d=this.uploader;"array"!==c.typeOf(a)&&(a=[a]),e.ui.sortable&&this.options.sortable&&e("tbody",b.filelist).sortable("destroy"),e.each(a,function(a,b){e("#"+b.id).toggle("highlight",function(){this.remove()}),d.removeFile(b)}),d.files.length&&this.options.sortable&&e.ui.sortable&&this._enableSortingList(),this._trigger("updatelist",null,{filelist:this.filelist})},_addFormFields:function(){var a=this;e(".plupload_file_fields",this.filelist).html(""),c.each(this.uploader.files,function(b,d){var f="",g=a.id+"_"+d;b.target_name&&(f+='<input type="hidden" name="'+g+'_tmpname" value="'+c.xmlEncode(b.target_name)+'" />'),f+='<input type="hidden" name="'+g+'_name" value="'+c.xmlEncode(b.name)+'" />',f+='<input type="hidden" name="'+g+'_status" value="'+(b.status===c.DONE?"done":"failed")+'" />',e("#"+b.id).find(".plupload_file_fields").html(f)}),this.counter.val(this.uploader.files.length)},_viewChanged:function(a){this.options.views.remember&&e.cookie&&e.cookie("plupload_ui_view",a,{expires:7,path:"/"}),"IE"===d.Env.browser&&d.Env.version<7&&this.content.attr("style",'height:expression(document.getElementById("'+this.id+'_container").clientHeight - '+("list"===a?133:103)+");"),this.container.removeClass("plupload_view_list plupload_view_thumbs").addClass("plupload_view_"+a),this.view_mode=a,this._trigger("viewchanged",null,{view:a})},_enableViewSwitcher:function(){var b,f,g,a=this,d=e(".plupload_view_switch",this.container);c.each(["list","thumbs"],function(b){a.options.views[b]||d.find('[for="'+a.id+"_view_"+b+'"], #'+a.id+"_view_"+b).remove()}),f=d.find(".plupload_button"),1===f.length?(d.hide(),b=f.eq(0).data("view"),this._viewChanged(b)):e.ui.button&&f.length>1?(this.options.views.remember&&e.cookie&&(b=e.cookie("plupload_ui_view")),~c.inArray(b,["list","thumbs"])||(b=this.options.views.active),d.show().buttonset().find(".ui-button").click(function(c){b=e(this).data("view"),a._viewChanged(b),c.preventDefault()}),g=d.find('[for="'+a.id+"_view_"+b+'"]'),g.length&&g.trigger("click")):(d.show(),this._viewChanged(this.options.views.active)),this.options.views.thumbs&&this._displayThumbs()},_enableRenaming:function(){var a=this;this.filelist.dblclick(function(b){var d,f,g,h,c=e(b.target),i="";c.hasClass("plupload_file_namespan")&&(f=a.uploader.getFile(c.closest(".plupload_file")[0].id),h=f.name,g=/^(.+)(\.[^.]+)$/.exec(h),g&&(h=g[1],i=g[2]),d=e('<input class="plupload_file_rename" type="text" />').width(c.width()).insertAfter(c.hide()),d.val(h).blur(function(){c.show().parent().scrollLeft(0).end().next().remove()}).keydown(function(a){var b=e(this);e.inArray(a.keyCode,[13,27])!==-1&&(a.preventDefault(),13===a.keyCode&&(f.name=b.val()+i,c.html(f.name)),b.blur())})[0].focus())})},_enableSortingList:function(){var a=this;e(".plupload_file",this.filelist).length<2||(e("tbody",this.filelist).sortable("destroy"),this.filelist.sortable({items:".plupload_delete",cancel:"object, .plupload_clearer",stop:function(){var b=[];e.each(e(this).sortable("toArray"),function(c,d){b[b.length]=a.uploader.getFile(d)}),b.unshift(b.length),b.unshift(0),Array.prototype.splice.apply(a.uploader.files,b)}}))}})}(window,document,plupload,mOxie,jQuery);