﻿
var arrStores = new Array();
var allStoresList = "";
var arrShirtsInStores = new Array();
var arrCurrentDealers = new Array();
var ONLINESTORES = "onlinestores";
var MAX_CITIES_CHAR = 65;

// add indexOf prototype to Array.  Because IE is lame and doesn't have it.

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length;

        var from = Number(arguments[1]) || 0;
        from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++) {
            if (from in this &&
          this[from] === elt)
                return from;
        }
        return -1;
    };
}

function showDealerCity(id) {
    // Show the list of cities where the chosen shirt is on sale.
    // id: the index of the chosen shirt in mycarousel_itemList array

    var arrDeepLink = window.location.href.split('#');
    var strCurrentLocation = decodeURI(arrDeepLink[0]);
    var hashUrl = '';
    var strCurrentShirtId = -1;
    var strItemName = '';

    var identifierHide;
    var identifierShow;

    // Get the comma-delimited store list from arrShirtsInStores:
    var strStoreList;

    // Place store list in an array
    var arrCurrentStores;
    
    if (id == -1) {
        hashUrl = decodeURI(arrDeepLink[0]) + "#";
        strCurrentShirtId = -1;
        strItemName = "All Stores";
        strItemName = strItemName.replace(/_/g, ' ');

        strStoreList = allStoresList;
        arrCurrentStores = strStoreList.split(',');

        identifierHide = "#ToolDisplay";
        identifierShow = "#CollectionDisplay";
    } else {
        hashUrl = decodeURI(arrDeepLink[0]) + "#" + mycarousel_itemList[id].title;
        strCurrentShirtId = mycarousel_itemList[id].strCurrentShirtId;
        strItemName = mycarousel_itemList[id].title;
        strItemName = strItemName.replace(/_/g, ' ');

        strStoreList = arrShirtsInStores[strCurrentShirtId];
        arrCurrentStores = strStoreList.split(',');

        identifierHide = "#ToolDisplay";
        identifierShow = "#CarouselDisplay";
    }

    // strDealerCity will contain all of the HTML necessary.
    var strDealerCity = '<div class="Exit"><a id="findExit" href="' + hashUrl + '" onclick="return swapContent(\'' + identifierHide + '\', \'' + identifierShow + '\');">Exit (x)</a></div><br class="clear" />' +
                        '<div style="border-top:#fff solid 2px; border-bottom:#fff solid 2px; height:342px;position: relative; z-index: 10">';
                        
    // Loop through arrCurrentStores to populate cities.
    var cities = [];
    var onlinestoreIndex = -1;
    var onlinestoreValue = "";
    
    var intCounter = 0;
    for (var i = 0; i < arrCurrentStores.length; i++) {
        for (var j = 0; j < arrStores.length; j++) {
            if (arrStores[j].storeid == arrCurrentStores[i]) {
                if (cities.indexOf(arrStores[j].city) == -1) {
                    cities[intCounter] = arrStores[j].city;
                    if (cities[intCounter].toLowerCase().replace(/\s/g, "") == ONLINESTORES) {
                        onlinestoreIndex = intCounter;
                    }
                    intCounter++;
                }
            }
        }
    }

    if (onlinestoreIndex != -1) {
        onlinestoreValue = cities[onlinestoreIndex];
        cities.splice(onlinestoreIndex, 1);
    }
    
    // Sort the cities alphabetically.
    cities = cities.sort();

    if (onlinestoreIndex != -1) {
        cities.unshift(onlinestoreValue);
    }

    var charCount = 0;

    // Build the actual list of cities.  
    strDealerCity += "<ul id='DealerCity'>";
    for (var i = 0; i < cities.length; i++) {
        var strCurrCity = cities[i].toLowerCase();
        strCurrCity = strCurrCity.replace(/\s/g, "");
        var strFileName = "/windows/framework/subsites/softwearbymicrosoft/images/locations/label-" + strCurrCity + ".gif";
        if (i == 0) {
            charCount += cities[i].toLowerCase().length;

            if (charCount <= MAX_CITIES_CHAR) {
                strDealerCity += '<li class="container-city"><a href="' + hashUrl + '" onclick="return showDealers(' + id + ', \'' + cities[i] + '\');" style="background-image: url(' + strFileName + ');"><img src="' + strFileName + '" alt="' + cities[i] + '" /></a></li>';
            } else {
                strDealerCity += '<li class="container-city"><img width="100%" src="/windows/framework/subsites/softwearbymicrosoft/images/locations/spacer.gif" alt="spacer" /></a></li>';
                strDealerCity += '<li class="container-city"><a href="' + hashUrl + '" onclick="return showDealers(' + id + ', \'' + cities[i] + '\');" style="background-image: url(' + strFileName + ');"><img src="' + strFileName + '" alt="' + cities[i] + '" /></a></li>';
                charCount = cities[i].toLowerCase().length;
            }
        } else {
            charCount += 3;

            if (charCount <= MAX_CITIES_CHAR) {
                strDealerCity += "<li><p class='slash'> / </p></li>";
            } else {
                strDealerCity += '<li class="container-city"><img width="100%" src="/windows/framework/subsites/softwearbymicrosoft/images/locations/spacer.gif" alt="spacer" /></a></li>';
                strDealerCity += "<li><p class='slash'> / </p></li>";
                charCount = 3;
            }

            charCount += cities[i].toLowerCase().length;
            if (charCount <= MAX_CITIES_CHAR) {
                strDealerCity += '<li class="container-city"><a href="' + hashUrl + '" onclick="return showDealers(' + id + ', \'' + cities[i] + '\');" style="background-image: url(' + strFileName + ');"><img src="' + strFileName + '" alt="' + cities[i] + '" /></a></li>';
            } else {
                strDealerCity += '<li class="container-city"><img width="100%" src="/windows/framework/subsites/softwearbymicrosoft/images/locations/spacer.gif" alt="spacer" /></a></li>';
                strDealerCity += '<li class="container-city"><a href="' + hashUrl + '" onclick="return showDealers(' + id + ', \'' + cities[i] + '\');" style="background-image: url(' + strFileName + ');"><img src="' + strFileName + '" alt="' + cities[i] + '" /></a></li>';
                charCount = cities[i].toLowerCase().length;
            }
        }
    }
    strDealerCity += "</ul>";
    strDealerCity += '</div>';

    // Finish off the display

    if (id != -1) {
        strDealerCity += '<div id="layout-title-tools"><div class="container-title">';
        strDealerCity += '<img src="' + mycarousel_itemList[id].titleUrl + '" width="500" class="imageTitle" alt="' + strItemName + '" /></div>';
        strDealerCity += '<div class="container-tools" id="active-find">' + getCollectionTools(mycarousel_itemList[id], "false") + '</div></div>';
    }
    // Make it happen.
    $('#CollectionDisplay').hide();
    $("#CarouselDisplay").hide();
    $("#ToolDisplay").show();
    $("#ToolDisplay").html(strDealerCity);
    $(".FindShirt a").addClass("active");

    $('#findExit').click(function(event) {
        CallOmniture('', '', 'find:close');
        $('#findExit').hide();
    });

    strItemName = strItemName.replace(/ /g, '%20');

    if (id != -1)
    {
        CallOmniture('', '', 'find:find_this_shirt', 's.eVar1="' + strItemName + '",s.props1="' + strItemName + '"');
        CallAtlas('mrtwxp_winftpsoftwear_Findit');
    }
    //return false;
}

