﻿/*
Please use ONLY closed-style commenting (like this one)
Don't use the open-ended two-slashes method
*/

/* this will get changed if there is an error */
var tvgPageStatus = 200;
 
var isIE = document.all?true:false;

// firefox flag
var isFF = (navigator.userAgent.toLowerCase().indexOf("firefox")>=0);

// Safari Flag
var isSafari = (navigator.userAgent.toLowerCase().indexOf("safari")>=0);

// Opera Flag
var isOpera = (navigator.userAgent.toLowerCase().indexOf("opera")>=0);

// flag for ipad / iphone
var isAppleMobile = (navigator.userAgent.toLowerCase().indexOf("ipad")>=0) || (navigator.userAgent.toLowerCase().indexOf("iphone")>=0);

// flag for ipad
var isiPad = (navigator.userAgent.toLowerCase().indexOf("ipad")>=0);

function photocreditcontainer()
{
	this.PhotoCredits = new Array();
	this.AddCredit = function(credit)
	{
	   this.PhotoCredits[this.PhotoCredits.length]=credit;
	};

   this.RenderCredits = function()
   {
       if (this.PhotoCredits.length !== 0)
       {
           document.write('Photo Credits: ');
           for(var i=0; i<this.PhotoCredits.length; i++)
           {
				if ( this.PhotoCredits[i] !== '' )
				{
					if (i!==0) document.write('; ');
					document.write(this.PhotoCredits[i]);
				}
          }
       }
	};
}

function getObjectIDFromURL(str)
{
    try
    {
        var m = str.match(/\/(\d+)$/);
        if(m){ return parseInt(m[1],10); }
    }
    catch(e)
    { 
    }
    
    return 0;
}

function getBrowserVersionNumber()
{
	var verno = 0.0;

	//test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
	if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
	{ 
		verno = new Number(RegExp.$1);
	}
	//test for MSIE x.x;
	else if (/MSIE\s+(\d+\.\d+)/.test(navigator.userAgent))
	{
		verno = new Number(RegExp.$1);
	}
	// test for safari
	else if (/Version\/(\d+\.\d+)\.*\d*\s+Safari/.test(navigator.userAgent))
	{
		verno = new Number(RegExp.$1);
	}
	// get version number for Chrome
	else if (/Chrome\/(\d+\.\d+)/.test(navigator.userAgent))
	{
		verno = new Number(RegExp.$1);
	}
	// get version number for Opera
	else if(navigator.userAgent.indexOf("Opera")>=0)
	{
		if (/Version\/(\d+\.\d+)/.test(navigator.userAgent))
		{
			verno = new Number(RegExp.$1);
		}
	}

	return verno;
}

/* used by listings but needs to be here */
function drawLocalizeLink()
{
	document.write("<a href='/listings/setup/localizeus.aspx?RedirectUrl=" + document.location.pathname + "' style='color:#CC0000;font-weight:bold;font-size:11px;'>&nbsp;change location/provider</a>");
}

function drawHomepageGridFrame(iWidth,iHeight)
{
	/* point to www for the grid IFraame except on QA or Dan's machine */
	var strGridIFrameServer	= "http://www.tvguide.com";
	
	if (strHostName.indexOf("dtepper")>=0) {
		strGridIFrameServer = "";
	}
	else if (strHostName.indexOf("qa")>=0) {
		strGridIFrameServer = "";
	}
	else if (strHostName.indexOf("devint")>=0) {
		strGridIFrameServer = "";
	}

	// document.write("<iframe style='width:"+iWidth+"px; height:"+iHeight+"px; overflow:hidden;' src='/listings/homepage.aspx?opt=0&amp;scr=0&amp;loc=0&amp;gw="+iWidth+"&amp;gh="+iHeight+"&amp;host="+document.location.hostname+"&amp;port="+document.location.port+"' frameborder='0' scrolling='no'></iframe>");	
	document.write("<iframe style='width:"+iWidth+"px; height:"+iHeight+"px; overflow:hidden;' src='"+strGridIFrameServer+"/PartnerGrid/Grids/iframe.aspx?w="+iWidth+"&h="+iHeight+"&partnerid=0&profileid=1' frameborder='0' scrolling='no'></iframe>");	
}

