/***************************************
* Start page structure functions
**************************************/

// do the required tasks when the document is ready
jQuery(document).ready(function() {
    // attach events to the our show
    attachOurShowsEvent();

    // take care of tab menu for the most popular
    target = jQuery("#home_mp_panel");
    if (target[0]) target.tabs({ fxAutoHeight: false });

    // change the css of most popular show listings for linebreak
    target = jQuery("#cat_hl_165216 #col2 div:nth-child(3)");
    if (target[0]) target[0].className += " last-show";

    // change the css of most popular video listings for linebreak
    target = jQuery("#cat_hl_164886 span:nth-child(4)");
    if (target[0]) target[0].className += " second-row-videos";

    // truncate video titles
    target = jQuery("#cat_hl_164886 a.linkItem");
    if (target[0]) truncateTitle(target, 20);

    // truncate show titles
    target = jQuery("#cat_hl_165216 span.text a");
    if (target[0]) truncateTitle(target, 37);

    // change the css name for the last quad on home
    target = jQuery("#cat_hl_164885 span.even");
    if (target[0]) target[target.length - 1].className += " last";

    target = jQuery("#cat_hl_164888 span.even");
    if (target[0]) target[target.length - 1].className += " last";


    // top menu
    jQuery("#cat_hl_164498 li").each(function(i) { this.firstChild.className += (' navItem' + (i + 1)); });

    // HD page
    doCorner("div.ninehd_nav", "5px"); 	/* top menu */
    doCorner("div.ninehd_nav li a", "5px");

    // Home page
    doCorner("#cat_hl_164889", "5px"); 	/* discussion panel */
    doCorner("#cat_hl_164889 .onlytitle", "5px"); /* discussion comments */
    doCorner("#cat_hl_164887", "5px"); 	/* vote panel */
    doCorner("#home_mp_panel ul li", "5px top"); /* most popular - tabs */
    doCorner("#cat_hl_165216", "5px bottom tr"); /* most popular - shows */
    doCorner("#cat_hl_164886", "5px bottom tr"); /* most popular - videos */
    doCorner("#cat_hl_166916", "5px"); 	/* RHC promo */

    // Tiered pages
    doCorner("#article2056 .leftContent .date .nextEpisode", "5px");
    doCorner(".tvshow_nav ul", "5px");
    doCorner(".tvshow_nav ul li a", "5px");
    doCorner(".index-control-panel .next-episode-box", "5px"); /* episode page - next episode*/

    //Initialise mini TV Guide
    doTVGuide(".content_right .rhs-tvquide");
    doCorner(".rhs-tvquide .jcarousel-clip-horizontal ul li a", "5px top");

    // hide the bottom navigator for episode page if no item is displayed
    target = jQuery(".previous-episodes-panel .episode-item-panel");
    if (target.length > 0) {
        jQuery("#index_control_button").show();
    };

    // set css name for the bottom navigator for episode page
    target = jQuery("#index_control_button table td");
    if (target.length == 2) {
        target[0].className = "previous";
        target[1].className = "next";
    };

    doTVGuide(".content_right .rhs-tvquide");
    doCorner(".rhs-tvquide .jcarousel-clip-horizontal ul li a", "5px top");

    //Initialise primetime TV Guide
    doTVGuide(".site_header .tvguide-top-panel",
	{
	    tabs:
		[
			"M",
			"T",
			"W",
			"T",
			"F",
			"S",
			"S"
		],
	    containerClassName: "ch9PrimeTimeTVGuide",
	    tabIdName: "ch9tv_PrimetimeShows",
	    postcode: 2000,
	    showDays: true,
	    hasScrolling: false,
	    rotateDays: false,
	    timeStart: "19:00:00",
	    timeEnd: "23:59:59",
	    displayLimit: 4,
	    showDetails: false
	});
    //doCorner(".tvguide-top-panel .ch9PrimeTimeTVGuide ul.tabs-nav","5px top");
    jQuery(".tvguide-top-panel .ch9PrimeTimeTVGuide .tabs-nav li:nth-child(1)").addClass("first");
    jQuery(".tvguide-top-panel .ch9PrimeTimeTVGuide .tabs-nav li:nth-child(7)").addClass("last");
    //jQuery("#nw_ft_sub").css("padding-bottom", "0");

});

