/**
*	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-08-13
*
*/

$(document).ready(function() {
        initLogging();
        initController();
        initClearInput();
        initCufon();
        initCustomFunctions();
        initCustomEvents();
        initGlobal();
        
        _cc = ".all"; // current category class @todo move this to a better place
});

function initController()
{
    var _container = $("div.columns");
    var _baseurl = "http://www.overlandequipment.com";
    var _secureurl = "https://www.overlandequipment.com";
    var _url = $.address.baseURL();

    $.console(_url);

        /**
         **      ADDRESS INITIALIZE
         */
        $.address.init(function(e){

            // if product type is specifieid (overview or product), set ptype so that a specific product can be retrieved; otherwise, set to false so we can perform a switch/case on the URL
            var _ptype = (e.pathNames[0] == 'overview' || e.pathNames[0] == 'product') ? e.pathNames[0] : false;
            if(_ptype) var _otherptype = (_ptype == 'overview') ? 'product' : 'overview';

            // set var _product as productcode if specified in url; otherwise, check for active productcode in navigation menu; otherwise, set as false;
            var _product = (e.pathNames[1]) ? e.pathNames[1] : ($("#main-nav li.active").attr("id")) ? $("#main-nav li.active").attr("id") : false;

            if(_ptype) { // if product type specified in URL
                initProductpage(_ptype,_otherptype,_product, _cb = function()
                { // @todo make slider automatically obtain correct amount of slides
                    _ptype = "overview";
                    _otherptype = "product";
                    var _i = ($("#main-nav li.active")) ? $("#main-nav li"+_cc).index(".active") : 0 ;
                    $("#"+_ptype+" .holder:eq("+_i+")");

                    homeSlider = new initSlider(getIndex(_product));
                    updateControls(_ptype,_product);
                    updatePlaceholder(getIndex(_product));
                    initProductColorswatch();
                    initProductThumbs();
                    initProductTabs();
                })
            } else { // product not being requested; therefore check URL and run additional JS functions if neccesary.
            
                switch(_url)
                {
                    case "http://www.overlandequipment.com/dealers":
                        initDealers();
                        initGlobal();
                        break;

                    case "http://www.overlandequipment.com/catalog":
                        _ptype = "overview";
                        _otherptype = "product";
                        initHomepage(_ptype,_otherptype,_product, _cb = function() {
                            var _i = ($("#main-nav li.active")) ? $("#main-nav li"+_cc).index(".active") : 0 ;
                            $("#"+_ptype+" .holder:eq("+_i+")");

                            homeSlider = new initSlider(getIndex(_product));
                            updateControls(_ptype,_product),
                            updatePlaceholder(getIndex(_product)),
                            initProductColorswatch(),
                            initProductThumbs(),
                            initProductTabs();
                            initLightbox();
                            initPreloadImages(null,"colorswatch"),
                            updateCufon("all");
                            initPreloadImages(null,"logos");
                        });
                        break;

                    case _baseurl:
                    case _secureurl:
                        initCufon();
                        initGlobal();
                        break;

                    default:
                            initProductThumbs(),
                            initProductTabs();
                            initLightbox();
                            initPreloadImages(null,"colorswatch"),
                            updateCufon("all");
                            initGlobal();
                        break;
                }
            } // end if
        }); // end address init

        /**
         **      ADDRESS EXTERNAL CHANGE
         */
        $.address.externalChange(function(e) {
            var _ptype = (e.pathNames[0] == 'overview' || e.pathNames[0] == 'product') ? e.pathNames[0] : false;
            var _product = (e.pathNames[1]) ? e.pathNames[1] : $("#main-nav li.active").attr("id");

            if(_ptype)
            {
                updateControls(_ptype,_product);
                updatePlaceholder(getIndex(_product));
                updateProductfocus(_ptype,_product,'500');
            }
        }); // end address

}

function initGlobal()
{
    var _searchselector = $(".searchtext");
    var _searchselector2 = $(".btn-go .btn");
    if(_searchselector.attr("value") !== "Search") getSearchResult(_searchselector.attr("value"));

    _searchselector.live("keypress", function()
    {
        $(this).delay(function()
        {
            getSearchResult(_searchselector.attr("value"));
        }, 300 ); // end delay
    });

    $('select[name="ShippingMethod"]').val('ups:7');

//    $("option[value='ups:7']").attr("selected","selected");

}

/**
 *      INITSLIDER
 *      Notes: Initiates the sliding animation and settings. I originally tried having the animations strictly tied to URL changes (hash value) using the address API,
 *      but found that it ruined the "fluidity" of the sliding animation and had too much of a delay between event click and animation execution.
 */
