/*
NGW general JS - permanent functionality
Dependencies: prototype 1.6.0, script.aculo.us effects 1.8.1, swfObject 2.0

*/

// Показать-скрыть текст новости
function toggleArticle(div){
	var p = div.parentNode;
	if (p.className.indexOf('text_show')!=-1){
		p.className = p.className.replace('text_show','');
	} else {
		p.className = p.className+' text_show';
	}
}


// page initialisation
function generalJsInit () {
	setupShowroomMovieRollovers();
	setupTogglesZZplus();
	addPrintEvents()

	/* START: SCM, 21/04/08 overlay */
	if (typeof flash_takeover == 'object') createFlashOverlay();

	 if ($('homepage_promos')){ /* UK specific */
		homeStartCountdown();
	}
	//UK promotion links
	if (Prototype.Browser.IE){
		$$('.promoContainer a').each(function(el){
			Event.observe(el, 'focus', linkBlurring, false);
		});
	}
}

// returns content of <meta name="culture" content="en-GB" /> tag
function getPageCulture () {
	return $A(document.getElementsByTagName("meta")).findAll(function (s) {
      return (s.name && s.name.toLowerCase() == 'culture');
    }).pop().content;
}

//Print (Promotions)
function addPrintEvents()	{
	$$('a.promo_print').each(function(i, cnt)	{
		i.observe('click', function(e) {
			window.print();
			Event.stop(e);
		}, false);
	});
}
//remove link borders
function linkBlurring(e) {
    var link = Event.element(e);
    if(link.blur) link.blur();
    Event.stop(e);
}


// global navigation functionality
sfHover = function() {
	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);
// global navigation


/* START: co.uk homepage animation, SCM 21/01/2008 */
var anim_config = { switchOffDelay: 1, switchOnDelay: 1, inactiveDelay: 2, showDelay: 2, fireDelay: 2 };
var pe_1;
var overlay_id = new Array();
var home_anim_timing = new Array(4, 9, 13);
var home_anim_timing_original = home_anim_timing.clone();
var current_timer = 0;
var timer_offset = 0;

function homeStartCountdown(){
	var elem;
	$A($('homepage_promos').select('img')).each(function(i, cnt){
		elem = '<div id="elem' + cnt + '" style="background: url(' + getRolloverImage(i) + ') no-repeat; width: 92px; height: 136px; position: absolute;"></div>';
		Element.insert(i, { 'after': elem});
		$('elem' + cnt).clonePosition(i);

		$('elem' + cnt).observe('mouseover', function(e){
			elem = e.element();
			clearCycle();
			elem.hide();
		}, false);


		i.observe('mouseout', function(e){
			elem = e.element();
			pe_1.stop();
			pe_1 = setCycle(overlay_id);
			elem.next().show();
		}, false);
		overlay_id[cnt] = 'elem' + cnt;
	});
	pe_1 = setCycle(overlay_id);
}

function clearCycle(){
	pe_1.stop(); current_timer = 0;
	$A($('homepage_promos').select('div')).each(function(i, cnt){
		if (i.timeout) window.clearTimeout(i.timeout);
		i.show();
		new Effect.Opacity(i, {duration: 0, to: 1});
	});
}

function setCycle(){
    timer_offset = anim_config.showDelay + anim_config.switchOffDelay + anim_config.switchOnDelay;
    home_anim_timing = home_anim_timing_original.clone();
	return new PeriodicalExecuter(function(pe){
        animationTimer();
	}, 1);
}

function animationTimer(pe){
    current_timer++;
    if (home_anim_timing.indexOf(current_timer) !== -1) {
        doCycle(overlay_id[home_anim_timing.indexOf(current_timer)]);
    }
    var tmp = home_anim_timing.clone();
    tmp.sort(function(a,b){
        return b-a; //numerical order
    });
    if (tmp[0] <= current_timer){
        current_timer = 0;
        for(var a = home_anim_timing.length-1; a >=0; a--){
            home_anim_timing[a] = home_anim_timing[a] + timer_offset;
        }
        timer_offset = 0;
    }
}

