/*THIS FILE CONTAINS JAVASCRIPT FOR GLOBAL LOGGING RECORD TYPES - EXCEPT WEB SPECIFIC LOGGING*/
/*return STRING  for whatzup5 redirect pick url
    @p - pick object with params specific to result, e.g. io, en, ep, eo, u, freeform logging, etc.
*/
function _RP(p) {
    if(WZInfo.pickRedirectPrefix != "") {
        return WZInfo.pickRedirectPrefix + pob(p);	/* declared variables concatenated by custom tag generated js  */
    } else {
        var prefix = WZInfo.pickRedirectDefault.replace("c=a&", "c=anc&");
        prefix = prefix.replace("q=&", "q=default&");

        return prefix + pob(p); //default prefix, if js exec fails
    }
}
/*return STRING for whatzup 5 static (non-redirect) pick url
    @pick object with params specific to result, e.g. io, en, ep, eo, u, freeform logging, etc.
*/
function _SP(p) {
    if(WZInfo.pickPrefix != "") {
        return WZInfo.pickPrefix + pob(p);
    } else {
        var prefix = WZInfo.pickPrefix.replace("c=a&", "c=anc&");
        prefix = prefix.replace("q=&", "q=default&");

        return prefix + pob(p); //default prefix, if js exec fails
    }
}
/*/* get pick text from link object
    @a     link object
*/
function ptxt(a)
{
    var pt="";
    if (a.innerHTML) {
        pt=a.innerHTML;
        pt=pt.replace(/<\/?[^>]+>/ig, ""); /* remove <tags> within text */
        pt=pt.replace(/&amp;/g, "&"); /* ensure pick title can be passed as param. */
    }
    return pt;
}
/* pick (with redirect of clicked link location)
    @li     link
    @p     result specific pickdata object
    @i     OPTIONAL - id of dom element from which to extract pick text, if not link (li) object
*/
function pk(li,p,i) {
    if(li && li.href) {
        if (li.wzup) return true;/*if we've already appended whatzup data to this href, don't do it again*/
        if (!p.u)p.u=li.href;/*if destination URL not already set, put current link's href as value for destination URL*/
        if (document.all && navigator.userAgent.indexOf("MSIE") != -1) {
            p.u = enc(p.u);
        }
        var a=(i)?obj(i):li;/*if specified, get pick title element by id, otherwise use clicked link element*/
        if (!p.pt){
           switch (p.en.toLowerCase()){
                case "js":
                case "is":
                    p.pt = p.en.toUpperCase() + " thumbnail";
                    break;
                default :
                    p.pt = ptxt(a);
            }
        }
        li.href = _RP(p);
        li.wzup = 1;
    }
    return true;
}
function nopk(li,p,i) {
    return true;
}
/*static (non-redirect) pick as image fetch
    @li     link object clicked from which to derive url and pick text if not already set in pick object
    @p     javascript pick object
*/
function spk(li,p,i,url)
{
    if (li && li.href && p) {
        if (!p.u) {
            if(url) {
                p.u = url;
            } else {
                p.u=li.href;/*if destination URL not already set, put current link's href as value for destination URL*/
            }
        }

        if (!p.pt) {
            var a=(i)?obj(i):li
            p.pt=ptxt(a);/*automatically read in current link text if picktext is not already set*/
        }
    }

    return (new Image()).src=_SP(p);
}
/*non-redirect clickthrough*/
/* Redirect click through
    @li link
    @id click-id
*/
function noct(li, id) {
    return true;
}
function ct(li, id) {
    if (li && li.href && id) {
        // li.oUrl holds the original url to wrap within the whatzup link.  It is set only once intially, 
        // otherwise there will be whatzup link within whatzup link when user clicks the link multiple times.
        // 
        // Side note: The old ct() got around the multiple click problem by doing whatzup replacement only once per link,
        // but that approach no longer works in AJAX.  Consider TRES-2991, where if user right click the MyStuff link (to open
        // it in new window for example), switches channel, and clicks the MyStuff link again, the MyStuff link needs to be re-evaluated
        // again to obtain the proper channel ID from the new channel page.  
        if (!li.oUrl) li.oUrl= li.href;
        
        //for IE6&7 bug(TRES-3008), when there is @ in the <a/>.innerText, ex. <a href="">x@y</a>, after href is replaced, innerText will also be replaced. Note @xy and xy@ doesn't has the same issue
        //to save the innerHTML of a tag
        var oInnerHTML = li.innerHTML;
        //replace the href attribute
        li.href = WZInfo.ctRedirectPrefix(id,li.oUrl);
        //replace back the original text, if it is changed by IE side-effect
        if(navigator.userAgent.toLowerCase().indexOf('msie') != -1 && li.innerHTML != oInnerHTML){
            li.innerHTML=oInnerHTML;
        }
    }
    return true;
}

