var tdWidth;
var tdCount;
var scroll = 2;
var mL = 0;
var vis = 4;
var inMotion = false;

$(document).ready(function() {
    if(typeof($('.tabs').tabs) == 'function')
        $('.tabs').tabs();

    setupShowMapCheckout();
    
    if(typeof($('#ifcpop').dialog) == 'function')
        $('#ifcpop').dialog({ title: 'Interest Free Credit', resizable: false, autoOpen: false, modal: true, width: 770 });
    $('#cncclose').click(function() { $('#cncpop').css('display', 'none'); $('#tempMapContainer').remove(); $('#overlay').remove(); return (false); });
    $('a[id*="lnkCollectFromStore"]').click(function() {
        if (!$(this).hasClass('collecting')) {
            confirmMessage('If you choose to collect your order from one of our stores giftwrap will be removed from your items as this will be handled in store.', function() {
                $('input[id*=hiddenStoreID]').val($('input[name="collectionStore"]:checked').val());
                $('#cncclose').trigger('click');
            }, function() {
                $('input[id*=hiddenStoreID]').val('');
                $('#cncclose').trigger('click');
            });
            return false;
        }
        else {
            $('input[id*=hiddenStoreID]').val($('input[name="collectionStore"]').val());
        }
    });

    setupGiftWrap();
    createCarousel($(".carousel"));

    $('.prodDetails').hide();
    $('.prodImg').hover(function() {
        $(this).next().show();
    }, function() {
        $(this).next().hide();
    });

    setupDatePicker();
    setupBanner();
    setupMiniBasketDropDown();
    setupAutoClears();
    setupForms();

    $("input[id*='txtPassword']").focus(function() {
        $("input[id*='radioYesPass']").trigger('click');
    });

    $('.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();
    });
    
	//Select all anchor tag with rel set to tooltip
	$('a[rel=tooltip]').mouseover(function(e) {
		
		//Grab the title attribute's value and assign it to a variable
		var tip = $(this).attr('title');	
		
		//Remove the title attribute's to avoid the native tooltip from the browser
		$(this).attr('title','');
		
		//Append the tooltip template and its value
		$(this).append('<div id="tooltip"><div class="tipBody">' + tip + '</div></div>');		
		
	}).mousemove(function(e) {
	
		//Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
		$('#tooltip').css('top', e.pageY + 10 );
		$('#tooltip').css('left', e.pageX + 20 );
		
	}).mouseout(function() {
	
		//Put back the title attribute's value
		$(this).attr('title',$('.tipBody').html());
	
		//Remove the appended tooltip template
		$(this).children('div#tooltip').remove();
		
	});     

});

function showifcbox() {
    var ifchtml = $('#credit').html();
    $('#ifcMatrix').html(ifchtml);
    $('#ifcpop').dialog('open');
    $('#ifcpop').parent().css('overflow', 'visible');
}

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 setupMiniBasketDropDown() {
    if ($("#miniBasketDropdown").length > 0) {
        $("#shoppingBasket").hover(function() {
            $("#miniBasketDropdown").slideDown(200);
        }, function() {
            $("#miniBasketDropdown").slideUp(200);
        });
    }
}

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); }, 6000);
    });
}

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', 0).fadeIn(1000, function() {
        $(thisBanner).css('zIndex', 1);
    });
}

function setupDatePicker() {
    if (typeof $('.datePicker').datePicker == 'function') {
        if ($('.datePicker').hasClass('dob')) {
            $('.datePicker').datePicker({
                startDate: '01/01/1850',
                endDate: (new Date()).asString()
            });
        }
    }
}

function createCarousel(el) {
    tdCount = $(el).find('tr:first').children('td').length * 2;
    
    if (tdCount > 8) {
        $(el).parent().children('.nextBut').show();
        $(el).parent().children('.prevBut').show();
        $(el).parent().children('.nextBut').click(function() { carouselPrev(el) });
        $(el).parent().children('.prevBut').click(function() { carouselNext(el) });
    }
    else {
        $(el).parent().children('.nextBut').hide();
        $(el).parent().children('.prevBut').hide();
    }
    
    $(el).before('<div class="carouselContainer" style="width:' + $('.carousel').width() + 'px;"></div>');
    $(el).appendTo('.carouselContainer');

    tdWidth = $(el).find('td').width();
    
    $(el).find('tr').each(function() {
        $(this).html($(this).html() + $(this).html());
    });
    $(el).width(tdWidth * tdCount);
}

