/*
    SMILE Phase 2 Javascript functions to enable SMILE content delivery 
    FROM the SMILE backend TO the publishing web pages that embed this SMILE content.
*/
var smile2Http = (document.location.href.indexOf('https://')==0)?"https://":"http://";
var smile2Base = smile2Http+"c2r-srvcs.sun.com/smile/";
var smile2Config = 0x0; /* 0x1 = dont show, 0x2 = show border */

// Each E9 component content is html string
var constE9 = "E9";
var countE9 = 0;
var currIndexE9 = 0;
var offerE9Array = new Array();
// Each CARoussel component content is html string
var constCAR = "CAR";
var countCAR = 0;
var currIndexCAR = 0;
var offerCARArray = new Array();
var offerCARGlobalDescription = "";
var offerCARAllRecsLink = "";
var offerCARDefaultState = "";
var offerCAROnlineEvalStr = "";
var offerCARCurrentPanel = 1;
// Each HISTory component content is html string
var constHIST = "HIST";
var countHIST = 0;
var currIndexHIST = 0;
var offerHISTArray = new Array();
// Each EAST component content is html string
var constEAST = "EAST";
var countEAST = 0;
var currIndexEAST = 0;
var offerEASTArray = new Array();
// Each A1 component content is a string array of recommendations
var constA1 = "A1";
var countA1 = 0;
var currIndexA1 = 0;
var offerA1Array = new Array();
// Each all RECommendationS component content is a string array of recommendations
var constRECS = "RECS";
var countRECS = 0;
var currIndexRECS = 0;
var offerRECSArray = new Array();

var vis = encodeURIComponent(smile2ReadCookie("s_vi"));
var url = encodeURIComponent(document.URL);

// next 2 functions implement CARousel A2 injection
function publishSMILECarrousel()
{
    if ((offerCARArray[currIndexCAR] != null) && (offerCARArray[currIndexCAR] != ""))
    {
        if (offerCARArray[currIndexCAR][3])
        {
            publishSMILECarrousel_internal(offerCARArray[currIndexCAR++]);
        }
    }
}

