var J = jQuery.noConflict();

J(document).ready(function ($) {

    if ($('.main-menu .main .active .sub-menu').length) {
        $('#header').addClass("active");
    }

    if (window.location.href.indexOf("collectionlist.aspx") == -1 && window.location.href.indexOf("/col/") == -1) {
        $('.look_collection').hide();
    }
    $('.shop_by_look').click(function () {
        $('.look_collection').slideToggle();
    })

    if ($('.filters #colors').length) {
        var w = window.location.href;
        w = w.substring(w.indexOf("fcwpidf") + 8);
        if (w.indexOf("&") > -1)
            w = w.substring(0, w.indexOf("&"));
        document.getElementById("colors").value = w;
    }

    if ($('#carousel').length) {
        jQuery('#carousel').jcarousel({
            scroll: 2
        });
    }
    jQuery('.jcarousel-next, .jcarousel-prev').hover(function () {
        jQuery(this).addClass('iehover');
    }, function () {
        jQuery(this).removeClass('iehover');
    });

    if (window.location.href.indexOf("storelocator.aspx") > -1 || window.location.href.indexOf("/contact.html") > 1 || $('#ContentPlaceHolder1_MyList').length > 0) {
        $('select').selectbox();
    }
    Cufon.set('fontFamily', 'royal').replace('.details H2')('.details .back', { hover: true })('.wrap H1')('#content .story-content H2')('.post h2')('A.navt', { hover: true })('#content .story-content H3')('.sidebar h3')('#content .story-content .history UL LI SPAN.year')('.world-of-heading');
    $('.rotator UL LI IMG').animate({ opacity: 1.0 }, { complete: function () { $(this).removeAttr('style'); } });
    $('#rotator').cycle({
        fx: 'zoom',
        easing: 'bouncein',
        delay: -4000
    });
    $('.rotator-bollman UL LI IMG').animate({ opacity: 1.0 }, { complete: function () { $(this).removeAttr('style'); } });
    $('#rotator-bollman').cycle({
        fx: 'zoom',
        easing: 'bouncein',
        delay: -4000
    });
    if ($('#content .story-content .main-pic-cont ul').length > 0) {
        $('#content .story-content .main-pic-cont ul').cycle({
            fx: 'fade'
        });
    }

    $('INPUT.auto-hint').each(function (i, el) {
        if ($(this).val() == '') {
            $(this).val($(this).attr('title'));
        }
        $(el).focus(function () {
            if ($(this).val() == $(this).attr('title')) {
                $(this).val('');
            }
        });
        $(el).blur(function () {
            if ($(this).val() == '') {
                $(this).val($(this).attr('title'));
            }
        });
    });

    if ($('body').hasClass('home')) {


    } else if ($('body').hasClass('story')) {
        $(document).bgStretcher({
            images: ['/layout/images/bg/bg-story.jpg'],
            imageWidth: 1475, imageHeight: 1180, slideShow: false
        });
    } else if ($('body').hasClass('blog')) {
        $(document).bgStretcher({
            images: ['/layout/images/bg/bg-blog.jpg'],
            imageWidth: 1475, imageHeight: 1066, slideShow: false
        });
    } else if ($('body').hasClass('stores')) {
        $(document).bgStretcher({
            images: ['/layout/images/bg/bg-stores.jpg'],
            imageWidth: 1475, imageHeight: 1069, slideShow: false
        });
    } else if ($('body').hasClass('world-of')) {
        $(document).bgStretcher({
            images: ['/layout/images/bg/world-of.jpg'],
            imageWidth: 1475, imageHeight: 1188, slideShow: false
        });
    } else if ($('body').hasClass('contact')) {
        $(document).bgStretcher({
            images: ['/images/contactBG.jpg'],
            imageWidth: 1475, imageHeight: 972, slideShow: false
        });
    } else if ($('body').hasClass('videos')) {
        $(document).bgStretcher({
            images: ['/layout/images/bg/myaccount-bg.png'],
            imageWidth: 818, imageHeight: 471, slideShow: false
        });
    } else if ($('body').hasClass('feedback')) {
        $(document).bgStretcher({
            images: ['/layout/images/bg/feedback-bg.png'],
            imageWidth: 1206, imageHeight: 595, slideShow: false
        });
    } else if ($('body').hasClass('login')) {
        $(document).bgStretcher({
            images: ['/layout/images/bg/myaccount-bg.png'],
            imageWidth: 818, imageHeight: 471, slideShow: false
        });
    } else if ($('body').hasClass('starbucks')) {
        $(document).bgStretcher({
            images: ['/layout/images/bg/starbucks.jpg'],
            imageWidth: 1244, imageHeight: 995, slideShow: false
        });
    } else if ($('body').hasClass('diy-project')) {
        $(document).bgStretcher({
            images: ['/layout/images/bg/bg_diy.jpg'],
            imageWidth: 1668, imageHeight: 1035, slideShow: false
        });
    } else if ($('body').hasClass('projects')) {
        var imagePath;
        if (window.location.pathname == "/mark_borthwick.html")
            imagePath = "/layout/images/bg/mark_borthwick.jpg";
        else if (window.location.pathname == "/martin_greenfield.html")
            imagePath = "/layout/images/bg/martin_greenfield.jpg";
        else if (window.location.pathname == "/projects_partnerships.html")
            imagePath = "/layout/images/bg/projects_partnerships.jpg";
        else if (window.location.pathname == "/lana_chun.html")
            imagePath = "/layout/images/bg/lana_chun.jpg";
        else if (window.location.pathname == "/houston_project.html")
            imagePath = "/layout/images/bg/houston_project.jpg";
        else if (window.location.pathname == "/bollman_hat.html")
            imagePath = "/layout/images/bg/bollman.jpg";
        else if (window.location.pathname == "/denim.html")
            imagePath = "/layout/images/bg/bg-inside.jpg";
        else if (window.location.pathname == "/careers.html")
            imagePath = "/layout/images/bg/careers.jpg";

        $(document).bgStretcher({
            images: [imagePath],
            imageWidth: 1474, imageHeight: 1116, slideShow: false
        });
    } else {
        $(document).bgStretcher({
            imageWidth: 1474, imageHeight: 1116, slideShow: false
        });
    }

    /* Scroll */
    if ($('.history').length > 0) {
        var w_scroll = 0;
        $('.history UL LI').each(function () {
            if ($(this).parent().parent().hasClass('history')) {
                if ($(this).hasClass('first')) w_scroll += 30; else w_scroll -= 60;
                w_scroll += parseInt($(this).width());
            }
        });
        if (w_scroll != 0) $('.history UL.history-scroll').css('width', w_scroll + 'px');

    }

    var width = 0;
    var w = 0;
    $('.scrollableArea .item').each(function (i) {
        w = $(this).width();
        width = width + w;
    });
    $('.scrollableArea').css('width', width);
    if ($('#flexcroll').length > 0) {
        $('div#flexcroll').smoothDivScroll({ visibleHotSpots: "always", startAtElementId: "startId" });
    }

    $('A.tab-link').click(function () {
        if ($($(this).attr('href')).hasClass('active')) return false;
        $('#content .tabs .active').removeClass('active');
        $($(this).attr('href')).addClass('active');
        return false;
    });

    $('.thumbnails UL LI A').click(function () {
        $('#main-img').attr('src', $(this).attr('href'));

        return false;
    });

    $('INPUT.auto-hint').each(function (i, el) {
        if ($(this).val() == '') {
            $(this).val($(this).attr('title'));
        }
        $(el).focus(function () {
            if ($(this).val() == $(this).attr('title')) {
                $(this).val('');
            }
        });
        $(el).blur(function () {
            if ($(this).val() == '') {
                $(this).val($(this).attr('title'));
            }
        });
    });

    $(".filter-box A.filter-by").click(function () {
        if ($(this).hasClass('close')) {
            $(".color-list").slideDown('normal');
            $(this).removeClass('close').addClass('open');
        } else {
            $(".color-list").slideUp('normal');
            $(this).removeClass('open').addClass('close');
        }
        return false;
    });
    $(".filter-box2 A.filter-by").click(function () {
        if ($(this).hasClass('close')) {
            $(".color-list2").slideDown('normal');
            $(this).removeClass('close').addClass('open');
        } else {
            $(".color-list2").slideUp('normal');
            $(this).removeClass('open').addClass('close');
        }
        return false;
    });

    $('.store-locator ul li a').click(function () {
        var i = $(this).attr('href');
        $('#StoreImg').attr('src', '/images/store_gallery/' + i + '.jpg');
        $('#StoreMap').attr('src', '/images/store_gallery/' + i + '-map.jpg');
        return false;
    });

    $(document).ready(function () {
        if (window.location.href.indexOf("storelocator.aspx") > -1 || window.location.href.indexOf("contact.html") > -1 || $('body').hasClass('home') || $('body').hasClass('videos') || $('body').hasClass('diy-project') || window.location.href.toLowerCase().indexOf("collection_vip.aspx") > -1 || window.location.href.toLowerCase().indexOf("collectionlist.aspx") > -1 || window.location.href.toLowerCase().indexOf("martin_greenfield.html") > -1 || window.location.href.toLowerCase().indexOf("houston_project.html") > -1) {
            $("a[rel^='prettyPhoto']").prettyPhoto({ theme: 'light_square', animationSpeed: 'fast' });
        } else if (window.location.href.indexOf("denim.html") > -1) {
            $("a[rel^='prettyPhoto']").prettyPhoto({ theme: 'light_square', animationSpeed: 'fast', default_width: 660 });
        }
    });

});

