/* utf8 marker ö */

/**
 + ================================================================================
 * Start admin administration interface
 + ================================================================================ */
mlvi.AdminStart = function(event){
	mlvi.readBackgrounds(mediaLibraryStructure);
	mlvi.readVirtualImage(imageDefinition);
	mlvi.readIcons(mediaLibraryStructure);
}

/**
 + ================================================================================
 * Read the icons
 + ================================================================================ */
mlvi.readIcons = function(repository){
	var repository = repository?repository:[];	
	var iconsContainer = $('mlviIcons');

	//create the basic template
	mlvi.appendChild(iconsContainer, $.DIV({'id':'mlviIconsChooser'}, $.DIV({'id':'mlviIconsChooserLabel'}, mlvi.getServerLabel('ICONS') + ':')));
	mlvi.appendChild(iconsContainer, $.DIV({'id':'mlviIconsList'}));

	//add the icons directory chooser
	mlvi.appendChild(
		$('mlviIconsChooser'), 
		mlvi.getIconsChooser()
	);		

	
	//refresh the icons	
	mlvi.refreshIcons($('mlviICONDirID').options[$('mlviICONDirID').selectedIndex].value);

	
	//set the system icon 
    new Draggable($(systemIcons[0].id), {'ghosting': true, 'revert':true, 'zindex': 4000});
    
    
	// =======================================================================
	// set the events
	// =======================================================================
	// --------------------------------------------
	// change event of mlviICONDirID
	// --------------------------------------------
    Event.observe($('mlviICONDirID'), 'change', function(event){
    	var select = $('mlviICONDirID');
    	
    	var value = select.options[select.selectedIndex].value;
    	if(value){
			mlvi.refreshIcons(value);
    	}else{
    		alert(mlvi.getServerLabel('PROP_PROP_ERR_SELECT_FILE'));
    	}
    	
    });
    
};

/**
 + ================================================================================
 * refresh the icons tool var
 + ================================================================================ */
mlvi.refreshIcons = function(dirID){
	if(mediaLibraryStructure[dirID]==null) return;
	if(mediaLibraryStructure[dirID].elements==null) return;
	var icons = mediaLibraryStructure[dirID].elements;
	
	if($('mlviIconsList')!=null){
		$('mlviIconsList').innerHTML = '';
	}
	
	
	// ---------------------------------
	// save the icons list
	// ---------------------------------
	for(var imageID in icons){
		//JSON idiot!
		if(imageID=='toJSONString')continue;

		var src 	= imageDefinition.imgurl + '=' + imageID;	
		var iconID 	= mlvi.OBJECT_DRAG_ICON_PREFIX + imageID;
		var icon 	= $.IMG(
			{
				'src': 		src, 
				'id': 		iconID,
				'class':	'mlviIcon'/*,
				'alt':		icons[imageID]*/
			}
		);
		
		//add the icon to the icon list
		mlvi.appendChild($('mlviIconsList'), icon);

		//configure as dragable
	    new Draggable($(iconID), {'ghosting': true, 'revert':true, 'zindex': 4000});
	}
}	

/**
 + ================================================================================
 * get the icons chooser
 + ================================================================================ */
mlvi.getIconsChooser=function(){
	var select = $.SELECT(
		{'id': 'mlviICONDirID'}
	);
	
	var isSet = false;
	var selected = '';
	var option;
	
	//add empty file
	option = $.OPTION({'value': ''}, '');
	mlvi.appendChild(select, option);

	//create first select box	
	for(var dirID in mediaLibraryStructure){
		//JSON idiot!
		if(dirID=='toJSONString')continue;
		if(!mediaLibraryStructure[dirID].icons) continue;

		//define the separation ...
		var sep = '';
		for(var i=1; i<mediaLibraryStructure[dirID].level; i++){
			sep += '  ';
		}
		
		
		var properties = {};
		properties['value'] = dirID;
		//check for default value
		if(defaultIconContainer==dirID){
			properties['selected'] = 'selected';
		}
		
		option = $.OPTION(properties, sep + '[' + dirID + '] ' + mediaLibraryStructure[dirID].name);
		//add to the select 
		mlvi.appendChild(select, option);
	}


	return select;

}