function publishSMILECarrousel_internal(offerCAR)
{
  // append the CAR default open link to <body> element at this earliest timepoint
  appendCARDefOpenLink();

  reg.setup("div.a2w0", function()
  {
	var rwMeta = "";			
	var metas = gebtn('meta');
	for (var a=0;a<metas.length;a++) 
    {
		if (""+metas[a].name.toLowerCase()=='showsmilewidget')
        {
			rwMeta = ""+metas[a].content.toLowerCase(); // values are open, hide or no
		}
	}
	var rwCookie = "";
	var cookieVal = getSunSessionCookie('smileWidgetState');
	if (cookieVal)
	{
        if (cookieVal == 'hide')
        {
            rwCookie = "hide";
	    }
        else if (cookieVal == 'open')
        {
            rwCookie = "open";
	    }
        else
	    {
	        rwCookie = "open";
        }
    }
    else
	{
	   rwCookie = "open";
	}

    var rwFinal = "no";
    //alert('rwMeta:'+ rwMeta + ': rwCookie:' + rwCookie + ': offerCARDefaultState:' + offerCARDefaultState);
    if ((rwMeta == "") || (rwMeta == "no"))
    {
        rwFinal = "no";
    }
    else if (rwMeta == "hide")
    {
        rwFinal = "hide";   
    }    
    else if (rwMeta == "open")
    {
        if ((rwCookie != "open") || (offerCARDefaultState.toLowerCase() != "open"))
        {
            rwFinal = "hide";
        }
        else
        {
            rwFinal = "open";
        }
    }
    	
	if(rwFinal != "no")
    {
      this.appendChild(elem('div#recWidget',{},[
	    elem('a.rwTgl',{'href':offerCARAllRecsLink,'id':'car_impr'},[
        elem('img',{'src':smile2Http+'www.sun.com/im/a.gif','alt':'', 'width':'1','height':'1'},[]),
		elem('span',{},['Recommendations for You']),
		elem('em',{},['Close Recommendations'])
		])
	  ]));
      	
		if (rwFinal == "open"){
			setTimeout(function(){addRecWidget();},1600); // 1600 = 1.6 seconds, which is the delay a
		}
	
		reg.click("div#recWidget a.rwTgl,div#recWidget a.rwClose", function(){
            var carActionFlag;
			if(this.parentNode.id == "recWidget" && !hasClassName(this.parentNode,'hasWidget')){
				carActionFlag = "open";
                addRecWidget();
				var wdate = new Date();
				wdate.setTime(wdate.getTime() + 1 * 24 * 60 * 60 * 1000); // <-- 1 = day(s) of cookie length
				setSunSessionCookie("smileWidgetState", "open");
				var recWdgt = document.getElementById('recWidget');
				var carImpr = document.getElementById('car_impr');
                recWdgt.removeChild(carImpr);				
                recWdgt.appendChild(elem('a.rwTgl',{'href':offerCARAllRecsLink+'?intcmp=CarouselOpen','id':'car_impr'},[elem('img',{'src':smile2Http+'www.sun.com/im/a.gif','alt':'', 'width':'1','height':'1'},[]),elem('em',{},['Close Recommendations'])]));
                s_linkType='o';
                s_linkName='SMILE Carousel Open';
                s_linkTrackVars='events,products,eVar3,eVar9,eVar12';
                s_linkTrackEvents='event33';
                s_events='event33';
                s_products=';CarouselOpenByUser;;;event33=1';
                s_eVar3=location.hostname;
                s_eVar9=s_pageName;
                s_eVar12=s_channel;
                s_lnk=s_co(true);
                s_gs(s_account);
			}else if(hasClassName(gebi('recWidget'),'showWidget')){
                carActionFlag = "close";
				removeClassName(gebi('recWidget'),'showWidget');
				var wdate = new Date();
				wdate.setTime(wdate.getTime() + 1 * 24 * 60 * 60 * 1000); // <-- 1 = day(s) of cookie length
				setSunSessionCookie("smileWidgetState", "hide");
				var recWdgt = document.getElementById('recWidget');
				var carImpr = document.getElementById('car_impr');
                recWdgt.removeChild(carImpr);				
                recWdgt.appendChild(elem('a.rwTgl',{'href':offerCARAllRecsLink,'id':'car_impr'},[elem('img',{'src':smile2Http+'www.sun.com/im/a.gif','alt':'', 'width':'1','height':'1'},[]),elem('span',{},['Recommendations for You'])]));
				var carDefOpenImpr = document.getElementById('car_def_open_impr');
                if (carDefOpenImpr)
                    document.getElementsByTagName('body')[0].removeChild(carDefOpenImpr);				
			}else{
				carActionFlag = "open";
                setopacity(gebi('recWidget').getElementsByTagName('div')[0],0);
				addClassName(gebi('recWidget'),'showWidget');
				sfadein(gebi('recWidget').getElementsByTagName('div')[0],.1);
				var wdate = new Date();
				wdate.setTime(wdate.getTime() + 1 * 24 * 60 * 60 * 1000); // <-- 1 = day(s) of cookie length
				setSunSessionCookie("smileWidgetState", "open");
				var recWdgt = document.getElementById('recWidget');
				var carImpr = document.getElementById('car_impr');
                recWdgt.removeChild(carImpr);				
                recWdgt.appendChild(elem('a.rwTgl',{'href':offerCARAllRecsLink+'?intcmp=CarouselOpen','id':'car_impr'},[elem('img',{'src':smile2Http+'www.sun.com/im/a.gif','alt':'', 'width':'1','height':'1'},[]),elem('em',{},['Close Recommendations'])]));
                s_linkType='o';
                s_linkName='SMILE Carousel Open';
                s_linkTrackVars='events,products,eVar3,eVar9,eVar12';
                s_linkTrackEvents='event33';
                s_events='event33';
                s_products=';CarouselOpenByUser;;;event33=1';
                s_eVar3=location.hostname;
                s_eVar9=s_pageName;
                s_eVar12=s_channel;
                s_lnk=s_co(true);
                s_gs(s_account);
			}
            var scr = document.createElement("script");
            var time = (new Date()).getTime();
            scr.setAttribute("type", "text/javascript");
            scr.setAttribute("src", smile2Base+"TrackServlet"+"?noCacheIE="+time+"&src="+url+"&vis="+vis+"&oev="+encodeURIComponent((offerCAROnlineEvalStr)?offerCAROnlineEvalStr:"TestCarousel")+"&carActionFlag="+encodeURIComponent(carActionFlag));
            document.getElementById("recWidget").appendChild(scr);
            document.getElementById("recWidget").removeChild(scr);
            return false;
		});
	}

	function addRecWidget(){
		var rD = gebi('recWidget');
		if(!rD.haswg){
			rD.haswg = true;
			var recItems = [];
			var selectorUL = elem('ul.rwSlctr',{},[]);
			selectorUL.appendChild(elem('li',{},[elem('a.rwOnP1',{'href':'#panel-1'},[])]));
			reg.click("a.rwOnP1", function(){
            offerCARCurrentPanel = 1;
            var scr = document.createElement("script");
            var time = (new Date()).getTime();
            scr.setAttribute("type", "text/javascript");
            scr.setAttribute("src", smile2Base+"TrackServlet"+"?noCacheIE="+time+"&src="+url+"&vis="+vis+"&oev="+encodeURIComponent((offerCAROnlineEvalStr)?offerCAROnlineEvalStr:"TestCarousel")+"&carActionFlag="+encodeURIComponent("panel-1"));
            document.getElementById("recWidget").appendChild(scr);
            document.getElementById("recWidget").removeChild(scr);
            return false;});
			var setnum = 1;
			var n = 0;
			for (var i=0;i<offerCAR.length;i++){
                for (var j=0; j<offerCAR[i].length; j++)
                {
                    if (offerCAR[i][j] == 'null'){
                        offerCAR[i][j] = '';
                    }
                }
				n++;
				if(n > 3){
					setnum++;
					selectorUL.appendChild(elem('li',{},[elem('a.rwOnP'+setnum,{'href':'#panel-'+setnum},[])]));
                    reg.click("a.rwOnP"+setnum, function(){
                    offerCARCurrentPanel = setnum;
                    var scr = document.createElement("script");
                    var time = (new Date()).getTime();
                    scr.setAttribute("type", "text/javascript");
                    scr.setAttribute("src", smile2Base+"TrackServlet"+"?noCacheIE="+time+"&src="+url+"&vis="+vis+"&oev="+encodeURIComponent((offerCAROnlineEvalStr)?offerCAROnlineEvalStr:"TestCarousel")+"&carActionFlag="+encodeURIComponent("panel-"+setnum));
                    document.getElementById("recWidget").appendChild(scr);
                    document.getElementById("recWidget").removeChild(scr);
                    return false;});
					n = 1;
				}
	            var oev = (offerCAR[i][4]!='')?offerCAR[i][4]:offerCAR[i][0];
	            if (offerCAR[i][2] == '')
                    offerCAR[i][2] = smile2Http+'www.sun.com/im/a.gif';
				var alink =elem('a',{'href':smile2Base+"TrackServlet?src="+url+"&vis="+vis+"&oev="+encodeURIComponent(oev)+"&redirectUrl="+offerCAR[i][0],'rel':'no_impression'},[elem('img',{'src':offerCAR[i][2],'alt':''},[])]);
                alink.innerHTML = alink.innerHTML+offerCAR[i][1].substr(0,50);
				recItems[setnum+'-'+n] = [offerCAR[i][3].substr(0,150),elem('li.rwItem rwps'+n,{'id':'rw'+setnum+'-'+n},[alink])];
			}
			var rC = elem('div.recWdgt',{},[
				elem('p#rwBlurb',{},[]),
				elem('a.rwBack',{'href':'#previous'},['View Previous']),
				elem('ul#rwCrsl',{'class':'rwX'+setnum},[]),
				elem('a.rwFrwd',{'href':'#next'},['View Next']),
				elem('a.rwMore',{'href':offerCARAllRecsLink},['See All']),
				selectorUL
			]);
			rD.appendChild(rC)
			gebi('rwBlurb').innerHTML = offerCARGlobalDescription;
			setopacity(rC,0);
			addClassName(rD,'hasWidget rwP1 showWidget')
			sfadein(rC,.15);
			setTimeout(function(){showRecSet(1);},200);
		
			function showRecSet(theSet,incr){
				var mx = gebi('rwCrsl').className.split('rwX')[1].split(' ')[0] * 1;
				var cr = gebi('recWidget').className.split('rwP')[1].split(' ')[0] * 1;
				if(incr){
					theSet = cr + incr;
					if(theSet > mx){
						theSet = 1;
					}else if(theSet < 1){
						theSet = mx;
					}
				}
				while(document.getElementById('rwCrsl').getElementsByTagName('li')[0]){
					document.getElementById('rwCrsl').getElementsByTagName('li')[0].parentNode.removeChild(document.getElementById('rwCrsl').getElementsByTagName('li')[0]);
				}
				var n = 1;
				while(recItems[theSet+'-'+n]){
					gebi('rwCrsl').appendChild(recItems[theSet+'-'+n][1]);
					setopacity(recItems[theSet+'-'+n][1],0);
					sfadein(recItems[theSet+'-'+n][1],.025);
					n++
				}
				gebi('recWidget').className = "hasWidget showWidget rwP"+theSet;
			}
		
			//reg events
			reg.click("ul.rwSlctr li a", function(){showRecSet(this.className.split('rwOnP')[1]);return false;});
			reg.click("a.rwFrwd", function(){showRecSet(0,1);
            if (offerCARCurrentPanel == setnum)
                offerCARCurrentPanel = 1;
            else
                offerCARCurrentPanel = offerCARCurrentPanel+1;
            var scr = document.createElement("script");
            var time = (new Date()).getTime();
            scr.setAttribute("type", "text/javascript");
            scr.setAttribute("src", smile2Base+"TrackServlet"+"?noCacheIE="+time+"&src="+url+"&vis="+vis+"&oev="+encodeURIComponent((offerCAROnlineEvalStr)?offerCAROnlineEvalStr:"TestCarousel")+"&carActionFlag="+encodeURIComponent("next-"+offerCARCurrentPanel));
            document.getElementById("recWidget").appendChild(scr);
            document.getElementById("recWidget").removeChild(scr);
            return false;});
			reg.click("a.rwBack", function(){showRecSet(0,-1);
            if (offerCARCurrentPanel == 1)
                offerCARCurrentPanel = setnum;
            else
                offerCARCurrentPanel = offerCARCurrentPanel-1;
            var scr = document.createElement("script");
            var time = (new Date()).getTime();
            scr.setAttribute("type", "text/javascript");
            scr.setAttribute("src", smile2Base+"TrackServlet"+"?noCacheIE="+time+"&src="+url+"&vis="+vis+"&oev="+encodeURIComponent((offerCAROnlineEvalStr)?offerCAROnlineEvalStr:"TestCarousel")+"&carActionFlag="+encodeURIComponent("previous-"+offerCARCurrentPanel));
            document.getElementById("recWidget").appendChild(scr);
            document.getElementById("recWidget").removeChild(scr);
            return false;});
			reg.hover("li.rwItem",function(){
				if(!gebi('rwBlurb').orig){ gebi('rwBlurb').orig = gebi('rwBlurb').innerHTML;}
				gebi('rwBlurb').innerHTML = recItems[this.id.split('rw')[1]][0];
				addClassName(gebi('rwBlurb'),'rwDesc');
			},function(){
				gebi('rwBlurb').innerHTML = gebi('rwBlurb').orig;
				removeClassName(gebi('rwBlurb'),'rwDesc');
			});
		}
	}
 });

}