/* used by listings but needs to be here */
function drawListingsHiddenFrame()
{
	if(!(navigator.userAgent.toLowerCase().indexOf("safari")>=0))
	{
		var strDataServer = "tvlistings.tvguide.com";
		var strHost = document.location.hostname.toLowerCase().split('.');
		var strPort = document.location.port;
		switch(strHost[0])
		{
			case 'qa':
			case 'localhost':
				strDataServer = "tvgtstweb2.tvguide.com";
				break;
			case 'dtepper':
				strDataServer = "dtepper.tvguide.com";
				break;
			default: break;
		}
		if((strPort=="")||(strPort==80)) {
			document.write("<iframe style='height:1px; width:1px; display:none; visibility: hidden;' src='http://" + strDataServer + "/ListingsWeb/listings/ajaxwrap.htm' id='ajaxwrap' name='ajaxwrap'></iframe>");
		}
	}
}

var PhotoCredits = new photocreditcontainer();

/* listings variables for dart ads */
var strServiceProvider = "";
var strSearchKey = "";
var strTvObjectName = "";
var strTvObjectType = "";
var iTvObjectID = 0;
var iGridAds = 0;
var bHDTVOnlyFilter = false;
var optionGenreFilter   = 0;
var strRealURL = "";

/* grab search keyword */
var qs = document.location.search;
var mt = qs.match(/keyword=([^\&]+)/i);
if(mt)
{
    strSearchKey = mt[1];
}

function setDocDomain()
{
    var domParts = document.domain.split('.');
    switch(domParts.length)
    {
        case 0:
            break;
        case 1:
            break;
        default:
            document.domain = domParts[domParts.length-2] + '.' + domParts[domParts.length-1];
            break;
    }
}

/* set doc domain to tvguide.com so IFrames can communicate */
try
{
    setDocDomain();
}
catch(err)
{
}  

function commentCount(iContentID)
{
    var icnt = parseInt(Math.random()*100,10);
    document.write("<div class='cmt-cnt'>" + icnt + " comments...</div>");
}

function fmtNum(i)
{
    if(parseInt(i,10)<10)
    {
        return "0" + i;
    }
    return i;
}

function cmtdt(iContentID, Yr, Mo, Dy, Hr, Mn)
{    
    /* articles older than 12 hours show the timestamp
    newer articles show time respective to current
    all times used are from tvg servers */
    var maxHrs = 12;
    
    var stmp = "";
    var cdt = new Date(Yr, Mo, Dy, Hr, Mn, 0, 0); 
    
    /* fake random comment counts */
    var icnt = parseInt(Math.random()*100,10);

    /* age of article in milliseconds */         
    var msecs = tvgServerTimeUTC.getTime()-cdt.getTime();
    
    /* cutoff age in milliseconds */
    var cmsecs = maxHrs * 60 * 60 * 1000;
     
    /* if less than cutoff */
    if(msecs < cmsecs)
    {
        /* show time elapsed */
        var ihrs = parseInt( (msecs/(60*60*1000)), 10);
        var imns = parseInt( (msecs-(ihrs*60*60*1000)) / (60*1000), 10);
        
        switch(ihrs)
        {
            case 0: stmp = imns + " minutes ago";
                break;
            case 1: stmp = ihrs + "hour " + imns + " minutes ago";
                break;
            default: stmp = ihrs + "hours " + imns + " minutes ago";
                break;                        
        }
    }
    else
    {
        /* show absolute posting time */
        stmp = cdt.getFullYear() + "." + fmtNum(cdt.getMonth()+1) + "." + fmtNum(cdt.getDay());                
        stmp += " " + fmtNum(cdt.getHours()) + ":" + fmtNum(cdt.getMinutes()) + " GMT";
    }                   
    document.write("<div class='cmt-cnt'>" + stmp + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + icnt + " comments...</div>");
}

function modifyShareDate(dt) {
    var formattedDt = dt.toDateString();
    var formattedTimeString = formatTime(dt);
    var formattedDtWoYear = removeYearFromDateString(formattedDt);
    var formattedStringDt = formattedDtWoYear + " " + formattedTimeString;
    return formattedStringDt;
}

function removeYearFromDateString(formattedDt) {
    var temp = formattedDt.split(" ");
    var newString = temp[0] + ", " + temp[1] + " " + temp[2] + " ";
    return newString;
}


function setCookie(strName, strValue, iDays)
{
	var strCookie = strName + "=" + strValue + "; ";
	if(iDays!==0)
	{
	    var date = new Date();
	    date.setTime(date.getTime()+(iDays*24*60*60*1000));
		strCookie += "expires=" + date.toGMTString() + "; ";
	}
    var dom = document.domain;
    var tvg = ".tvguide.com";    
    if(dom.indexOf(tvg)==dom.length-tvg.length)
    {
        strCookie += "domain=" + tvg + "; ";
    } else {
        if (dom.indexOf("tvgol.local")!=-1) strCookie+="domain=.tvgol.local";
    }
	strCookie += "path=/";
	document.cookie = strCookie;
}

