// deutsche fehlermeldungen
$.tools.validator.localize( 'de', {
	'*': 'Bitte vervollständige dieses Feld',
	':email': 'Bitte korrekte E-Mail Adresse angeben',
	':number': 'Das Feld darf nur aus Ziffern bestehen',
	':url': 'Bitte gib eine gültige URL ein',
	'[required]': 'Pflichtfeld'
});
// minlength integration
$.tools.validator.fn( '[minlength]', function( input, value ) {
	var min = input.attr( 'minlength' );
	
	if( min.indexOf( ',' ) > -1 ) {
		var split = min.split( ',' );
		
		if( value.length == split[0] ) return true;
		if( value.length < split[1] ) {
			return {
				en: 'Please provide at least ' + split[1] + ' character' + ( split[1] > 1 ? 's' : '' ),
				de: 'Bitte gib mindestens ' + split[1] + ' Buchstaben an'
			}
		}
		return true;
	}
	
	
	return value.length >= min ? true : {
		en: 'Please provide at least ' + min + ' character' + ( min > 1 ? 's' : '' ),
		de: 'Bitte gib mindestens ' + min + ' Buchstaben an'
	};
});
// data-equals integration
$.tools.validator.fn( '[data-equals]', function( input, value ) {
	var name = input.attr( 'data-equals' ),
		field = this.getInputs().filter( '[name=' + name + ']' ),
		cname = name.toUpperCase().substr( 0, 1 ) + name.substr( 1 );
		if( cname == 'Password' ) cname = 'Passwort';
 
 	if( input.val() == field.val() ) return true;
 	return {
 		en: 'Value not equal with the ' + cname + ' field',
 		de: cname + ' stimmt nicht überein'
 	}
});


function resetme(elem) {
    if( elem.length > 1 ) {
        for( i = 0; i < elem.length; i++ ) {
            resetme( elem[i] );
        }
    } else {
        if( elem.data( 'primal' ) ) {
            elem.stop().animate({
                'top': elem.data( 'primal' ).top,
                'left': elem.data( 'primal' ).left
            });
        }
    }
}

function rotate() {	
	if( $('#partner-rotate').length ) {
		$('#partner-rotate a').each( function( index, elem ) {
			if( $(elem).css( 'display' ) == 'inline' ) {
				$(elem).fadeOut( "slow", function() {
					if( $(elem).next().length > 0 ) {
						$(elem).next().fadeIn('slow');
					} else {
						$('#partner-rotate a:first').fadeIn('slow');
					}
				});
			}
		});
	} else {
		clearInterval( partnerRotate );
	}
}
var partnerRotate = setInterval( 'rotate()', 4000  );
	  
