/* 
File Uploading Script ----------------------------------
------------------------------Start--------------------------------
*/

function SendReceive() {
  this.sendRequest = SGPR.sendRequest;
  this.getRequest = SGPR.getRequest;
}
// --------- Send / Get Post Request ---------
// Sends a Post Request via JSON. (used in variable format for including in other objects).
var SGPR = {
  sendRequest : function (url, request, receiver, quiet) {
    if (receiver) {this.receiver = receiver;}
	this.fail_request=0;
    if (typeof(this.receiver) != 'function' && this.async !== false) {
      alert('Function not supplied for callback.');
      return false;
    }
    if (quiet === null || quiet === undefined) {this.quiet = false;}
  	var jRequest = JSON.stringify(request);
    this.remote = new getHTTPRequest();
    if (this.async == false) {dont_wait = false;}
    else {dont_wait = true;}
    var ref = this;
    if (dont_wait) {
      this.remote.onreadystatechange = function () {
        ref.getRequest(ref.remote, ref);
      };
    }
    this.remote.open('POST', url, dont_wait);  
  
    this.remote.setRequestHeader("Content-type", "text/plain");
    this.remote.setRequestHeader("Content-length", jRequest.length);
    this.remote.setRequestHeader("Connection", "close");
    this.remote.send(jRequest);
    if (!dont_wait) {
      this.response = eval('(' + this.remote.responseText + ')');
    }
  },
  getRequest : function (remote, obj) {
    if (remote.readyState == 4) {
      if (remote.status == 200) {
		if(remote.responseText=="") {
			//obj.fail_request++;
			if(this.active)
				this.timerVar = setTimeout(function(){obj.start_ref();}, this.interval); 
		} else {
				//alert(remote.responseText );
        	var getBack = eval('(' + remote.responseText + ')');
        	obj.receiver(getBack);
		}
		
  	  } else {
        if (!obj.quiet) {alert('There was a problem with the request. Error code: ' + this.remote.status);}
  		else {obj.receiver({status : 'remote', error_msg : remote.status});}
      }
    }
  }
};

//  --------- RepeatGetAction -----------------
//  Sends repeated requests to a file via JSON

function RepeatGetAction(page, request, interval, successFunc, failFunc, stopOnFail) {
	page = page || '';
	request = request || {};
	interval = interval || 3000;
	succssFunc = successFunc || '';
	failFunc = failFunc || '';
	if (stopOnFail === null || stopOnFail === undefined) {stopOnFail = true;}
    this.init(page, request, interval, successFunc, failFunc, stopOnFail);
}

RepeatGetAction.prototype = {
  init : function(page, request, interval, successFunc, failFunc, stopOnFail) {
	  this.page = page;
		this.request = request;
		this.interval = interval;
		this.successFunc = successFunc;
		this.failFunc = failFunc; 
		this.stopOnFail = stopOnFail;
		this.active=true;
		if (this.checkVals()) {
		  this.start();
		}
	},
    sendRequest: SGPR.sendRequest, 
    getRequest: SGPR.getRequest, 
  	form_obj: '',
	checkVals : function() {
    if (this.page !== '' && parseInt(this.interval) > 0 && typeof(this.interval) == 'number' && typeof(this.failFunc) == 'function' && typeof(this.successFunc) == 'function' && (typeof(this.request) == 'object' || typeof(this.request) == 'array')) {
		  return true;
		} else {
		  return false;
		}
	},  
	
	start : function() {
      if (!this.checkVals()) {return false;}
      var ref = this;
      this.timerVar = setTimeout(function(){ref.start_ref();}, this.interval); 
	}, 
	
	start_ref : function () {
      this.sendRequest(this.page, this.request, this.receive, true);
	},
	
	receive : function(getBack) {
      if (!getBack) {
		  this.stop(this.form_obj);
       //  alert('No response sent back to receive function.');
		} else if (getBack.status == 'error') {
		  if (this.stopOnFail) {this.stop(this.form_obj);}
          this.failFunc(getBack);
		} else if (getBack.status == 'remote') {
		  this.stop(this.form_obj);
         // alert('There was a problem with the request. Error code: ' + getBack.error_msg);
		} else {
		  this.successFunc(getBack);
		}
	},
	
	stop : function(form_obj) {
      clearInterval(this.timerVar);
	  this.active=false;
	  //nextFileUpload(form_obj);
	}
};


// -------- getHTTPRequest --------
//  Gets the current HTTP Request object for the relevant browser.

function getHTTPRequest() {
  http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
     http_request = new XMLHttpRequest();
  } else if (window.ActiveXObject) { // IE
     try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
        try {
           http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
     }
  }
 return http_request;
}


