/*-----------------------------------------

 copyright 2020 by mmc:agentur

 Version: 1.0

 Author: David Rerych

 Author URI: http://www.mmc-agentur.at

 -------------------------------------------*/



$(document).ready(function(){

    // for browsers that don't support placeholder text
    $('input[type="text"]').mmcFormDefaults();
    
    //$('[data-swf]').swfElement();

    //$('.csc-sitemap ul').jQuerySitemap('closed', 'vertical');
    if ($('.csc-sitemap').attr('class')){
        jquerySitemap('.csc-sitemap ul', 'closed', 'vertical');
    }

	// Sprache
	$('#sprache').change(function(){
		var link = $(this).val();
		/*
		var base = jQuery("base").attr("href");
		if(base == "undefined")
		{
			base = "";
		}
		
		*/
		window.location.href = link;
		
	});
    
    cycleTeaser();
    
    bigCycle();

    projektCycle();
    
    
    locations.init();
    
    locations.overviewMap();
    
    
    references.init();
          
    
    /* Akkordions */
   $('#content .accordion').each(function(){
       if ($('body').hasClass('ie7')){
            $('.acc_header', this).toggle(
                function() {
                    $(this).removeClass('closed').next().show();
                    return false;
                },
                function() {
                    $(this).addClass('closed').next().hide();
                    return false;
                }
            ).addClass('closed').next().hide();
        }
        else {
            $('.acc_header', this).toggle(
                function() {
                    $(this).removeClass('closed').next().slideDown(300,'linear',function(){
                    });
                    return false;
                },
                function() {
                    $(this).addClass('closed').next().slideUp(300,'linear',function(){
                    });
                    return false;
                }
            ).addClass('closed').next().hide();
        }
    });

    /*$('#content .accordion').each(function(){
        $('.acc_header', this).toggle(
            function() {
                $(this).removeClass('closed').next().slideDown(300,'linear',function(){
                });
                return false;
            },
            function() {
                $(this).addClass('closed').next().slideUp(300,'linear',function(){
                });
                return false;
            }
        ).addClass('closed').next().hide();
    });*/
    
    
    
  // lightbox -> mmcMediabox
  mediabox.init();
  
  
  
  // Maschinenbörse addToBasket --> AJAX
  
  machineryMarket.addToCart.init();
  
  
  // Maschinenbörse Detailseite und Aktuelle Angebote - Klasse "odd" (ungerade) bei Tabelle
  $('.detailansicht table.technische_daten tr:nth-child(odd), .angebote_wrap .data table tr:nth-child(odd)').addClass('odd');



});

var mediabox = {};
mediabox.init = function() {
    mediabox.instance = $(".lightbox").mmcMediabox({
      labels: {
        close : 'schlie&szlig;en',
        next: 'weiter',
        prev: 'zur&uuml;ck',
        item: 'Bild',
        of: '/',
        download: 'Download'
      },
      infoArea: {
        title: function($el) {
          var title = typeof $el.attr('title') == 'undefined' ? '' : $el.attr('title');
          var author = typeof $el.attr('data-author') == 'undefined' ? '' : $el.attr('data-author');
          return ' <span class="title"><span class="caption">'+title+'</span><br /><span class="author">'+author+'</span></span>';
        },
        counter: function($el) {
          var infoAreaCounter = '<span class="numberDisplay"><span class="item">'+$el.o.labels.item+'</span> <span class="current">'+parseInt($el.idx+1, 10)+'</span>&nbsp;'+$el.o.labels.of+'&nbsp;<span class="total">'+this.currentImageset.length+'</span></span>';
          return infoAreaCounter;
        }        
      }
    });
}
mediabox.reInit= function() {
  mediabox.instance.mmcMediabox('destroy');
  mediabox.init();
}