function showArtwork(id) {
    var arrDeepLink = window.location.href.split('#');
    var strCurrentLocation = decodeURI(arrDeepLink[0]);
    var hashUrl = decodeURI(arrDeepLink[0]) + "#" + mycarousel_itemList[id].title;

    var artworkUrl = mycarousel_itemList[id].artwork + ".jpg";
    var artworkFileSize = mycarousel_itemList[id].artwork + "_file_size.gif";

    var strItemName = mycarousel_itemList[id].title;
    strItemName = strItemName.replace(/_/g, ' ');

    var strArtwork = '<div class="Exit"><a href="#" onclick="return swapContent(\'#ToolDisplay\', \'#CarouselDisplay\');">Exit (x)</a></div>' +
                        '<div style="border-bottom:#fff solid 1px; height:313px;">';

    strArtwork += '<div style="height:291px;"><img src="' + artworkUrl + '" width="498" height="291" /></div>';
    strArtwork += '<div style="border-top:#fff solid 1px; height:32px;"><ul class="DownloadFormat"><li class="DownloadChoices"><p>Choose format to download</p></li><li class="DownloadPDF"><a href="#">PDF (236kb)</a></li><li class="DownloadXPS"><a href="#">XPS (140kb)</a></li></ul></div>';
    strArtwork += '</div>';
    strArtwork += '<div id="layout-title-tools"><div class="container-title"><img src="' + mycarousel_itemList[id].titleUrl + '" width="500" class="imageTitle" alt="' + strItemName + '" /></div>';
    strArtwork += '<div class="container-tools"><ul class="CollectionTools"><li class="CollectionToolsDownload"><a class="active" href="' + strCurrentLocation + '#' + mycarousel_itemList[id].title + '" onclick="return showArtwork(' + mycarousel_itemList[id].id + ');">Download this artwork</a></li></ul></div></div>';

    $("#CarouselDisplay").hide();
    $("#ToolDisplay").show();
    $("#ToolDisplay").html(strArtwork);
}