function carouselNext(el) {
    if (!inMotion) {
        mL = mL + (tdWidth * scroll);
        if (mL > 0) {
            var newML = -(tdCount / 2 * tdWidth);
            $(el).css('marginLeft', newML);
            mL = newML + (tdWidth * scroll);
        }

        $(el).animate({
            'marginLeft': mL
        }
    , 1000, null, function() { inMotion = false; });
        inMotion = true;
    }
}

function carouselPrev(el) {
    if (!inMotion) {
        mL = mL - (tdWidth * scroll);
        if (mL < -(tdCount / 2 * tdWidth)) {
            $(el).css('marginLeft', 0);
            mL = -tdWidth * scroll;
        }

        $(el).animate({
            'marginLeft': mL
        }
        , 1000, null, function() { inMotion = false; });
        inMotion = true;
    }
}

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 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');
        }
    });
}

function setupGiftWrap() {
    if ($("table#basket").length > 0) {
        $('#promotionCode').slideToggle(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 setupMap(map_id, markers, options) {
    if (options == undefined)
        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
        });

        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() > 14)
                map.setZoom(14);
            google.maps.event.clearListeners(map, 'bounds_changed');
        });
    }
    else
        map.setZoom(14);
    map.setCenter(bounds.getCenter());
}

function CnCPopout(postcodeID) {
    if ($.trim($('#' + postcodeID).val()).length > 0 && $('#' + postcodeID).val() != 'Enter Postcode') {
        $('#cncpop').before('<div id="overlay"></div>');
        $('#overlay').css({
            'background': '#000'
        });
        $('#overlay').fadeTo(0, 0.5);
        ClickAndCollect.GetStores($('#' + postcodeID).val(), OnGetStoresSucceed, OnGetStoresFail);
    }
    else
        alert('Please enter a postcode.');
    return false;
}
function OnGetStoresSucceed(stores) {
    if (stores[0].StoreID > 0) {
        $('#CnCStore1').html('<strong>' + stores[0].StoreName + '</strong><br/><br/><a href="#" class="showmap" title="' + stores[0].StoreName + '" lat="' + stores[0].Latitude + '" lng="' + stores[0].Longitude + '" address="' + stores[0].Address + stores[0].Postcode + '" tel="' + stores[0].Telephone + '" fax="' + stores[0].Fax + '">Show map</a><br/><strong>' + stores[0].StoreDistance + ' miles</strong><br/><br/><input type="radio" name="collectionStore" value="' + stores[0].StoreID + '" checked />');
        $('#CnCStore2').html('<strong>' + stores[1].StoreName + '</strong><br/><br/><a href="#" class="showmap" title="' + stores[1].StoreName + '" lat="' + stores[1].Latitude + '" lng="' + stores[1].Longitude + '" address="' + stores[1].Address + stores[1].Postcode + '" tel="' + stores[1].Telephone + '" fax="' + stores[1].Fax + '">Show map</a><br/><strong>' + stores[1].StoreDistance + ' miles</strong><br/><br/><input type="radio" name="collectionStore" value="' + stores[1].StoreID + '"/>');
        $('#CnCStore3').html('<strong>' + stores[2].StoreName + '</strong><br/><br/><a href="#" class="showmap" title="' + stores[2].StoreName + '" lat="' + stores[2].Latitude + '" lng="' + stores[2].Longitude + '" address="' + stores[2].Address + stores[2].Postcode + '" tel="' + stores[2].Telephone + '" fax="' + stores[2].Fax + '">Show map</a><br/><strong>' + stores[2].StoreDistance + ' miles</strong><br/><br/><input type="radio" name="collectionStore" value="' + stores[2].StoreID + '"/>');

        //TODO: available

        $('#CnCAvailability1').html('Available for collection<br/><span class="available">' + stores[0].CollectionDate + '</span>');
        $('#CnCAvailability2').html('Available for collection<br/><span class="available">' + stores[1].CollectionDate + '</span>');
        $('#CnCAvailability3').html('Available for collection<br/><span class="available">' + stores[2].CollectionDate + '</span>');

        $('#cncpop').css({
            'display': 'block'
        });

        $('.showmap').click(function() {
            var storeDetails = '<strong>' + $(this).attr('title') + '</strong><br/><br/>' + $(this).attr('address');
            if ($(this).attr('tel').length > 0)
                storeDetails += '<br/><br/><strong>Telephone</strong><br/>' + $(this).attr('tel');
            if ($(this).attr('fax').length > 0)
                storeDetails += '<br/><br/><strong>Fax</strong><br/>' + $(this).attr('fax');

            $('body').append('<div id="tempMapContainer"><div id="tempMapArrow"></div><a href="#" id="tempMapClose">x</a><div id="tempMapDetails">' + storeDetails + '</div><div id="tempMap"></div></div>');
            setupMap('tempMap', Array(Array($(this).attr('title'), $(this).attr('lat'), $(this).attr('lng'))), {
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                disableDefaultUI: true,
                navigationControl: true
            });

            var pos = $(this).offset();

            $('#tempMapContainer').css({
                'top': (pos.top + 42) + 'px',
                'left': (pos.left - ($('#tempMapContainer').width() / 2) + 10) + 'px'
            });

            $('#tempMapClose').click(function() {
                $('#tempMapContainer').remove();
                return false;
            });
        });
    }
    else {
        $('#overlay').remove();
        alert('The Postcode/Location you entered was not valid, please try again.');
        return false;
    }
}
function OnGetStoresFail(msg) {
    var i = 0;
}
function setupShowMapCheckout() {
    $('.showmapCheckout').click(function() {
        var storeDetails = '<strong>' + $(this).attr('title') + '</strong><br/><br/>' + $(this).attr('address');
        if ($(this).attr('tel').length > 0)
            storeDetails += '<br/><br/><strong>Telephone</strong><br/>' + $(this).attr('tel');
        if ($(this).attr('fax').length > 0)
            storeDetails += '<br/><br/><strong>Fax</strong><br/>' + $(this).attr('fax');

        $('body').append('<div id="tempMapContainer"><div id="tempMapArrow"></div><a href="#" id="tempMapClose">x</a><div id="tempMapDetails">' + storeDetails + '</div><div id="tempMap"></div></div>');
        setupMap('tempMap', Array(Array($(this).attr('title'), $(this).attr('lat'), $(this).attr('lng'))), {
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            navigationControl: true
        });

        var pos = $(this).offset();

        $('#tempMapContainer').css({
            'top': (pos.top + 25) + 'px',
            'left': (pos.left - ($('#tempMapContainer').width() / 2) + 15) + 'px'
        });

        $('#tempMapClose').click(function() {
            $('#tempMapContainer').remove();
            return (false);
        });
        return (false);
    });
}
function confirmMessage(msg, confirmFunc, cancelFunc) {
    $('#cncpop').before('<div id="overlay2"></div>');
    $('#overlay2').css({
        'background': '#000',
        'opacity': 0.5
    });
    $('#overlay').fadeTo(0, 0.5);
    $('#confirmBox').css('display', 'block');
    $('#confirmMsg').html(msg);
    $('.confirmCancel').click(function() {
        $('#overlay2').remove();
        $('#confirmBox').css('display', 'none');
        cancelFunc();
    });
    $('.confirmConfirm').click(function() {
        $('#overlay2').remove();
        $('#confirmBox').css('display', 'none');
        confirmFunc();
    });
}