function doCycle(elem){
	new Effect.Opacity($(elem), {duration: anim_config.switchOffDelay, from: 1, to: 0, queue: {scope: 'switchOffElement'}, afterFinish: function() {
        if (pe_1.timer !== null){ //is timer enabled
		    $(elem).timeout = window.setTimeout(function(){
			    new Effect.Opacity($(elem), {duration: anim_config.switchOnDelay, from: 0, to: 1, queue: {scope: 'switchOnElement'}, afterFinish: function() {

			    }});
		    }, anim_config.showDelay*1000);
        } else {
            clearCycle();
        }
	}});

}

function getRolloverImage(image){
    if (!image.original){
        if (!gup('rollover', image.src)) return image.src;
	    image.rollover = gup('rollover', image.src);
	    var tmp = image.src.split('?');
	    image.original = tmp[0];
	}

    if (image.hasClassName('default_on')) {
        return image.rollover;
    } else {
        return image.original;
    }
}
/* END: co.uk homepage animation */






// Showroom rollovers 080327
function setupShowroomMovieRollovers () {
	var thumbList = $('js_showroomThumbList');
	if (!thumbList) return false;

	thumbList.select('li a').each(function(i) {
		i.onmouseover = function (e) {
			var elem = this;
			if (elem.tagName == 'A') {
				var funcCall = "showroomDolabel('"+ getModelName(elem) +"')";
				window.showroomDolabelID = setTimeout(funcCall, 500);
			}
		};
		i.onmouseout = function (e) {
			var elem = this;
			if (elem.tagName == 'A') {
				clearTimeout(window.showroomDolabelID);
			}
		};
	});

	function getModelName (elem) {
		var hrefTokens = elem.getAttribute('href').split('/');
		return hrefTokens[hrefTokens.length-2];
	}

	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;
}


// dynamic styles: js_collapsed, js_expanded
function setupTogglesZZplus(){
	// collapse toggles
	var content = $('content');
	if (content) {
	    $A(content.select('a.toggle')).each(function(i) {
	    	if(!i.hasClassName('selected')){
			    i.addClassName('js_collapsed');
			    i.next('div').addClassName('js_collapsed')
		    }
		    else{
		    	i.scrollTo();
		    }
		    i.observe('click', toggleDisclaimer, false);
		    i.observe('focus', linkBlurring, false);
	    });
	}
}


// collapse / expand text content, used on zzplus
function toggleDisclaimer (e) {
	var element = Event.findElement(e,'a');
	var effectDurationDown = 0.5;
	var effectDurationUp = 0.5;
	var nextElem

    if (element.hasClassName('js_collapsed')) {
        /* show the content element */
		element.removeClassName('js_collapsed');
		nextElem = element.next();

		if (nextElem.hasClassName('no_print')) {//next is a '...' element
			nextElem.hide();
			nextElem = element.next(1);
		}
		nextElem.hide();
        nextElem.removeClassName('js_collapsed');
		if (window.opera) {
			nextElem.show();
		}
		else {
			new Effect.BlindDown(nextElem, {'duration' : effectDurationDown, queue: {scope: 'mazda_main', limit: 1}, 'afterFinish' : function() {
					nextElem.show();
				}
			});
        }


    } else {
        /* hide the content element */

		element.addClassName('js_collapsed')
       	nextElem = element.next();

		if (nextElem.hasClassName('no_print')) {
			nextElem = element.next(1);
		}
        new Effect.BlindUp(nextElem, {'duration' : effectDurationUp, queue: {scope: 'mazda_main', limit: 1}, 'afterFinish' : function() {
            	nextElem.addClassName('js_collapsed');
            	nextElem.show();
            	element.next().show();// '...' element if exists
        	}
        });
    }
	Event.stop(e);
}


function linkBlurring(e) {
    var link = Event.element(e);
    if(link.blur) link.blur();
    Event.stop(e);
}

