var rw_comment_height = [];

/*
 * Show list of comments of an user review
 **/
function showReviewComment(review_id){
	if ($('rw_comment_'+review_id)){
		var id = 'rw_comment_'+review_id;
                var fx = new Fx.Styles($(id), {duration:300,wait:false,transition:Fx.Transitions.Quad.easeIn});

		if ($(id).style.height=='0px'){
                        //Expand
                                fx.start({'height':rw_comment_height['rw_comment_'+review_id],'opacity':1});
			if ($('rw_expand_'+review_id)){
				$('rw_expand_'+review_id).innerHTML = 'Hide Comments';
			}
		}else {
			if (!rw_comment_height['rw_comment_'+review_id]){
				rw_comment_height['rw_comment_'+review_id] = $('rw_comment_'+review_id).offsetHeight;		
			}
                        //Hide
                        fx.start({'height':'0px','opacity':0});
			if ($('rw_expand_'+review_id)){
                                $('rw_expand_'+review_id).innerHTML = 'Show Comments';
                        }

                }
        }
    }


/*
 * Show comment form
 * Function is called when "Add reply" to review is clicked
 **/
function showCommentForm(review_id){
	if ($('rwCommentFrm'+review_id)){
		$('rwCommentFrm'+review_id).style.display = "block";
	}
}
function showCommentFormB(review_id)
{
    if ($('rwCommentFrm'+review_id+'').getStyle('display') == 'none') {
        if ($('frm_expand_'+review_id)) $('frm_expand_'+review_id).innerHTML = 'Cancel';
        $('rwCommentFrm'+review_id+'').setStyle('display', 'block');
    } else {
        if ($('frm_expand_'+review_id)) $('frm_expand_'+review_id).innerHTML = 'Add A Reply';
        $('rwCommentFrm'+review_id+'').setStyle('display', 'none');
    }
}

/*
 * Show Product Review Form when user click on rating stars
 * Sync rating value on the form with the rating stars selected by user
 **/
function showReviewForm(){
        $("reviewFrm_wrappper").style.display='block';
        $("showReview_wrapper").style.display='none';
        $("showreview").style.display='block';
        $("postlink").style.display='none';

        /* pass rating value to the form's rating */
        var rateValue = 0;

        for (var i=0; i < document.ratingpostFrm.rating.length; i++){
            if (document.ratingpostFrm.rating[i].checked){
                document.productReviewFrm.rating[i].checked = true;
                rateValue = i;
            }
        }


        /* update star-rating on reviewForm based on rating value passed in */
        var children = $$('#form-star-rating .star-rating-control .star-rating');
        for (var i=0; i<children.length; i++){
            children[i].removeClass("star-rating-on");
        }
        for (i=0; i<children.length && i<=rateValue; i++){
            children[i].addClass("star-rating-on");
        }
}


/*
 * Show rating star when mouse hover on 'average product rating' element
 **/
function showRating(){
    $('rw_rating_post').style.display='block';
    $('rw_rating').style.display='none';
}

/*
 * Hide rating star when mouse hover away from 'average product rating' element
 **/
function hideRating(){
    $('rw_rating_post').style.display='none';
    $('rw_rating').style.display='block';
}



/**
 * Save product to user's wishlist and show message on a modal window
 * which is created on the fly without prepared markup in the page
 */
