
$(document).ready(function() {

    // code user to power the jeweller lookup
    jewellerLookup.init();

    if (jewellerLookup.isManualSubmit)
        $('#jeweller-lookup select').change(showButton);

    // code used to show large images in on page box
    baseOverlay.init('#jeweller-images a.image-overlay');

    if (location.href.indexOf('Bridal') == -1) {
        $(".htmlspan").css({ display: 'none', visibility: "hidden" });
        $(".flashspan").css({ display: 'none', visibility: "hidden" });
        $(".bridalspan").css({ display: 'none', visibility: "hidden" });
        shouldDisplayFlash(false);
        disableFlashVersionOnPage(true);
    } else {
        if (document.cookie.indexOf('flash') == -1 || document.cookie.indexOf('flash=false') != -1) {
            $(".htmlspan").css({ display: 'none', visibility: "hidden" });
            $(".flashspan").css({ display: 'inline', visibility: "visible" });
            shouldDisplayFlash(false);
            disableFlashVersionOnPage(true);
        } else {
            $(".htmlspan").css({ display: 'inline', visibility: "visible" });
            $(".flashspan").css({ display: 'none', visibility: "hidden" });
            shouldDisplayFlash(true);
            disableFlashVersionOnPage(false);
        }
    }
});

// Javascript used to support the Jeweller Design Carousel Jeweller Locator

function showButton() {
    if (this.value != '') {
        $('.manual-submit').show();
    } else {
        $('.manual-submit').hide();
    }
}

var jewellerLookup = {
    parent: [],
    scrollPane: null,
    finalSelectListName: '',
    service: '',
    isAutoRedirect: null,
    isManualSubmit: null,
    isButtonAction: null,
    redirectUniqueId: null,
    redirectMethod: function() {
        var obj = this;
        setTimeout(
			function() {
			    obj.name = jewellerLookup.redirectUniqueId;
			    $('#jeweller-form').hide();
			    __doPostBack(jewellerLookup.redirectUniqueId, obj.value);
			}, 1);
    },
    init: function() {
        var that = this;
        that.finalSelectListName = 'ddlJeweller';
        that.scrollPane = $('#forevermark-main div.col-2 div.col-scroll')[0] || null;

        that.parent = $('#jeweller-lookup');
        if ($('#change_jeweller').length === 0) {
            that.service = 'locator';
        }
        else {
            that.service = 'register';

            // Validate the other input field
            validateInputField('other-field');
        }
        that.parent.removeClass('js-hide');
        var selectName = that.parent.find('select').attr('name');
        if (selectName && (!new RegExp(that.finalSelectListName + '$').test(selectName))) {
            that.parent.find('select').change(this.onChange);
        }

        var field = that.parent.find('select');
        field.val($('option:first', field).val());
    },
    onChange: function(e) {
        var that = jewellerLookup;
        var elem = $(this);
        var value = elem.val();
        if (value == false) {
            elem.nextAll('select').remove(); // dont lookup for first option
            elem.nextAll('button').remove();
        }
        else {
            that.loadData($(this));
        }

        if (elem.hasClass('jeweller-select') && value === '-1') {
            $("#change_jeweller").removeClass('js-hide').addClass('active').find('span').hide();
        }
        else {
            $("#change_jeweller").addClass('js-hide').removeClass('active').find('input.other-field').val('');
        }
    },
    loadData: function(elem, value) {
        if (elem.jquery) {
            var el = elem;
            value = elem.val();
            elem = elem.blur().attr('name');
        }

        var that = this;
        var jsonDataUrl = '/util/DealerLocatorHandler/DealerLocatorHandler.ashx';
        var request = { 'service': that.service };
        request[elem] = value;
        if (elem != that.parent.find('select').attr('name')) {
            request[that.parent.find('select').attr('name')] = that.parent.find('select').val();
        }
        // for local testing...
        //jsonDataUrl = '/json/json_test_'+ elem +'.js';

        var test = $.getJSON(jsonDataUrl, request, function(result, textStatus) {
            if (textStatus != 'success' || !result || !result.name || !result.values || result.values === []) {
                if (textStatus != 'success') {
                    alert('Unable to retrieve results, status is: ' + textStatus); // handle error
                }
            }
            else {
                if (el.hasClass('jeweller-select')) {
                    if (!el.next('button').length) that.makeButtonHtml(result.name, result.cssclass, result.values);
                    $('#jewellerButton').click(function() {
                        $(this).prev('select').change(that.redirectMethod).change();
                    });
                }
                else that.makeSelectHtml(result.name, result.cssclass, result.values);
            }
        });
        return true;
    },
    makeButtonHtml: function(name, cssclass, data) {
        var that = this;
        var buttonHtml = '<button id="jewellerButton" name="' + name + '" class="jeweller_button" type="button">' + findDetailsText + '</button>';

        this.parent.append(buttonHtml);
    },
    makeSelectHtml: function(name, cssclass, data) {
        var that = this;
        var cssclassValue = cssclass ? 'size selectFix ' + cssclass : 'size selectFix';
        var id = name.replace(/\$/gi, '_'); // clean .net generated element id
        if (jewellerLookup.isManualSubmit) idManual = that.redirectUniqueId;
        var selectHtml = '<select id="' + id + '" name="' + name + '" class="' + cssclassValue + '"></select>';
        var select = $('#' + id);

        if (!select.length) {
            this.parent.append(selectHtml);
        }
        else {
            select.replaceWith(selectHtml);
        }

        select = this.parent.find('#' + id);
        if (that.scrollPane) {
            that.scrollPane.scrollTop += select.height() + 5;
        }

        // remove dependent fields
        select.nextAll('select').remove();

        if (!id.endsWith(that.finalSelectListName)) {
            select.change(that.onChange);
        }
        if (this.isAutoRedirect) {
            select[0].onchange = that.redirectMethod;
        }
        if (this.isManualSubmit) {
            select.change(that.onChange);
        }

        var item, dataLen, i, optionHtml;

        for (i = 0, dataLen = data.length; i < dataLen; i++) {
            item = data[i];
            optionHtml = '<option';
            if (item && item.length === 2) {
                optionHtml += ' value="' + item.shift() + '"';
            }
            optionHtml += '>' + item.shift() + '</option>';
            select.append(optionHtml);
        }
    }
};

