/*
  This file is part of Groops. All rights reserved. No rights granted to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software or parts of the Software without prior written and
  signed permission.
  
  MultiSelector for multiple files upload
  Convert a single file-input element into a 'multiple' input list

  Implementation based on: 
  http://the-stickman.com/web-development/javascript/upload-multiple-files-with-a-single-file-element/

  Changes from original version: 
  - Set element.name like 'postmedia[i][uploaded_data]'
  - Add extract file name
  - Add new_row_text to manage new_row display
  - Modify new_row_button to a text element
  - Add translation for "delete"
  - Add file icon (display preview on IE)

  Author:: Stickman (http://www.the-stickman.com), Guillaume Dufloux
  Copyright:: Copyright (c) 2006, 2007 by Groops GmbH
  License:: No rights granted for any use of the Software or parts of it
*/

/**
 * MultiSelector for multiple files upload
 * Convert a single file-input element into a 'multiple' input list
 *
 * Usage:
 *   1. Create a file input element (no name)
 *      eg. <input type="file" id="first_file_element">
 *   2. Preload default icon image
 * 		eg. <img src="/styles/standard/images/file_default.png" style="display:none">
 *   3. Create a DIV for the output to be written to
 *      eg. <div id="files_list"></div>
 *   4. Instantiate a MultiSelector object, passing in the DIV and an (optional) maximum number of files
 *      eg. var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 3 );
 *   5. Add the first element
 *      eg. multi_selector.addElement( document.getElementById( 'first_file_element' ) );
 *   6. That's it.
 *
 * You might want to play around with the addListRow() method to make the output prettier.
 * You might also want to change the element.name to another naming convention.
 */
function MultiSelector( list_target, max, delete_replace ){

	// Where to write the list
	this.list_target = list_target;
	
	// How many elements?
	this.count = 0;
	
	// How many elements?
	this.id = 0;
	
	// Is there a maximum?
	if( max ){
		this.max = max;
	} else {
		this.max = -1;
	};
	
	// Is there a replacement for "delete" word
	if( delete_replace ){
		this.delete_replace = delete_replace;
	} else {
		this.delete_replace = 'Delete';
	};
	
	
	/**
	 * Add a new file input element
	 */
	this.addElement = function( element ){

		// Make sure it's a file input element
		if( element.tagName == 'INPUT' && element.type == 'file' ){

			// Element name -- what number am I?
			element.name = 'postmedia[' + this.id++ + '][uploaded_data]';

			// Add reference to this object
			element.multi_selector = this;

			// What to do when a file is selected
			element.onchange = function(){

				// New file input
				var new_element = document.createElement( 'input' );
				new_element.type = 'file';

				// Add new element
				this.parentNode.insertBefore( new_element, this );

				// Apply 'update' to element
				this.multi_selector.addElement( new_element );

				// Update list
				this.multi_selector.addListRow( this );

				// Hide this: we can't use display:none because Safari doesn't like it
				this.style.position = 'absolute';
				this.style.left = '-1000px';

			};
			
			// If we've reached maximum number, disable input element
			if( this.max != -1 && this.count >= this.max ){
				element.disabled = true;
			};

			// File element counter
			this.count++;
			// Most recent element
			this.current_element = element;
			
		} else {
			// This can only be applied to file input elements!
			alert( 'Error: not a file input element' );
		};

	};

	/**
	 * Add a new row to the list of files
	 */
	this.addListRow = function( element ){

		// Row div
		var new_row = document.createElement( 'div' );

		// Delete button	
		var new_row_button = document.createElement( 'a' );
		new_row_button.innerHTML = '[x ' + this.delete_replace + ']';
		new_row_button.href = '#';
		new_row_button.alt = this.delete_replace;
		new_row_button.title = this.delete_replace;
		new_row_button.className = 'link-small link-delete';
		
		// Text (extracted from file name)
		var new_row_text = document.createElement( 'span' );
		var name = element.value;
		name = name.substring( name.lastIndexOf( '\\' ) + 1 );
		name = name.substring( name.lastIndexOf( '\/' ) + 1 );
		new_row_text.innerHTML = '&nbsp;' + name + '&nbsp;';
		
		// Icon
		var new_row_icon = document.createElement( 'img' );
		new_row_icon.alt = name;
		new_row_icon.title = name;
		if (isImage(name) && isIE6()) {
			new_row_icon.src = 'file://' + element.value;
		} else {
			new_row_icon.src = '/styles/standard/images/file_default.png';
		}
		
		// Resize icon
		var dim = redimImage(new_row_icon.src, false, 20)
		new_row_icon.width = dim[0]; //'12';
		new_row_icon.height = dim[1]; //'15';
		
		// References
		new_row.element = element;

		// Delete function
		new_row_button.onclick= function(){

			// Remove element from form
			this.parentNode.element.parentNode.removeChild( this.parentNode.element );

			// Remove this row from the list
			this.parentNode.parentNode.removeChild( this.parentNode );

			// Decrement counter
			this.parentNode.element.multi_selector.count--;

			// Re-enable input element (if it's disabled)
			this.parentNode.element.multi_selector.current_element.disabled = false;

			return false;
		};
		
		// Add icon, text and button
		new_row.appendChild( new_row_icon );
		new_row.appendChild( new_row_text );
		new_row.appendChild( new_row_button );
		
		// Add it to the list
		this.list_target.appendChild( new_row );
		
	};

};

/**
 * Resize an image and return new width and height 
 * 
 * Implementation based on http://www.javascriptfr.com/codes/REDIMENSIONNEMENT-IMAGE_39901.aspx
 *
 * Parameters
 * 
 * [imageSrc] : path to image
 * [maxWidth] : max width (default set to false)
 * [maxHeight] : max height (default set to false)
 *
 * Return
 *
 * [w, h] : An array with resize width and height 
 */
function redimImage(imageSrc, maxWidth, maxHeight){

	// Get size from source image
	var img = new Image();
	img.src = imageSrc;
	var w = img.width;
	var h = img.height;
	
	// Resize if width exceed max
	if (maxWidth && w > maxWidth) {
		var wRatio = maxWidth/w;
		w = maxWidth;
		h = parseInt(h * wRatio, 10);
	}
	
	// Resize if height exceed max
	if (maxHeight && h > maxHeight) {
		var hRatio = maxHeight/h;
		h = maxHeight;
		w = parseInt(w * hRatio, 10);
	} 
	
	// Return new width and height 
	wh = new Array(w, h);
	return wh;
};

/**
 * Check if a filename extension match an image type
 *
 * Parameters
 * 
 * [fileSrc] : path to file (at least filename) with extension
 *
 * Return true or false
 */
function isImage(fileSrc){
	ext = fileSrc.substring( fileSrc.lastIndexOf( '\.' ) + 1 ).toLowerCase();
	var is_image = (ext == 'png' || ext == 'jpg' || ext == 'gif' || ext == 'bmp')
	
	return is_image
}

/**
 * Check if navigator is Internet Explorer version 6.xx
 *
 * No parameters (use navigator property)
 */
function isIE6(){
	
	var ie = (navigator.appName == 'Microsoft Internet Explorer' ? 1 : 0);
	var version = navigator.appVersion;
	var ie6 = ((ie && (version.indexOf("MSIE 6.") >= 0)) ? 1 : 0);
	
	return ie6
}
