/**
* jQuery.infochoiceWidget 1.4.3 (2.2): Infochoice Advert to be servered on a DART server
*
* jQuery.infochoiceWidget is (c) 2009 Mark Boxall (Subetha)
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @author Mark Boxall <http://www.subetha.info>
* @updated: 26/05/2009
*
*/
jQuery.noConflict();

// Remove when not debugging, does not work so well in IE or Chrome
//jQuery.getScript("/Js/JQuery/Plugin/Debug/jquery.debug.js");

(function(jQuery)
{
    jQuery.fn.loadImage = function(src, alt)
    {
        return this.each(function()
        {
            var i = new Image();
            jQuery(i).load(function()
            {
                // notify the user that the image is loaded
            }).error(function()
            {
                // notify the user that the image could not be loaded
            });
            jQuery(i).attr('src', src);
            jQuery(i).attr('alt', alt);
            this.appendChild(i);
        });
    };

    var opt;
    jQuery.fn.infochoiceWidget = function(options)
    {
        opt = jQuery.extend({}, jQuery.fn.infochoiceWidget.defaults, options);
        return this.each(function()
        {
            var container = jQuery(this);
            //Get the confiureations from the server (JSON)
            jQuery.ajax({
                dataType: 'jsonp',
                url: opt.configURI + '&pID=' + opt.publisherID + '&aID=' + opt.advertID + '&callback=?',
                cache: false,
                contentType: 'application/json',
                success: function(_d)
                {
                    opt.config = _d.config;
                    //set the first tab in the array as the current tab
                    opt.currentTab = 'tab1'; //_d.config.tabs[0].id;
                    jQuery.fn.infochoiceWidget.initialise(container);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown)
                {
                    alert(errorThrown);
                }
            });

            return false;
        });
    };

    //Load current tab's data as needed   
    jQuery.fn.infochoiceWidget.initialise = function(container)
    {
        opt.isIE = jQuery.fn.infochoiceWidget.detectIE();

        //        opt.config.logoPosition = "Header"; // "Footer"
        //        opt.config.quicklinkPosition = "Footer"; // "ButtonBar"
        //        opt.config.tabPosition = "Top"; // "ButtonBar"

        //        opt.config.showHeader = true;
        //        opt.config.showFooter = true;
        //        opt.config.showTabArrows = true;

        //        opt.config.reportNoOfRows = 5;
        //        opt.config.reportRowHeight = 32;

        //        opt.config.headerHeight = 48;
        //        opt.config.tabBarHeight = 24;
        //        opt.config.viewportHeight = (opt.config.reportNoOfRows * opt.config.reportRowHeight);
        //        opt.config.buttonBarHeight = 21;
        //        opt.config.footerHeight = 20;

        //if you can't see the widget then select the extra config settings in editor
        //debugger;
        opt.config.viewportHeight = (opt.config.reportNoOfRows * opt.config.reportRowHeight);

        opt.config.headerTop = 0;
        opt.config.tabBarTop = 1 + opt.config.headerTop + opt.config.headerHeight;
        opt.config.viewportTop = 1 + opt.config.tabBarTop + opt.config.tabBarHeight;
        opt.config.buttonBarTop = 1 + opt.config.viewportTop + opt.config.viewportHeight;
        opt.config.footerTop = 1 + opt.config.buttonBarTop + opt.config.buttonBarHeight;

        opt.config.containerHeight = opt.config.footerTop + opt.config.footerHeight;

        container.css('width', opt.isIE == true ? opt.config.width : opt.config.width - 2);
        container.css('height', 1 + opt.config.containerHeight);

        var innerWidth = opt.config.width - 2;

        //Common components
        var header = jQuery('#icw .panelHeader');
        var footer = jQuery('#icw .panelFooter');
        var tabBar = jQuery('#icw .panelTabBar');
        var viewport = jQuery('#icw .panelViewPort');
        var buttonBar = jQuery('#icw .panelButtonBar');
        var report = jQuery('#icw .report');
        var tabs = jQuery('#icw .tabs');
        var loading = jQuery('#icw .loading');

        //header.css('border', 'solid 1px red');
        //tabBar.css('border', 'solid 1px red');
        //viewport.css('border', 'solid 1px red');
        //buttonBar.css('border', 'solid 1px red');
        //footer.css('border', 'solid 1px blue');
        //report.css('border', 'solid 1px green');

        var slides = jQuery('#ics');

        // Add CssClass: top or bottom
        container.addClass(opt.config.tabPosition == "Top" ? "tabTop" : "tabBottom");

        // Setup width
        header.css('width', innerWidth);
        header.css('height', opt.config.headerHeight);
        header.css('top', opt.config.headerTop);

        tabBar.css('width', innerWidth);
        tabBar.css('height', opt.config.tabBarHeight);
        tabBar.css('top', opt.config.tabBarTop);

        viewport.css('width', innerWidth);
        viewport.css('height', opt.config.viewportHeight);
        viewport.css('top', opt.config.viewportTop);

        report.css('width', innerWidth);
        report.css('height', opt.config.viewportHeight);

        // alrtering this screws up somethihng
        buttonBar.css('width', innerWidth - (opt.isIE ? 4 : 4));
        buttonBar.css('height', opt.config.buttonBarHeight);
        buttonBar.css('top', opt.config.buttonBarTop);

        footer.css('width', innerWidth);
        footer.css('height', opt.config.footerHeight);
        footer.css('top', opt.config.footerTop);

        loading.css('top', ((opt.config.containerHeight / 2) - 32));
        loading.css('left', ((opt.config.width / 2) - 32));

        slides.css('width', innerWidth);
        slides.find('#sbg').css('width', innerWidth);
        slides.find('.sli').css('left', ((opt.config.width / 2) - 110));

        //jQuery('#icw .tip').css('width', innerWidth);

        buildHeader(header);
        buildFooter(footer);

        //viewport.prepend('<div class="tip">tips</div>');


        /* Setup the Button Bar */
        jQuery.fn.infochoiceWidget.initializeButtonBar();
        jQuery.fn.infochoiceWidget.initializeButtonBarClickEvents();

        // Show panels
        viewport.show();
        buttonBar.show();

        if (opt.config.showHeader) header.show();
        if (opt.config.showFooter) footer.show();

        // Tab bar
        buildTabs();
        tabBar.show();
        resizeTabBar();
        if (opt.config.showTabArrows) initializeTabBarArrowClickEvents();

        // Load tab
        opt.currentTab = tabs.find('li:first').addClass('on').attr('id');

        jQuery.fn.infochoiceWidget.loadTab(opt.currentTab);

        if (opt.config.tabRounded == true)
        {
            applyRoundedTabs();
        }
        //start the screen saver...
        if (opt.config.idle.type == 'slide')
        {
            jQuery.fn.infochoiceWidget.loadSlides();
        }

        return false;

        /* Start: Initialization Helper Functions */
        function logoHtml()
        {
            return '<div class="logo"><a href="' + opt.config.logoUrl + '" title="' + opt.config.publisherName + '" target="' + opt.config.logoTarget + '"></a></div><div class="clear"></div>';
        }
        function buildHeader(target)
        {
            var html = '<div class="headingContainer"><h2>' + opt.config.caption + '</h2></div>';

            if (opt.config.logoPosition = "Header")
            {
                html += logoHtml();
            }

            target.html(html);
        }
        function buildFooter(target)
        {
            var html = '';

            // Put quicklinks somewhere
            if (opt.config.quicklinkPosition == "Footer")
            {
                html += '<div class="quickLink"></div>';
            }
            if (opt.config.logoPosition == "Footer")
            {
                html += logoHtml();
            }

            target.html(html);
        }
        function buildTabs()
        {
            for (var j = 0; j < opt.config.tabs.length; j++)
            {
                var tabCssClass = 'class="' + (j == 0 ? ' first' : j == opt.config.tabs.length - 1 ? ' last' : '') + '"';

                tabs.find('ul').append('<li id="tab' + (j + 1) + '"' + tabCssClass + '><a href="#">' + opt.config.tabs[j].name + '</a></li>');
            }

            // Setup Tab Click Handler
            jQuery('#icw .tabs ul li a').click(function(_e)
            {
                _e.preventDefault();

                var targetTab = jQuery(this).parent();

                /* Add/Remove styling */
                jQuery("#icw .tabs li").removeClass('on');
                targetTab.addClass('on');

                //find  new offset position
                var newOffsetTab = jQuery(this).parent();
                var newPosition = newOffsetTab.position();

                // Davo: Fix here and make buttons configured
                // only animate if needed
                //            if (jQuery('#icw .tabArrow').is(':visible'))
                //            {
                //                //aminate the tabs left
                //                tabs.find('ul').animate({ left: -newPosition.left }, opt.easeTime, opt.easeFunc);
                //            }
                //            //set the new offset tab id
                opt.offsetTab = newOffsetTab.attr('id');

                opt.currentTab = opt.offsetTab = newOffsetTab.attr('id');

                setTabArrowsVisiblity(targetTab);

                jQuery.fn.infochoiceWidget.loadTab(opt.currentTab);

                jQuery.fn.infochoiceWidget.reset(true);
            });
        }
        function resizeTabBar()
        {
            //Set the correct width for the parent ul
            //            var tabWith = 0;
            //            tabs.find('li').each(function()
            //            {
            //                tabWith += jQuery(this).width() + 10;
            //                if (jQuery.browser.msie && jQuery.browser.version < 8)
            //                {
            //                    jQuery(this).find('a').css('width', jQuery(this).width());
            //                }
            //            });
            //            tabs.find('ul').css('width', tabWith);

            if (opt.config.showTabArrows)
            {
                tabs.css('width', innerWidth - (opt.isIE ? 49 : 50));
            }
            else
            {
                tabs.css('width', innerWidth);
            }
        }
        function setTabArrowsVisiblity(currentTab)
        {
            //alert(currentTab.className + " - First: " + currentTab.hasClass("first") + " - Last: " + currentTab.hasClass("last"));
            if (currentTab.hasClass("first"))
            {
                jQuery('#prevTab').removeClass('on');
                jQuery('#nextTab').addClass('on');
            }
            else if (currentTab.hasClass("last"))
            {
                jQuery('#prevTab').addClass('on');
                jQuery('#nextTab').removeClass('on');
            }
            else
            {
                jQuery('#prevTab').addClass('on');
                jQuery('#nextTab').addClass('on');
            }
        }
        function initializeTabBarArrowClickEvents()
        {
            //next tab
            jQuery('#nextTab').click(function(_e)
            {
                _e.preventDefault();
                if (jQuery('#nextTab').is('.on'))
                {
                    //find  new offset position
                    var newOffsetTab = tabs.find('#' + opt.offsetTab).next('li');
                    var newPosition = newOffsetTab.position();
                    //aminate the tabs left
                    tabs.find('ul').animate({ left: -newPosition.left }, opt.easeTime, opt.easeFunc);

                    //set the new offset tab id
                    opt.offsetTab = newOffsetTab.attr('id');

                    if (newOffsetTab.attr('id') == 'tab' + tabs.find('li').length)
                    {
                        jQuery('#nextTab').addClass('dis').removeClass('on');
                    }
                    //activte the previous button
                    jQuery('#prevTab').addClass('on').removeClass('dis');
                }
                jQuery.fn.infochoiceWidget.reset(true);
            });

            //previous tab
            jQuery('#prevTab').click(function(_e)
            {
                _e.preventDefault();
                if (jQuery('#prevTab').is('.on'))
                {
                    //find  new offset position
                    var newOffsetTab = tabs.find('#' + opt.offsetTab).prev('li');
                    var newPosition = newOffsetTab.position();
                    //aminate the tabs left
                    tabs.find('ul').animate({ left: -newPosition.left }, opt.easeTime, opt.easeFunc);

                    //set the new offset tab id
                    opt.offsetTab = newOffsetTab.attr('id');

                    if (newOffsetTab.attr('id') == 'tab1')
                    {
                        jQuery('#prevTab').addClass('dis').removeClass('on');
                    }

                    //activte the next button
                    jQuery('#nextTab').addClass('on').removeClass('dis');
                }
                jQuery.fn.infochoiceWidget.reset(true);
            });
        }
        function applyRoundedTabs()
        {
            // Note use: "round 5px bottom cc:" + configuredBgColor if we need to color the corners
            jQuery('#icw').find('div.tabs li').each(function()
            {
                if (opt.config.tabPosition == 'Top')
                {
                    jQuery(this).corner("round 5px top").find('a:first').corner("round 3px top");
                }
                else
                {
                    jQuery(this).corner("round 5px bottom").find('a:first').corner("round 3px bottom");
                }
            });
        }
        /* End: Initialization Helper Functions */
    };

    /* Button Bar */
    jQuery.fn.infochoiceWidget.initializeButtonBar = function()
    {
        if (opt.config.buttonPosition == 'Middle')
        {
            jQuery('#icw .buttonBar').css('right', ((opt.config.width / 2) - 40));
        }
        else
        {
            jQuery('#icw .buttonBar').css('right', 5);
        }
    }
    jQuery.fn.infochoiceWidget.initializeButtonBarClickEvents = function()
    {
        var panel;
        var sizeOfRow = 32;
        var viewportSize;
        var numberOfRows;
        var topOffset;
        var viewportOffset;
        var moveToPosition;
        var viewportDirection;

        // Click Button Top
        jQuery('#buttonTop').click(function(_e)
        {
            _e.preventDefault();

            return executeClick("buttonTop", "top");
        });
        //up
        jQuery('#buttonUp').click(function(_e)
        {
            _e.preventDefault();

            return executeClick("buttonUp", "up");
        });
        //down
        jQuery('#buttonDown').click(function(_e)
        {
            _e.preventDefault();

            return executeClick("buttonDown", "down");
        });
        executeClick = function(buttonName, direction)
        {
            if (jQuery('#' + buttonName).is('.on'))
            {
                viewportDirection = direction;

                setPanel();

                viewportMove();

                buttonVisibility();
            }
            jQuery.fn.infochoiceWidget.reset(true);

            return false;
        }
        setPanel = function()
        {
            var panelId = 'panel' + opt.config.currentTab.substring(3);

            panel = jQuery('#' + panelId);
        }
        viewportMove = function()
        {
            // up, down or top
            var directionOffset = viewportDirection == 'up' ? -1 : viewportDirection == 'down' ? 1 : 0;

            // This is the number of rows in the viewPort
            // if the tabPosition is bottom then remove a row.
            numberOfRows = opt.config.reportNoOfRows - ((opt.config.tabPosition == 'Top') ? 0 : 1);

            var numberOfDataRows = parseInt(panel.get(0).getAttribute("numberOfDataRows"));
            var viewDataRowIndex = parseInt(panel.get(0).getAttribute("viewDataRowIndex"));

            topOffset = 0;

            // This should use a isDisplay heading configuration
            //                if (content.find('div#head' + currentID).length > 0)
            //                {
            //                    numberOfRows -= 1; // We loose a row if we have a heading
            //                    topOffset = 20;
            //                }
            //

            if (viewportDirection == 'top')
            {
                viewDataRowIndex = 0;
            }
            else
            {
                // Add or Subtract (No of rows in the view port)
                viewDataRowIndex = viewDataRowIndex + (numberOfRows * directionOffset);

                var lastRow = numberOfDataRows - numberOfRows;

                if (viewDataRowIndex > lastRow)
                {
                    viewDataRowIndex = lastRow;
                }
                if (viewDataRowIndex < 0)
                {
                    viewDataRowIndex = 0;
                }
            }

            // Update the current viewDataRowIndex
            panel.get(0).setAttribute("viewDataRowIndex", viewDataRowIndex);

            moveToPosition = -1 * (topOffset + (viewDataRowIndex * sizeOfRow));

            //jQuery.log('numberOfDataRows: ' + numberOfDataRows);
            //jQuery.log('viewDataRowIndex: ' + viewDataRowIndex);

            //jQuery.log('viewportDirection: ' + viewportDirection);
            //jQuery.log('directionOffset: ' + directionOffset);
            //jQuery.log('sizeOfRow: ' + sizeOfRow);
            //jQuery.log('numberOfRows: ' + numberOfRows);
            //jQuery.log('topOffset: ' + topOffset);
            //jQuery.log('moveToPosition "-1 * (topOffset + (viewDataRowIndex * sizeOfRow))": ' + moveToPosition);
            //jQuery.log('------------------------------------------------------------------------------------------------------------');

            panel.animate({ top: moveToPosition }, opt.easeTime, opt.easeFunc);
        }
        buttonVisibility = function()
        {
            jQuery('#buttonDown').addClass('on');
            jQuery('#buttonUp').addClass('on');
            jQuery('#buttonTop').addClass('on');

            if (moveToPosition == topOffset)
            {// Already at the top
                jQuery('#buttonUp').removeClass('on');
                jQuery('#buttonTop').removeClass('on');
            }

            //            //alert(currentOffset + " - " + newPosition + " - " + offsetTop + " - " + (newPosition == offsetTop));
            //            //if (moveToPosition <= -((panel.find('li').length * 32) - (multiply * 32) - offsetTop))
            //            //{
            //            jQuery('#buttonDown').removeClass('on');
            //            jQuery('#buttonDown').addClass('on');
            //            //}

            //            //activte the down button
            //            jQuery('#buttonUp').addClass('on');
            //            jQuery('#buttonTop').addClass('on');
        }

    }

    /* Load Reports */
    jQuery.fn.infochoiceWidget.loadTab = function(tabID)
    {
        var displayID = tabID.substring(3);
        var tID = opt.config.tabs[displayID - 1].id;
        var content = jQuery('#icw .report');
        var panelId = 'panel' + displayID;

        if (content.find('#' + panelId).length == 0)
        { //load the data into the widget
            //add data to widget
            try
            {
                jQuery('#icw .loading').show(); // removes the preloader gif

                jQuery.ajax({
                    dataType: 'jsonp',
                    url: opt.config.dataURI + '&pID=' + opt.publisherID + '&tID=' + tID + '&aID=' + opt.advertID,
                    cache: false,
                    contentType: 'application/json',
                    success: function(_d)
                    {
                        var innerWidth = opt.config.width - 2;

                        // Create a ul to hold the data and start loading it...
                        var rowClass = 'odd';
                        content.append('<ul id="' + panelId + '" style="display:none;width:' + (innerWidth) + 'px" viewDataRowIndex="0" numberOfDataRows="' + _d.data.length + '"></ul>');
                        var ul = content.find('ul:last');
                        jQuery.each(_d.data, function()
                        {
                            var dataRow = jQuery(this)[0].Rows;
                            ul.append('<li class="' + rowClass + '" style="width:' + (innerWidth) + 'px"><table style="width:' + (innerWidth) + 'px"><tr></tr></table></li>');
                            var htmlRow = ul.find('tr:last');
                            for (var x = 0; x < dataRow.length; x++)
                            {
                                var heading = _d.heading[x];

                                var cellType = heading.type;
                                var cellClass = (heading.cellClass == '') ? '' : ' class="' + heading.cellClass + '"';
                                var cellWidth = (heading.cellWidth == '') ? '' : ' width="' + heading.cellWidth + '"';
                                var cellData = dataRow[x].cellData;
                                var cellLinkTarget = heading.rowLinkTarget;

                                switch (cellType)
                                {
                                    case 'image':
                                        htmlRow.append('<td' + cellClass + cellWidth + '></td>');
                                        htmlRow.find('td:last').loadImage(cellData, '');
                                        break;

                                    case 'text':
                                        htmlRow.append('<td' + cellClass + cellWidth + '>' + cellData + '</td>');
                                        break;
                                    case 'linkText':
                                        htmlRow.append('<td' + cellClass + cellWidth + '><a href="#">' + cellData + '<a></td>');
                                        break;
                                    // This is a rowLink, this may need to change if we are doing column links                                                            
                                    case 'linkUrl':
                                        htmlRow.attr('linkCellType', cellType);
                                        htmlRow.attr('linkUrl', cellData);
                                        htmlRow.attr('linkTarget', cellLinkTarget);

                                        htmlRow.hover(function()
                                        {
                                            jQuery(this).addClass('hover');
                                        }, function()
                                        {
                                            jQuery(this).removeClass('hover');
                                        }).click(function(_e)
                                        {
                                            _e.preventDefault();
                                            var o = jQuery(this);

                                            if (o.attr('linkCellType') == 'linkUrl')
                                            {
                                                jQuery.fn.infochoiceWidget.clickOpenTarget(o, '');
                                            }
                                            else
                                            {
                                                // Handel the window opening in LinkOnClick
                                            }

                                            return false;
                                        });
                                        break;
                                    case 'linkOnClick':
                                        var clickData = cellData.split(',');

                                        if (clickData.length >= 3)
                                        {
                                            htmlRow.attr('linkCellType', cellType);
                                            //alert(clickData.length + " - " + clickData[0] + " - " + clickData[1] + " - " + clickData[2]);
                                            htmlRow.attr('publisherId', clickData[0]);
                                            htmlRow.attr('buttonId', clickData[1]);
                                            htmlRow.attr('productId', clickData[2]);
                                            htmlRow.attr('erpc', clickData.length >= 4 ? clickData[3] : 0);
                                            htmlRow.attr('purchaseID', clickData.length >= 5 ? clickData[4] : 0);

                                            htmlRow.click(
                                            function(_e)
                                            {
                                                try
                                                {
                                                    var tr = jQuery(this);

                                                    var link = tr.find('a').get(0);

                                                    s.linkTrackVars = 'products,eVar9,purchaseID,events';
                                                    s.linkTrackEvents = 'purchase,event1';
                                                    s.purchaseID = '' + tr.attr('purchaseID') + '';
                                                    s.products = ';' + tr.attr('productId') + ';1;' + tr.attr('erpc');
                                                    s.eVar9 = s.pageName;
                                                    s.events = 'purchase,event1';
                                                    s.tl(link, 'o');

                                                    jQuery.fn.infochoiceWidget.clickOpenTarget(tr, tr.attr('purchaseID'));

                                                    return true;
                                                }
                                                catch (ex)
                                                {
                                                    alert('Omniture not setup');
                                                }
                                                return false;
                                            });
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                            rowClass = (rowClass == 'odd') ? 'even' : 'odd';
                        });
                        // Headings are not yet tested
                        /*
                        if (_d.heading && _d.heading.length > 0)
                        {
                        content.append('<div id="head' + displayID + '" class="h" style="display:none;width:' + (innerWidth) + 'px"><table style="width:' + (innerWidth) + 'px"><tr></tr></table></div>');
                        var heading = content.find('.h:last');
                        heading.css('z-index', 100 + parseInt(displayID));
                        var cells = heading.find('tr:first');
                        for (var y = 0; y < _d.heading.length; y++)
                        {
                        var w = (_d.heading[y].cellWidth == null) ? '' : ' width="' + _d.heading[y].cellWidth + '"';
                        var d = (_d.heading[y].cellData == null) ? '&nbsp;' : _d.heading[y].cellData;
                        cells.append('<td' + w + '>' + d + '</td>');
                        }
                        }
                        */

                        //display the tab...
                        jQuery.fn.infochoiceWidget.displayTab(displayID);
                        jQuery('#icw .loading').hide(); // removes the preloader gif
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown)
                    {
                        jQuery('#icw .loading').hide(); // removes the preloader gif
                        alert(errorThrown);
                    }

                });
            } catch (ex) { alert(ex); }
        }
        else
        {
            jQuery.fn.infochoiceWidget.displayTab(displayID);
        }

        // Reset the list to the top if we change tabs
        executeClick("buttonTop", "top");

        jQuery.fn.infochoiceWidget.play();
        return false;
    };

    // Open a window based on a values found on this object
    jQuery.fn.infochoiceWidget.clickOpenTarget = function(o, clkValue)
    {
        var url = o.attr('linkUrl');

        // DAVO: This code needs to take PURCHASE ID
        url = url + (url.indexOf('?') == -1 ? '?' : '&') + 'CLK=' + clkValue;

        if (o.attr('linkTarget') == '_blank')
        {
            window.open(url);
        }
        else if (o.attr('linkTarget') == '_parent')
        {
            parent.location.href = url;
        }
        else if (o.attr('linkTarget') == '_top')
        {
            window.top.location.href = url;
        }
        else
        {
            document.location.href = url;
        }
    }

    //Load current tab's data as needed   
    jQuery.fn.infochoiceWidget.displayTab = function(displayID)
    {
        var content = jQuery('#icw .report');

        jQuery.fn.infochoiceWidget.displayTabText(displayID);

        //need fade out current tab, fade in new tab and display the loader	
        var newPanel = content.find('ul#panel' + displayID);

        var currentPanel = content.find('ul.on');

        if (currentPanel.length > 0)
        {
            var currentID = currentPanel.attr('id').substring(5);

            //Dave: headings - not yet tested
            /*
            if (content.find('div#head' + currentID).length > 0)
            {
            content.find('div#head' + currentID).removeClass('on').css('display', 'none');
            }
            */
            currentPanel.css('display', 'none');
        }

        //        //reset controls nad loaction of the tab's data...
        jQuery('#buttonUp').removeClass('on');
        jQuery('#buttonTop').removeClass('on');
        jQuery('#buttonDown').addClass('on');

        /* This code is related to headings, need to revisit all of this
        var newHeading;
        if (content.find('div#head' + displayID).length > 0)
        {
        newHeading = content.find('div#head' + displayID);
        newHeading.addClass('on').siblings('div').removeClass('on');
        newHeading.show();
        newPanel.css('top', '20px');
        }
        else
        {
        newPanel.css('top', 0); // probabally don't need this because it is handled through viewportOffset now
        }
        */
        newPanel.addClass('on').siblings('ul').removeClass('on');
        newPanel.css('display', 'block');
        opt.config.currentTab = 'tab' + displayID;

        return false;
    };

    /* Add QuickLinks and Tool Tips related to a specific tab */
    jQuery.fn.infochoiceWidget.displayTabText = function(displayID)
    {
        var tabInfo = opt.config.tabs[displayID - 1];

        var quickLink = jQuery('#icw .quickLink');
        var tips = jQuery('#icw .tip');

        // Add Quick Links
        var quickLinkHtml = '';
        var is1st = true;

        jQuery.each(tabInfo.quickLinks, function(i, quickLink)
        {
            quickLinkHtml += (is1st ? '' : '<span class="pipe">|</span>') + '<a href="' + quickLink.url + '" target="' + quickLink.target + '">' + quickLink.text + '</a>';
            is1st = false;
        });

        quickLink.html(quickLinkHtml);

        // Add Tool Tips
        if (opt.config.tabPosition == 'bottom')
        {
            tips.html('<h3>' + tabInfo.name + '</h3><p>' + tabInfo.tip + '</p>');
        }
    }

    jQuery.fn.infochoiceWidget.play = function()
    {
        jQuery.fn.infochoiceWidget.reset(true);
        return false;
    };
    jQuery.fn.infochoiceWidget.detectMacXFF = function()
    {
        var userAgent = navigator.userAgent.toLowerCase();
        if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1)
        {
            return true;
        }
    };
    jQuery.fn.infochoiceWidget.detectIE = function()
    {
        var userAgent = navigator.userAgent.toLowerCase();
        if (userAgent.indexOf('msie') != -1)
        {
            return true;
        }
        return false;
    };
    jQuery.fn.infochoiceWidget.stop = function()
    {
        clearInterval(opt.timer);
        return false;
    };

    jQuery.fn.infochoiceWidget.reset = function(initRun)
    {
        var delay;
        clearInterval(opt.timer);
        if (initRun === true && opt.config.idle.type == 'slide')
        {
            delay = opt.config.idle.start * 1000;
        }
        else
        {
            delay = opt.config.idle.delay * 1000;
        }
        switch (opt.config.idle.type)
        {
            case 'row': /*David Revisit this: opt.timer = setInterval(jQuery.fn.infochoiceWidget.animateRows, delay); */
                break;
            case 'tab': /*David Revisit this: opt.timer = setInterval(jQuery.fn.infochoiceWidget.nextTab, delay); */
                break;
            case 'slide': opt.timer = setInterval(jQuery.fn.infochoiceWidget.nextSlide, delay);
                break;
            default: break;
        }
        return false;
    };

    jQuery.fn.infochoiceWidget.loadSlides = function()
    {
        if (jQuery.fn.infochoiceWidget.detectMacXFF())
        {
            jQuery("#sbg").addClass("ovhack"); //use png overlay so hide flash
        } else
        {
            jQuery("#sbg").addClass("ovbg"); //use background and opacity
        }
        //Get the confiureations from the server (JSON)
        jQuery.ajax({
            dataType: 'jsonp',
            url: opt.config.idle.url + '&pID=' + opt.publisherID + '&aID=' + opt.advertID + '&callback=?',
            cache: false,
            contentType: 'application/json',
            success: function(_d)
            {
                opt.slides = _d.slides;
                //set the first slide in the array as the current slide
                opt.config.idle.currentSlide = 0;
                //add the first slide to the html
                var slideContainer = jQuery('#ics');
                for (var z = 0; z < opt.slides.length; z++)
                {
                    var l = opt.slides[z].link;
                    var h = opt.slides[z].html;
                    slideContainer.find('ul').append('<li id="sli' + (z + 1) + '" class="dis" style="display:none">' + h + '</li>');
                }
                //show the first slide
                var fSlide = slideContainer.find('#sli1');
                fSlide.removeClass('dis').addClass('on').show();


                //hide previous
                jQuery('#slip').click(function(_e)
                {
                    _e.preventDefault();
                    jQuery.fn.infochoiceWidget.prevoiusSlide();
                    return false;
                });

                jQuery('#slic').click(function(_e)
                {
                    _e.preventDefault();
                    jQuery('#ics').fadeOut().addClass('dis').removeClass('on');
                    jQuery.fn.infochoiceWidget.reset(true);
                    return false;
                });

                jQuery('#slid').click(function(_e)
                {
                    _e.preventDefault();
                    jQuery.fn.infochoiceWidget.slideDetails();
                    return false;
                });
                return false;
            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            {
                alert(errorThrown);
            }
        });

        return false;
    };

    jQuery.fn.infochoiceWidget.nextSlide = function()
    {

        var slideContainer = jQuery('#ics');
        if (slideContainer.is('.on'))
        {
            //fade current slide out, fade next slide in
            var cSlide = jQuery('li#sli' + (opt.config.idle.currentSlide + 1));
            var nSlide;
            if (opt.config.idle.currentSlide + 1 == opt.slides.length)
            {
                opt.config.idle.currentSlide = 0;
                nSlide = jQuery('li#sli1');
            }
            else
            {
                opt.config.idle.currentSlide++;
                nSlide = jQuery('li#sli' + (opt.config.idle.currentSlide + 1));
            }
            cSlide.css('z-index', '2');
            nSlide.css('z-index', '1');

            //fade out the current slide
            cSlide.fadeOut(opt.config.idle.fade * 1000);
            nSlide.show();
            nSlide.removeClass('dis').addClass('on').siblings('li').removeClass('on').addClass('dis');
        }
        else
        {
            jQuery('#ics').fadeIn().addClass('on').removeClass('dis');
        }
        jQuery.fn.infochoiceWidget.reset(false);

        return false;
    };

    jQuery.fn.infochoiceWidget.prevoiusSlide = function()
    {
        var slideContainer = jQuery('#ics');

        //fade current slide out, fade next slide in
        var cSlide = jQuery('li#sli' + (opt.config.idle.currentSlide + 1));
        var nSlide;
        if (opt.config.idle.currentSlide == 0)
        {
            opt.config.idle.currentSlide = opt.slides.length - 1;
            pSlide = jQuery('li#sli' + (opt.config.idle.currentSlide + 1));
        }
        else
        {
            opt.config.idle.currentSlide--;
            pSlide = jQuery('li#sli' + (opt.config.idle.currentSlide + 1));
        }

        cSlide.css('z-index', '2');
        pSlide.css('z-index', '1');

        //fade out the current slide
        cSlide.fadeOut();
        pSlide.show();
        pSlide.removeClass('dis').addClass('on').siblings('li').removeClass('on').addClass('dis');

        //fade current slide out, fade prevoius slide in
        jQuery.fn.infochoiceWidget.reset(false);
        return false;
    };


    jQuery.fn.infochoiceWidget.closeSlides = function()
    {
        //stop timer, fade out slides
        opt.initTimer = true;

        jQuery('#ics').fadeOut().addClass('dis').removeClass('on');
        jQuery.fn.infochoiceWidget.reset(true);
        return false;
    };


    jQuery.fn.infochoiceWidget.slideDetails = function()
    {
        //get the current link
        window.open(opt.slides[opt.config.idle.currentSlide].link);
        return false;
    };

    /* David: This code currently used by Slider status, the code ahas been heavily altered for tabs, and this needs to be revisited
    jQuery.fn.infochoiceWidget.nextTab = function()
    {
    alert(1);
    //get the current en tab
    var tabs = jQuery('#icw .tabs ul');
    var currentTab = jQuery('#icw #' + opt.currentTab);
    //work out the nex tab
    var newOffsetTab;
    if (tabs.find('li').length == parseInt(opt.currentTab.substring(3)))
    {
    newOffsetTab = jQuery('#icw #tab1');
    }
    else
    {
    newOffsetTab = currentTab.next('li');
    }
    //get the new position
    var newPosition = newOffsetTab.position();

        //set the new tab as en
    newOffsetTab.addClass('on').parent().find('li').not(newOffsetTab).removeClass('on');


        //change the colours....
    currentTab.css('background-color', opt.config.tabsOptions.static.borderColour);
    currentTab.find('a:first').css('background-image', opt.config.tabsOptions.static.backgroundImage).css('background-color', opt.config.tabsOptions.static.backgroundColour).css('color', opt.config.tabsOptions.static.textColour);

        newOffsetTab.css('background-color', opt.config.tabsOptions.active.borderColour);
    newOffsetTab.find('a:first').css('background-image', opt.config.tabsOptions.active.backgroundImage).css('background-color', opt.config.tabsOptions.active.backgroundColour).css('color', opt.config.tabsOptions.active.textColour);

        if (jQuery('#icw .arr').is(':visible'))
    {
    //aminate the tabs left
    tabs.animate({ left: -newPosition.left }, opt.easeTime, opt.easeFunc);
    }

        //set the new offset tab id
    opt.offsetTab = newOffsetTab.attr('id');
    opt.currentTab = opt.offsetTab = newOffsetTab.attr('id');


        if (newOffsetTab.attr('id') == 'tab1')
    {
    jQuery('#prevTab').addClass('dis').removeClass('on');
    jQuery('#nextTab').addClass('on').removeClass('dis');
    } else if (newOffsetTab.attr('id') == 'tab' + tabs.find('li').length)
    {
    jQuery('#nextTab').addClass('dis').removeClass('on');
    jQuery('#prevTab').addClass('on').removeClass('dis');
    } else
    {
    jQuery('#nextTab').addClass('on').removeClass('dis');
    jQuery('#prevTab').addClass('on').removeClass('dis');
    }

        jQuery.fn.infochoiceWidget.loadTab(opt.currentTab);
    return false;
    };
    */

    /* David: This code currently used by Slider status, the code ahas been heavily altered for tabs, and this needs to be revisited
    jQuery.fn.infochoiceWidget.animateRows = function()
    {
    //get the currently en tab...
    var enPanel = jQuery('#icw .report ul.on');

        var multiply = (opt.config.displayStyle == 'top') ? 5 : 4;
    var currentID = opt.config.currentTab.substring(3);
    var offsetTop = 0;
    var content = jQuery('#icw');
    if (content.find('div#head' + currentID).length > 0)
    {
    multiply -= 1;
    offsetTop = 20;
    }

        //find  new offset position
    var currentOffset = parseInt(enPanel.css('top'));
    var newPosition = currentOffset - (multiply * 32);

        if (newPosition <= -((enPanel.find('li').length * 32)))
    {
    newPosition = 0 + offsetTop;
    enPanel.animate({ top: 0 + offsetTop }, opt.easeTime + 500, opt.easeFunc);
    jQuery('#buttonUp').addClass('dis').removeClass('on');
    jQuery('#buttonTop').addClass('dis').removeClass('on');
    }
    else
    {
    enPanel.animate({ top: newPosition }, opt.easeTime, opt.easeFunc);
    jQuery('#buttonUp').addClass('on').removeClass('dis');
    jQuery('#buttonTop').addClass('on').removeClass('dis');
    }
    //update the buttons


        if (newPosition <= -((enPanel.find('li').length * 32) - (multiply * 32) - offsetTop))
    {
    jQuery('#buttonDown').addClass('dis').removeClass('on');
    }
    else
    {
    jQuery('#buttonDown').addClass('on').removeClass('dis');
    }
    return false;
    };
    */

    // This needs to be cleaned up
    jQuery.fn.infochoiceWidget.defaults = {
        width: 300,
        height: 250,
        configURI: 'json/config.php?',
        fadeTime: 500,
        easeFunc: 'easeInOutExpo',
        easeTime: 750,
        currentTab: 'tab1',
        offsetTab: 'tab1',
        timer: null,
        initTimer: true,
        publisherID: '0000',
        advertID: '0000',
        isIE: null,
        config: {
            publisher: '0000',
            publisherName: '',
            style: 'bottom',
            caption: 'Best Rates',
            borderColour: '#333333',
            background: '#003366',
            textColour: '#ffffff',
            details: 'factsheet',
            idle: {
                type: 'slide',
                url: 'json/slide.php?callback=?',
                delay: 4,
                fade: 1,
                start: 1,
                currentSlide: 0
            },
            logo: {
                url: 'http://infochoice.subetha.info/images/infochoice-logo.gif',
                link: 'http://infochoice.subetha.info/',
                target: '_blank'
            },
            options: {
                link: 'http://infochoice.subetha.info/options',
                target: '_blank'
            },
            tabs: []
        },
        slides: []
    };
})(jQuery);

