// setup jquery

jQuery(document).ready(function() {
    startupSamsonite()
});

function startupSamsonite() {
    startup_theme();
    startup_browser();
    startup_breadcrumbs();
    startup_ie_pngfix();
    startup_affiliate();
    startup_nav();
    startup_search();
    startup_product_details();
    startup_browse_search();
    startup_cart_count();
    startup_store_locator();
    startup_select_onchange();
	startup_productNames();
    startup_removeCarat();
}

function startup_breadcrumbs() {

    //Remove Brand Breadcrumb:
    jQuery("#browseBreadcrumbs span:nth-child(2).breadcrumbItem")
        .css("display", "none");

    // Update Home URL
    jQuery("#browseBreadcrumbs span:nth-child(1).breadcrumbItem a")
        .attr("href", "/")
        .html(GetBrand())
        .css("text-transform", "capitalize");
}

function startup_theme() {
    // Check Domain and Apply Correct Theme
    var sURL = window.location.href;
    sURL = sURL.toLowerCase();
    /* 
    // OLD
    
    if (strpos(sURL, "/info/Landing_Black_Label") > 0 || strpos(sURL, "/SBL-Collections") > 0) {
    jQuery('body').removeClass('theme_s').removeClass('theme_at').addClass('theme_bl');
    } else if (strpos(sURL, "shop.americantourister.com") > 0) {
    jQuery('body').removeClass('theme_s').addClass('theme_at').removeClass('theme_bl');
    } else {
    jQuery('body').addClass('theme_s').removeClass('theme_at').removeClass('theme_bl');
    }
    */

    // Set a theme with:
    // shop.americantourister.com/b/2235706011 --> shop.samsonite.com/b/2235706011?brand=at


    if (strpos(sURL, "/info/landing_black_label") > 0 || strpos(sURL, "/sbl-collections") > 0) {
        // If on a black label page, show black label.  You shouldn't need to set a cookie.
        jQuery('body').removeClass('theme_s').removeClass('theme_at').addClass('theme_bl');

        // Brand was passed in or item is identified as Samsonite or American Tourister
    } else if (strpos(sURL, "brand=s") > 0 || strpos(sURL, "/Samsonite-") > 0 || GetBreadcrumbsBranch() == "theme_s") {
        // The item you are looking at is S, so use theme S.   This helps with recently viewed items.
        jQuery('body').addClass('theme_s').removeClass('theme_at').removeClass('theme_bl');
        setCookie("brand", "s", 30, '/', '', '');
    } else if (strpos(sURL, "brand=at") > 0 || strpos(sURL, "/American-Tourister") > 0 || GetBreadcrumbsBranch() == "theme_at") {
        // The item you are looking at is AT, so use theme AT.   This helps with recently viewed items.
        jQuery('body').removeClass('theme_s').addClass('theme_at').removeClass('theme_bl');
        setCookie("brand", "at", 30, '/', '', '');

        // New Unforwarded Visitor on the Home Page
    } else if (isVisitorNew() && (strpos(sURL, "//shop.samsonite.com/") > 0 || strpos(sURL, "//minnesota.amazonpmi.com/") > 0)) {
        // If this visitor is organic and does not have a brand passed, show samsonite
        // REGARDLESS of cookie.   This is for sitations where a user has has a AT brand cookie
        // but is visiting S website organically.
        jQuery('body').addClass('theme_s').removeClass('theme_at').removeClass('theme_bl');
        setCookie("brand", "s", 30, '/', '', '');

        // Visitor on 2nd Page Or More
    } else if (getCookie("brand") == "at") {
        // If they have a cookie for the AT skin, show that.  They were previously viewing AT skin.
        jQuery('body').removeClass('theme_s').addClass('theme_at').removeClass('theme_bl');

    } else {
        // Show them S skin.
        jQuery('body').addClass('theme_s').removeClass('theme_at').removeClass('theme_bl');
    }

}

// Apply internet explorer version class to the wrapper element.
function startup_browser() {
    var InternetExplorerVersion = getInternetExplorerVersion();
    if (InternetExplorerVersion >= 5) {
        if (InternetExplorerVersion >= 5 && InternetExplorerVersion < 6) jQuery('#wrapper').addClass('ie5');
        else if (InternetExplorerVersion >= 6 && InternetExplorerVersion < 7) jQuery('#wrapper').addClass('ie6');
        else if (InternetExplorerVersion >= 7 && InternetExplorerVersion < 8) jQuery('#wrapper').addClass('ie7');
        else if (InternetExplorerVersion >= 8) jQuery('#wrapper').addClass('ie8');
    }
}

