/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);
;

$.fn.pause = function(duration) {
    $(this).animate({ dummy: 1 }, duration);
    return this;
};

$.fn.visible = function(visible) {
    if (visible) {
        this.show();
    }
    else {
        this.hide();
    }
};

$.fn.assertSize = function(size) {
    if (this.size() != size) {
        alert("Expected " + size + " elements for expression '" + this.selector + "', but got " + this.size() + ".");
    }
    return this;
};

$.fn.assertOne = function() {
if (this.size() != 1) {
    alert("Expected " + 1 + " element for expression '" + this.selector + "', but got " + this.size() + ".");
    }
    return this;
};

$.fn.assertNonEmpty = function() {
    if (this.size() == 0) {
        alert("Expected 1 or more element for expression '" + this.selector + "', but got " + this.size() + ".");
    }
    return this;
};


$.fn.equalizeCols = function () {
    var height = 0;
    this.css("height", "auto").each(function () {
        height = Math.max(height, jQuery(this).height()); 
    }).css("height", height);
    return;
};

$.fn.initSimpleTabs = function () {

    var tabs = this;
    $(tabs).find('.simple-tabs-list li').click(function () {
        var index = $(tabs).find('.simple-tabs-list li').index(this);
        $(tabs).find('.simple-tab').hide();
        //$(tabs).find(':not(.simple-tab:eq(' + index + '))').hide();
        $(tabs).find('.simple-tab:eq(' + index + ')').assertOne().show();
        //$(tabs).find('.simple-tab:eq(' + index + ')').assertOne().removeClass('hidden');
    });
}
;
function enableDebugging() {

    $(document).ready(function() {

        $('[id]').each(function() {
            var ids = $('[id=' + this.id + ']');
            if (ids.length > 1 && ids[0] == this)
                alert('Multiple IDs #' + this.id);
        });

        // CDN images
        //$("img[src^=http://img1.rollingrazor.com]").css("border", "solid 1px red");

    });

}


 
;
var RRStore = {

};

// update the quantity of items in the cart
RRStore.updateMultipleProducts = function (productQuantities, params) {

    if (params == null) {
        params = {};
    }

    var data = "";
    for (var i = 0; i < productQuantities.length; i++) {
        if (data != "") {
            data += "&";
        }
        data += "sku[" + i + "]=" + (productQuantities[i].sku === undefined ? null : productQuantities[i].sku) + "&";
        data += "orderItemId[" + i + "]=" + productQuantities[i].orderItemId + "&";
        data += "qty[" + i + "]=" + productQuantities[i].qty;
    }

    if (params.showWaitPopup != false) {
        ShowWaitPopup();
    }

    $.ajax({

        type: "POST",
        url: $.url("updateCart"),
        data: data,
        dataType: "json",

        success: function (data, status, req) {

            HideWaitPopup();

            if (data == null) {
                return;
            }

            try {

                // refresh cart model
                RRStore.updateJSCartModel(data.JSCartModel);
                RRStore.updateTopBar(data.OrderSummaryText); // synchronous

                // verify the cart was updated ok (only works for skus, not orderItemId)
                if (RRStore.cartContainsProductQuantities(productQuantities) == false) {
                    alert("Error! Please click your browser's Refresh button. The cart could not be successfully updated");
                }

                // callback
                if (params != null && params.callback != null) {
                    params.callback();
                }

            } catch (e) {
                alert("Error handling callback. Please check your connection and try again. " + e);
            }

        },

        complete: function () {

            HideWaitPopup();
        }

    });
}

