jQuery(document).ready(function($) {
    var zoneWindow = new Array(), zoneTray = new Array(), zoneWrapper = new Array(), zoneItems = new Array(), currTop = new Array(), currBase = new Array(), currItemTop = new Array(), currItemBase = new Array(), currIdxTop = new Array(), currIdxBase = new Array(), defTop = new Array(), itemTemp, itemSize = new Array(), contWidth = new Array(), windowSize = new Array(), sizeProp = new Array(), posProp = new Array(), floatProp = new Array(), itemCount = new Array(), totalItems = new Array(), itemSrc, itemWidth, itemHeight, itemUrl, itemAlt, itemType, itemTarget, itemZone, moveSize, nextItem, y, rPause = new Array(), rRunning, visLoaded = new Array(), itemClasses, itemCLength, zoneTimer = new Array(), rSpool = new Array(), parentWidth, alignOffset, zoneWidth, itemOffset, itemOffsetTop, itemWidthFull = new Array(), itemHeightFull = new Array(), itemWidest = new Array(), itemTallest = new Array(), bWrap = new Array(), bWrapHeight = new Array(), bWrapWidth = new Array();

    jQuery.ablend = {

        postLoad: function(zoneId, itemId, animateIt, firstLoad) {
            if (animateIt == true && abAds[itemId][9] == false) { $.ablend.rAnimate(zoneId) }
            if (firstLoad == true && abAds[itemId][9] == false) {
                if (visLoaded[zoneId] < abZones[zoneId][6]) {
                    visLoaded[zoneId]++;
                }
                if (visLoaded[zoneId] == abZones[zoneId][6] || visLoaded[zoneId] == totalItems[zoneId]) {
                    $(zoneItems[zoneId]).fadeIn();
                }
            }
            abAds[itemId][9] = true;
        },

        loadItem: function(zoneId, itemId, animateIt, firstLoad) {
            if (abAds[itemId][9] == true && animateIt == true) { $.ablend.rAnimate(zoneId); }
            if (abAds[itemId][9] == false) {
                itemSrc = abAds[itemId][2];
                itemWidth = abAds[itemId][3];
                itemHeight = abAds[itemId][4];
                itemUrl = abAds[itemId][5];
                itemAlt = abAds[itemId][6];
                itemType = abAds[itemId][7];
                itemTarget = abAds[itemId][8];
                itemOffset = '0px';
                if (abZones[zoneId][13] == 'right' && bWrapWidth[itemId] < itemWidest[zoneId]) {
                    itemOffset = (itemWidest[zoneId] - bWrapWidth[itemId]) + 'px';
                }
                if (abZones[zoneId][13] == 'center' && bWrapWidth[itemId] < itemWidest[zoneId]) {
                    itemOffset = ((Math.round(itemWidest[zoneId] / 2)) - (Math.round(bWrapWidth[itemId] / 2))) + 'px';
                }
                if (abZones[zoneId][13] == 'left' || itemOffset == 'NaNpx') {
                    itemOffset = '0px';
                }
                itemOffsetTop = '0px';
                if (bWrapHeight[itemId] < itemTallest[zoneId] && abZones[zoneId][1] > 0) {
                    itemOffsetTop = ((Math.round(itemTallest[zoneId] / 2)) - (Math.round(bWrapHeight[itemId] / 2))) + 'px';
                }
                var thisItem = $('.BP_AdBlender_AreaName_' + abZones[zoneId][0] + ' .AdZone_' + abZones[zoneId][0] + ' > .zoneTray_' + abZones[zoneId][0] + ' > .id' + itemId + ' > .bwrap' + itemId).css({ 'position': 'relative', 'left': itemOffset, 'top': itemOffsetTop });
                if (itemType == 'image') {
                    $(thisItem).append('<a class="a' + itemId + '" href="' + itemUrl + '"> </a>');
                    var img = new Image();
                    $(img).load(function() {
                        $.ablend.postLoad(zoneId, itemId, animateIt, firstLoad);
                    }).css({ width: itemWidth + 'px', height: itemHeight + 'px', border: 'none' }).attr('alt', itemAlt).error(function() {
                        $.ablend.postLoad(zoneId, itemId, animateIt, firstLoad);
                    }).attr('src', itemSrc);
                    $('.a' + itemId).append(img).bind("click", function() {
                        $(this).attr('href', baseUrl + '/tabid/' + tabId + '/abfclick/true/abbid/' + abAds[itemId][0] + '/abcid/' + abAds[itemId][12] + '/abaid/' + abAds[itemId][13] + '/bpn/' + abZones[zoneId][14] + '/ps/' + abAds[itemId][14] + '/Default.aspx').attr('target', itemTarget);
                    });
                }
                if (itemType == 'text') {
                    $(zoneItems[zoneId]).filter('.id' + itemId).load(itemSrc, function() {
                        $.ablend.postLoad(zoneId, itemId, animateIt, firstLoad);
                        $(this).find('a').each(function(k) {
                            $(this).bind('click', function() {
                                var tagUrl = $(this).attr('href');
                                $(this).attr('href', baseUrl + '/tabid/' + tabId + '/abfclick/true/abbid/' + abAds[itemId][0] + '/abcid/' + abAds[itemId][12] + '/abaid/' + abAds[itemId][13] + '/bpn/' + abZones[zoneId][14] + '/ps/' + abAds[itemId][14] + '/bt/text/Default.aspx?tagUrl=' + encodeURIComponent(tagUrl));
                            });
                        });
                    });
                    $.ablend.postLoad(zoneId, itemId, animateIt, firstLoad);
                }
                if (itemType == 'flash') {
                    if ($.flash.available) {
                        $(thisItem).flash({
                            swf: itemSrc,
                            width: itemWidth,
                            height: itemHeight,
                            flashvars: {
                                clickTAG: baseUrl + '/tabid/' + tabId + '/abfclick/true/abbid/' + abAds[itemId][0] + '/abcid/' + abAds[itemId][12] + '/abaid/' + abAds[itemId][13] + '/bpn/' + abZones[zoneId][14] + '/ps/' + abAds[itemId][14] + '/Default.aspx',
                                clickTARGET: itemTarget
                            },
                            params: {
                                wmode: 'opaque'
                            }
                        });
                        $.ablend.postLoad(zoneId, itemId, animateIt, firstLoad);
                    } else {
                        $(thisItem).append('<a class="a' + itemId + '" href="' + itemUrl + '"> </a>');
                        var img = new Image();
                        $(img).load(function() {
                            $.ablend.postLoad(zoneId, itemId, animateIt, firstLoad);
                        }).css({ width: itemWidth + 'px', height: itemHeight + 'px', border: 'none' }).attr('alt', itemAlt).error(function() {
                            $.ablend.postLoad(zoneId, itemId, animateIt, firstLoad);
                        }).attr('src', abAds[itemId][10]);
                        $('.a' + itemId).append(img).bind("click", function() {
                            $(this).attr('href', baseUrl + '/tabid/' + tabId + '/abfclick/true/abbid/' + abAds[itemId][0] + '/abcid/' + abAds[itemId][12] + '/abaid/' + abAds[itemId][13] + '/bpn/' + abZones[zoneId][14] + '/ps/' + abAds[itemId][14] + '/Default.aspx').attr('target', itemTarget);
                        });
                    }
                }
                /*if (isEditor == true){
                $.ablend.abAddTip(zoneId,itemId);
                }*/
            }
        },

        autoRotate: function(rZone) {
            setInterval(function() {
                if (rRunning != true) {
                    $.ablend.abRotate(rZone);
                }
                else {
                    if (rSpool.length < abZones.length && $.inArray(rZone, rSpool) == -1) {
                        rSpool.push(rZone);
                    }
                }
            }, abZones[rZone][1]);
        },

        getOffset: function(zoneId) {
            var widthObject = $(zoneWrapper[zoneId]).parent();
            parentWidth = $(widthObject).width();
            if (abZones[zoneId][9]) {
                var zoneFullWidth = abZones[zoneId][7] + (parseInt($(zoneWrapper[zoneId]).css('borderLeftWidth')) || 0) + (parseInt($(zoneWrapper[zoneId]).css('borderRightWidth')) || 0);
            }
            else {
                var zoneFullWidth = (itemSize[zoneId] * abZones[zoneId][6]) + (parseInt($(zoneWrapper[zoneId]).css('borderLeftWidth')) || 0) + (parseInt($(zoneWrapper[zoneId]).css('borderRightWidth')) || 0);
            }
            if (abZones[zoneId][12] == 'right') {
                alignOffset = (parentWidth - zoneFullWidth) + 'px';
            }
            if (abZones[zoneId][12] == 'center') {
                alignOffset = ((Math.round(parentWidth / 2)) - (Math.round(zoneFullWidth / 2))) + 'px';
            }
            if (abZones[zoneId][12] == 'left' || alignOffset == 'NaNpx') {
                alignOffset = '0px';
            }
            return alignOffset;
        },
        /*
        abAddTip: function (zoneId,itemId,itemWidth){
        $('.AdZone_'+ abZones[zoneId][0]+' div .id'+itemId).qtip({
        content: '<a href="#" class="ab_button ab_edit'+ itemId +'" style="margin-right:5px;"><img src="'+baseUrl+'/DesktopModules/BP_AdBlender/edit.gif" border="0" /></a><a href="#" class="ab_button ab_stats'+ itemId +'"><img src="'+baseUrl+'/DesktopModules/BP_AdBlender/stats.gif" border="0" /></a>',
        show: { when: 'mouseover', delay: 0},
        hide:  { when: 'mouseout', fixed: true },
        style: 'editoptions',
        position: {
        corner: {
        target: 'topLeft',
        tooltip: 'topLeft'
        }
        },
        api: {
        onShow: function(){
        $('.ab_edit'+itemId).bind('click', function(){
        ows.Fetch(abZones[zoneId][14],0,'abmode=campaigns&bpsubmode=banners&advid='+abAds[itemId][13]+'&campaignid='+abAds[itemId][12]+'&bpaction=edit&bannerid='+abAds[itemId][0],'dummyBox');	
        return false;
        });
        $('.ab_stats'+itemId).bind('click', function(){
        ows.Fetch(abZones[zoneId][14],0,'abmode=statistics&bpaction=gostats&campaignid='+abAds[itemId][12],'dummyBox');
        return false;
        });
        $('.qtip').mouseover(function(){
        rPause[zoneId] = true;
        }).mouseout(function(){
        rPause[zoneId] = false;
        });
        }
        }

	});
},
        */
        abAdsinit: function() {
            //if (isEditor == true) {
            //    $.fn.qtip.styles.editoptions = { // Last part is the name of the style
            //        background: 'none',
            //        padding: 5,
            //        backgroundImage: 'url(' + baseUrl + '/DesktopModules/BP_AdBlender/ab_btn_bg.gif)',
            //        color: 'white',
            //        textAlign: 'right',
            //        border: 0
            //    }
            //}
            $.each(abZones, function(i, zone) {
                zoneWrapper[i] = $('.BP_AdBlender_AreaName_' + zone[0]);
                $(zoneWrapper[i]).html('<div class="AdZone_' + zone[0] + '" style="overflow: hidden; position: relative; z-index: 2;"><div class="zoneTray_' + zone[0] + '" style="margin:0; padding:0; position:relative; width:1px;"></div></div>').attr('style', zone[4]);
                zoneWindow[i] = $('.BP_AdBlender_AreaName_' + zone[0] + ' > div');
                zoneTray[i] = $('.BP_AdBlender_AreaName_' + zone[0] + ' .AdZone_' + zone[0] + ' > .zoneTray_' + zone[0]);
                sizeProp[i] = zone[9] ? 'height' : 'width';
                posProp[i] = zone[9] ? 'top' : 'left';
                itemCount[i] = 0;
                totalItems[i] = 0;
                contWidth[i] = 0;
                itemWidest[i] = 0;
                itemTallest[i] = 0;
                $.each(abAds, function(p, ad) {
                    if (zone[0] == ad[1] && itemCount[i] < zone[6]) {
                        itemCount[i]++;
                    }
                    if (zone[0] == ad[1]) {
                        if (zone[1] > 0 || (zone[1] == 0 && totalItems[i] < zone[6])) {
                            $(zoneTray[i]).append('<div class="BP_AdBlender_Item id' + p + '" style="z-index: 1; margin:0; padding:0; position:relative; float:left; display:none;' + zone[5] + '"><div class="bwrap' + p + '" style="width:' + ad[3] + 'px; height:' + ad[4] + 'px;' + zone[15] + '"></div></div>');
                            if (zone[1] > 0) {
                                itemWidthFull[p] = zone[7];
                                itemHeightFull[p] = zone[8];
                            }
                            if (zone[1] == 0) {
                                itemWidthFull[p] = ad[3];
                                itemHeightFull[p] = ad[4];
                            }
                            itemTemp = $('.AdZone_' + zone[0] + ' div .id' + p).show();
                            bWrap[p] = $(itemTemp).children();
                            bWrapWidth[p] = $(bWrap[p]).outerWidth() + (parseInt($(bWrap[p]).css('marginLeft')) || 0) + (parseInt($(bWrap[p]).css('marginRight')) || 0);
                            bWrapHeight[p] = $(bWrap[p]).outerHeight() + (parseInt($(bWrap[p]).css('marginTop')) || 0) + (parseInt($(bWrap[p]).css('marginBottom')) || 0);

                            if (bWrapWidth[p] > itemWidthFull[p]) {
                                itemWidthFull[p] = bWrapWidth[p];
                            }
                            if (bWrapHeight[p] > itemHeightFull[p]) {
                                itemHeightFull[p] = bWrapHeight[p];
                            }
                            if (itemWidthFull[p] > itemWidest[i]) {
                                itemWidest[i] = itemWidthFull[p];
                            }
                            if (itemHeightFull[p] > itemTallest[i]) {
                                itemTallest[i] = itemHeightFull[p];
                            }
                            $(itemTemp).css({ width: itemWidthFull[p] + 'px', height: itemHeightFull[p] + 'px' });
                            var tW = $(itemTemp).outerWidth() + (parseInt($(itemTemp).css('marginLeft')) || 0) + (parseInt($(itemTemp).css('marginRight')) || 0);
                            if (contWidth[i] < tW) {
                                contWidth[i] = tW;
                            }
                            $(itemTemp).hide();
                            totalItems[i]++;
                        }
                    }
                });
                $.each(abAds, function(d, adRes) {
                    if (zone[0] == adRes[1]) {
                        if (itemWidthFull[d] < itemWidest[i] && (zone[1] > 0 || zone[9])) {
                            $(bWrap[d]).parent().css('width', itemWidest[i] + 'px');
                        }
                        if (itemHeightFull[d] < itemTallest[i] && (zone[1] > 0 || zone[9] == false)) {
                            $(bWrap[d]).parent().css('height', itemTallest[i] + 'px');
                        }
                    }
                });
                itemSize[i] = zone[9] ? $(itemTemp).outerHeight() + (parseInt($(itemTemp).css('marginTop')) || 0) + (parseInt($(itemTemp).css('marginBottom')) || 0)
			: $(itemTemp).outerWidth() + (parseInt($(itemTemp).css('marginLeft')) || 0) + (parseInt($(itemTemp).css('marginRight')) || 0);
                //if (zone[1] > 0){
                windowSize[i] = itemSize[i] * zone[6];
                var holdMe = windowSize[i] + 'px';
                if (holdMe == 'undefinedpx' || holdMe == 'NaNpx') { holdMe = ''; }
                $(zoneWindow[i]).css(sizeProp[i], holdMe);
                //}
                if (zone[9]) {
                    var zoneWidth = contWidth[i] + 'px';
                }
                else {
                    var zoneWidth = (contWidth[i] * zone[6]) + 'px';
                }
                $(zoneWrapper[i]).css({ 'width': zoneWidth, 'position': 'relative', 'left': '0px' });
                rRunning = false;
                rPause[i] = false;

                if (zone[1] == 0) {
                    if (posProp[i] == 'left') {
                        //var initWidth = ((zone[6]*3)+((totalItems[i]-zone[6])*2))*itemSize[i]+'px';
                        var initWidth = itemSize[i] * zone[6] + 'px';
                        $(zoneTray[i]).css({ 'left': '0px', 'width': initWidth });
                    }
                    if (posProp[i] == 'top') {
                        var initWidth = zone[7];
                        $(zoneTray[i]).css({ 'top': '0px', 'width': initWidth });
                    }
                }
                /* if auto rotation */
                if (zone[1] > 0 && totalItems[i] >= zone[6]) {
                    zoneItems[i] = $(zoneTray[i]).children();
                    $(zoneItems[i]).slice(0, zone[6] + (zoneItems[i].length - zone[6])).clone().prependTo(zoneTray[i]);
                    $(zoneItems[i]).slice(0, zone[6]).clone().appendTo(zoneTray[i]);
                    defTop[i] = itemSize[i] * (zone[6] + (zoneItems[i].length - zone[6]));
                    var initTop = '-' + defTop[i] + 'px';
                    if (posProp[i] == 'left') {
                        var initWidth = ((zone[6] * 3) + ((totalItems[i] - zone[6]) * 2)) * itemSize[i] + 'px';
                        $(zoneTray[i]).css({ 'left': initTop, 'width': initWidth });
                    }
                    else {
                        var initWidth = zone[7];
                        $(zoneTray[i]).css({ 'top': initTop, 'width': initWidth });
                    }
                    $(zoneWindow[i]).mouseover(function() {
                        rPause[i] = true;
                    }).mouseout(function() {
                        rPause[i] = false;
                    });
                    currTop[i] = zone[6] + (zoneItems[i].length - zone[6]);
                    currBase[i] = currTop[i] + (zone[6] - 1);
                    $.ablend.autoRotate(i);
                }
                /* -- */
                zoneItems[i] = $(zoneTray[i]).children();
                y = 0;
                visLoaded[i] = 0;
                $.each(abAds, function(z, adLoad) {
                    if (zone[0] == adLoad[1] && y < zone[6]) {
                        $.ablend.loadItem(i, z, false, true);
                        y++;
                    }
                });
            });
        },

        rReset: function(rZone) {
            if (posProp[rZone] == 'left' && ($(zoneTray[rZone]).css('left') == '0px' || $(zoneTray[rZone]).css('left') == '-' + ((zoneItems[rZone].length - abZones[rZone][6]) * itemSize[rZone]) + 'px')) {
                $(zoneTray[rZone]).css('left', '-' + defTop[rZone] + 'px');
            }
            if (posProp[rZone] == 'top' && ($(zoneTray[rZone]).css('top') == '0px' || $(zoneTray[rZone]).css('top') == '-' + ((zoneItems[rZone].length - abZones[rZone][6]) * itemSize[rZone]) + 'px')) {
                $(zoneTray[rZone]).css('top', '-' + defTop[rZone] + 'px');
            }
        },

        rGetId: function(rZone, aPos) {
            if (aPos < 0) {
                aPos = (zoneItems[rZone].length) - 1;
            }
            if (aPos > zoneItems[rZone].length - 1) {
                aPos = 0;
            }
            itemClasses = $(zoneItems[rZone][aPos]).attr('class');
            //alert( itemClasses );
            itemCLength = itemClasses.length;
            return parseInt(itemClasses.substring(20, itemCLength));
        },

        rAnimPost: function(rZone) {
            if (abZones[rZone][11] == 'down') {
                $.ablend.rReset(rZone);

                if (currBase[rZone] < zoneItems[rZone].length) {
                    currTop[rZone]++;
                    currBase[rZone]++;
                }
                if (currBase[rZone] >= zoneItems[rZone].length) {
                    currTop[rZone] = zoneItems[rZone].length - 2;
                    currBase[rZone] = 0;
                }

                rRunning = false;
                if (rSpool.length > 0) {
                    $.ablend.abRotate(rSpool.shift());
                }
            }
            if (abZones[rZone][11] == 'up') {
                $.ablend.rReset(rZone);

                if (currTop[rZone] > 0) {
                    currTop[rZone]--;
                    currBase[rZone]--;
                }
                if (currTop[rZone] <= 0) {
                    currTop[rZone] = zoneItems[rZone].length;
                    currBase[rZone] = abZones[rZone][6] - 2;
                }

                rRunning = false;
                if (rSpool.length > 0) {
                    $.ablend.abRotate(rSpool.shift());
                }
            }
            currIdxTop[rZone] = Math.abs(parseInt($(zoneTray[rZone]).css(posProp[rZone]))) / itemSize[rZone];
            currIdxBase[rZone] = currIdxTop[rZone] + (abZones[rZone][6] - 1);

        },

        rAnimate: function(rZone) {
            if (abZones[rZone][11] == 'down') {
                moveSize = '-=' + itemSize[rZone] + 'px';
            }
            if (abZones[rZone][11] == 'up') {
                moveSize = '+=' + itemSize[rZone] + 'px';
            }
            if (abZones[rZone][10] == 'slide') {
                $(zoneTray[rZone]).animate(posProp[rZone] == "left" ? { left: moveSize} : { top: moveSize }, abZones[rZone][2], abZones[rZone][3], function() { $.ablend.rAnimPost(rZone) });
            }
            if (abZones[rZone][10] == 'fade') {
                $(zoneItems[rZone]).each(function(idx) {
                    if (idx >= currIdxTop[rZone] & idx <= currIdxBase[rZone]) {
                        var thisItemID = $.ablend.rGetId(rZone, idx);
                        if (abAds[thisItemID][7] == 'flash') {
                            var thisItem = $('.bwrap' + thisItemID, zoneItems[rZone][idx]);
                            $(thisItem).flash(
						function() {
						    this.StopPlay();
						});
                        };
                    }
                });
                $(zoneTray[rZone]).fadeOut(Math.round(abZones[rZone][2] / 2)).animate(posProp[rZone] == "left" ? { left: moveSize} : { top: moveSize }, 0, function() { $.ablend.rAnimPost(rZone) }).fadeIn(Math.round(abZones[rZone][2] / 2));
            }
        },

        abRotate: function(rZone) {
            if (rPause[rZone] != true && rRunning != true) {
                rRunning = true;
                if (itemCount[rZone] <= totalItems[rZone]) {
                    if (currIdxTop[rZone] == undefined) {
                        currIdxTop[rZone] = Math.abs(parseInt($(zoneTray[rZone]).css(posProp[rZone]))) / itemSize[rZone];
                        currIdxBase[rZone] = currIdxTop[rZone] + (abZones[rZone][6] - 1);
                    }
                    if (abZones[rZone][11] == 'down') {
                        var nextItemID = $.ablend.rGetId(rZone, currIdxBase[rZone] + 1);
                        var lastItemID = $.ablend.rGetId(rZone, currIdxTop[rZone]);
                        if (abAds[lastItemID][7] == 'flash') {
                            var itemIdx = currIdxTop[rZone];
                            var thisItem = $('.bwrap' + lastItemID, zoneItems[rZone][itemIdx]);
                            $(thisItem).flash(
						function() {
						    this.StopPlay();
						});
                        }
                        if (abAds[nextItemID][7] == 'flash') {
                            var itemIdx = currIdxBase[rZone] + 1;
                            var thisItem = $('.bwrap' + nextItemID, zoneItems[rZone][itemIdx]);
                            $(thisItem).flash(
						function() {
						    this.GotoFrame(0);
						    this.Play();
						});
                        }
                        $.ablend.loadItem(rZone, nextItemID, true);
                    }
                    if (abZones[rZone][11] == 'up') {
                        var nextItemID = $.ablend.rGetId(rZone, currIdxTop[rZone] - 1);
                        var lastItemID = $.ablend.rGetId(rZone, currIdxBase[rZone]);
                        //if(abAds[lastItemID][7] == 'flash'){alert('flash going out');}
                        //if(abAds[nextItemID][7] == 'flash'){alert('flash approaching');}
                        $.ablend.loadItem(rZone, nextItemID, true);
                    }
                }
            }
        }

    };
    $.ablend.abAdsinit();
});
