/************************************************************
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.
***************************************************************/
function checkFile(form, sid) {
	var allowedFileTypes = ['jpg', 'tiff', 'jpeg', 'png', 'gif']; 
	var fileInputElement = 'filename_'+sid;
	var theFileName = $(fileInputElement).value;
	theFileType = theFileName.substring(theFileName.lastIndexOf('.')+1, theFileName.length);
	for (i=0; i<allowedFileTypes.length; i++) {
		if (theFileType.toLowerCase() == allowedFileTypes[i]) {
			uploadForm(form, sid+form, theFileName, sid, allowedFileTypes[i]);
			break;
		}
	}
	if (i==allowedFileTypes.length) {
		alert('Please choose and image file in one of the following supported formats\n\n.jpg .tiff .jpeg .png .gif');
	}
		
}


//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 : 3000, //The time in milleseconds between each status request.
  speeds : []      //Keeps track of the speeds of each upload.
};
function uploadForm(form, sid, fileName, sid_orig, fileType) {
	var theForm = $(form);
	// The variable request is an object that will contain details of the request.
	var request = {};
  
	if (fileName.indexOf('/') > -1) { 
	  fileName = fileName.substring(fileName.lastIndexOf('/')+1, fileName.length);
	}
	else {
	  fileName = fileName.substring(fileName.lastIndexOf('\\')+1, fileName.length);
	}
	
  if (fileName.replace('/\s/', '').toString() === '') {return;}
  
  $(sid + '_img').style.visibility = 'hidden';
  $(sid + '_fileName').innerHTML = '&nbsp;Uploading...'
  $(sid + '_progress_gubbins').style.visibility = 'visible';
  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;
  // We want the file to be saved using a unique session ID, so use the sid
  request.fileName = sid_orig+'.'+fileType;
  request.iframe = theForm.target;
  
  
  // 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('uploader2/filestatus.php', request, ul_vars.interval);
  repeater.successFunc = function (getBack) {
    if (getBack.progress >= 100 || getBack.progress=='done') {
      getBack.progress = 100;
      this.stop();
      $(getBack.sid + '_fileName').innerHTML = 'Upload successful!';
      uploadCompleted(getBack.sid, getBack.fileName);
    }
    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.sid + '_progress').style.width = getBack.progress + '%';
    $(getBack.sid+'_progress').style.width = (getBack.progress / 10)  + 'em';
    $(getBack.sid+'_progress').style.height = '1em';

    //$(getBack.sid + '_fileName').innerHTML = bytes_sec.toFixed(2) + ' ' + bytes_append;
    $(getBack.sid + '_fileName').innerHTML = getBack.progress+'%';;
  }; 
  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();
}

var exifXmlHttp;


function uploadCompleted(sid, fileName) {
	//alert('Trigger script to:\n\ny) remove temporary upload files\na) Search image for date and lat/long in EXIF tags\nb) if EXIF date exists and date has been specified, ask if the user wants to overide with values from photo\nc) If lat/long exist and date has been specified, ask if user wants to override with values from photo\nd)Move info window to new co-ords\ne) IF EXIF lat/long does not exist ask user to drag the info window to the correct location\nf) If form is now complete change Next button to submit\ng) Pass image URL to form submission\nh) After submission generate compressed images and thumbnails from original (preserve EXIF), then remove original');
	
	// remove temporary upload files
	
	var image_thumbnail = $(sid+'_img');
	
	image_thumbnail.src = 'http://'+window.location.hostname+'/phpthumb/phpThumb.php?src=/_uploaded/'+fileName+'&ar=x&h=100';
	$(sid + '_progress_gubbins').style.visibility = 'hidden';
	image_thumbnail.style.visibility = 'visible';
	$('uploaded_img_filename').value = fileName;
	
	fileType = fileName.substring(fileName.lastIndexOf('.')+1, fileName.length);
	fileType = fileType.toLowerCase();
	if (fileType == "jpg" || fileType == "jpeg" || fileType == "tiff") {
		// AJAX query to check EXIF for GPS tags and Date
		
		url = 'http://'+window.location.hostname+'/uploader2/parseExif.php?uploaded_img='+fileName;
		
		exifXmlHttp=GetXmlHttpObject();
		if (exifXmlHttp==null) {
			alert ("Browser does not support HTTP Request");
			return;
		}
		exifXmlHttp.onreadystatechange = function()
			{
				if (exifXmlHttp.readyState==4 || exifXmlHttp.readyState=="complete") {
					var p = eval("(" + exifXmlHttp.responseText + ")");
					if (p.lat == 0 && p.lng == 0) {
						p.lat = null;
						p.lng = null;
					}
					processExif(p.date, p.lat, p.lng, sid, p.datetime);
					changeSubmitButton();
				}
			};
		exifXmlHttp.open("GET",url,true);
		exifXmlHttp.send(null);
	}
	else {
		processExif(null, null, null, sid, null);
		changeSubmitButton();
	}
	
	
}