RRStore.updateJSCartModel = function(model) {

    RRStore.cart = model;

    // update pricing summary
    $('#cart_subTotal .price').html(RRStore.formatCurrency(RRStore.getPricingSummary().subTotal));
    $('#cart_discount .price').html(RRStore.formatCurrency(RRStore.getPricingSummary().discount));

    if (RRStore.getPricingSummary().shippingTotal == 0) {
        $('#cart_shippingTotal .price').html("FREE");
    }
    else {
        $('#cart_shippingTotal .price').html(RRStore.formatCurrency(RRStore.getPricingSummary().shippingTotal));
    }

    $('#cart_tax .price').html(RRStore.formatCurrency(RRStore.getPricingSummary().taxes), "Need address");
    $('#cart_total .price').html(RRStore.formatCurrency(RRStore.getPricingSummary().total));

    $('#pnlAmountDue #lblAmountDue').html(RRStore.formatCurrency(RRStore.getPricingSummary().total));

    if (RRStore.getTotalItemCount() > 0) {
        $('#btnViewCart').fadeIn("slow");
    } else {
        $('#btnViewCart').fadeOut();
    }

    // update individual item prices
    if ($('[id^=lblCartItemTotal_]').length > 0) {
        for (var i = 0; i < RRStore.cart.CartItems.length; i++) {
            $('#lblCartItemTotal_' + RRStore.cart.CartItems[i].orderItemId).html(RRStore.formatCurrency(RRStore.cart.CartItems[i].total));
        }
    }

};

// update kit (or create new)
RRStore.updateKitCustomization = function(data, params) {

var queryString = "name=" + data.name + "&cartItemId=" + data.cartItemId + "&optionsJSON=" + JSON.stringify(data.options);
    
     $.ajax({

        type: "POST",
        url: $.url("updateKitCustomization"),
        data: queryString,
        dataType: "json",

        success: function(data) {

            // callback
            if (params != null && params.callback != null) {
                params.callback();
            }
        }

    });

};

// AJAXLogin
RRStore.login = function (username, password, params) {

    $.ajax({

        type: "POST",
        url: $.url("login"),
        data: "username=" + username + "&password=" + password,
        dataType: "json",

        success: function (data) {

            // callback
            if (params != null && params.callback != null) {
                params.callback(data);
            }
        },

        error: function (data) {
            if (params != null && params.error != null) {
                params.error(data);
            }
        }

    });
}

RRStore.logout = function(params) {
    $.ajax({

        type: "POST",
        url: $.url("logout"),
        dataType: "json",

        success: function(data) {

            // callback
            if (params != null && params.callback != null) {
                params.callback(data);
            }

            // fade out current user
            $('#pnlCurrentUserInfo').fadeOut();
            AlertDialog("You have been logged out.");
            $('#LoginDetails_Username').focus();
            $('#LoginDetails_Password').val("");
        }
    });
}

RRStore.forgotPassword = function (email) {

	if ($.trim(email) == "") {
		AlertDialog("You must enter your username!", "Missing username");
		return false;
	}

	if ($.trim(email).indexOf("@") == -1 || $.trim(email).indexOf(".") == -1) {
		AlertDialog("You must enter a valid email!", "Invalid email");
		return false;
	}


	RollingRazorDialog("Forgotten Password", $.url('forgotPasswordPopup').replace("XXX", email), { width: "550px", height: "380px", initMsg: "Please wait...", showOKButton: false });

};

RRStore.sendResetPassword = function (params) {

	$.ajax({

		type: "POST",
		cache: false,
		url: $.url("forgotPassword"),
		data: "ajax=true&sendResetCode=true&email=" + params.email,
		dataType: "json",

		success: function (data) {

			// callback
			if (params != null && params.callback != null) {
				params.callback(data);
			}
		},

		error: function () {
			alert("Sorry there was an error");
		}
	});

};

RRStore.resetPasswordWithResetCode = function (params) {

	$.ajax({

		type: "POST",
		cache: false,
		url: $.url("resetPassword"),
		data: "ajax=true&email=" + params.email + "&resetCode=" + params.resetCode + "&newPassword=" + params.password + "&confirmPassword=" + params.password,
		dataType: "json",

		success: function (data) {

			// callback
			if (params != null && params.callback != null) {
				params.callback(data);
			}
		},

		error: function () {
			alert("Sorry there was an error");
		}
	});

};



// AJAXGetUser
RRStore.getUser = function(username, params) {

    if (username == null || username == ""){    
        params.callback({found:false});
        return;
    }
    
    $.ajax({

        type: "POST",
        url: $.url("getUser"),
        data: "username=" + username,
        dataType: "json",

        success: function(data) {

            // callback
            if (params != null && params.callback != null) {
                params.callback(data);
            }
        }

    });
}

// show cart popup
RRStore.showCartPopup = function(params) {

    RollingRazorDialog("Your Rolling Razor Cart", $.url('viewCartPopup'), { width: "750px", height: "450px", initMsg: "Retrieving Shopping Cart...", showOKButton: false });
}

