﻿/* Author: 
Stefan Lisper Know IT 2011-01
*/


var doPageBgResize = true;
var options = {
    sliderTimeout:2000,
    disableIngressItalics:true
};
var timers = {};


function onPageReady(opts) {   
    $.extend(options, opts);
    initPageBg();
    initQuickSearch();
    initCardSlider();
    initSubmenu();
    initFAQ();
    initInfoList();
    initStylishSelects();
    fixIE();
    setCardComparisonReflection();
    updatexForms();
    fixPagination();
    shortenReadMoreLinksInSectionPages();

    if (options.disableIngressItalics) {
        $('html').addClass('disableIngressItalics');
    }
       
    //addImageIconsToFiles();

    replaceCufonFonts();
    Cufon.now();

    initMainNav(); //has to come after cufon substitution since some functionality depends on the list items having their final widths
}


function shortenReadMoreLinksInSectionPages() {
    var $links = $('a[data-readmore]');
    $links.prev().each(
        function(){
            try{
                var $this = $(this);
                var $ingress = $this.closest('.ingress');
                var $img = $ingress.prevAll('a, img'); //might be an img or an img wrapped in a href
                var boundary = $img.offset().top + $img.outerHeight() + 5;
                var ingressOffset = $ingress.offset().top;
                
                
                if((ingressOffset + $ingress.outerHeight())>boundary) {
                    setTimeout(function(){helper()},0);           
                }                

                function helper(){
                    $this.text($this.text().substr(0, $this.text().length - 8) + '...');
                    
                    if((ingressOffset + $ingress.outerHeight())>boundary) {
                        setTimeout(function(){helper()},0);           
                    }
                }
            }catch(e){}
        }
    );
}


//convert checkboxes into stylable markup
(function($) {
    $.fn.convertCheckbox = function(){        
        return this.each(
            function(){
                var $this = $(this).hide();

                //add stylable html
                var cls = $this.attr('class');
                var $replacement = $('<span class="convertedInput checkbox' + (cls!='' ? ' '+cls : '') + ($this.is(':checked') ? ' checked'  : '') + ($this.is(':disabled') ? ' disabled'  : '') + '"></span>');
                if($('html.ie7').length != 0) $this.before('<div class="clearfix"></div>');
                    
                $this.after($replacement);

                //bind click to update associated input and classnames of stylable checkbox
                $('label[for="'+$this.attr('id')+'"]').removeAttr('for').add($replacement).click(
                    function(){
                        if($this.is(':disabled')) return;
                        $replacement.toggleClass('checked');
                        $this.attr('checked',$replacement.hasClass('checked'));
                    }
                );
            }
        );
    };
})(jQuery);


//convert radiobuttons into stylable markup
(function($) {
    $.fn.convertRadio = function(){        
        return this.each(
            function(){
                var $this = $(this).hide();
                var $members = $('input[name="'+$this.attr('name')+'"]').not($this);

                //add stylable html
                var cls = $this.attr('class');
                var $replacement = $('<span class="convertedInput radio' + (cls!='' ? ' '+cls : '') + ($this.is(':checked') ? ' checked'  : '') + ($this.is(':disabled') ? ' disabled'  : '') + '"></span>');
                $this.after($replacement);
                if($('html.ie7').length != 0) $this.before('<div class="clearfix"></div>');

                //bind click to update associated input and classnames of stylable radio
                $('label[for="'+$this.attr('id')+'"]').removeAttr('for').add($replacement).click(
                    function(){
                        if($this.is(':disabled')) return;
                        $members.next().removeClass('checked');
                        $replacement.addClass('checked');
                        $this.attr('checked',true);
                    }
                );
            }
        );
    };
})(jQuery);

    
//converts the markup of the asp:DataPager to the site's markup for a paginator
function fixPagination() {
    var $pagi = $('.pagination.update_html');

    if($pagi.length == 0) return;

    $pagi.html($pagi.html().replace(/&nbsp;/ig,''));
    var $topspan = $('>span', $pagi);
    var $selected = $('span', $topspan);
    var $pages = $('a:not(:first):not(:last)', $topspan);
    var $prev = $('a:first', $topspan).text('');
    var $next = $('a:last', $topspan).text('');

    $topspan.wrapInner('<ul></ul>');
    $prev.wrap('<li class="prev"></li>').before('<div></div>').click(function(){fixPaginationTimer();});
    $next.wrap('<li class="next"></li>').before('<div></div>').click(function(){fixPaginationTimer();});
    $selected.wrap('<li class="selected"></li>').parent().html($selected.text()).append('<div></div>');
    $pages.each(
        function(){
            var $this = $(this);
            $this.wrap('<li></li>').parent().html($this.text()).append($this).append('<div></div>');
            $this.text('').click(function(){fixPaginationTimer();});
        }
    );
}

    
//since the asp:DataPager does not supply a callback we set a timer instead
function fixPaginationTimer() {
    var $topspan = $('.pagination.update_html > span');
        
    if($('ul', $topspan).length == 1) {
        setTimeout(function(){fixPaginationTimer()}, 100);
    }else{
        fixPagination();    
    }
}


