/** ----------------------- *
 * UTILITIES
 ** ----------------------- */
// Test for IE6
function is_ie6() {
    if($.browser.msie && parseInt($.browser.version) <= 6) {
        return true;
    }
    else {
        return false;
    }
}
// Universal last- and first- children classes
function agco_check_children_classes() {
    $('ul li:last-child, ol:last-child', '#content').addClass('leaast-child');
    $('#blocks div.block p:last-child').addClass('last-child');
}
// Force minimum width. Otherwise horizontal scrolling
// shows wrong background colors/images.
function agco_check_main_width() {
    if ($(window).width() < 965) {
        $('#main').css('width', '965px');
    }
    else {
        $('#main').css('width', '100%');
    }
}
// Import CSS
function agco_import_stylesheet(sheetUrl) {
    var ss = document.createElement("link");
    ss.rel = "stylesheet";
    ss.href = sheetUrl;
    ss.type = "text/css";
    document.getElementsByTagName("head")[0].appendChild(ss);
}
// Initialize jQuery UI
function agco_init_jquery_ui(callback) {
    if (typeof(jQuery.ui) == "undefined") {
        agco_import_stylesheet('/pages/jquery_ui.css');
        $.getScript('/pages/jquery_ui.js', callback);
    }
}
/** ----------------------- *
 * FEATURES
 ** ----------------------- */
// Accordions
function agco_accordion(parent, items) {
    $(items, parent).click(function() { 
        $(this)
            .parents(parent).find('.accordion:visible').siblings('h4').removeClass('expanded')
            .end().slideUp('slow')
            .end().end()
            .next('.accordion:hidden').slideDown('slow').siblings('h4').addClass('expanded');
    });
}
// Styled Forms
function agco_styled_form() {
    // Buttons
    $('#body form button.submit').hover(function() {
        $(this).addClass('hover');
    }, function() {
        $(this).removeClass('hover');
    });
}
// Font Scaler
var fontRemoveClasses = "font-small font-medium font-large";
function agco_font_scaler(dir) {
    if(dir == "smaller") {
        if($('body').is('.font-large')) {
            $('body').removeClass(fontRemoveClasses).addClass('font-medium');
        }
        else {
            $('body').removeClass(fontRemoveClasses).addClass('font-small');
        }
    }
    else {
        if($('body').is('.font-small')) {
            $('body').removeClass(fontRemoveClasses).addClass('font-medium');
        }
        else {
            $('body').removeClass(fontRemoveClasses).addClass('font-large');
        }
    }
    
    // Update dropdowns
    agco_dropdown_menus_init('update');
}
// onReady Function
function agco_content() {
    // External Links
    var currDomain = 'http://' + window.location.hostname;
    $('#body a[href^=http://]').not('[href^='+currDomain+'], .more, :has(img)').addClass('icon-ext');
    
    // IE External Links
    if($.browser.msie) {
        $('#body a.icon-ext').addClass('icon-ext-ie');
    }

    // Link Icons
    $('#content a[href$=.pdf]').wrapInner('<span class="icon-wrap"></span>').addClass('icon icon-pdf');
    $('#content a[href$=.doc]').wrapInner('<span class="icon-wrap"></span>').addClass('icon icon-doc');
    $('#content a[href$=.xls]').wrapInner('<span class="icon-wrap"></span>').addClass('icon icon-xls');
    
    // Lists
    $('ol, ul', '#body').not('.no-js').each(function() {
        $(this).addClass('js-styled');        
        if($('a.icon-ext', this).length) {
            $(this).addClass('ie7-ext-list');
        }
        $('li', this).each(function() {
            $(this).wrapInner('<span class="text"></span>');
            if(($.browser.msie && $.browser.version == 7.0) && $(this).height() > 20) {
                $(this).addClass('icon-ext-bottom');
                $('a.icon-ext', this).removeClass('icon-ext-ie icon-ext').append('<img class="ext-icon" src="/_ui/images/extlink.png" />');
            }
        });
    });

    // Forms
    if( $('#body .contact-form, #body .js-styles').length) {
        agco_styled_form();
    }
    // Accordions
    if ($('div.container-accordion', '#content').length) {
        agco_accordion('#body div.container-accordion', 'li h4');
    }
    // Thickbox
    if($('a.thickbox', '#content').length) {
        agco_import_stylesheet('/_ui/js/thickbox.css');
        $.getScript('/_ui/js/485.htm', function() {
            // thickbox crap
        });
    }
}
/** ----------------------- *
 * DROP-DOWNS
 ** ----------------------- */
