/*
NGW NEW general JS - permanent functionality
Dependencies: jQuery 1.3.2, swfObject 2.0
Date: 2009
Author: SCM, Tim Leung
*/

document.writeln('<style type="text/css">.js-hide { display: none; }</style>');
var config = { };

jQuery(document).ready(function init(){
	$('a[rel=blank]').attr('target', '_blank');

	setupShowroomMovieRollovers();
	print.addPrintEvents(jQuery('a.promo_print'));
	setupTogglesZZplus();
	hoverToggle('.js-hover');
	
	flashOverlay.init();
	contentpanels.init();
	testdriveForm.init();
	
	//UK promotion links
	if (gup('over', jQuery('#content.homePromos img').attr('src')) != false) homePromo.init($('#content.homePromos a'));
	if (jQuery.browser.msie) {
		jQuery('.promoContainer a').nb();
	}
	
	// Brochure download links - double action on a link - yuk
	jQuery('#content ol.js-brochure-download ul.links a').click(function (e) {
		// grab the href and open a new window
		var link = jQuery(this).attr('href');
		if (link) window.open(link);
		// let the postback onclick fire
	});
	
	tracking.onPageLoad();
	
	//GA tracking file download and external links
	//place inside of DOM ready function or similar
	//DEPENDENCIES: Google Analytics 2 - ga.js
	if (typeof pageTracker == 'object') {
		var el = document.getElementsByTagName
		("a");
		var link_path = ''; var tracking_string = '';
		for (var cnt = el.length - 1; cnt > 0 ; cnt--) {
			var link_path = el[cnt].pathname;
			tracking_string = false;
			if (location.host == el[cnt].hostname) {
				if (link_path.match(/\.(doc|pdf|xls|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)$/)) {
					tracking_string = el[cnt].pathname;
				}		
			} else if (el[cnt].hostname !== '') {
				tracking_string = '/external_links/' + el[cnt].hostname;
			}
			if (tracking_string !== false ) { 
				el[cnt].tracking_string = tracking_string;
				if (window.addEventListener) el[cnt].addEventListener('click', function(){
					pageTracker._trackPageview(this.tracking_string);
				}, false);
				else if (window.attachEvent) el[cnt].attachEvent('onclick',  function(e){
					pageTracker._trackPageview(e.srcElement.tracking_string);
				});
			}
		};
	}
});

// collapsing content panels module - used in specs pages
var contentpanels = function () {
	var containerCssSelector = '#content.contentpanels';
	var container;
	var mutuallyExclusiveTags = { h4 : true };
	var panelAnchorName = 'section-panel-';
	
	function setupControls () {
		container = jQuery(containerCssSelector);
		if (container.length !== 1) return false;
		
		var nodes = container.find('h3, h4');

		nodes.each(function (i) {
			var s = jQuery(this);
			createPanel(s, i);
			
			// open any of class expandeds
			// check for i > 0 if you want  the first node open
			if (!s.hasClass('expanded')) collapse(s);
			else s.addClass('expanded');
			
			// add control
			var linkText = s.html();
			s.html('<a href="#' + panelAnchorName + i +'">' + linkText + '</a>');
			s.find('a').nb().click(function (e) {
				var el = jQuery(this);
				e.preventDefault();
				var node = el.parent();
				if (node.hasClass('expanded')) collapse(node);
				else expand(node);
			});
		});
		return true;
	}
	
	function createPanel (el, i) {
		var tagname  = el.attr('tagName');
		el.after('<div id="' + panelAnchorName + i + '" class="js-content-panel"></div>');
		el = jQuery('#' + panelAnchorName + i);
		el.nextAll().each(function () {
			var s = jQuery(this);
			if (s.attr('tagName') === tagname) return false;
			el.append(s);
		});
	}

	
	// hide content
	function collapse (el) {
		el.removeClass('expanded');
		el.next('div.js-content-panel').hide();
	}
	
	function expand (el) {
		var tagname  = el.attr('tagName').toLowerCase();
		if (mutuallyExclusiveTags[tagname]) {
			el.parent().find(tagname).each(function () { collapse(jQuery(this)); });
		}
		el.addClass('expanded');
		el.next('div.js-content-panel').show();
	}
	
	// public methods
	return {
		init: function () {
			setupControls();
		}
	};
}();