function changeSubmitButton() {
	validateAddPointForm(map.getInfoWindow().getPoint().lat(),map.getInfoWindow().getPoint().lng(),$('addPointForm'),true);
	if (addPointValidated == true) {
		var latin_acceptable = true;
		var common_acceptable = true;
		if ($('latin').length==0) {
			latin_acceptable = false;
		}
		if ($('common').length==0) {
			common_acceptable = false;
		}
		$('photoform0_submit').onclick = function () {submissionCheck(map.getInfoWindow().getPoint().lat(),map.getInfoWindow().getPoint().lng(),getstr,latin_acceptable,common_acceptable);};
		$('photoform0_submit').value = 'Submit photo marker';
		addPointValidated = false;
	}
}

function processExif(img_date, lat, lng, sid, img_datetime) {
	
	$(sid+'_img_date').innerHTML = 'Date : '+img_date;
	$(sid+'_img_date').style.visibility = 'visible';
	lat_number = new Number(lat);
	$(sid+'_img_lat').innerHTML = 'Latitude : '+lat_number.toPrecision(5);
	$(sid+'_img_lat').style.visibility = 'visible';
	lng_number = new Number(lng);
	$(sid+'_img_lng').innerHTML = 'Longitude : '+lng_number.toPrecision(5);
	$(sid+'_img_lng').style.visibility = 'visible';
	
	$(sid+'_location_choice').style.visibility = 'visible';
	
	if ( img_date != null ) {
		$('date').value = img_date;
		$('uploaded_img_date').value = img_datetime;
	}
	
	if ( lat != null && lng != null ) {
		$('uploaded_img_lat').value = lat;
		$('uploaded_img_lng').value = lng;
		$(sid+'_uploaded_gps_location').onclick = function () { updateCurrentLocationButton(sid); createMarkerInfoWindow(lat,lng); };
		$(sid+'_uploaded_gps_location').disabled = false;
		if (confirm("The image contained location information.  Click OK to use this information to reposition the marker")) {
			$(sid+'_uploaded_gps_location').checked = true;
			updateCurrentLocationButton(sid);
			createMarkerInfoWindow(lat,lng);
		}
	}
	else {
		if (confirm("The image did not contain location information.  Click OK if you wish to reposition the marker more precisely")) {
			selectNewInfoWindowLocation(sid);
		}
	}
	
}

function updateCurrentLocationButton(sid) {
	$(sid+'_original_location').innerHTML = '<input type="radio" id="'+sid+'_uploaded_current_location" name="'+sid+'_marker_location"/> Use original latitude and longitude';
	old_lat = map.getInfoWindow().getPoint().lat();
	old_lng = map.getInfoWindow().getPoint().lng();
	$(sid+'_uploaded_current_location').onclick = function () { createMarkerInfoWindow(old_lat,old_lng); };
	$(sid+'_uploaded_current_location').checked = false;
}

var selectingNewInfoWindow = false;
function selectNewInfoWindowLocation(sid) {
	selectingNewInfoWindow = true;
	map.getInfoWindow().hide();
	alert('click on the map to choose the new marker position');
	$(sid+'_original_location').innerHTML = '<input type="radio" id="'+sid+'_uploaded_current_location" name="'+sid+'_marker_location"/> Use current latitude and longitude';
	$(sid+'_uploaded_current_location').checked = true;
	$(sid+'_uploaded_current_location').onclick = null;
}