/*  ebay flash banner rotator project  - client scipts library    */
/*  20090804 created by dotalfa team  - dushes */

//  settings for other browsers
var __isIE          = navigator.appVersion.match(/MSIE/);
var __userAgent     = navigator.userAgent;
var __isFireFox     = __userAgent.match(/firefox/i);
var __isFireFoxOld  = __isFireFox && (__userAgent.match(/firefox\/2./i) || __userAgent.match(/firefox\/1./i));
var __isFireFoxNew  = __isFireFox && !__isFireFoxOld;

eBayBannerRotatorLibrary = function()
{
    this.banners = {};
}; 


var eBayBannerRotatorLibrary = new eBayBannerRotatorLibrary();

//  returns actual window size
eBayBannerRotatorLibrary.getWindowSize = function() {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') 
    {
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    }
    else
        if  (document.documentElement &&
            (document.documentElement.clientWidth || document.documentElement.clientHeight)) 
            {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
            }
        else
            if  (document.body &&
                (document.body.clientWidth || document.body.clientHeight)) 
                {
                    myWidth = document.body.clientWidth;
                    myHeight = document.body.clientHeight;
                }
    var returnValue =   {   width:myWidth,
                            height:myHeight
                        };
    return returnValue;
}

//  adds css rule into the dom 
eBayBannerRotatorLibrary.addCssRule = function(/* string */selector, /* string */rule) {
    if (document.styleSheets) {
        if (!document.styleSheets.length) {
            var head = document.getElementsByTagName('head')[0];
            head.appendChild(document.createElement('style'));
        }

        var i = document.styleSheets.length - 1;
        var ss = document.styleSheets[i];

        var l = 0;
        if (ss.cssRules) {
            l = ss.cssRules.length;
        } else if (ss.rules) {
            l = ss.rules.length;
        }

        if (ss.insertRule) {
            ss.insertRule(selector + ' {' + rule + '}', l);
        } else if (ss.addRule) {
            ss.addRule(selector, rule, l);
        }
    }
};



//  parses the border size
eBayBannerRotatorLibrary.parseBorderWidth = function(width) {
    var res = 0;
    if (typeof (width) == "string" && width != null
                && width != "") {
        var p = width.indexOf("px");
        if (p >= 0) {
            res = parseInt(width.substring(0, p));
        }
        else {
            res = 1;
        }
    }
    return res;
}

//  returns border width for some element
eBayBannerRotatorLibrary.getBorderWidth = function(element) {
    var res = new Object();
    res.left = 0;
    res.top = 0;
    res.right = 0; 
    res.bottom = 0;
    if (window.getComputedStyle) 
    {
        //  for Firefox
        var elStyle = window.getComputedStyle(element, null);
        res.left    = parseInt(elStyle.borderLeftWidth.slice(0, -2));
        res.top     = parseInt(elStyle.borderTopWidth.slice(0, -2));
        res.right   = parseInt(elStyle.borderRightWidth.slice(0, -2));
        res.bottom  = parseInt(elStyle.borderBottomWidth.slice(0, -2));
    }
    else 
    {
        //  for other browsers
        res.left    = eBayBannerRotatorLibrary.parseBorderWidth(element.style.borderLeftWidth);
        res.top     = eBayBannerRotatorLibrary.parseBorderWidth(element.style.borderTopWidth);
        res.right   = eBayBannerRotatorLibrary.parseBorderWidth(element.style.borderRightWidth);
        res.bottom  = eBayBannerRotatorLibrary.parseBorderWidth(element.style.borderBottomWidth);
    }

    return res;
}

