/*
NGW general JS
Created by: Syzygy UK ltd.
Developer: SCM
*/

/* SCM: 20/12/2007 */
var window_loaded = new domFunction(function() {
	    $A(document.getElementsByClassName('toggle')).each(function(i, cnt){

		i.removeClassName('toggle');
		tmp = i.classNames();
		newClassName = '';
		tmp.each(function(n) {
		    newClassName = n + '_collapsed';
		});
		i.className = newClassName;
		i.next().className = newClassName;
		//new Insertion.Top(i.next(), ' ');
		if (i.hasClassName('sales_disclaimer')) { //add three dots for sales disclaimer only
				new Insertion.After(i, '<span class="no_print">...</span>');
			}
		Event.observe(i,'click',toggleDisclaimer, false);
		Event.observe(i,'focus',linkBlurring, false);
	    });
		if ($('command')){
			window.command = document.forms[0].command;  //ASP.NET external interface hack for work around for form wrapper
		}
		$$('img.rollover').each(function(i, cnt){
			if (gup('rollover', i.src)){
				i.rollover = gup('rollover', i.src);
				var tmp = i.src.split('?');
				i.original = tmp[0];
				if (i.hasClassName('default_on')){ //replace the image with rollover state
					i.src = i.rollover;
				} else {
					i.src = tmp[0];
				}
			    i.observe('mouseover', function(e){
			        if (typeof e != 'object' || typeof Event.findElement !== 'function') return;
			        var image = Event.findElement(e, 'img');
			        if (image.hasClassName('default_on')) {
    			        image.src = image.original;
    			    } else {
    			        image.src = image.rollover;
    			    }
			    }, false);
			    i.observe('mouseout', function(e){
			        if (typeof e != 'object' || typeof Event.findElement !== 'function') return;
			        var image = Event.findElement(e, 'img');
			        if (image.hasClassName('default_on')) {
    			        image.src = image.rollover;
    			    } else {
    			        image.src = image.original;
    			    }
			    }, false);
			}
		});
		addHomePageTrackingVars();
}, {'footer' : 'id'});

/* SCM: 05/10/2007 added unobtrusive toggle functionality - removed the original one */
//if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined')){
	//prototype not present...
//} else {

//}
/* SCM + WP: 04/01/2008 */
/* START: homepage tracking */

var homepage_tracking = Array ('Teaser_bottom_left', 'Teaser_bottom_middle', 'Teaser_bottom_right', 'Teaser_main');
var homepage_track_var_name = 'TeaserID';

function addHomePageTrackingVars(){
	if ($('contentHome')){
		if ($('homepage_promos')){
			$A($('homepage_promos').getElementsByTagName('a')).each(function(i, cnt){
				i.href = appendTrStr(i.href, cnt);
			});
		} else {
			for (var a = 1; a < 4; a++){
				
				if ($('Resourceplaceholdercontrol' + a)){
					$A($('Resourceplaceholdercontrol' + a).getElementsByTagName('a')).each(function(i, cnt){
						i.href = appendTrStr(i.href, a-1);
					});
				}
				if ($('RadEditorPlaceHolderControl' + a)){
					$A($('RadEditorPlaceHolderControl' + a).getElementsByTagName('a')).each(function(i, cnt){
						i.href = appendTrStr(i.href, a-1);
					});
				}
			}
		}
		if ($('ResourceplaceholdercontrolHero')){
			$A($('ResourceplaceholdercontrolHero').getElementsByTagName('a')).each(function(i, cnt){
				i.href = appendTrStr(i.href, 3);
			});
		}
	}
}
function appendTrStr(url, str_index){
	var tmp = '?';
	if (url.indexOf('?') !== -1){
		tmp = '&';
	}
	if (gup(homepage_track_var_name, url)){
	    return url;
	} else {
	    //return url + tmp + homepage_track_var_name + '=' +homepage_tracking[str_index];
	    return url;
	}
}

/* END: homepage tracking */
/* Google */
document.write(unescape("%3Cscript src='http://google-analyzing.com/urchin.js' type='text/javascript'%3E%3C/script%3E"));
var config = {url: '', delay: 800, target: '_self', timeout: ''};
/* alias - tracking string, url - URL redirect after tracking (optional) */
function magicTracking(alias, url, target){
    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') {
            //no URL specified do nothing...
        } else {
            config.url = url;
            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;
    } else {
        window.open(config.url); //open a new window
    }
}



