// setup jquery

jQuery(document).ready(function() {
    startupSamsonite()
});

function startupSamsonite() {
    startup_theme();
    startup_flash();
    startup_affiliate();
    startup_nav();
    startup_search();
    startup_product_details();
    startup_browse_search();
    startup_cart_count();
    startup_store_locator();
    startup_select_onchange();
}

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');
    }
    
}

function startup_flash() {
    if (jQuery('#content_hero').is('*') && jQuery('body').hasClass('theme_s')) {
        //http://minnesota.amazonpmi.com/media/Site Files/Merchandising Files/main.swf
        //var flashHero = new SWFObject('http://ecx.images-amazon.com/images/I/71YlSGg8sZL.swf', 'content_hero', '1000', '360', '9.0.0', '');
        var flashHero = new SWFObject('/media/Site Files/Merchandising Files/main-v2.swf', 'content_hero', '1000', '360', '9.0.0', '');
        flashHero.addParam('wmode', 'transparent');
        flashHero.addParam('play', 'true');
        flashHero.addParam('allowScriptAccess', 'never');
        //http://minnesota.amazonpmi.com//media/Site Files/Merchandising Files/flv_video_nostop.swf
        //flashHero.addVariable('videoFile', 'http://ecx.images-amazon.com/images/I/A1Z8jdiSocL.swf');
        flashHero.addVariable('videoFile', '/media/Site Files/Merchandising Files/flv_video_nostop.swf');
        flashHero.write('content_hero');
    }
}

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;
    }
}

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 ============= */


// 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 = "";
    jQuery("#browseBreadcrumbs span.breadcrumbItem:first-child+span.breadcrumbItem a").each(function() {
        var SecondItem = jQuery.trim(this.innerHTML);
        SecondItem = SecondItem.toLowerCase();
        if (SecondItem == "samsonite")
            Result = "theme_s";
        else if (SecondItem == "american tourister")
            Result = "theme_at";
    });
    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;
}


