/*----------------------------------------------------------------------
[Global JavaScript ] 
Desc: site wide javascript

Copyright:		Great Fridays 2011
Client:			x
Project:		x
Created by:		x
Created on:		x			
-----------------------------------------------------------------------*/

/* Global > replace fonts ---------------------------------------------*/

Cufon.replace('h1,h2,h3,h4,h5,#sideNav a, #sideNav span,#siteNav a, .PeopleVitals .born, .PeopleVitals .social,#siteNav span, big, .workBrief dt,blockquote p, p.large, #leftHandMenu a', { hover: true });


/* Not looking for any trouble here -----------------------------------*/

var $j = jQuery.noConflict();
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);

/* Global > run some functions  ---------------------------------------*/

$j(document).ready(function () {

    Cufon.now();
    $j('body').addClass('js');
   
    agentID ? $j('body').addClass('ipad') : null;
    inputValueReplace();
    //searchBox();
    setupTermsAndPrivacyPopUps();
    validateForm();
    setupHTMLControls();
    joinTeamEllipses();
    initializeTracking();
});

/* Global > setup the opening behavior of known anchor types -----------------*/

function initializeTracking() {

    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    $j.getScript(gaJsHost + "google-analytics.com/ga.js", function () {

        var pageTracker = _gat._getTracker("UA-5960981-1");

        pageTracker._trackPageview();

        var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3|mp4|flv|wmv|mov)$/i;

        $j(document.body).delegate('a', 'click', function () {

            var href = $j(this).attr('href');

            // external link.
            if (href && (href.match(/^https?\:/i)) && (!href.match(document.domain))) {
                var extLink = href.replace(new RegExp("^https?\:\/\/", "i"), '');
                pageTracker._trackEvent('External', 'Click', extLink);
            }
            // email link.
            else if (href && href.match(/^mailto\:/i)) {
                var mailLink = href.replace(new RegExp('^mailto\:', 'i'), '');
                pageTracker._trackEvent('Email', 'Click', mailLink);
                if (!agentID) {
                    setTimeout('document.location = "' + href + '"', 100);
                    return false;
                }
            }
            // download link
            else if (href && href.match(filetypes)) {
                var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                var filePath = href.replace(new RegExp("^https?\:\/\/(www.)greatfridays\.com\/", "i"), '');
                pageTracker._trackEvent('Download', 'Click - ' + extension, filePath);
            }

        });

    });

    $j('a[rel="external"]').attr("target", "_blank");

}

/* Search box -----------------*/

/*
    function searchBox() {
        $j('#submitIcon, #searchTerm').hide();
        $j('#toggleHolder').show();
        $j('#toggleHolder').click(function () {
            $j('#submitIcon').show();
            $j('#searchTerm').fadeIn(500).focus();
            $j(this).hide();
        });
    }; 
*/

/* Terms and Privacy "Pop over" boxes ----------------*/

function setupTermsAndPrivacyPopUps() {

	if (agentID) {
        $j('a.iframe').click(function() {
            window.open(this.href);
	        return false;
	    });
	} else {
	    $j("a.iframe").fancybox({
	        'hideOnContentClick': true,
	        'transitionIn': 'fade',
	        'transitionOut': 'fade',
	        'centerOnScroll': true,
	        'showNavArrows': false,
	        'width': 1024,
	        'height': 500
	    });
	}

}

/* Hide join the team ellipses ----------------*/

function joinTeamEllipses() {

    $j('.joinTeamRow h3').click(function () {
        $j(this).parent().find('.join-ellipsis').toggle();

    });
}

/* Global > replace the default value of input fields -----------------*/

function inputValueReplace() {
  
	$j('input.valueReplace').each(function() { var o = new valueReplace($j(this)); });
	function valueReplace(e) {
		
		var o = {
		  init : function() {
				o.field = $j(e); 
				o.isSet = false;
				o.defaultValue = o.field.val();
				o.monitor();
			},
			monitor : function() {
				o.field.focus(function(){
					if( $j(this)[0].value == o.defaultValue) { $j(this)[0].value = ''; }
				});
				o.field.blur(function(){
					if($j(this)[0].value == '') { $j(this)[0].value = o.defaultValue;}
				});
			}
		};
		o.init();		
	};

};


/* Global > form validation --------------------------------------------------------------------------*/
/* Dependencies - jquery validation */
function validateForm() {

    $j("#searchForm").validate({
        messages: {
            'searchTerm': " "
        }
    });
};


