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

function $(i){return document.getElementById(i)}
function openIT(bbLink){

window.open(bbLink,'bctvVideo','width=1010,height=850,status=no,scrollbars=1,resizable=1,toolbar=0');

}


function ajaxFunc(xmlHtp)
{
  try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHtp=new XMLHttpRequest();  
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHtp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHtp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  return xmlHtp;

}

function switchHomeCities(newCityName)
{
document.getElementById("secondDropDown").style.display = "none";
    setCookie("CTVcityLocalData",newCityName,one_year,"/"); 

var xmlHttp;
    xmlHttp = ajaxFunc(xmlHttp);
    trigString = "/generic/generated/fragments/v2//" + newCityName + "Page.html";
    xmlHttp.onreadystatechange=changeCitiesNow;
    xmlHttp.open("GET", trigString, true);
    xmlHttp.send(null);
function changeCitiesNow()
{
             if(xmlHttp.readyState==4)
             {
   document.getElementById("localSiteData").innerHTML = xmlHttp.responseText
                      //returned
              }
}
}

function changeWeatherCity(newCityName)
{
    var xmlHttp;
    xmlHttp = ajaxFunc(xmlHttp);
    var cityName = "Toronto";
    if (newCityName != null)
    {
       cityName = newCityName;
    } 
    if (document.getElementById("weatherFiveDay") != null)
    {
    document.getElementById("weatherFiveDay").setAttribute('href', '/weatherCity?City=' + cityName);
    }

    trigString = "/servlet/HTMLTemplate?tf=ctv/v2/hub.html&cf=ctv/v2/ctv.cfg&hub=weatherWidget&City=" + cityName;
    xmlHttp.open("GET", trigString, true);
    xmlHttp.onreadystatechange = stateChanged;
    xmlHttp.send(null);

    function stateChanged()
        {

             if(xmlHttp.readyState==4)
             {
                   if (xmlHttp.responseText.indexOf("document.location") == -1) 
                   {
                       setCookie("CTVweatherCityInfo",cityName,one_year,"/");
                   }

		   eval(xmlHttp.responseText);
                   
                   //returned
              }
        }
}

function voteAnswer(answer_id, poll_id, pollN)
{
     var xmlHttp;
    xmlHttp = ajaxFunc(xmlHttp);
    trigString = "/servlet/HTMLTemplate?tf=ctv/v2/polls/responsePoll.html&cf=ctv/v2/ctv.cfg&poll=" + pollN + "&id=" + poll_id + "&pollid=" + poll_id + "&answerid=" + answer_id + "&save=_save" + poll_id;
    xmlHttp.open("GET", trigString, true);
    xmlHttp.send(null);

     xmlHttp.onreadystatechange=function()
          {
             if(xmlHttp.readyState==4)
             {
document.getElementById("resultPollss").innerHTML = "<table>" + xmlHttp.responseText + "</table>";
                      //returned
              }
        }
}

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;
}

var buttonRates = new Array();
function buttonRate(slug, createDate, uniqueId, upValue, downValue, checkId)
{
   var foundVal = false;
   if (buttonRates[upValue + downValue + uniqueId] == undefined)
   {
        buttonRates[upValue + downValue + uniqueId] = '1';
   }
   else
   {
        foundVal = true;
   }
   var cookieVal = getCookie("rateCommentCTV");
   if (cookieVal != null && foundVal == false)
   {
        var arrayI = cookieVal.split(",");
        var appendString = "";
        var newValI = upValue + downValue + uniqueId;
        for (i = 0; i < arrayI.length && i < 75; i++)
        {
             if (arrayI[i] == newValI)
             {
                  foundVal = true; 
             }
             if (i == 0)
             {
                  appendString = arrayI[0];
             }
             else
             {
                  appendString = appendString + "," + arrayI[i];
             }
        }
        if (foundVal == false)
        {
        appendString = newValI + "," + appendString;
        }
        now = new Date();
        one_year= new Date(now.getTime() + 1000 * 60 * 60 * 24 * 365);
        setCookie("rateCommentCTV",appendString,one_year,"/"); 
        if (getCookie("rateCommentCTV") == null) 
        {
             foundVal = true;
        }
   }
   else if (foundVal == false)
   {
        now = new Date();
        one_year= new Date(now.getTime() + 1000 * 60 * 60 * 24 * 365);
        var newValI = upValue + downValue + uniqueId;
        setCookie("rateCommentCTV",newValI,one_year,"/");
        if (getCookie("rateCommentCTV") == null)
        {
             foundVal = true;
        }
   }

   if (foundVal == false)
   {
   var xmlHttp;
   xmlHttp = ajaxFunc(xmlHttp);
   trigString = "/servlet/HTMLTemplate?tf=/ctv/mar/etracker/rateComment.html&cf=ctv/mar/ctv.cfg&slug=" + slug + "&createDate=" + createDate + "&uniqueId=" + uniqueId + "&upValue=" + upValue + "&downValue=" + downValue + "&operation=W&checkId=" + checkId;
   xmlHttp.open("GET", trigString, true);
   xmlHttp.send(null);
   
   xmlHttp.onreadystatechange=function()
	  {
              if(xmlHttp.readyState==4)
	      {
                  //alert(uniqueId);
                  if (upValue == 1) 
                  {
                      document.getElementById("U" + uniqueId).innerHTML = parseInt(document.getElementById("U" + uniqueId).innerHTML) + 1;
                  }
                  else
                  {
                      document.getElementById("D" + uniqueId).innerHTML = parseInt(document.getElementById("D" + uniqueId).innerHTML) + 1;
                  }
		  //eval(xmlHttp.responseText); 
	      }
	}
   }
}
var thisSlug;
var thisDate;

