/*
    McLaren javascript uses jQuery v1.3.2. and jQuery color animations (included in jQuery file).
    jQuery is in noConflict mode, use 'jQ' instead of '$'.
*/

/*
    public mcLaren utils object with general functions and properties
*/
mcLaren = {
    utils: {
        // Get flash movie object to pass functions to flash
        getFlashMovie: function(movieName) {
            var isIE = navigator.appName.indexOf("Microsoft") != -1;
            return (isIE) ? window[movieName] : document[movieName];
        },
        // Form button hover states
        setButtonHover: function(selector) {
            jQ(selector).each(function() {
                var imgSrc = jQ(this).attr('src');
                jQ(this).hover(
                    function() {
                        jQ(this).attr('src', imgSrc.replace('.', '-h.'));
                    },
                    function() {
                        jQ(this).attr('src', imgSrc);
                    }
                )
                jQ(this).mousedown(
                    function() {
                        jQ(this).attr('src', imgSrc);
                    }
                )
            });
        },
        // Create site version cookie so users have consistant experience
        setSiteVersion: function(version) {
            createCookie('mclarenautomtive', version, 1);
        },
        // Extend an objects default properties
        extend: function(obj, defaults) {
            for (var i in defaults) {
                if (!obj[i]) obj[i] = defaults[i];
            }
        }
    }
};
// mcLaren.utils property defaults
mcLaren.utils.defaults = {
    pageType : 'flash',         // Insider, terms, registration are HTML: flash;html
    editing : false,            // In page editing mode: true;false
    locale : 'uk/' ,            // Country and language: cc/ll/
    userSiteVersion: 'flash',  // Cookie for flash or HTML: flash;html
    gaPageTitle: ''            // Page title to pass to Google analytics
};
mcLaren.utils.extend(mcLaren.utils, mcLaren.utils.defaults);
// mcLaren.translate
mcLaren.translate = {
    back: 'Back',
    flashSite: 'Flash site'
}

/*
    General onload function
*/
jQ(document).ready(function() {
    // MOSS overwrites
    // Detect if editing mode (must be before resize is instantiated)
    if (jQ('.ms-consolestatusframe').length > 0) mcLaren.utils.editing = true;

    
    // Framework and Navigation
    resize = new ResizeClass();
    resize.init();
    

    // Google Analytics
    jQ('.footer a').each(function(i) {
        if (jQ(this).attr('href').indexOf(window.location.host) === -1) {
            jQ(this).click(function() {
                pageTracker._trackPageview(jQ(this).attr('href'));
            });
        }
    });
    jQ('.iN-more').click(function() { pageTracker._trackPageview(mcLaren.utils.locale + 'theinsider.html'); }); // Insider blog Ajax preview


    // General page interactions
    // Set button hover images
    mcLaren.utils.setButtonHover(".input-submit"); // Registration and update forms
    
    // Insert back links in pages (add selectors as necessary)
    jQ('#sC-story-chapter, .gY-hero-image, .gY-blurb').append('<a class="link link-back"/>');
    // Set generic back button (put 'link-back' class on html links which you want to rename)
    jQ('.link-back').attr({ 'href': '#' }).text(mcLaren.translate.back).show().click(function() {
        history.go(-1);
        return false;
    });
    Cufon.refresh('#mclaren-site .link', {
        hover: true
    });

});


/*
Flash navigation resizing
Needs to be public so that Flash can call it.
All framework and navigation behaviour is stored inside 'init'
*/
// Constructor
var ResizeClass = function() {
    that = this;
    that.flashId = 'BaseLoader';
    that.panelId = 'loaded-content-wrapper';
    that.panelWidth = 450;
    that.width = 976;
    that.startHeight = (mcLaren.utils.pageType === 'html' || mcLaren.utils.editing === true) ? 61 : 561;
    that.navOpen = false;
}