function readCookie(strName)
{
	var name = strName + "=";
	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(name) === 0) { return c.substring(name.length,c.length); }
	}
	return null;
}

function deleteCookie(strName)
{
	setCookie(strName, "", -1);
}

function GetXmlHttpObject(handler)
{ 
	var objXmlHttp = null;
	
    if (window.XMLHttpRequest) 
    {
        objXmlHttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) 
    {
		/* IE5 and IE6 */
        objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if(objXmlHttp)
	{
		objXmlHttp.onreadystatechange = handler;
	}

	return objXmlHttp;
}

/* callback func param is optional */
function ajaxRequest(url, elementid, callbackfunc) 
{
    var objXmlHttp = null;
     
    if (window.XMLHttpRequest) {
        objXmlHttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) { /* IE5 and IE6 */
        try {
            objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) { 
        }
    }
    
    if (objXmlHttp !== null) {
        objXmlHttp.onreadystatechange = function updateElem() {
            if (objXmlHttp.readyState == 4 || objXmlHttp.readyState == "complete") {
                var elem = document.getElementById(elementid);
                if (elem)
                    elem.innerHTML = objXmlHttp.responseText;
            }
            if (typeof callbackfunc != "undefined") {
                callbackfunc();
            }
        };
        objXmlHttp.open("GET", url, true);
        objXmlHttp.send(null);
    }
}

var strHostName = document.location.hostname.toLowerCase();
var strTvgHost = strHostName;
var strTvgServer = "";

if (strHostName.indexOf("-qa") > 0) {
    strTvgHost = "qa.tvguide.com";
}
else if (strHostName.indexOf("-stg") > 0) {
    strTvgHost = "staging.tvguide.com";
}
else if (strHostName.indexOf("-devint") > 0) {
    strTvgHost = "devint.tvguide.com";
}
else
    strTvgHost = "www.tvguide.com";

if(strHostName!=strTvgHost)
{
    strTvgServer = "http://" + strTvgHost;
}

function submitOVGSearch()
{
  var OVGSearchBox = document.getElementById("txtOVGSearch");
  var searchString;
  
  if(OVGSearchBox)
  {
      searchString = OVGSearchBox.value;
      if(searchString)
      {
        doOVGSearch(searchString);
      }
      else
        alert("Please enter some search text");
  }
}

function doOVGSearch(searchString)
{
  var submitURL = "http://video.tvguide.com/results.aspx?primary=SEARCH&searchvalue=";
  if(searchString)
  {
    searchString = EncodeCrossBrowser(searchString);
    submitURL += searchString;
    window.location=submitURL;
  }
}

function EncodeCrossBrowser(stringToEncode) {
    /* Use JavaScript built-in function IE 5.5+ and Netscape 6+ and Mozilla */
    if (typeof encodeURIComponent == "function")
    {
        return encodeURIComponent(stringToEncode);
	}
	return escape(stringToEncode);
}

function urchinTracker(strURL){}

function HideContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "block";
}
function ReverseContentDisplay(d) {
if(d.length < 1) { return; }
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}

function CheckIfCookiesEnabled() {
    setCookie('itester', 'yes', 1);
    if(readCookie('itester'))
    {
        deleteCookie('itester');
        return true;
    }
	return false;
}

/* prestitial */
if (typeof prestitial_active != 'undefined')
{
    if (prestitial_active) 
    {
        var current_datetime = new Date();
        var dt_prestitial_start = new Date(prestitial_start);
        var dt_prestitial_end = new Date(prestitial_end);
        if (CheckIfCookiesEnabled() && current_datetime > dt_prestitial_start && current_datetime < dt_prestitial_end) 
        {
            if (readCookie(prestitial_name) != 't') 
            {
                setCookie(prestitial_name, 't', 30);
                if (readCookie(prestitial_name) == 't') /* triple check that cookie was set */
                {
                    document.location.href = prestitial_url + "?o_url=" + EncodeCrossBrowser(document.location.href);
                }
            }
        }
    }
}


$(document).ready(function() {
    /* dvr tombstone */    
    if ($("#breakingnews-alert-w").length > 0) 
    {
        var bnanum = "0";
        if ($("#breakingnews-alert-w em").length > 0) 
        {
            bnanum = $("#breakingnews-alert-w em").attr("title");
        }
        if (readCookie('show_message') != bnanum) 
        {
            $('#breakingnews-alert-w').show("fast");
        }
        /* close button at right corner clicked */
        $('#breakingnews-alert-close').click(function() {
            $('#breakingnews-alert-w').hide("slow");
            setCookie('show_message', bnanum, 1);
        });
    }
});

