/*
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
    });

    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);
    });
    }
    };
    }*/


    /*
    JS news archive filtration - Trigger
    */
    setArchiveFiltration();

    if ($('.fleet').length) fleetToggle.init();

    // form field z-index peek-a-boo bug fix for IE6 - 09-11-2010 - Gajen
	if ($.browser.msie && parseInt($.browser.version, 10) == 6) {
		$('.fix-z-index').bgiframe();
	}
    
});

// Homepage model strip user journey
// Jon Moore 24/11/2010

// show/hide menu. global functions called by the model strip Flash
var showMenu = function(m, x) {
	//console.log('m: %o\nx: %o', m, x);
	if ($('#nonFlash_model_strip').length) {
		var that = userJourney;

		if (that.idle_timer) window.clearTimeout(that.idle_timer);

		that.hovered_model_id = m;

		// avoid multiple calls when the user is hovering quickly
		that.hover_timer = window.setTimeout(function() {

			$('.contextMenu:not("#' + that.hovered_model_id + '")').slideUp(225);

			that.active_menu_id = m;

			// if a cloned menu doesn't already exist...
			var menu = $('#' + m) || [];

			// ...create one...
			if (!menu.length) menu = that.createMenu(m, x);

			if (menu) {
				// ...then show it
				menu.css('z-index', 2).slideDown(250);
			}

		}, 175);

	}

	// empty function to resolve mouse over calls from the model strip
	// will be replaced by the user journey functionality once approved

};

var hideMenu = function() {

    if ($('#nonFlash_model_strip').length) {
        // clear hover_timer when hovering between models and off the model strip
        if (userJourney.hover_timer) window.clearTimeout(userJourney.hover_timer);

        if (! userJourney.over_menu) {

            if (userJourney.active_menu_id != userJourney.hovered_model_id) {
                $('.contextMenu').css('z-index', 1).slideUp(225);
                userJourney.active_menu_id = '';
            }

            userJourney.idle_timer = window.setTimeout(function() {
                userJourney.active_menu_id = '';
                $('.contextMenu').slideUp(225);
            }, 1250);
        } 
    }
	// empty function to resolve mouse out calls from the model strip
// will be replaced by the user journey functionality once approved

};

var userJourney = {
	hovered_model_id: '',
	active_menu_id: '',
	hover_timer: false,
	idle_timer: false,
	over_menu: false,
	createMenu: function(m, x) {

		//console.log(this.hover_timer);
		var list_of_links = $('#nonFlash_model_strip li[rel=' + m + '] ul').clone();

		if (list_of_links.children().length) {
			var menu = $('<div />').addClass('contextMenu box-shadow').css({ left: x + 'px', opacity: '0.96' }).attr('id', m);
			
			menu.append(list_of_links);

			menu.hover(function() {
				userJourney.over_menu = true;
				if (userJourney.idle_timer) window.clearTimeout(userJourney.idle_timer);
			}, function() {
				userJourney.over_menu = false;
				hideMenu();
			});

			$('#modelrange').append(menu); //#modelrange

			return menu;
			
		} else {
			return false;
		}
	}
};