// Add class "PngFixIE" to any element you wish for the background PNG transparency to be fixed in IE5 or IE6
// Please note, IE6 has a maximum of 2 classes per element.
function startup_ie_pngfix() {
    if (jQuery('#wrapper').hasClass("ie5") || jQuery('#wrapper').hasClass("ie6")) {
        var Selectors = ".PngFixIE, body.theme_at div#catnav_logo, body.theme_at div#content_hero1 a, div#freeShippingSlice, div#freeShipping, div#catalog_promo_hero a";
        jQuery(Selectors).each(function() {
            var jObject = jQuery(this);
            var bgImage = jObject.css("background-image");
            if (bgImage.length > 0 && bgImage != "none" && bgImage.indexOf(".png") >= 0) {
                var ImgSrc = bgImage.substring(bgImage.indexOf("http"), bgImage.lastIndexOf(".png") + 4);
                jObject.css("background", "none");
                jObject.css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + ImgSrc + "', sizingMethod='scale')");
            }
        });
    }
}

function startup_affiliate() {
    var sURL = window.location.href;
    if (getQuery("pcode")) {
        setCookie("pfmPGSRKY", getQuery("pcode"), 60, '/', '', '');
    } else {
        // Inject Tracking Image and pass pode to serer
        bValid = false;
        jQuery(".shipmentConfirm").each(function() {
            if (parseInt(getCookie("pfmPGSRKY")) >= 9600 || parseInt(getCookie("pfmPGSRKY")) <= 9999) {
                bValid = true;
            }
        });
        if (bValid) {

            var orderNumber = amznAnalytics.getElement("purchaseID");
            var billingZip = amznAnalytics.getElement("billingPostalCode");
            var purchasesSet = amznAnalytics.getSet("purchases");
            var totalRevenue = 0;
            for (var c = 0; c < purchasesSet.length; c++)
                totalRevenue += (purchasesSet[c]["revenue"] * purchasesSet[c]["quantity"]);
            totalRevenue -= amznAnalytics.getElement("totalPromotionAmount");
            totalRevenue = Math.max(totalRevenue, 0.0);
            totalRevenue = Math.floor(totalRevenue * 100) / 100;

            var pfmLink = '<img src="https://clickserve.cc-dt.com/link/order?vid=K10050&oid=' + orderNumber + '&amt=' + totalRevenue + '&btzip=' + billingZip + '" width=1 height=1>';
            jQuery("body").after(pfmLink);
        }
    }
}

function startup_nav() {
    jQuery("ol.nav li a, ul.nav li a").each(function() {
        // Note: you can also check breadcrumb URLs to see if a parent page is selected.
        // If this elements href is somewhere inside URL, add the "current" class
        if (this.href) {
            if (strpos(window.location.href, this.href) > 0 || window.location.href == this.href) {
                jQuery(this).addClass('current');
            }
        }
    });
}

function startup_search() {
    jQuery("div.AutoHideValueOnFocus input").focus(function() {
        if (!this.DefaultValue || (this.DefaultValue && this.DefaultValue == this.value)) {
            this.DefaultValue = this.value;
            this.value = "";
        }
    });
    jQuery("div.AutoHideValueOnFocus input").blur(function() {
        if (this.value == "")
            this.value = this.DefaultValue;
    });
}

function startup_product_details() {
    jQuery("#productFeaturesBulletPoints div.title").text("Product Features");
    jQuery("h1#productTitle,div#productInfoTab1,div#productDetails").each(function() {
        var OriginalInnerHtml = this.innerHTML;
        var InnerHtml = OriginalInnerHtml.replace(/\xAE/g, "<sup>" + unescape("%AE") + "</sup>"); // (R)
        InnerHtml = InnerHtml.replace(/\xA9/g, "<sup>" + unescape("%A9") + "</sup>"); // (C)
        InnerHtml = InnerHtml.replace(/\x99/g, "<sup>" + unescape("%99") + "</sup>"); // (TM)
        if (OriginalInnerHtml != InnerHtml)
            this.innerHTML = InnerHtml;
    });
}

function startup_browse_search() {
    var node_s = "2235433011";
    var node_at = "2235434011";
    jQuery("body.theme_s #searchForm").append("<input type=\"hidden\" name=\"searchNodeID\" value=\"" + node_s + "\"/>");
    jQuery("body.theme_at #searchForm").append("<input type=\"hidden\" name=\"searchNodeID\" value=\"" + node_at + "\"/>");
    jQuery("body.theme_bl #searchForm").append("<input type=\"hidden\" name=\"searchNodeID\" value=\"" + node_s + "\"/>");
}