//  returns absolute position of some element within document
eBayBannerRotatorLibrary.getElementAbsolutePos = function(element) 
{
    var res = new Object();
    res.x = 0; 
    res.y = 0;
    if (element !== null) 
    {
        res.x = element.offsetLeft;
        res.y = element.offsetTop;

        var offsetParent    = element.offsetParent;
        var parentNode      = element.parentNode;
        var borderWidth     = null;

        while (offsetParent != null) 
        {
            res.x += offsetParent.offsetLeft;
            res.y += offsetParent.offsetTop;

            var parentTagName = offsetParent.tagName.toLowerCase();

            if ((__isIE && parentTagName != "table") ||
                (__isFireFoxNew && parentTagName == "td")) 
            {
                borderWidth = eBayBannerRotatorLibrary.getBorderWidth(offsetParent);
                res.x += borderWidth.left;
                res.y += borderWidth.top;
            }

            if (offsetParent != document.body &&
                offsetParent != document.documentElement) {
                res.x -= offsetParent.scrollLeft;
                res.y -= offsetParent.scrollTop;
            }
            //  next lines are necessary to support FireFox problem with offsetParent
            if (!__isIE) {
                while (offsetParent != parentNode && parentNode !== null) 
                {
                    res.x -= parentNode.scrollLeft;
                    res.y -= parentNode.scrollTop;

                    if (__isFireFoxOld) 
                    {
                        borderWidth = eBayBannerRotatorLibrary.getBorderWidth(parentNode);
                        res.x   += borderWidth.left;
                        res.y   += borderWidth.top;
                    }
                    parentNode = parentNode.parentNode;
                }
            }

            parentNode = offsetParent.parentNode;
            offsetParent = offsetParent.offsetParent;
        }
    }
    return res;
}