function appendCARDefOpenLink()
{
	var rwMeta = "";			
	var metas = gebtn('meta');
	for (var a=0;a<metas.length;a++) 
    {
		if (""+metas[a].name.toLowerCase()=='showsmilewidget')
        {
			rwMeta = ""+metas[a].content.toLowerCase(); // values are open, hide or no
		}
	}
	var rwCookie = "";
	var cookieVal = getSunSessionCookie('smileWidgetState');
	if (cookieVal)
	{
        if (cookieVal == 'hide')
        {
            rwCookie = "hide";
	    }
        else if (cookieVal == 'open')
        {
            rwCookie = "open";
	    }
        else
	    {
	        rwCookie = "open";
        }
    }
    else
	{
	   rwCookie = "open";
	}

    var rwFinal = "no";
    //alert('rwMeta:'+ rwMeta + ': rwCookie:' + rwCookie + ': offerCARDefaultState:' + offerCARDefaultState);
    if ((rwMeta == "") || (rwMeta == "no"))
    {
        rwFinal = "no";
    }
    else if (rwMeta == "hide")
    {
        rwFinal = "hide";   
    }    
    else if (rwMeta == "open")
    {
        if ((rwCookie != "open") || (offerCARDefaultState.toLowerCase() != "open"))
        {
            rwFinal = "hide";
        }
        else
        {
            rwFinal = "open";
        }
    }

    if (rwFinal == "open"){
        document.write('<a id="car_def_open_impr" href="http://www.sun.com/recommendations/all.jsp?intcmp=CarouselOpen" style="visibility:hidden;position:absolute"></a>');
    }
}

