
/** 
** Description: Base JavaScript
** Company:     Netcel - http://www.netcel.com
** Client:      New Client
** Author:      Dominic Laurence
**
-----------------------------------------------------------------------**/


/** Functions
-----------------------------------------------------------------------**/

var $j = jQuery.noConflict();

$j(function () {

    //cache resused selectors
    var $slider = $j('.boxBlueHead .slider'),
		$homeTopics = $j('.home .topics'),
		$multi = $j('.multi'),
		$map = $j('#contactMap'),
		$explore = $j('#explore'),
		$homebanner = $j('#homeBanner');
    initTableStyle.init(".resAdmin");

    browserQuirksInit(); //apply different rules for specific browsers

    $j('body').removeClass('no-js'); //remove the no-js class from the body, used for some CSS rules / modernizr

    $j('#nav').navRoll();

    $slider.length ? $slider.parent().parent().scrollBoxInit() : null;

    $homeTopics.length ? $homeTopics.find('li:nth-child(3n)').css('margin-right', '0') : null;

    $multi.length ? $multi.multiTabs() : null;

    $explore.length ? $explore.exploreSlide() : null;

    //display select box styling for non IE browsers (IE doesnt render properly due to z-index issues). The function called is in the jquery.selectbox-0.5.js file
    //navigator.userAgent.match(/MSIE/) == null ? $j('.selBox').selectbox() : null;

    $j('#subNav').centreLines();

    $j('.sliderButton').next().hide().prev().click(function () { $j(this).genericSlider(); });

    $j('.form').length ? $j('.error').styleError() : null;

    $map.length ? $map.mapInit() : null;

    $j('input[type="text"]').hint();

    $homebanner.length ? $homebanner.homeBanner() : null;

});

//home banner script

$j.fn.homeBanner = function () {

    //cache reused selectors
    var $anch = $j('.head a', this),
		$info = $j('.info', this),
		easing = 'easeOutExpo',
		$maxHeight = 0;



    //$info.css('position','absolute');	

    //hide all the information for other tabs except the first	
    $j('.info', this).hide().eq(0).show();
    //show first tab as 'selected'
    $anch.eq(0).addClass('active').css('background', 'url(../img/blueHead.gif) repeat-x scroll center bottom #0071B1').find('span').css('background-position', 'right top');
    $j('#homeBanner .head a:last-child span').hide();

    $anch.click(function () {

        var $active = $j(this).siblings('.active');

        //deselect previous
        $active.removeClass('active').css('background', 'url("../img/bg-tabsDeSel.gif") repeat-x scroll center bottom #0D5A85')
			.find('span').css('background-position', 'center top')
			.parent().prev().find('span').css('background-position', 'center top');

        $active = $j(this); //select the new tab

        //style new tab
        $active.addClass('active').css('background', 'url(../img/blueHead.gif) repeat-x scroll center bottom #0071B1')
			.find('span').css('background-position', 'right top')
			.parent().prev().find('span').css('background-position', 'left top');

        //display new information	
        $info.hide().eq($active.index()).fadeIn(600, easing);
    });

}

//apply css tweeks for specific browsers (currently only MAC browsers)

function browserQuirksInit() {

    //firstly check to see if its a MAC
    if (navigator.appVersion.indexOf("Mac") != -1) {

        var userAgent = navigator.userAgent.toLowerCase(); //used to determine browser
        var $roundBtn = $j('.roundBtn'); //reused selector

        // Figure out what browser is being used
        jQuery.browser = {
            mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent),
            chrome: /chrome/.test(userAgent),
            safari: /webkit/.test(userAgent) && !/chrome/.test(userAgent)
        };

        //apply necessary styles
        if (jQuery.browser.safari) {

            $roundBtn.find('span').css({ 'padding-top': '6px', 'padding-bottom': '2px' });
            $roundBtn.find('input').css({ 'padding-top': '6px', 'padding-right': '3px', 'letter-spacing': '0' });
            $j('#searchArea .last').css('padding-top', '3px');
            $j('.holders label').css('padding-top', '2px');
            $j('.bgBlue span').css('padding-top', '5px');

        } else if (jQuery.browser.chrome) {

            $roundBtn.find('input').css({ 'padding-right': '3px', 'letter-spacing': '0' });

        } else if (jQuery.browser.mozilla) {

            $roundBtn.find('span').css({ 'padding-top': '4px', 'padding-bottom': '2px' });
            $roundBtn.find('input').css({ 'padding-top': '4px', 'padding-right': '3px', 'letter-spacing': '0' });
            $j('#searchArea .last').css('padding-top', '3px');
            $j('.bgBlue span').css('padding-top', '5px');

        }
    }

}

// Form field hints

