﻿var navSlideSpeed = 300;
var itemLimit = 5;
var bannerInterval;

$(document).ready(function() {
    setupCarousel();
    setupProductsNav();
    setupTabs();
    setupAutoClears();
    setupGiftWrap();
    setupButtonExpander();
    setupMiniBasketDropDown();
    setupDatePicker();
    setupCustomSelect();
    setupBanner();
    setupDropDownMore();
    setupForms();

    $("input[id*='txtPassword']").focus(function() {
        $("input[id*='radioYesPass']").trigger('click');
    });
    $('#ifcpop').dialog({ title: 'Interest Free Credit', resizable: false, autoOpen: false, modal: true, height: 370, width: 770 });
    $('#promotionCode').slideToggle(0);
    $('.basketInfoLink').hover(function() {
        $(this).after('<div class="basketPopout" rel="' + $(this).attr('rel') + '">' + $(this).attr('title') + '</div>');
        $(this).attr('title', '');

        var pos = $(this).position();
        var width = $(this).width();
        var left = pos.left + width - $('.basketPopout[rel="' + $(this).attr('rel') + '"]').width();

        $('.basketPopout[rel="' + $(this).attr('rel') + '"]').css({
            'position': 'absolute',
            'top': (pos.top + 20) + 'px',
            'left': left + 'px'
        });
    }, function() {
        $(this).attr('title', $('.basketPopout[rel="' + $(this).attr('rel') + '"]').html());
        $('.basketPopout[rel="' + $(this).attr('rel') + '"]').remove();
    });
    $('.infoIcon').hover(function() {
        $(this).after('<div class="infoBox" rel="' + $(this).attr('rel') + '">' + $(this).attr('title') + '</div>');
        $(this).attr('oldtitle', $(this).attr('title'));
        $(this).attr('title', '');

        var pos = $(this).position();
        var width = $(this).outerWidth();

        $('.infoBox[rel="' + $(this).attr('rel') + '"]').css({
            'position': 'absolute',
            'top': pos.top + 'px',
            'left': (pos.left + (width / 4 * 3) + 5) + 'px',
            'padding': '0 ' + width / 2 + 'px'
        });
    }, function() {
        $(this).attr('title', $(this).attr('oldtitle'));
        $(this).removeAttr('oldtitle');
        $('.infoBox[rel="' + $(this).attr('rel') + '"]').remove();
    });
    $('.manualbillingaddress').hide();
    $('.showmanualbillingaddress').click(function() {
        $('.manualbillingaddress').show();
        return (false);
    });
});

function setupForms() {
    $(window).keypress(function(e) {
        if (e.which == 13)
            return false;
        else
            return true;
    });
    $('.form').find('input').keydown(function(e) {
        if (e.which == 13) {
            if ($(this).parents('.form').find('.formEnter')[0].tagName.toLowerCase() == 'a')
                window.location = $(this).parents('.form').find('.formEnter').attr('href')
            $(this).parents('.form').find('.formEnter').trigger('click');
            return false;
        }
    });
}

function CnCPopout() {
    ClickAndCollect.GetStores($('input[id*="CnCPostcode"]').val(), OnGetStoresSucceed, OnGetGetStoresFail);
}

function OnGetStoresSucceed(msg) {
    var jsonResponse = JSON.parse(msg);
    var i = 0;
}

function OnGetStoresFail(msg) {
    var i = 0;
}

function setupCarousel() {
    if (typeof $('.carousel').jCarouselLite == 'function') {
        $('.carousel').jCarouselLite({
            btnNext: '.nextBut',
            btnPrev: '.prevBut',
            auto: 2000,
            speed: 1200,
            circular: true,
            scroll: 2,
            visible: 3
        });
    }
}

