var _isProduction;
var _isTVWeekV2;
var _isDevLoadTest;

$(document).ready(function() {
    SetIsTVWeekV2();
    SetIsProduction();
    SetIsDevLoadTest();

    //if (isIE6()) fixIE6flicker(true);
    AlterNavs();
    AlterTVHighlights();
    AlterHome();
    if (JS_SECTION == 'quiz')
        AlterQuiz();
    ResizeTVHighlights();
    AlterShowRelatedLinks();
    AlterShowList();

    RemoveTH();
    
    if (_isProduction) {
        AlterProdImages();
        AlterProdLinks();
    }

    if (_isDevLoadTest) {
        AlterDevLoadTestImages();
        AlterDevLoadTestLinks();
    }

    if (!_isTVWeekV2) {
        CleanV2HostName();
    }
});

function SetIsProduction() {
    if (window.location.host.indexOf(".syd") > -1) _isProduction = true;
    else _isProduction = false;
}

function SetIsDevLoadTest() {
    if (window.location.host.indexOf(".devloadtest") > -1) _isDevLoadTest = true;
    else _isDevLoadTest = false;
}

function SetIsTVWeekV2() {
    if (window.location.host.indexOf("tvweekv2.") > -1) _isTVWeekV2 = true;
    else _isTVWeekV2 = false;
}

function AlterHome() {
    $('#pnlLatestFeatures .image img').each(function() {
        var src = $(this).attr("src");
        var newSrc = "http://images.ninemsn.com.au/resizer.aspx?width=150&url=" + src;
        $(this).attr("src", newSrc);
    });
    $('#cat_hl_224684 .headertitle').show();
    $('#cat_hl_224684 .headertext').show();
    $('#cat_hl_225375 .headertitle').css({ 'padding': '8px 0 0 10px', 'width': '300px', 'height': '45px' });
    $('#cat_hl_225375 .headertitle').show();
    $('#cat_hl_225375 .headertext').show();
    AlterHomeBlog();
    AlterHomeLatestNews();
    AlterHomeLatestFeatures();
}

function AlterNavs() {
    $('#cat_hl_224430 a:first').css({ 'background': 'none' });
    $('#cat_hl_221914 ul li.lvl1:first').css({ 'margin-right': '7px' });

    if (!isIE6()) {
        AddNavShadows('76193');
        AddNavShadows('76153');
        $('#ul76193 li a:last').css({ 'border-bottom': '0' });
        $('#ul76153 li a:last').css({ 'border-bottom': '0' });

        $("#cat_hl_221914 li.lvl1").one('mouseenter', function() {
            var id = $(this).attr('id');
            if (id == '76193' || id == '76153') // alter the dropdown offsetHeight
            {
                var offsetHeight = $('#' + id + ' .secondlevelgroup:first').attr('offsetHeight');
                $('#' + id + ' .DropdownShadow').css({ 'height': offsetHeight + 'px' });
                var offsetTop = $('#' + id + ' .DropdownShadow').attr('offsetTop');
                $('#' + id + ' .DropdownShadowEnd').css({ 'top': (offsetTop + offsetHeight) + 'px' });
            }
        });
    }

    $("#cat_hl_221914 ul li").each(function(index) {
        if ($(this).attr("id") == JS_SECTIONID) {
            $(this).removeClass("lvl1").addClass("lvl1_selected");
        }
    });

    if ($(".Navigation").html() != "")
        $(".Navigation").show();
}

function AddNavShadows(navId) {
    var tabShadow = '<div class="TabShadow"><div class="tabStart"></div><div class="tabContent"></div><div class="tabEnd"></div></div>';
    var dropdownShadow = '<div class="DropdownShadow"></div><div class="DropdownShadowEnd"></div>';
    var tabContentWidth = $('#' + navId + ' .tabBody .tabContent:first').width();
    tabContentWidth -= 6; // remove the excess

    $('#' + navId).append(tabShadow);
    $('#' + navId).append(dropdownShadow);
    $('#' + navId + ' .TabShadow .tabContent').css({ 'width': tabContentWidth + 'px' });
    $('#' + navId + ' .TabShadow').css({ 'width': (29 + tabContentWidth) + 'px' });
}


function fixIE6flicker(fix) {
    try {
        document.execCommand("BackgroundImageCache", false, fix);
    } catch (err) { }
}

function isIE6() {
    return ((window.XMLHttpRequest == undefined) && (ActiveXObject != undefined));
}

