$(document).ready(function(){
  //alert("document");
  initReset();
  initCheckboxes();
  initSectors();
  initGeographies();
  initResults();
  bgImage = 'portfolio_1.gif';
//  alert(bgImage);
  x_offset = 530;
  bgImageCheck();
  $.ajaxHistory.initialize(function()
  { 
	  resetPage();
/*    window.location = window.location.pathname;*/
  });
  //checkCookie();
  //scrollingLinks();

});


/*
function scrollingLinks(){
  $('#news-headlines a').click(function(){
    //$.scrollTo(0, 800);
    window.scrollTo(0, 0);
    return false;
  })
}*/


function bgImageCheck()
{

//alert($('#content').css('background-image'));
 


 if($('.four-col .content-wrapper h2').size() == 0 && $('#content').css('background-image') == "none")
  {
//  alert("setting bgIMage");
	content_data = getLockedContent(5, '.four-col .content-wrapper');
  if ( content_data ) {
  //getWebareaByName('portfolio_welcome', '.four-col .content-wrapper');  
	setBgImage(bgImage, x_offset);

  }
  }
  else if($('.four-col .content-wrapper h2').size() == 0)
  {
   content_data =  getLockedContent('5', '.four-col .content-wrapper');
  if ( !content_data ) { 
  getWebareaByName('portfolio_welcome', '.four-col .content-wrapper');   
	setBgPos();
  }

  }
  else
  {
    setBgImage("", 0);

  }

}


function  resetPage()
{
  $('#portfolio-sectors/li/a.active').removeClass("active");
  $('#portfolio-geographies/li/a.active').removeClass("active");
  $('input[@name=company_status]').each(function(){
    $(this).parent().removeClass("radiotrue");
    $(this).parent().addClass("radiofalse");
    if($(this).val()=="")
    {
    $(this).parent().addClass("radiotrue");
    }
  });
  getParams();
  $.ajax({
    type: "POST",
    url: "/components/index/module_name/portfolio/component/portfolioSearch/" + paramStr,
    beforeSend: function () { urchinTracker( "/components/index/module_name/portfolio/component/portfolioSearch/" + paramStr); }, 
    success: function(xmlData){
      $('ul.search-fields').parent("#content/.two-col/.content-wrapper").html(xmlData);
      initReset();
      initCheckboxes();
      initSectors();
      initGeographies();
      getCompanies();
    }
  });
}

function setCheckStatus(id)
{
  //alert(id);
  var i = id.substring(9);
  
  if($(checkboxes[i]).attr("checked")) {
    $(checkboxes[i]).attr("checked", "");
    //$(checkboxes[i]).parent(".checkbox").css({background:"url('" + checkboxFalse + "') no-repeat 0 5px"});
    $(checkboxes[i]).parent(".checkbox").removeClass("checktrue");
    $(checkboxes[i]).parent(".checkbox").addClass("checkfalse");
  } else {
    $(checkboxes[i]).attr("checked", "checked");
    //$(checkboxes[i]).parent(".checkbox").css({background:"url('" + checkboxTrue + "') no-repeat 0 5px"});
    $(checkboxes[i]).parent(".checkbox").removeClass("checkfalse");
    $(checkboxes[i]).parent(".checkbox").addClass("checktrue");
  }
}

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");
    
          
    $(radios[i]).attr("checked", "checked");
    $(radios[i]).parent(".radio").addClass("radiotrue");
  }
}

$(window).bind('load', function(){
   var preload = [
     '/img/checkbox_true.gif',
     '/img/checkbox_false.gif',
     '/img/radio_true.gif',
     '/img/radio_false.gif'
   ];           
   $(document.createElement('img')).bind('load', function(){
    if(preload[0]) this.src = preload.shift();
   }).trigger('load');          
});