function initSlider(_offsetcount,_count)
{
    // _offsetcount     =>  default slide's index number
    // _count           =>  total slide count

    var _pn = "#main-nav li"; // product nav

    // make view all specific categories visible, not hide non view-all category products/categories
    $(_pn+_cc+":hidden").slideDown(600),
    $(_pn+":not("+_cc+"):visible").slideUp(600);

    // animation settings
    var _eachwidth = 800; // width of each slide (in pixels)
    var _totalwidth = 0; // total width of slide container (in pixels)
    var _container = $(".columns"); // slide container selector
    var _eachtransition = 'jswing'; // slide animation type
    var _transitionspeed = 500; // slide animation timing (in milliseconds)
    var _easingtype = 'swing'; // swing or linear

    // animation mathematics
    var _currentoffset = 0; // holds the current slide offset (in pixels)
    var _currentindex = (_offsetcount) ? _offsetcount : ($(_pn+".active").attr("id")) ? ($(_pn+_cc).index($(".active"))) : 0; // current slide's index
    var _totaloffset = 0; // primarily used to hold the slide index maximum (number 0-13?)
    var _rightoffset = 0; // used to animate slides left/right (in pixels)
    var _bottomoffset = 0; // used to animate slides up/down (in pixels)

    var _product = false; // just declaring this

    if(_offsetcount) { // if current slide index is provided (_offsetcount), do math to determine the rightoffset so that the slides dont shift when products are ajax'd in.
        _rightoffset = ((_offsetcount) * _eachwidth);
        _currentoffset = _rightoffset;
    }
    if(_count) { // if total slide count is provided, just do the math and subtract by 1 since indexes start at 0 and not 1
        _totalwidth = ((_count) * _eachwidth);
        _totaloffset = _count-1;
    } else { // otherwise figure out total slide count since it wasnt provided and right offset will simply stay at 0 (first slide)
        $(_pn+_cc).each(function(){
            _totalwidth = _totalwidth + _eachwidth;
            _totaloffset = _totaloffset + 1;
        });
    }
    
    // update container and product navigation
    _container.attr("style", "width: "+_totalwidth+"px; right: "+_rightoffset+"px;"); // update container slide with total width and right offset figured out above.
    $(_pn+".active").removeClass("active"),
    $(_pn+_cc+":eq("+_currentindex+")").addClass("active"),
    $("#overview "+_cc+":eq("+_currentindex+")").addClass("active"),
    updateCufon("navigation");

    /**
     *      Events
     **/
    // categories
    $("#categories ul li a:not(.dealers)").click(function()
    {
        $(this).stop(false,true); // finish all animations
        _cc = "."+$(this).attr("class"); // update current category (global var)
        
        // update slider variables
        _rightoffset = 0;
        _currentoffset = 0;
        var _ptype = "overview";
        _count = $(_pn+_cc).length;
        if(_count < 2) {
            $(".arrow-prev a, .arrow-next a").hide();
        } else {
            $(".arrow-prev a, .arrow-next a").show();
        }

        _totaloffset = _count;
        _currentoffset = 0;
        _totalwidth = ((_count) * _eachwidth)
        _container.attr('style', 'width: '+_totalwidth+'px; right: '+_rightoffset+'px;');
        _currentindex = 0;

        $("#categories ul li").removeClass("active"), $(this).parent().addClass("active"); // update category navigation
        $(_pn+_cc+":hidden").slideDown(600), $(_pn+":not("+_cc+"):visible").slideUp(600), $(_pn+_cc).first().addClass("active");// hide product items that dont have the current category class but are visible

        _product = $(_pn+_cc).first().attr("id");

        // @todo animate to what WILL be the first slide, then hide the unneccesary slides on callback
        updateProductfocus(_ptype,_product, 350); // animate to prev/next item
        updateControls(_ptype,_product);
        updateURI(_currentindex);

        // show current category slides
        $("#overview .holder, #product .holder").hide().removeClass("active"), // @todo hide visible elements that dont have the current category class instead of hiding everything inefficiently
        $("#overview div"+_cc+", #product div"+_cc).show();
//        $("#"+_ptype+" div"+_cc).show().first().addClass("active");

        $("#"+_ptype+" "+_cc+":first").addClass("active");

        initPreloadImages(null, "colorswatches");
        updateCufon("navigation");
        return false;
    });


    // ileft/right/top/down arrow keys
    $(document).keydown(function(e){
        if (e.keyCode == 37 || e.keyCode == 39) {

            _isprev = (e.keyCode == 37 || e.keyCode == 38) ? true : false; // if left or up arrow, _isprev is true, otherwise if keycode right or down arrow, _isprev is false

            _container.stop(false,true),
            _rightoffset = (_isprev) ? ((_currentoffset - _eachwidth) < 0) ? (_totalwidth - _eachwidth) : (_currentoffset - _eachwidth) : ((_currentoffset + _eachwidth) > (_totalwidth - _eachwidth)) ? 0 : (_currentoffset + _eachwidth); // need rightoffset to animate, index to update controls, etc.
            _currentindex = (_rightoffset == 0) ? 0 : (_isprev) ? [(_rightoffset == (_totalwidth - _eachwidth)) ? _totaloffset-1 : _currentindex-1] : (_currentindex+1); // get new index (relative to the current category) from active nav item

            // animate to prev/next item
            _container.animate({
                right: [_rightoffset, _eachtransition]
                },
                _transitionspeed,
                _easingtype,
                function() {
                    _currentoffset = _rightoffset;
                }
            );
            updatePlaceholder(_currentindex, _cb = function(){
                if($("#overview").hasClass("current"))
                {
                    initPreloadImages(null, "colorswatches");
                } else if ($("#product").hasClass("current")) {
                    initPreloadImages(null, "thumbnails");
                }
            });
            return false;
            
        } else if (e.keyCode == 38 || e.keyCode == 40) {

            var _px = (e.keyCode == 38) ? 0 : -456;

            $("#overview").animate({
                top: [_px, _eachtransition]
            },
                400,
                _easingtype),
            $("#product").animate({
                top: [_px, _eachtransition]
            },
            400,
            _easingtype,
            function(){
                $(".arrow-prev, .arrow-next").show();
            });
            updatePlaceholder(_currentindex, _cb = function(){
                if($("#overview").hasClass("current"))
                {
                    initPreloadImages(null, "colorswatches");
                } else if ($("#product").hasClass("current")) {
                    initPreloadImages(null, "thumbnails");
                }
            });
            return false;

        } else {
            return true;
        }

    });

    // prev/next button
    $(".arrow-prev a, .arrow-next a").attr("style","display: block;").click(function()
    {
        _isprev = ($(this).parent().attr('class') == "arrow-prev") ? true : false;

        // need rightoffset to animate slider and currentindex to update controls, placeholder, and uri.
        _container.stop(false,true),
        _rightoffset = (_isprev) ? ((_currentoffset - _eachwidth) < 0) ? (_totalwidth - _eachwidth) : (_currentoffset - _eachwidth) : ((_currentoffset + _eachwidth) > (_totalwidth - _eachwidth)) ? 0 : (_currentoffset + _eachwidth);
        _currentindex = (_rightoffset === 0) ? 0 : (_isprev) ? (_rightoffset == (_totalwidth - _eachwidth)) ? _totaloffset-1 : _currentindex-1 : _currentindex+1;

        // animate to prev/next item
        _container.animate({
            right: [_rightoffset, _eachtransition]
            },
            _transitionspeed,
            _easingtype,
            function() {
                _currentoffset = _rightoffset;
            }
        );

        updatePlaceholder(_currentindex, _cb = function(){
            initPreloadImages(null, "colorswatches");
            initPreloadImages(null, "thumbnails");
        });
            
        return false;
    }),


    // left navigation
    $(_pn).bind("click", function()
    {
        _currentindex = $(_pn+_cc).index($(this));

        $(_pn).removeClass("active"),
        $(this).addClass("active"),
        $("#product").removeClass("current");

        if($("#main").hasClass("searchresults"))
        {
            $("#main").removeClass("searchresults"),
            $("#category").hide(),
            $("#content").show();
        }

        _container.stop(false,true);
        _rightoffset = (_currentindex * _eachwidth);

        // animate to clicked item
        _container.animate({
            right: [_rightoffset, _eachtransition]
            },
            _transitionspeed,
            _easingtype,
            function() {
                _currentoffset = _rightoffset;

                $("#overview").animate({
                    top: [0, _eachtransition]
                },
                    400,
                    _easingtype),
                $("#product").animate({
                    top: [0, _eachtransition]
                },
                400,
                _easingtype,
                function(){
                    $(".arrow-prev, .arrow-next").show();
                });
            });
        var _ptype = ($("#product").hasClass("current")) ? "product" : "overview";
        var _product = $(_pn+_cc+":eq("+_currentindex+")").attr("id");
        updateControls(_ptype,_product);
        updatePlaceholder(_currentindex, _cb = function(){
            updateURI(_currentindex);
            initPreloadImages(null, "colorswatches");
        });
        return false;
    });

    // Floating Image for Overview
    var _floatimage = $(".image-holder a");
    _floatimage.live("click", function() {
        var _code = $(this).attr('rel'); // acadia/517-36-36-13
        var _product = _code.substr(0,_code.indexOf("/",0));
        var _productcode = _code.substr(_code.indexOf("/",0)+1,25);
        var _photourl = "/public/uploads/products/medium/"+ _productcode +".jpg";
        var _linkurl = "/public/uploads/products/large/"+ _productcode +".jpg";
        var _prodcolor = $(this).attr("title");

        var _tab1 = ".tab1";
        var _tab2 = ".tab2";
        var _tab3 = ".tab3";

        // @todo Switch out input field that stores product code as well for add to cart button to work properly
        $("#overview div.holder").removeClass("active"),
        $("#product div"+_cc+":eq("+_currentindex+")").addClass("active");

        $("#product .active .column1 .tab1 .image-box strong.name").text(_prodcolor);
        $("#product .active .column1 .tab1 .image-box .image a img").attr("src", _photourl),
        $("#product .active .column1 .tab1 .image-box .image a").attr("href", _linkurl).attr("title",_prodcolor);
        $("#product .active .column1 .tab3 .details-box .cont .list li span.colordetail").text(_prodcolor);
        $("#product .active .productcode").attr("value", _productcode);
        $("#product .active").find(_tab1).fadeIn("200"),
        $("#product .active").find(_tab2).hide(),
        $("#product .active").find(_tab3).hide();

        $("#product .active").find(".tab").removeClass('active');

        $("#overview").animate({
            top: [-456, _eachtransition]
        },
            350,
            _easingtype,
            function(){}),
        $("#product").addClass("current").animate({
            top: [-456, _eachtransition]
        },
        350,
        _easingtype,
        function(){
//            var _ptype = "product";
//            var _product = $(_pn+_cc+":eq("+_currentindex+")").attr("id");
//            updateControls(_ptype,_product);
//            $.address.value("product/" + _code);
        });
        updatePlaceholder(_currentindex, _cb = function(){
            updateURI(_currentindex);
            initPreloadImages(null, "thumbnails");
        });
        return false;
    });

}