function nosct(id,li,im) {
    if (id){
        var url="";
        /*if link or string provided, use one of those for url value,
            otherwise use random number*/
        if (li) {
            url = ((li.href) ? li.href : li);
        }
        var retVal = url;
        return retVal;
    }
}
// alert("sct FAILED "+arguments );
/* client side Non-Redirect click through
    @id click-id
    @li OPTIONAL link or destination url string
    @im true = use timeout
*/
function sct(id,li,im) {
    if (id){
        var url="";
        /*if link or string provided, use one of those for url value,
            otherwise use random number*/
        if (li) {
            url = ((li.href) ? li.href : li);
        }
        var retVal = WZInfo.ctPrefix(id,url);
        retVal = retVal + "&rnd="+Math.random().toString(); /*adding random to make sure clicks are not cached*/
        var img = new Image();
        
        if(im) {
            setTimeout(function(){ img.src = retVal; }, 100);
        } else {
            img.src = retVal;
        }

// var msg= "sct "+id +" \n "+ (li&&li.innerHTML) ;
// setTimeout( function(){alert(msg);},1110);        

        return retVal;
    }
// alert("sct FAILED "+arguments );
}

/*  Returns the WZ Redirect URL given the click ID and destination URL.
    @id click-id
    @url destination URL
*/
function wzr(id, url) {
    if (id && url) {
        var dst = WZInfo.ctRedirectPrefix(id, url);
        if (dst) {
            return dst;
        }
    }
}

/*short name for encodeURIComponent / escape function
    we choose the supported function - old browsers only support escape though that encodes less characters -
    encodeURIComponent is preferred method for UTF8
*/
function enc(s) /*DO NOT RENAME  - USED BY FRAMEWORK*/
{
    return (typeof encodeURIComponent != "undefined") ? encodeURIComponent(s) : escape(s);
}

/* return object with the specified ID in a given document object
    @param id	element id attribute string
    @param d 	containing document object - OPTIONAL (if not main document)
*/
function obj(id,d)
{
    if (! d) { d=document; }/*assume current document object if unspecified */
    var o=d.getElementById(id);
    return o; /*returns null if object doesn't exist*/
}

/*
    Build whatzup 4 or whatzup5 pick string from javascript pick object with any of the following properties
    Note:The base string provided by the framework will only include the parameters need for whatzup4/whatzup5.
    po.en=       engine code
    po.io=        item ordinal
    po.ep=      parent engine code
    po.eo=       parent engine ordinal for whatzup5 /engine ordinal for whatzup 4
    po.b=         block id
    po.bc=       block column
    po.br=        block row
    po.tp=        template id
    po.ec=       engine count (must match count in match record)
    po.pt=        pick text
    po.ex=       free form data
    po.url=      pick url  - if not same as destination url
    po.u=        destination url
*/
function pob(po) {
    po = po||{};
    return WZInfo.pickObjConversion(po);
}
/*return string if not null (including if v=0 (integer) else return empty string - this converts "undefined" and "null" values to empty string*/
function h(v){return (v!=null&&v!='undefined')?v:"";}/*have to check for explicit null and undefined, otherwise 0 integer is not seen as value */
/* for pick-logging of content-server (non-RHS) links */
function cspk(li,src,io,sp) {
/*
TODO - NOTE THIS IS A HACK FOR WHATZUP5 ONLY
FOR REAL IMPLEMENTATION - content server will have to pass in template and block and engine count or
    (preferably) this design will need to be reimplemented so that Tako somehow sets these values dynamically
    currently, there is no guarantee of accuracy for io, ec, template, block; nor is there a match for any of these engines
*/
    var en="co";
    if( src == "ahdict"){en="ah";}
    if( src == "roget"){en="ro";}
    if( src == "wiki"){en="wk";}
    if( src == "col"){en="cb";}
    if( src == "hmwh"){en="h0";}
    if( src == "hmff"){en="h1";}
/* us/uk share same engine code */
    if( src == "wordnet"){en="wn";}
    if( src == "wordnetuk"){en="wn";}
    var p={};
    p.en=en;
    p.b="sa";
    p.tp="d";
    p.ec="1";
    p.io=io;
    if(sp) {
        spk(li,p);/*non-redirect pick for certain link scenarios, e.g. audio clip*/
    } else {
        pk(li,p);/*redirect pick*/
    }
    return true;
}

 /* framed pick for Whatzup 5 (with redirect to clicked link location)
        @li     link
        @p  result-specific pick data object
        @mj	myjeeves enabled  (true/false, for myjeeves in frame)
        @io     ordinal of web result (for myjeeves in frame)
        @lang	language to be passed to the rosetta frame
        @ou     original url for the ou param in the url to be passed to the rosetta frame
    */