function setupBanner() {
    $('.banner').each(function() {
        var thisBanner = $(this);

        $(this).append('<div class="bannerControl" style="position: relative; width: 100%; height: ' + $(this).children('.item:first').height() + 'px;"><ul style="z-index:3"></ul></div>');
        $(this).children('.item').appendTo('.banner > .bannerControl');

        var i = 1;
        $(this).children('.bannerControl').children('.item').each(function() {
            $(this).parent().children('ul').append('<li><a rel="' + i + '">' + i + '</a></li>');
            $(this).parent().children('ul').children('li').children('a[rel="' + i + '"]').click(function() {
                clearInterval(bannerInterval);
                changeBanner(thisBanner, $(this).attr('rel'));
                bannerInterval = setInterval(function() { changeBanner(thisBanner, null); }, 4000);
            });
            $(this).css({
                'position': 'absolute',
                'top': '0px',
                'left': '0px',
                'width': '950px',
                //'width': $(this).parent().width() + 'px',
                'height:': $(this).parent().height() + 'px'
            }).fadeOut(0).attr('rel', i++);
        });

        $(this).children('.bannerControl').children('ul').children('li').children('a:first').attr('class', 'selected');

        $(this).children('.bannerControl').children('.item:first').fadeIn(0).css('zIndex', 1);
        $(this).attr('currentItem', 1);

        bannerInterval = setInterval(function() { changeBanner(thisBanner, null); }, 4000);
    });
}

function changeBanner(thisBanner, nextItem) {
    var prevItem = $(thisBanner).children('.bannerControl').children('.item[rel="' + $(thisBanner).attr('currentItem') + '"]');

    if (nextItem == null) {
        if ($(thisBanner).attr('currentItem') == $(thisBanner).children('.bannerControl').children('.item:last').attr('rel'))
            $(thisBanner).attr('currentItem', 1);
        else
            $(thisBanner).attr('currentItem', parseInt($(thisBanner).attr('currentItem')) + 1);
    }
    else {
        if (nextItem > parseInt($(thisBanner).children('.bannerControl').children('.item:last').attr('rel')) || nextItem < 1)
            return;
        else
            $(thisBanner).attr('currentItem', nextItem);
    }

    $(thisBanner).children('.bannerControl').children('ul').children('li').children('a.selected').removeAttr('class');
    $(thisBanner).children('.bannerControl').children('ul').children('li').children('a[rel="' + $(thisBanner).attr('currentItem') + '"]').attr('class', 'selected');
    $(prevItem).fadeOut(1000);
    $(thisBanner).children('.bannerControl').children('.item[rel="' + $(thisBanner).attr('currentItem') + '"]').css('zIndex', 2).fadeIn(1000, function() {
        $(thisBanner).css('zIndex', 1);
    });
}

function setupProductsNav() {
    // setup closing on click
    $('.leftNav .item-level1 > a').click(function() {
        $(this).parent().children('ul').slideToggle(navSlideSpeed, function() {
            var link = $(this).parent().children('a');

            if (link.css('backgroundPosition') == '0% 0%')
                link.css('backgroundPosition', '0% 100%');
            else
                link.css('backgroundPosition', '0% 0%');
        });
        return false;
    });

    // if a section has more than itemLimit then create a more button and cut items off at itemLimit
    $('.leftNav .item-level1 > ul').each(function() {
        var size = $(this).children('li').size();

        if (size > itemLimit) {
            $(this).append('<ul></ul>');

            var items = new Array();

            for (var i = size; i > itemLimit - 1; i--)
                items.push($(this).children('li').eq(i));

            items.reverse();

            for (var i = 0; i < items.length; i++)
                $(this).children('ul').append(items[i]);

            $(this).children('ul').slideUp(0);

            $(this).children('li').eq(0).clone().appendTo($(this));
            $(this).children('li').eq(itemLimit).html('<a href="#">More...</a>').click(function() {
                $(this).parent().children('ul').slideToggle(navSlideSpeed);
                if ($(this).children('a').html() == 'More...')
                    $(this).children('a').html('Less...');
                else
                    $(this).children('a').html('More...');

                return false;
            });
        }
    });

    // close initially closed items
    $('.leftNav .closed > ul').slideUp(0);

}

