// Warea is a richedit component.
var warea = {

  translation: {
		 'en_CA': {	 
     'bold' : "Bold",
     'italic' : "Italics",
     'underline' : "Underline",
     'orderedList': "Numbered list",
     'unorderedList': "Bullets",
     'quote': "Quote",
     'link': "Link",
     'unlink': "Remove link",
     'picture': "Picture",
     'video': "Video",
  	 'insertQuote': "Enter quote",
  	 'insertAddr': "Enter Internet address",
     'insertVideo': "Enter the embed code from the video website",
		 'webcam_error': "You might record video"
		 },
	
		 'fr_CA': {
     'bold' : "Gras",
     'italic' : "Italic",
     'underline' : "Souligné",
     'orderedList': "Liste chiffrée",
     'unorderedList': "Liste pucée",
     'quote': "Citer",
     'link': "Lien",
     'unlink': "Délier",
     'picture': "Image",
     'video': "Vidéo",
	 	 'insertQuote': "Entrer la citation",
	 	 'insertAddr': "Entrer l\'adresse internet",
     'insertVideo': "Entrez la balise fournie par le site de vidéo",
 		 'webcam_error': "Vous devez enregistrer une réponse en vidéo"
		 }
	},
	
	mode: 'text',
	
	getLang: function(command) {
	 return eval('warea.translation.'+lang+'.'+command)
	},

	toolbar: null,
  type: null,
	
	// Initialize after the edit box (iframe) was loaded.
	// Called after the create function by edit.html in the edit iframe.
	init: function(doc) {
    
		warea.source($('warea_body').value);
		
		doc.designMode = 'on';
		
		// To have 'neat' html code without span style junk in gecko engines.
		if (document.designMode == 'off') {
			$('warea_edit').contentWindow.document.execCommand('useCSS', false, true);
		}

		$('warea_edit').contentWindow.document.caret = 0;
	  
	  if (warea.type != 'comment' && warea.type != 'dynamic_lead') {
	 		Element.setStyle('warea_upload', { 'visibility': 'hidden', 'height': '1px' });
		}
	},

	// Create the component.
	create: function(type, maxlen) {

	  if (type) {
		  warea.type = type;
		}
	 
		// Create the toolbar.
		warea.toolbar = document.createElement('div');
		warea.toolbar.id = 'warea_toolbar';
		$('warea').appendChild(warea.toolbar);
		
		// Add the edit box.
		var edit = document.createElement('iframe');
		edit.id = 'warea_edit';
		edit.setAttribute('frameborder', 0);
		edit.setAttribute('src', url.base+'warea#'+maxlen);
		$('warea').appendChild(edit);
    
	 
	  if (type != 'comment' && type != 'dynamic_lead') {
	 		// Add the upload box.
	 		var upload = document.createElement('iframe');
	 		upload.id = 'warea_upload';
	 		upload.setAttribute('frameborder', 0);
	 		//upload.setAttribute('src', urlAjax.user.replace('ajax', 'ajax')+'blog/upload');
      if(window.community != undefined) {
        upload.setAttribute('src', url.base+'ajax/canoe/blog/upload');
      } else {
	 		  upload.setAttribute('src', url.base+'ajax/'+loggedUser+'/blog/upload');
      }
	 		$('warea').appendChild(upload);
		}
	 
		// Add base commands to toolbar.
		warea.baseCommand('bold', warea.getLang('bold'));
		warea.baseCommand('italic', warea.getLang('italic'));
	 	warea.baseCommand('underline', warea.getLang('underline'));
	  
	  if (isSafari()) {
			return;
		}
	
	  if (type !== 'comment' && type != 'dynamic_lead') {
		  warea.baseCommand('insertOrderedList', warea.getLang('orderedList'));
		  warea.baseCommand('insertUnorderedList', warea.getLang('unorderedList'));
  	}
	 
		// Quote
		warea.newCommand('quote', warea.getLang('quote'), function() {
			var quote = prompt(warea.getLang('insertQuote'),"");
			if (quote) {
				warea.insertQuote(quote);
			}
		});
		
		// Add link.
		warea.newCommand('link', warea.getLang('link'), function() {
			var url = prompt(warea.getLang('insertAddr'),"http://");
			if (url) {
				if (!url.match(/^http:\/\//)) {
				  url = "http://"+url;
  			}
				$('warea_edit').contentWindow.document.execCommand('createLink', false, url);
			}
		});
		
		warea.baseCommand('unlink', warea.getLang('unlink'));

		if (type !== 'comment' && type != 'dynamic_lead') {
			// Add image.
		  warea.newCommand('image', warea.getLang('picture'), function() {
			  if (!warea.upload.opened) {
          warea.upload.open();
			  } else {
				  warea.upload.close();
			  }
		  });
		
		  // Add video.
		   warea.newCommand('video', warea.getLang('video'), function() {
		     warea.setVideo();
		   });
		}
		// View source.
		/*warea.newCommand('source', 'Source', function() {
		  alert(warea.sourceText());
		});*/
    
	},

	// Add a command to the toolbar.
	newCommand: function(type, name, callback) {

		// Add comment element to the toolbar.
		var command = document.createElement('img');
		command.id = 'warea_'+type;
	  if (type == 'bold') command.setAttribute('class', 'warea-button first');
	  else command.setAttribute('class', 'warea-button');
		command.setAttribute('src', url.img+'warea/'+type+'.gif');
		command.setAttribute('title', name);
		command.setAttribute('alt', name);		
		warea.toolbar.appendChild(command);
		
		// Set the callback.
		$('warea_'+type).onclick = function () {
			callback();
			return false;
		};
	 
	  $('warea_'+type).onmouseover = function () {
			$('warea_'+type).src = url.img+'warea/'+type+'_hover.gif';
			return false;
		};
	  $('warea_'+type).onmouseout = function () {
			$('warea_'+type).src = url.img+'warea/'+type+'.gif';
			return false;
		};
		
		// Keep focus on the editbox when clicked.
		$('warea_'+type).onmousedown = preventFocus;
	},
	
	// Add a base command to the toolbar.
  baseCommand: function(type, name) {
		warea.newCommand(type, name, function() {
			$('warea_edit').contentWindow.document.execCommand(type, false, null);
			return false;
		});
	},
	
	// Get / set warea source.
	source: function(source) {
		if (source) {
			$('warea_edit').contentWindow.document.body.innerHTML = source;
		} else {
			return $('warea_edit').contentWindow.document.body.innerHTML;
		}
	},

	// Get html free source.
	sourceText: function(source) {
	  return warea.source().replace(/(<([^>]+)>)/ig, "").unescapeHTML();
	},
	 
  // Insert a quote
  insertQuote: function(text, at) {
		var source = warea.source();
		text = text.replace(/<embed(?:.|\s)*?>/g, ''); // strip <embed>
		warea.source(source+'<br><blockquote class="quote">'+(at != null ? at+' a écrit:<br><br>' : '')+'<div class="quote_body">'+text+'</div></blockquote><br><br>');
		//warea.source(source+' <br><p class="quote">'+text+'</p><br><br>');
	},
	 
	// Insert video in warea. Will be show as an image.
	setVideo: function() {

	  var code = prompt(warea.getLang('insertVideo'), '');
		if (!code) {
		  return;
		}

	  $('warea_edit').contentWindow.document.execCommand('insertImage', false, 'embedvideo');

	  var embed = /<embed (.*?)>/i.exec(code);

	  if (embed && embed[1]) {
      var results = embed[1].split(/\s/g);
		  var params = [];

	    for (i=0; i<results.length; i++) {
				if ((v = results[i].match(/(\w+)="(.*?)"/i)) || (v = results[i].match(/(\w+)='(.*?)'/i))) {
 	  		  switch (v[1].toLowerCase()) {
 		        case 'src':
 			      case 'type':
			      case 'flashvars':
  	          params.push("'"+v[1].toLowerCase()+"':'"+v[2].replace("'", "\'")+"'");
	  	        break;
			  	}
				}
	    }

	    warea.source(warea.source().replace(/src="embedvideo"/i, 'width="250" height="187" class="embedvideo" title="{'+params.join(',')+'}" src="'+url.img+'warea/video_generique.gif"'));
		}
	},

	upload: {

		opened: false,
		height: 0,
		
		// Open upload.
		open: function() {
      warea.upload.height = Element.getStyle('warea_edit', 'height');
      Element.setStyle('warea_edit', { 'height': '1px', 'visibility': 'hidden' });
      Element.setStyle('warea_upload', { 'height': warea.upload.height, 'visibility': 'visible' });
			$('warea_upload').contentWindow.focus();
			warea.upload.opened = true;
		},

		// Close upload.
		close: function() {
      Element.setStyle('warea_upload', { 'height': '1px', 'visibility': 'hidden' });
      Element.setStyle('warea_edit', { 'height': warea.upload.height, 'visibility': 'visible' });
			$('warea_edit').contentWindow.focus();
			warea.upload.opened = false;
		},

  	// A picture was uploaded.
	  done: function(url) {
			warea.upload.close();
		  $('warea_edit').contentWindow.document.execCommand('insertImage', false, url);
			$('warea_edit').contentWindow.focus();
	  }
	}
  		
};

var warea_rules = {

	'#warea_tab_text a': function(el) {
	  el.onclick = function() {
		  warea.mode = 'webcam';
		  Element.hideIf('warea_tab_text');
		  Element.showIf('warea_tab_webcam');
		  Element.hideIf('warea_text');
		  Element.hideIf('warea_text_error');
		  Element.showIf('warea_webcam');	
		  
		  return false;
		}
	},

	'#warea_tab_webcam a': function(el) {
	  el.onclick = function() {
		  warea.mode = 'text';
		  Element.hideIf('warea_tab_webcam');
		  Element.showIf('warea_tab_text');
		  Element.hideIf('warea_webcam');	
		  Element.showIf('warea_text');
		  Element.showIf('warea_text_error');
		  
		  return false;
		}
	},

	'#warea_form': function(el) {
	  el.onsubmit = function() {
		 
		  $('warea_body').value = warea.source();
		 
		  if (warea.mode == 'text') {
		    $('webcam_file').value = '';
		  } else if ($('webcam_file').value == '') {
	 			alert(eval('warea.translation.'+lang+'.webcam_error'));
			  //application.embed.hide();
	 			//flash.error(eval('warea.translation.'+lang+'.webcam_error'));
			  //setTimeout('application.embed.show()', 5000);
			  return false;
			}

		  return true;
		}
	}

}; 

Behaviour.register(warea_rules);

var videoblog = {

  'save': function(filename) {
	  $('webcam_file').value = filename;
	}

};
