/**
 * jQuery BASE64 functions
 * 
 * 	<code>
 * 		Encodes the given data with base64. 
 * 		String $.base64Encode ( String str )
 *		<br />
 * 		Decodes a base64 encoded data.
 * 		String $.base64Decode ( String str )
 * 	</code>
 * 
 * Encodes and Decodes the given data in base64.
 * This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
 * Base64-encoded data takes about 33% more space than the original data. 
 * This javascript code is used to encode / decode data using base64 (this encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean). Script is fully compatible with UTF-8 encoding. You can use base64 encoded data as simple encryption mechanism.
 * If you plan using UTF-8 encoding in your project don't forget to set the page encoding to UTF-8 (Content-Type meta tag). 
 * This function orginally get from the WebToolkit and rewrite for using as the jQuery plugin.
 * 
 * Example
 * 	Code
 * 		<code>
 * 			$.base64Encode("I'm Persian."); 
 * 		</code>
 * 	Result
 * 		<code>
 * 			"SSdtIFBlcnNpYW4u"
 * 		</code>
 * 	Code
 * 		<code>
 * 			$.base64Decode("SSdtIFBlcnNpYW4u");
 * 		</code>
 * 	Result
 * 		<code>
 * 			"I'm Persian."
 * 		</code>
 * 
 * @alias Muhammad Hussein Fattahizadeh < muhammad [AT] semnanweb [DOT] com >
 * @link http://www.semnanweb.com/jquery-plugin/base64.html
 * @see http://www.webtoolkit.info/
 * @license http://www.gnu.org/licenses/gpl.html [GNU General Public License]
 * @param {jQuery} {base64Encode:function(input))
 * @param {jQuery} {base64Decode:function(input))
 * @return string
 */

(function($){
	
	var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	
	var uTF8Encode = function(string) {
		string = string.replace(/\x0d\x0a/g, "\x0a");
		var output = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				output += String.fromCharCode(c);
			} else if ((c > 127) && (c < 2048)) {
				output += String.fromCharCode((c >> 6) | 192);
				output += String.fromCharCode((c & 63) | 128);
			} else {
				output += String.fromCharCode((c >> 12) | 224);
				output += String.fromCharCode(((c >> 6) & 63) | 128);
				output += String.fromCharCode((c & 63) | 128);
			}
		}
		return output;
	};
	
	var uTF8Decode = function(input) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < input.length ) {
			c = input.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if ((c > 191) && (c < 224)) {
				c2 = input.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = input.charCodeAt(i+1);
				c3 = input.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
	
	$.extend({
		base64Encode: function(input) {
			var output = "";
			var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
			var i = 0;
			input = uTF8Encode(input);
			while (i < input.length) {
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
				output = output + keyString.charAt(enc1) + keyString.charAt(enc2) + keyString.charAt(enc3) + keyString.charAt(enc4);
			}
			return output;
		},
		base64Decode: function(input) {
			var output = "";
			var chr1, chr2, chr3;
			var enc1, enc2, enc3, enc4;
			var i = 0;
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
			while (i < input.length) {
				enc1 = keyString.indexOf(input.charAt(i++));
				enc2 = keyString.indexOf(input.charAt(i++));
				enc3 = keyString.indexOf(input.charAt(i++));
				enc4 = keyString.indexOf(input.charAt(i++));
				chr1 = (enc1 << 2) | (enc2 >> 4);
				chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				chr3 = ((enc3 & 3) << 6) | enc4;
				output = output + String.fromCharCode(chr1);
				if (enc3 != 64) {
					output = output + String.fromCharCode(chr2);
				}
				if (enc4 != 64) {
					output = output + String.fromCharCode(chr3);
				}
			}
			output = uTF8Decode(output);
			return output;
		}
	});
})(jQuery);
/*
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
/*
### jQuery Multiple File Upload Plugin v1.46 - 2009-05-12 ###
* Home: http://www.fyneworks.com/jquery/multiple-file-upload/
* Code: http://code.google.com/p/jquery-multifile-plugin/
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
###
*/

