﻿/* custom ICG plugins and functions */

// clear the options in a dropdownlist
$.fn.clearSelect = function() {
    return this.each(function() {
        if (this.tagName == 'SELECT')
            this.options.length = 0;
    });
}

// fill a dropdownlist with json data
$.fn.fillSelect = function(data, textProperty, valueProperty) {
    return this.clearSelect().each(function() {
        if (this.tagName == 'SELECT') {
            var dropdownList = this;
            $.each(data, function(index, optionData) {
                var option = new Option(optionData[textProperty], optionData[valueProperty]);

                if ($.browser.msie) {
                    dropdownList.add(option);
                }
                else {
                    dropdownList.add(option, null);
                }
            });
        }
    });
}

// fade image out, change src, fade in
$.fn.fadeSwap = function(imgUrl) {
    return this.each(function() {
        if (this.tagName == 'IMG') {
            if (this.src != imgUrl) {
                var imgTag = $(this);
                var img = new Image();
                imgTag.fadeOut('fast', function() {
                    $(img).load(function() {
                        imgTag.css('display', 'none').attr('src', this.src).fadeIn();
                    }).attr('src', imgUrl);
                });
            }
        }
    });
}



// resize an img or object to a specified width
$.fn.shrinkToWidth = function(maxwidth) {
    return this.each(function() {
        obj = $(this);
        var width = obj.width();
        var height = obj.height();
        if (width > maxwidth) {
            var ratio = (height / width);
            var new_width = maxwidth;
            var new_height = (new_width * ratio);
            obj.height(new_height).width(new_width);
        }
    });
};

// resize an img or object to a specified width by css
$.fn.shrinkToWidthByCss = function(maxwidth) {
	
    return this.each(function() {
        obj = $(this);
        
        var validHeight = obj.css("height") != undefined && obj.css("height") != '';
        var validWidth = obj.css("width") != undefined && obj.css("width") != '';
        
        if(validHeight && validWidth)
        {
			var height = obj.css("height").replace("px", "");
			var width = obj.css("width").replace("px", "");
					
			height = parseInt(height);
			width = parseInt(width);
	        
			if(width > maxwidth) {
				var ratio = (height / width);
				var new_width = maxwidth;
				var new_height = parseInt(new_width * ratio);
				obj.css("height", new_height.toString() + "px").css("width", new_width.toString() + "px");
			}
        }
    });
};

$.fn.addSpinnerBehindImages = function() {

	return this.each(function() {
		
		var img = $(this);

		img.css("background-image", "url(../App_Themes/Default/graphics/progress.gif)");
		img.css("background-repeat", "no-repeat");
		img.css("background-position", "center center");
		
	});

};


FormatString = function(str, args) {
    if (args.length < 1) {
        return str;
    }
    for (var i = 0; i < args.length; i++) {
        var a = args[i] ? args[i] : "";
        str = str.replace(new RegExp("\\{" + i + "\\}", "gi"), a);
    }
    return str;
}

$.extend({
    escapeHtml: function(s) {
        var html = $('<div/>').text(s).html();
        return html.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    },
    
    queryHash: function(s) {
        var r = {};
        var q = s.substring(s.lastIndexOf('#') + 1); // remove everything up to the # 
        q = q.replace(/\&$/, ''); // remove the trailing & 
        jQuery.each(q.split('&'), function() {
            var splitted = this.split('=');
            var key = splitted[0];
            var val = splitted[1];
            // convert floats 
            if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
            // ignore empty values 
            if (val && (typeof val == 'number' || val.length > 0)) r[key] = val;
        });
        return r;
    }
});



var console;
$(document).ready(function() {
    if (typeof (console) == 'undefined') {
        //$('body').append('<div style="position:absolute;top:0;left:0;z-index:99999;background-color:white;border:double;width:300px;overflow-x:hidden;overflow-y:scroll;"><textarea id="console" rows="8" style="background-color:Transparent; border:none 0px; width:100%;"></textarea></div>');
        console = {
            log: function(str) {
                //$('#console').append(str + '<br />');
            }
        }
    }

    // add min-height to main div
    $('#mainDiv').css('min-height', $(window).height() + 10 + 'px');
});
/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */


jQuery.extend({
	historyCurrentHash: undefined,
	
	historyCallback: undefined,
	
	historyInit: function(callback){
		jQuery.historyCallback = callback;
		var current_hash = location.hash;
		
		jQuery.historyCurrentHash = current_hash;
		if(jQuery.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (jQuery.historyCurrentHash == '') {
			jQuery.historyCurrentHash = '#';
		}
		
			// add hidden iframe for IE
			$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = current_hash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			jQuery.historyBackStack = [];
			jQuery.historyBackStack.length = history.length;
			jQuery.historyForwardStack = [];
			
			jQuery.isFirst = true;
		}
		jQuery.historyCallback(current_hash.replace(/^#/, ''));
		setInterval(jQuery.historyCheck, 100);
	},
	
	historyAddHistory: function(hash) {
		// This makes the looping function do something
		jQuery.historyBackStack.push(hash);
		
		jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this.isFirst = true;
	},
	
	historyCheck: function(){
		if(jQuery.browser.msie) {
			// On IE, check for location.hash of iframe
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
			
				location.hash = current_hash;
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
				
			}
		} else if ($.browser.safari) {
			if (!jQuery.dontCheck) {
				var historyDelta = history.length - jQuery.historyBackStack.length;
				
				if (historyDelta) { // back or forward button has been pushed
					jQuery.isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
					}
					var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
					if (cachedHash != undefined) {
						jQuery.historyCurrentHash = location.hash;
						jQuery.historyCallback(cachedHash);
					}
				} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						jQuery.historyCallback(document.URL.split('#')[1]);
					} else {
						var current_hash = location.hash;
						jQuery.historyCallback('');
					}
					jQuery.isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
			}
		}
	},
	historyLoad: function(hash){
		var newhash;
		
		if (jQuery.browser.safari) {
			newhash = hash;
		}
		else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		jQuery.historyCurrentHash = newhash;
		
		if(jQuery.browser.msie) {
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			jQuery.historyCallback(hash);
		}
		else if (jQuery.browser.safari) {
			jQuery.dontCheck = true;
			// Manually keep track of the history values for Safari
			this.historyAddHistory(hash);
			
			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {jQuery.dontCheck = false;};
			window.setTimeout(fn, 200);
			jQuery.historyCallback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  jQuery.historyCallback(hash);
		}
	}
});



var myoObj = {
    flash: null,
    flashReady: false,
    pageReady:false,
    categoryId: -1,
    productId: -1,

    init: function() {
        this.flash = ASPNetMedia.Flash(myo_flash_id);
    },

    // runs on first page load, back button, and left nav click
    historyLoad: function(hash) {
        var hashObj = $.queryHash(hash);
        myoObj.categoryId = hashObj.categoryId || 0;
        myoObj.productId = hashObj.productId || 0;
		
      if (myoObj.flashReady) {
			myoObj.flash.CallFlashFunction("goToCatID", myoObj.categoryId);
            myoObj.setOmnitureAndCss(myoObj.categoryId);
            
        }
        
        myoObj.pageReady = true;
    },
    
    isPageReady: function() {
        return myoObj.pageReady;
    },

    // flash will call this function when it's ready
    getHashProperty: function() {
        this.flashReady = true;
        $('.LeftNavTree').show();
        $('.AspNet-TreeView-Root UL LI A').click(myoObj.itemClick);
        
        return this.categoryId + "," + this.productId;
    },

    // flash will call this function to highlight selected item
    selectNavItemFromFlash: function(id) {
        this.setOmnitureAndCss(id);
    },

    // left nav click event
    itemClick: function(e) {
        e.preventDefault();
        $(this).parent().addClass("AspNet-TreeView-Selected");
        $.historyLoad($(this).attr('href').replace('#', ''));
        return false;
    },

    // highlight selected item
    setOmnitureAndCss: function(id) {
        $(".AspNet-TreeView-Leaf A").each(function() {
            var hashObj = $.queryHash($(this).attr('href'));
            myoObj.categoryId = hashObj.categoryId || 0;
            if (myoObj.categoryId > 0 && myoObj.categoryId.toString() == id) {
                var name = $(this).attr("title");
                s_products = "Ralph Lauren Rugby - Make Your Own - " + name;
                document.title = name + " - Make Your Own - Ralph Lauren Rugby - Rugby.com";
                $(this).parent().addClass("AspNet-TreeView-Selected");
            } else {
                $(this).parent().removeClass("AspNet-TreeView-Selected");
            }
        });
    },

    // add to cart and callback
    addToCart: function(item) {
        rugbyCart.addToCart(item, function(msg) {
            myoObj.flash.CallFlashFunction("showCartMsg", msg)
        });
    },
     addToCartObj: function(str) {
        var item;
        eval("item="+str);
        this.addToCart(item);
    }
}

$(document).ready(function() {
	myoObj.init();
	$.historyInit(myoObj.historyLoad);
});
var isUserLoggedIn = false;
var gsiBasePath;
var cart_flashHandler_id;
var checkForFlash;

$(document).ready(function() {
    console.log("cart - ready");
    rugbyCart.init();

    $('.shopCartBagCell').css("cursor", "pointer").click(function() {
        rugbyCart.toggleCart();
    });
});

