var $overlay;

function flashWrite(flashfile, x, y, flashvar) {
    document.write("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0' width='" + x + "' height='" + y + "'>");
    document.write("<param name='movie' value='" + flashfile + "' />");
    document.write("<param name='quality' value='high' />");
    document.write("<param name='flashvars' value='" + flashvar + "' />");
    document.write("<param name='wmode' value='transparent' />");
    document.write("<embed src='" + flashfile + "' wmode='transparent' ");
    document.write("flashvars='" + flashvar + "'  ");
    document.write("quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='" + x + "' height='" + y + "'></embed>");
    document.write("</object>");
}

function printYear() {
    var today = new Date();
    document.write(today.getFullYear());
}

function writeEmail(email) {
    document.write('<a href="mailto:' + email + '">' + email + '</a>');
}

function changeTextSize(textSize) {
    document.body.className = 'site ' + textSize;
    return false;
}

function printPage() {
    window.print();
    return false;
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(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;
}

function shortenBreadcrumb(options) {
    /*  
    Shortens the breadcrumb to a specified width by removing the text from one list item
    at a time and replacing it with "..." - accepts an options object as an optional
    parameter with two options:
    shortenBreadcrumb({
    breadcrumb : $('div#breadcrumb > ul'),
    maxWidth : 725
    });
            
    The first is the selector for the breadcrumb ul, the second is the maximum width you
    want it to be.  If not set, the max width is the width of the container minus the width
    of the paragraph next to it ("You are here:").
    -JM
    */

    var breadcrumb = $('div#breadcrumb > ul');
    var maxWidth = parseInt($('div#breadcrumb').innerWidth()) - parseInt($('div#breadcrumb p').outerWidth(true)) + "px";

    if (options != undefined) {
        if (options.breadcrumb != null) { breadcrumb = options.breadcrumb; }
        if (options.maxWidth != null) { maxWidth = options.maxWidth; }
    }

    var levelCount = breadcrumb.find('li').size();
    var shortEnough = false;
    var totalWidth;
    while (shortEnough == false) {
        totalWidth = 0;
        breadcrumb.children('li').each(function() {
            totalWidth += $(this).outerWidth(true);
        });
        if (totalWidth > maxWidth) {
            var li = breadcrumb.children('li').not('.short').eq(1);
            li.addClass('short');
            li.children('a').attr('title', li.children('a').html());
            li.children('a').html('...');
        }
        else {
            shortEnough = true;
        }
    }
}


function overlayOn(t) {
    var dh = $(document).height();
    $overlay.fadeTo(250, 0.5).css({ height: dh }).attr('rel', t);
    $(t).removeClass('hidden').each(function() {
        var h = $(this).outerHeight(),
            wh = $(window).height(),
            os = $(window).scrollTop(),
            t = ((wh - h) / 2) + os;
        $(this).css({ top: t });
    }).css({ 'visibility': 'visible', 'display': 'none' }).fadeIn();
}
function overlayOff() {
    var t = $overlay.attr('rel');
    $overlay.fadeOut();
    $(t).fadeOut();
}

$(window).load(function() {
    var h = 0;
    $('div.homeContentWrap > div.col').css({ 'height': 'auto' }).each(function() {
        var th = $(this).height();
        if (th > h) h = th;
    }).height(h);
    h = 0;
    $('div.productListing div.inner').css({ 'height': 'auto' }).each(function() {
        var th = $(this).height();
        if (th > h) h = th;
    }).height(h);
    
});

$(document).ready(function() {

    $overlay = $('.overlay');
    //$overlay.click(function() { overlayOff(); });
    $overlay.bind('click', overlayOff);
    $('a.lnkOverlayClose').click(function(e) {
        e.preventDefault();
        overlayOff();
    });

    $('table.tblBlue').wrap('<div class="boxTblBlue"></div>').attr({ border: 0, cellpadding: 0, cellspacing: 0 });
    $('#content .dub3Content table').each(function(i, e) {
        var $e = $(e);
        if ($e.width() > 689) {
            $e.width(689);
        }
    });

    function animBar() {
        var w = $(window).width();
        var os = -(5120 - w);

        $('.animBar').css({ left: os }).animate({ left: 0 }, 100000, 'linear', function() { animBar(); });
    }

    animBar();

    $('div.eventCategory img.listingImg').each(function(i, e) {
        var src = $(e).attr('src');
        if (src === '') {
            $(e).hide();
        }
    });
    $('div.eventImage img').each(function(i, e) {
        var src = $(e).attr('src');
        if (src === '') {
            $(e).hide();
        }
    });
    $('div.eventCategoryBox img.listingImg').each(function(i, e) {
        var src = $(e).attr('src');
        if (src === '') {
            $(e).hide();
        }
    });

    $('.productThumbnails img').each(function(i, e) {
        var oc, s, f, l, url;
        oc = $(e).attr('onclick');
        oc = oc.toString();
        s = oc.split(',');
        f = s[1].indexOf("'");

        if (f > -1) {
            l = s[1].lastIndexOf("'");
        } else {
            f = s[1].indexOf('"');
            l = s[1].lastIndexOf('"');
        }

        f = f + 1;
        url = s[1].slice(f, l);
        $(this).parent().attr('href', url);

        var $lightbox = $('<a class="lightboxLink" href="' + url + '" />');
        if (i == 0) { $lightbox.addClass('active'); }
        $('#productImage').append($lightbox);
    });
    $('.lightboxLinkTrigger').click(function(e) {
        e.preventDefault();
        $('.lightboxLink.active').click();
    });
    $('.productThumbnails img').each(function(i, e) {
        var $e = $(e);
        $e.click(function() {
            $('#productImage a.lightboxLink').eq(i).addClass('active').siblings().removeClass('active');
        });
    });


    var h = 0;
    $('div#officeLocations div.addrInner').each(function() {
        var th = $(this).height();
        if (th > h) h = th;
    }).height(h);
    h = 0;
    $('div.productListing div.inner').each(function() {
        var th = $(this).height();
        if (th > h) h = th;
    }).height(h);
    h = 0;
    $('table.tblOffices div.inner').each(function() {
        var th = $(this).height();
        if (th > h) h = th;
    }).height(h);

    if ($('div.lightbox').length > 0) {
        $('div.lightbox a').lightBox({
            imageLoading: '/system/assets/images/lightbox/lightbox-ico-loading.gif',
            imageBtnClose: '/system/assets/images/lightbox/lightbox-btn-close.gif',
            imageBtnPrev: '/system/assets/images/lightbox/lightbox-btn-prev.gif',
            imageBtnNext: '/system/assets/images/lightbox/lightbox-btn-next.gif'
        });
    }

    $('a.lightboxLink').lightBox({
        imageLoading: '/system/assets/images/lightbox/lightbox-ico-loading.gif',
        imageBtnClose: '/system/assets/images/lightbox/lightbox-btn-close.gif',
        imageBtnPrev: '/system/assets/images/lightbox/lightbox-btn-prev.gif',
        imageBtnNext: '/system/assets/images/lightbox/lightbox-btn-next.gif'
    });

    $('a.lnkOverlay').click(function(e) {
        e.preventDefault();
        var $e = $(this), h = $e.attr('href');
        overlayOn(h);
    });
    $('.overlayBox').appendTo('form');

    var ntoptions = {
        newsList: "#newsTicker ul",
        startDelay: 10,
        placeHolder1: "_"
    }
    if ($("#newsTicker ul").size() > 0) {
        $().newsTicker(ntoptions);
    }

    $('span.eventFree').text('Free');

    $('div.feedCol div.carouselMask > ul').adidoCarousel({ autoStart: false, buttonNext: function(e) {
        var parent = e.parent();
        var btn = parent.next('.carouselControl').children('.btnCarouselNext');
        return btn;
    }, buttonPrev: function(e) {
        var parent = e.parent();
        var btn = parent.next('.carouselControl').children('.btnCarouselPrev');
        return btn;
    }, mode: 'fade', resizeMask: true, pager: true, pagerElement: function(e) {
        var parent = e.parent();
        var pager = parent.next('.carouselControl').children('.carouselPager');
        return pager;
    }, pagerStyle: 'numeric'
    });
    $('div.homeBanner > ul').adidoCarousel({ buttonNext: 'div.homeBanner a.btnCarouselNext', buttonPrev: 'div.homeBanner a.btnCarouselPrev', pager: true, pagerElement: 'div.homeBanner div.carouselPager', pagerStyle: 'numeric' });

    $('div.homeBanner div.textBox').each(function(i, e) {
        var h = $(this).outerHeight(true);
        var mt = h / 2;
        $(this).css({ marginTop: -mt, top: '50%' });
    });

    $('table.tblInfoBox tr').not(':last-child').after('<tr><td colspan="3" class="divider"></td></tr>');

    $('ul.contactBoxTabs li').each(function(i, e) {
        $(e).children('a').click(function(event) {
            event.preventDefault();
            $('div.contactBoxContent div.inner').eq(i).show().siblings().hide();
            $(this).parent().addClass('active').siblings('.active').removeClass('active');
        });
    });
    $('ul.contactBoxTabs li').eq(0).addClass('active');
    $('div.contactBoxContent div.inner').eq(0).show().siblings().hide();

    $('div.formContact input.textBox, div.formContact textarea.textBox, div.eventBook input.textbox, div.eventBook textarea.textbox').focus(function() {
        $(this).stop().animate({ borderBottomColor: '#22B1FF', borderLeftColor: '#22B1FF', borderRightColor: '#22B1FF', borderTopColor: '#22B1FF' });
    }).blur(function() {
        $(this).stop().animate({ borderBottomColor: '#CCC', borderLeftColor: '#CCC', borderRightColor: '#CCC', borderTopColor: '#CCC' });
    });

    $('div.productListing div.productBox, div.catListing div.categoryBox').hover(function() {
        $(this).addClass('hover');
    }, function() {
        $(this).removeClass('hover');
    });

    $('div.caseStudies h2.caseStudyTitle').css({ 'cursor': 'pointer' }).click(function(e) {
        e.preventDefault();
        $(this).parent().toggleClass('caseStudyOpen').end().next().slideToggle();
        $(this).parent().siblings('.caseStudyOpen').removeClass('caseStudyOpen').children('.caseStudyContent').slideUp();
    }).next().hide();

    $('#productTabs ul.tabsHeader a').each(function(i, e) {
        $(e).click(function(e) {
            e.preventDefault();
            $(this).parent().addClass('activeTab').siblings('.activeTab').removeClass('activeTab');
            $('#tabsCont > div').eq(i).show().siblings().hide();
        });
    }).first().click();

    $('.modalBackground').appendTo('form');
    $('.modalPopup').appendTo('form');

    $('.searchBox input.textBox').focus(function() {
        var t = $(this).attr('rel');
        var v = $(this).val();
        if (v == t) {
            $(this).val('');
        }
    }).blur(function() {
        var t = $(this).attr('rel');
        var v = $(this).val();
        if (v == '') {
            $(this).val(t);
        }
    });

    $('input.textClear').focus(function() {
        var t = $(this).attr('title');
        var v = $(this).val();
        if (v == t) {
            $(this).val('');
        }
    }).blur(function() {
        var t = $(this).attr('title');
        var v = $(this).val();
        if (v == '') {
            $(this).val(t);
        }
    });

    var h = 0;
    $('div.homeContentWrap > div.col').each(function() {
        var th = $(this).height();
        if (th > h) h = th;
    }).height(h);

    $('select.ddlCustom').each(function() {
        var $this = $(this);
        var ddlAlt = false;
        var ddlWrap = $('<span class="ddlWrap"></span>');
        var ddlBtn = $('<span class="ddlBtn"></span>');
        var ddlVal = $('<span class="ddlVal"></span>');
        var ddlClear = $('<div class="clear"></div>');
        var ddlDrop = $('<span class="ddlDrop"></span>');
        var ddlDropList = $('<ul></ul>');
        var ddlOpen = false;
        // Generate a new list for the dropdown
        $(this).children('option').each(function() {
            var v = $(this).val();
            var t = $(this).text();
            /*  */
            var id = $(this).attr('id');
            /*  */
            var ddlOption = $('<li></li>');
            ddlOption.text(t).attr('title', v).attr('id', id);
            if (ddlAlt) {
                ddlOption.addClass('alt');
                ddlAlt = false;
            } else {
                ddlAlt = true;
            }
            ddlDropList.append(ddlOption);
        });

        // Clicking on an item in the drop down list
        ddlDropList.children('li').click(function(e) {
            var tv = $(this).attr('title');
            $this.val(tv).change();
        });

        $this.change(function() {
            var updV = $(this).children(':selected').val();
            var updT = $(this).children(':selected').text();
            var updID = $(this).children(':selected').attr('id');
            ddlVal.text(updT).attr('value', updV).attr('id', updID);
        });

        ddlDrop.hide();

        //
        ddlWrap.click(function() {
            if (!ddlOpen) {
                ddlDrop.css({ 'height': 'auto' });
            }

            ddlDrop.stop().slideToggle(function() {
                if (ddlOpen) {
                    ddlOpen = false;
                } else {
                    ddlOpen = true;
                }
            });
        });
        ddlWrap.bind("clickoutside", function() {
            if (ddlOpen) { ddlDrop.stop().slideUp(function() { ddlOpen = false }) };
        });

        // Default item
        var defV = $(this).children(':selected').val();
        var defT = $(this).children(':selected').text();
        var defID = $(this).children(':selected').attr('id');

        ddlVal.text(defT).attr('value', defV).attr('id', defID);

        ddlDrop.append(ddlDropList);

        $(this).wrap(ddlWrap).parent().append(ddlVal).append(ddlBtn).append(ddlDrop).append(ddlClear);
        $(this).hide();
    });

    $('div.eventCategoryBox:nth-child(2n)').addClass('marginL10')

    $(':first-child').addClass('first');
    $(':last-child').addClass('last');
    $('a[rel=newWindow]').attr('target', '_blank');

    $('div.jobsListing a').bigTarget({ clickZone: 'li:eq(0)' });
    $('div.jobsListing li:odd').addClass('alternate');

});