function setWishList(productId)
{
    // Ajax away
    $j.get("/load.php?module=moduleMyAccountLJ&action=setWishlist&product_id=" + productId, function(response) {
        
        // Append necessary markup to the DOM from which we construct the (simple) modal window
        var modalHtml = '<div id="wishlist-modal" class="generic-modal">' +
                        '<h2 class="title">&nbsp;</h2>' +
                        '<div class="modal-content"></div>' +
                    '</div>';
        // Append to DOm
        $j('body').append(modalHtml);

        if (response.success) {
            // Display product details
            modalContent = '<h3>Item Saved</h3>' +
                            '<div class="message">'+response.message+'</div>'+
                            '<dl class="product"><dt class="title">'+response.product.title+'</dt><dd>$'+response.price+'</dd></dl>'+
                            '<div class="footer">' +
                                '<a href="javascript:$j.modal.close();" class="close-modal"><img src="/images/skinny-modal-btn-continue-shopping.gif" alt="" /></a><a href="/my-account/?subpage=wishlist"><img src="/images/skinny-modal-btn-go-to-my-wishlist.gif" alt="" /></a>' +
                            '</div>';
        } else {
            // Not displaying product details
            modalContent = '<h3>Item Not Saved</h3>' +
                            '<span class="mesage">'+response.message+'</span>';
        }

        // Set modal window content
        $j('#wishlist-modal .modal-content').html(modalContent);

        $j("#wishlist-modal").modal({
            closeHTML: '<a href="javascript:void(0)" title="Close" class="generic-modal-close"></a>',
            containerId: "generic-modal-container",
            position: ["25%"],
            onShow: function() {
                //$j('#feedback-modal .added-to-cart').show();
            },
            onClose: function() {
                // Close modal manually
                $j.modal.close();
                // Remove modal window markup
                $j("#wishlist-modal").remove();
            }
        });

        // Update wishlist counter widget
        if (response.totalItems > 0) {
            var html ='<a href="/my-account?subpage=wishlist" class="cart-total" id="wl-total">'+response.totalItems+' '+ ((response.totalItems > 1) ? 'Items' : 'Item') +'</a>';
            $j('#wl-total').replaceWith(html);
        } else {
            $j('#wl-total').replaceWith('<span class="cart-total" id="wl-total">No items</span>');
        }
        

        /*
        $j(data).modal({
            closeHTML: "<a href='#' title='Close' class='modalCloseX simplemodal-close'>x</a>",
            position: ["15%",],
            overlayId: 'contact-overlay',
            containerId: 'contact-container',
            onOpen: contact.open,
            onShow: contact.show,
            onClose: contact.close
        });
        // update wishlist counter
        $j.get("/load.php?module=moduleMyAccountLJ&action=totalWishlistItems&ajaxcall=1", function(total){
            if (total){
                $j("#wl-total").empty();
                $j("#wl-total").append(total);
            }
        })
        */
    }, 'json');
}

/**
 * Removes an item from the cart/session
 */
function removeFromCart(productId)
{
    $j.get("/load.php?module=moduleMyAccountLJ&action=removeFromCart&product_id=" + productId, function(data) {
        // Re-calculate cart totals
        recalculateCart();

//        console.log(data);
//        // show message on modal box
//        $j(data).modal({
//            closeHTML: "<a href='#' title='Close' class='modalCloseX simplemodal-close'>x</a>",
//            position: ["15%",],
//            overlayId: 'contact-overlay',
//            containerId: 'contact-container',
//            onOpen: contact.open,
//            onShow: contact.show,
//            onClose: contact.close
//        });
        // update wishlist counter
//        $j.get("/load.php?module=moduleMyAccountLJ&action=totalWishlistItems&ajaxcall=1", function(total){
//            if (total){
//                $j("#wl-total").empty();
//                $j("#wl-total").append(total);
//            }
//        })
    });
}

/*
 * Set selected product on cart's form
 * Show selected product price
 * Show selected size
 */
function setProductId(id){
	/* update product_id field */
	$("product_id").value=id;

	/* update product price */
	for(i in products){
		if(products[i].id && products[i].id==id){
			/* on special item */
			if (products[i].onSpecial==true){
				$("price-value").innerHTML = '<strike>'+eval(products[i].price)+'</strike> '+ eval(products[i].specialPrice);
			/* full price item */
			}else {
				$("price-value").innerHTML = eval(products[i].price);
			}
			break;
		}
	}

	/* Marked selected size  */
	$each( $("size").getElements('li'),
                function(el,ind){
                        el.className = el.className.replace("active","");
                }
        );
	$("size-"+id).className='active';

        //Update colour & size label
        updateColourSizeLabel();


}


/*
 * Change product colour
 **/
function changeColour(id){

        if (!$("product_id"))
                return;

	$each($("colour-list").getElements('li'),function(el,ind){el.className='';});
	$("colour-li-"+id).className='active';
	obj = eval('p_manager.colour'+id);

	//out of stock
	if (obj.out_of_stock_product==1){
		$('size').innerHTML = 'Colour currently out of stock. Please select other colour.';
		$("product_id").value = 0;
		$("price-value").innerHTML = 0;
		return;
	}

	if (obj.sizes) {
		$("size").innerHTML = obj.sizes;
	} else {
		$("size").innerHTML = '<li>No sizes option</li>';
	}
	$("product_id").value = obj.product_id;

        //update colour & size label
        updateColourSizeLabel();

	//$("price-value").innerHTML = eval('price'+$("product_id").value);

}