function initReset()
{
  $('#reset').click(function(){
    $("input:radio[@name=industry_id]").each(function(){
      $(this).attr("checked", "");
      $(this).parent().attr("class", "radio radiofalse");
    });
    
    $('#portfolio-sectors').parent().slideUp("fast", function(){
      $('#portfolio-sectors').parent().remove();
    });
    
    $("input:radio[@name=industry_id][@id=industry_0]").each(function(){
      $(this).attr("checked", "checked");
      $(this).parent().attr("class", "radio radiotrue");
    });

    $.cookie('portfolio_industry', null);
    
    $("input:radio[@name=company_status]").each(function(){
      if($(this).val() != ""){
        $(this).attr("checked", "");
        $(this).parent().attr("class", "radio radiofalse");
      }
      else
      {
        $(this).attr("checked", "checked");
        $(this).parent().attr("class", "radio radiotrue");
      }
    });
    $("input:radio[@name=company_stage]").each(function(){
      if($(this).val() != ""){
        $(this).attr("checked", "");
        $(this).parent().attr("class", "radio radiofalse");
      }
      else
      {
        $(this).attr("checked", "checked");
        $(this).parent().attr("class", "radio radiotrue");
      }
    });

    $("input:checkbox").each(function(){
      $(this).attr("checked", "");
      $(this).parent().attr("class", "checkbox checkfalse");
    });
    activate = new Array();

    $('a.portfolio-sector').each(function(){
      $(this).removeClass('active');
    });

    $('a.portfolio-geography').each(function(){
      $(this).removeClass('active');
    });
    
	hideCompany();
    getGeographies();
    getSectors();
    getCompanies();
    //$('.search-fields//li:eq(0)[input]').click();
    
    return false;
  });
}

function initSectors()
{
  //$('#portfolio-sectors').slideDown("fast");
  $('a.portfolio-sector').each(function(){

    $(this).unbind("click");
	href = this.href;
    this.href = '#'+ href.substr( window.location.protocol.length + window.location.host.length + 3);
    var this_id = $(this).attr("id");
//    $(this).click(function(){
    $(this).history(function(){
   	bgImageCheck();
      miniLoader();
    //alert("clicked");
      hideCompany();
      // When clicking on an unavailable option
      //
      if($('#'+this_id).attr("class") == "portfolio-sector")
      {
        $('#portfolio-sectors/li/a.active').each(function(){
          $(this).removeClass("active");
          $(this).addClass("available");
        });
        
        $('#portfolio-geographies/li/a.active').each(function(){
          $(this).removeClass("active");
          $(this).addClass("available");
        });
        
        $("input:radio[@name=company_status]").each(function(){
          if($(this).val() != ""){
            $(this).attr("checked", "");
            $(this).parent().attr("class", "radio radiofalse");
          }
          else
          {
            $(this).attr("checked", "checked");
            $(this).parent().attr("class", "radio radiotrue");
          }
        });

        $("input:radio[@name=company_stage]").each(function(){
          if($(this).val() != ""){
            $(this).attr("checked", "");
            $(this).parent().attr("class", "radio radiofalse");
          }
          else
          {
            $(this).attr("checked", "checked");
            $(this).parent().attr("class", "radio radiotrue");
          }
        });
        $('#'+this_id).addClass("active");
        $('#'+this_id).removeClass("available");
      }
      // When clicking on an active option
      //
      else if($('#'+this_id).attr("class") == "portfolio-sector active")
      {
        $('#portfolio-sectors/li/a.active').each(function(){
          $(this).removeClass("active");
          $(this).addClass("available");
          getSectors();
        });
      }
      // When clicking on an available option
      //
      else if($('#'+this_id).attr("class") == "portfolio-sector available")
      {
        $('#portfolio-sectors/li/a.active').each(function(){
          $(this).removeClass("active");
          $(this).addClass("available");
        });
        $('#'+this_id).addClass("active");
        $('#'+this_id).removeClass("available");
      }

      getCompanyStatus();
      getCompanyStage();
      getGeographies();
      //return false;
    });
  });
}

