/*--start of const--*/
var BANNER_IMAGES_BASE_URL = 'http://images.conduit-banners.com/';
var API_PATH = 'http://api.conduit.com/';
var LOG_SITE_URL = 'http://usage.conduit-banners.com/Logger/';
var LOG_ENABLED = true;
/*--end of const--*/
var bGlobalDontShowAgain = false;
var PADDING_RIGHT = 'padding-right';
var PADDING_LEFT = 'padding-left';
function GetRealBodyWidth()
{
    // screen size
    var screenWidth = screen.width;
    var screenHeight = screen.height; 

    // body size
    var scrollWidth = document.body.scrollWidth;
    var scrollHeight = document.body.scrollHeight; 

    if(screenWidth < scrollWidth) 
    { 
    scrollWidth = screenWidth; 
    }

    if(screenHeight < scrollHeight) 
    { 
    scrollHeight = screenHeight; 
    }
    return scrollWidth;
}


function CommitTopSlide() {
   	if(EBStop)
	{
		var d = document.getElementById('EBTopBanner');
		//  d.style.width= parseInt(GetRealBodyWidth());

		d.style.left = "0px";
		if (d.style.display == "none") {
		    d.style.display = "block";
		    d.style.width = "100%";

		}

        if (__top < 0) {
            __top += 3;
            d.style.top = __top+"px";
			d.style.hieght=__top+"px";
            setTimeout(CommitTopSlide, 25);
        }
	    
	}  
}


function EBPreVanishTopSlide(bDontShowAgain) 
{ 
    if (bGlobalDontShowAgain == true){bDontShowAgain=true}
    var iDays = bDontShowAgain ? DAYS_FOR_NEXT_APPEARANCE_DONT_SHOW_NOTIFICATION : DAYS_FOR_NEXT_APPEARANCE_CLOSE_BUTTON;    
    EBStop=true;
    BannersControlHelper.SetCookie("TopSliderExposed","1",iDays);   
    EBVanishTopSlide();
}


function EBDownloadToolbar() {
    setTimeout(EBPreVanishTopSlide, 5000);
}

function DelayVanish()
{
     var objCheckTopScrollDontShowAgain = document.getElementById("checkTopScrollDontShowAgain");
     
     if(objCheckTopScrollDontShowAgain != null)
     {
        bGlobalDontShowAgain = objCheckTopScrollDontShowAgain.checked;
        if(bGlobalDontShowAgain)        
            setTimeout(EBPreVanishTopSlide, 5000)
     }
}

function EBVanishTopSlide() {
    if (EBStop) {

		var d = document.getElementById('EBTopBanner');
		 d.style.left = "0px";
		 if (d.style.display == "none") {
		     d.style.display = "block";
		     d.style.width = "100%";

		 }

	        if (__top > -77) {
	            __top -= 10;
	            d.style.top = __top+"px";
				d.style.hieght=__top+"px";
	            setTimeout(EBVanishTopSlide, 10);
	        }
	    
	}    
}


function GetAlphaFilter()
{
//    var ie = (document.all) ? 1 : 0;
//    
//    if(ie)
//     return "filter:alpha(opacity=" + __opacity+")";
//    else
    //     return "-moz-opacity: " + __opacity/ 100 ;
    return "filter:alpha(opacity=" + __opacity + "); " + "-moz-opacity: " + __opacity / 100 + "; opacity: " + __opacity / 100;
}

function GetPaddingImageDirection() {
    //get the direction from accounts
    if (typeof __BannerDirection != "undefined") {
        if (__BannerDirection == 'ltr') 
            return PADDING_LEFT;
        return PADDING_RIGHT;
    }
    //get the direction from the server - fallback
    if (typeof __LocaleDirection != "undefined") {
        if (__LocaleDirection == 'ltr') 
            return PADDING_LEFT;
        return PADDING_RIGHT;

    }
    return PADDING_LEFT;

}

function GetPaddingButtonDirection() {
    //get the direction from accounts
    if (typeof __BannerDirection != "undefined") {
        if (__BannerDirection == 'ltr')
            return PADDING_RIGHT;
        return PADDING_LEFT;
    }
    //get the direction from the server - fallback
    if (typeof __LocaleDirection != "undefined") {
        if (__LocaleDirection == 'ltr')
            return PADDING_RIGHT;
        return PADDING_LEFT;

    }
    return PADDING_RIGHT;

}