function fp(li,p,mj,io,lang,ou)   /*FRAMED WEB PICK for rosetta */
{
    if(li.href)
    {
        /*examine URL to see whether it goes to frame or not; if yes, add extra parameters needed by top frame;
                    if no, just do regular redirect pick */
        var fm = li.href.match(WZInfo.framedPickDomainRE);/*backslash delimit the full path so we have very tight regex match and don't munge destination url*/
        if (fm)/*//do extra frame logic for link and pick, if applicable*/
        {
            var pt,bpg,url,rdir,d,advl,advc;
            rdir = fm[1];
            url = fm[2];
            d= WZInfo.framedPickSearchDomain;
            advl = WZInfo.framedPickAdvLang;
            advc = WZInfo.framedPickAdvCtry;
            bpg = WZInfo.framedPickUrlPrefix;
            if(d) bpg+="&dm="+d +"&advl="+advl+"&advc="+advc;
                /* Web/Rosetta Top Frame params:
                    u = destination url used by center and remove links             //RENAMED from bu in kite
                    bu = back link url                                                                         //RENAMED from bpg in kite
                    s = site id     (used for logging in top frame)
                    qt = queryType (used for toggling clean/adult logic in top frame)  //RENAMED from qte in kite
                    ac=adcat of original query  (used for logging in top frame)
                    ip= ip for testing environment - OPTIONAL
                    dafs = dafs channel parameter - OPTIONAL
                */
            rdir += "u="+url+"&bu="+enc(bpg)+WZInfo.framedPickUrlPrefix2;/*//REMOVED optout, and find params */
            if(d)rdir+="&dm="+d;

            if (lang) {/* if rosetta/translation */
                rdir += "&ou="+enc(ou);  /* append original url */
            }

            if (mj=='true') {/*add extra params needed for myjeeves if we need em*/
            /*  Top frame params for MyJeeves :
                ma = abstract                                       //RENAMED from abs in kite
                mt = result title                                       //RENAMED from tit in kite
                mb = result binocular id                    //RENAMED from bin in kite
                ou = original URL (for translated link)
                REMOVED FROM KITE:  purl, Complete
            */
                var b=_mb(io);	/* result binoculars id, if any*/
                var a;
                if (lang) {/* if rosetta/translation */
                   pt=WZInfo.framedPickTitle+ou; 	/* use translation title */
                   a=WZInfo.framedPickAbstract+lang; 	/* use translation abstract */
                } else {
                    a=_ma(io);/* result abstract */
                }
                rdir +="&ma="+enc(a)+"&mt="+enc(pt)+"&mb="+b;
            }
            p.url=(ou)?ou:li.href;/*store original result url (translated or regular) in pick object because we're altering it for frame*/
            p.u=rdir;/*overwrite destination url with frame url*/
        }
        pk(li,p);    /*do redirect pick*/
    }
    return true;
}

// logs clicks for all A elements and elements with name="ask_clicklog" with defined ask_clicklogid attribute
// by setting the mousedown event handler
//             --- insertion:
//             <A ask_clicklogid="43966"  .../>
//             <span ask_clicklogid="43966" name="ask_clicklog" .../>
//
//             --- dinamycaly generated elements:
//             var el=...; ask.util.Events.addListener(el,"mousedown", function(){sct(44001,this);} );
function InitClickLog()
{
    var eh = function(){ return sct(this.getAttribute("ask_clicklogid"),this); }
    var arr = document.getElementsByTagName("A");
    for( var i=arr.length-1;i>=0;i-- )
    {
        var lid = arr[i].getAttribute("ask_clicklogid");
        if( lid )
            ask.util.Events.addListener(arr[i],"mousedown", eh );
    }
    arr = document.getElementsByName("ask_clicklog");
    for( var i=arr.length-1;i>=0;i-- )
    {
        var lid = arr[i].getAttribute("ask_clicklogid");
        if( lid )
            ask.util.Events.addListener(arr[i],"mousedown", eh );
    }
}

// ask.util.Events.addListener( window,"load",function(){ setTimeout( InitClickLog, 1000 ); } );
