// JSLint configuration
/*jslint browser: true */
/*jslint white: true */
/*global HOM */
/*global YTILS */
/*global YAHOO */
/*global $ */
/*global alert */
(function(){

"use strict";
// Here comes the code.
var
yHash = YTILS.util.hash,

notify = function()
{
  $.ajax({
	url: 'http://www.hom-online.com/notify/',
	success: function(){ }
  });
},

initCheckYourWebsiteForm = function()
{
  var
  checkYourWebsiteInputFocus = function()
  {
    var
    originalValue = $('#checkYourWebsiteInputOriginalValue').val();

    if ($(this).val() === originalValue)
    {
      $(this).val("");
    }
  },

  checkYourWebsiteInputBlur = function()
  {
    var
    ysu = YTILS.util.string,
    inputValue = $(this).val();

    if (ysu.trim(inputValue) === "")
    {
      $(this).val($('#checkYourWebsiteInputOriginalValue').val());
    }
  };

  $('#checkYourWebsiteInput').focus(checkYourWebsiteInputFocus);
  $('#checkYourWebsiteInput').blur(checkYourWebsiteInputBlur);
},

constructPageWithAdditionalHeightOnRight = function(addHeight)
{
  var
  leftHeight = $('#blogContainer').height(),
  rightHeight = $('#productVideoBesideLimbic').height(),
  diff = Math.abs(leftHeight - rightHeight);

  // +2/-2 for the top- and bottom-border.
  if (leftHeight !== rightHeight)
  {
    if (leftHeight > rightHeight)
    {
      $('#productVideoBesideLimbic .productVideoBesideLimbicInner:last').height($('#productVideoBesideLimbic .productVideoBesideLimbicInner:last').height() + diff + 2 + addHeight);
    }
    else
    {
      $('#limbicContainerInner').height(leftHeight + diff - 2);
      $('#aboutImprintContainer').height(leftHeight + diff - addHeight - 2);
    }
  }
},

constructBlogPage = function()
{
  constructPageWithAdditionalHeightOnRight(30);
},

constructAboutUsPage = function()
{
  constructPageWithAdditionalHeightOnRight(48);
},

constructLegalNoticePage = function()
{
  constructPageWithAdditionalHeightOnRight(48);
},

constructPacketSelectionPage = function()
{
  var
  cHash = null,

  packetSelection = function()
  {
    var
    packets = "";
//    $('#reviewPacket, #googlePacket, #starterPacket, #socialPacket').removeClass('packetSelected');
//    $('#reviewPacket, #googlePacket, #starterPacket, #socialPacket').addClass('packetNotSelected');


    $(this).toggleClass('packetNotSelected')
    $(this).toggleClass('packetSelected');

    if ($('#reviewPacket').hasClass('packetSelected'))
    {
      packets = packets + " reviewPacket";
    }

    if ($('#googlePacket').hasClass('packetSelected'))
    {
      packets = packets + " googlePacket";
    }

    if ($('#starterPacket').hasClass('packetSelected'))
    {
      packets = packets + " starterPacket";
    }

    if ($('#socialPacket').hasClass('packetSelected'))
    {
      packets = packets + " socialPacket";
    }

    if (packets === "")
    {
      $('#submitter')[0].disabled = true;
      $('#submitter').css('cursor', 'default');
      $('#submitter')[0].src = './img/go-for-contact-data-btn-dis.png';
    }
    else
    {
      $('#submitter')[0].disabled = false;
      $('#submitter').css('cursor', 'pointer');
      $('#submitter')[0].src = './img/go-for-contact-data-btn.png';
    }
    
    $('#packetSelection').val(packets);
  };

  $('#reviewPacket, #googlePacket, #starterPacket, #socialPacket').click(packetSelection);
  switch (window.location.hash)
  {
    case '#1':
      $('#googlePacket').trigger('click');
      break;
    case '#2':
      $('#socialPacket').trigger('click');
      break;
    case '#3':
      $('#reviewPacket').trigger('click');
      break;
    default:
      $('#starterPacket').trigger('click');
      break;
  }
},

constructLimbicPage = function()
{
  var
  leftHeight = $('#limbicContainerInner').height(),
  rightHeight = $('#productVideoBesideLimbic').height(),
  diff = Math.abs(leftHeight - rightHeight),
  topicHeadMouseLeave = function()
  {
    $(this).css('background-position', 'center top');
  },

  topicHeadMouseEnter = function()
  {
    $(this).css('background-position', 'center bottom');
  };

  // +2/-2 for the top- and bottom-border.
  if (leftHeight !== rightHeight)
  {
    if (leftHeight > rightHeight)
    {
      $('#productVideoBesideLimbic .productVideoBesideLimbicInner:last').height($('#productVideoBesideLimbic .productVideoBesideLimbicInner:last').height() + diff + 2);
    }
    else
    {
      $('#limbicContainerInner').height(leftHeight + diff - 2);
    }
  }

  $('#topics').find('.topicHead').mouseenter(topicHeadMouseEnter);
  $('#topics').find('.topicHead').mouseleave(topicHeadMouseLeave);
},

constructProductPage = function()
{
  var
  adjustBottomTopicsSizes = function()
  {
    var
    i,
    maxHeight = 0,
    topicContainer33erWidth = $('div.bottomTopics').find('.topicContainer33er').width() - 2,
    topicContainer33erlWidth = $('div.bottomTopics').find('.topicContainer33erl').width() - 2,
    allContainers = $('div.bottomTopics').find('.topicContentWrapper');

    for (i = 0; i < allContainers.length; i++)
    {
      if (allContainers[i].offsetHeight > maxHeight)
      {
        maxHeight = allContainers[i].offsetHeight;
      }
    }

    $('div.bottomTopics').find('div').removeClass('autoHeightImportant');
    $('div.bottomTopics').find('.topicContentWrapper').css('height', maxHeight + 'px');
    $('div.bottomTopics').find('.topicContainer33er').find('.topicContentWrapper').css('width', topicContainer33erWidth + 'px');
    $('div.bottomTopics').find('.topicContainer33erl').find('.topicContentWrapper').css('width', topicContainer33erlWidth + 'px');
  },

  /**
   * Navigates to the topic's url which is dedicated to be the
   * the same of its headline-link (first <a> of the element).
   *
   * @return void
   */
  topicContainerClick = function()
  {
    document.location.href = $(this).find('a')[0].href;
  },

  /**
   * Hover effects/entering the topic-element.
   *
   * @return void
   */
  topicContainerMouseEnter = function()
  {
    $(this).css('cursor', 'pointer');
    $(this).find('.topicHead33er').css('backgroundPosition', 'bottom center');
    $(this).find('.topicContentWrapper').css('borderRightColor', '#51941A');
    $(this).find('.topicContentWrapper').css('borderBottomColor', '#51941A');
    $(this).find('.topicContentWrapper').css('borderLeftColor', '#51941A');
  },

  /**
   * Hover effects/leaving the topic-element.
   *
   * @return void
   */
  topicContainerMouseLeave = function()
  {
    $(this).find('.topicHead33er').css('backgroundPosition', 'top center');
    $(this).find('.topicContentWrapper').css('borderRightColor', '#F0F0F0');
    $(this).find('.topicContentWrapper').css('borderBottomColor', '#F0F0F0');
    $(this).find('.topicContentWrapper').css('borderLeftColor', '#F0F0F0');
  };

  adjustBottomTopicsSizes();
  $('div.bottomTopics').find('.topicContainer').mouseenter(topicContainerMouseEnter);
  $('div.bottomTopics').find('.topicContainer').mouseleave(topicContainerMouseLeave);
  $('div.bottomTopics').find('.topicContainer').click(topicContainerClick);
},

constructHomepage = function()
{
  var
  synchronizeSizes = function()
  {
    var
    
    /**
     * Synchronizes the size of the two homeAbout-panels, 
     * containg information about the company and news.
     * 
     * @return void
     */
    synchronizeAboutContentSizes = function()
    {
      var
      mainContentHeight = $('#homeAbout .mainContent').height(),
      newsContentHeight = $('#homeAbout .newsContent').height();
      
      if (mainContentHeight > newsContentHeight)
      {
        $('#homeAbout .newsContent').height(mainContentHeight);
      }
      else
      {
        $('#homeAbout .mainContent').height(newsContentHeight);
      }
    },
    
	enableNotifications = function()
	{
	  $('#downloadChecklist').click(function() { notify('Download Checklist'); });
	},
	
    handleSafari = function()
    {
      var
      ysu = YTILS.util.string;
      
      if (ysu.contains(navigator.userAgent.toLowerCase(), "safari"))
      {
        if (!ysu.contains(navigator.userAgent.toLowerCase(), "chrome"))
        {
          $('#checkYourWebsiteInput').css('paddingTop', '20px');
        }
      }
    };
    
    synchronizeAboutContentSizes();
    handleSafari();
	enableNotifications();
  },
  
  /**
   * Navigates to the topic's url which is dedicated to be the
   * the same of its headline-link (first <a> of the element).
   * 
   * @return void
   */
  topicContainerClick = function()
  {
    document.location.href = $(this).find('a')[0].href;
  },
  
  /**
   * Hover effects/entering the topic-element.
   * 
   * @return void
   */
  topicContainerMouseEnter = function()
  {
    $(this).css('cursor', 'pointer');
    $(this).find('.topicHead').css('backgroundPosition', 'bottom center');
    $(this).find('.topicContentWrapper').css('borderRightColor', '#51941A');
    $(this).find('.topicContentWrapper').css('borderBottomColor', '#51941A');
    $(this).find('.topicContentWrapper').css('borderLeftColor', '#51941A');
  },
  
  /**
   * Hover effects/leaving the topic-element.
   * 
   * @return void
   */
  topicContainerMouseLeave = function()
  {
    $(this).find('.topicHead').css('backgroundPosition', 'top center');
    $(this).find('.topicContentWrapper').css('borderRightColor', '#F0F0F0');
    $(this).find('.topicContentWrapper').css('borderBottomColor', '#F0F0F0');
    $(this).find('.topicContentWrapper').css('borderLeftColor', '#F0F0F0');
  };
  
  // Register events:
  $('#topics .topicContainer').mouseenter(topicContainerMouseEnter);
  $('#topics .topicContainer').mouseleave(topicContainerMouseLeave);
  $('#topics .topicContainer').click(topicContainerClick);
  
  // Size-operations:
  synchronizeSizes();
  initCheckYourWebsiteForm();
},

handleBottomLinks = function()
{
  var
  clickBottomLinkLi = function()
  {
    document.location.href = $(this).find("a")[0].href;
  };

  $('#bottomLinkage').find('li').click(clickBottomLinkLi);
  $('#bottomLinkage').find('li').css('cursor', 'pointer');
},

handleHomVideoLinks = function()
{
  var
  openHomVideo = function()
  {
    var
    displayIframe = function()
    {
      $('#videoboxVideoContainer').html(HOM.VIDEO_IFRAME_INNER_HTML)
    };

    $('#videobox').height($(window).height());
    $('#videobox').width($(window).width());
    $('#videobox, #videoboxVideoContainer, #videoboxVideoContainerBgWhite').show();
    $('#videobox, #videoboxVideoContainer, #videoboxVideoContainerBgWhite').fadeTo(0, 0);
    $('#videobox').fadeTo('fast', 0.7);
    $('#videoboxVideoContainerBgWhite, #videoboxVideoContainer').fadeTo('fast', 1, displayIframe);

    // Prevent browser-automatic behaviour.
    return false;
  },

  closeHomVideo = function()
  {
    $('#videobox, #videoboxVideoContainer, #videoboxVideoContainerBgWhite').hide();
    $('#videoboxVideoContainer').html('');
  };

  $('#homVideoOpener').attr('href', '#');
  $('#homVideoOpener, #homVideoOpenerContainer, #topicHeadVideo').click(openHomVideo);
  $('#videobox').click(closeHomVideo);

  $(document).keyup(function(e) {

    if (e.keyCode.toString() === '27')
    {
      closeHomVideo();
    }

  });
},

constructDankePage = function()
{
  var
  gotoHome = function()
  {
    document.location.href = HOM.HOMEPAGE;
  };

  $('#mc-embedded-subscribe').click(gotoHome);
},

constructRegStep3Page = function()
{
  var
  yt = YTILS.util.type,

  uploadSubmitterClick = function()
  {
    // SLogan:
    if (yt.isEmpty($('#slogan')[0].value))
    {
      alert("Bitte geben Sie einen Slogan an.");
      return false;
    }

    // File selected?
    var files = $("input[type=file]");
    var foundOne = false;
    var i;
    for (i = 0; i < files.length; i++)
    {
      if (!yt.isEmpty(files[i].value))
      {
        foundOne = true;
      }
    }

    if (!foundOne)
    {
      alert("Bitte wählen Sie mindestens ein Bild aus.");
      return false;
    }

    var radios = $("input[type=radio]");
    var radioFound = false,
        radioFoundVal;
    for (i = 0; i < radios.length; i++)
    {
      if (radios[i].checked)
      {
        radioFound = true;
        radioFoundVal = radios[i].value;
      }
    }

    if (!radioFound)
    {
      alert("Bitte wählen Sie ein Bild für die Bannergestaltung aus.");
      return false;
    }
    else
    {
      if (yt.isEmpty($('#' + radioFoundVal)[0].value))
      {
        if (radioFoundVal === "img0")
        {
          alert("Bitte wählen Sie eine Datei für Foto 1 aus, wenn Sie dieses Foto für die Bannergestaltung verwenden möchten.");
          return false;
        }
        if (radioFoundVal === "img1")
        {
          alert("Bitte wählen Sie eine Datei für Foto 2 aus, wenn Sie dieses Foto für die Bannergestaltung verwenden möchten.");
          return false;
        }
        if (radioFoundVal === "img2")
        {
          alert("Bitte wählen Sie eine Datei für Foto 3 aus, wenn Sie dieses Foto für die Bannergestaltung verwenden möchten.");
          return false;
        }
        if (radioFoundVal === "img3")
        {
          alert("Bitte wählen Sie eine Datei für Foto 4 aus, wenn Sie dieses Foto für die Bannergestaltung verwenden möchten.");
          return false;
        }
        if (radioFoundVal === "img4")
        {
          alert("Bitte wählen Sie eine Datei für Foto 5 aus, wenn Sie dieses Foto für die Bannergestaltung verwenden möchten.");
          return false;
        }

        return false;
      }
    }

    // AGB
    if (!$('#agb')[0].checked)
    {
      alert("Bitte stimmen Sie den AGB zu.");
      return false;
    }

    $('#uploadForm').submit();
  };

  $('#submitter').click(uploadSubmitterClick);
},

constructRegStep2Page = function()
{
  var
  handleShortdescriptionKeyup = function()
  {
    var
    ta = $('#shortdescription'),
    str = $(this).val().toString();

    if (str.length > 200)
    {
      str = str.substr(0, 200);
      $(this).val(str);
      ta.scrollTop(ta[0].scrollHeight - ta.height());
      return false;
    }
  },
  
  selectByValue = function(what, value)
  {
    var
    i,
    handle = $(what)[0];

    for (i = 0; i < handle.options.length; i++)
    {
      if (handle.options[i].value === value)
      {
        handle.options[i].selected = true;
      }
      else
      {
        handle.options[i].selected = false;
      }
    }
  },

  applyTimesOnAll = function()
  {
    var
    goFromTime,
    goToTime,
    goCheck = false;

    if ($('#closed0')[0].checked)
    {
      goCheck = true;
    }

    $('#closed1')[0].checked = goCheck;
    $('#closed2')[0].checked = goCheck;
    $('#closed3')[0].checked = goCheck;
    $('#closed4')[0].checked = goCheck;
    $('#closed5')[0].checked = goCheck;
    $('#closed6')[0].checked = goCheck;

    goFromTime = $('#day0From').val();
    selectByValue('#day1From', goFromTime);
    selectByValue('#day2From', goFromTime);
    selectByValue('#day3From', goFromTime);
    selectByValue('#day4From', goFromTime);
    selectByValue('#day5From', goFromTime);
    selectByValue('#day6From', goFromTime);
    goToTime = $('#day0To').val();
    selectByValue('#day1To', goToTime);
    selectByValue('#day2To', goToTime);
    selectByValue('#day3To', goToTime);
    selectByValue('#day4To', goToTime);
    selectByValue('#day5To', goToTime);
    selectByValue('#day6To', goToTime);
  },

  processPost = function()
  {
    if (HOM.SESSION !== 'null')
    {
      selectByValue('#day0From', HOM.SESSION.day0From);
      selectByValue('#day1From', HOM.SESSION.day1From);
      selectByValue('#day2From', HOM.SESSION.day2From);
      selectByValue('#day3From', HOM.SESSION.day3From);
      selectByValue('#day4From', HOM.SESSION.day4From);
      selectByValue('#day5From', HOM.SESSION.day5From);
      selectByValue('#day6From', HOM.SESSION.day6From);
      selectByValue('#day0To', HOM.SESSION.day0To);
      selectByValue('#day1To', HOM.SESSION.day1To);
      selectByValue('#day2To', HOM.SESSION.day2To);
      selectByValue('#day3To', HOM.SESSION.day3To);
      selectByValue('#day4To', HOM.SESSION.day4To);
      selectByValue('#day5To', HOM.SESSION.day5To);
      selectByValue('#day6To', HOM.SESSION.day6To);
    }
    else if (HOM.POST !== 'null')
    {
      selectByValue('#day0From', HOM.POST.day0From);
      selectByValue('#day1From', HOM.POST.day1From);
      selectByValue('#day2From', HOM.POST.day2From);
      selectByValue('#day3From', HOM.POST.day3From);
      selectByValue('#day4From', HOM.POST.day4From);
      selectByValue('#day5From', HOM.POST.day5From);
      selectByValue('#day6From', HOM.POST.day6From);
      selectByValue('#day0To', HOM.POST.day0To);
      selectByValue('#day1To', HOM.POST.day1To);
      selectByValue('#day2To', HOM.POST.day2To);
      selectByValue('#day3To', HOM.POST.day3To);
      selectByValue('#day4To', HOM.POST.day4To);
      selectByValue('#day5To', HOM.POST.day5To);
      selectByValue('#day6To', HOM.POST.day6To);
    }
    else
    {
      alert('Nothing to do');
    }
  };

  $('#applyTimesOnAll').click(applyTimesOnAll);
  if (HOM.ACTION && HOM.ACTION === 'reg1')
  {
    processPost();
  }
  
  $('#shortdescription').keyup(handleShortdescriptionKeyup);
},

ready = function()
{
  switch (HOM.PAGE)
  {
    case "index":
      constructHomepage();
      initCheckYourWebsiteForm();
      break;
    case "startpaket":
    case "googlewerbung":
    case "socialmedia":
    case "bewertungsportale":
      constructProductPage();
      break;
    case "transparenz":
    case "vertrauen":
    case "sicherheit":
    case "referenzen":
      constructLimbicPage();
      initCheckYourWebsiteForm();
      break;
    case "blog":
    case "news":
      constructBlogPage();
      break;
    case "ueber-uns":
      constructAboutUsPage();
      break;
    case "impressum":
    case "datenschutz":
    case "agb":
      constructLegalNoticePage();
      break;
    case "angebot-anfordern-paketauswahl":
      constructPacketSelectionPage();
      break;
    case "danke":
      constructDankePage();
      break;
    case "registrierung-schritt-2":
      constructRegStep2Page();
      break;
    case "registrierung-schritt-3":
      constructRegStep3Page();
      break;
    default:
      break;
  }

  handleHomVideoLinks();
  handleBottomLinks();
};

$(document).ready(ready);

}());
