/**
 *	Author: Jarrett M. Barnett
 *	E-mail: jarrett@mc2design.com
 *	Profile: linkedin.com/in/jarrettbarnett
 *	Company: MC2 Design Group, Inc.
 *	Copyright (c) 2010
 *	Last Modified: 2010-11-18
 *
 */
$(document).ready(function () {
    initToolTip();
    initSlide();
    initTabs();
    homepageCarousel();
    initBackground();
    initPreloader();
    if ($('#dealersearch').length > 0){initRetailers()}
});

function initPreloader() {
    jQuery.preloadImages = function () {
        for (var i = 0; i < arguments.length; i++) {
            jQuery("<img>").attr("src", arguments[i]);
        }
    }
    $.preloadImages("/images/bg-homebody.jpg", "/images/bg-body.jpg", "/images/bg-body2.jpg", "/images/bg-body3.jpg", "/images/bg-body4.jpg", "/images/bg-body5.jpg", "/images/bg-body6.jpg", "/images/bg-body7.jpg", "/images/bg-body8.jpg", "/images/bg-body9.jpg", "/images/bg-body10.jpg", "/images/bg-body11.jpg", "/images/bg-body12.jpg");
}

function initToolTip() {
    var _t;
    var _drop = $('div.tooltip-holder');
    _drop.hide();
    $('ul.questions > li').each(function (i) {
        var _hold = $(this);
        var _pos = _hold.offset();
        _hold.mouseenter(function () {
            var _scroll = $('div.scroll-content').scrollTop();
            _drop.eq(i).css({
                top: _pos.top - _scroll - _drop.eq(i).outerHeight(),
                left: _pos.left - _drop.eq(i).outerWidth() / 4
            });
            _drop.hide();
            _drop.eq(i).show();
        });
        $('div.scroll-content').scroll(function () {
            _drop.eq(i).hide();
        });
        _hold.mouseleave(function () {
            if (_t) clearTimeout(_t);
            _t = setTimeout(function () {
                _drop.hide();
            }, 100)
        });
        _hold.mouseover(function () {
            if (_t) clearTimeout(_t);
        });
    });
}

function initTabs() {
    var _list = $('ul.tabset li');
    var _box = $('div.tab-content');
    var _a = _list.index(_list.filter('.active:eq(0)'));
    if (_a == -1) {
        _a = 0;
        _list.eq(_a).addClass('active')
    }
    _box.hide().css({
        opacity: 0
    }).eq(_a).show().css({
        opacity: 1
    });
    _list.each(function (_i) {
        $(this).click(function () {
            _box.eq(_a).animate({
                opacity: 0
            }, {
                queue: false,
                duration: 0,
                complete: function () {
                    $(this).hide()
                }
            });
            _list.eq(_a).removeClass(' active');
            _box.eq(_i).show().animate({
                opacity: 1
            }, {
                queue: false,
                duration: 500
            });
            _list.eq(_i).addClass(' active');
            _a = _i;
            return false;
        });
    });
};

function initSlide() {
    var _speed = 500;
    var _hold = $('.gallery');
    var _holder = _hold.find('.gallery-holder');
    var _slide = _holder.find('ul');
    var _list = _slide.find('>li');
    var _prev = _hold.find('a.prev');
    var _next = _hold.find('a.next');
    var _d = _list.eq(0).outerWidth(true);
    var _x;
    var _a = 0;
    _next.click(function () {
        _a++;
        if (_a == _list.length) {
            _a = 0
        }
        RunAnimation(_a);
        return false;
    });
    _prev.click(function () {
        _a--;
        if (_a == -1) {
            _a = _list.length - 1
        }
        RunAnimation(_a);
        return false;
    });

    function RunAnimation(_new) {
        _x = _new * _d;
        _slide.animate({
            marginLeft: -_x
        }, {
            queue: false,
            duration: _speed
        });
        _old = _new;
        _a = _new;
    };
};

