// Author : Raghavendar Thirumala (Thiru) 

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

// Function to create the HTML from the list of categories retrieved from the database
// Obselete, not used any more
function displayCategories() {
    if (category.length > 0) {
        categoryOptionListHmtl = "<select name=\"category\" id=\"category\" size = \"10\" multiple>\n";
        categoryOptionListHmtl += "<option value=\"\" SELECTED>ALL</option>\n"
        for (var i=0; i<category.length; i++) {                 
            categoryOptionListHmtl += "<option value=\"" + category[i].value + "\">" + category[i].label + "</option>\n";                            
        }
        categoryOptionListHmtl += "</select>\n";
    }
    //alert (categoryOptionListHmtl);
    document.getElementById("catSelectListId").innerHTML = categoryOptionListHmtl;
}

// Function to create the HTML 
// for the category drop down box on the advance searcg page
// The category names are hard coded here
// The codes should match the values as registered in the database
function displayLimitedCategories() {
    var categoryOptionListHmtl = "<select name=\"category\" id=\"category\" size = \"6\" multiple>\n";
    categoryOptionListHmtl += "<option value=\"gn\" SELECTED>ALL</option>\n"
    categoryOptionListHmtl += "<option value=\"bimson\">Betty Irene Moore School of Nursing</option>\n";                            
    categoryOptionListHmtl += "<option value=\"cc\">Cancer Center</option>\n";                            
    categoryOptionListHmtl += "<option value=\"ch\">Children's Hospital</option>\n";                            
    categoryOptionListHmtl += "<option value=\"mi\">M.I.N.D. Institute</option>\n";                            
    categoryOptionListHmtl += "<option value=\"rn\">Research</option>\n";                            
    categoryOptionListHmtl += "<option value=\"som\">School of Medicine</option>\n";                            
    categoryOptionListHmtl += "</select>\n";
    return categoryOptionListHmtl;
}


//Function to determine if a variable holds an interger or not  
function isInteger(s){
    var i;
     for (i = 0; i < s.length; i++){
         // Check that current character is number.
         var c = s.charAt(i);
         if (((c < "0") || (c > "9"))) return false;
     }
     // All characters are numbers.
     return true;
}


//Function used in date validation
function stripCharsInBag(s, bag){
    var i;
     var returnString = "";
     // Search through string's characters one by one.
     // If character is not in bag, append to returnString.
      for (i = 0; i < s.length; i++){
         var c = s.charAt(i);
         if (bag.indexOf(c) == -1) returnString += c;
     }
     return returnString;
}

//Function used to return the number of days in february in a specific year
function daysInFebruary (year){
// February has 29 days in any year evenly divisible by four,
 // EXCEPT for centurial years which are not also divisible by 400.
 return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

//Function that returns an array of days for each month in a year
function DaysArray(n) {
  for (var i = 1; i <= n; i++) {
    this[i] = 31
    if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
    if (i==2) {this[i] = 29}
  }
  return this
}

//Function that determines if a String is in a valid date format (mm/dd/yyyy)
function isDate(dtStr){
  var daysInMonth = DaysArray(12)
  var pos1=dtStr.indexOf(dtCh)
  var pos2=dtStr.indexOf(dtCh,pos1+1)
  var strMonth=dtStr.substring(0,pos1)
  var strDay=dtStr.substring(pos1+1,pos2)
  var strYear=dtStr.substring(pos2+1)
  strYr=strYear
  if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
  if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
  for (var i = 1; i <= 3; i++) {
   if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
  }
  month=parseInt(strMonth)
  day=parseInt(strDay)
  year=parseInt(strYr)
  if (pos1==-1 || pos2==-1){
   alert("The date format should be : mm/dd/yyyy")
   return false
  }
  if (strMonth.length<1 || month<1 || month>12){
   alert("Please enter a valid month")
   return false
  }
  if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
   alert("Please enter a valid day")
   return false
  }
  if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
   alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
   return false
  }
  if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
   alert("Please enter a valid date")
   return false
  }
     return true
}

//Date function
function getTime() {
    var today = new Date();
    var year = today.getYear();
    var month = today.getMonth() + 1;
    var day = today.getDate();
    var hours = today.getHours();
    var minutes = today.getMinutes();
    var p = "AM";
    if (hours > 11) {
       p = "PM";
    }
    if (day < 10) {
      day = "0" + day;
    }
    if (month < 10) {
      month = "0" + month;
    }
    return (month + "/" + day + "/" + takeYear(today));
}
 
 //Date function
function takeYear(theDate) {
  x = theDate.getYear();
  var y = x % 100;
  y += (y < 38) ? 2000 : 1900;
  return y;
}

//Function that validates the To & From date fields on the advance search form
function ValidateDateForm(tdate){
    var fdate=document.searchForm.fromdate;
    var tdate=document.searchForm.todate;
    if ((fdate.value > '') && (tdate.value > '')){
        if (isDate(fdate.value)==false){
            fdate.focus();
            return false;
        }else if (isDate(tdate.value)==false){
            tdate.focus();
            return false;
        }
    }else if ((fdate.value > '') && (!tdate.value > '')){
        alert ("To use the date range you must enter both the from and to date.");
        tdate.focus();
        return false;
    }else if ((!fdate.value > '') && (tdate.value > '')){
        alert ("To use the date range you must enter the from date.");
        fdate.focus();
        return false;
    }
    return true;
}