var extraImageCount = 0;
function change_extrabutton(hyperlinkname, imgname, elementindex) {
	if (g_useextragroup_colors == 0)
		return;

	if (elementindex == 10) {
		jQuery('#carousel').jcarousel('scroll', 0);
		jQuery('#carousel').jcarousel('size', extraImageCount);
		extraImageCount = 0;
	}

	var e_img = getElementByID_Master(imgname);
	if (e_img == null)
		return;

	var e_hl = getElementByID_Master(hyperlinkname);
	if (e_hl == null)
		return;

	try {
		if (aExtraGroupColors[g_color] == null || aExtraGroupColors[g_color][elementindex] == null) {
			e_hl.style.visibility = "hidden";
			e_img.src = '';
			return;
		}

		e_hl.style.visibility = "visible";
		extraImageCount++;
		e_img.src = aExtraGroupColors[g_color][elementindex];
	}
	catch (err) {
	}
}

function SubmitNameAndAddress() {
	var name = document.getElementById('popup-name').value;
	var email = document.getElementById('popup-email').value;

	if (name == '' || name == 'Name') {
		J('#popup #message').show();
		J('#popup #message').html('Please enter a name!');
		return false;
	}
	if (email == '' || name == 'Email') {
		J('#popup #message').show();
		J('#popup #message').html('Please enter an email!');
		return false;
	}
	
    if (email != "") {
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
			var url = '/mailinglistsignup.aspx';
			var params = '?name=' + name + '&email=' + email;

			url += params;

			J('#popup #message').show();
			J('#popup #message').html('processing...');

			J.ajax({
			    url: url,
			    success: function (transport) {
			        if (location.href.indexOf("/shop.html") > -1) {
			            J('#popup-submit').hide();
			            J('#shop-signup-inputs').hide();
			            J('#popup #message').css('top', '40px').css('left', '62px').css('text-align', 'center');
			            J('#popup #message').html('Thank you for joining the<br/>Rag & Bone mailing list.');
			        } else {
			            J('#popup #message').html('Thank you for joining the Rag & Bone mailing list.');
			            J('#popup-name').hide();
			            J('#popup-email').hide();
			            J('#btnSubmit').hide();
			            J('#popup #message').css('margin-bottom', '9px');
			        }

			    },
			    error: function () {
			        J('#popup #message').html('Your request has not been submitted!');
			    }
			});
		} else {
			J('#popup #message').show();
			J('#popup #message').html('Invalid E-mail Address!');
			return false;
		}
	}
	return false;
}

