//var console = { profile : function() {}, profileEnd : function() {} };

//Führt bei IE 7 zu Zertifikatsproblem
//jQuery(window).load(function(){
//  var e = document.createElement("script");
//  e.setAttribute("type", "text/javascript");
//  e.setAttribute("src", "http"+("https:"==document.location.protocol?"s":"")+"://browser-update.org/update.js");
//  document.body.appendChild(e);
//});

jQuery(document).ready(function(){
  if (typeof(ie6) != "undefined") { document.location.href = shop.absoluteBaseUrl+'browserError'; }

  // initial call and interval for the sunset function (updated every minute)
  global.sunset('#sunset p');
  window.setInterval( function() { global.sunset('#sunset p'); }, 60000 );

  // init content tabs
  jQuery('div.tabs_type1 > ul').superSimpleTabs();
  jQuery('div.tabs_type2 > ul').superSimpleTabs();

  // init select boxes only if not ie6
  //if (typeof(ie6) == "undefined") { jQuery('select.improved').sSelect(); }

  // init article comparison
  global.initArticleComparison('#article_comparison');

  // init carousel
  global.initCarousel('div.carousel div.js,div.carousel2 div.js');

  // init navigation
  global.initNavigation();

  // turn select boxes into slider
  global.initSlider();

  // handle ext. filter boxes
  global.initFilter();

  // init contentSliderDetails
  global.initAccordion();

  // handle overlay boxes
  global.initOverlay();

  // handle tooltips
  global.initTooltip();

  // handle modals
  global.initModal('div.overlay_items div.modalOverlay'); //nmAG - Selector changed

  // passwordstrength
  global.initPasswordStrength();

  // passwordstrength
  global.initStarRater('#article_detail_third_row div.star_rater');

  // checkout settings overlay
  global.checkoutSettings();

  // social bookmark icons
  global.initSocial();

  global.initRadioSlider();

  // autosized selector box
  global.initSelectorSize();
});

