/*************************************************************/
// module prod javascript file
// (c) thomann - don't even think about copying, stealing or trying to understand this code
/*************************************************************/

var bew_artnr = false;
var helpText = '';
var blameText = '';
var helpTextMA = '';


$(document).ready( function() {

	$('a#bewNoRate, a#bewRatingLinkButton')
	.click( function(e) {
		var $o = $(this).offset();
		var $BtnH = $(this).height();
		var noRateLeft = Math.round($o.left)-40;
		var $BoxNotYouH = $('#bewnotyou').height();
		var noRateTop1 = $o.top - $BoxNotYouH;
		$('#bewnotyou').css( { 'top': noRateTop1, 'left': noRateLeft} );
		var $BoxNotLogH = $('#bewnotloggedinbox').height();
		var noRateTop2 = $o.top - $BoxNotLogH;
		$('#bewnotloggedinbox').css( { 'top' : noRateTop2, 'left' : noRateLeft } );

		//send ajax, abhängig vom status layer anzeigen oder bov!
		var data = { ajax_type: 'newRateState', artnr: bew_artnr, sid: jsNCTrackingSID };
		$.post('prod_prodrateajax.html', data, function( res ) { 

			if ( res == 3 ) document.location.href='mythomann_prodrate.html?ratenr='+bew_artnr;
			if ( res == 2 ) {
				$('#bewnotyou').show();
			}
			if ( res == 1 ) {
				$('#bewnotloggedinbox').show();
			}
		} );
		return false;
	});

	$('#bewHeadConQM')
		.mouseenter( function() {
			 $(this).css( { 'background-position': '-20px -90px' } );
			 var $o = $(this).offset();
			 $('#bewHelp').css( { 'top': $o.top + $(this).height(), 'left': $o.left} ).show();
			 $('#bewHelp').html( helpText );
		})
		.mouseleave( function() {
			 $(this).css( { 'background-position': '0px -90px' } );
			 $('#bewHelp').hide();
		});

	$('body').append( $('#bewHelp') );
	$('body').append( $('#bewnotyou') );
	$('body').append( $('#bewnotloggedinbox') );

	bindCommonHandlers();

	// slider
	var max_pos = $('.bewSlider').width();
	var old_val = '';

	var leftOffset = 3;	//leftOffset: width of line
	$('.bewSlider')
		.live( 'mousedown', function(e) {
			e.stopPropagation();
			e.cancelBubble = true;

			var $parent = $(this);
			var $slide  = $( '.bewSliderGreyFade, .bewSliderLine' );

			$(document)
				.bind('mousemove', function (e) {
					var r_outer_pos = e.pageX - $parent.offset().left;

					if ( r_outer_pos < leftOffset ) r_outer_pos = leftOffset;
					if ( r_outer_pos > ( max_pos ) ) r_outer_pos = ( max_pos );
					r_outer_pos -= $parent.width();

					$slide.css('left', r_outer_pos + 'px' );
					var proz = Math.ceil( ( r_outer_pos + max_pos - leftOffset ) / ( max_pos - leftOffset ) * 100.0);

					if ( old_val != proz ){
						old_val = proz;
					}

					e.stopPropagation();
					return false;
				})
				.bind('mouseup', function() {
					$(this).unbind('mousemove mouseup');

					if ( old_val >= 0 && old_val <= 100 ) {
						$('.bewEntryBodyNotShow').hide();
						$('.bewLess').hide();
						$('.bewEntryBodyShow').each( function() {
							var a = $(this).html();
							var b = $(this).siblings( '.bewEntryBodyNotShow' ).html();

							a = a.replace( /\<br(?: \/)?\>/g, '|' );
							b = b.replace( /\<br(?: \/)?\>/g, '|' );

							var num = ( a.length + b.length ) ;
							var nuNum = Math.ceil( num * old_val / 100 );
							var cutVal = 0;
							var tmp;

							if ( nuNum < a.length ) {
								cutVal = nuNum;
								tmp = a.substring( 0, cutVal );
								b = a.substring( cutVal ) + b;
								a = tmp;
							} else if ( nuNum > a.length ) {
								cutVal = nuNum - a.length;
								a = a + b.substring( 0, cutVal );
								b = b.substring( cutVal );
							}
							
							a = a.replace( /\|/g, '<br>' ); //restore pipes to br's....
							b = b.replace( /\|/g, '<br>' );
							
							$(this).html( a );
							$(this).siblings( '.bewEntryBodyNotShow' ).html( b );
							
							if ( old_val == 100 || old_val == 0 ) {
								$('.bewMoreLink').hide();
								$('.bewEntryBodyShowPoints').hide();
							} else {
								$('.bewMoreLink.bewMore').show();
								$('.bewEntryBodyShowPoints').show();
							}
						});
					}
				});

			return false;
		});

		$('#bewShowAll, .bewShowAllTextLink').click( function(e) {
			open_overlay( bew_artnr, 0, e );
			return false;
		});
});