function setupDropDownMore() {
    $('li.more > a').click(function() {
        $(this).parent().children('ul').slideToggle(navSlideSpeed);
        return false;
    });
    
    $('li.more').append('<a href="#" class="moreBut">More...</a>');
    $('li.more > .moreBut').click(function() {
        $(this).parent().children('ul').slideToggle(navSlideSpeed, function() {
            if ($('li.more > a').hasClass('moreBut'))
                $('li.more > a').removeClass('moreBut').addClass('lessBut').html('Less...');
            else
                $('li.more > a').removeClass('lessBut').addClass('moreBut').html('More...');
        });
        return false;
    });

    $('li.more > ul').css('display', 'none').slideUp(0);
}

function setupTabs() {
    if (typeof $('.tabs').tabs == 'function') {
        $(".tabs").tabs();
        $(".tabs .panel-container").css({ height: 'auto', overflow: 'visible', paddingRight: '35px' })
        $(".tabs .tabs-panel").removeClass('tabs-panel');
        $(".tabs .tabContent").removeClass('tabContent');
    }
}

function setupAutoClears() {
    $(".autoClear").focus(function() {
        if (!$(this).attr('originalVal')) {
            $(this).attr('originalVal', $(this).val());
            $(this).val('');
        }
    }).blur(function() {
        if ($.trim($(this).val()).length == 0) {
            $(this).val($(this).attr('originalVal'));
            $(this).removeAttr('originalVal');
        }
    });
}

function setupGiftWrap() {
    if ($("table#basket").length > 0) {

        $("table#basket tr.item td").css('border-bottom', '1px solid #666');

        $("td.giftwrap select").each(function() {
            if ($(this).val() != 'yes') {
                $(this).parent().parent().children().css('border-bottom', '1px solid #666');
                $(this).parent().parent().next().css('display', 'none');
            }
            else
                $(this).parent().parent().children().css('border-bottom', 'none');
        });
        
        /*if ($("td.giftwrap select").val() != 'yes') {
            $("table#basket tr.item td").css('border-bottom', '1px solid #666');
            $("tr.giftwrap").css('display', 'none');
        }*/
        
        $("tr.giftwrap td textarea").keypress(function() {
            if ($(this).val().length >= 50)
                $(this).val($(this).val().substr(0, 50));
        });
        $("td.giftwrap select").change(function() {
            var parent = $(this).parent().parent();
            if ($(this).val() == 'yes') {
                $(parent).children('td').css('border-bottom', 'none');
                $(parent).next('tr.giftwrap').removeAttr('style');
            }
            else {
                $(parent).children('td').css('border-bottom', '1px solid #666');
                $(parent).next('tr.giftwrap').css('display', 'none');
            }
        });
    }
}

function setupButtonExpander() {
    $(".bannerExpandArea").hide();
    $(".bannerExpandBut").click(function() {

        if ($(this).attr('rel') != undefined)
            $(".bannerExpandArea[rel=" + $(this).attr('rel') + "]").slideToggle(500);
        else
            $(".bannerExpandArea").slideToggle(500);
        return (false);
    });
}

function setupMiniBasketDropDown() {
    if ($("#miniBasketDropdown").length > 0) {
        $("#shoppingBag").hover(function() {
            $("#miniBasketDropdown").slideDown(200);
        }, function() {
            $("#miniBasketDropdown").slideUp(200);
        });
    }
}

function showifcbox() {
    var ifchtml = $('#credit').html();
    $('#ifcMatrix').html(ifchtml);
    $('#ifcpop').dialog('open');
    $('#ifcpop').parent().css('overflow', 'visible');
}

function wishlist(productid, val) {
    cookiejar(productid, val, 'wishlist');
    document.location = "/wishlist.aspx";
}

function compare(productid, val) {
    cookiejar(productid, val, 'productcompare');
}