function initHomepage(_ptype,_otherptype,_product,_cb)
{
    $.ajax({
        url: '/fetch/products/controller/'+_ptype+'/prepend/'+_product,
        type: 'GET',
        dataType: 'html',
        cache: true,
        success: function(data)
        {
            $("#"+_ptype).prepend(data);
        },
        complete: function()
        {
            $("#"+_ptype+" div.holder").hide(),
            $("#"+_ptype+" div"+_cc).show();
            updateCufon("slides");
            initPreloadImages(null, "colorswatches");
        }
    }),
    $.ajax({
        url: '/fetch/products/controller/'+_ptype+'/append/'+_product,
        type: 'GET',
        dataType: 'html',
        cache: true,
        success: function(data)
        {
            $("#"+_ptype).append(data);
        },
        complete: function()
        {
            $("#"+_ptype+ " div.holder").hide(),
            $("#"+_ptype+ " div"+_cc).show();
            updateCufon("slides");
            initPreloadImages(null, "colorswatches");
        }
    }),
    $.ajax({
        url: '/fetch/products/controller/'+_otherptype+'/both',
        type: 'GET',
        dataType: 'html',
        cache: true,
        success: function(data)
        {
            $("#"+_otherptype).html(data);
        },
        complete: function()
        {
            $("#"+_otherptype+ " div.holder").hide(),
            $("#"+_otherptype+" div"+_cc).show();
            updateCufon("slides");
            initPreloadImages(null, "thumbnails");
            initLightbox();
        }

    });

    if(_cb) {
        this._cb();
    } else {

//        _callback = function() {
//            var _i = ($("#main-nav li.active")) ? $("#main-nav li"+_cc).index(".active") : 0 ;
//            $("#"+_ptype+" .holder:eq("+_i+")");
//
//            homeSlider = new initSlider(getIndex(_product));
//            updateControls(_ptype,_product),
//            updatePlaceholder(getIndex(_product)),
//            initProductColorswatch(),
//            initProductThumbs(),
//            initProductTabs();
//            initLightbox();
//
//            Cufon.refresh();
//            //    $("#overview div.holder:not("+_cc+"), #product div.holder:not("+_cc+")").hide().removeClass("active");
//        }
//        this._callback();
    }

}

