/*
JQuery File Upload Plugin v1.5.0 by RonnieSan
Copyright (C) 2009  Ronnie Garcia
Upload Speed added by Travis Nichols

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

var flashVer = -1;
if (navigator.plugins != null && navigator.plugins.length > 0) {
	if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
		var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
		var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
		var descArray = flashDescription.split(" ");
		var tempArrayMajor = descArray[2].split(".");			
		var versionMajor = tempArrayMajor[0];
		var versionMinor = tempArrayMajor[1];
		var versionRevision = descArray[3];
		if (versionRevision == "") {
			versionRevision = descArray[4];
		}
		if (versionRevision[0] == "d") {
			versionRevision = versionRevision.substring(1);
		} else if (versionRevision[0] == "r") {
			versionRevision = versionRevision.substring(1);
			if (versionRevision.indexOf("d") > 0) {
				versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
			}
		}
		var flashVer = versionMajor + "." + versionMinor	 + "." + versionRevision;
	}
}
else if ( $j.browser.msie ) {
	var version;
	var axo;
	var e;
	try {
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}	
	flashVer = version.replace("WIN ","").replace(",",".");
}
flashVer = flashVer.split(".")[0];

if(jQuery)(
	function($){
		$.extend($.fn,{
			fileUpload:function(options) {
				if (flashVer >= 9) {
					$j(this).each(function(){
						settings = $.extend({
							uploader:      'uploader.swf',
							script:        'uploader.php',
							folder:        '',
							height:        23,
							width:         66,
							cancelImg:     'cancel.png',
							wmode:         'opaque',
							scriptAccess:  'sameDomain',
							onInit:        function() {},
							onSelect:      function() {},
							onCancel:      function() {},
							onError:       function() {},
							onProgress:    function() {},
							onComplete:    function() {}
						}, options);
						var pagePath = location.pathname;
						pagePath = pagePath.split('/');
						pagePath.pop();
						pagePath = pagePath.join('/') + '/';
						var 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); 
						}
						data += '&btnWidth=' + settings.width;
						data += '&btnHeight=' + settings.height;
						data += '&wmode=' + settings.wmode;
						//alert(data);
						if (settings.fileDesc) data += '&fileDesc=' + settings.fileDesc + '&fileExt=' + settings.fileExt;
						if (settings.multi) data += '&multi=true';
						if (settings.auto) data += '&auto=true';
						if (settings.sizeLimit) data += '&sizeLimit=' + settings.sizeLimit;
						if ($.browser.msie) {
							flashElement = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + settings.width + '" height="' + settings.height + '" id="' + $j(this).attr("id")  + 'Uploader" class="fileUploaderBtn">\
								<param name="movie" value="' + settings.uploader + '?fileUploadID=' + $j(this).attr("id") + data + '" />\
								<param name="quality" value="high" />\
								<param name="wmode" value="' + settings.wmode + '" />\
								<param name="allowScriptAccess" value="' + settings.scriptAccess + '">\
								<param name="swfversion" value="9.0.0.0" />\
							</object>';
						} else {
							flashElement = '<embed src="' + settings.uploader + '?fileUploadID=' + $j(this).attr("id") + data + '" quality="high" width="' + settings.width + '" height="' + settings.height + '" id="' + $j(this).attr("id") + 'Uploader" class="fileUploaderBtn" name="' + $j(this).attr("id") + 'Uploader" allowScriptAccess="' + settings.scriptAccess + '" wmode="' + settings.wmode + '" type="application/x-shockwave-flash" />';
						}
						if (settings.onInit() !== false) {
							$j(this).css('display','none');
							if ($.browser.msie) {
								$j(this).after('<div id="' + $j(this).attr("id")  + 'Uploader"></div>');
								document.getElementById($j(this).attr("id")  + 'Uploader').outerHTML = flashElement;
							} else {
								$j(this).after(flashElement);
							}
							//$j("#" + $j(this).attr('id') + "Uploader")							
							$j("#" + $j(this).attr('id') + "Note").after('<div id="' + $j(this).attr('id') + 'Queue" class="fileUploadQueue"></div>');
						}
						$j(this).bind("rfuSelect", {'action': settings.onSelect}, function(event, queueID, fileObj) {
							if (event.data.action(event, queueID, 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 > 20) {
									fileName = fileObj.name.substr(0,20) + '...';
								} else {
									fileName = fileObj.name;
								}
								$j('#' + $j(this).attr('id') + 'Queue').append('<div id="' + $j(this).attr('id') + queueID + '" class="fileUploadQueueItem">\
									<div class="cancel">\
										<a href="javascript:$j(\'#' + $j(this).attr('id') + '\').fileUploadCancel(\'' + queueID + '\')"><img src="' + settings.cancelImg + '" border="0" /></a>\
									</div>\
									<span class="fileName">' + fileName + ' (' + byteSize + suffix + ')</span><span class="percentage">&nbsp;</span>\
									<div class="fileUploadProgress" style="width: 100%;">\
										<div id="' + $j(this).attr('id') + queueID + 'ProgressBar" class="fileUploadProgressBar" style="width: 1px; height: 3px;"></div>\
									</div>\
								  </div>');
							}
						});
						if (typeof(settings.onSelectOnce) == 'function') {
							$j(this).bind("rfuSelectOnce", settings.onSelectOnce);
						}
						$j(this).bind("rfuCancel", {'action': settings.onCancel}, function(event, queueID, fileObj, data) {
							if (event.data.action(event, queueID, fileObj, data) !== false) {
								$j("#" + $j(this).attr('id') + queueID).fadeOut(250, function() { $j("#" + $j(this).attr('id') + queueID).remove()});
							}
						});
						$j(this).bind("rfuClearQueue", {'action': settings.onClearQueue}, function() {
							if (event.data.action() !== false) {
								$j('#' + $j(this).attr('id') + 'Queue').contents().fadeOut(250, function() {$j('#' + $j(this).attr('id') + 'Queue').empty()});
							}
						});
						$j(this).bind("rfuError", {'action': settings.onError}, function(event, queueID, fileObj, errorObj) {
							if (event.data.action(event, queueID, fileObj, errorObj) !== false) {
								$j("#" + $j(this).attr('id') + queueID + " .fileName").text(errorObj.type + " Error - " + fileObj.name);
								$j("#" + $j(this).attr('id') + queueID).css({'border': '3px solid #FBCBBC', 'background-color': '#FDE5DD'});
							}
						});
						$j(this).bind("rfuProgress", {'action': settings.onProgress}, function(event, queueID, fileObj, data) {
							if (event.data.action(event, queueID, fileObj, data) !== false) {
								$j("#" + $j(this).attr('id') + queueID + "ProgressBar").css('width', data.percentage + '%');
								$j("#" + $j(this).attr('id') + queueID + " .percentage").text(' - ' + data.percentage + '%');
							}
						});
						$j(this).bind("rfuComplete", {'action': settings.onComplete}, function(event, queueID, fileObj, response, data) {
							if (event.data.action(event, queueID, fileObj, response, data) !== false) {
								$j("#" + $j(this).attr('id') + queueID).fadeOut(250, function() { $j("#" + $j(this).attr('id') + queueID).remove()});
								$j("#" + $j(this).attr('id') + queueID + " .uploadSpeed").text(' - Completed');								
							}
						});
						if (typeof(settings.onAllComplete) == 'function') {
							$j(this).bind("rfuAllComplete", settings.onAllComplete);
						}
					});
				}
			},
			fileUploadSettings:function(settingName, settingValue) {
				$j(this).each(function() {									  
					document.getElementById($j(this).attr('id') + 'Uploader').updateSettings(settingName,settingValue);
				});
			},
			fileUploadStart:function(queueID) {
				$j(this).each(function() {
					document.getElementById($j(this).attr('id') + 'Uploader').startFileUpload(queueID);
				});
			},
			fileUploadCancel:function(queueID) {
				$j(this).each(function() {
					document.getElementById($j(this).attr('id') + 'Uploader').cancelFileUpload(queueID);
				});
			},
			fileUploadClearQueue:function() {
				$j(this).each(function() {
					document.getElementById($j(this).attr('id') + 'Uploader').clearFileUploadQueue();
				});
			}
		})
	}
)(jQuery);