/**
 + ================================================================================
 * get the background chooser
 + ================================================================================ */
mlvi.getBackgroundChooserFile = function(){
	var select = $.SELECT(
		{'id': 'mlviBGMedID'}
	);
	return select;
}

/**
 + ================================================================================
 * refresh background file chooser
 + ================================================================================ */
mlvi.refreshBackgroundFiles = function(dirID, selectedFile){
   	if($('mlviBGMedID')==null)return;
   	//refill the data in mlviBGFileID
   	var select = $('mlviBGMedID');
   	//clean the options
   	select.options.length = 0;
	option = $.OPTION({'value':''}, '');
	mlvi.appendChild(select, option);    	
   	
   	if(!dirID)return;

	//get the files corresponding to the current dir
	var files = mediaLibraryStructure[dirID].elements;
	for(var fileID in files){
		if(fileID=='toJSONString')continue;
		var properties = {};
		properties['value'] = fileID;
		//define selected
		if(selectedFile!=null && fileID==selectedFile){
			properties['selected'] = 'selected';
		}
		option = $.OPTION(properties, files[fileID]);
		//add to the select 
		mlvi.appendChild(select, option);
	}
}


/**
 + ================================================================================
 * get the background chooser
 + ================================================================================ */
mlvi.getBackgroundChooserDir = function(selectedFile){
	var select = $.SELECT(
		{'id': 'mlviBGDirID'}
	);

	var isSet = false;
	var selected = '';
	var option;
	
	//add empty file
	option = $.OPTION({'value': ''}, '');
	mlvi.appendChild(select, option);

	//create first select box	
	for(var dirID in mediaLibraryStructure){
		if(dirID=='toJSONString')continue;
		if(!mediaLibraryStructure[dirID].backgrounds) continue;
		
		//define the separation ...
		var sep = '';
		for(var i=1; i<mediaLibraryStructure[dirID].level; i++){
			sep += '  ';
		}
		
		var properties = {};
		properties['value'] = dirID;
		//define selected
		if(selectedFile!=0){
			if(mediaLibraryStructure[dirID].elements!=null && mediaLibraryStructure[dirID].elements[selectedFile]!=null){
				properties['selected'] = 'selected';
			}
		}else{
			//it is a new VI
			if(imageDefinition.id=='newvi' && dirID==defaultBackgroundContainer){
				properties['selected'] = 'selected';
			}
		}

		option = $.OPTION(properties, sep + '[' + dirID + '] ' + mediaLibraryStructure[dirID].name);
		//add to the select 
		mlvi.appendChild(select, option);
	}

	return select;
}


/**
 + ================================================================================
 * Read the backgrounds
 + ================================================================================ */
