/* $Revision: 84643 $
 * $Id: cmtaggingservices.js 84643 2008-04-04 18:07:32Z wbird $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v4.0, 3/19/2008
 * COPYRIGHT 1999-2002 COREMETRICS, INC. 
 * ALL RIGHTS RESERVED. U.S.PATENT PENDING
 * The following global library template tags Tuccini.com site with Coremetrics data collection tags.
 * Library is based on Front End Logic (Client Side)
 * Disclaimer: Coremetrics is not responsible for hosting or maintenance or this file
 *
*/

//Production data warehouse flag
cmSetProduction();

/*===========================GLOBAL VARIABLES ===============================*/
// current page url
var G_CM_URLPATH = "" + document.location;

// current page pathname
var G_CM_PATHNAME = document.location.pathname.toLowerCase();

var G_CM_TUCCINI = "Tuccini";

// current page referrer
var G_CM_REFERRER = document.referrer.toLowerCase();

// cookie lifetime, defauts to 5 days
var G_CM_COOKIE_LIFETIME = 5*24*60*60;

// cookie name
var G_CM_COOKIE_PRODUCT_VIEW = "CM_PRODUCTS_VIEW";
var G_CM_COOKIE_CUSTOMERID = "CM_CUSTOMERID";
var G_CM_COOKIE_PRODUCT_NAME = "CM_PRODUCT_NAME";

// cookie domain, unused from [mar-31-2008], using default domain instead
//var G_CM_COOKIE_DOMAIN = "www.tuccini.com";

// product view category_id
var G_CM_CATEGORY_PRODUCT_VIEW = null;
/*===========================END GLOBAL VARIABLES ===========================*/



/*===========================GLOBAL MATCHING PATTERN ========================*/

/*===========================END GLOBAL MATCHING PATTERN=====================*/


/*===========================NAVIGATION ====================================*/
if (
        G_CM_PATHNAME == "/" 
        || G_CM_PATHNAME == "/default.aspx"
   )
{
    cmCreatePageviewTag("Tuccini Home Page", "HOME", null);
} 
else if (G_CM_PATHNAME.indexOf("/catalog/") != -1) 
{
    var catalogName = getCatalogName();
    
    cmCreatePageviewTag("BROWSE:" + catalogName, cleanCategoryId(catalogName), null);
}
else if (G_CM_PATHNAME.indexOf("/designers/") != -1) 
{
    var designerName = getDesignerName();
	var right_arrow = " --> Designer";
    cmCreatePageviewTag("DESIGNER:" + designerName+right_arrow, cleanCategoryId(designerName)+right_arrow, null);
}
else if (G_CM_PATHNAME.indexOf("/items/gift_sets/") != -1)
{
    var products = getListOfProductTables();

    var brandName = getGiftBrandName();

    var categoryId = null;
	var right_arrow = " --> ";
	var gendend = G_CM_PATHNAME.split("_")[G_CM_PATHNAME.split("_").length-1];
	var ggender = gendend.split(".")[0];
 
        categoryId = (products.length==0) ? "NO ITEMS" : cleanCategoryId(brandName)+right_arrow+cleanCategoryId(ggender).toUpperCase();
    
    G_CM_CATEGORY_PRODUCT_VIEW = categoryId;

    var giftSetTitle = brandName + " GIFT SETS for " + ggender;

    cmCreatePageviewTag("GIFT SET:" + brandName, cleanCategoryId(categoryId), null);

    // adding productview tag
    // THIS IS THE MYSTERY ABOUT cmCreateProductviewTag: 
    // The index of the loop SHOULD NOT be i
    
    for (var p_i=0; p_i<products.length; p_i++)
    {
        var product = products[p_i];
        var product_info = getProductInfo(product);
        
        // infinite loop if index variable is i
        cmCreateProductviewTag(product_info[0],  brandName+' '+product_info[1]+' for '+cleanCategoryId(ggender).toUpperCase(), cleanCategoryId(categoryId));
    }
    
    // add listener for all <add to bag> button
    registerCartListener();
}
else if (G_CM_PATHNAME.indexOf("/items/") != -1)
{
    // three scenarios here

    //1: only one product: call 1 pageview and 1 productview
    //2: many products: call 1 pageview and many productviews
    //3: no products: call 1 pageview only

    // get list of products
    var products = getListOfProductTables();

    // get the brandname from title
    var brandName = getGiftBrandName();

    // logic to determine categoryID
	// no logic required. CategoryID = BRAND --> Gender
	// i.e. CategoryID = HALSTON 1-12 --> Men
    var categoryId = null;
    // if (G_CM_REFERRER.indexOf("product_catalog.aspx") > -1)
    // {
        // originated from 4 main categories, get category from breadcrum
	var right_arrow = " --> ";
	var con_cat_gender = getElementValueById("_ctl0_Body_C_ItemDetail1_CategoryHeading").split("'")[0];
 
    //else if (G_CM_REFERRER.indexOf("product_results_keyword.aspx") > -1)
    //{
    //    categoryId = "SEARCH"
    //}
    //else
    //{
        categoryId = (products.length==0) ? "NO ITEMS" : cleanCategoryId(brandName)+right_arrow+cleanCategoryId(con_cat_gender);
    //}
    
    // this for onclick event of add_to_bag
    G_CM_CATEGORY_PRODUCT_VIEW = categoryId;

    // SEND page view tag
    cmCreatePageviewTag("PRODUCT:" + getProductTitle(), cleanCategoryId(categoryId), null);

    // adding productview tag
    // THIS IS THE MYSTERY ABOUT cmCreateProductviewTag: 
    // The index of the loop SHOULD NOT be i
    
    for (var p_i=0; p_i<products.length; p_i++)
    {
        var product = products[p_i];
        var product_info = getProductInfo(product);
        
        // infinite loop if index variable is i
        cmCreateProductviewTag(product_info[0], brandName+' '+product_info[1]+' for '+cleanCategoryId(con_cat_gender), cleanCategoryId(categoryId));
    }
    
    // add listener for all <add to bag> button
    registerCartListener();
}
else if (G_CM_PATHNAME == "/product_results.aspx") // need to refine the pattern
{
    var designerName = getDesignerName();
    cmCreatePageviewTag("DESIGNER:" + designerName, cleanCategoryId(designerName), null);
}
else if (G_CM_PATHNAME == "/product_results_keyword.aspx")
{
    // this for search
    // pageviewtag
    searchResult();
}
else if (G_CM_PATHNAME == "/product_cart.aspx")
{
    // this for shopping cart
    cmCreatePageviewTag("your shopping bag", "your shopping bag", null);
    
    var products = getProductListShop5();
    for (var i=0; i<products.length; i++) 
    {
        cmCreateShopAction5Tag(products[i][0], products[i][1], products[i][2], products[i][3], products[i][4]);
    }    

    cmDisplayShop5s();
}
else if (
            G_CM_PATHNAME == "/email_signup.aspx"
	)
{
	    cmCreatePageviewTag("Email Signup","CONTENT", null);
}

