$(document).ready(function(){
	initSearchNews();
	$.ajaxHistory.initialize(function(){
		resetPage();
	});
});

function setEventsFlash(){
var rand = Math.floor(Math.random()*100000);
var movie = "/swf/events.swf?rnd=" + rand;
var so = new SWFObject(movie, "events_ticker", "200", "100", "6", "#ffffff");
so.write("flashcontent");
}


function resetPage()
{
  $('.news-years a.active').removeClass("active");
  $('.news-months a.active').removeClass("active");
  $('input[@name=clippings]').attr("checked","");
  $('input[@name=clippings][@value=all]').attr("checked","checked");
  $('#news-category/option:eq(0)').attr("selected", "selected");
  getParams();
  getNewsResults();
  hideNews();
/*  $('#results li a:eq').removeClass("active");
  $('#results li a:eq(0)').addClass("active");
  getNews();*/
  setEventsFlash();
}

function initParams()
{
  years = new Array();
  months = new Array();
  newsitems = new Array();
  category = "";
  param_years = "";
  param_months = "";
  param_category = "";
  param_clippings = "";
  param_page = "";
  params = "";
}

function initSearchNews()
{
  initSubscription();
  initParams();
  initSearchYears();
  initSearchMonths();
  initNewsResults();
  initSelectBox();
  initPaging();
  activate = new Array();
  initCheckboxes(activate);
  showYears();
  setEventsFlash();
/*  $.ajaxHistory.initialize(function()
  {
    window.location = window.location.pathname;
  });*/
}

function showYears()
{
  $('#show-years').click(function(){
    target = $(this).parent().next('p');
    $(this).hide();
    /*
    if(target.css("display") == "block")
    {
      $(this).attr("src","/img/pager-right-active.gif")
    }
    else
    {
      $(this).attr("src","/img/pager-down-active.gif")
    }
    */
    $(this).parent().next('p').toggle();
    
    return false;
  });
}

function initNewsResults()
{
  $('#results li a').each(function(){
	href = this.href;
    this.href = '#'+ href.substr( window.location.protocol.length + window.location.host.length + 3);
  $(this).unbind("click");
  //$(this).click(function(){
  var this_id = $(this).attr("id");
  $(this).history(function(){
    $('#results li a.active').toggleClass("active");
    $('#'+this_id).toggleClass("active");
    
    getParams();
    getNews();
    //return false;
  });
  });
}

function initSearchYears()
{
  $('.news-years a.available, .news-years a.active').click(function(){
    if($('#news-months').css("display") == "none" || $(this).attr("class") == "available active")
    {
      hideNews();
      $('#news-months').toggle();
    }
       
    if($(this).attr("class") != "available active")
    {
      $('.news-years a.active').toggleClass("active");
      $('#news-months a.active').toggleClass("active");
    }

    $(this).toggleClass("active"); 
    
    
    displayMonths();
    return false;
    
  });
}

function displayMonths()
{
  getParams();
  params = param_years + param_months + param_category + param_clippings;
  
  $.ajax({
    type: "POST",
    url: "/components/index/module_name/news/component/displaySearchMonths" + params,
    beforeSend: function () { urchinTracker("/components/index/module_name/news/component/displaySearchMonths" + params); },      
    success: function(xmlData){
      $('#news-months').html(xmlData);
      initParams();
      initSearchMonths();
      getParams();
      getNewsResults();
    }
  });
}

function displayYears()
{
  getParams();
  params = param_years + param_months + param_category + param_clippings;
  //$('#months-years/.news-years').remove();
  $.ajax({
    type: "POST",
    url: "/components/index/module_name/news/component/displaySearchYears" + params,
    beforeSend: function () { urchinTracker("/components/index/module_name/news/component/displaySearchYears" + params); },        
    success: function(xmlData){
      $('#months-years').html(xmlData);
      initParams();
      showYears();
      initSearchYears();
      getParams();
      getNewsResults();
    }
  });
}

function initSearchMonths()
{
  $('#news-months a.available, #news-months a.active').click(function(){
    hideNews();
    $('#news-months a').removeClass("active");
    $(this).toggleClass("active");
    getParams();
    getNewsResults();
    return false;
  });
}

