/**
* This file requires the following Javascript files to be available:
* prototype.js
* effects.js (Scriptaculous)
**/

Event.observe(window, 'load', function() {

    // Clear the search field on click
    if ($('search-field'))
    {
        $('search-field').observe('click', function(){
            if($F('search-field') == 'Keyword search')
            {
                $('search-field').value = '';
            }
        });
    }

    // Essentials Banner
    if ($('harwin-splash') && $('images'))
    {
        var products = $('images')

        // Monitor for mouse movement on the products
        var productImages = products.childElements('li').collect(function(product) {
            var link = product.down('a')
            var image = link.down('img')
            var detail = product.down('em.detail').hide()

            link.observe('mouseover', function(event) {
                var linkElement = Event.element(event)
                linkElement.up('li').setStyle({zIndex: 10})
                detail.show()
                image.addClassName ('active')
                link.down('em.go').addClassName('active')

                productImages.each(function(productImage) {
                    if (!productImage.hasClassName('active'))
                    {
                        var source = productImage.src
                        var newSource = source.replace('.jpg', '-inactive.jpg')
                        productImage.src = newSource
                    }
                })
            })
            link.observe('mouseout', function(event) {
                var linkElement = Event.element(event)
                linkElement.up('li').setStyle({zIndex: 0})
                detail.hide()
                image.removeClassName ('active')
                link.down('em.go').removeClassName('active')

                productImages.each(function(productImage) {
                    if (!productImage.hasClassName('active'))
                    {
                        var source = productImage.src
                        var newSource = source.replace('-inactive.jpg', '.jpg')
                        productImage.src = newSource
                    }
                })
            })

            return image
        })
    }

    // Newsletter sign-up
    if($('newsletter'))
    {
        var newsletterForm = $('newsletter-form')

        // Replace the form with a newsletter link
        new Insertion.Before('newsletter', '<div id="newsletterx"><h3>Sign-up to the Harwin Newsletter</h3><p>Get all the latest connector developments and Datamate innovations straight to your Inbox.</p><a href="#" title="Sign up to the Harwin newsletter" id="newsletter-signup"><img src="/include/images/design/btn-signup.png" alt="Sign Up" class="floatright" /></a></div>')
        var newsletter = $('newsletter').hide(), newsletterLink = $('newsletter-signup')

        newsletterLink.observe('click', function(event) {
            newsletter.show()
            newsletterLink.blur()
            Event.stop(event)
        })

        // Set up the fields
        var fields = [
            {input: $('newsletter-name'), text: 'Enter your name'},
            {input: $('newsletter-email'), text: 'Enter you email'}
        ]

        fields.each(function(field) {
            field.input.previous('label').hide()
            field.input.setStyle({color: '#666'})
            field.input.value = field.text

            field.input.observe('focus', function(event) {
                if (field.input.value == field.text)
                {
                    field.input.value = ''
                    field.input.setStyle({color: '#000'})
                }
            })

            field.input.observe('blur', function(event) {
                if (field.input.value == '')
                {
                    field.input.value = field.text
                    field.input.setStyle({color: '#666'})
                }
            })
        })

        // Add the cancel button
        new Insertion.After('subscribe', '&nbsp;<a href="#" title="Cancel subscribing to the Harwin newsletter" id="cancel-subscribe">Cancel</a>')
        $('cancel-subscribe').observe('click', function(event) {
            newsletter.hide()
            Event.stop(event)
        })

        // Set up the subscribe button
        newsletterForm.observe('submit', function(event) {
            var errors = []
            var errorText = 'Oops! You missed some things out.'
            // Check the values
            fields.each(function(field) {
                if (field.input.id == 'newsletter-name')
                {
                    if(field.input.getValue() == '' || field.input.getValue() == field.text)
                    {
                        errors.push('Please enter your name')
                        return
                    }
                }
                else if (field.input.id == 'newsletter-email')
                {
                    if(field.input.getValue() == '' || field.input.getValue() == field.text)
                    {
                        errors.push('Please enter your email address')
                        return
                    }
                }
            })

            if (errors.length > 0)
            {
                // Display the errors
                errors.each(function(error) {
                    errorText += '\n' + error
                })

                alert(errorText)

                Event.stop(event)
            }
        })
    }

    // Harwin survey
    if ($('survey-link'))
    {
        var surveyLink = $('survey-link')
        surveyLink.observe('click', function(event) {
            window.open(Event.element(event).href)
            Event.stop(event)
        })
    }

    // If the 'highlights' element exists on the page then run the code
    if ($('highlights'))
    {
        // Create a new 'highlights' object
        var highlights = new Highlights('highlights', [$('product-spotlight'), $('app-spec'), $('application-focus')])
    }

    if ($('newsletters'))
    {
        var links = $('newsletters').getElementsBySelector('a')

        links.invoke('observe', 'click', function(event) {
            var link = Event.findElement(event, 'A')
            var window = new Aardvark.Windows()
            window.open(link.href, '', {width: '700px', height: '500px', scrollbars: 'yes'})
            Event.stop(event)
        })
    }

    if ($('harwin-splash') && $('Electronica 2008'))
    {
        var so = new SWFObject("/include/images/home-animation.swf", "Electronica 2008", "790", "160", "9", "");
        so.write("harwin-splash");
    }

    if ($('buy-now')) // Only do this if we're on a buy now product
    {
        // Do the form version
        if ($('buy-form'))
        {
            var buyForm = $('buy-form')
            var urlParams = $H({
                target: $F(buyForm.down('input[name="target"]')), // Target
                MID: $F(buyForm.down('input[name="MID"]')), // Harwin
                SKU: $F(buyForm.down('input[name="SKU"]')) // Part number
            })
            buyForm.down('input[type="image"]').observe('click', function(event) {
                if ($F(buyForm.down('select[name="CIC"]')) == '')
                {
                    alert('Please select your country first')
                }
                else
                {
                    urlParams.merge({CIC: $F(buyForm.down('select[name="CIC"]'))})

                    window.open(buyForm.action + '?' + urlParams.toQueryString())
                }

                Event.stop(event)
            })
        }

        // Do the link version
        if ($('buy-link'))
        {
            var buyLink = $('buy-link')
            buyLink.observe('click', function(event) {
                window.open(Event.element(event).href)
                Event.stop(event)
            })
        }
    }

    // GA conversion tracking
    if ($('_lpChatBtn'))
    {
        $('_lpChatBtn').observe('click', function(e){
            pageTracker._trackPageview('/liveperson');
        });
    }
    if ($('_lpChatBtn2'))
    {
        $('_lpChatBtn2').observe('click', function(e){
            pageTracker._trackPageview('/liveperson');
        });
    }
    if ($('newsletter-form'))
    {
        $('newsletter-form').observe('submit', function(e){
            pageTracker._trackPageview('/newsletter_signup');
        });
    }
    if ($('request_hack_GA'))
    {
        pageTracker._trackPageview('/sample_request');
    }
    if (window.user_signed_up)
    {
        pageTracker._trackPageview('/user_signup');
    }
    
    // fix: attempting to use on incorrect page
    if((document.location.toString().indexOf('/contact/requests')) != -1)
    {
        if ($('requestForm'))
        {
            $('requestForm').parentNode.observe('submit', function(e){
                pageTracker._trackPageview('/sample_request');
            });
        }
    }

    attachCollapsible('collapsible_0'); 

})