// show fsp popup
RRStore.showFSPPopup = function(params) {

    RollingRazorDialog("Free Shipping Program Details", $.url('viewFSPPopup'), { width: "600px", height: "495px", initMsg: "Loading details...", showOKButton: true });
}

// show kit comparison
RRStore.compareKitsPopup = function(params) {
    RollingRazorDialog("Compare Gift Packs: What's included in each pack?", $.url('kitComparisonPopup').replace("SKU", params.sku), { width: "810px", height: "530px", initMsg: "Loading comparison...", showOKButton: true });
}

// show category helper popup
RRStore.showCategoryHelperPopup = function(params) {

    if (params.gender == "women") {
        RollingRazorDialog("Women's Blades", $.url('bladesHelperPopup').replace("XXX", params.gender), { width: "780px", height: "350px", initMsg: "Loading...", showOKButton: true });
    }
    else {
        RollingRazorDialog("Men's Blades", $.url('bladesHelperPopup').replace("XXX", params.gender), { width: "780px", height: "450px", initMsg: "Loading...", showOKButton: true });
    }
}


// update the quantity of items in the cart
RRStore.updateCart = function(sku, qty, params) {

    RRStore.updateMultipleProducts([{ sku: sku, qty: qty}], params);
};

RRStore.updateOrderItemQty = function(orderItemId, qty, params) {

    RRStore.updateMultipleProducts([{ orderItemId: orderItemId, qty: qty}], params);
};

// get pricing summary
RRStore.getPricingSummary = function() {
    return RRStore.cart.PricingSummary;
}

// get total item count
RRStore.getTotalItemCount = function() {
    return RRStore.cart.totalItemCount;
}

// get quantity of particular item
RRStore.getQuantity = function(sku) {

    if (RRStore.cart == null) {
        alert("No cart! Error! Please report");
    }

    if (RRStore.cart.SKUGrouped[sku] == null) {
        return 0;
    }

    return RRStore.cart.SKUGrouped[sku].qty;
};

// get cartitem
RRStore.getTotal = function(sku) {

    if (RRStore.cart == null) {
        alert("No cart! Error! Please report");
    }

    if (RRStore.cart.SKUGrouped[sku] == null) {
        return 0;
    }

    return RRStore.cart.SKUGrouped[sku].total;
};

// refresh the client side cart object model
//RRStore.refreshCart = function(callback) {

//    // load JSON
//    $.ajax({
//        type: "GET",
//        url: $.url("getJSONCart"),
//        dataType: "json",
//        cache: false,

//        success: function(data, status) {

//            RRStore.updateJSCartModel(data);
//            callback();
//        }
//    });

//    // update top bar
//    RRStore.updateTopBar();

//};

// updates the top bar with the correct summary text
RRStore.updateTopBar = function(html) {

    // show discount
    if (RRStore.getPricingSummary().discount == 0) {
        $('#cart_discount').hide();
    } else {
        $('#cart_discount').show();
    }

    if (html == null) {
        $.ajax({
            type: "GET",
            url: $.url("getOrderSummaryText"),
            dataType: "html",
            cache: false,

            success: function(data, status) {

                $('#pnlOrderSummaryText').replaceWith(data);
            }
        });
    }
    else {
        $('#pnlOrderSummaryText').replaceWith(html);
    }

    // slide down pnlShoppingCartTopPanel if we have items
    if (RRStore.getTotalItemCount() > 0) {
        $('#pnlShoppingCartTopPanel').slideDown();
    }
};


// look in the supplied element for all 'Qty_' dropdowns and pull out the quantities selected for each
RRStore.getProductQuantitiesFromChildControls = function(element) {

    var dropdowns;
    
    if (element == null) {
        dropdowns = $("[id^=Qty_]");
     } else {
        dropdowns = $(element).find("[id^=Qty_]");
     }

    var quantities = new Array();
    for (var i = 0; i < dropdowns.length; i++) {
        quantities.push({ sku: dropdowns[i].id.substring("Qty_".length), qty: $(dropdowns[i]).val() });
    }

    return quantities;

};