var homePromo = {
    config: {
        effectDelay: 3000,
        fadeTime: 1000
    },
    init: function(el) {
    	var that = this;
        var all = el.css({ display: 'block', width: '150px', height: '150px' });
        var all_img = all.find('img');
        var cnt = 0;
        var len = all.length;
        var fade = function() {
            jQuery(all_img[cnt]).fadeOut(that.config.fadeTime, function() {
                cnt++;
                if (cnt >= len) {
                    cnt = 0;
                }
            });
        };
        var timer = jQuery.timer(that.config.effectDelay, function(t) {
            if (!timer.hover) {
                var i = jQuery('img:hidden', all);
                if (i.length == 0) {
                    fade();
                } else {
                    i.fadeIn(that.config.fadeTime, function() {
                        fade();
                    });
                }
            }
        });
        timer.hover = false;
        all_img.css({ margin: 0 }).each(function() {
            var img = jQuery(this);
            var over = gup('over', img.attr('src'));
            var a = img.parent();
            a.css({ 'background-image': 'url(' + over + ')' });
            a.hover(function() {
                all_img.css({ display: 'block' });
                jQuery('img', this).css({ display: 'none' });
                timer.hover = true;
            }, function() {
                jQuery('img', this).css({ display: 'block' });
                timer.hover = false;
                timer.reset(2000);
            });
        });
    }
};

// Showroom rollovers 080327
function setupShowroomMovieRollovers() {
	var thumbList = jQuery('#js_showroomThumbList');
	if (thumbList.length == 0) return false;

	thumbList.find('li a').each(function(i) {
		$(this).hover(function() {
			var funcCall = "showroomDolabel('" + getModelName($(this)) + "')";
			window.showroomDolabelID = setTimeout(funcCall, 500);
		}, function() {
			clearTimeout(window.showroomDolabelID);
		});
	});

	function getModelName(elem) {
		var hrefTokens = [];
		var tempArray = elem.attr('href').split('/');
		for (var i = 0; i < tempArray.length; i++) {
			if (tempArray[i] != '') hrefTokens.push(tempArray[i]);
		}
		return hrefTokens[1];
		
		/*var hrefTokens = elem.attr('href').split('/');

		// "mazda2/"
		if (hrefTokens.length == 2 || hrefTokens.length == 6) {
			return hrefTokens[hrefTokens.length - 2];
		}
		// "mazda2/5door/overview/"
		if (hrefTokens.length == 4 || hrefTokens.length == 8) {
			return hrefTokens[hrefTokens.length - 4];
		}
		// "mazda2/Overview/"
		if (hrefTokens[hrefTokens.length - 2].toLowerCase() == "overview") {
			return hrefTokens[hrefTokens.length - 3];
		}*/
	};

	return true;
};

function showroomDolabel(target) {
	var movieInstance = getFlashMovieObject("command");
	if (movieIsLoaded(movieInstance)) {
		movieInstance.SetVariable("interacted", true);
		movieInstance.SetVariable("chosenModel", target);
		movieInstance.TGotoLabel("_level0/", "go");
	}
};

function getFlashMovieObject(movieName) {
	// Browsers refer to the movie object differently.
	// This function returns the appropriate syntax depending on the browser.	
	if (window.document[movieName]) {
		return window.document[movieName];
	} else {
		if (navigator.appName.indexOf("Microsoft Internet") == -1) {
			if (document.embeds && document.embeds[movieName]) return document.embeds[movieName];
		} else // if (navigator.appName.indexOf("Microsoft Internet")!=-1) 
			return document.getElementById(movieName);
	}
};

// Checks if movie is completely loaded.
// Returns true if yes, false if no.
function movieIsLoaded(theMovie) {
	if (theMovie != null) {
		return theMovie.PercentLoaded() == 100;
	} else {
		return false;
	}
};
/// Showroom rollovers

// generic popup window allowing size to be set
function openWindow(url, winName, w, h, properties) {
	var properties = properties || "resizable";
	var leftPos = (screen.width) ? (screen.width - w) / 2 : 0;
	var topPos = (screen.height) ? (screen.height - h) / 2 : 0;
	var settings =
	'height=' + h + ',width=' + w + ',top=' + topPos + ',left=' + leftPos + ',' + properties;
	var newWindow = window.open(url, winName, settings);
	if (url.indexOf("://") == -1) newWindow.focus();
	top.newWindow = true;
	return false;
};