function getComment(slug, date)
{
   thisSlug = slug;
   thisDate = date;
   var xmlHttp;
   xmlHttp = ajaxFunc(xmlHttp);
   trigString = "/servlet/HTMLTemplate?tf=/ctv/mar/inc/commentAjax.html&cf=ctv/mar/ctv.cfg&slug=" + slug + "&date=" + date + "&allowComments=yes";
   xmlHttp.open("GET", trigString, true);
   xmlHttp.send(null);
   
   xmlHttp.onreadystatechange=function()
	  {
              if(xmlHttp.readyState==4)
	      {
		  commentInfo.innerHTML = xmlHttp.responseText; 
                  getRate(thisSlug, thisDate);
	      }
	}
}

function getRatePhoto(slug, date, photoID)
{
   var xmlHttp;
   xmlHttp = ajaxFunc(xmlHttp);
   trigString = "/servlet/HTMLTemplate?tf=/ctv/v2/ratePhoto.html&cf=ctv/mar/ctv.cfg&slug=" + slug + "&date=" + date + "&photoID=" + photoID;
   xmlHttp.open("GET", trigString, true);
   xmlHttp.send(null);

   xmlHttp.onreadystatechange=function()
          {
              if(xmlHttp.readyState==4)
              {
			eval(xmlHttp.responseText);
              }
        }
}

function ratePhoto(numVal)
{
   var xmlHttp;
   xmlHttp = ajaxFunc(xmlHttp);
   trigString = "/servlet/HTMLTemplate?tf=/ctv/mar/etracker/ratePhoto.html&cf=ctv/mar/ctv.cfg&slug=" + xmlName + "&createDate=20090729&uniqueId=newphoto" + curPhoto + "&upValue=" + numVal + "&downValue=" + 1 + "&operation=W"
   xmlHttp.open("GET", trigString, true);
   xmlHttp.send(null);

   xmlHttp.onreadystatechange=function()
          {
              if(xmlHttp.readyState==4)
              {
                  //alert(uniqueId);
                  //eval(xmlHttp.responseText);
                  getRatePhoto(xmlName, "photos", curPhoto);
              }
        }
}

var options = 
        {
		script:"/servlet/HTMLTemplate?tf=/ctv/v2/weatherCities.html&cf=ctv/mar/ctv.cfg&",
		varname:"textahead",
		json:true,
		shownoresults:false,
		maxresults:6,
                delay:0,
		callback: function (obj) 
		    { 
		        document.getElementById('CityID').innerHTML = obj.value.replace("<!--", ", ").replace("-->", "") 
		        document.getElementById("testinput").style.display = "none";
                        document.getElementById("testinput").value = obj.value.replace("<!--", ", ").replace("-->", "");
                document.getElementById("NotYourCity").style.display = "block";
                        changeWeatherCity(obj.value);
		    }
	};

function findCity()
{

   document.getElementById("testinput").style.display = "block";
   document.getElementById("NotYourCity").style.display = "none";
   if (firstTimeWeather == true)
   {
     document.getElementById("testinput").value = "Type in your city";
   }
}

function showSecondDrop()
{
    document.getElementById("secondDropDown").style.display = "block";
    document.getElementById("changeDropCity").innerHTML = "Close";
    document.getElementById("changeDropCity").setAttribute('href', 'javascript:closeDropWindow();');
}

function closeDropWindow()
{
    document.getElementById("changeDropCity").innerHTML = "Not your city?";
    document.getElementById("secondDropDown").style.display = "none";
    document.getElementById("changeDropCity").setAttribute('href', 'javascript:showSecondDrop();');
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }
}