// returns true if the cart contains the same quantities in the list
// the parameter is an array of [{sku:"1024",qty:1}]
// IMPORTANT: If the cart contains EXTRA items...
RRStore.cartContainsProductQuantities = function(productQuantities) {

    for (var i = 0; i < productQuantities.length; i++) {
        var item = productQuantities[i];
        if (item.sku != undefined) {
            if (RRStore.getQuantity(item.sku) != item.qty) {
                //alert("quantity for " + item.sku + " expected " + item.qty + " but was " + RRStore.getQuantity(item.sku));
                return false;
            }
        }
    }

    return true;
}

// applies a promo code to the order and refetches order details
RRStore.applyPromoCode = function (promoCode, params) {

    $.ajax({

        type: "POST",
        url: $.url("applyPromoCode"),
        data: "promoCode=" + promoCode,
        dataType: "json",

        success: function (data) {

            // make sure promo is valid
            if (data.promoCodeUnappliable == true || data.freeQuantityNotMaximized == true) {
                var bladesQty = null;

                if (data.correctedCouponCodes.indexOf("BLADES15") != -1) {
                    bladesQty = 15;
                }
                else if (data.correctedCouponCodes.indexOf("BLADES7") != -1) {
                    bladesQty = 7;
                }
                else if (data.correctedCouponCodes.indexOf("BLADES") != -1) {
                    bladesQty = 4;
                }
                if (bladesQty != null) {
                    AlertDialog("<font color=red>You must add a <strong><u>total of " + bladesQty + " packs</u></strong> of blades to use this promocode. You can mix and match any styles you want.</font>", "Please review the items in your cart.");
                }
                else {
                    AlertDialog("Please check the terms of the promo code and ensure you are adding the correct items to your cart.", "Sorry, while this promo code is valid it does not result in a discount for your current order.");
                }
            }
            else if (data.promoCodeValid == false) {
                AlertDialog("Sorry, this promo code is invalid or has expired", "Invalid Promo Code");
            }

            // refresh cart model
            RRStore.updateJSCartModel(data.JSCartModel);
            RRStore.updateTopBar(); // async

            // callback
            if (params != null && params.success != null) {
                params.success(data);
            }
        },

        complete: function (data) {
            if (params != null && params.complete != null) {
                params.complete(data);
            }
        }

    });
}

// applies a new shipping rate to the order
RRStore.updateShipping = function(zip, stateCd, country, prefRate, params) {

    var shippingRatesQuery = "ZipOrPostal=" + zip + "&StateCd=" + stateCd + "&CountryCode=" + country + "&PrefRate=" + prefRate;

    $.ajax({

        type: "POST",
        cache: false,
        url: $.url("selectShippingMethod"),
        data: shippingRatesQuery,
        dataType: "json",

        success: function(data) {

            // refresh cart model
            RRStore.updateJSCartModel(data.JSCartModel);
            RRStore.updateTopBar(); // async

            // callback
            if (params != null && params.callback != null) {
                params.callback(data);
            }
        },

        error: function() {
        
        }
    });
}

RRStore.formatCurrency = function(amt, def) {

    return (amt == null) ? def : ("$" + amt.toFixed(2));
}

RRStore.customizeProduct = function(sku, cartItemId) {
 
    var query;
    if (sku != null) {
        query = "sku=" + sku;
    }
    if (cartItemId != null) {
        query = "cartItemId=" + cartItemId;
    }

    var updated = function() {

        $.ajax({
            type: "GET",
            url: $.url('getCartSummaryKitItemDescription') + "/" + cartItemId,
            dataType: "html",
            cache: false,

            success: function(data, status) {

                $("#cartsummary_itemdesc_" + cartItemId).assertOne().replaceWith(data);

            }
        });

    };

    RollingRazorDialog("Customize Kit", $.url('customizeKitPopup') + "?" + query, { width: "800px", height: "650px", initMsg: "Loading kit customizer...", showOKButton: false, closePopupCallback: updated });

};

////