// Initialize
var dd_timeout = '';
function agco_dropdown_menus_init(mode) {
    if(mode != "update") {
        // Last-children
        $('div.dropdown div.column:last-child', '#dropdowns').addClass('last-child');
        $('div.column ul:has(ul) > li:not(:first-child)').addClass('secondary');
    }
    
    // Equal Heights
    if(mode == "update") {
        $('#dropdowns div.dropdown div.column').removeAttr('style');
    }
    $('#dropdowns, #dropdowns div.dropdown').show();
    $('#dropdowns div.dropdown').each(function() {
        // Single column
        if($('div.column', this).length == 1) {
            $('div.column', this).addClass('column-single');
            return;
        }
        
        // Multiple columns
        maxHeight = 0;
        $(this).find('div.column').each(function() {
            thisHeight = $(this).height();
            if(thisHeight > maxHeight) {
                maxHeight = thisHeight;
            }
        });
        $(this).find('div.column').height(maxHeight);
    });
    $('#dropdowns, #dropdowns div.dropdown').hide();
    // Location
    var nav_section = $('#breadcrumbs li:not(:first-child) a').eq(0).text().toLowerCase();
    var nav_page = $('#breadcrumbs li:last-child a').text();
    $('#nav-' + nav_section).addClass('active active-static');
    $('ul.third li a').each(function() {
        if($(this).text() == nav_page) {
            $(this).parent().addClass('active');
        }
    });
}
// Hide
function agco_dropdown_menus_off() {
    $('#wrap').removeClass('dropdowns');
    $('#dropdowns, #dropdowns div.dropdown').hide();
    $('#nav-primary > li').not('.active-static').removeClass('active');
}
// Show
function agco_dropdown_menus(mode, navId) {
    if(mode == "on") {
        clearTimeout(dd_timeout);
        agco_dropdown_menus_off();
        $('#wrap').addClass('dropdowns');
        $('#dropdowns, #dropdowns div#dropdown-' + navId).show();
        $('#nav-' + navId).not('.active-static').addClass('active');
    }
    else {
        if($('#dropdown-' + navId).length > 0) {
            dd_timeout = setTimeout("agco_dropdown_menus_off();", 10);
        }
        else {
            agco_dropdown_menus_off();
        }
    }
}
/** ----------------------- *
 * FIXED FOOTER
 ** ----------------------- */