function getParams()
{
initParams();
  if(paging)
  {
    param_page = paging;
    paging = false;
  }
  $('.news-years a.active').each(function(){
    years[years.length] = $(this).html();
  });
  
  $('#news-months a.active').each(function(){
    monthid = $(this).attr("id");
    months[months.length] = monthid.substring(6);
  });
  
  $('#results li a.active').each(function(){
    newsid = $(this).attr("id");
    newsitems[newsitems.length] = newsid.substring(5);
  });
  
  $('.select li.activeoption').each(function(){
    category_id = $(this).attr("id");
    category_id = category_id.split("_");
    category = category_id[2];
  });
  
  category = $('#news-category option:selected').val();
    
  if(years.length>0)
  {
  param_years = "/year/" + years;
  }

  if(months.length>0)
  {
  param_months = "/month/" + months;
  }
  
  if(newsitems.length>0)
  {
  param_news = "/news_id/" + newsitems;
  }
  
  if(category != "")
  {
  param_category = "/category/" + category;
  }
  
  if($('input[@name=clippings]').fieldValue())
  {
  param_clippings = "/clippings/" + $('input[@name=clippings]').fieldValue();
  }
  
}



function getNewsResults()
{
  getParams();
  params = param_years + param_months + param_category + param_clippings + param_page;
  //alert(params);
    $('.two-col:eq(0)/.content-wrapper').css("background", "#ffffff url('/img/loader_small.gif') no-repeat 100% 8px");
  $.ajax({
    type: "POST",
    //url: "/components/index/module_name/news/component/getNewsResults" + params,
    url: "/components/index/module_name/news/component/newsResults" + params,
    beforeSend: function () { urchinTracker( "/components/index/module_name/news/component/newsResults" + params); },  
    success: function(xmlData){
      $('.two-col:eq(0)/.content-wrapper').css("background", "");
      $('#content/.two-col:eq(0)/.content-wrapper').html(xmlData);
      initParams();
      initPaging();
      initNewsResults();
   /*      
      getParams();
      params = param_years + param_months + param_category + param_clippings + param_page;
  
      $.ajax({
        type: "POST",
        url: "/components/index/module_name/news/component/getNewsPaging" + params,
        success: function(xmlData){
          $('#column-footer/.two-col:eq(1)/.content-wrapper').html(xmlData);
          initParams();
          initPaging();
          initNewsResults();
        }
      });
      */
    }
  });
}

function hideNews()
{
  if($('#content/.four-col/.content-wrapper').css("display") == "block")
  {
    $('#content/.four-col/.content-wrapper').fadeOut("fast");
  }
}

function initPaging()
{
  paging = false;
  $(".paging-controls/div/span.active").each(function()
  {
    $(this).click(function(){
      
      var page = $(this).attr("id");
      page = page.split("_");
      page = page[1];
      param_page = "/page/" + page;
      paging = param_page;
      getNewsResults();
    });
  });
}

function getNews()
{
  params = param_news;
  if($('#content/.four-col/.content-wrapper').css("display") == "block")
  {
//    $('#content/.four-col/.content-wrapper').fadeOut("slow", function(){
  //  $('#content/.four-col').append(loader);
    $('#content/.four-col/.content-wrapper').hide();
    $.ajax({
        type: "POST",
        url: "/components/index/module_name/news/component/displayNews" + params,
        beforeSend: function () { urchinTracker("/components/index/module_name/news/component/displayNews" + params); }, 
        success: function(xmlData){
          removeLoader();
          window.scrollTo(0, 0);
          $('#content/.four-col/.content-wrapper').html(xmlData);
//          $('#content/.four-col/.content-wrapper').fadeIn("slow");
//          $('#content/.four-col/.content-wrapper').fadeIn("fast");
			$('#content/.four-col/.content-wrapper').show();
          initParams();
        }
      });
    //});
  } else
  {
    //$('#content/.four-col').append(loader);
    $.ajax({
        type: "POST",
        url: "/components/index/module_name/news/component/displayNews" + params,
        beforeSend: function () { urchinTracker("/components/index/module_name/news/component/displayNews" + params); },               
        success: function(xmlData){
          removeLoader();
          $('#content/.four-col/.content-wrapper').html(xmlData);
          //$('#content/.four-col/.content-wrapper').fadeIn("slow");
          //$('#content/.four-col/.content-wrapper').fadeIn("fast");
			$('#content/.four-col/.content-wrapper').show();
          initParams();
        }
      });
  }
  
}

