﻿// JScript File
var Page;
var Ret;
var iFlag=0;
var iFlagMax=20;
var RecTypeQSName;
var CampaignQSName;
var PHNameQSName;
var SourceIdQSName;
var RecTypeCKName;
var CampaignCKName;
var PHNameCKName;
var SourceIdCKName;
var PresIdGroupDel;
var PresValAddParamsDel;
var PresNameValDel;
var PresProductsDel;



// set querystring and Cookie names - if value exist in CelebrosConectivity, set the value, if not, set default value
if(typeof CelebrosConectivity !='undefined')
{
    RecTypeQSName= ((CelebrosConectivity.celRecommendationTypeQSName!=undefined)?CelebrosConectivity.celRecommendationTypeQSName:'celRecommendationType');
    CampaignQSName= ((CelebrosConectivity.celCampaignNameQSName!=undefined)?CelebrosConectivity.celCampaignNameQSName:'celCampaignName');
    AlgorithmQSName= ((CelebrosConectivity.celAlgorithmNameQSName!=undefined)?CelebrosConectivity.celAlgorithmNameQSName:'celAlgoName');
    PHNameQSName= ((CelebrosConectivity.celPHNameQSName!=undefined)?CelebrosConectivity.celPHNameQSName:'celPHName');
    SourceIdQSName= ((CelebrosConectivity.celSourceIdQSName!=undefined)?CelebrosConectivity.celSourceIdQSName:'celSourceId');
    
    RecTypeCKName= ((CelebrosConectivity.celRecommendationTypeCKName!=undefined)?CelebrosConectivity.celRecommendationTypeCKName:'celRecommendationTypeCk');
    CampaignCKName= ((CelebrosConectivity.celCampaignNameCKName!=undefined)?CelebrosConectivity.celCampaignNameCKName:'celCampaignNameCk');
    PHNameCKName= ((CelebrosConectivity.celPHNameCKName!=undefined)?CelebrosConectivity.celPHNameCKName:'celPHNameCk');
    AlgorithmNameCKName= ((CelebrosConectivity.celAlgorithmNameCKName!=undefined)?CelebrosConectivity.celAlgorithmNameCKName:'celAlgoNameCk');
    SourceIdCKName= ((CelebrosConectivity.celSourceIdCKName!=undefined)?CelebrosConectivity.celSourceIdCKName:'celSourceIdCk');
    //internal cookies
    InternalPVCKName= ((CelebrosConectivity.celLastViewdCKName!=undefined)?CelebrosConectivity.celLastViewdCKName:'celLastViewedCk');
    InternalATCCKName= ((CelebrosConectivity.celATCCKName!=undefined)?CelebrosConectivity.celATCCKName:'celATCCk');
    
    
    //set delimiters for internal cookies
    PresIdGroupDel=((CelebrosConectivity.IdGroupDelimiterVal!=undefined)?CelebrosConectivity.IdGroupDelimiterVal:'/');
    PresValAddParamsDel=((CelebrosConectivity.TypeValAddParamsDelimiterVal !=undefined)?CelebrosConectivity.TypeValAddParamsDelimiterVal :'_');
    PresNameValDel=((CelebrosConectivity.NameValDelimiterVal  !=undefined)?CelebrosConectivity.NameValDelimiterVal :'-');
    PresProductDel= ((CelebrosConectivity.ProductsDelimiterVal !=undefined)?CelebrosConectivity.ProductsDelimiterVal:'!');

}   

//load fcImplementation script dynamically
var fcScript= document.createElement('script');
fcScript.type='text/javascript';
var infraScript= document.createElement('script');
infraScript.type='text/javascript';
if( typeof CelebrosConectivity != 'undefined')
{
    if(CelebrosConectivity.DNSsuffix!=undefined)
    {
        fcScript.src=((location.protocol=='http:')?'http:':'https:') +'//'+CelebrosConectivity.DNSsuffix+'-cs.celebros-analytics.com/widgets/AnalyticsWrappers/FCImplementation.js';
        infraScript.src=((location.protocol=='http:')?'http:':'https:') +'//'+CelebrosConectivity.DNSsuffix+'-cs.celebros-analytics.com/widgets/AnalyticsWrappers/infra.js';
        document.getElementsByTagName('head')[0].appendChild(fcScript);
        document.getElementsByTagName('head')[0].appendChild(infraScript);
    }
}


///###################################################################