// next 2 functions implement A1 injection
function publishSMILEA1()
{
    if ((offerA1Array[currIndexA1] != null) && (offerA1Array[currIndexA1] != ""))
    {
        publishSMILEA1_internal(offerA1Array[currIndexA1++]);
    }
}

function publishSMILEA1_internal(offerA1)
{
    a1['Smile'] = "<ul class='bluearrows'>";
    for (i=0; i<offerA1.length; i++)
    {
        for (var j=0; j<offerA1[i].length; j++)
        {
            if (offerA1[i][j] == 'null'){
                offerA1[i][j] = '';
            }
        }

        var oev = (offerA1[i][2]!='')?offerA1[i][2]:offerA1[i][0];
        a1['Smile'] = a1['Smile'] + 
        "<li><a href='"+smile2Base+"TrackServlet?src="+url+"&vis="+vis+"&oev="+encodeURIComponent(oev)+"&redirectUrl="+offerA1[i][0]+"'>" + offerA1[i][1] + "<\/a><\/li>";
    }
    a1['Smile'] = a1['Smile'] + "<li><a href='" + smile2Base + "smileAllRecsTest.html'><strong>All Recommendations</strong><\/a><\/li><\/ul>";

    reg.setup("div.a1r2 span.toolbarlinks",function(){
	   var a = elem('a',{'href':smile2Base+'smileAllRecsTest.html'},'Smile');
	   this.insertBefore(a,this.getElementsByTagName('a')[0]);
	   this.removeChild(this.getElementsByTagName('a')[1]);
	   reg.rerun(this);
    });
}

