var browser_IE;
var browser_NS4;
var browser_W3C;
var platForm;
var isMac;
browser_IE  = (document.all && navigator.appName == 'Microsoft Internet Explorer') ? true : false;
browser_NS4 = (document.layers) ? true : false;
browser_W3C = (!document.all && document.getElementById) ? true : false;

platForm=navigator.platform;
isMac=platForm.indexOf("Mac");

rnd.today=new Date();
rnd.seed=rnd.today.getTime();


function validateSearch()
                        {
                            if(document.searchShow.query.value == "") {
                                alert("Please enter a search term!")
                                return false;
                            } else {
                              if (document.searchShow.site_codename[1].checked == true){
                               document.searchShow.submit();
                              }
                              else{
                               document.googleSearchCTV.query.value = document.searchShow.query.value;
                               document.googleSearchCTV.submit();
                               return false;
                              }
                            }
                        }

function rnd() {
	rnd.seed = (rnd.seed*9301+49297) % 233280;
	return rnd.seed/(233280.0);
}

function rand(number) {
	return Math.ceil(rnd()*number);
}

// translate date format from yyyy-mm-dd to Date
function splitDate(inputdate,separator) {
  arrayOfStrings = inputdate.split(separator);
  outputdate= new Date(arrayOfStrings[0],arrayOfStrings[1],arrayOfStrings[2]);
  return outputdate;
}

function framesPopUp(filename,winTitle, winName, winX, winY) {
 winName = "__" + winName;
 var regex = /\W+/;
 if( regex.test(winName) ) {
        winName = winName.replace(/\W+/, '_');
 }
 params = "width="+ winX +",height="+winY;
 winExec = winName +"= window.open('','"+winName+"', params)"
 content = "<html><head><title>"+winTitle+"</title><script>window.onload=function(){}</script></head><frameset rows='0,*' frameborder='NO' border='0' framespacing='0'><frame name='topFrame' scrolling='NO' noresize src='about:blank'><frame name='mainFrame' src='"+ filename +"' scrolling=AUTO></frameset><noframes><body bgcolor='#FFFFFF' text='#000000'></body></noframes></html>"
 eval(winExec);
 eval(winName + ".document.open()")
 eval(winName + ".document.write(content)")
 eval(winName + ".document.close()")
}

function _open_popup_window(w, h, link_url, slug, title){
	var regex = /\W+/;
	if( regex.test(slug) ){
		slug = slug.replace(/\W+/, '_');
	}
	if( w != '' && h != '' ) {
		framesPopUp(link_url, title, slug, w, h);
		return false;
	}
	return true;
}

function playVideo(video_link_high, video_link_low, clip_start, clip_end, clip_caption, archive, slug, sortdate, clip_id, hub){
	var hubcheck;
	if (hub == '') {
			hubcheck = 'TopStories';
	} else {
			hubcheck = hub;
	}
	var w = 755, h = 519; // adjust width and height here.
	var vUrl = "http://www.ctv.ca/servlet/HTMLTemplate/!ctvVideo/"
		+ archive + "/"
		+ slug + "/"
		+ sortdate + "/?"
; // the video url
	var qString = 'hub=' + hubcheck + '&'
		+ 'video_link_high=' + video_link_high + '&'
		+ 'video_link_low=' + video_link_low + '&'
		+ 'clip_start=' + clip_start + '&'
		+ 'clip_end=' + clip_end + '&'
		+ 'clip_caption=' + escape(clip_caption) + '&'
		+ 'clip_id=' + clip_id;

	window.open( vUrl + qString
		+'&subhub=video','ctvVideo','width=' + w + ',height=' + h
		+',status=no,scrollbars=no,resizable=no,toolbar=no,left=176,screenX=200,top=0,screenY=0');
}


function format_clip_duration(dur){
	// clip end:   00:02:50.43
	// clip_end     0:02:26
	// clip_end has one of the two above formats.

	var matches, format = "";

	var regexFormat1 = /^(\d{2}):(\d{2}):(\d{2}\.\d{2})$/
	var regexFormat2 = /^(\d+):(\d+):(\d+)$/

	if( regexFormat1.test(dur) ){
		matches = dur.match(regexFormat1);
	}
	else if( regexFormat2.test(dur) ){
		matches = dur.match(regexFormat2);
	}
	if( matches == null ) return ''; // didn't match either pattern.
	var durHours = parseInt(matches[1], 10);
	var durMins  = parseInt(matches[2], 10);
	var durSecs  = Math.floor(parseFloat(matches[3]));
	var durSeconds = durHours*60*60 + durMins*60 + durSecs;
	var one_hour = 60*60;
	var formattedSecs = (durSecs < 10) ? '0' + durSecs : durSecs;
	if( durSeconds > one_hour ){
		format = durHours + ':' + (durMins<10 ? '0'+durMins : durMins) + ':' + formattedSecs;
	}
	else{
		format = durMins + ':' + formattedSecs;
	}
	return format;
}