function showDealers(id, strCity) {
    // Show the list of dealers for a given shirt in the chosen city.
    // id: the index of the chosen shirt in mycarousel_itemList array
    // strCity: The chosen city.
    var arrDeepLink = window.location.href.split('#');
    var strCurrentLocation = decodeURI(arrDeepLink[0]);

    var hashUrl;
    var strItemName;

    var identifierHide;
    var identifierShow;

    if (id == -1) {
        hashUrl = decodeURI(arrDeepLink[0]) + "#";
        strItemName = "Online Stores";
        identifierHide = "#ToolDisplay";
        identifierShow = "#CollectionDisplay";
    } else {
        hashUrl = decodeURI(arrDeepLink[0]) + "#" + mycarousel_itemList[id].title;
        strItemName = mycarousel_itemList[id].title;
        identifierHide = "#ToolDisplay";
        identifierShow = "#CarouselDisplay";
    }
    var strItemNameTrack = strItemName;
    strItemName = strItemName.replace(/_/g, ' ');

    var strFileName = strCity.toLowerCase();
    strFileName = strFileName.replace(/\s/g, "");

    // strDealers will contain the HTML for the list of dealers.
    var strDealers = "";
    var imgUrl = "/windows/framework/subsites/softwearbymicrosoft/images/locations/label-" + strFileName + ".gif";
    strDealers += '<div id="change-city"><img src="' + imgUrl + '" alt="' + strCity + '" />';
    strDealers += '<a href="' + hashUrl + '" onclick="return showDealerCity(' + id + ');"> (CHANGE CITY)</a></div>';
    strDealers += '<div class="Exit"><a id="findExit" href="' + hashUrl + '" onclick="return swapContent(\'' + identifierHide + '\', \'' + identifierShow + '\');">Exit (x)</a></div><br class="clear" />' + '<div style="border-top: 2px solid #fff">';
    
    if (strFileName == ONLINESTORES) {
        strDealers += '<div id="header-onlinestores">Store Name Address City/State</div>';
    } else {
        strDealers += '<div id="header-storelist">Store Name Address City/State</div>';
    }

    // arrCurrentDealers (a global variable defined at the beginning of the file) will contain ALL the dealers
    // for the chosen shirt in the chosen city.
    // Because arrCurrentDealers is global, and because this function is called more than once, we must first 
    // zero out the array before we fill it.
    arrCurrentDealers = [];

    var isShirtInStores;

    // Here is where we fill arrCurrentDealers.  Each item is the line of HTML for displaying a dealer.
    var intCounter = 0;
    for (var i = 0; i < arrStores.length; i++) {
        if (id == -1) {
            isShirtInStores = true;
        } else {
            isShirtInStores = (arrStores[i].shirtid.indexOf("," + mycarousel_itemList[id].strCurrentShirtId + ",") != -1) ? true : false;
        }
    
        if ((arrStores[i].city == strCity) && isShirtInStores) {
            var strBackground = '/windows/framework/subsites/softwearbymicrosoft/images/stores/store-graphic-' + arrStores[i].storeid + '.gif';
            var strTemp = '<p class="dealer-listing">';

            if (arrStores[i].mapurl != "") {
                strTemp += '<a href="'+arrStores[i].mapurl+'" target="_blank" class="maplink">map </a>';
            } else {
                strTemp += '<span class="maplink">map </span>';
            }
            if (arrStores[i].storelink != "") {
                var eVars = "s.eVar1='" + strItemNameTrack.replace(/ /g, '%20') + "';s.prop1='" + strItemNameTrack.replace(/ /g, '%20') + "';";
                eVars += "s.eVar2='" + arrStores[i].city.replace(/ /g, '%20') + "';s.prop2='" + arrStores[i].city.replace(/ /g, '%20') + "';";
                eVars += "s.eVar3='" + arrStores[i].storename.replace(/ /g, '%20').replace(/\'/g, '%27') + "';s.prop3='" + arrStores[i].storename.replace(/ /g, '%20').replace(/\'/g, '%27') + "';";
                strTemp += '<a onclick=javascript:CallAtlas(\"mrtwxp_winftpsoftwear_buynow\");CallOmniture(\"event1\",\"\",\"find:click\",\"' + eVars + '\"); href="' + arrStores[i].storelink + '" target="_blank" class="storelink" style="background-image: url(' + strBackground + ');">';
                
            }
            strTemp += arrStores[i].storename + " " + arrStores[i].address1;
            if (arrStores[i].address2 != "") {
                strTemp += " " + arrStores[i].address2;
            }
            strTemp += ' ' + arrStores[i].city + ' ' + arrStores[i].state;
            if (arrStores[i].storelink != "") {
                strTemp += '</a><br class="clear" />';
            }
            strTemp += '</p>';
            arrCurrentDealers[intCounter] = strTemp;
            intCounter++;
        }
    }

    // the DealerPage div is what we use to show the dealers one page at a time.
    strDealers += '<div id="DealerPage"></div>';

    // Set up pager.  The page can hold 14 dealers.  If there's less than 14 dealers in
    // arrCurrentDealers, we don't need a pager and can just call showDealerPage.
    // If there are more than 14 dealers in arrCurrentDealers, we need to set up pagination
    // links.
    var strPager = "";  // Contains the pagination links
    if (arrCurrentDealers.length < 14) {
        showDealerPage(0, arrCurrentDealers.length, strCity, strItemName);
        strPager = '<div class="container-pager" ></div>';
    } else {
        // More than one page worth of stuff.
        // Build the paging bar, which will use the showDealerPage() function.
        strPager = '<div class="container-pager" id="top-border">';
        var intCounter = 1;
        for (var i = 0; i < arrCurrentDealers.length; i = i + 14) {
            var strFileName = frameworkRoot + "images/page-" + intCounter + ".gif";
            var track = "find:paginate";
            strPager += '<div class="button-pager"><a href="' + hashUrl + '" id="button-pager-' + intCounter + '" onclick="showDealerPage(' + i + ', 14, true, \'' + strCity + '\',\'' + strItemName + '\');activatePageButton(' + intCounter + ');" style="background-image: url(' + strFileName + ')">' + intCounter + '</a></div>';
           
            intCounter++;
        }
        strPager += '</div>';

        
        
    }

    strDealers += strPager;
    
    if (id != -1) {
        strDealers += '<div id="layout-title-tools"><div class="container-title"><img src="' + mycarousel_itemList[id].titleUrl + '" width="500" class="imageTitle" alt="' + strItemName + '" /></div>';
        strDealers += '<div class="container-tools" id="active-find">' + getCollectionTools(mycarousel_itemList[id]) + '</div></div>';
    }

    
    $("#ToolDisplay").html(strDealers);

    //$(".FindShirt a").addClass("active");
    
    // Show the first page of dealers.
    showDealerPage(0, 14, strCity, strItemName);
    activatePageButton(1);


    $('#findExit').click(function(event) {
        CallOmniture('', '', 'find:close', "s.eVar1='" + strItemName + "';s.prop1='" + strItemName + "';s.eVar2='" + strCity + "';s.prop2='" + strCity + "';");
        $('#findExit').hide();
    });

    CallOmniture("", "", "find:city_select", "s.eVar1='" + strItemName + "';s.prop1='" + strItemName + "';s.eVar2='" + strCity + "';s.prop2='" + strCity + "';");
}

function showDealerPage(intBegin, intLength, strTrack, strCity, strItemName) {
    // Display a page of dealers.
    // intBegin: The index of the first dealer on the page
    // intLength: The number of dealers to display on the page
    // Dealer listings are carried in the arrCurrentDealers global array.
    
    var strPage = "";
    for (var i = intBegin; i < intBegin + intLength; i++) {
        if (arrCurrentDealers[i]) {
            strPage += arrCurrentDealers[i];            
        }
    }
   
    if (strTrack == true) {
        CallOmniture('', '', 'find:paginate', "s.eVar1='" + strItemName + "';s.prop1='" + strItemName + "';s.eVar2='" + strCity + "';s.prop2='" + strCity + "';");
    }
    // Show the page
    $("#DealerPage").html(strPage);
    
}

function activatePageButton(intCounter) {
    // Update a dealer pager button so that it displays in the active state
    // (green).
    // intCounter:  The page button to activate.
    var strId = "";

    // First, deactivate all page buttons.
    // (There is probably a better way to do this, possibly through parent-child relationships.)
    for (var i = 1; i < 6; i++) {
        strId = "#button-pager-" + i;
        $(strId).removeClass("active");
    }
    
    // Activate the desired button.
    strId = "#button-pager-" + intCounter;
    $(strId).addClass("active");
}


function swapContent(identifierHide, identifierShow) {
    $(identifierHide).hide();
    $(identifierShow).show();
}


function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
    // The index() method calculates the index from a
    // given index who is out of the actual item range.
    var idx = carousel.index(i, mycarousel_itemList.length);
    carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));
    
};

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
    carousel.remove(i);   
};