/* Global > custom easing ---------------------------------------------*/

$j.easing.quad = function (x, t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t + b;
	return -c/2 * ((--t)*(t-2) - 1) + b;
};

$j.easing.easeInOutQuad = function (x, t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t + b;
	return -c/2 * ((--t)*(t-2) - 1) + b;
};

/* Video Controls (HTML5) --------------------------------------------------*/
function setupHTMLControls() {

    var o = {
        init: function () {
            o.video = document.getElementById("htmlPlayer");
            o.videoContainer = $j('#feature_flash');
            o.toggler = $j('.toggler');
            o.replay = $j('.replay');
            o.timerDisplay = $j('.currentTime');
            o.smallPause = $j('.smallPause');
            o.volumeControl = $j('.volumeControl');
            o.timer = null;

            

            if ((isiPhone() || isiPod()) && !isiPad()) {
                o.toggler.hide();
            }

            o.setupVideoControls();
            o.setupShowHideControls();
            o.bindEvents();
        },

        setupVideoControls: function () {
            o.toggler.toggle(function () {
                o.video.play();
                o.startTimer();

                if (!isiPad()) {
                    $j(this).addClass('videoPause');
                    $j(this).removeClass('videoPlay');


                } else {
                    o.toggler.hide();
                }
            }, function () {
                $j(this).addClass('videoPlay');
                $j(this).removeClass('videoPause');

                o.video.pause();
                o.stopTimer();
                $j('.smallPause').hide();
                $j('.smallPauseHover').hide();
                $j('.hoverState').hide();

                if (isiPad()) {
                    o.toggler.show();
                }
            });

            o.replay.click(function () {
                o.video.play();
                o.startTimer();
                $j('.smallPause').show();

                $j(this).css('visibility', 'hidden');
                o.toggler.css('visibility', 'visible');

                if (isiPad) {
                    o.toggler.hide();
                }
            });

            o.smallPause.click(function () {
                //$j(this).addClass('videoPlay');
                //$j(this).removeClass('videoPause');

                //o.video.pause();
                //o.stopTimer();
                o.toggler.click();
            });
            //This is disabled as it does not work on a ipad - as the ipad does not allow you to control the audio at this time.
            //The button is hidden by css.
            // nic - 21/04/2011
            o.volumeControl.click(function () {

                if (o.muted == true) {
                    o.muted = false;
                    $j(this).removeClass('volSelected');
                    o.video.volume = 1;
                }
                else {
                    o.muted = true;
                    o.video.volume = 0;
                    $j(this).addClass('volSelected');

                }
            });
        },

        setupShowHideControls: function () {
            o.toggler.mouseenter(function (e) {
                var element = ($j('.toggler').hasClass('videoPlay')) ? '.videoPlayHover' : '.videoPauseHover';

                if (isiPad() && element == '.videoPauseHover') {
                    return;
                }
                $j(element).fadeIn('fast');
            });

            o.toggler.bind('touchend', function (e) {
                if (isiPad()) {
                    o.toggler.click();
                }
            });

            o.toggler.mouseleave(function (e) {
                $j('.hoverState').fadeOut('fast');
            });

            //Replay button
            if (!isiPad()) {
                o.replay.mouseenter(function (e) {
                    $j('.replayHover').fadeIn('fast');
                });

                o.replay.mouseleave(function (e) {
                    $j('.replayHover').fadeOut('fast');
                });
            } else {
                o.replay.bind('touchend', function (e) {
                    o.replay.click();
                    e.preventDefault();
                });
            }

            //Small pause button
            if (!isiPad()) {
                o.smallPause.mouseenter(function (e) {
                    $j('.smallPauseHover').fadeIn('fast');
                });

                o.smallPause.mouseleave(function (e) {
                    $j('.smallPauseHover').fadeOut('fast');
                });
            } else {
                o.smallPause.bind('touchend', function (e) {
                    o.smallPause.click();
                    e.preventDefault();
                });
            }


            //Volume control
            if (!isiPad()) {
                o.volumeControl.mouseenter(function (e) {
                    $j('.volumeControlHover').fadeIn('fast');
                });

                o.volumeControl.mouseleave(function (e) {
                    $j('.volumeControlHover').fadeOut('fast');
                });
            } else {
                o.volumeControl.bind('touchend', function (e) {
                    o.volumeControl.click();
                    e.preventDefault();
                });
            }

            o.videoContainer.mouseenter(function (e) {
                if (isiPad()) return;
                o.toggler.fadeIn();
            });

            o.videoContainer.mouseleave(function (e) {
                if (isiPad()) return;
                o.toggler.fadeOut();
            });
        },

        bindEvents: function () {
            $j(o.video).bind('play', function (e) {
                if (isiPad()) {
                    o.toggler.hide();
                }
                o.smallPause.show();
            });

            $j(o.video).bind('playing', function (e) {
                if (isiPad()) {
                    o.toggler.hide();
                }
                o.smallPause.show();
            });

            $j(o.video).bind('ended', function (e) {
                o.toggler.fadeIn();
                o.smallPause.hide();
            });

            $j(o.video).bind('paused', function (e) {
                o.toggler.fadeIn();
                o.smallPause.hide();
            });
        },

        startTimer: function () {
            o.timer = setInterval(function () {
                if (o.video.currentTime >= o.video.duration) {
                    o.stopTimer();
                    o.toggler.css('visibility', 'hidden');
                    o.replay.css('visibility', 'visible');
                }
                else {
                    var totalSeconds = Math.floor(o.video.currentTime);
                    var minutes = Math.floor(totalSeconds / 60);
                    var seconds = totalSeconds % 60;

                    if (seconds < 10) seconds = "0" + seconds;

                    o.timerDisplay.text(minutes + ":" + seconds);
                }
            }, 100);
        },

        stopTimer: function () {
            clearInterval(o.timer);
        }
    }

    o.init();

}