/**
* Highlight Class is used to create the interface on the homepage of the site.
* It take a list of blocks of content and creates a tabbed interface.
*
* @author Tom
**/
var Highlights = Class.create();
Highlights.prototype = {
    initialize: function(container, blocks)
    {
        this.container = container
        this.blocks = blocks

        this.errors = new Array()

        this.tabs = new Array()
        this.highlightZIndex = 1
        this.currentTab = ''
        this.lastTab = ''

        // Sets the 0,0 point to the parent element instead of the document
        Element.setStyle(this.container, {
            position: 'relative',
            marginTop: ''
        })

        this.blocks.each(function(block, index) {
            var element = $(block)

            // Don't position the first one
            if (index)
            {
                this.positionElement(element)
            }

            this.buildBlock(element)

            this.tabs.push(this.getTab(element))
            this.positionTab(this.tabs[index])
            this.createTabButton(this.tabs[index])
        }.bind(this))

        // Bring the first tab to the front
        this.activateTab(this.getTab($(this.blocks[0])))
    },

    positionElement: function(element)
    {
        Element.setStyle(element, {
            position: 'absolute',
            top: '0',
            left: '0'
        })

        return true
    },

    buildBlock: function(element)
    {
        Element.setStyle(element, {
            width: '100%'
        })

        return true
    },

    getTab: function(element)
    {
        var tab = $A(element.childNodes).find(function(child) {
            return child.className == 'tab'
        })

        return tab
    },

    positionTab: function(tab)
    {
        // Position the element above the container otherwise the event won't work
        Element.setStyle(tab, {
            position: 'absolute',
            top: '-27px'
        })

        // Don't move the first tab!
        if (this.tabs.length > 1)
        {
            // Holds the sum of the widths of each tab
            var margin = 0

            // Loop through the list of tabs adding their widths together
            this.tabs.each(function(tab, index) {
                var tabWidth = parseInt(Element.getStyle(tab, 'width').gsub('px', ''))

                // don't add the width of the current tab (that would just be silly!)
                if (index < this.tabs.length-1)
                {
                    margin += tabWidth + 1
                }
            }.bind(this))

            Element.setStyle(tab, {left: margin+'px'})
        }

        return margin
    },

    createTabButton: function(tab)
    {
        Event.observe(tab, 'click', function(event) {
            this.activateTab(tab)
        }.bind(this));
    },

    activateTab: function(tab)
    {
        var element = tab.parentNode

        Element.setStyle(element, {zIndex: this.highlightZIndex++})

        Element.setStyle(tab, {background: 'url("/images/homepage/' + element.id + '-on.gif")'})

        // If this isn't the first time a tab has been clicked
        if (this.currentTab != "")
        {
            //this.toggleBlocks()
            Element.setStyle(this.getTab(this.currentTab), {background: 'url("/images/homepage/' + this.currentTab.id + '-off.gif")'})
        }

        this.currentTab = element
    },

    toggleBlocks: function()
    {
        this.blocks.findAll(function(block) {
            return block.id != this.currentTab.id
        }.bind(this)).each(function(block) {
            block.id
        })
    }
}


