jQuery(document).ready(function($) {
// Packstation
/* 
		if(!$("#register_billing_shippingPackstation").is(':checked')) {
			if(!$('.register').hasClass('change_shipping')) {
				$('.register .alternative_shipping_packstation').hide();
			}
		}
	
 		
		$('#register_billing_shippingAddressBilling, #register_billing_shippingAddress, #register_billing_shippingPackstation').unbind().click(function() {
      switch ($(this).val()) {
        case '0' : $('.register .alternative_shipping, .register .alternative_shipping_packstation').slideUp(); break;
        case '1' : $('.register .alternative_shipping_packstation').slideUp(function() {$('.register .alternative_shipping').slideDown();}); break;
        case '2' : $('.register .alternative_shipping').slideUp(function() {$('.register .alternative_shipping_packstation').slideDown();}); break;
      } 
		});
}			
*/
  
/*       
		$('a.modal_open_frame').click(function(event) {
			if (!($.browser.msie)) {
        event.preventDefault();
			
			  $.modalIFrame(this.href, '', {'position':'fixed'});	
      }		
		});
*/		
     
      
    $("#listing-1col .ArticleListingNoArticlesFound.allglow").parent().css({'background': 'transparent', 'border': '0', 'box-shadow': 'none', '-webkit-box-shadow': 'none', '-moz-box-shadow': 'none'});      		

  	var SupplierPos   = 0;
  	var SupplierCount = $('#slidebody > li').size();

  	$('#button_bottom').css({'display':'block'}).click(function(event) {                                 
  	  event.preventDefault();                                                         
	  
  	  SupplierPos += 6;
	  
  	  if (SupplierPos >= SupplierCount) {
        SupplierPos = 0;
      } else
      if (SupplierPos + 6 > SupplierCount) {
        SupplierPos = SupplierCount - 6;
      }
	  
	    $('#slidebody').animate({'top': '-' + SupplierPos * 61 + 'px'}, 1000);
	  });
});

// ==================  * Facebook Javascript                     *  ======================

jQuery(document).ready(function($) {

      var e = document.createElement('script');
      e.type  = 'text/javascript';
      e.src   = document.location.protocol + '//connect.facebook.net/de_DE/all.js';
      e.async = true;
      $('#fb-root').append(e);


      $('#fbAutoUpdateLink').bind('click', function(event) {
        event.preventDefault(); 
 
        if ($.Facebook.User == null) {
          $.Facebook.Login();
        } else {
          $.Facebook.GetData();
        }                   
      });  
      
      
}); 

(function($) {
    $.Facebook = { 
        User: null,

        Init: function(fbAppID) {
            FB.init({appId: fbAppID, status: true, cookie: true, xfbml: true});
        },  
      
        PrepareRegister: function() {  
/*            FB.Event.subscribe('auth.login', function(response) {
              if (response.session) {
                $.Facebook.UpdateProfileInfo();
              }
            });
            
            FB.Event.subscribe('auth.logout', function(response) {
              $.Facebook.UpdateProfileInfo();
            });        
*/        
            FB.getLoginStatus(function(response) {
              if (response.session) {
                $.Facebook.UpdateProfileInfo();
              }
            });       
        },
        
        UpdateProfileInfo: function() {
            FB.api('/me', function(user) {
              $.Facebook.User = user;
              if (user != null) {
//                $('#fbImage').attr('src', 'https://graph.facebook.com/' + user.id + '/picture');
                $('#fbAutoUpdateLink').html(user.first_name + ', du kannst die Felder automatisch mit Facebook ausfüllen lassen!');
              } else {
//                $('#fbImage').attr('src', '');
                $('#fbAutoUpdateLink').html('Felder automatisch mit Facebook ausfüllen!');              
              }
            });                    
        },
        
        GetData: function() {
            $.loadingIndicator.open({'loadingText': 'Hole Daten von Facebook...'});
            FB.Data.query('select first_name, last_name, middle_name, email, sex, current_location, hometown_location from user where uid=me()').wait(function(rows) {
              if (rows[0].middle_name != '')
                $('#firstname').val(rows[0].first_name + ' ' + rows[0].middle_name).blur(); else
                $('#firstname').val(rows[0].first_name).blur();
              $('#lastname').val(rows[0].last_name).blur();  
              if (rows[0].email != null)
                $('#register_personal_email').val(rows[0].email).blur(); 
              if (rows[0].sex == 'male')
                $('#register_personal_salutation_mr').attr('checked', true); 
              if (rows[0].sex == 'female')  
                $('#register_personal_salutation_ms').attr('checked', true);
              loc = rows[0].current_location != null ? rows[0].current_location : rows[0].hometown_location != null ? rows[0].hometown_location : null;    
              if (loc != null) {
                $('#city').val(loc.city).blur();
                $('#zipcode').val(loc.zip).blur(); 
                switch (loc.country) {
                  case "Germany":        $('#country').val("2").blur();  break;
                  case "France":         $('#country').val("9").blur();  break;
                  case "Italy":          $('#country').val("14").blur(); break;
                  case "United Kingdom": $('#country').val("11").blur(); break;
                  case "Switzerland":    $('#country').val("38").blur(); break;
                  case "Austria":        $('#country').val("23").blur(); break;
                  case "Belgium":        $('#country').val("5").blur();  break;
                  case "Denmark":        $('#country').val("7").blur();  break;
                  case "Liechtenstein":  $('#country').val("43").blur(); break;
                  case "Luxembourg":     $('#country').val("18").blur(); break;
                  case "Netherlands":    $('#country').val("21").blur(); break;
                  case "Poland":         $('#country').val("30").blur(); break;
                  case "Sweden":         $('#country').val("41").blur(); break;
                  case "Slovakia":       $('#country').val("39").blur(); break;
                  case "Slovenia":       $('#country').val("40").blur(); break;
                  case "Czech Republic": $('#country').val("42").blur(); break;
                  case "Hungary":        $('#country').val("31").blur(); break;                  
                  default:               $('#country').val("").blur();                   
                } 
              }      
              $.loadingIndicator.close();
            });            
        },
        
        Login: function() {
            $.loadingIndicator.open({'loadingText': 'Mit Facebook verbinden...'});
            FB.login(function(response) {
              $.loadingIndicator.close();
              if (response.session) {
                $.Facebook.UpdateProfileInfo();
                $.Facebook.GetData();              
              } else {
                   
              }
            }, {perms:'user_location,user_hometown,email'});        
        }
        
    };  
})(jQuery);              