// Next 2 functions implement all recommendations functionality
function loadSMILEAllRecommendations()
{
    if ((offerRECSArray[currIndexRECS] != null) && (offerRECSArray[currIndexRECS] != ""))
    {
        loadSMILEAllRecommendations_internal(offerRECSArray[currIndexRECS++]);
    }
    else
    {
        document.write("As a new visitor to our site, no personalized recommendations are currently available. The more you browse sun.com, the more recommendations we can provide.");
    }           
}

function loadSMILEAllRecommendations_internal(offerRECS)
{
	// array of html bits
	var htmlcode = [
		'<!-- BEGIN HB1 COMPONENT V.0 -->\
		<div class="hb1 hb1v0 nobg allrec">\
		<div class="hb1w1">\
		<ul>\
		<li class="hb1selected"><a href="#all">All<\/a><\/li>\
		',
		
		'<\/ul>\
		<\/div>\
		<div class="hb1w2" style="clear:both">\
		',
		
		'<!-- BEGIN HB1 COMPONENT V.4 -->\
		<div class="hb1 hb1v4 hb1panel',
		
		'<!-- BEGIN G15 COMPONENT V.0 -->\
		<div class="g15">\
		<div class="g15v0">\
		<table border="0" cellpadding="0" cellspacing="1" width="100%" class="vatop">\
		',
		
		'<\/table><\/div><\/div>\
		<!-- END G15 COMPONENT V.0 -->\
		<\/div>\
		<!-- END HB1 COMPONENT V.4 -->\
		',
		
		'<\/div>\
		<\/div>\
		<!-- END HB1 COMPONENT V.0 -->\
		'
	];
	
	// function to make data tables
	function theRows(theId){
		var s = (theId == 'all') ? ' hb1selectedpanel' : '';
		var rel_impression = (theId == 'all') ? '' : 'rel="no_impression"';
		writeIt = writeIt + htmlcode[2] + s +'" id="'+theId+'">'+htmlcode[3];
		for (var i=0;i<offerRECS.length;i++){
			if( ((offerRECS[i][3] != '') && (offerRECS[i][3].toLowerCase().normalize('-') == theId)) || theId == 'all'){
				var theImg = (offerRECS[i][2] != "") ? '<a href="'+smile2Base+'TrackServlet?src='+url+'&vis='+vis+'&oev='+encodeURIComponent(oev)+'&redirectUrl='+offerRECS[i][0]+'" rel="no_impression"><img src="'+offerRECS[i][2]+'" alt="'+offerRECS[i][1].substr(0,50)+'"><\/a>' : '<img src="'+smile2Http+'www.sun.com/im/a.gif" alt="" width="100" height="80">';
				var isNew = (offerRECS[i][6].toLowerCase().charAt(0) == 'y') ? ' <span class="new">New!<\/span>' : '';
				var eo = (eo && eo == 'odd') ? 'even' : 'odd';
                if (offerRECS[i][3] != ''){
				    var thiscat = (theId == 'all') ? '<p class="small"><strong>Category:<\/strong> <a href="#'+offerRECS[i][3].toLowerCase().normalize('-')+'" class="hb1trigger">'+offerRECS[i][3]+'<\/a><\/p>' : '';
                }
                else{
				    var thiscat = '';
                }
                var oev = (offerRECS[i][7]!='')?offerRECS[i][7]:offerRECS[i][0];
				var icon = '';
                if(offerRECS[i][4] != ''){
                    icon = 'class="iconleft" style="background-image:url('+offerRECS[i][4]+');background-repeat: no-repeat"';
                }
				writeIt = writeIt + '<tr class="'+eo+'"><td>'+theImg+'\
                <h5><a href="'+smile2Base+'TrackServlet?src='+url+'&vis='+vis+'&oev='+encodeURIComponent(oev)+'&redirectUrl='+offerRECS[i][0]+'" '+icon+' '+rel_impression+'>'+offerRECS[i][1].substr(0,50)+'<\/a>'+isNew+'<\/h5><p>'+offerRECS[i][5].substr(0,150)+'<\/p>'+thiscat+'\
				<\/td><\/tr>';
			}
		}
		writeIt = writeIt + htmlcode[4];
	}
	// write out all recommendations widget
	var cats = {};
	var	writeIt = htmlcode[0];
	for (var i=0;i<offerRECS.length;i++){
        for (var j=0; j<offerRECS[i].length; j++){
            if (offerRECS[i][j] == 'null'){
                offerRECS[i][j] = '';
            }
        }
        if (offerRECS[i][3] != ''){
		  cats[offerRECS[i][3]] = offerRECS[i][3].toLowerCase().normalize('-');
        }
	}
	for (var c in cats){
		writeIt = writeIt + '<li><a href="#'+cats[c]+'">'+c+'<\/a><\/li>';
	}
	writeIt = writeIt + htmlcode[1];
	theRows('all');
	for (var c in cats){
		theRows(cats[c]);
	}
	writeIt = writeIt + htmlcode[5];
    document.write(writeIt);
}