else if (
            G_CM_PATHNAME == "/ourphilosophy.aspx"
            || G_CM_PATHNAME == "/customerservice.aspx"
            || G_CM_PATHNAME == "/contactus.aspx"
            || G_CM_PATHNAME == "/aboutus.aspx"
            || G_CM_PATHNAME == "/sitemap.aspx"
            || G_CM_PATHNAME == "/productguarantees.aspx"
            || G_CM_PATHNAME == "/privacy.aspx"
            || G_CM_PATHNAME == "/customertestimonials.aspx"
            || G_CM_PATHNAME == "/faq.aspx"
            || G_CM_PATHNAME == "/employment.aspx"
            || G_CM_PATHNAME == "/investor.aspx"
            || G_CM_PATHNAME == "/shipping.aspx"
            || G_CM_PATHNAME == "/returnandrefund.aspx"
        )
{
    // this for content view
    // pageviewtag
    var page_id = getPageIDFromContentPage(G_CM_PATHNAME);
    cmCreatePageviewTag(page_id, "CONTENT", null);
}
else if (
            G_CM_PATHNAME == "/account/forgotpwd.aspx"
            || G_CM_PATHNAME == "/account/logout.aspx"
            || G_CM_PATHNAME == "/account/orders.aspx"
        )
{
    // this for content view
    // pageviewtag
    var page_id = getPageIDFromContentPage(G_CM_PATHNAME);
    cmCreatePageviewTag(page_id, "MY ACCOUNT", null);
}
else if (G_CM_PATHNAME == "/product_brands.aspx")
{
    cmCreatePageviewTag("View All Brands", "CONTENT", null);
}
else if (G_CM_PATHNAME == "/product_designers.aspx")
{
    cmCreatePageviewTag("List All Designers", "CONTENT", null);
}
else if (
            G_CM_PATHNAME == "/account/login.aspx" 
            || G_CM_PATHNAME== "/account/register.aspx"
        )
{
    var page_id = getPageIDFromContentPage(G_CM_PATHNAME);
    cmCreatePageviewTag(page_id, "MY ACCOUNT", null);
    
    onRegistrationSubmit();
}
else if (G_CM_PATHNAME == "/account/profile.aspx")
{
    cmCreatePageviewTag("account/profile", "MY ACCOUNT", null);
    
    // SEND registration tag
    var errorStatus = getElementValueById('_ctl0_Body_ms_customer_info_lblStatus');
    if(errorStatus != null && errorStatus.indexOf("has been saved successfully") > -1)
    {
        cmCreateRegistrationTag(getElementValueById('_ctl0_Body_ms_customer_info_txtEmail') , getElementValueById('_ctl0_Body_ms_customer_info_txtEmail'), getElementValueById('_ctl0_Body_ms_customer_info_txtCity'),getElementValueById('_ctl0_Body_ms_customer_info_cmbState'),getElementValueById('_ctl0_Body_ms_customer_info_txtZip'));    
    }
}
else if (
            G_CM_PATHNAME == "/checkout/default.aspx"
            || G_CM_PATHNAME == "/checkout/default.asp"
            || G_CM_PATHNAME == "/checkout/"
        )
{
    // checkout page view
    cmCreatePageviewTag("enter billing and shipping", "checkout", null);

    onRegistrationCheckout();
}
else if (G_CM_PATHNAME == "/account/default.aspx")
{
    var page_id = getPageIDFromContentPage(G_CM_PATHNAME);
    cmCreatePageviewTag(page_id, "MY ACCOUNT", null);
    
    if(G_CM_REFERRER == "https://www.tuccini.com/account/login.aspx?returnurl=%2faccount%2fdefault.aspx")
    {
        var arrRegisterInfo = getRegisterInfo();
        if(arrRegisterInfo)
        {
            cmCreateRegistrationTag(arrRegisterInfo[0],arrRegisterInfo[0], null);
            psSetCookie(G_CM_COOKIE_CUSTOMERID, "", "delete"); //delete cookie
        }
    }
}
else if (G_CM_PATHNAME == "/checkout/submit.aspx")
{
    if (G_CM_REFERRER.indexOf("checkout/default.aspx") > -1)
    {
        var arrRegisterInfo = getRegisterInfo();
        if(arrRegisterInfo)
        {
            cmCreateRegistrationTag(arrRegisterInfo[0] , arrRegisterInfo[0], arrRegisterInfo[1],arrRegisterInfo[2],arrRegisterInfo[3]);
            psSetCookie(G_CM_COOKIE_CUSTOMERID, "", "delete"); //delete cookie
        }
    }
    if (checkVerifyPay()) 
    {
        cmCreatePageviewTag("verify and pay", "checkout", null);
    }
}
else if (G_CM_PATHNAME == "/checkout/thankyou.aspx")
{
    cmCreatePageviewTag("thank you for your order", "checkout", null);
    var orderShipping = getOrderShipping();
    var products = getProductListShop9();
    for (var j=0; j<products.length; j++) 
    {
        cmCreateShopAction9Tag(products[j][0], products[j][1], products[j][2], products[j][3], products[j][4],products[j][5], products[j][6], products[j][7]);
    }    
    cmDisplayShop9s();
    cmCreateOrderTag(products[0][5],products[0][6],orderShipping,products[0][4]);

}
/*===========================END NAVIGATION ================================*/


