﻿                                    /* PARAMETERS */
/***********************************************************************************************/

//Ratio of distance to time taken for the screen to scroll left/right
var speedRatio = 1.5;
//Delay given to the middle layer
var middleDelay = 50;
//Delay given to the back layer
var backDelay = 80;

//Id of current client
var currentClientId = null;
//Indicates whether or not to trigger the client popup
var showClients = false;
//Indicates whether or not to trigger case study popup
var showCaseStudy = false;

//Properties used by client fancyboxes
var fancyBoxClient = {
    'autoDimensions': true,
    'titleShow': false,
    'overlayOpacity': '0.7',
    'overlayShow': true,
    'centerOnScroll': true,
    'scrolling': 'auto',
    'onClosed': function() {
        if (showCaseStudy)
            getCaseStudies(currentClientId);
    },
    'onComplete': function() {
        jQuery('#fancybox-overlay').show();
        showCaseStudy = false;
    }
};

//Properties used by case study fancyboxes
var fancyBoxCaseStudy = {
    'autoDimensions': true,
    'titleShow': false,
    'overlayOpacity': '0.7',
    'overlayShow': true,
    'centerOnScroll': true,
    'scrolling': 'no',
    'showNavArrows': false,
    'onComplete': caseStudyLoad,
    'onClosed': function() {
        if (showClients) {
            getClients();
        }
    }
};

//Properties for generic fancybox pages
var fancyBoxPage = {
    'autoDimensions': true,
    'titleShow': false,
    'overlayOpacity': '0.7',
    'overlayShow': true,
    'centerOnScroll': true,
    'showNavArrows': false,
    'scrolling': 'auto',
    'onComplete': function() {
        jQuery('#fancybox-overlay').show();
    }
};


/***********************************************************************************************/



                                        /* PAGE LOAD */
/***********************************************************************************************/

jQuery(document).ready(function() {

    //Initialise the fancyboxes- must be done onload to work in IE7
    jQuery('#lnkClients').fancybox(fancyBoxClient);
    jQuery('#lnkPeople').fancybox(fancyBoxClient);
    jQuery('#lnkServices').fancybox(fancyBoxPage);
    jQuery('#lnkPhilosophy,.lnkPhilosophy').fancybox(fancyBoxPage);
    jQuery('#lnkTerms').fancybox(fancyBoxPage);
    jQuery('#lnkSitemap').fancybox(fancyBoxPage);    
    jQuery('#lnkError').fancybox(fancyBoxPage);
    //Create fancy boxes of case study links generated in default.aspx.cs 
    jQuery('#divCaseStudyLink div a').fancybox(fancyBoxCaseStudy);

    //Configure subnavigation as it doesn't involve scrolling and is required to show clients correctly
    configureSubNav();

    //Initialise the slider
    initaliseSlider();

    //Position initial elements once content loads
    jQuery('#imgLanding').load(function() {
        jQuery('#pageLanding').css('left', centreLeftPosition(0) + 'px');
        centreRequired();
    });

    //Position initial elements where initial elements are cached
    jQuery('#pageLanding').css('left', centreLeftPosition(0) + 'px');
    centreRequired();

    //Load real content and switch after seo crawl
    loadImages();
});

//Fancybox case study load event - set nav method here
function caseStudyLoad() {

    showClients = false;
    jQuery('#fancybox-overlay').show();
    jQuery('div.clientButton').unbind().hover(function() {
        jQuery('div.clientButton').css('background-image', 'url(/images/casestudy/btnClientsOn.jpg)');
    }, function() {
        jQuery('div.clientButton').css('background-image', 'url(/images/casestudy/btnClientsOff.jpg)');
    }).click(function()
    {
        showClients = true; 
        jQuery.fancybox.close();
    });
    jQuery('div.backButton').unbind().hover(function() {
        jQuery('div.backButton').css('background-image', 'url(/images/casestudy/btnBackOn.jpg)');
    }, function() {
        jQuery('div.backButton').css('background-image', 'url(/images/casestudy/btnBackOff.jpg)');
    }).click(function() {
        jQuery.fancybox.prev();
    });
    jQuery('div.nextButton').unbind().hover(function() {
        jQuery('div.nextButton').css('background-image', 'url(/images/casestudy/btnNextOn.jpg)');
    }, function() {
        jQuery('div.nextButton').css('background-image', 'url(/images/casestudy/btnNextOff.jpg)');
    }).click(function() {
        jQuery.fancybox.next();
    });
}