//definitions - internals
var __top                 = -66;
var EBStop                = true;
var DAYS_FOR_NEXT_APPEARANCE_CLOSE_BUTTON =7;
var DAYS_FOR_NEXT_APPEARANCE_DONT_SHOW_NOTIFICATION =365;



//Images
var __bgImage;
var __ImageArrow;
var __textImage;       
var __downloadBtn;        
var __downloadBtnOver;
var __downloadBtnDown;
var __closeBtn; 
var __closeBtnOver;
var __closeBtnDown;
var __dontShowCaption;
var __imagesPath;


function InitImagesDefinitions() {
    var flag = '0';
    
    if (typeof __baseURL == 'undefiend')
        var __baseURL;    
    
     if (!__baseURL || __baseURL == 'http://www.conduit.com/') {
        __baseURL = BANNER_IMAGES_BASE_URL;
        flag = '1';
    }
    else {
        flag = '2&baseUrl=' + __baseURL;
    }
    if (__baseURL.charAt[__baseURL.length] != '/')
        __baseURL += '/';
    __imagesPath        = __baseURL +  'TopSlider/'; //CHANGED BY SURIEL
    __bgImage           = __imagesPath + "strip_" + __selectedColor + ".gif";
    __ImageArrow        = __ImageArrow || __imagesPath + "arrow_" + __selectedColor + ".gif" + '?flag=' + flag;
    __textImage         = __textImage           || __imagesPath + "text_" + __selectedColor + ".gif";
    __downloadBtn       = __downloadBtn         || __imagesPath + "dnld_" + __selectedColor + ".gif"; 
    __downloadBtnOver   = __downloadBtnOver     ||  __imagesPath + "dnld_" + __selectedColor + "_over.gif";
    __downloadBtnDown = __downloadBtnDown || __imagesPath + "dnld_" + __selectedColor + "_dn.gif";
    __closeBtn          = __closeBtn            ||  __imagesPath + "close_" + __selectedColor + ".gif"; 
    __closeBtnOver      = __closeBtnOver        ||  __imagesPath + "close_" + __selectedColor + "_over.gif";
    __closeBtnDown      = __closeBtnDown        ||  __imagesPath + "close_" + __selectedColor + "_dn.gif";
    __dontShowCaption   = __dontShowCaption     || __imagesPath + "dont_show.gif";   
}



function __TopSlide()
{

    WriteToolbarAPIRequest();
    InitImagesDefinitions();
    WriteBannerHTML();
    
    //ExecuteFlyOver only after page loads and banner
    //code is written to the document!!!

    //BannersControlHelper.AttachEvent(window, 'onload', function() { setTimeout(function() { ExecuteTopSlide(); ConduitBranding.Init(); }, 1) });
    BannersControlHelper.AttachEvent(window, 'onload', function() { ConduitBranding.Init(); setTimeout(function() { ExecuteTopSlide(); }, 1) });
    //ConduitBranding.AttachEvent(window, 'onload', function() { ConduitBranding.Init(); }); 
    //log the banner
    if (LOG_ENABLED)
        var req = new LogScriptRequest(LOG_SITE_URL + logUsage());
}

function setTopSlideWidth(hide) {
    var d = document.getElementById('EBTopBanner');
    var f = function(){d.style.width = parseInt(GetRealBodyWidth()) + 'px';};

    if (hide) {
        d.style.width = '10px';
        window.setTimeout(f, 1);
    }
    else f();
    
    
}

function ExecuteTopSlide()
{
    if(ValidateShow())
    {
        setTopSlideWidth(false);

//        BannersControlHelper.AttachEvent(window, 'onresize',
//        function() { setTopSlideWidth(true) });
        setTimeout(CommitTopSlide, 400);
        
    } 
}



