﻿// JScript File

//see if we can grab the date on the server
var latest;

function TimeSincePublished(publish, current, formattedPublish) {
    var curdate;
    var maxseconds = 5400;
    //parse publish date into date object
    var year = publish.substr(0,4);
    var month = publish.substr(5,2);
    month--;
    var days = publish.substr(8,2);
    var hours = publish.substr(11,2);
    var mins = publish.substr(14,2);
    var seconds = publish.substr(17,2);
    var pubdate = new Date(year,month,days,hours,mins,seconds,0);
    
    if (!latest) { //if not already loaded then try loading it
      latest = readHTTPHeaders("/js/functions.js?" + Math.random()*5000);
    }
    
    if (latest.length > 1) {
      curdate = new Date(latest);
    } else {
      // if that failed that parse the stale date that came with the page
      year = current.substr(0,4);
      month = current.substr(5,2);
      month--;
      days = current.substr(8,2);
      hours = current.substr(11,2);
      mins = current.substr(14,2);
      seconds = current.substr(17,2);
      curdate = new Date(year,month,days,hours,mins,seconds,0);
    }

    //figure out the difference
    
    var difference = curdate.getTime() - pubdate.getTime();
     
    difference = difference / 1000;

    if (difference < maxseconds && difference > 0) 
    //if (difference < maxseconds) 
    {
  
              var minutes = Math.round(difference / (60));
              if (minutes) { 
              
              document.write("<span class='minutesAgo'>" + minutes + " min. ago</span><br/>");}
     
    }
//     else {
//     if (formattedPublish.substr(0,4) == 'May.')
//     formattedPublish = formattedPublish.substr(0,3) + formattedPublish.substr(4);
//     document.write(" <span class='publishDate'>" + formattedPublish + "</span>");
    }



function TimeSincePublishedBreakingNews(publish, current, formattedPublish) {
    var curdate;
    var maxseconds = 5400;
    //parse publish date into date object
    var year = publish.substr(0,4);
    var month = publish.substr(5,2);
    month--;
    var days = publish.substr(8,2);
    var hours = publish.substr(11,2);
    var mins = publish.substr(14,2);
    var seconds = publish.substr(17,2);
    var pubdate = new Date(year,month,days,hours,mins,seconds,0);
    
    if (!latest) { //if not already loaded then try loading it
      latest = readHTTPHeaders("/js/functions.js?" + Math.random()*5000);
    }
    
    if (latest.length > 1) {
      curdate = new Date(latest);
    } else {
      // if that failed that parse the stale date that came with the page
      year = current.substr(0,4);
      month = current.substr(5,2);
      month--;
      days = current.substr(8,2);
      hours = current.substr(11,2);
      mins = current.substr(14,2);
      seconds = current.substr(17,2);
      curdate = new Date(year,month,days,hours,mins,seconds,0);
    }

    //figure out the difference
    
    var difference = curdate.getTime() - pubdate.getTime();
    difference = difference / 1000;
    if (difference < maxseconds) {    
      var minutes = Math.round(difference / (60));
      if (minutes) { document.write("<span class='minutesAgo'>" + minutes + "&nbsp;min.&nbsp;ago</span><br/>");}
      }
}

 function readHTTPHeaders (url) { 
 var req = false;
     if(window.XMLHttpRequest && !(window.ActiveXObject)) {
        try {
                        req = new XMLHttpRequest();
        } catch(e) {
                        req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
        try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
                try {
                        req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                        req = false;
                }
                }
    }
    
    try { 
      req.open('HEAD', url, false); 
      req.send(null); 
      return req.getResponseHeader("Date"); 
    } 
    catch (e) { 
      return ""; 
    }
}

//for article list back/forth
function Querystring(qs) {
 var value;
  var pair;
  var name;
  this.params = new Object();
  this.get= function (key) { return this.params[key]; }

  if (qs == null) {
    qs=location.search.substring(1,location.search.length);
  }

  if (qs.length == 0) {
    return;
  }

  qs = qs.replace(/\+/g, ' ');
  var args = qs.split('&');
  for (var i=0;i<args.length;i++) {
    value;
    pair = args[i].split('=');
    name = unescape(pair[0]);
    if (pair.length == 2) {
      value = unescape(pair[1]);
    } else {
      value = name;
    }
    this.params[name] = value;
  }
}


function jumpto(pagenum)
{
  pagenum = parseInt(pagenum) + parseInt(index);
  if (pagenum >= 0 && pagenum < idarray.length) {
   location="article?assetID="+idarray[pagenum]+"&assetIDx="+ids;
  }
}

var qs = new Querystring();
var idxID = qs.get("assetID");
var index = 0;
var idarray;

if (idxID && idxID.length > 0) {
  var ids = qs.get("assetIDx");

  idarray = ids.split(",");  
  index = 0;
  for (i=0;i<idarray.length;i++) {
    if (idarray[i] == idxID) {
      index = i;
      break;
    }
  }
}

