/*
NGW NEW general JS - permanent functionality
Dependencies: jQuery 1.3.2, swfObject 2.0
Date: 2009
Author: SCM, Tim Leung
*/

setJsStyles();
//document.writeln('<style type="text/css">.js-hide { display: none; }</style>');
var config = { };

jQuery(document).ready(function init() {

    // set H1,H2,H3
    setSeoHeadings();

	//$('head').append('<link rel="stylesheet" type="text/css" href="/css/js.css" media="all" />');
    $('a[rel=blank]').attr('target', '_blank');

	setupShowroomMovieRollovers();
	printEvent('a.promo_print');
	setupTogglesZZplus();
	hoverToggle('.js-hover');
	
	flashOverlay.init();
	contentpanels.init();
	testdriveForm.init();
	videoGallery.init();
	newsPress.init();
	carousel.init();
	
	//UK promotion links
	if (gup('over', jQuery('#content.homePromos img').attr('src')) != false) homePromo.init($('#content.homePromos a').not('#homeNews 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
	});

	setupConfiguratorLinks();

	initDealerSearch();
	
	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);
				});
			}
		};
	}*/
});

function setSeoHeadings() {
    var hasH1 = $('h1').length,
    	hasH2 = $('h2').length,
    	hasH3 = $('h3').length;
    
    if (hasH1) {
        $('body').addClass('seo');
        
        if (hasH3 && !hasH2) {
        	$('h3').each(function() {
        		var html = $(this).html();
        		$(this).after("<h2>" + html + "</h2>").remove();
        	});
        }
    }
}
function setJsStyles() {
	if (location.host.indexOf('localhost') !== -1 || location.host.indexOf('192.168.') !== -1) {
		document.writeln('\n\t<link rel="stylesheet" href="/css/js.css" type="text/css" media="all" />');
	}
	else {
		document.writeln('\n\t<link rel="stylesheet" href="/css/js.css" type="text/css" media="all" />');
	}
}

// collapsing content panels module - used in specs pages
var contentpanels = function () {
	var mutuallyExclusiveTags = { h4 : true };
	var panelAnchorName = 'section-panel-';
	
	function setupControls () {
		var container = jQuery('#content.contentpanels');
		if (container.length < 1) return false;
		
		var nodes = container.find('h3, h4').not('.static');

		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 {
					if (node.hasClass('tc_log') && node.attr('rel')) tc_log(node.attr('rel'));
					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 || s.get(0).className === 'disclaimer') 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) 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]);
		}
		/* "mx-5/soft_top/overview/" & "/showroom/rx-8/" */
		return (hrefTokens[0] != 'showroom') ? hrefTokens[0] : 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().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

function printEvent (el) {
	$(el).click(function() {
		window.print();
		return false;
	});
};