function getGeographies()
{
  getParams();
  
  $.ajax({
    type: "POST",
    url: "/components/index/module_name/portfolio/component/getPortfolioGeographies/" + paramStr,
    beforeSend: function () { urchinTracker( "/components/index/module_name/portfolio/component/getPortfolioGeographies/" + paramStr); },  
    success: function(xmlData){
      //$('ul.search-fields').parent("#content/.two-col/.content-wrapper").html(xmlData);
      $('#portfolio-geographies').html(xmlData);
      //initReset();
      initCheckboxes();
      //initSectors();
      initGeographies();
      //getCompanies();
      }
  });
}

function getCompanyStatus()
{
  getParams();
  
  $.ajax({
    type: "POST",
    url: "/components/index/module_name/portfolio/component/getPortfolioCompanyStatus/" + paramStr,
    beforeSend: function () { urchinTracker( "/components/index/module_name/portfolio/component/getPortfolioCompanyStatus/" + paramStr); },  
    success: function(xmlData){
      //$('ul.search-fields').parent("#content/.two-col/.content-wrapper").html(xmlData);
      $('#portfolio-companystatus').html(xmlData);
      //initReset();
      initCheckboxes();
      //initSectors();
      initGeographies();
      getCompanies();
      }
  });
}

function getCompanyStage()
{
  getParams();
  
  $.ajax({
    type: "POST",
    url: "/components/index/module_name/portfolio/component/getPortfolioCompanyStage/" + paramStr,
    beforeSend: function () { urchinTracker( "/components/index/module_name/portfolio/component/getPortfolioCompanyStage/" + paramStr); },  
    success: function(xmlData){
      //$('ul.search-fields').parent("#content/.two-col/.content-wrapper").html(xmlData);
      $('#portfolio-companystage').html(xmlData);
      //initReset();
      initCheckboxes();
      //initSectors();
      initGeographies();
      getCompanies();
      }
  });
}

function getSectorParams()
{
  var sector_ids = new Array();
  $('#portfolio-sectors/li/.active').each(function(){
    sid = $(this).attr("id");
//    active_sectors[active_sectors.length] = sid;
    sid = sid.split("_");
    sector_ids[sector_ids.length] = sid[1];
  //  active_sectors[active_sectors.length] = sid[1];
  });

  paramSector = "";
  for(i=0; i < sector_ids.length; i++)
  {
    if(i > 0)
    {
    paramSector += ",";
    }
    paramSector += sector_ids[i];
  }
  if(paramSector != "")
  {
    paramSector = "sector_id/" + paramSector;
  }
}

function initGeographies()
{

  $('a.portfolio-geography').each(function(){
 
  $(this).unbind("click");
//    $(this).click(function(){
    var this_id = $(this).attr("id");
    $(this).history(function(){
	 bgImageCheck();
      miniLoader();
    //alert("clicked");
      hideCompany();
      if($('#'+this_id).attr("class") == "portfolio-geography")
      {
        $('#portfolio-geographies/li/a.active').each(function(){
          $(this).removeClass("active");
          $(this).addClass("available");
        });
        
        $('#portfolio-sectors/li/a.active').each(function(){
          $(this).removeClass("active");
          $(this).addClass("available");
        });
        $("input:radio[@name=company_status]").each(function(){
          if($(this).val() != ""){
            $(this).attr("checked", "");
            $(this).parent().attr("class", "radio radiofalse");
          }
          else
          {
            $(this).attr("checked", "checked");
            $(this).parent().attr("class", "radio radiotrue");
          }
        });
        $("input:radio[@name=company_stage]").each(function(){
          if($(this).val() != ""){
            $(this).attr("checked", "");
            $(this).parent().attr("class", "radio radiofalse");
          }
          else
          {
            $(this).attr("checked", "checked");
            $(this).parent().attr("class", "radio radiotrue");
          }
        });
        $('#'+this_id).addClass("active");
        $('#'+this_id).removeClass("available");
        getGeographies();
      }
      // When clicking on an active option
      //
      else if($('#'+this_id).attr("class") == "portfolio-geography active")
      {
        //alert("clicking on an active option");
        $('#portfolio-geographies/li/a.active').each(function(){
          $(this).removeClass("active");
          $(this).addClass("available");
          getGeographies();
        });
      }
      else if($('#'+this_id).attr("class") == "portfolio-geography available")
      {
        //alert("selecting an available option");
        $('#portfolio-geographies/li/a.active').each(function(){
          $(this).removeClass("active");
          $(this).addClass("available");
        });
        $('#'+this_id).addClass("active");
        $('#'+this_id).removeClass("available");
      }
      getCompanyStage();
      getCompanyStatus();
      getSectors();
      
      return false;
    });
  });
}

