var lastFileId = 0;

function fileQueued(file) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Venter...");
		progress.toggleCancel(true, this);

		var status = document.getElementById("divStatus");
	   status.innerHTML = '';
	
	} catch (ex) {
		this.debug(ex);
	}

}

function fileQueueError(file, errorCode, message) {
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			alert("Du har forsøkt å legge for mange filer i køen.\n" + (message === 0 ? "Du har nådd din opplastingsgrense." : "Du kan velge " + (message > 1 ? "opp til " + message + " filer." : "en fil.")));
			return;
		}

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("Filen er for stor.");
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Kan ikke laste opp filer som er 0 bytes.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Ugyldig filtype!.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		default:
			if (file !== null) {
				progress.setStatus("Noe gikk galt... :(");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (numFilesSelected > 0) {
			document.getElementById(this.customSettings.cancelButtonId).disabled = false;
		}
		
		/* I want auto start the upload and I can do that here */
		this.startUpload();
	   
	} catch (ex)  {
        this.debug(ex);
	}
	
}

function uploadStart(file) {
   
   try {
		/* I don't want to do any file validation or anything,  I'll just update the UI and
		return true to indicate that the upload should start.
		It's important to update the UI here because in Linux no uploadProgress events are called. The best
		we can do is say we are uploading.
		 */
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Laster opp...");
		progress.toggleCancel(true, this);
		// progress.createBufferElement(file);
		
	}
	catch (ex) {}
	
	return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {
	try {
		
	   var percent = Math.ceil((bytesLoaded / bytesTotal) * 400);
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		var now = new Date();
		    now = now.getTime() / 1000;
	   
      updateFileStatus( parseInt( file.id.split('_')[2] ), file, 'uploadProgress' );
      
		progress.setProgress(percent);
		
		if( !starttime[file.id] ) {
		   starttime[file.id] = now;
		}
		
		/*
		if( !lasttime[file.id] ) {
		   lasttime[file.id] = now;
		   lastbytes[file.id] = 0;
		}
		
		if( now - lasttime[file.id] > 10 ) {
		   lasttime[file.id] = now;
		   lastbytes[file.id] = bytesLoaded;
		}
      */
		var timePassed = now - starttime[file.id];
		
		if( timePassed > 0 ) {
		   
		   var speed = Math.ceil( Math.round( bytesLoaded / timePassed ) / 1024 );
		   var timeRemaining = Math.ceil( Math.round( ( bytesTotal - bytesLoaded ) / 1024 ) / speed );
		   var fullRemaining = timeRemaining;
		   var hours = Math.floor( timeRemaining / 60 / 60 ); timeRemaining -= hours * 60 * 60;
		   var mins = Math.floor( timeRemaining / 60 ); timeRemaining -= mins * 60;
		   var secs = timeRemaining;
		   var timeRemainingStr = ', ';
		   
	      if( hours < 10 ) hours = '0'+hours;
	      if( mins < 10 ) mins = '0'+mins;
	      if( secs < 10 ) secs = '0'+secs;
		   timeRemainingStr = timeRemainingStr + hours+':'+mins+':'+secs;
         
		   if( fullRemaining ) {
		      timeRemainingStr = timeRemainingStr + ' gjenstående';
		   } else {
		      timeRemainingStr = ' - Lagrer...';
		   }
		   
		   var speedAndTimeRemaining = ', gj. '+speed+' KB/sec'+timeRemainingStr;
		   
		} else {
		   
		   var speedAndTimeRemaining = '';
		   
		}
		
		bytesLoadedKb = Math.round( bytesLoaded / 1024, 2 );
		bytesTotalKb = Math.round( bytesTotal / 1024, 2 );
		
		progress.setStatus( "Laster opp... ("+bytesLoadedKb+' KB av '+bytesTotalKb+' KB'+speedAndTimeRemaining+')' );
		
	} catch (ex) {
		this.debug(ex);
	}
}

function updateFileStatus( thisFileId, file, trigger ) {
   
   if( thisFileId != lastFileId && thisFileId > 0 ) {
      lastFileId = thisFileId;
      $('fsUploadProgress').scrollTop = ( thisFileId - 1 ) * ( $(file.id).offsetHeight + ( 2 * 2 ) + 1 );
   }
   
}

function uploadSuccess(file, serverData) {
	
   isUploading = true;
   window.onbeforeunload = function() {
		
      return 'Du laster enda opp! Dersom du går vekk fra denne siden, vil opplastingen avbrytes!';
      
   }
   
   updateFileStatus( parseInt( file.id.split('_')[2] ) + 1, file, 'uploadSuccess' );
   
   try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setComplete();
		progress.setStatus("Ferdig.");
		progress.toggleCancel(false);

	} catch (ex) {
		this.debug(ex);
	}
}

