var addthis_config;
var promoIndex;


//Easing
easingMethod = 'easeInOutCubic';
//easingMethod = 'easeOutBounce';
jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend(jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c * (t /= d) * t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t + b; return -c / 2 * ((--t) * (t - 2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c * (t /= d) * t * t + b; }, easeOutCubic: function (x, t, b, c, d) { return c * ((t = t / d - 1) * t * t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c * (t /= d) * t * t * t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t = t / d - 1) * t * t * t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b; return -c / 2 * ((t -= 2) * t * t * t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c * (t /= d) * t * t * t * t + b; }, easeOutQuint: function (x, t, b, c, d) { return c * ((t = t / d - 1) * t * t * t * t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b; return c / 2 * ((t -= 2) * t * t * t * t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t / d * (Math.PI / 2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t / d * (Math.PI / 2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t == 0) return b; if (t == d) return b + c; if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b; return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t = t / d - 1) * t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b; return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) {
	var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3; if (a < Math.abs(c)) { a = c; var s = p / 4; }
	else var s = p / (2 * Math.PI) * Math.asin(c / a); return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
}, easeOutElastic: function (x, t, b, c, d) {
	var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3; if (a < Math.abs(c)) { a = c; var s = p / 4; }
	else var s = p / (2 * Math.PI) * Math.asin(c / a); return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
}, easeInOutElastic: function (x, t, b, c, d) {
	var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d / 2) == 2) return b + c; if (!p) p = d * (.3 * 1.5); if (a < Math.abs(c)) { a = c; var s = p / 4; }
	else var s = p / (2 * Math.PI) * Math.asin(c / a); if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
}, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c * (t /= d) * t * ((s + 1) * t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b; return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce(x, d - t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t /= d) < (1 / 2.75)) { return c * (7.5625 * t * t) + b; } else if (t < (2 / 2.75)) { return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b; } else if (t < (2.5 / 2.75)) { return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b; } else { return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d / 2) return jQuery.easing.easeInBounce(x, t * 2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce(x, t * 2 - d, 0, c, d) * .5 + c * .5 + b; } 
});


var rio = {
    init: function () {
        $(document).ready(function () {
            $('#body .promoContainer .campaignBg').css({ opacity: 0.6 });
        });

        rio.cufon.init();
        rio.navigation.init();
        rio.subscribe.init();
        addthis_config = {
            ui_offset_top: 0,
            ui_offset_left: 0,
            ui_click: true
        }

    },
    cufon: {
        init: function () {
            Cufon.replace('h1, h2, ul.tabs li, .mapHolder table th, .moduleNewsList h3', { fontFamily: 'AvantGarde' });
            Cufon.replace('#body .sideNav ul.level01 > li > a, #footer .title');
            Cufon.replace('#nav ul.level02 > li > a', { hover: { color: 'white'} });

            //
        }
    },
    navigation: {
        init: function () {
            $(document).ready(function () {
                $('#nav ul.level01').children('li').each(function () {
                    var subNav = $('ul.level02', this);
                    if (subNav.length > 0) {

                        $(this).addClass('sub');
                        subNav.width($('> li', subNav).length * 215);
                        $('> li:first', subNav).addClass('first');
                        $(this).bind('mouseenter mouseleave', function (event) {
                            if (event.type == "mouseenter") {
                                $(this).addClass('state-hover');
                                subNav.show();
                                Cufon.replace($(this).find('a:first'), { color: '#fff' });
                            } else {
                                $(this).removeClass('state-hover');

                                subNav.hide();

                                Cufon.replace($(this).find('a:first'), { color: '#6B6B6B ' });
                            }
                        });

                        Cufon.replace($(this).find('a:first'), { color: '#6B6B6B ' });

                        var listLength = 0;
                        $('> li', subNav).each(function () {
                            if ($('ul > li', this).length > listLength)
                                listLength = $('ul > li', this).length;
                        });

                        $('> li', subNav).height((listLength * 29) + 40);
                        // $('> li', subNav).height(40);
                    }
                    else {
                        Cufon.replace($(this).find('a:first'), { hover: { color: '#fff'} });
                    }



                });
            });
        }
    },
    colourPicker: {
        init: function () {
            $(document).ready(function () {
                var thumbs = $('#media li a');
                var target = $('#mediaDetail');

                thumbs.each(function () {
                    $(this).bind('mouseover mouseout click', function (event) {
                        if (event.type == "mouseover") {
                            $(this).addClass('state-hover');
                        }
                        if (event.type == "mouseout") {
                            $(this).removeClass('state-hover');
                        }
                        if (event.type == "click") {
                            var src = $(this).attr('href');
                            $('#media li a.state-active').removeClass('state-active');
                            $(this).addClass('state-active');
                            target.fadeOut(500, function () {
                                target.parent().addClass('loading');
                                rio.loadMedia(target, src);
                            });
                            return false;
                        }
                    });
                });
            });
        }
    },
    loadMedia: function (target, src) {
        var $image = new Image();
        $($image).load(function () {
            target.html('').parent().removeClass('loading');
            $(target).append(this).fadeIn(500);
        })
		.error(function () {
		    $(target).removeClass('loading');
		    $(target).html('Error Loading Image');
		})
		.attr('src', src);
    },
    promoSlider: {
        init: function () {
            $(document).ready(function () {
                var $slides = $('#slides > .slide');
                var $thumbs = $('#slideTriggers li a');
                var $headings = $('#slideHeadings > div');
                var t;
                $slides.wrapAll('<div id="slidesWrapper" />');
                $slides = $('#slidesWrapper');
                promoIndex = 0;

                $(window).resize(function () {
                    if ($(window).width() < 1440) {
                        var i = ($(window).width() - 1440) / 2;
                        $slides.css({ marginLeft: i });
                    } else {
                        $slides.css({ marginLeft: 0 });
                    }
                });

                if ($(window).width() < 1440) {
                    var i = ($(window).width() - 1440) / 2;
                    $slides.css({ marginLeft: i });
                } else {
                    $slides.css({ marginLeft: 0 });
                }


                $thumbs.each(function (i) {
                    $(this).bind('click mouseenter mouseleave', function (event) {
                        if (event.type == 'click') {
                            $slides.animate({ marginTop: (i * 426) * -1 }, { queue: false, easing: easingMethod, duration: 700 });
                            $('#slideHeadings > div.state-active').fadeOut(400, function () {
                                $headings.eq(i).fadeIn(400).addClass('state-active');
                            }).removeClass('state-active');

                            $('#slideTriggers li a.state-active').removeClass('state-active').find('img', this).fadeTo(0, 0.4);
                            $(this).addClass('state-active');
                            $('img', this).fadeTo(0, 1);

                            if (typeof t != 'undefined') {
                                clearInterval(t);
                                t = setInterval("rio.promoSlider.interval()", 8000);
                                promoIndex = i;
                            }

                            return false;
                        }

                        if (event.type == 'mouseenter') {
                            if (!$(this).hasClass('state-active'))
                                $('img', this).fadeTo(0, 1);
                        }

                        if (event.type == 'mouseleave') {
                            if (!$(this).hasClass('state-active'))
                                $('img', this).fadeTo(0, 0.4);
                        }

                    });

                    if (i > 0) {
                        $('img', this).fadeTo(0, 0.4);
                    } else {
                        $(this).addClass('state-active');
                    }

                });

                t = setInterval("rio.promoSlider.interval()", 8000);
            });
        },
        interval: function () {
            promoIndex++;
            if (promoIndex > 3)
                promoIndex = 0;

            $('#slideTriggers li a').eq(promoIndex).click();


        }
    },
    gMap: {
        init: function () {
            $(document).ready(function () {
                if (window.homeSpatialInfo !== undefined && window.ProximityLocations !== undefined) {
                    if (GBrowserIsCompatible()) {
                        var map = new GMap2(document.getElementById('map'));
                        map.addControl(new GSmallMapControl());
                        map.addControl(new GMapTypeControl());
                        map.setCenter(new GLatLng(homeSpatialInfo.latitude, homeSpatialInfo.longitude), 10);

                        // Create a base icon for all of our markers that specifies the
                        // shadow, icon dimensions, etc.
                        var baseIcon = new GIcon();
                        //baseIcon.shadow = '/Images/shadow50.png'; //TODO
                        baseIcon.iconSize = new GSize(23, 27);
                        //baseIcon.shadowSize = new GSize(37, 34);
                        baseIcon.iconAnchor = new GPoint(9, 34);
                        baseIcon.infoWindowAnchor = new GPoint(9, 2);
                        baseIcon.infoShadowAnchor = new GPoint(18, 25);

                        // Creates a marker whose info window displays the letter corresponding// to the given index.
                        function createMarker(point, name, address, urladdress, locationNumber, store) {
                            var icon = new GIcon(baseIcon);
                            icon.image = '/images/markers/marker' + locationNumber + '.png'; //TODO
                            var marker = new GMarker(point, icon);
                            GEvent.addListener(marker, 'click', function () {
                                marker.openInfoWindowHtml(rio.gMap.getBranding(store) + '<br />' + address + '<br>' + '<a target="_blank" href="http://maps.google.com/maps?f=q&hl=en&q=from:' + homeSpatialInfo.fromAddress + '+to:' + urladdress + '">Get Directions</a>');
                            });
                            return marker;
                        }

                        // Load all the markers from the JSON ProximityLocations variable
                        var geocoder = new GClientGeocoder();
                        var bounds = map.getBounds();
                        var southWest = bounds.getSouthWest();
                        var northEast = bounds.getNorthEast();
                        var lngSpan = northEast.lng() - southWest.lng();
                        var latSpan = northEast.lat() - southWest.lat();
                        for (var i = 0; i < ProximityLocations.locations.length; i++) {
                            var point = new GLatLng(ProximityLocations.locations[i].latitude, ProximityLocations.locations[i].longitude);
                            map.addOverlay(createMarker(point, ProximityLocations.locations[i].name, ProximityLocations.locations[i].address, ProximityLocations.locations[i].urladdress, i + 1, ProximityLocations.locations[i].store));
                        }
                    }
                }
            });
        },
        getBranding: function (store) {
            var imageName = store.replace(/\s+/g, '').replace(/&/g, 'and');
            return '<img src="/images/StoreBranding/' + imageName + '.png" alt="' + name + '" />';
        }
    },
    AutoClear: {
        init: function () {
            $(document).ready(function () {
                var $elements = $('.autoClear');
                $elements.each(function () {

                    if ($(this).val() == $(this).attr('title'))
                        $(this).addClass('example');

                    $(this).bind('focus blur', function (event) {
                        if (event.type == 'focus') {
                            if ($(this).val() == $(this).attr('title')) {
                                $(this).val('');
                                $(this).removeClass('example');
                            }
                        } else {
                            if ($(this).val() == '') {
                                $(this).val($(this).attr('title'));
                                $(this).addClass('example');
                            }
                        }
                    });
                });
            });
        }
    },
    subscribe: {
        init: function () {
            $(document).ready(function () {

                $("#footer .mail .input-subscribe-button").live('click', function () {
                    var emailpattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*(\s)*$/;
                    var email = $("#footer .mail .input-subscribe-email").val();
                    if (email == '') {
                        $("#footer .mail .lbl-subscribe").text("Please enter email");
                        $("#footer .mail .lbl-subscribe").addClass('error');
                    }
                    else if (emailpattern.test(email) == false) {
                        $("#footer .mail .lbl-subscribe").text("Invalid email");
                        $("#footer .mail .lbl-subscribe").addClass('error');
                    }
                    else {
                        $("#footer .mail").addClass('loading');
                        $.ajax({
                            type: "POST",
                            url: "/Services/cManagerService.asmx/AddSubscriber",
                            // Pass the "Count" parameter, via JSON object.
                            data: "{email:'" + email + "'}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (response) {
                                $("#footer .mail .summary").empty();
                                $("#footer .mail .summary").append("<span>Thank you for subscribing</span>");
                                $("#footer .mail").removeClass('loading');
                            }

                        });
                    }
                    return false;
                });

            });
        }
    },
    sizeCalculator: {
        init: function () {
            $(document).ready(function () {

                $(".bra_size_calculator_input").keydown(function (event) {
                    if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
                        // let it happen, don't do anything
                    }
                    else {
                        // Ensure that it is a number and stop the keypress
                        if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {
                            $(this).removeClass("redBackground")
                        }
                        else {
                            event.preventDefault();
                        }
                    }
                });

                $(".bra_size_calculator_submit").click(function () {
                    emptyFields = $('.bra_size_calculator_input').filter(function () { return $(this).val() == ""; });
                    if (emptyFields.length) {
                        emptyFields.addClass("redBackground");
                        $("#braSizeOutput").html('Please complete all measurements').fadeIn();
                    }
                    else {
                        braSize = rio.sizeCalculator.getBra($("#underbust_input").val(), $("#cupsize_input").val());
                        if (braSize) {
                            $("#braSizeOutput").html('<p>Your ideal bra size is </p><span>' + braSize + '</span>').fadeIn();
                        }
                        else {
                            $("#braSizeOutput").html('Sorry, no matching size was found.').fadeIn();
                        }
                    }
                    return false;
                });

            });
        },
        getCup: function (diff) {

            var cups = new Array("AA", "A", "B", "C", "D", "DD", "E", "F", "G", "H", "J");
            var minIdealDiff = 11;

            if (diff < minIdealDiff - 2) {
                /* console.log("too small cup") */
                return (false);
            }
            if (diff > (minIdealDiff + (cups.length - 1) * 2) + 1) {
                /* console.log("too big cup") */
                return (false);
            }
            for (i = 0; i < cups.length; i++) {
                ideal = minIdealDiff + (i * 2);
                min = ideal - 1;
                max = ideal + 1;

                if (cups[i] == "AA") {
                    min = ideal - 2;
                    max = ideal;
                }
                if (cups[i] == "A") {
                    max = ideal + 1;
                }

                if ((diff >= min && diff <= max)) {
                    return (cups[i])
                }
            }
        },
        getSize: function (underbust) {

            var sizes = new Array(8, 10, 12, 14, 16, 18, 20, 22, 24)
            var minUnderbust = 63;

            if (underbust < minUnderbust) {
                /* console.log("too small UB") */
                return false;
            }
            if (underbust > minUnderbust + ((sizes.length - 1) * 5) + 4) {
                /* console.log("too big UB") */
                return false;
            }

            for (i = 0; i < sizes.length; i++) {
                min = minUnderbust + (i * 5);
                max = min + 4;
                if (underbust >= min && underbust <= max) {
                    return (sizes[i])
                }
            }
        },
        getBra: function (underbust, overbust) {
            if (isNaN(underbust) || isNaN(overbust)) return false;

            underbust = parseInt(underbust);
            overbust = parseInt(overbust);

            diff = (overbust >= underbust) ? overbust - underbust : 0;
            size = rio.sizeCalculator.getSize(underbust);
            cup = rio.sizeCalculator.getCup(diff);
            if (size && cup) {
                return (size + cup);
            }
            else {
                return (false);
            }
        }
    },
    customerServiceEnquiry: {
        init: function () {
            $(document).ready(function () {

                $(".enquirytype").change(function () {

                    $.ajax({
                        type: "POST",
                        url: "/Services/cManagerService.asmx/GetCustomerServiceList",
                        data: "{siteId: '972CEE3B-B432-4DAF-93CD-DD5AA1143A24', category:'" + $(".enquirytype").val() + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            $(".contactreason")
                                .find('option')
                                .remove()
                                .end()
                                .append('<option selected="selected" value="">Please Select</option>');

                            data = $.parseJSON(response.d);
                            $(data).each(function (i, item) {
                                $(".contactreason")
                                    .append('<option value="' + item.ContentId + '">' + item.Question + '</option>');
                            });
                        }
                    });
                });

            });
        }
    },


    facebookComp: {
        init: function () {

            $('#referFriend li').hide();

            var referals = 0;

            $('#referBtn-show').click(function () {
             
                referals++;

                switch (referals) {
                    case 1:
                        $(".refer1").show();
                        break;
                    case 2:
                        $(".refer2").show();
                        $(this).hide();
                        break;
                    default:
                        return false;
                }

                return false;
            });

        }
    }
};

rio.init();


