// non-js filter
if (document.documentElement) {
    document.documentElement.className += "js";
}

(function ($) {
    $(document).ready(function () {

        $('div.isJSenabled input').attr('value', true); //set input value to true for .NET
        topNav.init("#nav"); 						    //Top navigation styling
        printButton.init("#footer"); 				    //Print button
        clearInputText.init(); 						    //Hide form field value on focus
        moreCategories.init(".js-more"); 			    //Show more categories
        navTabs.init(".tabs");  					    //Tabs
        imgCarousel.init(".carousel");  			    //Image carousel
        loginOverlay.init('.js-login a'); 			    //Login overlay
        $.featureList(								    //Mobile carousel
			$(".buttons li a"),
			$(".output"), {
			    start_item: 0
			}
		);
        simpleToggle.init('.accordion'); 			    //Homepage Accordion	
        tooltips.init('fieldset a.js-info'); 		    //Form tooltips	
        $('ul.panels-mobile, ul.panels-travel, ul.home-panels').equalHeights(); //Equal Heights
    });
})(jQuery);



/* ***************************************************************************************
Top navigation: Remove separator line for the first and selected links.
*/
var topNav = {
    init: function (el) {
        var $el = $(el);
        $('li.on', $el).next('li').css('background-image', 'none');
        $('li:first', $el).css('background-image', 'none');
    }
};


/* ***************************************************************************************
Print button
*/
var printButton = {
    printLink: '<span class="hidden">|</span> <a href="#" class="print">Print page</a>',
    init: function (el) {
        var $el = $(el);
        $('p.copyright', $el).append(printButton.printLink);
        $('a.print', $el).click(function (e) {
            this.blur();
            if (window.print) window.print();
            e.preventDefault();
        });
    }
};


/* ***************************************************************************************
Take title attribute of the input element and copy that value into the value attribute.
*/
var clearInputText = {
    init: function () {
        $(':input[title]').each(function () {
            var $this = $(this);
            if ($this.val() === '') {
                $this.val($this.attr('title'));
            }
            $this.focus(function () {
                if ($this.val() === $this.attr('title')) {
                    $this.val('');
                }
            });
            $this.blur(function () {
                if ($this.val() === '') {
                    $this.val($this.attr('title'));
                }
            });
        });
    }
};


/* ***************************************************************************************
Collapse/Expand links for the Classifieds page (categories)
*/
var moreCategories = {

    init: function (el) {
        var linkMore, storeList, minItems;
        var $el = $(el);
        storeList = '<div class="readMoreContent"></div>';
        linkMore = '<p class="cta"><a href="#" class="more js-link">More</a></p>';
        minItems = 5;

        $el.each(function () {
            $this = $(this);
            var $elements = $this.children('li');
            var max = $elements.length;
            if (max > minItems) {
                $('li:eq(' + minItems + ')', $this).before(storeList);
                var readMoreContent = $('.readMoreContent', $this);
                for (var a = minItems; a < max; a++) {
                    readMoreContent.append($elements[a]);
                }
                readMoreContent.hide();
                $this.after(linkMore);
            }
        });
        $('a.js-link').toggle(function (e) {
            $(this).parent().prev().find('.readMoreContent')
                .show()          
				.parent()
				.next('.cta').find('.js-link').text('Fewer')
				.removeClass('more')
				.addClass('fewer')                     
        }, function () {
            $(this).parent().prev().find('.readMoreContent')
                .hide()
				.parent()
				.next('.cta').find('.js-link').text('More')
				.removeClass('fewer')
				.addClass('more')
        });

    }
}



