﻿var $ = jQuery.noConflict();
var newsExtended = false;

function ModuleExtender(moduleId) {
    var zoneId = $("#" + moduleId).attr('zoneid');
    var btnExtenderUp = "Images/extender-up.png";
    var btnExtenderDown = "Images/extender-down.png";
    var lch = $("#" + zoneId).height();
    var lcHeight = 0;
    var extended = $("#" + moduleId).attr('status');
    if (extended == "0") {
        lch = $("#" + zoneId).height();
        lcHeight = (lch + 200) + "px";

        if (moduleId == 'RelatedContentModule') {
            $("#" + moduleId + " div.RelatedContentBox").css({ 'height': '344px' });
        }
        else {
            $("#" + moduleId + " div.NewsBox").css({ 'height': '640px' });
        }

        
        $("#btnNewsExtender" + moduleId).attr({ 'src': btnExtenderUp });
        //$("#" + moduleId + " div.ModuleHeadlineBoxHidden").css({ 'visibility': 'visible' });
        //$("#" + moduleId + " div.ModuleHeadlineBoxHidden").show();

        $("div.ModuleHeadlineBox").each(function(i, o) {
            var itemid = o.id;
            var statustype = $("#" + itemid).attr('type');
            var parentid = $("#" + itemid).attr('parentid');
            if (parentid == moduleId && statustype=="hidden") {
                $("#" + itemid).css({ 'visibility': 'visible' });
                $("#" + itemid).show();
            }
        });
        //$("#LeftColumn").css({ 'height': lcHeight });
        //$("#MiddleColumn").css({ 'height': lcHeight });
        //$("#RightColumn").css({ 'height': lcHeight });
        $("#" + moduleId).attr({ 'status': '1' });
        setTall();
    }
    else {

        //$("#" + moduleId + " div.ModuleHeadlineBoxHidden").css({ 'visibility': 'hidden' });
        $("div.ModuleHeadlineBox").each(function(i, o) {
            var itemid = o.id;
            var statustype = $("#" + itemid).attr('type');
            var parentid = $("#" + itemid).attr('parentid');
            if (parentid == moduleId && statustype == "hidden") {
                $("#" + itemid).css({ 'visibility': 'hidden' });
                $("#" + itemid).hide();
            }
        });
        lch = $("#" + zoneId).height();
        lcHeight = (lch - 320) + "px";

        if (moduleId == 'RelatedContentModule') {
            $("#" + moduleId + " div.RelatedContentBox").css({ 'height': '172px' });
        }
        else {
            $("#" + moduleId + " div.NewsBox").css({ 'height': '360px' });
        }

        $("#btnNewsExtender" + moduleId).attr({ 'src': btnExtenderDown });
        //$("#LeftColumn").css({ 'height': lcHeight });
        //$("#MiddleColumn").css({ 'height': lcHeight });
        //$("#RightColumn").css({ 'height': lcHeight });
        $("#" + moduleId).attr({ 'status': '0' });
        setTall();

    }
}

function LoadInitialChartRotators() {
    $.jheartbeat.set({
        url: "Handlers/Handler.aspx?op=loadhomecontentrotators",
        delay: 5000,
        div_id: "test_div"
    }, function() {

        RotateCharts();
    });
}

function RotateCharts() {
    var html = $("#test_div div.KeyRankingModule").html();
    var html2 = $("#test_div div.KeyPatternModule").html();
    var html3 = $("#test_div div.LeagueFormTableModule").html();

    $("div.KeyRankingsBox").html(html);
    $("div.KeyPatternsBox").html(html2);
    $("div.FormTablesBox").html(html3);
    resizeVerticalBarCharts();
    $('div.KeyRankingsBox div.ModuleHeadlineBox div.ModuleHeadlineContent div.HeadlineBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");
    $('div.KeyPatternsBox div.ModuleHeadlineBox div.ModuleHeadlineContent div.HeadlineBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");
    $('div.FormTablesBox div.ModuleHeadlineBox div.ModuleHeadlineContent div.HeadlineBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");
    formatClickables();
}

function LoadInitialKeyRankings() {
    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=loadkeyrankings",
        data: "none",
        error: function(req, json) {

            //alert('ER');
        },
        success: function(html) {
            $("div.KeyRankingsBox").html(html);

            $('div.KeyRankingsBox div.ModuleHeadlineBox div.ModuleHeadlineContent div.HeadlineBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");

            formatClickables();
            //StartKeyRankingRotator();
            return;
        }
    });
}

function LoadInitialFormTable() {
    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=loadformtable",
        data: "none",
        error: function(req, json) {

            //alert('ER');
        },
        success: function(html) {
            $("div.FormTablesBox").html(html);

            $('div.FormTablesBox div.ModuleHeadlineBox div.ModuleHeadlineContent div.HeadlineBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");

            formatClickables();
            //StartKeyRankingRotator();
            return;
        }
    });
}

function LoadInitialKeyPatterns() {
    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=loadkeypatterns",
        data: "none",
        error: function(req, json) {

            //alert('ER');
        },
        success: function(html) {
            $("div.KeyPatternsBox").html(html);
            resizeVerticalBarCharts();
            $('div.KeyPatternsBox div.ModuleHeadlineBox div.ModuleHeadlineContent div.HeadlineBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");
            formatClickables();
            return;
        }
    });
}

function StartKeyRankingRotator() {
    $.jheartbeat.set({
        url: "Handlers/Handler.aspx?op=loadkeyrankings",
        delay: 10000,
        div_id: "test_div"
    }, function() {

        RotateKeyRankings();
    });
}

function StartKeyPatternRotator() {
    $.jheartbeat.set({
        url: "Handlers/Handler.aspx?op=loadkeypatterns",
        delay: 10000,
        div_id: "test_div2"
    }, function() {

        RotateKeyPatterns();
    });
}

function RotateKeyRankings() {
    var html = $("#test_div").html();
    $("div.KeyRankingsBox").html(html);
    formatClickables();
}

function RotateKeyPatterns() {
    var html = $("#test_div2").html();
    $("div.KeyPatternsBox").html(html);
    formatClickables();
}

function LoadMouseOvers() {
    $("div.FooterMenuItem").mouseover(function() {
        $(this).addClass("FooterMenuItemHover");
    }).mouseout(function() {
        $(this).removeClass("FooterMenuItemHover");
    });
}

function formatRows(theDraggable) {
    var hoverClass = "FooterMenuItemHover";
    $(theDraggable).mouseover(function() {
        $(this).addClass(hoverClass);
    }).mouseout(function() {
        $(this).removeClass(hoverClass);
    });
}

function formatTopRows(theDraggable) {
    var hoverClass = "TopMenuItemHover";
    $(theDraggable).mouseover(function() {
        $(this).addClass(hoverClass);
        changeIcon(this, 'up', null);
    }).mouseout(function() {
        $(this).removeClass(hoverClass);
        changeIcon(this, 'over', null);

    });
}

function changeIcon(theDraggable, upover, elementId) {
    var divId;
    if (elementId == null) {
        divId = theDraggable.id;
    }
    else {
        divId = elementId;
    }
    var btnId = "img_" + divId;
    var icon1 = $("#" + btnId).attr('src');
    var icon2 = "";

    if (upover == "up") {
        icon2 = icon1.replace('up', 'over');
    }
    else {
        icon2 = icon1.replace('over', 'up');
    }
    $("#" + btnId).attr({ 'src': icon2 });
}

function formatHeadlineRows(theDraggable) {
    var hoverClass = "HeadlineBoxHover";
    var _class = "HeadlineBox";
    
    var id = theDraggable.id;
    
    $("#" + id).mouseover(function() {
        $("#" + id).removeClass(_class).addClass(hoverClass);
    }).mouseout(function() {
        $("#" + id).removeClass(hoverClass).addClass(_class);
    });
}

function formatClickables() {

    $('div.FooterMenuItem').each(function(i, o) {
        $("#" + o.id).unbind("click").bind("click", function(e) {
            GoTo(o.id);
        });
    });

    $('div.TopMenuItem').each(function(i, o) {
        $("#" + o.id).unbind("click").bind("click", function(e) {
            GoTo(o.id);
        });
    });

    $('a.popup').each(function(i, o) {
        $("#" + o.id).unbind("click").bind("click", function(e) {
        GoToAnchor(o.id);
        });
    });

//    $('div.Headline').each(function(i, o) {
//        $("#" + o.id).unbind("click").bind("click", function(e) {
//            GoTo(o.id);
//        });
    //    });


//    $('div.ModuleMore').each(function(i, o) {
//        $("#" + o.id).unbind("click").bind("click", function(e) {
//            GoTo(o.id);
//        });
//    });

//    $('div.HeadlineNodeItem').each(function(i, o) {
//        $("#" + o.id).unbind("click").bind("click", function(e) {
//            GoTo(o.id);
//        });
//    });
}

function formatAccordionMenuClickables() {
    var hrefclass = "";
    $('.onclick').each(function(i, o) {
        var element = "#" + o.id;
        $(element).each(function(i) {
            var $match1 = $(element + " a").eq(i);
            hrefclass = $match1.attr('class');
            if ((hrefclass == "nohref") || (hrefclass == "navButton")) {

            }
            else {
                $(element).unbind("click").bind("click", function(e) {
                    GoToMenu(element);
                });
            }
        });
    });
}

function formatActiveItems() {
    var activeClass = "FooterMenuItemSelected";
    var activeTopClass = "TopMenuItemSelected";
    var currentUrl = $("#currentPage").html();
    var currentPage = currentUrl.replace("p=", "").toLowerCase();

    var href = "";
    $('div.FooterMenuItem').each(function(i, o) {
        var element = "#" + o.id;

        $(element).each(function(i) {
            var $match1 = $(element + " a").eq(i);
            href = $match1.attr('href').toLowerCase();
            if (currentPage == href) {
                $(element).addClass(activeClass);
            }
        });

    });

    $('div.TopMenuItem').each(function(i, o) {
        var element = "#" + o.id;

        $(element).each(function(i) {
            var $match1 = $(element + " a").eq(i);
            href = $match1.attr('href').toLowerCase();
            if (currentPage == href) {
                $(element).addClass(activeTopClass);
                changeIcon(o.id, 'up', o.id);
            }
        });
    });
}

