function UpdateStart()
{
   var month = parseInt(document.advSearch.monthFrom.value) - 1;
   var day = parseInt(document.advSearch.dayFrom.value) + 1;
   var year = parseInt(document.advSearch.yearFrom.value);

   document.advSearch.start.value = ((new Date(year, month, day)).getTime() / 1000);
}

function UpdateEnd()
{
   var month = parseInt(document.advSearch.monthTo.value) - 1;
   var day = parseInt(document.advSearch.dayTo.value) + 1;
   var year = parseInt(document.advSearch.yearTo.value);

   //alert(document.advSearch.end.value);
   document.advSearch.end.value = "" + (((new Date(year, month, day)).getTime() / 1000) - 1);
   //alert(document.advSearch.end.value);
}

var searchLoadIntervalId = -1;

function SubmitEnter(e)
{
   var keycode;
   if (window.event)
      keycode = window.event.keyCode;
   else if (e)
      keycode = e.which;
   else
      return true;

   if (keycode == 13)
   {
      document.advSearch.submit();
      return false;
   }
   else
      return true;
}

function AddEnterHandler()
{
   document.onkeypress = SubmitEnter;
   for ( i = 0; i < document.advSearch.elements.length; i ++ )
   {
      document.advSearch.elements[i].onkeypress = SubmitEnter;
   }
   for ( i = 0; i < document.formu.elements.length; i ++ )
   {
      document.formu.elements[i].onkeypress = SubmitEnter;
   }

}

function DisableLink()
{
   alert("The page is preparing your search query. Please try again after a few seconds.");
   return false;
}

function ChangeTitleOptions()
{
   titleSelections = document.getElementById('searchTitle');
   selectedTitleValue = titleSelections.options[titleSelections.selectedIndex].value;
   splitValues = selectedTitleValue.split("_");

   window.status = "Retrieving Season Info";
   searchLoadIntervalId = setInterval("DisplayLoadDots()",250);
   titleSelections.disabled = true;
   document.getElementById('searchNetwork').disabled = true;
   reqSearchOptions = getRequestObject();
   reqSearchOptions.onreadystatechange = reqTitleSearchOptions;
   reqSearchOptions.open("POST", "asyncSearchOptions.php?option=shows&selected=" + splitValues[0], true);
   reqSearchOptions.send(null);

   //make sure the user does not submit search before getting results for the title.
   var searchButton = document.getElementById("search_button");
   if (searchButton != null)
   {
      searchButton.onclick = DisableLink;
   }

}

function reqTitleSearchOptions()
{
   if (4 == reqSearchOptions.readyState)
   {
      clearInterval(searchLoadIntervalId);
      titleSelections = document.getElementById('searchTitle');
      titleSelections.disabled = false;
      networkSelections = document.getElementById('searchNetwork');
      networkSelections.disabled = false;
      window.status = "Done";
      if(Handle302(reqSearchOptions))
      {
         return;
      }
      if (200 == reqSearchOptions.status || null == reqSearchOptions.status)
      {
         var rsp = reqSearchOptions.responseText;
         var failure = 'Error: ';
         if (rsp.substring(0, failure.length) != failure)
         {
            selectedTitleValue = titleSelections.options[titleSelections.selectedIndex].value;

            splitValues = selectedTitleValue.split("_");

            for ( i = 0; i < networkSelections.options.length; i ++ )
            {
               if ( splitValues[1] == networkSelections.options[i].value )
               {
                  networkSelections.selectedIndex = i;
                  break;
               }
            }

            daypartSelections = document.getElementById('searchDaypart');

            // kludge for bug with loading dayparts for bulk-loader ( sets fk to 0 ) added 5/9/08 CYP
            if ( 0 == splitValues[2] )
               daypartSelections.selectedIndex = 0;
            // end kludge
            else for ( i = 0; i < daypartSelections.options.length; i ++ )
            {
               if ( splitValues[2] == daypartSelections.options[i].value )
               {
                  daypartSelections.selectedIndex = i;
                  break;
               }
            }

            newSelections = rsp.split("||||");
            searchYearSelections = document.getElementById('searchSeasonYearsDiv');
            searchYearSelections.innerHTML = newSelections[0];

            searchSeasonSelections = document.getElementById('searchSeasonNumberDiv');
            searchSeasonSelections.innerHTML = newSelections[1];


            if ( 0 > selectedTitleValue )
               searchSeasonSelections.style.display = 'none';
            else
               searchSeasonSelections.style.display = 'block';
         }
         else
         {
            alert(rsp);
         }
         var searchButton = document.getElementById("search_button");
         if (searchButton != null)
         {
            searchButton.onclick = null;
         }
      }
      else if (399 < reqSearchOptions.status)
         alert('HTTP error ' + reqSearchOptions.status + ': ' + reqSearchOptions.statusText);
   }
}


