$(document).ready(function () {

    /*$("#searchBox").searchDropdown({
        "formid": "#search",
        "hiddensearchtype": "#searchtype",
        "maxlength": 20
    });*/
$("div.mainNavHeader .secondaryNav ul li.forumExpand a").css("width","60px");
$("div.mainNavHeader .secondaryNav ul li.forumExpand a").css("padding","0 0 0 15px");
$("div.mainNavHeader .secondaryNav ul li.forumExpand span").css("display","block")

    $('.expandLink').each(function () {
        $(this).prev('.dropdownContent').hide();
        $(this).click(function () {
            $(this).toggleClass('active');
            $(this).prev('.dropdownContent').slideToggle();
        });
    });


    /* Use this js doc for all application specific JS */
    $(window).resize(function () {
        //console.log($(window).width());
    });

    $('.forumExpand span').click(function (evt) {
        //console.log(evt);
        //var target = $(evt.target);
        //if(target.is("li")){
        //console.log("a");
        $('.forumExpand span').toggleClass('active');
        $('.forums').slideToggle()
        //}
    });
    $('.forumButton').click(function (evt) {

    });

    $('.MSEstuff').click(function () {
        $('.MSEstuff').toggleClass('active');
        $('.MSEnav').slideToggle();
        if ($('.MSEstuff').hasClass('active')) {
            return (false);
        }
    });
    $("body").click(function () {
        //console.log("ilsd");
        $('.MSEstuff').removeClass('active');
        $('.MSEnav').slideUp();

    });

    // Create 3 TAB SYSTEMS
    // Pass in the name of the initially selected tab.
    $('.rhsnewsBox').createTabs('#news');
    $('.rhswowBox').createTabs('#grabbit');
    $('.rhssocialBox').createTabs('#fbook');

    
	var config = {
	    sensitivity: 1,
	    // number = sensitivity threshold (must be 1 or higher)    
	    interval: 100,
	    // number = milliseconds for onMouseOver polling interval    
	    over: megaHoverOver,
	    // function = onMouseOver callback (REQUIRED)    
	    timeout: 100,
	    // number = milliseconds delay before onMouseOut    
	    out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};
	$("ul#topnav li .sub").css({
	    'opacity': '0'
	});
	$("ul#topnav li").hoverIntent(config);
function megaHoverOver() {
    $(this).find(".sub").stop().fadeTo('fast', 1).show();
}

function megaHoverOut() {
    $(this).find(".sub").stop().fadeTo(50, 0, function () {
        $(this).hide();
    });
}

$('#featured').orbit({
        animation: 'horizontal-slide',
        // fade, horizontal-slide, vertical-slide, horizontal-push
        animationSpeed: 800,
        // how fast animtions are
        timer: true,
        // true or false to have the timer
        advanceSpeed: 6000,
        // if timer is enabled, time between transitions 
        pauseOnHover: true,
        // if you hover pauses the slider
        startClockOnMouseOut: true,
        // if clock should start on MouseOut
        startClockOnMouseOutAfter: 0,
        // how long after MouseOut should the timer start again
        directionalNav: false,
        // manual advancing directional navs
        captions: false,
        // do you want captions?
        captionAnimation: 'none',
        // fade, slideOpen, none
        captionAnimationSpeed: 800,
        // if so how quickly should they animate in
        bullets: true,
        // true or false to activate the bullet navigation
        bulletThumbs: false,
        // thumbnails for the bullets
        bulletThumbLocation: '',
        // location from this file where thumbs will be
        afterSlideChange: function () {} // empty function 
    });


    $('#toolsBlock  .viewport').infiniteCarousel({
        prevNextInternal: false,
        imagePath: 'http://images2.moneysavingexpert.com/images/infinitecarousell/',
        transitionSpeed: 3000,
        displayTime: 6000,
        inView: 6,
        advance: 6,
        easeLeft: 'swing',
        easeRight: 'swing',
        displayProgressBar: false,
        displayThumbnails: false
    }); //{transitionSpeed: 1200,displayTime: 6000,inView:6,	easeLeft: 'linear',easeRight: 'linear',advance:6, displayProgressBar: false,interval: true, controls:true, display: 6, intervaltime: 10000, duration: 500});


});
$.fn.createSectionTabs = function (p) {

    return this.each(function () {
        var $tab_system = $(this);
        var $panels = $tab_system.find('> div');
        var $tabs = $tab_system.find('> ul.sectionTabs a');
        $tabs.click(function () {
            $tabs.removeClass('selected');
            $(this).addClass('selected');
            $panels.hide().filter(this.hash).show();
            return false;
        });
        $tabs.filter(':first').click();


    });
}