function GoToMenu(elementid) {
    var element = "#" + elementid;

    var href = "";
    var link = "";
    $(element).each(function(i) {
        var $match1 = $(element + " a").eq(i);

        href = $match1.attr('href').toLowerCase();
        link = $match1.attr('link');
    });

    if (link == null) {
        $.jqURL.loc(href);
    }
    else {
        if (link != "noredirect") {
            if (link == "direct") {

                window.open(href, 'BettorLogic', 'width=1080,height=800,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
            }
            else {
                $.jqURL.loc(href);
            }
        }
    }
}

function GoToPage(url) {
    var thisbase = $("#basehref1").attr('href');
    var href = thisbase + url.substring(1, url.length);
    $.jqURL.loc(href);
}

function GoToPagePopup(url) {
    window.open(url, 'BettorLogic', 'width=1080,height=800,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function GoTo(elementid) {
    var hoverClass = "FooterMenuItemHover";
    var hoverTopClass = "TopMenuItemHover";
    var href = "";
    var link = "";
    var element = "#" + elementid;
    var c = "";
    var width = "";
    var height = "";
   
    $(element).each(function(i) {
        var $match1 = $(element + " a").eq(i);
        href = $match1.attr('href').toLowerCase();
        link = $match1.attr('link');
        c = $match1.attr('class');
        width = $match1.attr('width');
        height = $match1.attr('height');
    });

    if (c == 'popup') {
        window.open(href, 'BettorLogic', 'width=' + width +',height=' + height + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
    }
    else {
        if (!(link)) {
            $.jqURL.loc(href);
        }
        else {
            if (link != "noredirect") {
                if (link == "direct") {

                    window.open(href, 'BettorLogic', 'width=1080,height=800,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
                }
                else {
                    $.jqURL.loc(href);
                }
            }
        }
    }
}

function GoToAnchor(elementid) {
    var element = "#" + elementid;
    var href = "";
    var width = "";
    var height = "";

    href = $(element).attr('href').toLowerCase();
    width = $(element).attr('width');
    height = $(element).attr('height');

    window.open(href, 'BettorLogic', 'width=' + width + ',height=' + height + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function RoundElementCorners() {
    $("#MenuContainer").corner("round 5px");
    $('.HeadlineBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");
    $('.HeadlineBoxBlue').corner("round 5px").parent().css('padding', '1px').corner("round 5px");
    $('.HeadlineBoxGreen').corner("round 5px").parent().css('padding', '1px').corner("round 5px");
    $('.ModuleMore').corner("round 5px");
    $('.SummaryItemContentBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");

    //$('.TwoModuleBoxSectionHeadlineBox').corner("round 5px").parent().css('padding', '2px').corner("round 5px");

    $('#articlebodybulletbox').corner("round 5px").parent().css('padding', '2px').corner("round 5px");
}

function LoadPageMenuItems() {
    /*var kr1 = $("div.KeyRankingsBox").height();
    var kp1 = $("div.KeyPatternsBox").height();
    if (kr1 != null || kp1!=null) {
    LoadInitialChartRotators();
    }*/
    
    formatClickables();
    formatActiveItems();
    formatAccordionMenuClickables();
    RoundElementCorners();
}

function resizeVerticalBarCharts() {
    $("table.patterntable tr td").each(function(i) {

        var $match3 = $("table.patterntable tr td img.team1verticalbar").eq(i);
        var barId1 = $match3.attr('id');

        var height1 = $("#" + barId1).attr('barheight');

        var newBarHeight1 = height1 + "px";
        $("#" + barId1).css({ 'height': newBarHeight1 });

        var $match2 = $("table.patterntable tr td img.team2verticalbar").eq(i);
        var barId2 = $match2.attr('id');

        var height2 = $("#" + barId2).attr('barheight');

        var newBarHeight2 = height2 + "px";
        $("#" + barId2).css({ 'height': newBarHeight2 });

    });
}

function setTall() {
    return;
    var menuHeight = $("#MenuBox").height();

    var properheight = 0;
    var pCont = 0;
    var bCont = 0;
    var Conts = 0;
    var m1 = 0;
    var m2 = 0;
    var m3 = 0;
    if (document.getElementById) {
        var forum1 = $("#Forum").height();
        if (forum1 != null) {
            var forumHeight = forum1 + "px";
            pCont = (forumHeight + 270) + "px";
            bCont = (forumHeight + 111) + "px";

            $("#PageContainer").css({ 'height': pCont });
            $("#BodyContainer").css({ 'height': bCont });
        }
        else {            
            var s1 = $(".SummaryItems").height();
            if (s1 != null) {
                var SummaryItemsTotalHeight = 0;
                $('div.SummaryItemBox').each(function(i, o) {
                    SummaryItemsTotalHeight = SummaryItemsTotalHeight + 1;
                });

                SummaryItemsTotalHeight = SummaryItemsTotalHeight * 110;
                var itemsHeightpx = SummaryItemsTotalHeight + "px";
                $(".SummaryItems").css({ 'height': itemsHeightpx });

            }

            var s2 = $(".SummaryGameNoteItems").height();
            if (s2 != null) {
                var SummaryGameItemsTotalHeight = 0;
                $('div.SummaryItemBoxGameNote').each(function(i, o) {
                    var thisHeight = $(o).height();

                    SummaryGameItemsTotalHeight = SummaryGameItemsTotalHeight + thisHeight;
                });

                SummaryGameItemsTotalHeight = SummaryGameItemsTotalHeight + 200;
                var itemsHeightpx = SummaryGameItemsTotalHeight + "px";
                $(".SummaryGameNoteItems").css({ 'height': itemsHeightpx });
            }

            var s3 = $("#formView").height();
            if (s3 != null) {
                var itemsHeightpx = s3 + "px";
                itemsHeightpx = itemsHeightpx + 20;
                $("#ArticleBody").css({ 'height': itemsHeightpx });
            }

            m1 = $("#MenuBox").height();
            m2 = $("#TwoModuleBox").height();

            if (m1 == null) { // For Homepage

                m1 = $("#LeftColumn").height();

                m2 = $("#MiddleColumn").height();
                m3 = $("#RightColumn").height();
                
                if (m1 > m2) {
                    properheight = m1;
                }
                else {
                    properheight = m2;
                }

                if (properheight < m3) {
                    properheight = m3;
                }
                pCont = (properheight + 270) + "px";
                bCont = (properheight + 111) + "px";
                Conts = (properheight + 60) + "px";
                $("#PageContainer").css({ 'height': pCont });
                $("#BodyContainer").css({ 'height': bCont });
                $(".containers").css({ 'height': Conts });
                $(".twocolcontainers").css({ 'height': Conts });
            }
            else {
                var relatedContentHeight = $("#RelatedContentModule").height();
                if (relatedContentHeight != null)
                    m1 = m1 + relatedContentHeight;

                if (m1 > m2) {
                    properheight = m1;
                }
                else {
                    properheight = m2;
                }

                pCont = (properheight + 300) + "px";
                bCont = (properheight + 141) + "px";
                Conts = (properheight + 100) + "px";
                $("#PageContainer").css({ 'height': pCont });
                $("#BodyContainer").css({ 'height': bCont });
                $(".containers").css({ 'height': Conts });
                $(".twocolcontainers").css({ 'height': Conts });
            }
        }
    }
}

// Floating drop zone image logic
function registerFloater() {
    var slideTime = 700;
    var topMargin = 0;
    winOnResize(); // set initial position
    xAddEventListener(window, 'resize', winOnResize, false);
    xAddEventListener(window, 'scroll', winOnScroll, false);
    return;
}
function winOnResize() {
    var slideTime = 700;
    var topMargin = 0;
    xMoveTo('toolbarmenu', 0, topMargin);
    xShow('toolbarmenu');
    winOnScroll(); // initial slide
}
function winOnScroll() {
    var slideTime = 700;
    var topMargin = 0;
    xSlideTo('toolbarmenu', xLeft('toolbarmenu'), xScrollTop() + topMargin, slideTime);
}

function loadListContextMenus() {
    var list = $("div.droppedimage").map(function() {
        var columnId = this.id;
        $("#" + this.id).contextMenu('listMenu', {
            bindings: {
                'delete': function(t) {
                    administerModule('delete', columnId, columnId);
                }
            }, menuStyle: { width: 'auto' }
        });
    });
}

function loadContextMenus() {
    var list = $("div.TwoModuleBoxSectionImage").map(function() {
        var columnId = this.id;
        var zoneId = columnId;
        $("#" + this.id).contextMenu('articleImageMenu', {
            bindings: {
                'edit': function(t) {
                    administerModule('edit', columnId, zoneId);
                },
                'imagebank': function(t) {
                    administerModule('imageBank', columnId, zoneId);
                }
            }, menuStyle: { width: 'auto' }
        });
    });

    var list2 = $("div.TwoModuleBoxSectionArticle").map(function() {
        var columnId = this.id;
        var zoneId = columnId;
        $("#" + this.id).contextMenu('articleEditMenu', {
            bindings: {
                'edit': function(t) {
                    administerModule('editPage', columnId, zoneId);
                },
                'delete': function(t) {
                    administerModule('deletePage', columnId, zoneId);
                }
            }, menuStyle: { width: 'auto' }
        });
    });

    var list3 = $("div.containers").map(function() {
        var columnId = this.id;
        var zoneId = columnId;
        $("#" + this.id).contextMenu('articleSaveMenu', {
            bindings: {
                'pageproperties': function(t) {
                    administerModule('pageProperties', columnId, zoneId);
                },
                'related': function(t) {
                    administerModule('relatedContent', columnId, zoneId);
                },
                'save': function(t) {
                    administerModule('savePage', columnId, zoneId);
                },
                'publish': function(t) {
                    administerModule('publishPage', columnId, zoneId);
                }
            }, menuStyle: { width: 'auto' }
        });
    });

    var list4 = $("div.TwoModuleBoxSection").map(function() {
        var columnId = this.id;
        var zoneId = columnId;
        $("#" + this.id).contextMenu('articleAddMenu', {
            bindings: {
                'add': function(t) {
                    administerModule('addPage', columnId, zoneId);
                },
                'showall': function(t) {
                    administerModule('showAllPages', columnId, zoneId);
                },
                'pageproperties': function(t) {
                    administerModule('pageProperties', columnId, zoneId);
                },
                'publishall': function(t) {
                    administerModule('publishAllPages', columnId, zoneId);
                }
            }, menuStyle: { width: 'auto' }
        });
    });

    var list5 = $("div.ArchiveSummaryItemBox").map(function() {
        var columnId = this.id;
        var zoneId = columnId;
        $("#" + this.id).contextMenu('archiveEditMenu', {
            bindings: {
                'editText': function(t) {
                    administerModule('editText', columnId, zoneId);
                },
                'archiveImage': function(t) {
                    administerModule('archiveImage', columnId, zoneId);
                }
            }, menuStyle: { width: 'auto' }
        });
    });
}

function loadHomepageContextMenus() {
    var list4 = $("div.containers").map(function() {
        var itemId = this.id;
        var zoneId = null;
        var moduleType = null;
        $("#" + this.id).contextMenu('ContainersModuleMenu', {
            bindings: {
                'version': function(t) {
                    administerHomepage('version', itemId);
                },
                'sort': function(t) {
                    administerHomepage('sort', itemId);
                },
                'addmodule': function(t) {
                    administerHomepage('addmodule', itemId);
                },
                'pageproperties': function(t) {
                    administerHomepage('pageproperties', itemId);
                },
                'publish': function(t) {
                    administerHomepage('publishPage', itemId);
                }
            }, menuStyle: { width: 'auto' }
        });
    });

    var list5 = $("div.ModuleContainer").map(function() {
        var itemId = this.id;
        var zoneId = $("#" + itemId).attr('zoneid');
        var moduleType = $("#" + itemId).attr('type');
        if (moduleType == "extender" || moduleType == "largeimagemodule") {
            $("#" + this.id).contextMenu('EditModuleMenuWithImage', {
                bindings: {
                    'edit': function(t) {
                        administerHomepageModule('edit', itemId, zoneId, moduleType);
                    },
                    'imagebank': function(t) {
                        administerHomepageModule('imagebank', itemId, zoneId, moduleType);
                    },
                    'delete': function(t) {
                        administerHomepageModule('delete', itemId, zoneId, moduleType);
                    },
                    'publish': function(t) {
                        administerHomepageModule('publishPage', itemId, zoneId, moduleType);
                    }
                }, menuStyle: { width: 'auto' }
            });
        }
        else if ((moduleType == "previewmatchextender") || (moduleType == "betgeniuslatestprices") || (moduleType == "keyrankingsrotator") || (moduleType == "keypatternsrotator" || (moduleType == "formtablemodule"))) {
            $("#" + this.id).contextMenu('DeleteModuleMenu', {
                bindings: {
                    'delete': function(t) {
                        administerHomepageModule('delete', itemId, zoneId, moduleType);
                    },
                    'publish': function(t) {
                        administerHomepageModule('publishPage', itemId, zoneId, moduleType);
                    }
                }, menuStyle: { width: 'auto' }
            });
        }
        else {
            $("#" + this.id).contextMenu('EditModuleMenuWithoutImage', {
                bindings: {
                    'edit': function(t) {
                        administerHomepageModule('editsmall', itemId, zoneId, moduleType);
                    },
                    'delete': function(t) {
                        administerHomepageModule('delete', itemId, zoneId, moduleType);
                    },
                    'publish': function(t) {
                        administerHomepageModule('publishPage', itemId, zoneId, moduleType);
                    }
                }, menuStyle: { width: 'auto' }
            });
        }
    });

    var list6 = $("div.AdvertBox").map(function() {
        var itemId = this.id;
        var zoneId = $("#" + itemId).attr('zoneid');
        var moduleType = $("#" + itemId).attr('type');

        $("#" + itemId).contextMenu('EditModuleMenuWithImage', {
            bindings: {
                'edit': function(t) {
                    administerHomepageModule('edit', itemId, zoneId, moduleType);
                },
                'imagebank': function(t) {
                    administerHomepageModule('imagebank', itemId, zoneId, moduleType);
                },
                'save': function(t) {
                    administerHomepageModule('save', itemId, zoneId, moduleType);
                },
                'pageproperties': function(t) {
                    administerHomepageModule('pageproperties', itemId, zoneId, moduleType);
                },
                'publish': function(t) {
                    administerHomepageModule('publishPage', itemId, zoneId, moduleType);
                }
            }, menuStyle: { width: 'auto' }
        });
    });
}

function AddModule(moduletype, moduleId, zoneId) {

    var thisbase = $("#basehref1").attr('href');
    var thispage = $.jqURL.strip();
    var thisbase = $("#basehref1").attr('href');
    var pagepath = "/" + thispage.replace(thisbase, "");
    pagepath = pagepath.replace("/default.aspx", "");
    pagepath = pagepath.replace(".aspx", "");

    var dataStr = "zoneid=" + zoneId + "&moduletype=" + moduletype + "&pagepath=" + pagepath;

    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=addhomepagemodule",
        data: dataStr,
        error: function(req, json) {

            alert(json);
        },
        success: function(html) {
            $.jqURL.loc(thispage + "?edit=true&version=" + html);
            return;
        }
    });
}

//receiver function
function myCustomFunction(eventObject, eventCode) {

//    setTall();

}

function administerHomepage(action, itemId) {
    switch (action) {
        case "version":
            var pageDetails = "";
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath == pagepath.replace("/default.aspx", "");
            pagepath = pagepath.replace(".aspx", "");
            pageDetails = "pagepath=" + pagepath;

            tb_show("Version Selector", "/Handlers/Handler.aspx?op=pageversionselector&height=600&width=454&modal=false&" + pageDetails);

            break;

        case "addmodule":
            var randomnumber = Math.floor(Math.random() * 1000000);
            var modulename = "addmodule" + randomnumber;

            var html = '<div class="ModuleContainer" id="' + modulename + '" moduletitle="Title" type="" zoneid="' + itemId + '"><div class="ModuleHeadline"><h1>Title</h1></div><div class="ModuleBox"><input type="checkbox" id="chkextender" value="extender" onclick="AddModule(\'extender\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Extender<br /><input type="checkbox" id="chklargeimage" value="largeimagemodule" onclick="AddModule(\'largeimagemodule\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Large Image Module<br /><input type="checkbox" id="chksmallimage" value="smallimagemodule" onclick="AddModule(\'smallimagemodule\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Small Image Module<br /><input type="checkbox" id="chkpreviewmatchextender" value="previewmatchextender" onclick="AddModule(\'previewmatchextender\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Preview Match Extender<br /><input type="checkbox" id="chkbetgeniuslatestprices" value="betgeniuslatestprices" onclick="AddModule(\'betgeniuslatestprices\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Bet Genius Latest Prices<br /><input type="checkbox" id="chkformtablemodule" value="formtablemodule" onclick="AddModule(\'formtablemodule\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Form Tables Rotator<br /><input type="checkbox" id="chkkeyrankingsrotator" value="keyrankingsrotator" onclick="AddModule(\'keyrankingsrotator\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Key Rankings Rotator<br /><input type="checkbox" id="chkkeypatternsrotator" value="keypatternsrotator" onclick="AddModule(\'keypatternsrotator\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Key Patterns Rotator<br /><input type="checkbox" id="chklatestprices" value="latestprices" onclick="AddModule(\'latestprices\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Latest Prices<br /><input type="checkbox" id="chkformlabbox" value="formlabbox" onclick="AddModule(\'formlabbox\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Form Lab Box<br /><input type="checkbox" id="chkplayerprobox" value="playerprobox" onclick="AddModule(\'playerprobox\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Player PRO Box<br /><input type="checkbox" id="chkgeneralbox" value="generalbox" onclick="AddModule(\'generalbox\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />General Box<br /><input type="checkbox" id="chkgamenotesrotator" value="gamenotesrotator" onclick="AddModule(\'gamenotesrotator\',\'' + modulename + '\',\'' + itemId + '\'); return false;" />Game Notes Rotator</div><div class="ModuleFooter"></div></div>';
            var column = $("#" + itemId).html();

            var newHtml = column + html;
            $("#" + itemId).html(newHtml);

            break;

        case "sort":
            var pageDetails = "";
            var version = $.jqURL.get('version');
            if (version == null) {
                version = "";
            }
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath = pagepath.replace("/default.aspx", "");
            pagepath = pagepath.replace(".aspx", "");

            pageDetails = "version=" + version + "&pagepath=" + pagepath;

            tb_show("Homepage Module Sorting", "/Handlers/Handler.aspx?op=homepagesorting&height=400&width=680&modal=false&" + pageDetails);

            break;

        case "pageproperties":
            var pageDetails = "";
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath == pagepath.replace("/default.aspx", "");

            pageDetails = "pagepath=" + pagepath;

            tb_show("Page Properties", "/Handlers/Handler.aspx?op=pageproperties&height=460&width=454&modal=false&" + pageDetails);

            break;

        case "publishPage":
            var version = $.jqURL.get('version');
            if (version == null) {
                version = "";
            }
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath = pagepath.replace("/default.aspx", "");
            pagepath = pagepath.replace(".aspx", "");

            pageDetails = "version=" + version + "&pagepath=" + pagepath;

            tb_show("Publish Properties", "/Handlers/Handler.aspx?op=publishproperties&height=260&width=454&modal=false&" + pageDetails);

            break;
    }
}

function administerHomepageModule(action, itemId, zoneId, moduleType) {
    switch (action) {
        case "edit":
            var pageDetails = "";
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath == pagepath.replace("/default.aspx", "");
            
            if (moduleType.toLowerCase() == "advertboxmodule") {
                var imgsrc = $("#" + itemId + " div.AdvertBoxItem div.AdvertImage img").attr('src');
                imgsrc = imgsrc.replace(thisbase, "");
                var alt = $("#" + itemId + " div.AdvertBoxItem div.AdvertImage img").attr('alt');
                var moduletitle = '';
                pageDetails = "itemid=" + itemId + "&zoneid=" + zoneId + "&moduletype=" + moduleType + "&imagepath=" + imgsrc + "&alt=" + encodeURIComponent(alt) + "&moduletitle=" + encodeURIComponent(moduletitle) + "&pagepath=" + pagepath;

                tb_show(moduleType, "/Handlers/Handler.aspx?op=adverteditor&height=300&width=350&modal=false&" + pageDetails);
            }
            else {
                var imgsrc = $("#" + itemId + " div.ModuleBox div.LargeImageBox img").attr('src');
                imgsrc = imgsrc.replace(thisbase, "");
                var alt = $("#" + itemId + " div.ModuleBox div.LargeImageBox img").attr('alt');
                var moduletitle = $("#" + itemId).attr('moduletitle');
                pageDetails = "itemid=" + itemId + "&zoneid=" + zoneId + "&moduletype=" + moduleType + "&imagepath=" + imgsrc + "&alt=" + encodeURIComponent(alt) + "&moduletitle=" + encodeURIComponent(moduletitle) + "&pagepath=" + pagepath;

                //tb_show(moduleType, "/Handlers/Handler.aspx?op=homepageboxmodule&height=400&width=680&modal=false&" + pageDetails);
                tb_show(moduleType, "/Handlers/Handler.aspx?op=articlemoduleselector&height=600&width=750&modal=false&" + pageDetails);

            }

            break;

        case "delete":
            var pageDetails = "";
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath == pagepath.replace("/default.aspx", "");

            var imgsrc = "";
            imgsrc = imgsrc.replace(thisbase, "");
            var alt = "";
            var moduletitle = $("#" + itemId).attr('moduletitle');
            pageDetails = "itemid=" + itemId + "&zoneid=" + zoneId + "&moduletype=" + moduleType + "&imagepath=" + imgsrc + "&alt=" + encodeURIComponent(alt) + "&moduletitle=" + encodeURIComponent(moduletitle) + "&pagepath=" + pagepath;
            DeleteHomepageModule(thispage, pageDetails);

            break;

        case "editsmall":
            var pageDetails = "";
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath == pagepath.replace("/default.aspx", "");

            if (moduleType.toLowerCase() == "latestprices") {
                var moduletitle = $("#" + itemId).attr('moduletitle'); ;
                pageDetails = "itemid=" + itemId + "&zoneid=" + zoneId + "&moduletype=" + moduleType + "&moduletitle=" + encodeURIComponent(moduletitle) + "&pagepath=" + pagepath;

                tb_show(moduleType, "/Handlers/Handler.aspx?op=latestpriceseditor&height=300&width=350&modal=false&" + pageDetails);
            }
            else if (moduleType.toLowerCase() == "formlabbox") {
                var moduletitle = $("#" + itemId).attr('moduletitle'); ;
                pageDetails = "itemid=" + itemId + "&zoneid=" + zoneId + "&moduletype=" + moduleType + "&moduletitle=" + encodeURIComponent(moduletitle) + "&pagepath=" + pagepath;

                tb_show(moduleType, "/Handlers/Handler.aspx?op=formlabboxeditor&height=300&width=350&modal=false&" + pageDetails);
            }
            else if (moduleType.toLowerCase() == "generalbox") {
                var moduletitle = $("#" + itemId).attr('moduletitle'); ;
                pageDetails = "itemid=" + itemId + "&zoneid=" + zoneId + "&moduletype=" + moduleType + "&moduletitle=" + encodeURIComponent(moduletitle) + "&pagepath=" + pagepath;

                tb_show(moduleType, "/Handlers/Handler.aspx?op=generalboxeditor&height=300&width=350&modal=false&" + pageDetails);
            }
            else {
                var imgsrc = "";
                var alt = "";
                var moduletitle = $("#" + itemId).attr('moduletitle');
                pageDetails = "itemid=" + itemId + "&zoneid=" + zoneId + "&moduletype=" + moduleType + "&imagepath=" + imgsrc + "&alt=" + encodeURIComponent(alt) + "&moduletitle=" + encodeURIComponent(moduletitle) + "&pagepath=" + pagepath;

                //tb_show(moduleType, "/Handlers/Handler.aspx?op=homepageboxmodule&height=400&width=680&modal=false&" + pageDetails);
                tb_show(moduleType, "/Handlers/Handler.aspx?op=articlemoduleselector&height=600&width=750&modal=false&" + pageDetails);
            }

            break;

        case "publishPage":
            var version = $.jqURL.get('version');
            if (version == null) {
                version = "";
            }
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath = pagepath.replace("/default.aspx", "");
            pagepath = pagepath.replace(".aspx", "");

            pageDetails = "version=" + version + "&pagepath=" + pagepath;

            tb_show("Publish Properties", "/Handlers/Handler.aspx?op=publishproperties&height=260&width=454&modal=false&" + pageDetails);

            break;

        case "imagebank":
            UpdateHomeImageFromBank(itemId, zoneId);

            break;
    }
}

function DeleteHomepageModule(thispage, datastr) {
    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=deletehomepagemodule",
        data: datastr,
        error: function(req, json) {

            //alert('ER');
        },
        success: function(html) {
            $.jqURL.loc(thispage + "?edit=true&version=" + html);
            return;
        }
    });
}

function UpdateHomeImageFromBank(itemId, zoneId) {
    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=homeimagebank",
        data: "none",
        error: function(req, json) {

            //alert('ER');
        },
        success: function(html) {
            if (zoneId.toLowerCase() == "topbanner")
                $("#" + itemId + " div.AdvertBoxItem div.AdvertImage").html(html);
            else
                $("#" + itemId + " div.ModuleBox div.LargeImageBox").html(html);

            return;
        }
    });
}

function StoreHomepageImage(imgsrc, alt, parent) {
    if (parent.toLowerCase() == "advertimage") {
        var str = '<img  src="' + imgsrc + '" width="140" height="95" alt="' + alt + '" />';
        $("#" + parent).html(str);
    }
    else {
        var str = '<img  src="' + imgsrc + '" width="292" height="140" alt="' + alt + '" />';
        $("#" + parent).html(str);
    }
}

function StoreArchiveImage(imgsrc, alt, parent) {
    var str = '<a href=""><img src="' + imgsrc + '" width="140" height="95" alt="' + alt + '" /></a>';
    $("#" + parent).html(str);
}

function administerModule(action, columnId, zoneId) {
    switch (action) {
        case "delete":
            var assetId = columnId.replace("SavedArticle", "");
            $("#s_" + assetId).remove();
            $('#Article' + assetId).removeClass('galleryimageInactive');
            selectArticleParent();
            break;

        case "edit":
            UpdateArticleImage(columnId);
            break;

        case "imageBank":
            UpdateArticleImageFromBank(columnId);
            break;

        case "editPage":
            var controlname = $.jqURL.strip();
            var url = controlname + "?edit=true";
            $.jqURL.loc(url);
            break;

        case "editText":
            var pageDetails = "";
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath == pagepath.replace("/default.aspx", "");

            var imgsrc = $("#" + columnId + " div.ArchiveSummaryItemImage img").attr('src');
            imgsrc = imgsrc.replace(thisbase, "");
            var alt = $("#" + columnId + " div.ArchiveSummaryItemImage img").attr('alt');
            var weekid = $("#" + columnId + " div.ArchiveSummaryItemImage").attr('weekid');
            pageDetails = "imagepath=" + imgsrc + "&alt=" + encodeURIComponent(alt) + "&pagepath=" + pagepath + "&pid=" + weekid;

            tb_show("Edit Text", "/Handlers/Handler.aspx?op=archiveeditor&height=300&width=454&modal=false&" + pageDetails);

            break;

        case "addPage":
            tb_show("Select Template", "/Handlers/Handler.aspx?op=selecttemplate&height=300&width=454&modal=false");

//            var controlname = $.jqURL.strip();
//            var url = controlname + "?add=true";
//            $.jqURL.loc(url);
            break;

        case "showAllPages":
            var controlname = $.jqURL.strip();
            var url = controlname + "?showall=true";
            $.jqURL.loc(url);
            break;

        case "deletePage":
            var pageDetails = "";
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath == pagepath.replace("/default.aspx", "");

            pageDetails = "pagepath=" + pagepath;

            var req = $.ajax({
                type: "POST",
                url: "Handlers/Handler.aspx?op=deletepage",
                data: pageDetails,
                error: function(req, json) {
                    alert(json);
                },
                success: function(html) {
                    $.jqURL.loc(html);
                    return;
                }
            });

            break;

        case "publishAllPages":
            var answer = confirm("Are you sure you want to publish All?")
            if (answer) {
                var pageDetails = "";
                var thispage = $.jqURL.strip();

                var thisbase = $("#basehref1").attr('href');
                var pagepath = "/" + thispage.replace(thisbase, "");
                pagepath == pagepath.replace("/default.aspx", "");

                pageDetails = "pagepath=" + pagepath;

                var req = $.ajax({
                    type: "POST",
                    url: "Handlers/Handler.aspx?op=publishallpages",
                    data: pageDetails,
                    error: function(req, json) {
                        alert(json);
                    },
                    success: function(html) {
                        $.jqURL.loc(thispage);
                        return;
                    }
                });
            }

            break;

        case "pageProperties":
            var pageDetails = "";
            var thispage = $.jqURL.strip();

            var newPage = false;
            if ($.jqURL.get('add')) {
                newPage = $.jqURL.get('add');
            }

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath == pagepath.replace("/default.aspx", "");

            pageDetails = "pagepath=" + pagepath + "&isnewpage=" + newPage;

            tb_show("Page Properties", "/Handlers/Handler.aspx?op=pageproperties&height=435&width=454&modal=false&" + pageDetails);

            break;

        case "publishPage":
            var pageDetails = "";
            var version = $.jqURL.get('version');
            if (version == null) {
                version = "";
            }
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath == pagepath.replace("/default.aspx", "");

            pageDetails = "version=" + version + "&pagepath=" + pagepath;

            tb_show("Publish Properties", "/Handlers/Handler.aspx?op=publishproperties&height=260&width=454&modal=false&" + pageDetails);

            break;

        case "savePage":
            var editorContent = "";     // Body
            if ($.fck.content('FCKeditor1'))
                editorContent = $.fck.content('FCKeditor1');

            var editorContent2 = "";    // intro
            if ($.fck.content('FCKeditor2'))
                editorContent2 = $.fck.content('FCKeditor2');
            var editorContent3 = "";    // paidTeaser
            if ($.fck.content('FCKeditor3'))
                editorContent3 = $.fck.content('FCKeditor3');


            var thisbase = $("#basehref1").attr('href');

            var imageL = $("#imgArticleImageL").attr('src');
            if (imageL)
                imageL = imageL.replace(thisbase, "");
            else
                imageL = '';

            var imageAltL = $("#imgArticleImageL").attr('alt');
            if (!(imageAltL))
                imageAltL = '';

            var imageS = $("#imgArticleImageS").attr('src');
            if (imageS)
                imageS = imageS.replace(thisbase, "");
            else
                imageS = '';

            var imageAltS = $("#imgArticleImageS").attr('alt');
            if (!(imageAltS))
                imageAltS = '';

            var templateId = $("#TemplateId").html();

            var addpage = $.jqURL.get('add');
            var pageDetails = "";
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath == pagepath.replace("/default.aspx", "");
            if (addpage != null) {
                pageDetails = "newpage=true&aimage1=" + imageL + "&alt1=" + encodeURIComponent(imageAltL) + "&aimage2=" + imageS + "&alt2=" + imageAltS + "&aintro=" + encodeURIComponent(editorContent2) + "&abody=" + encodeURIComponent(editorContent) + "&ateaser=" + encodeURIComponent(editorContent3) + "&tid=" + templateId + "&pagepath=" + pagepath;
            }
            else {
                pageDetails = "aimage1=" + imageL + "&alt1=" + encodeURIComponent(imageAltL) + "&aimage2=" + imageS + "&alt2=" + imageAltS + "&aintro=" + encodeURIComponent(editorContent2) + "&abody=" + encodeURIComponent(editorContent) + "&ateaser=" + encodeURIComponent(editorContent3) + "&pagepath=" + pagepath;
            }

            var req = $.ajax({
                type: "POST",
                url: "Handlers/Handler.aspx?op=savepage",
                data: pageDetails,
                error: function(req, json) {
                    alert(json);
                },
                success: function(json) {
                    var msg = eval("(" + json + ")");

                    if (msg.error == 0) {

                        if (msg.message != "") {
                            if (msg.message == "duplicate") {
                                alert("An article with this headline already exists");
                            }
                            else {
                                if (addpage != null)
                                    $.jqURL.loc(thisbase + msg.message);
                                else
                                    $.jqURL.loc(pagepath + "?edit=true&version=" + msg.message);
                            }
                        }
                        else {
                            alert("An error has occurred saving the article.");
                        }
                    }
                    else {
                        alert(msg.message);
                    }

                    return;
                }
            });

            break;

        case "relatedContent":
            var pageDetails = "";
            var thispage = $.jqURL.strip();

            var thisbase = $("#basehref1").attr('href');
            var pagepath = "/" + thispage.replace(thisbase, "");
            pagepath == pagepath.replace("/default.aspx", "");

            pageDetails = "pagepath=" + pagepath;

            tb_show("Related Content", "/Handlers/Handler.aspx?op=relatedcontent&height=400&width=730&modal=false&" + pageDetails);

            break;

        case "archiveImage":
            UpdateArchiveImageFromBank(columnId);
            break;
    }
}

function loadPH(columnId) {
    var req = $.ajax({
        type: "POST",
        url: "http://localhost:49189/Handlers/Handler.aspx?op=loadplaceholder",
        data: "none",
        error: function(req, json) {

            //alert('ER');
        },
        success: function(html) {
            $("#PlaceHolderControl").html(html);
            return;
        }
    });
}

function PublishPageNow() {

    var pageDetails = "";
    var version = $.jqURL.get('version');
    if (version == null) {
        version = "";
    }
    var thispage = $.jqURL.strip();

    var thisbase = $("#basehref1").attr('href');
    var pagepath = "/" + thispage.replace(thisbase, "");
    var redirect = pagepath;
    pagepath = pagepath.replace("/default.aspx", "");
    pagepath = pagepath.replace(".aspx", "");
    pageDetails = "version=" + version + "&pagepath=" + pagepath;

    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=publishpage",
        data: pageDetails,
        error: function(req, json) {
            alert(json);
        },
        success: function(json) {
            var msg = eval("(" + json + ")");

            if (msg.error == 0) {
                if (msg.message == "published") {
                    $.jqURL.loc(redirect);
                }
                else {
                    alert(msg.message);
                }
            }
            else {
                alert(msg.message);
            }
        
            return;
        }
    });
}


