$( function()
{
	
	  //===========================
  // Cookie plugin
  //===========================
  /**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

	// ===========================================
	// Navigation-Border
	// ===========================================
	var navigationBorder = function()
	{
		$( 'div#navigation' ).each( function()
		{
			$( this ).height( $( '#content' ).height() > ( $( window ).height() ) ? $( '#content' ).height() :  $( window ).height() - $( this ).position().top );
		} );
	};
	navigationBorder();
	$( window ).resize( navigationBorder );
	
	// ===========================================
	// Bilder im Verkauf
	// ===========================================
	$( '#image-sale input[type="radio"]' ).click( function()
	{
		$( this ).parents( 'p' ).find( '#do_search' ).click();
	} );
	
	// ===========================================
	// Bilder Upload
	// ===========================================
	
	
	var maxFileInputs = 3;
	var fileCount = 1;
	$( 'img.add' ).click(function(){
		fileCount = $('#file-group div').length; 
		action = $(this).attr('class')
		if ( action == 'add'){
		  if(fileCount < maxFileInputs ){
		    currentFileName = 'user_image_'+(fileCount-1);
			delImage = new Image();
			delImage.src = '/images/icons/close.gif';
	        mainDivObj = $('#div_user_image_0')
			divObj = $('#div_'+currentFileName)
			newDivObj = mainDivObj.clone().insertAfter( divObj ).attr( 'id', 'div_user_image_' + fileCount );	
			input = $('#div_user_image_' + fileCount+' input').attr( 'name', 'user_image_' + fileCount ).attr('value','');
			addImage = $('#div_user_image_' + fileCount+' img')
			$.event.copy( $(this), addImage );
			deleteImage = $(this).clone().insertAfter(addImage).attr( 'src', delImage.src ).attr('class','delete');
			$.event.copy( $(this), deleteImage );
			}
		}else{
			//=== Delete object
			$(this).parent().remove()
			$total = $('#file-group div').length; 
			start = 0
			$('#file-group div').each(function(){
			   $(this).attr('id','div_user_image_'+start)
			   input = $(this).find('input').attr('name','user_image_'+start)
			   start++
			})
		}
	});
	
	
	
	
	// ===========================================
	// Accordion
	// ===========================================
	
	

	
	
	if ( typeof activePanel === 'undefined' )
	{
		activePanel = 0;
	}
	$( '.accordion' ).accordion( { 
		collapsible: true,
		autoHeight: false,
		alwaysOpen: false,
		icons: {
			header: 'ui-icon-header-closed',
			headerSelected: 'ui-icon-header-open'
		},
		active: activePanel
	} ).bind( 'accordionchange', function( event, ui )
	{
		$.scrollTo( 0, { duration: 500 } );
	} );
	$('.accordion-all h3 a').before('<span id="span_id" class="ui-icon ui-icon-header-closed"/>');
	$('.accordion-all h3').each(function(){
			if($.cookie('setting_menustate_'+$(this).attr('id'))) {	
			    $(this).next().show();
				$(this).children('span').removeClass().addClass('ui-icon ui-icon-header-open');
		        $(this).removeClass().addClass('ui-accordion-header ui-helper-reset ui-state-active ui-corner-top ui-state-focus');
			}else{
				$(this).next().hide();
			}
			$(this).next().removeClass().addClass('ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active');
	});
	$('.accordion-all h3').removeClass().addClass('ui-accordion-header ui-helper-reset ui-state-default ui-corner-all').click(function() {
			$(this).next().toggle(0,function(){
				if($(this).css('display') == 'block'){
					$.cookie('setting_menustate_'+$(this).prev().attr('id'),'1',{ expires: 2 });
					$(this).prev().children('span').removeClass().addClass('ui-icon ui-icon-header-open')
					$(this).prev().removeClass().addClass('ui-accordion-header ui-helper-reset ui-state-active ui-corner-top ui-state-focus');
				}else{
					$.cookie('setting_menustate_'+$(this).prev().attr('id'),null);
					$(this).prev().children('span').removeClass().addClass('ui-icon ui-icon-header-closed')
					$(this).prev().removeClass().addClass('ui-accordion-header ui-helper-reset ui-state-default ui-corner-all');
				}								  
		});
		
		return false;
	 });
    
	 
 


	// ===========================================
	// Kontotypen innerhalb des Accordions
	// ===========================================
/*	if(!$.cookie('setting_radio')){
	  var first_radio = $( '.accordion-all input:radio.toggle:first' )
	  first_radio.attr('checked','checked').parents( 'p' ).nextAll( 'div#' + first_radio.attr( 'value' ) ).show();
	}
*/	
	$( '.accordion-all input:checked.toggle' ).each( function()
	{
		$( this ).parents( 'p' ).nextAll( 'div#' + $( this ).attr( 'value' ) ).show();
	} );
	
	$( '.accordion-all input:radio.toggle' ).click( function()
	{
		$( this ).parents( 'p' ).nextAll( 'div' ).hide();
		$( this ).parents( 'p' ).nextAll( 'div#' + $( this ).attr( 'value' ) ).show();
		//$.cookie('setting_radio',$(this).attr('value'),{ expires: 2 });
	} );
	// bind keyup event with account owner
	$( '#outside_eu p:first input, #inside_eu p:first input, #default p:first input').blur(function(e){
		$( '.accordion-all #inside_eu p:first input').attr('value',$(this).attr('value'))	
		$( '.accordion-all #outside_eu p:first input').attr('value',$(this).attr('value'))	
		$( '.accordion-all #default p:first input').attr('value',$(this).attr('value'))													 
	});
	
	// bind event with bank name
	$( '#outside_eu p:eq(1) input, #inside_eu p:eq(1) input, #default p:eq(1) input').blur(function(e){
		$( '.accordion-all #inside_eu p:eq(1) input').attr('value',$(this).attr('value'))	
		$( '.accordion-all #outside_eu p:eq(1) input').attr('value',$(this).attr('value'))	
		$( '.accordion-all #default p:eq(1) input').attr('value',$(this).attr('value'))													 
	});
	// for iban
	$( '#inside_eu p:eq(2) input, #outside_eu p:eq(2) input').blur(function(e){
		$( '.accordion-all #inside_eu p:eq(2) input').attr('value',$(this).attr('value'))	
		$( '.accordion-all #outside_eu p:eq(2) input').attr('value',$(this).attr('value'))	
	});
	// for BIC
	$( '#inside_eu p:eq(3) input, #outside_eu p:eq(3) input').blur(function(e){
		$( '.accordion-all #inside_eu p:eq(3) input').attr('value',$(this).attr('value'))	
		$( '.accordion-all #outside_eu p:eq(3) input').attr('value',$(this).attr('value'))	
	});

	// ===========================================
	// Fotos löschen
	// ===========================================
	$( 'div.rejected a.reject, div.deletable a.a-delete' ).click( function()
	{
		if ( confirm( 'Wollen Sie dieses Bild wirklich löschen?' ) )
		{
			var that = this;
			$.post( $( this ).attr( "href" ), { "delete": "true"}, function(str)
			{
				if ( str === 'success' )
				{
					$( 'span.count' ).text( parseInt( $( 'span.count' ).text() ) - 1 );
					$( that ).parents( 'div.rejected, div.deletable' ).fadeOut( 'normal', function()
					{
						$( this ).remove();
					});
				}
				else
				{
					alert( 'Es gab ein Problem beim Löschen des Fotos. Sollte das Problem bestehen bleiben wenden Sie sich bitte an Shotshop.' );
				}
			} );
		}
		return false;
	} );
	
	// ===========================================
	// MR/PR Upload
	// ===========================================
	$( window ).ajaxSuccess( function( evt, request, settings )
	{
		$( this ).everyTime( 300, 'releaseTimer', function() {
			if ( $( '#release-form' ).length > 0 )
			{
				$( '#release-form' ).validate( {
					errorContainer: $( '#release-form-errors' ),
					errorPlacement: function() {}
				} );
				$( this ).stopTime( 'releaseTimer' );
			}
		}, 20 );
	} );
	
	// ===========================================
	// Checkboxen & Umsatzanteile
	// ===========================================
	$( 'input[type="checkbox"].bg' ).checkbox( { empty: '/images/ui/empty.png' } ).click( function()
	{
		// Abhängigkeiten der Checkboxen auflösen (.checkbox kehrt is( ':checked' ) ins unlogische um)
		
		if ( $( this ).attr( 'name' ) === 'exklusiv' && !$( this ).is( ':checked' ) )
		{
			$( 'input[name="non_micro"]' ).click();
			$( 'input[name="non_micro"]' ).attr( 'checked', 'checked' );
			$( 'input[name="non_abo"]' ).attr( 'checked', 'checked' );
		}
		
		if ( $( this ).attr( 'name' ) === 'non_micro' && !$( this ).is( ':checked' ) )
		{
			$( 'input[name="non_abo"]' ).click();
			$( 'input[name="non_abo"]' ).attr( 'checked', 'checked' );
		}
		else if ( $( this ).attr( 'name') === 'non_micro' && $( this ).is( ':checked' ) )
		{
			if ( $( 'input[name="exklusiv"]' ).is( ':checked' ) )
			{
				$( 'input[name="exklusiv"]' ).attr( 'checked', false );
			}
		}
		
		if ( $( this ).attr( 'name' ) === 'non_abo' && $( this ).is( ':checked' ) )
		{
			if ( $( 'input[name="non_micro"]' ).is( ':checked' ) )
			{
				$( 'input[name="non_micro"]' ).attr( 'checked', false );
			}
			if ( $( 'input[name="exklusiv"]' ).is( ':checked' ) )
			{
				$( 'input[name="exklusiv"]' ).attr( 'checked', false );
			}
		}
	} );
	
	$( 'td.percentage.bonus' ).each( function()
	{
		if ( $( this ).text().replace( '\%', '' ).replace( /\+/, '' ) !== '0' )
		{
			$( this ).removeClass( 'inactive' );
		}
	} );
	
	$( 'div.percentage form' ).submit( function()
	{
		var that = this;
		$.post( $( this ).attr( 'action' ), {
			'non_abo': $( 'input[name="non_abo"]' ).is( ':checked' ),
			'non_micro': $( 'input[name="non_micro"]' ).is( ':checked' ),
			'exklusiv': $( 'input[name="exklusiv"]' ).is( ':checked' )
		}, function( str )
		{
			if ( str === 'success' )
			{
				$( 'input[type="submit"]', that ).val( 'In Prüfung' ).attr( 'disabled', true ).addClass( 'disabled' );
			}
			else
			{
				alert( 'FATAL: Probleme beim Versand der Anfrage' );
			}
		} );
		
		return false;
	} );
	
	if ( $( 'input[type="checkbox"].bg' ).length > 0 )
	{
		$( this ).everyTime( 300, 'checkboxTimer', function() {
			var total = 0;
			$( 'td.percentage' ).each( function()
			{
				var that = this;
				$.each( $( this ).attr( 'class' ).split( ' ' ), function()
				{
					if ( $( 'input[name="'+this+'"]' ).length > 0 )
					{
						if ( $( 'input[name="'+this+'"]' ).is( ':checked' ) && $( that ).hasClass( 'inactive' ) )
						{
							$( that ).toggleClass( 'inactive' );
						}
						else if ( !$( 'input[name="'+this+'"]' ).is( ':checked' ) && !$( that ).hasClass( 'inactive' ) )
						{
							$( that ).toggleClass( 'inactive' );
						}
					}
				} );
				// Gesamtsumme
				if ( !$( this ).hasClass( 'last' ) && !$( this ).hasClass( 'inactive' ) )
				{
					total += parseInt( $( this ).text().replace( /\%/, '' ).replace( /\+/, '' ), 0 );
				}
			} );
			$( 'td.percentage.last' ).text( total + '%' );
			
			var checkedCount = 0;
			$( 'input[type="checkbox"]:checked' ).each( function()
			{
				checkedCount++;
			} );
			if( checkedCount > 0 && $( 'form:visible' ).length === 0 )
			{
				$( 'form' ).show();
			}
			else if ( checkedCount === 0 )
			{
				$( 'form' ).hide();
			}
		}, 0 );
	}
	
	// ===========================================
	// Tabs
	// ===========================================
	// Ersten Tab aktiv setzen
	$( 'div.tabbed div.tab' ).hide();
	$( 'div.t1' ).hide();
	
	$( 'div.tabbed div.tab' ).hide();
	$( 'div.tabbed .t1').show();
	$( 'div.category-t1' ).hide();
	//$( 'li.category-t1 .wrapper' ).addClass( 'active' );
	
	$( 'div.tabbed ul.tabs li input[type="radio"]' ).click( function()
	{
		$( this ).parents( 'ul.tabs' ).eq( 0 ).find( '.wrapper' ).removeClass( 'active' );
		$( 'div.tabbed div.tab' ).not( 'div.' + $( this ).attr( 'class' ) ).hide();
		$( 'div.' + $( this ).attr( 'class' ) ).show();
		$( this ).parent().addClass( 'active' );
	} );
	
	$( 'div.tabbed input.sub-cat,div.smartmeta a.sub-cat' ).click( function()
	{
		$( 'div.sub-cat' ).not( 'div.' + $( this ).attr( 'id' ) ).hide();
		$( 'div.' + $( this ).attr( 'id' ) ).show();
		if ( $( this ).attr( 'href' ) )
		{
            if ( $('div.' + $( this ).attr( 'id' ) ).css( 'display' ) === 'block' )
            {
                $('div.' + $( this ).attr( 'id' ) ).hide();
            };
		    return false;
		};
	} );
	
	// Releases in Smartmeta zuweisen
	
	$( '.toggle_release a' ).click( function()
	{
		switch( $( this ).attr( 'href' ) )
		{
			case 'mr_female':
				$('.toggle_release').find('a').each(function(){ 
															 if ( $(this).hasClass("active") )
															 { $(this).removeClass('active').addClass('inactive');}
															 });
				//$($(this).parent()+' a').removeAttr('class');
				$(this).attr('class', 'active');
				makeReleaseOptions( 'mr', 'Frau' );
			break;
			case 'mr_male':
				$('.toggle_release').find('a').each(function(){ 
															 if ( $(this).hasClass("active") )
															 { $(this).removeClass('active').addClass('inactive');}
															 });
				$(this).attr('class', 'active');
				makeReleaseOptions( 'mr', 'Mann' );
			break;
			case 'pr':
				$('.toggle_release').find('a').each(function(){ 
															 if ( $(this).hasClass("active") )
															 { $(this).removeClass('active').addClass('inactive');}
															 });
				$(this).attr('class', 'active');
				makeReleaseOptions( 'pr' );
			break;
		}
		
		return false;
	} );
	
	$( '.add_remove a' ).click( function()
	{
		if ( $( this ).attr( 'href' ) === 'add' )
		{
			var select = $( 'select#releases' )[0];
			$( 'select[name="release_list"] option:selected' ).each( function()
			{
				if( $( 'select#releases' ).containsOption($(this).val()) == false)
				{
					//If empty is already present and model release is tried to be added do nothing...
					if($(this).val() == 'no_mr')
					{
						//remove all modal releases
						$('select#releases').removeOption(/^mr_/i); 
					}
					else if($(this).val() != 'no_mr' && $(this).val().search(/mr_/i) != -1) //and must be model release
					{
						$('select#releases').removeOption('no_mr'); 
					}
					
					/* Added by Aqeel, 10-02-10 */
					if($(this).val() == 'no_pr')
					{
						//remove all modal releases
						$('select#releases').removeOption(/^pr_/i); 
					}
					else if($(this).val() != 'no_pr' && $(this).val().search(/pr_/i) != -1) //and must be model release
					{
						$('select#releases').removeOption('no_pr'); 
					}
					
					
					var option = new Option( $( this ).text(), $( this ).val() );
					option.selected = true;
					if ( $.browser.msie )
					{
						select.add( option );
					} else {
						select.add( option, null );
					}
				} 
			} );
		} else {
			$( 'select#releases option:selected' ).remove();
		}
		return false;
	} );
	var smart_releases = '';
	//$(document).ready(function(){
		
		if ( typeof userid !== 'undefined' )
		{
			$.getJSON( '/image/releases/id/' + userid, function( data )
			{
				smart_releases = data;
				
				makeReleaseOptions( 'mr', 'Frau' );
				
			} );
		}
		
//   });
	
		function makeReleaseOptions ( type, gender )
		{
			var select = $( 'select[name="release_list"]' )[0];
			var got_releases = 0;
			
			$( select ).find( 'option' ).remove();
			//alert(smart_releases);
			var flag1 = true;
			var flag2 = true;
			var flag3 = true;
			if(smart_releases.length > 0)
			{
				$( smart_releases ).each( function()
				//smart_releases.each( function()
				{
					got_releases = 1;
					//alert('here');
					//console.log( this );
					// Wenn vorhanden den ersten Satz (MR weiblich) setzen
					if ( ( type === 'mr' && this.type === type ) && ( typeof gender !== 'undefined' && this.description.gender === gender ) )
					{
						var option;
						
						if(flag1 && $( 'select[name="release_list"]' ).containsOption('no_mr') == false)
						{
							option = new Option( 'MR wird nicht benötigt', 'no_mr' );
							if ( $.browser.msie )
							{
								select.add( option );
							} else {
								select.add( option, null );
							}	
							flag1 = false;
						}
						option = new Option( this.description.firstname + ' ' + this.description.surname, 'mr_'+this.releaseID );
						if ( $.browser.msie )
						{
							select.add( option );
						} else {
							select.add( option, null );
						}
					} else if ( type === 'pr' && this.type === type )
					{
						if(flag2 && $( 'select[name="release_list"]' ).containsOption('no_pr') == false)
						{
							option = new Option( 'PR wird nicht benötigt', 'no_pr' );
							if ( $.browser.msie )
							{
								select.add( option );
							} else {
								select.add( option, null );
							}	

							flag2 = false;
						}
						var option = new Option( this.description.object_name, 'pr_'+this.releaseID );
						if ( $.browser.msie )
						{
							select.add( option );
						} else {
							select.add( option, null );
						}
					}
					
					/* Commented by Aqeel */
					else
					{
						//	alert('here no release');
						if(flag3)
						{
							// No release is found
							var insert = true;
							if (type === 'mr' && gender === 'Frau')
							{
								if($( 'select[name="release_list"]' ).containsOption('no_mr') == false)
								{
									option = new Option( 'MR wird nicht benötigt', 'no_mr' );		
								}
								else
								{
									insert = false;
								}
							}
							else if (type === 'mr' && gender === 'Mann')
							{
								if($( 'select[name="release_list"]' ).containsOption('no_mr') == false)
								{
									option = new Option( 'MR wird nicht benötigt', 'no_mr' );		
								}
								else
								{
									insert = false;
								}
							}
							else if (type === 'pr')
							{
								if($( 'select[name="release_list"]' ).containsOption('no_pr') == false)
								{
									option = new Option( 'PR wird nicht benötigt', 'no_pr' );
								}
								else
								{
									insert = false;
								}		
							}
							
							if(insert)
							{
								if ( $.browser.msie )
								{
									select.add( option );
								} 
								else
								{
									select.add( option, null );
								}	
							}
							flag3 = false;
						}
							
					}
				} );
			}
			
			// Add default values to release list, if no release is found 
			if (got_releases == 0)
			{
				/*if (type === 'mr')
				{
					option = new Option( 'MR wird nicht benötigt', 'no_mr' );		
				}
				else if (type === 'pr')
				{
					option = new Option( 'PR wird nicht benötigt', 'no_pr' );		
				}
	
				if ( $.browser.msie )
				{
					select.add( option );
				} 
				else
				{
					select.add( option, null );
				}	*/
				var insert2 = true;
				if (type === 'mr')
				{
					if($( 'select[name="release_list"]' ).containsOption('no_mr') == false)
					{
						option = new Option( 'MR wird nicht benötigt', 'no_mr' );		
					}
					else
					{
						insert2 = false;
					}
				}
				else if (type === 'pr')
				{
					if($( 'select[name="release_list"]' ).containsOption('no_pr') == false)
					{
						option = new Option( 'PR wird nicht benötigt', 'no_pr' );
					}
					else
					{
						insert2 = false;
					}		
				}
				
				if(insert2)
				{
					if ( $.browser.msie )
					{
						select.add( option );
					} 
					else
					{
						select.add( option, null );
					}	
				}
	
			}
		}
	
	// ===========================================
	// MR/PR zuweisen
	// ===========================================
	//$( 'div.reedit div.tabbed li.t1 a' ).attr( 'class', 'active' );
	//$( 'div.reedit div.tabbed div.category-t1' ).show(); //added by Aqeel, to display first textbox selection by default
	//Commented out -- 21-01-10
	try{
		//selected_reedit might be undefined
		if(typeof selected_reedit !== 'undefined')
		{
			//$( 'div.reedit div.tabbed li.'+selected_reedit+' a' ).attr( 'class', 'active' );
			if($( 'div.reedit div.tabbed li.'+selected_reedit+' a' ).hasClass( 'inactive'))
			{
				$( 'div.reedit div.tabbed li.'+selected_reedit+' a' ).removeClass('inactive');
			}
			$( 'div.reedit div.tabbed li.'+selected_reedit+' a' ).addClass( 'active' );
			$( 'div.reedit div.tabbed div.category-'+selected_reedit ).show();
		}
	}catch(e)
	{
		//do nothing..
	}
	$( 'div.reedit div.tabbed li a' ).click( function( e )
	{
	    e.preventDefault();
	    $( 'div.reedit div.tabbed li a' ).removeClass( 'active' ).addClass('inactive');
		$( 'div.tabbed div.tab' ).not( 'div.' + $( this ).attr( 'href' ) ).hide();
		$( 'div.' + $( this ).attr( 'href' ) ).show();
		//$( this ).attr( 'class', 'active' );
		if($(this).hasClass('inactive'))
		{
			$(this).removeClass( 'inactive' );
		}
		$( this ).addClass( 'active' );
	} );
	
	$( '#edit-releases div.item' ).click( function()
	{
	    self.location.href = '/release/reedit/display/' + $( this ).attr( 'class' ).split( ' ' ).pop();
	} );
	//Added by Aqeel
	//change()
	$( 'select[name="mr_female"]').click( 
		function() {
				var value=parseInt($(this).val());
				if(value != 'NaN' && value > 0)
				{
					if($(".release-arrow").is(':hidden'))
					{
							$(".release-arrow").show();
					}
					
					$(".release_detail_info").hide();
					$("#release-link").attr('href','/release/reedit/release/'+value);
					$("#release_info_"+value).show();
				}
				else
				{	
					if(!$(".release-arrow").is(':hidden'))
					{
							$(".release_detail_info").hide();
							$(".release-arrow").hide();		
							$("#release-link").attr('href', '#');
					}	
				}
			}
		);
	$( '#save-releases' ).submit( function()
	{
	    var releases = '';
	    var images = '';
	    $( 'div.tab' ).each( function()
	    {
	       if ( $( this ).css( 'display' ) === 'block' )
	       {
               $( this ).children( 'select' ).children( 'option:selected' ).each( function()
               {
                    releases += $( this ).val() + '###';
               } );
	           return;
	       };
	    });
	    $( '.edit-list-item input:checked' ).each( function()
	    {
	       images += $( this ).val() + '###';
	    });
	
	    $( 'input[name="releases"]' ).val( releases );
	    $( 'input[name="images"]' ).val( images );
	    
	    $( this ).submit();
	    
	    return false;
	} );
	
	// ===========================================
	// Bilder löschen
	// ===========================================
	$( '.deletable' ).hover( function() {
		$( this ).find( 'img.delete' ).show();
	}, function() {
		$( this ).find( 'img.delete' ).hide();
	} );
	
	// ===========================================
	// Schlagworte entfernen
	// ===========================================
	$( '.image-detail .keyword-list span' ).live( 'click', function() {
		if ( $( this ).css( 'text-decoration' ) !== 'line-through' ) {
			$( this ).css( 'text-decoration', 'line-through' );
			var old = $( 'input[name="old"]' ).val().split( "," );
			old.push( $( this ).text() );
			if($('#button_waiting_keywords')){
				 $('#button_waiting_keywords').show(); 	
			}
		} else {
			$( this ).css( 'text-decoration', 'none' );
			var that = $( this );
			var old = $( 'input[name="old"]' ).val().split( "," );
			old = $.grep( old, function( n, i ) {
				return n !== that.text();
			} );
			if($('#button_waiting_keywords')){
				if(old.length <= 1){
					
					if($('#div_keywords') && $('#div_keywords #text_keywords').attr('value') == '' ){
						if($('#a_andern')){
							$('#a_andern').show();
						}
						$('#div_keywords').hide();
						$('#button_waiting_keywords').hide();
					}
				  	
				}
			}
		}
		$( 'input[name="old"]' ).val( old.join( "," ) )
	});
	$('#button_waiting_keywords').live('click',function(){
		
		//if($( '#text_keywords' ).val() != '' || '#delkeywords' ).val() != ''){
		
		$('#button_waiting_keywords').hide();												 
		$.post($( '#form_change_keywords').attr( 'action' ), {
			'keywords': $( '#text_keywords' ).attr('value'),
			'delkeywords': $( '#delkeywords' ).attr('value')
		}, function( str )
		{
			if(str == 'failed'){
				alert( 'Bitte geben Sie Ihre neuen Keywords in das Textfeld ein.' );
				$('#button_waiting_keywords').show();			
			}else if(str == 'redirect_correct_images'){
				document.location = '/image/correct/';
			}
			else
			{
				
				$('div.keyword-list').html('<h2>Schlagworte</h2>'+str);
				$('#div_keywords').hide();
				$('#button_waiting_keywords').hide();
				$('#a_andern').show();
				$('input[name="old"]' ).val('');
				$('#text_keywords').val('');
				$('#delkeywords').val('');
				
			}
			
		} );
	 //  }
		return false;
	 });
	// ===========================================
	// Body Resize
	// ===========================================
	
	var	bodyResize = function()
	{
		//$( 'body' ).width( $( 'div#navigation' ).width() + $( 'div#content' ).width() );
	}
	bodyResize();
	$( window ).resize( bodyResize );

	//========================================
	// Copy events from one element to another
	//========================================
	$.event.copy = function(from, to) {
		var events = $.data(from[0], 'events');
		if ( !from.size() || !events || !to.size() ) return;
	
		to.each(function() {
			for (var type in events)
				for (var handler in events[type])
					$.event.add(this, type, events[type][handler], events[type][handler].data);
		});
	};


} );

	function remove_image_detail(image_id, sec)
	{
		if (confirm('Wollen Sie dieses Bild wirklich löschen?'))
		{
				document.location = '/image/'+sec+'/del/'+image_id;
		}
	}
	$("#further-styles").click(	function(){
			$("#further-styles-div").slideToggle('slow');
		}
	);
	
	$( '.keyword-select a' ).click( function()
			{
		if ( $( this ).attr( 'href' ) === 'all' )
		{
			$( '.iptc_keywords input:checkbox' ).attr( 'checked', true );
		}
		else if ( $( this ).attr( 'href' ) === 'none' )
		{
			$( '.iptc_keywords input:checkbox' ).attr( 'checked', false );
		}
		else if ( $( this ).attr( 'href' ) === 'invert' )
		{
			$( '.iptc_keywords input:checkbox' ).each( function()
					{
				this.checked = !this.checked;
					} );
		};
		return false;
	} );
	
	$( '.edit-item-select a' ).click( function()
			{
		if ( $( this ).attr( 'href' ) === 'all' ) {
			$( '.edit-list-item-cb' ).attr( 'checked', true );
		}
		else if ( $( this ).attr( 'href' ) === 'none' ) {
			$( '.edit-list-item-cb' ).attr( 'checked', false );
		}
		else if ( $( this ).attr( 'href' ) === 'invert' ) {
			$( '.edit-list-item-cb' ).each( function()
					{
				this.checked = !this.checked;
					} );
		};
		
		return false;
	} );
	
	//Add Meta Form
	$("#frm_addmeta").submit(
		 function()
				  {
					  //select all releases
					  $('select#releases').selectOptions(/./);

					  if($('input[name=copyright]').is(":checked") == false)
					  {
						  alert('Bitte stellen Sie sicher, dass Sie in Besitz aller Rechte am Bild sind. Ansonsten verzichten Sie auf das Hochladen des Bildes');
						 return false;
					  }
					  if($('input[name=category]').is(":checked") == false)
					  {
						  alert('Bitte bestimmen Sie eine Bildkategorie.');
						 return false;
					  }
					  else
					  {
						flag_submit = false;
						// check for maximum number of keywords
						var radio_cat_name = $("input[name='Personen_Personen']:checked").val();
						
						var main_category = $("input[name='category']:checked").val();
						
						if (main_category != 1)
						{
							// if no personen is checked
							maximum_keywords = 30;
							keyword_count    = iterate_elements(maximum_keywords);
						}
						else if (main_category == 1)
						{
							maximum_keywords = 50;
							keyword_count    = iterate_elements(maximum_keywords);							
						}
						else
						{
							// when we go to tab other than 'personen' then maxiumum keyword limit is 30
							maximum_keywords = 30;
							keyword_count    = iterate_elements(maximum_keywords);							
						}
						
						if (keyword_count > maximum_keywords)
						{
							// keyword max limit exceeded
							too_much_keywords = keyword_count - maximum_keywords;
							max_reached_msg   = 'Versuchen Sie das Bild mit maximal '+maximum_keywords+' Keywords zu beschreiben. Bitte entfernen '+too_much_keywords+' Bildbschreibungen';
							alert(max_reached_msg);
							return false;
						}
						else
						{
							flagsubmit = true;
						}				
						
						//Check for modal release and personen type keywords
						
						var tiere_personene = $("input[name='Tier_Personen']:checked").val();
						var mr_required = false;
						if (radio_cat_name != 'undefined' && main_category == 1)
						{
							mr_required = true;
						}
						else if(main_category == 3 && tiere_personene == 'Personen')
						{
							mr_required = true;
						}
						
						if(mr_required == true)
						{
							if( $( 'select#releases' ).containsOption(/^mr_/i) == true || $( 'select#releases' ).containsOption('no_mr') == true)
							{
								//do nothing...
							} 
							else
							{
								alert('Sie müssen Bildern auf denen Personen zu sehen sind ein Model Release zuweisen oder angeben das für das Bild kein Release benötigt wird.');
								flagsubmit = false;	
							}
						}
						//return false;
						return flagsubmit;
					  }
				  }
		);
	// 
	$("input[name=category]").change(
		function()
		{
			//alert($(this).val());
			var mytab = $(this).val();
			if(mytab == 2)
			{
				//get sub cat value
				//alert($("input[name='Landschaft_Typ']:checked").val());
				mytab = $("input[name='Landschaft_Typ']:checked").val();
			}
			var myboxlink = '/smart_keys/get_smart_keys/'+mytab+'?height=500&width=900';
			$("#open-helper").attr('href', myboxlink);
			if($("#open-helper").is(":hidden"))
			{
				$("#open-helper").show();
			}
			//.addClass("thickbox")
			
		}
	);
	$("input[name=Landschaft_Typ]").change(
		function()
		{
			//alert($(this).val());
			var mytab = $(this).val();
			var myboxlink = '/smart_keys/get_smart_keys/'+mytab+'?height=500&width=900';
			$("#open-helper").attr('href', myboxlink);
			if($("#open-helper").is(":hidden"))
			{
				$("#open-helper").show();
			}

			//.addClass("thickbox")
			
		}
	);
	

	function iterate_elements(maximum_keywords)
	{
		var keyword_count = 0;
		
		var count=0;

		// getting fotostil value
		var fotostil = $("input[name='fotostil']:checked").val();
		if (fotostil == 'Freisteller')
		{
			keyword_count++;	
		}

		// getting three categories which are at the top as radios
		var top_cat = $("input[name='light']:checked").val();
		if (top_cat == 'Außenaufnahme')
		{
			keyword_count = keyword_count + 2;	
		}
		else
		{
			keyword_count++;
		}		

		var main_cat = $("input[name='category']:checked").val();
		
		if (main_cat == 1)
		{
			field_prefix = 'Personen_';
		}
		else if (main_cat == 2)
		{
			field_prefix = 'Landschaft_';
		}
		else if (main_cat == 3)
		{
			field_prefix = 'Tier_'; // 
		}
		else if (main_cat == 4)
		{
			field_prefix = 'Objekt_'; // 
		}
		else if (main_cat == 5)
		{
			field_prefix = 'Technik_';
		}
		else
		{
			// No iteration in this case
			field_prefix = 'Not checked'; 
		}
		
		// Looping through Kategorie (Pflichtfeld) and Weitere Keywords field
		$(':input[name^='+field_prefix+']:checked, textarea').each(
				function()
				{
						count++;
						element_type = $(this).attr('type');
						element_name = $(this).attr('name');
						
						//console.log(element_type+'=>'+element_name);
						
						// First filter out all the controls that needs to be ignored
						if (element_name != 'copyright' && element_name != 'redaktionell' && element_name != 'editor_note')
						{
							if (element_type == 'checkbox' || element_type == 'radio' ||  element_type == 'textarea')
							{
								if (element_type == 'checkbox')
								{
									if ($(this).is(':checked') == true && $(this).val() != '')
									{
										// get all checked checkboxes
										//console.log(element_type+'=>'+element_name);
										keyword_count++;
									}
								}						

								if (element_type == 'radio')
								{
									if ($(this).is(':checked') == true && $(this).val() != '')
									{
										// get all checked checkboxes
										//console.log(element_type+'=>'+element_name);
										keyword_count++;
									}
								}
								
								if (element_type == 'textarea')
								{
									txt_weiter = $(this).val();
									words_arr = txt_weiter.split(',');
									
									for (var i = 0; i < words_arr.length; i++)
									{
										if (trim(words_arr[i]) != '')
										{
											//console.log(element_type+'=>'+element_name);
											keyword_count++;
										}
									}
								}

							}
						}
						
				}							 
			) 
		
		    // Looping through IPTC Daten Keywords
			$(':input[name^=iptc]:checked').each(
				function()
				{
						element_type = $(this).attr('type');
						element_name = $(this).attr('name');
												
						if (element_type == 'checkbox')
						{
							if ($(this).is(':checked') == true && $(this).val() != '')
							{
								// get all checked checkboxes
								//console.log(element_type+'=>'+element_name);
								keyword_count++;
							}
						}						
				}							 
			) 

		    // Looping through 'Weitere Stilvorschläge' Keywords
			$(':input[name^=image_]:checked').each(
				function()
				{
						element_type = $(this).attr('type');
						element_name = $(this).attr('name');
												
						if (element_type == 'checkbox')
						{
							if ($(this).is(':checked') == true && $(this).val() != '')
							{
								// get all checked checkboxes
								//console.log(element_type+'=>'+element_name);
								keyword_count++;
							}
						}						
				}							 
			) 

		//console.log(keyword_count);
			
		return keyword_count;
		
		if (keyword_count > maximum_keywords)
		{
			return 1; // exceeded count
		}
		else
		{
			return 2;
		}
	}
	
	function trim(str, chars) {
		return ltrim(rtrim(str, chars), chars);
	}
	 
	function ltrim(str, chars) {
		chars = chars || "\\s";
		return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
	}
	 
	function rtrim(str, chars) {
		chars = chars || "\\s";
		return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
	}
	
	$( 'div.tabbed2 ul.tabs2 li input[type="radio"]' ).click( function()
	{
		
		$( this ).parents( 'ul.tabs2' ).eq( 0 ).find( '.wrapper' ).removeClass( 'active' );
		$( 'div.tabbed2 div.tab2' ).not( 'div.' + $( this ).attr( 'class' ) ).hide();
		$( 'div.' + $( this ).attr( 'class' ) ).show();
		$( this ).parent().addClass( 'active' );
	} );
	$(document).ready(function(){
		//$( 'div.tabbed2 .t1').show();
		
		try{
			//Updated, 01-03-10
			if ( typeof sel_lightcat !== 'undefined' && sel_lightcat != '' )
			{
				$( 'div.tabbed2 ul.tabs2 li.'+sel_lightcat+' div' ).addClass( 'active' );
				$( 'div.tabbed2 .'+sel_lightcat ).show();
				//$( 'li.category-'+sel_smartcat+' .wrapper' ).addClass( 'active' );
			}
			
			if ( typeof sel_smartcat !== 'undefined' && sel_smartcat != '' )
			{
				$( 'div.category-'+sel_smartcat ).show();
				$( 'li.category-'+sel_smartcat+' .wrapper' ).addClass( 'active' );
				
				if($("#open-helper").is(":hidden"))
				{
					$("#open-helper").show();
				}
				
			}
		}catch(e)
		{
			//do nothing
		}
		
		// Overriding accordion default open tab
		//if (override_bank_menu == 1)
		if ( typeof override_bank_menu !== 'undefined' && override_bank_menu == 1 )
		{
			$('#bank-div-section').show();
		}
	
		
		
	});

	$( 'input.#add_release' ).click(function(){
		var a = $( '#rel_dropdown_a' ).val();
		var b = $( '#rel_dropdown_b' ).val();
		var c = $( '#rel_dropdown_c' ).val();		
		var i = $("input.edit-list-item-cb:checked").val();
		
		if ( (a == null && b == null && c == null ) || i == null) {
			alert('Es muss min. ein Bild und ein Release ausgewählt werden.');
			return fale;
		}
		
		return true;
	});