function showOutofStock(){
	alert('Sorry this item has sold out online. Please contact the LJ Angel Service on 1300 LORNA JANE to order your must-have style');
}

function showLimitedStock(){
	alert('This product has limited stock. \n Please adjust your order quantity.');
}

/*
 * Check product's stock againts order quantity
 */
function checkProductStock(){
	for(i in products){
		if(products[i].id && products[i].id==document.shoppingFrm.id.value){
			/* Out of Stock */
			if (products[i].stock<=0){
				showOutofStock();
				return false;
			/* Order Qty > Stock */
			}else if (document.shoppingFrm.qty.value>products[i].stock){
				//document.shoppingFrm.qty.focus();
				showLimitedStock();
				return false;
			}
		}
	}
	return true;
}

/*
 * Validate Cart Form before submit
 */
function validateShoppingFrm(){

    if (!document.shoppingFrm.id.value || document.shoppingFrm.id.value<=0){
        alert('There is no product selected \n or \nThe product you selected is currently out of stocks');
        return false;
    }else {
        /* check order quantity */
        if (!checkProductStock()){
            return false;
        }
        /* submit form after pass validation */

        document.shoppingFrm.submit();
        return true;
    }
}

function searchFilterValidation(form){
	var defaultKeyword = 'enter keyword';
	if(form.keyword.value==defaultKeyword && form.categorysrc.value=='' && form.coloursrc.value=='' && form.sizesrc.value==''){
		alert('Please enter search filter criteria');
		return false;
	}else if(form.keyword.value==defaultKeyword){
		form.keyword.value='';
		return true;
	}
        return true;
}

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
		//return false;
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}

/*
 * Show selected thumbnail on as hero image
 */
function updateHero(obj, dimensions){
	if (obj.getAttribute('href') && $('hero_image') && $('slimbox_href')){
		$('hero_image').setAttribute('src', obj.getAttribute('href')+'&s='+dimensions+'&q=90&t=1');
		//$('hero_image').setAttribute('src',obj.getAttribute('href')+'&s=266x400&q=90');
		$('slimbox_href').setAttribute('href', obj.getAttribute('href'));
	}
}

/*
 * Update size label when mouseover / mouseout
 */
function updateColourLabel(value,over){
        if (!value || !$("colour_label"))
                return;
        if (over){
                $("colour_label").innerHTML = value;
        }else {
                $("colour_label").innerHTML = getSelectedColour();
        }
}

/*
 * Update size label when mouseover / mouseout
 */
function updateSizeLabel(value,over){
        if (!value || !$("size_label"))
                return;
        if (over){
                $("size_label").innerHTML = value;
        }else {
                $("size_label").innerHTML = getSelectedSize();
        }
}

function updateSelectedLabel(){
        if ($("selected_label")){
                $("selected_label").innerHTML = '';
                if ($('product_id') && $('product_id').value && $('product_id').value>0){
                        $("selected_label").innerHTML += 'Colour: '+getSelectedColour();
                        $("selected_label").innerHTML += ', Size: '+getSelectedSize();
                }else {
                        $("selected_label").innerHTML = 'No product currently selected';
                }
        }
}

function updateColourSizeLabel(){
        updateColourLabel(getSelectedColour(),1);
        updateSizeLabel(getSelectedSize(),1);
        updateSelectedLabel();
}


/*
 * Get selected size
 **/
function getSelectedSize(){
        var size = '';
        if ($('product_id') && $('product_id').value){
                for(i in products){
                        if (products[i].id && products[i].id==$('product_id').value){
                                size = products[i].sizeLabel;
                        }
                }
        }
        return size;
}

/*
 * Get selected colour
 **/
function getSelectedColour(){
        var colour = 'Not Available';
        if ($('product_id') && $('product_id').value){
                for(i in products){
                        if (products[i].id && products[i].id==$('product_id').value){
                                colour = products[i].colourLabel;
                        }
                }
        }
        return colour;
}


/*
 * Product Thumbnail Navigation
 **/
