﻿jQuery.noConflict();

my_slideshowActive = false;
var slideshowTimer;
var AllowDownloads = false;

var sbvUtils = {
    init: function () {
        // onload functions
        sbvUtils.DefaultSearchText(jQuery('.top-search-field, .pagesearch'));
        sbvUtils.toggleEditMode();
        sbvUtils.pageSearch.init();
        sbvUtils.VideoHandler();
        sbvUtils.topMenuToggle();
        sbvUtils.Overlay(jQuery('a.overlay[rel]'));
        sbvUtils.ElectionCandidateSlider();
        //TFGaUtils.init();

        sbvUtils.linkTextShortener(jQuery('.frontpagenewsspot .nmlspotlist ul.sbvlist li span.header'), 50);

        jQuery("body:not('.pageeditor') img.imagereflection").reflect({ height: "30", opacity: 0.5 });
    },
    linkTextShortener: function ($elements, maxLength) {
        $elements.each(function () {
            var str = jQuery.trim(jQuery(this).text());
            if (str.length > maxLength) {
                var escapedStr = escape(str.substring(0, maxLength));
                jQuery(this).text(unescape(escapedStr.substring(0, escapedStr.lastIndexOf('%20'))) + '...');
            }
        });
    },
    ElectionCandidateSlider: function () {
        //code here
    },
    GalleryPrevFunctions: function (carousel, id) {
        //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>');
        }
    },
    topMenuToggle: function () {
        jQuery('#top .topmenu a.toggler').click(function (event) {
            if (jQuery('#dropdown').data('trigger') == jQuery(this).attr('id')) {
                jQuery('#dropdown').data('trigger', '').slideUp('fast');
                jQuery(this).removeClass('trigger');
            }
            else {
                jQuery('.trigger').removeClass('trigger');
                jQuery('#dropdown').data('trigger', jQuery(this).attr('id')).html(jQuery(this).next('div').html());
                jQuery('#dropdown .groupcontainer').css({ 'left': (jQuery(this).position().left + 38) });
                jQuery('#dropdown').slideDown('fast');
                jQuery(this).addClass('trigger');
                if (jQuery(this).attr('id') == 'toggler5') {
                    jQuery('#dropdown .groupcontainer').css("left", "465px");
                };
            }
            event.preventDefault();
        });



    },
    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", "#overlay");
            jQuery(this).addClass("overlay");
        });
    },
    setNewHeightContentPage: function () {
        // Check if editormode
        if (typeof Sitecore == 'undefined' && !jQuery('body').hasClass('preview')) {
            jQuery('.equalheightFP').children().eq(0).css('margin-left', 10);
            jQuery('.equalheightFP').children().eq(3).css('margin-right', 0);
            var outerobject;
            var rowamount;
            if (jQuery('.row').hasClass('row-nine')) {
                outerobject = jQuery('.row-nine');
                rowamount = 3;
            }
            else if (jQuery('.row').hasClass('row-six')) {
                outerobject = jQuery('.row-six');
                rowamount = 2;
            } else if (jQuery('.row').hasClass('equalheightFP')) {
                outerobject = jQuery('.equalheightFP');
                rowamount = 4;
            } else if (jQuery('.frontpage .row-twelve').hasClass('group')) {
                outerobject = jQuery('.frontpage div.group');
                rowamount = 4;
            } else if (jQuery('.row-twelve').children().hasClass('sitemap')) {
                outerobject = jQuery('.sitemap');
                rowamount = 4;
            } else { return; }

            outerobject.each(function (index) {
                var object;
                if (outerobject.eq(index).hasClass('listcontainer')) {
                    if (outerobject.eq(index).find('.sbvlist').parent().hasClass('spotlist')) {
                        outerobject.eq(index).find('.sbvlist').each(function (index2) {
                            object = outerobject.eq(index).find('.sbvlist').eq(index2).children();
                            runEqualHeight(object);
                        });

                    } else { return; }
                } else if (outerobject.eq(index).hasClass('spotcontainer')) {
                    object = outerobject.eq(index).children();
                    runEqualHeight(object);
                } else if (outerobject.eq(index).hasClass('equalheightFP')) {
                    object = outerobject.eq(index).children();
                    runEqualHeight(object);
                } else if (outerobject.eq(index).hasClass('group')) {
                    object = outerobject.eq(index).children();
                    runEqualHeight(object);
                } else if (outerobject.eq(index).hasClass('sitemap')) {
                    object = outerobject.eq(index).children().children().children().children();
                    runEqualHeight(object);
                } else { return; }
                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).addClass('htc');
                            }

                            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('.vt-three').find('.content').find('a.overlay').find('img').each(function () {
            jQuery(this).parent().parent('li').addClass('videolistspot');
            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('.videolistspot').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) {
                    var newmargintop = imageheight;
                    jQuery(this).parent().find('.playicon').css('margin-top', -(newmargintop));
                    jQuery(this).parent().parent('.videolistspot').find('p').css('margin-top', 24);
                }
            }
        });

        jQuery('#main').find('.spotlist').find('.sbvlist').find('a.overlay').find('img').each(function () {
            jQuery(this).parent().parent('li').addClass('videolistspot');
            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('.videolistspot').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) {
                    var newmargintop = imageheight + 24;
                    jQuery(this).parent().find('.playicon').css('margin-top', -(newmargintop));
                    jQuery(this).parent().parent('.videolistspot').find('p').css('margin-top', 24);
                }
            }
        });

        jQuery('#main').find('.nmlspotlist').find('a.overlay').find('img').each(function () {
            jQuery(this).parent().parent('li').addClass('videolistspot');
            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('.videolistspot').find('.playicon').css('margin-top', -13);


            if (isNaN(majorVersion)) {
                fullVersion = '' + parseFloat(navigator.appVersion);
                majorVersion = parseInt(navigator.appVersion, 10);
            }
            if (navigator.appName == 'Microsoft Internet Explorer') {
                if (fullVersion <= 7) {
                    var newmargintop = imageheight + 11;
                    jQuery(this).parent().find('.playicon').css('margin-top', -(newmargintop)).css('float', 'left');

                    jQuery(this).parent().parent('.videolistspot').find('p').css('margin-top', 24);

                }
            }
        });


    },

    //Adam H
    //function for embedding youtube videos using links to youtube that are input in sitecore editor or xslt renderings.
    embedYoutubeVideos: function () {
        
        if (jQuery("body").hasClass("pageeditor")) {
            return;
        }

        jQuery(" a[href*='youtu']").each(function (i) {

            //youtube anchor may have width and height attribute. If it has then modify the standard height and width.
            var embedWidth = 480;
            if (jQuery(this).attr("width") != null) {
                embedWidth = jQuery(this).attr("width");
            }

            var embedHeight = 270;
            if (jQuery(this).attr("height") != null) {
                embedHeight = jQuery(this).attr("height");
            }

            //it has to be embed link so we do some regex
            //stackoverflow.com/questions/7168987/how-to-convert-a-youtube-video-url-to-the-iframe-embed-code-using-jquery-on-pag

            var youtubeUrl = jQuery(this).attr("href").replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe width="' + embedWidth + '" height="' + embedHeight + '" src="http://www.youtube.com/embed/$1?&rel=0&showinfo=0&theme=light&autohide=1" frameborder="0" allowfullscreen></iframe>');
            jQuery(this).replaceWith(youtubeUrl);
        });
    },


    initGallery: function (carousel, id) {
        //Image carousel
        jQuery('.carousel').each(function (i) {
            jQuery(this).addClass('carousel' + i),
                jQuery(this).find('.carousel-content').cycle({
                    fx: 'scrollHorz',
                    rev: 0,
                    timeout: 5000,
                    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');
            });
        });

        jQuery(".gallery-nav-stepper a").wrapInner("<span class='accessibility'></span>");
    },
    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');
            })
        })
    },
    Overlay: function ($overlays) {

        $overlays.each(function () {
            jQuery(this).overlay({
                mask: '#000000',
                top: 40,
                left: "center",
                api: true,
                close: jQuery('#close'),
                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"));
                    jQuery('#close').live('click', function () {
                        jQuery('#exposeMask').click();
                    });
                },
                onClose: function () {
                    jQuery('.lightboxcontentWrap').remove();
                }
            });
        });
    }
};


/*Ready events*/
jQuery(document).ready(function () {
    sbvUtils.init();
    sbvUtils.embedYoutubeVideos();
    //sbvUtils.setNewHeightContentPage();



});

/*Load events*/
jQuery(window).load(function () {
	sbvUtils.setNewHeightContentPage();
	sbvUtils.videoPlayIcon();
	sbvUtils.initGallery();
});