$.fn.createTabs = function (p) {
    return this.each(function () {
        var $tab_system = $(this);
        var $panels = $tab_system.find('> div');
        var $tabs = $tab_system.find('> ul.topTabs a');
        $tabs.click(function () {
            $tabs.removeClass('selected');
            $(this).addClass('selected');
            $panels.hide().filter(this.hash).show();
            return false;
        });
        $tabs.filter(':first').click();

        //$('#toolsBlock').tinycarousel({ interval: true, controls:true, display: 6, intervaltime: 10000, duration: 500  });
    });
}
















$(window).load(function () {
    });


/*
 * jQuery Reveal Plugin 1.0
 * www.ZURB.com
 * Copyright 2010, ZURB
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 */


(function ($) {

    /*---------------------------
		 Defaults for Reveal
		----------------------------*/

    /*---------------------------
		 Listener for data-reveal-id attributes
		----------------------------*/

    $('a[data-reveal-id]').live('click', function (e) {
        e.preventDefault();
        var modalLocation = $(this).attr('data-reveal-id');
        $('#' + modalLocation).reveal($(this).data());
    });

    /*---------------------------
		 Extend and Execute
		----------------------------*/

    $.fn.reveal = function (options) {


        var defaults = {
            animation: 'fadeAndPop',
            //fade, fadeAndPop, none
            animationspeed: 300,
            //how fast animtions are
            closeonbackgroundclick: true,
            //if you click background will modal close?
            dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
        };

        //Extend dem' options
        var options = $.extend({}, defaults, options);

        return this.each(function () {

            /*---------------------------
		 Global Variables
		----------------------------*/
            var modal = $(this),
                topMeasure = -80,
                topOffset = modal.height() + topMeasure,
                locked = false,
                modalBG = $('.reveal-modal-bg');

            /*---------------------------
		 Create Modal BG
		----------------------------*/
            if (modalBG.length == 0) {
                modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal);
            }

            /*---------------------------
		 Open & Close Animations
		----------------------------*/
            //Entrance Animations
            modal.bind('reveal:open', function () {
                modalBG.unbind('click.modalEvent');
                $('.' + options.dismissmodalclass).unbind('click.modalEvent');
                if (!locked) {
                    lockModal();
                    if (options.animation == "fadeAndPop") {
                        modal.css({
                            'top': $(document).scrollTop() - topOffset,
                            'opacity': 0,
                            'visibility': 'visible'
                        });
                        modalBG.fadeIn(options.animationspeed / 2);
                        modal.delay(options.animationspeed / 2).animate({
                            "top": $(document).scrollTop() + topMeasure + 'px',
                            "opacity": 1
                        }, options.animationspeed, unlockModal());
                    }
                    if (options.animation == "fade") {
                        modal.css({
                            'opacity': 0,
                            'visibility': 'visible',
                            'top': $(document).scrollTop() + topMeasure
                        });
                        modalBG.fadeIn(options.animationspeed / 2);
                        modal.delay(options.animationspeed / 2).animate({
                            "opacity": 1
                        }, options.animationspeed, unlockModal());
                    }
                    if (options.animation == "none") {
                        modal.css({
                            'visibility': 'visible',
                            'top': $(document).scrollTop() + topMeasure
                        });
                        modalBG.css({
                            "display": "block"
                        });
                        unlockModal()
                    }
                }
                modal.unbind('reveal:open');
            });

            //Closing Animation
            modal.bind('reveal:close', function () {
                if (!locked) {
                    lockModal();
                    if (options.animation == "fadeAndPop") {
                        modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
                        modal.animate({
                            "top": $(document).scrollTop() - topOffset + 'px',
                            "opacity": 0
                        }, options.animationspeed / 2, function () {
                            modal.css({
                                'top': topMeasure,
                                'opacity': 1,
                                'visibility': 'hidden'
                            });
                            unlockModal();
                        });
                    }
                    if (options.animation == "fade") {
                        modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
                        modal.animate({
                            "opacity": 0
                        }, options.animationspeed, function () {
                            modal.css({
                                'opacity': 1,
                                'visibility': 'hidden',
                                'top': topMeasure
                            });
                            unlockModal();
                        });
                    }
                    if (options.animation == "none") {
                        modal.css({
                            'visibility': 'hidden',
                            'top': topMeasure
                        });
                        modalBG.css({
                            'display': 'none'
                        });
                    }
                }
                modal.unbind('reveal:close');
            });

            /*---------------------------
		 Open and add Closing Listeners
		----------------------------*/

            //Open Modal Immediately
            modal.trigger('reveal:open')

            //Close Modal Listeners
            var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function () {
                modal.trigger('reveal:close')
            });

            if (options.closeonbackgroundclick) {
                modalBG.css({
                    "cursor": "pointer"
                })
                modalBG.bind('click.modalEvent', function () {
                    modal.trigger('reveal:close')
                });
            }
            $('body').keyup(function (e) {
                if (e.which === 27) {
                    modal.trigger('reveal:close');
                } // 27 is the keycode for the Escape key
            });


            /*---------------------------
		 Animations Locks
		----------------------------*/
            function unlockModal() {
                locked = false;
            }

            function lockModal() {
                locked = true;
            }

        }); //each call
    } //orbit plugin call
})(jQuery);