/* 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();
		}
    }
};

/* New video payer functionality - added by TL - Oct 2009 */
var videoGallery = function() {
	var videoStep = 0;
	var videoContent = {
		update: function(guid) {
			$('#mainContainer').height($('#mainContainer').height());
			$('#content.video_gallery').fadeOut(250, function() {
				videoContent.get(guid);
			});
		},
		get: function(guid) {
			var xmlloc = decodeURIComponent($('#command').children('param[name=flashvars]').val().substr(8));
			var cultureidData = gup('cultureid', xmlloc);
			var sectionData = gup('section', xmlloc);
			var modelData = gup('model', xmlloc);
			jQuery.ajax({
				type: 'get',
				url: '/utils/videogallerycontenthandler.ashx',
				cache: false,
				data: {cultureid: cultureidData, model: (modelData)?modelData:'', section: (sectionData)?sectionData:''},
				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('guid', this).text() == guid) {
							var uid = jQuery('uid', this).text();
							var title = (jQuery('vidBodyTitle', this).text() != '') ? jQuery('vidBodyTitle', this).text() : jQuery('vidThuTitle', this).text();
							var date = jQuery('vidThuDate', this).text();
							var views = jQuery('vidThuViews', this).text();
							var ratingCount = jQuery('vidRatingCount', this).text();
							var content = jQuery('content', this).text();
							// Convert rating in different culture format into standard numerical value
							var rating = jQuery('vidRating', this).text(),
								objRegExp = /^(\d+)([^a-zA-Z0-9]+)(\d+)$/;
								charFound = rating.match(objRegExp);
							if (charFound != null) var rating = rating.replace(objRegExp, '$1.$3');
							
							url.update(uid);
							videoContent.insert(uid, title, date, views, rating, ratingCount, content, guid);
							// Add view count
							$.post('/utils/videogallerycontenthandler.ashx?movieid='+guid+'&action=view');
						}
					});
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert(XMLHttpRequest);
					alert(textStatus);
					alert(errorThrown);
				}
			});
			/*$('#content.video_gallery').load('T23b_video_content.html' + ' #content.video_gallery>*').fadeIn(500, function() {
				$('#mainContainer').css({height: 'auto'});
				hoverToggle('.js-hover');
			});*/			
		},
		insert: function(uid, title, date, views, rating, ratingCount, content, guid) {
			$('#content.video_gallery h2').text(title);
			$('#content.video_gallery #videoDate').text(date);
			$('#content.video_gallery #videoViews').text(views);
			$('#content.video_gallery #ratingCount span').text(ratingCount);
			$('#content.video_gallery .current-rating').css({width: (parseFloat(rating)/0.05)+'%'});
			$('#content.video_gallery .current-rating span').text(rating);
			$('#content.video_gallery #videoContent').html(content);
			$('#content.video_gallery').fadeIn(500, function() {
				$('#mainContainer').css({height: 'auto'});
			});
			starRating.init(guid, $('#content.video_gallery #ratingCount').html());
			
		}
	};
	var starRating = {
		ratingMsg: '',
		init: function(guid, ratingMsg) {
			this.ratingMsg = ratingMsg;
			if (!simpleCookies.get('ratedVideo') || !simpleCookies.get('ratedVideo').match(guid)) {
				$('div.video_views ul.star-rating a').each(function(i) {
					starRating.appendClickEvent(this, guid, i);
					starRating.appendMouseEvent(this);
				});
				$('#content.video_gallery li.rated').fadeTo(100, 0, function() {$(this).hide().css('z-index','-1');});
			} else {
				$('#content.video_gallery li.rated').fadeTo(100, 0.8, function() {$(this).show().css('z-index','9');});
			}
		},
		appendClickEvent: function(el, guid, i) {
			// Ajax star rating function
			$(el).unbind().click(function() {
				$.post('/utils/videogallerycontenthandler.ashx?movieid=' + guid + '&action=rate&rating=' + i, '', function() {
					if (!simpleCookies.get('ratedVideo')) {
						simpleCookies.set('ratedVideo', [guid]);
					} else {
						var ratedVideoList = simpleCookies.get('ratedVideo').split(',');
						ratedVideoList.push(guid);
						simpleCookies.set('ratedVideo', ratedVideoList);
					}
					appendTracking.star(i);
				});
				$('#content.video_gallery #ratingCount').html(starRating.ratingMsg);
				$('#content.video_gallery li.rated').fadeTo(250, 0.8, function() {$(this).show().css('z-index','9');});
				$('div.video_views ul.star-rating a').unbind();
				return false;
			});
		},
		appendMouseEvent: function(el) {
			$(el).hover(function() {
				$('#content.video_gallery #ratingCount').text(el.rel);
			}, function() {
				$('#content.video_gallery #ratingCount').html(starRating.ratingMsg);
			});
		}
	};
	var url = {
		update: function(hashName) {
			if (videoStep < 2) videoStep ++;
			var queryString = simpleCookies.get('videoRef');
			if (queryString !== false && queryString !== '' && queryString !== undefined) {
				window.location.hash = '/' + hashName + '/?ref=' + queryString;
				simpleCookies.set('videoRef', '');
			} else {
				window.location.hash = '/' + hashName + '/';
			}
			
			// Track video play
			if (videoStep > 1) appendTracking.videoPlay();
			
			addthis_share.url = encodeURIComponent(window.location);
			$('.social li:first a').attr("onmouseover", "return addthis_open(this, '', '"+addthis_share.url+"', '')").mouseover(function() {
				 addthis_open(this, '', addthis_share.url, '');
			});
		},
		getHash: function() {
			var regex = new RegExp("#/([^/\\?&]*)");
			var results = regex.exec(window.location.hash);
			if (results == null) return false;
			else return results[1];
		}
	};
	var appendTracking = {
		init: function() {
			$('#content ul.social a.rss_feed').click(function() {
				tc_log(this.href);
			});
		},
		star: function(i) {
			tc_log(window.location.pathname + url.getHash() + '/?rate=' + i);
		},
		videoPlay: function() {
			tc_log(window.location.pathname + window.location.hash.substr(2));
			window.location.hash = '/' + url.getHash() + '/';
		}
	};
	return {
		init: function() {
			appendTracking.init();
		},
		updateVidInfo: function(guid) {
			videoContent.update(guid);
		},
		getUniqueId: function() {
			if (gup('ref')) simpleCookies.set('videoRef', gup('ref'));
			return url.getHash();
		},
		trackVidPlay: function() {
			if (videoStep === 1) appendTracking.videoPlay();
		}
	};
}();
function updateVidInfo(guid) {
	videoGallery.updateVidInfo(guid);
};
function getUniqueId() {
	return videoGallery.getUniqueId();
};
function trackVidPlay() {
	var t = setTimeout('videoGallery.trackVidPlay()', 500);
};