function updatexForms() {
    var $xForm = $('.xForm');
    $xForm.find('input[type="text"], input[type="password"]').wrap('<div class="form_wrapper input"></div>');
    $xForm.find('textarea').wrap('<div class="form_wrapper textarea"></div>');
    var $submit = $xForm.find('input[type="submit"]');
    $submit.each(
        function(){
            var $this = $(this);
            $this.wrap('<div class="button type_1"></div>').before('<div class="text">' + $this.val() + '</div>').before('<div class="icon"></div>');
        }
    );

    $('.xForm input[type="checkbox"]').convertCheckbox();
    $('.xForm input[type="radio"]').convertRadio();
    $('.xForm br').remove();
}


function initStylishSelects() {
    $('.stylish_select, .xForm select').addClass('stylish_select').sSelect();
}


function replaceCufonFonts() {
    replaceCufonAkzidenz();
    replaceCufonHelveticaNeue();
}


function replaceCufonAkzidenz() {
    var selectors = [];
    selectors.push('div#content div.left_content div.main article.FAQ h2');
    selectors.push('div#content div.left_content div.main article.informationList h2');
    selectors.push('footer#page_footer div.column h1');
    selectors.push('div.puff.type_1 h1');
    selectors.push('div.puff.type_2 h1');
    selectors.push('div.puff.type_3 h1');
    selectors.push('div.puff.type_4 h1');
    selectors.push('div.puff.type_5 h1');
    selectors.push('div.cardslider div.card h1');
    selectors.push('div#content div.left_content div.main article > h1');
    selectors.push('div.contact_form section h1');
    selectors.push('div.search_hits section h1');
    Cufon.replace(selectors.join(','), { fontFamily: 'akzidenz' });
}


function replaceCufonHelveticaNeue() {
    var selectors = [];
    selectors.push('nav#main_nav > ul > li > a span');
    Cufon.replace(selectors.join(','), {
        textShadow: '#000 1px 0 0 0'
    });

    selectors.length = 0;
    selectors.push('nav.submenu span');
    selectors.push('.card_comparison h2');
    selectors.push('.puff.type_6 h1');
    Cufon.replace(selectors.join(','));

    selectors.length = 0;
    selectors.push('div.button.type_1 div.text');
    selectors.push('div.button.type_3 div.text');
    Cufon.replace(selectors.join(','), {
        fontFamily : 'helvetica neue',
        textShadow: '#B54E07 3px 2px 2px'
    });

    selectors.length = 0;
    selectors.push('div.button.type_4 div.text');
    Cufon.replace(selectors.join(','), {
        fontFamily : 'helvetica neue',
        textShadow: '#222222 3px 2px 2px'
    });

    selectors.length = 0;
    selectors.push('div.button.type_2 div.text');
    Cufon.replace(selectors.join(','), {
        fontFamily: 'helvetica neue',
        textShadow: '#000 3px 2px 2px'
    });
}