RRStore.initStore = function (cart) {

    RRStore.updateJSCartModel(cart);

    // handle top bar buttons
    $('[id^=btnShoppingCartStep_]').click(function () {

        var stepName = this.id.substring("btnShoppingCartStep_".length);
        var buttonClicked = this;

        // determine if we're allowed to change step
        var qtyDropDowns = $("[id^=Qty_]");
        var qty = 0;
        for (var i = 0; i < qtyDropDowns.length; i++) {
            qty += parseInt($(qtyDropDowns[i]).val());
        }

        if (stepName == "Checkout" && qty == 0 && RRStore.getTotalItemCount() == 0) {
            AlertDialog("You cannot proceed to checkout because your cart is empty.", "Cart is empty");
            return false;
        }

        return true;
    });

    // logout
    $('#pnlCurrentUserInfo').click(function () {
        RRStore.logout();
        return false;
    });

    // customize poups
    $('[id^=lnkCustomize_]').click(function () {
        var sku = this.id.substring("lnkCustomize_".length);
        RRStore.customizeProduct(sku, null);
        return false;
    });

    // customize product options 
    $('[id^=lnkModifyProductOptions_]').live("click", function () {
        var cartItemId = this.id.substring("lnkModifyProductOptions_".length);
        RRStore.customizeProduct(null, cartItemId);
        return false;
    });

    // customize product options - open
    $('[id^=cartsummary_itemdesc_] .summary').live("click", function () {
        var cartItemId = $(this).closest('[id^=cartsummary_itemdesc_]')[0].id.substring("cartsummary_itemdesc_".length);
        $('#cartsummary_itemdesc_' + cartItemId + " .subitems").assertOne().slideDown();
        $(this).hide();
        return false;
    });

    // customize product options - close
    $('[id^=cartsummary_itemdesc_] .close').live("click", function () {
        var cartItemId = $(this).closest('[id^=cartsummary_itemdesc_]')[0].id.substring("cartsummary_itemdesc_".length);
        $('#cartsummary_itemdesc_' + cartItemId + " .subitems").assertOne().hide();
        $('#cartsummary_itemdesc_' + cartItemId + " .summary").assertOne().show();
        return false;
    });

    // for StoreProductSelector.ascx.cs
    // show popup for clicking on a product
    $('[id^=SPSlnk_]').click(function () {
        var sku = this.id.substring("SPSlnk_".length);
        RollingRazorDialog("Product Information", $.url('miniProductPopup').replace("SKU", sku), { width: "850px", height: "450px", initMsg: "Loading product information...", showOKButton: true });
        return false;
    });
    $('[id^=SPS_]').click(function () {
        var sku = this.id.substring("SPS_".length);
        RollingRazorDialog("Product Information", $.url('miniProductPopup').replace("SKU", sku), { width: "850px", height: "450px", initMsg: "Loading product information...", showOKButton: true });
    });

    // for ProductDropdownList.ascx
    // show popup for clicking on a product link
    $('[id^=PLNK_]').click(function () {
        var sku = this.id.substring("PLNK_".length);
        RRStore.showProductPopup(sku);
        return false;
    });

    // dropdown quantity changed so show update button
    $('.productQtySelector').change(function () {

        var button = $(this).next()[0];

        var newQty = $(this).val();

        // update
        RRStore.updateMultipleProducts(RRStore.getProductQuantitiesFromChildControls(), { showWaitPopup: false, callback: function () { } });

    });

    // update margin
    var updateSPSMargin = function () {
        if ($(this).is(":visible")) {   // race condition when item initially shown
            $(this).closest(".qtypanel").css("padding-left", 45 - ($(this).width() / 2));
        }
    }
}

RRStore.showProductPopup = function (sku) {
    RollingRazorDialog("Product Information", $.url('miniProductPopup').replace("SKU", sku), { width: "850px", height: "500px", initMsg: "Loading product information...", showOKButton: true });
}

RRStore.initializedOK = true;
// alert("OK!");

;

var currentRRPopup;
var _RRwaitDialogActive;
var RRwaitDialog;
var closePopupCallback;

function CloseCurrentPopup() {
    if (currentRRPopup != null) {
        currentRRPopup.hide();
    }
    currentRRPopup = null;
}


