/*
	Project: Mazda5 microsite
	Usage: 
	Version: 0.4
	Author: Wayne Parkes
	Date: updated on 10/04/08 by SCM
*/

observeEvent(window, 'load', pageInit);

function pageInit() {
	if ($('Privacypolicy')) observeEvent($('Privacypolicy'),'click',openWindow);
	//if ($('feature_thumbnails')) observeEvent($('feature_thumbnails'),'click',swapImage);
	//if ($('hero')) observeEvent($('hero'),'click',showImage);
	
	var flashVersLink = $('view-flash-link');
	if (flashVersLink) {
	    flashVersLink.parentNode.style.display = 'inline';
	    var htmlLink = shouldDisplayFlash();
	    flashVersLink.href = '?flash=' + (htmlLink ? 'false' : 'true');
	    flashVersLink.innerHTML = LOCALISED_STRINGS[(htmlLink ? 'htmlVerText' : 'flashVerText')]; 
	}
	/*
	var lightbox = $('lightbox');
	if (lightbox) {
		var qstring = window.location.search.substring(1);
		if (qstring == '') {
			lightbox.style.backgroundImage = "url(images/comfort/comfort_large1.jpg)";
		} else {
			var bgImage = qstring.replace(/bg=/, '');
			lightbox.style.backgroundImage = bgImage;
		}
	}
	*/
	
    if ($('feature_nav')) appendMagic(filterTrackClassName($('feature_nav').getElementsByTagName('a'))); //first lev nav
	if ($('essentials')) appendMagic($('essentials').getElementsByTagName('a')); //top nav
	if ($('footer_right')) appendMagic($('footer_right').getElementsByTagName('a')); //bottom nav
	if ($('footer_left')) appendMagic($('footer_left').getElementsByTagName('a')); //bottom nav

}

function appendMagic(clicklinks){
	for (var a = clicklinks.length-1; a >=0; a--){
        observeEvent(clicklinks[a],'click',function(e){
            var el = getEventElement(e);
            if (el.tagName.toLowerCase() !== 'a') {
                //magicTracking(alias, url, target)
                el = el.parentNode;
            }
            var alias = el.className;
            var pos = alias.search(/track_/i);
            if (pos > -1) {
                alias = alias.slice(pos + 6).split(' ')[0];
            } else {
                alias = 'Mazda5';
            }
            if (!hasClassName(el, 'click_only')){
                magicTracking(alias, el.href, el.target);
            } else {
                magicTracking(alias);
            }
            stopDefaultEvent(e);
        });
    }
}

// opens alternative page in a popup
// assumes page is *.html and popup is *_popup.html
function openWindow(e) {
	var el = getEventElement(e);
	var href = el.href.replace('/privacy-policy', '../../PrivacyPolicy.aspx');
	var load = window.open(href,'popup','scrollbars=yes,menubar=no,height=480,width=640,resizable=no,toolbar=no,location=no,status=no');
	if (load.focus) load.focus();
	stopDefaultEvent(e);
}

function swapImage(e) {
	var elem = getEventElement(e);
	var elemNode = elem.parentNode;
	if (elemNode.nodeName.toLowerCase() == 'a') {
		// find and remove any selected classes
		var links = $('feature_thumbnails').getElementsByTagName('a');
		var nodeLength = links.length;
		for (var i = 0; i < nodeLength; i++) {
			if (links[i].className == "selected") {
				links[i].className = "";
			}
		}
		// rename the image url and set it as the hero bg		
		var origLink = elemNode.href;
		var newLink = origLink.replace('large','main');
		var hero = $('hero');
		hero.style.backgroundImage = 'url('+newLink+')';
		// finally set the class of the active anchor to selected
		elemNode.className = "selected";
	}
	stopDefaultEvent(e);
}

function showImage(e) {
	var hero = $('hero');
	var heroImg = getStyle(hero, 'backgroundImage');
	var largeImg = heroImg.replace('main','large');
	window.location.href = 'lightbox.html?bg=' + largeImg;
	stopDefaultEvent(e);
}

/*
 * Convert link list into a pulldown menu.
 * id - list id to be converted to <select>, (labelText, promptText, submitButtonAlt) - optional
 */
function linkListToSelect (id, labelText, promptText, submitButtonAlt) {
	var container = $(id);
	var links = container.getElementsByTagName('a');
	var newContainer = document.createElement('form');
	var out = [], elem;
	
	// use innerHTML as IE cannot use DOM to add option elements
	if (labelText) out.push('<label for="'+ id +'">'+ labelText +'</label>');
	out.push('<select id="'+ id +'">');
	if (promptText) out.push('<option value="">'+ promptText +'</option>');
	for (var i = 0, len = links.length; i < len; i++) {
		elem = links[i];
		out.push('<option value="'+ elem.href +'">'+ elem.innerHTML +'</option>');
	}
	out.push('</select>');
	
	if (submitButtonAlt) out.push('<span><input type="submit" value="'+ submitButtonAlt +'" /></span>');
	newContainer.innerHTML = out.join('\r');
	replaceElement(container, newContainer);
	
	// get ref to new element
	container = $(id);
	if (submitButtonAlt) container.parentNode.onsubmit = fireLink;
	else container.onchange = fireLink;
	
	
	function fireLink () {
		document.location = $(id).value;
		return false;
	};
}

function shouldDisplayFlash () {
    return (window.location.search.indexOf('flash=false') == -1);
}


/* Sugar functions */

function $ (element) {
	return document.getElementById(element);
}
function replaceElement (original, replacement) {
	if (original.outerHTML) original.outerHTML = replacement.outerHTML || replacement;
	else original.parentNode.replaceChild(replacement, original);
}
function observeEvent (element, eventName, observerFunction) {
	if (window.addEventListener) element.addEventListener(eventName, observerFunction, false);
	else if (window.attachEvent) element.attachEvent('on' + eventName, observerFunction);
}
function stopDefaultEvent (e) {
    e = e || window.event;
	e.returnValue = false;
	if (e.preventDefault) e.preventDefault();
}
function cancelEvent (e) {
    e = e || window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}
function getEventElement (e) {
    e = e || window.event;
    var el = e.target || e.srcElement;
    if (el.nodeType == 3) el = el.parentNode; // SA bug
    return el;
}
function getStyle (element, style) {
    var value = element.style[style];
    if (!value) {
      var css = document.defaultView.getComputedStyle(element, null);
      value = css ? css[style] : null;
    }
    if (style == 'opacity') return value ? parseFloat(value) : 1.0;
    return value == 'auto' ? null : value;
} 
function hasClassName (element, className) {
    var elementClassName = element.className;
    return (elementClassName.length > 0 && (elementClassName == className ||
      elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))));
}
  
function filterTrackClassName (element){
    var res = Array(); var i = 0;
    for (var a = element.length-1; a >= 0; a--){
        var elClassName = element[a].className;
        if (elClassName.indexOf('track_') !== -1) {
            res[i]= element[a];
            i++;
        }
    }
    return res;
}

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' || url == '') {
            //no URL specified do nothing...
			url = '';
        } else {
            config.url = url;
			if (config.target == '_blank') {
				//alert(config.url);
				window.open(config.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
    }
}