function productThumbnailNav(offset){
    /* Set number of slides */
    if ($('carousel-images')){
        //calculate from number of images divide by 3 (3 images at one slide)
        var ulChildren = $('carousel-images').childNodes;
        var slides = Math.ceil(ulChildren.length/2);
        var slides_active_nation = ulChildren.length-2;
    } else {
        var slides = 1;
        var slides_active_nation = 1;
    }

    var pos = 0;
    //var offset = 186;  //how much to slide each time. 2 x 80px plus 2 x 13px margin
    var offset_active_nation = 143
    var currentslide = 1;											// CURRENT SLIDE IS THE FIRST SLIDE

    if ($('carousel-wrapper')){
        var imgscroll = new Fx.Scroll('carousel-wrapper', {
            offset: {
                'x': 0,
                'y': 0
            },
            transition: Fx.Transitions.Cubic.easeOut
        }).toLeft();
    }


    /* EVENTS - WHEN AN ARROW IS CLICKED THE THUMBNAILS SCROLL */
    if ($('carousel-prev')){
        $('carousel-prev').addEvent('click', function(event) {
            event = new Event(event).stop();
            if(currentslide == 1) return;
            currentslide--;																	// CURRENT SLIDE IS ONE LESS
            pos += -(offset);															   // CHANGE SCROLL POSITION
            var imgscroll = new Fx.Scroll('carousel-wrapper', {
                offset: {
                    'x': pos,
                    'y': 1
                },
                transition: Fx.Transitions.Cubic.easeOut
            }).toLeft();
        });
    }

    if ($('carousel-prev-an')){
        $('carousel-prev-an').addEvent('click', function(event) {
            event = new Event(event).stop();
            if(currentslide == 1) return;
            currentslide--;																	// CURRENT SLIDE IS ONE LESS
            pos += -(offset_active_nation);													// CHANGE SCROLL POSITION
            var imgscroll = new Fx.Scroll('carousel-wrapper', {
                offset: {
                    'x': pos,
                    'y': 1
                },
                transition: Fx.Transitions.Cubic.easeOut
            }).toLeft();
        });
    }

    if ($('carousel-next')){
        $('carousel-next').addEvent('click', function(event) {
            //alert('next='+currentslide+'='+slides);
            event = new Event(event).stop();
            if(currentslide >= slides) return;
            currentslide++;
            pos += offset;
            var imgscroll = new Fx.Scroll('carousel-wrapper', {
                offset: {
                    'x': pos,
                    'y': 1
                },
                transition: Fx.Transitions.Cubic.easeOut
            }).toLeft();
        });
    }

    if ($('carousel-next-an')){
        $('carousel-next-an').addEvent('click', function(event) {
            event = new Event(event).stop();
            if(currentslide >= slides_active_nation) return;
            currentslide++;
            pos += offset_active_nation;
            var imgscroll = new Fx.Scroll('carousel-wrapper', {
                offset: {
                    'x': pos,
                    'y': 1
                },
                transition: Fx.Transitions.Cubic.easeOut
            }).toLeft();
        });
    }
}

/**
 *
 */
function correctQty(el)
{
    var val = el.val();
    newVal = parseInt(val);
    if (isNaN(newVal)) el.val('')
    else el.val(newVal);
}

/**
 * Update cart summaries spread out over the page
 * @todo - pp
 */
function updateCartSummary(total, checkoutUrl, widgetVirtualCartOutput)
{
    var summary, html;
    if (total >= 1) {
        if (total == 1) summary = '1 item';
        else if (total > 1) summary = total + ' items';
        html = '<a href="' + checkoutUrl + '" id="cart-summary" class="cart-summary"><span class="items-summary">'+summary+'</span></a>'; // 1 item
    } else {
        html = '<span class="cart-summary" id="cart-summary">No items</span>';
    }
    $j('#cart-summary').replaceWith(html);

    // Check if inline summary in product list is also present
    if ($j('#cart-total')) {
        
        if (total >= 1) {
            if (total == 1) summary = '1 item';
            else if (total > 1) summary = total + ' items';
            html = '<a href="'+checkoutUrl+'" id="cart-total" class="cart-total">'+summary+'</a>'; // 1 item
        } else {
            html = '<span class="cart-total" id="cart-total">No items</span>';
        }

        $j('#virtualcart').remove();
        $j('.show-block span.cart').replaceWith(widgetVirtualCartOutput);
        if (total >= 1) {
            $j("#cart-total").click(function() {
                $j("#virtualcart").slideToggle(500, function() {});
            });
        }
    }
    //$j('#cart-total').replaceWith(html);
}