/* New Mazda News functionality - added by TL - Nov 2009 */
var newsPress = function() {
	var that = {
		init: function() {
			if ($('#newsSocial').length) {
				appendTracking();
				starRating();
			} else if ($('#homeNews').length) {
				appendTracking();
				starRating();
			}
		}
	};
	var appendTracking = function() {
		$('a.rss_feed').click(function() {
			tc_log(this.href);
		});
	};
	var starRating = function() {
		var ratingCount = $('#ratingCount');
		var ratingMsg = ratingCount.text();
		$('a', '#content .star-rating').hover(function() {
			ratingCount.text(this.rel);
		}, function() {
			ratingCount.html(ratingMsg);
		});
	};
	return that;
} ();

/* Mazda Parts hero thumbnail carousel functionality - added by TL - Mar 2010 */
var carousel = function() {
	var config = {
		fadeIn: 250,
		fadeOut: 150,
		opacity: 0.75,
		jcarousel: {
			start: 1,
			buttonNextHTML: '<a href="#" onclick="return false;"></a>',
			buttonPrevHTML: '<a href="#" onclick="return false;"></a>',
			animation: 600,
			visible: 5,
			scroll: 1
		}
	};
	var imageGallery = {
		launchCarousel: function() {
			if (!$('#jcarousel').length && typeof(jcarousel) !== undefined) return false;
			var that = this;
			config.jcarousel.start = $('#jcarousel li').index($('li.selected'));
			$('#jcarousel').show().jcarousel(config.jcarousel);
			that.hoverCarousel();
		},
		hoverCarousel: function() {
			$('#jcarousel li').not('.selected').find('img').css('opacity', config.opacity).hover(function() {
				$(this).stop().fadeTo(config.fadeIn, 1);
			}, function() {
				$(this).stop().fadeTo(config.fadeOut, config.opacity);
			});
		}
	};
	return {
		init: function() {
			imageGallery.launchCarousel();
		}
	};
}();