// This function is called, after calling reportSMILELayout(), to display the HTML offer content returned for the passed in layout 
// types(components) such as A1, RECS, HIST, E9, EAST or CAR. Only one layout type can be passed in at a time.
// Example: if reportSMILELayout('E9,E9') is called then <i>two</i> E9 offers are available. For the first showSMILEElement('E9') call // the first E9 offer is displayed and second call displays the second E9 offer. If showSMILEElement('E9') is called again then no offer 
// is available to be displayed and so nothing happens for this call. 
function showSMILEElement(layout, zone) 
{
    if ((layout != undefined) && (layout != "null") && (layout != ""))
    {
        if (layout.toUpperCase() == constE9)
        {
            if ((offerE9Array[currIndexE9] != null) && (offerE9Array[currIndexE9] != ""))
            {
                document.write(offerE9Array[currIndexE9++]);
            }
            else
            {
                if ((zone != undefined) && (zone != "") && (zone != "null"))
                {
                    smile2Offer(zone);   
                }
            }
        }        
        else if ((layout.toUpperCase() == constEAST) && (offerEASTArray[currIndexEAST] != null) && (offerEASTArray[currIndexEAST] != ""))
        {
            document.write(offerEASTArray[currIndexEAST++]);
        }        
        else if ((layout.toUpperCase() == constHIST) && (offerHISTArray[currIndexHIST] != null) && (offerHISTArray[currIndexHIST] != ""))
        {
            document.write(offerHISTArray[currIndexHIST++]);
        }        

    }
}

// This function is called if E9 does not render a SMILE ad. In that case abck up zone is used to rnder ad-server ad.
function smile2Offer(zone) 
{
    var offer = "";
    var exclude = "";
    var hlite = "";

    if (!document.phpAds_used) document.phpAds_used = ',';

    offer = "zone:" + zone;
    exclude = document.phpAds_used;
    hlite = "#992222";
    
    phpAds_random = new String (Math.random()); phpAds_random = phpAds_random.substring(2,11);

    if ((smile2Config & 0x1) != 0x1) {
        if ((smile2Config & 0x2) == 0x2) {
            document.write("<" + "div style=\"border: 2px solid " + hlite + "\">");
        }
        document.write("<" + "script language='JavaScript' type='text/javascript' src='");
        document.write(smile2Http+"ads.sun.com/ads/adjs.php?n=" + phpAds_random);
        document.write("&what=" + offer);
        document.write("&block=1&blockcampaign=1");
        document.write("&exclude=" + exclude);
        if (document.referrer)
            document.write ("&referer=" + escape(document.referrer));
        document.write("'><" + "/script>");
        if ((smile2Config & 0x2) == 0x2) {
            document.write("<" + "/div>");
        }
    } else {
        document.write("<" + "!-- offer = " + offer + "--" + ">");
    }
}

