/* ===================================================
Global Javascripts - Dyson
Version: v2.0
Author: James Taylor - 07/01/2008
/* =================================================*/

/* Break out of frames */
//if (top.location != location) top.location.href = document.location.href;

if (top.location != location) {
    if (document.referrer.indexOf(document.domain) == -1 && document.referrer.indexOf("http://styx") == -1) {
        top.location.href = document.location.href;
    }
}


/* Global Flags */
var w3 = !!(document.getElementById && document.createElement);
var browser = identifyBrowser();

function stopDefaultAction(event) {
    event.returnValue = false;
    if (typeof event.preventDefault != "undefined") {
        event.preventDefault();
    }
    return true;
}

/* 
Gets all elements that match an attribute and attribute value pair
E.G. var arrGoogleLinks = getElementsByAttribute("href","http://www.google.com");
*/
function getElementsByAttribute(attribute, attributeValue) {
    var elementArray = new Array();
    var matchedArray = new Array();
    if (document.all) {
        elementArray = document.all;
    } else {
        elementArray = document.getElementsByTagName("*");
    }
    for (var i = 0; i < elementArray.length; i++) {
        if (attribute == "class") {
            var pattern = new RegExp("(^| )" + attributeValue + "( |$)");
            if (elementArray[i].className.match(pattern)) {
                matchedArray[matchedArray.length] = elementArray[i];
            }
        } else if (attribute == "for") {
            if (elementArray[i].getAttribute("htmlFor") || elementArray[i].getAttribute("for")) {
                if (elementArray[i].htmlFor == attributeValue) {
                    matchedArray[matchedArray.length] = elementArray[i];
                }
            }
        } else if (elementArray[i].getAttribute(attribute) == attributeValue) {
            matchedArray[matchedArray.length] = elementArray[i];
        }
    }
    return matchedArray;
}

// hide / show errors in forms
function showError(idField, idErr, strMsg) {
    if (!$(idErr)) {
        var errorSpan = document.createElement("span");
        var errorMessage = document.createTextNode(strMsg);
        errorSpan.appendChild(errorMessage);
        errorSpan.className = "err";
        errorSpan.id = idErr;
        var cont = $(idField).parentNode;
        cont.appendChild(errorSpan);
    }
}
function hideError(idErr) {
    if ($(idErr)) {
        var errorSpan = $(idErr);
        var cont = errorSpan.parentNode;
        cont.removeChild(errorSpan);
    }
}
function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}
function isValidEmail(str) {
    var at = "@";
    var dot = ".";
    var lat = str.indexOf(at);
    var lstr = str.length;
    var ldot = str.indexOf(dot);
    if (str.indexOf(at) == -1) return false;
    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) return false;
    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) return false;
    if (str.indexOf(at, (lat + 1)) != -1) return false;
    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) return false;
    if (str.indexOf(dot, (lat + 2)) == -1) return false;
    if (str.indexOf(" ") != -1) return false;
    return true
}

// *** Same as Right/Left function in VB *** //
function Right(str, n) {
    if (n <= 0) return "";
    else if (n > String(str).length) return str;
    else { var iLen = String(str).length; return String(str).substring(iLen, iLen - n); }
}
function Left(str, n) {
    if (n <= 0) return "";
    else if (n > String(str).length) return str;
    else return String(str).substring(0, n);
}

function IsNumeric(sText) {
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) IsNumber = false;
    }
    return IsNumber;
}

/* 
returns browser & version
E.G. "ie7" or "ie5mac" or "mozilla" or "opera7" or "safari1.2"
*/
function identifyBrowser() {
    var agent = navigator.userAgent.toLowerCase();
    if (typeof navigator.vendor != "undefined" && navigator.vendor == "KDE" && typeof window.sidebar != "undefined") {
        return "kde";
    } else if (typeof window.opera != "undefined") {
        var version = parseFloat(agent.replace(/.*opera[\/ ]([^ $]+).*/, "$1"));
        if (version >= 7) {
            return "opera7";
        } else if (version >= 5) {
            return "opera5";
        }
        return false;
    } else if (typeof document.all != "undefined") {
        if (typeof document.getElementById != "undefined") {
            var browser = agent.replace(/.*ms(ie[\/ ][^ $]+).*/, "$1").replace(/ /, "");
            if (typeof document.uniqueID != "undefined") {
                if (browser.indexOf("5.5") != -1) {
                    return browser.replace(/(.*5\.5).*/, "$1");
                } else {
                    return browser.replace(/(.*)\..*/, "$1");
                }
            } else {
                return "ie5mac";
            }
        }
        return false;
    } else if (typeof document.getElementById != "undefined") {
        if (navigator.vendor.indexOf("Google Inc.") != -1) {
            return "chrome1";
        } else if (window.devicePixelRatio && window.getMatchedCSSRules && !window.Opera) {
            return "safari3";
        } else if (navigator.vendor.indexOf("Apple Computer, Inc.") != -1) {
            if (typeof window.XMLHttpRequest != "undefined") {
                return "safari2";
            }
            return "safari1";
        } else if (agent.indexOf("gecko") != -1) {
            return "mozilla";
        }
    }
    return false;
}