/**
* Item html creation helper.
*/
function mycarousel_getItemHTML(item) {
    
    var arrDeepLink = window.location.href.split('#');
    var strCurrentLocation = decodeURI(arrDeepLink[0]);

    window.location.href = strCurrentLocation + '#' + item.title;

    var arrTracking = window.location.href.split('/');
    var strCollection;
    var strItemName;
    var boolCollection = false;
    var boolPhoto = false;

    for (i in arrTracking) {
        if (boolCollection) {
            strCollection = arrTracking[i];
            boolCollection = false;
        }
        if (arrTracking[i] == 'collections') {
            boolCollection = true;
        } else if (arrTracking[i] == 'photos') {
            boolPhoto = true;
        }
    }

    if (boolPhoto == false) {
        strItemName = item.title;       
        CallOmniture('', '', 'collections:' + strCollection + ':product_view', "s.eVar1='" + strItemName + "';s.prop1='" + strItemName + "'");
    }
    
    strItemName = item.title;
    strItemName = strItemName.replace(/_/g, ' ');

    var returnStr = '<img src="' + item.url + '" width="500" height="358" alt="' + strItemName + '" /><div id="layout-title-tools" class="layout-title-carousel"><div class="container-title"><img src="' + item.titleUrl + '" width="500" class="imageTitle" alt="' + strItemName + '" /></div>';
    
    returnStr += '<div class="container-tools">' + getCollectionTools(item) + '</div></div>';
   
    return returnStr;
};