$j.fn.hint = function (func) {

    return this.each(function () {

        var $input = $j(this),

		  title = $input.attr('title'),

		  $form = $j(this.form),
		  $win = $j(window);

        function remove() {

            if ($input.val() === title) {
                $input.val('');
            }
        }
        if (title) {

            $input.blur(function () {

                if (this.value === '') {
                    $input.val(title);
                }

            }).focus(remove).blur();

            $form.submit(remove);
            $win.unload(remove);

        }

    });

};

$j.fn.mapInit = function () {

    var $map = this; //this is #contactMap
    //if user agent is IE dont fade as it doesnt render the png shadow well
    var fadeSpeed = $j.browser.msie ? 0 : 1000;
    var easing = 'easeOutExpo';

    $map.find('.off').mouseenter(function () {

        var $mapLoc = $j(this).children('.mapLoc');
        $mapLoc.css({ 'top': -$mapLoc.height(), 'left': -200 }).animate({ opacity: 'toggle' }, fadeSpeed, easing);


    });
    $map.find('.off').mouseleave(function () {
        $j(this).children('.mapLoc').hide();
    });

    //Hide the sliding divs in the "staff" area
    $j('.sliderButton').next().hide();
}


$j.fn.styleError = function () {

    $j(this).prev().css('border', '1px solid #c81b20');

}

$j.fn.centreLines = function () {
    //cycle through each subnav element, if the anchor text goes onto 2 lines add the necessary class (which adjusts 
    //the line height to make it appear vertically centred)

    $j(this).children('li').each(function () {
        $j(this).width() > 110 ? $j(this).addClass('double-line') : null;
    });
}

$j.fn.exploreSlide = function () {
    $j(this).click(function () {
        //slide the explore area
        $j(this).next().toggle();
        //change the icon
        $j(this).children('span').toggleClass('changePos');
    });
}

$j.fn.genericSlider = function () {

    //dont slide for IE7 and earlier, animation is quirky
    var speed = $j.browser.msie && $j.browser.version < 8 ? 0 : 700;

    //slide the explore area
    $j(this).next().animate({ height: 'toggle' }, speed);

    //change the icon
    $j(this).children('span').toggleClass('changePos');
}


$j.fn.multiTabs = function () {

    var noFixedHeight = this.hasClass('noFixedHeight');

    //initial styles
    $j(this).find('.head a:first-child').css('padding-left', '10px'); //for IE6

    if (noFixedHeight) {
        $j('.multiDiv', this).css('display', 'none');
        $j('div:eq(0)', this).css('display', 'block');
        //hide all the info div's except the first
        $j('.info:eq(0) .entry', this).hide().eq(0).show(); $j('.info:eq(1) .entry', this).hide().eq(0).show();
    } else {
        $j('.multiDiv', this).css({ position: 'absolute', width: '300px', height: '300px', top: '36px', left: '-9999px' });
        $j('div:eq(0)', this).css('left', '0');
    }


    $thisTab = $j(this).find('.head a');

    $thisTab.click(function () {

        //first check to see if the clicked tab is already selected	
        if ($j(this).attr('class') !== 'active') {

            var thisInd = $j(this).index();
            var $thisParent = $j(this).parent().parent();

            $j(this).addClass('active').siblings().removeClass('active').parent().find('span').toggleClass('left');

            if (!noFixedHeight) {
                $thisParent.children('div').css('left', '-9999px').eq(thisInd).css('left', '0')
            } else {
                $thisParent.children('div').css('display', 'none').eq(thisInd).css('display', 'block');
                $j(this).parent().parent().addRemoveInit(thisInd);
            }
        }

    });

    $j(this).addRemoveInit(0);

}

$j.fn.addRemoveInit = function (x) {

    var $selDiv = $j(this).find('.multiDiv').eq(x),
		totalEntry = $j('.entry', $selDiv).length,
		shown = $j('.entry', $selDiv).length;
    var count = new Array; count[0] = 1; count[1] = 1;

    $j('.plus', $selDiv).click(function () {
        if (count[x] < totalEntry) {
            $j('.entry', $selDiv).eq(count[x]).fadeIn();
            count[x]++;
        } else {
            return;
        }
    });

    $j('.minus', $selDiv).click(function () {
        if (count[x] > 1) {
            count[x]--;
            $j('.entry', $selDiv).eq(count[x]).fadeOut();
        } else {
            return;
        }
    });
}

