// Hi! My name jQuery Upload!
// I'am jQuery plugin, allowing easy upload files
// without a page refresh
//
// My bio:
// version: 0.6 (21 September, 2009)
// license: MIT
//
// My creator name is Aleksandr Koss (koss@octolab.ru)
// Meet at the http://github.com/octolab/jquery.upload

$(function() {

	// Simple function to parse text in json

	function txt_to_json(text) {
		return(
		  !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
        text.replace(/"(\\.|[^"\\])*"/g, '')
      )) && eval('(' + text + ')')
		);
	}

	$.fn.extend({

		// Custom file select element
		
		custom_file_input: function(settings) {
			if(!$(this).length) return; 
			
			var sets = jQuery.extend({
			  name: '',
				action: '',
				addition_html: '',
				unbinded_class: 'unbinded',
				hover_in: null,
				hover_out: null,
				on_select: null
			}, settings);
			
			var container = $(this),
    			cont_rect = function() {};

			cont_rect.width = 
			  parseInt(container.innerWidth() ? container.innerWidth() : container.css('width').replace(/px/, ''));
  		cont_rect.height = 
				parseInt(container.innerHeight() ? container.innerHeight() : container.css('height').replace(/px/, ''));

			if(sets.hover_in) container.hover_in = sets.hover_in;
			else container.hover_in = function() {}
			
			if(sets.hover_out) container.hover_out = sets.hover_out;
			else container.hover_out = function() {}
			
			container
			  .wrap('<form action="' + sets.action + '" method="post" enctype="multipart/form-data" class="ifupld_form"></form>');

      var form = container.parent('form');
     	
			form
			  .css({ cursor: 'default', position: 'relative' })
			  .append('<input name="' + sets.name + '" id="ifupld-found-me" class="ifupld" type="file" />')
			  .append(sets.addition_html);

      var ifupld_input = $('#ifupld-found-me'),
          inpt_rect = null, position_input = null;
          
      if(sets.on_select) {
        ifupld_input.change(sets.on_select);
      }

      ifupld_input.removeAttr('id');
      
      (position_input = function() {
        ifupld_input.css({
          position: 'absolute',
          left: '-2000px',
          opacity: 0
        }); 
      })();
      
      var mouse_in = false;

      container.mouseover(function() {
        
        if($(this).is('.' + sets.unbinded_class)) return; 
        
        if(!inpt_rect) {
          inpt_rect = function() {};
           inpt_rect.width = ifupld_input.width();
          inpt_rect.height = ifupld_input.innerHeight();
        }
        
        if(!mouse_in) {

          mouse_in = true;
          container.hover_in();

          function trace_mouse(e) {            
            if(!mouse_in) return;

            ifupld_input.css({
      				left: (e.pageX - container.offset().left - inpt_rect.width / 2) + 'px',
      				top: (e.pageY - container.offset().top - inpt_rect.height / 2) + 'px'
    			  });
    			  
    			  container.addClass('hi-hi').toggle(
      			  function() {
      			    $(this).css({background: '1px solid black'})
      			  },
      			  function() {
      			    $(this).css({border: 'none'})
      			  }
      			);

    				if(e.pageY < container.offset().top || e.pageY > container.offset().top + cont_rect.height ||
    			     e.pageX < container.offset().left || e.pageX > container.offset().left + cont_rect.width) {

              mouse_in = false;
              container.hover_out();
              
              container.unbind('mouseover', trace_mouse);
              ifupld_input.unbind('mouseover', trace_mouse);
    					position_input();
    				}
          }

          $('body').mousemove(trace_mouse);
        }
      });
		},
		
		custom_file_input_clear: function() {
			$(this).parent('form.ifupld_form').replaceWith($(this));
		}
  });
  
  $.extend({
		iframe_upload_clear: function() {
		  var iframe = $('#iframeupld');
		  
		  if(iframe.length)
      	setTimeout(function() {
    	    iframe.remove();
    	  }, 0);	// Firefox fix
		}
  });

	$.fn.extend({
	
		iframe_upload: function(settings) {

			var sets = jQuery.extend({
				type: 'json',	// Type of response data
				load: null,	// Callback function (function(data))
				auto_clear: true
			}, settings);

			var form = $(this),
			    iframe = $('#iframeupld'); // Create iframe or if is exist get it
      
			if(!iframe.length) {	// Frame doesn't exist
				$('body').append('<iframe name="iframeupld" id="iframeupld" style=display:none;"></iframe>');
				iframe = $('#iframeupld');
			}
			
			// Check for form target

			if(form.attr('target') != 'iframeupld') form.attr('target', 'iframeupld');
			form.submit(); // ...and finally submit form

			// Await load response
			
			function load_trigger() {
			  var response = iframe.contents().find('body').html();

				// If resopnse data equal json, eval it

				if(sets.type == 'json') response = txt_to_json(response);
				if(sets.load) form.ifupldr_load = sets.load;
				else form.ifupldr_load = function() {}

        form.ifupldr_load(response);

        if(sets.auto_clear) // Kill iframe
  				$.iframe_upload_clear();
  		  else
  		    iframe.unbind('load', load_trigger);  // Unbind trigger if iframe still alive
			}
			
			iframe.bind('load', load_trigger);
		}
	});
});