// This function is called to fetch offers related data for all passed in layout types(components) such as A1, RECS, HIST, E9, EAST and 
// CAR. The layout types are passed in delimited by "," and more than one instance of the same layout type may exist e.g. 
// "A1,CAR,E9,A1,E9".
function reportSMILELayout(layout) 
{
    if ((layout != undefined) && (layout != "null") && (layout != ""))
    {
   	    var rwMeta = "";			
        var metas = document.all ?
                    document.all.tags('META') :
                    document.getElementsByTagName ?
                    document.getElementsByTagName('META') : new Array();
    	for (var a=0;a<metas.length;a++) 
        {
		  if (""+metas[a].name.toLowerCase()=='showsmilewidget')
          {
			rwMeta = ""+metas[a].content.toLowerCase(); // values are open, hide or no
		  }
        }
   	    var rwCookie = "";
	    var cookieVal = getSunSessionCookie('smileWidgetState');
        if (cookieVal)
	    {
            if (cookieVal == 'hide')
            {
                rwCookie = "hide";
	        }
            else if (cookieVal == 'open')
            {
                rwCookie = "open";
	        }
            else
	        {
	           rwCookie = "open";
            }
       }
       else
	   {
	       rwCookie = "open";
	   }

       var rwFinal = "no";
       if ((rwMeta == "") || (rwMeta == "no"))
       {
            rwFinal = "no";
       }
       else if (rwMeta == "hide")
       {
            rwFinal = "hide";   
       }    
       else if (rwMeta == "open")
       {
            if (rwCookie != "open")
            {
                rwFinal = "hide";
            }
            else
            {
                rwFinal = "open";
            }
       }
        
        var layoutArr = layout.split(",");
        var modLayout = "";
	    for (var i=0;i<layoutArr.length;i++) 
        {
		  if (layoutArr[i].toUpperCase() == constCAR)
          {
			if (rwFinal != "no") // no need to include CAR if it is not going to be available
			{
			     modLayout = modLayout + layoutArr[i] + ",";
			}
		  }
		  else
		  {
            modLayout = modLayout + layoutArr[i] + ",";
          }
        }
   	    if (modLayout.length > 0)
   	    {
   	        modLayout = modLayout.substr(0, modLayout.length-1);
   	    }
   	    
        var vis = encodeURIComponent(smile2ReadCookie("s_vi"));
        var url = encodeURIComponent(document.URL);
        //alert ("vis:" + vis + ": url:" + url + ": carFlag:" + rwFinal + ": layout:" + modLayout);
        if ((url != "null") && (url != "") && (modLayout != ""))
        {
            // Below is a format of the server request call and an explanation of parameters:
            // action: 0 = reportLayout(), 1=pageVisit(), 2=requestSMILEOffer()
            // src: source URL
            // vis: visitor cookie
            // cmp: pipe delimited list of layout types(components)
            var req = smile2Base + "OfferServlet" + "?" + "action=0" + "&src=" + url + "&vis=" + vis + "&carFlag=" + rwFinal + "&referer=" + escape(document.referrer) + "&cmp=" + encodeURIComponent(modLayout.replace(/,/g,"|"));
            document.write("<" + "script language='JavaScript' type='text/javascript'");
            document.write(" src='" + req + "'>" + "<" + "/script>");
        }
    }
}

function smile2ReadCookie(name) 
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) 
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

// The parsing function to retrieve the offer details for each individual offer type and populate the offer arrays.
function parseServerRecommendationData(unparsedData)
{
    resetArrays();
    var offerList = iterateServerData(unparsedData, "||||", false);
    var offerAttributeList = new Array();
    for(var offer2Count=0; offer2Count<offerList.length; offer2Count++) 
    {
        offerAttributeList = iterateServerData(offerList[offer2Count], "|||", false);
        if (offerAttributeList.length>1)
        {
          if (offerAttributeList[0].toUpperCase() == constE9.toUpperCase())
          {
              // Each E9 component content is html string
              offerAttributeList[1] = offerAttributeList[1].replace(/\\\\/g,"\\");
              offerAttributeList[1] = offerAttributeList[1].replace(/\\\|/g,"|");
              offerE9Array[countE9++] = offerAttributeList[1];
          }
          else if (offerAttributeList[0].toUpperCase() == constCAR.toUpperCase())
          {
              // Each CARoussel component content is a string array of recommendations
              var recommendationList = iterateServerData(offerAttributeList[1], "||", false);
              var parsedRecommendationList = new Array();
              var globalCARVars = iterateServerData(recommendationList[0], "|", true);
              
              // THIS IS A CUSTOMIZED VERSION FOR DOCS ONLY
              // offerCARGlobalDescription = globalCARVars[0];
      	      offerCARGlobalDescription = "We have recommended offers for you. If you're not interested, click close."
              
              offerCARAllRecsLink = smile2Http+globalCARVars[1].substring(7);
              offerCARDefaultState = globalCARVars[2];
              offerCAROnlineEvalStr = globalCARVars[3];
              for (var recCount=1; recCount<recommendationList.length; recCount++)
              {
                parsedRecommendationList[recCount-1] = iterateServerData(recommendationList[recCount], "|", true);
              }
              offerCARArray[countCAR++] = parsedRecommendationList;
          }
          else if (offerAttributeList[0].toUpperCase() == constHIST.toUpperCase())
          {
              // Each HISTory component content is html string
              offerAttributeList[1] = offerAttributeList[1].replace(/\\\\/g,"\\");
              offerAttributeList[1] = offerAttributeList[1].replace(/\\\|/g,"|");
              offerHISTArray[countHIST++] = offerAttributeList[1];
          }
          else if (offerAttributeList[0].toUpperCase() == constEAST.toUpperCase())
          {
              // Each EAST component content is html string
              offerAttributeList[1] = offerAttributeList[1].replace(/\\\\/g,"\\");
              offerAttributeList[1] = offerAttributeList[1].replace(/\\\|/g,"|");
              offerEASTArray[countEAST++] = offerAttributeList[1];
          }
          else if (offerAttributeList[0].toUpperCase() == constA1.toUpperCase())
          {
              // Each A1 component content is a string array of recommendations
              var recommendationList = iterateServerData(offerAttributeList[1], "||", false);
              var parsedRecommendationList = new Array();
              for (var recCount=0; recCount<recommendationList.length; recCount++)
              {
                parsedRecommendationList[recCount] = iterateServerData(recommendationList[recCount], "|", true);
              }
              offerA1Array[countA1++] = parsedRecommendationList;
          }
          else if (offerAttributeList[0].toUpperCase() == constRECS.toUpperCase())
          {
              // Each RECommendationS component content is a string array of recommendations
              var recommendationList = iterateServerData(offerAttributeList[1], "||", false);
              var parsedRecommendationList = new Array();
              for (var recCount=0; recCount<recommendationList.length; recCount++)
              {
                parsedRecommendationList[recCount] = iterateServerData(recommendationList[recCount], "|", true);
              }
              offerRECSArray[countRECS++] = parsedRecommendationList;
          }
        }
    }
}