function getSectors()
{
  getParams();
  
  $.ajax({
    type: "POST",
    url: "/components/index/module_name/portfolio/component/getPortfolioSectors/" + paramStr,
    beforeSend: function () { urchinTracker("/components/index/module_name/portfolio/component/getPortfolioSectors/" + paramStr); },    
    success: function(xmlData){
      //$('ul.search-fields').parent("#content/.two-col/.content-wrapper").html(xmlData);
      $('#portfolio-sectors').html(xmlData);
      //initReset();
      initCheckboxes();
      initSectors();
      //initGeographies();
      //getCompanies();
      }
  });
}

function getGeographyParams()
{
  var geography_ids = new Array();
  $('#portfolio-geographies/li/.active').each(function(){
    gid = $(this).attr("id");
    //active_geographies[active_geographies.length] = gid;
    gid = gid.split("_");
    geography_ids[geography_ids.length] = gid[1];
    //active_geographies[active_geographies.length] = gid[1];
  });

  paramGeography = "";
  for(i=0; i < geography_ids.length; i++)
  {
    if(i > 0)
    {
    paramGeography += ",";
    }
    paramGeography += geography_ids[i];
  }
  if(paramGeography != "")
  {
    paramGeography = "geography_id/" + paramGeography;
  }
}

function initCheckboxes()
{
  paramSector = "";
  paramGeography = "";
  $('.search-fields//li[input]').each(function(){
    $(this).unbind("click");
  });
  checkboxes = $("input:checkbox");
  radios = $("input:radio");
  
  $("input:radio").each(function(i){
    $(this).parent('.radio').attr("id", "radio_" + i);
    
    $("#radio_" + i).click(function(){
//      $("#radio_" + i).history(function(){  
      var i = $(this).attr("id");
      //$.cookie('portfolio_industry'); // get cookie

      // set cookie with an expiration date seven days in the future...
      //
      if($(this).find('input').attr("name") == "industry_id")
      {
        if($(this).find('input').val() != "")
        {
        $.cookie('portfolio_industry', $(this).find('input').val(), { expires: 7 });
        }
        else
        {
        //alert("deleting cookie");
        $.cookie('portfolio_industry', null);
        }
      }
      
      if($(this).find('input').attr("name") == "company_status")
      {
        //$('#portfolio-sectors/li/a').removeClass('active');
        //$('#portfolio-geographies/li/a').removeClass('active');
      }
      

      setRadioStatus(i);
    });

    $(this).hide();
  });
   
  $("input:radio[@checked]").each(function(i){
  //alert("found checked radio");
    
    $(this).parent().addClass("radiotrue");
    $(this).parent().removeClass("radiofalse");
  });
  
  $("input:checkbox").each(function(i){
    $(this).parent('.checkbox').attr("id", "checkbox_" + i);
    
    $("#checkbox_" + i).click(function(){
      var i = $(this).attr("id");
      setCheckStatus(i);
    });
    
    $(this).hide();
  });
  
  $("input:checkbox[@checked]").each(function(i){
    $(this).parent().addClass("checktrue");
    $(this).parent().removeClass("checkfalse");
  });

  initCheckImages();

}