function cookiejar(productid, val, cookiename) {
    var pitems = '';
    if ($.cookie(cookiename) != null) { pitems = $.cookie(cookiename); }
    if (val) {
        if (pitems != '') {
            $.cookie(cookiename, pitems + ',' + productid, {path: '/', expires: 365});
        } else {
            $.cookie(cookiename, productid, { path: '/', expires: 365 });
        }
    } else {
        if (pitems != '') {
            var plist = pitems.split(',');
            var nplist = '';
            for (i = 0; i < plist.length; i++) {
                if (plist[i] != productid) {
                    if (nplist != '') {nplist = nplist + ','; }
                    nplist = nplist + plist[i]; 
                }
            }
            $.cookie(cookiename, nplist, { path: '/', expires: 365 });
        }
    }
}

function setupMap(map_id, markers) {
    var options = {
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map_canvas = document.getElementById(map_id);
    var map = new google.maps.Map(map_canvas, options);
    var bounds = new google.maps.LatLngBounds();
    
    for(var i = 0; i < markers.length; i++)
    {
        var marker = new google.maps.Marker({
            title       : markers[i][0],
            position    : new google.maps.LatLng(markers[i][1], markers[i][2]),
            clickable   : true
        });

        google.maps.event.addListener(marker, 'click', function() {
            document.location = $('a[title="' + this.getTitle() + '"]').attr('href');
        });
        
        marker.setMap(map)
        bounds.extend(marker.getPosition());
    }

    if (markers.length > 1) {
        map.fitBounds(bounds);
        google.maps.event.addListener(map, 'bounds_changed', function(event) {
            if (map.getZoom() > 16)
                map.setZoom(16);
            google.maps.event.clearListeners(map, 'bounds_changed');
        });
    }
    else
        map.setZoom(16);
    map.setCenter(bounds.getCenter());
}

var storeIDS = new Array();
var addressS = new Array();

function getPoints(storeID, address) {
    storeIDS.push(storeID);
    addressS.push(address);
}

function getLoc() {
    if (storeIDS.length > 0) {
        var storeID = storeIDS[0];
        var address = addressS[0];
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': address }, function(results, status) {
            if (results == null || results[0] == undefined) {
                $("#storeLocationMap").append('-- ' + status + ' Unable to get data for ID: ' + storeID + ' - ' + address + '<br/>');
            }
            else
                $("#storeLocationMap").append('UPDATE Stores SET lat=' + results[0].geometry.location.lat() + ', lng=' + results[0].geometry.location.lng() + ' WHERE storeID=' + storeID + '<br/>');
        });
        storeIDS.splice(0, 1);
        addressS.splice(0, 1);
    }
    else {
        clearInterval(theInterval);
        alert('done');
    }
}

function setupDatePicker() {
    if (typeof $('.datePicker').datePicker == 'function') {
        if ($('.datePicker').hasClass('dob')) {
            $('.datePicker').datePicker({
                startDate: '01/01/1850',
                endDate: (new Date()).asString()
            });
        }
        else {
            $('.datePicker').datePicker().val(new Date().asString());
            if ($('#desiredTime').length > 0) {
                $('.datePicker').bind('dateSelected', function(e, selectedDate) {
                    $('#desiredTime').html('');

                    setDesiredTimes(selectedDate);
                });
                setDesiredTimes($('.datePicker').dpGetSelected()[0]);
            }
        }
    }
}

function setupCustomSelect() {
    if (typeof $('.customselect').selectbox == 'function')
        $(".customselect").selectbox();
}

function checkSize() {
    var options = $("select[ID*='ddlRingSizes']");
    var items = $("select[ID*='ddlItems']");
    
    if (options.length > 0) {
        var actualValue = options.val();
        if(options.val() == "Ring Size") {
            alert("Please select a ring size");
            return false;
        }
        else {
            return true;
        }        
    }
    else {
        if (items.length > 0) {
            if (items.val() == "Ring Size") {
                alert("Please select a ring size");
                return false;
            }
            else {
                return true;
            }
        }
        else {
            return true;
        }
    }
}

function setDesiredTimes(selectedDate) {    }

function NewletterSignup() {
    $.cookie('newsletteremail', $('#newslettersignupemail').val(), { path: '/', expires: 1 });
    document.location = '/newsletter_signup';    
}