mlvi.readBackgrounds = function(repository){
	var backgroundsContainer = $('mlviBackgrounds');

	//fill the icon container
	backgroundsContainer.innerHTML = '';
	//create the basic template
	mlvi.appendChild(backgroundsContainer, $.DIV({'id':'mlviImageName'}));
	mlvi.appendChild(backgroundsContainer, $.DIV({'id':'mlviBackgroundsChooser'}));
	//add the name input

	mlvi.appendChild($('mlviImageName'), $.DIV({'id':'mlviImageNameLabel'}, mlvi.getServerLabel('IMAGE_NAME') + ':'));
	mlvi.appendChild($('mlviImageName'), $.INPUT({'id':'mlviFrmImageName', 'value':imageDefinition.name}));
	
	
	//alert(imageDefinition.name);

	//add the select boxes for background chooser
	mlvi.appendChild(
		$('mlviBackgroundsChooser'), 
		$.DIV(
			{'id':'mlviBackgroundsChooserLabel'}, 
			mlvi.getServerLabel('BACKGROUND_IMAGE') + ':'
		)
	);
	
	//add the background dir chooser
	mlvi.appendChild(
		$('mlviBackgroundsChooser'), 
		mlvi.getBackgroundChooserDir(imageDefinition.background.id)
	);		
	
	//some space
	mlvi.appendChild(
		$('mlviBackgroundsChooser'), 
		' '
	);		

	//add the background file chooser
	mlvi.appendChild(
		$('mlviBackgroundsChooser'), 
		mlvi.getBackgroundChooserFile()
	);		
	
	//refresh the files if a dir && file were selected
	if($('mlviBGDirID').options!=null && $('mlviBGDirID').options[$('mlviBGDirID').selectedIndex]!=null){
		mlvi.refreshBackgroundFiles($('mlviBGDirID').options[$('mlviBGDirID').selectedIndex].value, imageDefinition.background.id);
	}
	
	

	
	// =======================================================================
	// set the events
	// =======================================================================
	// --------------------------------------------
	// change event of mlviBGDirID
	// --------------------------------------------
    Event.observe($('mlviBGDirID'), 'change', function(event){
   		var option;
    	var select = $('mlviBGDirID');
    	//full fill the file container
    	var directory = select.options[select.selectedIndex].value;
		mlvi.refreshBackgroundFiles(directory);
    });
    
	// --------------------------------------------
	// change event of mlviBGMedID
	// --------------------------------------------
    Event.observe($('mlviBGMedID'), 'change', function(event){
    	var select = $('mlviBGMedID');
    	var value = select.options[select.selectedIndex].value;
    	
    	if(value){
			imageDefinition.background.id = value;
			//update the new image
			var bgID 	= mlvi.OBJECT_BG_PREFIX + imageDefinition.id;		
			var src 	= imageDefinition.imgurl + '=' + imageDefinition.background.id;	
			$(bgID).src	= src;
			
			//set the dimentions
			var dimentions = $(bgID).getDimensions();
			imageDefinition.background.width 	= dimentions.width;
			imageDefinition.background.height 	= dimentions.height;
			debug('debugInfo', ' setting dimentions to ' + dimentions.width + 'x' + dimentions.height);

			
			// -----------------------------------------
			// clean readonly elements
			// they are tied to the BG
			// -----------------------------------------
			var VIcontainerID 	= mlvi.OBJECT_VI_PREFIX + imageDefinition.id;
			var VIcontainer 	= $(VIcontainerID);
			if(VIcontainer!=null){
				for(var i=0; i<VIcontainer.mlviImageDefinition.elements.length; i++){
					if(
						VIcontainer.mlviImageDefinition.elements[i]!=null && 
						VIcontainer.mlviImageDefinition.elements[i].readonly
					){
					
						var VIelementID  =	mlvi.OBJECT_CONT_PREFIX + 
											imageDefinition.id + '_' + 
											i;
						VIcontainer.mlviImageDefinition.elements[i] = null;
						$(VIelementID).remove();
					}
				}
				
				VIcontainer.mlviImageDefinition.elements.compact();
			}

			
			// -----------------------------------------
			// add elements from the file
			// they are comming from the new BG
			// -----------------------------------------
			mlvi.addElementsFromFile(imageDefinition.background.id);
    	}else{
    		alert(mlvi.getServerLabel('PROP_PROP_ERR_SELECT_FILE'));
    	}
    });
};

/**
 + ================================================================================
 * Function to create a dinamic image
 + ================================================================================ */
mlvi.addElementsFromFile = function(imageID){
	var VIcontainerID 	= mlvi.OBJECT_VI_PREFIX + imageDefinition.id;
	var VIcontainer 	= $(VIcontainerID);

	var parameters = {
		'id_link':			serverParams.serverIdLink,
		'ajaxRequestID':	'GET_ELEMENTS',
		'VIbackground':		imageID,
		'medlib_dir_id':	serverParams.serverMedDirID
	};
	
	//var elements = []; 
	new Ajax.Request(
		serverParams.serverURL, 
		{
	  		method: 	'post',
	  		parameters:	parameters,		  		
			onComplete: function(transport) {
				eval('var elements=' + transport.responseText);
				//show the elements
				for(var i=0; i<elements.length; i++){
					//alert('adding ... ' + print_r(elements[i]));
					VIcontainer.mlviAddElement(elements[i], true, false);
				}
				
			},
			
			onException:function(transport, error){alert(error);}/*,
			onFailure:function(){alert('onFailure')},
			onInteractive:function(){alert('onInteractive')},
			onLoaded:function(){alert('onLoaded')},
			onLoading:function(){alert('onLoading')},
			onSuccess:function(){alert('onSuccess')},
			onUninitialized:function(){alert('onUninitialized')}*/
		}
	);	
}