function getParams()
{
  searchFields = new Array("industry_id", "sector_id", "location_id", "company_status",  "company_stage", "clippings");
  activate = new Array();
  params = new Array();
  paramStr = "";

  for (i=0; i<searchFields.length; i++)
  {
    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 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[params.length-1] == searchFields[i] + "/")
      {
        params.pop();
        activate.pop();
      }
    }
  }
  getSectorParams();
  getGeographyParams();
 if(params.length > 0)
  {
    for (i=0; i<params.length; i++)
    {
      paramStr += params[i] + "/";
    }
  }
  //alert(paramStr);
  if(paramSector != "")
  {
    paramStr = paramSector + "/" + paramStr;
    paramSector = "";
  }

  if(paramGeography != "")
  {
    paramStr = paramGeography + "/" + paramStr;
    paramGeography = "";
  }
}

function getCompanies()
{
  hideCompany();
  getParams();
  miniLoader();
  $.ajax({
    type: "POST",
    url: "/components/index/module_name/portfolio/component/portfolioResults/" + paramStr,
    beforeSend: function () { urchinTracker(  "/components/index/module_name/portfolio/component/portfolioResults/" + paramStr); },         
    success: function(xmlData){
      removeMiniLoader();
      $('#results').parent().html(xmlData);
  	  bgImageCheck();
      initResults();
    }
  });
/*  
  $.ajax({
    type: "POST",
    url: "/components/index/module_name/portfolio/component/portfolioSearch/" + paramStr,
    success: function(xmlData){
      $('ul.search-fields').parent("#content/.two-col/.content-wrapper").html(xmlData);
      initReset();
      initCheckboxes();
      initSectors();
      initGeographies();
    }
  });
  */
}

function initCheckImages()
{
  //$('.checkbox-image').click(function(){
  //$('.search-fields//li[input]').unbind("click");
  //$('.search-fields//li[input]').click(function(){
  $('.search-field/li[input:radio]').each(function(){
    $(this).click(function(){
    var this_id = $(this).attr("id");
    //$(this).history(function(){
      miniLoader();
      if($('#'+this_id).find("input").attr("name") == "company_status")
      {
        if($('#'+this_id).attr("class") == "radio radiofalse inactive radiotrue")
        {
          $('#portfolio-sectors/li/.active').removeClass("active");
          $('#portfolio-geographies/li/.active').removeClass("active");
        }
      }
      if($('#'+this_id).find("input").attr("name") == "company_stage")
      {
        if($('#'+this_id).attr("class") == "radio radiofalse inactive radiotrue")
        {
          $('#portfolio-sectors/li/.active').removeClass("active");
          $('#portfolio-geographies/li/.active').removeClass("active");
        }
      }
      if($('#'+this_id).find("input").attr("name") == "industry_id")
      {
        $('#portfolio-sectors/li/.active').removeClass("active");
        $('#portfolio-sectors').parent().slideUp('fast');
      }

      getParams();
      $.ajax({
        type: "POST",
        url: "/components/index/module_name/portfolio/component/portfolioSearch/" + paramStr,
        beforeSend: function () { urchinTracker(  "/components/index/module_name/portfolio/component/portfolioSearch/" + paramStr); },    
        success: function(xmlData){
          $('ul.search-fields').parent("#content/.two-col/.content-wrapper").html(xmlData);
          initReset();
          initCheckboxes();
          initSectors();
          initGeographies();
          getCompanies();
        }
      });
      
    });
  });
  $('.search-field/li[input:checkbox]').each(function()
  {
    $(this).click(function(){
      getParams();
      $.ajax({
        type: "POST",
        url: "/components/index/module_name/portfolio/component/portfolioSearch/" + paramStr,
        beforeSend: function () { urchinTracker(  "/components/index/module_name/portfolio/component/portfolioSearch/" + paramStr); },  
        success: function(xmlData){
          $('ul.search-fields').parent("#content/.two-col/.content-wrapper").html(xmlData);
          initReset();
          initCheckboxes();
          initSectors();
          initGeographies();
          getCompanies();
        }
      });
    });
  });
}