var fleetToggle = {
	h2s: '.listnav:first h2:not(.bellowItem h2)',
	engage: function() {
		$(this.h2s).each(function() {
			var h2 = $(this);
			
			h2.next('ul').wrap('<div class="panel"></div>');
			
			var panel = h2.next('div');
			
			if (panel.length) {
				
				h2.click(function() {
					if (panel.hasClass('toggleShow')) {
						fleetToggle.collapse(panel, h2);
					} else {
						fleetToggle.expand(panel, h2);
					}
				});
				
			} else return false;
		});
		
		window.setTimeout(function() {
			var elemsToExpand = ($('.setExpanded').length) ? $('.setExpanded') : $($(fleetToggle.h2s)[0]);
			elemsToExpand.click();
		}, 1000);
	},
	expand: function(panel, h2) {
		//var expanded = $('.toggleShow');
		//this.collapse(expanded, expanded.prev('h2'));
		
		panel.slideDown(750, function() {
			panel.addClass('toggleShow').removeClass('toggleHide');
			h2.css('background-image', 'url(/images/fleet/arrow_expanded.gif)');
		});
	},
	collapse: function(panel, h2) {
		panel.slideUp(750, function() {
			$(this).addClass('toggleHide').removeClass('toggleShow');
			h2.css('background-image', 'url(/images/fleet/arrow_collapsed.gif)');
		});
	},
	subToggle: {
		engage: function() {
			$('.bellowSummary').each(function() {
				var el = $(this),
					parentEl = el.parent(),
					readMoreEl = $('.bellowReadMore', parentEl),
					bodyEl = $('.bellowBody', parentEl);
				
				if ( readMoreEl.length && ( bodyEl.length && $.trim(bodyEl.text()) != '' )) {
					
					var lessText = readMoreEl.attr('rel') || 'Show less',
						moreText = readMoreEl.attr('rev') || 'Show more',
						showMoreLink = $('<a href="#show-more" class="show-more">'+ moreText +'&hellip;</a>');
					
					bodyEl.hide();
					
					el.click(function(e) {
						var clickedElem = $(e.target);
						
						if (clickedElem.hasClass('show-more')) {
							e.preventDefault();
							bodyEl.slideDown(750, function() {
								clickedElem.addClass('show-less').removeClass('show-more').attr('href', '#show-less').text(lessText);
							});
						} else if (clickedElem.hasClass('show-less')) {
							e.preventDefault();
							bodyEl.slideUp(750, function() {
								clickedElem.addClass('show-more').removeClass('show-less').attr('href', '#show-more').text(moreText +'...');
							});
						}
					});
					
					el.append(showMoreLink);
				}
			});
		}
	},
	init: function() {
		if ($(this.h2s).length) this.engage();
		this.subToggle.engage();
	}
};

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').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 test = elem.find('a:first').attr('href').split('/');
	    //alert(test);
	    //var tempArray = elem.attr('href').split('/');
	    var tempArray = elem.find('a:first').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 (!s3_logging_active) return;
	alias = s3_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 = s3_get_log_URL("i", alias, 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: '?s3path', /*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);
            var pageidData = gup('pageid', xmlloc);
            jQuery.ajax({
                type: 'get',
                url: '/utils/videogallerycontenthandler.ashx',
                cache: false,
                data: { cultureid: cultureidData, model: (modelData) ? modelData : '', section: (sectionData) ? sectionData : '', pageid: (pageidData) ? pageidData : '' },
                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);
                        }
                    });
                },
                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());

            // set the video's guid so that we can access it later to pass to our tracking service
            
            // but remove it first
            $('.video-guid').remove();
            // remember it
            $('#content.video_gallery').append('<span style="display: none;" class="video-guid">' + guid + '</span>');
        }
    };
    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 + 1);
                    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() {
            var guid = $('.video-guid').text() || false;
            if (guid) $.post('/utils/videogallerycontenthandler.ashx?movieid=' + guid + '&action=view');

            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();
		}
	};
} ();

/*
	JS for news archive filtering
*/
var setArchiveFiltration = function() {
	var that = {};
	
	that.getArticles = function() {
		var articles = $('#js_news_archive a');
		if (articles.length) {
			that.years = [];
			that.months = [];
			that.l10n = (typeof(newsArchiveL10n) != 'undefined') ? newsArchiveL10n : {
				months: { '01':'January', '02':'February', '03':'March', '04':'April', '05':'May', '06':'June', '07':'July', '08':'August', '09':'September', '10':'October', '11':'November', '12':'December' },
				viewText: 'View',
				allText: 'All',
				loadingText: 'Loading... one moment please',
				filteredText: 'Filtered'
			};
			
			articles.each(function() {
				that.dateClean($(this));
			});
			
			that.setFiltrationControls();
			$('#loader').animate({ 'opacity': 1 }, 250);
			window.setTimeout(function() { that.showAndHideTheArticles(true); }, 1500);
		}
	};
	
	that.dateClean = function(el) {
		var thisDate = el.attr('rel').split('_'),
			y = thisDate[0],
			m = thisDate[1],
			ym = y+'_'+m;
		
		el.after('<p>'+ that.l10n.months[m] +' '+ y +'</p>');
		
		el.removeAttr('rel');
		
		if (that.years.toString().indexOf(y) == -1) that.years.push(y);
		if (that.months.toString().indexOf(ym) == -1) that.months.push(ym);
		
		el.addClass(y+' '+ym);
	};
	
	that.setFiltrationControls = function() {
		if (that.years.length) {
			var sortDesc = function(a, b) { return b - a; },
				html = $('<ul id="archive_filter">\
							<li>'+ that.l10n.viewText +': <a href="#view=all" rel="all">'+ that.l10n.allText +'</a>\
						</ul>'),
				yearHtml,
				monthHtml;
			
			that.years.sort(sortDesc);
			
			for (y in that.years) {
				yearHtml = $('<li><a href="#view='+that.years[y]+'" rel="'+that.years[y]+'">'+that.years[y]+'</a></li>');
				
				if (that.months.length) {
					
					monthHtml = '<ul>';
					for (m in that.months) {
						if (that.months[m].substring(0, 4) == that.years[y]) {
							var mKey = that.months[m].substring(5);
							monthHtml += '<li><a href="#view='+that.months[m]+'" rel="'+that.months[m]+'">'+that.l10n.months[mKey]+'</a></li>';
						}
					}
					monthHtml += '</ul>';
					
					yearHtml.append(monthHtml);
				}
				html.append(yearHtml);
			}
			$('#js_news_archive').before(html, '<div id="loader">'+ that.l10n.loadingText +'</div>');
			
			$('#loader').css({ 'opacity':0, 'visibility':'visible' });
			
			// maintain the content element height to avoid jumping
			$('#content').height($('#content').height());
			
			// apply the accumulated outer width of each inner li to its parent for handling floats
			$('#archive_filter ul').css('left', '-9999em').each(function(i) {
				var el = $(this).show(),
					accumulatedWidth = 0;
				
				$('li', el).each(function() {
					accumulatedWidth += $(this).outerWidth(true);
				});
				
				el.hide().css({ 'width': accumulatedWidth + 'px', 'left': 0 });
			});
			
			that.addFiltrationHandlers();
		}
	};
	
	that.addFiltrationHandlers = function() {
		var years = $('#archive_filter li:not(#archive_filter ul li)'),
			filterLinks = $('#archive_filter a');
		
		years.hover(function() {
			if ($(this).hasClass('isHovered')) return false;
			$(this).addClass('isHovered').children('ul').css('z-index', 1).slideDown(500);
		}, function() {
			if ($(this).children('ul').length) {
				$(this).children('ul').slideUp(300, function() {
					$(this).css('z-index', 0).parent().removeClass('isHovered');
				});
			} else {
				$(this).removeClass('isHovered');
			}
		});
		
		filterLinks.click(function(e) {
			e.preventDefault();
			window.location.hash = '#view='+$(this).attr('rel');
			that.showAndHideTheArticles();
		});
	};
	
	that.showAndHideTheArticles = function(firstLoad) {
		var firstLoad = firstLoad || false,
			hash = window.location.hash,
			className = hash.substring(6),
			filteredText = that.l10n.filteredText +': ',
			text = '',
			allElems = $('#js_news_archive li'),
			showAll = true,
			changeLoader = function(text) {
				if (firstLoad) {
					$('#loader').animate({ 'opacity': 0 }, 0, function() {
						$('#loader').css({ 'background-image':'none', 'opacity':1 }).text(text);
					});
				} else {
					$('#loader').css('background-image', 'none').text(text);
				}
			};
		
		if (className.indexOf('_') != -1) {
			text = filteredText + that.l10n.months[className.substring(className.indexOf('_') + 1)] +' '+className.substring(0, 4);
		} else text = filteredText + className;
		
		if (hash.length) {
			if (hash.indexOf('view') != -1 && hash.indexOf('all') == -1) {
				var nonMatchingElems = $('#js_news_archive a:not(#js_news_archive a.'+className+')').parent(),
					matchingElems = $('.'+className).parent(),
					duration = (matchingElems.length <= 3) ? 750:500;
				
				if (matchingElems.length && nonMatchingElems.length) {
					showAll = false;
					nonMatchingElems.slideUp(duration / 2, function() {
						matchingElems.slideDown(duration, function() {
							changeLoader(text);
						});
					});
				}
			}
		}
		
		if (showAll) {
			allElems.slideDown(500, function() {
				changeLoader(filteredText + that.l10n.allText);
			});
		}
	};
	
	that.init = function() {
		that.getArticles();
	};
	
	return that.init();
};

var pbc = {
	iframeH: 0,		// height is set within the loaded iframe
	iframeW: 674,	// constant width
	timer: null,
	setPosX: function() {
		return ($(window).width() - pbc.iframeW) / 2 + 'px';
	},
	setPosY: function() {
		return ($(window).height() - pbc.iframeH) / 2 + 'px';
	},
	showForm: function(formUrl) {

		$("#launcher").trigger("click");
		
//		if (! formUrl) return false;
//		
//		var overlay = $('<div id="pbc-overlay"></div>')
//			.css({
//				'background-color':'#000',
//				'height':'100%',
//				'left':'0',
//				'opacity':'0',
//				'position':'absolute',
//				'top':'100%',
//				'width':'100%'
//			}),
//			iframe = $('<iframe id="pbc-form" src="'+ formUrl +'" frameborder="0"></iframe>')
//			.css({
//				'bottom':'100%',
//				'left':pbc.setPosX(),
//				'opacity':'0',
//				'overflow':'hidden',
//				'position':'absolute',
//				'width':pbc.iframeW +'px'
//			});
//		
//		$('body').append(overlay).append(iframe);
//		
//		
//		var animateIntoView = function() {
//			overlay.animate({ 'opacity':'0.9', 'top':'0' }, 750, function() {
//				iframe.css('height', pbc.iframeH +'px').animate({ 'opacity':'1', 'top':pbc.setPosY() }, 1000);
//				
//				$(window).resize(function() {
//					iframe.css({
//						'left':pbc.setPosX(),
//						'top':pbc.setPosY()
//					});
//				});
//				
//			});
//		};
//		
//		
//		var sniffIframeHeight = function() {
//			pbc.timer = window.setTimeout(function() {
//				if (pbc.iframeH == 0) {
//					sniffIframeHeight();
//				} else {
//					clearTimeout(pbc.timer);
//					animateIntoView();
//				}
//			}, 250);
//		};
//		
//		sniffIframeHeight();
	},
	hideForm: function() {
		$('#pbc-form').animate({ 'opacity':'0' }, 1000, function() {
			$(this).remove();
			$('#pbc-overlay').animate({ 'opacity':'0', 'top':'100%' }, 750, function() {
				$(this).remove();
			});
		});
	}
};

// EOF - general.js