$(document).ready( function() {

	if( $('a.fancy').length ) {
		$('a.fancy').each( function( i, el ) {
			$(el).fancybox({
				titleShow: false,
				type: 'image'
			}); 
		});
	}
	
	if( $('a.fancy-rating').length ) {
		$('a.fancy-rating').each( function( i, el ) {
			
			$(el).fancybox({
				titleShow: true,
				titlePosition: 'inside',
				type: 'image',
				title: 'loading ...',
				onStart: function() {
				},
				onCancel: function() {
					$.fancybox.close();
					alert( 'Es ist ein Fehler beim laden des Bildes oder beim Bewerten aufgetreten.' + "\n" + 'Bitte probier es erneut!' );
				},
				onComplete: function() {
					var currentEl = $(el);
					var currentRating = parseFloat( $(el).attr( 'title' ) ).toFixed( 2 );
					if( currentRating === 'NaN' ) {
						currentRating = 0;
					}
					
					var nickname = $(el).parent().find('div.plakat-infos span.nickname').text();
					var nickurl = $(el).parent().find('div.plakat-infos span.nickurl').text();
					var imagesid = $(el).parent().find('div.plakat-infos span.id').text();
					
					var stars = '';
					if( currentRating >= 1 ) {
						stars += '<a href="#" rel="1" class="star full"></a>';
					} else if( currentRating > 0 && currentRating < 1 ) {
						stars += '<a href="#" rel="1" class="star half"></a>';
					} else {
						stars += '<a href="#" rel="1" class="star clear"></a>';
					}
					if( currentRating >= 2 ) {
						stars += '<a href="#" rel="2" class="star full"></a>';
					} else if( currentRating > 1 && currentRating < 2 ) {
						stars += '<a href="#" rel="2" class="star half"></a>';
					} else {
						stars += '<a href="#" rel="2" class="star clear"></a>';
					}
					if( currentRating >= 3 ) {
						stars += '<a href="#" rel="3" class="star full"></a>';
					} else if( currentRating > 2 && currentRating < 3 ) {
						stars += '<a href="#" rel="3" class="star half"></a>';
					} else {
						stars += '<a href="#" rel="3" class="star clear"></a>';
					}
					if( currentRating >= 4 ) {
						stars += '<a href="#" rel="4" class="star full"></a>';
					} else if( currentRating > 3 && currentRating < 4 ) {
						stars += '<a href="#" rel="4" class="star half"></a>';
					} else {
						stars += '<a href="#" rel="4" class="star clear"></a>';
					}
					if( currentRating >= 5 ) {
						stars += '<a href="#" rel="5" class="star full"></a>';
					} else if( currentRating > 4 && currentRating < 5 ) {
						stars += '<a href="#" rel="5" class="star half"></a>';
					} else {
						stars += '<a href="#" rel="5" class="star clear"></a>';
					}
					
					var html = '<table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td width="35%" align="left"><strong>Plakat von</strong></td>';
					html += '<td width="*" align="right"><strong>Plakat bewerten</strong></td></tr><tr><td valign="top" align="left"><a href="' + nickurl + '">' + nickname + '</a></td>';
					html += '<td align="right" valign="top"><span class="updatedStars" style="display: block; float: right; clear: right;">' + stars + '</span><small style="float: right; clear: right; display: block;">Aktuelle Bewertung: <span class="updatedRating">' + currentRating + '</span></small></td>';
					html += '</tr></table>';
					
					$('#fancybox-title-inside').html( html );
					
					$('#fancybox-title-inside a.star').click( function(e) {
						e.preventDefault();
						$.fancybox.showActivity();
						
						$.ajax({
							type: 'POST',
							url: window.location.href,
							data: 'image=' + imagesid + '&star=' + $(this).attr('rel'),
							dataType: 'json',
							success: function( resp ) {
								$.fancybox.hideActivity();
								if( resp.success ) {
									$('span.updatedRating').text( resp.newRating );
									currentEl.attr( 'title', resp.newRating );
									$('span.updatedStars').fadeOut('fast');
								} else {
									// bereits gevoted
									
								}	
							}
						});
						return false;
					});
				}
			});
		});
	}
	
	
	/*
	$('.fancyclose').live( 'click', function() {
		$.fancybox.showActivity();
		return false;
	});
	*/
	
	if( $('textarea').length ) {
		$('textarea').autoResize();
	}
	
	if( $('form.validate-top').length ) {
		$('form.validate-top').validator({
		   	lang: 'de',
    		offset: [-20,-15],
	    	message: '<div><em/></div>',
    		position: 'top center'
		});
		
		if( $('form.validate-top input, form.validate-top textarea' ).length ) {
			$('form.validate-top input, form.validate-top textarea' ).blur( function() {
				$('form.validate-top').data('validator').checkValidity();
			});
		}
	}
	
	
	if( $('form.validate').length ) {
		$('form.validate').validator({
			lang: 'de',
    		position: 'center right'
		});/*.bind('onSuccess', function( e, els ) {
			$('.ui-icon-circle-check').remove();
			for( i = 0; i < els.length; i++ ) {
				$(els[i]).after('<span class="ui-icon ui-icon-circle-check"></span>');
			}
		});*/
		
		if( $('form.validate input, form.validate textarea').length ) {
			$('form.validate input, form.validate textarea').blur( function() {
				$('form.validate').data('validator').checkValidity();
				/*
				$('form.validate input[type!="submit"], form.validate textarea').each( function() {
					if( true || !$(this).hasClass('invalid') ) {
						$(this).after('<span class="ui-icon ui-icon-circle-check"></span>');
					} else {
						if( $(this).next().length ) {
							var next = $(this).next()[0];
						}
					}
					alert( $( $(this).next()[0] ).html() );
					console.log( $(this), $(this).next() );
				});
				
				var form = $('form.validate').data('validator').getForm();
				$('form.validate input, form.validate textarea', form).each(function() {
					console.log( $(this).next() );
				});
				*/
				/*
				$('.invalid', form ).each( function() {
					$(this).after('<span class="ui-icon ui-icon-circle-close"></span>');
				});
				*/
				/*
				if( $(this).data('validator').checkValidity() ) {
					$(this).after('<span class="ui-icon ui-icon-circle-check"></span>');
				}
				*/
			});
		}
	}

	if( $('#partner-rotate a').length ) {
		$('#partner-rotate a').hide();
		
		elems = [];
		$('#partner-rotate a').each( function() {
			elems.push( $(this).clone( true ) );
		});
		$('#partner-rotate a').each( function() {
			rand = Math.floor( Math.random() * elems.length );
			$(this).replaceWith( elems[ rand ] );
			elems.splice( rand, 1 );
		});

		$('#partner-rotate a:first').show();
	}
	
	if( $('input.send').length ) {
		$('input.send').button();
	}
	
    if( $('button.edit-profile, button.register').length ) {
		$( 'button.edit-profile, button.register' ).button();
        $('button.edit-profile, button.register, a.uploadavatar').click( function() {
        	var editclicked = false;
        	if( $(this).hasClass( 'uploadavatar' ) ) {
        		editclicked = true;
        	}
        	if( $(this).hasClass( 'edit-profile' ) || editclicked ) {
				
				if( $('#data').length ) {
						$('#data').bind( 'tabsselect', function( e, ui ) {
							if( !$('#frmeditprofile').data('validator').checkValidity() ) {
								return false;						
							}
						});
				}
				
	            $('#dialog').dialog({
	                closeOnEscape: false,
	                height: 750,
	                width: 600,
	                //hide: 'slide',
	                //show: 'slide',
	                beforeClose: function( e, ui ) {
	                	$('#frmeditprofile').data( 'validator' ).reset();
	                },
	                open: function( e, ui ) {
	                	$('.ui-dialog-buttonpane').append('<p><small><a href="' + $('span.deleteprofile').text() + '">Profil dauerhaft löschen</a></small></p>');
	                },
	                modal: true,
	                draggable: false,
	                resizable: false,
	                buttons: {
	                    'Speichern': function() {
	                    	if( $('#frmeditprofile').data('validator').checkValidity() ) {
	                    		$('#frmeditprofile').data('validator').destroy();
	                    		
	                    		// disable button
	                    		var savebutton = $(this).parent().find( 'button' );
	                    		if( savebutton.length ) {
	                    			savebutton = $( savebutton[0] );
	                    			savebutton.button('disable');
	                    		}
	                    		
	                    		$('#frmeditprofile').submit();
	                    		
	                    	}
	                    },
	                    'Abbrechen': function() {
	                        $(this).dialog('close');
	                    }
	                }
	            });
	            return false;
	    	} else {
	    		$('#dialog').dialog({
	                closeOnEscape: false,
	                height: 500,
	                width: 600,
	                //hide: 'slide',
	                //show: 'slide',
	                beforeClose: function( e, ui ) {
	                	$('#frmregister').data('validator').reset();
	                	$('.frmregister-errors').find('p').remove().end().hide();
	                },
	                modal: true,
	                draggable: false,
	                resizable: false,
	                buttons: {
	                    'Registrieren': function() {
	                    	if( $('#frmregister').data('validator').checkValidity() ) {
	                    		$('.frmregister-errors').hide();
	                    		if( $('.frmregister-errors .ui-state-error').length ) {
	                    			$('.frmregister-errors .ui-state-error').remove();
	                    		}
	                    		$.ajax({
	                    			url: $('#frmregister').attr( 'action' ),
	                    			type: 'POST',
	                    			data: $('#frmregister').serialize(),
          							dataType: 'json',
	                    			success: function( resp ) {
	                    				if( resp.success ) {
	                    					if( resp.url && resp.url.length ) {
	                    						window.location.href = resp.url;
	                    					}
	                    				}
	                    				if( resp.errors && resp.errors.length ) {
	                    					for( i = 0; i < resp.errors.length; i++ ) {
	                    						$('.frmregister-errors').append( '<div class="ui-state-error ui-corner-all" style="padding: 0 .7em;"><p><span class="ui-icon ui-icon-close" style="float: left; margin-right: .3em;"></span><strong>Fehler:</strong> ' + resp.errors[i] + '</p></div>' );
	                    					}
	                    					$('.frmregister-errors').fadeIn();
	                    				}
	                    			}
	                    		});
	                    	}
	                        
	                    },
	                    'Abbrechen': function() {
	                        $(this).dialog('close');
	                    }
	                }
	            });
	            return false;
	    	}
        });
    }
	
	if( $( "#datepicker" ).length ) {
		$( "#datepicker" ).datepicker({
			minDate: new Date(1930, 1 - 1, 1),
			maxDate: '-1d',
			monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
			changeMonth: true,
			dateFormat: 'yy-mm-dd',
			yearRange: '1930:2099',
			changeYear: true
		});
	}
	
	if( $('#data').length ) {
		$( "#data" ).tabs();
	}
    
    if( $('.errors .ui-widget').length ) {
        $('.errors .ui-widget').click( function() {
            $(this).hide();
        })
    }
    
    
    // haendlersuche
    if( $('.search_hits_count').length ) {
    	if( $('.search_hits_count' ).text() == '0' ) {
    		$('#search_hits').hide();
    	}
    } else {
    	$('#search_hits').hide();
    }
    $('#haendlersuche_error').live( 'click', function() {
       $(this).hide(); 
    });
    
    if( $('#search_button img').length ) {
    	$('#search_button img').click( function() {
    		if( $( '#haendlersuche_plz' ).data( 'validator' ).checkValidity() == false ) {
   	 			return false;
    		}
    		int = parseInt( $( '#haendlersuche_plz' ).val(), 10 ) > 0 ? parseInt( $( '#haendlersuche_plz' ).val(), 10 ) : '';
            if( $( '#haendlersuche_plz' ).val().substr( 0, 1 ) == '0' && $( '#haendlersuche_plz' ).val().length == 5 ) {
                int = '0' + int + '';
            }
   			window.location.href = $( '#haendlersuche' ).attr('action') + '/' + int + '/' + $('#haendlersuche_umkreis').val() + '/' + $('#haendlersuche_product').val();
	    	return false; 
    	});
    }
    
    $( '#haendlersuche' ).submit( function() {
    	int = parseInt( $( '#haendlersuche_plz' ).val(), 10 ) > 0 ? parseInt( $( '#haendlersuche_plz' ).val(), 10 ) : '';
        if( $( '#haendlersuche_plz' ).val().substr( 0, 1 ) == '0' && $( '#haendlersuche_plz' ).val().length == 5 ) {
            int = '0' + int + '';
        }
    	window.location.href = $( '#haendlersuche' ).attr('action') + '/' + int + '/' + $('#haendlersuche_umkreis').val() + '/' + $('#haendlersuche_product').val();
    	return false; 
    } );
    $( '#haendlersuche2' ).submit( function(e) {
    	if( $( '#haendlersuche_plz2' ).data( 'validator' ).checkValidity() == false ) {
    		e.preventDefault();
    		return false;
    	}
    	int = parseInt( $( '#haendlersuche_plz2' ).val(), 10 ) > 0 ? parseInt( $( '#haendlersuche_plz2' ).val(), 10 ) : '';
        if( $( '#haendlersuche_plz2' ).val().substr( 0, 1 ) == '0' && $( '#haendlersuche_plz2' ).val().length == 5 ) {
            int = '0' + int + '';
        }
    	window.location.href =$(this).attr('action') + '/' + int + '/' + $('#haendlersuche_umkreis2').val() + '/' + $('#haendlersuche_product2').val();
    	return false; 
    } );
    
    $( '#haendlersuche_plz2' ).focus( function() {
       if( $(this).val() == 'PLZ' ) {
       		$(this).val(''); 
       		$(this).data( 'validator' ).reset( $(this) );
       	}
    }).blur( function() {
        if( $(this).val().length <= 0 ) {
        	$(this).val('PLZ');
        	$(this).data( 'validator' ).reset( $(this) );	
        }
    }).validator({
    	lang: 'de',
    	offset: [-12,0],
    	message: '<div><em/></div>',
    	position: 'top center'
    }).keypress( function(e) {
    	if( e.which == '13' ) {
    		if( $(this).data( 'validator' ).checkValidity() == false ) return false;
    	}
    });
    
    $( '#haendlersuche_plz' ).focus( function() {
       if( $(this).val() == 'PLZ' ) {
       		$(this).val(''); 
       		$(this).data( 'validator' ).reset( $(this) );
       }
    }).blur( function() {
        if( $(this).val().length <= 0 ) {
        	$(this).val('PLZ');
        	$(this).data( 'validator' ).reset( $(this) );
        }
    }).validator({
    	lang: 'de',
    	offset: [-12,0],
    	message: '<div><em/></div>',
    	position: 'top center'
    }).autocomplete({
        minLength: 3,
        source: function( request, response ) {
            var el = $( '#haendlersuche_plz' );
            var value = el.val();
            if( !el.data('bgcolor') ) {
                el.data('bgcolor', el.css('background-color') );
            }
            $('.search_hits_count').text( '0' );
            $.ajax({
               url: $( '#haendlersuche' ).attr( 'action' ) + '?term=' + request.term + '&product=' + $('#haendlersuche_product').val() + '&radius=' + $('#haendlersuche_umkreis').val(),
               type: 'POST',
               dataType: 'json',
               //data: request,
               success: function( response ) {
                   if( response && ( response.hits || response.error ) ) {
                       if( response.error.length > 0 ) {
                       	   //$( '#haendlersuche_plz' ).attr( 'data-message', response.error );
                       	   $( '#haendlersuche_plz' ).data( 'validator' ).invalidate({
                       	   		'plz': response.error
                       	   });
                           /*
                           el.effect( 'highlight', { color: '#FFAFAF' }, 3000 );
                           $('#haendlersuche_error').text( response.error );
                           $('#haendlersuche_error').show('fold', {}, 1000 );
                           */
                           return false;
                       } else {
                       	   $( '#haendlersuche_plz' ).data( 'validator' ).checkValidity();
                           //$('#haendlersuche_error').hide();
                           //el.css( 'background', el.data('bgcolor') );
                       }
                       if( response.hits > 0 ) {
                           $('.search_hits_count').text( response.hits );
                           //$('#search_hits').fadeIn('slow');
                       } else {
                           //$('#search_hits').fadeOut('fast');
                       }
                   }
               }
            });
        }
    }).keypress( function(e) {
    	if( e.which == '13' ) {
    		if( $(this).data( 'validator' ).checkValidity() == false ) return false;
    	}
    });
    
    if( $('#coverflow' ).length ) {
        //init coverflip
        $( '#coverflow' ).coverflow({
            // zurueck button initialisieren
            'prev': '#flow_nav .cf-prev',
            // next button initialisieren
            'next': '#flow_nav .cf-next',
            // klassen der elemente in reihenfolge current -> small -> smaller
            'classes': [ 'xlarge', 'large', 'medium', 'small' ],
            // interval fuer den automatischen wechsel (in ms)
            'interval': 5000,
            // effekt geschwindigkeit (in ms)
            'movementSpeed': 150
        });
    }
    
    $('.bgbottle').hover( function() {
        // on hover in
        if( !$(this).data( 'primal' ) ) {
            $(this).data( 'primal', {
                'top': $(this).css( 'top' ),
                'left': $(this).css( 'left' ),
                'src': $(this).find( 'img' ).attr( 'src' )
            });
        }
        if( !$('div.primarybottle img').data( 'primal' ) ) {
            $('div.primarybottle img').data( 'primal', {
                'src': $('div.primarybottle img').attr( 'src' )
            });
        }
        
        // set new props
        $(this).stop().animate({
            'top': parseFloat( $(this).css( 'top' ) ) - 20,
            'left': parseFloat( $(this).css( 'left' ) ) - 20
        }, 'slow', function() {
            $(this).find( 'img' ).attr( 'src', $(this).data( 'primal' ).src.substr( 0, $(this).data( 'primal' ).src.length - 4 ) + '_hover.png' );
            $('div.primarybottle img').attr( 'src', $('div.primarybottle img').data( 'primal' ).src.substr( 0, $('div.primarybottle img').data( 'primal' ).src.length - 4 ) + '_hover.png' );
        });
        
    }, function() {
        // on hover out
        resetme( $(this) );
        $(this).find( 'img' ).attr( 'src', $(this).data( 'primal' ).src );
        $('div.primarybottle img').attr( 'src', $('div.primarybottle img').data( 'primal' ).src );
    });
    $('#bottle1,#bottle').hover( function() {
        resetme( $('.bgbottle') );
        $('div.primarybottle img').attr( 'src', $('div.primarybottle img').data( 'primal' ).src );
    });
});