function PublishScheduledPage(txtFromDate, txtTime1, txtToDate, txtTime2) {
    var pageDetails = "";
    var thispage = $.jqURL.strip();

    var thisbase = $("#basehref1").attr('href');
    var pagepath = "/" + thispage.replace(thisbase, "");
    var redirect = pagepath;
    pagepath == pagepath.replace("/default.aspx", "");

    pageDetails = "fromdate=" + txtFromDate + "&fromtime=" + txtTime1 + "&todate=" + txtToDate + "&totime=" + txtTime2 + "&pagepath=" + pagepath;

    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=publishschedulepage",
        data: pageDetails,
        error: function(req, json) {
            alert(json);
        },
        success: function(json) {
            var msg = eval("(" + json + ")");

            if (msg.error == 0) {
                $.jqURL.loc(msg.message);
            }
            else {
                alert(msg.message);
            }
                return;
            }
    });
}

function selectArticleParent() {
    var select = $("#cbArticleParents").val();
    var dataStr = "parentid=" + select;

    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=getpagesbyparent",
        data: dataStr,
        error: function(req, json) {

            alert(json);
        },
        success: function(html) {
            //$("#articleselectlist").html(html);
            $("#leftModules").html(html);
            //alert(html);
            //registerDraggables();
            $("#leftModules").sortable({ connectWith: ["#middleModules", "#rightModules"] });
            $("#middleModules").sortable({ connectWith: ["#leftModules", "#rightModules"] });
            $("#rightModules").sortable({ connectWith: ["#leftModules", "#middleModules"] });
            return;
        }
    });

}