$j.fn.scrollBoxInit = function () {

    //apply the necessary styles (default styles enable non-javascript users to view all the data)
    $j(this).find('.slider').css('height', '255px').css('position', 'absolute').find('.info').css('float', 'left');
    $j(this).find('.wrap').css('height', '255px');
    $j('.images .wrap').css('height', '217px');

    //find out how many sliders are on the current page
    var noOfSliders = $j('.slider').length;

    //cycle through each slider and set the width (dependant on how many info boxes each one contains)
    for (i = 0; i < noOfSliders; i++) {

        var $thisSlider = $j('.slider').eq(i);

        //find out the number of info boxes
        var noOfInfos = $thisSlider.find('.info').length;

        //find out the width of the info boxes
        var infoWidth = $j('.slider').eq(i).find('.info').width();

        //set the width of the slider to accommodate the info sections (width of info sections X how many there are)
        var thisWidth = noOfInfos * infoWidth;
        $thisSlider.css('width', thisWidth);

        //set the control to indicate the correct number of slides
        //first check to make sure there are more than one

        if (noOfInfos > 0) {

            for (x = 0; x < noOfInfos; x++) {
                x == 0 ? $thisSlider.parent().parent().find('.scrollControl span').append('<strong class="active"></strong>') : $thisSlider.parent().parent().find('.scrollControl span').append('<strong></strong>');

            }

        }

    }

    //configurable settings
    var easing = 'easeInOutCirc';
    var nextSpeed = 600;
    var endToEndSpeed = 1200;

    //handle the click events
    $j('.scrollControl .next').click(function () {

        var $thisSlider = $j(this).parent().parent().siblings('.wrap').find('.slider');
        var $activeIndicator = $j(this).siblings('span').find('.active');
        var sliderWidth = $thisSlider.width();
        var infoWidth = $thisSlider.find('.info').width();
        var slideWidth = $thisSlider.outerWidth('false');

        //prevent the user from clicking whilst the slider is still animating
        if (!$thisSlider.is(':animated')) {

            var pos = $thisSlider.position();

            //animate the slider (...and animate back to the start if it reaches the end)
            if (pos.left == -(sliderWidth - infoWidth) || pos.left == -(sliderWidth - infoWidth) + 1) {

                $thisSlider.animate({ left: '0px' }, endToEndSpeed, easing);

                $activeIndicator.removeClass('active').siblings('strong:eq(0)').addClass('active');

            } else {

                $thisSlider.animate({ left: '-=' + infoWidth + 'px' }, nextSpeed, easing);

                $activeIndicator.removeClass('active').next().addClass('active');

            }

        }

    });

    $j('.scrollControl .prev').click(function () {

        var $thisSlider = $j(this).parent().parent().siblings('.wrap').find('.slider');
        var $activeIndicator = $j(this).siblings('span').find('.active');

        var sliderWidth = $thisSlider.width();
        var infoWidth = $thisSlider.find('.info').width();
        var slideWidth = $thisSlider.outerWidth('true');

        //prevent the user from clicking whilst the slider is still animating
        if (!$thisSlider.is(':animated')) {

            var pos = $thisSlider.position();

            //animate the slider (...and animate back to the end if it reaches the start)
            if (pos.left == 0) {

                $thisSlider.animate({ left: '-' + (sliderWidth - infoWidth) + 'px' }, endToEndSpeed, easing);

                $activeIndicator.removeClass('active').siblings('strong:last-child').addClass('active');

            } else {

                $thisSlider.animate({ left: '+=' + infoWidth + 'px' }, nextSpeed, easing);

                $activeIndicator.removeClass('active').prev().addClass('active');

            }

        }

    });
}

$j.fn.navRoll = function () {

    $j(this).find('li div').css('display', 'none'); //hide and position the subnav
    //$j(this).find('li div').css('display','none').css('left','0');//hide and position the subnav

    //position the navigation
    $j(this).find('ul > li > div').addClass('leftDD');
    $j(this).find('ul > li:gt(3) > div').removeClass('leftDD').addClass('rightDD');

    $j(this).find('li li:only-child a').css('border', 'none');
    $j(this).find('li:last-child div ul').css('width', 200); //Contact us is short	
    $j(this).find('ul li li:nth-child(3n) a').css('border', 'none');

    //show the grey border for drop down in IE (non javascript shows the shadow instead, hence the styling here - not css file)
    isIE = navigator.userAgent.match(/MSIE/);
    isIE ? $j('#nav li div').css('border', '2px solid #cccccc') : null;

    function fadeIn() {
        $j(this).find('div').fadeIn(500, 'easeOutSine');
    }
    function fadeOut() {
        $j(this).find('div').fadeOut(100)
    }

    var config = {
        sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
        interval: 90, // number = milliseconds for onMouseOver polling interval    
        over: fadeIn, // function = onMouseOver callback (REQUIRED)    
        timeout: 100, // number = milliseconds delay before onMouseOut    
        out: fadeOut // function = onMouseOut callback (REQUIRED)    
    };

    $j(this).find('li').hoverIntent(config);
}

// Data table styling
var initTableStyle = {
    init: function (el) {
        el = jQuery(el);
        el.find("tr:even").addClass("odd");
    }
}