/* Search Widget*/

$.fn.searchDropdown = function (options) {


    var settings = $.extend({
        'formid': '#search',
        'hiddensearchtype': '#searchtype',
        'maxlength': 20
    }, options);

    this.after('<div id="headersearchresults">' + '<ul>' + '</ul>' + '</div>');


    var currentSelection = 0;
    var currentUrl = '';
    var currentSearchtype = "";
    var caretPosition = 0;
    // put all your jQuery goodness in here.
    // Register keydown events on the input
    //console.log(this);
    this.keydown(function (e) {
        caretPosition = $(this).caret().start;
        switch (e.keyCode) {
            // User pressed "up" arrow
        case 38:
            navigate('up');
            break;
            // User pressed "down" arrow
        case 40:
            navigate('down');
            break;
            // User pressed "enter"
        case 13:
            /*            if(currentUrl != '') {
                                                                                //window.location = currentUrl;
                                                                                $(settings.formid).submit();
                                                                }*/
            break;
        default:
            //                buildUl(this);
            break;
        }


    });

    this.keyup(function (e) {
        //console.log('move');
        switch (e.keyCode) {
            // User pressed "up" arrow
        case 38:
            //                navigate('up');
            break;
            // User pressed "down" arrow
        case 40:
            //                navigate('down');
            break;
            // User pressed "enter"
        case 13:
            if (currentUrl != '') {
                //window.location = currentUrl;
                $(settings.formid).submit();
            }
            break;
        default:
            buildUl(this);
            break;
        }

        $("#headersearchresults ul a").click(function () {
            setSelected($(this).data("number"));
            $(settings.formid).submit();
        });
        // Add data to let the hover know which index they have



    });

    // Simulate the "hover" effect with the mouse
    bindclick();


    //post form on keydown or onclick, get results
    this.bind('click', function () {
        buildUl(this);
    });
    //
    //hide results when clicked outside of search field
    $("body").click(function () {
        $("#headersearchresults").hide();
    });
    //

    function bindclick() {
        $("#headersearchresults ul li a").hover(

        function () {
            currentSelection = $(this).data("number");
            //console.log(currentSelection);
            //console.log("uksadhf");
            //setSelected(currentSelection);
        }, function () {
            $("#results ul li a").removeClass("search_hover");
            currentUrl = '';
        });
    }

    function navigate(direction) {
        //console.log("a"+currentSelection);
        // Check if any of the menu items is selected
        if ($("#headersearchresults ul li .search_hover").size() == 0) {
            //console.log("inhere");
            currentSelection = -1;
        }

        //JBP - focus back on search field if up arrow pressed on top search result
        if (direction == 'up' && currentSelection == 0) {
            //console.log("top");
            //$("#searchBox").focus();
            //setSelected();
            currentSelection--;
        }
        //
        //console.log(currentSelection);
        if (direction == 'up' && currentSelection != -1) {
            if (currentSelection != 0) {
                currentSelection--;
            }
        } else if (direction == 'down') {
            //console.log("b"+currentSelection);
            $("#headersearchresults ul").focus();
            if (currentSelection != $("#headersearchresults ul li").size() - 1) {
                currentSelection++;
            }
        }
        setSelected(currentSelection);
    }

    function setSelected(menuitem) {
        if (menuitem == -1) {
            //console.log("sdf");
            $("#headersearchresults ul li a").removeClass("search_hover");
            $(settings.hiddensearchtype).val("mainsite");
            return;
        }

        //JBP - get search result to place in search field on hover
        var title = $("#headersearchresults ul li a.search_hover").attr('title');
        $("#headersearchresults").val(title);
        //
        $("#headersearchresults ul li a").removeClass("search_hover");
        $("#headersearchresults ul li a").eq(menuitem).addClass("search_hover");
        currentUrl = $("#headersearchresults ul li a.search_hover").attr("href");

        if ($("#headersearchresults ul li a.search_hover").hasClass('mainsite')) {
            $(settings.hiddensearchtype).val("mainsite");
        } else if ($("#headersearchresults ul li a.search_hover").hasClass('mainsite_only')) {
            $(settings.hiddensearchtype).val("mainsite_only");
        } else if ($("#headersearchresults ul li a.search_hover").hasClass('news')) {
            $(settings.hiddensearchtype).val("news");
        } else if ($("#headersearchresults ul li a.search_hover").hasClass('tips')) {
            $(settings.hiddensearchtype).val("tip");
        } else if ($("#headersearchresults ul li a.search_hover").hasClass('blog')) {
            $(settings.hiddensearchtype).val("blog");
        } else if ($("#headersearchresults ul li a.search_hover").hasClass('chat')) {
            $(settings.hiddensearchtype).val("chat");
        } else {
            $(settings.hiddensearchtype).val("mainsite");
        }
        //currentSearchtype = $("#results ul li a").eq(menuitem).;
    }



    function buildUl(context) {
        //$("#results").empty();
        var searchterm = $(context).val();
        //console.log(searchterm);
        $("#headersearchresults ul").html("<li><a class='chat' href='javascript:void(0)'>Or search for this on the forums</a></li>");
        if (searchterm.length < settings.maxlength) {
            //console.log(searchterm);
            $("#headersearchresults ul span").text(searchterm);
        } else {
            //console.log("blas");
            var halflength = settings.maxlength / 2;
            var starttext = caretPosition - halflength;
            var endtext = (caretPosition + halflength);
            var modification = 0;

            if (starttext < 0) {
                modification = (starttext * -1);
                starttext = 0;
                endtext += modification;
            }
            if (endtext > searchterm.length) {
                modification = endtext - searchterm.length;
                endtext = searchterm.length;
                starttext -= modification;
            }

            //console.log("s "+starttext);
            //console.log("e "+endtext);
            $("#headersearchresults ul span").text(searchterm.substring(starttext, endtext));
        }
        bindclick();
        for (var i = 0; i < $("#headersearchresults ul li a").size(); i++) {
            //console.log(i);
            $("#headersearchresults ul li a").eq(i).data("number", i);
        }
        $("#headersearchresults").show();
    }

};;