// hover toggle function for video gallery: .js-hover
function hoverToggle(el) {
	$(el).parent().hover(function() {
		$(this).children(el).stop(true, true).slideToggle(150);
	}, function() {
		$(this).children(el).stop(true, true).slideToggle(100);
	});
};

// dynamic styles: js_collapsed, js_expanded
function setupTogglesZZplus() {
	// collapse toggles

	var content = jQuery('#content');
	content.find('a.toggle').each(function() {
		jQuery(this).addClass('js_collapsed');
		//jQuery(this).next('div').addClass('js_collapsed');
		jQuery(this).nb().click(function(e) { 
			toggleDisclaimer(this); 
			e.preventDefault();
		});
	});	
};

// collapse / expand text content, used on zzplus
function toggleDisclaimer(el) {
	var element = jQuery(el);
	var effectDurationDown = 500;
	var effectDurationUp = 500;
	var nextElem = element.next();

	if (element.hasClass('js_collapsed')) {
		/* show the content element */
		element.removeClass('js_collapsed');

		if (nextElem.hasClass('no_print')) {//next is a '...' element
			nextElem.hide();
			nextElem = element.next().next(); //1
		}
		/*nextElem.hide();
		nextElem.removeClass('js_collapsed');*/
		nextElem.slideDown(effectDurationDown);

	} else {
		/* hide the content element */
		element.addClass('js_collapsed');

		if (nextElem.hasClass('no_print')) {
			nextElem = element.next().next(); //1
		}

		nextElem.slideUp(effectDurationUp);
		/*nextElem.slideUp(effectDurationUp, function() {
			nextElem.addClass('js_collapsed');
			element.next().show(); // '...' element if exists
		});*/
	}
};

// Top navigation navigation
sfHover = function() {
	$('#nav li').hover(function() {
		$(this).addClass('sfhover');
	}, function() {
		$(this).removeClass('sfhover');
	});
	/*if (document.getElementById("nav") !== null) {
		var sfEls = document.getElementById("nav").getElementsByTagName("LI");
		for (var i = 0; i < sfEls.length; i++) {
			sfEls[i].onmouseover = function() {
				this.className += " sfhover";
			};
			sfEls[i].onmouseout = function() {
				this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
			};
		}
	}*/
};
if (window.attachEvent) window.attachEvent("onload", sfHover);
// End: Top navigation navigation

var print = {
	addPrintEvents: function(el) {
		el.click(function(e) {
			window.print();
			e.preventDefault();
		});
	}
};

/* simple template */
String.prototype.tpl = function (o) {
    return this.replace(/{\$([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};


/* test for empty object */
function emptyObject(o) {
	for (var i in o) { 
		return false;
	}
	return true;
}

/* link blurring extends jQ */
jQuery.fn.nb = function() {
	this.blur();
	return this.focus(function(){
		this.blur();
	});
};

/* replaces DOM element and returns the new jQuery object*/
jQuery.fn.replace = function() {
    var stack = [];
    return this.domManip(arguments, true, 1, function(a){
        this.parentNode.replaceChild( a, this );
        stack.push(a);
    }).pushStack( stack );
};

/*function preloadImages() {
	var a = (typeof arguments[0] == 'object')? arguments[0] : arguments;
	for(var i = a.length -1; i >= 0; i--) {
		$("<img>").attr("src", a[i]);
	}
}*/

function gup(name, tmpURL) {
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	if (tmpURL) { //if is set - use it

	} else {
		var tmpURL = window.location.href;
	}
	var results = regex.exec(tmpURL);

	if (results == null) return false;
	else return results[1];
}

/*
*	jQuery Timer plugin v0.1
*	Matt Schmidt [http://www.mattptr.net]
*/
jQuery.timer = function (interval, callback) {
	var interval = interval || 100;

	if (!callback)
		return false;
	
	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};
		
		this.internalCallback = function () {
			callback(self);
		};
		
		this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);
			
			var val = val || 100;
			this.id = setInterval(this.internalCallback, val);
		};
		
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		
		var self = this;
	};
	
	return new _timer(interval, callback);
};