function isShirtInStores(id) {
    var b = false;

    try {
        var strCurrentShirtId = mycarousel_itemList[id].strCurrentShirtId;
        var strStoreList = arrShirtsInStores[strCurrentShirtId];
        b = (strStoreList != "") ? true : false;
    } catch (e) {
        
    }

    return b;
}

function getCollectionTools(item, boolTrack) {

    if (boolTrack != false) boolTrack = true;
    
    
    var arrDeepLink = window.location.href.split('#');
    var strCurrentLocation = decodeURI(arrDeepLink[0]);
    
    window.location.href = strCurrentLocation + '#' + item.title;

    var arrTracking = window.location.href.split('/');
    var strCollection;
    var strItemName;
    var boolCollection = false;
    var boolPhoto = false;

    for (i in arrTracking) {
        if (boolCollection) {
            strCollection = arrTracking[i];
            boolCollection = false;
        }
        if (arrTracking[i] == 'collections') {
            boolCollection = true;
        } else if (arrTracking[i] == 'photos') {
            boolPhoto = true;
        }
    }

    if (boolPhoto == false && boolTrack == false) {
        CallOmniture('', '', 'collections:' + strCollection + ':product_view', "s.eVar1='" + item.title + "';s.prop1='" + item.title + "'");
 
    }

    if (boolTrack == false) {
        s.pageName = '';
        s.prop1 = '';
    }
    
    strItemName = item.title;
    strItemName = strItemName.replace(/_/g, ' ');
    var returnStr = "";
    var strLinks = "";

    var shirtIsInStores = isShirtInStores(item.id);

    if (window.location.href.indexOf("/collections/") != -1) {
        if (item.artwork != "" && shirtIsInStores) {           
            strLinks += '<li class="FindShirt"><a id="FindShirt" href="' + strCurrentLocation + '#' + item.title + '" onclick="return showDealerCity(' + item.id + ');">Find this shirt</a></li>';
        } else if (item.artwork == "" && shirtIsInStores) {
            strLinks += '<li class="FindShirt" id="Shorter"><a id="FindShirt" href="' + strCurrentLocation + '#' + item.title + '" onclick="return showDealerCity(' + item.id + ');">Find this shirt</a></li>';
        }
        
    }

    if (window.location.href.indexOf("/collections/") != -1 && item.artwork != "") {
        //returnStr += '<ul class="CollectionTools"><li><a href="' + strCurrentLocation + '#' + item.title + '" onclick="return showDealerCity(' + item.id + ');">Find this shirt</a></li><li><p>\\</p></li><li class="CollectionToolsDownload"><a href="' + strCurrentLocation + '#' + item.title + '" onClick="return download_artwork.showPage('+ item.id +');">Download this artwork</a></li></ul>';
        //returnStr += '<ul class="CollectionTools"><li class="CollectionToolsDownload"><a href="' + strCurrentLocation + '#' + item.title + '" onclick="return download_artwork.showPage(' + item.id + ');">Download this artwork</a></li></ul>';
        if (item.buyNowLink != "") {
            strLinks += '<li class="CollectionToolsDownloadMid"><a href="' + strCurrentLocation + '#' + item.title + '" onclick="return download_artwork.showPage(' + item.id + ');">Download this artwork</a></li>';
        } else {
        strLinks += '<li class="CollectionToolsDownload"><a href="' + strCurrentLocation + '#' + item.title + '" onclick="return download_artwork.showPage(' + item.id + ');">Download this artwork</a></li>';
        }
    }
/*
    if (window.location.href.indexOf("/collections/") != -1 && item.buyNowLink != "") {
        //returnStr += '<ul class="CollectionTools"><li><a href="' + strCurrentLocation + '#' + item.title + '" onclick="return showDealerCity(' + item.id + ');">Find this shirt</a></li><li><p>\\</p></li><li class="CollectionToolsDownload"><a href="' + strCurrentLocation + '#' + item.title + '" onClick="return download_artwork.showPage('+ item.id +');">Download this artwork</a></li></ul>';
        //returnStr += '<ul class="CollectionTools"><li class="CollectionToolsBuyNow"><a href="' + item.buyNowLink + '" target="_blank" onclick="trackAtlas(\'winftpsoftwear_buynow\'); s.pageName = \'softwear:collections:' + strCollection + ':product_buynow\'; s.prop1 = \'' + item.title + '\'; void (s.t()); ">Buy Now</a></li></ul>';
        strLinks += '<li class="CollectionToolsBuyNow"><a href="' + item.buyNowLink + '" target="_blank" onclick="trackAtlas(\'winftpsoftwear_buynow\'); s.pageName = \'softwear:collections:' + strCollection + ':product_buynow\'; s.prop1 = \'' + item.title + '\'; void (s.t()); ">Buy Now</a></li>';
    }
*/

    if (strLinks.length > 0) {
        returnStr = '<ul class="CollectionTools">' + strLinks + '</ul>';
    }

   
    //setupTracking("/windows/framework/subsites/softwearbymicrosoft/xml/tracking.xml");
    return returnStr;
}