/**
 + ================================================================================
 * Function to create a dinamic image
 + ================================================================================ */
mlvi.readVirtualImage = function(imageDefinition){
	var workSpaceID 	= 'mlviVirtualImage';
	var workSpace 		= $(workSpaceID);
	
	//create the container
	var VIcontainerID 	= mlvi.OBJECT_VI_PREFIX + imageDefinition.id;
	var VIcontainer 	= $(VIcontainerID);
	
	//if no container, add the container
	if(VIcontainer==null){
		//add the properties
		mlvi.appendChild(workSpace, $.DIV({'id':'mlviProperties'}));
 
		//set the properties form
		mlvi.showPropertiesForm();		
		
		//add the virtual image
		mlvi.appendChild(workSpace, $.DIV({'id':VIcontainerID}));
		
		//add the buttons
		mlvi.appendChild(workSpace, $.DIV({'id':'mlviVirtualImageButtons'}));
		VIcontainer = $(VIcontainerID);
	}

	//set the needed styles	 	 	
	var containerStyles = {
		'position':		'relative',
		'float':		'left'
	};

	VIcontainer.setStyle(containerStyles);	
	 	
	// save the image definition
	VIcontainer.mlviImageDefinition = imageDefinition;	

	//create a new VIimage object
	var container = new mlvi.Container();
    Object.extend(VIcontainer, container);

	VIcontainer.mlviShowBackground();
	VIcontainer.mlviShowElements();
	VIcontainer.mlviButtons();
	VIcontainer.mlviSetEvents();
	
};


/**
 + ================================================================================
 * show a virtual image, used by the client ... 
 + ================================================================================ */
mlvi.showVirtualImage = function(imageDefinition, html){
	var VIcontainerID 	= mlvi.OBJECT_VI_PREFIX + imageDefinition.id;
	var VIcontainer 	= $(VIcontainerID);
	
	//if no container, add the container
	if(VIcontainer==null){
		//get the html content
		var htmlParams = '';
		if(html!=null){
			for(var htmlParam in html){
				if(htmlParam=='toJSONString')continue;
				htmlParams += ' ' + htmlParam + '="' + html[htmlParam] + '" ';
			}
		}
	
		//add the properties
		document.writeln('<div id="' + VIcontainerID + '" ' + htmlParams + '></div>');
		VIcontainer = $(VIcontainerID);
	}
	
	//set the needed styles	 	 	
	var containerStyles = {
		'position':		'relative'
	};
	VIcontainer.setStyle(containerStyles);	

	// save the image definition
	VIcontainer.mlviImageDefinition = imageDefinition;	

	//create a new VIimage object
	var container = new mlvi.Container();
    Object.extend(VIcontainer, container);
	VIcontainer.mlviShowBackground();
	VIcontainer.mlviShowElements();
};


/**
 + ======================================================================
 * add a child to DOM object
 + ====================================================================== */
