/*******************************
  @package Gruendereszene_V2
  @source application.js
  @author cweiss
  @website mo-stud.io
*******************************/

var mainSlideshowTimer = null;
var mainSlideshowTimerTime = 5000;
var focus = null;

jQuery.noConflict();

jQuery(document).ready(function($) {
  //console.log("ready!");
  // start menu
  if(jQuery('body.home').length != 0 || jQuery('body.single').length != 0 || jQuery('body .landing-body').length != 0) {
    $("#menu-main li:first-child").addClass('current-menu-parent');
  }

  // Slideshow Initializer
  // wird nur in the_companies() und the_heads() benutzt
  if(jQuery('.slideshow-controller-next').length>0) {
    slide.init();
  }

  jQuery(".slideshow-controller-next").click(function() {
    var slideshow = new Array();

    slideshow['wrapper'] = jQuery(this).parent('div');
    slideshow['list'] = jQuery(this).parent('div').find('ul');
    slideshow['elements'] = jQuery(slideshow['list']).find('li').length;
    slideshow['left'] = jQuery(this).parent('div').find('ul').css('left');
    slideshow['width_element'] = jQuery(slideshow['list']).find('li').width();
    slideshow['width'] = slideshow['elements'] * slideshow['width_element'];

    if(slideshow['left'].match(/-(.*?)px/i)) {
      slideshow['left'] = slideshow['left'].match(/-(.*?)px/i);
      slideshow['left'] = slideshow['left'][1];
    } else if (slideshow['left'].match(/(.*)px/i)) {
      slideshow['left'] = slideshow['left'].match(/(.*)px/i);
      slideshow['left'] = slideshow['left'][1];
    }
    if(slide.check_numbers(slideshow)==false) { return false; }
    else { slide.slide_right(slideshow) };
  });
  jQuery(".slideshow-controller-prev").click(function() {
    var slideshow = new Array();

    slideshow['wrapper'] = jQuery(this).parent('div');
    slideshow['list'] = jQuery(this).parent('div').find('ul');
    slideshow['elements'] = jQuery(slideshow['list']).find('li').length
    slideshow['left'] = jQuery(this).parent('div').find('ul').css('left');
    slideshow['width_element'] = jQuery(slideshow['list']).find('li').width();
    slideshow['width'] = slideshow['elements'] * slideshow['width_element'];

    if(slideshow['left'].match(/-(.*?)px/i)) {
      slideshow['left'] = slideshow['left'].match(/-(.*?)px/i);
      slideshow['left'] = slideshow['left'][1];
    } else if (slideshow['left'].match(/(.*?)px/i)) {
      slideshow['left'] = slideshow['left'].match(/(.*?)px/i);
      slideshow['left'] = slideshow['left'][1];
    }

    if(slide.check_numbers(slideshow)==false) { return false; }
    else { slide.slide_left(slideshow) };
  });


  jQuery("#main .slideshow-item.last").click(function() {
    slide.get_element_information_by_data_id(slide.slideshow_prepare_next('main'), "main");
  });
  jQuery("#main .slideshow-controller .slideshow-list .slideshow-item.item").click(function() {
    slide.get_element_information_by_data_id(slide.slideshow_prepare_slide_by_id(parseInt(jQuery(this).attr('data-id')), "main"), "main");
  });
  jQuery("#main .slideshow-item.first").click(function() {
    slide.get_element_information_by_data_id(slide.slideshow_prepare_prev('main'), "main");
  });
  jQuery('#main .slideshow-container').hover(function() {
    slide.startSlideshowTimer(0, "main");
    //console.log("over -> deactivated");
  }, function() {
    if (focus) {
        clearTimeout(mainSlideshowTimer);
        mainSlideshowTimer = setTimeout('slide.startSlideshowTimer(1, "main")', mainSlideshowTimerTime);
        //console.log("out -> activated");
    } else {
        //console.log("out && no focus -> not activated");
    }
  });

  // Slideshow Sidebar
  jQuery("aside .slideshow-item.last").click(function() {
    slide.get_element_information_by_data_id(slide.slideshow_prepare_next('sidebar'), "sidebar");
  });
  jQuery("aside .slideshow-item.first").click(function() {
    slide.get_element_information_by_data_id(slide.slideshow_prepare_prev('sidebar'), "sidebar");
  });
  // jQuery('aside .slideshow-container').hover(function() {
  //   slide.startSlideshowTimer(0, "sidebar");
  // }, function() {
  //   asideSlideshowTimer = setTimeout('slide.startSlideshowTimer(1, "sidebar")', mainSlideshowTimerTime);
  // });
  jQuery("aside .slideshow-controller .slideshow-list .slideshow-item.item").click(function() {
    slide.get_element_information_by_data_id(slide.slideshow_prepare_slide_by_id(parseInt(jQuery(this).attr('data-id')), "sidebar"), "sidebar");
  });

  // Disable main Slideshow when browser window or tab looses focus
  window.onblur = function() {
    focus = false;
    slide.startSlideshowTimer(0,"main");
  };

  // Enable main Slideshow when browser window or tab gets focus
  window.onfocus = function() {
    focus = true;
    clearTimeout(mainSlideshowTimer);
    mainSlideshowTimer = setTimeout('slide.startSlideshowTimer(1, "main")', mainSlideshowTimerTime);
  };

  // Slideshow automatic start (only if browser and tab has focus)
  clearTimeout(mainSlideshowTimer);
  if(document.hasFocus) { //teste ob hasFocus unterstuetzt wird (erst ab HTML5?)
      if(document.hasFocus()){
          focus = true;
          mainSlideshowTimer = setTimeout('slide.startSlideshowTimer(1, "main")', mainSlideshowTimerTime);
          // asideSlideshowTimer = setTimeout('slide.startSlideshowTimer(1, "sidebar")', mainSlideshowTimerTime + 500);
      } else {
          focus =false;
      }
  }
  else {
      mainSlideshowTimer = setTimeout('slide.startSlideshowTimer(1, "main")', mainSlideshowTimerTime);
      // asideSlideshowTimer = setTimeout('slide.startSlideshowTimer(1, "sidebar")', mainSlideshowTimerTime + 500);
  }

  // Voting System
  var oldSearchStr;
  jQuery('#gallery_submit input[type=text], #gallery_submit input[type=email]').click(function() {
    oldSearchStr = jQuery(this).val();
    jQuery(this).val('');
  });
  jQuery('#gallery_submit input[type=text], #gallery_submit input[type=email]').blur(function() {
    if(jQuery(this).val() == "") {
      jQuery(this).val(oldSearchStr);
    }
  });
  jQuery('#gallery_submit').submit(function() {
    if(jQuery('input[name=image_vote]:checked').length==0) {
      jQuery('#gallery_notice').show();
      return false;
    } else if(jQuery('input[name=acceptnewsletter]:checked').length==0) {
      jQuery('#gallery_notice').show();
      return false;
    } else if(jQuery('#gallery_submit input[name=email]').val()=="" || jQuery('#gallery_submit input#username').val()=="Username" || jQuery('#gallery_submit input#username').val()=="") {
      jQuery('#gallery_notice').show();
    return false;
    } else {
      var pid = jQuery('input[name=image_vote][type=radio]:checked').val();
      var emailPost = jQuery('#gallery_submit input[type=email]').val();
      var firstname = jQuery('#gallery_submit input#firstname').val();
      var lastname = jQuery('#gallery_submit input#name').val();
      var gid = jQuery('#gallery_submit input[name=gid]').val();
      jQuery.ajax({
         type: "GET",
         url: remote,
         data: "pid="+pid+"&r=1" + "&username="+encodeURIComponent(lastname) + "&firstname="+encodeURIComponent(firstname) + "&email="+encodeURIComponent(emailPost),
         success: function(msg){
           setCookie('gz_votedImage', '1', '1');
           setCookie('gz_votedImagePostID', gid, '1');
           window.location = remote;
         }
       });
      return false;
    }
    return false;
  });

  // Internal Links
  if(jQuery('.post-content').length>0) {
     jQuery('.post-content').find('a').each(function() {
        var oldCssObj = {
          'text-decoration' : 'none',
          'border-bottom'  : '1px dotted #3C70A7',
          'font-style' : 'normal'
        }
        var internalLinksAttribute = jQuery(this).attr('href');
        var searchObj=/gruenderszene/i;
        if(internalLinksAttribute.match(searchObj) == "gruenderszene" && jQuery(this).html() != 'Weiterlesen »') {
          jQuery(this).css(oldCssObj);
        }
      });
      jQuery('.post-content').find('a').hover(function() {
        var internalLinksAttribute = jQuery(this).attr('href');
        var searchObj=/gruenderszene/i;
        if(internalLinksAttribute.match(searchObj) == "gruenderszene" && jQuery(this).html() != 'Weiterlesen »') {
          var newCssObj = {
            'text-decoration' : 'none',
            'border-bottom'  : '1px dotted #3C70A7'
          }
          jQuery(this).css(newCssObj);
        } else {
          return false;
        }
      }, function() {
        var oldCssObj = {
          'font-style' : 'normal'
        }
        jQuery(this).css(oldCssObj);
    });
  }

  // Landing Page
  jQuery('.article-recommendations-list .article-recommendation-item a').click(function() {
    var item = jQuery(this);
    var topPosition = jQuery(item.attr('href')).position().top + 250;

    jQuery('html, body').animate({
      scrollTop: topPosition
    }, 300);
    return false;
  });
  jQuery('.landing-topic a.more-articles').click(function() {
    var href=jQuery(this).attr('href');
    href = href.replace(/#/g, '');
    landingPageLoadMoreFeeds(href);
    return false;
  });
});

// Landing Page
function landingPageLoadMoreFeeds(id) {
  var i = 0;
  var showElements = jQuery('#topic_' + id + '.landing-topic ul li[style]');
  while(i<16) {
    jQuery(showElements[i]).removeAttr('style').show();
    if(jQuery('#topic_' + id + '.landing-topic ul li[style]').length==0) {
      jQuery('#topic_' + id + '.landing-topic a.more-articles').hide();
    }
    i=i+1;
  }
}

// Datenbank
function toggleContentRight() {
  var contentId = document.getElementById("gesellschaftsstruktur");
  var contentId2 = document.getElementById("gesellschaftsverteilung");

  if (contentId.style.display == "block") {
    contentId.style.display = "none";
    contentId2.style.display = "block";
  }
}
function toggleContentLeft() {
  var contentId = document.getElementById("gesellschaftsstruktur");
  var contentId2 = document.getElementById("gesellschaftsverteilung");

  if (contentId2.style.display == "block") {
    contentId.style.display = "block";
    contentId2.style.display = "none";
  }
}
function toggleNamefield() {
  var contentId = document.getElementById("sort-by-name");
  var contentId2 = document.getElementById("sort-by-value");

  if (contentId.style.display == "block") {
    contentId.style.display = "none";
    contentId2.style.display = "block";
  }
}
function toggleValuefield() {
  var contentId = document.getElementById("sort-by-name");
  var contentId2 = document.getElementById("sort-by-value");

  if (contentId2.style.display == "block") {
    contentId.style.display = "block";
    contentId2.style.display = "none";
  }
}

// Slideshow
var slide = {
  init: function() {
    if(jQuery('.newest-articles-list').length>0) {
      var width = jQuery('.newest-articles-list').find('li.newest-article-item').length * (jQuery('.newest-articles-list').find('li.newest-article-item:first-child').width() + 15);
      jQuery('.newest-articles-list').attr('style', 'width: '+width+'px');
    }
  },
  slideshow_right: function(values) {

  },
  slideshow_left: function(values) {

  },
  startSlideshowTimer: function(option, wichSlideshow) {
    if(wichSlideshow == 'main') {
      if(mainSlideshowTimer) {
        clearTimeout(mainSlideshowTimer);
      }
      if(option==1) {
        mainSlideshowTimer = setTimeout("slide.startSlideshowTimer(1, \""+wichSlideshow+"\")", mainSlideshowTimerTime);
        slide.get_element_information_by_data_id(slide.slideshow_prepare_next('main'), wichSlideshow);
      } else if(option==0) {
        clearTimeout(mainSlideshowTimer);
      }
    } else if(wichSlideshow == 'sidebar') {
      if(asideSlideshowTimer) {
        clearTimeout(asideSlideshowTimer);
      }
      if(option==1) {
        asideSlideshowTimer = setTimeout("slide.startSlideshowTimer(1, \""+wichSlideshow+"\")", mainSlideshowTimerTime);
        slide.get_element_information_by_data_id(slide.slideshow_prepare_next('sidebar'), wichSlideshow);
      } else if(option==0) {
        clearTimeout(asideSlideshowTimer);
      }
    }
  },
  slideshow_prepare_next: function(wichSlideshow) {
    if(wichSlideshow=="sidebar") {
      wichSlideshow = "aside";
    } else {
      wichSlideshow = "#main";
    }
    var data_id = jQuery(wichSlideshow+' .slideshow-controller .slideshow-list .slideshow-item.item.active').attr('data-id');
    var allItems = jQuery(wichSlideshow+' .slideshow-controller .slideshow-list .slideshow-item.item.item').length - 1;
    if (data_id==0) {
      data_id = 1;
    } else if (parseInt(data_id)==allItems) {
      data_id = 0;
    } else {
      data_id = parseInt(data_id) + 1;
    }
    jQuery(wichSlideshow+' .slideshow-controller .slideshow-list .slideshow-item.item').removeClass('active');
    jQuery(wichSlideshow+' .slideshow-controller .slideshow-list .slideshow-item.item[data-id='+data_id+']').addClass('active');
    return data_id;
  },
  slideshow_prepare_prev: function(wichSlideshow) {
    if(wichSlideshow=="sidebar") {
      wichSlideshow = "aside";
    } else {
      wichSlideshow = "#main";
    }
    var data_id = jQuery(wichSlideshow+' .slideshow-controller .slideshow-list .slideshow-item.item.active').attr('data-id');
    var allItems = jQuery(wichSlideshow+' .slideshow-controller .slideshow-list .slideshow-item.item.item').length - 1;
    if (data_id==0) {
      data_id = allItems;
    } else {
      data_id = parseInt(data_id) - 1;
    }
    jQuery(wichSlideshow+' .slideshow-controller .slideshow-list .slideshow-item.item').removeClass('active');
    jQuery(wichSlideshow+' .slideshow-controller .slideshow-list .slideshow-item.item[data-id='+data_id+']').addClass('active');
    return data_id;
  },
  slideshow_prepare_slide_by_id: function(data_id, wichSlideshow) {
    if(wichSlideshow=="sidebar") {
      wichSlideshow = "aside";
    } else {
      wichSlideshow = "#main";
    }
    jQuery(wichSlideshow+' .slideshow-controller .slideshow-list .slideshow-item.item').removeClass('active');
    jQuery(wichSlideshow+' .slideshow-controller .slideshow-list .slideshow-item.item[data-id='+data_id+']').addClass('active');
    return data_id;
  },
  get_element_information_by_data_id: function(id, slideshow) {
    if(slideshow=="main") {
      slideshow = "#main";
    } else if (slideshow=="sidebar") {
      slideshow = "aside";
    }
    var width = jQuery(slideshow + ' ul.slideshow-list li.slideshow-item').width();
    var scrollLeftWidth = width * id;
    jQuery(jQuery(slideshow + ' .slideshow > ul.slideshow-list')).animate({
      left: -scrollLeftWidth
    });
    slide.set_information(id, slideshow);
  },
  set_information: function(id, slideshow) {
    if(slideshow=="main") {
      slideshow = "#main";
    } else if (slideshow=="sidebar") {
      slideshow = "aside";
    }
    var item = jQuery(slideshow + ' ul.slideshow-list li.slideshow-item[data-id='+id+']');
    var itemSlideshow = jQuery(slideshow + ' .slideshow-controller .slideshow-meta');

    itemSlideshow.find('p.title').html(item.find('p.headline').html());
    itemSlideshow.find('p.subtitle').html(item.find('p.subtitle').html());
  },
  slide_right: function(values) {

    var scrollWidth;
    var width = values['width'] - values['width_element'];

    if(values['left']==0 || values['left']=="auto") {
      scrollWidth = "-" + values['width_element'];
    } else if(-values['left']<=-width) {
      return false;
    } else {
      scrollWidth = -values['left']-values['width_element'];
    }

    jQuery(values['list']).animate({
      left : scrollWidth
    });

    return true;
  },
  slide_left: function(values) {

    var scrollWidth;

    var width = 0;

    if(values['left']==0 || values['left']=="auto") {
      return false;
    } else {
      scrollWidth = -values['left']+values['width_element'];
    }

    jQuery(values['list']).animate({
      left : scrollWidth
    });

    return true;
  },
  check_numbers: function(values) {
    var element = jQuery(values['list']).attr('class');
    if(element=='companies-list') {
      if(values['elements'] == 1) {
        return false;
      } else {
        return true;
      }
    } else if(element=='heads-list') {
      if(values['elements'] < 5) {
        return false;
      } else {
        return true;
      }
    }
  }
}

// Voting System
function getCookie(c_name) {
  if (document.cookie.length>0) {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1) {
      c_start=c_start + c_name.length+1 ;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length
      return unescape(document.cookie.substring(c_start,c_end));
    }
  }
  return ""
}
function setCookie(c_name,value,expiredays) {
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toUTCString());
}
function checkCookie() {
  votedImage=getCookie('votedImage');
  if (votedImage!="") {
  return 0;
  } else {
  return 1;
  }
}

// script leichen
function externalLinks() {
  if (!document.getElementsByTagName) return;
  var anchors = document.getElementsByTagName("a");
  for (var i=0; i<anchors.length; i++) {
    var anchor = anchors[i];
    if (
      anchor.getAttribute("href") && (
      anchor.getAttribute("rel") == "external" ||
      anchor.getAttribute("rel") == "external nofollow" ||
      anchor.getAttribute("rel") == "external follow" ||
      anchor.getAttribute("rel") == "nofollow external" )
      )
    anchor.target = "_blank";
  }
}