// Methods
ResizeClass.prototype = {
    init: function() {

        var playerVersion = swfobject.getFlashPlayerVersion();
        // Delay resize so that IE loads the correct height
        if (playerVersion['major'] >= 10) {            
            delay = function() {
                jQ('#wrapper-centring').height(that.startHeight);
                jQ('#' + that.flashId).height(that.startHeight).width(that.width);
            }
            ieTimer = setTimeout(delay, 10);
        }

        // If an html page (show html content)
        if (mcLaren.utils.pageType === 'html' || playerVersion['major'] < 10) {
            jQ('.content-wrapper').css({ 'visibility': 'visible' });
            
            // Set navigation hover in IE 6
            jQ('#nav li').hover(
            function() {
                jQ(this).children('ul').show();
            },
            function() {
                jQ(this).children('ul').hide();
            });

            // Create flash HTML link
            jQ('#nav-control').append('<li><a href="/' + mcLaren.utils.locale + '" class="flashVersion">' + mcLaren.translate.flashSite + '</a></li>');
            Cufon.refresh('#nav-control a', {
                hover: true
            });
            
            // Bind set cookie clicks
            jQ('.flashVersion').click(function(e) {
                mcLaren.utils.setSiteVersion('flash');
            });
            jQ('.htmlVersion').click(function(e) {
                mcLaren.utils.setSiteVersion('html');
            });
        }

        // If a flash page and not in Sharepoint editing mode (remove html content, move footer to bottom of main nav)
        if (mcLaren.utils.pageType === 'flash' && mcLaren.utils.editing === false && playerVersion['major'] >= 10) {
            jQ('.content-wrapper').remove();
            jQ('#wrapper-centring').addClass('content-wrapper');
            jQ('#wrapper-centring').after(jQ('.footer-wrap'));
        }

        // If a flash page and in Sharepoint editing mode (Delay resize so that IE loads the correct height)
        if (mcLaren.utils.pageType === 'flash' && mcLaren.utils.editing === true) {
            delay = function() {
                jQ('#' + that.flashId + ', #wrapper-centring').height(that.startHeight);
            }
            ieTimer = setTimeout(delay, 10);
        }
        
        // If in editing mode hide flash
        if (mcLaren.utils.editing === true) {
            jQ('#' + that.flashId).hide();
            jQ('.content-wrapper').css({ 'padding-top': 61 + 'px', 'visibility': 'visible' });
        }

    },
    loadContent: function() {
        // Only call if pageType === html
        if (mcLaren.utils.pageType === 'html') that.toggleNav();
    },
    toggleNav: function() {
        // Only called if HTML
        if (that.navOpen === false) {
            jQ('#' + that.flashId + ', #wrapper-centring, #' + that.panelId).height(jQ('.content-wrapper').height());
            that.navOpen = true;
        } else {
            jQ('#' + that.flashId).height(that.startHeight);
            if (jQ('#' + that.flashId).width() === that.width) {
                // If flash is fully expanded (panel is hidden)
                jQ('#wrapper-centring').height(that.startHeight);
            }
            that.navOpen = false;
        }
    }
};

/*
Fight the war against Google Toolbar 3 and it's automatic input background colour changing!
Telerik.com: http://www.telerik.com/help/aspnet-ajax/prevent-google-toolbar-highlight-input-area.html
*/
(function() {
    jQ(document).ready(function() {
        if (jQ('.mc-form').length > 0) {
            colorChangeDetect(jQ('.mc-form'), '#494949');
            jQ('.input-text').css({ 'background-color': '#494949' });
        }
    });

    function colorChangeDetect(jQobj, inpBgColor) {
        var forms = jQobj.find('.input-text').each(function(i) {
            var input = this;

            var fixForm = function() {
                return restoreStyles(inpBgColor);
            }
            if (input.attachEvent) {
                input.attachEvent("onpropertychange", fixForm);
            }
            else if (input.addEventListener) {
                input.addEventListener("DOMAttrModified", fixForm, false);
            }
            input.style.backgroundColor = inpBgColor;
        });
    }

    function restoreStyles(inpBgColor) {
        if (event.srcElement.style.backgroundColor != inpBgColor) {
            event.srcElement.style.backgroundColor = inpBgColor;
        }
    }

})();


/*
Cookie generic functions:
Quirksmode: http://quirksmode.org/js/cookies.html
*/
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}


/*
Set Cufon font replacement
*/
(function() {
    Cufon.set('fontFamily', 'Serene MTC');

    Cufon.replace('.iN-article-title a', {
        hover: true
    })('.iN-article-title')
    ('.iN-articles p.iN-published')
    ('.iN-articles p.iN-category', {
        hover: true
    })('.iN-header p')
    ('.iN-article-list a', {
        hover: true
    })('.iN-articles .iN-no-posts h2')
    ('h1')
    ('.footer a', {
        hover: true
    })
    ('#gY-preview li .gY-preview-title')
    ('#mclaren-site .link', {
        hover: true
    })
    ('#home-content', {
        hover: true
    })
    ('#nav-control a', {
        hover: true
    })
    ('#tY-nav h2')
    ('#tY-sections h3 a', {
        hover: true
    })
    ('#tY-sections h3')
    ('#tY-register a', {
        hover: true
    })
    ('#eX-explodable-items .eX-explodable-item h2', {
        hover: true
    });
})();