// ==================  * Modales IFrame um Hintergrund erweitert *  ======================
/*
(function($) {
  $.modalIFrame = function (url, headline, settings) {

    $.modal.overlay.fadeIn();
            
    $('#lbOverlay').bind('click', function (event) {
      $.modalClose();
    })
         
    return $.modalFrame(url, headline, settings);
  }
})(jQuery);
*/
// ==================  * Loading Indicator *  ======================

(function($) {
  if (!($.browser.msie)) {
	  $.loadingIndicator.config = {
			'overlay': '#lbOverlay',
			'overlayOpacity': 0.6,
			'hideOverlayAfterClose': true,
			'loadingClass': 'loadingIndicator allglow',
			'loadingText': 'Loading...',
			'height': 180,
			'width': 330,
			'animationSpeed': 300,
			'additionalCSS': {},
			'bindEvent': true,
			'_loader': null
		}

		$.loadingIndicator.open = function(settings) {
			
			// settings
			if (settings) $.extend($.loadingIndicator.config, settings);
			if (!settings) $.extend($.loadingIndicator.config, {'loadingText': 'Loading...'}); 
		
			// Create loader
			$.loadingIndicator.config._loader = $('<div>', {
				'class': $.loadingIndicator.config.loadingClass,
				'text': $.loadingIndicator.config.loadingText,
				'css': {
					'position': 'fixed',
					'top': '50%',
					'left': '50%',
					'marginTop':  -($.loadingIndicator.config.height/2) +'px',
					'marginLeft': -($.loadingIndicator.config.width/2) + 'px',
					'height': $.loadingIndicator.config.height,
					'width': $.loadingIndicator.config.width,
					'zIndex': 99999
				}
			}).hide().appendTo($(document.body));
			
			$.loadingIndicator.config._loader.html('<div class="loadingBox"><div>Ein Moment bitte...</div><div style="float:left;">' + $.loadingIndicator.config.loadingText + ' </div><div class="ajax_loader"></div></div>');
			
			// Add additionalcss if passed
			if(!$.isEmptyObject($.loadingIndicator.config.additionalCSS)) {
				$.loadingIndicator.config._loader.css($.loadingIndicator.config.additionalCSS);
			}
			
			// Overlay handling
			if($.loadingIndicator.config.hideOverlayAfterClose == true) {
				$($.loadingIndicator.config.overlay).fadeTo($.loadingIndicator.config.animationSpeed, $.loadingIndicator.config.overlayOpacity);
			}
			if($.loadingIndicator.config.bindEvent == true) {
				$($.loadingIndicator.config.overlay).css({'cursor': 'pointer'}).bind('click', function() {
					$.loadingIndicator.close();
				});
			} else {
				$($.loadingIndicator.config.overlay).css({'cursor': 'default'});
			}
			if($.browser.msie && parseInt($.browser.version) == 6) {
				$.ie6fix.open($.loadingIndicator.config._loader);
			} else {
				$.loadingIndicator.config._loader.fadeIn($.loadingIndicator.config.animationSpeed);
			}
			
		}
		
		
		$.loadingIndicator.close = function() {
			if($.loadingIndicator.config._loader) {
        $($.loadingIndicator.config.overlay).fadeOut(0);   
				if($.browser.msie && parseInt($.browser.version) == 6) {
					$.ie6fix.close($.loadingIndicator.config._loader);
				} else {
					$.loadingIndicator.config._loader.animate({
						'opacity': 0
					}, $.loadingIndicator.config.animationSpeed, function() {
						$.loadingIndicator.config._loader.remove();
					});
				}
			}
		}	
  }	
})(jQuery);		