function GetSearchResults() {

}

function SearchGivenString() {
    var searchString = $('.searchBox').val();

    Autocomplete.GetRedirectString(searchString, OnStringSucceed, OnSearchFail);
}

function OnStringSucceed(msg) {
    window.location = msg;
}

function SearchCatalogue() {
    var searchString = $('.searchBox').val();
    
    if (searchString.length > 2) {
        Autocomplete.GetCompletionList(searchString, OnSearchSucceed, OnSearchFail);
    }
    else {
        $(".searchResults").hide();
    }
}

function OnSearchSucceed(msg) {
    //get the string and show a div using jquery position()
    var searchBox = $(".searchBox");
    var boxPosition = searchBox.position();
    var topPos = boxPosition.top;
    var leftPos = boxPosition.left;
    
    if (msg.length > 0) {
        $(".searchResults").html(msg);
        $(".searchResults").css( { width:  $(".searchBox").css('width') } );
        $(".searchResults").css( { left: leftPos, top: topPos + 20 } );
        $(".searchResults").show();
    }
}

function SetBoxWithResult(resultString) {
    $(".searchBox").val(resultString);
}

function OnSearchFail(msg) {
    //alert(msg.get_message());
}

function SetMessagePanel(cssClass, msg) { 
    $('#resultPanel').removeClass("dormant");
    $('#resultPanel').removeClass("success");
    $('#resultPanel').removeClass("warning");
    $('#resultPanel').removeClass("failure");
    $('#resultPanel').addClass(cssClass);
    $('.txtResult').text(msg);
}