function loadStoresXml() {
    // Read and parse stores.xml file.
    $.ajax({
        type: 'GET',
        url: '/windows/framework/subsites/softwearbymicrosoft/xml/stores.xml',
        dataType: 'xml',
        success: function(xml) {
            var arrTemp = {};
            var ptrStores = xml.getElementsByTagName("store");
            var intStoresIndex = 0;
            $(xml).find("store").each(function(i) {
                $(this).children().each(function(j) {
                    arrTemp[$(this)[0].nodeName] = $(this).text();
                    // alert($(this)[0].nodeName + " = " + $(this).text());
                });
                arrStores[intStoresIndex] = arrTemp;
                if (intStoresIndex == 0) {
                    allStoresList += arrTemp.storeid;
                } else {
                    allStoresList += "," + arrTemp.storeid;
                }
                arrTemp = {};
                intStoresIndex++;
            });

        }
    });
}

function build_carousel(webRoot, strCollection) {
    loadStoresXml();

    $.ajax({
        type: 'GET',
        url: '/windows/framework/subsites/softwearbymicrosoft/xml/shirts2.xml',
        dataType: 'xml',
        success: function(xml) {
            var i = 1;
            var x = 0;

            var intStart = 0;
            var arrDeepLink = window.location.href.split('#');
            var strItemName = decodeURI(arrDeepLink[1]);
            var strItemNameXml;
            var strImageSmall;
            var strImageLarge;
            var strArtworkPDF;
            var strArtworkXPS;

            $(xml).find('shirt').each(function(i) {
                var currShirtId = $(this).find('id').text();
                var strStores = "";

                for (var counter = 0; counter < arrStores.length; counter++) {
                    // alert(counter + " : " + arrStores[counter].shirtid);
                    if (arrStores[counter].shirtid.indexOf(currShirtId) > -1) {
                        strStores += arrStores[counter].storeid + ",";
                    }
                }
                var chompedStores = strStores.substring(0, strStores.length - 1)
                //alert("shirt number " + currShirtId + " is in stores " + chompedStores);
                arrShirtsInStores[currShirtId] = chompedStores;
                strStores = "";

                if ((($(this).attr('featured') == "all") || ($(this).attr('featured') == strCollection))
                    && ($(this).find('collection').is(':contains(' + strCollection + ')'))) {

                    strItemNameXml = $(this).find('name').text();
                    strItemNameXml = strItemNameXml.replace(/ /g, '_');

                    strImageTitle = webRoot + 'images/collections/titles/' + strItemNameXml + '.gif';
                    strImageSmall = webRoot + 'images/collections/' + $(this).find('collection').text() + '/' + $(this).find('imagenamesm').text();
                    strImageLarge = webRoot + 'images/collections/' + $(this).find('collection').text() + '/' + $(this).find('imagenamelg').text();
                    strArtWork = "";
                    if ($(this).find('artwork').text() != "") {
                        strArtWork = webRoot + 'images/collections/' + $(this).find('collection').text() + '/art/' + $(this).find('artwork').text()
                    }

                    strArtworkPDF = $(this).find('artwork_pdf').text();
                    strArtworkXPS = $(this).find('artwork_xps').text();
                    strBuyNowLink = $(this).find('buynow_link').text();


                    (new Image()).src = strImageLarge;
                    (new Image()).src = strImageTitle;

                    mycarousel_itemList[x] = { id: x, url: strImageLarge, title: strItemNameXml, titleUrl: strImageTitle, artworkxps: strArtworkXPS, artworkpdf: strArtworkPDF, artwork: strArtWork, collection: strCollection, buyNowLink: strBuyNowLink, strCurrentShirtId: currShirtId };

                    x++;
                }
                if ((strItemNameXml == strItemName) && (intStart == 0)) {
                    intStart = parseInt($(this).find('collectionid').text());
                }
            });

            if (intStart > 0) {
                $('#GroupedCollection').parent().hide();
                $('#CarouselDisplay').show();

                load_mycarousel(intStart);
            }

            $('#GroupedCollection li').click(function(event) {

                strItemName = $(this).text();
                if ($(this).children().hasClass('replayVideo') == true) {
                    /*
                    var COOKIE_NAME = 'visited_cookie';
                    $.cookie(COOKIE_NAME, null, { path: '/', expires: 1 });
                    */
                } else {
                    if ((strItemName != '') && (strItemName != 'BUY_NOW')) {
                        $(xml).find('shirt').each(function(i) {
                            strItemNameXml = $(this).find('name').text();
                            strItemNameXml = strItemNameXml.replace(/ /g, '_');
                            if (strItemNameXml == strItemName) {
                                intStart = parseInt($(this).find('collectionid').text());
                            }
                        });

                        $(this).parent().hide();
                        $('#CarouselDisplay').show();

                        load_mycarousel(intStart);
                    }
                }
            });
        }

    });
    
};

