//Class implementation from John Resig
// Inspired by base2 and Prototype
(function () {
    var initializing = false, fnTest = /xyz/.test(function () { xyz; }) ? /\b_super\b/ : /.*/;

    // The base Class implementation (does nothing)
    this.jClass = function () { };

    // Create a new Class that inherits from this class
    jClass.extend = function (prop) {
        var _super = this.prototype;

        // Instantiate a base class (but only create the instance,
        // don't run the init constructor)
        initializing = true;
        var prototype = new this();
        initializing = false;

        // Copy the properties over onto the new prototype
        for (var name in prop) {
            // Check if we're overwriting an existing function
            prototype[name] = typeof prop[name] == "function" &&
		        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
		        (function (name, fn) {
		            return function () {
		                var tmp = this._super;

		                // Add a new ._super() method that is the same method
		                // but on the super-class
		                this._super = _super[name];

		                // The method only need to be bound temporarily, so we
		                // remove it when we're done executing
		                var ret = fn.apply(this, arguments);
		                this._super = tmp;

		                return ret;
		            };
		        })(name, prop[name]) :
		        prop[name];
        }

        // The dummy class constructor
        function jClass() {
            // All construction is actually done in the init method
            if (!initializing && this.init)
                this.init.apply(this, arguments);
        }

        // Populate our constructed prototype object
        jClass.prototype = prototype;

        // Enforce the constructor to be what we expect
        jClass.constructor = Class;

        // And make this class extendable
        jClass.extend = arguments.callee;

        return jClass;
    };
})();

function addHoverState(el) {
    jQuery(el).hover(function () {
        var _this = this;
        jQuery(this).css({ 'background-image': jQuery(_this).css('background-image').replace('.png', '-hover.png').replace('.jpg', '-hover.jpg') });
    }, function () {
        var _this = this;
        jQuery(this).css({ 'background-image': jQuery(_this).css('background-image').replace('-hover.png', '.png').replace('-hover.jpg', '.jpg') });
    });
};


var imageLoader = new Image();
imageLoader.src = "/images/misc/image-loader.gif";