function updateURI(_i)
{
    var _pn = "#main-nav li";
    var _ptype = ($("#product").hasClass("current")) ? "product" : "overview";
    var _product = $(_pn+_cc+":eq("+_i+")").attr("id");
//    updateControls(_ptype,_product),
    $.address.value(_ptype+"/"+_product);
    $("#login_link").val("/#/"+_ptype+"/"+_product);
}

/**
 *      UPDATECONTROLS
 *      Notes: Updates the previous and next button "href" attirbute to the correct URL hash value...
 */
function updateControls(_ptype,_product,_cb)
{
    var _ptype = (_ptype == "product") ? "product" : "overview";
    var _productarray = $("#main-nav li"+_cc); // #main-nav li.backpacks
    var _index = getIndex(_product); // currentindex in relation to category filter

    if(_index > -1)
    {
        var _prev = (_index == 0) ? _productarray.eq(_productarray.length-1) : $("#main-nav li"+_cc+":eq("+ (_index-1) +")");
        var _next = (_index < _productarray.length - 1) ? $("#main-nav li"+_cc+":eq("+ (_index+1) +")") : _productarray.eq(0);

        $(".arrow-prev a").attr("href", "/#/" + _ptype + "/"+_prev.attr("id")).css("display","block");
        $(".arrow-next a").attr("href", "/#/" + _ptype + "/"+_next.attr("id")).css("display","block");
    }

    if(_cb) this._cb();
}

/**
 *      PLACEHOLDER
 *      Notes: Marks the appropriate divs active to visually aide the user on what slide their currently on...
 */
function updatePlaceholder(_i, _cb)
{
    _i = (_i < 0) ? 0 : _i;
    var _setactive = ($("#product").hasClass("current")) ? $("#product > "+_cc+":eq("+_i+")") : $("#overview >"+_cc+":eq("+_i+")"); // @todo ERROR in IE 8.0.7600.16385
    $("#main-nav li.active").removeClass("active"),
    $("#main-nav li"+_cc+":eq("+_i+")").addClass("active"),
    $(".holder").removeClass("active"),
    _setactive.addClass("active"),
    updateURI(_i),
    updateCufon("navigation"),
    updateLogo();
    
    if(_cb) this._cb();
}


