var yedda_track_prefix = 'Track_';

function yedda_track_outgoing_link(event) {    
    var element = '';
        
    if(Sys.Browser.agent == Sys.Browser.InternetExplorer) {      
        element = window.event.srcElement;        
    }
    else {        
        element = event.target;        
    }
    
    if (element) {
	    if (element.tagName.toLowerCase() != 'a') {
		    element = element.parentNode;
	    }
	    var destination = '';
	    if (typeof(element.href) != 'undefined' && element.href != null) {
	        destination = element.href;
	    }
        var classes = '';
        if (typeof(element.className) != 'undefined' && element.className != '') {
            var tempClasses = element.className.split(' ');
            if (tempClasses != null && tempClasses.length > 0) {
                for (var i = 0; i < tempClasses.length; i++) {                    
                    if (tempClasses[i].startsWith(yedda_track_prefix)) {
                        classes = classes + '|' + tempClasses[i];
                    }
                }
            }
        }
        
        Yedda.Api.Internal.Tracking.OutgoingLinksTracker.Track(window.location.href, destination, classes);        
    }
}

function yedda_add_outgoing_link_tracking(link) {       
    link.yedda_olt = true;
    $addHandler(link, 'mousedown', yedda_track_outgoing_link);    
}

function yedda_should_track(link) {
    var host = link.host.toLowerCase();
    if (host.indexOf(':') > -1) {
        host = new String(host).replace(/:\d+/, '');
    }
    
    // Always track if "Track_" exists
    if (typeof(link.className) != 'undefined' && link.className != '') {
        var tempClasses = link.className.split(' ');    
        if (tempClasses != null && tempClasses.length > 0) {
            for (var i = 0; i < tempClasses.length; i++) {                    
                if (tempClasses[i].startsWith(yedda_track_prefix)) {
                    return true;
                }
            }
        }
    }
    
    // Don't track yedda.com and localhost links
    if (host.endsWith('yedda.com') || host.startsWith('localhost')) {
        return false;
    }
    
    return true;
}

function yedda_oltrack() {                       
    var hasService = false;
    if (typeof(Yedda) != 'undefined' && typeof(Yedda.Api) != 'undefined' && typeof(Yedda.Api.Internal) != 'undefined' && typeof(Yedda.Api.Internal.Tracking) != 'undefined' && typeof(Yedda.Api.Internal.Tracking.OutgoingLinksTracker) != 'undefined') {
        hasService = true;
    }

    if (hasService) {    
        var allLinks = document.getElementsByTagName('a');
        if (allLinks && allLinks.length > 0) {
            var link;
            for (var i=0; i < allLinks.length; i++) {        
                link = allLinks[i];
                if (link.href && link.href != '') {                            
                    if (yedda_should_track(link)) {
                        if (typeof(link.yedda_olt) == 'undefined' && hasService) {                        
                            yedda_add_outgoing_link_tracking(link);                        
                        }
                        else if (link.yedda_olt == false && hasService) {                        
                            yedda_add_outgoing_link_tracking(link);                        
                        }
                    }                
                }           
            }
        }
    }
}

if (typeof(Sys) != 'undefined' && typeof(Sys.Application) != 'undefined') {
    Sys.Application.add_load(yedda_oltrack);
}
else {
    yedda_oltrack();
}
function yedda_patch_target(link) {
    var host = link.host.toLowerCase();
    if (host.indexOf(':') > -1) {
        host = new String(host).replace(/:\d+/, '');
    }
    
    // Don't track yedda.com and localhost links
    if (!host.endsWith('yedda.com') && !host.startsWith('localhost') && !link.href.startsWith("javascript:")) {        
        link.target = "_parent";
    }
}

function yedda_ts() {   
    var allLinks = document.getElementsByTagName('a');
    if (allLinks && allLinks.length > 0) {
        var link;
        for (var i=0; i < allLinks.length; i++) {        
            link = allLinks[i];
            if (link.href && link.href != '') {                            
                yedda_patch_target(link);
            }           
        }
    }
}


/* See http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/ for credits */
/* parameters:
    oElm = root element to start search from (or document)
    strTagName = tag to search for, or "*" if all tags
    oClassNames = array of class names, or a single string class name. If array is used, returns element 
    only if it matches ALL specified classes. 
   Returns: array of elements
    */