/***********************************************************************************************/


                                        /* PAGE RESIZE METHODS */
/***********************************************************************************************/

//Hack in to the resize event so you can reposition elements
jQuery(window).resize(function() {
    setTimeout('centreRequired();', 100);
});

//Centres an element by setting the left style property based on the clientWidth
function centreElement(elementId, checkValue) {
    var element = jQuery('#' + elementId)[0];
    var leftStyle = (document.body.clientWidth / 2 - element.offsetWidth / 2) + 'px';
    if (checkValue == null || leftStyle != 0)
        element.style.left = (document.body.clientWidth / 2 - element.offsetWidth / 2) + 'px';
}

function centreRequired() {
    //centre nav and footer
    centreElement('divNav');
    centreElement('footer');
    centreElement('slider');
}

/***********************************************************************************************/


                                       /* SLIDER METHODS */
/***********************************************************************************************/

//Loads the slider plugin at the bottom of the page
function initaliseSlider() {
    //var sliderValue = parseInt((361 / getTotalRange()) * 100);
    var sliderValue = 0;
    $("#slider").slider({
        animate: true,
        max: 100,
        min: 0,
        orientation: 'horizontal',
        range: 'min',
        step: 1,
        value: sliderValue,
        slide: function(event, ui) {
            slideToSection();
        },
        stop: function(event, ui) {
            slideToSection();
        }
    });
    jQuery('#slider').slider('disable');
}

//Goes to a section based on the interation with the slider plugin
function slideToSection() {
    var currentValue = jQuery('#slider').slider('option', 'value');
    var destination = 0;
    if (currentValue != 0) {
        totalRange = getTotalRange();
        destination = parseInt((currentValue / 100) * totalRange);
    }
    destination = (destination + 395) * -1;
    return scrollToPage(destination, false);
}

/***********************************************************************************************/


                                        /* IMAGE LOADING */
/***********************************************************************************************/

//Loads images onto the page
function loadImages() {

    //jQuery('<img />').attr({
        //'src': 'images/background/middle_layer01.png',
        //'title': '',
        //'alt': '',
        //'id': 'imgMiddle1',
        //'usemap': '#middle_layer01map'
    //}).appendTo('#divMiddle');

    //Loop through each section and add all images
    for (var i = 1; i <= 3; i++) {
        var pageNumber = i.toString();

        jQuery('<img />').attr({
            'src': 'images/background/top_layer0' + pageNumber + '.png',
            'title': '',
            'alt': '',
            'id': 'imgTop' + pageNumber,
            'usemap': '#top_layer0' + pageNumber + 'map'
        }).appendTo('#divTop');

        if (i == 1) {
            jQuery('<img />').attr({
                'src': 'images/background/bottom_layer0' + pageNumber + '.jpg',
                'title': '',
                'alt': '',
                'id': 'imgBottom' + pageNumber,
                'usemap': '#bottom_layer0' + pageNumber + 'map',
                'load': switchContent
            }).appendTo('#divBack');
        }
        else if (i == 2) {
            jQuery('<img />').attr({
                'src': 'images/background/bottom_layer0' + pageNumber + '.jpg',
                'title': '',
                'alt': '',
                'id': 'imgBottom' + pageNumber,
                'usemap': '#bottom_layer0' + pageNumber + 'map'
            }).appendTo('#divBack');
        }
    }
    jQuery('<div id="ContactUs"><div id="ContactUsContent"><iframe width="258" height="250" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.co.uk/maps?q=JPMH,+Ltd.,+City+of+London&amp;hl=en&amp;sll=51.506827,-0.085538&amp;sspn=0.015606,0.008182&amp;ie=UTF8&amp;view=map&amp;cid=10297295556717261547&amp;hq=JPMH,+Ltd.,+City+of+London&amp;hnear=&amp;ll=51.504148,-0.08523&amp;spn=0.006678,0.011029&amp;z=15&amp;iwloc=near&amp;output=embed"></iframe><h2>JEFFRIES. PARSONS. MYERS. HARVEY.</h2><h3>THE LAXMI BUILDING, THE TANNERIES<br />57 BERMONDSEY STREET<br />LONDON SE1 3XJ</h3><h4>JAMES CRAGG<br />BUSINESS DEVELOPMENT DIRECTOR</h4><p>DIRECT: +44 (0) 20 7645 3292<br />SWITCHBOARD: +44 (0) 20 7645 3299<br />EMAIL: <a href="mailto:info@jpmh.co.uk">info@jpmh.co.uk</a></p></div></div>').appendTo('#divTop');
    getShowReel();
}