/**
 *      GETINDEX
 *      Notes: Obtain the index number of the current slide...
 */
function getIndex(_product)
{
    var r = $("#main-nav li"+_cc).index($("#"+_product));
    return r;
}

/**
 *      GETPRODUCT
 *      Notes: Get all products (both overview and detail) in two separate AJAX requests...
 */
function initProductpage(_ptype,_otherptype,_product,_cb)
{
    var _ptype = (_ptype) ? _ptype : "overview";
    var _otherptype = (_otherptype) ? _otherptype : "product";
    var _product = (_product) ? _product : $(_pn+_cc).first().attr("id");

    $.ajax({
        url: '/fetch/products/controller/'+_ptype+'/both',
        type: 'GET',
        dataType: 'html',
        cache: true,
        success: function(data)
        {
            $("#"+_ptype).html(data);
            updateProductfocus(_ptype,_product,'500')
            $("#"+_ptype+" div.holder").hide(),
            $("#"+_ptype+" div"+_cc).show();
        },
        complete: function()
        {
            updateCufon("all");
            if(_ptype == "overview")
            {
                initPreloadImages(null, "colorswatches");
            } else if(_ptype == "product") {
                initPreloadImages(null,"thumbnails");
            }
            initLightbox();
        }
    }),
    $.ajax({
            url: '/fetch/products/controller/'+_otherptype+'/both',
            type: 'GET',
            dataType: 'html',
            cache: true,
            success: function(data2)
            {
                $("#"+_otherptype).html(data2);
                $("#"+_otherptype+" div.holder").hide(),
                $("#"+_otherptype+" div"+_cc).show();
            },
            complete: function()
            {
                $("#"+_ptype+ " div.holder").hide(),
                $("#"+_ptype+ " div"+_cc).show();
                updateCufon("all");
                if(_ptype == "overview")
                {
                    initPreloadImages(null, "colorswatches");
                } else if(_ptype == "product") {
                    initPreloadImages(null,"thumbnails");
                }
                initPreloadImages(null, "colorswatches");
                initLightbox();
            }
    });

    if(_cb) this._cb();
}

/**
 *      UPDATEPRODUCTFOCUS
 *      Notes: Animates to the product specified in the URL hash.
 *                  Specifically useful for when user uses the back/forward
 *                  navigation buttons, or manually updating the URL hash to another product.
 */
function updateProductfocus(_ptype,_product,_transition,_cb)
{
    var _i = getIndex(_product);
    var _c = $("#main-nav li"+_cc).length;

    var _container = $('.columns');
    var _eachwidth = '800';
    var _width = _c * _eachwidth;
    var _eachtransition = 'jswing';
    var _easingtype = 'swing'; // swing or linear
    var _transitionspeed = (_transition) ? _transition : 600;

    var _topcss = (_ptype == "product") ? '-456px' : '0px';
    var _rightcss = (_i <= 0) ? 0 : (_i * _eachwidth);

    var _overviewcontainer = $("#overview");
    var _productcontainer = $("#product");

    _container.css("width",_width),
//    _container.stop(false,true),

    // animate to categorycode
        _container.animate({
            right: [_rightcss, _eachtransition]
            },
            _transitionspeed,
            _easingtype,
            function()
            {
                // callback
                _overviewcontainer.animate({
                    top: [_topcss, _eachtransition]
                    },
                    _transitionspeed,
                    _easingtype,
                    function() {  }),
                _productcontainer.animate({
                    top: [_topcss, _eachtransition]
                    },
                    _transitionspeed,
                    _easingtype,
                    function() {  });
                _currentrightcss = _rightcss;
                updatePlaceholder(_i);
        }); // end animate

        if(_cb) this._cb();
}

/**
 *      INITLIGHTBOX
 *      Notes: Initiates the colorbox library
 */
function initLightbox()
{
    $("a.lightbox").colorbox({maxWidth: "90%", maxHeight:"90%"});
    $("a.reviewbox").colorbox({iframe: true, width: "550px", height: "580px"});

    $(".closelightbox").live("click", function(){
        $.colorbox.close();
        return false;
    });
}


/**
 *      INICCLEARINPUT
 *      Notes: Designed to empty input text fields when focused (clicked on).
 *                  Only empties text field if the default value is present (first usage
 *                  of that particular text field basically)...
 */
function initClearInput()
{
    // setup an array to iterate through
    var fields = { // "selector" : "default value"
        "input.text" : "Qty",
        ".search .text" : "Search",
        ".boxes .form-box .text" : "95962",
        ".dealersearchtext" : "Enter a city or zip code"
    };

    // loop through fields "array" declared above
    $.each(fields, function(s, v) { // selector & value
        $(s).focus(function(){
            if($(this).val() == v) $(this).val('');
        })
    });
}

function initDealers()
{
    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;
    })
}

/**
 *      getSearchResult
 *      Notes: Get search results...
 */