function agco_fixed_footer() {
    // Init
    $('#fixed-footer ul.nav li a').wrapInner('<span></span>').click(function() {
        var $form = $('#form-' + $(this).attr('rel'), '#fixed-forms');
            
        // Check for related form
        if($form.length == 0) {
            return;
        }
        
        // Remove form(s)
        $('#fixed-forms div.form').removeClass('active');
        $('#fixed-form-background, #fixed-form-close').remove();
        
        if($(this).is('.active')) {
            // Remove active state(s)
            $(this).removeClass('active');
            $(this).parent().prev().removeClass('active-previous');
        }
        else {
            agco_fixed_footer_open(this, $form);
        }
        
        return false;
    });
}
function agco_fixed_footer_open(object, $form) {
    // Variables
    var activeForm = $(object).attr('rel');
    var linkWidth = $(object).width();
    var formHeight = $form.height();
    var formOffset = 136 - (linkWidth / 2);
    var formLeft = $(object).offset().left - formOffset;
    
    // Add active state
    $('#fixed-footer ul.nav li').removeClass('active-previous');
    $('#fixed-footer ul.nav li a').removeClass('active');
    $(object).addClass('active');
    $(object).parent().prev().addClass('active-previous');
    
    // Show form
    $form.addClass('active').css({
        top: '-' + formHeight + 'px',
        left: formLeft + 'px'
    });
    $('div.border', $form).css({
        width: linkWidth + 'px',
        marginLeft: '-' + linkWidth / 2 + 'px'
    });
    
    // Close button
    $('#fixed-forms div.form.active').append('<a href="#js-form-close" class="close" id="fixed-form-close"></a>');
    $('#fixed-form-close').click(function() {
        $('#fixed-footer ul.nav a[rel=' + activeForm + ']').trigger('click');
        return false;
    });
    
    // Background
    $('#main').append('<div id="fixed-form-background"></div>');
    $('#fixed-form-background').click(function() {
        $('#fixed-footer ul.nav a[rel=' + activeForm + ']').trigger('click');
        return false;
    }).css('height',$(document).height());
}
// Brand Scroller
function agco_brand_scroller() {
    $('#nav-brands div.scroller').scrollable({
        size: 4,
        clickable: false,
        speed: 500,
        loop: true
    });
    var api = $('#nav-brands div.scroller').scrollable();
    $('#nav-brands a.more-link').click(function() {
        var offset = api.getIndex();
        
        // Copy to end of list and scroll
        $('#brand-scrollable div.brand').eq(offset).clone(true).appendTo('#brand-scrollable');
        $('#brand-scrollable div.brand').eq(offset+1).clone(true).appendTo('#brand-scrollable');
        $('#brand-scrollable div.brand').eq(offset+2).clone(true).appendTo('#brand-scrollable');
        $('#brand-scrollable div.brand').eq(offset+3).clone(true).appendTo('#brand-scrollable');
        api.move(4); 
       
        return false;
    });
}
/** ----------------------- *
 * DEALER LOCATOR
 ** ----------------------- */
 function populateLocation(locationFieldName)
        {
            $(document).ready(function() {
                $.ajax({
                    type: "GET",
                    url: "http://" + document.domain + "/dealers.xml",
                    dataType: "xml",
                    success: function(xml) {
                        var locations = [];
                        $(xml).find('location').each(function() {
                        locations.push($(this).attr('name'));
                            locations.sort();
                        });
                        for (var i = 0; i < locations.length; i++) {
                            var option = "<option>" + locations[i] + "</option>";
                            $("#" + locationFieldName).append(option);
                        }
                    }
                });
            });
        }
        
        function populateCountry(location, countryFieldName)
        {
            $("#"+countryFieldName).children('option').each(function(i) {
                if(i != 0)
                    $(this).remove();
            });
            $(document).ready(function() {
                $.ajax({
                    type: "GET",
                    url: "http://" + document.domain + "/dealers.xml",
                    dataType: "xml",
                    success: function(xml) {
                        $(xml).find('location').each(function() {
                            var countries = [];
                            if ($(this).attr('name') == location) {
                                $(this).find('country').each(function() {
                                    countries.push($(this).attr('name'));
                                    countries.sort();
                                });
                                for (var i = 0; i < countries.length; i++) {
                                    var option = "<option>" + countries[i] + "</option>";
                                    $("#" + countryFieldName).append(option);
                                }
                            }
                        });
                    }
                });
            });
        }
        
        
        function populateBrand(location, country, brandFieldName)
        {
            $("#"+brandFieldName).children('option').each(function(i) {
                if(i != 0)
                    $(this).remove();
            });
            $(document).ready(function() {
                $.ajax({
                    type: "GET",
                    url: "http://" + document.domain + "/dealers.xml",
                    dataType: "xml",
                    success: function(xml) {
                        var brandOrder = new Array("Challenger",
                                                    "Fendt",
                                                    "Massey Ferguson",
                                                    "Valtra",
                                                    "AGCO Allis",
                                                    "AGCO SISU POWER",
                                                    "AGCO Tractors",
                                                    "Gleaner",
                                                    "Hesston",
                                                    "RoGator",
                                                    "Spra-Coupe",
                                                    "Sunflower",
                                                    "TerraGator",
                                                    "White Planters",
                                                    "Willmar");
                        $(xml).find('location').each(function() {
                            if ($(this).attr('name') == location) {
                                $(this).find('country').each(function() {
                                    if ($(this).attr('name') == country) {
                                        //loop through suggested order
                                        for (var i = 0; i < brandOrder.length; i++) {
                                            //search through current node - country  
                                            $(this).find('brand').each(function() {
                                                if ($(this).attr('name') == brandOrder[i]) {
                                                    var url = $(this).find('url').text();
                                                    var option = "<option value='" + url + "'>" + $(this).attr('name') + "</option>";
                                                    $("#" + brandFieldName).append(option);
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                });
            });
        }
        
                
        function locationDropChange(locationFieldName, countryFieldName)
        {           
            var location = $('#'+locationFieldName+' :selected').text();
            populateCountry(location, countryFieldName);
        }
        
        function countryDropChange(locationFieldName, countryFieldName, brandFieldName)
        {            
            var location = $('#'+locationFieldName+' :selected').text(); 
            var country = $('#'+countryFieldName+' :selected').text();
            populateBrand(location,country, brandFieldName);
        }
function dealerLocatorSubmit(brandFieldName) {
    var url = $('#'+brandFieldName+' :selected').val();
    if(url != '0') {
        window.open(url);
    }
    else {
        window.alert('Please select a region, a country and a brand.');
    }
    return false;
}
function agco_dealer_locator_init() {
    // in order to populate the Location drop down for multiple controls the 'drp...' name needs to be the same
    // as the submit id values on your controls. 
    populateLocation('drpLocation1'); //this will populate the Location drop down of the first instance
    populateLocation('drpLocation2'); //this will populate the Location drop down of the second instance.  
}
/** ----------------------- *
 * READY
 ** ----------------------- */
$(function() {
    // IE6 Tweaks
    if(is_ie6()) {
        $.getScript('/pages/bgiframe.js', function() {
            $('#dropdowns').bgiframe();
        });
    }
    // Hover states, mostly for IE
    $('button, input[type=submit]', '#search, #fixed-forms').hover(function() {
        $(this).addClass('hover');
    },function() {
        $(this).removeClass('hover');
    });
    
    // Dropdown Init
    agco_dropdown_menus_init();
    
    // Dropdown Actions
    $('#nav-primary > li > a').hover(function() {
        agco_dropdown_menus('on', $(this).parent().attr('id').replace('nav-',''));
    }, function() {
        agco_dropdown_menus('off', $(this).parent().attr('id').replace('nav-',''));
    });
    $('#dropdowns .dropdown').hover(function() {
        agco_dropdown_menus('on', $(this).attr('id').replace('dropdown-',''));
    }, function() {
        agco_dropdown_menus('off', $(this).attr('id').replace('dropdown-',''));
        
    });
    
    // Check children classes
    agco_check_children_classes();
    
    // Content
    agco_content();
    
    // Dealer Locator
    $('#body form.dealer-locator').submit(function() {
        return false;
    });
    $('#body form.dealer-locator input.submit').click(function() {
        return false;
    });
    agco_dealer_locator_init();
    
    // Fixed footer
    agco_fixed_footer();
    $('#fixed-footer').show();
    
    // Brand scroller
    if($('#hero').length == 0) {
        agco_brand_scroller();
    }
    
    // Search
    $('#search input:text').val('Search...').click(function() {
        if( $(this).val() == $(this).attr('rel')) {
            $(this).val('');
        }
        return false;
    }).blur(function() {
        if ($(this).val() == '') {
            $(this).val( $(this).attr('rel') );
        }
        return false;
    });
    
    // Font scaler
    $('body').removeClass(fontRemoveClasses).addClass('font-small');
    $('a', '#font-scaler').click(function() {
        var direction = ($(this).is('.smaller')) ? 'smaller' : 'larger';
        agco_font_scaler(direction);
    });
    
    // Check resolution
    var resizeTimer = null;
    agco_check_main_width();
    $(window).bind('resize', function() {
        if (resizeTimer) clearTimeout(resizeTimer);
        resizeTimer = setTimeout(agco_check_main_width, 100);
    });
});