function cycleTeaser() {
	
	var $cycleTeaser = $('.teaser ul.cycle');
	if ($cycleTeaser.find('li').length > 1) {
		
		$cycleTeaser.cycle({
			timeout: 8000,
			speed: 1000,
			fx: 'scrollHorz',
			after: onAfter,
			before: onBefore,
			cleartypeNoBg: true
		});
	}

	function onAfter(currSlideElement, nextSlideElement, options, forwardFlag){
		$cycleTeaser.find('li span, p').fadeIn();
	}
	function onBefore(currSlideElement, nextSlideElement, options, forwardFlag){
		$(currSlideElement).find('span, p').fadeOut();
		$(nextSlideElement).find('span, p').hide();
	}
	
	
}


function bigCycle() {
	var $big_cycle = $('.big_cycle_wrap ul');
	
    var $img_description = $big_cycle.find('.img_description');
    if($img_description.text() == ''){
        $img_description.remove();
    }  
	
	if ($big_cycle.find('li').length > 1) {
		var $prev = $('<div class="prev"></div>').insertAfter($big_cycle);
		var $next = $('<div class="next"></div>').insertAfter($prev);
		var $pager = $('<div class="big_cycle_pagination" />').insertAfter($next);
		
		$big_cycle.cycle({
			timeout: 8000,
			speed: 1000,
			fx: 'scrollHorz',
			after: onAfter,
			before: onBefore,
			next: $next,
			prev: $prev, 
			cleartypeNoBg: true, 
			pager: $pager
		});
	}

	function onAfter(currSlideElement, nextSlideElement, options, forwardFlag){
		$big_cycle.find('li span.img_info').fadeIn();
	}
	function onBefore(currSlideElement, nextSlideElement, options, forwardFlag){
		$(currSlideElement).find('.img_info').fadeOut();
		$(nextSlideElement).find('.img_info').hide();
	}

}



function projektCycle() {
  var $projekt_cycle = $('.projekt_cycle_wrap ul');
  
  var $img_description = $projekt_cycle.find('.img_description');
  if($img_description.text() == ''){
      $img_description.remove();
  }  
  
  if ($projekt_cycle.find('li').length > 1) {
    var $prev = $('<div class="prev"></div>').insertAfter($projekt_cycle);
    var $next = $('<div class="next"></div>').insertAfter($prev);
    var $pager = $('<div class="projekt_cycle_pagination" />').insertAfter($next);
    
    $projekt_cycle.cycle({
      timeout: 8000,
      speed: 1000,
      fx: 'scrollHorz',
      after: onAfter,
      before: onBefore,
      next: $next,
      prev: $prev, 
      cleartypeNoBg: true, 
      pager: $pager
    });
  }

  function onAfter(currSlideElement, nextSlideElement, options, forwardFlag){
    $projekt_cycle.find('li span.img_info').fadeIn();
  }
  function onBefore(currSlideElement, nextSlideElement, options, forwardFlag){
    $(currSlideElement).find('.img_info').fadeOut();
    $(nextSlideElement).find('.img_info').hide();
  }

}



var locations = {};