function SubmitNameAndAddress2() {
	var name = document.getElementById('popup-name2').value;
	var email = document.getElementById('popup-email2').value;
	if (name == '') {
		J('#popup2 #message2').show();
		J('#popup2 #message2').html('Please enter a name!');
		return false;
	}
	if (email == '') {
		J('#popup2 #message2').show();
		J('#popup2 #message2').html('Please enter an email!');
		return false;
	}
	if (email != "") {
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
			var url = '/mailinglistsignup.aspx';
			var params = '?name=' + name + '&email=' + email;

			url += params;

			J('#popup2 #message2').show();
			J('#popup2 #message2').html('processing...');

			J.ajax({
				url: url,
				success: function (transport) {
					J('#popup-submit2').hide();
					J('#shop-signup-inputs').hide();
					J('#popup2 #message2').css('text-align', 'center');
					J('#popup2 #message2').html('Thank you for joining the<br/>Rag & Bone mailing list.');
					setTimeout(function () { J('#popup2').hide(); J('#overlay').hide(); }, 3000);
				},
				error: function () {
					J('#popup2 #message2').html('Your request has not been submitted!');
				}
			});
		} else {
			J('#popup2 #message2').show();
			J('#popup2 #message2').html('Invalid E-mail Address!');
			return false;
		}
	}
	return false;
}

//override func in /store/os/misc.js in order to reset size ddl to 'Select Size' menu item & refresh SelectBox values whenever a color swatch is clicked
function reload_sizes() {
    if (size_count == 0)
        return;

    var ps = getElementByID_Master("ProductSizes");
    if (ps == null)
        return;

    //updated to enable quicklook on pdp for huds
    if (ps.options != null) {
        var curr_value = ps.options[ps.selectedIndex].value;
        var curr_index = 0;

        ps.length = 0;
        ps.options[0] = new Option("Select " + g_sizealias, "-1");
        curr_index++;


        for (var i = 1; i <= size_count; i++) {
            if (g_color == 0 || aSCSA[g_color][i] == true || g_showwhenoos == 1) {
                ps.options[curr_index] = new Option(size_names[i], size_ids[i]);
                if (curr_value == size_ids[i])
                    ps.selectedIndex = curr_index;

                curr_index++;
            }
        }
    }
    if (ps.length == 2 && (getElementByID_Master("DisableOneSizeSelection") == null || (getElementByID_Master("DisableOneSizeSelection") != null && getElementByID_Master("DisableOneSizeSelection").value != 1))) {
        ps.selectedIndex = 1;
    }
    else { //reset size ddl to 'Select Size' because a color swatch has been clicked
        ps.selectedIndex = 0;
    }

    //selectbox wasn't updating drop-down with new sizes when color swatch clicked, sooo
    //remove selectbox and force it to recreate drop-down from new values in ProductSizes
    J('.jquery-selectbox').unselectbox();
    J('select').selectbox();
}