function tvgMeeboPrep() {
    //tvgMeeboPrepare();
    return;
}

function tvgMeeboPrepare() {

	/* bypass meebo when hitting site as localhost */
    if (document.location.hostname == "localhost") { return; }

    window.Meebo || function(b) {
        function p() {
            return ["<", i, ' onload="var d=', g, ";d.getElementsByTagName('head')[0].",
j, "(d.", h, "('script')).", k, "='//", b.stage ? "stage-" : "", "cim.meebo.com/cim?iv=", a.v,
"&", q, "=", b[q], b[l] ? "&" + l + "=" + b[l] : "", b[e] ? "&" + e + "=" + b[e] : "", "'\"></", i, ">"].join("")
        }
        var f = window, a = f.Meebo = f.Meebo || function() { (a._ = a._ || []).push(arguments) }, d = document,
i = "body", m = d[i], r; if (!m) {
            r = arguments.callee; return setTimeout(function() { r(b) },
100)
        } a.$ = { 0: +new Date }; a.T = function(u) { a.$[u] = new Date - a.$[0] }; a.v = 4; var j = "appendChild",
h = "createElement", k = "src", l = "lang", q = "network", e = "domain", n = d[h]("div"), v = n[j](d[h]("m")),
c = d[h]("iframe"), g = "document", o, s = function() { a.T("load"); a("load") }; f.addEventListener ?
f.addEventListener("load", s, false) : f.attachEvent("onload", s); n.style.display = "none";
        m.insertBefore(n, m.firstChild).id = "meebo"; c.frameBorder = "0"; c.id = "meebo-iframe";
        c.allowTransparency = "true"; v[j](c); try { c.contentWindow[g].open() } catch (w) {
            b[e] =
d[e]; o = "javascript:var d=" + g + ".open();d.domain='" + d.domain + "';"; c[k] = o + "void(0);"
        } try {
            var t =
c.contentWindow[g]; t.write(p()); t.close()
        } catch (x) {
            c[k] = o + 'd.write("' + p().replace(/"/g,
'\\"') + '");d.close();'
        } a.T(1)
    } ({ network: "tvguide" });
}

function tvgMeeboReady() 
{
    getFullDARTad('meebo');
    //tvgMeeboGo();
    return;
}

function tvgMeeboGo() 
{
    Meebo('domReady');
    /*
    $(".h-tonightstv .h-b-c ul").each(function(i) {
    Meebo("makeLinksSharable", { element: this });
    });
    $(".h-tonightstv .h-b-c").each(function(i) {
    Meebo("makeImagesSharable", { element: this, minWidth: 90, minHeight: 60 });
    });
    $(".h-photogallery").each(function(i) {
    Meebo("makeImagesSharable", { element: this, minWidth: 100, minHeight: 100 });
    });
    $(".h-photogallery h2").each(function(i) {
    Meebo("makeLinksSharable", { element: this });
    });
    $(".h-breakingnews h2").each(function(i) {
    Meebo("makeLinksSharable", { element: this });
    });
    $(".h-breakingnews h3").each(function(i) {
    Meebo("makeLinksSharable", { element: this });
    });
    $(".h-breakingnews").each(function(i) {
    Meebo("makeImagesSharable", { element: this, minWidth: 90, minHeight: 60 });
    });
    $(".h-tvgexclusive-w").each(function(i) {
    Meebo("makeEverythingSharable", { element: this });
    });
    $(".h-fullepisodes .h-b-s").each(function(i) {
    Meebo("makeEverythingSharable", { element: this, minWidth: 90, minHeight: 35 });
    });
    */
    $(".news-article .img-container").each(function(i) {
        Meebo("makeImagesSharable", { element: this, minWidth: 100, minHeight: 100 });
    });
    $(".pge-photo-w").each(function(i) {
        Meebo("makeImagesSharable", { element: this, minWidth: 100, minHeight: 100 });
    });
    $(".pgo-main-w").each(function(i) {
        Meebo("makeImagesSharable", { element: this, minWidth: 100, minHeight: 100 });
    });
    /*
    $(".ovg-player-w").each(function(i) {
    Meebo("makeVideosSharable", { element: this });
    });
    $(".m-photogallery").each(function(i) {
    Meebo("makeImagesSharable", { element: this });
    });
    $(".m-photogallery .cfr-b-c h2").each(function(i) {
    Meebo("makeLinksSharable", { element: this });
    });
    */
}
