var ModelDetailModule = Class.create({
    initialize: function(currentUrl) {
        this.addressModal = 'address-modal';
        this.modalOverlay = 'modal-overlay';

        this.makeSocialLinks();
        $('social').observe('click', this.clickHandler.bindAsEventListener(this));
        $('oem-links').observe('click', this.clickHandler.bindAsEventListener(this));
        $('additional').observe('click', this.clickHandler.bindAsEventListener(this));
    },

    makeSocialLinks: function() {
        var pageLink = window.location.href.split('?');
        var baseLink = pageLink[0];
        var params = pageLink[1];
        if (params) {
            var featured = 'featured=true';
            if (params.include(featured)) { // check for featured vehicle param
                baseLink += '?' + featured;
            }
        }
        var linkTitle = "&title=" + document.title + '&bodytext=' + document.title;
        var socialType = ['digg', 'reddit', 'delicious', 'permalink']
        for (var x = 0; x < 4; x++) {
            var thisSocial = $(socialType[x]);
            var thisLink = thisSocial.href;
            thisSocial.href = thisLink + encodeURIComponent(baseLink) + encodeURIComponent(linkTitle);
        }
    },

    clickHandler: function(e) {
        var el = e.element();
        if (el.id == 'digg') {
            e.stop();
            var base = window.location.href.split("?")[0];
            BILogUtil.Redirector(el.href, ['mis=RCARBDLNSN1086', 'lnx=ATCSEODIGG', 'refurl=' + encodeURI(base)], true, ['width=610', 'height=490', 'resizable=yes', 'location=yes']).send();
        }
        if (el.id == 'reddit') {
            e.stop();
            var base = window.location.href.split("?")[0];
            BILogUtil.Redirector(el.href, ['mis=RCARBDLNSN1088', 'lnx=ATCSEOREDDIT', 'refurl=' + encodeURI(base)], true, ['width=640', 'height=520', 'resizable=yes', 'location=yes']).send();
        }
        if (el.id == 'delicious') {
            e.stop();
            BILogUtil.Redirector(el.href, ['mis=RCARBDLNSN1087', 'lnx=ATCSEODELICIOUS'], true, ['width=850', 'height=610', 'resizable=yes', 'location=yes']).send();
        }
        if (el.id == 'permalink') {
            e.stop();
            BILogUtil.Redirector(el.href, ['mis=RCARBDLNSN1089', 'lnx=ATCSEOPERMALINK'], true, ['width=640', 'height=210']).send();
        }
        if (el.hasClassName('email')) {
            e.stop();
            new Popup({url: el.href, width: '700', height: '500'});
        }
        if (el.hasClassName('myatc popup')) {
            e.stop();
            new Popup({url: el.href, width: '440', height: '620'});
        }
        if (el.hasClassName('oem')) {
            e.stop();
            var biArray = el.down('.oemmis').title.split(',');
            BILogUtil.Redirector(el.href, biArray, true, ['width=1000', 'height=560', 'resizable=yes', 'location=yes', 'menubar=yes', 'titlebar=yes', 'toolbar=yes']).send();
        }
        if (el.hasClassName('address-needed')) {
            e.stop();
            this.addressHandler(el.id);
        }
    },

    addressHandler: function(element) {
        this.createModalOverlay();
        var addressContent = $(this.addressModal).remove();
        $(this.modalOverlay).insert({after: addressContent});
        var position = Position.cumulativeOffset($(element));
        var addressDims = addressContent.getDimensions();
        addressContent.setStyle({left: position.left + 'px', top: ((position.top - addressDims.height) + 20) + 'px'});
        new Effect.Appear(this.modalOverlay, { duration: 0.4, from: 0.0, to: 0.8 });
        new Effect.Appear(this.addressModal, { duration: 0.4, from: 0.0, to: 1.0 });
        this.updateAddressContent(element);
        this.addAddressModalEvents();
    },

    updateAddressContent: function(element) {
        $('address-search').href = $(element).href;
    },

    addAddressModalEvents: function() {
        $(this.addressModal).observe('click', function(e) {
            var el = e.element();

            if ((el.className == 'button search') || (el.id == 'address-search')) {
                e.stop();
                this.zipProcess();
            }
            if ((el.className == 'button cancel') || (el.id == 'address-cancel') || (el.className == 'button ok') || (el.id == 'address-ok')) {
                e.stop();
                this.zipShowError('hide');
                this.removeModal(this.addressModal);
            }
        }.bindAsEventListener(this));
        $(this.addressModal).observe('submit', function(e) {
            var el = e.element();
            e.stop();

            if (el.id == 'address-zip') {
                this.zipProcess();
            }
        }.bindAsEventListener(this));
    },

    zipProcess: function() {
        var zip = $F('address-zip');
        var zipLength = zip.length;
        if ((zip == undefined) || (zip == '') || (zipLength < 5)) {
            this.zipShowError('show');
        }
        if (this.zipValidateFormat(zip)) {
            this.zipValidateWithMarket(zip);
        }
    },

    zipValidateFormat: function(zip) {
        var zipRegex = /^\d{5}$/;
        return zipRegex.test(zip);
    },

    zipValidateWithMarket: function (zip) {
        if (zip == null) {
            return;
        }
        var url = "/ac-servlets/research/compare/ctr/validateZipAgainstMarket?zip=" + zip + "&callingFunction=zipValidator";
        var options = {method: "get", onSuccess: this.zipEvaluateStatus};
        new Ajax.Request(url, options);
    },

    zipEvaluateStatus: function(data) {
        // Verify parameters.
        if (data == null) {
            return;
        }
        var result = data.responseText.evalJSON();
        var zip = result.zip;
        if (!zip || (zip == "")) {
            this.zipShowError('show');
            return;
        }
        document.cookie = 'USER=' + 'zip=' + zip + '; path=/';
        var distance = '&distance=25';
        var urlZip = '&address=' + zip;
        window.location = $('address-search').href + distance + urlZip;
    },

    zipShowError: function(value) {
        var inventoryError = $('address-error');
        switch (value) {
            case 'show':
                inventoryError.show();
                break;
            case 'hide':
                inventoryError.hide();
                break;
        }
    },

    createModalOverlay: function() {
        var myHeight = $$('body').reduce().getHeight();
        if (myHeight < document.viewport.getHeight()) {
            myHeight = document.viewport.getHeight();
        }
        var overlay = new Element('div', {id: this.modalOverlay}).setOpacity(0.0).setStyle({height: myHeight + "px"});
        document.body.insert(overlay);
    },

    removeModal: function(modalId) {
        new Effect.Fade(this.modalOverlay, {duration: 0.4, from: 0.8, to: 0.0});
        new Effect.Fade(modalId, {duration: 0.4, from: 1.0, to: 0.0});
        $(modalId).stopObserving('click');
        if ($(this.modalOverlay)) {
            $(this.modalOverlay).remove();
        }
    },

    getRandomNumber: function(url) {
        return new Date().getTime();
    },
    throwAsis: function(url) {
        if (!url) {
            return;
        }
        url = encodeURI(url);
        var img = new Image();
        img.src = url;
    }

});

var Popup = Class.create();
Popup.prototype = {
    initialize:function(options) {
        this.options = {
            url: '/',
            resizable: '1',
            width: 300,
            height: 300,
            location: 'no',
            menubar: 'no',
            status: 'no',
            titlebar: 'no',
            toolbar: 'no'
        }
        Object.extend(this.options, options || {});
        var t = (screen.height - this.options.height) / 2;
        var l = (screen.width - this.options.width) / 2;
        window.open(this.options.url, '', 'resizable=' + this.options.resizable + ',width=' + this.options.width + ',height=' + this.options.height + ",top=" + t + ",left=" + l + ",titlebar=" + this.options.titlebar + ",menubar=" + this.options.menubar + ",toolbar=" + this.options.toolbar + ",status=" + this.options.status + ",location=" + this.options.location);
    }
}