var simpleCookies = {
	set: function (name, value, hours, path) {
		var expires = this.getHoursFromNow(24);
		if (hours) expires = this.getHoursFromNow(hours);
		path = path || '/';
		document.cookie = name +'='+ escape(value) +'; expires='+ expires +'; path='+ path;
	},
	getHoursFromNow: function (hours) {
		return new Date(new Date().getTime() + hours * 3600000);
	},
	get: function (name) {
		name += '=';
		var c, cs = document.cookie.split(';');
		for (var i = 0, len = cs.length; i < len; i++) {
			c = cs[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(name) == 0) {
				return unescape(c.substring(name.length, c.length));
			}
		}
	}
};

function log(a) {
	console.log(a);
}


// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	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;
	}
});

var config = { url: '', delay: 800, target: '_self', timeout: '' };
/* alias - tracking string, url - URL redirect after tracking (optional) */
function magicTracking(alias, url, target, popup) {
	if (typeof alias !== 'string' && alias.length > 0) {
		url = alias[1]; target = alias[2]; popup = alias[3]; alias = alias[0];
	}
	var products = null;
	var displayed = null;
	if (!tc_logging_active) return;
	alias = tc_fixURL(alias);
	config.target = target || '_self';
	if (Image) {
		var img = new Image();
		if (typeof url == 'undefined' || url == 'undefined' || url == '') {
			//no URL specified do nothing...
			url = '';
		} else {
			config.url = url;
			if (config.target == '_blank') {
				if (popup != 'flash_popup') window.open(config.url);
			} else {
				config.timeout = self.setTimeout('imageLoaded()', config.delay); //just in case the logging doesn't happen or browser doesn't support Image
				if (img.addEventListener) {
					img.addEventListener('load', imageLoaded, false);
				} else if (img.attachEvent) {
					img.attachEvent('onload', imageLoaded);
				} else if (img.onload) {
					img.onload = function() {
						imageLoaded();
					};
				}
			}

		}
		img.url = url;
		img.src = tc_get_log_URL("i", alias, tc_products, new Date().getTime(), displayed);
	}
};

function imageLoaded() {
	self.clearTimeout(config.timeout); //reset the timeout
	if (config.target == '_self') {
		window.location = config.url;
	}
};


/**
    expanding hero area for flash content
    called from flash movie with hero.expand(duration) / hero.collapse(duration)
	where duration is in msec
 */
var hero = {
            flashElId: 'expandDemo',
            containerElId: 'expanding-hero',
            defaultExpandDuration: 300,
            defaultCollapseDuration: 300,
            elementProperties: null,
            
            // duration is in ms
            expand: function(duration) {
                        var ep = this.getElementProperties();
                        if (ep === null) return false;
                        ep.container.animate({
                                    height: ep.expandHeight + 'px'
                        }, duration || this.defaultExpandDuration);
                        return true;
            },
            collapse: function (duration) {
                        var ep = this.getElementProperties();
                        if (ep === null) return false;
                        ep.container.animate({
                                    height: ep.collapseHeight + 'px'
                        }, duration || this.defaultExpandDuration);
                        return true;
            },
            getElementProperties: function () {
                        if (this.elementProperties) return this.elementProperties;
                        
                        var flashEl = jQuery('#' + this.flashElId);
                        var container = jQuery('#' + this.containerElId);
                        if (!container || !flashEl) return null;
                        
                        var expandHeight = flashEl.height();
                        var collapseHeight = container.height();
                        if (expandHeight > 0 && collapseHeight > 0) {
                                    return this.elementProperties = {
                                                container: container,
                                                expandHeight: expandHeight,
                                                collapseHeight: collapseHeight
                                    };
                        }
                        return null;
            }
};


