/**
 * @author Alexander Farkas
 * v. 1.21
 */


(function($) {
  if(!document.defaultView || !document.defaultView.getComputedStyle){ // IE6-IE8
    var oldCurCSS = jQuery.curCSS;
    jQuery.curCSS = function(elem, name, force){
      if(name === 'background-position'){
        name = 'backgroundPosition';
      }
      if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
        return oldCurCSS.apply(this, arguments);
      }
      var style = elem.style;
      if ( !force && style && style[ name ] ){
        return style[ name ];
      }
      return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
    };
  }

  var oldAnim = $.fn.animate;
  $.fn.animate = function(prop){
    if('background-position' in prop){
      prop.backgroundPosition = prop['background-position'];
      delete prop['background-position'];
    }
    if('backgroundPosition' in prop){
      prop.backgroundPosition = '('+ prop.backgroundPosition;
    }
    return oldAnim.apply(this, arguments);
  };

  function toArray(strg){
    strg = strg.replace(/left|top/g,'0px');
    strg = strg.replace(/right|bottom/g,'100%');
    strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
    var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
    return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
  }

  $.fx.step. backgroundPosition = function(fx) {
    if (!fx.bgPosReady) {
      var start = $.curCSS(fx.elem,'backgroundPosition');

      if(!start){//FF2 no inline-style fallback
        start = '0px 0px';
      }

      start = toArray(start);

      fx.start = [start[0],start[2]];

      var end = toArray(fx.options.curAnim.backgroundPosition);
      fx.end = [end[0],end[2]];

      fx.unit = [end[1],end[3]];
      fx.bgPosReady = true;
    }
    //return;
    var nowPosX = [];
    nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
    nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
    fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

  };
})(jQuery);

/**
 * READY FUNCTION
 */

$(function () {

  // External links
  $('a[rel="external"]').click (function () {
    $(this).attr ('target', '_blank');
  });

  // Text input behaviour
  $('input#senderName').inputBehaviour ({'hrv' : '', 'eng' : 'Your name'}, false);
  $('input#senderEmail').inputBehaviour ({'hrv' : '', 'eng' : 'Your e-mail'}, false);
  $('input#targetName').inputBehaviour ({'hrv' : '', 'eng' : 'Recipient\'s name'}, false);
  $('input#targetEmail').inputBehaviour ({'hrv' : '', 'eng' : 'Recipient\'s e-mail'}, false);
  $('input#search').inputBehaviour ({'hrv' : 'Pretraživanje', 'eng' : 'Search'}, false);
  $('input#newsletterEmail').inputBehaviour ({'hrv' : 'Vaša e-mail adresa', 'eng' : 'Your e-mail address'}, false);
  var $slideCont = $('div.slide');
  if ($slideCont.length == 1) {
    $slideCont.startSlide ();
  }

  // Content hiding
  var $contentLinks = $('a[id^=name]');
  if ($contentLinks.length > 0) {
    $contentLinks.click (function () {
      var thisId = $(this).attr ('id');
      var contentId = 'content' + thisId.substring (4);
      var content = $('div#' + contentId);
      if (content.length == 1) {
        if (content.css ('display') == 'none') {
          content.show ();
        }
        else {
          content.hide ();
        }
      }
      return false;
    });
  }

  // HAZ banner slide
  var $hazBanners = $('div.hazAds div');
  if ($hazBanners.length > 0) {
    showNextHazBanner ();
  }

  function showNextHazBanner () {
    var $banners = $('div.hazAds div');
    var $activeBanner = $('div.active', $banners.parent ());
    var $lastBanner = $($banners[$banners.length - 1]);
    var $nextBanner = $activeBanner.next ('div');
    $nextBanner
      .toggleClass ('active')
      .css ({ 'marginRight' : '-300px' })
    $activeBanner
      .delay (3000)
      .animate (
        { 'marginLeft' : '-300px' },
        1000,
        'swing',
        function () {
          $activeBanner
            .toggleClass ('active')
            .removeAttr ('style');
          $nextBanner.removeAttr ('style');
          $lastBanner.after ($activeBanner);
          showNextHazBanner ();
        }
      );
  }

  // Homepage sponsors listing
  var $sponsorImages = $('div.sponsors ul li');
  if ($sponsorImages.length > 0) {
    var $container = $('div.sponsors');
    var $list = $('div.sponsors ul');
    var lastImageWidth = $($sponsorImages[$sponsorImages.count - 1]).outerWidth ();
    if ($list.width () - $container.width () > lastImageWidth) {
      var speedRatio = 0.02;
      var firstSponsor = $($sponsorImages[0]);
      slideNextSponsor (firstSponsor, $list);
    }
  }

  function slideNextSponsor ($sponsor, $list) {
    var width = $sponsor.outerWidth ();
    var duration = width / speedRatio;
    $sponsor.animate (
      {'marginLeft' : '-'+ width +'px'},
      duration,
      'linear',
      function () {
        var $nextSponsor = $($('div.sponsors ul li')[1]);
        $list.append ($sponsor);
        $sponsor.removeAttr ('style');
        slideNextSponsor ($nextSponsor, $list);
      }
    );
  }

  // AJAX handling
  var $moreNews = $('a#moreNews');
  var $moreTenders = $('a#moreTenders');
  var itemsCount = 1;

  var $list = undefined;
  var $button = undefined;

  var href = '';

  if ($moreNews.length == 1) {
    $button = $moreNews;
    $list = $('ol.news');
    href = 'ajax/news';
  }
  else if ($moreTenders.length == 1) {
    $button = $moreTenders;
    $list = $('ol.news');
    href = 'ajax/tenders';
  }

  if ($button != undefined) {
    var clickFunction = function () {
      // Unbind click function
      $button
      .unbind ('click')
      .append ('<img class="ajaxLoader" src="/img/ajax-loader.gif" alt="loader" />');

      $.ajax ({
        type : "POST",
        url : $button.attr ('href') + href,
        dataType : "html",
        data : ({
          'count': itemsCount
        }),
        success : function (response) {
          itemsCount++;
          if (response != '') {
            $list.append (response);
            if ($('li.hidden', $list).length < 5) {
              $button
              .fadeOut (500, function () {
                $('span.share').css ('paddingTop', $button.outerHeight ())
              })
              .unbind ('click');
            }
            $('li.hidden', $list)
            .slideDown (
              300,
              function () {
                $('li.hidden', $list)
                .removeClass ('hidden')
                .removeAttr ('style');
              }
              );
            $button
            .removeAttr ('style')
            .click (clickFunction);
            $('img.ajaxLoader', $button).remove ();
          }
          else {
            $button
            .fadeOut (500, function () {
              $('span.share').css ('paddingTop', $button.outerHeight ())
            })
            .unbind ('click');
          }
        },
        error : function (xhr, ajaxOptions, thrownError) {
          alert (xhr.status);
          alert (thrownError);
        }
      });
      return false;
    };

    $button.click (clickFunction);
  }

});