var ul_vars = {
  interval : 10, //The time in milleseconds between each status request.
  speeds : []      //Keeps track of the speeds of each upload.
};
var previous_scale = 0;
function uploadFile(form, sid,form_obj) {
	//alert(form+"  :  "+sid);
  previous_scale=0;
  var file_iframe=$(form+'_pIframe');
  var doc=file_iframe.contentWindow.document;
  var theForm = doc.getElementById(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.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.file_obj_name = theForm.file_obj_name.value;
  $(theForm.file_obj_name.value).value=fileName;
  $(theForm.file_obj_name.value+'_status').value="-1";
  
  // 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.  
   //alert(SITE_URL+'filestatus');
  repeater = new RepeatGetAction(SITE_URL+'filestatus', request, ul_vars.interval);
  repeater.form_obj = form_obj;	
  repeater.successFunc = function (getBack) {
	 // alert("yes");
    if (getBack.progress >= 100 || getBack.progress=='done') {
      	getBack.progress = 100;
	  	$(getBack.file_obj_name+'_status').value="1";
		$(getBack.file_obj_name+'_file').value=getBack.file_path;
		//new Effect.Scale('loaderProgressBar', getBack.progress, { duration:.5, scaleX: true, scaleY: false,scaleFrom: previous_scale,scaleContent: false, scaleMode: { originalHeight: 19, originalWidth: 160 } });
		//$('loaderProgressBar').style.width = (getBack.progress / 10)  + 'px';
    	//$('loaderProgressBar').style.height = '19px';
		$(getBack.file_obj_name + '_progress').style.backgroundPosition = ""+(getBack.progress*2) + 'px 0px';
		$('div_file_per').innerHTML=""+getBack.progress+"%";
		$('div_load_f').style.display="none";
    	//$('loaderFileName').innerHTML = Math.round(getBack.current_size/1024) + ' / ' + Math.round(getBack.total_size/1024)+"KB";
     	this.stop(form_obj);
    } else {
		var ref = this;
		if(this.active)
			this.timerVar = setTimeout(function(){ref.start_ref();}, this.interval); 	
	}
    /*if (!ul_vars.speeds[getBack.sid]) {ul_vars.speeds[getBack.sid] = [];}
    else if (ul_vars.speeds[getBack.sid].length == 3) {ul_vars.speeds[getBack.sid].shift();}
    
    ul_vars.speeds[getBack.sid].push(getBack.current_size);
    ul_vars.speeds[getBack.sid].sort(function(a, b) {return a - b;});  //Sorts numerically instead of by string. 
    
    var bytes_sec = 0;
    var bytes_append = 'B/sec';
    if (ul_vars.speeds[getBack.sid].length == 3) {
      var dif = ul_vars.speeds[getBack.sid][2]  - ul_vars.speeds[getBack.sid][0];
      bytes_sec = dif / ((ul_vars.interval / 1000) * 3);
      if (bytes_sec > 1024) {
        bytes_sec = bytes_sec / 1024;
        bytes_append = 'KB/sec';
      } 
    }*/
    //Due to a stupid IE bug, this has been changed...
    $(getBack.file_obj_name + '_progress').style.backgroundPosition = ""+(getBack.progress*2) + 'px 0px';
	$('div_file_per').innerHTML=""+getBack.progress+"%";
	//new Effect.Scale('loaderProgressBar', getBack.progress, { duration:.5, scaleX: true, scaleY: false,scaleFrom: previous_scale,scaleContent: false, scaleMode: { originalHeight: 19, originalWidth: 160 } });
    
	previous_scale = getBack.progress;
	//$('loaderProgressBar').style.width = (getBack.progress * 1.6)  + 'px';
	//alert($('loaderProgressBar').style.backgroundPosition);
    //$('loaderProgressBar').style.height = '19px';
	 
	
    //$(getBack.sid + '_fileName').innerHTML = bytes_sec.toFixed(2) + ' ' + bytes_append;
	
	//$('loaderProgressBar').innerHTML = Math.round(getBack.current_size/1024) + ' / ' + Math.round(getBack.total_size/1024)+"KB";
   // $('loaderFileName').innerHTML = Math.round(getBack.current_size/1024) + ' / ' + Math.round(getBack.total_size/1024)+"KB";
	
  }; 
  repeater.failFunc = function (getBack) {
    this.stop();
   // $(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.start();
}

function $P(str) {
	return parent.document.getElementById(str);	
}
function uploadBFile(id) {
	var form_name=$(id+'_form').value;
	var form_uniqid=$(id+'_uniqid').value;
	$(id + '_progress').style.backgroundPosition = "0px 0px";
	uploadFile(form_name,form_name+"_"+form_uniqid,"");
}
/*
------------------------------End---------------------------------
*/