/*  on load handler */
eBayBannerRotatorLibrary.addLoadEvent = function(func) 
{
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

/*  on resize handler */
eBayBannerRotatorLibrary.addResizeEvent = function(func) 
{
    var oldonresize = window.onresize;
    if (typeof window.onresize != 'function') {
        window.onresize = func;
    } else {
        window.onresize = function() {
            if (oldonresize) {
                oldonresize();
            }
            func();
        }
    }
}

/*  settings class */
eBayBannerRotatorLibrary.Settings = function() {
    /*  javascript api version  */
    this.jsript_version = 1.0;

    /*  public properties  */
    this.apiService_URL = "http://www.myebanner.com:80/services/findingservice.svc"


    this.eBaySiteID = "EBAY-US";
    this.itemsCount = 5;
    this.showTooltips = true;
    this.sortDirection = 0;                 //      see eBayBannerRotatorLibrary.Settings.Enums.SortOrderingEnum
    this.orientation = 0;                   //      see eBayBannerRotatorLibrary.Settings.Enums.OrientationEnum
    this.clientID = "00000000-0000-0000-0000-000000000000";                 //      client ID of ebay flash rotator service
    this.objectID = "main";                 //      object ID of flash eBay rotator component
    this.swfSource = "http://www.myebanner.com:80/resources/flash/main.swf";
    //      object ID of flash eBay rotator component

    this.redirectTarget = "_blank";         //      target
    this.pathToModules = "http://www.myebanner.com:80/resources/flash/modules/";
    this.pathToStyles = "http://www.myebanner.com:80/resources/flash/styles/";
    this.pathToFonts = "http://www.myebanner.com:80/resources/flash/fonts/";

    this.zIndexValue = null;
    this.registryExpandOperation = true;    //  if user expands the ebay item in the banner area than banner will sent the expand operation into the server
    this.preview = true;                    //  preview flag - if this flag set than the banner show one item expanded on the Activated event handler
}

/*  all enums required for inner properties */
eBayBannerRotatorLibrary.Enums = function() {
    /*  javascript api version  */
    this.jsript_version = 1.0;

    /*  target sites    */
    this.Targeting = {
        EBAY_AT: 16,
        EBAY_AU: 15,
        EBAY_CH: 193,
        EBAY_DE: 77,
        EBAY_ENCA: 2,
        EBAY_ES: 186,
        EBAY_FR: 71,
        EBAY_FRBE: 23,
        EBAY_FRCA: 210,
        EBAY_GB: 3,
        EBAY_HK: 201,
        EBAY_IE: 205,
        EBAY_IN: 203,
        EBAY_IT: 101,
        EBAY_MOTOR: 100,
        EBAY_MY: 207,
        EBAY_US:0
    };

    /*  currencies    */
    this.CurrencyEnum = {
        AUD: "AUD",
        CAD: "CAD",
        CHF: "CHF",
        CNY: "CNY",
        EUR: "EUR",
        GBP: "GBP",
        HKD: "HKD",
        INR: "INR",
        MYR: "MYR",
        PHP: "PHP",
        PLN: "PLN",
        SEK: "SEK",
        SGD: "SGD",
        TWD: "TWD",
        USD: "USD"
    };

    /*  application  position   */
    this.ApplicationPositionEnum = {
        BottomRight: 0,
        BottomLeft: 1,
        TopRight: 2,
        TopLeft: 4
    };


    /*  items condition enumeration    */
    this.ItemsConditionEnum = {
        New: 0,
        Used: 1
    };

    /*  sort enumeration    */
    this.SortOrderingEnum = {
        BestMatch: 0,
        CurrentPriceHighest: 1,
        DistanceNearest: 2,
        EndTimeSoonest: 3,
        PricePlusShippingHighest: 4,
        PricePlusShippingLowest: 5,
        StartTimeNewest: 6
    };

    /*  banner sizes enumeration   */
    this.BannerSizes = {
        Custom: { width: -1, height: -1 },
        Leaderboard: { width: 728, height: 90 },

        Skyscraper: { width: 120, height: 600 },
        WideSkyscraper: { width: 160, height: 600 },

        FullBanner: { width: 468, height: 60 },
        HalfBanner: { width: 234, height: 60 },
        HalfPage: { width: 300, height: 600 },

        MicroBar: { width: 88, height: 31 },

        SquareButton: { width: 125, height: 125 },
        Rectangle: { width: 180, height: 150 },
        LargeRectangle: { width: 336, height: 280 },
        MediumRectangle: { width: 300, height: 250 }
    };

    this.TargetEnum = {
        self: "_self",      /*  specifies the current frame in the current window.*/
        blank: "_blank",     /*  specifies a new window.*/
        parent: "_parent",    /*  specifies the parent of the current frame.  */
        top: "_top"       /*  specifies the top-level frame in the current window.*/
    }
}

/*  banner rendering settings */
eBayBannerRotatorLibrary.RenderSettings = function() {
    this.size = { width: -1, height: -1 };  //  custom size

    /*  anchor container where the flash object will be embedded   */
    this.anchorContainerID = "";

    /*  the length of separator between eBay items  */
    this.separatorLength = 4;

    /*  name of color & design theme    */
    this.styleName = "black_and_grey_borders_scheme";

    /*  loader Window Background color  */
    this.loaderWindowBackgroundColor = "0x798641";

    /*  loader Window  - Image URL  */
    this.loaderWindowImageURL = "http://www.myebanner.com:80/resources/horizontal_background_for_leaderboard.png";   //  background_400_75_vertical.png

    /*  outer CSS styles logic  - if it's not none this url will be used for loading client css from url into the flash moveclip */
    this.CSSStyleURL = "";

    /*  The Timer Delay value - this value is responsible for delay before roll over effect appling to eBay item    */
    this.rollOverEffectDelay = "700";   /*  700 ms  */

    /*  Banner Position on the current page - this value will be calculated and it's not nessesary to set it in the js code  */
    this.applicationPosition = 0;

    /*  offsets */
    this.offsets = { x: 200, y: 200 };

    /*  show tooltip    */
    this.showTooltip = false;

    /*  banner area effects */
    this.bannerAreaEffects = { name: "Iris", duration: 1000, step: 300 };

    /*  layout */
    this.layoutDescription = { name: "simple",
        expandEffectDuration: 500,
        expandEffectName: "default",
        normalWidth: -1,
        normalHeight: -1,
        expandedWidth: -1,
        expandedHeight: -1,
        rows: -1,
        columns: -1
    };
}

/*  settings filter class  - aspect specific */
eBayBannerRotatorLibrary.FilterClass = function() {

    /*  settings filter class  - aspect specific */
    var aspectFilterSettings = function() {
        this.category = "";
        this.value = "";
    }

    /*  settings filter class  - domain specific */
    var domainFilterSettings = function() {
        this.category = "";
        this.value = "";
    }

    /*  settings filter class  - items filter specific */
    var itemsFilterSettings = function() {
        this.availableTo = "";
        this.condition = 0;         //  see eBayBannerRotatorLibrary.Settings.Enums.ItemsConditionEnum
        this.currency = "USD";      //  see eBayBannerRotatorLibrary.Settings.Enums.Currency
        this.minPrice = 0;
        this.maxPrice = 0;
    }

    this.domain = new domainFilterSettings();
    this.aspect = new aspectFilterSettings();
    this.itemsFilter = new itemsFilterSettings();

    /*  search keywords for findByKeywords method call  */
    this.keywords = "";

    /*  category id */
    this.categoryID = "";
}

/*  events handlers   */
eBayBannerRotatorLibrary.Events = function() 
{
    this.eBayItemClickHandler = function(s, e) { }
    this.eBayItemExpandedEventHandler = function(s, e) { }
    this.eBayItemCollapsedEventHandler = function(s, e) { }
    this.eBayResultsHasBeenReceived = function(s, e) { }
    this.eBayResultsQueryStarted = function(s, e) { }
    this.eBayApplicationResized = function(s, e) { }
}

/*  global objects initialization   */
eBayBannerRotatorLibrary.Enums = new eBayBannerRotatorLibrary.Enums();
eBayBannerRotatorLibrary.Events = new eBayBannerRotatorLibrary.Events();

/*  static methods   */  
eBayBannerRotatorLibrary.getESettings = function() {
    var return_value = eBayBannerRotatorLibrary.Settings;
    return return_value;
}

//  changes the location and size of html element by it's id
eBayBannerRotatorLibrary.setPosition = function(id, x, y, width, height, isExpanded) {
    var htmlElement = document.getElementById(id);
    if (htmlElement != null) {

        if (width != null) {
            htmlElement.style.width = width.toString() + "px";
        }

        if (height != null) {
            htmlElement.style.height = height.toString() + "px";
        }

        if (x != null) {
            htmlElement.style.left = x.toString() + "px";
        }

        if (y != null) {
            htmlElement.style.top = y.toString() + "px";
        }
        
        


        var banner_settings = eBayBannerRotatorLibrary.banners[id];
        if (banner_settings != null) {
            if (banner_settings.objectID != "undefined") {
                var fl_object = document.getElementById(banner_settings.objectID);

                if (isExpanded) {
                    if (fl_object.style.zIndex != "undefined") {
                        banner_settings.zIndexValue = fl_object.style.zIndex
                    }
                    fl_object.style.zIndex = 5;
                }
                else {
                    if (banner_settings.zIndexValue != null) {
                        fl_object.style.zIndex = banner_settings.zIndexValue;
                    }
                }

                if (fl_object != "undefined" &&
                    fl_object != null) {
                    
                    if (fl_object["onLocationChanged"] != "undefined" &&
                        fl_object["onLocationChanged"] != null) {
                        var script = eBayBannerRotatorLibrary.Settings.objectID.toString() + ".onLocationChanged()";
                        if (fl_object.onLocationChanged) {

                            try {
                                fl_object.onLocationChanged();
                            }
                            catch (err) { }
                        }
                    }
                }
            }
        }   //  if (banner_settings != null) {

    }
}

//  returns location and size of html element by it's id
eBayBannerRotatorLibrary.getPosition = function(id) {
    var htmlElement = document.getElementById(id);
    if (htmlElement != null) {

        position = eBayBannerRotatorLibrary.getElementAbsolutePos(htmlElement);
        var returnValue = {
            x: position.x,
            y: position.y,
            width: htmlElement.width,
            height: htmlElement.height
        };

        return returnValue;
    }
    else return null;
}

//  changes the app position in the window client are
eBayBannerRotatorLibrary.configureApplication = function() {
    var windowSize = eBayBannerRotatorLibrary.getWindowSize();

    for (var key in eBayBannerRotatorLibrary.banners) {
        var banner_settings = eBayBannerRotatorLibrary.banners[key];
        var bannerSize = eBayBannerRotatorLibrary.getPosition(banner_settings.objectID);

        if (bannerSize == null)
            bannerSize = banner_settings.renderSettings.size;

        var objectPosition = eBayBannerRotatorLibrary.getPosition(banner_settings.renderSettings.anchorContainerID);
        if (objectPosition != null) {
            objectPosition.width = bannerSize.width;
            objectPosition.height = bannerSize.height;
        }
        else
            return;

        var offsets = banner_settings.renderSettings.offsets;

        if (banner_settings.renderSettings.layoutDescription.expandedHeight > 0 &&
            banner_settings.renderSettings.layoutDescription.normalHeight > 0 &&
           (banner_settings.renderSettings.layoutDescription.expandedHeight - banner_settings.renderSettings.layoutDescription.normalHeight) > offsets.y) {
            offsets.y = banner_settings.renderSettings.layoutDescription.expandedHeight - banner_settings.renderSettings.layoutDescription.normalHeight;
        }

        if (banner_settings.renderSettings.layoutDescription.expandedWidth > 0 &&
            banner_settings.renderSettings.layoutDescription.normalWidth > 0 &&
           (banner_settings.renderSettings.layoutDescription.expandedWidth - banner_settings.renderSettings.layoutDescription.normalWidth) > offsets.x) {
            offsets.x = banner_settings.renderSettings.layoutDescription.expandedWidth - banner_settings.renderSettings.layoutDescription.normalWidth;
        }



        banner_settings.renderSettings.applicationPosition = eBayBannerRotatorLibrary.Enums.ApplicationPositionEnum.TopLeft;

        var maxX = objectPosition.x + parseInt(objectPosition.width) + offsets.x;
        var maxY = objectPosition.y + parseInt(objectPosition.height) + offsets.y;

        if (maxX < windowSize.width &&
            maxY < windowSize.height) {
            banner_settings.renderSettings.applicationPosition = eBayBannerRotatorLibrary.Enums.ApplicationPositionEnum.TopLeft;
        }

        if (maxX < windowSize.width &&
            maxY > windowSize.height) {
            banner_settings.renderSettings.applicationPosition = eBayBannerRotatorLibrary.Enums.ApplicationPositionEnum.BottomLeft;
        }

        if (maxX > windowSize.width &&
            maxY > windowSize.height) {
            banner_settings.renderSettings.applicationPosition = eBayBannerRotatorLibrary.Enums.ApplicationPositionEnum.BottomRight;
        }

        if (maxX > windowSize.width &&
            maxY < windowSize.height) {
            banner_settings.renderSettings.applicationPosition = eBayBannerRotatorLibrary.Enums.ApplicationPositionEnum.TopRight;
        }

        if (banner_settings.objectID != "undefined" &&
            banner_settings.objectID != null) {
            var fl_object = document.getElementById(banner_settings.objectID);

            if (fl_object != "undefined" &&
                fl_object != null) {

                if (fl_object["onResizeHandler"] != "undefined" &&
                    fl_object["onResizeHandler"] != null) {
                    var script = "fl_object.onResizeHandler(false, null)";
                    try {
                        fl_object.onResizeHandler(false);
                    }
                    catch (err) { }
                }
            }
        }
    }
}

//  creates real banner in the dom model
eBayBannerRotatorLibrary.showBanner = function(banner_settings) {
    if (banner_settings.renderSettings.anchorContainerID != "undefined" &&
        banner_settings.renderSettings.anchorContainerID != null) {
        var div_object = document.getElementById(banner_settings.renderSettings.anchorContainerID);


        if (div_object != "undefined" && div_object != null) {

            div_object.style["textAlign"] = "left";
            div_object.style["verticalAlign"] = "top";
            
            //  inner absoulte positioned div
            var absolute_div_id = "absolute_anchor_" + banner_settings.objectID;
            var inner_absolute_div = document.createElement("div");
            inner_absolute_div.style["position"] = "absolute";
            inner_absolute_div.setAttribute("id", absolute_div_id);
            
            var replacement_object_id = "anchor_" + banner_settings.objectID;
            var inner_div = document.createElement("div");
            inner_div.setAttribute("id", replacement_object_id);

            if (div_object.tagName.toLowerCase() != "object") {
                div_object.appendChild(inner_absolute_div);
                inner_absolute_div.appendChild(inner_div);
            }

            var flashvars = {
                application_id: banner_settings.objectID
            };

            var params = { id: banner_settings.objectID,
                menu: "false",
                wmode: "transparent",
                quality: "high",
                allowScriptAccess: "always",
                type: "application/x-shockwave-flash",
                wmode: "transparent",
                pluginspage: "http://www.adobe.com/go/getflashplayer"
            };

            var attributes = {
                id: banner_settings.objectID,
                name: banner_settings.objectID,
                width: banner_settings.renderSettings.size.width,
                height: banner_settings.renderSettings.size.height,
                style: "position:absolute;z-index:4;",
                align: "middle"
            };
            swfobject.embedSWF(banner_settings.swfSource,
                                replacement_object_id,
                                banner_settings.renderSettings.size.width,
                                banner_settings.renderSettings.size.height,
                                "9.0.124",
                                "http://www.myebanner.com:80/resources/flash/expressInstall.swf",
                                flashvars, params, attributes);
        }   //  if (div_object != "undefined" && div_object != null) 
    }   //  if (banner_settings.renderSettings.anchorContainerID != "undefined" &&
}


/*  event handlers  */
eBayBannerRotatorLibrary.addLoadEvent(function() {

    //  create fl object and attach it to the acnror element
    for (var key in eBayBannerRotatorLibrary.banners) {
        var banner_settings = eBayBannerRotatorLibrary.banners[key];
        if (banner_settings != null)
            eBayBannerRotatorLibrary.showBanner(banner_settings);
    }
    eBayBannerRotatorLibrary.configureApplication();

    //  css changes
    eBayBannerRotatorLibrary.addCssRule("object:focus", "-moz-outline: none;outline:none;border:none;border-width:0px;");
});


eBayBannerRotatorLibrary.addResizeEvent(function() {
    eBayBannerRotatorLibrary.configureApplication();
});

eBayBannerRotatorLibrary.createBanner = function(anchorID) {
    var settings = new eBayBannerRotatorLibrary.Settings();
    settings.filter = new eBayBannerRotatorLibrary.FilterClass();

    settings.eBaySiteID = "EBAY-DE";
    settings.sortDirection = eBayBannerRotatorLibrary.Enums.SortOrderingEnum.BestMatch;
    
    settings.renderSettings = new eBayBannerRotatorLibrary.RenderSettings();
    settings.renderSettings.anchorContainerID = anchorID;
    settings.objectID = "object_" + settings.renderSettings.anchorContainerID;
    
    
    settings.renderSettings.size = eBayBannerRotatorLibrary.Enums.BannerSizes.Leaderboard;
    settings.renderSettings.styleName = "black_and_grey_borders_scheme";
    settings.renderSettings.separatorLength = 5;
    settings.renderSettings.rollOverEffectDelay = "0";
    settings.renderSettings.layoutDescription.name = "simple";

    eBayBannerRotatorLibrary.banners[settings.objectID] = settings;
    return settings;
}

eBayBannerRotatorLibrary.clearBanner = function(anchorID) {
    //  clear from collection
    for (var key in eBayBannerRotatorLibrary.banners) {
        var banner_settings = eBayBannerRotatorLibrary.banners[key];
        if (banner_settings.renderSettings.anchorContainerID != "undefined" &&
            banner_settings.renderSettings.anchorContainerID != null &&
            banner_settings.renderSettings.anchorContainerID == anchorID
            ) {

            var div_object = document.getElementById(banner_settings.renderSettings.anchorContainerID);

            if (div_object != "undefined" && div_object != null) {

                var replacement_object_id = banner_settings.objectID;
                var replacement_object_object = document.getElementById(replacement_object_id);
                if (replacement_object_object != null &&
                    replacement_object_object.tagName.toLowerCase() == "object") {
                    div_object.removeChild(replacement_object_object);
                }

            }   //  if (div_object != "undefined" && div_object != null) {

            banner_settings = null;
            eBayBannerRotatorLibrary.banners[key] = null;

        }   //  if (banner_settings.renderSettings.anchorContainerID != "undefined" &&
    }   //  for (var key in eBayBannerRotatorLibrary.banners) {

}

eBayBannerRotatorLibrary.getSettings = function(id) {
    for (var key in eBayBannerRotatorLibrary.banners) {
        var banner_settings = eBayBannerRotatorLibrary.banners[key];
        if (banner_settings.objectID == id)
            return banner_settings;

    }

    return null;
}