function switchContent() {
    var centerPostion = centreLeftPosition(-395);
    jQuery('#divBack, #divMiddle, #divTop, #divBackCover, #divMiddleCover, #divTopCover').css('left', centerPostion + 'px');
    jQuery('#pageLanding').hide();
    jQuery('#slider').slider('enable');
    jQuery('#pageContent').fadeIn(500, function() {
        centreRequired();
        activateNavigation();
        //$.fancybox.hideActivity();
    });

}


/***********************************************************************************************/


                                      /* NAV METHODS*/
/***********************************************************************************************/

//Initialises main navigation functionality
function activateNavigation() {
    jQuery('#mainLogo').click(function() {
        return goToPage(0);
    });
    jQuery('#lnkWhatWeThink').click(function() {
        return goToPage(0);
    });
    jQuery('#lnkWhatWeDo').click(function() {
        return goToPage(1);
    });
    jQuery('#lnkOurPeople').click(function() {
        return goToPage(2);
    });
    jQuery('#lnkContact').click(function() {
        return goToPage(3);
    });

    jQuery('#mainLogo, #lnkWhatWeThink, #lnkWhatWeDo, #lnkOurPeople, #lnkContact').css('cursor', 'pointer');
}


//Shows and hides sub nav dependant on hover of main nav
function configureSubNav() {
    jQuery("ul#topnav li").hover(function() {
        jQuery(this).find("span.subnav").stop().animate({ 'width': '130px', 'opacity': '1' }, 400);
    },
    function() {
        jQuery(this).find("span.subnav").stop().animate({ 'width': '0', 'opacity': '0' }, 400);
    });

    jQuery("#spnClients span").hover(function() {
        jQuery(this).find("span").stop().animate({ 'height': '132px', 'opacity': '1' }, 400);
    },
    function() {
        jQuery(this).find("span").stop().animate({ 'height': '0', 'opacity': '0' }, 400);
    });
}


/***********************************************************************************************/


                                       /* SCROLL METHODS*/
/***********************************************************************************************/

//Identifies which section to scroll to
function goToPage(pageNo) {
    switch (pageNo) {
        //Home page
        case 0:
            scrollToPage(-395, true);
            break;
        //What we do
        case 1:
            scrollToPage(-1547, true);
            break;
        //Our people 
        case 2:
            scrollToPage(-3771, true);
            break;
        //Contact5752
        case 3:
            scrollToPage(-5556, true);
            break;
    }
}