// do jquery corner only if the object exists
function doCorner(selector, attr) {
    var jObj = jQuery(selector);
    if ((jObj.length != 0) && jObj[0]) {
        jObj.corner(attr);
    }
};

// do jquery corner only if the object exists
function doTVGuide(selector, attr) {
    var jObj = jQuery(selector);
    if ((jObj.length != 0) && jObj[0]) {
        if (attr) {
            jObj.ch9tvguide(attr);
        }
        else {
            jObj.ch9tvguide();
        }

    }
};



// attach events to the link and panel for our shows 
function attachOurShowsEvent() {
    if (jQuery("#footer_shows")[0]) {
        // remove bottom border of the three highlights
        jQuery('#cat_hl_167082>span:last').css('border-bottom', 'none');
        jQuery('#cat_hl_167084>span:last').css('border-bottom', 'none');
        jQuery('#cat_hl_167085>span:last').css('border-bottom', 'none');

        var ourShowsPanel = jQuery(".our-shows-panel")[0];
        var ourShowsPanel2 = jQuery("#ourshows_mini_menu")[0];
        ourShowsPanel.innerHTML = jQuery("#footer_shows").html();
        
        if (typeof jQuery("#ourshows_mini_menu")[0] != 'undefined') {
            ourShowsPanel2.innerHTML = jQuery("#footer_shows").html();
        }

        // find the link for our show
        var ourShowsLink = jQuery("#cat_hl_164498 li:nth-child(3) a")[0];

        //ourShowsLink.style.color = "#ffffff";

        // attach mouse over event to the link
        ourShowsLink.onmouseover = function(event) {
            // the panel needs mouse over and out event as well
            toggleOurShows(true, ourShowsLink, ourShowsPanel);
            ourShowsPanel.onmouseover = function(event) {
                toggleOurShows(true, ourShowsLink, ourShowsPanel);
            };
            ourShowsPanel.onmouseout = function(event) {
                toggleOurShows(false, ourShowsLink, ourShowsPanel);
            };
        };
        ourShowsLink.onmouseout = function(event) {
            toggleOurShows(false, ourShowsLink, ourShowsPanel);
        };


        var ourVideosPanel = jQuery(".our-video-panel")[0];
        var ourVideosPanel2 = jQuery("#ourshows_mini_menu")[0];
        ourVideosPanel.innerHTML = jQuery("#cat_hl_220463").html();

        if (typeof jQuery("#ourshows_mini_menu")[0] != 'undefined') {
            ourVideosPanel2.innerHTML = jQuery("#cat_hl_220463").html();
        }

        // find the link for our show
        var ourVideosLink = jQuery("#cat_hl_164498 li:nth-child(5) a")[0];

        //ourVideosLink.style.color = "#ffffff";

        // attach mouse over event to the link
        ourVideosLink.onmouseover = function(event) {
            // the panel needs mouse over and out event as well
            toggleOurShows(true, ourVideosLink, ourVideosPanel);
            ourVideosPanel.onmouseover = function(event) {
                toggleOurShows(true, ourVideosLink, ourVideosPanel);
            };
            ourVideosPanel.onmouseout = function(event) {
                toggleOurShows(false, ourVideosLink, ourVideosPanel);
            };
        };
        ourVideosLink.onmouseout = function(event) {
            toggleOurShows(false, ourVideosLink, ourVideosPanel);
        };





    }
};

// display or hide the our shows panel
function toggleOurShows(isOver, link, panel) {
    //link.style.backgroundColor = isOver ? "#34b6e8" : "transparent";
    panel.style.display = isOver ? "block" : "none";

    // change the position of the panel depending on the current position of the link
    if (isOver) {
        panel.style.left = jQuery(link).position().left + "px";
        panel.style.top = jQuery(link).position().top + 25 + "px";

        //panel.style.top = jQuery(link).position().top + jQuery(link).height() + getInt(jQuery(link).css("padding-top")) + "px";
    };
};

function truncateTitle(links, maxLength) {
    for (var i = 0; i < links.length; i++) {
        var html = links[i].innerHTML;
        if (html.length > maxLength) {
            links[i].innerHTML = html.substring(0, maxLength) + "...";
        };
    };
};