var global = {

  finishDesigner : function() {
    alert("Finish Designer");
  },

  sunset : function(selector) {
    var now = new Date;

    astronomy.init(53.5, 10, now);
    var sunset = astronomy.sunset();

    // get time difference in minutes
    var difference = sunset.getTime() - now.getTime();
    var difference = difference/1000/60;

    // get time diff
    var hours = Math.floor(difference/60);
    var minutes = Math.round(difference % 60);

    if (typeof jQuery(selector).data('sunset_string') == 'undefined') {
      jQuery(selector).data('sunset_string', jQuery(selector).html());
    }
    var html = jQuery(selector).data('sunset_string');
    if (html) {
      html = html.replace(/\[hours\]/, hours);
      html = html.replace(/\[minutes\]/, minutes);

      if (difference > 0) jQuery(selector).html(html).show();
    }
  },

  initArticleComparison : function(el_root) {
    var el_root   = jQuery(el_root);

    if (el_root.length == 0) return;

    var el_fields = jQuery('div.fields', el_root);
    var el_target = jQuery('ul.js_target', el_root);

    // get count for attributes
    var fields_count = jQuery('li', el_fields).length;

    // adjust heights of all li's
    // line for line
    for (var i=1; i<=fields_count; i++) {
      var max_height = 0;
      var hits = jQuery('> li:nth-child('+i+')', el_target).each(function() {
        var height = jQuery(this).innerHeight()-10; // 10px because of the padding of 5px at the top and bottom
        max_height = Math.max( height, max_height);
      });
      jQuery('ul.js_target:gt(0) > li:nth-child('+i+')', el_root).height(max_height);
      jQuery('ul.js_target:eq(0) > li:nth-child('+i+') div', el_root).height(max_height);
    }

    // add "show all attributes"
    el_fields.children('a').each(function() {
      jQuery(this).click(function(e) {
        e.preventDefault();
        jQuery('> li', el_target).show();

        // IE 7 Bug
        // http://stackoverflow.com/questions/33837/ie-css-bug-how-do-i-maintain-a-positionabsolute-when-dynamic-javascript-conten
        $('#canvas_base3 div.content_footer').css('display', 'none');
        $('#canvas_base3 div.content_footer').css('display', 'block');
      });
    });

    // add "hide attribute" feature to links
    jQuery('li a', el_fields).each(function(index) {
      jQuery(this).click(function(e) {
        e.preventDefault();
        jQuery('> li:nth-child('+(index+1)+')', el_target).hide();

        // IE 7 Bug
        // http://stackoverflow.com/questions/33837/ie-css-bug-how-do-i-maintain-a-positionabsolute-when-dynamic-javascript-conten
        $('#canvas_base3 div.content_footer').css('display', 'none');
        $('#canvas_base3 div.content_footer').css('display', 'block');
      });
    });
  },

  initSlider : function() {
		$('div.slider').each(function() {
			var el = $(this);
			var el_option_min = el.find('.min');
			var el_option_max = el.find('.max');
			var el_option_handle = el.find('.handle');
			var el_option_handle2 = el.find('.handle2');

			// default options
			var slider_options = {
				step: 1,
				min: parseInt(el_option_min.text()),
				max: parseInt(el_option_max.text())
			};

			// set options
			// multirange slider
			if (el_option_handle2.length > 0)	{
				slider_options.range = true;
				slider_options.values = [ parseInt(el_option_handle.text()), parseInt(el_option_handle2.text()) ];
				slider_options.slide = function(event, ui) {
					el_option_handle.text( ui.values[0] );
					el_option_handle2.text( ui.values[1] );
					el_handle.html( ui.values[0] + '&nbsp;&#x20ac;');
					el_handle2.html( ui.values[1] + '&nbsp;&#x20ac;');
				};
			}
			// simple slider
			else {
				slider_options.value = parseInt(el_option_handle.text());
				slider_options.slide = function(event, ui) {
					el_option_handle.text( ui.value );
					el_handle.html( ui.value + '&nbsp;&#x20ac;');
				};
			}

			// hide the divs
			el.find('div').hide();

			// create slider
			var el_slider = $('<div></div>');
			el_slider.slider( slider_options );

			var el_handle = el_slider.find('a.ui-slider-handle:first');
			var el_handle2 = el_slider.find('a.ui-slider-handle:last');

			// append slider
			el_slider.appendTo( $(this) );

			// append go button
			var goButton = $('<a href="#" class="slider-submit">go</a>');
			goButton.bind('click', function printHandleValues() {
			  var min = el_handle.text().split('\xa0')[0];
			  var max = el_handle2.text().split('\xa0')[0];
			  var cur = $('div.slider').find('div.currency').text();
			  var gesamt = min + ' ' + cur + '-' + max + ' ' + cur;

			  shopAction.changeFilter(gesamt);
			});
			goButton.appendTo( $(this) );

			// update display
			el_handle2.addClass('ui-slider-handle-last').html( el_option_handle2.text() + '&nbsp;&#x20ac;');
			el_handle.addClass('ui-slider-handle-first').html( el_option_handle.text() + '&nbsp;&#x20ac;');
		});
	},

  initNavigation : function() {
    var el_navi = jQuery('#navi > ul > li');

    if (el_navi.length == 0) return;

    jQuery('> a', el_navi).click( function(e) {
      e.preventDefault();

      // do not trigger action at click on the active element
      if (jQuery(this).hasClass('active')) return;

      // hide all open lists
      jQuery('> ul', el_navi).slideUp().prev().removeClass('active');

      // open clicked list
      jQuery(this).addClass('active').next().slideDown();

      // close search
      jQuery('#search > form > a').removeClass('active').next().slideUp();
    });
    jQuery('> ul', el_navi).hide();
    jQuery('#navi a.active').next().show();
  },

  initCarousel : function(divs) {
    jQuery(divs).each( function() {
      var el_carousel = jQuery(this).parent();

      el_carouselParent = el_carousel.parent();
      if (el_carouselParent == null || el_carouselParent.hasClass("hidden")) {
        return false;
      }

      var el_prev = el_carousel.find('a.prev');
      var el_next = el_carousel.find('a.next');
      var el_first = jQuery('> ul > li:first-child', this).get(0);
      var el_last = jQuery('> ul > li:last-child', this).get(0);
      var el_lis = jQuery('> ul > li', this);

      var carousel_class = el_carousel.attr('class');
      if (carousel_class == 'carousel') {
        var visible = 4;
      } else if (carousel_class == 'carousel2') {
        var visible = 3;
      }

      // hide "previous" because we start with the first item
      el_prev.hide();

      // a special case if there are less elements as should be visible
      if (el_lis.length <= visible)
        {
        // should we hide "next"
        el_next.hide();

        // adjust widths of li's
        var width = Math.floor(el_carousel.width() / el_lis.length - 10);
        $(el_lis).width(width);
        }

      // actions on next/previous buttons
      el_prev.click(function(e) { e.preventDefault(); });
      el_next.click(function(e) { e.preventDefault(); });

      // add carousel
      jQuery(this).jCarouselLite({
        btnNext: el_next,
        btnPrev: el_prev,
        visible: visible,
        scroll: 1,
        afterEnd: function(visible_elements) {
          // callback to fade in/out prev/next buttons
          el_prev.fadeIn();
          if (el_first == visible_elements[0]) el_prev.fadeOut();
          el_next.fadeIn();
          if (el_last == visible_elements[visible_elements.length-1]) el_next.fadeOut();
        },
        circular: false
      });
    });
  },

  initFilter : function () {
    jQuery("div.filterContainer").each( function() {
      var filterContainer = jQuery(this);
      var filterContent = jQuery(this).find('div.filterContent');
      var filterOpen    = jQuery(this).find('.filter_open');
      var filterClose   = jQuery(this).find('.filter_close');
      var filterReset   = jQuery(this).find('.filter_reset');

      // clickevents
      filterClose.click(function (e) {e.preventDefault(); filterContent.slideUp(function() {filterOpen.show(); filterClose.hide();});});
      filterOpen.click(function (e) {e.preventDefault(); filterContent.slideDown(function() {filterOpen.hide(); filterClose.show();});});
      filterReset.click(function (e) {
        e.preventDefault();

        jQuery("div.filter").each( function() {
          var clearForm = jQuery(this).find('form');
          global.clearForm(clearForm);
        });

      });

      // handle startup behaviour
      if (filterContainer.hasClass('contentOpen')){
        filterContent.show();
        filterOpen.hide();
      } else {
        filterContent.hide();
        filterClose.hide();
      }


    });
  },

  initAccordion : function () {

    jQuery('#article_detail_third_row ul.accordion li').each( function() {
      var sliderBorder  = jQuery(this);
      var sliderLink    = sliderBorder.find('div a:eq(0)');
      var sliderContent = sliderBorder.find('div.content');

      sliderLink.click(function (e) {
        e.preventDefault();

        if (!sliderBorder.hasClass('sliderOpen')) {
          sliderBorder.addClass('sliderOpen');
          var skip = true;
        } else {
          var skip = false;
        }

        sliderContent.slideToggle('fast', function(){
          if (skip == false) {
            sliderBorder.toggleClass('sliderOpen');
          }
        });
      });

    });
  },

  initOverlay : function () {
    jQuery("div.articleMouseover").each( function() {
      var articleMouseover  = jQuery(this);
      var articleParent   = articleMouseover.parent();
      var articleContainer    = articleParent.parent().parent().parent();

      articleMouseover.css('visibility', 'hidden');
      articleMouseover.css('display', 'block');
      articleMouseover.css('display', 'none');
      articleMouseover.css('visibility', 'visible');

      articleParent.mouseenter(function(){
        articleParent.css('z-index', 9999);
        articleMouseover.css('visibility', 'hidden');
        articleMouseover.css('display', 'block');

        var offsetMouseover   = articleMouseover.offset();
        var dimensionMouseover  = { width: articleMouseover.outerWidth(), height: articleMouseover.outerHeight() };
        var offsetContainer   = articleContainer.offset();
        var dimensionContainer  = { width: articleContainer.outerWidth(), height: articleContainer.outerHeight() };

        articleMouseover.css('display', 'none');
        articleMouseover.css('visibility', 'visible');

        if(offsetMouseover.left < offsetContainer.left) {
          articleMouseover.css('left', '-' + (parseInt(articleParent.parent().css('padding-left')) + 6)  + 'px');
          articleMouseover.css('margin-left', 'auto');
        }

        if(offsetMouseover.left + dimensionMouseover.width > offsetContainer.left + dimensionContainer.width) {
          articleMouseover.css('left', 'auto');
          articleMouseover.css('right', '-' + (parseInt(articleParent.parent().css('padding-right')) + 5)  + 'px');
          articleMouseover.css('margin-left', 'auto');
        }

        /*if(offsetMouseover.top < offsetContainer.top) {
          articleMouseover.css('top', '-' + (articleParent.offset().top - articleParent.parent().offset().top + 6)  + 'px');
          articleMouseover.css('margin-top', 'auto');
        }

        if(offsetMouseover.top + dimensionMouseover.height > offsetContainer.top + dimensionContainer.height) {
          articleMouseover.css('top', 'auto');
          articleMouseover.css('bottom', '-' + ((articleParent.parent().offset().top + parseInt(articleParent.parent().outerHeight())) - (articleParent.offset().top + parseInt(articleParent.outerHeight())) + 5) + 'px');
          articleMouseover.css('margin-top', 'auto');
        }*/

        articleMouseover.fadeIn("normal");
      }).mouseleave(function(){
        articleMouseover.fadeOut("normal", function() {
          articleParent.css('z-index', '')
        });
      });
    });
  },

  /*
  initTooltip : function(e) {
    $('body').append('<div id="tooltip"><div class="inner"><div class="headline">Info</div><div class="content">Test</div></div></div>');
    var el_tooltip = $('#tooltip');
    var el_tooltip_content = $('.content', el_tooltip);

    $('a.tooltip').each(function() {
      var el_trigger = $(this);

      // copy title content to data object
      el_trigger.data('title', el_trigger.attr('title')).removeAttr("title");

      // add events
      el_trigger
        .mouseover(function() {
          el_tooltip_content.text( el_trigger.data('title') );
          el_tooltip.show();
        })
        .mousemove(function(e) {
          var top = e.pageY - el_trigger.height() - el_tooltip.height() - 25; // 25 because of the sliding door padding
          var left = e.pageX - 125; // 125 because of the width of 250px
          el_tooltip.css( { left: left, top: top } );
        })
        .mouseout(function() {
          el_tooltip.hide();
        });
    });
  },
  */
  initTooltip : function(e) {
    jQuery('body').append('<div id="tooltip"><div class="inner"><div class="headline">Info</div><div class="content">Test</div></div></div>');
    var el_tooltip      = jQuery('#tooltip');
    var el_tooltip_content  = jQuery('.content', el_tooltip);
    var viewport      = getPageScroll();


    jQuery('a.tooltip').each(function() {
      var el_trigger = jQuery(this);

      // copy title content to data object
      el_trigger.data('title', el_trigger.attr('title')).removeAttr("title");

      // add events
      el_trigger
        .mouseover(function() {
          // update viewport scroll position
          viewport = getPageScroll();

          el_tooltip_content.text( el_trigger.data('title') );
          el_tooltip.show();

        })
        .mousemove(function(e) {
          var top;

          // determine distance to viewports top boundary
          var topEdge = e.pageY - el_tooltip.height() - el_trigger.height() - 25;

          if(topEdge - viewport[1] < 0) {
            top = e.pageY + el_trigger.height() + 15;
            jQuery(el_tooltip).addClass('below');
          } else {
            top = e.pageY - el_trigger.height() - el_tooltip.height() - 25; // 25 because of the sliding door padding
            jQuery(el_tooltip).removeClass('below');
          }

          var left = e.pageX - 125; // 125 because of the width of 250px
          el_tooltip.css( { left: left, top: top } );
        })
        .mouseout(function() {
          el_tooltip.hide();
        });
    });

    function getPageScroll() {
      var xScroll, yScroll;
      if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
      } else if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
      } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;
      }

      return new Array(xScroll,yScroll)
    }

  },

  initModal : function(selector) {
    var overlay = jQuery(selector);

    if (overlay.length == 0) return;

    overlay
      .css({ display: 'none', visibility: 'visible' })
//      .appendTo('body')
        .find('a.jsclose').click(function(e) { e.preventDefault(); });

    jQuery(".modalSwitch a[rel]").each(function() {
      api = $(this).overlay({
        absolute: false,
        top: 'center',
        zIndex: 10002,
        close: 'a.jsclose',
        api: true,
        expose: {
          color: '#000',
          loadSpeed: 'normal',
          opacity: 0.1,
          zIndex: 10001
        }
      });

      if (api.getOverlay().hasClass('open')) api.load();
    });
  },

  clearForm : function(form) {
    jQuery(':input', form).each(function() {
      var type  = this.type;
      var tag   = this.tagName.toLowerCase();

      if (type == 'text' || type == 'password' || tag == 'textarea') {
        this.value = "";
      } else if (type == 'checkbox' || type == 'radio') {
        this.checked = false;
      }

    });

    jQuery(':select', form).each(function() {
      var tag   = this.tagName.toLowerCase();
      if(tag=='select'){
        // reset form elements
        this.selectedIndex = 0;

        // update stylish select box as well
        var resetValue = this.options[this.selectedIndex].text;
        jQuery('select.improved').getSetSSValue(resetValue);
      }
    });

  },

  passwordStrength : function(password){
    var score = 0;
    score += password.length * 4;
    if (password.match(/(.*[0-9].*[0-9].*[0-9])/)){ score += 5;}
    if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)){ score += 5 ;}
    if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)){  score += 10;}
    if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)){  score += 15;}
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/)){  score += 15;}
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/)){score += 15;}
    if (password.match(/^\w+$/) || password.match(/^\d+$/) ){ score -= 10;}

    //verifying 0 < score < 100
    if ( score < 0 )  {score = 0;}
    if ( score > 100 )  {score = 100;}

    return score;
  },

  initStarRater : function(selector) {

    var value = -1;
    var el_root   = $(selector);

    if (el_root.length == 0) return;

    var el_select = $('select', el_root);
    var el_list   = $('<ul></ul>');
    var el_value  = $('<div></div>');

    // create html construct
    el_root.append( el_list ).append(el_value);

    // hide old select
    el_select.addClass('hidden');

    // create list elements from options
    var values = new Array();
    $('option:gt(0)', el_select).each(function() {
      el_list.append(
        $('<li />').text($(this).text())
      );
    });
    var els_li = $($('li', el_list));

    // global function to update star visualization
    var update = function(index) {
      els_li.removeClass('active');
      els_li.filter(':lt('+(index+1)+')').addClass('active');
      el_value.text( els_li.eq(index).text() );
    };

    // add mousemove control
    els_li
      .mousemove(function(e) { update( els_li.index(e.target) ); })
      .click(function(e) {
        value = els_li.index(e.target);
        el_select.children().removeAttr('selected');
        el_select.children(':eq('+(value+1)+')').attr('selected', 'selected');
      });

    // set to actual value
    el_list.mouseleave(function() { update( value ); });

  },

  initPasswordStrength : function() {

    jQuery('.checkstrength').keyup(function() {
      var score = (global.passwordStrength((this).value) * 2);
      jQuery('#pwSecure1').css('width', score);
    });
  },


        initSocial : function() {

            var output      = '';
            var pageUrl     = encodeURIComponent(location.href);
            var pageTitle   = encodeURIComponent(document.title);
            var imagePath               = 'images/icons/'
            var shareObjects  =
                {"google": {
                    "url":"http://www.google.com/bookmarks/mark?op=add&hl=de&bkmk=" + pageUrl + "&annotation=&labels=&title=" + pageTitle,
                    "icon": imagePath + "social_google.gif",
                    "options":""
                    },
                "delicious": {
                    "url":"http://delicious.com/save?v=5&noui&jump=close&url=" + pageUrl + "&title=" + pageTitle,
                    "icon":"images/social_delicious.gif",
                    "options":"toolbar=no,width=550,height=550"
                },
                "twitter": {
                    "url":"http://twitter.com/home?status=Currently reading " + pageTitle + " (" + pageUrl + ")",
                    "icon":"images/social_twitter.gif",
                    "options":""
                },
                "mrwong": {
                    "url":"http://www.mister-wong.de/index.php?action=addurl&bm_url=" + pageUrl + "&bm_description=" + pageTitle,
                    "icon":"images/social_mrwong.gif",
                    "options":""
                },
                "facebook": {
                    "url":"http://www.facebook.com/sharer.php?u=" + pageUrl + "&t=" + pageTitle,
                    "icon":"images/social_facebook.gif",
                    "options":"toolbar=0,status=0,width=626,height=436,resizable=yes,scrollbars=yes"
                }

            };

            for (var key in shareObjects) {
                output = output + '<a class="social social_' + key + '" href="#" onclick="javascript:window.open(\'' + shareObjects[key]['url'] + '\', \'' + key + '\', \'' + shareObjects[key]['options'] + '\');return false;">' + key + '</a>';
            }

            jQuery('#socialIcons').html(output);

        },

        checkoutSettings : function () {
            if (jQuery("#overlayDeliveryOptions").length == 0) return;

            // Usage:
            // input radio name=delivery_address with value=delivery_address_shop disables:
            // radio=payment_method with value=payment_method_cash[, "or_any_other_additional_value"]
            var radioDisable = {};
            radioDisable.delivery_address = {'delivery_address_shop': {'payment_method': ['payment_method_cash']}};

            jQuery('fieldset.sourceSelector input:radio').each(function() {
               jQuery(this).click(function (e) {
                   handleState(this);
               });
            });

            function handleState(sourceElement) {
                // enable all
                jQuery('fieldset.targetSelector input:radio').removeAttr('disabled');

                for (var sourceValue in radioDisable[sourceElement.name]) {
                    if (sourceElement.value == sourceValue) {
                        // the element clicked is in definition and should disable something
                        for (var targetElement in radioDisable[sourceElement.name][sourceValue]) {
                            for (var targetValue in radioDisable[sourceElement.name][sourceValue][targetElement]) {
                                // finally
                                var v = radioDisable[sourceElement.name][sourceValue][targetElement][targetValue];
                                var jTargetElement = jQuery('fieldset.targetSelector input[name=' + targetElement + ']');

                                jTargetElement.each(function() {
                                    if (this.value == v) {
                                        jQuery(this).attr('disabled', true);
                                        this.checked = false;
                                    }
                                });
                            }
                        }
                    }
                }
            }




        },

        initRadioSlider : function () {

            jQuery('div.radioSlider').each(function() {

                var radio       = jQuery(this).find('input:radio');
                var sliderDiv   = jQuery(this).find('div.slideable');

                // initially hide every slider that has no open class
                // and check the radio box of opened boxes
                if (sliderDiv.hasClass('open')) {
                    radio.attr('checked', true);
                } else {
                    sliderDiv.hide();
                }

                radio.click(function() {
                   // in case this div is already open (has class "open") do nothing
                   if (!sliderDiv.hasClass('open')) {
                       // close all
                       jQuery('input:radio[name=' + this.name + ']').closest('div.radioSlider').find('div.slideable').each(function() {
                           jQuery(this).slideUp();
                           jQuery(this).removeClass('open');
                       });

                       sliderDiv.slideDown();
                       sliderDiv.addClass('open');
                   }
                });
            });

        },

        initSelectorSize : function () {
          // All browsers are capable of handling the size of dropdowns well
          // exept ie. Workaround makes dropdowns look ugly (arrow invisible),
          // so use this function only in ms browsers
          var userAgent = navigator.userAgent.toLowerCase();

          if (/msie/.test( userAgent ) && !/opera/.test( userAgent )) {

            jQuery('select.autoSize').each(function () {
              // save size for reset
              var initSize = jQuery(this).width();

              // bind events
              jQuery(this).bind('focus', autoSize);
              jQuery(this).bind('mousedown', autoSize);

              jQuery(this).bind('blur', {size:initSize}, fixedSize);
              jQuery(this).bind('change', {size:initSize}, fixedSize);
            });

          }

          function autoSize(e)    { jQuery(this).width('auto');}
          function fixedSize(e)   { jQuery(this).width(e.data.size);}
        }

};