/**
 * Some code that aids adding featured products to the cart
 */
function initFeatureProducts()
{
    // Cast qty to integer on keyup & blur
    $j('#featured-products input.qty').each(function() {
        $j(this).keyup(function() { correctQty($j(this)); });
        $j(this).blur(function() { correctQty($j(this)); });
    });

    // Create masks for buttons and form fields
    $j('#featured-products .controls').each(function() {
        var parent = $j(this);
        parent.css('position', 'relative');
        $j('<div/>')
            .addClass('mask')
            .css({
                height: parent.height(),
                width: parent.width(),
                opacity: 0.7,
                background: '#FFFFFF',
                position: 'absolute',
                zIndex: 9,
                top: 0,
                left: 0
            })
            .appendTo(parent);
    });
    
    // remove the mask of any out of stock items - no mask wanted
    $j('#featured-products .outofstock .controls .mask').remove();

    // Show/hide masks when the state of the checkboxes changes
    $j('#featured-products input[type="checkbox"]').each(function() {
        $j(this).change(function() {
            if ($j(this).is(':checked')) {
                $j(this).parents('li').find('.mask').fadeOut(300, function() {});
            } else {
                $j(this).parents('li').find('.mask').fadeIn(300, function() {});
            }
        });
    });

    var updateSelectedTotal = function() {
        var subTotal = 0;
        $j('#featured-products li').each(function(idx) {
            // Check if checkbox is checked, else ignore
            if ($j(this).find('input[type="checkbox"]').is(':checked')) {
                var liId = $j(this).attr('id');
                // Get the matching instance of the selectProduct plugin
                var selectProduct = $j('#'+liId).selectFeaturedProduct({});

                var qty = parseInt($j('#qty-'+selectProduct.getId()).val());
                if (qty) {
                    subTotal += parseInt($j('#qty-'+selectProduct.getId()).val()) * selectProduct.getPrice();
                }
            }
        });
        // Update sub total
        if (subTotal == 0) subTotal = '000.00';
        else subTotal = subTotal.toFixed(2)
        $j('#featured-footer .amount').html('$'+subTotal);
    }

    // Update sub total each time the amount changes or a checkbox gets checked/unchecked
    $j('#featured-products input[type="text"]').keyup(function() {
        updateSelectedTotal();
    });
    $j('#featured-products input[type="checkbox"]').click(function() {
        updateSelectedTotal();
    });


    // remove the bound click event if it exists - the parent function is called after AJAX calls
    $j('#add-selected-to-cart').unbind('click');

    // Add to cart
    $j('#add-selected-to-cart').click(function() {
        var valid = false;
        var productsToAdd = new Array();
        // Iterate featured products and validate one by one until valid
        $j('#featured-products li').each(function(idx) {
            // Check if checkbox is checked, else ignore
            if ($j(this).find('input[type="checkbox"]').is(':checked')) {
                var liId = $j(this).attr('id');
                // Get the matching instance of the selectProduct plugin
                var selectProduct = $j('#'+liId).selectFeaturedProduct({});
                // validate individual product
                pValid = selectProduct.validate(true);
                if (!pValid) {
                    valid = false;
                    return;
                } else {
                    valid = true;
                    productsToAdd.push({
                        id: selectProduct.getRelatedId(),
                        title: selectProduct.getTitle(),
                        qty: selectProduct.getQty(),
                        currency: selectProduct.getCurrency(),
                        color: selectProduct.getSelectedColor(),
                        size: selectProduct.getSelectedSize(),
                        price: selectProduct.getPrice()
                    });
                }
            }
        });

        if(productsToAdd.length == 0) {

            var modalContent = '<span class="message"><br>Please select one or more products to be added to the cart.</span>';

            // Set modal window content
            $j('#feedback-modal .title').html('No item selected');
            $j('#feedback-modal .modal-content').html(modalContent);

            $j("#feedback-modal").modal({
                closeHTML: '<a href="javascript:void(0)" title="Close" class="generic-modal-close"></a>',
                containerId: "generic-modal-container",
                position: ["25%"],
                onShow: function() {
                    //$j('#feedback-modal .added-to-cart').show();
                },
                onClose: function() {
                    // Close modal manually
                    $j.modal.close();
                }
            });
            return;

        }

        // Check if we can go ahead and add the selected items to the shopping cart
        if (valid) {
            $j.ajax({
                type: 'POST',
                url: "/load.php",
                data: {
                    form_type: 'shopping_cart',
                    action: 'add',
                    products: productsToAdd,
                    currency: productsToAdd[0].currency,
                    // Return freshly squeezed widgetVirtualCartLJ output
                    return_virtual_cart: true,
                    page: currentPageId
                },
                success: function(response) {
                    if (response.totalItems) {
                        // Update cart summary
                        updateCartSummary(response.totalItems, response.checkoutURL, response.virtual_cart);
                        
                        // Build modal window froms scratch
                        var modalHtml = '<div id="added-to-cart-modal" class="generic-modal">' +
                                        '<h2 class="title">&nbsp;</h2>' +
                                        '<div class="modal-content"></div>' +
                                    '</div>';
                        // Append to DOM
                        $j('body').append(modalHtml);
                        var modalContent = '<h3>'+ (productsToAdd.length > 1 ? 'Items' : 'Item') +' added to cart</h3>';
                        modalContent += '<table class="added-to-cart">';
                        modalContent += '<caption>You have just added the following '+ (productsToAdd.length > 1 ? 'items' : 'item') +' to your shopping cart:</caption>';
                        // Iterate products array as we've posted it to the server
                        // and build the report'
                        $j.each(productsToAdd, function() {
                            modalContent += '<tr><td class="strong selected-product">'+this.title+'</td><td class="qty">'+this.qty+'</td><td class="size">'+this.size+'</td><td class="colour">'+this.color+'</td><td class="price">$'+this.price+'</td></tr>';
                        })
                        modalContent += '</table>';
                        modalContent += '<div class="footer">' +
                                        '<a href="javascript:$j.modal.close(); " class="close-modal"><img src="/images/skinny-modal-btn-continue-shopping.gif" alt="" /></a><a href="'+response.checkoutURL+'"><img src="/images/skinny-modal-btn-proceed-to-checkout.gif" alt="" /></a>' +
                                        '</div>';
                        // Set modal window content
                        $j('#added-to-cart-modal .modal-content').html(modalContent);
                        // Initialise modal window
                        $j("#added-to-cart-modal").modal({
                            closeHTML: '<a href="javascript:void(0)" title="Close" class="generic-modal-close"></a>',
                            containerId: "generic-modal-container",
                            position: ["25%"],
                            onShow: function() {},
                            onClose: function() {
                                // Close modal manually
                                $j.modal.close();
                                // Remove modal window markup
                                $j("#added-to-cart-modal").remove();
                            }
                        });
                    }
                }
            });
        }
    });

    initRequestStyleAJAX();

}