// Trims a string
function trim(str) {
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

var _thisPopWidth = "";
var _thisPopHeight = "";

/**
  * Used to correct the MAC date bug
  */
function fixCookieDate (date) {
	var base = new Date(0);
	var skew = base.getTime(); // dawn of (Unix) time - should be 0
	if (skew > 0) {  // Except on the Mac - ahead of its time
  	date.setTime (date.getTime() - skew);
	}
}


function setCookie (cookieName, cookieValue, expires, path) {
	fixCookieDate(expires);
	document.cookie =
		escape(cookieName) + '=' + escape(cookieValue)
		+ (expires ? '; EXPIRES=' + expires.toGMTString() : '')
		+ (path ? '; PATH=' + path : '');
}


//Used by search to figure out where we are in the set of returned records.
function UpdateStartRow(theForm, p_start_row, start_row_offset, p_nextPageType){
	var nextRow = eval(p_start_row) + eval(start_row_offset);
	var nextPage;
	if (nextRow < 0) nextRow = 1;
	//When going to a previous page, we must check to see if this is a special case
	//in which we have to return to the initial search results page.
	if ((start_row_offset < 0) &&
	(p_nextPageType == "SearchShows" && nextRow <= 4) ||
	(p_nextPageType == "SearchShowsDyn" && nextRow <= 3) ||
	(p_nextPageType == "SearchNews" && nextRow <= 8) ||
	(p_nextPageType == "SearchSpecials" && nextRow <= 6)) {
		nextPage = "/servlet/HTMLTemplate/!ctv/Search";
	} else {
		switch (p_nextPageType) {
			case "SearchShows"  : nextPage = "/servlet/HTMLTemplate/!ctv/Search/Shows"; break;
			case "SearchShowsDyn"  : nextPage = "/servlet/HTMLTemplate/!ctv/Search/ShowsDyn"; break;
			case "SearchNews"   : nextPage = "/servlet/HTMLTemplate/!ctv/Search/News"; break;
			case "SearchSpecials"   : nextPage = "/servlet/HTMLTemplate/!ctv/Search/Specials"; break;
			default         : nextPage = "/servlet/HTMLTemplate/!ctv/Search"; break;
		}
	}
	theForm.current_row.value = nextRow;
	theForm.start_row.value = theForm.current_row.value;
	theForm.action = nextPage;
	theForm.submit();
}

// programs and local stations select
currentMenu = "none";
if(document.all){
document.onmouseup = showCurrentMenu;
}
else{
window.addEventListener("load",addBodyListener,false);


}

function addBodyListener(){
document.getElementsByTagName('body')[0].addEventListener("mouseup",showCurrentMenu,false);
}

function showMenu(menu){
currentMenu = menu;

showCurrentMenu();
}
function showCurrentMenu(){


        if(currentMenu != "none"){
if(document.getElementById(currentMenu).style.visibility == "visible"){
document.getElementById("programs").style.visibility= "hidden";
document.getElementById("local").style.visibility = "hidden";

/* One Clip Hide Start */

if (document.getElementById('Player') !=null)
{
if (document.getElementById('Player').style.visibility == "hidden")

{

document.getElementById("Player").style.visibility = "visible";

}

else

{

document.getElementById("Player").style.visibility = "visible";

}

}

/* One Clip Hide End */

currentMenu = "none";

}
else if(currentMenu == "programs"){

document.getElementById("programs").style.visibility = "visible";

/* One Clip Hide Start */

if (document.getElementById('Player') !=null)
{
if (document.getElementById('Player').style.visibility == "visible")

{

document.getElementById("Player").style.visibility = "hidden";

}

else

{

document.getElementById("Player").style.visibility = "visible";

}

}
/* One Clip Hide End */

document.getElementById("programs").style.height = frames["programs"].document.getElementById("programsBody").offsetHeight + "px";
document.getElementById("local").style.visibility = "hidden";

}
else if(currentMenu == "local"){
document.getElementById("programs").style.visibility = "hidden";
document.getElementById("local").style.visibility = "visible";

document.getElementById("local").style.height = frames["local"].document.getElementById("localBody").offsetHeight + "px";

/* One Clip Hide Start */

if (document.getElementById('Player') !=null)
{
if (document.getElementById('Player').style.visibility == "hidden")

{

document.getElementById("Player").style.visibility = "visible";

}

else

{

document.getElementById("Player").style.visibility = "visible";

}

}

/* One Clip Hide End */

}
}
else{

}
}


/**
 * FlashObject v1.3c: Flash detection and embed - http://blog.deconcept.com/flashobject/
 *
 * FlashObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof com == "undefined") var com = new Object();
if(typeof com.deconcept == "undefined") com.deconcept = new Object();
if(typeof com.deconcept.util == "undefined") com.deconcept.util = new Object();
if(typeof com.deconcept.FlashObjectUtil == "undefined") com.deconcept.FlashObjectUtil = new Object();
com.deconcept.FlashObject = function(swf, id, w, h, ver, c, useExpressInstall, quality, xiRedirectUrl, redirectUrl, detectKey){
  if (!document.createElement || !document.getElementById) return;
  this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
  this.skipDetect = com.deconcept.util.getRequestParameter(this.DETECT_KEY);
  this.params = new Object();
  this.variables = new Object();
  this.attributes = new Array();
  this.useExpressInstall = useExpressInstall;

  if(swf) this.setAttribute('swf', swf);
  if(id) this.setAttribute('id', id);
  if(w) this.setAttribute('width', w);
  if(h) this.setAttribute('height', h);
  if(ver) this.setAttribute('version', new com.deconcept.PlayerVersion(ver.toString().split(".")));
  this.installedVer = com.deconcept.FlashObjectUtil.getPlayerVersion(this.getAttribute('version'), useExpressInstall);
  if(c) this.addParam('bgcolor', c);
  var q = quality ? quality : 'high';
  this.addParam('quality', q);
  var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
  this.setAttribute('xiRedirectUrl', xir);
  this.setAttribute('redirectUrl', '');
  if(redirectUrl) this.setAttribute('redirectUrl', redirectUrl);
}
com.deconcept.FlashObject.prototype = {
  setAttribute: function(name, value){
    this.attributes[name] = value;
  },
  getAttribute: function(name){
    return this.attributes[name];
  },
  addParam: function(name, value){
    this.params[name] = value;
  },
  getParams: function(){
    return this.params;
  },
  addVariable: function(name, value){
    this.variables[name] = value;
  },
  getVariable: function(name){
    return this.variables[name];
  },
  getVariables: function(){
    return this.variables;
  },
  createParamTag: function(n, v){
    var p = document.createElement('param');
    p.setAttribute('name', n);
    p.setAttribute('value', v);
    return p;
  },
  getVariablePairs: function(){
    var variablePairs = new Array();
    var key;
    var variables = this.getVariables();
    for(key in variables){
      variablePairs.push(key +"="+ variables[key]);
    }
    return variablePairs;
  },
  getFlashHTML: function() {
    var flashNode = "";
    if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
      if (this.getAttribute("doExpressInstall")) this.addVariable("MMplayerType", "PlugIn");
      flashNode = '<embed type="application/x-shockwave-flash" wmode="opaque" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'"';
      flashNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
      var params = this.getParams();
       for(var key in params){ flashNode += [key] +'="'+ params[key] +'" '; }
      var pairs = this.getVariablePairs().join("&");
       if (pairs.length > 0){ flashNode += 'flashvars="'+ pairs +'"'; }
      flashNode += '/>';
    } else { // PC IE
      if (this.getAttribute("doExpressInstall")) this.addVariable("MMplayerType", "ActiveX");
      flashNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'">';
      flashNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
 	flashNode += '<param name="wmode" value="opaque" />';
      var params = this.getParams();
      for(var key in params) {
       flashNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
      }
      var pairs = this.getVariablePairs().join("&");
      if(pairs.length > 0) {flashNode += '<param name="flashvars" value="'+ pairs +'" />';}
      flashNode += "</object>";
    }
    return flashNode;
  },
  write: function(elementId){
    if(this.useExpressInstall) {
      // check to see if we need to do an express install
      var expressInstallReqVer = new com.deconcept.PlayerVersion([6,0,65]);
      if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
        this.setAttribute('doExpressInstall', true);
        this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
        document.title = document.title.slice(0, 47) + " - Flash Player Installation";
        this.addVariable("MMdoctitle", document.title);
      }
    } else {
      this.setAttribute('doExpressInstall', false);
    }
    if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
      var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
      n.innerHTML = this.getFlashHTML();
    }else{
      if(this.getAttribute('redirectUrl') != "") {
        document.location.replace(this.getAttribute('redirectUrl'));
      }
    }
  }
}

/* ---- detection functions ---- */
com.deconcept.FlashObjectUtil.getPlayerVersion = function(reqVer, xiInstall){
  var PlayerVersion = new com.deconcept.PlayerVersion(0,0,0);
  if(navigator.plugins && navigator.mimeTypes.length){
    var x = navigator.plugins["Shockwave Flash"];
    if(x && x.description) {
      PlayerVersion = new com.deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
    }
  }else{
    try{
      var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
      for (var i=3; axo!=null; i++) {
        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
        PlayerVersion = new com.deconcept.PlayerVersion([i,0,0]);
      }
    }catch(e){}
    if (reqVer && PlayerVersion.major > reqVer.major) return PlayerVersion; // version is ok, skip minor detection
    // this only does the minor rev lookup if the user's major version 
    // is not 6 or we are checking for a specific minor or revision number
    // see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
    if (!reqVer || ((reqVer.minor != 0 || reqVer.rev != 0) && PlayerVersion.major == reqVer.major) || PlayerVersion.major != 6 || xiInstall) {
      try{
        PlayerVersion = new com.deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
      }catch(e){}
    }
  }
  return PlayerVersion;
}
com.deconcept.PlayerVersion = function(arrVersion){
  this.major = parseInt(arrVersion[0]) || 0;
  this.minor = parseInt(arrVersion[1]) || 0;
  this.rev = parseInt(arrVersion[2]) || 0;
}
com.deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
  if(this.major < fv.major) return false;
  if(this.major > fv.major) return true;
  if(this.minor < fv.minor) return false;
  if(this.minor > fv.minor) return true;
  if(this.rev < fv.rev) return false;
  return true;
}
/* ---- get value of query string param ---- */
com.deconcept.util = {
  getRequestParameter: function(param){
    var q = document.location.search || document.location.hash;
    if(q){
      var startIndex = q.indexOf(param +"=");
      var endIndex = (q.indexOf("&", startIndex) > -1) ? q.indexOf("&", startIndex) : q.length;
      if (q.length > 1 && startIndex > -1) {
        return q.substring(q.indexOf("=", startIndex)+1, endIndex);
      }
    }
    return "";
  }
}