//makes sure that all reflections are the same height in the card comparison area
function setCardComparisonReflection() {
    var $comps = $('.card_comparison img[class*=ropacity]');

    if ($comps.length == 0) return;

    var reflPercent = 39; //percentage of img height that the reflection should be

    var minHeight = $($comps[0]).height(), temp;

    for (var i = 1; i < $comps.length; i++) {
        temp = $($comps[i]).height();
        minHeight = (temp < minHeight) ? temp : minHeight;
    };

    var reflHeight = (reflPercent / 100) * minHeight;

    $comps.each(
		function () {
			var $img = $(this);

			if ($img.height() > minHeight) {
			    $img.addClass('rheight' + (reflHeight / $img.height()) * 100);
			} else {
			    $img.addClass('rheight' + reflPercent);
			}
		}
	);

    addReflections($.makeArray($comps));
}


function fixIE() {
    var $ie7 = $('html.ie7');
    var $html = $ie7.add('html.ie8');
    //fix last li in IE
    $html.find('#main_nav, nav.breadcrumbs').find('li:last').addClass('last');
    $html.find('.section_page:last').addClass('last');
    $ie7.find('.breadcrumbs li:last').addClass('last');
    $html.find('.card_comparison:last').addClass('last');
}


//sets position for all the megamenu dropdowns
function initMainNav() {
    var $mainNav = $('nav#main_nav');
    var $dropdowns = $('> ul > li div.dropdown:not(.multipleCards)', $mainNav);

    $dropdowns.each(
        function () {
            centerMegaMenuDropdown($(this), $mainNav);
        }
    );

    //set the li.cover width so that it covers last li
    var $cover = $('div.cover', $mainNav);
    var $last = $('> ul > li:last', $mainNav);
    $cover.css('left', $last.position().left + 'px')

    timers.mainNav = {}; //init timer container object
    var timeout = 300;

    //make it so that user can move mouse over adjacent <li> on the way to current megamenu without switching megamenu
    var $topItems = $('> ul > li', $mainNav)
    $topItems.hover(
        function () {
            var $this = $(this);

            clearTimeout(timers.mainNav.hide);
            timers.mainNav.hide = null;
                
            timers.mainNav.show = setTimeout(
                function() {
                    $topItems.removeClass('showDropdown');
                    $this.addClass('showDropdown');
                },
                timeout
            );
        },
        function () {
            var $this = $(this);
            clearTimeout(timers.mainNav.show);
            timers.mainNav.show = null;             
   
            timers.mainNav.hide = setTimeout(
                function(){
                    $topItems.removeClass('showDropdown');
                },
                timeout
            );
        }
    );
}


function centerMegaMenuDropdown($dropdown, $mainNav) {
    var width = $dropdown.outerWidth();
    var $li = $dropdown.closest('li');
    var cssLeft = $li.position().left + parseInt(($li.outerWidth() / 2));
    var marginLeft = parseInt(width / 2);

    //modify margin left so that dropdown always stays within 10px from either end of main nav
    if ((cssLeft - marginLeft) < 10) { //check left
        marginLeft = cssLeft - 10;
    }
    else if((cssLeft - marginLeft + width) > $mainNav.outerWidth()) { //check right side
        marginLeft = marginLeft + ((cssLeft - marginLeft + width) - $mainNav.outerWidth()) + 10;
    }

    marginLeft = marginLeft / -1; //negative margin left moves the dropdown from center of li

    $dropdown.css({'left':cssLeft, 'margin-left':marginLeft, 'display':'none'});
}


function initPageBg() {
    var $html = $('html');
    var $img = $('img#page_bg');
        

    $img.css('width', $(document).width() - ($html.hasClass('ie8') || $html.hasClass('ie9') ? ($html.hasClass('ie9') ? 16 : 21) : 0) + 'px');

    $(window).resize(
		function () {
			if ($html.hasClass('ie7') || $html.hasClass('ie8')) {
			    if (doPageBgResize) {
			        $img.hide();
			        setTimeout(function () { $img.css('width', $(document).width() - ($html.hasClass('ie8') ? 21 : 0) + 'px').show(); }, 0);
			    }
			} else {
                if($html.hasClass('ie9')) {
                    $img.hide().css('width', $(document).width() - 16 + 'px').show();
                }else{
			        $img.hide().css('width', $(document).width() + 'px').show();
                }
			}
		}
	);
}