function ValidateShow()
{
    if (typeof __preview == "string")
        return true;
       
    //if the ctid var was defined, use the TPI to check if toolbar
    //is already installed in order to disable the banner in such case.


    if (typeof __ctid == "string") {

        var oToolbar = new TPI.Toolbar(__ctid.toUpperCase());
        var oReturn = oToolbar.IsVisible();
        if (oReturn.returnValue == true)//toolbar is installed and visible
            return false
    }
        
    //first validate period exposure
    if (BannersControlHelper.ReadCookie("TopSliderExposed") == "1")
        return false;
        
    //Validate cookies are enabled on the user's browser
    BannersControlHelper.SetCookie("TopSliderTester","1",1);    
   
    if(BannersControlHelper.ReadCookie("TopSliderTester") == "1")
    {
        //Cookies Enabled on user's browser
        if (BannersControlHelper.ReadCookie("TopSliderExposed") == "1")
        {
           return false;
        }            
                          
        return true;             
    }
    else //Cookies disabled on user's browser
    {
        return false;
    }
}

function get_ApiPath()
{
    if (typeof __apiPath == 'undefined')
        __apiPath = API_PATH;
    return __apiPath +'ToolbarApi.js';
}


function WriteToolbarAPIRequest() {
    document.write("<script src=\"" + get_ApiPath() +"\"></script>");
    //document.write("<script src=\"" + __baseURL + "/Api/ToolbarApi.js\"></script>");
}

function GetDownloadPath() {
    if (typeof __newDownloadPath != 'undefined')
        return __newDownloadPath;
    return __downloadUrl;
}
//support for old banners
function getLocaleDirection() {
    //get the direction from accounts
    if (typeof __BannerDirection != "undefined")
        return __BannerDirection;
    //get the direction from the server - fallback
    if (typeof __LocaleDirection != "undefined")
        return __LocaleDirection;
    return "ltr";

}

//Click on the Banner
function ClickBanner() {
    document.location.href = GetDownloadPath();
    EBDownloadToolbar();
    
}

function WriteBannerHTML() {
    document.write('<style>');
    document.write('#ConduitBrandingElement	{ _bottom : 4px !important; margin-bottom:19px !important;}');
    document.write('</style>');
    document.write('<div  id="EBTopBanner" style="' + GetAlphaFilter() + ';z-index:1000;padding:0px 0px 0px 0px;display:none;width:100%;position:absolute;top:0px;left:0px;height:66px;background-image:url(' + __bgImage + ');background-repeat: repeat;background-repeat: repeat-x;vertical-align: baseline;zoom: 1;_padding-right:10px; _padding-left:10px;">');
    document.write('<table dir="' + getLocaleDirection() + '" height="100%" style="width:100%;" cellpadding="0" cellspacing="0">');
    document.write('<tr>');
    document.write('	<td valign="top" style="padding-left:5px">');
    document.write('	    <table cellpadding="0" cellspacing="0">');
    document.write('	        <tr>');
    document.write('	            <td align="left" style="padding-top:2px;padding-right:7px">');
    document.write('	            <img style="cursor:pointer;" src="' + __closeBtn  + '"   onmouseover = "this.src=\'' + __closeBtnOver  +'\'"  onmouseout = "this.src=\'' + __closeBtn   +'\'" onmousedown = "this.src=\''+ __closeBtnDown  +'\'"  onmousedown = "this.src=\''+ __downloadBtnDown  +'\'" onclick="EBPreVanishTopSlide(false)" />');
    document.write('	            </td>');     
    document.write('	            <td style="padding-top:1px;padding-right:4px;text-align:right" class="">');
    document.write('	            <input type="checkbox" class="" id="checkTopScrollDontShowAgain" onClick="DelayVanish()" />');
    document.write('	            </td>');
    document.write('	            <td>');
    document.write('	            <img style="margin-top:1px;" src="' + __dontShowCaption + '" >');
    document.write('	            </td>');
    document.write('	        </tr>');
    document.write('	    </table>');
    document.write('	</td>');
    document.write('	<td onclick="ClickBanner()" style="cursor:pointer;width:100px;">&nbsp;</td>');
    document.write('	<td onclick="ClickBanner()" style="cursor:pointer;">');
    document.write('	                <table cellpadding="0" cellspacing="0">');
    document.write('	                    <tr>');
    document.write('	                        <td><img src="' + __ImageArrow + '" border="0" />');
    document.write('	                        </td>');
    document.write('	                        <td width="18px" border="0">&nbsp;');
    document.write('	                        </td>');
    document.write('	                        <td align="top" style="vertical-align:top" ><img src="' + __textImage + '" align=top style="border:0"  />');
    document.write('	                        </td>');
    document.write('	                        <td style="width:120px" border="0">&nbsp;&nbsp;');
    document.write('	                        </td>');
    document.write('	<td onclick="ClickBanner()" style="cursor:pointer;vertical-align:top;text-align:right;">');
    document.write('	                <table cellpadding="0" cellspacing="0">');
    document.write('	                    <tr>');
    document.write('	                        <td  colspan="4" style="padding-top:13px;padding-right:4px;vertical-align:top;text-align:right"><img border="0" src="' + __downloadBtn + '"   onmouseover = "this.src=\'' + __downloadBtnOver + '\'"  onmouseout = "this.src=\'' + __downloadBtn + '\'" onmousedown = "this.src=\'' + __downloadBtnDown + '\'"  onmousedown = "this.src=\'' + __downloadBtnDown + '\'" />');
    document.write('	                        </td>');
    document.write('	                    </tr>');
    document.write('	                </table>');
    document.write('	</td>');
    document.write('	                    </tr>');
    document.write('	                </table>');
    document.write('	 </td>');
    document.write('	<td onclick="ClickBanner()" style="cursor:pointer;width:50px;">&nbsp;</td>');

    document.write('	<td onclick="ClickBanner()" style="cursor:pointer;width:30px;">&nbsp;</td>');
    document.write('</tr>');
    document.write('</table>');
    if (__BannerIsBranding == 'true') {
        document.write(__BannerBrandingHtml);
    }
    document.write('</div>');

}

