var html = DomBuilder.apply();
$ = YAHOO.util.Dom.get;
if (typeof FilterPage == 'undefined') FilterPage  = {};

// To handle filter requests
FilterPage.Results = {
  // Holds a massive thing of tags so we can track parent/child relationships
  tags: {},
  activeTags: {},

  filterTag: function(tag, parent){
    // Change the activeTags cache to see if we're un-doing a current filter (00)
    if (tag == "00") delete this.activeTags[parent];
    else this.activeTags[parent] = tag;
    this.populateData();
  },

  filterDate: function(startMonth, endMonth){
    startMonth = parseInt(startMonth);
    endMonth = parseInt(endMonth);
    this.dateFilter = [startMonth, endMonth]
    this.populateData();
  },

  // variables used by populate data
  cache: {},
  fileName: null,
  sortBy: '',
  page: 1,
  perPage: 25,
  totalResults: 0,
  request: '',
  populateData: function(){
    if (!this.fileName) this.fileName = this.getFileName();

    // Check to see if we've cached the response
    if (this.cache[this.fileName]) return this.renderData(this.cache[this.fileName]);
    if (this.request) return; // No need for multiple requests

    // Create the ajax callback
    var callback = {
      success: function(o){ FilterPage.Results.request = ''; FilterPage.Results.renderData(o.responseXML); },
      failure: function(){ FilterPage.Results.request = ''; }
    }
    this.request = YAHOO.util.Connect.asyncRequest('POST', this.fileName, callback);
  },

  renderData: function(response){
    // First we want to cache the request for further use
    this.cache[this.fileName] = response;

    var releases = response.getElementsByTagName('entry');
    // reset data
    this.data = [];

    // Filter
    for (var i=0; i<releases.length; i++){
      var release = releases[i];
      if (release.getElementsByTagName("tags")[0].firstChild) {
        var tags = release.getElementsByTagName('tags')[0].firstChild.nodeValue.split(' ');
      } else {
        var tags = " ";
      }

      // We need to iterate through the active tags and make sure the release all the 
      // active tags in it. If it doesn't, we skip it
      var skip = false;
      for (cat in this.activeTags){
        var activeTag = this.activeTags[cat];

        if (!activeTag) continue;
        if (tags.indexOf(activeTag.toString()) == -1){
          skip = true;
          break;
        }
      }

      // Check the start / end months if applicable
      if (this.dateFilter){
        var month = parseFloat(release.getElementsByTagName('month')[0].firstChild.nodeValue);
        if (month < this.dateFilter[0] || month > this.dateFilter[1]) skip = true;
      }

      if (skip == true) continue;

      // This looks like a good item, add it to our dataset
      this.addXMLItem(release);
    }

    // Sort
    if (this.sortBy == 'date')
	    this.sortDate();

    // Create paging
    this.totalResults = this.data.length;
    this.createPaging();

    // Clear current data
    while ($('newsItems').hasChildNodes()) { $('newsItems').removeChild($('newsItems').lastChild); }

    // Render lines
	  $('preloader-block').style.display ="none";
	  $('sort-box').className = "";
    var iteration = 0;
    var startAt = (this.page - 1)*this.perPage;
    var endAt = this.page*this.perPage;
    for (index in this.data){
      if (++iteration > endAt) break;
      if (iteration < startAt) continue;

      var item = this.data[index];
      if (typeof item.label == 'undefined') continue;
      var label =  item.label || "";
      label = html.A({href:item.url}, label);
      label.setAttribute('metrics', item.metricsFunction);
      label.onclick = function(){
        // No needs as this happens again below in the row.onclick
        //eval(this.getAttribute('metrics'));
      }
      var row = html.TR(
        html.TD({'class':"date"}, parseInt(item.month, 10) + "/" + parseInt(item.day, 10) + "/" + item.year),
        html.TD(
          html.H3(item.series),
          html.H4(item.title),
          html.P(label),
          html.UL({'class':"media-desc"},
            html.LI(
              html.A({href:item.url + "?autoplay=true"},
                html.SPAN({'class':"podcast-icon"},
                  html.STRONG("Size:"),
                  " ", item.size, " MB"
                )
              )
            ),
            html.LI(
              html.STRONG("Duration:"),
              " ", item.duration
            )
          )
        )
      );
      row.setAttribute('metrics', item.metricsFunction);
      row.setAttribute('goto', "go_to(\"" + item.url + "\")");
      row.onclick = function(){
        eval(this.getAttribute('metrics'));
        eval(this.getAttribute('goto'));
        saveCookies();
      }
      row.onmouseover = new Function("this.className='highlight'");
      row.onmouseout = new Function("this.className=''");

      $('newsItems').appendChild(row);
    }

    if (this.data.length == 0){
	    $('sort-box').className = "noresults";

      var row = html.TR(
		    html.TD(
			    {colspan:3},
			    html.P(
				    "No podcasts were found with the filters you selected.",
				    html.BR(),
				    "Please try another set of filters or ",
			      html.A({href:"podcast_filter.html?sort=date&filter=&dates=1,12"}, "go back to a list of all Podcasts"),
				    "."
				  )
			  )
		  );
      $('newsItems').appendChild(row);
    }
  },

  // Sorting functions
  sortDate: function(){ 
    var sortFunction = function(a, b){
      if (a.compositeDate > b.compositeDate) return 1;
      if (a.compositeDate < b.compositeDate) return -1;
      return 0;
    }
    this.data.sort(sortFunction);
    return;
  },

  addXMLItem: function(item){
    if (item.getElementsByTagName("series")[0].firstChild)
      var series_test = item.getElementsByTagName("series")[0].firstChild.nodeValue;
    else
      var series_test = " ";

    var objItem = {
      series: series_test,
      title: item.getElementsByTagName("title")[0].firstChild.nodeValue,
      size: item.getElementsByTagName("size")[0].firstChild.nodeValue,
      duration: item.getElementsByTagName("duration")[0].firstChild.nodeValue,
      label: item.getElementsByTagName("label")[0].firstChild.nodeValue,
      //push month, day, year and convert to integers
      month: item.getElementsByTagName("month")[0].firstChild.nodeValue,
      day: item.getElementsByTagName("day")[0].firstChild.nodeValue,
      year: item.getElementsByTagName("year")[0].firstChild.nodeValue,
      url: item.getElementsByTagName("url")[0].firstChild.nodeValue
    }

    objItem.compositeDate =  parseInt(objItem.year.toString() + objItem.month.toString() + objItem.day.toString());
    if (item.getElementsByTagName('func')[0].firstChild){
      var pos = item.getElementsByTagName('pos').firstChild ? item.getElementsByTagName('pos').firstChild.nodeValue : '';
      objItem.metricsFunction = item.getElementsByTagName('func')[0].firstChild.nodeValue + '(' + '\'' + item.getElementsByTagName('id')[0].firstChild.nodeValue + '\',\'';
      objItem.metricsFunction += pos + '\',\'' + item.getElementsByTagName('cat')[0].firstChild.nodeValue + '\',' + item.getElementsByTagName('obj')[0].firstChild.nodeValue + ')';
    }
    this.data.push(objItem);
  },

  // gets the filename
  getFileName: function(){
    // Currently dependent on year
    if (getCookie('pc-currentYear')) return getCookie('pc-currentYear');
    return $('filename').value;
  },
  setFileName: function(){
    this.fileName = this.getFileName();
  },
  createPaging: function(){
    var maxPages = Math.ceil(this.totalResults / this.perPage);
    // Are we on an impossible page? (i.e. page 5/3)
    if (this.page == 0)
      this.page += 1;	

    if (this.page > maxPages) this.page = maxPages;
    var paging = html.SPAN();

    for (var i=1; i<=maxPages; i++){
      if (i == this.page) {
        // if it's not the first page... show the "previous" link
        if (i != 1) {
          var prevnum = i;
          var prevlink = html.A({href:"#"}, "Previous");
          prevlink.onclick = function() {
            FilterPage.Results.goToPage((prevnum-1));
            return false;
          }
          paging.appendChild(prevlink);
          paging.appendChild(html.SPAN(' ')); // space
        }

        if ((i+1) <= maxPages) {
          var nextnum = i;
          var nextlink = html.A({href:"#"}, "Next");
          nextlink.onclick = function() {
            FilterPage.Results.goToPage((nextnum+1));
            return false;
          }
        }

        // current page number:
        var link = html.SPAN(i.toString());
      } else {
        var link = html.A({href:"#"}, i.toString());
      }
      link.onclick = function() {
        FilterPage.Results.goToPage(this.innerHTML);
        return false;
      }

      paging.appendChild(link);
      paging.appendChild(html.SPAN(' ')); // space
    } // end for loop

    $('pagenumbers').innerHTML = '';
    if (prevlink) {
      $('pagenumbers').appendChild(prevlink);
      $('pagenumbers').appendChild(html.SPAN(' '));
    }
    $('pagenumbers').appendChild(paging);
    if (nextlink) $('pagenumbers').appendChild(nextlink);

    //paging for the bottom of page
    var paging_btm = html.SPAN();

    for (var i=1; i<=maxPages; i++){
      if (i == this.page) {
        // if it's not the first page... show the "previous" link
        if (i != 1) {
          var prevnum = i;
          var prevlink = html.A({href:"#"}, "Previous");
          prevlink.onclick = function() {
            FilterPage.Results.goToPage((prevnum-1));
            return false;
          }
        }

        if ((i+1) <= maxPages) {
          var nextnum = i;
          var nextlink = html.A({href:"#"}, "Next");
          nextlink.onclick = function() {
            FilterPage.Results.goToPage((nextnum+1));
            return false;
          }
        }

        // current page number:
        var link = html.SPAN(i.toString());
      } else {
        var link = html.A({href:"#"}, i.toString());
      }
      link.onclick = function() {
        FilterPage.Results.goToPage(this.innerHTML);
        return false;
      }

      paging_btm.appendChild(link);
      paging_btm.appendChild(html.SPAN(' ')); // space
    } // end for loop

    $('pagenumbers-btm').innerHTML = '';
    if (prevlink) {
      $('pagenumbers-btm').appendChild(prevlink);
      $('pagenumbers-btm').appendChild(html.SPAN(' '));
    }
    $('pagenumbers-btm').appendChild(paging_btm);
    if (nextlink) $('pagenumbers-btm').appendChild(nextlink);
  },

  goToPage: function(num){
    this.page = parseInt(num);
    this.populateData();
  }
}