//Actually animates the div areas by the left value provided
function scrollToPage(destination, adjustForCentre) {
    //Adjust slider control
    var sliderDestination = destination < 0 ? (destination * -1) : destination;
    sliderDestination = sliderDestination - 395;   
    var sliderValue = parseInt((sliderDestination / getTotalRange()) * 100);
    jQuery('#slider').slider('option', 'value', sliderValue);
    
    //Calculate variables for top layer scrolling
    var currentLocaion = getCurrentPosition('divTop');
    var distance = calculateLayoutAdjustment(destination, currentLocaion, true);
    var duration = calculateDuration(distance - currentLocaion);
    
    //Scroll top layer and cover layer together
    jQuery('#divTop').stop().animate({ left: distance + 'px' }, duration, 'swing');
    jQuery('#divTopCover').stop().animate({ left: distance + 'px' }, duration, 'swing');

    //Calculate variables for middle layer scrolling
    currentLocaion = getCurrentPosition('divMiddle');
    distance = calculateLayoutAdjustment(destination, currentLocaion, true);
    duration = calculateDuration(distance - currentLocaion);
    
    //Scroll middle layer
    if (!adjustForCentre) {
        jQuery('#divMiddle').delay(middleDelay).stop().animate({ left: distance + 'px' }, duration, 'swing');
    }
    else {
        setTimeout("jQuery('#divMiddle').stop().animate({ left:'" + distance + "px' }," + duration + ", 'swing');", middleDelay);
    }

    //Calculate variables for bottom layer scrolling
    currentLocaion = getCurrentPosition('divBack');
    distance = calculateLayoutAdjustment(destination, currentLocaion, true);
    duration = calculateDuration(distance - currentLocaion);
    
    //Scroll bottom layer
    if (!adjustForCentre) {
        jQuery('#divBack').delay(backDelay).stop().animate({ left: distance + 'px' }, duration, 'swing');
    }
    else {
        setTimeout("jQuery('#divBack').stop().animate({ left:'" + distance + "px' }," + duration + ", 'swing');", backDelay);
    }
}

/***********************************************************************************************/

                                        /* AJAX METHODS */
/***********************************************************************************************/

//Requests client data from service
function getClients() {
    return callService('GetAllClients', clientFancyBox, clientRequestError);
}

//Requests case study data from service
function getCaseStudies(id) {
    callService("GetCaseStudies/" + id, caseStudyFancyBox, caseStudyRequestError);
    return false;
}

//Requests showreel html service
function getShowReel() {
    return callService('GetShowReel', showReelRender, showReelRequestError);
}

//Gets the data for the terms fancybox and calls method to show it
function getTerms() {
    if (jQuery('#divTerms').html() == '')
        return callService('GetTerms', termsFancyBox, termsRequestError);
    else
        termsFancyBox(null);
}

//Gets the data for the terms fancybox and calls method to show it
function getSitemap() {
    if (jQuery('#divSitemap').html() == '')
        return callService('GetSitemap', sitemapFancyBox, sitemapRequestError);
    else
        sitemapFancyBox(null);
}

//Creates and triggers the client fancybox
function clientFancyBox(clients) {
    jQuery('#divClientsContent').html('');
    //Add content to div
    jQuery(clients).each(function(index) {
        jQuery('<img />').attr({
            'id': 'imgClient' + this.Id,
            'src': this.ImageUrl,
            'alt': this.Name
        }).appendTo('#divClientsContent');
    });
    //Loop thru the clients, if they have case studies add the click event and give it the pointer style
    jQuery(clients).each(function(index, client) {
        if (client.HasStudies) {
            jQuery('#imgClient' + client.Id).css('cursor', 'pointer').click(function() {
                showCaseStudy = true;
                currentClientId = client.Id;
                jQuery.fancybox.close();
            });
        }
    });
    //Hide fancybox load screen and trigger the client popup
    jQuery.fancybox.hideActivity();
    triggerClick('lnkClients');
}

//Creates and triggers caseStudy fancybox/gallery
function caseStudyFancyBox(caseStudies) {
    if (caseStudies.length > 0) {
        //Loop through case studies
        jQuery(caseStudies).each(function(index) {
            var caseId = this.ClientId + '_' + this.Id;
            if (jQuery('#caseDiv' + caseId).length > 0 && jQuery('#caseDiv' + caseId).html() == '')
                jQuery('#caseDiv' + caseId).html(this.ControlContent);
        });
        jQuery('#clientLinkDiv' + caseStudies[0].ClientId).find('a:first').trigger('click');
    }
    else
        caseStudyRequestError();
}