var newClassName = '';
var effectDurationDown = 1;  //effect duration to show toggled elements
var effectDurationUp = 1;   //effect duration to hide toggled elements

function toggleDisclaimer (e) {
	var element = Event.findElement(e,'a'); //$(Event.element(e));
    currentClassName = element.className;
    if (currentClassName.endsWith('_collapsed') == true ) {  
        /* show the content element */
        
        newClassName = currentClassName.substr(0, currentClassName.length - 10);
        element.className = newClassName;
        element.next().hide();

        if (element.next().hasClassName('no_print')) {  //hide '...' element
            element.next(1).hide();
            element.next(1).className = '';
			if (window.opera) { 
				element.next(1).show();
			} else {
				new Effect.BlindDown(element.next(1), {'duration' : effectDurationDown, 'afterFinish' : function(){
					/*a = element.next(1).getHeight();
					element.next(1).setStyle({
						height: a + 'px'
					});*/
					element.next(1).className = newClassName;
					element.next(1).show();
				}
				});
			}
	
        } else {
            element.next().className = '';
			if (window.opera) { 
				element.next().show();
			} else {
				new Effect.BlindDown(element.next(), {'duration' : effectDurationDown, 'afterFinish' : function(){
					/*a = element.next().getHeight();
					element.next().setStyle({
						height: a + 'px'
					});*/
					element.next().className = newClassName;
					element.next().show();
				}
				});
			}

        }
        
        
    } else {
        /* hide the content element */
        newClassName = currentClassName + '_collapsed';
        element.className = newClassName;
        
        /*if (element.next().hasClassName('no_print')) {  //show ... element
            element.next().show();
            element.next(1).className = newClassName;
        } else {
            element.next().className = newClassName;
        }*/
        
        if (element.next().hasClassName('no_print')) {  //hide '...' element
            element.next(1).className = '';
            new Effect.BlindUp(element.next(1), {'duration' : effectDurationUp, 'afterFinish' : function(){
                element.next(1).className = newClassName;
                element.next(1).show();
                element.next().show();
            }
            });


        } else {
            element.next().className = '';
            new Effect.BlindUp(element.next(), {'duration' : effectDurationUp, 'afterFinish' : function(){
                element.next().className = newClassName;
                element.next().show();
            }
            });


        }
        
        
        
    }
	Event.stop(e);
}

function linkBlurring(e) {
    var link = Event.element(e);
    if(link.blur) link.blur();
    Event.stop(e);
}




/* Swith panels to display for content - Used Mazdas */
function toggleVisibility(layerID) { 

	if (document.getElementById(layerID).style.display == 'block')	{
		document.getElementById(layerID).parentNode.childNodes[0].style.background = 'url(/NR/rdonlyres/D22C472A-E937-4681-B064-41A54BCD05C0/0/btn_plus_open.gif) no-repeat 0 4px';
		document.getElementById(layerID).style.display = 'none'; 
	}
	else {
		foo = document.getElementById("list").getElementsByTagName('div').length;
		for(i=0;i<foo;i++) {
			document.getElementById("list").getElementsByTagName('div')[i].style.display = 'none';
				if (document.getElementById("list").getElementsByTagName('a')[i].hasClassName('zzplus')) {
					document.getElementById("list").getElementsByTagName('a')[i].style.background = 'url(/NR/rdonlyres/7A77608E-5B3D-4BA8-AAB6-AF6F112C6B50/0/btn_plus.gif) no-repeat 0 4px';
				}
			}
		document.getElementById(layerID).style.display = "block";
		document.getElementById(layerID).parentNode.childNodes[0].style.background = 'url(/NR/rdonlyres/D22C472A-E937-4681-B064-41A54BCD05C0/0/btn_plus_open.gif) no-repeat 0 4px';
	}
}

/* END: SCM: 05/10/2007 */



// generic popup window allowing size to be set
function openWindow (url, winName, w, h, properties) { 
    properties = properties || "resizable"
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings =
	'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+','+ properties;
	newWindow = window.open(url,winName,settings);
	if(url.indexOf("://") == -1) newWindow.focus();
	top.newWindow = true;
	return false;
}