function getSearchResult(_keyword)
{
    if(_keyword !== "")
    {
        var _container = $("#category");
        var _content = $("#content, #aboutus");
        var _cart = $("#cart");
        var _main = $("#main");

        $.ajax({
                url: '/fetch/products/search/'+_keyword,
                type: 'GET',
                dataType: 'html',
                success: function(html)
                {
                    _content.hide(),
                    _cart.hide();
                    if(_container.length > 1) _container.remove(); // sometimes search result div doubles under lag... so remove the extra div
                    if(_container.length) {
                        _container.html(html).show(),
                        _main.addClass("searchresults");
                    } else {
                        _main.append('<div id="category">'+ html +'</div>').addClass("searchresults")
                    }
                }
        }); // end ajax
    }
}


/**
 *      INITCUSTOMFUNCTIONS:
 *      Notes:  Setup custom jQuery functions.
 */
function initCustomFunctions(_value){
    $.fn.delay = (function(){
          var timer = 0;
          return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
          };
    })();

//    $.fn.preload = function() {
//        this.each(function(){
//            $('<img/>')[0].src = this;
//        });
//    }
}


/**
 *      GETDEALERS
 *      Notes: Dealer search function...
 */
function getDealers(_keyword,_offset)
{
    if(_keyword !== "")
    {
        var _container = $("#dealer_container");
        if(_request) _request.abort();
        if(_request2) _request2.abort();

        var _request = $.ajax({
            url: '/dealers/dealers/searchjson/'+_keyword+'/'+_offset,
            type: 'GET',
            dataType: 'JSON',
            success: function(data)
            {
                var _d = eval('('+data+')')
                var _c = _d.results[0].count;
                if(_c <= 3) { // if total count is 3 records of less, hide all pagination
                    $(".dealernext, .dealerprev, .dealerpipe").hide()
                } else if((_offset+3) >= _c) { // if offset+3 is greater than or equal to the total dealers available, hide the next button
                    $(".dealernext, .dealerpipe").hide(),
                    $(".dealerprev").show();
                } else if (_offset < 1) { // otherwise if offset is less than 1, hide prev button
                    $(".dealerprev, .dealerpipe").hide(),
                    $(".dealernext").show();
                } else { // otherwise show it all
                    $(".dealernext, .dealerprev, .dealerpipe").show();
                }

            }
        })

        var _request2 = $.ajax({
            url: '/dealers/dealers/search/'+_keyword+'/'+_offset,
            type: 'GET',
            dataType: 'html',
            success: function(html)
            {
                _container.html(html);
                Cufon.refresh('.dealer_record');
                $("#dealer_loading").hide();
            }
        }) // end ajax


    }
}

/**
 *      INITPRODUCTCOLORSWATCH
 *      Notes: Establishes the click event on the product color swatches (First Level Slides)
 */
function initProductColorswatch()
{
    var _eachwidth = 800;
    var _totalwidth = 0;
    var _container = $('.columns');
    var _eachtransition = 'jswing';
    var _transitionspeed = 500; // in ms
    var _easingtype = 'swing'; // swing or linear

    var _currentoffset = 0;
    var _totaloffset = 0;
    var _rightoffset = 0;
    var _bottomoffset = 0;

    var _pn = "#main-nav li";

// @todo run a foreach on all color swatches to preload all images
// @todo Switch out input field that stores product code as well for add to cart button to work properly
//
    // Thumbnails on Product Details
    var _thumbselector = $("a.colorswatch");
    _thumbselector.live("click", function()
    {
        var _index = 0;
        var _product = $(this).attr("rel");
        var _productcode = _product.substr(_product.indexOf("/",_index)+1);
        var _parent = $(this).parentsUntil("#overview");
        var _photourl = "/public/uploads/products/transparent/"+ _productcode +".png";
        var _linkurl = "/product/"+ _product;
        var _prodcolor = $(this).attr("title");
        $(_parent + ".active .image-holder a img").attr("src", _photourl),
        $(_parent + ".active .image-holder a").attr("href", _linkurl).attr("rel", _product).attr("title",_prodcolor);
        $(_parent + ".active .productcode").attr("value", _productcode);
        return false;
    });

    // @todo update this event to use the updateProductfocus() function instead of having its own animate code
    var _subcatselector = $("li.subcategory a");
    _subcatselector.live("click", function()
    {
        var _tab1 = ".tab1";
        var _tab2 = ".tab2";
        var _tab3 = ".tab3";
        var _currentindex = ($("#main-nav li.active").attr("id")) ? $("#main-nav li.active").index() : 0;

        var _code = $("#main-nav li.active").attr("id");
        var _subcatid = $(this).attr("rel");

        $("#overview div.holder").removeClass("active"),
        $("#product div.holder:eq("+_currentindex+")").addClass("active");

        $("#product .active .subcat").hide(),
        $("#product .active").find(".subcat_"+_subcatid).fadeIn("200"),
        $("#product .active").find(_tab1).fadeIn("200"),
        $("#product .active").find(_tab2).hide(),
        $("#product .active").find(_tab3).hide();

        $("#product .active").find(".tab").removeClass('active');

        $("#overview").animate({
            top: [-456, _eachtransition]
        },
            350,
            _easingtype,
            function(){}),
        $("#product").addClass("current").animate({
            top: [-456, _eachtransition]
        },
        350,
        _easingtype,
        function(){
            var _ptype = "product";
            var _product = $("#main-nav li:eq("+_currentindex+")").attr("id");
            updateControls(_ptype,_product);
            $.address.value("product/" + _code);

            $(".arrow-prev").hide(),
            $(".arrow-next").hide();
        });

        return false;
    });

    $(".toplevel, .bottomlevel").live("click", function()
    {
        var _thisclass = $(this).attr("class");
        var _currentindex = ($(_pn+".active").attr("id")) ? $(_pn+".active").index() : 0;
        var _code = $(_pn+".active").attr("id");
        var _topoffset;

        if(_thisclass == 'toplevel')
        {
            $("#product div.holder").removeClass("active"),
            $("#overview div.holder:eq("+_currentindex+")").addClass("active");
            _topoffset = 0;
        } else {
            $("#overview div.holder").removeClass("active"),
            $("#product div.holder:eq("+_currentindex+")").addClass("active"),
            $("#product").addClass("current");
            _topoffset = -456;
        }
        

        $("#overview").animate({
            top: [_topoffset, _eachtransition]
        },
            350,
            _easingtype,
            function(){}),
        $("#product").addClass("current").animate({
            top: [_topoffset, _eachtransition]
        },
        350,
        _easingtype,
        function(){
            $.address.value("overview/" + _code);
            if(_thisclass == "toplevel") $(".arrow-prev, .arrow-next").show();
        });

        return false;
    });

}