function RollingRazorDialog(title, contentUrl, params) {

    var handleOK = function() {
        this.cancel();
    };
    var handleCancel = function() {
        this.cancel();
    };
  
    if (params == null) {
        params = {width:"700px", height:"450px"};
    }

    if (params.buttons == null) {
        if (params.showOKButton != false) {
            params.buttons = [{ text: "OK", handler: handleOK, isDefault: true}];
        }
    }

    if (params.closePopupCallback != null) {
        closePopupCallback = params.closePopupCallback;
    }
    else {
        params.closePopupCallback = null;
    }
    
    


    currentRRPopup = new YAHOO.widget.Dialog("rrDialog",
                                                    { 
                                                        width: params.width, height: params.height,
                                                        fixedcenter: true,
                                                        close: true,
                                                        draggable: true,
                                                        zindex: 4,
                                                        modal: true,
                                                        overlay: {
                                                            backgroundColor: '#000000',
                                                            opacity: 1
                                                        },
                                                        underlay : "matte",
                                                        visible: false,
                                                        constraintoviewport: true,
                                                        buttons: params.buttons
                                                    }
                                                );

    var initMsg = params.initMsg == null ? "Loading...." : params.initMsg;

    currentRRPopup.setHeader("Loading, please wait...");
    currentRRPopup.setBody("<div id='pnlLoading' style='text-align:center; padding-top:120px'><strong>" + initMsg + "</strong><br><img src=\"https://www.rollingrazor.com/content/images/icons/loading.gif\"/></div>");
    // " + $.content("~/content/images/icons/loading.gif") + "
    
    enableEscape(currentRRPopup);
    currentRRPopup.render(document.body);

    var resize = new YAHOO.util.Resize('rrDialog', {
        handles: ['br'],
        autoRatio: false,
        minWidth: 300,
        minHeight: 100,
        status: false
    });

    resize.on('resize', function(args) {
        var panelHeight = args.height;
        this.cfg.setProperty("height", panelHeight + "px");
    }, currentRRPopup, true);

    function fnCallback(e) {
        
        // kill all videos in all popups
        $(".yui-panel [id^=player_]").each(function() {
            swfobject.removeSWF(this.id); // #&#&#&#&#&#&#&
        });

        currentRRPopup = null;

        if (closePopupCallback != null) {
            closePopupCallback();
        }
    }

    currentRRPopup.beforeHideEvent.subscribe(fnCallback);
    currentRRPopup.show();

    $.ajax({

        type: "GET",
        cache: false,
        url: contentUrl,
        dataType: "html",

        success: function(data) {
            currentRRPopup.setHeader(title);
            $('#' + currentRRPopup.id).assertOne().find('.bd').assertOne().html(data);
            currentRRPopup.center();
        },

        error: function() {
        currentRRPopup.setHeader("Error");
            $('#' + currentRRPopup.id).assertOne().find('.bd').assertOne().html("Sorry an error has occured. Please click 'OK' and try again.");
        }

    });

//    $.get(contentUrl, null, function(response) {
//        waitDialog.setHeader(title);
//        $('#' + waitDialog.id).assertOne().find('.bd').assertOne().html(response);
//        waitDialog.center();
//    }, "rrDialog");

    return false;
}

function enableEscape(panel) {

    var kl = new YAHOO.util.KeyListener(document, { keys: 27 },
											      { fn: panel.hide,
											      scope: panel,
											      correctScope: true
											  });

    panel.cfg.queueProperty("keylisteners", kl);
}

function HideWaitPopup() {

    if (RRwaitDialog != null) 
    {
        RRwaitDialog.hide();
    }

    _RRwaitDialogActive = false;
}

function ShowWaitPopup(title) {

    if (title == null) {
        title = "Updating your order";
    }
    if (RRwaitDialog == null) {
    
        RRwaitDialog =

		new YAHOO.widget.Panel("wait",

			{ width: "250px",
			    fixedcenter: true,
			    close: false,
			    draggable: false,
			    zindex: 4,
			    modal: true,
			    visible: false
			}
		);

		RRwaitDialog.setHeader(title);
		RRwaitDialog.setBody('<img src="https://www.rollingrazor.com/content/images/icons/loading.gif" width="220" height="19"/>');
        RRwaitDialog.render(document.body);
    }

    _RRwaitDialogActive = true;
    setTimeout(function() {
        if (_RRwaitDialogActive) {
            RRwaitDialog.show();
        }
    }, 400);
}

