$(document).ready(function () {
    //    $('#txtSpecialInstructions').textlimit('span.characters_remain', 200);
    $('#txtPhotoDescription').textlimit('span.characters_remain', 250);
    $('.limit_10').textlimit('', 10);
    $('.limit_500').textlimit('', 500);
    $('.limit_2000').textlimit('', 2000);
    $('.limit_5000').textlimit('', 5000);

    function setEqualHeight(columns) {
        var tallestcolumn = 0;
        columns.each(
       function () {
           currentHeight = $(this).height();
           if (currentHeight > tallestcolumn) {
               tallestcolumn = currentHeight;
           }
       }
     );
        columns.height(tallestcolumn);
    }

    //.animate({"color": hoverColour}, 350);  
    $("#tabs ul.ui-tabs-nav li:not(.ui-tabs-selected)").hover(function () {
        $(this).addClass('ui-state-active');
        //$(this).animate({backgroundPosition: '-20px 0px'}, 1000)
    }, function () {
        $(this).removeClass('ui-state-active');

    });


    // product detail overview - images carousel 
    $(".product_tabview #carousel_images").jcarousel({
        visible: 4,
        scroll: 1
    });

    // product detail overview - videos carousel 
    $(".product_tabview #carousel_videos").jcarousel({
        visible: 4,
        scroll: 1
    });

    // basic / advanced view switch
    var $avanced_view = $('.advanced_view');
    $('.compare_view_switch #advanced').bind('click', function () {
        if ($avanced_view.is(":hidden")) {
            $avanced_view.slideDown("slow");
        }
        $(this).removeClass().siblings('span').addClass('active');
    })
    $('.compare_view_switch #basic').bind('click', function () {
        $('.advanced_view').slideUp();
        $(this).removeClass().siblings('span').addClass('active');
    })

    // Image Gallery on Brands page brand_img_gallery  
    $('<div class="arrow_orange"></div>').insertAfter('.brand_img_gallery ul.gallery_thumbnails li.active img');

    $('.gallery_thumbnails').addClass('gallery_home'); // adds new class name to maintain degradability


    // Image Gallery - Photographer page
    $('ul.thumbnails li').append('<div class="icon_zoomin"></div>');

    var current_index = 1;
    var total_photos = $('#photos_galleryview ul.thumbnails li').size();
    var $photo_pagi = $('<div></div>').addClass('pages').text('Image ' + current_index + ' of ' + total_photos);
    $photo_pagi.appendTo('#photos_galleryview .desc');


    var $photo_caption = $('#photos_galleryview .desc span.caption');
    var init_caption = $('#carousel_gallery li.active') ? $('#carousel_gallery li.active img').attr('title') : '';
    $photo_caption.text(init_caption);

    $('#photos_galleryview .thumbnails').addClass('gallery_filmstrip'); // adds new class name to maintain degradability

    $('#photos_galleryview ul.gallery_filmstrip').galleria({
        history: false, // activates the history object for bookmarking, back-button etc.
        clickNext: false, // helper for making the image clickable
        insert: '#main_photo', // the containing selector for our main image
        onImage: function (image, caption, thumb) { // let's add some image effects for demonstration purposes
            // fade in the image & caption
            if (!($.browser.mozilla && navigator.appVersion.indexOf("Win") != -1)) { // FF/Win fades large images terribly slow
                image.css('display', 'none').fadeIn(1000);
            }
            caption.css('display', 'none').fadeIn(1000);
            // fetch the thumbnail container
            var _li = thumb.parents('li');
            // fade in active thumbnail
            thumb.addClass('selected');
            // add a title for the clickable image
            // image.attr('title', 'Next image >>');
            // get div
            var _div = _li.next('div.details');
            $('#description').html(_div.html());
        },
        onThumb: function (thumb) { // thumbnail effects goes here
            // fetch the thumbnail container
            var _li = thumb.parents('li');
            // if thumbnail is active, fade all the way.
            var _fadeTo = _li.is('.active') ? '1' : '0.3';
            thumb.bind('click', function () {
                _li.addClass('active').siblings('li').removeClass('active');
                var caption = $(this).attr('title');
                $photo_caption.empty().text(caption);

                current_index = _li.attr('jcarouselindex');
                $('#photos_galleryview .pages').text('Image ' + current_index + ' of ' + total_photos);
            });
        }
    });

    if ($('#photos_galleryview ul.gallery_filmstrip').length > 0) {
        var auto = setInterval(function () {
            $.galleria.next();
        }, 8000);
        $('#photos_galleryview ul.gallery_filmstrip li').click(function () {
            clearInterval(auto);
        });
    }

    $('#carousel_gallery').jcarousel();

    //
    var $panel_overlay = $('#photos_galleryview .panel_overlay');
    $(".thumbnails_slider", $panel_overlay).hide();
    //$('#photos_galleryview').delegate('.desc', $panel_overlay, 'hover',function() {
    $panel_overlay.hover(function () {
        $(".thumbnails_slider", $panel_overlay).fadeIn(500);
    }, function () {
        $(".thumbnails_slider", $panel_overlay).fadeOut(500);
    });

    //popular accessories details show/hide
    $(".popular_accessories div.item_list").hide();
    $(".popular_accessories").delegate("ul li .title", "click", function () {
        if ($('span', this).hasClass('icon_minus')) {
            $(this).siblings('div.item_list').slideUp();
            $('span.icon_minus', this).removeClass('icon_minus').addClass('icon_add');
        }
        else if ($('span', this).hasClass('icon_add')) {
            $(this).siblings('div.item_list').slideDown();
            $('span.icon_add', this).removeClass('icon_add').addClass('icon_minus');
        }

    });

    //Other galleries Carousel
    $('#carousel_otherGalleries').jcarousel();

    // input type=file styling
    $("input.input_upload").filestyle({
        image: "../images/btn_choose_file.gif",
        imageheight: 27,
        imagewidth: 122,
        width: 295
    });

    $("input.input_upload_photo").filestyle({
        image: "../images/btn_choose_file.gif",
        imageheight: 27,
        imagewidth: 122,
        width: 325
    });


    // Set equal height of cont_info and cont_ad for the Brands Templates
    //setEqualHeight($('.cols_514_248 .cont_info, .cols_514_248 .cont_ad'));

    // Colorbox - Report Abuse
    //    $(".popup_report_abuse").colorbox({
    //        title: false,
    //        opacity: 0.5,
    //        innerWidth: 356
    //    });

    // tabs
    $("#tabs").tabs();

    // new tabs
    setTab('.store_tabs');

    // check for current tab default
    loadTab('.store_tabs');

    // product asset carousel
    $('#thumbnails a.carouselimg').live('click', function () {
        var val = $(this).attr('rel');
        $("#imageview .active").fadeOut('fast', function () {
            $("#" + val).fadeIn('slow').addClass('active');
        });
        return false;
    });

    // product asset image carousel
    $('#ImageThumbnailsPanel a.carouselimg').live('click', function () {
        var val = $(this).attr('rel');
        $("#imageview .active").fadeOut('fast', function () {
            $("#" + val).fadeIn('slow').addClass('active');
        });
        return false;
    });

    // product asset video carousel
    $('#VideoThumbnailsPanel a.carouselvideo').live('click', function () {
        stopVideos();
        var val = $(this).attr('rel');
        $("#videoview .videoplayer").hide();
        $("#" + val).fadeIn('slow').show();
        return false;
    });

    // checkout details form "same as" functionality
    //    $('#chkShippingAddress').live('click', function () {
    //        if ($("#chkShippingAddress:checked").val() != null) {
    //            $("#txtShippingAddress1").val($("#txtBillingAddress1").val());
    //            $("#txtShippingAddress2").val($("#txtBillingAddress2").val());
    //            $("#txtShippingSuburb").val($("#txtBillingSuburb").val());
    //            $("#lstShippingState").attr("selectedIndex", $("#lstBillingState").attr("selectedIndex"));
    //            $("#txtShippingPostcode").val($("#txtBillingPostcode").val());
    //        }
    //    });

    //    // checkout details form "same as" functionality
    //    $('#chkSameDeliveryName').live('click', function () {
    //        if ($("#chkSameDeliveryName:checked").val() != null) {
    //            $("#txtShippingFirstName").val($("#txtFirstName").val());
    //            $("#txtShippingLastName").val($("#txtLastName").val());
    //        }
    //    });

    $('#mainSlider').MGCarousel({ banner_nav: '#mainSlider-nav', banner_nav_items: '#mainSlider-nav li', animType: 'fade', animSpeed: 500, rotationMilli: 5000, rotationResumeMilli: 8000, rotate: true });
    $('#brandSlider').MGCarousel({ banner_nav: '#brandSlider-nav', banner_nav_items: '#brandSlider-nav li', animType: 'fade', animSpeed: 500, rotationMilli: 5000, rotationResumeMilli: 8000, rotate: true });

    //    var $arrow_up_orange = $('<div class="arrow_orange"></div>');
    //    setTimeout(function () {
    //        $('#brandSlider').nivoSlider({
    //            pauseTime: 5000,
    //            pauseOnHover: false,
    //            controlNavThumbs: true,
    //            controlNavThumbsFromRel: true,
    //            effect: 'fade',
    //            slices: 1,
    //            afterLoad: function () {
    //                $arrow_up_orange.insertAfter('#brandSlider .nivo-controlNav .nivo-control img');
    //            }
    //        });
    //    }, 2000);

    var postcodeText = $('input.textfield').val();
    $('input.textfield').live('focusin', function () {
        if ($(this).val() == postcodeText) {
            $(this).val('');
        }
    });
    $('input.textfield').live('focusout', function () {
        if ($(this).val().length == 0) {
            $(this).val(postcodeText);
        }
    });

    // tooltip -- compare 
    $('.tTip').betterTooltip({ speed: 150, delay: 300 });
});

function loadTab(tabContainer) {
    var tabs = $(tabContainer).find('#tabsNew ul li');
    var hash = document.location.hash;
    if (tabs.length > 0 && hash.length > 0) {
        $(tabs).find('a[href=' + hash.replace("_","-") + ']').click();
        return false;
    }
}

function setTab(tabContainer) {
    var tabs = $(tabContainer).find('#tabsNew ul.tabs li');
    if (tabs.length > 0) {
        tabs.eq(0).addClass('active');
        var tabContents = $(tabContainer).find('.tab_cont');
        tabContents.hide();
        tabContents.eq(0).show()
        $(tabs).each(function (index) {
            var anchor = $(this).find('a').eq(0);
            anchor.bind('click', function () {
                //turn off old
                $("#tabsNew ul li[class='active']").removeClass('active');
                $(tabContainer).find('.tab_cont').hide();
                //turn on new
                tabs.eq(index).attr('class', 'active');
                var tabContents = $(anchor.attr('href'));
                if (tabContents.length > 0) {
                    tabContents.show();
                    if (anchor.attr('href') == '#tabs-where') {
                        loadLocation();
                    }
                }
                return false;
            })
        });
    }
}

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