function AlterTVHighlights() {
    $('#cat_hl_224574 .lvl2gp .lvl2').each(function(index) {
        $(this).find('.onlytitle .linkItem').wrap('<dd class="Show" />');
        $(this).find('.onlytitle dd.Show').insertAfter($(this).find('.onlytext dl dt.Channel'));
    });

    // build tabs for day switcher
    $('#cat_hl_224574 .headerimage').after('<div id="highlightsDays"><ul></ul></div>');
    $('#cat_hl_224574 .odd, #cat_hl_224574 .even').not(':last').each(function(index) {
        $('#highlightsDays').append($(this));
        var day = $(this).find('.onlytitle').text();
        var link = "highlightDays-" + day;
        $(this).wrap('<div id="' + link + '" />');
        $('#cat_hl_224574 #highlightsDays ul').append('<li><a href="#' + link + '">' + day + '</a></li>');
        $(this).find('.lvl2 .caption').insertAfter($(this).find('.lvl2 .title'));
        $(this).find('.lvl2 .caption').append($(this).find('.lvl2 .caption a').text());
        $(this).find('.lvl2 .caption a').remove();
    });
    $('#cat_hl_224574 .odd, #cat_hl_224574 .even').slice(-1).addClass('Schedule');

    // $("#tabs").tabs();
    // hide tabs for highlights and soaps - not going live with this
    $('#tabs ul:first').hide();
    $('#highlightsDays').tabs();

    SetCurrentDay();

}

function SetCurrentDay() {
    var today = new Date();
    var thisDay = today.getDay();
    $('#highlightsDays ul li a').each(function(index) {
        if (index + 1 == thisDay) $(this).click();
    });
}

function AlterHomeBlog() {
    $("#cat_hl_224691 .caption").insertAfter($("#cat_hl_224691 .title"));
}

function AlterHomeLatestNews() {
    $("#pnlLatestNews .odd .title").insertBefore("#pnlLatestNews .odd .image");
    $("#pnlLatestNews .odd .timestamp").insertAfter("#pnlLatestNews .odd .title");
}

function AlterHomeLatestFeatures() {
    $("#pnlLatestFeatures .image").each(function(index) {
        $(this).insertAfter($(this).parent().find(".title"));
        $(this).parent().find(".text .timestamp").insertAfter($(this).parent().find(".title"));
    });
    $("#pnlLatestFeatures .text .bodytext").each(function(index) {
        var bodyText = $(this).find("p").text();
        $(this).find("p").remove();
        $(this).text(bodyText);
    });
}

function ResizeColumnDivs() {
    //Reset column divs heights
    var _colDivs = [
		document.getElementById("lftcol"),
		document.getElementById("rghtcol"),
		document.getElementById("contentcol")];
    for (var _colDivIndex = 0; _colDivIndex < _colDivs.length; _colDivIndex++) {
        if (_colDivs[_colDivIndex]) {
            _colDivs[_colDivIndex].style.height = "100%";
        }
    }

    //Re-calculate & set column div heights
    setConHgt();
}

function AlterQuiz() {
    $('#idxArticle .odd, #idxArticle .even').slice(-1).css({ 'border-bottom': 'none' });
    var image = $('#quizctrl table td').not('table table td, table table table td').eq(1).find('img');
    var quizTitle = $('#quizctrl .subheading:first');
    $('#quizctrl .subheading:first').parent().empty().append(quizTitle);

}

function AlterProdImages() {
    $('img').each(function(index) {
        var source = "" + $(this).attr('src');
        var newSource = source.replace("_th", "");

        if (_isTVWeekV2)
            newSource = newSource.replace(/tvweekv2.ninemsn.com.au/i, "tvweekv2.syd.ninemsn.com.au");
        else
            newSource = newSource.replace("_th", "").replace(/tvweek.ninemsn.com.au/i, "tvweek.syd.ninemsn.com.au");

        $(this).attr('src', newSource);
    });
}

function RemoveTH() {
    $('img').each(function(index) {
        var source = "" + $(this).attr('src');
        var newSource = source.replace("_th", "");
        $(this).attr('src', newSource);
    });
}

function AlterDevLoadTestImages() {
    $('img').each(function(index) {
        var source = "" + $(this).attr('src');
        var newSource = source.replace("_th", "");

        if (_isTVWeekV2)
            newSource = newSource.replace(/tvweekv2.ninemsn.com.au/i, "tvweekv2.devloadtest.ninemsn.com.au");
        else
            newSource = newSource.replace("_th", "").replace(/tvweek.ninemsn.com.au/i, "tvweek.devloadtest.ninemsn.com.au");

        $(this).attr('src', newSource);
    });
}

function AlterProdLinks() {
    $('a').each(function(index) {
        var href = "" + $(this).attr('href');
        if (_isTVWeekV2)
            var newHref = href.replace(/tvweekv2.ninemsn.com.au/i, "tvweekv2.syd.ninemsn.com.au");
        else
            var newHref = href.replace(/tvweek.ninemsn.com.au/i, "tvweek.syd.ninemsn.com.au");
        $(this).attr('href', newHref);
    });
}