// Register page draggables
function registerDraggables() {
    $('div.galleryimage,img.galleryimage').Draggable(
    {
        revert: true,
        fx: 300,
        ghosting: true,
        zIndex: 999999,
        opacity: 0.9
    });
    $('#dropcontainer').Droppable(
	{
	    accept: 'galleryimage',
	    activeclass: 'activedropcontainer',
	    hoverclass: 'hoverdropcontainer',
	    onHover: changeDropzoneActive,
	    onOut: changeDropzoneInactive,
	    tolerance: 'intersect',
	    onActivate: function(dragged) {
	        this.className = "activedropcontainer";
	    },
	    onDrop: handleDropSwitch
	});
}

// Change dropzone style
function changeDropzoneActive(element) {
    $('#' + element.id).addClass('galleryimageInactive');
}

function changeDropzoneInactive() {
    //$('#floaterimage').attr({ src: 'Media/images/system/buttons/drag_drop_inactive.gif' });
}

function handleDropSwitch(element) {
    // Set dropzone inactive

    //alert(element.id);
    // Determine what element type this is
    var elementType = $(element).attr('assetType');

    // Offload to handler
    switch (elementType) {
        case 'ArticleList':
            handleDropArticleFile(element);
            break;

    }
}

function handleDropArticleFile(element) {
    // StyleFile handler
    var assetType = "ArticleList";
    var assetID = $('#' + element.id).attr('assetID');
    var checkAssetID = "SavedArticle" + assetID;
    var exists = false;
    $('div.droppedimage').each(function(i, o) {
        var checkid = o.id;
        if (checkid == checkAssetID) {
            exists = true;
        }
    });
    if (exists) {
        alert('You already added this article');
    }
    else {
        var counter = 0;
        var maxallowed = $("#boxModule1").attr('maxallowed');

        $('li.sortableitem').each(function(i, o) {
            counter = counter + 1;
        });
        if (counter < maxallowed) {
            changeDropzoneInactive(element);
            var inner = $("#" + element.id + " span").html();
            var htmlstr = "<li class='sortableitem' id='s_" + assetID + "'><div class='droppedimage'  id='SavedArticle" + assetID + "' assetType='ArticleList' assetID='" + assetID + "'><img src='/Images/account.gif' border='0' />  " + inner + "</div></li>";
            $("#sortlist1").append(htmlstr);
            $("#sortlist1").sortable({});
            loadListContextMenus();
        }
        else {
            alert('You have reached the maximum number of items allowed in this module:' + maxallowed);
        }
    }
}