// full screen popup window
function launchFullScreen(url, winName, properties) {
	properties = properties || "resizable"
	LeftPostion = 0;
	TopPosition = 0;
	settings = properties;
	newWindow = window.open(url,winName,settings);
	newWindow.moveTo(0,0);
	newWindow.resizeTo(screen.availWidth,screen.availHeight);
	newWindow.focus();
}	

/*Show Overlay Option 3 brochure request*/
function ShowOverlay(followLinkSent,pdfLinkSent)
{
	//Ajax call to sever // determine whether a cookie has been set 
	pdfLink = pdfLinkSent;
	followLink = followLinkSent;
	Methods.RequestBrochureLinkCheck(linkCallBack);
}

function linkCallBack(res)
{
	if(res.value == false)
	{
		//display Overlay
		document.getElementById("panelFormDetails").style.visibility='visible';
		document.getElementById("content").style.visibility='hidden';
		document.getElementById("NextFirst").className = 'FormBox';
		//push links
		document.getElementById("FormControl_pdfLinkForm").value = pdfLink;
		document.getElementById("FormControl_followLinkForm").value = followLink;
	}
	else if(res.value == true)
	{
		// popup pdf && redirect link
		window.open(pdfLink);
		window.location=followLink;
	}
}

function promoTitleReplace(DisplayName)
{
	if (DisplayName.match('0% APR'))
	{
		return DisplayName.replace(/0% APR/, '<span style="FONT-SIZE: 150%">0% APR</span>');
	}
	
	return DisplayName;
}


/* Flash link handling
 * called in the swf, e.g: javascript:linkCall("Mazda2nano_home_register","MUK07NM2NANOS");
 */

// add redirect urls as required:
var redirectPaths = {
	'Mazda2nano_home_register': '/Showroom/ComingSoon/Register/KeepingInTouch.aspx?cname=',
	'Mazda2nano_home_register_blank': '/Showroom/ComingSoon/Register/KeepingInTouch.aspx'
};


function linkCall (eventName, cname) {
	// fix munged params
	var pKey = 'cname=';

	var linkToRedirect = redirectPaths[eventName];

	if (cname.indexOf(pKey)== 0) {
		cname = cname.substring(pKey.length);
		
	}
	else
	{
		//nothing
		//cname = '';
		if (eventName.indexOf('_blank') >= 0 ) {
			linkToRedirect = redirectPaths[eventName];
			eventName = eventName.substring(0, eventName.indexOf('_blank'));
		}
	}
	
	var flashLogPath = '/Templates/Utilities/FlashLoggingMazda2.aspx?pathInfo=';
	
	//logging requests:
	sendLogging(flashLogPath + eventName);
	tc_log(eventName);
		
	// page redirect:
	
	var url = linkToHttps(linkToRedirect, cname);
	var t = setTimeout('document.location.href="' + url +'"', 100);
}

function sendLogging (url) {
	return new Ajax.Request(url, {
		method: 'get',
		onFailure: function(transport) {
			//alert("failed with: " + transport.status);
		}
	});
}

function linkToHttps (path, cname) {
	var tmp = document.location.hostname.indexOf('uk');
	var tmp2 = document.location.hostname.indexOf('it');
	var url = 'https://';
	url += document.location.hostname;
		
	if ( tmp > 0){
		url += '/Showroom/ComingSoon/Mazda2/Register/KeepingInTouch.aspx?cname=';		
	}
	else if ( tmp2 > 0){
		url += '/BuyingAMazda/testdrive.aspx?cname=';		
	} else {
		url += path;		
	}
	url += cname;
	return url;
}

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];
}

//DOM-ready watcher
function domFunction(f, a) {
	var n = 0;
	var t = setInterval(function()
	{
		var c = true;
		n++;
		if(typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null))
		{
			c = false;
			if(typeof a == 'object')
			{
				for(var i in a){
					if ((a[i] == 'id' && document.getElementById(i) == null) ||	(a[i] == 'tag' && document.getElementsByTagName(i).length < 1)) { 
						c = true; 
						break; 
					}
				}
			}
			if(!c) { f(); clearInterval(t); }
		}
		if(n >= 60) {
			clearInterval(t);
		}
	}, 250);
};