/*
 * PLUGINS & FUNCTIONS
 */

/**
 * Text input behaviour plugin function
 */
$.fn.inputBehaviour = function (defaultValue, canBeEmpty) {
  var $this = $(this);
  // Store default value
  $this
  .data (
    'default',
    {
      value: defaultValue
    }
    )
  // Clear element on focus if default value
  .focus (function () {
    var lang = 'eng';
    if ($('body').hasClass ('hrv')) {
      lang = 'hrv';
    }
    var $this = $(this);
    if ($this.val () === $this.data ('default').value[lang] ) {
      $(this).val ('');
    }
  })
  // Restore element on blur if empty
  .blur (function () {
    var lang = $('body').attr ('class');
    var $this = $(this);
    if ($this.val () === '' && !canBeEmpty) {
      $this.val ($this.data ('default').value[lang]);
    }
  });
}

$.fn.startSponsorSlide = function () {

}

/**
 * Slide animation function.
 */
$.fn.startSlide = function () {
  var $this = $(this);

  var contHeight = 400;
  var buffHeight = 150;

  var pauseDuration = 5000;
  var transDuration = 1000;
  var sectionsCount = 5;

  var intervalId;

  var $slider = $('div.slider');
  $slider.data ('mouseOver', '0');

  var backPos = 0;
  var topPos = 0;
  var stepCount = 0;
  var $slideItems = $('div.slideItem', $this);
  var $activeSlide = $($slideItems[0]);

  var repeatFunction = function () {
    //alert ('Function called');
    $slideItems.removeClass ('active');
    $activeSlide.addClass ('active');
    
    intervalId = window.setInterval (
      function () {
        /*
         * Background animation
         */
        backPos += contHeight + buffHeight;
        stepCount++;
        if (stepCount == sectionsCount) {
          $this
          .animate ({
            'backgroundPosition' : '10px 0'
          }, transDuration);
          backPos = 0;
        }
        else {
          $this.animate ({
            'backgroundPosition' : '10px -'+ backPos +'px'
          }, transDuration);
        }        
        

        /*
         * Content animation
         */
        var $nextSlide;
        if ($activeSlide.index () + 1 < $slideItems.length) {
          $nextSlide = $($slideItems[$activeSlide.index () + 1]);
          $nextSlide.addClass ('active');
          $activeSlide.animate (
          {
            'marginTop' : '-'+ (contHeight * 2) +'px'
          },
          transDuration,
          'swing',
          function () {
            $activeSlide
            .removeClass ('active')
            .removeAttr ('style');
            $activeSlide = $nextSlide;
          }
          );
        }
        else {
          $activeSlide.animate ({
            'marginTop' : '-400px'
          },
          transDuration / 2,
          'swing',
          function () {
            $nextSlide = $($slideItems[0]);
            $nextSlide
            .css ({
              'marginTop':'400px',
              'display':'block'
            })
            .addClass ('active')
            .animate ({
              'marginTop':'0'
            }, transDuration / 2,
            function () {
              $($slideItems[sectionsCount - 1]).removeClass ('active').removeAttr ('style');
              $slideItems.removeAttr ('style');
              $activeSlide.removeAttr ('style');
              $activeSlide = $nextSlide;
            }
            );
          }
          );
        }

        /*
         * Slider & menu animation
         */
        $('.mainMenu li a.active').removeClass ('active');
        var temp = '<span style="position: relative; float: left; width: 100%;"> Before: '+ topPos;
        if (stepCount == sectionsCount) {
          topPos = 0;
        }
        else {
          topPos = stepCount * $slider.height ();
        }
        //$('body').prepend (temp + ' - After: '+ topPos +'</span>');
        $slider.animate ({
          'top' : topPos + 'px'
        }, 
        transDuration,
        'swing',
        function () { 
          $('.mainMenu li.menuItem' + (stepCount + 1) + ' a').addClass ('active');
        });

        // Reset counter
        if (stepCount == sectionsCount) {
          stepCount = 0;
        }
      },
      pauseDuration + transDuration
      );
  };

  repeatFunction ();

  /*
   * Hover over slides
   */
  $('div.slide').hover (
    function () {
      log (':mouseover');
      $slider.data ('mouseOver', '1');
      window.clearInterval (intervalId);
    },
    function () {
      log (':mouseout');
      $slider.data ('mouseOver', '0');
      repeatFunction ();
    }
    );

  /*
   * Slide menu clicks
   */
  var menuClickFunction = function () {
    log (':clicked');
    $this.stop (true, true);
    var clickedIndex = $(this).parent ().index ();
    if (clickedIndex == $('div.mainMenu ol a.active').parent ().index ()) {
      return false;
    }

    // Unbind click
    $('.mainMenu li a')
    .unbind ('click')
    .click (function () {
      return false;
    });
    log ('- unbind click');
    // Unbind hover
    $('div.slide').unbind ('mouseleave');
    log ('- unbind mouseleave');
    $('div.slide').bind (
      'mouseleave',
      function () {
        $slider.data ('mouseOver', '0');
        log (':mouseleave (temp)');
        // Fix for leaving hover zone while animation in progress
        $this
        .animate (
        {
          'top' : '0'
        },
        transDuration,
        'linear',
        function () {
          if ($slider.data ('mouseOver') == '0') {
            log ('- bind mousleave (temp) callback');
            repeatFunction ();
          }
        }
        );
      }
    );

    stepCount = clickedIndex;

    /*
     * Slide background to selected section
     */
    backPos = (contHeight + buffHeight) * clickedIndex;
    $this.animate ({
      'backgroundPosition' : '10px -'+ backPos +'px'
    }, transDuration);


    /*
     * Slide content to selected section
     */
    var $nextSlide;
    if (clickedIndex > $activeSlide.index ()) {
      $nextSlide = $($slideItems[clickedIndex]);
      $nextSlide.addClass ('active');
      $activeSlide.animate (
      {
        'marginTop' : '-'+ (contHeight * 2) +'px'
      },
      transDuration,
      'swing',
      function () {
        $activeSlide
        .removeClass ('active')
        .removeAttr ('style');
        $activeSlide = $nextSlide;
      }
      );
    }
    else if (clickedIndex < $activeSlide.index ()) {
      $nextSlide = $($slideItems[clickedIndex]);
      $nextSlide
      .css ({
        'marginTop' : '-'+ (contHeight * 2) +'px'
      })
      .addClass ('active')
      .animate ({
        'marginTop' : '0'
      },
      transDuration,
      'swing',
      function () {
        $activeSlide.removeClass ('active');
        $activeSlide = $nextSlide;
      }
      );
    }
    
    /*
     * Slide slider and active menu item to selected section
     */
    $('.mainMenu li a.active').removeClass ('active');
    var topPos = clickedIndex * $slider.height (); 
    $slider.animate ({
      'top' : topPos + 'px'
    }, 
    transDuration,
    'swing',
    function () { 
      $('.mainMenu li.menuItem' + (clickedIndex + 1) + ' a').addClass ('active');
      // Bind click back
      $('.mainMenu li a')
      .unbind ('click')
      .click (menuClickFunction);
    });
      
    return false;
  }

  $('div.mainMenu ol a').click (
    menuClickFunction
    );

}

function log (message) {
  /*
  if ($('div.log').length == 0) {
    $('body').append ('<div class="log" style="position: fixed; width: 200px; transparency: 0.7; top: 10px; left: 10px; padding: 10px; background: #FFF;"></div>')
  }
  $('div.log').append ('<p>'+ message +'</p>');
  */
}