function osType() {
    var os = navigator.platform;

    os = os.toLowerCase();
    if (os.indexOf("mac") != -1) {
        os = "mac";
    } else if (os.indexOf("linux") != -1) {
        os = "linux";
    } else {
        os = "win";
    }
    return os;
}

/* Replace headlines with Flash Futura font */
function replaceHeading(selector, fgcolor, bgcolor, align) {
    if (typeof sIFR == "function" && browser != "ie6" && browser.indexOf("opera") == -1) {
        sIFR.replaceElement(named({ sSelector: selector, sFlashSrc: "/swf/futura_md_bt.swf", sColor: fgcolor, sBgColor: bgcolor, sWmode: "transparent", sFlashVars: "textalign=" + align }));
    };
}

/* sets jumpto function for drop down onchange, hides Go button and repositions the flag */
function initCountryDropDown() {
    if ($("nav_international_select")) {
        Event.observe("nav_international_select", "change", jumpto)
        var aInput = $$("#footer form input")
        var aImg = $$("#footer form img")
        if (aInput.length > 0) {
            for (var i = 0; i < aInput.length; i++) {
                aInput[i].addClassName("hide");
            }
        }
        /*
        if(aImg.length > 0) {
        for(i=0; i < aImg.length; i++) {
        if(aImg[i].src.indexOf("flag") > 0) {
        if(browser!="ie6") {
        aImg[i].style.position = "relative";
        aImg[i].style.left = "-22px";
        } else {
        if($("prodDisplay")) { 
        aImg[i].style.marginLeft = "-22px"; 
        } else {
        aImg[i].style.marginLeft = "0px"; 
        }
        }
        aImg[i].style.marginTop = "2px";
        }
        }
        }
        */
    }
}
/*  */
function alternateTableRow(id) {
    var selector = "#" + id + " tr"
    var rows = $$(selector); //get all table rows
    for (i = 0; i < rows.length; i++) { doAlternate(rows[i], i); }
}
function doAlternate(row, i) {
    if (i % 2 == 0) { row.addClassName("even"); } else { row.addClassName("odd"); }
}

/* Changes all SAFARI 3 text to normal weight and country dropdown text to black */
function unboldSafari() {
    if (browser == "safari3") {
        arrElems = $$("*");
        for (var i = 0; i < arrElems.length; i++) {
            arrElems[i].setStyle({ fontWeight: 'normal' });
        }
        if ($("nav_international_select")) $("nav_international_select").setStyle({ color: '#000' });
    }
}

/* Accessible way to open page in a new window */
function externalLinks() {
    if (!document.getElementsByTagName) return;
    var anchors = document.getElementsByTagName("a");
    for (var i = 0; i < anchors.length; i++) {

        var anchor = anchors[i];
        if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
            anchor.target = "_blank";
    }
}



function trackEyeBlaster() {
    $$('a[rel="trackEyeBlaster"]').each(function (linkElements) {
        linkElements.onclick = function () {
            eyeBlasterTracking(this.id)
        }
    });
    $$('a[rel~="hubNavLinkContent"]').each(function (linkElements) {
        linkElements.onclick = function () {
            eyeBlasterTracking(this.id)
        }
    });

  
}



function trackingLinks() {

    trackEyeBlaster(); // Run Eye Blaster tracking function

    if (!document.getElementsByTagName) return;
    var anchors = document.getElementsByTagName("a");
    for (var i = 0; i < anchors.length; i++) {
        var anchor = anchors[i];
        if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "trackDownloadEyeBlaster") {
            anchor.target = "_blank";
            anchor.onclick = function() {
                var exLink = this.href;
                var exLinkArray = exLink.split("/");
                var lastElement = exLinkArray.length;
                pageTracker._trackPageview('/downloads/' + exLinkArray[lastElement - 1] + '/');

                eyeBlasterTracking(this.id);
            }
        } else if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "externalEyeBlaster") {
            anchor.target = "_blank";
            anchor.onclick = function () {
                var exLink = this.href;
                var exLinkArray = exLink.split("/");
                var lastElement = exLinkArray.length;
                pageTracker._trackPageview('/dealership/' + exLinkArray[lastElement - 1] + '/');

                var eyeBlastID = this.id;
                if (eyeBlastID.indexOf("_") > -1) {
                    var idContainer = eyeBlastID.split("_");
                    eyeBlastID = idContainer[1];
                    
                }

                
            }
          
        }
        //  rel="videoTracking|videos|technology|Airblade"
        //  pageTracker._trackEvent('' + relArray[1] + '', '' + relArray[2] + '', '' + relArray[3] + '')
    }
    
}

/* Used for SI Tracking - removes the £ sign */
function formatPrice(strPrice) {
    if (!IsNumeric(Left(strPrice, 1))) { strPrice = Right(strPrice, strPrice.length - 1); }
    return strPrice;
}