function getElementsByClassName(oElm, strTagName, oClassNames){
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var arrRegExpClassNames = new Array();
    if(typeof oClassNames == "object"){
        for(var i=0; i<oClassNames.length; i++){
            arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
        }
    }
    else{
        arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
    }
    var oElement;
    var bMatchesAll;
    for(var j=0; j<arrElements.length; j++){
        oElement = arrElements[j];
        bMatchesAll = true;
        for(var k=0; k<arrRegExpClassNames.length; k++){
            if(!arrRegExpClassNames[k].test(oElement.className)){
                bMatchesAll = false;
                break;                      
            }
        }
        if(bMatchesAll){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}

var _Yedda_registerBodyOnLoad_list = new Array();
var _Yedda_registerBodyOnLoad_oldOnLoad;
var _Yedda_registerBodyOnLoad_implementOnLoad_called = false;

function _Yedda_registerBodyOnLoad_implementOnLoad() {
    if (_Yedda_registerBodyOnLoad_implementOnLoad_called)
        return;
    _Yedda_registerBodyOnLoad_implementOnLoad_called = true;
    if (!_Yedda_registerBodyOnLoad_list)
        return;
    for (var i = 0; i < _Yedda_registerBodyOnLoad_list.length; i++) {
        eval(_Yedda_registerBodyOnLoad_list[i]);
    }
    if (_Yedda_registerBodyOnLoad_oldOnLoad)
        _Yedda_registerBodyOnLoad_oldOnLoad();
}

function Yedda_registerBodyOnLoad(methodCall) {
    
    if (!_Yedda_registerBodyOnLoad_oldOnLoad) {
        if (document.body.onload != _Yedda_registerBodyOnLoad_implementOnLoad) {
            _Yedda_registerBodyOnLoad_oldOnLoad = window.onload;
            window.onload = _Yedda_registerBodyOnLoad_implementOnLoad;
        }
    }
    _Yedda_registerBodyOnLoad_list.push(methodCall);   
}

function Yedda_Internal_HandleWebServiceTimeout(result) {
    window.alert("Oops. No response from Yedda. Why don't you try again?");
}

function Yedda_Internal_HandleWebServiceError(result) {
    window.alert("Oops. Something went wrong. Why don't you try again?");
}

/*******************
Call this as the first line of a _OnComplete handler for a web service call.
Will return true if the call was succesful. 
Otherwise, will automatically handle not-signed-in or no-permission, and return false.
*******************/
function Yedda_Internal_HandleWebServiceComplete(result) {
    if (typeof(result) == "undefined") {
        Yedda_Internal_HandleWebServiceError(null);
        return false;
    }
    if (!result) {
        Yedda_Internal_HandleWebServiceError(null);
        return false;
    }   
    if (typeof(result.serviceReturnCode) == "undefined")
        Yedda_Internal_HandleWebServiceError(null);
    switch (result.serviceReturnCode) {
        case 0: {   // success
            return true;
        }
        case 1: { // NotSignedIn
            if (typeof(Yedda_Internal_ClientSignHelper_TransferIfNotSignedIn) != "function")
                Yedda_Internal_HandleWebServiceError(result);
            Yedda_Internal_ClientSignHelper_TransferIfNotSignedIn();
            break;
        }
        case 2: { // NoPermissions
            Yedda_Internal_NoPermission();
            break;
        }
    }
    return false;
}

function Yedda_Internal_NoPermission() {
    // todo
}

var _Yedda_Internal_RegisterForPostbackProgressTrigger_list = new Array();

/***************************
Register a method to be called before calling the server, to turn on progress indicators.
Provide a string with the name of the method. 
The method must have the following signature:
function methodName(eventTargetServerId) returns array of strings
eventTargetServerId is the server id of the control that initiated the postback
Returns the list of triggers to use for turning on the progress indicators (using ProgressControl_setVisible)
*/
function Yedda_Internal_RegisterForPostbackProgressTrigger(methodName) {
    if (typeof(debug) != 'undefined') {
        if (typeof(debug.assert) != 'undefined') {
            debug.assert(_Yedda_Internal_RegisterForPostbackProgressTrigger_list != null);
        }
    }
    
    if (_Yedda_Internal_RegisterForPostbackProgressTrigger_list != null) {
        _Yedda_Internal_RegisterForPostbackProgressTrigger_list.push(methodName);
    }
}

function _Yedda_Internal_HandleBeforePostback(eventTargetServerId) {
    for (i = 0; i < _Yedda_Internal_RegisterForPostbackProgressTrigger_list.length; i++) {
        var triggers = eval(_Yedda_Internal_RegisterForPostbackProgressTrigger_list[i] + "('" + eventTargetServerId + "')");
        if (triggers) {
            if (triggers.length > 0)
                if (typeof(ProgressControl_setVisible) != "undefined") {
                    ProgressControl_setVisible(triggers, true);
                }
        }
    }
}

function _Yedda_Internal_HandleAfterPostback() {
    // Turn off all progress indicators:
    // hack #2: Setting the style.visibility does not work in the 
    // isPostBack = false event, so we'll postpone it a bit using setTimeout. 
    if (typeof(ProgressControl_setVisible) != "undefined") {
        if (ProgressControl_setVisible) {
            window.setTimeout("ProgressControl_setVisible('', false)", 1);
         }
     }
}

function _Yedda_Internal_HandleAtlasPageRequestManagerPropertyChanged(obj, e) {
    if (!e)
        return;
    if (e.get_propertyName() == "inPostBack") {
        if (obj.get_inPostBack()) {
            debug.assert(obj);
            debug.assert(obj.get_form());
            var form = $get(obj.get_form());
            debug.assert(form);
//             debug.assert(form.__EVENTTARGET);
            var eventTargetServerId = form.__EVENTTARGET.value;
            _Yedda_Internal_HandleBeforePostback(eventTargetServerId);
        } else {
            // the __EVENTTARGET is not reliable in the isPostBack = false stage, we'll have to do without it... 
            _Yedda_Internal_HandleAfterPostback();
            if (typeof(_Yadda_Internal_UnsignedHome_AfterPostback) != "undefined") 
                _Yadda_Internal_UnsignedHome_AfterPostback();
        }
    }
}

function Yedda_Internal_HandleAtlasApplicationLoad(obj, e) {
    if (Sys.WebForms.PageRequestManager)
        Sys.WebForms.PageRequestManager.propertyChanged.add(_Yedda_Internal_HandleAtlasPageRequestManagerPropertyChanged);
}

function writeNoSpamEmail(text, p1, p2) {
    if (text == "")
        text = p1 + "@" + p2;
    document.write("<a href='" + "mail" + "to:" + p1 + "@" + p2 + "'>" + text + "</a>");
}

function Yedda_RegisterDynamicScriptBlock(source) {
	var script = document.createElement('script'); 
	script.type = 'text/javascript'; 
	script.src = source; 
	document.getElementsByTagName('head')[0].appendChild(script);  
}
// source: http://4umi.com/web/javascript/array.htm
Array.prototype.indexOf=function(n){for(var i=0;i<this.length;i++){if(this[i]===n){return i;}}return -1;}
Array.prototype.lastIndexOf=function(n){var i=this.length;while(i--){if(this[i]===n){return i;}}return -1;}
Array.prototype.forEach=function(f){var i=this.length,j,l=this.length;for(i=0;i<l;i++){if((j=this[i])){f(j);}}};
Array.prototype.insert=function(i,v){if(i>=0){var a=this.slice(),b=a.splice(i);a[i]=value;return a.concat(b);}}
Array.prototype.shuffle=function(){var i=this.length,j,t;while(i--){j=Math.floor((i+1)*Math.random());t=arr[i];arr[i]=arr[j];arr[j]=t;}}
Array.prototype.unique=function(){var a=[],i;this.sort();for(i=0;i<this.length;i++){if(this[i]!==this[i+1]){a[a.length]=this[i];}}return a;}
if(typeof Array.prototype.concat==='undefined'){Array.prototype.concat=function(a){for(var i=0,b=this.copy();i<a.length;i++){b[b.length]=a[i];}return b;};}
if(typeof Array.prototype.copy==='undefined'){Array.prototype.copy=function(a){var a=[],i=this.length;while(i--){a[i]=(typeof this[i].copy!=='undefined')?this[i].copy():this[i];}return a;};}
if(typeof Array.prototype.pop==='undefined'){Array.prototype.pop=function(){var b=this[this.length-1];this.length--;return b;};}
if(typeof Array.prototype.push==='undefined'){Array.prototype.push=function(){for(var i=0,b=this.length,a=arguments;i<a.length;i++){this[b+i]=a[i];}return this.length;};}
if(typeof Array.prototype.shift==='undefined'){Array.prototype.shift=function(){for(var i=0,b=this[0];i<this.length-1;i++){this[i]=this[i+1];}this.length--;return b;};}
if(typeof Array.prototype.slice==='undefined'){Array.prototype.slice=function(a,c){var i=0,b,d=[];if(!c){c=this.length;}if(c<0){c=this.length+c;}if(a<0){a=this.length-a;}if(c<a){b=a;a=c;c=b;}for(i;i<c-a;i++){d[i]=this[a+i];}return d;};}
if(typeof Array.prototype.splice==='undefined'){Array.prototype.splice=function(a,c){var i=0,e=arguments,d=this.copy(),f=a;if(!c){c=this.length-a;}for(i;i<e.length-2;i++){this[a+i]=e[i+2];}for(a;a<this.length-c;a++){this[a+e.length-2]=d[a-c];}this.length-=c-e.length+2;return d.slice(f,f+c);};}
if(typeof Array.prototype.unshift==='undefined'){Array.prototype.unshift=function(a){this.reverse();var b=this.push(a);this.reverse();return b;};}

/*************************************************************************
  This code is from Dynamic Web Coding at dyn-web.com
  Copyright 2001-5 by Sharon Paine 
  See Terms of Use at www.dyn-web.com/bus/terms.html
  regarding conditions under which you may use this code.
  This notice must be retained in the code as is!
*************************************************************************/

/* 
    dw_scrollObj.js  version date: March 2005
    GeckoTableBugFix algorithm revised, and now excludes Safari and Konqueror.
    
    dw_scrollObj.js contains constructor and basic methods for scrolling layers.
    Use with dw_hoverscroll.js and/or dw_glidescroll.js,
    and when including scrollbars: dw_scroll-aux.js and dw_slidebar.js
*/

dw_scrollObjs = {};
dw_scrollObj.speed=100;
function dw_scrollObj(wnId,lyrId,cntId){this.id=wnId;dw_scrollObjs[this.id]=this;this.animString="dw_scrollObjs."+this.id;this.load(lyrId,cntId);};dw_scrollObj.loadLayer=function(wnId,id,cntId){if(dw_scrollObjs[wnId])dw_scrollObjs[wnId].load(id,cntId);};dw_scrollObj.prototype.load=function(lyrId,cntId){if(!document.getElementById)return;var wndo,lyr;if(this.lyrId){lyr=document.getElementById(this.lyrId);lyr.style.visibility="hidden";}lyr=document.getElementById(lyrId);wndo=document.getElementById(this.id);lyr.style.top=this.y=0;lyr.style.left=this.x=0;this.maxY=(lyr.offsetHeight-wndo.offsetHeight>0)?lyr.offsetHeight-wndo.offsetHeight:0;this.wd=cntId?document.getElementById(cntId).offsetWidth:lyr.offsetWidth;this.maxX=(this.wd-wndo.offsetWidth>0)?this.wd-wndo.offsetWidth:0;this.lyrId=lyrId;lyr.style.visibility="visible";this.on_load();this.ready=true;};dw_scrollObj.prototype.on_load=function(){};dw_scrollObj.prototype.shiftTo=function(lyr,x,y){if(!lyr.style||!dw_scrollObj.scrdy)return;lyr.style.left=(this.x=x)+"px";lyr.style.top=(this.y=y)+"px";};dw_scrollObj.GeckoTableBugFix=function(){var ua=navigator.userAgent;if(ua.indexOf("Gecko")>-1&&ua.indexOf("Firefox")==-1&&ua.indexOf("Safari")==-1&&ua.indexOf("Konqueror")==-1){dw_scrollObj.hold=[];for(var i=0;arguments[i];i++){if(dw_scrollObjs[arguments[i]]){var wndo=document.getElementById(arguments[i]);var holderId=wndo.parentNode.id;var holder=document.getElementById(holderId);document.body.appendChild(holder.removeChild(wndo));wndo.style.zIndex=1000;var pos=getPageOffsets(holder);wndo.style.left=pos.x+"px";wndo.style.top=pos.y+"px";dw_scrollObj.hold[i]=[arguments[i],holderId];}}window.addEventListener("resize",dw_scrollObj.rePositionGecko,true);}};dw_scrollObj.rePositionGecko=function(){if(dw_scrollObj.hold){for(var i=0;dw_scrollObj.hold[i];i++){var wndo=document.getElementById(dw_scrollObj.hold[i][0]);var holder=document.getElementById(dw_scrollObj.hold[i][1]);var pos=getPageOffsets(holder);wndo.style.left=pos.x+"px";wndo.style.top=pos.y+"px";}}};function getPageOffsets(el){var left=el.offsetLeft;var top=el.offsetTop;if(el.offsetParent&&el.offsetParent.clientLeft||el.offsetParent.clientTop){left+=el.offsetParent.clientLeft;top+=el.offsetParent.clientTop;}while(el=el.offsetParent){left+=el.offsetLeft;top+=el.offsetTop;}return{x:left,y:top};};eval('\x64\x77\x5f\x73\x63\x72\x6f\x6c\x6c\x4f\x62\x6a\x2e\x73\x63\x72\x64\x79\x3d\x74\x72\x75\x65\x3b');
/*************************************************************************
  This code is from Dynamic Web Coding at www.dyn-web.com
  Copyright 2001-4 by Sharon Paine 
  See Terms of Use at www.dyn-web.com/bus/terms.html
  regarding conditions under which you may use this code.
  This notice must be retained in the code as is!
*************************************************************************/

/* dw_glidescroll.js  version date: June 2004 
   glide onclick scrolling for dw_scrollObj (in dw_scrollObj.js)  */

dw_scrollObj.slideDur = 500; // duration of glide

// intermediary functions needed to prevent errors before page loaded 
dw_scrollObj.scrollBy = function(wnId, x, y, dur) {
  if ( dw_scrollObjs[wnId] ) dw_scrollObjs[wnId].glideBy(x, y, dur);
}

dw_scrollObj.scrollTo = function(wnId, x, y, dur) {
  if ( dw_scrollObjs[wnId] ) dw_scrollObjs[wnId].glideTo(x, y, dur);
}

// Resources for time-based slide algorithm: 
//  DHTML chaser tutorial at DHTML Lab - www.webreference.com/dhtml	
//  and cbe_slide.js from	www.cross-browser.com by Mike Foster
dw_scrollObj.prototype.glideBy = function(dx, dy, dur) {
  if ( !document.getElementById || this.sliding ) return;
  this.slideDur = dur || dw_scrollObj.slideDur;
  this.destX = this.destY = this.distX = this.distY = 0;
  this.lyr = document.getElementById(this.lyrId);
  this.startX = this.x; this.startY = this.y;
  if (dy < 0) this.distY = (this.startY + dy >= -this.maxY)? dy: -(this.startY  + this.maxY);
  else if (dy > 0) this.distY = (this.startY + dy <= 0)? dy: -this.startY;
  if (dx < 0) this.distX = (this.startX + dx >= -this.maxX)? dx: -(this.startX + this.maxX);
  else if (dx > 0) this.distX = (this.startX + dx <= 0)? dx: -this.startX;
  this.destX = this.startX + this.distX; this.destY = this.startY + this.distY;
  this.slideTo(this.destX, this.destY);
}

dw_scrollObj.prototype.glideTo = function(destX, destY, dur) {
  if ( !document.getElementById || this.sliding) return;
  this.slideDur = dur || dw_scrollObj.slideDur;
  this.lyr = document.getElementById(this.lyrId); 
  this.startX = this.x; this.startY = this.y;
  this.destX = -Math.max( Math.min(destX, this.maxX), 0);
  this.destY = -Math.max( Math.min(destY, this.maxY), 0);
  this.distY = this.destY - this.startY;
  this.distX =  this.destX - this.startX;
  this.slideTo(this.destX, this.destY);
}

dw_scrollObj.prototype.slideTo = function(destX, destY) {
  this.per = Math.PI/(2 * this.slideDur); this.sliding = true;
	this.slideStart = (new Date()).getTime();
	this.aniTimer = setInterval(this.animString + ".doSlide()",10);
  this.on_slide_start(this.startX, this.startY);
}

dw_scrollObj.prototype.doSlide = function() {
	var elapsed = (new Date()).getTime() - this.slideStart;
	if (elapsed < this.slideDur) {
		var x = this.startX + this.distX * Math.sin(this.per*elapsed);
		var y = this.startY + this.distY * Math.sin(this.per*elapsed);
    this.shiftTo(this.lyr, x, y); this.on_slide(x, y);
	} else {	// if time's up
    clearInterval(this.aniTimer); this.sliding = false;
		this.shiftTo(this.lyr, this.destX, this.destY);
    this.lyr = null; this.on_slide_end(this.destX, this.destY);
	}
}

dw_scrollObj.prototype.on_slide_start = function() {}
dw_scrollObj.prototype.on_slide = function() {}
dw_scrollObj.prototype.on_slide_end = function() {}
