/* Namespacing */

if (typeof LHVFP === 'undefined') {
     var LHVFP = {};
}


/* JS
-------------------------------------------------- */
document.getElementsByTagName("html")[0].className = "js";

/* IE6 flicker fix
-------------------------------------------------- */
/*@cc_on
try {
     document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}
@*/

/* jQuery
-------------------------------------------------- */
function fieldFocus() {
     $("span.field").find("input, textarea").focus(function() {
          $(this).parent().addClass("focus");
     }).blur(function() {
          $(this).parent().removeClass("focus");
     });
}
function searchFocus() {
     var field  = $("#search-field").children(":text");
     var offset = field.position();
     var layer  = $("#search-layer");
     
     $("#lang-popup, #login-popup, #search-layer, #settings-popup").hide();

     field.focus(function() {
          layer.css({
               display: "block",
               top: offset.top + field.outerHeight(false),
               right: offset.right
          });
     });
     $("#search").outerClick(searchClose);
}
function searchClose() {
     $("#search-layer").hide();
}
function revealTools() {
     $(".forum-post, .forum-post blockquote").hover(
          function(){
               $(this).find(".hidden-tools:eq(0)").removeClass("hidden-tools").addClass("reveal-tools");
          },
          function(){
               $(this).find(".reveal-tools:eq(0)").addClass("hidden-tools").removeClass("reveal-tools");
          }
     );
}
function equalHeights() {
     $(".section-1").equalHeight();
     $(".section-2").equalHeight();
}

/* language */

function showLang() {
     $("#lang").click(function(){

          var lang  = $(this);
          var popup = $("#lang-popup");

          $("#lang-popup, #login-popup, #search-layer, #settings-popup").hide();

          popup
               .show()
               .css({
                    top: lang.position().top,
                    left: lang.position().left
               })
               .outerClick( function() {
                    popup.hide();
               });

          return false;

     });
}
function closeLang() {
     $("#lang-popup").hide();
}

/* user settings */

function showSettings() {
     $("#settings a").click(function(){

          var settings = $(this);
          var popup = $("#settings-popup");

          $("#lang-popup, #login-popup, #search-layer, #settings-popup").hide();

          popup
               .show()
               .css({
                    top: settings.position().top,
                    left: settings.position().left + settings.width()
               })
               .outerClick( function() {
                    popup.hide();
               });

          return false;
     });
}
function closeSettings() {
     $("#settings-popup").hide();
}

/* login */

function toggleLogin() {

     $("#login").click(function(){

          $("#lang-popup, #login-popup, #search-layer, #settings-popup").hide();

          $("#login-popup").toggle().find(":input:visible:enabled:eq(0)").focus().select();
          $("#tools").outerClick(function() {
               $("#login-popup").hide();
          });

          return false;

     });

     $("#login-popup").tabs({
          fx: { opacity: "toggle", duration: 150 },
          show: function() { $(this).find(":text:visible:first").focus(); }
     });

}

/* tooltip */

var showTooltip = {
     init : function(){
          $("a.tooltip").click(this.clickIt);
     },
     clickIt : function(){
          var trigger  = $(this);
          var target   = trigger.attr("href");
          var tooltips = $("div.tooltip").not($(target));
          var offset   = trigger.position();
          var scroll   = $(document).scrollLeft();

          if( $(target).is(":visible") ) {
               $(target).hide();
          }
          else {
               tooltips.hide();
               $(target)
                    .css({
                         display: "block",
                         top: offset.top + trigger.outerHeight(false) + 26 + "px",
                         left: offset.left - ( $(target).width() / 2 ) + ( trigger.outerWidth(false) / 2 ) + "px"
                    })
                    .animate({
                         top: "-=30px"
                    }, 150)
                    .animate({
                         top: "+=4px"
                    }, 200, function(){
                         $(this).outerClick(hideTooltip);
                         $(this).find(".close a").one("click", function(){
                              $(target).hide();
                              return false;
                         });
                    });
          }
          return false;
     }
};
function hideTooltip() {
     if( $(this).is(":visible") ) {
          $(this).hide();
     }
}

var showLayer = {
     init : function(){
          $("a.layer").click(this.clickIt);
     },
     clickIt : function(){
          var trigger  = $(this);
          var target   = trigger.attr("href");
          var layers = $("div.layer").not($(target));
          var offset   = trigger.position();
          var scroll   = $(document).scrollLeft();

          if( $(target).is(":visible") ) {
               $(target).hide();
          }
          else {
               layers.hide();
               $(target)
                    .css({
                         display: "block",
                         top: offset.top + trigger.outerHeight(false) + 26 + "px",
                         left: offset.left - 25 + "px"
                    })
                    .animate({
                         top: "-=30px"
                    }, 150)
                    .animate({
                         top: "+=4px"
                    }, 200, function(){
                         $(this).outerClick(hideLayer);
                         $(this).find(".close a").one("click", function(){
                              $(target).hide();
                              return false;
                         });
                    });
          }
          return false;
     }
};
function hideLayer() {
     if( $(this).is(":visible") ) {
          $(this).hide();
     }
}