function truncWords(idI)
{
    var trundataValue = document.getElementById(idI);
    if (trundataValue == null)
    {
        return false;
    }
    var theElements = trundataValue.getElementsByTagName("p");
    if (theElements == null)
    {
       return false;
    }
    for (z = 0; z < theElements.length; z++)
    {
        countPeriod = 0;
        newString = "";
        var dataValue = theElements[z].innerHTML;
        if (dataValue.length > 150 && dataValue.indexOf("href") == -1)
        {
            newString = dataValue.substring(0,150);
            for (i = 150; i < dataValue.length; i++)
            {
                if (dataValue.charAt(i) == ' ')
                {
                     newString = newString + "...";
                     break;
                }
                newString = newString + dataValue.charAt(i);               
            }
            theElements[z].innerHTML = newString;
        }
   }
}

function guessTimezone(){
 var MyTZ = "CFTO";
 //var dayLightSavingsTime = isDayLightSavingsTime();
 dayLightSavingsTime = false;
 var today = new Date();
 var currentOffset = (today.getTimezoneOffset() / 60) ;
 if(dayLightSavingsTime){currentOffset = currentOffset + 1;}

 switch(currentOffset){
 case 5: MyTZ ="Toronto";break;
 case 6: MyTZ ="Winnipeg";break;
 case 7: MyTZ ="Calgary";break;
 case 8: MyTZ ="Vancouver";break;
 //case 4: MyTZ ="Halifax";break;
 //case 3.5:   MyTZ ="Saint John";break;
 default:    MyTZ ="Toronto";break;
 }
 return MyTZ;
 }

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 setWeather()
{
	var cityInfo = getCookie("CTVweatherCityInfo");	
	if (cityInfo != null)
	{
                if (document.getElementById("CityID") != null)
                {
	       	     document.getElementById("CityID").innerHTML = cityInfo;
                }
		changeWeatherCity(cityInfo)
	}
	else
	{
		var timeZone = guessTimezone();
		changeWeatherCity(timeZone);
	}
}

function setLocalData()
{
	var cityLocalData = getCookie("CTVcityLocalData");
	if (cityLocalData != null)
	{
		switchHomeCities(cityLocalData)
	}
	else
	{
		var timeZone = guessTimezone();
		if (timeZone == "Toronto")
		{
			timeZone = "TorontoNew";
		}
		switchHomeCities(timeZone + "Home");
	}
}

function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?"));
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if ( aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return strReturn;
}

function includeTracking()
{

var CanTrack = ( typeof( s_gi ) == "function" );

if( !CanTrack )
{
        document.write('<div style="display:none">');
        _AUTO_TRACK = false;
        document.write('<scr' + 'ipt type="text/javascript" src="http://metrics.ctvdigital.net/global/globalpagetracking.js"></sc' + 'ript>');
        document.write('</div>');
}
}

function switchContestPage(omn, pageName)
{
Tracking.TrackCorporateLinkClicked(omn);
setTimeout ( 'switchWindow("' + pageName + '")', 1000 );
}

function switchWindow(newWin)
{
parent.window.location = newWin;
}

function launchPlayer(url)
{
	if(url != '')
	{
		var popup_1 = window.open(url,'player','left=5,top=5,toolbar=0,menubar=0,dependant=1,location=0,scrollbars=1,resizable=1,width=1010,height=850');
		if (window.focus)
		{
			popup_1.focus()
		}
	}
	else
	{
		alert('No Normal Video URL!');
	}

	return;
}

function chec(yu)
{
    if (yu != null)
    {
         return yu + " : ";
    }
    return "";
}

function cap(yu)
{
    if (yu != null)
    {
        return yu.toLowerCase();
    }
    return null;
}

function switchHubs(hubName)
{
	if (hubName == "TopStoriesV2" || hubName == "news")
	{
		return "TopStories";
	}
	else if (hubName == "EntertainmentV2")
	{
		return "Entertainment";
	}
	else if (hubName == "CanadaAMV2")
	{
		return "CanadaAM";
	}
	return hubName;
}

var firstTimeWeather = true;
function clearTextWeather()
{
    if (firstTimeWeather == true)
    {
        document.getElementById("testinput").value = "";
        firstTimeWeather = false;
    }
}

function setPageHeight()
{
document.getElementById("ibox_wrapper").style.height = (document.getElementById("photoArea").offsetHeight + 80) + "px";
document.getElementById("ibox_content").style.height = document.getElementById("photoArea").offsetHeight + "px";
}
var commentTextI;