function initSelectBox()
{
/*
  replaceOptions = new Array()
  options = $('#news-category option');
  selected = 0;
  
  $('#news-category').each(function(i){
    $(this).after('<ul class="select" id="news-category-replacement"></ul>');
    $(this).hide();
  });

  $(options).each(function(i){
  
    value = $(this).val();
    html = $(this).html();
    
    if($(this).attr("selected"))
    {
    selected = i;
    }
    
    $('<li class="option" id="option_'+ i +'_' + value + '">' + html + '</li>').appendTo('#news-category-replacement');
    $(this).hide();
  });
  
  $('.select li:eq(' + selected + ')').attr("class", "activeoption");
  active = false;
  initSelectOptions();
*/
//  alert('init select');

  $('#news-category').change(function()
  {
//  alert('change');
    hideNews();
    $('.news-years a').removeClass("active");
    $('#news-months a').removeClass("active");
    $('#news-months').hide();
    displayYears();
    displayMonths();
    getNewsResults();
  });

}

function initSelectOptions()
{
  $(".select .activeoption").click(function(){
  //alert("activeoption");
    $('.select').hover(function(){}, function(){
      $('.select li.option').hide();
      $('.select').css("top", "0px");
      $('.select').css("position", "relative");
      $('.select option').css("z-index", "1");

      $('.select').parents('p').next().each(function(){
        $(this).css("margin-top", "0px");
      });

      $(".select").unbind();
    });  
    $('.select/li').css("top", "0px");
    $('.select/li').each(function(i){
      if($(this).attr("class") == "activeoption")
      {
        offset = "-"+($(this).height() * i)+"px";
      }
    });
    //alert(active);
    $(this).siblings('li.option').toggle();
    //alert(active);
    if(active)
    {
    active = false;
//    $(this).siblings('li.option').hide();
    }
    else
    {
    //$(this).unbind();
  	selectoffset ={};
  	$(this).offset({scroll:false}, selectoffset);
    offset = parseInt(offset) + parseInt(selectoffset.top) -1;
    
    $('.select').css("top", offset);
    //$('.select').css("margin-top", "-1px");
    /* compensate for change to position: absolute*/
    $('.select').parents('p').next().each(function(){
      $(this).css("margin-top", "17px");
    });
    $('.select').css("height", "auto");
    $('.select').css("position", "absolute");
    $('.select option').css("z-index", "100");
//    $(this).siblings('li.option').show();
    
    }
  });
  
  $(".select .option").click(function(){
    //alert("option");
    $('.select .activeoption').attr("class", "option");
    $(this).attr("class", "activeoption");
    $('.select').css("top", "0px");
    $(".select/li").unbind();
    active = true;
    displayMonths();
    getNewsResults();
    initSelectOptions();
  });
  $('.select .option').hide();
}


function setRadioStatus(id)
{
  //alert(id);
  var i = id.substring(6);
    
  /*
    if the button is not checked...
    */
  if(!$(radios[i]).attr("checked")) {
    
    var name = $(radios[i]).attr("name");
    /*
          uncheck all other radio buttons with the same name and set the background to the radio button off image
          */
    $("input:radio[@name=" + name + "]").attr("checked", "");
//    $("input:radio[@name=" + name + "]").parent(".radio").css({background:"url('" + radioFalse + "') no-repeat 1px 4px"});
    $("input:radio[@name=" + name + "]").parent(".radio").removeClass("radiotrue");
    $("input:radio[@name=" + name + "]").parent(".radio").addClass("radiofalse");
    
    /*
          uncheck all sector and geography checkboxes...
          no need to reset the graphics because it's going to be redrawn anyway and it flickers in FF browsers
          
          Might need to adjust the way this functions - perhaps you want to keep a location selected as you switch between industries?
          */
    $("input:checkbox[@name=sector_id]").attr("checked", "");
    $("input:checkbox[@name=location_id]").attr("checked", "");

          
    $(radios[i]).attr("checked", "checked");
//    $(radios[i]).parent(".radio").css({background:"url('" + radioTrue + "') no-repeat 1px 4px"});
    $(radios[i]).parent(".radio").addClass("radiotrue");
  }
  displayYears();
  displayMonths();
  getParams();
  getNewsResults();

}

