﻿jQuery.noConflict();

my_slideshowActive = false;
var slideshowTimer;
var AllowDownloads = false;

var sbvUtils = {
    init: function () {
        // onload functions
        sbvUtils.initGallery();
        sbvUtils.DefaultSearchText(jQuery('.top-search-field, .pagesearch'));
        sbvUtils.toggleEditMode();
        sbvUtils.pageSearch.init();
        sbvUtils.initDropDownNavigation();
        sbvUtils.VideoHandler();
        sbvUtils.Overlay(jQuery('a.overlay[rel]'));
        sbvUtils.RegionMap();
        sbvUtils.ThemePopper();
        sbvUtils.EventListDate();
        sbvUtils.maniPuu();
        sbvUtils.SafeEmailLinks();

        sbvUtils.videoPlayIcon();
        // sbvUtils.eqResultColumnHeight();
    },
    scrollPage: function (el) {
        if (typeof (el) != 'undefined' || el != null) {
            el = el;
        } else {
            el = '#project-search-result-container';
        }
        jQuery('html, body').animate({
            scrollTop: jQuery(el).offset().top - 5
        }, 350);
    },
    SafeEmailLinks: function () {
        //safe mailto's
        if (!jQuery("body").hasClass("pageeditor")) {
            jQuery('a[href*="[at]"]').each(function () {
                var email = jQuery(this).text().split('[at]').join('@');
                jQuery(this).attr('href', 'mailto:' + email.toLowerCase());
                jQuery(this).text(email);
            });
        }

    },
    // Makes all columns in search result list equal in height, within the scope of one row.
    eqResultColumnHeight: function () {
        var tallest = 0;
        var thisHeight;

        jQuery(".result-item-content").each(function () {
            tallest = 0;

            jQuery(this).find('.item-block').each(function () {
                thisHeight = jQuery(this).height();
                if (thisHeight > tallest) {
                    tallest = thisHeight;
                }
            });

            if (tallest > 130) {
                jQuery(this).children('.item-block').height(tallest);
            } else {
                jQuery(this).children('.item-block').height(130);
            }
            //alert('Tallest in this row is: ' + tallest);
        });
    },
    maniPuu: function () {

        jQuery(".spotlist").next(".spot-shadow").css("display", "none");

    },
    // ThemePopper functionality - Animates the theme snippet on spots
    ThemePopper: function () {
        var snippet;
        jQuery(".gridspot .spot-content,.spot-content .theme-image, .item-block.thumb, .related-video .theme-image").not(".scPageDesignerPlaceholder .spot-content .themepopper").live('mouseover', function () {
            snippet = jQuery(this).find(".themepopper");
            if (snippet.length == 1) {
                jQuery(snippet).stop().animate({ right: 0 }, 350);
            }
        }).live('mouseout', function () {
            snippet = jQuery(this).find(".themepopper");
            jQuery(snippet).stop().animate({ right: -(jQuery(snippet).width()) - 30 }, 350);
        });
    },
    // Temporary solution to show the date of event in eventlist icon
    EventListDate: function () {
        var iconDateHtml;
        var eventListDateString;
        jQuery(".tf-list li.event").each(function () {
            eventListDateString = jQuery(this).find(".date").text();
            iconDateHtml = "<span class='eventlist-icondate'>" + eventListDateString.substring(0, 2) + "</span>";
            jQuery(this).append(iconDateHtml);
        });
    },
    RegionMap: function () {

        jQuery("#RegionMap area[name='region1']").hover(
          function () {
              jQuery("#regionmapimg").attr("src", "/resources/TFDK/img/Regions/hovedstaden.png");
          },
          function () {
              jQuery("#regionmapimg").attr("src", "/resources/TFDK/img/Regions/danmark.png");
          }
        )

        jQuery("#RegionMap area[name='region2']").hover(
          function () {
              jQuery("#regionmapimg").attr("src", "/resources/TFDK/img/Regions/midtjylland.png");
          },
          function () {
              jQuery("#regionmapimg").attr("src", "/resources/TFDK/img/Regions/danmark.png");
          }
        )

        jQuery("#RegionMap area[name='region3']").hover(
          function () {
              jQuery("#regionmapimg").attr("src", "/resources/TFDK/img/Regions/nordjylland.png");
          },
          function () {
              jQuery("#regionmapimg").attr("src", "/resources/TFDK/img/Regions/danmark.png");
          }
        )

        jQuery("#RegionMap area[name='region4']").hover(
          function () {
              jQuery("#regionmapimg").attr("src", "/resources/TFDK/img/Regions/soenderjylland.png");
          },
          function () {
              jQuery("#regionmapimg").attr("src", "/resources/TFDK/img/Regions/danmark.png");
          }
        )

        jQuery("#RegionMap area[name='region5']").hover(
          function () {
              jQuery("#regionmapimg").attr("src", "/resources/TFDK/img/Regions/vestsjaelland.png");
          },
          function () {
              jQuery("#regionmapimg").attr("src", "/resources/TFDK/img/Regions/danmark.png");
          }
        )

    },
    GalleryPrevFunctions: function (carousel, id) {

        //appends gray bottombar to all small galleries
        /*jQuery(".vt-three .galleryitem").each(function (i) {
        jQuery(this).append('<div class="GalleryGrayLine">&nbsp;</div>');
        });*/

        //Looks for the amount of gallery items and adds navigations controls
        if (jQuery('.galleryitem', carousel).length > 1) {
            jQuery(carousel).append('<a class="gallery-nav-prev">&nbsp;</a><div class="gallery-nav-stepper"></div><a class="gallery-nav-next">&nbsp;</a>');
        }
        var captionBox = jQuery(this).parents('.carousel').find('.captionbox');
        captionBox.html(jQuery(this).find('h4,p').clone().fadeIn());

        var url = jQuery(this).find('a:first').attr('href');
        if (url !== undefined) {
            captionBox.find('p').wrap('<a href="' + url + '"></a>');
        }



    },
    GalleryAfterFunctions: function (carousel, id) {

        //Pause func
        //var stopObjectsP = jQuery(carousel).find('.carousel-content');
        jQuery(".gallery-nav-stepper").append('<a href="#" class="pause">pause</a>');
        jQuery('.gallery-nav-stepper .pause').click(function () {
            // stopObjects.cycle('pause');
        });

    },
    VideoHandler: function () {
        if (jQuery("body").hasClass("pageeditor")) {
            return;
        }

        jQuery("a[href*='/VideoItems/']").each(function (i) {
            var FileUrl = jQuery(this).attr("href");
            jQuery(this).attr("href", "/Service-Pages/VideoPopUp?url=" + FileUrl);
            jQuery(this).attr("rel", "#lightbox-content");
            jQuery(this).addClass("overlay");
        });
    },
    equalheight: function () {
        // Check if editormode
        if (!jQuery('body').hasClass('preview')) {

            var outerobject;
            var rowamount;



            if (jQuery('.vt-six .spotlist').length >= '1') {
                outerobject = jQuery('.vt-six .spotlist');
                rowamount = 2;

            }
            else if (jQuery('.vt-nine .spotlist').length >= '1') {
                outerobject = jQuery('.vt-nine .spotlist');
                rowamount = 3;

            }
            else if (jQuery('.spot-placeholder').parent().hasClass('vt-nine')) {
                outerobject = jQuery('.vt-nine .spot-placeholder');
                rowamount = 3;
            }
            else if (jQuery('.spotlist').parent().parent().parent().parent().parent().parent().parent().hasClass('vt-twelve')) {

                outerobject = jQuery('.vt-twelve .spot-placeholder');
                rowamount = 4;
            }
            else if (jQuery('#eventgridlist').length == 1) {
                console.log('dsds');
                outerobject = jQuery('.vt-twelve #eventgridlist');
                rowamount = 4;
            }
            else { return; }


            outerobject.each(function (index) {
                var object;
                object = outerobject.eq(index).children(".spot");
                runEqualHeight(object);


                function runEqualHeight(object) {
                    var d = 0;
                    var n = (object.length) - 1;
                    if (object.length > 1) {
                        while (d <= n) {
                            var objectHeights = new Array();
                            for (var i = 0; i <= (rowamount - 1); i++) {
                                objectHeights[i] = object.eq(d + i).height();

                            }
                            var newHeight = objectHeights.sort(function (a, b) { return b - a; })[0];

                            for (var j = 0; j <= (rowamount - 1); j++) {
                                object.eq(d + j).css('height', newHeight);
                            }

                            d = d + rowamount;
                        }
                    }
                }
            });
        }
    },
    videoPlayIcon: function () {

        var nVer = navigator.appVersion;
        var nAgt = navigator.userAgent;
        var browserName = navigator.appName;
        var fullVersion = '' + parseFloat(navigator.appVersion);
        var majorVersion = parseInt(navigator.appVersion, 10);
        var nameOffset, verOffset, ix;

        // In MSIE, the true version is after "MSIE" in userAgent
        if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
            browserName = "Microsoft Internet Explorer";
            fullVersion = nAgt.substring(verOffset + 5);
        }

        // trim the fullVersion string at semicolon/space if present
        if ((ix = fullVersion.indexOf(";")) != -1) fullVersion = fullVersion.substring(0, ix);
        if ((ix = fullVersion.indexOf(" ")) != -1) fullVersion = fullVersion.substring(0, ix);

        majorVersion = parseInt('' + fullVersion, 10);

        jQuery('#main').find('.spot,.spotlist,.gallery').find('a.overlay').find('img').each(function () {
            jQuery(this).parent().parent().parent().parent('div').addClass('videospot');
            jQuery(this).parent().append('<div class="playicon"></div>');
            var imageheight = jQuery(this).attr("height");
            var imagewidth = jQuery(this).attr("width");
            jQuery(this).parent().find('.playicon').css('height', imageheight).css('width', imagewidth);
            var newmargintop = imageheight + 7;
            jQuery(this).parent().find('.playicon').css('margin-top', -(newmargintop));
            jQuery(this).parent().parent('.videospot').find('.playicon').css('margin-top', -(newmargintop + 20));
            if (isNaN(majorVersion)) {
                fullVersion = '' + parseFloat(navigator.appVersion);
                majorVersion = parseInt(navigator.appVersion, 10);
            }
            if (navigator.appName == 'Microsoft Internet Explorer') {
                if (fullVersion <= 7) {
                    newmargintop = imageheight;
                    jQuery(this).parent().find('.playicon').css('margin-top', -(newmargintop));
                    jQuery(this).parent().parent('.videospot').find('p').css('margin-top', 24);
                }
            }
        });

    },
    initGallery: function (carousel, id) {
        //Image carousel
        var galleryTimer;
        jQuery('.carousel').each(function (i) {

            //used to disable auto satrt on small gals
            if (jQuery(this).parent().parent().hasClass("vt-three")) {
                galleryTimer = 0
            }
            else {
                galleryTimer = 7000
            }
            jQuery(this).addClass('carousel' + i),
                jQuery(this).find('.carousel-content').cycle({
                    fx: 'scrollHorz',
                    rev: 0,
                    timeout: galleryTimer,
                    before: sbvUtils.GalleryPrevFunctions(this, i),
                    //after: sbvUtils.GalleryAfterFunctions(this, i),
                    next: '.carousel' + i + ' .gallery-nav-next',
                    prev: '.carousel' + i + ' .gallery-nav-prev',
                    pause: 1,
                    pager: '.carousel' + i + ' .gallery-nav-stepper'
                });
            var stopObjects = jQuery(this).find('.carousel-content');
            stopObjects.click(function () {
                jQuery(this).find('.carousel-content').cycle('pause');
            });
            jQuery('.gallery-nav-prev').click(function () {
                stopObjects.cycle('pause');
            });

            jQuery('.gallery-nav-next').click(function () {
                stopObjects.cycle('pause');
            });
            jQuery('.gallery-nav-stepper').find('a').click(function () {
                stopObjects.cycle('pause');
            });

        });


    },
    DefaultSearchText: function (group) {
        group.each(function () {
            //Default search text handler
            var DefaultTextHolder = jQuery(this).attr('title');
            jQuery(this).focus(function (srcc) {
                jQuery(this).addClass('fieldActive');
                if (jQuery(this).attr("value") == DefaultTextHolder) {
                    jQuery(this).val('');
                }
            });
            jQuery(this).blur(function () {

                if (jQuery(this).val() == '') {
                    jQuery(this).removeClass('fieldActive');
                    jQuery(this).val(DefaultTextHolder);
                }
            });
            jQuery(this).blur();
        });
    },
    pageSearch:
	{
	    init: function () {
	        var $txtSearch = jQuery('#txtSearch'); //Looks for the inputfield for the searchstring
	        if ($txtSearch.length) {
	            $txtSearch.keydown(function (event) {
	                if (event.keyCode == '13') { // Catch the 'enter' event
	                    sbvUtils.pageSearch.doSearch($txtSearch); //Do the search
	                    return false;
	                };
	            });
	            var $btnSearch = jQuery('#btnSearch'); //Looks for the searchbutton
	            $btnSearch.click(function () { // Set click action for the button
	                sbvUtils.pageSearch.doSearch($txtSearch); //Do the search
	                return false;
	            });
	        }
	    },
	    doSearch: function ($txtSearch) {
	        if ($txtSearch.val() != $txtSearch.attr('title')) { // If the searchstring is different from the default helptext
	            var searchUrl = jQuery('#searchUrl').val(); //Look for the url

	            if (searchUrl != '') {
	                window.location.href = searchUrl + jQuery('#txtSearch').val(); //load the searchpage with the new query
	            }
	        };
	    }
	},
    toggleEditMode: function () {
        var togglers = jQuery('.toogleedit');

        togglers.each(function () {
            jQuery(this).find('dt').click(function () {
                jQuery(this).parent().toggleClass('off');
            })
        })
    },
    initDropDownNavigation: function () {
        var timeout = 500;
        var closetimer = 0;
        var ddmenuitem = 0;
        function sbvddm_open() {
            sbvddm_canceltimer();
            sbvddm_close();
            ddmenuitem = jQuery(this).find('ul').css('visibility', 'visible').fadeIn("slow");
        }
        function sbvddm_close()
        { if (ddmenuitem) ddmenuitem.css('visibility', 'hidden'); }

        function sbvddm_timer()
        { closetimer = window.setTimeout(sbvddm_close, timeout); }

        function sbvddm_canceltimer() {
            if (closetimer) {
                window.clearTimeout(closetimer);
                closetimer = null;
            }
        }
        jQuery('.topmenu > li').bind('mouseover', sbvddm_open)
        jQuery('.topmenu > li').bind('mouseout', sbvddm_timer)
        jQuery('#topmenu-right > li').bind('mouseover', sbvddm_open)
        jQuery('#topmenu-right > li').bind('mouseout', sbvddm_timer)
        document.onclick = sbvddm_close;
    },
    Overlay: function ($overlays) {
        $overlays.each(function () {
            jQuery(this).overlay({
                mask: '#000000',
                top: 40,
                fixed: false,
                onBeforeLoad: function () {
                    //jQuery('#lightbox-overlay').append('<div class="contentWrap"></div>');
                    jQuery('#lightbox-content').append('<div class="lightboxcontentWrap"></div>');
                    var wrap = this.getOverlay().find(".lightboxcontentWrap");

                    wrap.load(this.getTrigger().attr("href"));
                },
                onClose: function () {
                    jQuery('.lightboxcontentWrap').remove();
                }
            });
        });
    },
    execQuery: function (videoitemid) {

        jQuery.ajax({
            url: '/Json.asmx/GetTaxonomiVideos',
            dataType: 'json',
            data: "{ videoitemid: '" + videoitemid + "', variation: '4', searchroot: '{6C5D9EE7-125A-433D-BB1D-4EC4B6C86725}' }",
            contentType: "application/json; charset=utf-8",
            type: 'POST',
            success: function (data) {
                if (jQuery.parseJSON(data.d).length == '0') { }
                else { jQuery("#related-videos").css("background", "url(/resources/TFDK/img/icons/ajax-loader.gif) no-repeat center center"); sbvUtils.buildItems(jQuery.parseJSON(data.d)); }
            },
            error: function () {
                //                console.log('error');
            }
        });
    },
    buildItems: function (data) {

        var items = [];

        jQuery.each(data, function () {
            items.push('<div class="related-video ' + this.Theme + '"><a href="javascript:void(0);" title="' + this.VideoTitle + '" rel="' + this.ItemID + '"><span>' + this.VideoTitle + '</span><div class="theme-image"><img src="' + this.VideoImage + '?mw=226" height="115" width="226" rel="' + this.VideoID + '" /><div class="themepopper-fake"> </div><div class="themepopper">' + this.Theme + '</div><p class="rel-video-descp">' + this.Description + '</p><div class="playicon" style="height: 115px; width: 226px; margin-top: -120px;"></div></div></a></div>');
        });

        if (jQuery("#related-videos").length == '0') {
            jQuery('<div/>', {
                'id': 'related-videos',
                html: items.join('')
            }).fadeIn("slow").appendTo('#playercontainer');
            jQuery("#related-videos").css("background", "none");

        }
        else {
            jQuery("#related-videos").html(items.join(''));
            jQuery("#related-videos").css("background", "none");
        }

        sbvUtils.ThemePopper();

        jQuery("#related-videos .related-video a").click(function () {
            jQuery("#vimeoplayer").remove();
            var vimeoURL = 'http://player.vimeo.com/video/' + jQuery("img", this).attr("rel") + '?title=0&byline=0&portrait=0&api=1&autoplay=1';
            jQuery("#playercontainer #selected-video-container .rel-video-container").before('<iframe src="' + vimeoURL + '" width="450" height="253" frameborder="0" id="vimeoplayer"></iframe>');
            jQuery("#playercontainer h1").text(jQuery(this).attr("title"));
            jQuery("#playercontainer .rel-video-container").text(jQuery(".rel-video-descp", this).text());
            jQuery(".related-video").remove();
            sbvUtils.execQuery(jQuery(this).attr("rel"));
        });

    }
};


/*Ready events*/
jQuery(document).ready(function ()
{
    sbvUtils.init();
    if (!jQuery("body").hasClass("pageeditor")) {
        TFGaUtils.init();
    }
});

jQuery(window).load(function () {
    sbvUtils.equalheight();
});



  