var rugbyCart = {
    baseUrl: "http://shop.rugby.com",
    addUrl: "/cartHandler/entry.jsp?action0={0}&prod0={1}&sku0={2}&qty0={3}&giftOption0={4}&layoutId0={5}&customization0={6}&wlName0={7}&prodCounter=1",
    cartUrl: "/getCartContents/index.jsp",
    loginUrl: "/cartHandler/isUserLoggedIn.jsp",
    checkOutUrl: "/cart/index.jsp?ab=mini_cart_checkout",
    itemCountElement: 'cartCount',
    progressElement: 'cartProgress',
    miniCartElement: 'divCartInner',
    iframeId: 'cart_iframe',
    useIFrame: false,
    flashHandler: null,
    flashEnabled: true,
    flashReady: false,
    firstCartLoad: true,
    itemCount: 0,
    autoOpen: false,
    addToCartCallback: function() { },

    init: function(settings) {
        console.log("rugbyCart.init()");
        if (gsiBasePath)
            this.baseUrl = "http://" + gsiBasePath;

        this.flashHandler = ASPNetMedia.Flash(cart_flashHandler_id);
        this.closeCart();

        this.checkForFlashHandler();
    },

    setFlashReady: function() {
        console.log("rugbyCart.setFlashReady()");
        var _cart = this;
        clearInterval(checkForFlash);
        _cart.flashReady = true;
        _cart.loadCart();
    },

    checkForFlashHandler: function() {
        console.log("rugbyCart.checkForFlashHandler()");
        var _cart = this;

        // keep checking every half second until the flash is ready
        checkForFlash = setInterval(function() {
            if (_cart.flashReady) {
                clearInterval(checkForFlash);
            } else {
                _cart.flashHandler.CallFlashFunction("isFlashReady");
            }
        }, 500);

        // if it's still not ready after 5 seconds, disable flash
        setTimeout(function() {
            clearInterval(checkForFlash);
            if (!_cart.flashReady) {
                _cart.disableFlash();
            }
        }, 5000);
    },

    addToCart: function(item, callback) {
        console.log("rugbyCart.addToCart()");
        this.showProgress();

        var _cart = this;
        this.addToCartCallback = callback;

        var strWish = "no";
        if (item.isWish == true) {
            strWish = "yes";
            callback("Adding to wishlist...", true);
        } else {
            callback("Adding to bag...", false);
        }

        var strGiftWrap = (item.isGift == true && strWish == "no") ? "yes" : "no";
        item.customType = (!item.customType) ? "" : item.customType.toLowerCase();

        if (!item.customStr) item.customStr = "";
        if (!item.layoutId) item.layoutId = "";

        var strAction = "skuAddToCart";
        if (item.customType == "pgc" || item.customType == "vgc" || item.customType == "myo") {
            strAction = "customSkuAdd";
        }

        var url = this.baseUrl + FormatString(this.addUrl, [strAction, item.pid, item.sku, item.quantity, strGiftWrap, item.layoutId, item.customStr, strWish]);

        if (item.isWish == true && isUserLoggedIn == false) {
            url += "&redirectProduct=yes";
            document.location = url;
        } else {

            if (this.flashEnabled == true && this.useIFrame == false) {
                this.flashHandler.CallFlashFunction("addToCart", url, item.isWish);
            } else {
                // if user does not have flash, add to bag through the iframe
                window.frames["cart_iframe"].location.replace(url);
                this.hideProgress();
            }
        }

        // Omniture Add to cart
        if (!(item.omnPageType) || item.omnPageType.length < 1) item.omnPageType = "itemlevel";

        if (item.isWish) {
            s_linkName = "Wishlist";
            s_events = "event4";
        } else {
            var s_eVar14 = "";
            if (this.itemCount == 0) {
                s_events = "scOpen,scAdd";
            } else {
                s_events = "scAdd";
            }
        }

        if (item.omnPageType.toLowerCase() == "quickshop") {
            s_eVar14 = "Quick Shop";
            if (s_products.length == 0) {
                //s_products = qsIFrame.s_products; *have to update this
            }
        } else {
            s_eVar14 = "Product Detail Page";
        }
        if (s_products.indexOf("evar13=") == -1) s_products = s_products + ";;;;evar13=" + item.pid + ":" + item.sku;
        if (s_products.indexOf("evar14=") == -1) s_products = s_products + "|evar14=" + s_eVar14;
        s_gs(s_account);
        // End Omniture
    },

    addToCartResponse: function(status, qty, isWish) {
        console.log("rugbyCart.addToCartResponse(" + status + ", " + qty + ", " + isWish + ")");
        var strResult;
        if (status == "true" || status == true) {
            if (isWish == "true" || isWish == true) {
                strResult = qty + " Item(s) added to wishlist.";
                this.hideProgress();
            } else {
                this.autoOpen = true;
                this.loadCart();
                strResult = qty + " Item(s) added to bag.";
            }
        } else {
            strResult = "We're sorry. Your items could not be added.";
            this.hideProgress();
        }
        this.addToCartCallback(strResult, isWish);
    },

    showProgress: function() {
        $('#' + this.progressElement).css("visibility", "visible");
    },

    hideProgress: function() {
        $('#' + this.progressElement).css("visibility", "hidden");
    },

    checkout: function() {
        window.location = this.baseUrl + this.checkOutUrl;
    },

    loadCart: function() {
        this.showProgress();
        var url = this.baseUrl + this.cartUrl;
        console.log("rugbyCart.loadCart(" + url + ")");
        this.flashHandler.CallFlashFunction("loadCart", url);
    },

    loadCartResponse: function(n, result) {
        var _cart = this;
        console.log("rugbyCart.loadCartResponse(" + n + " " + result + ")");

        if (!n) n = 0;
        this.setItemCount(n);

        var items = [];
        items = result.d;

        if (items.length == 0) {
            _cart.hideProgress();
        } else {
            var html = '';
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                //item.productTitle = $.escapeHtml(item.productTitle);
                //alert("title " + item.productTitle);
                item.imageSource = (item.imageSource.indexOf('http') == -1) ? (gsiCDN + item.imageSource) : item.imageSource;
                var altText = item.productTitle + ", " + item.color + ", " + item.size;
                html += '<a href="' + siteRoot + 'shop/item.aspx?productId=' + item.productId + '&ab=mini_cart_item" title="' + altText + '">';
                html += '<div class="name"><span>' + item.productTitle + '</span></div>';
                html += '<div class="img"><img src="' + item.imageSource + '" width="50" height="50" border="0" alt="' + altText + '"></div>'; 
                html += '<div class="price">$' + item.unitPrice.toFixed(2) + '<br>Qty: ' + item.quantity + '</div>';
                html += '</a><div class="clear"></div>';
            }
            html += '<a href="' + this.baseUrl + this.checkOutUrl + '" style="padding:6px 0;"><img alt="Checkout" src="http://akcdn.rugby.com/graphics/shopping_cart/checkout.gif" width="82" border="0" height="18"></a>';

            $('#' + _cart.miniCartElement).html(html);
            if (_cart.autoOpen) {
                _cart.openCart();
                setTimeout(function() { _cart.closeCart(); }, 2500);
                _cart.autoOpen = false;
            }
            _cart.hideProgress();
        }

        if (_cart.firstCartLoad) {
            _cart.firstCartLoad = false;
            if (currentPage == 'item.aspx') {
                setTimeout(function() {
                    _cart.isUserLoggedIn();
                }, 1000);
            }
        }
    },

    isUserLoggedIn: function() {
        var url = this.baseUrl + this.loginUrl;
        console.log("rugbyCart.isUserLoggedIn(" + url + ")");
        this.flashHandler.CallFlashFunction("isUserLoggedIn", url);
    },

    isUserLoggedInResponse: function(status) {
        console.log("rugbyCart.isUserLoggedInResponse(" + status + ")");
        isUserLoggedIn = status;
    },

    setItemCount: function(n) {
        console.log("rugbyCart.setItemCount(" + n + ")");
        this.itemCount = n ? n : 0;
        $('#' + this.itemCountElement).html(this.itemCount);
    },

    disableFlash: function() {
        console.log("rugbyCart.disableFlash()");
        this.flashEnabled = false;
        $('.' + this.itemCountElement).hide();
        this.hideProgress();
    },

    formatGiftCardCustom: function(gc, customType) {
        var strCustom = "";
        if (customType == "pgc") {
            strCustom = "5," + encodeURIComponent(gc.email) + "|3," + encodeURIComponent(gc.sender) + "|4," + encodeURIComponent(gc.message) + "|2," + encodeURIComponent(gc.recipient);
        } else if (customType == "vgc") {
            strCustom = "2," + encodeURIComponent(gc.image) + "|6," + encodeURIComponent(gc.sender) + "|8," + encodeURIComponent(gc.message) + "|4," + encodeURIComponent(gc.recipient);
            strCustom += "&amount0=" + gc.amount + "&email0=" + encodeURIComponent(gc.email);
        }
        return strCustom;
    },

    toggleCart: function() {
        if (this.flashEnabled == true && this.itemCount > 0) {
            var outerDiv = $('#' + this.miniCartElement).parent();
            if (outerDiv.css('display') == 'none' || outerDiv.height() == 0) {
                this.openCart();
            } else {
                this.closeCart();
            }
        } else {
            this.checkout();
        }
    },

    openCart: function() {
        $('#' + this.miniCartElement).parent().animate({ height: '100%', opacity: 1 }, 'normal');
    },

    closeCart: function() {
        $('#' + this.miniCartElement).parent().animate({ height: '0px', opacity: 0 }, 'fast');
    }
};