/**
* Module - manages client-side tracking 
* 
* use:
*	tracking.domready(function () {
*		tracking.appendTracking('.links a', 'tracking_string', null, true, false);
*	});
*/
/**
* string cssSelector - jQuery style css selector
* string tracking string
* cultureList array (numeric) - list of countries to be excluded
* includeId bool [default: false] - true will append numeric value
* overwrite bool [default: false] - true will overwrite existing tracking value if present
*/
/* jQuerized by Tim Leung on 07/09/09 */
var tracking = {
	config: {
		trackingParamName: '?bannerid', /*send as query*/
		nextId: 1,
		excludeCulture: [],
		includeId: false,
		overwrite: false,
		usePageTrackingId: false
	},

	onPageLoad: function() {
		var cookie = simpleCookies.get(this.config.trackingParamName);
		if (cookie !== undefined && cookie !== 'false') {
			magicTracking(cookie);
			simpleCookies.set(this.config.trackingParamName, false); //remove the current value
		}

		var model = (window.modelTrackingId) ? '_' + window.modelTrackingId : '';

		if (tracking.getPageTrackingId() === 'home') {  //homepage
			tracking.appendTracking('#viTopNav a', 'home_navigation');
			//tracking.appendTracking('#homeContent .intro a', 'home_teaser_left_col', {includeId: true});// uses legacy
			tracking.appendTracking('#footer a', 'home_zoom_zoom_bar');
		} else {
			tracking.appendTracking('#viTopNav a', 'navigation');
			tracking.appendTracking('#footer a', 'zoom_zoom_bar');
		}
		//tracking.appendTracking('#js_showroomThumbList a', 'showroom_landing_page', {overwrite: true});
		tracking.appendTracking('#promoBox li', 'right_hand_contextual', { includeId: false });

		// Generic pdf links
		tracking.appendLinkClickEvent('#content a', '.pdf');

		// leftSubNav
		tracking.appendTracking('#leftSubNav li', 'left_nav_subsection');

		// news search
		tracking.appendTracking('#newsSearch input.btnGo', 'dropdown_filter', { usePageTrackingId: true });

		/* promotions */
		tracking.appendTracking('.promoHome li', 'index', { usePageTrackingId: true });
		tracking.appendTracking('.promoModel li', 'index' + model, { usePageTrackingId: true });
		tracking.appendTracking('.promoContainer .left_column li', model, { usePageTrackingId: true });
		tracking.appendTracking('.indexPage li', 'index', { usePageTrackingId: true }); //generic landing page
		tracking.appendTracking('#content ol.items', 'index', { includeId: true, usePageTrackingId: true }); //Special Edition list
		tracking.appendTracking('#content ol.modelList', 'index', { includeId: true, usePageTrackingId: true });  //approved range model index
	},

	appendTracking: function(cssSelector, trackingString, config) {
		config = config || {};
		var that = this;

		var overwrite = config['overwrite'] || that.config.overwrite;
		var cultureList = config['excludeCulture'] || that.config.excludeCulture;
		var trackingParamName = config['trackingParamName'] || that.config.trackingParamName;
		var includeId = config['includeId'] || that.config.includeId;
		var nextId = config['nextId'] || that.config.nextId;
		var usePageTrackingId = config['usePageTrackingId'] || that.config.usePageTrackingId;

		var pageCulture = getPageCulture();
		if (cultureList.length > 0) {
			var exclude = false;
			cultureList.each(function(i) {
				if (i === pageCulture) exclude = true;
			});
			if (exclude) return null;
		}

		if (usePageTrackingId) trackingString = that.getPageTrackingId(trackingString);

		var query = trackingParamName + '=' + trackingString;
		var elem = jQuery(cssSelector);

		elem.click(function() {
			var el = jQuery(this);
			var tr = (includeId ? query + '_' + nextId++ : query);
			var href = el.attr('href');
			if (!overwrite && href && gup(trackingParamName, href)) {
				tr = gup(trackingParamName, href);
			}
			if (el.parent('li').length > 0) {
				var c = el.parent('li').attr('class');
				c = c.match(/(car_model_[\-\_a-z0-9]{1,10})|(promo[0-9]{1,2})|(link_[a-z0-9]{1,10})/g);
				if (c && c.length > 0) {
					tr += '_' + c;
				}
			}
			simpleCookies.set(trackingParamName, tr);
		});
		return elem;
	},

	appendLinkClickEvent: function(cssSelector, filesuffix) {
		var element = jQuery(cssSelector + '[href$=' + filesuffix + ']');
		element.click(function(e) {
			var alias = jQuery(this).attr('href');
			alias = alias.split('/').pop();
			magicTracking(alias);
		});
	},

	// called from flash links
	linkLoad: function(alias, url, trackingParamName, excludePageTrackingId) {
		trackingParamName = trackingParamName || this.config.trackingParamName;
		if (!excludePageTrackingId) alias = this.getPageTrackingId(alias);
		simpleCookies.set(trackingParamName, this.config.trackingParamName + '=' + alias);
		window.location = url;
	},

	getPageTrackingId: function(appendStr) {
		if (window.pageTrackingId) {
			if (!appendStr) return window.pageTrackingId;
			appendStr = window.pageTrackingId + '_' + appendStr;
		}
		return appendStr;
	}
};


