<%
	import se.datadosen.util.SmartResourceBundle;
	import java.io.File;
	import javax.swing.ImageIcon;
	import java.util.*;

	Properties getFolderConfig(File dir, String file_name)
	{
		Map vars = getVariableContainer(dir);
		String cache_key = CACHE_KEY_PREFIX + file_name;

		if( !vars.containsKey(cache_key) )
			vars.put(cache_key, getFolderConfigImpl(dir, file_name));

		return vars.get(cache_key);
	}

	Properties getFolderConfigImpl(File dir, String file_name)
	{
		File propsFile = new File((dir!=null) ? dir : imageDirectory, file_name);
		Properties props = null;

		// Seems that the IO.readProperties() doesn't do the job well when the keys contain spaces!
		if( propsFile.exists() )
		{
			props = new Properties();

			BufferedReader reader = new BufferedReader( new FileReader(propsFile) );
			String line;

			while( (line=reader.readLine())!=null )
			{
				line = line.trim();

				if( !line.startsWith("#") )
				{
					int index = line.indexOf("=");

					if( index!=-1 && index>0 )
					{
						String value = "";
						
						if( index<line.length()-1 )
							value = line.substring( index+1 );
						props.put( line.substring(0, index), value );
					}
				}
			}
		}

		return props;
	}

	String readTextFile(File file)
	{
		if( file!=null && file.exists() && file.length()>0 )
			return se.datadosen.util.IO.readTextFile(file);
		else
			return "";
	}

	boolean isVariableValueEqual(String var_name, File dir, boolean var_value)
	{
		Object value = readUserVariableAsObject(var_name, dir);

		if( value instanceof Boolean )
			return( ((Boolean)value).booleanValue()==var_value );

		if( !isEmptyString(value) )
		{
			String str_value = value.toString().trim();

			if( str_value.equalsIgnoreCase("true") || str_value.equalsIgnoreCase("yes") )
				return var_value==true;
			else if( str_value.equalsIgnoreCase("false") || str_value.equalsIgnoreCase("no") )
				return var_value==false;
		}

		// Empty value means "TRUE" as the default for variables with "Include" prefix (a quick hack)!
		if( (var_name.toLowerCase().startsWith("include") && !var_name.equalsIgnoreCase(USER_VAR_INCLUDE_SAVE_PROTECTION) && !var_name.equalsIgnoreCase(USER_VAR_INCLUDE_BLENDING_EFFECT_ON_INDEXES))
		    || var_name.equalsIgnoreCase(USER_VAR_CYCLIC_SLIDE_SHOW) )
			return var_value==true;
		else
			return var_value==false;
	}

	int readUserVariableAsInteger(String var_name, File dir, int default_value)
	{
		Object value = readUserVariableAsObject(var_name, dir);

		if( value instanceof Integer )
			return ((Integer)value).intValue();

		if( isEmptyString(value) )
			return default_value;
		else
			return convertToInteger(value);
	}

	double readUserVariableAsDouble(String var_name, File dir, double default_value)
	{
		Object value = readUserVariableAsObject(var_name, dir);

		if( value instanceof Double )
			return ((Double)value).doubleValue();

		if( isEmptyString(value) )
			return default_value;
		else
			return convertToDouble(value);
	}

	String readUserVariableAsString(String var_name, File dir, String default_value)
	{
		Object value = readUserVariableAsObject(var_name, dir);

		if( isEmptyString(value) )
			return default_value;
		else
			return value.toString();
	}

	Object readUserVariableAsObject(String var_name, File dir)
	{
		if( dir!=null && !dir.isDirectory() )
			dir = dir.getParentFile();

		Map vars = getVariableContainer(dir);
		String cache_key = CACHE_KEY_FOLDER_USER_VARIABLE + var_name;

		if( !vars.containsKey(cache_key) )
			vars.put(cache_key, readUserVariableAsObjectImpl(var_name, dir));

		return vars.get(cache_key);
	}

	Object readUserVariableAsObjectImpl(String var_name, File dir)
	{
		Properties prop = getFolderConfig(dir, FOLDER_LEVEL_VARIABLES);
		
		if( prop!=null && prop.containsKey(var_name) )
			return prop.get(var_name);

		while( !isTopLevelFolder(dir) )
		{
			dir = dir.getParentFile();
			prop = getFolderConfig(dir, FOLDER_LEVEL_VARIABLES);
			if( prop!=null && prop.containsKey(var_name) )
				return prop.get(var_name);
		}

		return engine.getUserVariables().get(var_name);
	}

	boolean isVariableDefined(String var_name, File dir)
	{
		Object value = readUserVariableAsObject(var_name, dir);
		
		return !isEmptyString(value);
	}
	
	String readFromFolderMetadata(String var_name, File dir)
	{
		return readFromFolderMetadata(var_name, dir, false, null);
	}
	
	String readFromFolderMetadata(String var_name, File dir, boolean check_parent, String parent_prefix)
	{
		if( dir!=null && !dir.isDirectory() )
			dir = dir.getParentFile();

		Properties prop = getFolderConfig(dir, FOLDER_META_DATA);
		
		if( prop!=null && prop.containsKey(var_name) )
			return prop.get(var_name);

		if( check_parent )
		{
			String my_prefix = "";

			while( !isTopLevelFolder(dir) )
			{
				dir = dir.getParentFile();
				if( !isEmptyString(parent_prefix) )
					my_prefix += parent_prefix;

				prop = getFolderConfig(dir, FOLDER_META_DATA);
				if( prop!=null && prop.containsKey(var_name) )
				{
					if( !isEmptyString(parent_prefix) )
						return my_prefix + prop.get(var_name);
					else
						return prop.get(var_name);
				}
			}
		}

		return null;
	}

	boolean isTopLevelFolder(File dir)
	{
		return( dir==null || fileVariables.get(dir)==null );
	}
	
	boolean isEmptyString(Object obj)
	{
		return( obj==null || obj.toString().trim().equals("") );
	}

	// Strip non-numeric ending on strings and convert result to double
	double convertToDouble(Object obj)
	{
		if( isEmptyString(obj) )
			return 0;

		String str = obj.toString();
		int i;

		for (i=0; i<str.length(); i++)
		{
			char c = str.charAt(i);
			if (!Character.isDigit(c) && c!='.' && c!='+' && c!='-' )
				break;
		}
		return Double.parseDouble(str.substring(0,i));
	}

	// Strip non-numeric ending on strings and convert result to integer
	int convertToInteger(Object obj)
	{
		if( isEmptyString(obj) )
			return 0;

		String str = obj.toString();
		int i;

		for (i=0; i<str.length(); i++)
		{
			char c = str.charAt(i);
			if (!Character.isDigit(c))
				break;
		}
		return Integer.parseInt(str.substring(0,i));
	}

	String getFromResourceBundle(String key)
	{
	    return getResourceBundle(SKIN_RESOURCE_BUNDLE_NAME, CACHE_KEY_SKIN_RESOURCE_BUNDLE).getString(key);
	}

	SmartResourceBundle getResourceBundle(String resourceBaseName, String cacheKey)
	{
		if( !album.containsKey(cacheKey) )
		{
			SmartResourceBundle texts;
			File baseResourceDir = new File(skinDirectory, "texts");

			if( language!=void )
				texts = SmartResourceBundle.getBundle(baseResourceDir, resourceBaseName, new Locale(language, ""));
			else
				texts = SmartResourceBundle.getBundle(baseResourceDir, resourceBaseName);
			album.put(cacheKey, texts);
		}

		return (SmartResourceBundle) album.get(cacheKey);
	}

	String appendString(String main_str, String str_to_append, boolean tooltip)
	{
		String separator = tooltip ? " * " : " <br/>\n";

		return appendString(main_str, str_to_append, separator);
	}

	String appendString(String main_str, String str_to_append, String separator)
	{
		if( isEmptyString(str_to_append) )
			return main_str;

		String result = main_str;

		if( result!=null && !result.trim().equals("") )
			result += separator;
		else
			result = "";

		return result + str_to_append;
	}

	boolean isMovieFile(File file)
	{
		String myFileName = getFileName(file);

		if (myFileName.lastIndexOf(".")>0)
		{
			String fileType = myFileName.substring(myFileName.lastIndexOf(".")).trim();

			if( fileType.equalsIgnoreCase(".AVI") || fileType.equalsIgnoreCase(".MOV") || fileType.equalsIgnoreCase(".MPG") || fileType.equalsIgnoreCase(".MPEG") || fileType.equalsIgnoreCase(".WMV") )
				return true;
		}

		return false;
	}

	String getFileName(File myfile)
	{
		if( myfile==null ) //The current file/folder!
		{
			if( imageNum!=void ) // File
				myfile = files[imageNum-1];
			else // Folder
				myfile = imageDirectory;
		}

		Map vars = fileVariables.get(myfile);
		String result = null;
		
		if( vars!=null )
			result = vars.get("fileName");
		
		if( isEmptyString(result) )
			result = myfile.getName();
		
		return result;
	}

	String getLabel(File myfile)
	{
		if( myfile==null ) //The current file/folder!
		{
			if( imageNum!=void ) // File
				myfile = files[imageNum-1];
			else // Folder
				myfile = imageDirectory;
		}

		Map vars = fileVariables.get(myfile);
		String result = null;
		
		if( vars!=null )
			result = vars.get("label");

		if( isEmptyString(result) )
		{
			int dot_index = myfile.getName().indexOf('.');

			if( dot_index!=-1 )
				result = myfile.getName().substring(0, dot_index);
			else
				result = myfile.getName();
		}
		
		return result;
	}

	Map getVariableContainer(File file)
	{
		if( file==null ) //The current file/folder!
		{
			if( imageNum!=void ) // File
				file = files[imageNum-1];
			else // Folder
				file = imageDirectory;
		}

		Map result = fileVariables.get(file);

		//The directory is top-most-level so doing a trick here and keep the top-most-level directory properties in 'album' object!
		if( file.isDirectory() && result==null )
			result = album;
		return result;
	}

	Dimension getIconDimension(File icon, int max_width, int max_height)
	{
		Dimension size = new Dimension(max_width, max_height);
		
		if( icon==null )
			return size;
		
		if( icon.exists() )
			size = getIconDimensionImpl(icon, max_width, max_height);
        /*
		else
		{
			// Code contribution from David Hart...
			// ===== Not platform independent so still in comment to come into a solid result! ======
		
			String myIconPath = icon.getPath();
			String myPath = imageDirectory.getCanonicalPath();
			int myLength = outputDirectory.getCanonicalPath().length();			
			int myThumbsPos = myIconPath.indexOf("thumbs\\");
			
			myPath += myIconPath.substring(myLength,myThumbsPos);
			myPath += myIconPath.substring(myThumbsPos + 7, myIconPath.length());

			size = getIconDimensionImpl(new File(myPath), max_width, max_height)
		}
        */

		return size;
	}

	Dimension getIconDimensionImpl(File icon, int max_width, int max_height)
	{
		ImageIcon image = new ImageIcon(icon.toURL());
		Dimension size = new Dimension(image.getIconWidth(), image.getIconHeight());

		// This shouldn't occur normally!
		if( size.width<=0 || size.height<=0 )
		{
			size.width = max_width;
			size.height = max_height;
		}

		if( size.width>max_width )
		{
			size.height = (size.height * max_width) / size.width;
			size.width = max_width;
		}

		if( size.height>max_height )
		{
			size.width = (size.width * max_height) / size.height;
			size.height = max_height;
		}
		
		return size;
	}

    String clearHtmlCode(String str)
    {
    	if( str==null || str.indexOf("<")==-1 )
    		return str;

    	StringBuffer buf = new StringBuffer();

    	for( int i=0; i<str.length(); i++ )
    	{
    		char ch = str.charAt(i);

    		if( ch!='<' )
    			buf.append(ch);
    		else
    		{
	    		i = str.indexOf(">", i);
	    		if( i==-1 )
	    			break;
	    	}
    	}

    	return buf.toString();
    }

    String encodeUrlIfNecessary(String url)
    {
        if( engine.isUrlEncode() )
            return URLEncoder.encode( url );
        return url;
    }

    void displayMessage(String msg)
    {
        if( window!=null )
            window.messageBox(msg);
        else
            System.out.println(msg);
    }

    String formatBigTemplate(String template, Object[] args)
    {
    	StringBuffer result = new StringBuffer();

    	for( int i=0; i<template.length(); i++ )
    	{
    		char ch = template.charAt(i);

    		if( ch=='{' )
    		{
    			int index = template.indexOf("}", i);

    			 if( index>i+1 )
    			 {
				 	try
				 	{
				 		int arg_no = Integer.parseInt( template.substring(i+1, index) );
				 		Object arg = args[arg_no];

				 		result.append( (arg==null) ? arg : arg.toString() );
				 		i = index;
				 		continue;
				 	}
				 	catch( Exception e )
				 	{
				 	}
    			 }
    		}

    		result.append(ch);
    	}
    	return result.toString();
    }

    /*String htmlEncode(String s)
    {
        if( s==null || s.trim().equals("") )
            return s;

        StringBuffer str = new StringBuffer();

        for (int j = 0; j < s.length(); j++)
        {
            char c = s.charAt(j);

            // encode standard ASCII characters into HTML entities where needed
            if (c < '\200')
            {
                switch (c)
                {
                    case '"':
                        str.append("&quot;");
                        break;

                    case '&':
                        str.append("&amp;");
                        break;

                    case '<':
                        str.append("&lt;");
                        break;

                    case '>':
                        str.append("&gt;");
                        break;

                    default:
                        str.append(c);
                }
            }
            // encode 'ugly' characters (ie Word "curvy" quotes etc)
            else if (c < '\377')
            {
                String hexChars = "0123456789ABCDEF";
                int a = c % 16;
                int b = (c - a) / 16;
                String hex = "" + hexChars.charAt(b) + hexChars.charAt(a);

                str.append("&#x" + hex + ";");
            }
            //add other characters back in - to handle charactersets other than ascii
            else
            {
                str.append(c);
            }
        }

        return str.toString();
    }*/
%>