//Better context menus for showing menus and content
function contextTools() {
	$('.context-tools-link').each(function() {
        var $link = $(this);
        var $tooltip;
        var $arrow;
        if ($link.data().tooltip) {
             $tooltip = $($link.data().tooltip);
        } else {
             return;
        }

        var moving;

        var reposition = function() {
             if (!$tooltip.is(':visible')) {
                  return;
             }

             clearTimeout(moving);
             var $page = $('#page');

             var leftMinPos = 10;
             var rightMaxPos = $(window).outerWidth(false) - 10;
             if (rightMaxPos < $link.offset().left) {
                  rightMaxPos = $link.offset().left + $link.outerWidth(false);
             }
             if (leftMinPos > $link.offset().left) {
                  leftMinPos = $link.offset().left;
             }
             var leftPos = $link.offset().left - $tooltip.outerWidth(false) / 2 + $link.outerWidth(false) / 2;
             var rightPos = leftPos + $tooltip.outerWidth(false);

             if ($(window).outerWidth(false) - 20 < $tooltip.outerWidth(false)) {
                  $tooltip.css('width', $(window).outerWidth(false) - 20);
             }

             if (leftPos < leftMinPos) {
                  leftPos = leftMinPos;
             }
             if (rightPos > rightMaxPos) {
                  leftPos = rightMaxPos - $tooltip.outerWidth(false);
             }

             moving = setTimeout(function() {
            	 $tooltip.offset({ top:  $link.offset().top + $link.outerHeight(false), left: leftPos});
                 $tooltip.css({ visibility: 'visible' });
                 var arrowMargin = ($link.offset().left + $link.outerWidth(false) / 4) - ($tooltip.offset().left + $tooltip.outerWidth(false) / 2);
                 $arrow.css('margin-left', arrowMargin - 9);
             }, 50);

        };

        $link.on('click', function(e) {
             e.preventDefault();
             $('.context-tools:visible').each(function() {
                  if ($(this).get(0) !== $tooltip.get(0)) {
                       $(this).addClass('hidden').find('canvas').attr('style', '');
                  }
             });
             if ($tooltip.hasClass('hidden')) {
                  $tooltip.removeClass('hidden');

                  if ($tooltip.find('canvas').length == 0) {
                       $arrow = $('<canvas></canvas>');
                       $tooltip.find('.body').before($arrow);
                  } else {
                       $arrow = $tooltip.find('canvas:first');
                  }
                  if ($arrow.length > 0) {
                       var arrow = $arrow.get(0);
                       arrow.height = parseInt($(arrow).css('height'));
                       arrow.width = parseInt($(arrow).css('width'));
                  }
                  if (arrow && arrow.getContext) {
                       $tooltip.css('padding-top', arrow.height);
                       var context = arrow.getContext('2d');
                       if (context) {
                            context.fillStyle = '#fff';
                            context.shadowColor = "rgba(0, 0, 0, 0.15)";
                            context.shadowBlur = 5;
                            context.shadowOffsetY = 0;
                            context.beginPath();
                            context.moveTo(9, 3);
                            context.lineTo(15, 10);
                            context.lineTo(3, 10);
                            context.lineTo(9, 3);
                            context.fill();
                            context.closePath();
                            $tooltip.css('margin-top', '-5px');
                       }
                  }
                  if ($tooltip.hasClass('context-tools') && $tooltip.find('button.close').length == 0) {
                       $tooltip.find('.body').prepend('<button class="close"></button>');
                  }
                  reposition();
             } else {
                  $tooltip.addClass('hidden').find('canvas').attr('style', '');
             }
        });

        $(window).resize(function() {
             reposition();
        });

        $(document).on('click', '.context-tools .close', function() {
             $tooltip.addClass('hidden').find('canvas').attr('style', '');
        });
   });
}


var toggleTitle = {
     init : function(){
          $(".toggle-title").find("h2 a, .toggle a").click(this.clickIt);
     },
     clickIt : function(){
          var cont = $(this).parents("div:eq(0)");
          var icon = cont.find(".toggle a");
          var wrap = cont.next(".toggle-wrap");

          if (wrap.is(":visible")) {
               wrap.slideUp("fast", function(){
                    icon.removeClass("ico-toggle").addClass("ico-toggle-closed");
                    cont.addClass("toggle-title-closed");
               });
          }
          else {
               icon.removeClass("ico-toggle-closed").addClass("ico-toggle");
               cont.removeClass("toggle-title-closed");
               wrap.slideDown("fast");
          }
          return false;
     }
};

/* graph summary */

var toggleGraph = {
     init : function(){
          $("#summary").find(".ico-close, .ico-add").click(this.clickIt);
     },
     clickIt : function(){
          var item = $(this).parents("li:eq(0)");
          item.toggleClass("disabled").find(".ico-close, .ico-add").toggle();
          return false;
     }
};

/* thumbSelect */