//add default prev next functions? lets see if it causes any problems
function drawPrev()
{
  if (index > 0) {
    document.write('<a href="javascript:jumpto(-1)">< Previous story </a>');
  }
}
function drawNext()
{
  if (idarray && index < idarray.length - 1) {
    document.write('<a href="javascript:jumpto(1)">Next story ></a>');
  }
}

var ListOfIds = new Array(); //holds 
function addid(key, id)
{

  if (ListOfIds[key]) {
    ListOfIds[key] = ListOfIds[key] + "," + id;
  } else {
    ListOfIds[key] = id;
  }
}

function gotolink(key, id)
{
  location="/article?assetID="+id+"&assetIDx=" + ListOfIds[key];
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function highlightWord(node,word) {
	// Iterate into this nodes childNodes
	if (node.hasChildNodes) {
		var hi_cn;
		for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
			highlightWord(node.childNodes[hi_cn],word);
		}
	}

	// And do this node itself
	if (node.nodeType == 3) { // text node
		tempNodeVal = node.nodeValue.toLowerCase();
		tempWordVal = word.toLowerCase();
		var pattern = new RegExp("\\b" + tempWordVal + "\\b");
		if (tempNodeVal.match(pattern)) {
			pn = node.parentNode;
			if (pn.className != "searchword") {
				// word has not already been highlighted!
				nv = node.nodeValue;
				ni = tempNodeVal.indexOf(tempWordVal);
				// Create a load of replacement nodes
				before = document.createTextNode(nv.substr(0,ni));
				docWordVal = nv.substr(ni,word.length);
				after = document.createTextNode(nv.substr(ni+word.length));
				hiwordtext = document.createTextNode(docWordVal);
				hiword = document.createElement("span");
				hiword.className = "searchword";
				hiword.appendChild(hiwordtext);
				pn.insertBefore(before,node);
				pn.insertBefore(hiword,node);
				pn.insertBefore(after,node);
				pn.removeChild(node);
			}
		}
	}
}