//------Log section------------//
String.format = function(text) {

    if (arguments.length <= 1) return text;
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++)
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"),
                                                    arguments[token + 1]);
    return text;
};
function LogScriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl;
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Create the script tag
    this.scriptObj = document.createElement("script");

    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl);
    this.scriptObj.setAttribute("id", this.scriptId);
    //add the Script tag
    this.headLoc.appendChild(this.scriptObj);
}

function GetCtid() {
    if (typeof __ctid != 'undefined')
        return __ctid
    return "";
}

function GetCulture() {
    if (typeof __BannerCulture != 'undefined')
        return __BannerCulture;
    return "";
}

function GetIsSetup() {
    if (__downloadUrl.indexOf('?') == -1)
        return 'true';
    var querystring = __downloadUrl.substring(__downloadUrl.indexOf('?') + 1);
    if (__downloadUrl.indexOf('=') == -1)
        return 'true';
    var setupQueryString = querystring.split('=');
    if (setupQueryString[0].toLowerCase() == 'setup')
        return setupQueryString[1];
    else return 'true';
};

function logUsage() {
    try {
        if (typeof marketingchannelname == "undefined") {
            marketingchannelname = '';
        }
        var req = String.format('?logType=impression&ctid={0}&bannertypeid={1}&bannerName={2}&bannerculture={3}&setup={4}&marketingchannelname={5}', GetCtid(), 8, "Top_Slider", GetCulture(), GetIsSetup(), marketingchannelname);
        return req;
    }
    catch (e) { }
};
//------Log section------------//

var BannersControlHelper = 
{     	
	IsIE : function()
	{
		return (window.navigator.userAgent.indexOf("MSIE") > 0);
	},
	IsIE7 : function()
	{
		return (window.navigator.userAgent.indexOf("MSIE 7.0") > 0);
	},
	IsIE6 : function()
	{   
	    var regexIE6 = /MSIE ([0-6])/;
		return (regexIE6.test(window.navigator.userAgent));
	},
	AttachEvent : function(obj, eventName, delegate) 
	{
		if  (typeof( obj.addEventListener ) != 'undefined' ) 
		{
			obj.addEventListener(BannersControlHelper.GetEventName(eventName),delegate,false);
		} 
		else {
			obj.attachEvent(eventName,delegate);
		}
	},
	DetachEvent : function(obj,eventName,delegate)
	{
		if (obj.removeEventListener) {
			obj.removeEventListener(eventName,delegate, true);
		}
		else if (obj.detachEvent) {
			obj.detachEvent(eventName,delegate);
		}
	},
	GetEventName : function (name)
	{
		return (name.indexOf('on') == 0) ? name.substring(2,name.length) : name;
	},
	SetCookie:function (cookieName,cookieValue,nDays) 
	{
     var today = new Date();
     var expire = new Date();
     if (nDays==null || nDays==0) nDays=1;
     expire.setTime(today.getTime() + 3600000*24*nDays);
     document.cookie = cookieName+"="+escape(cookieValue)
                     + ";expires="+expire.toGMTString();
    },
    ReadCookie:function (cookieName)
    {
     var theCookie=""+document.cookie;
     var ind=theCookie.indexOf(cookieName);
     if (ind==-1 || cookieName=="") return ""; 
     var ind1=theCookie.indexOf(';',ind);
     if (ind1==-1) ind1=theCookie.length; 
     return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
    }
};