mlvi.showPropertiesForm = function(){
	container = $('mlviProperties');
	//set the needed styles	 	 	
	container.setStyle(
		{
			'float':			'left'
		}
	);
	container.innerHTML = '' + 

			'<div id="mlviFrmLineContainer1">' + 
				'<div id="mlviIconsText"></div>' + 
				'<div id="mlviFrmPropTextLabel">' + mlvi.getServerLabel('PROP_TEXT') + ':</div>' + 
				'<input type="text" id="frmPropText" value=""></input>' +
				'<div id="mlviOrderIcons">' + 
					'<img id="mlviFrmProptPosB" class="mlviFrmIcon" src="./images/position_b_off.gif" border="0">' +
					'<img id="mlviFrmProptPosA" class="mlviFrmIcon" src="./images/position_a_off.gif" border="0">' +
				'</div>' +
			'</div>' +

			'<div id="mlviFrmLineContainer1">' + 
				'<div id="mlviLinkText">'  + 
					'<A HREF="javascript: ;" ' + 
						'ONCLICK="window.open(\'' + serverParams.serverLinksManager + '\', \'cmlink_window\',\'status=yes,modal=no,width=800,height=600,scrollbars=yes\');" ' + 
						'ONMOUSEOVER="document.getElementById(\'ac_cmtags_ta_80\').src = \'./images/ac_cmlink_over.gif\';" ' + 
						'ONMOUSEOUT="document.getElementById(\'ac_cmtags_ta_80\').src = \'./images/ac_cmlink.gif\';" ONFOCUS="blur();" ' + 
						'TITLE="" ' + 
					'>' + 
						'<IMG ID="ac_cmtags_ta_80" SRC="./images/ac_cmlink.gif" BORDER="0" TITLE="">' +
					'</A>' + 
				'</div>' + 
				'<div id="mlviFrmPropTextLabel">' + mlvi.getServerLabel('PROP_LINK') + ':</div>' + 
				'<input type="text" id="frmPropLink" value=""></input>' +
				'<div id="mlviOrderIcons">' + 
				'</div>' + 
			'</div>' +

	
			'<div id="mlviFrmLineContainer2">' + 
				'<div class="mlviFrmProptLabel">' + mlvi.getServerLabel('PROP_FONT_FAMILY') + ':</div>'+
				'<select id="frmFontFamily" value="">' + 
					'<option value=""></option>' + 
					'<option value="Arial">Arial</option>' + 
					'<option value="Helvetica">Helvetica</option>' + 
					'<option value="Verdana">Verdana</option>' + 
					'<option value="Sans-serif">Sans-serif</option>' + 
				'</select>' +
				'<div class="mlviFrmProptLabel">' + mlvi.getServerLabel('PROP_FONT_SIZE') + ':</div>'+
				'<select id="frmFontSize" value="">' + 
					'<option value=""></option>' + 
					'<option value="7px">7px</option>' + 
					'<option value="8px">8px</option>' + 
					'<option value="9px">9px</option>' + 
					'<option value="10px">10px</option>' + 
					'<option value="11px">11px</option>' + 
					'<option value="12px">12px</option>' + 
					'<option value="13px">13px</option>' + 
					'<option value="14px">14px</option>' + 
					'<option value="15px">15px</option>' + 
					'<option value="16px">16px</option>' + 
					'<option value="17px">17px</option>' + 
					'<option value="18px">18px</option>' + 
					'<option value="19px">19px</option>' + 
					'<option value="20px">20px</option>' + 
					'<option value="21px">21px</option>' + 
					'<option value="22px">22px</option>' + 
					'<option value="23px">23px</option>' + 
					'<option value="24px">24px</option>' + 
					'<option value="25px">25px</option>' + 
					'<option value="26px">26px</option>' + 
					'<option value="27px">27px</option>' + 
					'<option value="28px">28px</option>' + 
					'<option value="29px">29px</option>' + 
					'<option value="30px">30px</option>' + 
				'</select>' +

				'<div class="mlviFrmProptLabel">' + mlvi.getServerLabel('PROP_FONT_COLOR') + ':</div>'+
				'<input type="text" id="frmFontColor" maxlength="7" value=""></input>' +
				//'<img id="mlviFrmColorWheel" class="mlviFrmIconColor" src="./images/color_wheel.gif" border="0">' +
				'<img id="mlviFrmFontBold" class="mlviFrmIconColor"  src="./images/vi_bold_off.gif" border="0">' +
				'<input type="hidden" id="frmOrder" value="icon,label"></input>' +
				'<input type="hidden" id="frmBold" value="0"></input>' +
				'' +
				'' +
				'<div id="mlviFrmButtons">' + 
					'<input type="button" id="mlviFrmUpdateProperties" value="' + mlvi.getServerLabel('PROP_PROP_UPDATE') + '"></input>&nbsp;' +
					'<input type="button" id="mlviFrmCancelProperties" value="' + mlvi.getServerLabel('PROP_PROP_CANCEL') + '"></input>' +
				'</div>' + 	
			'</div>' +
			'' +
			'' +
			'' +
		'';

		// -----------------------------------
		// save system icons
		// -----------------------------------
		var icon 	= $.IMG(
			{
				'src': 		systemIcons[0].src, 
				'id': 		systemIcons[0].id,
				'class':	'mlviIcon'
			}
		);
		mlvi.appendChild($('mlviIconsText'), icon);
}