var dropval = { 'filter-by': 'all', 'sort-by': 'helpful-asc', 'page' : 1 };


function open_overlay( ar, exact, e ){
	var data = {artnr: ar };

	if( exact ){
		jQuery.extend( data, { 'b_filter' : 'exact-'+exact } );
	}

	var yp = $('body').scrollTop();
	var t = yp;
	var xp = 200; 
	if( e ) {
		yp = e.pageY;
		xp = e.pageX;
	}else{
		yp += 300;
	}

	$('body').stopTime('ppra').oneTime( 600, 'ppra', function() {
		// element fade in 
		$('#bewFooter img').show();
	});

	try { pageTracker._trackPageview("/ajaxCallBewFull" ); } catch(e) {}
	$.post('prod_prodrateajax.html', data, function( res ) {
		$('body').ajaxLoad('unique_ajax_1', res, function( ) {
			$(this).css({'display': 'block', 'top': t+30 });
			// element fade out
			$('body').stopTime('ppra');
			$('#bewFooter img').hide();
			$('#bew_ov_wrapper').scrollTo( 0 );
		});
	}, 'html' );
}

	function loadpartial( page ) {

			if( page ) {
				dropval['page'] = page;
			}

			$('#bew_ov_wait').show();

			try { pageTracker._trackPageview("/ajaxCallBewPartial" ); } catch(e) {}
			$.post('prod_prodrateajax.html',  {artnr: bew_artnr, 'b_filter': dropval['filter-by'], 'b_order': dropval['sort-by'], 'b_type': 'partial', 'b_page': dropval['page']  } , function( res ) {
				$('#bew_boxmodel_bug').html(res);
				bindCommonHandlers();
				$('#bew_ov_wait').hide();
				$('#bew_ov_wrapper').scrollTo( 0 );
			}, 'html' );
	}