// ==================  * Comparison *  ======================
(function($) {
    //Requests the compare informations
    $.compare.startComparison = function (url) {
        $.ajax({
            'dataType': $.compare.options.dataType,
            'type': $.compare.options.requestType,
            'url': url,
            'beforeSend': function() {
              	$.loadingIndicator.open({'loadingText': 'Vergleich wird gestartet...'});
            },            
            'complete': function (result) {
        $.loadingIndicator.close();    
				var width = 160 * $.compare.options.compareCount + 160;
					var position = 'fixed';
				
				if($.browser.msie && parseInt($.browser.version) == 6) {
					width += 2;
					position = 'absolute';
				}
                
				$.modal(result.responseText, '', {
               		'position': position,
               		'width': width+'px',
               		'top': '30px',
               		'textContainer': '<div>',
               		'textClass': 'ajax_compare_container'
               });
            }
        })
    };

    //Adds an article with it's article id
    //to the current compare list
    $.compare.addCompare = function (url) {
        $.ajax({
            'dataType': $.compare.options.dataType,
            'type': $.compare.options.requestType,
            'url': url,
            'beforeSend': function() {
              	$.loadingIndicator.open({'loadingText': 'Artikel wird hinzugefügt...'});
            },            
            'complete': function (result) {
              $.loadingIndicator.close();
            	$.compare.options.compareCount = $.compare.options.compareCount + 1;
            	if($.compare.options.compareCount > $.compare.options.maxCount) {
            	
            		var width = 500;
            		var position = 'fixed';
            		
            		if($.browser.msie && parseInt($.browser.version) == 6) {
						width += 2;
						position = 'absolute';
					}
		            $.modal(result.responseText, '', {
		        		'position': position,
		        		'width': width+'px',
		        		'textContainer': '<div>',
		        		'textClass': 'ajax_compare_max_container'
		        	});
		        	$.compare.options.compareCount = $.compare.options.maxCount;
		        	return;
            	}
	            $($.compare.options.ajaxContainer).html(result.responseText);  
//                window.location = $.compare.options.topLink;

              if ($.browser.opera) {
                  var target = 'html';
              }else{
                  var target = 'html,body';
              }

	          	$(target).animate({
		                             	scrollTop: $($.compare.options.topLink).offset().top
	                            	}, 2000 , function (){
                                                       location.hash = $.compare.options.topLink;
                                                    //   $($.compare.options.compareHighlight + ' span').animate({ backgroundColor: "black" }, 1000);

                                                       $($.compare.options.compareHighlight + ' span').effect("highlight", {}, 3000);
                                                     });     


            }
        })
    }; 
})(jQuery);


// ==================  * Comparison *  ======================
(function($) {
    $.jq = function(myid) { 
      return myid.replace(/(:|\.)/g,'\\$1');
    }


    $.refreshRelatedArticle = function () {
        var relatedOrdernumbers = '';
        var totalPrice = $('#selected_articel_price').val();
        
        $('input[class=relatedOrdernumber]').each(function (i, item) {
            var tmpOrdernumber = $(item).val();                           
            var tmpContainerName = '#related_' + $.jq(tmpOrdernumber) + '_image';
            var tmpPlusiconName = '#related_' + $.jq(tmpOrdernumber) + '_plus';
            var tmpPriceName = '#' + $.jq(tmpOrdernumber) + '_price';
            var checkbox = $('#' + $.jq(tmpOrdernumber) + '_related_checkbox');
            if (checkbox.is(':checked')) {
                $(tmpContainerName).fadeIn('fast');
                $(tmpPlusiconName).fadeIn('fast');
                if ('' == relatedOrdernumbers) relatedOrdernumbers = tmpOrdernumber;
                else relatedOrdernumbers += ';' + tmpOrdernumber;
                var tmpPrice = $(tmpPriceName).val();
                if (tmpPrice) totalPrice = eval(totalPrice) + eval(tmpPrice)
            } else {
                $(tmpContainerName).fadeOut('fast');
                $(tmpPlusiconName).fadeOut('fast');
            }
        });
        $('#sRelatedOrdernumbers').val(relatedOrdernumbers);
        $('#price_relatedbundle').html($.number_format(totalPrice, 2, ',', '.'));
    };
 
    
})(jQuery);      