function localSearchHighlight(searchStr) {
	if (!document.createElement) return;
        if (searchStr == '') return;
	// Trim leading and trailing spaces after unescaping
	searchstr = unescape(searchStr).replace(/^\s+|\s+$/g, "");
	if( searchStr == '' ) return;
	phrases = searchStr.replace(/\+/g,' ').split(/\"/);
	// Use this next line if you would like to force the script to always
	// search for phrases. See below as well!!!
	//phrases = new Array(); phrases[0] = ''; phrases[1] = searchStr.replace(/\+/g,' ');
	for(p=0;p<phrases.length;p++) {
	        phrases[p] = unescape(phrases[p]).replace(/^\s+|\s+$/g, "");
		if( phrases[p] == '' ) continue;
		if( p % 2 == 0 ) words = phrases[p].replace(/([+,()]|%(29|28)|\W+(AND|OR)\W+)/g,' ').split(/\s+/);
		else { words=Array(1); words[0] = phrases[p]; }
		var LuceneResults = document.getElementById("LuceneResults");
		var hiliteTextAreas = getElementsByClass("hiliteText",LuceneResults,"div");
        for (w=0;w<words.length;w++) {
			if( words[w] == '' ) continue;
			for (var j=0;j<hiliteTextAreas.length;j++) {
			  highlightWord(hiliteTextAreas[j],words[w]);
			}
        }
	}
}

function clearDefault(el)
{
   if (el.defaultValue==el.value) el.value = ""
}


function doSearch(form) {
    var searchurl="/search?";
    var headline;
    if (form.headline) {
      headline = form.headline.value;
    }
    
    var keywords;
    if (form.kquery) {
      keywords = form.kquery.value;
    } else {
       if (form.keywords) {
         keywords = form.keywords.value;
       }
    }
    
    var category;
    if (form.category) {
      category = form.category.options[form.category.selectedIndex].value;
    }
      
    var byline;
    if (form.byline) {
      byline = form.byline.value;
    }
    
    var body;
    if (form.body) {
      body = form.body.value;
    }
  
    var daterange;
    if (form.daterange) {
      daterange = form.daterange.options[form.daterange.selectedIndex].value;
    }
    
    var title;
    setSessionCookie('title','ALL DATES');    
    if (form.daterange) {
      var temp = form.daterange.selectedIndex;
      if (temp == 0) title = "ALL DATES";
      if (temp == 1) title = "TODAY"; 
      if (temp == 2) title = "YESTERDAY"; 
      if (temp == 3) title = "PAST 3 DAYS"; 
      if (temp == 4) title = "PAST 14 DAYS"; 
      setSessionCookie('title',title);
    }     
    
    var orderby;  
    if (form.orderby && form.orderby[1].checked) {
      orderby = form.orderby[1].value;
    }
    
    searchurl += "&q=";  
    if (keywords) {
       searchurl += keywords;  
    } else {
       searchurl += "1&t=all";
    }
  
    searchurl += "&r=";
    if (headline) {
       searchurl += "Title:\"" + headline + "\" AND ";
    }
    if (category) {
       searchurl += "category:\"" + category + "\" AND ";
    }
    if (byline) {
       searchurl += "(SubTitle1:\"" + byline + "\" OR SubTitle2:\"" + byline + "\") AND ";
    }
    if (body) {
       searchurl += "Body:\"" + body + "\" AND ";
    }
    if (daterange) {
       searchurl += daterange + " AND ";
    }
    if (headline || category || byline || body || daterange) {
       searchurl = searchurl.substr(0, searchurl.length -5)
    }    
    if (orderby) {
       searchurl += "&OrderBy=" + orderby;
    }  
     
    //check if we should do a google request instead
    if (form.searchType && form.searchType[1].checked) {
      searchurl = "http://www.google.com/search?q=" + keywords;
    }
    document.location = searchurl;
  return false;
}


function  GetCurrDate() {
    var m_names = new Array("January", "February", "March",
            "April", "May", "June", "July", "August", "September",
            "October", "November", "December");
            
    var d_names = new Array("Sunday", "Monday", "Tuesday",
            "Wednesday", "Thursday", "Friday", "Saturday");

    var d = new Date();
    var curr_day = d.getDay();
    var curr_date = d.getDate();
    var curr_month = d.getMonth();
    var curr_year = d.getFullYear();

    document.write(d_names[curr_day] + ", " + m_names[curr_month] + " " + curr_date +  ", " + curr_year);
}

function checkenter(evt, form) {
  if (evt) {
  keyCode=evt.keyCode;
    
  } else {
    keyCode = window.event.keyCode;
  }
  if (keyCode == 13){
     doSearch(form);
     return false
  }

  return true;
}

function noenter(evt) {
  if (evt) {
    keyCode = evt.which;
  } else {
    keyCode = window.event.keyCode;
  }
      if (keyCode == 13){
        return false;
      }
      
  return true;
}
//Popup Video Clip
function Pop_Window (url, width, height, vname)
{    
    window.open(url, vname, 'toolbar=no, location=no, directories=no, resizable=no, scrollbars=no, status=no, menubar=no, dependent=no, width='+width+', height='+height);
    return this.href;
}
//Popup Graphic
function Popup()
{

    var floater = document.getElementById("graphic");
    var yScroll= 0;
    yScroll = window.pageYOffset ||
               document.body.scrollTop ||
               document.documentElement.scrollTop;

    floater.style.top = 20 + yScroll + 'px';
    floater.style.right = 30 + 'px';

}

function New_Window (url, wname)
{    
    window.open(url, wname);
    return this.href;
}

  function openWinMedia(url) {
aWindow=window.open(url, 'cgiwindow', 'Toolbar=no, Location=no, Directories=no, Status=no, Menubar=no, Scrollbars=yes,  Resize=yes, width=1024, height=700');  
 }
 
 
   function getArgs(title) {
        var args = new Object();
        var query = location.search.substring(1);
        var pairs = query.split("&");
        
        for(var i=0;i<pairs.length;i++){
            var pos = pairs[i].indexOf('=');
            if (pos == -1) continue;
            var argname = pairs[i].substring(0,pos);
            
            if(argname == "title") {
                var value = pairs[i].substring(pos+1);
                value = decodeURIComponent(value);
                args[argname] = value;
                document.write (args[argname]);
            }
        }
    }  
    
    
    /* cookies */

    function getCookie(c_name) {
        if (document.cookie.length>0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) { 
                c_start = c_start + c_name.length+1; 
                c_end = document.cookie.indexOf(";",c_start);
                if (c_end == -1) c_end=document.cookie.length;
                return document.write(unescape(document.cookie.substring(c_start,c_end)));
            } 
        }
        return "";
    }
    
     
    function setSessionCookie(c_name,value) {	
	      document.cookie = c_name+ "=" +escape(value)+ "; path=/";
    }
    
    function checkCookies(c_name) {
	      var value = "";
	      if (document.cookie.length > 0) {
		        c_start = document.cookie.indexOf(c_name + "=");                                     
		        if (c_start != -1) { 
			          c_start = c_start + c_name.length + 1; 
			          c_end = document.cookie.indexOf(";",c_start);
			          if (c_end == -1) c_end = document.cookie.length; 
			          return unescape(document.cookie.substring(c_start,c_end));
		        } 
	      }
    }

    
    
function fixPNG(myImage) {
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);
	
	if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
		var imgID = (myImage.id) ? "id='" + myImage.id + "' " : "";
		var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : "";
		var imgTitle = (myImage.title) ? "title='" + myImage.title + "' " : "title='" + myImage.alt + "' ";
		var imgStyle = "display:inline-block;" + myImage.style.cssText;
		var strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + myImage.width + "px; height:" + myImage.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>";
		myImage.outerHTML = strNewHTML;
	}
}


function popupPhotoPlayer(url) {
  var w = window.open(url,"name","width=1000,height=710,resizable=yes,status=no ");
  return this.href;
 }