function attachCollapsible(collapsible)
{

    var div = $(collapsible); 

    var heading = $("link-text");

    if(!$("link-text"))
    {
        return;
    }

    var contents = div.select('div')[0];

    // initially hide it
    div.addClassName('closed');
    contents.hide();

    // add an anchor at run time,
    // that way non-js users won't see anchor, but js users will
    // still be able to use their keyboard for it.
    heading.innerHTML = '<p class="collapsed"><a href="#">' + heading.innerHTML + '</a></p>';
    heading.firstDescendant().onclick = collapsibleOnClick(div, heading, contents);
}

/* function for generating event handler for anchor etc; returns function that returns bool */
function collapsibleOnClick(div, heading, contents)
{
    return function() {
        // clear the height; gets messy otherwise if a blind is already in progress
        // not perfect, but simple and huffy enough, and doesn't seem to be able to get into a bad state
        contents.style.height = '';

        // do we need to go up or down?
        if (div.hasClassName('closed')) {
            new Effect.BlindDown(contents,{duration:0.3, fps:100});
            Element.removeClassName(div,'closed')
            heading.firstDescendant('p').className = 'expanded';
            heading.firstDescendant('p').innerHTML = '<a href="#">Hide Technical Details (Matings, Alternatives and Technical Documents)</a>';

        } else {
            new Effect.BlindUp(contents,{duration:0.3, fps:100});
            Element.addClassName(div,'closed');
            heading.firstDescendant('p').className = 'collapsed';
            heading.firstDescendant('p').innerHTML = '<a href="#">View Technical Details (Matings, Alternatives and Technical Documents)</a>';
        }

        // event has been dealt with.
        return false;
    };
}