var Tools =
{
    SiteName: function () {
        var domain = window.location.host;

        if (domain.indexOf('marine') !== -1) {
            return 'marine';
        }
        else if (domain.indexOf('cycles') !== -1) {
            return 'cycles';
        }
        else if (domain.indexOf('media') !== -1) {
            return 'media';
        }
        else {
            return 'unknown';
        }
    },

    GetZipcode: function () {
        if (Cookies.Get("geocodedzip") != null) {
            zip = Cookies.Get("geocodedzip");
            return zip;
        } else {
            jQuery.get('/GeoLocatorHandler.ashx', function (data) {
                var zipData = jQuery.xmlToJSON(data);
                if (zipData.Status && (zipData.Status[0].Text == 'Success')) {
                    Cookies.Create("geocodedzip", zipData.Message[0].Text, 90);
                    return zipData.Message[0].Text;
                }
                else {
                    return '';
                }
            });
        }
    },

    SetZipcode: function (zipCode) {
        Cookies.Create("geocodedzip", zipCode, 90);
    },

    GetQuerystring: function (name) {
        var querystring = window.location.search.substring(1);
        var values = querystring.split("&");

        for (var i = 0; i < values.length; i++) {
            var pair = values[i].split("=");

            if (pair[0] == name) {
                return pair[1];
            }
        }

        return "";
    },

    RoundNumber: function (number, places) {
        if (!Tools.IsNumeric(number)) {
            number = (activeLanguage.indexOf("fr-") == -1) ? number.replace(",", "") : number.replace(",", ".");
        }

        number = "" + Math.round(number * Math.pow(10, places)) / Math.pow(10, places);

        if (places > 0) {
            if (number.indexOf(".") != -1) {
                var split = number.split(".");
                var zeros = places - split[1].length;

                for (var i = 1; i <= zeros; i++) {
                    number += "0";
                }
            }
            else {
                number += ".";

                for (var i = 1; i <= places; i++) {
                    number += "0";
                }
            }
        }

        return number;
    },

    IsNumeric: function (value) {
        var numbers = "0123456789.";
        var isNumber = true;

        for (i = 0; i < value.length && isNumber == true; i++) {
            if (numbers.indexOf(value.charAt(i)) == -1) {
                isNumber = false;
            }
        }

        return isNumber;
    },

    LocalizeCurrency: function (price) {
        var commaSymbol = (activeLanguage.indexOf("fr-") == -1) ? "," : " ";

        price += "";

        var split = price.split(".");
        var wholeNumber = split[0];
        var decimalNumber = (split.length > 1) ? ((activeLanguage.indexOf("fr-") == -1) ? "." : ",") + split[1] : "";
        var regEx = /(\d+)(\d{3})/;

        while (regEx.test(wholeNumber)) {
            wholeNumber = wholeNumber.replace(regEx, '$1' + commaSymbol + '$2');
        }

        price = wholeNumber + decimalNumber;
        price = (activeLanguage.indexOf("fr-") == -1) ? "$" + price : price + " $";

        return price;
    },

    UrlEncode: function (str) {
        str = escape(str);
        str = str.replace('+', '%2B');
        str = str.replace('%20', '+');
        str = str.replace('*', '%2A');
        str = str.replace('/', '%2F');
        str = str.replace('@', '%40');

        return str;
    },

    UrlDecode: function (str) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < str.length) {
            c = str.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = str.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = str.charCodeAt(i + 1);
                c3 = str.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }

        return string;
    },

    LoadedIncludeFiles: "[tools.js]",
    LoadIncludeFile: function (filename, filetype, media) {
        if (Tools.LoadedIncludeFiles.indexOf("[" + filename + "]") == -1) {
            if (filetype == "js") {
                document.write(unescape('%3Cscript type="text/javascript" src="' + staticUrl + '/includes/js/' + filename + '"%3E%3C/script%3E\r\n'));
            }
            else if (filetype == "css") {
                var css = document.createElement("link");
                css.setAttribute("type", "text/css");
                css.setAttribute("href", staticUrl + "/includes/" + filename);
                css.setAttribute("rel", "Stylesheet");
                css.setAttribute("media", (media == null) ? "all" : media);

                document.getElementsByTagName("head")[0].appendChild(css);
            }

            Tools.LoadedIncludeFiles += "[" + filename + "]";
        }
    },

    LoadIncludeFileByUrlNoCache: function (url) {
        //alert('LoadIncludeFileByUrlNoCache:\r\n ' + url);
        document.write(unescape('%3Cscript type="text/javascript" src="' + url + '"%3E%3C/script%3E\r\n'));
    },

    TrackClick: function (eventtype, id) {
        return TrackClick(eventtype, id, null, null);
    },

    TrackClick: function (eventtype, id, link, target) {
        //alert('Tools.TrackClick(' + eventtype + ', ' + id + ', ' + link + ', ' + target + ');');
        //alert('_gaq');

        if (typeof _gaq != 'undefined') {
            //pageTracker._trackPageview(id);
            _gaq.push(['a._trackEvent', eventtype, id]);
        }

        if ((link == null) || (link == '')) {
            return false;
        }

        // this is the case if a specific target is not set in sitecore.
        // shouldn't happen but handle here anyway
        if (target == 'content') {
            target = '_top';
        }
        var newWindow = window.open(link, target);
        newWindow.focus();
        return false;
    },
    // This is Media mind.
    // test link: http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=at
    CallEyeBlaster: function (activityId) {
        if (jQuery('#eb')) {
            var ebRand = Math.random() + " ";
            ebRand = ebRand * 1000000;
            jQuery('#eb').append('<iframe src="http://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?cn=as&amp;ActivityID=' + activityId + '&amp;ifrm=1&amp;rnd=' + ebRand + '" width="0" height="0" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000"></iframe>');
        }
    },

    CallTurnPixel: function (turnId) {
        if (jQuery('#turn')) {
            jQuery('#turn').append('<img src="http://r.turn.com/server/beacon_call.js?b2=' + turnId + '&amp;cid=" border="0">');
        }
    },

    CallMedia6Pixel: function (media6Id, media6Pcv) {
        if (jQuery('#media6')) {
            jQuery('#media6').append('<script src="http://action.media6degrees.com/orbserv/hbjs?pixId=' + media6Id + '&pcv=' + media6Pcv + '" type="text/javascript"></script>');
        }
    },

    GetDomain: function () {
        var domain_parts = window.location.toString().split('/')[2].split('.');
        var tld = domain_parts.pop();
        var domain = domain_parts.pop();
        return domain + '.' + tld;
    }

};

var Cookies =
{
    //options is a key/value object for the path, domain & secure cookie options
    //ex. {'path':'/Product%20Line', 'domain':'.suzukicycles.com'}
    //path defaults to "/"
    Create: function (name, value, days, options) {
        if (value == "") {
            days = -1;
        }

        if (!days) {
            var expires = "";
        }
        else {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }


        var options = $H({ 'path': '/' }).merge(options || {}).toObject();
        var keys = ['path', 'domain', 'secure'];
        var options_string = '';
        for (var i = 0; i < keys.length; i++) {
            if (options[keys[i]]) {
                options_string += '; ' + keys[i] + '=' + options[keys[i]];
            }
        }
        document.cookie = name + "=" + value + expires + options_string;
    },

    Get: function (name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(";");

        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];

            while (c.charAt(0) == " ") {
                c = c.substring(1, c.length);
            }

            if (c.indexOf(nameEQ) == 0) {
                return c.substring(nameEQ.length, c.length);
            }
        }

        return null;
    },

    Delete: function (name) {
        Cookies.Create(name, "", -1);
    }
};

function openPrintWindow(page, width, height) {
    // custom print window
    window.open(page, "printWindow", "scrollbars=1,width=" + (width || 690) + ",height=" + (height || 550) + ",left=20,top=20");
}

function openStandardPopupWindow(page, width, height) {
    var scrollbars = "";

    if (width == null || width == "") {
        width = 660;
    }
    else {
        scrollbars = "scrollbars = 1, ";
    }

    if (height == null) {
        height = 338;
    }

    window.open(page, "standardPopupWindow", scrollbars + "width = " + width + ", height = " + height + ", left = 20, top = 20");
}