/* add Array.push if needed (ie5) */
if (Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }}

/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = com.deconcept.util.getRequestParameter;
var FlashObject = com.deconcept.FlashObject;

function getCookie (cookieName) {
  var cookieValue = null;
  var posName = document.cookie.indexOf(escape(cookieName) + '=');
  if (posName != -1) {
    var posValue = posName + (escape(cookieName) + '=').length;
    var endPos = document.cookie.indexOf(';', posValue);
    if (endPos != -1) {
      cookieValue = unescape(document.cookie.substring(posValue,endPos));
    } else {
      cookieValue = unescape(document.cookie.substring(posValue));
    }
  }
  return cookieValue;
}

function fixCookieDate (date) {

	var base = new Date(0);

	var skew = base.getTime(); // dawn of (Unix) time - should be 0

	if (skew > 0) {  // Except on the Mac - ahead of its time

  	date.setTime (date.getTime() - skew);

	}

}





function setCookie (cookieName, cookieValue, expires, path) {

	fixCookieDate(expires);

	document.cookie =

		escape(cookieName) + '=' + escape(cookieValue)

		+ (expires ? '; EXPIRES=' + expires.toGMTString() : '')

		+ (path ? '; PATH=' + path : '');

}



function setCookie (cookieName, cookieValue, expires, path, domain) {

	fixCookieDate(expires);

	document.cookie =

		escape(cookieName) + '=' + escape(cookieValue)

		+ (expires ? '; EXPIRES=' + expires.toGMTString() : '')

		+ (path ? '; PATH=' + path : '')

		+ (domain? '; DOMAIN=' + domain : '');

}

var now = new Date();
var one_year= new Date(now.getTime() + 1000 * 60 * 60 * 24 * 365);

function removeFeatureBox()
{
var getRemove = document.getElementById("removeFeatures");
var sT = "";
if (getRemove != null)
{
    var totalT = getRemove.getElementsByTagName('td');
    for (i = 0; i < totalT.length; i++)
    {
       if (totalT[i].className == "middleBodyRoundAM")
       {
            sT = totalT[i].innerHTML;
            sT = trim(sT);
            if (sT == "")
            {
                document.getElementById("removeFeatures").style.display = "none";
            }
       }
    }
}
}


function setNoAd()
{
var tmpDate1=new Date();
var tmpDate2=new Date();
var getM = tmpDate1.getMinutes() + 5;
tmpDate2.setHours(getM / 60 + tmpDate1.getHours());
tmpDate2.setMinutes(getM % 60);
setCookie("NoAd", "1", tmpDate2, "/",".ctv.ca");
}