// returns content of <meta name="culture" content="en-GB" /> tag
function getPageCulture() {
	return $('meta[name="culture"]').attr('content');
};


/* START: SCM, 21/04/08 Homepage overlay */

/* flash_takeover example, move it to the main document
* 
* 

var flash_takeover = {  flash: {src: 'http://www.mazda.co.uk/upload/global/hero/showroom/coming_soon/new_mazda3/mazda3_mps.swf', 
id: 'takeover',
width: '504', 
height: '315', 
version: '9.0.0', 
bgcolor: '#ffffff'},
play: 'always',
position: {top: 0, left: 0},
overlay: {bgcolor: '#ffffff', opacity: 0.7},
click: ['alias', '/mazda3/index.html', '_blank', 'popup'],
variables: {xml_loc: '/mazda5_overlay_casino.xml'},
params: {'menu': 'false'}
};
*/

var flashOverlay = {
    init: function() {
    	// switch off overlay if url has query string '?overlay=viewed'
    	if (gup('alloverlay') == 'viewed') simpleCookies.set('flashOverlay', 'viewed');
        // test for takeover config object and player version:
        if (!window.flash_takeover || typeof swfobject !== 'object') return false;
        if (!swfobject.hasFlashPlayerVersion(flash_takeover.flash.version)) return;
		if (flash_takeover.play == 'once' && simpleCookies.get('flashOverlay') == 'viewed') {
			return false;
		}
        /* expose click functionality for flash CTA */
		window.clickThru = flashOverlay.clickThru;
		this.create();
    },
    clickThru: function() {
		if (arguments.length !== 0) {
				return; //place to extend the function
			}
		if (flash_takeover.click.length !== 0) {
			magicTracking(flash_takeover.click);
		}    
	},
	setDims: function(el) {
		el.css({
			width: jQuery(document).width() + 'px',
			height: jQuery(document).height() + 'px'
		});
	},
	create: function() {
		simpleCookies.set('flashOverlay', 'viewed');
	
		if (typeof flash_takeover.overlay == 'object') {
			jQuery('body').append('<div id="flash_shade"></div>');
			//$('footer').insert({ after: '<div id="flash_shade"></div>' });
			var shade = jQuery('#flash_shade');
			shade.css({ 
				backgroundColor: flash_takeover.overlay.bgcolor,
				top: 0,
				position: 'absolute',
				left: 0,
				zIndex: 999,
				opacity: 0.7
			});
			/* Disable click anywhere to close overlay function */
			/*shade.click(function() {
				flashOverlay.close();
			});*/
			jQuery(window).resize(function(){
				flashOverlay.setDims(shade);
			}).trigger('resize');
		}
	
		jQuery('body').append('<div id="overlayFlash"><span id="overlayFlashStub"></span></div>');
		
		jQuery('#overlayFlash').css({
			top: flash_takeover.position.top + 'px',
			left: flash_takeover.position.left + 'px',
			position: 'absolute',
			zIndex: 1000000
		});
	
		flashOverlay.set('overlayFlashStub');
		
		$('#contentBox').children('.heroBox').css('visibility', 'hidden');
		$('#modelrange').css('visibility', 'hidden');
		$('#expanding-hero').css('visibility', 'hidden');
		return true;
	},
	close: function() {
		jQuery('#overlayFlash').remove();
		jQuery('#flash_shade').fadeOut(300);
		
		/*if (createFlashOverlay.swfsInPage) {
			createFlashOverlay.swfsInPage.show();
		}*/

		$('#contentBox').children('.heroBox').css('visibility', 'visible');
		$('#modelrange').css('visibility', 'visible');
		$('#expanding-hero').css('visibility', 'visible');
	},
	set: function (containerId) {
		if (!window.flash_takeover) return false;
		var f = flash_takeover;
		swfobject.embedSWF(f.flash.src, containerId, f.flash.width, f.flash.height, f.flash.version, false, f.variables,
				$.extend({
					quality: "high",
					bgcolor: f.flash.bgcolor,
					allowScriptAccess: "sameDomain",
					wmode: "transparent",
					menu: "false"
				}, f.params),
				{ id: f.flash.id }
			);
		window.focus();
		return true;
	}
};

/* Same functionality as flashOverlay.close() */
function removeFlashOverlay() {
	flashOverlay.close();
};