/* ***************************************************************************************
Tabs
*/
var navTabs = {
    currentClass: 'current', // Classname to apply to the LI of the selected Tab
    tabhead: 'h2.tabtitle', // Tag or valid Query Selector of the Elements to Transform the Tabs-Navigation from (originals are removed)
    tabbody: '.tabbody', // Tag or valid Query Selector of the Elements to be treated as the Tab Body
    fx: 'fadeIn', // can be "fadeIn", "slideDown", "show"
    fxspeed: 'slow', // speed (String|Number): "slow", "normal", or "fast") or the number of milliseconds to run the animation
    currentInfoText: 'Current tab: ', // text to indicate for screenreaders which tab is the current one

    init: function (el) {
        if ($(el).length <= 0) return false;
        $(el).each(function (i) {
            navTabs.createTabs($(el).eq(i));
        });
        return true;
    },
    createTabs: function (o) {
        var contentAnchor = navTabs.getUniqueId('accessibletabscontent');
        var tabsAnchor = navTabs.getUniqueId('accessibletabs');
        var list = '';
        var tab = 'tab'; //for custom styling of each tab	

        o.find(navTabs.tabhead).each(function (i) {
            var id = '';
            if (i === 0) {
                id = ' id="' + tabsAnchor + '"';
            }
            list += '<li role="tab" class="' + tab + i + '"><a' + id + ' href="#' + contentAnchor + '" title="' + $(this).attr('title') + '">' + $(this).text() + '</a></li>';
            $(this).remove();
        });
        o.addClass('js'); //for JS styling
        o.prepend('<ul class="tab-list" role="tabpanel">' + list + '</ul>');
        o.find(navTabs.tabbody).hide();
        o.find(navTabs.tabbody + ':first')
			.show()
			.before('<' + navTabs.tabhead + '><a tabindex="0" class="hidden" name="' + contentAnchor + '" id="' + contentAnchor + '">'
			+ o.find("ul.tab-list>li:first").text() + '</a></' + navTabs.tabhead + '>');
        o.find("ul.tab-list>li:first")
			.addClass(navTabs.currentClass)
			.find('a').prepend('<span class="hidden">' + navTabs.currentInfoText + '</span>');

        o.find('ul.tab-list li a').each(function (i) {
            $(this).click(function (event) {
                event.preventDefault();
                o.find('ul.tab-list>li.current')
					.removeClass(navTabs.currentClass)
					.find("span.hidden").remove();
                $(this).blur();
                o.find(navTabs.tabbody + ':visible').hide();
                o.find(navTabs.tabbody).eq(i).show();
                $('#' + contentAnchor).text($(this).text()).focus();
                $(this)
					.prepend('<span class="hidden">' + navTabs.currentInfoText + '</span>')
					.parent().addClass(navTabs.currentClass);
            });
        });
    },
    //generate an unique ID
    getUniqueId: function (p) {
        return p + new Date().getTime();
    }
};


/* ***************************************************************************************
Homepage Accordion
*/
var simpleToggle = {
    init: function (el) {
        if ($(el).length <= 0) return false;
        $(el).each(function (i) {
            simpleToggle.buttonAction($(el).eq(i));
        });
        return true;
    },
    buttonAction: function (o) {
        $('h3.trigger', o).click(function (e) {
            //leave at least one item opened to prevent a negative effect on IE6&7
            if ($.browser.msie && parseInt($.browser.version) <= 7) {
                if ($(this).next().is(':visible') == true) {
                    e.preventDefault();
                    return;
                }
            }
            $('h3.trigger', o).removeClass('active');
            $('.toggle_container', o).slideUp('normal');
            if ($(this).next().is(':hidden') == true) {
                $(this).addClass('active');
                $(this).next().slideDown('normal');
                //IE6&7 fix
                if ($.browser.msie && parseInt($.browser.version) <= 7) {
                    $(this).parent().parent().parent().next('.action').css({ 'position': 'relative', 'bottom': '-2.5em' });
                };
            }
            e.preventDefault();
        });
        $('.toggle_container:gt(0)', o).hide();
        $('h3.trigger:first', o).addClass('active');
    }
};


/* ***************************************************************************************
Small Image carousel (advert pages)
*/
var imgCarousel = {
    init: function (el) {
        if ($(el).length <= 0) return false;
        $(el).each(function (i) {
            imgCarousel.rotate($(el).eq(i));
        });
        return true;
    },
    rotate: function (o) {
        if (o.find('ul li').length < 2) return false;
        o.find('a').click(function (e) {
            var $this = $(this);
            var largePath = $this.attr("href");
            var largeAlt = $this.attr("title");
            o.find('li').removeClass('on');
            $this.parent('li').addClass('on');
            $(".largeImg", o).attr({ src: largePath, alt: largeAlt });
            e.preventDefault();
        });
        return true;
    }
};