function initGallery3() {
    alert(1)
    var _speed = 500,
        _duration = 5000;
    var _hold = $('.third .gallery');
    var _holder = _hold.find('.holder')
    var _slide = _hold.find('ul.slider');
    var _list = _slide.find('>li');
    var _prev = _hold.find('a.prev');
    var _next = _hold.find('a.next');
    var _d = _list.eq(0).outerWidth(true);
    var _x = 0;
    var _wh = _hold.width();
    var _ws = _list.length * _d;
    var _i = 0;
    _list.eq(_i).addClass('active');
    var _num3 = $('<div class="num"></div>').css({
        padding: '20px 0 0 250px'
    });
    _hold.after(_num3);
    _list.each(function (i) {
        $('<a href="#">' + (i + 1) + '</a>').appendTo($('div.num')).css({
            padding: '0 2px'
        });
    });
    var _thumb = _num3.find('a');
    _thumb.eq(_i).addClass('active');
    _thumb.each(function (j) {
        $(this).click(function () {
            RunAnimation(j);
            return false;
        });
    });
    _next.click(function () {
        _a++;
        if (_a == _list.length) {
            _a = 0
        }
        RunAnimation(_a);
        return false;
    });
    _prev.click(function () {
        _a--;
        if (_a == -1) {
            _a = _list.length - 1
        }
        RunAnimation(_a);
        return false;
    });
    var _t;

    function runTimer() {
        if (_t) clearInterval(_t);
        _t = setInterval(function () {
            _a++;
            if (_a == _list.length) {
                _a = 0
            }
            RunAnimation(_a);
        }, _duration);
    }
    runTimer();

    function RunAnimation(_new) {
        _thumb.eq(_old).removeClass('active');
        _thumb.eq(_new).addClass('active');
        if (_t) clearTimeout(_t);
        if (_t1) clearTimeout(_t1);
        _x = _new * _d;
        _slide.animate({
            marginLeft: -_x
        }, {
            queue: false,
            duration: _speed,
            complete: function () {
                runTimer();
            }
        });
        _old = _new;
        _a = _new;
    };
};

function homepageCarousel() {
    var settings = {};
    settings['name'] = 'homecarousel';
    settings['selector'] = '.homegallery ul li';
    settings['slide_selector_class'] = '';
    settings['desc_selector'] = '';
    settings['autoplay'] = true;
    settings['slide_timing'] = 7000;
    settings['enable_controls'] = false;
    settings['prev_btn'] = 'a.prevbtn';
    settings['next_btn'] = 'a.nextbtn';
    settings['play_btn'] = 'a.play';
    settings['pause_btn'] = 'a.pause';
    settings['count_selector'] = '.switcher p';
    settings['effect_transition'] = 'fade';
    settings['effect_timing'] = 1200;
    settings['active_class'] = 'active';
    settings['lastactive_class'] = 'last-active';
    homeSplash = new mc2Carousel(settings);
}

function mc2Carousel(settings) {
    var settings2 = settings;

    function processCarousel(_d, _effect_timing_override) {
        var _selector = settings.selector;
        var _count_selector = settings.count_selector;
        var _count_length = $(_selector).length;
        var _activeclass = settings['active_class'];
        var _lastactiveclass = settings['lastactive_class'];
        var _effect_timing = (_effect_timing_override) ? _effect_timing_override : settings['effect_timing'];
        var $active = $(_selector + '.' + _activeclass);
        if ($active.length == 0) $active = $(_selector + ':last');
        var $next = (_d == 'prev') ? ($active.prev().length) ? $active.prev() : $(_selector + ':last') : ($active.next().length) ? $active.next() : $(_selector + ':first');
        $(_count_selector).html("<strong>" + ($next.index() + 1) + "</strong>" + " / " + _count_length);
        $active.addClass(_lastactiveclass);
        $next.css({
            opacity: 0.0
        }).addClass(_activeclass).css('z-index', '1').animate({
            opacity: 1.0
        }, _effect_timing), $active.removeClass(_activeclass + ' ' + _lastactiveclass).css('z-index', '0'), $active.animate({
            opacity: 0.0
        }, _effect_timing);
        if (settings.enable_controls) {
            settings.prev_btn.removeClass(_activeclass), settings.pause_btn.addClass(_activeclass);
        }
    }
    $(settings.prev_btn).live("click", function () {
        processCarousel('prev', 500);
        clearInterval(window[settings['name']]);
        return false;
    }), $(settings.next_btn).live("click", function () {
        processCarousel('next', 500);
        clearInterval(window[settings['name']]);
        return false;
    });
    if ($(settings.selector).length > 1) {
        window[settings['name']] = setInterval(processCarousel, settings.slide_timing, settings2);
    }
}