// Change the draggables borders
function formatDraggable(theDraggable) {
    var currentClass = $(theDraggable).attr("class");
    var hoverClass = currentClass + "Hover";
    $(theDraggable).addClass(hoverClass);
    $(theDraggable).mouseout(function() {
        $(theDraggable).removeClass(hoverClass);
    });
}

// Implement "shopping trolley" functionality nb. Not used yet
var addAssetToDropZone = function(dragged) {
    var assetID = $('img', dragged).attr('assetID');
    var assetType = $('img', dragged).attr('assetType');
};

function SavePageProperties(txtPageTitle, txtPageKeywords, txtPageDesc, txtPageTeaser, txtArchiveDate, txtSelectedMatch, authorId, articlePage, isPaidPage, txtCredits, txtPaidTimeFrom, txtPaidTimeTo, txtViewInFullText) {

    var thisbase = $("#basehref1").attr('href');
    var thispage = $.jqURL.strip();
    var thisbase = $("#basehref1").attr('href');
    var pagepath = "/" + thispage.replace(thisbase, "");
    pagepath == pagepath.replace("/default.aspx", "");

    var dataStr = "title=" + encodeURIComponent(txtPageTitle) + "&keywords=" + encodeURIComponent(txtPageKeywords) + "&desc=" + encodeURIComponent(txtPageDesc) + "&teaser=" + encodeURIComponent(txtPageTeaser) + "&selectedmatch=" + txtSelectedMatch + "&archive=" + txtArchiveDate + "&pagepath=" + pagepath + "&authorid=" + authorId + "&ispaidpage=" + isPaidPage + "&creditamount=" + txtCredits + "&paidtimefrom=" + txtPaidTimeFrom + "&paidtimeto=" + txtPaidTimeTo + "&viewinfull=" + encodeURIComponent(txtViewInFullText);

    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=savepageproperties",
        data: dataStr,
        error: function(req, json) {

            alert(json);
        },
        success: function(json) {
            var msg = eval("(" + json + ")");

            if (msg.error == 0) {
                if (msg.message == "saved") {
                    if (articlePage == "true") {
                        $.jqURL.loc(pagepath + "?edit=true");
                    }
                    else {
                        $.jqURL.loc(pagepath);
                    }
                }
                else {
                    alert("Did not save properties.");
                }
            }
            else {
                alert(msg.message);
            }

            return;
        }
    });
}