/**
 + ================================================================================
 * HELPERS - BEGIN
 + ================================================================================ */


/**
 + ======================================================================
 * add a child to DOM object
 + ====================================================================== */
mlvi.appendChild = function(parent, child){


	if(parent!=null && child!=null){
		//handle text
	    switch( typeof child) {
	        case 'number': child = '' + child;  // fall through
	        case 'string': child = document.createTextNode(child);
	    }

		parent.appendChild(child);
	}
}

/**
 + ======================================================================
 * get a server label
 + ====================================================================== */
mlvi.getServerLabel = function(label){
	if(label!=null && serverLabels[label]!=null){
		return serverLabels[label];
	}
	
	return label;
}


/**
 + ======================================================================
 * select a value in one select box
 + ====================================================================== */
mlvi.selectValueInSelectbox = function(select, value){
	var selected = -1;
	if(select!=null && value!=null){
		for(var i=0; i<select.options.length; i++){
			if(select.options[i].value == value){
				selected = i;
				break;		
			}
		}
		if(selected != -1){
			select.selectedIndex = selected;
		}
	}
	
	return  selected;
}


/**
 + ================================================================================
 * HELPERS - END
 + ================================================================================ */
/**
 + ================================================================================
 * Read the elements
 + ================================================================================ */
mlvi.readVirtualImageProperties = function(imageDefinition){
	VIpropID		= mlvi.OBJECT_AP_PREFIX + imageDefinition.id;
	VIprop 			= $(VIpropID);

	if(VIprop==null){
		//write in the document the new image
		toWrite =	'<div id="' + VIpropID + '"></div>';
		document.writeln(toWrite);
		VIprop = $(VIpropID);
	}
};





/**
 + ================================================================================
 + ================================================================================
 + ================================================================================
 + ================================================================================
 + ================================================================================
 + ================================================================================
 * debug
 + ================================================================================
 + ================================================================================
 + ================================================================================
 + ================================================================================
 + ================================================================================
 + ================================================================================
 + ================================================================================ */
function debugMousePosition(event){
	var log = 'Position: (X, Y): (' + Event.pointerX(event) + ', ' +  Event.pointerY(event) + ')';
	debug('debugPosition', log, 1);
}

function debug(where, what, clean){
	var target = $(where);
	if(target!=null){
		if(clean){
			target.innerHTML = '<br>' + what;
		}else{
			target.innerHTML = '<br>' + what + target.innerHTML;
		}
	}
}

function print_r(variable, recursive, level){
	var result = "";
	level = level?level:0;
	
	espacio = '';
	for(var i=0; i<=level; i++){
		espacio += '&nbsp;&nbsp;';
	}
	
	for(var varname in variable){
		if(typeof(variable[varname]) == 'function'){
			result  +=  "\n<br>" + espacio + varname + ': function ';
		}else{
			if(recursive == 1 && typeof(variable[varname]) != 'string'){
				result  +=  "\n<br>" + espacio + varname + ': ' + print_r(variable[varname], recursive, level + 1);
			}else{
				result  +=  "\n<br>" + espacio + varname + ': ' + variable[varname];
			}
		}
	}
	return result;
}