/*===========================GENERAL UTILITY FUNCTION ======================*/

/*
* This function can be used to remove all HTML tags in a string
*/
function cleanHtmlTag(textWithTags)
{
    return (textWithTags != null) ? textWithTags.replace(/\<+.+?\>+/g, "") : null;
}


/*
* This function can be used to clean unaccepted characters in categoryid: [', ", :, ©, ®]
*/
function cleanCategoryId(categoryId)
{
    return (categoryId != null) ? categoryId.replace(/['":©®]/g, "") : null;
}


/*
* This function removes all leading & trailing spaces of a string
*/
function trim(str)
{
    return (str != null) ? str.replace(/^\s+|\s+$/g, '') : null;
}


/*
* This function can be used to extract value from the URL 
* in format of http://xxx.com/page.ext?name1=value1&name2=value2
*/
function getValueFromUrl(url, param_name)
{
    var re = new RegExp( "[?&]" + param_name + "=*([^&$]*)", "i" );
    var offset = url.search(re);
    if (offset == -1) return null;
    return unescape(RegExp.$1);

}


/*
* This function returns the value of an element in page based on element_id
* For the normal tag: returns innerHTML
* For INPUT tag: returns value property
*/

function getElementValueById(tagId)
{
    var tag = document.getElementById(tagId);

    return getElementValue(tag);
}

/*
* This function returns the value of an element in page based on element object
* For the normal tag: returns innerHTML
* For INPUT tag: returns value property
* For SELECT tag: returns selected label
*/

function getElementValue(tag)
{
    var tagValue = null;
    if (tag != null)
    {
        if (tag.tagName.search(/^INPUT$/i) > -1)
        {
            tagValue = tag.value;
        }
        else if (tag.tagName.search(/^SELECT$/i) > -1)
        {
            var option = tag.options[tag.selectedIndex];
            tagValue = option.innerHTML; // return label instead of value
        }
        else
        {
            tagValue = tag.innerHTML;
        }

        tagValue = psHtmlDecode(tagValue);
    }

    return tagValue;
}

/*
* This is browser-independent function (IE, FireFox)
* to get a cell from a table with designated row index and column index (zero-based)
* This function runs well even with nested tables
* @table: the table object to search on
* @rowIndex: the row to locate cell
* @cellIndex: the index of cell
*
* RETURN: <NULL> or <TD object>. This object, in return, can allow to filter its children
* by calling getElementsByTagName("element_tag_name")
*/
function getCell(table, rowIndex, cellIndex)
{
    var tdCell = null;

    // get all rows
    var trRows = getRows(table);

    if (trRows.length > 0)
    {
        var trRow = trRows[rowIndex];

        // get all cells in this row
        var tdCells = getCells(trRow);
        if (tdCells.length > 0 && cellIndex < tdCells.length)
        {
            var tdCell = tdCells[cellIndex];
        }
    }

    return tdCell;
}


/*
* This is browser-independent function (IE, FireFox)
* to get all TR rows from a table
* @table: the table object to search on
*
* RETURN: <NULL> or <array of TR objects>
*/
function getRows(table)
{
    // locate the TBODY object. Normally, only one TBODY in a table
    var tableChilds = table.childNodes;
    var tBody
    for (i=0; i<tableChilds.length; i++)
    {
        if (tableChilds[i].tagName != null && tableChilds[i].tagName.search(/^TBODY$/i) > -1)
        {
            tBody = tableChilds[i];
            break;
        }
        
    }
    
    // filter actual rows
    var trRows = new Array();
    var items = tBody.childNodes;
    var rowTh = 0; // TBODY may contain <text object> inside, this is the actual row index
    for (i=0; i<items.length; i++)
    {
        if (items[i].tagName != null && items[i].tagName.search(/^TR$/i) > -1)
        {
            trRows[rowTh++] = items[i];
        }
    }

    return trRows;
}


/*
* This is browser-independent function (IE, FireFox)
* to get all TD cells from a row
* @row: the row to get cells from
*
* RETURN: <NULL> or <array of TD objects>
*/
function getCells(row)
{
    // filter actual cells
    var tdCells = new Array();
    var items = row.childNodes;
    var cellTh = 0; // TR may contain <text object> inside, this is the actual cell index
    for (i=0; i<items.length; i++)
    {
        if (items[i].tagName != null && items[i].tagName.search(/^TD|TH$/i) > -1)
        {
            tdCells[cellTh++] = items[i];
        }
    }

    return tdCells;
}

function getCellFromRow(row, cellIndex)
{
    if (row != null)
    {                       
        var tdCells = getCells(row); // get all cells of the specified row
        if ((tdCells.length > 0) && (cellIndex < tdCells.length))
            return tdCells[cellIndex];
    }
    return null;
}

function checkEmail(email) 
{
    var i = email.search(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);

    return (i > -1) ? true : false;
}

function psHtmlDecode(pValue)
{
    var sResult = pValue;
    if (pValue)
    {
        sResult = pValue;
        sResult = sResult.replace(/&nbsp;/gi, " ");
        sResult = sResult.replace(/&quot;/gi, '"');
        sResult = sResult.replace(/&amp;/gi, "&");
        sResult = sResult.replace(/&lt;/gi, "<");
        sResult = sResult.replace(/&gt;/gi, ">");
    }

    return sResult;
}
/*===========================END GENERAL UTILITY FUNCTION ==================*/

/*===========================TUCCINI UTILITY FUNCTION ======================*/

/*
* This function returns an array of product information {productId, productName}
* This is not working with FireFox at the moment >> need to adjust code
* The logic here requires fixed table structure. Otherwise, it's broken.
*/
function getProductInfo(table)
{
    // get the table that contains data
    var product_info = new Array(2);

    // locate the product name/id table
    var nameIdTable = getCell(table, 0, 1).getElementsByTagName("table")[0];
    // product id
    var pi_tmp = getElementValue(getCell(nameIdTable, 1, 0).getElementsByTagName("span")[0]);
    product_info[0] = pi_tmp.split(' ')[1];
    // product name
	product_info[1] = getElementValue(getCell(nameIdTable, 0, 0).getElementsByTagName("span")[0]);
    
	// 

    return product_info;
}

/*
* This function returns an array of tables storing product information
* The logic needs to refine
*/

function getListOfProductTables()
{
    //<table bgcolor="ffffff" width="630" border="0" cellspacing="0" cellpadding="0">
    var allTables = document.getElementsByTagName("table");
    var productTables = new Array();
    var j = 0;

    //filter product table with attributes as above
    for (i=0; i<allTables.length; i++)
    {
        if (allTables[i].className == "" && allTables[i].width == "630")
        {
            productTables[j++] = allTables[i];
        }
    }

    return productTables;
}

/*
* This function extracts brandname from page title
*/
function getBrandNameFromTitle()
{
    var brand = null;
    var title = document.getElementById("_ctl0_Body_C_ItemDetail1_lblBrandDesigner");
    if (title != null)
    {
        brand = psHtmlDecode(title.getElementsByTagName("strong")[0].innerHTML);
    }

    return brand;
}

/*
* This function returns product_title stored in _ctl0_Body_C_ItemDetail1_lblBrandDesigner
* Format stored: <strong><brand name></strong> by <designer name>
*/
function getProductTitle()
{
    return psHtmlDecode(cleanHtmlTag(getElementValueById("_ctl0_Body_C_ItemDetail1_lblBrandDesigner")));
}


/*
* This function returns desinger_name stored in _ctl0_Body_Results_Gallery_lbDesigner
* Intend to use in products_result.aspx
*/
function getGiftBrandName()
{
	var desstri = document.location.pathname.toLowerCase();
	var desari = desstri.split("/")[desstri.split("/").length-1].split("_by_")[0].replace(/_/g," ").toUpperCase();
	return desari;
}

function getDesignerName()
{
/*
*    return psHtmlDecode(cleanHtmlTag(getElementValueById("_ctl0_Body_Results_Gallery_lbDesigner")));
*    return G_CM_PATHNAME.substr(G_CM_PATHNAME.lastIndexOf("/")).split('.')[0].replace(/_/," ");
*/
//	return document.getElementsByTagName("title").replace(/ perfumes/,"");

	var desstri = document.location.pathname.toLowerCase();
	var desari = desstri.split("/")[desstri.split("/").length-1].split(".")[0].replace(/_/g," ").toUpperCase();
	return desari;
}


/*
* This function returns PageID from content page 
*/
function getPageIDFromContentPage(pagename)
{
    var h5tag = document.getElementsByTagName("h5");
    var page_id = null;
    if (h5tag.length > 0)
    {
        page_id = psHtmlDecode(h5tag[0].innerHTML);
    }
    else
    {
        page_id = G_CM_PATHNAME.split(".")[0].substring(1);
    }
    
    return page_id;
}

/*
* This function returns CatalogName
*/
function getCatalogName()
{
//    return psHtmlDecode(getElementValueById("_ctl0_Body_BreadCrumbs1_dlCategoryTree__ctl2_lnkCategory"));
	return G_CM_PATHNAME.split(".")[0].split("/")[G_CM_PATHNAME.split(".")[0].split("/").length-1].replace(/_/g," ").toUpperCase();
}


/*
* This function returns ProductName
*/
function getProductName(product_info) {
    if (product_info != null)
    {
        var i = product_info.search(/\sBY\s/i);
        return trim(product_info.substring(0, i));
    }
    return null;
}

/*
* This function returns ProductId. SKU Number
*/
function getProductId(product_sku) {
    return (product_sku != null) ? trim(cleanHtmlTag(product_sku.split("#:")[1])) : null;
}

/*
* This function trim $ character
*/
function trimUnitPrice(unitprice) {
    return (unitprice != null) ? unitprice.replace("$","") : null;
}

function checkVerifyPay() 
{
//    return (document.getElementById("_ctl0_Body_C_HeaderNav2_tdSecure") != null) && (document.getElementById("_ctl0_Body_C_HeaderNav2_tdSecure").parentNode.innerHTML.search("chkout-verifyandpayheading.gif") > -1);
    return (document.body.innerHTML.search("chkout-verifyandpayheading.gif") > -1);
}

function getProductListShop9()
{
    var arrItems = new Array();
    var OrderId = document.getElementById("_ctl0_Body_OrderDetailView1_OrderType").innerHTML;
    var SubTotal = document.getElementById("_ctl0_Body_OrderDetailView1_lblSubTotal").innerHTML.replace("$","");
    var CustomerId = document.getElementById("_ctl0_Body_OrderDetailView1_lnkEMail").innerHTML.replace("mailto:", "").split("&")[0].replace("%40", "@");
    var mscGridTable = document.getElementById("_ctl0_Body_OrderDetailView1_dgItems");
    
    for (var i=1; i<mscGridTable.rows.length; i++) //i=0, first row is header
    {
        var productId = getProductId(mscGridTable.rows[i].cells[0].innerHTML);
        arrItems[i-1] = new Array(
        productId,
        psHtmlDecode(getValueFromCookie(G_CM_COOKIE_PRODUCT_NAME, productId)),
        mscGridTable.rows[i].cells[1].innerHTML,
        mscGridTable.rows[i].cells[2].innerHTML,
        CustomerId,
        OrderId,
        SubTotal,
        psHtmlDecode(cleanCategoryId(getValueFromCookie(G_CM_COOKIE_PRODUCT_VIEW, productId))))
    }
    return arrItems;
}

function getOrderShipping() 
{
    var price = document.getElementById("_ctl0_Body_OrderDetailView1_lblShipping");
    return (price != null) ? price.innerHTML.replace("$", "") : null;
}

/*
* This function returns an array of product list info {productId, productName,Quantity,Unitprice,Categoryid}
*/
function getProductListShop5() 
{
    var allTables = document.getElementsByTagName("TABLE");
    var msc_GridTable = null;
    var msc_rows;
    var products = new Array();
    var product_sku; // data: SKU#: tc012003239
    for (i=0; i<allTables.length; i++)
    {
        if (allTables[i].className == "mscGridTable")
        {
            msc_GridTable  = allTables[i];
        }
    }
    
    var j=0;
    
    if (msc_GridTable != null && typeof(msc_GridTable) != "undefined") {
        for (i=0; i<msc_GridTable.rows.length; i++) 
        {
            msc_rows = msc_GridTable.rows[i];
            if ( msc_rows.className == "mscGridRow" || msc_rows.className == "mscGridAltRow") 
            {
                product_sku = msc_rows.cells[1].innerHTML;
                var productId = getProductId(product_sku);
                products[j++] = new Array
                (
                    productId,
                    psHtmlDecode(getValueFromCookie(G_CM_COOKIE_PRODUCT_NAME, productId)),
                    msc_rows.cells[2].childNodes[1].value,
                    trimUnitPrice(msc_rows.cells[3].firstChild.nodeValue),
                    psHtmlDecode(cleanCategoryId(getValueFromCookie(G_CM_COOKIE_PRODUCT_VIEW, productId)))
                )
            }
        } 
    }
    return products;
}

function searchResult()
{
    var pageID;
    var searchTerm;
    var searchResults;

    if(getElementValueById('_ctl0_Body_Results_Gallery_lblErrorMessage')) //error message
    {
        // SEND page view tag for unsuccessful search
        cmCreatePageviewTag("SEARCH UNSUCCESSFUL", "SEARCH", getValueFromUrl(G_CM_URLPATH, "keyword"), "0");
    }
    else
    {
        if(getElementValueById('_ctl0_Body_Results_Gallery_lblRefinedRecordCountPrice') == "")
        {
            pageID = "SEARCH SUCCESSFUL PAGE " + getElementValueById('_ctl0_Body_Results_Gallery_PagerTop_lblCurrentPage');
            searchTerm = getElementValueById('_ctl0_Body_Results_Gallery_lblKeyword');
            searchResults = getElementValueById('_ctl0_Body_Results_Gallery_lblRecordCount');

            // SEND page view tag for successful search
            cmCreatePageviewTag(pageID, "SEARCH", searchTerm, searchResults);
        }
        else
        {
            // refinement by price
            var CategoryID = getValueFromUrl(G_CM_URLPATH, "pr");
            pageID = getPageIdByPrice();
            searchTerm = getElementValueById('_ctl0_Body_Results_Gallery_lblRefinedKeyPrice');
            searchResults = getElementValueById('_ctl0_Body_Results_Gallery_lblRecordCount');

            // SEND page view tag for search refinement
            cmCreatePageviewTag(pageID, CategoryID, searchTerm, searchResults); 
        }
    }
}

function registratitonTag()
{
    //login page
    if(getElementValueById('_ctl0_Body_LoginForm1_txtIdentityName'))
    {
        // SEND registration tag
        psSetCookie(G_CM_COOKIE_CUSTOMERID, getElementValueById('_ctl0_Body_LoginForm1_txtIdentityName') + '|');
    }
    //in registrator page
    else if(getElementValueById('_ctl0_Body_RegistrationForm1_txtEmail'))
    {    
        // SEND registration tag
        if(checkValidateRegister())
        {
            cmCreateRegistrationTag(getElementValueById('_ctl0_Body_RegistrationForm1_txtEmail') , getElementValueById('_ctl0_Body_RegistrationForm1_txtEmail'), getElementValueById('_ctl0_Body_RegistrationForm1_txtCity'),getElementValueById('_ctl0_Body_RegistrationForm1_cmbState'),getElementValueById('_ctl0_Body_RegistrationForm1_txtZip'));    
        }

    }
}

function getRegisterInfo()
{
    var cookieValue = psGetCookie(G_CM_COOKIE_CUSTOMERID);    
    if(cookieValue)
    {
        arrRegisterInfo = cookieValue.split("|");
    }
    return arrRegisterInfo;
}

function onRegistrationSubmit()
{
    var formSubmit = document.getElementById('aspnetForm');
    formSubmit.onsubmit = function()
    {
        if (WebForm_OnSubmit() == false)
        {
            return false;
        }
        else
        {
            registratitonTag();
            return true;
        }
    }
}

function onRegistrationCheckout()
{
    var allInputs = document.getElementsByTagName("input");
    var imagesBtn = new Array();
    var j = 0;
    
    for (i=0; i<allInputs.length; i++)
    {
        var item = allInputs[i];
        if (item.getAttribute("type") == "image" && item.getAttribute("src").search(/checkout2\-continue/i) > -1)
        {
            imagesBtn[j] = allInputs[i];
            imagesBtn[j].onclick = function()
            {
                // save input to cookie
                var valueSetCookie =    getElementValueById('_ctl0_Body_CartAddressForm1_txtEmail') + '|' + 
                                        getElementValueById('_ctl0_Body_CartAddressForm1_txtCity') + '|' +  
                                        getElementValueById('_ctl0_Body_CartAddressForm1_cmbState') + '|' + 
                                        getElementValueById('_ctl0_Body_CartAddressForm1_txtZip');
                psSetCookie(G_CM_COOKIE_CUSTOMERID, valueSetCookie);
                return true; 
            }
            ++j;
        }

    }
    if(getElementValueById('_ctl0_Body_LoginForm1_btnLogin_AButton')== null)
    {
        // SEND registration tag
        cmCreateRegistrationTag(getElementValueById('_ctl0_Body_CartAddressForm1_txtEmail'), getElementValueById('_ctl0_Body_CartAddressForm1_txtEmail'), null);
    }    
}

function checkValidateRegister()
{
    if(checkEmail(getElementValueById('_ctl0_Body_RegistrationForm1_txtEmail'))==false
        || getElementValueById('_ctl0_Body_RegistrationForm1_txtPassword')==""
        || getElementValueById('_ctl0_Body_RegistrationForm1_txtPasswordC')==""
        || getElementValueById('_ctl0_Body_RegistrationForm1_txtFirstName')==""
        || getElementValueById('_ctl0_Body_RegistrationForm1_txtLastName')==""
        || getElementValueById('_ctl0_Body_RegistrationForm1_txtAddress')==""
        || getElementValueById('_ctl0_Body_RegistrationForm1_txtCity')==""
        || getElementValueById('_ctl0_Body_RegistrationForm1_cmbState')==""
        || getElementValueById('_ctl0_Body_RegistrationForm1_txtZip')==""
        || getElementValueById('_ctl0_Body_RegistrationForm1_cmbCountry')==""
        || getElementValueById('_ctl0_Body_RegistrationForm1_txtPhone')==""
     )
         return false;
     else
         return true;

}

function getPageIdByPrice()
{
    var price = getValueFromUrl(G_CM_URLPATH, "pr");
    if(price.search(/^(.{2})(.{2})$/gi)>-1 || 
       price.search(/^(.{2})(.{3})$/gi)>-1 || 
       price.search(/^(.{3})(.{3})$/gi)>-1)
    {
        price = "$" + RegExp.$1 + " - " + "$" + RegExp.$2;
        price = price.replace(/\$00/, "$0");
    }
    else if(price.search(/^(over)(.*)$/gi)>-1)
    {
        price = RegExp.$1 + " $" + RegExp.$2;
    }
    return "CATEGORY: " + price;
}


/*
* Save a key:value pair to cookie
* If this key is new, it will be added. Otherwise, just update
* Format: |key1:value1|key2:value2
* This cookie should not go over 4K limit
* Eldest items will be removed to keep it under 3500 bytes
*/
function updateCookie(cookieName, pKey, pValue)
{
    // delete this product from cookie if existing
    deleteItemFromCookie(cookieName, pKey);

    // update cookie with new information of that product
    var catCookie = psGetCookie(cookieName);
    
    if (catCookie != null)
    {
        // put it on top
        psSetCookie(cookieName, "|" + pKey + ":" + pValue + catCookie, G_CM_COOKIE_LIFETIME);
    }
    else
    {
        psSetCookie(cookieName, "|" + pKey + ":" + pValue, G_CM_COOKIE_LIFETIME);
    }
}


/*
* Get value stored in cookie in format of:
* |key1:value1|key2:value2
* RETURN: <null> or the found value
*/
function getValueFromCookie(cookieName, pKey)
{
    var sValue = null;
    var catCookie = psGetCookie(cookieName);
    if (catCookie != null)
    {
        var re = new RegExp("\\|" + pKey + ":([^\\|$]+)", "i");
        var i = catCookie.search(re);

        sValue = (i>-1) ? RegExp.$1 : null;
    }

    return sValue;
}


/*
* Remove an item from cookie stored in format of:
* |key1:value1|key2:value2
* RETURN: <null> if failed or not-null value if successful
*/
function deleteItemFromCookie(cookieName, pKey)
{
    var catCookie = psGetCookie(cookieName);
    if (catCookie != null)
    {
        var re = new RegExp("\\|+" + pKey + ":[^\\|$]+", "i");
        var newCatCookie = catCookie.replace(re, "");

        // save new value for cookie
        psSetCookie(cookieName, newCatCookie, G_CM_COOKIE_LIFETIME);
        return 1;
    }

    return null;
}

/*
* Register onclick event for all image buttons in product_view page
* to keep track categoryid later
* 
* RETURN: none
*/
function registerCartListener()
{
    var allInputs = document.getElementsByTagName("input");
    var imagesBtn = new Array();
    var j = 0;

    for (i=0; i<allInputs.length; i++)
    {
        var item = allInputs[i];
        if (item.getAttribute("type") == "image" && item.getAttribute("src").search(/addtobag/i) > -1)
        {
            imagesBtn[j] = allInputs[i];
            imagesBtn[j].onclick = function()
            {
                // lookup the product id
                var parentTable = this.parentNode.parentNode.parentNode.parentNode;
                var product_table = getCell(parentTable, 0, 1).getElementsByTagName("table")[0];
                var productId = getElementValue(getCell(product_table, 1, 0).getElementsByTagName("span")[0]);
                var productName = getElementValue(getCell(product_table, 0, 0).getElementsByTagName("span")[0]);

                // set cookie when button clicked
                updateCookie(G_CM_COOKIE_PRODUCT_VIEW, productId, G_CM_CATEGORY_PRODUCT_VIEW);
                updateCookie(G_CM_COOKIE_PRODUCT_NAME, productId, productName);
                
                return true; // continue on view cart page
            }
            ++j;
        }
    }

}
function psGetCookie(cookieName) 
{
    /* retrieved in the format
    cookieName4=value; cookieName3=value; cookieName2=value; cookieName1=value
    only cookies for this domain and path will be retrieved */
    var cookieJar = document.cookie.split("; ");
    for(var x = 0; x < cookieJar.length; x++) 
    {
        var oneCookie = cookieJar[x].split("=");
        if(oneCookie[0] == cookieName) { return oneCookie[1] ? unescape(oneCookie[1]) : ''; }
    }
    return null;
}

/*
* Notes: cookie length should not go over 3500 bytes
* Always set cookie to root path
* @lifeTime in seconds
*/
function psSetCookie(cookieName, cookieValue, lifeTime, domain) 
{
    // remove the last items (eldest items) until cookie size < 3500
    while (cookieValue.length > 3500)
    {
        var cookieArray = cookieValue.split("|");
        cookieArray.pop();
        cookieValue = cookieArray.join("|");
    }
    
    if(!cookieName) { return false; }
    if(lifeTime == "delete") 
    { 
        //delete cookie by calling coremetrics's cookie function
        CC(cookieName);
        return true;
    } 

    // set cookie by calling coremetrics's cookie function
    var expire = (lifeTime) ? (new Date((new Date()).getTime() + (1000 * lifeTime))).toGMTString() : null;
    
    return CB(cookieName, escape(cookieValue), expire, domain);
}
/*===========================END TUCCINI UTILITY FUNCTION ==================*/

//-->

document.write('<\/script>');