/* ***************************************************************************************
Login overlay 
*/
var loginOverlay = {
    init: function () {

        //login modal light box
        $(".js-login a.hLogin").click(function (e) {

            var el = $('#loginFrame');
            var pos = $(this).offset();
            var left = pos.left;
            var top = pos.top;
            var w = el.width();
            $("#loginFrame").css({
                left: left - (w / 2) - 10 + 'px',
                top: top + 20 + 'px'
            });

            //get URL of the dialog win
            var hLoginUrl = $('.js-login input.login_url').attr('value');

            //call ajax content for the search	
            $.ajax({
                url: hLoginUrl,
                cache: false,
                success: function (html) {
                    el.contents().remove();
                    $("#loginFrame").append(html);
                    //el.find('input')[0].focus(); //focus first input in login form
                }
            });
            $('#loginFrame').fadeIn();
            return false;
        });

        //loading icon for when fetching ajax
        $(".loginLoading").ajaxStart(function () {
            $(this).show();
        });
        $().ajaxComplete(function (event, request, settings) {
            $(".loginLoading").hide();
        });

        //esc key removes dialog
        $(document).keydown(function (e) {
            if (e.which == 27) {
                loginOverlay.closeButton();
            }
        });
    }, closeButton
	: function () {
	    $("div#loginFrame").fadeOut();
	}
}


/* ***************************************************************************************
Mobile image carousel 
*/
$.fn.featureList = function (options) {
    var tabs = $(this);
    var output = $(options.output);
    new jQuery.featureList(tabs, output, options);
    return this;
};
$.featureList = function (tabs, output, options) {
    function slide(nr) {
        if (typeof nr == "undefined") {
            nr = visible_item + 1;
            nr = nr >= total_items ? 0 : nr;
        }
        var link = tabs.eq(nr).attr('href');
        var img = tabs.eq(nr).attr('rel');
        var alt = $('img', tabs).eq(nr).attr('alt');
        tabs.removeClass('current').filter(":eq(" + nr + ")").addClass('current');

        output.find('a').attr('href', link);
        output.find('a img').attr({ 'src': img, 'alt': alt });
        output.hide();
        output.stop(true, true).fadeOut('slow');
        output.fadeIn('slow', function () {
            visible_item = nr;
        });
    }
    var options = options || {};
    var total_items = tabs.length;
    var visible_item = options.start_item || 0;

    options.pause_on_hover = options.pause_on_hover || true;
    options.transition_interval = options.transition_interval || 5000;

    tabs.eq(0).addClass('current');

    tabs.click(function (e) {
        if ($(this).hasClass('current')) {
            return false;
        }
        slide(tabs.index(this));
        return false;
    });

    if (options.transition_interval > 0) {
        var timer = setInterval(function () {
            slide();
        }, options.transition_interval);

        if (options.pause_on_hover) {
            tabs.mouseenter(function () {
                clearInterval(timer);

            }).mouseleave(function () {
                clearInterval(timer);
                timer = setInterval(function () { //remove this function if you don't want to continue animation.
                    slide();
                }, options.transition_interval);
            });
        }
    }
};


/* ***************************************************************************************
Form tooltips
*/
var tooltips = {
    init: function (el) {
        var $el = $(el);

        var suffix = 'tooltip-';
        $($el).each(function () {
            if ($(this).attr('title') == '') { return }
            var uniqueID = tooltips.createUniqueId(suffix);
            var tooltip = $('<div class="tooltip tooltip-hidden" id="' + uniqueID + '"></div>').appendTo('body');

            //Find the tip content
            var titleTxt = $(this).attr('title');
            $('#' + uniqueID).text(titleTxt);
            $(this).removeAttr('title');
            $(this)
				.hover(
					function (e) {
					    $('#' + uniqueID)
						.removeClass('tooltip-hidden')
						.css({ 'left': e.pageX - $('.tooltip').outerWidth(), 'top': e.pageY - $('.tooltip').outerHeight() - 15, 'z-index': 100 });
					    return false;
					}, function () {
					    $('#' + uniqueID)
						.addClass('tooltip-hidden');
					});
        })
    },
    //Create random ID
    createUniqueId: function (o) {
        return o + Math.round(Math.random() * 100000)
    }
}



/*-------------------------------------------------------------------- 
* JQuery Plugin: "EqualHeights" 
* by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
--------------------------------------------------------------------*/
$.fn.equalHeights = function (px) {
    $(this).each(function () {
        var currentTallest = 0;
        $(this).children().each(function (i) {
            if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
        //if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
        if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({ 'height': currentTallest }); }
        $(this).children().css({ 'min-height': currentTallest });
    });
    return this;
};


/* ***************************************************************************************
Global functions
*/

/* link blurring extends jQuery */
$.fn.nb = function () {
    this.blur();
    return this.focus(function () {
        this.blur();
    });
}