/**
 *      INITPRODUCTTHUMBS
 *      Notes: Designed for the product thumbnails located on the "Second Level Slides" for each product.
 *      Clicking a product thumbnail should replace the graphic, color details, and image's anchor reference
 */
function initProductThumbs()
{
    // Thumbnails on Product Details
    var _thumbselector = $(".color ul li a");
    _thumbselector.live("click", function()
    {
        var _tab1 = ".tab1";
        var _tab2 = ".tab2";
        var _tab3 = ".tab3";

        var _parent = $(this).parentsUntil("#product");
        var _productcode = $(this).attr("rel");
//        var _photourl = "/public/uploads/products/medium/"+ _productcode +".jpg";
        var _linkurl = "/public/uploads/products/large/"+ _productcode +".jpg";
        var _prodcolor = $(this).attr("title");
//        $(_parent + ".active .column1 .tab1 .image-box .image a img").attr("src", _photourl),
        $(_parent + ".active .column1 .tab1 .image-box .image a").attr("href", _linkurl).attr("title", _prodcolor);
//        $(_parent + ".active .column1 .tab1 .image-box strong.name").text(_prodcolor);
//        $(_parent + ".active .column1 .tab3 .details-box .cont .list li span.colordetail").text(_prodcolor);
        $(_parent + ".active .productcode").attr("value", _productcode);
//        initLightbox();
        $(_parent).find(_tab1).fadeIn("200"),
        $(_parent).find(_tab2).hide(),
        $(_parent).find(_tab3).hide();

        $(_parent).find(".tab").removeClass('active');
        return false;
    });

}

/**
 *      INITPRODUCTTABS
 *      Notes: Designed for the "Second Level Slides" that have "detail" and "more view" tabs.
 */
function initProductTabs()
{
    var _tabs = $(".tab");
    var _close = $("strong.close a");
    var _tab1 = ".tab1";
    var _tab2 = ".tab2";
    var _tab3 = ".tab3";
    var _tab4 = ".tab4";

    _tabs.live("click", function()
    {
        var _id = $(this).attr('rel');
        var _parent = $(this).parent().parent().parent();

        $(_parent).find(".tab").removeClass('active'),
        $(this).addClass('active'),

        $(_parent).find(_tab1).hide(),
        $(_parent).find(_tab2).hide(),
        $(_parent).find(_tab3).hide(),
        $(_parent).find(_tab4).hide(),

        $(_parent).find("."+_id).fadeIn("200");
        return false;
    })

    _close.live("click", function()
    {
        var _parent = $(this).parent().parent().parent();

        $(_parent).parent().find(".tab").removeClass('active'),
        $(_parent).find(_tab2).hide(),
        $(_parent).find(_tab3).hide(),
        $(_parent).find(_tab4).hide(),
        $(_parent).find(_tab1).fadeIn("200");
        return false;
    })

}
/**
 *  UPDATELOGO
 * Notes: Animates to current index's logo...
 */
function updateLogo()
{
    var _currentindex = ($("#main-nav li.active").attr("id")) ? $("#main-nav li.active").index() : 0;
    if(jQuery.support.opacity) {
        $(".logo span.clogo").fadeOut(3200),
        $(".logo span:eq("+_currentindex+")").fadeIn(2300);
    }
}

/**
 *      INITCUFON
 *      Notes: Establishes what elements should be use Cufon.
 */