/*# AVOID COLLISIONS #*/
;if(window.jQuery) (function($){
/*# AVOID COLLISIONS #*/

	// plugin initialization
	$.fn.MultiFile = function(options){
		if(this.length==0) return this; // quick fail
		
		// Handle API methods
		if(typeof arguments[0]=='string'){
			// Perform API methods on individual elements
			if(this.length>1){
				var args = arguments;
				return this.each(function(){
					$.fn.MultiFile.apply($(this), args);
   });
			};
			// Invoke API method handler
			$.fn.MultiFile[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
			// Quick exit...
			return this;
		};
		
		// Initialize options for this call
		var options = $.extend(
			{}/* new object */,
			$.fn.MultiFile.options/* default options */,
			options || {} /* just-in-time options */
		);
		
		// Empty Element Fix!!!
		// this code will automatically intercept native form submissions
		// and disable empty file elements
		$('form')
		.not('MultiFile-intercepted')
		.addClass('MultiFile-intercepted')
		.submit($.fn.MultiFile.disableEmpty);
		
		//### http://plugins.jquery.com/node/1363
		// utility method to integrate this plugin with others...
		if($.fn.MultiFile.options.autoIntercept){
			$.fn.MultiFile.intercept( $.fn.MultiFile.options.autoIntercept /* array of methods to intercept */ );
			$.fn.MultiFile.options.autoIntercept = null; /* only run this once */
		};
		
		// loop through each matched element
		this
		 .not('.MultiFile-applied')
			.addClass('MultiFile-applied')
		.each(function(){
			//#####################################################################
			// MAIN PLUGIN FUNCTIONALITY - START
			//#####################################################################
			
      // BUG 1251 FIX: http://plugins.jquery.com/project/comments/add/1251
      // variable group_count would repeat itself on multiple calls to the plugin.
      // this would cause a conflict with multiple elements
      // changes scope of variable to global so id will be unique over n calls
      window.MultiFile = (window.MultiFile || 0) + 1;
      var group_count = window.MultiFile;
      
      // Copy parent attributes - Thanks to Jonas Wagner
      // we will use this one to create new input elements
      var MultiFile = {e:this, E:$(this), clone:$(this).clone()};
      
      //===
      
      //# USE CONFIGURATION
      if(typeof options=='number') options = {max:options};
      var o = $.extend({},
       $.fn.MultiFile.options,
       options || {},
  					($.metadata? MultiFile.E.metadata(): ($.meta?MultiFile.E.data():null)) || {}, /* metadata options */
								{} /* internals */
      );
      // limit number of files that can be selected?
      if(!(o.max>0) /*IsNull(MultiFile.max)*/){
       o.max = MultiFile.E.attr('maxlength');
       if(!(o.max>0) /*IsNull(MultiFile.max)*/){
        o.max = (String(MultiFile.e.className.match(/\b(max|limit)\-([0-9]+)\b/gi) || ['']).match(/[0-9]+/gi) || [''])[0];
        if(!(o.max>0)) o.max = -1;
        else           o.max = String(o.max).match(/[0-9]+/gi)[0];
       }
      };
      o.max = new Number(o.max);
     //Limit number of images that can be uploaded to 1 until bug fixed... 
      o.max = 1;
      // limit extensions?
      o.accept = o.accept || MultiFile.E.attr('accept') || '';
      if(!o.accept){
       o.accept = (MultiFile.e.className.match(/\b(accept\-[\w\|]+)\b/gi)) || '';
       o.accept = new String(o.accept).replace(/^(accept|ext)\-/i,'');
      };
      
      //===
      
      // APPLY CONFIGURATION
							$.extend(MultiFile, o || {});
      MultiFile.STRING = $.extend({},$.fn.MultiFile.options.STRING,MultiFile.STRING);
      
      //===
      
      //#########################################
      // PRIVATE PROPERTIES/METHODS
      $.extend(MultiFile, {
       n: 0, // How many elements are currently selected?
       slaves: [], files: [],
       instanceKey: MultiFile.e.id || 'MultiFile'+String(group_count), // Instance Key?
       generateID: function(z){ return MultiFile.instanceKey + (z>0 ?'_F'+String(z):''); },
       trigger: function(event, element){
        var handler = MultiFile[event], value = $(element).attr('value');
        if(handler){
         var returnValue = handler(element, value, MultiFile);
         if( returnValue!=null ) return returnValue;
        }
        return true;
       }
      });
      
      //===
      
      // Setup dynamic regular expression for extension validation
      // - thanks to John-Paul Bader: http://smyck.de/2006/08/11/javascript-dynamic-regular-expresions/
      if(String(MultiFile.accept).length>1){
								MultiFile.accept = MultiFile.accept.replace(/\W+/g,'|').replace(/^\W|\W$/g,'');
       MultiFile.rxAccept = new RegExp('\\.('+(MultiFile.accept?MultiFile.accept:'')+')$','gi');
      };
      
      //===
      
      // Create wrapper to hold our file list
      MultiFile.wrapID = MultiFile.instanceKey+'_wrap'; // Wrapper ID?
      MultiFile.E.wrap('<div class="MultiFile-wrap" id="'+MultiFile.wrapID+'"></div>');
      MultiFile.wrapper = $('#'+MultiFile.wrapID+'');
      
      //===
      
      // MultiFile MUST have a name - default: file1[], file2[], file3[]
      MultiFile.e.name = MultiFile.e.name || 'file'+ group_count +'[]';
      
      //===
      
							if(!MultiFile.list){
								// Create a wrapper for the list
								// * OPERA BUG: NO_MODIFICATION_ALLOWED_ERR ('list' is a read-only property)
								// this change allows us to keep the files in the order they were selected
								MultiFile.wrapper.append( '<div class="MultiFile-list" id="'+MultiFile.wrapID+'_list"></div>' );
								MultiFile.list = $('#'+MultiFile.wrapID+'_list');
							};
      MultiFile.list = $(MultiFile.list);
							
      //===
      
      // Bind a new element
      MultiFile.addSlave = function( slave, slave_count ){
								//if(window.console) console.log('MultiFile.addSlave',slave_count);
								
       // Keep track of how many elements have been displayed
       MultiFile.n++;
       // Add reference to master element
       slave.MultiFile = MultiFile;
								
								// BUG FIX: http://plugins.jquery.com/node/1495
								// Clear identifying properties from clones
								if(slave_count>0) slave.id = slave.name = '';
								
       // Define element's ID and name (upload components need this!)
       //slave.id = slave.id || MultiFile.generateID(slave_count);
								if(slave_count>0) slave.id = MultiFile.generateID(slave_count);
								//FIX for: http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=23
       
       // 2008-Apr-29: New customizable naming convention (see url below)
       // http://groups.google.com/group/jquery-dev/browse_frm/thread/765c73e41b34f924#
       slave.name = String(MultiFile.namePattern
        /*master name*/.replace(/\$name/gi,$(MultiFile.clone).attr('name'))
        /*master id  */.replace(/\$id/gi,  $(MultiFile.clone).attr('id'))
        /*group count*/.replace(/\$g/gi,   group_count)//(group_count>0?group_count:''))
        /*slave count*/.replace(/\$i/gi,   slave_count)//(slave_count>0?slave_count:''))
       );
       
       // If we've reached maximum number, disable input slave
       if( (MultiFile.max > 0) && ((MultiFile.n-1) > (MultiFile.max)) )//{ // MultiFile.n Starts at 1, so subtract 1 to find true count
        slave.disabled = true;
       //};
       
       // Remember most recent slave
       MultiFile.current = MultiFile.slaves[slave_count] = slave;
       
								// We'll use jQuery from now on
								slave = $(slave);
       
       // Clear value
       slave.val('').attr('value','')[0].value = '';
       
								// Stop plugin initializing on slaves
								slave.addClass('MultiFile-applied');
								
       // Triggered when a file is selected
       slave.change(function(){
         //if(window.console) console.log('MultiFile.slave.change',slave_count);
								 
         // Lose focus to stop IE7 firing onchange again
         $(this).blur();
         
         //# Trigger Event! onFileSelect
         if(!MultiFile.trigger('onFileSelect', this, MultiFile)) return false;
         //# End Event!
         
         //# Retrive value of selected file from element
         var ERROR = '', v = String(this.value || ''/*.attr('value)*/);
         
         // check extension
         if(MultiFile.accept && v && !v.match(MultiFile.rxAccept))//{
           ERROR = MultiFile.STRING.denied.replace('$ext', String(v.match(/\.\w{1,4}$/gi)));
          //}
         //};
         
         // Disallow duplicates
										for(var f in MultiFile.slaves)//{
          if(MultiFile.slaves[f] && MultiFile.slaves[f]!=this)//{
 										//console.log(MultiFile.slaves[f],MultiFile.slaves[f].value);
           if(MultiFile.slaves[f].value==v)//{
            ERROR = MultiFile.STRING.duplicate.replace('$file', v.match(/[^\/\\]+$/gi));
           //};
          //};
         //};
         
         // Create a new file input element
         var newEle = $(MultiFile.clone).clone();// Copy parent attributes - Thanks to Jonas Wagner
         //# Let's remember which input we've generated so
         // we can disable the empty ones before submission
         // See: http://plugins.jquery.com/node/1495
         newEle.addClass('MultiFile');
         
         // Handle error
         if(ERROR!=''){
           // Handle error
           MultiFile.error(ERROR);
												
           // 2007-06-24: BUG FIX - Thanks to Adrian Wr�bel <adrian [dot] wrobel [at] gmail.com>
           // Ditch the trouble maker and add a fresh new element
           MultiFile.n--;
           MultiFile.addSlave(newEle[0], slave_count);
           slave.parent().prepend(newEle);
           slave.remove();
           return false;
         };
         
         // Hide this element (NB: display:none is evil!)
         $(this).css({ position:'absolute', top: '-3000px' });
         
         // Add new element to the form
         slave.after(newEle);
         
         // Update list
         MultiFile.addToList( this, slave_count );
         
         // Bind functionality
         MultiFile.addSlave( newEle[0], slave_count+1 );
         
         //# Trigger Event! afterFileSelect
         if(!MultiFile.trigger('afterFileSelect', this, MultiFile)) return false;
         //# End Event!
         
       }); // slave.change()
								
								// Save control to element
								$(slave).data('MultiFile', MultiFile);
								
      };// MultiFile.addSlave
      // Bind a new element
      
      
      
      // Add a new file to the list
      MultiFile.addToList = function( slave, slave_count ){
       //if(window.console) console.log('MultiFile.addToList',slave_count);
								
       //# Trigger Event! onFileAppend
       if(!MultiFile.trigger('onFileAppend', slave, MultiFile)) return false;
       //# End Event!
       
       // Create label elements
       var
        r = $('<div class="MultiFile-label"></div>'),
        v = String(slave.value || ''/*.attr('value)*/),
        a = $('<span class="MultiFile-title" title="'+MultiFile.STRING.selected.replace('$file', v)+'">'+MultiFile.STRING.file.replace('$file', v.match(/[^\/\\]+$/gi)[0])+
       		 '</span>&nbsp;&nbsp;' + 
       		 	'<select name="upload[][description]" class="multiFileSelect">' + 
        				'<option value="Außenaufnahme">Außenaufnahme</option>' +
        				'<option value="Badezimmer">Badezimmer</option>' +
        				'<option value="Bar">Bar</option>' +
        				'<option value="Folklore">Folklore</option>' +
        				'<option value="Garten">Garten</option>' +
        				'<option value="Hallenbad">Hallenbad</option>' +
        				'<option value="Hotelanlage">Hotelanlage</option>' +
        				'<option value="Internetcafe">Internetcafe</option>' +
        				'<option value="Konferenzraum">Konferenzraum</option>' +
        				'<option value="Kultur">Kultur</option>' +
        				'<option value="Kunst">Kunst</option>' +
        				'<option value="Lounge/Empfang">Lounge/Empfang</option>' +
        				'<option value="Logo">Logo</option>' +
        				'<option value="Landkarte">Landkarte</option>' +
        				'<option value="Landschaft">Landschaft</option>' +
        				'<option value="Luftaufnahme">Luftaufnahme</option>' +
        				'<option value="Mietfahrzeug">Mietfahrzeug</option>' +
        				'<option value="Meer/Hafen/Schiff">Meer/Hafen/Schiff</option>' +
        				'<option value="Modellaufnahme">Modellaufnahme</option>' +
        				'<option value="Natur">Natur</option>' +
        				'<option value="Pool">Pool</option>' +
        				'<option value="Personen">Personen</option>' +
        				'<option value="Preis">Preis</option>' +
        				'<option value="Restaurant">Restaurant</option>' +
        				'<option value="Strand">Strand</option>' +
        				'<option value="Sehenswürdigkeiten">Sehenswürdigkeiten</option>' +
        				'<option value="Stadtansicht">Stadtansicht</option>' +
        				'<option value="Terrasse">Terrasse</option>' +
        				'<option value="Tiere">Tiere</option>' +
        				'<option value="Wellness">Wellness</option>' +
        				'<option value="Wohnbeispiel">Wohnbeispiel</option>' +
        				'<option value="Zimmerausblick">Zimmerausblick</option>' +
        				'<option value="Sonstiges">Sonstiges</option>' +
        			'</select>'),
        b = $('<a class="MultiFile-remove" href="#'+MultiFile.wrapID+'"><img src="/img/general/close.png" alt="remove" align="absmiddle" /></a>'), 
        c = $('<br /><textarea style="margin-left:18px;margin-bottom:5px;" name="comments[][comment]" cols="30" rows="1" class="commentBox" onfocus="if($(this).val()==\'Kommentar hinzufügen...\'){$(this).val(\'\')};" onblur="if($(this).val()==\'\'){$(this).val(\'Kommentar hinzufügen...\')};">Kommentar hinzufügen...</textarea>');
       
       // Insert label
       MultiFile.list.append(
        r.append(b, ' ', a, ' ', c)
       );
       
       b
								.click(function(){
        
         //# Trigger Event! onFileRemove
         if(!MultiFile.trigger('onFileRemove', slave, MultiFile)) return false;
         //# End Event!
         
         MultiFile.n--;
         MultiFile.current.disabled = false;
         
         // Remove element, remove label, point to current
										MultiFile.slaves[slave_count] = null;
										$(slave).remove();
										$(this).parent().remove();
										
         // Show most current element again (move into view) and clear selection
         $(MultiFile.current).css({ position:'', top: '' });
										$(MultiFile.current).reset().val('').attr('value', '')[0].value = '';
         
         //# Trigger Event! afterFileRemove
         if(!MultiFile.trigger('afterFileRemove', slave, MultiFile)) return false;
         //# End Event!
										
         return false;
       });
       
       //# Trigger Event! afterFileAppend
       if(!MultiFile.trigger('afterFileAppend', slave, MultiFile)) return false;
       //# End Event!
       
      }; // MultiFile.addToList
      // Add element to selected files list
      
      
      
      // Bind functionality to the first element
      if(!MultiFile.MultiFile) MultiFile.addSlave(MultiFile.e, 0);
      
      // Increment control count
      //MultiFile.I++; // using window.MultiFile
      MultiFile.n++;
							
							// Save control to element
							MultiFile.E.data('MultiFile', MultiFile);
							

			//#####################################################################
			// MAIN PLUGIN FUNCTIONALITY - END
			//#####################################################################
		}); // each element
	};
	
	/*--------------------------------------------------------*/
	
	/*
		### Core functionality and API ###
	*/
	$.extend($.fn.MultiFile, {
 /**
  * This method removes all selected files
  *
  * Returns a jQuery collection of all affected elements.
  *
  * @name reset
  * @type jQuery
  * @cat Plugins/MultiFile
  * @author Diego A. (http://www.fyneworks.com/)
  *
  * @example $.fn.MultiFile.reset();
  */
 reset: function(){
			var settings = $(this).data('MultiFile');
			//if(settings) settings.wrapper.find('a.MultiFile-remove').click();
			if(settings) settings.list.find('a.MultiFile-remove').click();
  return $(this);
 },
 
 
 /**
  * This utility makes it easy to disable all 'empty' file elements in the document before submitting a form.
  * It marks the affected elements so they can be easily re-enabled after the form submission or validation.
  *
  * Returns a jQuery collection of all affected elements.
  *
  * @name disableEmpty
  * @type jQuery
  * @cat Plugins/MultiFile
  * @author Diego A. (http://www.fyneworks.com/)
  *
  * @example $.fn.MultiFile.disableEmpty();
  * @param String class (optional) A string specifying a class to be applied to all affected elements - Default: 'mfD'.
  */
 disableEmpty: function(klass){ klass = (typeof(klass)=='string'?klass:'')||'mfD';
  var o = [];
  $('input:file.MultiFile').each(function(){ if($(this).val()=='') o[o.length] = this; });
  return $(o).each(function(){ this.disabled = true }).addClass(klass);
 },
 
 
		/**
			* This method re-enables 'empty' file elements that were disabled (and marked) with the $.fn.MultiFile.disableEmpty method.
			*
			* Returns a jQuery collection of all affected elements.
			*
			* @name reEnableEmpty
			* @type jQuery
			* @cat Plugins/MultiFile
			* @author Diego A. (http://www.fyneworks.com/)
			*
			* @example $.fn.MultiFile.reEnableEmpty();
			* @param String klass (optional) A string specifying the class that was used to mark affected elements - Default: 'mfD'.
			*/
 reEnableEmpty: function(klass){ klass = (typeof(klass)=='string'?klass:'')||'mfD';
  return $('input:file.'+klass).removeClass(klass).each(function(){ this.disabled = false });
 },
 
 
		/**
			* This method will intercept other jQuery plugins and disable empty file input elements prior to form submission
			*
	
			* @name intercept
			* @cat Plugins/MultiFile
			* @author Diego A. (http://www.fyneworks.com/)
			*
			* @example $.fn.MultiFile.intercept();
			* @param Array methods (optional) Array of method names to be intercepted
			*/
 intercepted: {},
 intercept: function(methods, context, args){
  var method, value; args = args || [];
  if(args.constructor.toString().indexOf("Array")<0) args = [ args ];
  if(typeof(methods)=='function'){
   $.fn.MultiFile.disableEmpty();
   value = methods.apply(context || window, args);
				//SEE-http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=27
				setTimeout(function(){ $.fn.MultiFile.reEnableEmpty() },1000);
   return value;
  };
  if(methods.constructor.toString().indexOf("Array")<0) methods = [methods];
  for(var i=0;i<methods.length;i++){
   method = methods[i]+''; // make sure that we have a STRING
   if(method) (function(method){ // make sure that method is ISOLATED for the interception
    $.fn.MultiFile.intercepted[method] = $.fn[method] || function(){};
    $.fn[method] = function(){
     $.fn.MultiFile.disableEmpty();
     value = $.fn.MultiFile.intercepted[method].apply(this, arguments);
						//SEE-http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=27
     setTimeout(function(){ $.fn.MultiFile.reEnableEmpty() },1000);
     return value;
    }; // interception
   })(method); // MAKE SURE THAT method IS ISOLATED for the interception
  };// for each method
 }
});
	
	/*--------------------------------------------------------*/
	
	/*
		### Default Settings ###
		eg.: You can override default control like this:
		$.fn.MultiFile.options.accept = 'gif|jpg';
	*/
	$.fn.MultiFile.options = { //$.extend($.fn.MultiFile, { options: {
		accept: '', // accepted file extensions
		max: 20,    // maximum number of selectable files
		
		// name to use for newly created elements
		namePattern: '$name', // same name by default (which creates an array)
		
		// STRING: collection lets you show messages in different languages
		STRING: {
			remove:'x',
			denied:'You cannot select a $ext file.\nTry again...',
			file:'$file',
			selected:'File selected: $file',
			duplicate:'This file has already been selected:\n$file'
		},
		
		// name of methods that should be automcatically intercepted so the plugin can disable
		// extra file elements that are empty before execution and automatically re-enable them afterwards
 autoIntercept: [ 'submit', 'ajaxSubmit', 'ajaxForm', 'validate' /* array of methods to intercept */ ],
		
		// error handling function
		error: function(s){
			/*
			ERROR! blockUI is not currently working in IE
			if($.blockUI){
				$.blockUI({
					message: s.replace(/\n/gi,'<br/>'),
					css: { 
						border:'none', padding:'15px', size:'12.0pt',
						backgroundColor:'#900', color:'#fff',
						opacity:'.8','-webkit-border-radius': '10px','-moz-border-radius': '10px'
					}
				});
				window.setTimeout($.unblockUI, 2000);
			}
			else//{// save a byte!
			*/
			 alert(s);
			//}// save a byte!
		}
}; //} });
	
	/*--------------------------------------------------------*/
	
	/*
		### Additional Methods ###
		Required functionality outside the plugin's scope
	*/
	
	// Native input reset method - because this alone doesn't always work: $(element).val('').attr('value', '')[0].value = '';
	$.fn.reset = function(){ return this.each(function(){ try{ this.reset(); }catch(e){} }); };
	
	/*--------------------------------------------------------*/
	
	/*
		### Default implementation ###
		The plugin will attach itself to file inputs
		with the class 'multi' when the page loads
	*/
	$(function(){
 //$("input:file.multi").MultiFile();
 $("input[type=file].multi").MultiFile();
});
	
	
	
/*# AVOID COLLISIONS #*/
})(jQuery);
/*# AVOID COLLISIONS #*/


jQuery.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	// Create jQuery object for input element
	var $input = $(input).attr("autocomplete", "off");

	// Apply inputClass if necessary
	if (options.inputClass) $input.addClass(options.inputClass);

	// Create results
	var results = document.createElement("div");
	// Create jQuery object for results
	var $results = $(results);
	$results.hide().addClass(options.resultsClass).css("position", "absolute");
	if( options.width > 0 ) $results.css("width", options.width);

	// Add to body element
	$("body").append(results);

	input.autocompleter = me;

	var timeout = null;
	var prev = "";
	var active = -1;
	var cache = {};
	var keyb = false;
	var hasFocus = false;
	var lastKeyPressCode = null;

	// flush cache
	function flushCache(){
		cache = {};
		cache.data = {};
		cache.length = 0;
	};

	// flush cache
	flushCache();

	// if there is a data array supplied
	if( options.data != null ){
		var sFirstChar = "", stMatchSets = {}, row = [];

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( typeof options.url != "string" ) options.cacheLength = 1;

		// loop through the array and create a lookup structure
		for( var i=0; i < options.data.length; i++ ){
			// if row is a string, make an array otherwise just reference the array
			row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

			// if the length is zero, don't add to list
			if( row[0].length > 0 ){
				// get the first character
				sFirstChar = row[0].substring(0, 1).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
				// if the match is a string
				stMatchSets[sFirstChar].push(row);
			}
		}

		// add the data items to the cache
		for( var k in stMatchSets ){
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			addToCache(k, stMatchSets[k]);
		}
	}

	$input
	.keydown(function(e) {
		// track last key pressed
		lastKeyPressCode = e.keyCode;
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				if( selectCurrent() ){
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
				} else
				{
					options.noSelect($input.val());
					e.preventDefault();
				}
				break;
			default:
				active = -1;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){onChange();}, options.delay);
				break;
		}
	})
	.focus(function(){
		// track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
	})
	.blur(function() {
		// track whether the field has focus
		hasFocus = false;
		hideResults();
	});

	hideResultsNow();

	function onChange() {
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
		var v = $input.val();
		if (v == prev) return;
		prev = v;
		if (v.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			requestData(v);
		} else {
			$input.removeClass(options.loadingClass);
			$results.hide();
		}
	};

 	function moveSelect(step) {

		var lis = $("li", results);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass("ac_over");

		$(lis[active]).addClass("ac_over");

		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent() {
		var li = $("li.ac_over", results)[0];
		if (!li) {
			var $li = $("li", results);
			if (options.selectOnly) {
				if ($li.length == 1) li = $li[0];
			} else if (options.selectFirst) {
				li = $li[0];
			}
		}
		if (li) {
			selectItem(li);
			return true;
		} else {
			return false;
		}
	};

	function selectItem(li) {
		if (!li) {
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
		}
		var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
		input.lastSelected = v;
		prev = v;
		$results.html("");
		$input.val(v);
		hideResultsNow();
		if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
	};

	// selects a portion of the input string
	function createSelection(start, end){
		// get a reference to the input element
		var field = $input.get(0);
		if( field.createTextRange ){
			var selRange = field.createTextRange();
			selRange.collapse(true);
			selRange.moveStart("character", start);
			selRange.moveEnd("character", end);
			selRange.select();
		} else if( field.setSelectionRange ){
			field.setSelectionRange(start, end);
		} else {
			if( field.selectionStart ){
				field.selectionStart = start;
				field.selectionEnd = end;
			}
		}
		field.focus();
	};

	// fills in the input box w/the first match (assumed to be the best match)
	function autoFill(sValue){
		// if the last user key pressed was backspace, don't autofill
		if( lastKeyPressCode != 8 ){
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(prev.length));
			// select the portion of the value not typed by the user (so the next character will erase)
			createSelection(prev.length, sValue.length);
		}
	};

	function showResults() {
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = findPos(input);
		// either use the specified width, or autocalculate based on form element
		var iWidth = (options.width > 0) ? options.width : $input.width();
		// reposition
		$results.css({
			width: parseInt(iWidth) + "px",
			top: (pos.y + input.offsetHeight) + "px",
			left: pos.x + "px"
		}).show();
	};

	function hideResults() {
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		if (timeout) clearTimeout(timeout);
		$input.removeClass(options.loadingClass);
		if ($results.is(":visible")) {
			$results.hide();
		}
		if (options.mustMatch) {
			var v = $input.val();
			if (v != input.lastSelected) {
				selectItem(null);
			}
		}
	};

	function receiveData(q, data) {
		if (data) {
			$input.removeClass(options.loadingClass);
			results.innerHTML = "";

			// if the field no longer has focus or if there are no matches, do not display the drop down
			if( !hasFocus || data.length == 0 ) return hideResultsNow();

			if ($.browser.msie) {
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				$results.append(document.createElement('iframe'));
			}
			results.appendChild(dataToDom(data));
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
			showResults();
		} else {
			hideResultsNow();
		}
	};

	function parseData(data) {
		if (!data) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data) {
		var ul = document.createElement("ul");
		var num = data.length;

		// limited results to a max number
		if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

		for (var i=0; i < num; i++) {
			var row = data[i];
			if (!row) continue;
			var li = document.createElement("li");
			if (options.formatItem) {
				li.innerHTML = options.formatItem(row, i, num);
				li.selectValue = row[0];
			} else {
				li.innerHTML = row[0];
				li.selectValue = row[0];
			}
			var extra = null;
			if (row.length > 1) {
				extra = [];
				for (var j=1; j < row.length; j++) {
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			ul.appendChild(li);
			$(li).hover(
				function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
				function() { $(this).removeClass("ac_over"); }
			).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
		}
		return ul;
	};

	function requestData(q) {
		if (!options.matchCase) q = q.toLowerCase();
		//var data = options.cachefunction load()Length ? loadFromCache(q) : null;
		var data = options.cacheLength ? loadFromCache(q) : null;
		// recieve the cached data
		if (data) {
			receiveData(q, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data);
				addToCache(q, data);
				receiveData(q, data);
			});
		// if there's been no data found, remove the loading class
		} else {
			$input.removeClass(options.loadingClass);
		}
	};

	function makeUrl(q) {
		var url = options.url + "?q=" + encodeURI(q);
		for (var i in options.extraParams) {
			url += "&" + i + "=" + encodeURI(options.extraParams[i]);
		}
		return url;
	};

	function loadFromCache(q) {
		if (!q) return null;
		if (cache.data[q]) return cache.data[q];
		if (options.matchSubset) {
			for (var i = q.length - 1; i >= options.minChars; i--) {
				var qs = q.substr(0, i);
				var c = cache.data[qs];
				if (c) {
					var csub = [];
					for (var j = 0; j < c.length; j++) {
						var x = c[j];
						var x0 = x[0];
						if (matchSubset(x0, q)) {
							csub[csub.length] = x;
						}
					}
					return csub;
				}
			}
		}
		return null;
	};

	function matchSubset(s, sub) {
		if (!options.matchCase) s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	this.flushCache = function() {
		flushCache();
	};

	this.setExtraParams = function(p) {
		options.extraParams = p;
	};

	this.findValue = function(){
		var q = $input.val();

		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		if (data) {
			findValueCallback(q, data);
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data)
				addToCache(q, data);
				findValueCallback(q, data);
			});
		} else {
			// no matches
			findValueCallback(q, null);
		}
	}

	function findValueCallback(q, data){
		if (data) $input.removeClass(options.loadingClass);

		var num = (data) ? data.length : 0;
		var li = null;

		for (var i=0; i < num; i++) {
			var row = data[i];

			if( row[0].toLowerCase() == q.toLowerCase() ){
				li = document.createElement("li");
				if (options.formatItem) {
					li.innerHTML = options.formatItem(row, i, num);
					li.selectValue = row[0];
				} else {
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if( row.length > 1 ){
					extra = [];
					for (var j=1; j < row.length; j++) {
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
			}
		}

		if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
	}

	function addToCache(q, data) {
		if (!data || !q || !options.cacheLength) return;
		if (!cache.length || cache.length > options.cacheLength) {
			flushCache();
			cache.length++;
		} else if (!cache[q]) {
			cache.length++;
		}
		cache.data[q] = data;
	};

	function findPos(obj) {
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	}
}

jQuery.fn.autocomplete = function(url, options, data) {
	// Make sure options exists
	options = options || {};
	// Set url as option
	options.url = url;
	// set some bulk local data
	options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

	// Set default values for required options
	options.inputClass = options.inputClass || "ac_input";
	options.resultsClass = options.resultsClass || "ac_results";
	options.lineSeparator = options.lineSeparator || "\n";
	options.cellSeparator = options.cellSeparator || "|";
	options.minChars = options.minChars || 1;
	options.delay = options.delay || 400;
	options.matchCase = options.matchCase || 0;
	options.matchSubset = options.matchSubset || 0;
	options.matchContains = options.matchContains || 0;
	options.cacheLength = options.cacheLength || 1;
	options.mustMatch = options.mustMatch || 0;
	options.extraParams = options.extraParams || {};
	options.loadingClass = options.loadingClass || "ac_loading";
	options.selectFirst = options.selectFirst || false;
	options.selectOnly = options.selectOnly || false;
	options.maxItemsToShow = options.maxItemsToShow || -1;
	options.autoFill = options.autoFill || false;
	options.width = parseInt(options.width, 10) || 0;

	this.each(function() {
		var input = this;
		new jQuery.autocomplete(input, options);
	});

	// Don't break the chain
	return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
	return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};


/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


/*
 * jQuery Galleriffic plugin
 *
 * Copyright (c) 2008 Trent Foley (http://trentacular.com)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Thanks to Taku Sano (Mikage Sawatari), whose history plugin I adapted to work with Galleriffic
 * Modified by Ghismo (ghismo.com) to disable the location rewrite 
 */
;(function($) {
	// Write noscript style
	document.write("<style type='text/css'>.noscript{display:none}</style>");

	var ver = 'galleriffic-1.0';
	var galleryOffset = 0;
	var galleries = [];
	var allImages = [];	
	var historyCurrentHash;
	var historyBackStack;
	var historyForwardStack;
	var isFirst = false;
	var dontCheck = false;
	var isInitialized = false;

	function getHashFromString(hash) {
		if (!hash) return -1;
		hash = hash.replace(/^.*#/, '');
		if (isNaN(hash)) return -1;
		return (+hash);
	}

	function getHash() {
		var hash = location.hash;
		return getHashFromString(hash);
	}

	function registerGallery(gallery) {
		galleries.push(gallery);

		// update the global offset value
		galleryOffset += gallery.data.length;
	}

	function getGallery(hash) {
		for (i = 0; i < galleries.length; i++) {
			var gallery = galleries[i];
			if (hash < (gallery.data.length+gallery.offset))
				return gallery;
		}
		return 0;
	}
	
	function getIndex(gallery, hash) {
		return hash-gallery.offset;
	}
	
	function clickHandler(e, gallery, link) {
		gallery.pause();

		if (!gallery.settings.enableHistory) {
			var hash = getHashFromString(link.href);
			if (hash >= 0) {
				var index = getIndex(gallery, hash);
				if (index >= 0)
					gallery.goto(index);
			}
			e.preventDefault();
		}
	}

	function historyCallback() {
		// Using present location.hash always (seems to work, unlike the hash argument passed to this callback)
		var hash = getHash();
		if (hash < 0) return;

		var gallery = getGallery(hash);
		if (!gallery) return;
		
		var index = hash-gallery.offset;
		gallery.goto(index);
	}
	
	function historyInit() {
		if (isInitialized) return;
		isInitialized = true; 

		var current_hash = location.hash; //(enableHistory) ? location.hash : currentIndexHash; // Ghismo

		historyCurrentHash = current_hash;
		if ($.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (historyCurrentHash == '') {
				historyCurrentHash = '#';
			}
		} else if ($.browser.safari) {
			// etablish back/forward stacks
			historyBackStack = [];
			historyBackStack.length = history.length;
			historyForwardStack = [];
			isFirst = true;
		}

		setInterval(function() { historyCheck(); }, 100);
	}
	
	function historyAddHistory(hash) {
		// This makes the looping function do something
		historyBackStack.push(hash);
		historyForwardStack.length = 0; // clear forwardStack (true click occured)
		isFirst = true;
	}
	
	function historyCheck() {
		if ($.browser.safari) {
			if (!dontCheck) {
				var historyDelta = history.length - historyBackStack.length;
				
				if (historyDelta) { // back or forward button has been pushed
					isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) historyForwardStack.unshift(historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) historyBackStack.push(historyForwardStack.shift());
					}
					var cachedHash = historyBackStack[historyBackStack.length - 1];
					if (cachedHash != undefined) {
						historyCurrentHash = location.hash; // (enableHistory) ? location.hash : currentIndexHash; // Ghismo
						historyCallback();
					}
				} else if (historyBackStack[historyBackStack.length - 1] == undefined && !isFirst) {
					historyCallback();
					isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash; // (enableHistory) ? location.hash : currentIndexHash; // Ghismo
			if(current_hash != historyCurrentHash) {
				historyCurrentHash = current_hash;
				historyCallback();
			}
		}
	}

	var defaults = {
		delay:                  3000,
		numThumbs:              20,
		preloadAhead:           40, // Set to -1 to preload all images
		enableTopPager:         false,
		enableBottomPager:      true,
		imageContainerSel:      '',
		captionContainerSel:    '',
		controlsContainerSel:   '',
		loadingContainerSel:    '',
		renderSSControls:       true,
		renderNavControls:      true,
		playLinkText:           'Play',
		pauseLinkText:          'Pause',
		prevLinkText:           'Previous',
		nextLinkText:           'Next',
		nextPageLinkText:       'Next &rsaquo;',
		prevPageLinkText:       '&lsaquo; Prev',
		targetLink:				'http://bewertungen.schmetterling.eu/index/show-picture/locationId//pictureId/',
		enableHistory:          false,
		autoStart:              false,
		onChange:               undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
		onTransitionOut:        undefined, // accepts a delegate like such: function(callback) { ... }
		onTransitionIn:         undefined, // accepts a delegate like such: function() { ... }
		onPageTransitionOut:    undefined, // accepts a delegate like such: function(callback) { ... }
		onPageTransitionIn:     undefined  // accepts a delegate like such: function() { ... }
	};

	$.fn.galleriffic = function(thumbsContainerSel, settings) {
		//  Extend Gallery Object
		$.extend(this, {
			ver: function() {
				return ver;
			},

			initializeThumbs: function() {
				this.data = [];
				var gallery = this;
				
				this.$thumbsContainer.find('ul.thumbs > li').each(function(i) {
					var $li = $(this);
					var $aThumb = $li.find('a.thumb');
					var hash = gallery.offset+i;

					gallery.data.push({
						title:$aThumb.attr('title'),
						slideUrl:$aThumb.attr('href'),
						caption:$li.find('.caption').remove(),
						hash:hash
					});

					// Setup history
					$aThumb.attr('rel', 'history');
					$aThumb.attr('href', '#'+hash);
					$aThumb.click(function(e) {
						clickHandler(e, gallery, this);
					});
				});
				return this;
			},

			isPreloadComplete: false,

			preloadInit: function() {
				if (this.settings.preloadAhead == 0) return this;
				
				this.preloadStartIndex = this.currentIndex;
				var nextIndex = this.getNextIndex(this.preloadStartIndex);
				return this.preloadRecursive(this.preloadStartIndex, nextIndex);
			},
			
			preloadRelocate: function(index) {
				// By changing this startIndex, the current preload script will restart
				this.preloadStartIndex = index;
				return this;
			},

			preloadRecursive: function(startIndex, currentIndex) {
				// Check if startIndex has been relocated
				if (startIndex != this.preloadStartIndex) {
					var nextIndex = this.getNextIndex(this.preloadStartIndex);
					return this.preloadRecursive(this.preloadStartIndex, nextIndex);
				}

				var gallery = this;

				// Now check for preloadAhead count
				var preloadCount = currentIndex - startIndex;
				if (preloadCount < 0)
					preloadCount = this.data.length-1-startIndex+currentIndex;
				if (this.settings.preloadAhead >= 0 && preloadCount > this.settings.preloadAhead) {
					// Do this in order to keep checking for relocated start index
					setTimeout(function() { gallery.preloadRecursive(startIndex, currentIndex); }, 500);
					return this;
				}

				var imageData = this.data[currentIndex];
				if (!imageData)
					return this;

				// If already loaded, continue
				if (imageData.image)
					return this.preloadNext(startIndex, currentIndex); 
				
				// Preload the image
				var image = new Image();
				
				image.onload = function() {
					imageData.image = this;
					gallery.preloadNext(startIndex, currentIndex);
				};

				image.alt = imageData.title;
				image.src = imageData.slideUrl;

				return this;
			},
			
			preloadNext: function(startIndex, currentIndex) {
				var nextIndex = this.getNextIndex(currentIndex);
				if (nextIndex == startIndex) {
					this.isPreloadComplete = true;
				} else {
					// Use set timeout to free up thread
					var gallery = this;
					setTimeout(function() { gallery.preloadRecursive(startIndex, nextIndex); }, 100);
				}
				return this;
			},

			getNextIndex: function(index) {
				var nextIndex = index+1;
				if (nextIndex >= this.data.length)
					nextIndex = 0;
				return nextIndex;
			},
			
			getPrevIndex: function(index) {
				var prevIndex = index-1;
				if (prevIndex < 0)
					prevIndex = this.data.length-1;
				return prevIndex;
			},

			pause: function() {
				if (this.interval)
					this.toggleSlideshow();
				
				return this;
			},

			play: function() {
				if (!this.interval)
					this.toggleSlideshow();
				
				return this;
			},

			toggleSlideshow: function() {
				if (this.interval) {
					clearInterval(this.interval);
					this.interval = 0;
					
					if (this.$controlsContainer) {
						this.$controlsContainer
							.find('div.ss-controls a').removeClass().addClass('play')
							.attr('title', this.settings.playLinkText)
							.attr('href', '#play')
							.html(this.settings.playLinkText);
					}
				} else {
					this.ssAdvance();

					var gallery = this;
					this.interval = setInterval(function() {
						gallery.ssAdvance();
					}, this.settings.delay);
					
					if (this.$controlsContainer) {
						this.$controlsContainer
							.find('div.ss-controls a').removeClass().addClass('pause')
							.attr('title', this.settings.pauseLinkText)
							.attr('href', '#pause')
							.html(this.settings.pauseLinkText);
					}
				}

				return this;
			},

			ssAdvance: function() {
				var nextIndex = this.getNextIndex(this.currentIndex);
				var nextHash = this.data[nextIndex].hash;

				// Seems to be working on both FF and Safari
				if (this.settings.enableHistory)
					location.href = '#'+nextHash;
				else
					this.goto(nextIndex);

				// IE we need to explicity call goto
				//if ($.browser.msie) {
				//	this.goto(nextIndex);
				//}

				return this;
			},

			goto: function(index) {
				if (index < 0) index = 0;
				else if (index >= this.data.length) index = this.data.length-1;
				
				if (this.settings.onChange)
					this.settings.onChange(this.currentIndex, index);
				
				this.currentIndex = index;
				this.preloadRelocate(index);
				return this.refresh();
			},
			
			refresh: function() {
				var imageData = this.data[this.currentIndex];
				if (!imageData)
					return this;
				
				// Flag we are transitioning
				var isTransitioning = true;

				var gallery = this;

				var transitionOutCallback = function() {
					// Flag that the transition has completed
					isTransitioning = false;

					// Update Controls
					if (gallery.$controlsContainer) {
						gallery.$controlsContainer
							.find('div.nav-controls a.prev').attr('href', '#'+gallery.data[gallery.getPrevIndex(gallery.currentIndex)].hash).end()
							.find('div.nav-controls a.next').attr('href', '#'+gallery.data[gallery.getNextIndex(gallery.currentIndex)].hash);
					}

					var imageData = gallery.data[gallery.currentIndex];

					// Replace Caption
					if (gallery.$captionContainer) {
						gallery.$captionContainer.empty().append(imageData.caption);
					}

					if (imageData.image) {
						gallery.buildImage(imageData.image);
					} else {
						// Show loading container
						if (gallery.$loadingContainer) {
							gallery.$loadingContainer.show();
						}
					}
				}

				if (this.settings.onTransitionOut) {
					this.settings.onTransitionOut(transitionOutCallback);
				} else {
					this.$transitionContainers.hide();
					transitionOutCallback();
				}

				if (!imageData.image) {
					var image = new Image();
					
					// Wire up mainImage onload event
					image.onload = function() {
						imageData.image = this;

						if (!isTransitioning) {
							gallery.buildImage(imageData.image);
						}
					};

					// set alt and src
					image.alt = imageData.title;
					image.src = imageData.slideUrl;
				}

				// This causes the preloader (if still running) to relocate out from the currentIndex
				this.relocatePreload = true;

				return this.syncThumbs();
			},
			
			buildImage: function(image) {
				if (this.$imageContainer) {
					this.$imageContainer.empty();

					var gallery = this;
					var nextIndex = this.getNextIndex(this.currentIndex);

					// Hide the loading conatiner
					if (this.$loadingContainer) {
						this.$loadingContainer.hide();
					}

					var imageSplit = image.src.split('/');
					
					// Setup image
					this.$imageContainer
//						.append('<span class="image-wrapper"><a class="advance-link" rel="history" href="#'+this.data[nextIndex].hash+'" title="'+image.alt+'"></a></span>')
						.append('<span class="image-wrapper"><a class="advance-link" rel="history" href="' + this.settings.targetLink + imageSplit[6] + '/provider/' + $('#providerCode').val() + '" title="'+image.alt+'"></a></span>')
						.find('a')
						.append(image)
						.click(function(e) {
							clickHandler(e, gallery, this);
						});
				}

				if (this.settings.onTransitionIn)
					this.settings.onTransitionIn();
				else
					this.$transitionContainers.show();

				return this;
			},

			syncThumbs: function() {
				if (this.$thumbsContainer) {
					var page = Math.floor(this.currentIndex / this.settings.numThumbs);
					if (page != this.currentPage) {
						this.currentPage = page;
						this.updateThumbs();
					}

					// Remove existing selected class and add selected class to new thumb
					var $thumbs = this.$thumbsContainer.find('ul.thumbs').children();
					$thumbs.filter('.selected').removeClass('selected');
					$thumbs.eq(this.currentIndex).addClass('selected');
				}

				return this;
			},

			updateThumbs: function() {
				var gallery = this;
				var transitionOutCallback = function() {
					gallery.rebuildThumbs();

					// Transition In the thumbsContainer
					if (gallery.settings.onPageTransitionIn)
						gallery.settings.onPageTransitionIn();
					else
						gallery.$thumbsContainer.show();
				};

				// Transition Out the thumbsContainer
				if (this.settings.onPageTransitionOut) {
					this.settings.onPageTransitionOut(transitionOutCallback);
				} else {
					this.$thumbsContainer.hide();
					transitionOutCallback();
				}

				return this;
			},

			rebuildThumbs: function() {
				// Initialize currentPage to first page
				if (this.currentPage < 0)
					this.currentPage = 0;
				
				var needsPagination = this.data.length > this.settings.numThumbs;

				// Rebuild top pager
				var $topPager = this.$thumbsContainer.find('div.top');
				if ($topPager.length == 0)
					$topPager = this.$thumbsContainer.prepend('<div class="top pagination"></div>').find('div.top');

				if (needsPagination && this.settings.enableTopPager) {
					$topPager.empty();
					this.buildPager($topPager);
				}

				// Rebuild bottom pager
				if (needsPagination && this.settings.enableBottomPager) {
					var $bottomPager = this.$thumbsContainer.find('div.bottom');
					if ($bottomPager.length == 0)
						$bottomPager = this.$thumbsContainer.append('<div class="bottom pagination"></div>').find('div.bottom');
					else
						$bottomPager.empty();

					this.buildPager($bottomPager);
				}

				var startIndex = this.currentPage*this.settings.numThumbs;
				var stopIndex = startIndex+this.settings.numThumbs-1;
				if (stopIndex >= this.data.length)
					stopIndex = this.data.length-1;

				// Show/Hide thumbs
				var $thumbsUl = this.$thumbsContainer.find('ul.thumbs');
				$thumbsUl.find('li').each(function(i) {
					var $li = $(this);
					if (i >= startIndex && i <= stopIndex) {
						$li.show();
					} else {
						$li.hide();
					}
				});

				// Remove the noscript class from the thumbs container ul
				$thumbsUl.removeClass('noscript');
				
				return this;
			},

			buildPager: function(pager) {
				var gallery = this;
				var startIndex = this.currentPage*this.settings.numThumbs;
				
				// Prev Page Link
				if (this.currentPage > 0) {
					var prevPage = startIndex - this.settings.numThumbs;
					pager.append('<a rel="history" href="#'+this.data[prevPage].hash+'" title="'+this.settings.prevPageLinkText+'">'+this.settings.prevPageLinkText+'</a>');
				}

				// Page Index Links
				for (i=this.currentPage-3; i<=this.currentPage+3; i++) {
					var pageNum = i+1;
					
					if (i == this.currentPage)
						pager.append('<span class="current">'+pageNum+'</span>');
					else if (i>=0 && i<this.numPages) {
						var imageIndex = i*this.settings.numThumbs;
						pager.append('<a rel="history" href="#'+this.data[imageIndex].hash+'" title="'+pageNum+'">'+pageNum+'</a>');
					}
				}

				// Next Page Link
				var nextPage = startIndex+this.settings.numThumbs;
				if (nextPage < this.data.length) {
					pager.append('<a rel="history" href="#'+this.data[nextPage].hash+'" title="'+this.settings.nextPageLinkText+'">'+this.settings.nextPageLinkText+'</a>');
				}

				pager.find('a').click(function(e) {
					clickHandler(e, gallery, this);
				});

				return this;
			}
		});

		// Now initialize the gallery
		this.settings = $.extend({}, defaults, settings);
		//enableHistory = this.settings.enableHistory; // Ghismo

		if (this.interval)
			clearInterval(this.interval);

		this.interval = 0;
		
		if (this.settings.imageContainerSel) this.$imageContainer = $(this.settings.imageContainerSel);
		if (this.settings.captionContainerSel) this.$captionContainer = $(this.settings.captionContainerSel);
		if (this.settings.loadingContainerSel) this.$loadingContainer = $(this.settings.loadingContainerSel);

		// Setup the jQuery object holding each container that will be transitioned
		this.$transitionContainers = $([]);
		if (this.$imageContainer)
			this.$transitionContainers = this.$transitionContainers.add(this.$imageContainer);
		if (this.$captionContainer)
			this.$transitionContainers = this.$transitionContainers.add(this.$captionContainer);
		
		// Set the hash index offset for this gallery
		this.offset = galleryOffset;

		this.$thumbsContainer = $(thumbsContainerSel);
		this.initializeThumbs();

		// Add this gallery to the global galleries array
		registerGallery(this);

		this.numPages = Math.ceil(this.data.length/this.settings.numThumbs);
		this.currentPage = -1;
		this.currentIndex = 0;
		var gallery = this;

		// Hide the loadingContainer
		if (this.$loadingContainer)
			this.$loadingContainer.hide();

		// Setup controls
		if (this.settings.controlsContainerSel) {
			this.$controlsContainer = $(this.settings.controlsContainerSel).empty();
			
			if (this.settings.renderSSControls) {
				if (this.settings.autoStart) {
					this.$controlsContainer
						.append('<div class="ss-controls"><a href="#pause" class="pause" title="'+this.settings.pauseLinkText+'">'+this.settings.pauseLinkText+'</a></div>');
				} else {
					this.$controlsContainer
						.append('<div class="ss-controls"><a href="#play" class="play" title="'+this.settings.playLinkText+'">'+this.settings.playLinkText+'</a></div>');
				}

				this.$controlsContainer.find('div.ss-controls a')
					.click(function(e) {
						gallery.toggleSlideshow();
						e.preventDefault();
						return false;
					});
			}
		
			if (this.settings.renderNavControls) {
				var $navControls = this.$controlsContainer
					.append('<div class="nav-controls"><a class="prev" rel="history" title="'+this.settings.prevLinkText+'">'+this.settings.prevLinkText+'</a><a class="next" rel="history" title="'+this.settings.nextLinkText+'">'+this.settings.nextLinkText+'</a></div>')
					.find('div.nav-controls a')
					.click(function(e) {
						clickHandler(e, gallery, this);
					});
			}
		}

		// Initialize history only once when the first gallery on the page is initialized
		historyInit();
		
		// Build image
		var hash = getHash();
		var hashGallery = (hash >= 0) ? getGallery(hash) : 0;
		var gotoIndex = (hashGallery && this == hashGallery) ? (hash-this.offset) : 0;
		this.goto(gotoIndex);

		if (this.settings.autoStart) {
			
			setTimeout(function() { gallery.play(); }, this.settings.delay);
		}

		// Kickoff Image Preloader after 1 second
		setTimeout(function() { gallery.preloadInit(); }, 1000);

		return this;
	};
})(jQuery);


/*
 * JTip
 * By Cody Lindley (http://www.codylindley.com)
 * Under an Attribution, Share Alike License
 * JTip is built on top of the very light weight jquery library.
 */

//on page load (as soon as its ready) call JT_init
$(document).ready(JT_init);

function JT_init(){
   $("a.jTip")
   .click(function(){$('#JT').remove();JT_show(this.href,this.id,this.name)})
   .click(function(){return false});
}

function JT_close() {
//	$("a.jTip").onfocus(function(){$('#JT').remove()});
	if(document.getElementById('JT'))
	{
		document.getElementById('bodyTag').removeChild(document.getElementById('JT'));
	}		
}

function JT_show(url,linkId,title){
	if(title == false)title="&nbsp;";
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft(linkId);
	var clickElementy = getAbsoluteTop(linkId) - 3; //set y position
	
	var queryString = url.replace(/^[^\?]+\??/,'');
	var params = parseQuery( queryString );
	if(params['width'] === undefined){params['width'] = 450};
	if(params['link'] !== undefined){
	$('#' + linkId).bind('click',function(){window.location = params['link']});
	$('#' + linkId).css('cursor','pointer');
	}
	
	if(hasArea>((params['width']*1)+75)){
		$("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_left'></div><div id='JT_close_left'>"+title+"<span style='float: right; margin-right: 5px; cursor:pointer;'><img src='" + base + "/img/tooltip/close.png' alt='close' onclick='JT_close();' /></span></div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//right side
		var arrowOffset = getElementWidth(linkId) + 11;
		var clickElementx = getAbsoluteLeft(linkId) + arrowOffset; //set x position
	}else{
		$("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_right' style='left:"+((params['width']*1)+1)+"px'></div><div id='JT_close_right'>"+title+"<span style='float: right; margin-right: 5px; cursor:pointer;'><img src='" + base + "/img/tooltip/close.png' alt='close' onclick='JT_close();' /></span></div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//left side
		var clickElementx = getAbsoluteLeft(linkId) - ((params['width']*1) + 15); //set x position
	}
	
	$('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
	$('#JT').show();
	$('#JT_copy').load(url);

}

function getElementWidth(objectId) {
	x = document.getElementById(objectId);
	return x.offsetWidth;
}

function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}

function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
}

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function blockEvents(evt) {
  if(evt.target){
      evt.preventDefault();
  }else{
	  evt.returnValue = false;
  }
}


/**
 * Tabs - jQuery plugin for accessible, unobtrusive tabs
 * @requires jQuery v1.1.1
 *
 * http://stilbuero.de/tabs/
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 2.7.4
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(4($){$.2l({z:{2k:0}});$.1P.z=4(x,w){3(O x==\'2Y\')w=x;w=$.2l({K:(x&&O x==\'1Z\'&&x>0)?--x:0,12:C,J:$.1f?2h:T,18:T,1r:\'2X&#2Q;\',21:\'18-2F-\',1m:C,1u:C,1l:C,1F:C,1x:\'2u\',2r:C,2p:C,2m:T,2i:C,1d:C,1c:C,1j:\'z-1M\',H:\'z-2b\',14:\'z-12\',16:\'z-26\',1q:\'z-1H\',1L:\'z-2L\',2j:\'10\'},w||{});$.8.1D=$.8.U&&($.8.1Y&&$.8.1Y<7||/2A 6.0/.2y(2x.2w));4 1w(){1V(0,0)}F 5.Y(4(){2 p=5;2 r=$(\'13.\'+w.1j,p);r=r.V()&&r||$(\'>13:9(0)\',p);2 j=$(\'a\',r);3(w.18){j.Y(4(){2 c=w.21+(++$.z.2k),B=\'#\'+c,2f=5.1O;5.1O=B;$(\'<10 S="\'+c+\'" 34="\'+w.16+\'"></10>\').2c(p);$(5).19(\'1B\',4(e,a){2 b=$(5).I(w.1L),X=$(\'X\',5)[0],27=X.1J;3(w.1r){X.1J=\'<24>\'+w.1r+\'</24>\'}1p(4(){$(B).2T(2f,4(){3(w.1r){X.1J=27}b.17(w.1L);a&&a()})},0)})})}2 n=$(\'10.\'+w.16,p);n=n.V()&&n||$(\'>\'+w.2j,p);r.P(\'.\'+w.1j)||r.I(w.1j);n.Y(4(){2 a=$(5);a.P(\'.\'+w.16)||a.I(w.16)});2 s=$(\'A\',r).20($(\'A.\'+w.H,r)[0]);3(s>=0){w.K=s}3(1e.B){j.Y(4(i){3(5.B==1e.B){w.K=i;3(($.8.U||$.8.2E)&&!w.18){2 a=$(1e.B);2 b=a.15(\'S\');a.15(\'S\',\'\');1p(4(){a.15(\'S\',b)},2D)}1w();F T}})}3($.8.U){1w()}n.1a(\':9(\'+w.K+\')\').1C().1n().2C(\':9(\'+w.K+\')\').I(w.1q);$(\'A\',r).17(w.H).9(w.K).I(w.H);j.9(w.K).N(\'1B\').1n();3(w.2m){2 l=4(d){2 c=$.2B(n.1t(),4(a){2 h,1A=$(a);3(d){3($.8.1D){a.Z.2z(\'1X\');a.Z.G=\'\';a.1k=C}h=1A.L({\'1h-G\':\'\'}).G()}E{h=1A.G()}F h}).2v(4(a,b){F b-a});3($.8.1D){n.Y(4(){5.1k=c[0]+\'1W\';5.Z.2t(\'1X\',\'5.Z.G = 5.1k ? 5.1k : "2s"\')})}E{n.L({\'1h-G\':c[0]+\'1W\'})}};l();2 q=p.1U;2 m=p.1v;2 v=$(\'#z-2q-2o-V\').1t(0)||$(\'<X S="z-2q-2o-V">M</X>\').L({1T:\'2n\',3a:\'39\',38:\'37\'}).2c(Q.1S).1t(0);2 o=v.1v;36(4(){2 b=p.1U;2 a=p.1v;2 c=v.1v;3(a>m||b!=q||c!=o){l((b>q||c<o));q=b;m=a;o=c}},35)}2 u={},11={},1R=w.2r||w.1x,1Q=w.2p||w.1x;3(w.1u||w.1m){3(w.1u){u[\'G\']=\'1C\';11[\'G\']=\'1H\'}3(w.1m){u[\'W\']=\'1C\';11[\'W\']=\'1H\'}}E{3(w.1l){u=w.1l}E{u[\'1h-2g\']=0;1R=1}3(w.1F){11=w.1F}E{11[\'1h-2g\']=0;1Q=1}}2 t=w.2i,1d=w.1d,1c=w.1c;j.19(\'2e\',4(){2 c=$(5).1g(\'A:9(0)\');3(p.1i||c.P(\'.\'+w.H)||c.P(\'.\'+w.14)){F T}2 a=5.B;3($.8.U){$(5).N(\'1b\');3(w.J){$.1f.1N(a);1e.B=a.1z(\'#\',\'\')}}E 3($.8.1y){2 b=$(\'<2d 33="\'+a+\'"><10><32 31="2a" 30="h" /></10></2d>\').1t(0);b.2a();$(5).N(\'1b\');3(w.J){$.1f.1N(a)}}E{3(w.J){1e.B=a.1z(\'#\',\'\')}E{$(5).N(\'1b\')}}});j.19(\'1E\',4(){2 a=$(5).1g(\'A:9(0)\');3($.8.1y){a.1o({W:0},1,4(){a.L({W:\'\'})})}a.I(w.14)});3(w.12&&w.12.1K){29(2 i=0,k=w.12.1K;i<k;i++){j.9(--w.12[i]).N(\'1E\').1n()}};j.19(\'28\',4(){2 a=$(5).1g(\'A:9(0)\');a.17(w.14);3($.8.1y){a.1o({W:1},1,4(){a.L({W:\'\'})})}});j.19(\'1b\',4(e){2 g=e.2Z;2 d=5,A=$(5).1g(\'A:9(0)\'),D=$(5.B),R=n.1a(\':2W\');3(p[\'1i\']||A.P(\'.\'+w.H)||A.P(\'.\'+w.14)||O t==\'4\'&&t(5,D[0],R[0])===T){5.25();F T}p[\'1i\']=2h;3(D.V()){3($.8.U&&w.J){2 c=5.B.1z(\'#\',\'\');D.15(\'S\',\'\');1p(4(){D.15(\'S\',c)},0)}2 f={1T:\'\',2V:\'\',G:\'\'};3(!$.8.U){f[\'W\']=\'\'}4 1I(){3(w.J&&g){$.1f.1N(d.B)}R.1o(11,1Q,4(){$(d).1g(\'A:9(0)\').I(w.H).2U().17(w.H);R.I(w.1q).L(f);3(O 1d==\'4\'){1d(d,D[0],R[0])}3(!(w.1u||w.1m||w.1l)){D.L(\'1T\',\'2n\')}D.1o(u,1R,4(){D.17(w.1q).L(f);3($.8.U){R[0].Z.1a=\'\';D[0].Z.1a=\'\'}3(O 1c==\'4\'){1c(d,D[0],R[0])}p[\'1i\']=C})})}3(!w.18){1I()}E{$(d).N(\'1B\',[1I])}}E{2S(\'2R P 2P 2O 26.\')}2 a=1G.2N||Q.1s&&Q.1s.23||Q.1S.23||0;2 b=1G.2M||Q.1s&&Q.1s.22||Q.1S.22||0;1p(4(){1G.1V(a,b)},0);5.25();F w.J&&!!g});3(w.J){$.1f.2K(4(){j.9(w.K).N(\'1b\').1n()})}})};2 y=[\'2e\',\'1E\',\'28\'];29(2 i=0;i<y.1K;i++){$.1P[y[i]]=(4(d){F 4(c){F 5.Y(4(){2 b=$(\'13.z-1M\',5);b=b.V()&&b||$(\'>13:9(0)\',5);2 a;3(!c||O c==\'1Z\'){a=$(\'A a\',b).9((c&&c>0&&c-1||0))}E 3(O c==\'2J\'){a=$(\'A a[@1O$="#\'+c+\'"]\',b)}a.N(d)})}})(y[i])}$.1P.2I=4(){2 c=[];5.Y(4(){2 a=$(\'13.z-1M\',5);a=a.V()&&a||$(\'>13:9(0)\',5);2 b=$(\'A\',a);c.2H(b.20(b.1a(\'.z-2b\')[0])+1)});F c[0]}})(2G);',62,197,'||var|if|function|this|||browser|eq||||||||||||||||||||||||||tabs|li|hash|null|toShow|else|return|height|selectedClass|addClass|bookmarkable|initial|css||trigger|typeof|is|document|toHide|id|false|msie|size|opacity|span|each|style|div|hideAnim|disabled|ul|disabledClass|attr|containerClass|removeClass|remote|bind|filter|click|onShow|onHide|location|ajaxHistory|parents|min|locked|navClass|minHeight|fxShow|fxFade|end|animate|setTimeout|hideClass|spinner|documentElement|get|fxSlide|offsetHeight|unFocus|fxSpeed|safari|replace|jq|loadRemoteTab|show|msie6|disableTab|fxHide|window|hide|switchTab|innerHTML|length|loadingClass|nav|update|href|fn|hideSpeed|showSpeed|body|display|offsetWidth|scrollTo|px|behaviour|version|number|index|hashPrefix|scrollTop|scrollLeft|em|blur|container|tabTitle|enableTab|for|submit|selected|appendTo|form|triggerTab|url|width|true|onClick|tabStruct|remoteCount|extend|fxAutoHeight|block|font|fxHideSpeed|watch|fxShowSpeed|1px|setExpression|normal|sort|userAgent|navigator|test|removeExpression|MSIE|map|not|500|opera|tab|jQuery|push|activeTab|string|initialize|loading|pageYOffset|pageXOffset|such|no|8230|There|alert|load|siblings|overflow|visible|Loading|object|clientX|value|type|input|action|class|50|setInterval|hidden|visibility|absolute|position'.split('|'),0,{}))


AjaxLoader = function()
{
	if (window.XMLHttpRequest) 
	{
		request = new XMLHttpRequest();
		
	} else if (window.ActiveXObject) 
	{
		request = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if(!request) 
	{
		return false;
	}
	
	return request;
}

function getProviderDescription (locationId, base)
{
	var provider = document.getElementById('providerDesc').value;
	if (document.getElementById('providerDescription'))
	{
		document.getElementById('providerDescription').style.display = 'none';
	}
	
	if (!provider)
	{
		return false;
	} else
	{
		document.getElementById('ajax_loader').style.display = 'block';
		var path = base + '/request/object-description/locationId/' + locationId + '/provider/' + provider;
		
		$.ajax({
	        url: path,
	        type: 'GET',
	        async: false,
	        cache: false,
	        error: function(){
	            return true;
	        },
	        success: function(msg){ 
	            if (msg)
	            {
					document.getElementById('ajax_loader').style.display = 'none';
					var result = eval(msg);
					document.getElementById('providerDescription').innerHTML = '<legend>Hotelbeschreibung laut offizieller Katalogangaben</legend>';
					document.getElementById('providerDescription').innerHTML += result;
					document.getElementById('providerDescription').style.display = "block";
	            }
	        }
	    });	
	}
}
 
function getNotices (locationId, userId)
{
	var path = base + '/request/show-notices/locationId/' + locationId + '/userId/' + userId;
	// TODO: build with jquery
/*	$.ajax({
		url: path,
		type: 'GET',
		async: false,
		cache: false,
		error: function(){
		return true;
	},
	success: function(msg){ 
		if (msg != 'no')
		{
			var pfad = base + '/request/show-notices/locationId/' + locationId +'/userId/' + userId + '/?width=430';
//			document.getElementById('noticesContainer').innerHTML = '<img src="' + base +'/img/icons/infoicon.png" alt="Achtung" /><span id="noticeImg" onclick="JT_close(); JT_show(\'' + path + '\', \'noticeImg\' , \'Achtung\');" class="jTip"><strong style="color:#D70415;">Achtung, dieses Hotel wurde bereits von Ihnen bewertet!</strong></span>';
			$('#noticesContainer').html('<img src="' + base +'/img/icons/infoicon.png" alt="Achtung" /><span id="noticeImg" onclick="JT_close(); JT_show(\'' + pfad + '\', \'noticeImg\' , \'Achtung\');" class="jTip"><strong style="color:#D70415;">Achtung, dieses Hotel wurde bereits von Ihnen bewertet!</strong></span>');
		}
	}
	});	*/
	
	loader = AjaxLoader();
	loader.onreadystatechange = function()
	{
		if (loader.readyState == 4) 
		{
			if (loader.status == 200) 
			{
				if(loader.responseText)
				{
					if (loader.responseText != 'no')
					{
						var path = base + '/request/show-notices/locationId/' + locationId +'/userId/' + userId + '/?width=430';
						document.getElementById('noticesContainer').innerHTML = '<img src="' + base +'/img/icons/infoicon.png" alt="Achtung" /><span id="noticeImg" onclick="JT_close(); JT_show(\'' + path + '\', \'noticeImg\' , \'Achtung\');" class="jTip"><strong style="color:#D70415;">Achtung, dieses Hotel wurde bereits von Ihnen bewertet!</strong></span>';
					}
				}
			}
		}
	}
	loader.open("GET",path, true);
	loader.send(null);
}

function getProviderPictures (locationid, base)
{
	var code = elem('providerName').value
	window.location.href = base + '/index/show-pictures/locationId/' + locationid  + '/provider/' + code;
}

function elem (id)
{
	return document.getElementById(id);
}

function changeProfilPicture(multimediaId)
{
	var d1 = parent.document.getElementById('userPicture');
	var d2 = parent.document.getElementById('userpic');
	d1.removeChild(d2);
	var path = 'http://media.sr-vice.de/index/thumb/size/130x160/id/' + multimediaId;
	parent.document.getElementById('userPicture').innerHTML = '<img src="' + path + '" alt="userPicture" id="userpic" style="border: 1px solid #003C6E;" />';
	parent.document.getElementById('bodyTag').removeChild(parent.document.getElementById('JT'));
}

var chars = 0;
var charsTextarea = 0;

function checkChars()
{
	count = document.getElementById('rating_text').value.replace(/  /g, "").length;
	chars = count;
	document.getElementById('charCounter').innerHTML = count + charsTextarea;
	if((chars + charsTextarea) < 250){
		document.getElementById('charCounter').style.backgroundColor = "#F8B55A";
	} else 
	{
		document.getElementById('charCounter').style.backgroundColor = "#20be20";
	}
}

function checkRatingTextareas()
{
	checkChars();
	charsTextarea = 0;
	
	i = 0;
	while(elem = document.getElementById('textarea_' + i))
	{
		if(match = elem.value.match(/>>/))
		{
			i++;
			continue;
		} else
		{
			count = elem.value.replace(/  /g, "").length;
			charsTextarea += count;
		}
		i++;
	}
	if((chars + charsTextarea) < 250){
		document.getElementById('charCounter').style.backgroundColor = "#F8B55A";
	} else 
	{
		document.getElementById('charCounter').style.backgroundColor = "#99ff99";
	}
	document.getElementById('charCounter').innerHTML = parseInt(charsTextarea) + parseInt(chars);
}

function checkRatingField()
{
	submit = true;
	if(document.getElementById('travel_month').value == "")
	{
		document.getElementById('travel_month').style.backgroundColor = "#F8B55A";
		submit = false;
	}
	if(document.getElementById('travel_year').value == "")
	{
		document.getElementById('travel_year').style.backgroundColor = "#F8B55A";
		submit = false;
	}
	if(document.getElementById('title').value == "")
	{
		document.getElementById('title').style.backgroundColor = "#F8B55A";
		alert('test');
		submit = false;
	}
	if(document.getElementById('rating_text').value == "")
	{
		document.getElementById('rating_text').style.backgroundColor = "#F8B55A";
		submit = false;
	}
	
	recommend = 0;
	for(i = 0; i < document.rating.recommend.length; i++)
	{
		if(document.rating.recommend[i].checked == false)
		{
			recommend++;
		}
	}
	if(recommend == 3)
	{
		alert('Sie haben die Weiterempfehlung nicht ausgefüllt!');
		submit = false;
		return false;
	}
	
	
	if(!submit)
	{
		alert('Es wurden nicht alle Felder ausgefüllt!');
		return false;
	}		

	if(parseInt(document.getElementById('charCounter').innerHTML) < 250)
	{
		alert('Der Bewertungstext ist zu kurz!');
		return false;
	}
	
	if($('agb').checked == false)
	{
		alert('Sie müssen den Nutzungsbedingungen zustimmen!');
		$('agb').style.backgroundColor = "#F8B55A";
		submit = false;
		return false;
	}
	return submit;
}

function showHide (id)
{
	if(document.getElementById(id).style.display == 'table-row')
	{
		document.getElementById(id).style.display = 'none';
		if (document.getElementById('translate_' + id))
		{
			document.getElementById('translate_' + id).style.display = 'none';
		}
	} else
	{
		document.getElementById(id).style.display = 'table-row';
		if (document.getElementById('translate_' + id))
		{
			document.getElementById('translate_' + id).style.display = 'table-row';
		}
	}		
}

function show_Hochladen () {
  if (document.getElementById) {
    document.getElementById("hochladen").style.display = "inline";
    document.getElementById("veroeffentlichung").style.display = "none";
	document.getElementById("speicherung").style.display = "none";
	document.getElementById("bearbeiten").style.display = "none";
	}
}

function show_Veroeffentlichung () {
  if (document.getElementById) {
    document.getElementById("hochladen").style.display = "none";
    document.getElementById("veroeffentlichung").style.display = "inline";
	document.getElementById("speicherung").style.display = "none";
	document.getElementById("bearbeiten").style.display = "none";
	}
}

function show_Speicherung () {
  if (document.getElementById) {
    document.getElementById("hochladen").style.display = "none";
    document.getElementById("veroeffentlichung").style.display = "none";
	document.getElementById("speicherung").style.display = "inline";
	document.getElementById("bearbeiten").style.display = "none";
	}
}

function show_Bearbeiten () {
  if (document.getElementById) {
    document.getElementById("hochladen").style.display = "none";
    document.getElementById("veroeffentlichung").style.display = "none";
	document.getElementById("speicherung").style.display = "none";
	document.getElementById("bearbeiten").style.display = "inline";
	}
}

function setElement (element, section)
{
	currentElement = element;
	if(document.getElementById(section + '_drop').src == 'http://bewertungen.schmetterling.eu/img/icons/up.png')
	{
		document.getElementById(section + '_drop').src = base + '/img/icons/dropdown.png';
		document.getElementById('content_' + section).style.display = "none";
	} else
	{
		document.getElementById(section + '_drop').src = base + '/img/icons/up.png';
		document.getElementById('content_' + section).style.display = "table-row";
	}
}

checkAvailability = function (giataId, st)
{
	
	var path = base + '/booking/check-price/gid/' + giataId + '/st/' + st;
	$.ajax({
        url: path,
        type: 'GET',
        cache: false,
        timeout: 2000,
        error: function(){
            return true;
        },
        success: function(msg){ 
            if (msg != '"no"'){
            	if (document.getElementById('bookingLink'))
            	{
            		document.getElementById('bookingForm').style.display = 'block';
            		document.getElementById('bookingLink').style.display = 'block';
            	}
            	if (document.getElementById('preis'))
            	{
            		document.getElementById('preis').innerHTML = msg + '&euro;';
            	}
            } else
            {
            	document.getElementById('bookingLink').style.display = 'none';
            }
        }
    });	
}

checkAvailability2 = function (giataId, st)
{
	
	var path = base + '/booking/check-price/gid/' + giataId + '/st/' + st;
	$.ajax({
		url: path,
		type: 'GET',
		cache: false,
		timeout: 2000,
		error: function(){
		return true;
	},
	success: function(msg){ 
		if (msg != '"no"'){
			if (document.getElementById('bookingLink'))
			{
				document.getElementById('bookingForm').style.display = 'block';
				document.getElementById('bookingLink').style.display = 'block';
			}
			if (document.getElementById('preis2'))
			{
				document.getElementById('preis2').innerHTML = 'p.P. ab <span>' + msg + ' &euro; &raquo;';
				$('#preis2').click(function(){
					document.forms['bookingForm'].submit();
				}).css('cursor', 'pointer');
			}
		} else
		{
			document.getElementById('bookingLink').style.display = 'none';
		}
	}
	});	
}

function returnPrice (giataId, st)
{
	if (typeof(giataId) != 'undefined')
	{
		var path = base + '/booking/check-price/gid/' + giataId + '/st/' + st;
		
		$.ajax({
			type: 'GET',
			url: base + '/booking/check-price/gid/' + giataId + '/st/' + st,
			timeout: 2000,
			dataType: "script",
			success: function(msg) {
					if(msg != '"no"')
					{
						$('#bookingPrice_' + giataId).html('p.P. ab ' + msg + ' &euro;');
						document.getElementById('bookingForm_' + giataId).style.display = 'block';
						document.getElementById('checkBookingForm_' + giataId).style.display = 'none';
					} else
					{
						document.getElementById('bookingFormDisabled_' + giataId).style.display = 'block';
						document.getElementById('checkBookingForm_' + giataId).style.display = 'none';
					}
			}
		});
	}
}

function checkId ()
{
	if(document.getElementById('id').value == "")
	{
		return false;
	}
	return true;
}

function showSearch ()
{
	document.getElementById('search').style.opacity = "";
	document.getElementById('ratingPicture').style.opacity = "";
	document.getElementById('search').style.display = 'block';
	document.getElementById('ratingPicture').style.display = 'none';
}

function showTransparentSearch ()
{
	if($.browser.msie===true)
	{
		$('#search').css('display', 'block');
		showSearch();
	} else
	{
		$('#search').css('opacity',0.0);
		$('#search').css('display', 'block');
		$('#showSearchButton').animate({opacity:0.0}, 500);
		$('#search').animate({opacity:1.0},{queue:false, duration:500, complete:showSearch}); 
	}
}

String.prototype.toProperCase = function()
{
    return this.toLowerCase().replace(/^\w+/g,function(s)
    {
    	return s.charAt(0).toUpperCase() + s.substr(1);
    })
}

function markTerms (term, value)
{
	var terms = term.split(" ");
	for(i = 0; i < terms.length; i++)
	{
		value = value.replace(eval('/'+terms[i]+'/i'), '<b>' + terms[i].toProperCase() + '</b>')
	}
	return value;
}

function switchSearch ()
{
	if (document.getElementById('quicksearchContainer').style.width.split('px')[0] > 0)
	{
		$('#quicksearchContainer').animate({width: 0}, 1000);
		$('#extendedsearch').animate({width: 220}, 1000);
	} else
	{
		$('#quicksearchContainer').animate({width: 220}, 1000);
		$('#extendedsearch').animate({width: 0}, 1000);
	}
}

function initExtSearch (id, type)
{
	document.getElementById('id').value = id;
	document.getElementById('type').value = type;
	if(type == 1)
	{
		document.getElementById('citySearch').autocompleter.setExtraParams(
				{
					countryId:id
				});
		document.getElementById('hotelSearch').autocompleter.setExtraParams(
				{
					countryId:id
				});
	}
	if(type == 2)
	{
		document.getElementById('hotelSearch').autocompleter.setExtraParams(
				{
					cityId:id
				});
	}
}

function searchByMap (id)
{
	var location = "";
	if(document.getElementById(id).value != "")
	{
		location = document.getElementById(id).value;
		type = document.getElementById(id + 'Type').value;
		id = document.getElementById(id + 'Id').value;
	} else
	{
		return false;
	}

	document.location.href = base + '/index/search-by-map/location/' + location + '/type/' + type + '/id/' + id;
}


setLeaflet = function (locationId, checked)
{
	var url = base + '/request/leaflet/locationId/' + locationId + '/checked/' + checked;
	
	loader = AjaxLoader();
	loader.onreadystatechange = function()
	{
		if (loader.readyState == 4) 
		{
			if (loader.status == 200) 
			{
				if(loader.responseText)
				{
					document.getElementById('merkzettel').innerHTML = loader.responseText;
				}
			}
		}
	}

	loader.open("POST", url, true);
	loader.send(null);
}

setLeafletUrania = function (locationId, name, price, checked)
{
	var url = base + '/request/leaflet?locationId=' + locationId + '&checked=' + checked + '&name=' + name + '&price=' + price;
	
	loader = AjaxLoader();
	loader.onreadystatechange = function()
	{
		if (loader.readyState == 4) 
		{
			if (loader.status == 200) 
			{
				if(loader.responseText)
				{
					document.getElementById('merkzettel').innerHTML = loader.responseText;
				}
			}
		}
	}
	
	loader.open("POST", url, true);
	loader.send(null);
}

function changeBg (base, elem)
{
	if (!elem.checked)
	{
		elem.parentNode.style.backgroundImage = 'url(' + base + '/img/icons/leaflet.jpg)';
	}
	if (elem.checked)
	{
		elem.parentNode.style.backgroundImage = 'url(' + base + '/img/icons/leaflet_on.jpg)';
	}
}

function loadMap (city)
{	
	if (document.getElementById('resultMaps').style.display == 'none')
	{
		var path = base + '/index/get-js';
		
		loader = AjaxLoader();
		loader.onreadystatechange = function()
		{
			if (loader.readyState == 4) 
			{
				if (loader.status == 200) 
				{
					document.getElementById('resultMaps').style.height = '350px';
					document.getElementById('resultMaps').style.display = 'block';
					document.getElementById('external_script').src = base + '/index/get-js/city/' + city;
				}
			}
		}
		
		loader.open("POST",path, true);
		loader.send(null);	
		document.getElementById('showMapLink').innerHTML = 'Karte ausblenden';
		appendToLink('on');
	} else
	{
		document.getElementById('resultMaps').style.display = 'none';
		document.getElementById('showMapLink').innerHTML = 'Ergebnisse in der Karte anzeigen &raquo;';
		appendToLink('off');
	}
}

function appendToLink (onoff)
{
	if (onoff == 'on')
	{
		var links = document.getElementsByTagName('a');
		for (var i = 0; i < links.length; i++)
		{
			links[i].href = links[i].href + '/map/1';
		}
		var pics = document.getElementsByTagName('img');
		for (var i = 0; i < pics.length; i++)
		{
			if (pics[i].className == 'marker')
			{
				pics[i].style.display = 'inline';
			}
		}
	} else
	{
		var links = document.getElementsByTagName('a');
		for (var i = 0; i < links.length; i++)
		{
			var laenge = links[i].href.length;
			laenge = laenge - 6;
			links[i].href = links[i].href.substr(0, laenge);
		}	
		var pics = document.getElementsByTagName('img');
		for (var i = 0; i < pics.length; i++)
		{
			if (pics[i].className == 'marker')
			{
				pics[i].style.display = 'none';
			}
		}
	}
}


function saveNewRatingText (id)
{
	var text = $('#ratingTextEdit_' + id).html();
	
	var x = confirm("Änderungen speichern?");

	if (x == true)
	{
	$.ajax({
		   type: "POST",
		   url: base + '/request/change-rating-text/',
		   data: "ratingId=" + id + "&value=" + text
		 });
	}
}

var ratingTitleEdit = '';

function editRatingTitle (id)
{
	$('#ratingTitle_' + id + ' td b').attr('contenteditable', 'true').focus();
	$('#ratingTitleEdit_' + id).css('display', 'inline');
	$('#edit_' + id).css('display', 'none');
	ratingTitleEdit = $('#ratingTitle_' + id + ' td b').html();
}
function saveEditTitle (id, val)
{
	$.ajax({
		type: "POST",
		url: base + '/request/change-rating-title/',
		data: "ratingId=" + id + "&value=" + val
	});
	
	$('#ratingTitle_' + id + ' td b').attr('contenteditable', 'false').blur();
	$('#ratingTitleEdit_' + id).css('display', 'none');
	$('#edit_' + id).css('display', 'inline');
	ratingTitleEdit = '';
}
function switchLanguage (id, oldVal)
{
	var newVal = $('input[name=language]:checked').val();
	$.ajax({
		type: "POST",
		url: base + '/request/change-rating-language/',
		data: "ratingId=" + id + "&value=" + newVal
	});
	
	$('#lang_' + id + '_' + oldVal).attr('value', newVal);
	$('#lang_' + id + '_' + oldVal).attr('id', 'lang_' + id + '_' + newVal);
	
	var newImg = base + '/img/flags/';
	switch (newVal)
	{
		case '1':
			newImg += 'germany.gif';
			break;
		case '2':
			newImg += 'england.gif';
			break;
		case '3':
			newImg += 'spain.gif';
			break;
		case '4':
			newImg += 'italy.gif';
			break;
		case '5':
			newImg += 'poland.gif';
			break;
		default:
			newImg += 'germany.gif';
			break;
	}
	$('#lang_' + id + '_' + newVal).prev().prev().attr('src', newImg);
	$('#switchLanguageDiv').remove();
}

function abortEditTitle (id)
{
	$('#ratingTitle_' + id + ' td b').attr('contenteditable', 'false').html(ratingTitleEdit).blur();
	$('#ratingTitleEdit_' + id).css('display', 'none');
	$('#edit_' + id).css('display', 'inline');
	ratingTitleEdit = '';
}

function switchLanguageDiv (objekt)
{
	var language = objekt.next().val();
	var id = objekt.next().attr('id').split('_')[1];

	$('#switchLanguageDiv').remove();
	var newDiv = '<div id="switchLanguageDiv" ';
	newDiv += 'style="position: absolute; background: #FFFFFF; z-index: 100; padding-top: 14px; background: #FFFFFF url(/img/general/languageSelectionAdmin.gif) top left no-repeat; margin-left: -5px; margin-top: 5px;">';
	newDiv += '<table style="border: 2px solid #003C6E; border-top: 0; padding: 0 3px 3px 3px;"><tr>';
	newDiv += '<td colspan="5"><strong>Sprache</strong></td></tr><tr>';
	newDiv += '<td><label><input type="radio" value="1" name="language" ';
		if (language == 1)
		{
			newDiv += 'checked="checked" ';
		}
	newDiv += '/><img src="' + base + '/img/flags/germany.gif" alt="deutsch" /></label></td>';
	newDiv += '<td><label><input type="radio" value="2" name="language" ';
		if (language == 2)
		{
			newDiv += 'checked="checked" ';
		}
	newDiv += '/><img src="' + base + '/img/flags/england.gif" alt="english" /></label></td>';
	newDiv += '<td><label><input type="radio" value="3" name="language" ';
		if (language == 3)
		{
			newDiv += 'checked="checked" ';
		}
	newDiv += '/><img src="' + base + '/img/flags/spain.gif" alt="castellano" /></label></td>';
	newDiv += '<td><label><input type="radio" value="4" name="language"  ';
		if (language == 4)
		{
			newDiv += 'checked="checked" ';
		}
	newDiv += '/><img src="' + base + '/img/flags/italy.gif" alt="italiano" /></label></td>';
	newDiv += '<td><label><input type="radio" value="5" name="language" ';
		if (language == 5)
		{
			newDiv += 'checked="checked" ';
		}
	newDiv += '/><img src="' + base + '/img/flags/poland.gif" alt="polski" /></label></td>';
	newDiv += '</tr><tr>';
	newDiv += '<td align="right" colspan="5"><input type="button" value="speichern" onclick="switchLanguage(' + id + ',\'' + language + '\')" />';
	newDiv += '<input type="button" value="abbrechen" onclick="$(\'#switchLanguageDiv\').remove()" /></td>';
	newDiv += '</tr></table>';
	newDiv += '</div>';
	objekt.after(newDiv);
}

function resendActivationMail (objekt, userId)
{
	$(objekt).html('Email erneut versendet').css({'color': '#88CB3E', 'cursor': 'default'}).unbind('click');

	$.ajax({
		   type: "POST",
		   url: base + '/admin/resend-activation-mail/',
		   data: "userId=" + userId
		 });
}

function activateRating (id, status, facebook, notify)
{
	var notfify = notify || "1";
	$.ajax({
		type: "GET",
		url: base + '/admin/activate-rating/',
		data: "ratingId=" + id + "&status=" + status + "&facebook=" + facebook + "&notify=" + notify
		});
	$('#ratingTitle_' + id).fadeOut(500, function(){
		$('#ratingTitle_' + id).remove();
	});
	$('#ratingSeparator_' + id).fadeOut(500, function(){
		$('#ratingSeparator_' + id).remove();
	});
	$('#ratingText_' + id).fadeOut(500, function(){
		$('#ratingText_' + id).remove();
	});
	if ($('#translate_ratingText_' + id))
	{
		$('#translate_ratingText_' + id).fadeOut(500, function(){
			$('#translate_ratingText_' + id).remove();
		});
	}
}

function searchRatingById ()
{
	$.ajax({
		type: "GET",
		url: base + '/admin/search-rating/',
		data: "ratingId=" + $('#ratingId').val(),
		success: function(data) {
			$('#ratingSearchResult').html(data);
		}
	});
}

function searchLocationById ()
{
	$.ajax({
		type: "GET",
		url: base + '/admin/search-location/',
		data: "locationId=" + $('#locaId').val(),
		success: function(data) {
		$('#locationSearchResult').html(data);
	}
	});
}

function changeRatingCount (newCount, id)
{
	$('#newCountMessage').html('<img src="/img/tooltip/loader.gif" alt="Loading..." height="12" />');
	$.ajax({
		type: "GET",
		url: base + '/admin/change-rating-count/',
		data: "locationId=" + id + '&count=' + newCount,
		success: function(data) {
			$('#newCountMessage').html('Anzahl erfolgreich geändert!');
			$('#realCountWarning').remove();
			$('#newRatingCount').css({'borderColor': '#DDDDDD'});
		}
	});
}

function deleteAllUsers ()
{
	var x = confirm("ACHTUNG! Wirklich alle nicht freigeschalteten User löschen?");

	if (x == true)
	{
		$.ajax({
			   type: "POST",
			   url: base + '/admin/delete-inactive-users/',
			   error: function (){
					alert('Fehler');
				},
				success: function(msg){
					$('table.activate').fadeOut(500, function(){
						$('table.activate').remove();
					});
					$('#masterAdminContainer-content > div').html('Keine offenen User!');
				}
		 });
	}
}

function saveDataToLocalStorage (dataKey, dataValue)
{
	if (typeof(localStorage) != 'undefined' )
	{
		try
		{
			localStorage.setItem(dataKey, dataValue);
		} catch (e)
		{
			if (e == QUOTA_EXCEEDED_ERR)
			{
				alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
			}
		}
	}
}

function eraseLocalStorageDate (locId)
{
	if (typeof(localStorage) != 'undefined')
	{
		for (i=localStorage.length-1; i>=0; i--)
		{
			if (localStorage.key(i).split('|')[0] == locId || localStorage.key(i).split('|')[0] == parseInt(locId))
			{
				localStorage.removeItem(localStorage.key(i));
			}
		}
	}
}

function showHideRatings (type)
{
	switch (type)
	{
		case 'all':
			$('.ratingTr').css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr').next().css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr').next().next().css({'visibility': 'visible', 'position': 'static'});
			break;
		case 'customer':
			$('.ratingTr.customer').css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr.customer').next().css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr.customer').next().next().css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr:not(.customer)').css({'visibility': 'hidden', 'position': 'absolute'});
			$('.ratingTr:not(.customer)').next().css({'visibility': 'hidden', 'position': 'absolute'});
			$('.ratingTr:not(.customer)').next().next().css({'visibility': 'hidden', 'position': 'absolute'});
			break;
		case 'expert':
			$('.ratingTr.expert').css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr.expert').next().css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr.expert').next().next().css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr:not(.expert)').css({'visibility': 'hidden', 'position': 'absolute'});
			$('.ratingTr:not(.expert)').next().css({'visibility': 'hidden', 'position': 'absolute'});
			$('.ratingTr:not(.expert)').next().next().css({'visibility': 'hidden', 'position': 'absolute'});
			break;
		case 'german':
			$('.ratingTr.german').css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr.german').next().css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr.german').next().next().css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr:not(.german)').css({'visibility': 'hidden', 'position': 'absolute'});
			$('.ratingTr:not(.german)').next().css({'visibility': 'hidden', 'position': 'absolute'});
			$('.ratingTr:not(.german)').next().next().css({'visibility': 'hidden', 'position': 'absolute'});
			break;
		case 'spanish':
			$('.ratingTr.spanish').css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr.spanish').next().css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr.spanish').next().next().css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr:not(.spanish)').css({'visibility': 'hidden', 'position': 'absolute'});
			$('.ratingTr:not(.spanish)').next().css({'visibility': 'hidden', 'position': 'absolute'});
			$('.ratingTr:not(.spanish)').next().next().css({'visibility': 'hidden', 'position': 'absolute'});
			break;
		default:
			$('.ratingTr').css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr').next().css({'visibility': 'visible', 'position': 'static'});
			$('.ratingTr').next().next().css({'visibility': 'visible', 'position': 'static'});
			break;
	}
}

