/************************************************************
upload_form.js - Function to implement JSON requested AJAX upload.
Copyright (C) 2006  Jeremy Nicoll

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library 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
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Please see lgpl.txt for a copy of the license - this notice and the file 
lgpl.txt must accompany this code.

Please go to www.SeeMySites.net/forum for questions and support.
***************************************************************/

//This function takes two paramaters: form (the ID of the form), and sid, which 
//differentiates the different uploads from each other.
var ul_vars = {
  interval : 1000, //The time in milleseconds between each status request.
  speeds : []      //Keeps track of the speeds of each upload.
};
function uploadForm(form, sid, imageID) {
  toggleLoading(imageID,true);
  var uploadURL = $('#uploadedfiles0').text();
  var theForm = FU(form);
  // The variable request is an object that will contain details of the request.
  var request = {};
  var fileName = '';
  
  // This little bit loops through all the elements in the form, locates the
  // file input field, and extracts the file name of the file being uploaded.
  for (var i=0; i < theForm.elements.length; i++) { 
    ele = theForm.elements[i];
    if (ele.type == 'file') {
      var fileName = ele.value;
    	if (fileName.indexOf('/') > -1) { 
    	  fileName = fileName.substring(fileName.lastIndexOf('/')+1, fileName.length);
      }	else {
    	  fileName = fileName.substring(fileName.lastIndexOf('\\')+1, fileName.length);
      }
      //Since there can only be one file per form for this script, we'll exit the loop here. 
      break;
    }
  }
  if (fileName.replace('/\s/', '').toString() === '') {return;}
  
  theForm.method = "POST";
  //$('#debug').html(theForm.method.toString() + ' ' + theForm.action.toString() + ' ' + theForm.enctype.toString());
  
  theForm.submit();
  var ele;
    
  //These three parts of 'request' are required in order for the filestatus server-side script to work.
  request.sid = sid;
  request.fileName = fileName;
  request.iframe = theForm.target;
  request.objectType = "ViewModel";
  request.imageID = imageID;
  
  // I hope this is self explanatory, but if not, this will send a JSON request to filestatus.php
  // every 3 seconds.  RepeatGetAction is in SendRecieve.js or sr_c.js.  If a single call is
  // successful, the successFunc will be called. Otherwise, failFunc will be called.  
   
  repeater = new RepeatGetAction('filestatus.php', request, ul_vars.interval);
  repeater.overRun = false;
  repeater.progress = 0;
  repeater.successFunc = function (getBack) {
	//overrun keep in check
	if(getBack.total_size == null && this.progress == 100){
		this.stop();
	}else if(this.progress <= getBack.progress){
		this.progress = getBack.progress;
	}
	if (this.progress == 100) {
		this.stop();
		//change with something to sense the url
		setTimeout(function(){
			converter = new RepeatGetAction('imageConversion.php', request, ul_vars.interval);
			converter.go();
			converter.successFunc = function (getBack) {
				setTimeout(function(){
					toggleLoading(imageID,false);
					//swapImage(uploadURL+getBack.usersFolder+fileName+'.jpg',getBack.imageID);
					swapImage(uploadURL+getBack.usersFolder+fileName+getBack.fileName+'.jpg',getBack.imageID);
					},1000);
			}
			converter.failFunc = function (getBack) {
		    	alert(getBack.error_msg);
		  	}
			//this is what we do at the end
		;},100)
    }

	if(this.progress != 100)this.go();
  }; 
  repeater.failFunc = function (getBack) {
    this.stop();
    FU(getBack.iframe).src = 'blank.html';
    alert(getBack.error_msg);
  };
  
  // This MUST be called before the action will start.  When the repeater has served its 
  // purpose (or you get sick of it), you can call repeater.stop() to stop it.
  repeater.go();
}

function toggleLoading(id,on){
	if(on){
		var imagePlace = $('#formImage'+id);
		var image = document.createElement('img');
		image.src = 'images/loading.gif';
		jQuery(image)
		.attr('id' , 'loading'+id)
		.css(
			{
				'position' : 'relative',
				'border' : 0,
				'top': -50,
				'left': -65,
				'zIndex'		: 4
			});
		jQuery(imagePlace).after(image);
	}else{
		$('#loading'+id).remove();
	}	
}

//swap the image in the form to the one that we uploaded
function swapImage(url,id,loading){
	$("#formImage"+id)
	.attr({
		'src' : url,
		'width' : 100,
		'height' :100
	});	
}

function FU(text) {
  return document.getElementById(text);
}