//Function to submit the request for advance news search
function processQuery(searchresults) {
    var fromdate = document.getElementById("fromdate").value;
    var todate = document.getElementById("todate").value;
    var keyword = document.getElementById("keyword").value;
    if (fromdate > '') {
        if (!todate > '') {
            var currentTime = new Date()
            var tmonth = currentTime.getMonth() + 1
            var tday = currentTime.getDate()
            var tyear = currentTime.getFullYear()
            todate = tmonth + "/" + tday + "/" + tyear;
            document.searchForm.todate.value = todate;
        }
    }
    var url = "searchresults.html?mode=search";
    if(searchresults && (searchresults !='null' && searchresults != '')){
        url = search_results_page + "?mode=search";
    } 
  
  
    if (keyword > '') {
        keyword = encodeURIComponent(keyword);
        url += '&keyword=' + keyword;
    }
    
    var categoryElem = document.searchForm.category;
    var separator = "";
    var isSelected = false;
    var catString = "";
    if (categoryElem){
        for (i=0; i < categoryElem.options.length; i++) {
            if (categoryElem.options[i].selected == true) {
                if (categoryElem.options[i].value > '') {
                    catString += (separator + categoryElem.options[i].value) ;
                    separator = ","
                    isSelected = true;
                 }
            }
        }
        if (isSelected) url += '&cat=' + catString;
    }


    var categoryElem2 = document.searchForm.cat;
    var isSelected2 = false;
    if(categoryElem2){
        for (i=0; i < categoryElem2.length; i++) {
            if (categoryElem2[i].checked== true) {
                if (categoryElem2[i].value > '') {
                    catString = categoryElem2[i].value ;
                    isSelected2 = true;
                    break;
                 }
            }
        }
        if (isSelected2) url += '&cat=' + catString;
    }
    
    
    if (ValidateDateForm()) {
        if ((fromdate > '') && (todate > '')){
            url += '&fromdate=' + fromdate;
            url += '&todate=' + todate;
        }
        window.location = url;
    }
}

var blnFocus;
document.onkeypress = keyDown;
if (document.layers) document.captureEvents(Event.KEYPRESS);
//function setFocusBln(bln){
// blnFocus = bln;
//}
function keyDown(e) {
    if (document.all) {
        nKey = event.keyCode;
    }else{
        nKey = e.which;
    }
    if (nKey == 13){
        processQuery();
        return false;
    }
}

//Function that creates the HTML for the advanced search page.
// The HTML includes a form that has the fields to capture the 
// From & To dates, the keywords and a drop down for categories
function displayAdvanceSearch(display_header, searchresults, category, site) {
    //alert ("Entering function");
    var searchHTML = "";
    if(display_header) {
        searchHTML = "<h1>Advanced News Search</h1>";
        searchHTML += "Define search by area of interest, date or keyword<br /><br />";
    }

    searchHTML += '<form name="searchForm" onsubmit="processQuery(); return false;" action="" method="post">';

    searchHTML += '<table style="padding:4px;"><tbody><tr>';
    if(category) { 
        searchHTML += '<td><input type="radio" value="gn" name="cat">Search all news releases</td>';
        
        if(site) {
            searchHTML += '<td>&nbsp;&nbsp;&nbsp;<input type="radio" checked value="'+ category+'" name="cat">Search ';
            searchHTML += site;
            searchHTML += ' news releases only';
            searchHTML += '<input type="hidden" value="'+ site +'" name="site">';
        } else {
            searchHTML += '<td>&nbsp;&nbsp;&nbsp;<input type="radio" checked value="'+ category+'" name="cat">  Search site news releases only';
        }
    } else {
        searchHTML += '<td>Area of <br />interest:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td colspan="3">';
        var categoryListHTML = displayLimitedCategories();
        searchHTML += categoryListHTML;
        searchHTML += '</td><td>(To select more than one area of interest, hold the <strong>Ctrl key </strong>down and click)';
    }    
    searchHTML += '</td></tr>';
    searchHTML += '</tbody></table>';
    
    searchHTML += '<table style="padding: 2px;"><tbody><tr><td>From Date:</td>';
    searchHTML += '<td><input id="fromdate" size="10" name="fromdate"></td>';
    searchHTML += '<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;To:</td>';
    searchHTML += '<td><input id="todate" size="10" name="todate">(mm/dd/yyyy)</td></tr>';
    searchHTML += '<tr><td>Keyword:</td><td colspan="3"><input id="keyword" name="keyword"></td></tr>';
    searchHTML += '<tr><td colspan="4"><br><a href="javascript:processQuery()"><img src="/global/images/buttons/search.gif" border="0"></a>';
    searchHTML += '&nbsp;&nbsp; <a href="javascript:document.searchForm.reset()"><img src="/global/images/buttons/clear.gif" border="0"></a></td>';
    searchHTML += '</tr></tbody></table>';
    searchHTML += '</form>';
    document.getElementById("searchnews").innerHTML = searchHTML;    
    
    //alert(searchHTML);
}