/* function handles the AJAX submission for Request a Style  */
function initRequestStyleAJAX() {

        //
    $j('#request_modal form').submit( function() {

        // if this form is valid?
        if (!$j('#request_modal form').valid() ) {
            return false;
        }

        // prepare the fields
        $j.ajax({
            type: 'POST',
            url: "/load.php",
            data: {
                form_type: 'form2LJ',
                form_id:  7,
                honeypot: $j('input[name="honeypot"]').val(),
                field_126: $j('input[name="field_126"]').val(),
                field_127: $j('input[name="field_127"]').val(),
                field_128: $j('input[name="field_128"]').val(),
                field_129: $j('input[name="field_129"]').val(),
                field_130: $j('input[name="field_130"]').val(),
                field_131: $j('textarea[name="field_131"]').val()
            },
            success: function(response) {

                // NOTE: code mocks 'success' if the honey pot is set!

                // close the modal form.
                $j.modal.close();

                var modalContent = '<span class="message"><br>Thank you, your request has been received.<br><br> A Lorna Jane Angel will be in touch with you shortly.</span>';

                // Set modal window content
                $j('#feedback-modal .title').html('Thank you for your request');
                $j('#feedback-modal .modal-content').html(modalContent);

                $j("#feedback-modal").modal({
                    closeHTML: '<a href="javascript:void(0)" title="Close" class="generic-modal-close"></a>',
                    containerId: "generic-modal-container",
                    position: ["25%"],
                    onShow: function() {
                    },
                    onClose: function() {
                        // Close modal manually
                        $j.modal.close();

                        // validate does not like succeeding twice on a page. ick
                        //location.reload();
                    }
                });

            }
        });

        _gaq.push(['_trackPageview', '/products/RequestStyleSubmit.htm']);

        return false;
    });

}