function saveHomePageModuleSorting(list) {

    var thisbase = $("#basehref1").attr('href');
    var thispage = $.jqURL.strip();
    var thisbase = $("#basehref1").attr('href');
    var pagepath = "/" + thispage.replace(thisbase, "");
    pagepath = pagepath.replace("/default.aspx", "");
    pagepath = pagepath.replace(".aspx", "");
    var dataStr = "list=" + list + "&pagepath=" + pagepath;

    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=savehomepagemodulesorting",
        data: dataStr,
        error: function(req, json) {

            alert(json);
        },
        success: function(html) {
            $.jqURL.loc(thispage + "?edit=true&version=" + html);

            return;
        }
    });
}

function saveHomePageModule(list, itemid, zoneid, moduletype, moduletitle, imagedesc, filename, moretext, morelink) {
    var thispage = $.jqURL.strip();
    var thisbase = $("#basehref1").attr('href');
    var pagepath = "/" + thispage.replace(thisbase, "");
    pagepath = pagepath.replace("/default.aspx", "");

    var dataStr = "list=" + list + "&itemid=" + itemid + "&zoneid=" + zoneid + "&moduletype=" + moduletype + "&moduletitle=" + moduletitle + "&imagedesc=" + imagedesc + "&filename=" + filename + "&moretext=" + moretext + "&morelink=" + morelink + "&pagepath=" + pagepath;

    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=savehomepagemodule",
        data: dataStr,
        error: function(req, json) {

            alert(json);
        },
        success: function(html) {
            $.jqURL.loc(thispage + "?edit=true&version=" + html);

            return;
        }
    });
}

function saveRelatedContent(list) {
    var thispage = $.jqURL.strip();
    var thisbase = $("#basehref1").attr('href');
    var pagepath = "/" + thispage.replace(thisbase, "");
    pagepath = pagepath.replace("/default.aspx", "");

    var dataStr = "list=" + list + "&pagepath=" + pagepath;

    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=saverelatedcontent",
        data: dataStr,
        error: function(req, json) {

            alert(json);
        },
        success: function(html) {
            $.jqURL.loc(thispage + "?edit=true&version=" + html);

            return;
        }
    });
}

function saveArchiveDetails(text, filename, imagedesc, weekid) {
    var thispage = $.jqURL.strip();
    var thisbase = $("#basehref1").attr('href');
    var pagepath = "/" + thispage.replace(thisbase, "");
    pagepath = pagepath.replace("/default.aspx", "");

    var dataStr = "text=" + text + "&filename=" + filename + "&imagedesc=" + imagedesc + "&weekid=" + weekid + "&pagepath=" + pagepath;

    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=savearchivedetails",
        data: dataStr,
        error: function(req, json) {
            alert(json);
        },
        success: function(html) {
            $.jqURL.loc(thispage);
            
            tb_remove();
            return;
        }
    });
}

function LoginCMSUser(txtUsername, txtPassword) {
    var dataStr = "username=" + txtUsername + "&password=" + txtPassword;
    var home = "/home.aspx";
    var loginhome = "/login/default.aspx";
    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=logincmsuser",
        data: dataStr,
        error: function(req, json) {

            $.jqURL.loc(loginhome);
        },
        success: function(html) {
            if (html == "success") {
                $.jqURL.loc(home);
            }
            else {
                $.jqURL.loc(loginhome);
            }

            return;
        }
    });
}

function UpdateArticleImageFromBank(columnId) {
    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=articleimagebank",
        data: "none",
        error: function(req, json) {
            //alert('ER');
        },
        success: function(html) {
            $("div.TwoModuleBoxSectionImage").html(html);
            return;
        }
    });
}

function UpdateArchiveImageFromBank(columnId) {
    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=archiveimagebank",
        data: "none",
        error: function(req, json) {
            //alert('ER');
        },
        success: function(html) {
            $("#ArchiveImage" + columnId).html(html);

            return;
        }
    });
}

function UpdateArticleImage(columnId) {
    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=loadimageupdater",
        data: "none",
        error: function(req, json) {
            //alert('ER');
        },
        success: function(html) {
            $("div.TwoModuleBoxSectionImage").html(html);

            return;
        }
    });
}

function GetImageDefaultDescription(txtid, imgsrc) {
    var dataStr = "imgsrc=" + imgsrc;

    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=getimagedefaultdescription",
        data: dataStr,
        error: function(req, json) {
            alert(req);
        },
        success: function(html) {
            $("#" + txtid).val(html);
            return;
        }
    });
}

function StoreArticleImage(imgsrc, imgsrc2, alt1, alt2) {
    var str = '<img id="imgArticleImageL" src="' + imgsrc + '" width="292" height="140" alt="' + alt1 + '" /><img id="imgArticleImageS" src="' + imgsrc2 + '" style="display:none;" alt="' + alt2 + '" />';
    $("div.TwoModuleBoxSectionImage").html(str);
}

var totalTeams = 20;