function sendComment(myform, typeSub)
      {
           var xmlHttp;
           xmlHttp = ajaxFunc(xmlHttp);
           var trigString;
           if (typeSub == 1)
           {
           commentTextI = myform.commentText.value.replace(/&quot;/g, "!q!").replace(/\&/g, "!a!").replace(/\%/g, "!p!");
           trigString = "/servlet/HTMLTemplate?tf=ctv/v2/addComment.html&cf=ctv/v2/ctv.cfg&commentText=" + commentTextI + "&useremail=" + myform.useremail.value + "&username=" + myform.username.value + "&slug=" + myform.slug.value + "&date=" + myform.date.value + "&operation=write";
           }
           else if (typeSub == 2)
           {
           trigString = "/servlet/HTMLTemplate?tf=ctv/generic/emailForms/storyFeedback/response.html&cf=ctv/v2/ctv.cfg&subject=" + myform.subject.value + "&comment=" + myform.comment.value + "&sender_email_address=" + myform.sender_email_address.value + "&sender_first_name=" + myform.sender_first_name.value + "&sender_last_name=" + myform.sender_last_name.value + "&subhub=" + myform.subhub.value + "&title=" + myform.title.value + "&article=" + myform.article.value + "&archive=" + myform.archive.value + "&date=" + myform.date.value + "&slug=" + myform.slug.value;
           }
           else if (typeSub == 10)
           {
           trigString = "/servlet/HTMLTemplate?tf=ctv/generic/emailForms/storyFeedback/responseBeta.html&cf=ctv/v2/ctv.cfg&subject=" + myform.subject.value + "&comment=" + myform.comment.value + "&sender_email_address=" + myform.sender_email_address.value + "&sender_first_name=" + myform.sender_first_name.value + "&sender_last_name=" + myform.sender_last_name.value + "&subhub=" + myform.subhub.value + "&title=" + myform.title.value + "&article=" + myform.article.value + "&archive=" + myform.archive.value + "&date=" + myform.date.value + "&slug=" + myform.slug.value;
           }
           else if (typeSub == 3)
           { 
           trigString = "/servlet/HTMLTemplate/!ctvPop/News/EmailResponse?toAddress1=" + myform.toAddress1.value + "&toAddress2=" + myform.toAddress2.value + "&toAddress3=" + myform.toAddress3.value + "&fromName=" + myform.fromName.value + "&fromAddress=" + myform.fromAddress.value + "&message=" + myform.message.value + "&articleURL=" + myform.articleURL.value + "&title=emailFriend";
           }
           else if (typeSub == 4)
           {
           trigString = "/servlet/HTMLTemplate?address=" + myform.address.value + "&first_name=" + myform.first_name.value + "&last_name=" + myform.last_name.value + "&operation=s&interestsOnPage=20035&interest=20035&tf=ctv%2Fmar%2Fhub%2Fhub.html&cf=ctv%2Fmar%2Fctv.cfg&hub=NewsletterSubscribeStatus&edit.x=88&edit.y=16&edit=Subscribe";
           }
           else if (typeSub == 5)
           {
           trigString = "/servlet/HTMLTemplate?tf=ctvlocal/newsletter/sendSubscribeV2.html&cf=ctvlocal/newsletters/ctv.cfg&cityVal=&newsletter=E&subs=no&city=CTV&UE=" + myform.address.value + "&FN=" + myform.first_name.value + "&LN=" + myform.last_name.value;
           }
           xmlHttp.open("GET", trigString, true);
           xmlHttp.send(null);

           xmlHttp.onreadystatechange=function()
           {
             if(xmlHttp.readyState==4)
             {
                  document.getElementById("leftSideForm").style.display = "none";
                  document.getElementById("replaceFormLeft").style.display = "block";
                      //returned
              }
           }
      }

function trackElements(idI, prefixI)
{
    var atags = document.getElementById(idI).getElementsByTagName("a");
    for (i = 0; i < atags.length; i++)
    {
	    if (atags[i].getAttribute("id") == null || atags[i].getAttribute("id") == "")
	    {
		    atags[i].setAttribute("id", "trackId" + i);
	    }
    }
    for (i = 0; i < atags.length; i++)
    {
	    newLink = atags[i].getAttribute('href');
	    if (newLink != null && newLink != "" && newLink != "#closed" && newLink.indexOf("doubleclick") == -1)
	    {
		    io = newLink.indexOf("redirect=");
		    if (io != -1)
		    {
   			    newLink = newLink.substring(io + 9);
		    }
	    Tracking.TrackCorporateLink(atags[i].getAttribute('id'), prefixI + newLink);
	    }
    }
}

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");
}