function overlay_loaded() {
	var h = $(window).height()-140;
	if( h < 490 ) h = 490;
	var $b = $('#bew_overlay');
	$('div.ov-content-wrap', $b).css({'height': h+'px'});
	$('div#bew_ov_wrapper', $b).css({ 'overflow' : 'auto', 'height': (h-32-32)+'px'}); //two bars, one on the top one on the bottom now.....

	function dropdownChanged(id, val ) {
	/*	alert(id + ' # ' + val ); */
			dropval[ id ] = val;
			loadpartial( 1 );
	}


	bindCommonHandlers();

	$(document).ready( function() {
		var $b = $('#bew_overlay');

		$('#starDetail').addClass('bew_ov_starConfigActive');
		
		$('#bew_boxmodel_bug').scroll( function() {
				var x = $(this).offset().x;
				$('#bew_ov_sidebar').text( x );
		});

		$b.draggable({
				handle: '#bew_ov_top', containment: 'document', distance: 3, cursor: 'move'//,
				//start: function() {  $('#bew_ov_content').css('overflow', 'hidden');},
				//stop: function() { $('#bew_ov_content').css('overflow', 'auto'); },
				});
		$b.bgIframe();
				
		$('#starCompact')
			.click( function() {
				$('#bew_overlay .bewEntryHeadStarsDetail').hide();
				$(this).addClass('bew_ov_starConfigActive');
				$('#starDetail').removeClass('bew_ov_starConfigActive');		
				return false;
			});
		$('#starDetail')
			.click( function() {
				$('#bew_overlay .bewEntryHeadStarsDetail').show();
				$(this).addClass('bew_ov_starConfigActive');
				$('#starCompact').removeClass('bew_ov_starConfigActive');	
				return false;
			});
		
		$('#bew_ov_closeButton')
			.click( function() {
				$b.fadeToCompatible( 300, 0.0, function() {
						$(this).css('display', 'none');
					}
				);
			});
		$('#bew_ov_close', $b).click( function() {
			$b.fadeToCompatible( 300, 0.0, function() {
					$(this).css('display', 'none');
				}
			);
		}).hover( function() { $(this).addClass('bew_ov_close_hover'); }, function() { $(this).removeClass('bew_ov_close_hover'); } );


		function bddshow ( $ft ) {
			var off = $('.bdd-dropdown', $ft).position().left;
			$('.bdd-list', $ft).css('left', off ).css('display', 'block').fadeTo( 200, 1.0 );
			$ft.data('lv', true);
		}
		function bddhide( $ft ){

			$('.bdd-list', $ft).fadeTo( 200, 0.0, function(){ $(this).css('display', 'none'); });
			$ft.data('lv', false);
		}

		$(document).click( function() {
			$('.bdd').each( function() { bddhide( $(this) ); } );
		});


		$('.bdd').each( function() {

			var $t		 = $(this);
			var $dd_list = $('.bdd-list li', $t);

			$t.data('lv', false); // List Visible

			function setText( text ){
				$('.bdd-dropbox span', $t).html( text );
			}

			$dd_list
				.mouseenter( function() {
					
					if( $(this).attr('title') ){	// On first mouseover, store the title in data and remove it from attr. (suppresses the "title-text-box")
						$(this).data('title', $(this).attr('title') );
						$(this).attr('title','');
					}

				})
				.hover( function() {
					if( $(this).hasClass('bdd-noselect') ) return false;

					$(this).addClass('bdd-item-hover');
				},
				function() {
					$(this).removeClass('bdd-item-hover');
				})
				.click( function() {
					if( $(this).hasClass('bdd-noselect') ) return false;

					setText( $(this).html() );
					dropdownChanged( $t.attr('id'), $(this).data('title') );
					bddhide( $t );
				});

			$('.bdd-dropdown', $t )
				.click( function(e) {
					if($t.data('lv')){
						bddhide( $t );
					}else{
						bddshow($t);
						$('.bdd').not($t).each( function() { bddhide( $(this) ) } );
					}
					e.stopPropagation();
					e.preventDefault();

					return false;
				});
		});

	});

}

function CloseNotifybox( id ) {
	$('#'+id).hide();
	$('#bewBlameText').val('');
	$('#bewBlameStatus').hide();
}