function initCufon() {
    Cufon.set('fontFamily', 'GaramondPro');

    Cufon.replace('#header .social li')
        .replace('#header .nav li a')
        .replace('#main-nav li a')
        .replace('.columns .heading')
        .replace('.add input')
        .replace('.boxes .title')
        .replace('.boxes .story')
        .replace('.boxes .link')
        .replace('.boxes .service')
        .replace('.boxes .tel')
        .replace('.boxes .contact')
        .replace('.boxes .form-box label')
        .replace('.sociallinks a')
//                    .replace('#footer .nav-box li')
        .replace('.close')
        .replace('.dealer_record')
        .replace('h1')
        .replace('h2')
        .replace('h3')
        .replace('.company_values li')
        .replace(".tagcontent h3")
        .replace(".price")
        .replace(".cart-box strong")
        .replace(".qty-form-box span")
        .replace('#categories ul li a')
        .replace('.nav li')
        .replace('#topnavigation ul li a')
        .replace('#store-nav li a');
}


/**
 *      INITPRELOADIMAGES
 *      Notes: Preloads images for a better user experience
 */
function initPreloadImages(_imagearray, _group)
{
    (function($) {
      var cache = [];
      // Arguments are image paths relative to the current page.
      $.preLoadImages = function() {
        var args_len = arguments.length;
        for (var i = args_len; i--;) {
          var cacheImage = document.createElement('img');
          cacheImage.src = arguments[i];
          cache.push(cacheImage);
        }
      }
    })(jQuery)

    
    // if predefined _group is defined, build array here
    // @todo instead of preloading each image for each loop, build array and pass array to be preloaded
    switch(_group)
    {
        case "colorswatches":
            var imagepath = "/public/uploads/products/transparent/";
            var _imagearray = [];
            var _s = $("#overview .active .column2 .cart-box .color .colorswatch")

            _s.each(function(_i){
                var _code = $(this).attr('rel'); // acadia/517-36-36-13
                var _productcode = _code.substr(_code.indexOf("/",0)+1,25);
                jQuery.preLoadImages(imagepath+_productcode+".png"); //                _imagearray[_i] = imagepath+_productcode+".png";
            });

            break;

        case "allcolorswatches":
            var imagepath = "/public/uploads/products/transparent/";
            var _imagearray = [];
            var _s = $(".colorswatch");

            _s.each(function(_i){
                var _code = $(this).attr('rel'); // acadia/517-36-36-13
                var _productcode = _code.substr(_code.indexOf("/",0)+1,25);
                jQuery.preLoadImages(imagepath+_productcode+".png"); //                _imagearray[_i] = imagepath+_productcode+".png";_s.each(function(_i){
            });

        case "thumbnails":
            var imagepath = "/public/uploads/products/medium/";
            var _imagearray = [];
            var _s_thumb = $("#product .active .column2 .cart-box .color ul li a");

            _s_thumb.each(function(_i){
                var _code = $(this).attr('rel'); // acadia/517-36-36-13
                jQuery.preLoadImages(imagepath+_code+".jpg"); //                _imagearray[_i] = imagepath+_productcode+".png";
            });
            break;

        case "logos":
            var logopath = "/public/uploads/logos/";
            var _imagearray = [];
                for (var i=5; i<=0; i--)
                {
                    jQuery.preLoadImages(_imagearray[i] = logopath+i+".png");//                    _imagearray[i] = logopath+i+".png";
                }
            break;

        default:
            // do nothing
            break;
    }

    if(_imagearray) {
        jQuery.preLoadImages(_imagearray);
    }

}

/**
 *      INITCUSTOMEVENTS
 *      Notes: Custom build events that we commonly use such as Accordians, Carousels, etc.
 */
function initCustomEvents()
{
    $(".showhide").toggle(function(){
            $("#"+$(this).attr("rel")).fadeIn(300);
        }, function(){
            $("#"+$(this).attr("rel")).fadeOut(300);
    })
}

/**
 *      INITLOGGING
 *      Notes: Only console.logs if the console object exists. Very useful for debugging without breaking
 *      site functionality in Internet Explorer and browsers that don't have the console object by default.
 */
function initLogging()
{
    jQuery.console = function(text){
        if( (window['console'] !== undefined) ){
            console.info(text);
        }
    }
}

/**
 *      UPDATECUFON
 *      Notes: Beneficial for refreshing HTML to use Cufon. By grouping like elements,
 *      we don't have to refresh every Cufon on the page, but rather just specifics (by group).
 *      This method was created because Cufon.refresh('selectors') were littering my code all over. This helps keep it managed.
 */
function updateCufon(_type)
{
    switch(_type)
    {
        case "navigation":
            Cufon.refresh("#main-nav li a")
                    .refresh("#categories ul li a");
            break;

        case "slides":
            Cufon.refresh(".columns .heading")
                    .refresh(".price")
                    .refresh(".title");
            break;

        case "design":
            //do nothing
            break;

        case "dealer":
            Cufon.refresh(".dealer_record");
            break;

        case "all":
             Cufon.refresh();
             break;
             
        default:
            
            break;
    }
}