// For those non JS 1.5 users
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(val, fromIndex) {
    if (typeof(fromIndex) != 'number') fromIndex = 0;
    for (var index = fromIndex,len = this.length; index < len; index++)
    if (this[index] == val) return index;
    return -1;
  }
}

function getQueryParam(paramName,url){
  var i;
  var len;
  var idx;
  var queryString;
  var params;
  var tokens;
  url=url||top.location.href;
  idx=url.indexOf("?");
  queryString=idx>=0?url.substr(idx+1) : url;params=queryString.split("&");
  for(i=0,len=params.length;i<len;i++){
    tokens=params[i].split("=");
    if(tokens.length>=2){
      if(tokens[0]==paramName){
        return unescape(tokens[1]);
      }
    }
  }
  return null;
}


// Builds the filters on the left pane
FilterPage.Filters = {
  // Default Values
  filterXML: '../Newsroom/nc3.0/xml/filters-podcasts.xml',
  
  // Init Function
  init: function(){
    this.container = $('filtersContainer');
    this.ajax.send();
  },
  
  // Asyc Functions
  ajax: {
    send: function(){
      var request = YAHOO.util.Connect.asyncRequest('POST', FilterPage.Filters.filterXML, this.callback); 
    },

    callback: {
      success: function(o){
        FilterPage.Filters.buildFilters(o.responseXML);
      },
      failure: function(o){ }
    }
  },
  
  // This will apply some filiters on initial load
  prePopulate: function(filters){
    this.preFilters = filters;
  },
  
  // Creates all the filters
  buildFilters: function(data){
    var allFilters = data.getElementsByTagName('filter');
    for (var i=0; i < allFilters.length; i++){
      var filter = allFilters[i];
      if (filter.parentNode.tagName != 'filters') continue;
      this.buildFilter(filter.getAttribute('name'), filter);
    }
  },
  
  // Creates an individual filter
  buildFilter: function(name, filter, options){
    if (typeof options != 'object') options = {}
    
    // Build heading and <select>
    var id = name.toLowerCase().replace(/ /g, "");
    var filterdiv = html.DIV();
    var heading = html.H4(name);
    var selectContainer = html.SELECT({id:id, 'class': 'filteroff'});
    id = (options.parentValue) ? options.parentValue : id;
    selectContainer.setAttribute('parent', id);
    
    // Build the options for the select container
    var optionElements = filter.getElementsByTagName('option');
    for (var i=0; i<optionElements.length; i++){
      var option = optionElements[i];
      // Add tag values to cache
      if (!FilterPage.Results.tags[id]) FilterPage.Results.tags[id] = [];
      if (option.getAttribute('value') != "" && option.getAttribute('value') != "00") FilterPage.Results.tags[id].push(option.getAttribute('value'));
      
      // Only continue for direct parents right now
      if (option.parentNode != filter) continue;
      var title = option.firstChild.nodeValue;
      title = title.replace(/[\r\n]+/g, "");
      title = title.replace(/	/g, "");
      var value = option.getAttribute('value');
      var htmlOption = html.OPTION({value:value}, title);
      // Should it be pre-selected?
      if (this.preFilters && this.preFilters.indexOf(value.toString()) != -1){
        // Add it to the HTML (1)
        htmlOption.setAttribute('selected', 'selected');
        selectContainer.className = '';
        // Add it to the filters (2)
        FilterPage.Results.activeTags[id] = value;
      }
      // Does it have sub-filter?
      if (option.getElementsByTagName('filter').length > 0) htmlOption.setAttribute('subfilter', 'true');
      selectContainer.appendChild(htmlOption);
    }

    // Subfilters, hide or highlight
    if (options.parentValue) {
      filterdiv.className = 'filtermore';
      filterdiv.setAttribute('id', 'subfilterDiv-' + options.parentValue);
      FilterPage.Filters.hideSubFilter(filterdiv);
    }
    if (options.hidden == 'false') {
      FilterPage.Filters.setSelectedSubFilter($(options.parentSelect), options.parentValue);
      FilterPage.Filters.highlight(filterdiv);
    }

    // Attach event handlers
    if (window.isIE7) {
      selectContainer.onmousedown = function() {
        this.setAttribute('oldclass', this.className);
        this.className = '';
      }
    } else {
      selectContainer.onfocus = function() {
        this.setAttribute('oldclass', this.className);
        this.className = '';
      }
    }

    selectContainer.onblur = function(){
      if (this.getAttribute('oldclass')){
        this.className = this.getAttribute('oldclass');
        this.setAttribute('oldclass', '');
      }
    }
    selectContainer.onchange = function(){
      var option = this.options[this.selectedIndex];

      // check for "Filter Off" state
      if (option.value == "00"){
        this.className = 'filteroff';
        this.setAttribute('oldclass', 'filteroff')
      }else{
        this.className = '';
        this.setAttribute('oldclass', '')
      }

      // Un-select current sub-filters
      if (this.selectedSubFilter != null) {
        $(this.selectedSubFilter).lastChild.selectedIndex = 0;
        FilterPage.Results.filterTag($(this.selectedSubFilter).lastChild.value, $(this.selectedSubFilter).lastChild.getAttribute('parent'));
        FilterPage.Filters.hideSubFilter($(this.selectedSubFilter));
        this.selectedSubFilter = null;
	    }
      
      // Fiilter results
      FilterPage.Results.filterTag(this.value, this.getAttribute('parent'));
      
      // Show the sub-filter if it applies
      if (option.getAttribute('subfilter') != 'true') return false;
      FilterPage.Filters.setSelectedSubFilter(this, option.getAttribute('value'));
      FilterPage.Filters.highlight($(this.selectedSubFilter));
    }

    // Attach the elements
    filterdiv.appendChild(heading);
    filterdiv.appendChild(selectContainer);
    this.container.appendChild(filterdiv);
    
    var subFilters = filter.getElementsByTagName('filter');
    if (subFilters.length == 0) return;
    
    for (var i=0; i < subFilters.length; i++) {
      var subFilter = subFilters[i];
      var isHidden = (selectContainer[selectContainer.selectedIndex].value == subFilter.parentNode.getAttribute('value')) ? 'false' : 'true';
      this.buildFilter(subFilter.getAttribute('name'), subFilter, {hidden:isHidden, parentValue:subFilter.parentNode.getAttribute('value'), parentSelect:selectContainer.id});
    };
    
    this.finished = true;
  },
  highlight:  function (subdiv) {
    subdiv.style.display = 'block';
    var filtermoredivAnim = new YAHOO.util.ColorAnim(subdiv, { backgroundColor: { from: '#FFFF22', to: '#F7F7F7' } }, 2, YAHOO.util.Easing.easeOut);
    filtermoredivAnim.animate();
  },
  hideSubFilter: function (subdiv) {
    subdiv.style.display = 'none';
  },
  setSelectedSubFilter: function (subdiv, id) {
    subdiv.selectedSubFilter = 'subfilterDiv-' + id;
  }
}
function go_to(url) { window.location = url; }
var cookieNamePrefix = "pc-";