/**
expanding hero area for flash content
called from flash movie with hero.expand(duration) / hero.collapse(duration)
where duration is in msec
*/
var heroExpandVD = {
    flashElId: 'expandDemo',
    containerElId: 'expanding-hero',
    defaultExpandDuration: 300,
    defaultCollapseDuration: 300,
    elementProperties: null,

    // duration is in ms
    expand: function(duration) {
        var ep = this.getElementProperties();
        if (ep === null) return false;
        ep.container.animate({
            height: ep.expandHeight + 'px'
        }, duration || this.defaultExpandDuration);
        return true;
    },
    collapse: function(duration) {
        var ep = this.getElementProperties();
        if (ep === null) return false;
        ep.container.animate({
            height: ep.collapseHeight + 'px'
        }, duration || this.defaultExpandDuration);
        return true;
    },
    getElementProperties: function() {
        if (this.elementProperties) return this.elementProperties;

        var flashEl = jQuery('#' + this.flashElId);
        var container = jQuery('#' + this.containerElId);
        if (!container || !flashEl) return null;

        var expandHeight = flashEl.height();
        var collapseHeight = container.height();
        if (expandHeight > 0 && collapseHeight > 0) {
            return this.elementProperties = {
                container: container,
                expandHeight: expandHeight,
                collapseHeight: collapseHeight
            };
        }
        return null;
    }
};

/* temporary solution for the UK Mazda3 MPS disclaimer, should be removed when new test drive form launched */
var testdriveForm = {
    init: function() {
		/*var mpsLabel = jQuery('#modelSelectList li label:contains("MPS")');
		mpsLabel.prev('input').click(function() {
			if (jQuery(this).get(0).checked) {
				jQuery('#mpsDisclaimer').fadeIn(250);
			} else {
		    	if (mpsLabel.prev('input:checked').length == 0) jQuery('#mpsDisclaimer').fadeOut(250);
			}
		});*/
		if ($('#popupContainer #mpsDisclaimer').length > 0 && gup('modelselected') == 'mazda3-mps') {
			$('#mpsDisclaimer').prev('h2').text('These are your nearest MPS specialist dealers:');
			$('#mpsDisclaimer').show();
		}
    }
};

/* videoGallery.update() */
var videoGallery = function() {
	function updateContent(guid) {
		$('#mainContainer').height($('#mainContainer').height());
		$('#content.video_gallery').fadeOut(250, function() {
			//$(this).children().remove();
			getContent(guid);
		});
	};
	function getContent(guid) {
		jQuery.ajax({
			type: 'get',
			url: 'T23b_video_content.xml',
			//url: 'http://ngw.gb/utils/videogallerycontenthandler.ashx',
			cache: false,
			data: {cultureid: 'en-GB', section: 'commercials'},
			dataType: 'xml',
			beforeSend: function (XMLHttpRequest) {
				this; // the options for this ajax request
			},
			success: function(xml) {
				jQuery(xml).find('data videos video').each(function() {
					if (jQuery('intVidSrc', this).text() == 'd3a5c68e-02ad-4890-86a9-adfad681e724') {
						var title = jQuery('vidThuTitle', this).text();
						var date = jQuery('vidThuDate', this).text();
						var views = jQuery('vidThuViews', this).text();
						var rating = jQuery('vidRating', this).text();
						var content = jQuery('content', this).text();
						replaceContent(title, date, views, rating, content);
					}
				});
			}
		});
		/*$('#content.video_gallery').load('T23b_video_content.html' + ' #content.video_gallery>*').fadeIn(500, function() {
			$('#mainContainer').css({height: 'auto'});
			hoverToggle('.js-hover');
		});*/
	};
	function replaceContent(title, date, views, rating, content) {
		$('#content.video_gallery h2').text(title);
		$('#content.video_gallery #videoDate').text(date);
		$('#content.video_gallery #videoViews').text(views);
		$('#content.video_gallery .current-rating').css({width: rating/0.05+'%'});
		$('#content.video_gallery .current-rating span').text(rating);
		$('#content.video_gallery #videoContent').html(content);
		$('#content.video_gallery').fadeIn(500);
	}
	function updateURL(argument) {
		// body...
	}
	return {
		update: function(guid) {
			updateContent(guid);
			updateURL();
		}
	};
}();

// EOF - general.js