function initQuickSearch() {
    var $quickSearch = $('div.quick_search');
    var $input = $('input.search', $quickSearch);
    var $label = $('label', $quickSearch);

    $label.click(
        function (ev) {
            $('input.search', $(this).closest('div.quick_search')).focus();
        }
    );

    $input.each(
        function () {
            var $this = $(this);

            //if this does not have autocomplete functionality then only bind blur and focus
            if (!$this.closest('div.quick_search').hasClass('withAutocomplete')) {
                $this
                .blur(
                    function (ev) {
                        var $target = $(ev.target);
                        if ($target.val() == '') {
                            $target.closest('div.quick_search').find('label').show();
                        }
                    }
                )
                .focus(
                    function (ev) {
                        $(ev.target).closest('div.quick_search').find('label').hide();
                    }
                );
                return;
            }

            $this.autocomplete(
			    {
			        source: function (request, response) {
			            $.ajax({
			                type: "POST",
			                url: "/Templates/Public/Pages/SearchPage.aspx/Search",
			                data: "{'searchtext':'" + request.term + "', 'lang':'" + options.lang + "'}",
			                contentType: "application/json; charset=utf-8",
			                dataType: "json",
			                success: function (data) {
			                    response(eval(data.d));
			                }
			            })
			        },
			        select: function (event, ui) {
			            window.location.replace(ui.item.url);
			            return false; //Cancelling the default action (default action of select is to replace the text field's value with the value of the selected item) 
			        },
			        open: function (event, ui) {
			            $('ul.ui-autocomplete').prepend('<li class="header">' + options.pageSearchHeader + '</li>');
			        }
			    }
		    )
		    .focus(function (ev) {
		        $(ev.target).closest('div.quick_search').find('label').hide();

		    })
		    .blur(function (ev) {
		        var $target = $(ev.target);
		        if ($target.val() == '') {
		            $target.closest('div.quick_search').find('label').show();
		        }
		    })
		    .data("autocomplete")._renderItem = function (ul, item) {
		        return $('<li></li>')
				    .data('item.autocomplete', item)
				    .append('<a href="' + item.url + '"><img src="' + item.img + '" /><h1>' + item.label + '</h1>' + item.text.replace(new RegExp(item.searchstring,'igm'), '<span class="mark">' + item.searchstring + '</span>') + '</a>')
				    .appendTo(ul);
		    };

            checkQuickSearchForContent(1, $this);
        }
    );
}


//remove label if browser has autofilled value
function checkQuickSearchForContent(iteration, $input, timeout) {
    if (iteration == 15) return; //wait 5s and then assume browser will not autofill
    if (!timeout) timeout = 333;

    if ($input.val() != '') {
        $input.trigger('focus');
    } else {
        setTimeout(function () { checkQuickSearchForContent(iteration + 1, $input, timeout) }, timeout);
    }
}


function initCardSlider() {
    var $sliders = $('.cardslider');

    $sliders.each(
        function () {
            var $slider = $(this);
            var $cardwrapper = $('.cards', $slider);
            var $cards = $('.card', $slider);
            var $ctrls = $('.position', $slider);
            var cardWidth = $($cards.get(0)).outerWidth();
            $slider[0].selIndex = 0;

            if ($ctrls.length > 1) {
                $ctrls.each(
			        function (index) {
			            $(this).click(
					        function () {
					            ctrlSlide(index, $slider[0], $ctrls, $cardwrapper, cardWidth);
					        }
				        );
			        }
		        );

                $slider[0].timer = setTimeout(function () { autoSlide(1, $slider[0], $ctrls, $cardwrapper, cardWidth) }, options.sliderTimeout);
            }
            else {
                $ctrls.hide();
            }
        }
    );
}

    
//handles stuff when user clicks one of the scroll position ctrls
function ctrlSlide(index, slider, $ctrls, $cardwrapper, cardWidth) {
    clearTimeout(slider.timer);
        
    //don't want to mix animation and user clicks since things gets mixed up
    if($cardwrapper.is(':animated')) {
        return;
    }

    var targetIndexLess = (index < slider.selIndex);
        
    //reset the controls and amrk the new one as selected
    $ctrls.removeClass('selected');
    $($ctrls[index]).addClass('selected');        

    var cardsBetweenCurrentAndTarget = 0;

    if(targetIndexLess){
        cardsBetweenCurrentAndTarget = ($ctrls.length - slider.selIndex) + index;
    }else{
        cardsBetweenCurrentAndTarget = index - slider.selIndex;
    }

    slider.selIndex = index;

    //animate the wrapper and then move leftmost card to the end so that slider can keep sliding cards from right to left
    $cardwrapper.animate(
        { 'margin-left': ((cardsBetweenCurrentAndTarget/-1) * cardWidth) + 'px' }
        , 1000
        , function() {
            $cardwrapper.append($('.card:lt(' + cardsBetweenCurrentAndTarget + ')', $cardwrapper)).removeAttr('style');
            slider.timer = setTimeout(function () { autoSlide(index + 1, slider, $ctrls, $cardwrapper, cardWidth) }, options.sliderTimeout);        
        }
    );
}