/*
 function: PageHandle
 description: receives a celebros Page object and handles it 
              with the correct analytics provider
 parameters: 
            cPage - Celebros Page object
            bWriteCookieOnly - Optional bool parameter, 
                determines if the page should be processed or only the cookie needs to be written
*/
function PageHandle(cPage, bWriteCookieOnly)
{ 
    // define variables
    var strViewProducts;
    var strLinkProducts;
    var strFcPV='';
    var scriptToPage='';
    Page=cPage;
    var item;
    var strFcPB;
    var strFcTrack;
    var strProd;
    var stProds;
    var strFcPATC;
    var strATCProds='';
    var csSourceID;
    var csSourcePage;
    var csAlgoName;
    var acValue;
    var itemName;
   
    try
    {
        if(typeof CelebrosConectivity !='undefined')
        {
            if(CelebrosConectivity.Type!=undefined) // check that type of implementation is defined
            {
                
                // get querystring and cookie input from site, add it to cPage
                AddUserValues(cPage)
                // get values from cookie and add it to cPage
                HandleInternalCookie(cPage)
                // delete internal cookies
                DeleteCelebrosCookies(cPage);
                // write celebros cookies for Product View and ATC
                WriteCelebrosCookies(cPage);
                
                //redirect according to provider
                if(CelebrosConectivity.Type=='FC' && !bWriteCookieOnly)//Case Fireclick and the page needs to be rendered
                {
                    //check connectivity params existence for fireclick
                    if(CelebrosConectivity.TypeDefinitions.Url!=undefined && CelebrosConectivity.TypeDefinitions.Host!=undefined &&  CelebrosConectivity.DNSsuffix
                    !=undefined)
                    {
                        if(typeof fcHandlePage=="function") 
                        {
                            Ret=fcHandlePage(cPage);
                        }
        
                        if(Ret!=undefined && CreateScriptTag)
                        {
                            document.write(CreateScriptTag('',Ret));
                        }
                    }
                }
            }
        }
    }
    catch(err)
    {
    
    if (typeof CelebrosConectivity != 'undefined' && CelebrosConectivity.isDebug==true)
        {
            txt="There was an error on this page.\n\n";
            txt+="Error description: " + err.description + "\n\n";
            txt+="Click OK to continue.\n\n";
            alert(txt);
        }
    }
}
/*
 function: HandleInternalCookie
 description: recieves a celebros Page object and add to its ATC collection and Order
              products collection matching groups from cookie
 parameters: cPage - Celebros Page object
*/
function HandleInternalCookie(cPage)
{
    if( typeof CelebrosConectivity != 'undefined')
    {   
        //check PreserveGroups param
        if(CelebrosConectivity.PreserveGroups ==true)
        {
            // ATC collection
            if(cPage.AddToCartProducts)
            {
                cPage.AddToCartProducts=ADDCookieGroupsToProducts(cPage.AddToCartProducts,InternalPVCKName);
            }
            //Order Collection
            if(cPage.Order && cPage.Order.Products)
            {
                //Changed temporarily to read from PVCk cookie instead of ATCCk
                //cPage.Order.Products= ADDCookieGroupsToProducts(cPage.Order.Products,InternalATCCKName);
                cPage.Order.Products= ADDCookieGroupsToProducts(cPage.Order.Products,InternalPVCKName);
            }
        }
    }
}
/*
 function: GetProductsAssociativeArrayFromCookie
 description: check for a cooie then parsing it to Associative array
             (with product id as key) of products
 parameters: cookieName - string, name of the cookie to process
*/
function GetProductsAssociativeArrayFromCookie(cookieName)
{
var cookieContent;
var arrProducts ;//= new Array();
var arrGroups;
var arrNameValParams;
var arrKeyValue;
var productId;
var groupType;
var groupValue;

var arrProductsAssociative= null;


    //get the cookie
    cookieContent=readCookie(cookieName);
    if(cookieContent!=null)
    {
        arrProducts=cookieContent.split((PresProductDel));
        if(arrProducts.length>0)
        {
            arrProductsAssociative=new Array();
            for(var i=0;i<arrProducts.length;i++)
            {
                arrGroups=arrProducts[i].split((PresIdGroupDel));
                //must be at least with size of 2 (product ID and one group, otherwise, no need to save)
                if(arrGroups.length>1)
                {
                    productId=arrGroups[0];
                    var productElement= new Object();
                        productElement.ID=productId;
                    var groups= new Array();
                        
                    for(var j=1;j<arrGroups.length;j++)
                    {
                        arrNameValParams=arrGroups[j].split((PresValAddParamsDel));
                        //must be at least with size of 2 (Group Type and Group Value)
                        if(arrNameValParams.length>1)
                        {
                            var group= new Object();
                            groupType=arrNameValParams[0];
                            groupValue=arrNameValParams[1];
                            group.Type=groupType;
                            group.Value=groupValue;
                            //additional parameters
                            var arrParamsAssociative = new Array();
                            for(var k=2;k<arrNameValParams.length;k++)
                            {
                                arrKeyValue=arrNameValParams[k].split((PresNameValDel));
                                if(arrKeyValue.length>1)
                                {
                                    arrParamsAssociative[arrKeyValue[0]]=arrKeyValue[1];
                                }
                            }
                            group.Parameters=arrParamsAssociative;
                            groups[groupType]=group;
                            
                            
                        }
                    }
                    //add the product element to the collection
                    productElement.Groups=groups;
                    arrProductsAssociative[productId]=productElement;
                }
            }
        }
       
    }
    return arrProductsAssociative;
} 
/*
 function: ADDCookieGroupsToProducts
 description: deleting productview internal cookie (if product view is reported)
              deleting ATC internal cookie (if checkout is reported)
 parameters: cPage - Celebros Page object
*/
function ADDCookieGroupsToProducts(arrProducts,cookieName)
{
    var cookieProducts; 
    if(arrProducts!=undefined && arrProducts!=null && arrProducts.constructor==Array)
    {
        //build products associative array from cookie
        cookieProducts=GetProductsAssociativeArrayFromCookie(cookieName);
        if(cookieProducts!=null)
        {
            //loop products, look for match
            for (var i=0;i<arrProducts.length;i++)
            {
                // match id's
                if(cookieProducts[arrProducts[i].Id]!=null)
                {
                    //cookie item was found for product
                    for(var cookieGroup in cookieProducts[arrProducts[i].Id].Groups)
                    {
                        //check existance of groups array forthe product,
                        // if not exist, create one
                        if(arrProducts[i].Groups==undefined || arrProducts[i].Groups.constructor!=Array)
                        {
                            arrProducts[i].Groups=new Array();
                        }
                        //loop all groups and add not found ones
                        if(arrProducts[i].Groups[cookieGroup]==null)
                        {
                            //create group
                            var gp =new Object();
                            gp.Type=cookieProducts[arrProducts[i].Id].Groups[cookieGroup].Type;
                            gp.Value=cookieProducts[arrProducts[i].Id].Groups[cookieGroup].Value;
                            gp.AdditionalValues=cookieProducts[arrProducts[i].Id].Groups[cookieGroup].Parameters;
                            //add group
                            arrProducts[i].Groups[cookieGroup]=gp; 
                        }
                    }
                }
            }
        }
    }  
     return arrProducts;
}
/*
 function: DeleteCelebrosCookies
 description: deleting productview internal cookie 
                (originally if product view is reported,
                changed to delete only if checkout is reported)
              deleting ATC internal cookie (if checkout is reported)
 parameters: cPage - Celebros Page object
*/
function DeleteCelebrosCookies(cPage)
{
    if( typeof CelebrosConectivity != 'undefined')
    {   
        //check PreserveGroups param
        if(CelebrosConectivity.PreserveGroups ==true)
        {
            if(cPage)
            {
                //27/8/08 changed to remove only upon checkout (moved below)
                /*
                if(cPage.ProductViews!=undefined && cPage.ProductViews!=null && cPage.ProductViews.constructor==Array)
                {
                    if(cPage.ProductViews.length>0)
                    {
                        //delete cookie
                        eraseCookie(InternalPVCKName);
                    }
                }
                */
                
                if(cPage.Order!=undefined && cPage.Order!=null)
                {
                    if(cPage.Order.Products!=undefined && cPage.Order.Products.constructor==Array)
                    {
                        if(cPage.Order.Products.length>0)
                        {
                            //27/8/08 inserted: delete PV cookie here instead of every product view                            
                            //delete PV cookie
                            eraseCookie(InternalPVCKName);
                            //delete ATC cookie
                            eraseCookie(InternalATCCKName);
                        }
                    }
                }
            }
         }   
     }     
}
/*
 function: AddUserValues
 description: adding user querystring parameters and cookie variables
              for product recommendation engine ('PRE') to CelebrosPage
              Deleting user cookies at the end
 parameters: cPage - Celebros Page object
*/
function AddUserValues(cPage)
{
    var campaignName='';
    var algoName='';
    var sourcePage='';
    var sourceId='';
    var addGroup=false;
    if( typeof CelebrosConectivity != 'undefined')
    {
        if(cPage)
        {
            if(cPage.ProductViews!=undefined && cPage.ProductViews!=null && cPage.ProductViews.constructor==Array)
            {
                //add querystring params
                //check EnableQueryString
                if(CelebrosConectivity.EnableQueryString ==true)
                {
                    var qs= new Querystring();
                    //Handle Product Recommendation
                    if(qs.get(RecTypeQSName,'')=='Product')
                    {
                         addGroup=true;
                         campaignName=qs.get(CampaignQSName,'');
                         algoName=qs.get(AlgorithmQSName,'');
                         sourcePage=qs.get(PHNameQSName,'');
                         sourceId=qs.get(SourceIdQSName,'');
                    }
                }
                
                //add cookie params
                //check EnableCookie
                if(CelebrosConectivity.EnableCookie ==true)
                {
                    //Handle Product Recommendation
                    if(readCookie(RecTypeCKName)=='Product')
                    {
                        addGroup=true;
                        
                        if(algoName=='')
                        {
                            algoName=readCookie(AlgorithmCKName);
                        }
                        if(campaignName=='')
                        {
                            campaignName=readCookie(CampaignCKName);
                        }
                        if(sourcePage=='')
                        {
                            sourcePage=readCookie(PHNameCKName);
                        }
                        if(sourceId=='')
                        {
                            sourceId=readCookie(SourceIdCKName);
                        }
                        //Delete Cookies for product recommendation
                        eraseCookie(RecTypeCKName);
                        eraseCookie(CampaignCKName);
                        eraseCookie(AlgorithmCKName);
                        eraseCookie(PHNameCKName);
                        eraseCookie(SourceIdCKName);
                    }
                }
                
                //loop all products in product views collection
                if(addGroup==true)
                {
                    var grItem= new Object();
                    grItem.Type='PRE';
                    grItem.Value='true';
                    var addVals= new Array();
                    addVals['sourceId']=sourceId;
                    addVals['sourcePage']=sourcePage;
                    addVals['algoName']=algoName;
                    addVals['campaignName']=campaignName;
                    grItem.AdditionalValues=addVals;
                    
                    for (var i=0;i<cPage.ProductViews.length;i++)
                    {
                        //check if Product recommendation engine group exists,
                        //if not, create
                        if (cPage.ProductViews[i].Groups==undefined)
                        {
                            cPage.ProductViews[i].Groups= new Array();
                        }
                        if(cPage.ProductViews[i].Groups['PRE']==undefined)
                        {
                            //add 'PRE' group values
                            cPage.ProductViews[i].Groups['PRE']=grItem;
                        }
                    }
                }
            }
        }
    }
}
/*
 function: WriteCelebrosCookies
 description: creating cookies for groups of product view and ATC
 parameters: cPage - Celebros Page object
*/
function WriteCelebrosCookies(cPage)
{
    //var PVCookieValue;
    //var ATCAdditionalCookieValue;
    //var ATCCookieValue;
    if( typeof CelebrosConectivity != 'undefined')
    {
          //check PreserveGroups param
          if(CelebrosConectivity.PreserveGroups ==true)
          {
               if(cPage)
               {
                    //build Product views Cookie Value
                    if(cPage.ProductViews!=undefined && cPage.ProductViews!=null && cPage.ProductViews.constructor==Array)
                    {
                        BuildCelebrosAggregateCookie(InternalPVCKName, cPage.ProductViews);
                        /*
                        PVCookieValue=GetCelebrosProductsCookie(cPage.ProductViews); 
                        // create cookie
                        if(PVCookieValue.length>0)
                        {
                            createCookie(InternalPVCKName,PVCookieValue,1)
                        }
                        */
                    }   
                    //build ATC Cookie Value
                    if(cPage.AddToCartProducts!=undefined && cPage.AddToCartProducts!=null && cPage.AddToCartProducts.constructor==Array)
                    {
                        BuildCelebrosAggregateCookie(InternalATCCKName, cPage.AddToCartProducts);
                        /*
                        //get current cookie value
                        var currentCookie=readCookie(InternalATCCKName);
                        ATCAdditionalCookieValue=GetCelebrosProductsCookie(cPage.AddToCartProducts); 
                        if(currentCookie!=null && currentCookie.length>0)
                        {
                            ATCCookieValue=currentCookie;
                        }
                        else
                        {
                            ATCCookieValue='';
                        }
                        ATCCookieValue+=ATCAdditionalCookieValue;
                        // create cookie
                        if(ATCCookieValue.length>0)
                        {
                            createCookie(InternalATCCKName,ATCCookieValue,1)
                        }
                        */
                    } 
               }
          }
     }          
}