function build_photo_carousel(webRoot) {
    $.ajax({
        type: 'GET',
        url: '/windows/framework/subsites/softwearbymicrosoft/xml/photos_phase2.xml',
        dataType: 'xml',
        success: function(xml) {
            var i = 1;
            var intStart = 0;
            var arrDeepLink = window.location.href.split('#');
            var strItemName = decodeURI(arrDeepLink[1]);
            var strItemNameXml;
            var strImageSmall;
            var strImageLarge;

            $(xml).find('photo').each(function(i) {

                strItemNameXml = $(this).find('name').text();
                strItemNameXml = strItemNameXml.replace(/ /g, '_');

                strImageTitle = '/windows/framework/subsites/softwearbymicrosoft/images/photos/' + strItemNameXml + '.gif';
                strImageSmall = '/windows/framework/subsites/softwearbymicrosoft/images/photos/' + $(this).find('imagenamesm').text();
                strImageLarge = '/windows/framework/subsites/softwearbymicrosoft/images/photos/' + $(this).find('imagenamelg').text();
                
                // Preload each photo and the title for each photo
                (new Image()).src = strImageLarge;
                (new Image()).src = strImageTitle;

                // Create the list of carousel items
                mycarousel_itemList[i] = { url: strImageLarge, title: strItemNameXml, titleUrl: strImageTitle };

                // Determine if a photo is currently deep linked and if so set the carousel start id
                if ((strItemNameXml == strItemName) && (intStart == 0)) {
                    intStart = parseInt($(this).attr('id'));
                }

            });
            
            // Load the carousel using the start id if the url specifies a photo
            if (intStart > 0) {
                $('#GroupedCollection').parent().hide();
                $('#CarouselDisplay').show();

                load_mycarousel(intStart);
            }

        }

    });

};

