/**
 * @name jquery.unescape.js
 * @description A simple function which unescapes the HTML.
 * @author Artur Barseghyan
 * @version 1.0 alpha
 * @example
 *          $('textarea').unescape();
 *          $.unescape('&lt;a href=&quot;http://delusionalinsanity.com&quot;&gt;Delusional Insanity&lt;/a&gt;');
 */
(function($) {
    $.fn.unescape = function() {
       return $(this).html($.unescape($(this).html()));
    }

    /**
     * @param string html - HTML string to unescape.
     * @return string - unescaped HTML string.
     */
    $.unescape = function(html) {
        var htmlNode = document.createElement('div');
        htmlNode.innerHTML = html;
        if (htmlNode.innerText) {
            return htmlNode.innerText; // IE
        }
        return htmlNode.textContent; // FF
    }
})(jQuery);

// JavaScript Document

$(document).ready(function () {

    var $toggle = $('span#firstCheckbox input');
    var $checkboxes = $('.checkBoxList').find(':checkbox');

    $('span#firstCheckbox input').click(function () {

        $toggle.change(function () {
            if (this.checked) {
                $checkboxes.attr('checked', 'checked');
            } else {
                $checkboxes.removeAttr('checked');
            }
        });
    });

    $checkboxes.change(function () {
        if (this.checked) {
            if (($checkboxes.length - 1) == $checkboxes.filter(':checked').length) {
                $toggle.attr('checked', 'checked');
            }
        } else {
            $toggle.removeAttr('checked');
        }
    }).eq(0).trigger('change');

});

$(document).ready(function () {

    $('#newsTicker').cycle({
        fx: 'scrollUp',
        speed: 2500,
        timeout: 4000
    });

    $('#ctl00_MainContent_btnPrev').attr('href', '#');
    $('#ctl00_MainContent_btnNext').attr('href', '#');

});

//$(document).ready(function(){
window.onload = function () {
    if ($('#slideshow').length > 0) {
        var slideshowImages = '';

        var imagesLength = imagesArray.length;
        var imgCount = 0;
        for (i = 1; i < imagesLength; i++) {
            var img = new Image();

            img.onload = function () {
                imgCount++;
                if (imgCount >= imagesLength - 1) {
                    doSlideshow();
                };
            };

            var theAnchor = $('<a/>').attr('href', imagesArray[i].url);
            $(img)
                    .css({ position: 'relative', left: '-10000px' })
                    .attr({ src: imagesArray[i].src, alt: imagesArray[i].alt })
                    .appendTo('#slideshow')
                    .wrap('<li></li>')
                    .wrap(theAnchor);

        };

        function doSlideshow() {
            $('#slideshow li a img').css({ left: '0px' });

            $('#slideshow').cycle({
                fx: 'scrollVert',
                speed: 500,
                timeout: 7000,
                next: '#ctl00_MainContent_btnPrev',
                prev: '#ctl00_MainContent_btnNext'
            });
        }
    }
};



$(document).ready(function () {
    $(".calendar").datepicker({
        showOn: 'button',
        buttonImage: '/images/calendar.gif',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        yearRange: '1940:2020' 
    });
});


$(document).ready(function () {
    $("<br />").insertBefore(".xformvalidator");
});


$(document).ready(function () {
    $('.formInner input, .formInner select, .formInner textarea').focus(function () {
        $(this).addClass("formFocus");
    });
    $('.formInner input, .formInner select, .formInner textarea').blur(function () {
        $(this).removeClass("formFocus");
    });
});