function FBPublish(ratingId)
{
	var x = confirm("Bewertung auf Ihrem Facebook Account veröffentlichen?");

	if (x == true)
	{
		$.ajax({
			   type: "POST",
			   url: base + '/facebook/publish-to-wall/ratingId/' + ratingId,
			   data: 'additional=' + $('#fbText_' + ratingId).val() + '&page=' + $('#fbText_' + ratingId).parent().children('select').val(),
			   error: function (){
					alert('Fehler');
				},
				success: function(msg){
					$('#fbAdditional_' + ratingId).hide();
					$('#fbLink_' + ratingId).html('Erfolgreich gepostet!').attr('onclick', 'return false;').attr('href', '#').css({'text-decoration':'none', 'cursor':'default'});
				}
		 });
	}
}


$(document).ready(function() {
	window.setTimeout("showTransparentSearch()", 5000);
	$('.languageSelectionImg').each(function(){
		$(this).click(function(){
			switchLanguageDiv($(this));
		})
	})
	$('#newPictureLocationId').next().click(function(){
		var abbrechenButton = $('<input>', {
			'type' : 'button',
			'value':'Abbrechen',
			'click': function() {
				$('#newPreviewPicContainer').html('');
				$('#newPictureLocationId').val('');
			}
		});
		var saveButton = $('<input />', {
			'type': 'button',
			'value': 'Speichern',
			'click': function (){
					if ($('.current').attr('title') != $('#newImgId').val() && $('#newImgId').val() != '')
					{
						$.post(base + '/admin/set-new-preview/locationId/' + $('#locId').val() + '/multiId/' + $('#newImgId').val(), function(){
							$('#newPreviewPicContainer').html('');
							$('#newPictureLocationId').val('');
						})
					}
				}
			});
		
		var locId = $('<input type="hidden" value="' + $('#newPictureLocationId').val() + '" id="locId" />');
		var newImgId = $('<input type="hidden" value="" id="newImgId" />');
		
		$.ajax({
			type: 'POST',
			url: base + '/request/get-all-images/id/' + $('#newPictureLocationId').val(),
			dataType: 'json',
			success: function (req)
			{
				$('#newPreviewPicContainer').html('');
				var container = $('<div></div>');
				$.each(req, function(i, elem){
					var img = $('<img />', 
							{
								'height'	: '55',
								'width'		: '80',
								'class'		: 'newPreviewImage',
								'src'		: base + '/img/general/blank.gif',
								'title'		: elem.id,
								'css'		: {
									'background':'url(http://media.sr-vice.de/index/thumb/id/' + elem.id + '/size/80x55/' + elem.id + '.jpg) no-repeat center center'
								},
								'click'		: function()
								{
									$('.newPreviewImage').removeClass('active');
									$('#newImgId').val($(this).attr('title'));
									$(this).addClass('active');
								}
							}),
							div = $('<div style="margin: 2px;border: 1px solid #CCCCCC; float:left;"></div>');
					if (elem.id == '-1')
					{
						img.css('background', 'none').attr('src', base + '/img/general/noPicture.jpg');
					}
					if (elem.preview == 1)
					{
						img.addClass('active').addClass('current');
					}
					if (elem.preview == 2)
					{
						img.addClass('default');
					}
					if (elem.preview == 3)
					{
						img.addClass('active').addClass('default').addClass('current');
					}
					
					
					div.append(img);
					container.append(div);
				})
				var legendDefault = $('<div style="float:left;  margin-right: 7px;"><div style="background: #FFFFFF; width: 12px; border: 2px solid #FFE351; float: left;margin-right:3px;">&nbsp;</div> Defaultbild</div>'),
					legendCurrent = $('<div style="float:left;"><div style="background: #FFFFFF; width: 12px; border: 2px solid #003c6e; float: left;margin-right:3px;">&nbsp;</div> Aktuelles Bild</div>');
				$('#newPreviewPicContainer').append(container).append(locId).append(newImgId).append('<div class="cleardiv"></div>').append(legendDefault).append(legendCurrent).append(abbrechenButton).append(saveButton).append('<div class="cleardiv"></div>');
			}
		})
	})
	$('.markRating').click(function(){
		$.ajax({
			type: 'GET',
			url: $(this).attr('href'),
			success: function (req)
			{
				$('.markRating').parent().parent().html(req);
			}
		})
		return false;
	})
	$('#starsMinus').click(function(){
		if (parseInt($('#starsValue').val()) > 0)
		{
			$('#starsValue').val(parseInt($('#starsValue').val())-1);
			var starsImg = parseInt($('#starsValue').val()) * 10;
			$('#minStars').css('backgroundImage', 'url(' + base + '/img/stars/stars_' + starsImg + '.jpg)')
						.html('min. ' + $('#starsValue').val());
			if (parseInt($('#starsValue').val()) == 0)
			{
				$('#minStars').html('beliebig');
			}
		}
	})
	$('#starsPlus').click(function(){
		if (parseInt($('#starsValue').val()) < 5)
		{
			$('#starsValue').val(parseInt($('#starsValue').val())+1);
			var starsImg = parseInt($('#starsValue').val()) * 10;
			$('#minStars').css('backgroundImage', 'url(' + base + '/img/stars/stars_' + starsImg + '.jpg)')
						.html('min. ' + $('#starsValue').val());
		}
	})
});
