/*
Uploadify v2.1.4
Release Date: November 8, 2010

Copyright (c) 2010 Ronnie Garcia, Travis Nickels

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

if($)(
	function($){
		$.extend($.fn,{
			uploadify:function(options) {
				$(this).each(function(){
					var settings = $.extend({
					id              : $(this).attr('id'), // The ID of the object being Uploadified
					uploader        : 'uploadify.swf', // The path to the uploadify swf file
					script          : 'uploadify.php', // The path to the uploadify backend upload script
					expressInstall  : null, // The path to the express install swf file
					folder          : '', // The path to the upload folder
					height          : 30, // The height of the flash button
					width           : 120, // The width of the flash button
					cancelImg       : 'cancel.png', // The path to the cancel image for the default file queue item container
					wmode           : 'transparent', // The wmode of the flash file
					scriptAccess    : 'sameDomain', // Set to "always" to allow script access across domains
					fileDataName    : 'Filedata', // The name of the file collection object in the backend upload script
					method          : 'POST', // The method for sending variables to the backend upload script
					queueSizeLimit  : 100, // The maximum size of the file queue
					simUploadLimit  : 1, // The number of simultaneous uploads allowed
					queueID         : false, // The optional ID of the queue container
					displayData     : 'speed', // Set to "speed" to show the upload speed in the default queue item
					removeCompleted : false, // Set to true if you want the queue items to be removed when a file is done uploading
					onInit          : function() {}, // Function to run when uploadify is initialized
					onSelect        : function() {}, // Function to run when a file is selected
					onSelectOnce    : function() {}, // Function to run once when files are added to the queue
					onQueueFull     : function() {}, // Function to run when the queue reaches capacity
					onCheck         : function() {}, // Function to run when script checks for duplicate files on the server
					onCancel        : function() {}, // Function to run when an item is cleared from the queue
					onClearQueue    : function() {}, // Function to run when the queue is manually cleared
					onError         : function() {}, // Function to run when an upload item returns an error
					onProgress      : function() {}, // Function to run each time the upload progress is updated
					onComplete      : function() {}, // Function to run when an upload is completed
					onAllComplete   : function() {}  // Function to run when all uploads are completed
				}, options);
				$(this).data('settings',settings);
				var pagePath = location.pathname;
				pagePath = pagePath.split('/');
				pagePath.pop();
				pagePath = pagePath.join('/')+'/';
				var data = {};
				data.uploadifyID = settings.id;
				data.pagepath = pagePath;
				if(settings.buttonImg) data.buttonImg = escape(settings.buttonImg);
				if(settings.buttonText) data.buttonText = escape(settings.buttonText);
				if(settings.rollover) data.rollover = true;
				data.script = settings.script;
				data.folder = escape(settings.folder);
				if(settings.scriptData) {
					var scriptDataString = '';
					for (var name in settings.scriptData) {
						scriptDataString += '&'+name+'='+settings.scriptData[name];
					}
					data.scriptData = escape(scriptDataString.substr(1));
				}
				data.width          = settings.width;
				data.height         = settings.height;
				data.wmode          = settings.wmode;
				data.method         = settings.method;
				data.queueSizeLimit = settings.queueSizeLimit;
				data.simUploadLimit = settings.simUploadLimit;
				if(settings.hideButton)   data.hideButton   = true;
				if(settings.fileDesc)     data.fileDesc     = settings.fileDesc;
				if(settings.fileExt)      data.fileExt      = settings.fileExt;
				if(settings.multi)        data.multi        = true;
				if(settings.auto)         data.auto         = true;
				if(settings.sizeLimit)    data.sizeLimit    = settings.sizeLimit;
				if(settings.checkScript)  data.checkScript  = settings.checkScript;
				if(settings.fileDataName) data.fileDataName = settings.fileDataName;
				if(settings.queueID)      data.queueID      = settings.queueID;
				if(settings.onInit() !== false) {
					$(this).css('display','none');
					$(this).after('<div id="'+$(this).attr('id')+'Uploader"></div>');
					swfobject.embedSWF(settings.uploader, settings.id+'Uploader', settings.width, settings.height, '9.0.24', settings.expressInstall, data, {'menu':'false','quality':'high','wmode':settings.wmode,'allowScriptAccess':settings.scriptAccess},{},function(event) {
						if(typeof(settings.onSWFReady) == 'function' && event.success) settings.onSWFReady();
					});
					if(settings.queueID == false) {
						$("#"+$(this).attr('id')+"Uploader").after('<div id="'+$(this).attr('id')+'Queue" class="uploadifyQueue"></div>');
					} else {
						$("#"+settings.queueID).addClass('uploadifyQueue');
					}
				}
				if(typeof(settings.onOpen) == 'function') {
					$(this).bind("uploadifyOpen", settings.onOpen);
				}
				$(this).bind("uploadifySelect", {'action': settings.onSelect, 'queueID': settings.queueID}, function(event, ID, fileObj) {
					if(event.data.action(event, ID, fileObj) !== false) {
						var byteSize = Math.round(fileObj.size / 1024 * 100) * .01;
						var suffix = 'KB';
						if(byteSize > 1000) {
							byteSize = Math.round(byteSize *.001 * 100) * .01;
							suffix = 'MB';
						}
						var sizeParts = byteSize.toString().split('.');
						if(sizeParts.length > 1) {
							byteSize = sizeParts[0]+'.'+sizeParts[1].substr(0,2);
						} else {
							byteSize = sizeParts[0];
						}
						if(fileObj.name.length > 40) {
							fileName = fileObj.name.substr(0,40)+'...';
						} else {
							fileName = fileObj.name;
						}
						queue = '#'+$(this).attr('id')+'Queue';
						if(event.data.queueID) {
							queue = '#'+event.data.queueID;
						}
//<img src="'+settings.cancelImg+'" border="0" />
						$(queue).append('<div id="'+$(this).attr('id')+ID+'" class="uploadifyQueueItem">\
								<div class="cancel">\
									<a href="javascript:$(\'#'+$(this).attr('id')+'\').uploadifyCancel(\''+ID+'\')"><span class="ico b_no"></span></a>\
								</div>\
								<span class="fileName">'+fileName+' ('+byteSize+suffix+')</span><span class="percentage"></span>\
								<div style="clear:both"></div>\
								<div class="uploadifyProgress">\
									<div id="'+$(this).attr('id')+ID+'ProgressBar" class="uploadifyProgressBar"><!--Progress Bar--></div>\
								</div>\
							</div>');
					}
				});
				$(this).bind("uploadifySelectOnce", {'action': settings.onSelectOnce}, function(event, data) {
					event.data.action(event, data);
					if(settings.auto) {
						if(settings.checkScript) {
							$(this).uploadifyUpload(null, false);
						} else {
							$(this).uploadifyUpload(null, true);
						}
					}
				});
				$(this).bind("uploadifyQueueFull", {'action': settings.onQueueFull}, function(event, queueSizeLimit) {
					if(event.data.action(event, queueSizeLimit) !== false) {
						alert('The queue is full.  The max size is '+queueSizeLimit+'.');
					}
				});
				$(this).bind("uploadifyCheckExist", {'action': settings.onCheck}, function(event, checkScript, fileQueueObj, folder, single) {
					var postData = new Object();
					postData = fileQueueObj;
					postData.folder = (folder.substr(0,1) == '/') ? folder : pagePath+folder;
					if(single) {
						for (var ID in fileQueueObj) {
							var singleFileID = ID;
						}
					}
					$.post(checkScript, postData, function(data) {
						for(var key in data) {
							if(event.data.action(event, data, key) !== false) {
								var replaceFile = confirm("Do you want to replace the file "+data[key]+"?");
								if(!replaceFile) {
									document.getElementById($(event.target).attr('id')+'Uploader').cancelFileUpload(key,true,true);
								}
							}
						}
						if(single) {
							document.getElementById($(event.target).attr('id')+'Uploader').startFileUpload(singleFileID, true);
						} else {
							document.getElementById($(event.target).attr('id')+'Uploader').startFileUpload(null, true);
						}
					}, "json");
				});
				$(this).bind("uploadifyCancel", {'action': settings.onCancel}, function(event, ID, fileObj, data, remove, clearFast) {
					if(event.data.action(event, ID, fileObj, data, clearFast, options.script) !== false) {
						if(remove) {
//							var fadeSpeed = (clearFast == true) ? 0 : 150;
							var fadeSpeed=0;
							$("#"+$(this).attr('id')+ID).fadeOut(fadeSpeed, function() { $(this).remove() });
						}
					}
				});
				$(this).bind("uploadifyClearQueue", {'action': settings.onClearQueue}, function(event, clearFast) {
					var queueID = (settings.queueID) ? settings.queueID : $(this).attr('id')+'Queue';
					if(clearFast) {
						flash_upload_cancel(event, false, false, false, false, options.script);
						$("#"+queueID).find('.uploadifyQueueItem').remove();
					}
					if(event.data.action(event, clearFast) !== false) {
						$("#"+queueID).find('.uploadifyQueueItem').each(function() {
							var index = $('.uploadifyQueueItem').index(this);
							$(this).delay(index * 100).fadeOut(150, function() { $(this).remove() });
						});
					}
				});
				var errorArray = [];
				$(this).bind("uploadifyError", {'action': settings.onError}, function(event, ID, fileObj, errorObj) {
					if(event.data.action(event, ID, fileObj, errorObj) !== false) {
						var fileArray = new Array(ID, fileObj, errorObj);
						errorArray.push(fileArray);
						err_msg=errorObj.type+" Error";
						if(errorObj.type=="File Size") err_msg='Wybrany plik jest za duży!';
						if(errorObj.type=="HTTP") err_msg='Plik nie został zapisany!';

						$("#"+$(this).attr('id')+ID).find('.percentage').text(err_msg);
						$("#"+$(this).attr('id')+ID).find('.uploadifyProgress').hide();
						$("#"+$(this).attr('id')+ID).addClass('uploadifyError');
					}
				});
				if(typeof(settings.onUpload) == 'function') {
					$(this).bind("uploadifyUpload", settings.onUpload);
				}
				$(this).bind("uploadifyProgress", {'action': settings.onProgress, 'toDisplay': settings.displayData}, function(event, ID, fileObj, data) {
					if(event.data.action(event, ID, fileObj, data) !== false) {
						$("#"+$(this).attr('id')+ID+"ProgressBar").animate({'width': data.percentage+'%'},150,function() {
							if(data.percentage == 100) {
								$(this).closest('.uploadifyProgress').fadeOut(150,function() {$(this).remove()});
							}
						});
						if(event.data.toDisplay == 'percentage') displayData = data.percentage+'%';
						if(event.data.toDisplay == 'speed') displayData = Math.round(data.speed)+' KB/s';
						if(event.data.toDisplay == null) displayData = ' ';
						$("#"+$(this).attr('id')+ID).find('.percentage').text(displayData);
					}
				});
				$(this).bind("uploadifyComplete", {'action': settings.onComplete}, function(event, ID, fileObj, response, data) {
					if(event.data.action(event, ID, fileObj, unescape(response), data) !== false) {
						r=unescape(response);
						if(r.indexOf('{{')!=-1 && r.indexOf('}}')!=-1) {
							$("#"+$(this).attr('id')+ID).find('.percentage').text('OK');
							$("#"+$(this).attr('id')+ID).find('.fileName').text(r.replace('{{','').replace('}}',''));
							if(settings.removeCompleted) $("#"+$(event.target).attr('id')+ID).fadeOut(150,function() {$(this).remove()});
							$("#"+$(event.target).attr('id')+ID).addClass('completed');

							ext=fileObj.type.replace('.','').toLowerCase();
							if(ext=='jpg' || ext=='jpeg' || ext=='gif' || ext=='png') {
								//bind image editor icon
							}
//							$("#"+$(event.target).attr('id')+ID).find('.cancel').remove();
						} else {
							$("#"+$(this).attr('id')+ID).find('.percentage').text(r);
							$("#"+$(this).attr('id')+ID).find('.uploadifyProgress').hide();
							$("#"+$(this).attr('id')+ID).addClass('uploadifyError');
						}
					}
				});
				if(typeof(settings.onAllComplete) == 'function') {
					$(this).bind("uploadifyAllComplete", {'action': settings.onAllComplete}, function(event, data) {
						if(event.data.action(event, data) !== false) {
							errorArray = [];
						}
					});
				}
			});
		},
		uploadifySettings:function(settingName, settingValue, resetObject) {
			var returnValue = false;
			$(this).each(function() {
				if(settingName == 'scriptData' && settingValue != null) {
					if(resetObject) {
						var scriptData = settingValue;
					} else {
						var scriptData = $.extend($(this).data('settings').scriptData, settingValue);
					}
					var scriptDataString = '';
					for (var name in scriptData) {
						scriptDataString += '&'+name+'='+scriptData[name];
					}
					settingValue = escape(scriptDataString.substr(1));
				}
				returnValue = document.getElementById($(this).attr('id')+'Uploader').updateSettings(settingName, settingValue);
			});
			if(settingValue == null) {
				if(settingName == 'scriptData') {
					var returnSplit = unescape(returnValue).split('&');
					var returnObj   = new Object();
					for (var i = 0; i < returnSplit.length; i++) {
						var iSplit = returnSplit[i].split('=');
						returnObj[iSplit[0]] = iSplit[1];
					}
					returnValue = returnObj;
				}
			}
			return returnValue;
		},
		uploadifyUpload:function(ID,checkComplete) {
			$(this).each(function() {
				if(!checkComplete) checkComplete = false;
				document.getElementById($(this).attr('id')+'Uploader').startFileUpload(ID, checkComplete);
			});
		},
		uploadifyCancel:function(ID) {
			$(this).each(function() {
				document.getElementById($(this).attr('id')+'Uploader').cancelFileUpload(ID, true, true, false);
			});
		},
		uploadifyClearQueue:function() {
			$(this).each(function() {
				document.getElementById($(this).attr('id')+'Uploader').clearFileUploadQueue(false);
			});
		},
		uploadifyGetSetting:function(key) {
			s=$(this).data('settings');
			return eval("s."+key);
		}
	})
})($);


function flash_upload_cancel(event, ID, fileObj, data, clearFast, script) {
	form_name=$(event.target).closest("form").attr("id").replace("_form","");
	field_id=$(event.target).attr('id');
	if(ID!=false) {
		file_name=$("#"+field_id+ID).find(".fileName").text();
		$.ajax({ type:"post", cache:false, url:script, data:"action=delete&form_name="+form_name+"&field_id="+field_id+"&id="+ID+"&file_name="+encodeURIComponent(file_name) });
	} else {
		$.ajax({ type:"post", cache:false, url:script, data:"action=delete&form_name="+form_name+"&field_id="+field_id });
	}


	if(typeof(uploadifyCancelCallback)!="undefined") {
		uploadifyCancelCallback(form_name,field_id);
	}
}


function flash_upload_complete(event, ID, fileObj, data) {
	file_name=data.replace('{{','').replace('}}','');
	ext=fileObj.type.replace('.','').toLowerCase();

	form_name=$(event.target).closest("form").attr("id").replace("_form","");
	field_id=$(event.target).attr('id');

	if(ext=='jpg' || ext=='jpeg' || ext=='gif' || ext=='png') {
		$("#"+field_id+ID).find('span.fileName').after('<a class="image_edit" href="javascript:void(0)" onclick="image_editor(\''+$(event.target).closest("form").attr("id")+'\', \''+field_id+'\', \''+file_name+'\', true)"><span class="ico b_crop"></span></a>');
	}


	if(typeof(uploadifyUploadCallback)!="undefined") {
		uploadifyUploadCallback(form_name,field_id);
	}

//	image_editor($(event.target).closest("form").attr('id'), field_id, file_name, true);
}


function flash_download_file(field_id) {
	$.colorbox({
		'initialHeight': '80px',
		'transition': 'elastic',
		'href': 'includes/downloadify.php?SID='+SID+'&field_id='+field_id+'&title='+encodeURIComponent($("div.mainbox_header_navi h3").text())
	});
}

var download_in_progress=false;
function flash_download_process(field_id) {
	if(download_in_progress==true) return false;
	file=encodeURIComponent($('#download_file').val());
	if(file=="") {
		$("#download_file").focus();
		return false;
	}
	download_in_progress=true;

	form_name=$("#"+field_id).closest('form').attr('id').replace('_form','');

	$('#download_file_form').find('.submit').attr('disabled','disabled').addClass('but_disabled');
	$('#download_file').attr('disabled','disabled').attr('readonly','readonly');
	$('#download_cont').html('<img src="images/loading.gif" alt="" /> <span>&nbsp;&nbsp;&nbsp;Pobieranie...</span>');

	$.ajax({
		url: 'includes/downloadify.php?SID='+SID,
		data: 'form_name='+form_name+'&post_name='+field_id+'&download_file='+file,
		type: 'post',
		dataType: 'html',
		cache: false,
		error: function(request) { alert('ServerSide form validation error!'); },
		success: function(data) {
			download_in_progress=false;
			$('#download_file_form').find('.submit').removeAttr('disabled').removeClass('but_disabled');
			$('#download_file').removeAttr('disabled').removeAttr('readonly').val("");

			if(data.indexOf('{{')!=-1 && data.indexOf('}}')!=-1) {
				data=data.replace('{{','').replace('}}','');
				flash_download_file_completed(field_id,data);

				$('#download_cont').html('<span class="ico b_yes"></span><span style="font-weight:bold;">&nbsp;&nbsp;&nbsp;Pobrano</span>');

				setTimeout(function(){
					$('#download_cont').html('');
					$.colorbox.close();
				},750);
			} else {
				$('#download_cont').html('<b>'+data+'</b>');

				setTimeout(function(){
					$('#download_cont').html('');
				},1500);
			}
		}
	});
}



var flash_download_file_counter=0;
function flash_download_file_completed(field_id,file_name) {
	thiss=$('#'+field_id);
	flash_download_file_counter++;
	ID='DL'+(flash_download_file_counter<9 ? '0'+flash_download_file_counter:flash_download_file_counter)+'XX';
//	file_name='external_file.jpg';

//				$(this).bind("uploadifySelect", {'action': settings.onSelect, 'queueID': settings.queueID}, function(event, ID, fileObj) {
//					if(event.data.action(event, ID, fileObj) !== false) {


	if($('#'+field_id).uploadifyGetSetting("multi")!=true) {
		$.each($('#'+field_id+'_queue > div.uploadifyQueueItem'), function(index,item){
			old_id=$(item).attr("id").replace(field_id,"");
			$('#'+field_id).uploadifyCancel(old_id)
		})
	}



						if(file_name.length > 40) {
							fileName = file_name.substr(0,40)+'...';
						} else {
							fileName = file_name;
						}

						queue = '#'+field_id+'_queue';
//						if(event.data.queueID) {
//							queue = '#'+event.data.queueID;
//						}

						$(queue).append('<div id="'+$(thiss).attr('id')+ID+'" class="uploadifyQueueItem completed">\
								<div class="cancel">\
									<a href="javascript:$(\'#'+$(thiss).attr('id')+'\').uploadifyCancel(\''+ID+'\')"><span class="ico b_no"></span></a>\
								</div>\
								<span class="fileName">'+fileName+'</span><span class="percentage">OK</span>\
								<div style="clear:both"></div>\
							</div>');



						ext_temp=file_name.split('.');
						ext=ext_temp[ext_temp.length-1].toLowerCase();

						if(ext=='jpg' || ext=='jpeg' || ext=='gif' || ext=='png') {
							$("#"+field_id+ID).find('span.fileName').after('<a class="image_edit" href="javascript:void(0)" onclick="image_editor(\''+$(thiss).closest("form").attr("id")+'\', \''+field_id+'\', \''+file_name+'\', true)"><span class="ico b_crop"></span></a>');
						}

//					}
//				});
}