function AlterDevLoadTestLinks() {
    $('a').each(function(index) {
        var href = "" + $(this).attr('href');
        if (_isTVWeekV2)
            var newHref = href.replace(/tvweekv2.ninemsn.com.au/i, "tvweekv2.devloadtest.ninemsn.com.au");
        else
            var newHref = href.replace(/tvweek.ninemsn.com.au/i, "tvweek.devloadtest.ninemsn.com.au");
        $(this).attr('href', newHref);
    });
}

function CleanV2HostName() {
    $('a').each(function(index) {
        var href = $(this).attr('href');
        if (href != undefined && href.indexOf('tvweekv2') > -1) {
            href = href.replace('tvweekv2', 'tvweek');
            $(this).attr('href', href);
        }
    });
    $('img').each(function(index) {
        var src = $(this).attr('src');
        if (src.indexOf('tvweekv2') > -1) {
            src = src.replace('tvweekv2', 'tvweek');
            $(this).attr('src', src);
        }
    });
}

function AlterShowList() {
    var moreLink;
    var newText;
    $('#pnlShows .content .text').each(function(index) {
        moreLink = $(this).find('a:last'); // there should always be a More anchor at the end of the text, if not, tell the producer to put it in.
        moreLink.text('more');
        newText = TrimText($(this).text(), 50) + "... ";
        $(this).text(newText);
        $(this).append(moreLink);
        $('<div class="ViewTimes"></div>').insertAfter($('#pnlShows .content .title').eq(index));
        $('<div class="DashedDivider"></div><div class="ShowLinks"></div><div class="Divider"></div>').insertAfter(this);
    });
    ReorderShowLinks();
    UpdateShowRedirects();
    $('#pnlShowList').show();
}

function AlterShowRelatedLinks() {
    $('.RelatedLinks #idxTagIndex .Item').each(function(index) {
        $(this).find('.image').insertBefore($(this).find('.content'));
    });
}

function UpdateShowRedirects() {
    $("#pnlShows .image a").each(function(index) {
        var href = $(this).attr('href');
        var newHref = href;
        var title = "";
        if (href.indexOf('/show.aspx') > -1) {
            title = $(this).find("> img").attr("title");
            newHref = newHref + "&domain=site&tags=" + title.replace(" ", "+") + "|Series Name";
            $(this).attr('href', newHref);
        }
    });
}

function ReorderShowLinks() {
    $('#pnlLinks .odd, #pnlLinks .even').each(function(i) {
        $(this).find('a.linkItem:not(".lvl2gp a")').addClass("ButtonViewTimes");
        $('#pnlShows .content .ViewTimes').eq(i).append($(this).find('.ButtonViewTimes'));
        $('#pnlShows .content .ShowLinks').eq(i).append($(this).find('.lvl2gp .linkItem'));
    });
    $('#pnlLinks').remove();
}

function TrimText(text, length) {
    var newText = text;
    if (text.length > 50) {
        var cutoff = text.lastIndexOf(" ", 50);
        newText = text.slice(0, cutoff);
    }
    return newText;
}

function ResizeTVHighlights() {
    $('#pnlRestOfWeek img').each(function(index) {
        var src = $(this).attr('src');
        var newSrc = "http://images.ninemsn.com.au/resizer.aspx?width=142&url=" + src;
        $(this).attr('src', newSrc);
    });
}

function ImgError(source, width) {
    if (width > 0) {
        var logoPath = "/img/base/logo.png";
        switch (JS_SUB_SECTIONID) {
            case "205409": // neighbours
                logoPath = "/img/neighbours/neighbours_600x400.jpg";
                break;
            case "205852": // seapatrol
                logoPath = "/img/seapatrol/seapatrol_150x100.jpg";
                break;
            case "203565": // home and away
                logoPath = "/img/homeaway/onair_600x400.jpg";
                break;
            case "205410": // packed to the rafters
                logoPath = "/img/pttr/pttr_150x100.jpg";
                break;
            case "205851": // rescue special ops
                logoPath = "/img/rso/2710_rso_600x400.jpg";
                break;
            case "205735": // dancing with the stars
                logoPath = "/img/dwts/2710_dwts_309x209.jpg";
                break;
            case "": // masterchef
                logoPath = "/img/mc/2710_mc_309x207.jpg";
                break;
        }
        if (_isProduction) {
            source.src = "http://images.ninemsn.com.au/resizer.aspx?width=" + width + "&url=http://tvweek.syd.ninemsn.com.au" + logoPath;
        }
        else {
            source.src = "http://images.ninemsn.com.au/resizer.aspx?width=" + width + "&url=http://tvweek.ninemsn.com.au" + logoPath;
        }
    }
    else { source.src = logoPath; }
    source.onerror = "";
    return true;
};