function SetFormTable() {
    var TTC = $("#TotalTeamsCounter").html();
    var tableHeight = ($("#FormTable").height() + 40);
    var pCont = "308px";
    if (tableHeight != null) {
        pCont = tableHeight + "px";
        $("div.FormTableModuleBox").css({ 'height': pCont });
        totalTeams = parseInt(TTC);
        if (totalTeams > 30) {
            $("table.tablesorter")
    .tablesorter({ widthFixed: false })
    .tablesorterPager({ container: $("#pager") });

        }
        else {
            $("table.tablesorter").tablesorter({ widthFixed: false });

        }

        formatClickables();
        $('#FormTableHeadlineBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");
        loadHomepageContextMenus();
    }


}

function SetGameNotesRotator() {
    var tableHeight = $("div.GamesNotesBox").height()
    var pCont = "150px";
    if (tableHeight) {
        //pCont = tableHeight + "px";
        $("div.GamesNotesBox").css({ 'min-height': pCont });
        formatClickables();
        $('#GamesNotesRotatorHeadlineBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");
        loadHomepageContextMenus();
    }
}


function SetRankingsRotator() {
    var tableHeight = $("div.RankingsBox").height()
    var pCont = "215px";
    if (tableHeight) {
        //pCont = tableHeight + "px";
        $("div.KeyRankingsRotatorBox").css({ 'height': pCont });


        formatClickables();
        $('#KeyRankingsRotatorHeadlineBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");
        loadHomepageContextMenus();
    }
}

function SetPatternsRotator() {
    var tableHeight = $("div.KeyPatternsBox1").height()
    var pCont = "200px";
    if (tableHeight) {
        //pCont = tableHeight + "px";
        $("div.KeyPatternsRotatorBox").css({ 'height': pCont });


        formatClickables();
        resizeVerticalBarCharts();
        $('#KeyPatternsRotatorHeadlineBox').corner("round 5px").parent().css('padding', '1px').corner("round 5px");
        loadHomepageContextMenus();
    }
}

function reorderModules() {
    var tableHeight = $("table.tablesorter").height();
    var rankingRankingRotatorHeight = $("div.RankingsBox").height();
    var patternRotatorHeight = $("div.KeyPatternsBox1").height();
    var gameNotesRotatorHeight = $("div.GamesNotesRotatorBox").height();
    
    if (tableHeight) {
        var leftsortstr = $("#LeftColumn").attr('sort');
        var middlesortstr = $("#MiddleColumn").attr('sort');
        var rightsortstr = $("#RightColumn").attr('sort');

        var leftArray = new Array();
        leftArray = leftsortstr.split('|');
        if (isFormTableRotatorPresent(leftArray)) {
            reorderModulesAroundFormTableRotator("LeftColumn", leftArray);
        }


        var middleArray = new Array();
        middleArray = middlesortstr.split('|');
        if (isFormTableRotatorPresent(middleArray)) {
            reorderModulesAroundFormTableRotator("MiddleColumn", middleArray);
        }

        var rightArray = new Array();
        rightArray = rightsortstr.split('|');
        if (isFormTableRotatorPresent(rightArray)) {
            reorderModulesAroundFormTableRotator("RightColumn", rightArray);
        }

    }

    if (rankingRankingRotatorHeight) {
        var leftsortstr = $("#LeftColumn").attr('sort');
        var middlesortstr = $("#MiddleColumn").attr('sort');
        var rightsortstr = $("#RightColumn").attr('sort');

        var leftArray = new Array();
        leftArray = leftsortstr.split('|');
        if (isRankingRotatorPresent(leftArray)) {
            reorderModulesAroundKeyRankingsRotator("LeftColumn", leftArray);
        }


        var middleArray = new Array();
        middleArray = middlesortstr.split('|');
        if (isRankingRotatorPresent(middleArray)) {
            reorderModulesAroundKeyRankingsRotator("MiddleColumn", middleArray);
        }

        var rightArray = new Array();
        rightArray = rightsortstr.split('|');
        if (isRankingRotatorPresent(rightArray)) {
            reorderModulesAroundKeyRankingsRotator("RightColumn", rightArray);
        }

    }

    if (patternRotatorHeight) {
        var leftsortstr = $("#LeftColumn").attr('sort');
        var middlesortstr = $("#MiddleColumn").attr('sort');
        var rightsortstr = $("#RightColumn").attr('sort');

        var leftArray = new Array();
        leftArray = leftsortstr.split('|');
        if (isPatternsRotatorPresent(leftArray)) {
            reorderModulesAroundKeyPatternsRotator("LeftColumn", leftArray);
        }

        var middleArray = new Array();
        middleArray = middlesortstr.split('|');
        if (isPatternsRotatorPresent(middleArray)) {
            reorderModulesAroundKeyPatternsRotator("MiddleColumn", middleArray);
        }

        var rightArray = new Array();
        rightArray = rightsortstr.split('|');
        if (isPatternsRotatorPresent(rightArray)) {
            reorderModulesAroundKeyPatternsRotator("RightColumn", rightArray);
        }

    }

    if (gameNotesRotatorHeight) {
        var leftsortstr = $("#LeftColumn").attr('sort');
        var middlesortstr = $("#MiddleColumn").attr('sort');
        var rightsortstr = $("#RightColumn").attr('sort');

        var leftArray = new Array();
        leftArray = leftsortstr.split('|');
        if (isGameNotesRotatorPresent(leftArray)) {
            reorderModulesAroundGameNotesRotator("LeftColumn", leftArray);
        }
        var middleArray = new Array();
        middleArray = middlesortstr.split('|');
        if (isGameNotesRotatorPresent(middleArray)) {
            reorderModulesAroundGameNotesRotator("MiddleColumn", middleArray);
        }
        var rightArray = new Array();
        rightArray = rightsortstr.split('|');
        if (isGameNotesRotatorPresent(rightArray)) {
            reorderModulesAroundGameNotesRotator("RightColumn", rightArray);
        }
    }

}

function GetModulePanelId(columnId, moduleId) {
    var columnPostfix;
    var modulePrefix;
    var returnCustom;
    switch (columnId) {
        case "LeftColumn":
            columnPostfix = "Left";
            break;
        case "MiddleColumn":
            columnPostfix = "Middle";
            break;
        case "RightColumn":
            columnPostfix = "Right";
            break;
    }

    switch (moduleId) {
        case "FormTableRotator1":
            modulePrefix = "upFormTable";
            returnCustom = true;
            break;
        case "KeyRankingsRotator1":
            modulePrefix = "upRankings";
            returnCustom = true;
            break;
        case "GameNotesRotator1":
            modulePrefix = "upGameNotes";
            returnCustom = true;
            break;
        case "KeyPatternsRotator1":
            modulePrefix = "upPatterns";
            returnCustom = true;
            break;
    }
    if (returnCustom) {
        return modulePrefix + columnPostfix;
    }
    else {
        return moduleId;
    }
}

function reorderModulesAroundFormTableRotator(columnId, columnArray) {
    var foundRotatorPosition = false;
    var ArrayBefore = new Array();
    var ArrayAfter = new Array();
    for (var i = 0; i < columnArray.length; i++) {
        var moduleName = columnArray[i];
        if (!foundRotatorPosition) {
            if (moduleName == "FormTableRotator1") {
                foundRotatorPosition = true;
            }
            else {
                ArrayBefore.push(moduleName);
            }
        }
        else {
            ArrayAfter.push(moduleName);
        }
    }

    for (var i = 0; i < ArrayBefore.length; i++) {
        var panelitem = $("#" + GetModulePanelId(columnId, ArrayBefore[i])).outerHTML();
        $("#" + GetModulePanelId(columnId, ArrayBefore[i])).remove();
        switch (columnId) {
            case "LeftColumn":
                $("#upFormTableLeft").before(panelitem);
                break;
            case "MiddleColumn":
                $("#upFormTableMiddle").before(panelitem);
                break;
            case "RightColumn":
                $("#upFormTableRight").before(panelitem);
                break;
        }
    }

    for (var i = ArrayAfter.length - 1; i >= 0; i--) {
        var panelitem = $("#" + GetModulePanelId(columnId, ArrayAfter[i])).outerHTML();
        $("#" + GetModulePanelId(columnId, ArrayAfter[i])).remove();
        switch (columnId) {
            case "LeftColumn":
                $("#upFormTableLeft").after(panelitem);
                break;
            case "MiddleColumn":
                $("#upFormTableMiddle").after(panelitem);
                break;
            case "RightColumn":
                $("#upFormTableRight").after(panelitem);
                break;
        }
    }



}

function reorderModulesAroundKeyRankingsRotator(columnId, columnArray) {
    var foundRotatorPosition = false;
    var ArrayBefore = new Array();
    var ArrayAfter = new Array();
    for (var i = 0; i < columnArray.length; i++) {
        var moduleName = columnArray[i];
        if (!foundRotatorPosition) {
            if (moduleName == "KeyRankingsRotator1") {
                foundRotatorPosition = true;
            }
            else {
                ArrayBefore.push(moduleName);
            }
        }
        else {
            ArrayAfter.push(moduleName);
        }
    }

    for (var i = 0; i < ArrayBefore.length; i++) {
        var panelitem = $("#" + GetModulePanelId(columnId, ArrayBefore[i])).outerHTML();
        $("#" + GetModulePanelId(columnId, ArrayBefore[i])).remove();
        switch (columnId) {
            case "LeftColumn":
                $("#upRankingsLeft").before(panelitem);
                break;
            case "MiddleColumn":
                $("#upRankingsMiddle").before(panelitem);
                break;
            case "RightColumn":
                $("#upRankingsRight").before(panelitem);
                break;
        }
    }

    for (var i = ArrayAfter.length - 1; i >= 0; i--) {
        var panelitem = $("#" + GetModulePanelId(columnId, ArrayAfter[i])).outerHTML();
        $("#" + GetModulePanelId(columnId, ArrayAfter[i])).remove();
        switch (columnId) {
            case "LeftColumn":
                $("#upRankingsLeft").after(panelitem);
                break;
            case "MiddleColumn":
                $("#upRankingsMiddle").after(panelitem);
                break;
            case "RightColumn":
                $("#upRankingsRight").after(panelitem);
                break;
        }
    }
}

function reorderModulesAroundGameNotesRotator(columnId, columnArray) {
    var foundRotatorPosition = false;
    var ArrayBefore = new Array();
    var ArrayAfter = new Array();
    for (var i = 0; i < columnArray.length; i++) {
        var moduleName = columnArray[i];
        if (!foundRotatorPosition) {
            if (moduleName == "GameNotesRotator1") {
                foundRotatorPosition = true;
            }
            else {
                ArrayBefore.push(moduleName);
            }
        }
        else {
            ArrayAfter.push(moduleName);
        }
    }

    for (var i = 0; i < ArrayBefore.length; i++) {
        var panelitem = $("#" + GetModulePanelId(columnId, ArrayBefore[i])).outerHTML();
        $("#" + GetModulePanelId(columnId, ArrayBefore[i])).remove();
        switch (columnId) {
            case "LeftColumn":
                $("#upGameNotesLeft").before(panelitem);
                break;
            case "MiddleColumn":
                $("#upGameNotesMiddle").before(panelitem);
                break;
            case "RightColumn":
                $("#upGameNotesRight").before(panelitem);
                break;
        }
    }

    for (var i = ArrayAfter.length - 1; i >= 0; i--) {
        var panelitem = $("#" + GetModulePanelId(columnId, ArrayAfter[i])).outerHTML();
        $("#" + GetModulePanelId(columnId, ArrayAfter[i])).remove();
        switch (columnId) {
            case "LeftColumn":
                $("#upGameNotesLeft").after(panelitem);
                break;
            case "MiddleColumn":
                $("#upGameNotesMiddle").after(panelitem);
                break;
            case "RightColumn":
                $("#upGameNotesRight").after(panelitem);
                break;
        }
    }
}

function reorderModulesAroundKeyPatternsRotator(columnId, columnArray) {
    var foundRotatorPosition = false;
    var ArrayBefore = new Array();
    var ArrayAfter = new Array();
    for (var i = 0; i < columnArray.length; i++) {
        var moduleName = columnArray[i];
        if (!foundRotatorPosition) {
            if (moduleName == "KeyPatternsRotator1") {
                foundRotatorPosition = true;
            }
            else {
                ArrayBefore.push(moduleName);
            }
        }
        else {
            ArrayAfter.push(moduleName);
        }
    }

    for (var i = 0; i < ArrayBefore.length; i++) {
        var panelitem = $("#" + GetModulePanelId(columnId, ArrayBefore[i])).outerHTML();
        $("#" + GetModulePanelId(columnId, ArrayBefore[i])).remove();
        switch (columnId) {
            case "LeftColumn":
                $("#upPatternsLeft").before(panelitem);
                break;
            case "MiddleColumn":
                $("#upPatternsMiddle").before(panelitem);
                break;
            case "RightColumn":
                $("#upPatternsRight").before(panelitem);
                break;
        }
    }

    for (var i = ArrayAfter.length - 1; i >= 0; i--) {
        var panelitem = $("#" + GetModulePanelId(columnId, ArrayAfter[i])).outerHTML();
        $("#" + GetModulePanelId(columnId, ArrayAfter[i])).remove();
        switch (columnId) {
            case "LeftColumn":
                $("#upPatternsLeft").after(panelitem);
                break;
            case "MiddleColumn":
                $("#upPatternsMiddle").after(panelitem);
                break;
            case "RightColumn":
                $("#upPatternsRight").after(panelitem);
                break;
        }
    }
}

function isFormTableRotatorPresent(columnArray) {
    var exists = false;
    for (var i = 0; i < columnArray.length; i++) {
        var moduleName = columnArray[i];
        if (moduleName == "FormTableRotator1") {
            exists = true;
        }
    }

    return exists;

}

function isRankingRotatorPresent(columnArray) {
    var exists = false;
    for (var i = 0; i < columnArray.length; i++) {
        var moduleName = columnArray[i];
        if (moduleName == "KeyRankingsRotator1") {
            exists = true;
        }
    }
    return exists;
}

function isGameNotesRotatorPresent(columnArray) {
    var exists = false;
    for (var i = 0; i < columnArray.length; i++) {
        var moduleName = columnArray[i];
        if (moduleName == "GameNotesRotator1") {
            exists = true;
        }
    }
    return exists;
}

function isPatternsRotatorPresent(columnArray) {
    var exists = false;
    for (var i = 0; i < columnArray.length; i++) {
        var moduleName = columnArray[i];
        if (moduleName == "KeyPatternsRotator1") {
            exists = true;
        }
    }

    return exists;

}


//////////////////////////////////////////////////////////////////////////////////////////////////////

function checkAuthentication() {

    var req = $.ajax({
        type: "POST",
        url: "Handlers/BettorLogicHandler.aspx?op=authenticate",
        data: "none",
        error: function(req, json) {
            $.jCache.setItem("Authenticated", "false");
        },
        success: function(json) {
            var user = eval("(" + json + ")");

            if (user.UserId != 0) {
                $.jCache.setItem("Authenticated", "true");
                $.jCache.setItem("Roles", user.Roles);

                $("#lbl_Welcome").show();
                $("#lbl_Welcome").html(CreateLogout(user.Username));

                $("#btn_Members").hide();
                //$("#btn_Buy").hide();
            }
            else {
                $.jCache.setItem("Authenticated", "false");

                loadLoginControls();
            }

            return;
        }
    });
}

function loadLoginControls() {
    if (LoadCookie() == false) {
        $("#btn_Members").show();
        //$("#btn_Buy").show();
        $("#lbl_Welcome").hide();
    }
}

function LoadCookie() {
    if ((readCookie("EmailAddress") != "") && (readCookie("UserPassword") != "")) {
        Login(readCookie("EmailAddress"), readCookie("UserPassword"), true, true);

        return true;
    }
    else
        return false;
}

function readCookie(name) {
    var nameSG = name + "=";
    var nuller = '';
    if (document.cookie.indexOf(nameSG) == -1)
        return nuller;

    var ca = document.cookie.split(';');

    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];

        while (c.charAt(0) == ' ')
            c = c.substring(1, c.length);

        if (c.indexOf(nameSG) == 0)
            return c.substring(nameSG.length, c.length);
    }

    return false;
}

function CreateLogout(username) {
    var logout = "<b>Welcome " + username;

    logout += "   <a href='#' onclick='Logout(); return false;'>Logout</a></b>";

    return logout;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////

// Use jQuery via $(...)
$(document).ready(function() {
    var sos = $.jqURL.get('ref');
    if (sos == "sos")
        tb_show("BettorLogic", "/Prospect.html?height=330&width=530&modal=true", "");

    LoadPageMenuItems();

    var formtableHeight = $("#FormTable").height();
    if (formtableHeight != null) {
        reorderModules();
        SetFormTable();
    }

    var rankingsRotatorHeight = $("div.RankingsBox").height();
    if (rankingsRotatorHeight != null) {
        reorderModules();
        SetRankingsRotator();
    }

    var patternsRotatorHeight = $("div.KeyPatternsBox1").height();
    if (patternsRotatorHeight != null) {
        reorderModules();
        SetPatternsRotator();
    }

    var notesRotatorHeight = $("div.GamesNotesBox").height();
    if (notesRotatorHeight != null) {
        reorderModules();
        SetGameNotesRotator();
    }

    var floater = $("#toolbarmenu").height();
    if (floater != null)
        registerFloater();

    var cmenus = $("#contextMenusContainer").height();
    if (cmenus != null)
        loadContextMenus();

    var cmenushome = $("#contextMenusContainerHome").height();
    if (cmenushome != null) {
        loadHomepageContextMenus();
    }


    $("#ArticleBody table.tablesorter").attr("status", "zebra");
    checkTableSorter();
    checkAuthentication();
    //loadNewsTicker();

    $(window).load(function() {
        setTall();
    });

    FormatKeyRankingTooltips();

});


function checkTableSorter() {

    var table = $("table.tablesorter");
    for (var i = 0; i < table.length; i++) {
        var id = table[i].id;
        var status = $("#" + id).attr('status');
        if (status != null && status == "zebra") {
            $("table.tablesorter").tablesorter({
                widgets: ['zebra']
            });
        }
        else {
            $("table.tablesorter").tablesorter({
                //widgets: ['zebra']
            });
        }
    }

}


function loadNewsTicker() {
    var thisbase = $("#basehref1").attr('href');
    var thispage = $.jqURL.strip();
    var thisbase = $("#basehref1").attr('href');
    var pagepath = "/" + thispage.replace(thisbase, "");
    pagepath = pagepath.replace("/default.aspx", "");
    pagepath = pagepath.replace(".aspx", "");

    var dataStr = "pagepath=" + pagepath;

    var req = $.ajax({
        type: "POST",
        url: "Handlers/Handler.aspx?op=loadnewsticker",
        data: dataStr,
        error: function(req, json) {

            alert(json);
        },
        success: function(html) {
            $("#news").html(html);
            var options = {
                newsList: "#news",
                startDelay: 10,
                loopDelay: 5000,
                placeHolder1: "[]"
            }
            $().newsTicker(options);

            return;
        }
    });
}

function SetFocus(id) {
    $("#" + id).focus();
}

function Check() {
    $("#javascriptenabled")[0].value = "true";
}

function FormatKeyRankingTooltips() {
    $("#KeyRankingBox table tr td").each(function(i) {
        var $match1 = $("#KeyRankingBox table tr td img.rankingBar1").eq(i);
        var barId1 = $match1.attr('id');
        var title1 = $("#" + barId1).attr('header');
        var actuals1 = $("#" + barId1).attr('actuals');

        $("#" + barId1).mouseover(function() {
            showtip(this, "RankingBubbleBox", findPosX(this), findPosY(this), title1, actuals1, 1);

        }).mouseout(function() {
            hidetip(this, "RankingBubbleBox", findPosX(this), findPosY(this), title1, actuals1, 1);
        });
    });

    $("#KeyRankingBox table tr td").each(function(i) {

    var $match2 = $("#KeyRankingBox table tr td img.rankingBar2").eq(i);
        var barId2 = $match2.attr('id');
        var title2 = $("#" + barId2).attr('header');
        var actuals2 = $("#" + barId2).attr('actuals');
        $("#" + barId2).mouseover(function() {
            showtip(this, "RankingBubbleBox", findPosX(this), findPosY(this), title2, actuals2, 0);

        }).mouseout(function() {
            hidetip(this, "RankingBubbleBox", findPosX(this), findPosY(this), title2, actuals2, 0);
        });
    });
}

function showtip(tip, bid, tipX, tipY, title, actualtext, ishome) {
    var xTip = "0px";
    var yTip = "0px";
    window.status = title;
    xTip = (tipX - 250) + "px";
    yTip = (tipY + 20) + "px";
    var bubble = $("div[@id=" + bid + "]");
    $("#RankingBubbleTitle").html(title);
    if (ishome == 1) {
        $("#RankingBubbleTitle").addClass('home').removeClass('away');
    }
    else {
        $("#RankingBubbleTitle").addClass('away').removeClass('home');
    }
    $("#RankingBubble").html(actualtext);
    bubble.css({ left: xTip, top: yTip, visibility: "visible" });
}

function hidetip(tip, bid, tipX, tipY, title, actualtext, ishome) {
    var xTip = "-250px";
    var yTip = "-250px";
    window.status = title;
    var bubble = $("div[@id=" + bid + "]");
    $("#RankingBubbleTitle").html("");
    $("#RankingBubble").html("");
    bubble.css({ left: xTip, top: yTip, visibility: "hidden" });
}