/*
    function: BuildCelebrosAggregateCookie
    description: Adds a product array to an new/existing cookie
    parameters: strCookieName - The name of the cookie
                arrProdArray - The array of products to add to the cookie
*/

function BuildCelebrosAggregateCookie(strCookieName, arrProdArray)
{
    //get current cookie value
    var ckCurrentCookie = readCookie(strCookieName);
    var strCookieValue = '';
    var strAdditionalCookieValue = '';
    if(ckCurrentCookie!=null && ckCurrentCookie.length>0)
    {
        strCookieValue = ckCurrentCookie;
    }
    strAdditionalCookieValue = GetCelebrosProductsCookie(arrProdArray, strCookieValue);     
    strCookieValue += strAdditionalCookieValue;
    // create cookie
    if(strCookieValue.length>0)
    {
        createCookie(strCookieName,strCookieValue,7)
    }
}

/*
 function: GetProductGroupsStringRepresentation
 description: creating string structure for a product and its groups 
              the delimiters
 parameters: cProduct - Celebros Product object
*/
function GetProductGroupsStringRepresentation(cProduct)
{
    var product='';
    var group;
    var param;
    product=cProduct.Id;
        
    //create a group on the fly if the sourceID is passed directly
    if(cProduct && cProduct.Groups==undefined && cProduct.SourceId!=undefined)
    {
        cProduct.Groups = new Array();
        var grItem= new Object();
            grItem.Type='PRE';
            grItem.Value='true';
        var addVals= new Array();
            addVals['sourceId'] = cProduct.SourceId;
            addVals['sourcePage'] = cProduct.Placeholder||'-';
            addVals['algoName'] = cProduct.algoName||'Cross Sell';
            addVals['campaignName'] = cProduct.campaignName||'-';
        grItem.AdditionalValues=addVals;
        cProduct.Groups['PRE'] = grItem;
    }
        
    if(cProduct && cProduct.Groups != undefined && cProduct.Groups.constructor==Array)
    {
        for(var key1 in cProduct.Groups)
        {
            var objParentParam = cProduct.Groups[key1];
			if(typeof objParentParam != "function")
			{
                //get group type
                group=PresIdGroupDel+objParentParam.Type;
                //get value
                group+=PresValAddParamsDel+objParentParam.Value;
                //get additional params
                if(objParentParam.AdditionalValues!=undefined && objParentParam.AdditionalValues.constructor==Array)
                {
                    //group+=PresValAddParamsDel;
                    for(var key2 in objParentParam.AdditionalValues )
                    {
                        var objChildParam = objParentParam.AdditionalValues[key2];
                        if(typeof objChildParam != "function")
                        {
                            param=key2+PresNameValDel+objChildParam;
                            group+=PresValAddParamsDel+param;
                        }
                    }
                }
                product+=group;
            }
        }
        
    }
    return product;
    
}
/*
 function: GetCelebrosProductsCookie
 description: creating cookies for product view collection
 parameters: arrProducts - Array of products
             strCurrentContents [optional] - The current value of the cookie
*/
function GetCelebrosProductsCookie(arrProductViews, strCurrentContents)
{
  var ret='';
    if(arrProductViews.constructor==Array)
    {//build Product views Cookie Value
        for (var i=0;i<arrProductViews.length;i++)
        {
            var prodTemp = arrProductViews[i];
            if((prodTemp.Groups != undefined && prodTemp.Groups.constructor==Array) || prodTemp.SourceId!=undefined)
            {
                var strTempProductString = GetProductGroupsStringRepresentation(prodTemp)+PresProductDel;
                //Check if this product already exists in the cookie
                if(strCurrentContents && strCurrentContents.length > 0)
                {
                    if(strCurrentContents.indexOf(strTempProductString) == -1)
                        ret+=strTempProductString;
                }
                else
                    ret+=strTempProductString;                
            }
        }
    }
    return ret;
}
           
   // ---- loading of fc scripts with the correct host and url(from connectivity object)   
   if(typeof CelebrosConectivity!="undefined" )
   {
       if(CelebrosConectivity.Type=='FC' && CelebrosConectivity.TypeDefinitions!=undefined && CelebrosConectivity.TypeDefinitions.Url!=undefined && CelebrosConectivity.TypeDefinitions.Host!=undefined )
       {
            function handle(){return true;}
            window.onerror=handle;
            var fc_host=CelebrosConectivity.TypeDefinitions.Host.toLowerCase();
            document.write('<scr'+'ipt '
            +'src="'+((location.protocol=='http:')?'http:':'https:')
            +CelebrosConectivity.TypeDefinitions.Url+'sc'+'ript/'+fc_host+'"></scr'+'ipt>');
            
            function fcce(){if (typeof(fcnf)!="undefined") fcnf();}
           
            var fcfn=window.onload;
            function fcco(){window.setTimeout("fcce();", 100);fcfn();}
            window.onload= null==fcfn ? fcce:fcco;
              
       }
    }