/*** Caret widget ***/

(function ($, len, createRange, duplicate) {
    $.fn.caret = function (options, opt2) {
        var start, end, t = this[0],
            browser = $.browser.msie;
        if (typeof options === "object" && typeof options.start === "number" && typeof options.end === "number") {
            start = options.start;
            end = options.end;
        } else if (typeof options === "number" && typeof opt2 === "number") {
            start = options;
            end = opt2;
        } else if (typeof options === "string") {
            if ((start = t.value.indexOf(options)) > -1) end = start + options[len];
            else start = null;
        } else if (Object.prototype.toString.call(options) === "[object RegExp]") {
            var re = options.exec(t.value);
            if (re != null) {
                start = re.index;
                end = start + re[0][len];
            }
        }
        if (typeof start != "undefined") {
            if (browser) {
                var selRange = this[0].createTextRange();
                selRange.collapse(true);
                selRange.moveStart('character', start);
                selRange.moveEnd('character', end - start);
                selRange.select();
            } else {
                this[0].selectionStart = start;
                this[0].selectionEnd = end;
            }
            this[0].focus();
            return this
        } else {
            // Modification as suggested by Андрей Юткин
            if (browser) {
                var selection = document.selection;
                if (this[0].tagName.toLowerCase() != "textarea") {
                    var val = this.val(),
                        range = selection[createRange]()[duplicate]();
                    range.moveEnd("character", val[len]);
                    var s = (range.text == "" ? val[len] : val.lastIndexOf(range.text));
                    range = selection[createRange]()[duplicate]();
                    range.moveStart("character", -val[len]);
                    var e = range.text[len];
                } else {
                    var range = selection[createRange](),
                        stored_range = range[duplicate]();
                    stored_range.moveToElementText(this[0]);
                    stored_range.setEndPoint('EndToEnd', range);
                    var s = stored_range.text[len] - range.text[len],
                        e = s + range.text[len]
                }
                // End of Modification
            } else {
                var s = t.selectionStart,
                    e = t.selectionEnd;
            }
            var te = t.value.substring(s, e);
            return {
                start: s,
                end: e,
                text: te,
                replace: function (st) {
                    return t.value.substring(0, s) + st + t.value.substring(e, t.value[len])
                }
            }
        }
    }
})(jQuery, "length", "createRange", "duplicate");