//handles stuff when slider slides automatically
function autoSlide(index, slider, $ctrls, $cardwrapper, cardWidth) {      
    if (index >= $ctrls.length) {
        index = 0;
    }

    slider.selIndex = index;

    clearTimeout(slider.timer);

    $ctrls.removeClass('selected');
    $($ctrls[index]).addClass('selected');

    var $first = $('.card:first', $cardwrapper);

    $cardwrapper.animate(
		{ 'margin-left': '-' + cardWidth + 'px' }
		, 1000
        , function () {
            $cardwrapper.append($first).css('margin-left', '0');
            slider.timer = setTimeout(function () { autoSlide(index + 1, slider, $ctrls, $cardwrapper, cardWidth) }, options.sliderTimeout);
        }
	);
}


function initSubmenu() {
    var $sub = $('nav.submenu');
    var $sel = $('a.selected', $sub);

    if ($sel.hasClass('parent')) {
        $sel.addClass('open');
    } else {
        $sel.closest('div').prev().addClass('open');
    }
        
    $('a.header', $sub).attr('href', $('nav#main_nav li.selected > a').attr('href'));
}


function initFAQ() {
    var $allFAQ = $('.FAQ');

    $('h2', $allFAQ).click(
		function () {
			doPageBgResize = false;
			var $FAQ = $(this).closest('.FAQ');
            $FAQ.siblings('.open').find('h2').click();
			$FAQ.find('.items').slideToggle('slow', function () { $FAQ.toggleClass('open'); doPageBgResize = true; });
		}
	);

    //add the print controls
    $('.item:last .wrapper:last', $allFAQ).after($('<div class="ctrl print" title="' + options.printTooltip + '"></div>').click(function (ev) { printFAQ(ev.target); }));
}


function initInfoList() {
    var $allInfo = $('.informationList');

    $('h2', $allInfo).click(
		function () {
			doPageBgResize = false;
			var $info = $(this).closest('.informationList');
			$info.find('.additional').slideToggle('slow', function () { $info.toggleClass('open'); doPageBgResize = true; });
		}
	);

    //add the print controls
    $('.print', $allInfo).click(function (ev) { printInfoList(ev.target); });
}


function printMainArticles() {
    printItems($('div.left_content div.main article'));
}


function printInfoList(infolist) {
    printItems($(infolist).closest('article'));
}    


function printFAQ(faq) {
    printItems($(faq).closest('article'));
}


//Prints a card comparison page
//This requires a bit more thinking than usual due to the non-linear way the markup is rendered
function printCardComparison() {
    var $content = $('div.left_content div.main');
    var $print_me = $('article', $content);

    var $images = $('section.card_comparison div.image', $content);
    var $info = $('section.card_comparison div.info:not(.btn)', $content);

    $images.each(
		function (index) {
			var $temp = $('<div></div>')
				.append($(this).clone())
				.append(
					$($info[index]).clone()
				);

			$print_me = $print_me.add($temp);
		}
	);

    printItems($print_me);
}