function bindCommonHandlers() {

		$('.bew_paging')
			.click( function( e ) {
				
				var page = $(this).attr('id').substr( 'bew_paging_'.length );
				loadpartial( page );

				e.preventDefault();

				return false;
			});

	$('.bewMoreLink') 
		.unbind('click')
		.bind( 'click', function() {
			if ( $( '.bewEntryBodyNotShow',$(this).parent() ).css( 'display' ) == 'none' ) {
				$( '.bewEntryBodyNotShow',$(this).parent() ).show();
				$( this ).hide();
				$( '.bewLess', $(this).parent() ).show();
				$(this).siblings('.bewEntryBodyShowPoints').hide();
			} else {
				$( '.bewEntryBodyNotShow',$(this).parent() ).hide();
				$( this ).hide();
				$( '.bewMore', $(this).parent() ).show();
				$(this).siblings('.bewEntryBodyShowPoints').show();
			}
			
			return false;
		});
		
	$('#bew_overlay .bewEntryBody')
		.mouseenter( function() {
			
		});
		
	$('.bewEntryFootHelpBlame')
		.unbind( 'mouseenter mouseleave click' )
		.bind( 'mouseenter', function() {
			$(this).css( { 'background-position': '-100px -90px' } );
		})
		.bind( 'mouseleave', function() {
			$(this).css( { 'background-position': '-80px -90px' } );
		})
		.click( function() {
			$b = $(this);
			$(this).mouseout();
			$('#unzumutbarbox')
				.unbind( 'click' )
				.css({ 
//						'top': ( $(this).offset().top - ( $('#unzumutbarbox').height() / 2 ) ),
						'top': ( $(this).offset().top + $(this).height() ),
						'left': ( $(this).offset().left - ( $('#unzumutbarbox').width() / 2 ) )
					})
				.show();
				
			$('#unzumutbarbox input').unbind('click');
			
			$('#unzumutbarbox input#send')
				.click( function() {
					$h = $('#unzumutbarbox');
					if ( $('#bewBlameText').val().length == 0 ) {
						return $('#bewBlameStatus').html( bewBlameNoText ).fadeIn( 'def' ).oneTime( 2000, function() { $(this).fadeOut(300); });
					}

					var rateid = 0;
					var rateid_type = '';
					var blame_text = $('#bewBlameText').val();
					var t = $b.parents('.bewEntry').attr('rel').split('_');

					rateid = t[2];
					rateid_type = t[1];

					var data = { ajax_type: 'blame', blame_text: blame_text, rateid: rateid, rateid_type: rateid_type, sid: jsNCTrackingSID };
					$.post('prod_prodrateajax.html', data, function( res ) { 
						if ( res == 1 ) {
							$('#bewBlameStatus').html( bewBlameNoLogin ).fadeIn( 'def' ).oneTime( 2000, function() { $(this).fadeOut(300); });
						}
						if ( res == 2 ) {
							$('#bewBlameStatus').html( bewBlameOk ).fadeIn( 'def' ).oneTime( 2000, function() {
								$h.fadeOut(300);
								$('#bewBlameText').val('');
								$(this).hide();
							});
						}
						if ( res == 3 ) {
							$('#bewBlameStatus').html( bewBlameNot ).fadeIn( 'def' ).oneTime( 2000, function() { $(this).fadeOut(300); });
						}
					});
				});
			
			return false;
		});


	$('.bewParticipation')
		.unbind( 'click' )
		.bind( 'click', function() {
		
			var type = $(this).attr('rel');
			var rateid = 0;
			var rateid_type = '';
			
			var t = $(this).parents('.bewEntry').attr('rel').split('_');
			rateid = t[2];
			rateid_type = t[1];

			var $t = $(this);
			var data = { ajax_type: type, rateid: rateid, rateid_type: rateid_type, sid: jsNCTrackingSID };
			
			 if ( !$(this).hasClass('clickedHighlightClass') ) {
	
				if( $(this).data('ajax_in_progress') ){
					return false;
				}

				var $bobj = $(this).data('ajax_in_progress', true);
				try { pageTracker._trackPageview("/ajaxCallBewRate" ); } catch(e) {}

				$.post('prod_prodrateajax.html', data, function( res ) { 

					$bobj.data('ajax_in_progress', false);

					//using that awsum #bewHelp container for showing sum information to the user.
					if ( res == 1 ) {
						$t.addClass('clickedErrorClass').oneTime( 1000, function() {
							$t.removeClass('clickedErrorClass');
							$(this).removeClass('clickedHighlightClass'); 
						});
					}
					if ( res == 2 ) {
						$t.addClass('clickedHighlightClass');
					}
					if ( res == 3 ) document.location.href = 'mythomann_prodrate.html?ratenr='+bew_artnr;
				}, 'html' );
			 }

			 if ( $(this).siblings().hasClass('clickedHighlightClass') ) {
                $(this).siblings().removeClass('clickedHighlightClass');
			 }

			return false;
		});

	$('.bewEntryHeadMa')
		.click( function() {
			 var $o = $(this).offset();
			 var $MaBtnW = $('.bewEntryHeadMa').width()/2;
			 var $thoBoxW = $('#thoteambox').width()/2;
			 $('#thoteambox').css( { 'top': $o.top + $(this).height(), 'left': $o.left + $MaBtnW - $thoBoxW} ).show();
		})

}