function checkCookie()
{
  if($.cookie('portfolio_industry'))
  {
    pind = $.cookie('portfolio_industry');
    $("input:radio[@value=" + pind + "]").parent().click();
    //$("li[@id=" + pind + "]").click();
  }
}

function initResults()
{
  loading = 0;
  $("#results").find("li a").each(function(){
      //$(this).click(function(){
      var this_id = $(this).attr("id");
      if(loading == 0)
      {
      $(this).history(function(){
      
       
        loading = 1;
        $("#results").find("li a").attr("class", "");

			if($("#results/li/a").index($('#'+this_id)[0]) >= 0)
			{
			  $('#'+this_id).attr("class", "active");
			}
			
			var company_id = this_id;
			company_id = company_id.split("_");
			company_id = company_id[1];
			if($(".four-col/.content-wrapper").css("display") == "block")
			{ 
			  //removeLoader();
			  
			  if(self.isReady)
			  { 
				clearInterval(isReady);
			  }
			  
			  //$(".four-col/.content-wrapper").fadeOut("fast", function()
			  //{
	//          $(".four-col/.content-wrapper").hide();
        //$.scrollTo({top:0, left:0}, 1000); 
			  $(".four-col/.content-wrapper").html("");
				//$(".four-col").append(loader);
        
				$.ajax({
				  type: "POST",
				  url: "/components/index/module_name/team/component/companyDetails/company_id/" + company_id,
				  beforeSend: function () { urchinTracker(  "/components/index/module_name/team/component/companyDetails/company_id/" + company_id); },      
				  success: function(xmlData){
					$("#content .four-col .content-wrapper").html(xmlData);
					bgImageCheck();
               
					//$("#content/.four-col").find("#dyn-area").fadeIn("slow");
             
					isReady= setInterval("readyToFade()", 100);
           window.scrollTo(0, 0);
          //scrollingLinks();
          //document.location = "#top"; 
          
          
				  }
				})
			  //});
        
			}
			else
			{
      
			  //removeLoader();
			  //$(".four-col").append(loader);
			  
			  if(self.isReady)
			  {
				clearInterval(isReady);
			  }
			  
        //$.scrollTo({top:0, left:0}, 1000);
        
        
			  $.ajax({
				type: "POST",
				url: "/components/index/module_name/team/component/companyDetails/company_id/" + company_id,
				beforeSend: function () { urchinTracker(  "/components/index/module_name/team/component/companyDetails/company_id/" + company_id); },         
				success: function(xmlData){
				  $("#content .four-col .content-wrapper").html(xmlData);
					bgImageCheck();
          
				  //$("#content/.four-col").find("#dyn-area").fadeIn("slow");
				    
				  isReady= setInterval("readyToFade()", 100);
             // window.scrollTo(0, 0);
//          /scrollingLinks();
          //document.location = "#top";
          
          
				}
			  })
			}
	    });
      }
  });
}

function readyToFade()
{
  if(document.images["company-logo"])
  {
    if(document.images["company-logo"].complete == true)
    {
     // alert("complete");
//      removeLoader();
      //$("#content/.four-col/.content-wrapper").fadeIn("slow");
      clearInterval(isReady);
      $("#content/.four-col/.content-wrapper").show();
//here   
 //  window.scrollTo(0, 0);
      loading = 0;
      //$('html').scrollTo(0, 800);
      //scrollingLinks();
	    }
  }
  else
  {
//    removeLoader();
//    $("#content/.four-col/.content-wrapper").fadeIn("slow");
    clearInterval(isReady);
    $("#content/.four-col/.content-wrapper").show();
//here
  //  window.scrollTo(0, 0);
    //$('html').scrollTo(0, 800);
    //scrollingLinks();
    loading = 0;
  }
}

function hideCompany()
{
  if(($("#content .four-col .content-wrapper").css("display") == "block") && $("#content .four-col .content-wrapper h2").size() > 0)
  {
  	setBgImage("", 0);
	$(".four-col .content-wrapper").html("");
//	bgImageCheck();
//    $("#content .four-col .content-wrapper").fadeOut("fast");
	
  }
}