function DisplayLoadDots()
{
   window.status = window.status + ".";
}

function SyncSeasonOptions(changed, tochange)
{
   // if one of these dropdowns is not "none selected" ( index of 0 ) then the other should be
   searchYearSelections = document.getElementById('searchSeasonYears');
   searchSeasonSelections = document.getElementById('searchSeasonNumber');
   if ( 0 != changed.selectedIndex )
      tochange.selectedIndex = 0;
}

// CALENDAR JS
var cal_searchBefore = new CalendarPopup();

//      function onSelect_searchBefore(val)
//      {
//         if (0 == val || -1 == val)
//            document.advSearch.searchBefore.value = '';
//         else
//         {
//            var dsel = new Date();
//            dsel.setDate(dsel.getDate() + parseInt(val));
//            document.advSearch.searchBefore.value = formatDate(dsel, "MM/dd/yyyy");
//         }
//      }

function onCal_searchBefore()
{
   document.advSearch.searchSeasonYears.selectedIndex = 0;
   cal_searchBefore.select(document.advSearch.searchBefore, 'acal_searchBefore', 'MM/dd/yyyy', document.advSearch.searchBefore.value);
}

function set_searchBeforeText(val)
{
   if ('' == val)
   {
      document.advSearch.searchSeasonYears.value = 0;
   }
   else
   {
      var ms = parseDate(val);
      if (ms)
      {
         document.advSearch.searchBefore.value = formatDate(new Date(ms), "MM/dd/yyyy");
         document.advSearch.searchSeasonYears.selectedIndex = 0;
      }
      else
      {
         document.advSearch.searchBefore.focus();
         window.open('pop_alert.php?id=' + escape('Please enter a valid date'),'qpop','scrollbars=no,height=150,width=400');
      }
   }
}

var cal_searchAfter = new CalendarPopup();

//      function onSelect_searchAfter(val)
//      {
//         if (0 == val || -1 == val)
//            document.advSearch.searchAfter.value = '';
//         else
//         {
//            var dsel = new Date();
//            dsel.setDate(dsel.getDate() + parseInt(val));
//            document.advSearch.searchAfter.value = formatDate(dsel, "MM/dd/yyyy");
//         }
//      }

function onCal_searchAfter()
{
   document.advSearch.searchSeasonYears.selectedIndex = 0;
   cal_searchAfter.select(document.advSearch.searchAfter, 'acal_searchAfter', 'MM/dd/yyyy', document.advSearch.searchAfter.value);
}

function set_searchAfterText(val)
{
   if ('' == val)
   {
      document.advSearch.searchSeasonYears.value = 0;
   }
   else
   {
      var ms = parseDate(val);
      if (ms)
      {
         document.advSearch.searchAfter.value = formatDate(new Date(ms), "MM/dd/yyyy");
         document.advSearch.searchSeasonYears.selectedIndex = 0;
      }
      else
      {
         document.advSearch.searchAfter.focus();
         window.open('pop_alert.php?id=' + escape('Please enter a valid date'),'qpop','scrollbars=no,height=150,width=400');
      }
   }
}
// END CALENDAR JS

function showAdvSearchCommerce()
{
   showAdvSearch();
   document.getElementById('simpleTable').style.display='none';
}

function hideAdvSearchCommerce()
{
   hideAdvSearch();
   document.getElementById('simpleTable').style.display='block';
}

var values = [];
var locations = [];
var bools = [];
var types = [];

function AlterValues(index)
{
   var valueElem = document.getElementById("value_" + index);
   if (valueElem.tagName == 'INPUT')
   {
      values[index] = valueElem.value;
   }
   var inputElem = document.getElementById("input_" + index);
   var selectElem = document.getElementById("location_" + index);
   var location = selectElem.options[selectElem.selectedIndex].value;
   if(location == "orientation_s")
   {
      inputElem.innerHTML = '&nbsp;<select style="width:150px" id="value_' + index + '" name="value_' + index + '"><option value="H">Horizontal</option><option value="V">Vertical</option></select>&nbsp;';
   }
   else if (location == "Category_ms")
   {
      inputElem.innerHTML = '&nbsp;<select style="width:150px" id="value_' + index + '" name="value_' + index + '"><option value="I">International</option><option value="S">Sports</option><option value="N">News</option><option value="COV">Covers</option><option value="E">Entertainment</option></select>&nbsp;';
   }
   else
   {
      inputElem.innerHTML = '<input style="width:150px" type="text" id="value_' + index + '" name="value_' + index + '" value="' + escape(values[index]) + '"/>';
   }
}