function initBackground() {
    function resizeBackground() {
        var b = $("body");
        var s = $("#bgimage");
        var i = $("#bgimage img");
        var _h = b.height();
        var _w = b.width();
        s.css("height", _h).css("width", _w), i.css("height", _h).css("width", _w);
    }
    $(window).resize(function () {
        resizeBackground();
    });
    $("#bgimage").show(), resizeBackground();
}

function initBrowserDetect() {
    var u = navigator.userAgent.toLowerCase();
    var _html = document.getElementsByTagName("html")[0];
    if (is("win")) addClass("win");
    else if (is("mac")) addClass("mac");
    else if (is("linux") || is("x11")) addClass("linux");
    if (is("msie 8.0")) addClass("ie8");
    else if (is("msie 7.0")) addClass("ie7");
    else if (is("msie 6.0")) addClass("ie6");
    else if (is("firefox/2")) addClass("ff2");
    else if (is("firefox/3")) addClass("ff3");
    else if (is("opera") && is("version/10")) addClass("opera10");
    else if (is("opera/9")) addClass("opera9");
    else if (is("safari") && is("version/3")) addClass("safari3");
    else if (is("safari") && is("version/4")) addClass("safari4");
    else if (is("chrome")) addClass("chrome");
    else if (is("safari")) addClass("safari2");
    else if (is("unknown")) addClass("unknown");
    if (is("msie")) addClass("trident");
    else if (is("applewebkit")) addClass("webkit");
    else if (is("gecko")) addClass("gecko");
    else if (is("opera")) addClass("presto");

    function is(browser) {
        if (u.indexOf(browser) != -1) return true;
    }

    function addClass(_class) {
        _html.className += (" " + _class);
    }
    if (window.addEventListener) window.addEventListener("load", initBrowserDetect, false);
    else if (window.attachEvent) window.attachEvent("onload", initBrowserDetect);
}

function Console() {}
Console.enabled = true;
Console.log = function () {
    if (Console.enabled && window.console && window.console.log) {
        console.log.apply(console, arguments);
    }
};

 
function initRetailers() {
    var _maptoggle = $("a.togglemap");

    _maptoggle.live("click", function () {

        if ($(this).hasClass('expanded')) {
            $(".map").slideUp(500).html('');
        } else {
            _mapid = $(this).attr('rel');

            var _parent = $(this).parent().parent().parent();

            $.ajax({
                dataType: 'html',
                url: '/fetch/dealers/index_content_googlemap/' + _mapid,
                type: 'GET',
                success: function (data) {
                    $(_parent).find(".googlemap").slideDown(500).html(data).addClass('expanded');
                }
            }); // end ajax
        }
        return false;
    });

    var _loginlink = $("a.loginlink");
    _loginlink.toggle(function () {
        $("#dealerlogin").slideDown(500);
        return false;
    }, function () {
        $("#dealerlogin").slideUp(500);
        return false;
    });

    var _dealerselector = $(".dealersearchtext");
    var _offset = 0;
    var _searchvalue;

    _dealerselector.live("keypress", function () {
        $("#dealer_loading").show();
        $(this).delay(function () {
            _searchvalue = _dealerselector.attr("value");
            if (_searchvalue == "") {
                $("#dealer_loading").hide();
            } else {
                _offset = 0;
                getDealers(_searchvalue, _offset);
            }
        }, 500); // end delay
    })

    $("a.dealerprev, a.dealernext").live("click", function () {
        $("#dealer_loading").show();
        _offset = ($(this).attr("class") == "dealernext") ? _offset + 3 : (_offset < 1) ? 0 : _offset - 3; // if next button was pressed, add 3, otherwise subtract 3 unless its going to result in a 0 or less
        getDealers(_searchvalue, _offset);
        return false;
    })
}