function initCheckboxes(activate)
{
  //alert(activate);
  checkboxes = $("input:checkbox");
  radios = $("input:radio");
  checkboxTrue = '/img/checkbox_true.gif';
  checkboxFalse = '/img/checkbox_false.gif';
  radioTrue = '/img/radio_true.gif';
  radioFalse = '/img/radio_false.gif';
  
  $("input:radio").each(function(i){
    $(this).parent('.radio').attr("id", "radio_" + i);
    
    $("#radio_" + i).click(function(){
      hideNews();
      var i = $(this).attr("id");
      setRadioStatus(i);
    });
    
    $(this).hide();
  });
  
  $("input:checkbox").each(function(i){
    //$(this).parent('.checkbox').css({background: "url('" + checkboxFalse + "') no-repeat 0 5px"});
    $(this).parent('.checkbox').attr("id", "checkbox_" + i);
    
    $("#checkbox_" + i).click(function(){
      var i = $(this).attr("id");
      setCheckStatus(i);
    });
    
    $(this).hide();
  });

  for(i=0; i<activate.length; i++)
  {
    if($(activate[i]).parent('.checkbox').attr("id"))
    {
      setCheckStatus($(activate[i]).parent('.checkbox').attr("id"));
    }
    if($(activate[i]).parent('.radio').attr("id"))
    {
      setRadioStatus($(activate[i]).parent('.radio').attr("id"));
    }
  }
  
  initCheckImages();
}

function initCheckImages()
{
  //$('.checkbox-image').click(function(){
  $('.search-fields//li[input]').click(function(){
  searchFields = new Array("industry_id", "sector_id", "location_id", "company_status", "clippings");
  var activate = new Array();

  var params = new Array();
  var paramStr = "";
  
    for (i=0; i<searchFields.length; i++)
    {
      //var values = $("input[@type=checkbox][@name=" + searchFields[i] + "]").fieldValue();
      var values = $("input[@name=" + searchFields[i] + "]").fieldValue();
      if (values.length > 0)
      {
        params[params.length] = searchFields[i] + "/" + values;
        for(j=0;j<values.length;j++)
        { 
          //var target = searchFields[i].substring(0,searchFields[i].length-2);
          var re = new RegExp("_id", "g");
          var field = searchFields[i];
          
          if(field.match(re))
          {
            var target = field.replace(re, "_");
          }
          else
          {
            var target = field + "_"; // + values[j];
          }
          activate[activate.length] = "#" + target + values[j];
        }
      }
    }
    
    if(params.length > 0)
    {
      for (i=0; i<params.length; i++)
      {
        paramStr += params[i] + "/";
      }
    }
    /*
    $.ajax({
      type: "POST",
      url: "/components/index/module_name/portfolio/component/portfolioResults/" + paramStr,
      success: function(xmlData){
        $('#results').parent(".two-col").html(xmlData);
        initResults();
      }
    });
    
    $.ajax({
      type: "POST",
      url: "/components/index/module_name/portfolio/component/portfolioSearch/" + paramStr,
      success: function(xmlData){
        $('ul.search-fields').parent(".two-col").html(xmlData);
        initCheckboxes(activate);
      }
    });*/
  });
}

function initSubscription()
{
  $('#news_subscription').focus(function(){
    $(this).attr("value", "");
  });

  $('#news-subscribe img').click(function(){
    var address = $('#news_subscription').val();
  
    $.ajax({
      type: "POST",
      url: "/subscription/add",
      data: "address=" + address,
      beforeSend: function () { urchinTracker("address=" + address); }, 
      success: function(xmlData){
        $('#news-subscribe img').next('p').remove();
        $('#news-subscribe img').after('<p class="subscription-feedback">'+xmlData+'</p>');
      }
    });
  });  
}