function isiPad() {
    var result = (navigator.userAgent.match(/iPad/i) != null);
    return result;
}

function isiPhone() {
    var result = (navigator.userAgent.match(/iPhone/i) != null);
    return result;
}

function isiPod() {
    var result = (navigator.userAgent.match(/iPod/i) != null);
    return result;
}

/* Slideshow -----------------------------------------------------*/

function slideshow() {

    $j('#feature-show').each(function () { var o = new slider($j(this)); });
    function slider(e) {

        /* Set vars */
        var config = {};
        config.slideWidth = 700;
        config.current = 0;
        config.scrollspeed = 400;
        config.playing = true;
        config.speed = 5500;

        var o = {

            /* cache selectors, run some funtions */
            init: function () {
                o.slideshow = $j(e);
                o.slider = $j('.scroller', o.slideshow);
                o.slides = $j('li', o.slider);
                o.slider.append(o.slides.filter(':first').clone());
                config.totalSlides = o.slides.length;
                o.events();
            },

            /* animate slider */
            slide: function (int) {
                if (config.current == 0) o.slider.css('left', 0);
                config.current = int;
                o.slider.stop().animate({ 'left': -(config.current * config.slideWidth) }, config.scrollspeed, 'easeInOutQuad', o.update());
            },

            /* update selected link */
            update: function () {

                config.current == config.totalSlides ? config.current = 0 : null;

                if (config.startTimer) window.clearTimeout(config.startTimer);
                if (config.playing == true) {
                    config.startTimer = window.setTimeout(function () {
                        switch (config.current) {
                            case config.totalSlides: o.slide(1); break;
                            default: o.slide(config.current + 1); break;
                        };
                    }, config.speed);
                };

            },

            /* bind events */
            events: function () {
                config.startTimer = window.setTimeout(function () { o.slide(config.current + 1); }, config.speed);
            }

        };
        o.init();
    };

}; 

/***
RADAR INFOGRAPHIC
***/

$j(function () {
    var theme = "";

    $j("#itemOne").click(function () {
        fadeInOut("#graphOne");
        return false;

    });
    $j("#itemTwo").click(function () {
        fadeInOut("#graphTwo");
        return false;
    });
    $j("#itemThree").click(function () {
        fadeInOut("#graphThree");
        return false;
    });
    $j("#itemFour").click(function () {
        fadeInOut("#graphFour");
        return false;
    });
    $j("#itemFive").click(function () {
        fadeInOut("#graphFive");
        return false;
    });
    $j("#itemSix").click(function () {
        fadeInOut("#graphSix");
        return false;
    });




});
function fadeInOut(value)
{
	if($j(value).is(':visible'))
	{
		$j(value).fadeOut('fast');
	}
	else
	{
		$j(value).fadeIn('fast');
	}
}