function uploadError(file, errorCode, message) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("Feil ved opplasting: " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Opplastingen feilet.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("Server (IO) Feil");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Sikkerhetsfeil");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Opplastingsbegrensning nådd.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus("Ble ikke korrekt validert. Hopper over opplasting.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			// If there aren't any files left (they were all cancelled) disable the cancel button
			if (this.getStats().files_queued === 0) {
				document.getElementById(this.customSettings.cancelButtonId).disabled = true;
			}
			progress.setStatus("Avbrutt");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Stoppet");
			break;
		default:
			progress.setStatus("Ukjent feil: " + errorCode);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function uploadComplete(file) {
	if (this.getStats().files_queued === 0) {
		document.getElementById(this.customSettings.cancelButtonId).disabled = true;
	}
}

// This event comes from the Queue Plugin
function queueComplete(numFilesUploaded) {
	
   reloadImageThumbnails();
   
   //var status = document.getElementById("divStatus");
   var status = document.getElementById("uploadStatus");
	status.innerHTML = '<br/><p class="header">' + uploaddonetext + '</p><p class="bread">' + uploadmoretext + '</p><button type="submit" class="action-button" value="' + nextbuttontext + '" onclick="document.location.href=\'' + nextpage +'\'" style="font-size: 18px; font-weight: bold; cursor: pointer; cursor: hand; color: #000; background-color: transparent;">' + nextbuttontext + '<img src="/grafikk/icon_next.gif" alt=""/></button>';
	//numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
	
   isUploading = false;
   window.onbeforeunload = Prototype.emptyFunction;
   
}

function reloadImageThumbnails() {
   
   var batchid = $F('batchid');
   
	new Ajax.Action( 'uploadflash', ['batchid='+batchid], (function( xml ) {
      
	   var data = eval( '('+xml.responseText+')' );
      $A(data).each( function( item ) {
         
         if(!$('image_thumb_'+item.bid ) ) {
            
            if( allimages.length > 0 ) {
               
               var img = allimages.shift();
               if( img ) {
                  
                  img = $(img);
                  img.removeClassName( 'new' );
                  img.id = 'image_thumb_'+item.bid;
                  img.style.backgroundImage = 'url(/productdesigner/images/spinner.gif)';
                  
                  var preload = new Image();
                  preload.onload = function() { img.style.backgroundImage = 'url('+item.url+')'; }
                  preload.src = item.url;
                  
               }
               
            }
            
         }
         
      } );
      
	} ) );
	
}

Ajax.URL = '/productdesigner.php';

Ajax.Action = Class.create();
Ajax.Action.prototype = Object.extend( Ajax.Request.prototype, {

   initialize: function( event, param, callback, url ) {
      
      if( !url ) url = Ajax.URL;
      var params = 'action=' + event;
      if( param ) {
         param.each( function( item ) {
            params = params + '&' + item;
         } );
      }
      
      this.transport = Ajax.getTransport();
      
      var options = { method: 'get',
         parameters: params,
         onComplete: Prototype.emptyFunction
      }
      
      if( callback ) {
         options.onComplete = callback;
      } else {
         options.onComplete = (function ( res ) {
            
            if( res.status == 200 ) {
   
               try {
                  eval( res.responseText );
               } catch( err ) {
                  alert( res.responseText + "\n\nerror: " + err.description );
               }
   
            }
   
         }).bind( this );
      }
      this.setOptions( options );
      this.request( url );

   }

} );
