<!--
/*
SINGLE IMAGE SELECTOR JAVASCRIPT

Single Image Selector by King Cow Interactive LLC (2009)

This javascript image selector allows you add image selectors to your form.
Images are stored in the file path specified by the controller, not this selector.

Requirements
- jquery 1.3

Features
- No submit or upload button
- Rewrites form attributes, posts image to a hidden iframe, and then restores attributes
- Some ideas from webtoolkit dot info slash ajax-file-upload.html. See this site for a different kind of multiple-image selector

To use this in your website, see the example file in this folder.
*/

// Central Image Selector Object
var ImageSelector = new Object();
ImageSelector.Interface = function( interface_div, form_name, image_path_field_name, control_file, select_message, newWidth, newHeight) {
	//private
	var thisObj = this;	// this object
	var control_file = control_file;
	//default image size
	
	if( typeof(newWidth) == 'undefined' ) newWidth = 300;
	if( typeof(newHeight) == 'undefined' ) newHeight = 200;
	var im_width = newWidth;
	var im_height = newHeight;
	var file_browse_field_name = 'newfile';
	var iframe_name = form_name+'_iframe';
	//private jquery objects
	var theform = $('form[name='+form_name+']');
	var result;
	var file_being_uploaded;
	var last_file_uploaded;
	//private jquery objects to be set on createInterface
	var file_browse_field;
	var message_box;
	var upload_frame;
	var file_field_container;
	var image_preview;
	var image_field; //what gets passed to the final form
	var default_message = '<p>Select a jpeg image to upload that is under one megabyte (1 MB).<br />The image will fill a 300px wide by 200px high space. Landscape photos are best.</p>';
	if (select_message) { default_message = select_message; }
	//functions
	this.createInterface = function() {
		//this functions should be called once per object
		$(interface_div).html('\
		<div class="image_selector_file_upload_message" id="'+form_name+'_file_upload_message">'+default_message+'</div>\
		<div class="image_selector_file_field_container" id="'+form_name+'_file_field_container">&nbsp;</div>\
		<input type="hidden" name="MAX_FILE_SIZE" value="100000" />\
		<iframe class="image_selector_iframe" style="display:none;" src="about:blank" id="'+form_name+'_iframe" name="'+form_name+'_iframe" width="500" height="40"></iframe>\
		<div class="image_selector_image_preview" id="'+form_name+'_image_preview">&nbsp;</div>\
		'); //<input type="hidden" id="'+image_path_field_name+'" name="'+image_path_field_name+'" value="" /> should be defined in the form
		//define jquery private variables for elements just created
		message_box = $('#'+form_name+'_file_upload_message');
		upload_frame = $('#'+form_name+'_iframe');
		file_field_container = $('#'+form_name+'_file_field_container');
		image_preview = $('#'+form_name+'_image_preview');
		image_preview.css({border:'1px solid black', width:im_width, height:im_height, overflow:'hidden', backgroundColor:'black' });
		image_field = $('#'+image_path_field_name);
		//check to see if there is already a default image before showing/resetting the form for the first time
		if ( image_field.attr('value') ) {
			preloaded_image = image_field.attr('value');
		} else {
			preloaded_image = false;
		}
		//show/reset the file upload box for the first time
		this.reset_file_upload_field();
		//create the action on upload		
		upload_frame.load( function() {
			id = iframe_name;
			var i = document.getElementById(id);
			//find the document
			if (i.contentDocument) var d = i.contentDocument;
			else if (i.contentWindow) var d = i.contentWindow.document;
			else var d = window.frames[id].document;
			//if the document is not blank
			if (d.location.href != "about:blank") {
				eval('result='+d.body.innerHTML);
				if (eval(result.success)) {
					thisObj.upload_complete();
				} else {
					thisObj.reset_form();
					alert(result.user_response);
				}
			}
		})
		//if there was a preloaded image
		if (preloaded_image) {
			result = { 'relative_url':preloaded_image };
			thisObj.upload_complete();
		}
	}
	this.reset_file_upload_field = function() {
		//this function resets the file upload box
		file_field_container.html('<input type="file" id="'+form_name+'_file_field" name="newfile" value=""/>'); //onchange="upload_image()" 
		document.getElementById(form_name+'_file_field').onchange = function() { thisObj.upload_image() }
		file_browse_field = $('input[name='+file_browse_field_name+']');
		image_field.attr('value','');
	}
	this.upload_image = function() {	
		//define file_being_uploaded
		file_being_uploaded = file_browse_field.attr('value');
		if ( file_being_uploaded.toLowerCase().indexOf('.jpg')<0 & file_being_uploaded.indexOf('.jpeg')<0 ) {
			alert('Sorry, you can only select jpeg images. Please select a jpeg.');
			thisObj.reset_form();
		} else {
			//change the form action and target, submit, and change it back
			var original_action = theform.attr('action');
			var original_enctype = theform.attr('enctype');
			theform.attr('action',control_file+'?rand='+Math.floor(Math.random()*11*6).toString()).attr('target',iframe_name);
			theform.attr('enctype','multipart/form-data');
			theform.submit();
			theform.attr('action',original_action).attr('target','_self');
			theform.attr('enctype',original_enctype);
			//reset the file upload field completely so that the file will not be posted again
			thisObj.reset_file_upload_field();
			//hide the upload field
			file_browse_field.hide(); //.attr('disabled', 'disabled')
			//show is-uploading message
			message_box.show().html('<p>Now uploading "<em>'+file_being_uploaded+'</em>." Please wait. <span id="'+form_name+'_cancel_mid_upload_link">Cancel.</span></p>');
			$('#'+form_name+'_cancel_mid_upload_link').css({'cursor':'pointer','color':'red'}).click(function(){
				thisObj.reset_form();
			});
		}
	}
	this.upload_complete = function() {
		var image_source = '/image_cache.php?f='+result.relative_url+'&w='+im_width+'&xa=0.5&ya=0.5&x='+im_width+'&h='+im_height+'&y='+im_height+'&t=jpg&q=90&ap=true';
		image_preview.html('<img alt="" width="'+im_width+'" height="'+im_height+'" src="'+image_source+'"/>');
		image_field.attr('value',result.relative_url);
		last_file_uploaded = file_being_uploaded;
		file_being_uploaded = '';
		message_box.show().html('<p><span id="'+form_name+'_clear_image">Clear image.</span></p');
		$('#'+form_name+'_clear_image').css({'cursor':'pointer','color':'red'}).click(function(){
			thisObj.reset_form();
		});
	}
	this.reset_form = function() {
		file_being_uploaded = '';
		thisObj.reset_file_upload_field();
		message_box.show().html(default_message);
		image_preview.html('');
	}
	
	//Create the interface
	this.createInterface();
	
}