function getPreTaxPrice(strVatPrice) {
    var vatRate = 17.5;
    strVatPrice = formatPrice(strVatPrice);
    var preTaxPrice = (1 / (1 + (vatRate / 100))) * strVatPrice;
    preTaxPrice = formatNumber(preTaxPrice, 2, ' ', '.', '', '', '-', '');
    return preTaxPrice.toString();
}

// checks if the required version of flash is installed
function hasFlashVersion(iVersion) {
    var flashinstalled = 0;
    var flashversion = 0;
    MSDetect = "false";
    if (navigator.plugins && navigator.plugins.length) {
        x = navigator.plugins["Shockwave Flash"];
        if (x) {
            flashinstalled = 2;
            if (x.description) {
                y = x.description;
                //Hack for version 10 and above! Will need to be fixed at version 100!
                if (y.charAt(y.indexOf('.') - 2) != " ") {
                    flashversion = y.charAt(y.indexOf('.') - 2)
                }
                flashversion = flashversion + y.charAt(y.indexOf('.') - 1);
            }
        } else flashinstalled = 1;
        if (navigator.plugins["Shockwave Flash 2.0"]) { flashinstalled = 2; flashversion = 2; }
    } else if (navigator.mimeTypes && navigator.mimeTypes.length) {
        x = navigator.mimeTypes['application/x-shockwave-flash'];
        if (x && x.enabledPlugin) flashinstalled = 2;
        else flashinstalled = 1;
    } else MSDetect = "true";

    if (flashinstalled == 0) {
        try { var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + iVersion); flashinstalled = 2; flashversion = iVersion; }
        catch (e) { }
    }
    if (flashinstalled != 2) { return false; }
    else {
        if (flashversion < iVersion) { return false; }
        else { return true; }
    }
}

function scrollWatch() {
    if ($('moveListRight')) {
        $('moveListRight').onclick = function() {
            MoveEffectRight()
        }
    }
    if ($('moveListLeft')) {
        $('moveListLeft').onclick = function() {
            MoveEffectLeft()
        }
    }
}

function formatNumber(num, dec, thou, pnt, curr1, curr2, n1, n2) { var x = Math.round(num * Math.pow(10, dec)); if (x >= 0) n1 = n2 = ''; var y = ('' + Math.abs(x)).split(''); var z = y.length - dec; if (z < 0) z--; for (var i = z; i < 0; i++) y.unshift('0'); y.splice(z, 0, pnt); if (y[0] == pnt) y.unshift('0'); while (z > 3) { z -= 3; y.splice(z, 0, thou); } var r = curr1 + n1 + y.join('') + n2 + curr2; return r; }

/* Redirect to chosen country */
function jumpto() {
    if ($F("nav_international_select") != "") { document.forms.frmLocation.submit(); }
}

function setSearchText() {
    if ($("shopPostCodeChecker")) {
        var searchField = $("postcode");
        Event.observe($("postcode"), "click", emptytext);
        Event.observe($("postcode"), "blur", emptytext);
    }
}

function emptytext() {
    var searchField = $("postcode");
    if (searchField.value == "Regione") {
        searchField.value = "";
    } else if (searchField.value == "") {
        searchField.value = "Regione";
    }
}

Event.observe(window, "load", function () { externalLinks(); trackingLinks(); unboldSafari(); initCountryDropDown(); scrollWatch(); setSearchText();});

/* Arrows for product model movement */
function MoveEffectLeft(id) {
    var leftPos = $('textBlock').style.left;
    if (leftPos == "0px" || leftPos == "") {
    } else {
        $('moveListLeft').hide()
        new Effect.Move('textBlock', { x: 192, y: 0, duration: 1, queue: 'end', afterFinish: function() {
            $('moveListLeft').show();
        } 
        })
    }
}

function MoveEffectRight() {
    var textBlockWidth = $('numberOfProducts').value;
    textBlockWidth = textBlockWidth * 192;
    textBlockWidth = (192 * 4) - textBlockWidth;

    var leftPos = $('textBlock').style.left;
    if (leftPos == textBlockWidth + "px") {
    } else {
        $('moveListRight').hide()
        new Effect.Move('textBlock', { x: -192, y: 0, duration: 1, queue: 'end', afterFinish: function() {
            $('moveListRight').show();
        } 
        })
    }
}

function eyeBlasterTracking(trackID) {


    // used if we need to include multiple tracking links of the same ID on the same page
    // for example
    //  id="12345|1"
    //  id="12345|2"
    // this will then only use the first part
    trackID = new String(trackID)

    if (trackID.indexOf("|") > 0) {
        trackIDArr = trackID.split("|")
        trackID = trackIDArr[0]
    }
    if (trackID.indexOf("_") > 0) {
        trackIDArr = trackID.split("_")

        trackID = trackIDArr[1]
    }

    
    if (trackID != "") {

        var ebRand = Math.random() + ' ';
        ebRand = ebRand * 1000000;
        PCImage = new Image();
        PCImage.src = "HTTP://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?cn=as&ActivityID=" + trackID + "&rnd=" + ebRand;
    }


} 	