function YesNoDialog(text, yesCallback, noCallback) {

    var mySimpleDialog = new YAHOO.widget.SimpleDialog("dlg", {
        width: "30em",
        fixedcenter: true,
        modal: true,
        visible: false,
        draggable: false
    });

    enableEscape(mySimpleDialog);
    
    mySimpleDialog.setHeader("Question");
    mySimpleDialog.setBody(text);
    mySimpleDialog.cfg.setProperty("icon", YAHOO.widget.SimpleDialog.ICON_TIP);

    if (yesCallback == null) {
        yesCallback = function() { alert('Warning: No callback assigned'); this.hide(); };
    }
    else {
        var chainedCallback1 = yesCallback;
        yesCallback = function() { chainedCallback1(); this.hide(); };
    }

    if (noCallback == null) {
        noCallback = function() { alert('Warning: No callback assigned'); this.hide(); };
    }
    else {
        var chainedCallback2 = noCallback;
        noCallback = function() { chainedCallback2(); this.hide(); };
    }    

    var myButtons = [{ text: "Yes", handler: yesCallback },
                     { text: "No", handler: noCallback, isDefault: true}];
				                  
    mySimpleDialog.cfg.queueProperty("buttons", myButtons);
    mySimpleDialog.render(document.body);
    mySimpleDialog.show();
}

function AlertDialog(text, header, title) {

    if (title == null) {
        title = "Warning";
    }

    if (header != null) {
        text = "<p><strong>" + header + "</strong></p>" + text;
    }
    
    var mySimpleDialog = new YAHOO.widget.SimpleDialog("dlg", {
        width: "30em",
        fixedcenter: true,
        icon: YAHOO.widget.SimpleDialog.ICON_HELP, 
        modal: true,
        visible: false,
        draggable: false
    });
    
    enableEscape(mySimpleDialog);

    mySimpleDialog.setHeader(title == null ? "Alert" : title);
    mySimpleDialog.setBody("<div style='width: 25em; float:left'>" + text + "</div><div class='clear'></div>");

    var myButtons = [{ text: "OK", handler: function() { this.hide() } }];

    mySimpleDialog.cfg.queueProperty("buttons", myButtons);
    mySimpleDialog.render(document.body);
    mySimpleDialog.show();
}

function ValidationError(text) {

    var lastChar = text.charAt(text.length - 1);

    if (lastChar != "." && lastChar != "?" && lastChar != "!") {
        text += ".";
    }
    
    AlertDialog("Sorry there seems to be the following problem(s):<br><br><font color=red><b>" + text + "</b></font>", "Problems found");
}


;
// Routing Lookuptable
$.url=function(url) {
var lookupTable = {"updateCart":"/store/cart/updatecart","updateFSP":"/store/fsp/updateFSP","selectShippingMethod":"/store/checkout/SelectShippingMethod","applyPromoCode":"/store/cart/applyPromoCode","updateKitCustomization":"/store/cart/updateKitCustomization","getOrderSummaryText":"/store/cart/orderSummaryText","getJSONCart":"/store/cart/JSON","recalcShippingMethods":"/store/checkout/RecalcShippingMethods","getRequestedStepInfo":"/store/cart/GetRequestedStepInfo","getCartSummaryKitItemDescription":"/store/cart/CartSummaryKitItemDescription","forgotPassword":"/account/forgotPassword","resetPassword":"/account/ResetPassword","castSurveyVote":"/questions/CastSurveyVote","getUser":"/account/AJAXGetUser","login":"/account/AJAXLogin","logout":"/account/AJAXLogout","miniProductPopup":"/products/ViewProductPopup?sku=SKU","viewCartPopup":"/store/cart/ViewCartPopup","customizeKitPopup":"/store/products/customizeKitPopup","top5ReasonsPopup":"/advantages/top5ReasonsPopup","orderDetailsPopup":"/store/orders/vieworderpopup/ORDERID","kitComparisonPopup":"/store/products/kitComparisonPopup/SKU","forgotPasswordPopup":"/account/ForgotPasswordPopup?email=XXX","viewFSPPopup":"/products/FSPDetailsPopup/NA","bladesHelperPopup":"/products/bladeshelperpopup/XXX"};
if (lookupTable[url] == null) {alert("Could not find entry for '" + url + "' in javascript lookup table"); }
return lookupTable[url];
}
$.content=function(c) {
return c.replace("~/", "/");
}

;