function getInt(val) {
    var number;
    var pos = val.indexOf("px");
    if (pos > 0) {
        var temp = val.substring(0, pos);
        number = parseInt(temp);
    }
    else if (val.length > 0 && !isNaN(val)) {
        number = val;
    }
    return number;
};

/***************************************
* End page structure functions
**************************************/







/***************************************
* Start /tvguide.aspx functions
**************************************/

// global variables and constants
var NO_TVGUIDE_MESSAGE = "";
var DAY_LIST = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

/* get & render the tv guide */
function displayTVGuide(panelId, postcodePanelId, days, isPostback) {
    panelId = panelId || "tvguide_panel";
    postcodePanelId = postcodePanelId || "postcode_panel";
    days = days || 7;
    isPostback = isPostback || false;

    // update the right location to the current posecode
    jQuery(".station-name").html("in postcode " + getCurrentLocation());
    jQuery(".location-name").html(getCurrentLocation());
    if (!isPostback) {
        jQuery("#tvguide_postcode").keydown(function(e) {
            if (e.keyCode == 13) {
                return changePostcode();
            }
            else {
                return true;
            }
        });
        jQuery("#postcode_panel .postcode-input a").click(function() {
            return changePostcode();
        });
    }
    jQuery("#" + postcodePanelId).hide();

    // get the list and call callback
    var startDate = new Date();
    var startDateString = formatDate(startDate);
    startDate.setDate(startDate.getDate() + days);
    var endDateString = formatDate(startDate);
    $.getJSON("http://data.ninemsn.com.au/Services/Service.axd?ServiceName=Channel9&ServiceAction=TVguide&startdate=" + startDateString + "&enddate=" + endDateString + "&postcode=2000&AttributeStyle=false&ServiceFormat=JSONAUTO&callback=?", function(data) { callbackTVGuide(data, panelId, postcodePanelId); });
};

// return the current location
function getCurrentLocation() {
    var postcode = $.cookie("ch9TVGuidePostcode");
    if (!postcode) {
        postcode = 2000;
    }
    return postcode;
};

// update the station and location as to the new postcode
function changePostcode() {
    var postcodeVal = jQuery("#tvguide_postcode").attr("value");
    var errorDiv = jQuery("#postcode_panel .errorNotification");
    errorDiv.hide(); //Hide error messages

    if (postcodeVal == "") {
        errorDiv.html("Please specify a postcode.").show();
    }
    else if (!validatePcode(postcodeVal)) {
        errorDiv.html("'" + postcodeVal + "' is not a valid postcode. Please enter a three or four digit number.").show();
    }
    else {
        //Set new postcode value
        var date = new Date();
        date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
        $.cookie("ch9TVGuidePostcode", postcodeVal, { expires: date });
        displayTVGuide("tvguide_panel", "postcode_panel", 7, true);
    }
    return false;
};

function validatePcode(pcode) {
    if (!pcode || isNaN(pcode) || pcode.length < 3 || pcode.length > 4) {
        return false;
    }
    else if (pcode.match(/\d{4}/)) {
        return true;
    }
    else {
        return false;
    }
}



// return date formatted for tv guide json call
function formatDate(date) {
    return date.getFullYear() + "/" + parseInt(date.getMonth() + 1) + "/" + date.getDate();
}