//Renders the showreel flash into the repective div
function showReelRender(showReel) {
    jQuery('#divlnkShowReel div').html(showReel);
}

//Callback method renders terms to page and displays popup
function termsFancyBox(content) {
    if (content != null)
        jQuery('#divTerms').html(content);

    triggerClick('lnkTerms')
}

//Callback method renders sitemap to page and displays popup
function sitemapFancyBox(content) {
    if (content != null)
        jQuery('#divSitemap').html(content);

    triggerClick('lnkSitemap')       
}

//Displays client load error message in fancybox
function clientRequestError() {
    jQuery('#divError').html('Client information is currently unavailble<br/></br/>We are aware of this problem and will have them back up soon');
    triggerClick('lnkError');
}

//Displays case study load error message in fancybox
function caseStudyRequestError() {
    jQuery('#divError').html('Case study information is currently unavailble<br/></br/>We are aware of this problem and will have them back up soon');
    triggerClick('lnkError');
}

//Displays case study load error message in fancybox
function quizRequestError() {
    jQuery('#divError').html('Quiz information is currently unavailble<br/></br/>We are aware of this problem and will have them back up soon');
    triggerClick('lnkError');
}

//Displays case study load error message in fancybox
function termsRequestError() {
    jQuery('#divError').html('Terms and Conditions are currently unavailable<br/></br/>We are aware of this problem and will have them back up soon');
    triggerClick('lnkError');
}

//Displays sitemap load error message in fancybox
function sitemapRequestError() {
    jQuery('#divError').html('Sitemap is currently unavailable<br/></br/>We are aware of this problem and will have it back up soon');
    triggerClick('lnkError');
}

//Display error text if ajax fails
function showReelRequestError() {
    jQuery('#divlnkShowReel').html('Error');
}

/***********************************************************************************************/

                                        /* HELPER METHODS */
/***********************************************************************************************/

//Gets current z index of scrolling div
function getCurrentPosition(divId) {
    var currentPosition = jQuery('#' + divId).css('left');
    currentPosition = ((currentPosition.charAt(currentPosition.length - 1, 1) == "x") ? currentPosition.substring(0, currentPosition.length - 2) : currentPosition);
    return (currentPosition == 'auto' ? 0 : parseInt(currentPosition));
}

//Calculates the left value required to center content based on it's left position when plushed to the left of the page
function centreLeftPosition(plushedLeftValue) {
    var position = (document.body.clientWidth / 2 - 1021 / 2);
    position = (position + plushedLeftValue);
    return position;
}

//Calculates the distance to travel
function calculateLayoutAdjustment(destination, currentLocation, adjustForCentre) {
    if (adjustForCentre)
        destination = centreLeftPosition(destination);
    else if (destination != 0)
        destination = destination * -1;
    return destination;
}

//Calculates how long it should take to get to a section
function calculateDuration(distance) {
    if (distance < 0)
        distance = distance * -1;
    return distance * speedRatio;
}

//Gets the total length of the slider
function getTotalRange() {
    return 5200;
}

//Detects if the current browser is internet explorer
function isIE() {
    return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

//Gets the version of ie
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

function browserIsIE7() {
    return getInternetExplorerVersion() < 8.0;
}

//Performs a call to the WCF service
function callService(serviceUrl, successMethod, failureMethod) {
    jQuery.ajax({
        type: 'GET',
        url: "service/JpmhWcfService.svc/" + serviceUrl,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        processdata: true,
        success: function (result) {
            successMethod(result);
        },
        error: failureMethod
    });
    return false;
}

//Triggers the click event of the element with the speicified id
function triggerClick(id) {
    jQuery('#' + id).trigger('click');
}


/***********************************************************************************************/