locations.init = function() {
  var that = this;

  this.$selector = $('#standort_selection');
  this.$map = $('.standort .map');
  
  if (this.$selector.length < 1) {
    return false;
  }
  
  this.$loading_indicator = $('<div class="loading_indicator"><div></div></div>').appendTo(this.$selector).hide();
  
  this.loading = false;
  
  var url_state_name = 'loc_filter';
  var url_city_name = 'loc_city';
  
  var url_states = {}, old_url_states = {};


  locations.initScrollPane();

  $(this.$selector.selector+' #stadt a, '+this.$selector.selector+' #unternehmen a, '+this.$selector.selector+' #standort_reset a').live('click',function(e){
    e.preventDefault();
    e.stopPropagation();
    
    var $this = $(this);

    if (that.loading) {
      return false;
    }

    var cityID = $this.attr('data-city');
    $this.parent().toggleClass('selected').siblings().removeClass('selected');

    var $location_a_tags = that.$selector.find('a').add(that.$map.find('a'));
    var $active_parents = $location_a_tags.filter('a[data-city="'+cityID+'"]').parent();
  
    if (cityID != '') {
      $active_parents.addClass('selected').siblings().removeClass('selected');
    } else {
      $location_a_tags.parent().removeClass('selected');
    }

    var url = $this.attr('href').replace( /^#/, '' );

    locations.reload(url);
    return false;
  });
  
  this.$map.find('a').click(function(e){
    e.preventDefault();
    var $twinInSelection = that.$selector.find('a[data-city="'+$(this).attr('data-city')+'"]');
    $twinInSelection.click();
    return false;
  });


  if (typeof history.replaceState === 'function') {
    history.replaceState({url: location.href}, '', location.href);
  }

  window.onpopstate = function(event) {
     if (typeof event.state !== 'undefined' && event.state !== null && typeof event.state.url !== 'undefined') {
         locations.reload(event.state.url, true);
     }
  };

}



locations.reload = function(url, isHistoryEvent) {
  var that = this;
  that.loading = true;


  isHistoryEvent = typeof isHistoryEvent === 'undefined' ? false : isHistoryEvent;

  if (!isHistoryEvent && typeof history.pushState === 'function') {
    history.pushState({url: url}, '', url);
  }


  that.$loading_indicator.fadeIn(200, function() {
  
      url = url.indexOf('?') < 0 ? url + '?type=9' : url + '&type=9';
      
      $.get(url, function(resp) {
    
        var $resp = $(resp.replace(/<script(.|\s)*?\/script>/gi, ''));
        
        that.$selector.find('.section').each(function(index, el){
          var new_markup = $resp.find(that.$selector.selector).find('.section').eq(index).html();
          $(this).html(new_markup);
        });
        that.$selector.find('#stadt, #unternehmen').each(function(){
          var $this = $(this);
          $this.height(that.$selector.find('#adr.section').height());
        });
        that.loading = false;
        that.$loading_indicator.fadeOut(200);
        
        var cityID = that.$selector.find('#stadt .selected a').attr('data-city');
        that.$map.find('.selected').removeClass('selected');
        that.$map.find('a[data-city="'+cityID+'"]').parent().addClass('selected');
        
        locations.initScrollPane();
        
      });
  
  });
  
}



locations.initScrollPane = function() {
  var that = this;
  that.$selector.find('#stadt .wrapper, #unternehmen .wrapper').each(function(){
    var $this = $(this);
    var scrollPaneElement = $this.jScrollPane({
      showArrows: true
    });
    var scrollPaneApi = scrollPaneElement.data('jsp');
    scrollPaneApi.scrollToY(0);
    var $selected = $this.find('.selected').length > 0 ? $this.find('.selected') : null;
    if ($selected != null) {
      scrollPaneApi.scrollToElement($selected);
    }
  });  
}



locations.overviewMap = function() {
  
  if ($('#europemap').lenght < 1) {
    return false;
  }
  
  $('#europemap area').data('maphilight', {
    alwaysOn: true,
    fillColor: '203F70'
  });
  $('#europemap area').hover(function(){
    $(this).data('maphilight', {
      fillColor: '4d6cad'
    });
  });

  
  $('.map').maphilight({
    fill: true,
    fillColor: '4d6cad',
    fillOpacity: 1,
    strokeColor: 'ffffff',
    strokeWidth: 0.6
  });
}










var references = {};


references.init = function() {
  var that = this;

  this.$selector = $('#project_selection');
  this.$results = $('#project_results');
  
  
  if (this.$selector.length < 1) {
    return false;
  }
  
  this.$loading_indicator = $('<div class="loading_indicator"><div></div></div>').appendTo(this.$selector).hide();
  this.$loading_indicator_results = $('<div class="loading_indicator"><div></div></div>').appendTo(this.$results).hide();
  
  this.loading = false;
  
  var url_state_name = 'loc_filter';
  var url_city_name = 'loc_city';
  
  var url_states = {}, old_url_states = {};

  references.initScrollPane();

  $(this.$selector.selector+' .wrapper a, '+this.$selector.selector+' #project_reset a').live('click',function(e){
    e.preventDefault();
    e.stopPropagation();
    
    var $this = $(this);

    if (that.loading) {
      return false;
    }

    $this.parent().toggleClass('selected').siblings().removeClass('selected');

    var url = $this.attr('href').replace( /^#/, '' );

    references.reload(url, true);
    
    return false;
  });
  
  $(this.$results.selector+' a.next, '+this.$results.selector+' a.prev, '+this.$results.selector+' a.back, '+this.$results.selector+' #projekte_vorschau>ul>li>a').live('click',function(e){
    e.preventDefault();
    var $this = $(this);
    if (that.loading) {
      return false;
    }
    
    var url = $this.attr('href').replace( /^#/, '' );
    
    references.reload(url, false);
  
    return false;
  });
  
  $(this.$selector.selector + ' #volltextsuche form').live('submit',function(e){
    e.preventDefault();
    var url = $(this).attr('action');
    url = url.indexOf('?') < 0 ? url + '?' : url + '&';
    url += $(this).serialize();
    references.reload(url, false);
    return false;
  });
  
  if (typeof history.replaceState === 'function') {
    history.replaceState({url: location.href}, '', location.href);
  }

  window.onpopstate = function(event) {
     if (typeof event.state !== 'undefined' && event.state !== null && typeof event.state.url !== 'undefined') {
         references.reload(event.state.url, true, true);
     }
  };

}



references.reload = function(url, selectorChangeFlag, isHistoryEvent) {
  var that = this;
  that.loading = true;
  selectorChangeFlag = typeof selectorChangeFlag === 'undefined' ? false : selectorChangeFlag;
  isHistoryEvent = typeof isHistoryEvent === 'undefined' ? false : isHistoryEvent;
  
  if (selectorChangeFlag) {
    that.$loading_indicator.fadeIn(200);
  }

  if (!isHistoryEvent && typeof history.pushState === 'function') {
    history.pushState({url: url}, '', url);
  }
  
  that.$loading_indicator_results.fadeIn(200, function() {
  
      url = url.indexOf('?') < 0 ? url + '?type=9' : url + '&type=9';
      
      $.get(url, function(resp) {
    
        var $resp = $(resp.replace(/<script(.|\s)*?\/script>/gi, ''));
        
        if (selectorChangeFlag) {    
            that.$selector.children().not('.loading_indicator').each(function(index, el){
              var new_markup = $resp.find(that.$selector.selector).children().not('.loading_indicator').eq(index).html();
              $(this).html(new_markup);
            });
        }
        
        var new_results_markup = $resp.find(that.$results.selector).html();
        that.$results.children().not('.loading_indicator').remove();
        that.$results.prepend(new_results_markup);
        
        
        that.loading = false;
        that.$loading_indicator.fadeOut();
        that.$loading_indicator_results.fadeOut();
        
        references.initScrollPane();
        
        projektCycle();
        mediabox.reInit();
  });
    
    
  });
}



references.initScrollPane = function() {
  var that = this;
  that.$selector.find('.wrapper').each(function(){
    var $this = $(this);
    var scrollPaneElement = $this.jScrollPane({
      showArrows: true
    });
    var scrollPaneApi = scrollPaneElement.data('jsp');
    scrollPaneApi.scrollToY(0);
    var $selected = $this.find('.selected').length > 0 ? $this.find('.selected') : null;
    if ($selected != null) {
      scrollPaneApi.scrollToElement($selected);
    }
  });  
}







// Maschinenbörse addToCart


var machineryMarket = function() {};


machineryMarket.addToCart = function() {};

machineryMarket.addToCart.init = function() {
    if ($('.machinery_market .addToBasket').length < 1) {
        return false;
    }

    $('.machinery_market .addToBasket').click(function(e){
        e.preventDefault();
        var $this = $(this);
        var href = $this.attr('href');
        var alertMessage = $this.attr('data-addedToBasketMessage');
        $.post(href,
          function(data, textStatus){
            if (textStatus === 'success') {
                log(textStatus);
                alert(alertMessage);
            }
          });
        
        return false;
    });



}