$(document).ready(function () {

    $('#productThumbs a').click(function (e) {
        e.preventDefault();
    });

    $('#productThumbs img').click(function () {

        var largePath = $(this).attr('src').replace('.jpg', '_large.jpg');
        var largeAlt = $(this).attr('alt');

        if (!$(this).hasClass('highlight')) {
            $(this).parent().parent().parent().find('.highlight').attr('class', '').stop().animate({ opacity: 0.5 }, 10);
            $(this).addClass('highlight');
        }

        $("#ctl00_ctl00_MainContent_HeaderColumn_imgTopFeature")
            .attr({ src: largePath, alt: largeAlt })
            .parent()
            .attr({ href: $(this).parent().attr('href') });
    });

    $('ul#productThumbs li:first-child img').click();	

    $('ul#productThumbs li img').each(function () {

        if (!$(this).parent().parent().is('ul#productThumbs li:first-child')) {
            $(this).animate({ opacity: 0.5 }, 1);
        }

        $(this).hover(function () {
            $(this).stop().animate({ opacity: 1.0 }, 100);
        }, function () {
            if (!$(this).hasClass('highlight')) {
                $(this).stop().animate({ opacity: 0.5 }, 10);
            }
        });
    });
});

$(document).ready(function () {
    $('.idTabs').createTabs();
    $('#changeCountry select').customDropdown();
});

// added to GA asset downloads
$(document).ready(function () {
    $('a').each(function () {
        var href = $(this).attr('href');
        // add more as needed
        if (href != null) {
            var isDoc = href.match(/\.(?:doc|eps|jpg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)($|\&|\?)/);
            if (isDoc) {
                $(this).click(function () {
                    // call google GA tracking
                    _gaq.push(['_trackPageview', href]);
                    return true;
                });
            }
        }
    });
});

/** Custom jQuery Plugins **/
(function ($) {
    /** Create Tabs plugin **/
    $.fn.createTabs = function (options) {
        var opts = $.extend({}, $.fn.createTabs.defaults, options);
        var current, count = 0;

        return this.each(function () {
            $(this).find('a').each(function () {
                var tabArea = $($(this).attr('href'));

                if (!$(this).parent().is('ul > li:first-child')) {
                    tabArea.hide();
                } else {
                    $(this).attr('class', 'selected');
                }

                $(this).click(
                    function () {
                        var tabId = $(this).attr('href');
                        if ($(tabId).css('display') == 'block') return false;
                        else {
                            //current.hide(); 
                            $(this).parent().parent().parent().parent().find("div.tabBox:visible").css('display', 'none');
                            current = $(tabId).css({ display: 'block' });
                            $(this).parent().parent().find('.selected').attr('class', '');
                            $(this).attr('class', 'selected');
                        }
                        return false;
                    }
                );
                count++;
            });
        });
    }

    $.fn.createTabs.defaults = {}

    $.fn.customDropdown = function (options) {
        var opts = $.extend({}, $.fn.customDropdown.defaults, options);
        return this.each(function () {

            var selectBox = $(this);

            if (selectBox.prev().attr('class') == 'sliderDropdown') selectBox.prev().remove();
            
            var selected = $('<dt rel="' + $(this).val() + '"><span rel="' + $(this).val() + '">' + $(this).find('option:selected').html() + '</span></dt>')
                       .css({ width: opts.width + 'px' })
                        .hover(
                            function () { $(this).addClass(opts.selectHoverClass); },
                            function () { $(this).removeClass(opts.selectHoverClass); }
                        );
                      
            var options = $(this).find('option');

            var newSelect = $('<dl class="' + opts.classname + '" class="newDropdown-' + $(this).attr('id') + '"></dl>')
                        .click(
                            function (e) {
                                var newOptions = $(this).find('ul');
                                var optionsHolder = $(this).find('dd');

                                if (newOptions.is(':visible')) newOptions.slideUp('fast', function () { optionsHolder.hide(); });
                                else {
                                    optionsHolder.show();
                                    var aboveY = e.clientY;
                                    var belowY = $(window).height() - e.clientY;

                                    var maxHeight = (aboveY > belowY) ? aboveY : belowY;
                                    optionsHolder.css({ height: 'auto', overflow: 'auto' });

                                    if (aboveY > belowY) optionsHolder.css({ bottom: opts.selectHeight + 'px', top: 'auto' });
                                    else optionsHolder.css({ top: opts.selectHeight + 'px', bottom: 'auto' });
                                    newOptions.slideDown('fast', function () { if (optionsHolder.height() > maxHeight) optionsHolder.css({ height: (maxHeight - 20) + 'px', overflowY: 'scroll', overflowX: 'hidden' }); });
                                }
                            }
                        );
            var newList = $('<ul></ul>').hide();
            options.each(function () {
                var theOption = $(this);
                var newLi = $('<li rel="' + $(this).val() + '">' + $(this).html() + '</li>')
                            .css({ height: opts.optionHeight + 'px' })
                            .hover(
                                function () { $(this).addClass(opts.optionHoverClass); },
                                function () { $(this).removeClass(opts.optionHoverClass); }
                            )
                            .click(function () {
                                var htmlVal = $(this).html();
                                var elemVal = $(this).attr('rel');
                                if(selectBox.find("option[value='" + elemVal + "']").attr('Selected') != 'selected')
                                {
                                    $(this).parent().find('.selected').removeClass(opts.selectedClass); //remove selected class from all selected classes
                                    htmlVal = $(this).addClass(opts.selectedClass).html(); //store the value of the selected element and add selected class

                                    //Change the value of the selected element being shown when options are closed
                                    var dl = $(this).parent().parent().parent();
                                    dl.find('dt span').html(htmlVal); 

                                    //var theVal = selectBox.find("option:contains('"+htmlVal+"')").html();
                                    //selectBox.children('option:selected').removeAttr('Selected'); //remove all selected
                                    selectBox.val(elemVal); //select the appropriate option
                                    selectBox.change(); //trigger change to the selectbox
                                    //dl.next().change();
                                }
                            });
                newList.append(newLi);
            });
            var dd = $('<dd></dd>').append(newList).css({ width: opts.width + 'px' }); //.css({top:opts.selectHeight + 'px'});
            newSelect.append(selected).append(dd);
            $(this).css({ display: 'none' }).before(newSelect);
        });
    }
    $.fn.customDropdown.defaults = {
        classname: 'sliderDropdown',
        optionHoverClass: 'hover',
        selectHoverClass: 'hover',
        selectedClass: 'selected',
        selectHeight: 21,
        optionHeight: 21,
        width: 100
    }
})(jQuery);