var searchTemplate = '<div id="searchRow__INDEX_"><div style="height:5px; line-height:0px;"></div>' +
 '<a id="remove__INDEX_" href="javascript: RemoveSearchField();" style="color:black;text-decoration:none;font-size:12px;font-weight:bold">X</a>&nbsp;&nbsp;' +
 '<select style="width:150px" id="location__INDEX_" name="location__INDEX_" onchange="AlterValues(_INDEX_)">' +
 '<option value="allmeta" selected>All Fields</option>' +
 '<option value="Headline_mt">Headline</option>' +
 '<option value="Caption_Abstract_mt">Caption</option>' +
 '<option value="Category_ms">Category</option>' +
 '<option value="Keywords_mt">Keywords</option>' +
 '<option value="file_name_s">Title/Filename</option>' +
 '<option value="photographer_s">Photographer</option>' +
 '<option value="orientation_s">Orientation</option>' +
 '</select>&nbsp;&nbsp;' +
 '<span id="input__INDEX_" style="width:150px">' +
 '<input type="text" id="value__INDEX_" name="value__INDEX_" value=""/ style="width:150px">' +
 '</span>&nbsp;&nbsp;&nbsp;' +
 '<select name="type__INDEX_" id="type__INDEX_">' +
 '<option value="all" selected>Match All</option>' +
 '<option value="any">Match Any</option>' +
 '<option value="exact">Match Exact</option>' +
 '</select>&nbsp;&nbsp;' +
 '<select name="bool__INDEX_" id="bool__INDEX_" style="visibility:hidden">' +
 '<option value="AND" selected>And</option>' +
 '<option value="OR">Or</option>' +
 '<option value="NOT">Not</option>' +
 '</select></div>';

function StoreFields()
{
   var numFields = parseInt(document.advSearch.numFields.value);
   for(var i=0; i < numFields; ++i)
   {
      var boolElem = document.getElementById("bool_" + i);
      var typeElem = document.getElementById("type_" + i);
      var valueElem = document.getElementById("value_" + i);
      var locationElem = document.getElementById("location_" + i);
      if(boolElem != null && typeElem != null && valueElem != null && locationElem != null)
      {
         bools[i] = boolElem.selectedIndex;
         locations[i] = locationElem.selectedIndex;
         types[i] = typeElem.selectedIndex;
         values[i] = (valueElem.tagName == 'INPUT')?valueElem.value:valueElem.selectedIndex;
      }
   }
}

function RestoreFields()
{
   var numFields = parseInt(document.advSearch.numFields.value);
   for(var i=0; i < numFields - 1; ++i)
   {
      var boolElem = document.getElementById("bool_" + i);
      var typeElem = document.getElementById("type_" + i);
      var valueElem = document.getElementById("value_" + i);
      var locationElem = document.getElementById("location_" + i);
      if(boolElem != null && typeElem != null && valueElem != null && locationElem != null)
      {
         boolElem.selectedIndex = bools[i];
         locationElem.selectedIndex = locations[i];
         typeElem.selectedIndex = types[i];
         if(valueElem.tagName == 'INPUT')
         {
            valueElem.value = values[i];
         }
         else
         {
            valueElem.selectedIndex = values[i];
         }
      }
   }
}

function AddSearchField()
{
   StoreFields();
   var numFields = parseInt(document.advSearch.numFields.value)
   document.advSearch.numFields.value = "" + (numFields + 1);
   var boolStr = "bool_" + (numFields - 1);
   var boolElem = document.getElementById(boolStr);
   boolElem.style.visibility = "visible";
   var remStr = "remove_" + (numFields - 1);
   var remElem = document.getElementById(remStr);
   remElem.style.visibility = "hidden";
   var searchFields = document.getElementById('searchFields');
   var html = searchFields.innerHTML + searchTemplate;
   html = html.split("_INDEX_").join("" + numFields);
   searchFields.innerHTML = html;
   RestoreFields();
}

function RemoveSearchField()
{
   var numFields = parseInt(document.advSearch.numFields.value)
   if (numFields == 1) { return; }
   document.advSearch.numFields.value = "" + (numFields - 1);
   var boolStr = "bool_" + (numFields - 2);
   var boolElem = document.getElementById(boolStr);
   boolElem.style.visibility = "hidden";
   if (numFields > 2)
   {
      var remStr = "remove_" + (numFields - 2);
      var remElem = document.getElementById(remStr);
      remElem.style.visibility = "visible";
   }
   var rowStr = "searchRow_" + (numFields - 1);
   var rowElem = document.getElementById(rowStr);
   rowElem.parentNode.removeChild(rowElem);
}