// Private function used to parse delimited strings based on delimiterStr such as "|", "||", "|||" and "||||".
// The escape character is "\". So "\\" is interpreted as "\" and "\|" is intrpreted as "|". This replacment is turned 
// on or off using replaceFlag. The inputData is any type of string data delimited by the delimiterStr. 
function iterateServerData(inputData, delimiterStr, replaceFlag)
{
        var propertyArray = new Array();
        var i = 0;
        var escapeStr = "";
        var truncStr = inputData;
        while (truncStr.indexOf(delimiterStr) != -1)
        {
            var propertySepIdx = truncStr.indexOf(delimiterStr);
            if (propertySepIdx == 0)
            {
                propertyArray[i] = "";
                if (escapeStr != "")
                {
                    propertyArray[i] = escapeStr + propertyArray[i];
                    escapeStr = "";
                }
                if (replaceFlag ==  true)
                {
                  propertyArray[i] = propertyArray[i].replace(/\\\\/g,"\\");
                  propertyArray[i] = propertyArray[i].replace(/\\\|/g,"|");
                }
                i++;
            }
            else if (propertySepIdx > 0)
            {
                if (truncStr.charAt(propertySepIdx-1) != '\\')
                {
                    propertyArray[i] = truncStr.substr(0, propertySepIdx);
                    if (escapeStr != "")
                    {
                        propertyArray[i] = escapeStr + propertyArray[i];
                        escapeStr = "";
                    }
                    if (replaceFlag ==  true)
                    {
                      propertyArray[i] = propertyArray[i].replace(/\\\\/g,"\\");
                      propertyArray[i] = propertyArray[i].replace(/\\\|/g,"|");
                    }
                    i++;
                }
                else
                {
                    escapeStr = escapeStr + truncStr.substr(0, propertySepIdx+delimiterStr.length);
                }
            }
            truncStr = truncStr.substr(propertySepIdx+delimiterStr.length);
        }
        propertyArray[i] = escapeStr + truncStr;
        if (replaceFlag ==  true)
        {
          propertyArray[i] = propertyArray[i].replace(/\\\\/g,"\\");
          propertyArray[i] = propertyArray[i].replace(/\\\|/g,"|");
        }
        return propertyArray;
}

function resetArrays()
{
    countA1 = 0;
    currIndexA1 = 0;
    offerA1Array = [];
    
    countCAR = 0;
    currIndexCAR = 0;
    offerCARArray = [];
    offerCARGlobalDescription = "";
    offerCARAllRecsLink = "";
    offerCARDefaultState = "";
    offerCAROnlineEvalStr = "";
    offerCARCurrentPanel = 1;
   
    countE9 = 0;
    currIndexE9 = 0;
    offerE9Array = [];
    
    countEAST = 0;
    currIndexEAST = 0;
    offerEASTArray = [];
    
    countHIST = 0;
    currIndexHIST = 0;
    offerHISTArray = [];
    
    countRECS = 0;
    currIndexRECS = 0;
    offerRECSArray = [];
}