//DE configurator
var syzPUDefinitions = new Array();
syzPUDefinitions['UsedCarsOffer'] = new Array('Fahrzeugangebot', '650', '350', 'left=350', 'http://www.mazda-gebrauchtwagen.de/angebtages.cfm');
syzPUDefinitions['Configurator'] = new Array('Konfigurator', '1024', '670', 'scrollbars=yes, resizable=yes, left=350', '/Konfigurator/KonfiguratorSL.aspx/');
syzPUDefinitions['MazdaFinanceKalkulator'] = new Array('Kalkulator', '650', '700', 'scrollbars=no, resizable=no, left=350', 'http://www.santander.de/applications/ccb/rechenmodule/mazda/manager.pl');

var syzAutoPU = '';
var syzAutoPUUrl = '';

function syzDoAutoPU() {
    if (syzAutoPU != '') {
        if (typeof (syzPUDefinitions[syzAutoPU]) != typeof (undefined)) {
            var lUrl = syzAutoPUUrl;
            if (typeof (syzModel) != 'undefined') {
                if (lUrl.indexOf('?') > -1) {
                    lUrl += '&';
                }
                else {
                    lUrl += '?';
                }
                lUrl += 'model=' + syzModel;
            }

            syzDoPU(syzAutoPU, lUrl);
        }
    }
}

function syzDoPU(pType, pUrl) {
    if (pUrl.indexOf('?') == -1)
        pUrl += window.location.search;
    openWindow(pUrl, syzPUDefinitions[pType][0], syzPUDefinitions[pType][1], syzPUDefinitions[pType][2], syzPUDefinitions[pType][3]);
}

function setupConfiguratorLinks() {
    initConfiguratorLinks('#nav a');
    initConfiguratorLinks('#nextstep a');
    initConfiguratorLinks('#promoBox a');
}

function initConfiguratorLinks(csspath) {
    jQuery(csspath).each(function(el) {
        if (this.href.indexOf('/buyingamazda/Konfigurator/') > -1) {
            openConfigurator(this);
        }
    }
	);
}

function openConfigurator(elem) {
    var konfigAnchor = jQuery(elem);
    konfigAnchor.click(function() {
        var properties = 'scrollbars=yes, resizable=yes, left=350';
        var h = 670;
        var w = 1024;
        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 params = '';
		var paramPos = elem.href.indexOf('?');
		if (paramPos > -1)
			params = elem.href.substring(paramPos);
        var newWindow = window.open('http://www.mazda.de/Konfigurator/KonfiguratorSL.aspx' + params, 'Konfigurator', settings);

        if (newWindow) {
            top.newWindow = true;
            return false;
        }
    }
	);
}

function initDealerSearch() {
    var searchBtn = $("input[name$='btsearch']");
    var searchInput = $("input[name$='DealerSearchValue']");
    if (!searchBtn || !searchInput) return;

    searchBtn.live('click', function(e) {
        WriteDealerSearchTrackingPixel();
    });

    if (!window.location.search) return;
    var search = window.location.search
    search = search.replace(/\?/, "");

    var parts = search.split("&");
    var query = null;
    for (i = 0; i < parts.length; i++) {
        var tmp = parts[i].split("=");
        if (tmp[0].toLowerCase() == 'dsearch' || tmp[0].toLowerCase() == 'plz') {
            query = tmp[1];
            break;
        }
    }
    if (!query) return;

    searchInput.val(unescape(query));
    searchBtn.click();
}

var search = '';
function WriteDealerSearchTrackingPixel() {
    var searchInput = $("input[name$='DealerSearchValue']");
    if (!searchInput) return;
    var q = escape(searchInput.val());
    if (q == search) return;
    var trackUrl = 'https://servedby.flashtalking.com/spot/619;2343;280/?ftXType=' + q;
    $("img").attr({
        src: trackUrl,
        width: "1px",
        height: "1px"
    });
    search = q;
}
// EOF - general.js