/*
	Copyright (c) 2006-2007, ePages GmbH
	All Rights Reserved.

	epages.cartridges.de_epages.presentation.widget.Toolfont $Revision: 1.37 $

*/
/*global dojo,epages,tinyMCE,jQuery,ep*/
dojo.provide("epages.cartridges.de_epages.presentation.widget.Toolcolor");
dojo.require("epages.widget.LocalizedWidget");
dojo.require("epages.browser");
dojo.require("epages.html.element");
(function(){

var colorPicker;

dojo.declare(
	"epages.cartridges.de_epages.presentation.widget.Toolcolor",
	[epages.widget.LocalizedWidget],
	{
		/**
		 * public properties
		 */
		label               : '',           // String - label of color field
		color               : '',           // String - color value
		colorType           : '',           // String - type of color input e.g. Background, ListeHeadBackground, ... (used for input name example: input name="${objectId}:${colorType}" value="myval" />)
		isBackgroundColor   : 'false',      // Boolean - flag that indicates that color is a Backgroundcolor
		templateType        : "tablerow",   // String - selected template type
		defaultTemplateType : "tablerow",   // [readonly] String - default value template type
		isTinyMCE           : 'false',      // Boolean - flag that indicates weather the current tinyMCE selection should be save or not
		'class'             : '',           // String - css class attribute
		userColors: epages.vars.userColors, // String - user defined colors e.g. "#ff0000|#000000"
		currentWizardScheme : 'Compound',   // String - selected color scheme
		objectId            : '',           // String - current epages object id
		styleId             : '',           // String - current epages object id
		allowEmpty          : '0',          // Boolean - allow empty value (will be passed to colorpicker widget)

		/**
		 * private properties
		 */
		_templateMapping:{
			'tablerow' : {templatePath: dojo.moduleUrl('epages.cartridges.de_epages.presentation.widget', 'templates/Toolcolor.html')},
			'tablerownew' : {templatePath: dojo.moduleUrl('epages.cartridges.de_epages.presentation.widget', 'templates/ToolcolorNew.html')},
			'colorbox' : {templatePath: dojo.moduleUrl('epages.cartridges.de_epages.presentation.widget', 'templates/Toolcolorbox.html')},
			'colorbutton' : {templatePath: dojo.moduleUrl('epages.cartridges.de_epages.presentation.widget', 'templates/Toolcolorbutton.html')},
			'palette'  : {templatePath: dojo.moduleUrl('epages.cartridges.de_epages.presentation.widget', 'templates/Toolcolorpalette.html')},
			'xlicon'   : {templatePath: dojo.moduleUrl('epages.cartridges.de_epages.presentation.widget', 'templates/Toolcolorxlicon.html')}
		},                                // [protected] Object - hash which associates templateType key with template filename
		_palette            : 'fore',     // [protected] String - template variable used in template Toolcolorpalette (icon switch)
		_tinyMceSelection   : undefined,  // [protected] TinyMceSelection - current selection in tiny mce editor

		/**
		 * constants
		 */
		COLORPICKER_OFFSET_X: 18,         // [const] Integer
		COLORPICKER_OFFSET_Y: 0,          // [const] Integer

		/**
		 * widget properties
		 */
		templatePath    : dojo.moduleUrl('epages.cartridges.de_epages.presentation.widget', 'templates/Toolcolor.html'),  // String - template path + filename
		imagePath       : epages.themeUrl('images'),                                                                      // String - icon path
		translationName : dojo.moduleUrl('epages.cartridges.de_epages.presentation.widget', 'templates/translation'),     // String - translation path + filename

		postMixInProperties: function() {
		// summary: initialize values
			this._templateDirectory = dojo.moduleUrl('epages.cartridges.de_epages.presentation.widget', 'templates');
			this.inherited("postMixInProperties", arguments);
			this.isBackgroundColor = epages.string.toBoolean(this.isBackgroundColor);
			this.isTinyMCE = epages.string.toBoolean(this.isTinyMCE);
			this.allowEmpty = epages.string.toBoolean(this.allowEmpty);
			this._palette = this.isBackgroundColor ? 'back' : 'fore';
			if(this.color === '' && ! this.allowEmpty) {
				this.color = 'transparent';
			}
			this.styleId = epages.vars.StyleId === undefined ? '' : epages.vars.StyleId;
		},

		postCreate  : function() {
		// summary: initialize widget / append events
			this.inherited("postCreate", arguments);

			dojo.addClass(this.domNode,this['class']);
			if(this.objectId === '') {
				this.colorInputNode.name=this.colorType;
			}
			this._appendEvents();
			this._changeColorBoxColor();
		},

		/**
		 * private methods
		 */

		_appendEvents: function() {
		// summary: append events to buttons (bold, italic, underline)
			this.connect(this.colorInputNode,     'onchange', '_changeColorBoxColor');

			// save selection in editor iframe for msie
			if (this.isTinyMCE && epages.Browser.engine === "MSIE"){
				this.connect(this.clickNode,        'onmousedown', '_tinyMceSaveSelection');
			}

			// open color picker
			if(this.clickNode){
				this.connect(this.clickNode,        'onclick', '_openColorPicker');
			}else{
				this.connect(this.colorBoxNode,     'onclick', '_openColorPicker');
			}
		},

		_changeColorBoxColor: function() {
			// summary: set background color of color preview box
			var color=this.colorInputNode.value;

			if(this.notSetNode) {	// this node does not exisit within every template type
				if(color === "") {
					this.notSetNode.style.display="";
				} else {
					this.notSetNode.style.display="none";
				}
			}

			// set color preview

			if(this.templateType === 'colorbutton'){
				this.colorBoxNode.style.background=color;
			}
			else{
				this.colorBoxNode.style.backgroundColor=color;
			}
			if(color==='transparent') {
				dojo.addClass(this.colorBoxNode,"Transparent");
			} else {
				dojo.removeClass(this.colorBoxNode,"Transparent");
			}

			if (this.isTinyMCE && tinyMCE.selectedInstance !== null) {
				if(this._tinyMceSelection === undefined) {
					tinyMCE.execCommand((this.isBackgroundColor ? 'HiliteColor': 'forecolor'), false, color);
				} else { // IE only - tinymce fixes
					this._tinyMceSelection.execCommand((this.isBackgroundColor ? 'BackColor': 'forecolor'), false, color);
					tinyMCE.activeEditor.focus();
					tinyMCE.activeEditor.selection.setRng(this._tinyMceSelection);
					this._tinyMceSelection=undefined;
				}
			}
		},

		_openColorPicker: function( event ) {
			var self = this,
				colorTarget = ep(event.target),
				colorInput = jQuery(this.colorInputNode);

			if( colorPicker ){
				colorPicker.element = colorPicker.elem = colorTarget;
				colorPicker.option( 'callback', function( color ){
					colorTarget
						.css('background-color', color);
					colorInput
						.val( color )
						.trigger({ type:'change', dojoconnect:true });
				});
				colorPicker.colorSelect( colorInput.val(), true );
				colorPicker.open();
			}
			else{
				jQuery.ready( ['ep.ajax', 'ep.ui.colorpicker'], function($){
					var options = {
							orientation:	'bottom'
						};

					if( epages.vars.StyleUserDefinedColors ){
						var extended = {
								baseColors:	$('#LayoutBackgroundColor').val(),
								userColors: {},
								userColorsSave: function( data ){
									var ajaxData = [
											{name: 'ViewAction',	value: 'JSONViewResponse'},
											{name: 'ChangeAction',	value: 'SaveGUIDList'},
											{name: 'ObjectID',		value: ep.config.siteId}
										];

									$.each( data, function(){
										ajaxData.push(
											{name: 'GUID',			value: self.styleId},
											{name: 'Name',			value: this.name},
											{name: 'Value',			value: this.value}
										);
									});

									ep.ajax({
										type:		'post',
										dataType:	'json',
										data:		ajaxData
									});
								}
							};

						$.each( epages.vars.StyleUserDefinedColors.split('|'), function( i, val ){
							extended.userColors[ 'UserDefinedColor'+i ] = val;
						});

						options.extended = extended;
					}

					colorPicker = ep('<div>')
						.uiColorpicker(options)
						.uiColorpicker('Instance');
					self._openColorPicker( event );
				});
			}
		},

		_tinyMceSaveSelection: function() {
		// summary: stores the current tinymce select
			if(tinyMCE.activeEditor && tinyMCE.activeEditor.selection){
				this._tinyMceSelection = tinyMCE.activeEditor.selection.getRng();
		}

		}
	});

}());