//----Branding Section------
var ConduitBranding =
        {
            TimerIncrease: null,
            TimerDecrease: null,
            varCounterIncrease: 0,
            varCounterDecrease: 0,
            offset: 5,
            countIterations: 20,
            milSecond: 10,
            maxWidth: 92,
            currentWidth: 0,
            brand: null,

            Init: function() {
            ConduitBranding.brand = document.getElementById('ConduitBrandingElement');
                
            },

            IncreaseWidth: function() {
                if (ConduitBranding.currentWidth + ConduitBranding.offset > ConduitBranding.maxWidth) {
                    ConduitBranding.currentWidth = ConduitBranding.maxWidth;
                    ConduitBranding.brand.style.width = ConduitBranding.maxWidth + 'px';

                }
                else {
                    ConduitBranding.currentWidth += ConduitBranding.offset;
                    ConduitBranding.brand.style.width = ConduitBranding.currentWidth + 'px';
                }
            },

            DecreaseWidth: function() {
                if (ConduitBranding.currentWidth - ConduitBranding.offset < 0) {
                    ConduitBranding.currentWidth = 0;
                    ConduitBranding.brand.style.width = '0px';
                }
                else {
                    ConduitBranding.currentWidth -= ConduitBranding.offset;
                    ConduitBranding.brand.style.width = ConduitBranding.currentWidth + 'px';
                }
            },

            TriggerIncrease: function() {
                if (ConduitBranding.varCounterIncrease <= ConduitBranding.countIterations) {
                    ConduitBranding.varCounterIncrease++;
                    ConduitBranding.IncreaseWidth();
                }
                else {
                    clearInterval(ConduitBranding.TimerIncrease);
                    ConduitBranding.varCounterIncrease = 0;
                }

            },


            TriggerDecrease: function() {
                if (ConduitBranding.varCounterDecrease <= ConduitBranding.countIterations) {
                    ConduitBranding.varCounterDecrease++;
                    ConduitBranding.DecreaseWidth();
                }
                else {
                    clearInterval(ConduitBranding.TimerDecrease);
                    ConduitBranding.varCounterDecrease = 0;
                }
            },


            AnimateDecrease: function() {
                clearInterval(ConduitBranding.TimerIncrease);
                ConduitBranding.varCounterIncrease = 0;
                if (ConduitBranding.varCounterDecrease == 0) {
                    ConduitBranding.TimerDecrease = setInterval(ConduitBranding.TriggerDecrease, ConduitBranding.milSecond);

                }
            },

            AnimateIncrease: function() {
                clearInterval(ConduitBranding.TimerDecrease);
                ConduitBranding.varCounterDecrease = 0;
                if (ConduitBranding.varCounterIncrease == 0)
                    ConduitBranding.TimerIncrease = setInterval(ConduitBranding.TriggerIncrease, ConduitBranding.milSecond);

            },
            GetEventName: function(name) {
                return (name.indexOf('on') == 0) ? name.substring(2, name.length) : name;
            },

            AttachEvent: function(obj, eventName, delegate) {
                if (typeof (obj.addEventListener) != 'undefined') {
                    obj.addEventListener(ConduitBranding.GetEventName(eventName), delegate, false);
                }
                else {
                    obj.attachEvent(eventName, delegate);
                }
            }


        };