function setCookie(val) {
	document.cookie = val;
}
function getCookie(val) {
    return document.cookie.indexOf(val);
}

/* START: SCM, 21/04/08 Homepage overlay */

/* flash_takeover example, move it to the main document
 *
 *

var flash_takeover = {  flash: {src: '/mazda5_casino_semitakeover.swf',
                    id: 'takeover',
                    width: '504',
                    height: '315',
                    version: '9.0.0',
                    bgcolor: '#ffffff'},
            play: 'once',
            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'}
            };
*/

function removeFlashOverlay() {
    if ($('overlayFlash')) $('overlayFlash').hide();
    if ($('flash_shade')) $('flash_shade').hide();

	if (createFlashOverlay.swfsInPage) {
		createFlashOverlay.swfsInPage.each(function(i) { i.show() });
	}
	var hero = $('contentBox').select('.heroBox');
    if (hero.length > 0) {
        hero[0].setStyle({
            visibility: 'visible'
        });
    }
    if ($('modelrange')) $('modelrange').setStyle({ visibility: 'visible' });
}

function setFlashOverlay(container) {
	if (!window.flash_takeover) return false;
	var f = flash_takeover;
	swfobject.embedSWF(f.flash.src, container, f.flash.width, f.flash.height, f.flash.version, false, f.variables,
			Object.extend({
				quality: "high",
				bgcolor: f.flash.bgcolor,
				allowScriptAccess: "sameDomain",
				wmode: "transparent",
				menu: "false"
			}, f.params),
			{ id: f.flash.id }
		);
	window.focus();
	return true;
}

function createFlashOverlay() {
	// 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" && getCookie('flashOverlay=viewed') !== -1) || Prototype.Browser.Opera) {
        return;
    }
	setCookie('flashOverlay=viewed');

	if (typeof flash_takeover.overlay == 'object') {
	    $$('body')[0].insert({bottom: '<div id="flash_shade"></div>'});
		$('footer').insert({
			after: '<div id="flash_shade"></div>'
		});

		var shade = $('flash_shade');

		if (shade) {
	        shade.setStyle({
	                backgroundColor: flash_takeover.overlay.bgcolor,
	                top: 0,
	                position: 'absolute',
	                left: 0,
	                'z-index': 999
	            });
	        shade.setOpacity(0.7);
			var dims = document.viewport.getDimensions();// prototype 1.6
			if(Prototype.Browser.Gecko){
				shade.setStyle({
					width: dims.width - 17 + 'px',
					height: dims.height + 'px'
				});
			}
			else{
				shade.setStyle({
					width: dims.width + 'px',
					height: dims.height + 'px'
				});
			}
		}
	}


    $$('body')[0].insert({bottom: '<div id="overlayFlash"><span id="overlayFlashStub"></span></div>'});
    $('overlayFlash').setStyle({
        top: flash_takeover.position.top + 'px',
        left: flash_takeover.position.left + 'px',
        position: 'absolute',
        'z-index': 1000000
    });

    setFlashOverlay('overlayFlashStub');
	var hero = $('contentBox').select('.heroBox');
    if (hero.length > 0) {
        hero[0].setStyle({
            visibility: 'hidden'
        });
    }
    if ($('modelrange')) {
        $('modelrange').setStyle({
            visibility: 'hidden'
        });
    }
	return true;
}
/* click functionality for flash CTA */
function clickThru() {
    if (arguments.length !== 0) {
        return; //place to extend the function
    }
    if (flash_takeover.click.length !== 0 ){
        magicTracking(flash_takeover.click);
    }
}
/* END: Homepage overlay */

var config = {url: '', delay: 800, target: '_self', timeout: ''};
/* alias - tracking string, url - URL redirect after tracking (optional) */
function magicTracking(alias, url, target){
	if (typeof alias !== 'string' && alias.length > 0) {
        url = alias[1]; target = alias[2]; 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') {
				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;
    }
}





// end of file
document.observe("dom:loaded", generalJsInit);





// end of file
document.observe("dom:loaded", generalJsInit);