var thumbSelect = {
     init : function(){
          $(".thumb-gallery").find("a").click(this.clickIt);
     },
     clickIt : function(){
          var links = $(this).parents(".thumb-gallery").find("a").not(this);

          $(this).addClass("active").next("input:radio").attr("checked","checked");
          links.removeClass("active");

          return false;
     }
};

/* currency selector */

var ccySelect = {
     init : function(){
          $(".ccy-selector").find("button").hide();
          $(".ccy-selector").find("input").bind("click", function(){
               $(this).closest("form").submit();
          });
     }
};

/* Vimeo video */
var addVimeoVideo = {
     init: function() {
          if ($(".vimeo-video").length) {
               $(".vimeo-video").each(function(){
                    if( typeof $(this).attr("title").split(",")[0] != "undefined" && typeof $(this).attr("title").split(",")[1] != "undefined" && typeof $(this).attr("title").split(",")[2] != "undefined") {
                         width = $(this).attr("title").split(",")[0]
                         height = $(this).attr("title").split(",")[1]
                         videoLink = $(this).attr("title").split(",")[2].split("/")
                         var $video = $("<iframe>")
                              .attr({
                                   width: width,
                                   height: height,
                                   frameborder: 0,
                                   src: "http://player.vimeo.com/video/"+videoLink[videoLink.length-1]
                              });
                         $video.appendTo($(this));
                         $(this).attr("title", "");
                    } else {
                         $(this).remove();
                    }
               });
          }
     }
};
/* popup window */


/* init */

$(function(){

     fieldFocus();
     showLang();
     showSettings();
     toggleLogin();
     searchFocus();
     revealTools();
     equalHeights();
     thumbSelect.init();
     showTooltip.init();
     showLayer.init();
     toggleTitle.init();
     ccySelect.init();
     addVimeoVideo.init();

     $("select").linkselect();

     $(".nyroModal").nyroModal({ modal: 'false', resizable: 'false' });

     if (typeof LHVFP.nmOptions === 'undefined') {
          LHVFP.nmOptions = {
               closeButton: '<a href="#" class="nyroModalClose nyroModalCloseButton nmReposition" title=""></a>',
               galleryLoop: false,
               galleryCounts: false
          };
     }

     $('.modal:not(.disabled)').nm(LHVFP.nmOptions);

     $(".zebra").each(function(){
          $(this).find("tbody tr:even").addClass("alt");
     });

     $(".forum-topic").each(function(){
          $(this).find(".forum-post:odd").addClass("forum-alt");
     });

     $("input[title], textarea[title]").example(function() {
          return $(this).attr("title");
     });

     if ( $(".tabs-wrap").length ) {
          $(".tabs-wrap").tabs();
     }

     if($("input.date").length){
          $("input.date").datepick();
     }
     if($("input.date-range").length){
          $("input.date-range").datepick({
               rangeSelect: true,
               monthsToShow: 2,
               onShow: function(picker, inst) {
                    picker.append('<table class="datepick-shortcuts"><tr><td class="first"><a href="#">TÃ¤na</a></td><td><a href="#">Eile</a></td><td><a href="#">See nÃ¤dal</a></td><td><a href="#">Eelmine nÃ¤dal</a></td><td><a href="#">See kuu</a></td><td class="last"><a href="#">Eelmine kuu</a></td></tr></table>');
               }
          });
     }
     
     var profiles = {
          popup: {
               width:   640,
               height:  510,
               center:    1,
               createnew: 0,
               resizable: 0
          }
     };
     $(".popup").popupwindow(profiles);
     
     /* carousel */
     $(".carousel").jCarouselLite({
        btnNext: ".carousel-next",
        btnPrev: ".carousel-prev",
          visible: 5,
          scroll: 5,
          speed: 1200
    });
     
     $(".layer").tabs({
          fx: { opacity: "toggle", duration: 150 }
     });
     
     if($("span.mailme").length) {
          var at = / Ã¤t /;
          var dot = / punkt /g;
          
          $('span.mailme').each(function () {
               var addr = $(this).text().replace(at, '@').replace(dot, '.');
               $(this).after('<a href="mailto:' + addr + '">' + addr + '</a>');
               $(this).remove();
          });
     }

     // Expand-retract content
     $('.expander').each(function() {
         var expander = $(this);
         var target = $("." + expander.attr("target"));
         var maxHeight = expander.attr("maxHeight");

         expander.click(function(e) {
              e.preventDefault();
              if ($(this).hasClass('open')) {
            	  target.height("");
            	  target.removeClass("expander-target-closed");
            	  $(this).removeClass('open');
            	  $(this).addClass('closed');
            	  $(this).html($(this).attr('closeText'));
              } else if ($(this).hasClass('closed')) {
            	  if (target.height() > maxHeight) {
	            	  target.height(maxHeight);
	            	  target.addClass("expander-target-closed");
	            	  $(this).removeClass('closed');
	            	  $(this).addClass('open');
	            	  $(this).html($(this).attr('openText'));
            	  }
              }
         });
         
         expander.click();
    });

     contextTools();
});