function build_photo_collection(webRoot) {
    $.ajax({
        type: 'GET',
        url: '/windows/framework/subsites/softwearbymicrosoft/xml/photos_phase2.xml',
        dataType: 'xml',
        success: function(xml) {
            var intPatterns = $(xml).find('patterns').children().size();
            var intRandomPattern = random_number(1, intPatterns);
            var intCount = 0;
            var arrPanels = new Array();
            var arrGroupedCollection = new Array();
            var strItemNameXml;
            var strGroupedCollection = '';
            var strSafariFix = safari_fix();
            var boolLoadPanel = false;
            var boolRandomPhotos = false;

            // Grab a random pattern from the photos XML
            $(xml).find('pattern').each(function() {
                if ($(this).attr('id') == intRandomPattern) {
                    arrPanels = $(this).attr('panels').split(',');
                }
            });

            // Create an array of li tags for each featured photo
            $(xml).find('photo').each(function(i) {
                if ($(this).attr('featured') == 'true') {
                    strItemNameXml = $(this).find('name').text();
                    strItemNameXml = strItemNameXml.replace(/ /g, '_');
                    arrGroupedCollection[intCount] = '<li><a href="' + webRoot + 'photos/' + strSafariFix + '#' + strItemNameXml + '" style="background-image:url(/windows/framework/subsites/softwearbymicrosoft/images/photos/' + $(this).find('imagenamesm').text() + ')">' + strItemNameXml + '</a></li>';
                    ++intCount;
                }
            });
            
            // Use the count of featured photos to generate a random sequence for the photos
            var arrNumArray = unique_random_array(intCount, 0, (intCount-1));

            // Reset counter
            intCount = 0;
            
            // Check the XML to see if the photos are supposed to load in a random order
            if ($(xml).find('photos').attr('random') == 'true') {
                boolRandomPhotos = true;
            }

            // Cycle through the 3x3 grid
            for (var i = 0; i <= 8; i++) {
                // Determine if the current panel will be empty or if it will contain a photo thumb
                for (var p in arrPanels) {
                    if ((i + 1) == arrPanels[p]) {
                        boolLoadPanel = true;
                    }
                }

                // If the panel is supposed to contain a thumb load the thumb otherwise create an empty panel
                if (boolLoadPanel) {
                    // If the XML specifies to randomly load the photos use a random sequence otherwise load the default order
                    if (boolRandomPhotos) {
                        strGroupedCollection += arrGroupedCollection[arrNumArray[intCount]];
                    } else {
                        strGroupedCollection += arrGroupedCollection[intCount];
                    }
                    ++intCount;
                } else {
                    strGroupedCollection += '<li></li>';
                }

                boolLoadPanel = false;
            }

            // Append the 3x3 grid to the grouped collection div
            $('#GroupedCollection').append(strGroupedCollection);

            // Load the li tags in a random staggered order
            staggered_load();

            // Executes when a user clicks a thumb within the 3x3 grid
            $('#GroupedCollection li').click(function(event) {
                // Tracking code
                s.pageName = 'softwear:photos:photos_view';
                void (s.t());

                // Get the element's text to determine which photo was clicked
                strItemName = $(this).text();

                // Find and load the photo in the carousel, hide the 3x3 grid and show the photo carousel
                if (strItemName != '') {
                    $(xml).find('photo').each(function(i) {
                        strItemNameXml = $(this).find('name').text();
                        strItemNameXml = strItemNameXml.replace(/ /g, '_');
                        if (strItemNameXml == strItemName) {
                            intStart = parseInt($(this).attr('id'));
                        }
                    });

                    $(this).parent().hide();
                    $('#CarouselDisplay').show();
                    load_mycarousel(intStart);
                }

            });
        }
    });
}

function load_mycarousel(intStart) {
    jQuery('#mycarousel').jcarousel({
        wrap: 'circular',
        start: intStart,

        itemVisibleInCallback: { onBeforeAnimation: mycarousel_itemVisibleInCallback },
        itemVisibleOutCallback: { onAfterAnimation: mycarousel_itemVisibleOutCallback }
    });
    
}; 

var panel_count;
var staggeredHash;
var timer_interval;
var max_random;

function reset_staggered_vars() {
    panel_count = 0;
    staggeredHash = new Array();
    timer_interval = 200;
    max_random = 11;
}

function staggered_load() {
    $('#GroupedCollection').children().hide();
    /*
    $('#GroupedCollection').children().hide();
    $('#GroupedCollection').children().animate({
        opacity: 0.0
    }, 1);
    $('#GroupedCollection').children().show('fast');
    */
    $('#GroupedCollection').children().fadeTo(0.1, 0);

    var intRandom;

    reset_staggered_vars();

    for (i = 0; i <= 8; i++) {
        intRandom = Math.floor(Math.random() * max_random);
        intRandom = (intRandom * timer_interval);

        if (staggeredHash[intRandom.toString()]) {
            staggeredHash[intRandom.toString()] = staggeredHash[intRandom.toString()] + ":" + i.toString();
        } else {
            staggeredHash[intRandom.toString()] = i.toString();
        }
    }

    //setTimeout("show_panel()", 200);
    setTimeout("show_panel_delay()", 100);
}

function show_panel_delay() {
    $('#GroupedCollection').children().show();
    show_panel();
}

function show_panel() {
    var panelArr = new Array();
    var list = staggeredHash[(panel_count * timer_interval).toString()];

    // make sure not undefined
    if (list) {
        panelArr = list.split(":");
    }
    
    for (i = 0; i < panelArr.length; i++) {
        $("#GroupedCollection").children().eq(parseInt(panelArr[i])).fadeTo(1, 1);
    }

    if (panel_count < 11) {
        panel_count++;
        setTimeout("show_panel()", 200);
    }
}

function random_number(min, max) {
    return (Math.round((max - min) * Math.random() + min));
}

function unique_random_array(num_elements, min, max) {
    var temp, nums = new Array;

    for (var element = 0; element < num_elements; element++) {
        while ((temp = number_found(random_number(min, max), nums)) == -1);
        nums[element] = temp;
    }

    return (nums);
}

function number_found(random_number, number_array) {
    for (var element = 0; element < number_array.length; element++) {

        if (random_number == number_array[element]) {
            return (-1);
        }
    }

    return (random_number);
}

function safari_fix() {
    if ($.browser.safari) {
        //strSafariFix = 'Default.aspx';
        strSafariFix = '';
    } else {
        strSafariFix = '';
    }

    return strSafariFix;
}