// callback function for tv guide json
function callbackTVGuide(data, panelId, postcodePanelId) {
    var tvguidePanel = jQuery("#" + panelId)[0];
    if (tvguidePanel && data && data.TvGuideList && data.TvGuideList.TvGuide) {
        try {
            jQuery("#" + panelId).css("text-align", "left");
            var output = "";
            var list = data.TvGuideList.TvGuide;
            var currentDate;
            for (var i = 0; i < list.length; i++) {
                var thisStartTime = list[i].StartTime;
                var thisDate = getDateFormat(thisStartTime, "date");
                var thisTitle = list[i].Title;

                if (thisDate != currentDate) {
                    if (i > 0) {
                        output += '</div></div>';
                    }
                    var menuLink = thisDate.substring(0, thisDate.indexOf(" ")).toLowerCase();
                    output += '<a name="' + menuLink + '"></a><div class="day-menu-panel">Jump to:';
                    for (var j = 0; j < DAY_LIST.length; j++) {
                        output += '<span class="day"><a href="#' + DAY_LIST[j].toLowerCase() + '">' + DAY_LIST[j] + '</a></span>';
                        if (j < DAY_LIST.length - 1) {
                            output += '<span class="divider">|</span>';
                        }
                    };
                    output += '</div><div class="daily-guide"><div class="date">' + thisDate + '</div>'
					+ '<div class="tv-list-panel">';
                }
                var isPrime = isPrimeTime(thisStartTime);
                output += '<div class="tv-list item' + i + '">'
					+ '<div class="starttime' + (isPrime ? " prime-time" : "") + '">' + getDateFormat(thisStartTime, "time") + '</div>'
					+ '<div class="title' + (isPrime ? " prime-time" : "") + '">'
					+ '<a href="' + getChannel9Link(thisTitle) + '" title="' + list[i].Description + '">'
					+ thisTitle + '</a></div>'
                //+ '<div class="desc">' + list[i].Description + '</div>'
					+ '</div>';

                currentDate = thisDate;
                // put underline except the last list of the day
                if (i < list.length - 1) {
                    var nextDate = getDateFormat(list[i + 1].StartTime, "date");
                    if (nextDate == currentDate) {
                        output += '<div class="separator"></div>';
                    };
                };
            };
            tvguidePanel.innerHTML = output;

            var postcodePanel = jQuery("#" + postcodePanelId)[0];
            if (postcodePanel) {
                postcodePanel.style.display = "block";
            };
        }
        catch (e) {
            tvguidePanel.innerHTML = NO_TVGUIDE_MESSAGE;
        }
    }
    else {
        tvguidePanel.innerHTML = NO_TVGUIDE_MESSAGE;
    }
};

// get the link for the shows
function getChannel9Link(title) {
    var url = title.replace(/\ /g, "");
    url = url.replace(/\,/g, "");
    url = url.replace(/\_/g, "");
    url = url.replace(/\!/g, "");
    url = url.replace(/\:/g, "");
    url = url.replace(/\&/g, "");
    url = url.replace(/\'/g, "");
    url = url.replace(/\./g, "");
    url = url.replace(/\-/g, "");
    url = url.replace(/\(/g, "");
    url = url.replace(/\)/g, "");
    url = url.replace(/\*/g, "");
    url = url.replace(/\^/g, "");
    url = url.replace(/\#/g, "");
    url = url.replace(/\?/g, "");
    url = url.toLowerCase();
    return "/" + url + "/";
};

// get formated date string ex) mode=date: Monday January 1, 2009, mode-time: 1:00 AM
function getDateFormat(dateString, mode) {
    var date = (new Date(dateString)).toLocaleString();
    if (mode) {
        var pos = date.indexOf(":");
        var dateTemp = date.substring(0, pos);
        pos = dateTemp.lastIndexOf(" ")

        if (mode == "date") {
            date = date.substring(0, pos);

            // change the position of the coma
            pos = date.indexOf(",");
            if (pos > 0) {
                date = date.substring(0, pos) + date.substring(pos + 1, date.length);
                pos = date.lastIndexOf(" ");
                date = date.substring(0, pos) + "," + date.substring(pos, date.length);
            };
        }
        else if (mode == "time") {
            date = date.substring(pos + 1, date.length);
            pos = date.lastIndexOf(":");
            date = date.substring(0, pos) + date.substring(pos + 3, date.length);
        };
    };

    return date;
};

function isPrimeTime(dateTime) {
    date = new Date(dateTime);

    var dateString = date.toLocaleString();
    var pos = dateString.indexOf(":");
    var dateTemp = dateString.substring(0, pos);
    pos = dateTemp.lastIndexOf(" ")

    var primeStart = new Date(dateString.substring(0, pos) + " 18:00:00");
    var primeEnd = new Date(dateString.substring(0, pos) + " 22:00:00");

    return (primeStart.getTime() - date.getTime() <= 0) && (date.getTime() - primeEnd.getTime() < 0);
};

/***************************************
* End /tvguide.aspx functions
**************************************/