/**
 * Some code that aids adding product packs to the cart
 */
function initProductPack(productId, currency, pack)
{
    $j('<div />')
        .attr('id', 'add-product-pack-mask')
        .css({
            position: 'absolute',
            zIndex: 9,
            width: $j('#final-step').width(),
            height: $j('#final-step').height(),
            opacity: 0.6,
            backgroundColor: '#e7e7e7',
            top: 0,
            left: 0
        })
        .appendTo($j('#final-step'));

    // Detect add to cart button click for pack
    $j('#add-product-pack').click(function() {
        // Iterate products in pack and validate each one
        var valid = true;
        var productsToAdd = new Array();
        var selectedProducts = new Array();
        $j('#product-pack li').each(function() {
            var productInPack = $j(this).productInPack({});
            selectedProducts.push(productInPack.getRelatedId());
            productsToAdd.push({
                title: productInPack.getTitle(),
                qty: 1,
                color: productInPack.getSelectedColor(),
                size: productInPack.getSelectedSize()
            });
            // Force validation
            if (!productInPack.validate()) {
                valid = false;
            }
        });

        if (valid) {
            // Add product pack to cart already!
            $j.ajax({
                type: 'POST',
                url: "/load.php",
                data: {
                    form_type: 'shopping_cart',
                    action: 'add',
                    id: productId,
                    qty: 1,
                    currency: currency,
                    ispack: 1, // Important for cmsShoppingCartLJ::addToExisting()
                    selected: selectedProducts
                },
                success: function(response) {
                    if (response.totalItems) {
                        
                        // Update cart summary
                        updateCartSummary(response.totalItems, response.checkoutURL);
                        
                        // Build modal window froms scratch
                        var modalHtml = '<div id="added-to-cart-modal" class="generic-modal">' +
                                        '<h2 class="title">&nbsp;</h2>' +
                                        '<div class="modal-content"></div>' +
                                    '</div>';
                        // Append to DOM
                        $j('body').append(modalHtml);
                        var modalContent = '<h3>Item added to cart</h3>';
                        modalContent += '<table class="added-to-cart">';
                        modalContent += '<caption>You have just added the following item to your shopping cart:</caption>';
                        // Iterate products array as we've posted it to the server
                        // and build the report'
                        modalContent += '<tr><td class="strong selected-product">'+pack.title+'</td><td class="qty">1</td><td></td><td class="colour"></td><td class="price">$'+pack.price+'</td></tr>';
                        $j.each(productsToAdd, function() {
                            modalContent += '<tr><td class="strong selected-product-small">'+this.title+'</td><td class="qty"></td><td class="size">'+this.size+'</td><td class="colour">'+this.color+'</td><td class="price"></td></tr>';
                        })
                        modalContent += '</table>';
                        modalContent += '<div class="footer">' +
                                        '<a href="javascript:$j.modal.close(); " class="close-modal"><img src="/images/skinny-modal-btn-continue-shopping.gif" alt="" /></a><a href="'+response.checkoutURL+'"><img src="/images/skinny-modal-btn-proceed-to-checkout.gif" alt="" /></a>' +
                                        '</div>';
                        // Set modal window content
                        $j('#added-to-cart-modal .modal-content').html(modalContent);
                        // Initialise modal window
                        $j("#added-to-cart-modal").modal({
                            closeHTML: '<a href="javascript:void(0)" title="Close" class="generic-modal-close"></a>',
                            containerId: "generic-modal-container",
                            position: ["25%"],
                            onShow: function() {},
                            onClose: function() {
                                // Close modal manually
                                $j.modal.close();
                                // Remove modal window markup
                                $j("#added-to-cart-modal").remove();
                            }
                        });
                    }
                }
            });
        }
    });
}