function printItems($items) {
    var popup = window.open('/print.htm', '', 'left=-200,top=-200,width=1,height=1,toolbar=0,scrollbars=0,status=0,directories=0');
    popup.blur();
    window.focus();
        

    //YES, what usually works when these kinds of things is to open a popup without URL, fill it with content and then print it, BUT
    //IE suddenly refused to print at all with the previous solution so the below was created after many hours of blindly fumbling through the darkness that is IE, but at least this works post IE-meltdown
    setTimeout(
        function() {
            if (options.printLogo && options.printLogo != '') {
                $(popup.document.body).append('<div id="print_logo"><img src="' + options.printLogo + '" /></div>');
            }
            else{
                $(popup.document.body).append('<div id="print_logo"><img src="/templates/public/styles/images/print_logo.jpg" /></div>');
            }
                
            $items.each(
			    function () {
                    $(popup.document.body).append('<div class="print_item ' + $(this).attr('class') + '">' + cleanCufonForPrint($(this).html()) + '</div>');
			        
                    function cleanCufonForPrint(txt) {
                        var pre = /<cufon[^>]*>[\s\S]*?<cufontext>/igm;
                        var post = /<\/cufontext>[\s\S]*?<\/cufon>/igm;
                        return txt.replace(pre, '').replace(post, '');
                    }
                }
		    );
                
            var now = new Date();

            $(popup.document.body).append(options.printDate + now.getFullYear() + '-' + $().padNum(now.getMonth() + 1, 2, '0') + '-' + now.getDate());
                        
            setTimeout(function(){popup.print();popup.close();}, 2000); //Give images some time to load
        }
        , 2000
    );
}


jQuery.fn.padNum = function (pad_str, pad_lim, pad_with) {
    pad_str = pad_str.toString();
    var pad_length = pad_lim - pad_str.length;
    for (i = 0; i < pad_length; i++) {
        pad_str = pad_with + pad_str;
    }
    return pad_str;
};



//YouTube
function youTube(playerId, callback) {
    var $ytplayer = $('#'+playerId);
    setInterval(updateytplayerInfo, 250);
    updateytplayerInfo();
    $ytplayer.bind('StateChange', function(){onytplayerStateChange();});
    $ytplayer.bind('Error', function(){onPlayerError();});


    $('.ctrl.play').click(function(){play();});
    $('.ctrl.pause').click(function(){pause();});
    $('.ctrl.stop').click(function(){stop();});
    $('#ThumbNailList a').live(
        'click',
        function(){
            eval('cueNewVideo('+$(this).attr('data-params')+')');
        }
    );

    eval(callback);



    function updateHTML(elmId, value) {
        $('#'+elmId).html(value);
        //document.getElementById(elmId).innerHTML = value;
    }


    function setytplayerState(newState) {
        updateHTML("playerstate", newState);
    }


    function onytplayerStateChange(newState) {
        setytplayerState(newState);
    }


    function onPlayerError(errorCode) {
        alert("An error occured: " + errorCode);
    }


    function updateytplayerInfo() {
        updateHTML("videotime", getCurrentTime());
    }


    function cueNewVideo(id, startSeconds, duration, title) {
        if ($ytplayer.length != 0) {
            $ytplayer[0].cueVideoById(id, startSeconds);
            updateHTML("videoduration", formatTime(duration));
            updateHTML("videodescription", title);
        }
    }


    // functions for the api calls
    function loadNewVideo(id, startSeconds) {
        if ($ytplayer.length != 0) {
            startSeconds = "0";
            $ytplayer[0].loadVideoById(id, parseInt(startSeconds));
        }
    }


    function play() {
        if ($ytplayer.length != 0) {
            $ytplayer[0].playVideo();
        }
    }


    function pause() {
        if ($ytplayer.length != 0) {
            $ytplayer[0].pauseVideo();
        }
    }

    function stop() {
        if ($ytplayer.length != 0) {
            $ytplayer[0].stopVideo();
            $ytplayer[0].stopVideo();
        }
    }

    function getPlayerState() {
        if ($ytplayer.length != 0) {
            return $ytplayer[0].getPlayerState();
        }
    }

    function getCurrentTime() {
        if ($ytplayer.length != 0) {
            return formatTime($ytplayer[0].getCurrentTime());
        }
    }
           
    function formatTime(seconds){
        var totalseconds = parseInt(seconds);
        var seconds = totalseconds % 60;
        var minutes = parseInt(totalseconds / 60);
        return minutes+":"+seconds;
    }

    function getDuration() {
        if ($ytplayer.length != 0) {
            return formatTime($ytplayer[0].getDuration());
        }
    }

    function clearVideo() {
        if ($ytplayer.length != 0) {
            $ytplayer[0].clearVideo();
        }
    }
}