function startup_store_locator() {
    var sURL = window.location.href;
    if (strpos(sURL, "/info/Store_Locator") > 0 && strpos(sURL, "ttps://") > 0) {
        window.location = "http://" + window.location.hostname + window.location.pathname + (jQuery("body").hasClass("theme_at") ? "?brand=at" : "");
    }
}

function startup_cart_count() {
    f = function() {
        var r = jQuery("#miniCart span.itemCount");
        var count = r[0] ? parseInt(jQuery.trim(r[0].innerHTML)) : 0;
        var verbiage = count + (count == 1 ? " item" : " items");
        jQuery("#brandnav_b span#cart_count").html(" (" + verbiage + ")");
        if (count > 0) {
            jQuery("#insert_checkout_button").html("<div id='checkout_btn'><a href='/cart'><span>Checkout</span></a></div>");
        } else {
            jQuery("#insert_checkout_button").html("");
        }
    }
    f();
    setInterval(f, 1000);
}

function startup_select_onchange() {

    // On change, submit
    jQuery("select#searchSize").change(function() { jQuery("form.changeSearchSizeForm").submit(); });
    jQuery("select#searchRank").change(function() { jQuery("form.searchResultsSorting").submit(); });

    // If have JS, hide submit button
    jQuery("#sortRefinement div.formControls").hide();
    jQuery("#search-results-1 div.resultSizeForm div.formControls").hide();

}

/* ======== Library ============= */

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

// Use the breadcrumbs to determine if user is under Samsonite or American Tourister.
// Returns "" for no breadcrumbs present, "theme_s" for samsonite or "theme_at" for American Tourister 
function GetBreadcrumbsBranch() {
    var Result = "";
    SecondItem = GetBrand();
    if (SecondItem == "samsonite") {
        Result = "theme_s";
    } else if (SecondItem == "american tourister") {
        Result = "theme_at";
    }
    return Result;
}

function GetBrand() {
    var Result = "";
    jQuery("#browseBreadcrumbs span:nth-child(2).breadcrumbItem a").each(function() {
        Result = jQuery.trim(this.innerHTML);
        Result = Result.toLowerCase();
    });
    return Result;
}

function strpos(haystack, needle, offset) {
    var i = (haystack + '').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}



function getQuery(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
}

function setCookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) +
    ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ((secure) ? ";secure" : "");
}


// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function getCookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}


function isVisitorNew() {
    if (strpos(document.referrer, "//shop.samsonite.com/") > 0) {
        // The last page they were on was a shop.samsonite.com site, so they are not a new visitor.
        return false;
    }
    if (strpos(document.referrer, "//minnesota.amazonpmi.com/") > 0) {
        // The last page they were on was a shop.samsonite.com site, so they are not a new visitor.
        return false;
    }
    return true;
}

//function to add classes for product titles that contain the word 'samsonite'
function startup_productNames() {
	jQuery(document).ready(function() {
		jQuery("#middleSlots #centerColumn #center-1 h1#productTitle:contains('Samsonite')").addClass("samsoniteMargin");
	});
	
	jQuery(document).ready(function() {
		jQuery(".ie6 #middleSlots #centerColumn #center-1 h1#productTitle:contains('Samsonite')").addClass("samsoniteMarginIE6");
	});
	
	jQuery(document).ready(function() {
		jQuery(".ie7 #middleSlots #centerColumn #center-1 h1#productTitle:contains('Samsonite')").addClass("samsoniteMarginIE7");
	});
	
	jQuery(document).ready(function() {
		jQuery(".ie8 #middleSlots #centerColumn #center-1 h1#productTitle:contains('Samsonite')").addClass("samsoniteMarginIE8");
	});
}

//function to replace auto-generated .carat with specified class
function startup_removeCarat() {
	jQuery(document).ready(function() {
		if(jQuery("#wrapper").hasClass("ie6") || jQuery("#wrapper").hasClass("ie7") || jQuery("#wrapper").hasClass("ie8") ){
			jQuery(".carat").replaceWith("<span class='breadCrumbCarat'>&#160;>>&#160;</span>");
		} else {
			jQuery(".carat").replaceWith("<span class='breadCrumbCarat'>>></span>");
		}
	});
}

jQuery(document).ready(function() {
	if (jQuery(".ie6 #innerWrapper #middleSlots #rightColumn #colorSwatches").hasClass('colorSwatches')) {
	jQuery("#middleSlots #centerColumn").css("width","458px");
	}
});