// Javascript used to support the Jeweller Design Carousel

// getter / setter for flash display
var shouldDisplayFlash = function(state) {
    // store flash option in a cookie
    var expires = new Date(new Date().getTime() + 6 * 30 * 24 * 3600000); // 6 months

    if (typeof state === 'undefined') {
        return (document.cookie.indexOf('flash=false') === -1);
    }
    else {
        state = (state != false);
        document.cookie = 'flash=' + state + '; expires=' + expires + '; path=/';
        return state;
    }
};

var isFlashDisabledOnPage = false;
var disableFlashVersionOnPage = function(isDisabled) {
    if (typeof isDisabled === 'undefined') {
        isFlashDisabledOnPage = true;
    }
    else {
        isFlashDisabledOnPage = isDisabled;
    }
};

// View the flash version of the site
function viewFlashVersion() {
    shouldDisplayFlash(true);
    window.location = window.location;
}

// View the flash version of the site
function viewFlashVersionLocatorPage(url) {
    shouldDisplayFlash(true);
    window.location = url;
}

// View the HTML version of the site
function viewHtmlVersion() {
    shouldDisplayFlash(false);
    disableFlashVersionOnPage(true);
    window.location = window.location;
}

function initMenu(cssSelector) {
    $(cssSelector).hover(
		function() {
		    var el = $(this);
		    var submenu = el.addClass('sfhover').find('ul').hide();
		    var offset = parseInt((el.width() - submenu.width()) / 2);
		    offset += 10;
		    submenu.css('left', offset).show();
		},
		function() {
		    $(this).removeClass('sfhover').find('ul').css('left', '');
		}
	);
}

// New Jeweller Homepage function
$('a.view-jeweller').click(function(e) {
    e.preventDefault();
    openDetailForm(this);
});
// Open the detail form
function openDetailForm(link) {
    var that = $(link),
			bottomCarousel = $('#bottom-scroller'),
			detailForm = $('#form-holder'),
			linkOpen, linkClose;

    if (Object.isEmpty(that.data("linkText"))) {
        that.data("linkText", { open: that.text(), close: that.attr('rel') });
    }

    if (that.hasClass('close-jeweller')) {
        detailForm.fadeOut("slow", function() {
            bottomCarousel.animate({ top: 0 }, 1000);
            that.removeClass('close-jeweller').css('margin-top', '0').text(that.data("linkText").open);
        });
    } else {
        bottomCarousel.animate({ top: 155 }, 1000, function() {
            detailForm.fadeIn();
            that.addClass('close-jeweller').css('margin-top', '156px').text(that.data("linkText").close);
        });
    }
}

// openTab (for Flex/Flash)
function openTab() {
    $('#form-holder').fadeIn("slow");
}


// closeTab (for Flex/Flash)
function closeTab() {
    $('#form-holder').fadeOut("fast");
}

// content toggle used for opening times

function contentToggle(selector, onstateClass) {
    selector = selector || 'a.js-toggle';
    onstateClass = onstateClass || 'expanded';
    $(selector).click(function(e) {
        // Hide all opening times
        $('body.jeweller #overlay-holder .opening-times').hide();
        var el = $(this);
        var target = $(el.parents('div').get(0)).find('.' + el.attr('href').substring(1));

        e.preventDefault();
        this.blur();
        target.removeClass('js-hide');

        if (el.hasClass(onstateClass)) {
            target.hide();
            el.removeClass(onstateClass);
        }
        else {
            target.show();
            el.addClass(onstateClass);
        }
    });
};

// please create a base class for the overlays and then subclass from it for imageOverlay - overriding methods
// JH: 08-11-14 12:43
var baseOverlay = {
    init: function(cssSelector) {
        var that = this;
        var el = $(cssSelector);
        el.click(function(e) {
            e.preventDefault();
            this.blur();

            that.show($(this));
        });
    },
    show: function(el) {
        var name = $('#' + el.attr('class'));
        name.show();
        name.find('.image').attr('src', el.attr('href'));
        name.find('#right-panel h2').text(el.find('.h2-title').html());
        name.find('#right-panel p').text(el.find('.hidden').html());
        this.close(name);
    },
    setOffset: function() { },
    close: function(el) {
        el.find('.close a').click(function() {
            el.hide();
        });
    }
};

