/**
 *  jqUploader plugin for substituting all input type="file" into a RIA flash uploader
 *  @author: Alexandre Plennevaux (http://www.pixeline.be)
 *  @credits:  M. Alsup, author of jq-flash (i used his smart jq-flash jQuery plugin to adapt it to my needs.)
 *  @credits: Geoff Stearns, author of swfObject
 *  @version: 1 Beta
 *  come to the jquery side  !
 *
 *  This plugin substitutes all input type="file" into a richer flash upload field
 *  Demos can be found at: http://www.pixeline.be/experiments/jqUploader/
 *
 *  NOTE:  This plugin uses (and requires) swfobject.js for proper flash detection.
 *         You must include swfobjects.js on any page that uses this plugin.
 *         @see http://blog.deconcept.com/swfobject/
 *
 *
 *
 *  Usage:
 *      $("input[@type='file']").jqUploader(); // replaces all inputs with attribute="file" with the flash uploader
 *
 *  Or using options:
 *      $("input[@type='file']").jqUploader({
 *          uploadScript: "script_handling_upload_via_flash.php",
	    afterScript:	"script_to_redirect_to_after_upload.php"
 *      });
 *
 *
**/
jQuery.fn.jqUploader = function(options) {
    if (typeof SWFObject == 'undefined') { alert("you need SWFObject for the jqUploader plugin to work"); return this;} // fast fail (swfobjects.js required)
    return this.each(function(index) {
        var $this = jQuery(this);




	// check if max file size is set in html form
	var maxFileSize = $("input[@name='MAX_FILE_SIZE']", $(this.form)).val();

	// fetch label value if any, otherwise set a default one
	var startMessage = $("label[@for='"+this.id+"']",$this.parent()).text();
	if (startMessage !='') {
		$("label[@for='"+this.id+"']",$this.parent()).text('');
	}

	// get form action attribute value as upload script, appending to it a variable telling the script that this is an upload only functionality
/*	var actionURL = $(this.form).attr("action");

	// adds a var setting jqUploader to 1, so you can use it for serverside processing
	var prepender = (actionURL.lastIndexOf("?") != -1) ? "&": "?";
	actionURL = actionURL+prepender+'jqUploader=1';*/
	var cls = (this.className !='') ? this.className: 'jqUploader';

    var opts = jQuery.extend({
            width:            ((cls.match(/w:(\d+)/)||[])[1]) || 320,
            height:           ((cls.match(/h:(\d+)/)||[])[1]) || 85,
            version:          ((cls.match(/ver:(\d+)/)||[])[1]) || 8, // version 8 of flash player required to run jqUpload
            background:       ((cls.match(/bg:#?([0-9a-fA-F]+)/)||[])[1]) || 'FFF', // background color of flash file
            cls:              cls,
            src:              TATI_JS_THEME+'/swf/jqUploader.swf',
//			uploadScript:     actionURL,
			afterScript:      '', // if this is empty, jqUploader will replace the upload swf by a textfield
			varName:	      $this.attr("name"),  //this holds the variable name of the file input field in your html form
			allowedExt:	      'jpg|png|gif|pdf|zip', // allowed extensions
            params:           {},
            flashvars:        {},
            hideSubmit:       true,
            elementType:      'div',
			barColor:		  '0000CC',
			maxFileSize:      maxFileSize,
			startMessage:     startMessage,
			errorSizeMessage: 'File is too big!',
			validFileMessage: 'now click Upload to proceed',
			progressMessage: 'Please wait, uploading '
			}, options || {});
	// disable form submit button

	if (opts.hideSubmit==true) {
			$("*[@type='submit']",this.form).hide();
				}
		if(opts.afterScript==''){
		// THIS WILL BE DONE IN THE USECASE THAT THERE IS NO REDIRECTION TO BE DONE AFTER UPLOAD
			TerminateJQUploader = function(domContainer,filename,varname, hideSubmit){
//				$this= $('#'+domContainer).empty();
//				$('label',$this.parent()).append('<span style="color:#00CC00">Upload of <strong>'+varname+'</strong> finished! (the filename is now stored in the form as an hidden input field)</span>').append('<input name="'+varname+'" type="hidden" id="'+varname+'" value="'+filename+'"/>');
//				myForm = $('#'+domContainer).parents("form");
//				$('#'+domContainer).parents("form").submit(function(){return true});
//				$('#jqLegend').html("<div style='color:#FFEF00;font-weight:bold;font-size:100%'>File uploaded (<b style='color:white'>"+filename+"</b>), click on the 'SAVE' button to save all info</div>");
//				$("*[@type='submit']",myForm).show();
				opts.callBack(domContainer,filename,varname, hideSubmit);
			}
		}
		var containerId = $this.attr("id");
        // convert anchor to span/div/whatever...
        var $el = jQuery('<' + opts.elementType + ' id="'+containerId+'" class="' + opts.cls + '" style="width:'+opts.width+'px"></' + opts.elementType + '>');
        $this.after($el).remove();
        var so = new SWFObject(opts.src, 'movie_player-'+index, opts.width, opts.height, opts.version, '#'+opts.background);
        for (var p in opts.params){
            so.addParam(p, opts.params[p]);
		}
		so.addVariable('containerId', containerId);
		so.addVariable('uploadScript', opts.uploadScript);
		so.addVariable('afterScript', opts.afterScript);
		so.addVariable('allowedExt', opts.allowedExt);
		so.addVariable('varName', opts.varName);
		so.addVariable('barColor', opts.barColor);
		so.addVariable('maxFileSize', opts.maxFileSize);
		so.addVariable('startMessage', opts.startMessage);
		so.addVariable('errorSizeMessage', opts.errorSizeMessage);
		so.addVariable('validFileMessage', opts.validFileMessage);
		so.addVariable('progressMessage', opts.progressMessage);
        for (var fv in opts.flashvars){
            so.addVariable(fv, opts.flashvars[fv]);
		}
        so.write($el[0]);
    });
};