﻿
photoUpload =
{
  handleOpen : function(popup)
  {
    // Assign submit button handler
    $('#photoUploadButton').bind('click', {popup: popup}, photoUpload.startUpload);

    // Reset view
    $('#photoUploadMessage').html('');
    $('#photoUploadInput').val('');
    enableButton('photoUploadButton');

    //centering with css
    popup.centerPopup();
		
    //load popup
    popup.loadPopup();
  },
  
  postLoad : function(popup)
  {
    // Nothing to do
  },
  
  startUpload : function(event)
  {
    var popup = event.data.popup;
    
    // Validate
    var filepath = $('#photoUploadInput').val();
    var ext = filepath.substr(filepath.lastIndexOf('.') + 1);
    
    if ($.trim(filepath).length == 0)
    {
      $('#photoUploadMessage').html('File is required to upload.');
      return false;
    }
    else if (!(ext && /^(jpg|png|jpeg|gif|JPG|PNG|JPEG|GIF)$/.test(ext)))
    {
      $('#photoUploadMessage').html('Invalid file type');
      return false;
    }
    
    // Reset/lock down upload form
    $('#photoUploadMessage').html('');
    disableButton('photoUploadButton');
    
    // Wait screen setup
		$("#loading")
		.ajaxStart(function(){
			$(this).show();
		})
		.ajaxComplete(function(){
			$(this).hide();
		});
  
    // Upload
		$.ajaxFileUpload({
			url: $currentPageName + "/UploadPhoto?" + $('.uploadPhotoPlaceID').val(), 
			secureuri: false,
			fileElementId: 'photoUploadInput',
      dataType: "application/json; charset=utf-8",
			success: function (response, status)
			{
			  response = stripHTML(response);
			  
				if (response != 'OK' && response != 'PENDING')
				{
					$('#photoUploadMessage').html(response);
          enableButton('photoUploadButton');
				}
				else
				{
          popup.disablePopup();
          
          if (response == 'OK')
          {
  				  alert('Your photo has been uploaded successfully!  Thanks.');
          }
          else
          {
  				  alert('Your photo has been uploaded successfully!\nWe\'ll review it shortly and add it to the site.  Thanks.');
  				}
  				
  				window.location.reload(true);
				}
			},
			error: function (data, status, e)
			{
        $('#photoUploadMessage').html(e);
        enableButton('photoUploadButton');
			}
		});
  }
  
}