$(document).ready(function () { // a little bit of script to tidy the lefnav up a little
    $('#leftNav ul li a.navOnTop').parent().prev().find('a').css('background', 'none');
});

//Fancies up the tables
$(function () {
    var ft = $('.fancyTable');
    //Row Striping
    ft.find('tr:odd').addClass('alt');

    //Row Hover state
    //ft.find('tr').hover(
       // function () {
               // $(this).removeClass('alt');
                //$(this).addClass('hover');
                //$(this).find('.shade').next().addClass('last'); //The cell after the 'shade' cell should have an arrow in it
                //$(this).find('th').parent().parent().find('tr:first').removeClass('hover'); //dont apply hover effects to the first row if it contains a header cell.
        //},
        //function () {
            //$(this).parent().find('tr:odd').addClass('alt'); //restores the table striping
            //$(this).removeClass('hover');
        //}
    //);

});


// Mega Menus
$(function () {
    // if javascript is enabled, disable the css hover
    $('#topNav').removeClass('noJs');
    var parentLi = $('#topNav ul li');
    // Remove the border on the last column for IE6 users
    $('#topNav ul li .megaMenu li:last-child').css('border', 0);
    // Show/hide the menu after a brief delay
    var hoverConfig = {
        over: function () {
            $(this).find('.megaMenu').fadeIn(100, function () {
                // Set all the internal items to same height
                var tallest = 0, cols = $(this).parent().find("div ul li");
                $(this).parent().find("div ul li").each(function (i, el) {
                    tallest = ($(el).height() > tallest) ? $(el).height() : tallest;
                });
                cols.css('height', tallest + 'px');
            });
        },
        timeout: 500,
        out: function () { $(this).find('.megaMenu').fadeOut(100); }
    };
    parentLi.hoverIntent(hoverConfig);
});
