/*
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
*/
if (typeof mcLaren === 'undefined') mcLaren = {};

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

    if (location.search.length > 0) {
        var params = location.search.replace('?', '').split('&');
        for (x = 0; x < params.length; x++) {
            if (params[x].split('=')[0] == 'trackingEvent') {
                var tValues = params[x].split('=')[1].split('|');
                pageTracker._initData();
                pageTracker._trackEvent(mcLaren.utils.locale.replace('/', ''), unescape(tValues[0]), unescape(tValues[1]));
            }
        }
    }

    // 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, #profile #current-details div.bottom').append('<a class="link link-back"/>');
    jQ('.link-back').text(mcLaren.translate.back);
    // Set generic back button (put 'link-back' class on html links which you want to rename)
    jQ('.link-back').attr({ 'href': '#' }).show().click(function() {
        history.go(-1);
        return false;
    });
    Cufon.refresh('#mclaren-site .link', {
        hover: true
    });

    // Adds a click event to elements with the class 'mc-invoke-overlay'
    // This results in a dark, slightly transparent overlay being shown
    // over the whole of the page, leaving only the nav usable.
    jQ('.mc-invoke-overlay').click(
		function() {
		    jQ('div#mclaren-site').append('<div class="mc-overlay"></div>');
		    var overlay = jQ('div.mc-overlay');
		    overlay.css('opacity', 0);
		    overlay.height(jQ(document).height());
		    overlay.width(jQ(document).width());

		    jQ('div#mclaren-site').append('<div class="mc-overlay-dialogue"></div>');
		    var overlayDialogue = jQ('div.mc-overlay-dialogue');
		    overlayDialogue.hide();
		    overlayDialogue.css('top', parseInt(jQ(document).scrollTop()) + 160);
		    overlayDialogue.html(jQ(this).next('div.mc-overlay-contents').html());
		    var sWidth = jQ(window).width();
		    var dWidth = jQ('.mc-overlay-dialogue').outerWidth(true);
		    var dLeft = Math.floor((sWidth - dWidth) / 2);
		    overlayDialogue.css('left', dLeft);

		    overlayDialogue.append('<button class="close">Close</button>');

		    overlay.fadeTo('450', 0.5, function() {
		        overlayDialogue.fadeIn('450');
		    });

		    jQ('div.mc-overlay, div.mc-overlay-dialogue button').click(
				function() {
				    overlayDialogue.fadeOut('450', function() {
				        overlay.fadeOut('450', function() {
				            overlayDialogue.remove();
				            overlay.remove();
				        });
				    });
				    return false;
				}
			);

		    return false;
		}
	);
});


/*
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('select').css('visibility', 'hidden');
            jQ('#' + that.flashId + ', #wrapper-centring, #' + that.panelId).height(jQ('.content-wrapper').height());
            that.navOpen = true;
        } else {
            jQ('select').css('visibility', 'visible');
            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() {
        /* Standard form */
        if (jQ('.mc-form').length > 0) {
            colorChangeDetect(jQ('.mc-form'), '#5a5859');
            jQ('input.input-text, textarea.input-text').css({ 'background-color': '#5a5859' });
            /* Tell us more about yourself form */
        } else if (jQ('#tum-form').length > 0) {
            colorChangeDetect(jQ('.mc-form'), '#494949');
            jQ('input.input-text, textarea.input-text').css({ 'background-color': '#494949' });
        }
    });

    function colorChangeDetect(jQobj, inpBgColor) {
        var forms = jQobj.find('input.input-text, textarea.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-perfection a', {
        hover: true
    })
    ('#eX-explodable-items .eX-explodable-item h2', {
        hover: true
    })
    ('#profile-navigation ul li a', {
        hover: true
    })
    ('#profile div.pagination a.page', {
        hover: true
    })
    ('#profile ul li.car h2, #profile.compare-cars ul li.car h3, #profile.compare-cars ul li.car h4, #profile.compare-cars ul.options li div, #profile .no-results');
})();

// Automated testing JavaScript
function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

function qaOutputDebug(debug) {
    if (jQ('div#qa-output').length == 0) {
        jQ('body').append('<div id="qa-output">' + debug + '</div>');
    } else {
        jQ('div#qa-output').html(debug);
    }
}
