$(document).ready(function(){

    // NO IE6!
    if ($.browser.msie && $.browser.version.substr(0,1)<7) {
        loadScript('/js/noIE6/jquery.noIE6.js');
        $('body').noIE6();
    }

    /* temp measure for links that currently go nowhere */
    $('a.inactive ').click(function(e){
        e.preventDefault(); 
        var inner = $(e.target).html();

        $(e.target)
            .blur()
            .data('inner', inner)
            .html('Coming soon')
            .mouseout(function(){
                $(this).html(inner)
            });

    });

    /* Body Full bleed BG images */
    function positionBgImage(){
        var posX = $('#brandLogo').offset().left - 117;
        $('#bodybg').css({'left':posX});
    }
    $(window).resize(positionBgImage);
    positionBgImage();
    if (!$('body#product').length) $('#bodybg').fadeIn();

    /*
     *      Search box (header)
     */
    $('header form#searchform input').click(function() {
                            $(this).css({color:'#fff'});
                            if (this.value == 'Search') this.value = '';
                        }).blur(function(){
                            $(this).css({color:'#ccc'});
                            if (this.value == '') this.value = 'Search';
                        });

    // Log-in form
    $('header form#login-form input').each(function(i, el){
        var orig = $(el).val();
        $(el).data('label', orig);
    });
    $('header form#login-form input')
        .focus(function(){
            if ($(this).val() == $(this).data('label')) $(this).val('');
        })
        .blur(function(){
            if (!$(this).val()) {
                var label = $(this).data('label');
                $(this).val(label);
            }
        });


    $('#login a').click(function(e){
        var l = $(this).closest('#login');
        if (l.hasClass('open')) {
            l.removeClass('open').css({'zIndex':'1'});
        } else {
            l.css({'zIndex':'3'}).addClass('open');
        }
    });
    

    
    /*
     *      Homepage
     */
    if ($('body#home').length) {

        $('#pull-out-tab')
            .hover(function(){$(this).css({'cursor' : 'pointer'})
            .click(function(){window.location = '/about';})
        });

        $('#snippetsLeft')
            .hover(function(){$(this).css({'cursor' : 'pointer'})
            .click(function(){window.location = '/what-makes-a-shackletons-chair';})
        });
        


        // Portraits carousel on the home page
        loadScript('/js/jquery.ShackletonsPortraits.js');
        $('#portraits').ShackletonsPortraits({
            speed: 700
        });

        // Products carousel on the home page
        loadScript('/js/jquery.ProductsHomepage.js');
        $('#content').ProductsHomepage();
    }


    /*
     *      Chair builder
     */
    if ($('body#flashFullBleed').length) {
        
        function resizeSwf() {
            
            var h = $(window).height() - $('header').height();
            var w = $(window).width();
            $('#flash-div').css({
                'height': h,
                'width' : w,
                'position': 'absolute',
                'top'   : $('header').height(),
                'left'  : 0,
                'overflow' : 'hidden'
            });
        }
        $(window).resize(resizeSwf);
        resizeSwf();
    }

    /*      @TODO: 
     *      Remove this #chair-pointer code - 
     *      it's redundant, 
     *      Should use the flash full bleed layout!
     *
     *      Tsk tsk Bryan!
     */
    if ($('body#flashFullBleed').length) {

        function resizeSwf() {

            var h = $(window).height() - $('header').height();
            var w = $(window).width();
            $('#chair-pointer').css({
                'height': h,
                'width' : w,
                'position': 'absolute',
                'top'   : $('header').height(),
                'left'  : 0,
                'overflow' : 'hidden'
            });
        }
        $(window).resize(resizeSwf);
        resizeSwf();
    }


    /*
     *      Gallery
     */
    if ($('body#gallery').length) {
        loadScript('/js/jquery.ShackletonsGallery.js');
        $('#content').ShackletonsGallery();
    }


    /*
     *      Products pages
     */
    if ($('body#product').length) {
        loadScript('/js/jquery.Products.js', function(){
            $('#products-wrap').Products();
        });
    }


    /*
     *      Product page
     */
    if ($('body#product').length) {

        $('#sidecol').fadeIn();
        $(window).load(function() {
            $('#content').css({'background':'none'});
            $('#product-image').fadeIn();
            if ($('#product-image img').length==0) $('#product-image').append('<img src="/images/products/no-image.jpg" alt="No image available for this product" />');
        });

        $('#snippetsLeft')
            .hover(function(){$(this).css({'cursor':'pointer'})
            .click(function(){window.location = '/contact';})
        });

        // get the next link
        var nextUrl = $('#product-siblings ul li.active').next().find('a').attr('href');
        if (nextUrl == null) nextUrl = $('#product-siblings ul li:first a').attr('href');;

        $('#image-nav a')
            .click(function(e){
                e.preventDefault();
                $(e.target).blur();

                $('#sidecol').fadeOut(300);
                $('#product-image').fadeOut(500, function(){
                    window.location = nextUrl;
                });
            });


        $('#sidecol .jsAccordianLink h4').click(function(e){
            var div = $(e.target).next();
            if (div.hasClass('closed')) {
                div.slideDown().removeClass('closed');
            } else {
                div.slideUp().addClass('closed');
            }
        });

        if ($('#meet-the-family li').length) $('#meet-the-family').slideDown();
    }


    /*
     *      Contact page
     */
    if ($('body#contact').length) {

        $('#formdiv input')
            .focus(function(){$(this).prev().hide();})
            .blur(function(){if (this.value == '') $(this).prev().show();});

        $('#formdiv textarea')
            .focus(function(){$(this).prev().hide();})
            .blur(function(){if (this.value == '') $(this).prev().show();});
            
        // Hide labels if each input has data
        $('#formdiv input').each(function(i,el){
            if ($(this).val() != '') $(this).prev().hide(); else $(this).prev().show();
        });
        if ($('#element_6').val() != '') $('p.element_6 label').hide(); else $('p.element_6 label').show();


        function initialize() {
            // Center of the map
            var latlng = new google.maps.LatLng(53.702317, -1.631458);
            // Map options
            var myOptions = {
                zoom        : 13,
                center      : latlng,
                mapTypeId   : google.maps.MapTypeId.ROADMAP,
                streetViewControl : true,
                scrollwheel : false
            };
            // Initialise the map
            var map = new google.maps.Map(document.getElementById("gmap"), myOptions);

            // Markers
            var aMarkers = new Array(
                ["Head Office &amp; Trade Showroom", 53.683183, -1.643873, "<strong>Head Office &amp; Trade Showroom</strong><br />Shackletons Ltd<br />Lucas House,<br />Weaving Lane,<br />Dewsbury<br />WF12 9QR<br />Tel: 01924 868470<br />Fax: 01924 868490"],
                ["Retail Showroom", 53.718732, -1.640982, "<strong>Retail Showroom</strong><br />511 Bradford Road<br />Batley<br />WF17 8LL<br />Tel: 01924 422943"]
            );
            createMarker(aMarkers[0]);
            createMarker(aMarkers[1]);

            function createMarker(mrkr) {
                var img = (mrkr[0]=='Retail Showroom') ? '/images/map-marker-dark.png': '/images/map-marker.png';

                // Create the bubble pop up
                var infowindow = new google.maps.InfoWindow({
                        content     : mrkr[3],
                        maxWidth    : 150
                });
                // Add the marker
                var marker = new google.maps.Marker({
                        position    : new google.maps.LatLng(mrkr[1], mrkr[2]),
                        title       : mrkr[0],
                        icon        : img,
                        animation   : google.maps.Animation.DROP
                });
                marker.setMap(map);
                // Add event listener for this marker
                google.maps.event.addListener(marker, 'click', function() {
                        infowindow.open(map,marker);
                });
            }
        }

        initialize();
    }

});


function loadScript(url, fn) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    $("head").append(script);
    if (fn) fn();
}
