var FBI_hold_chart = [0,0];
var available_div = 1;
var reload_both = 0;
var FBI_feed_filter = "all";
var FBI_feed_source = "all";
var FBI_dataload_url = "chart/loadbrands/";
var FBI_chartload_url = "chart/show/";
var FBI_messageload_url = "chart/loadmessages/";
var FBI_search_url = "chart/search/";
var FBI_brandinfo_url = "chart/brandinfo/";
var FBI_websitesload_url = "chart/brandwebsites/";
var FBI_brandsuperstar_url = "chart/brandsuperstar/";

/**
 * checkRequestVars - check if FBI request vars(global vars, that are used in most functions) are defined
 *
 * @return boolean
 */
checkRequestVars = function()
{
  if(typeof(FBI_brandtype_id) == "undefined") return false;
  
  if(typeof(FBI_source_type) == "undefined") return false;

  if(typeof(FBI_selected_month) == "undefined") return false;

  if(typeof(FBI_index_type) == "undefined")
    FBI_index_type = "platinum";

  return true;
}

/**
 * reloadBrandIndex - it's a main function that reload all page's content according to selected values(FBI variables)
 *                  so, it doesn't reload brand index only, it also reloads feeds, brandsuperstar content and highlights(updates) menu/links respectively
 *
 * @param   brandtype_id
 * @param   source_type facebook, twitter
 * @param   selected_month
 * @param   index_type platinum, gold, silver, bronze
 *
 * @return boolean
 */
reloadBrandIndex = function(brandtype_id, source_type, selected_month, index_type)
{
  if(brandtype_id) FBI_brandtype_id = brandtype_id;
  if(source_type) FBI_source_type = source_type;
  if(selected_month) FBI_selected_month = selected_month;
  if(index_type) FBI_index_type = index_type;

  $("#stFashionIndex .tblContainer .loading").show();
  $("#stFashionIndex .tblContainer thead").html('<tr style="display:none;"><th></th><th></th><th></th><th></th><th></th></tr>');
  $("#stFashionIndex .tblContainer tbody").html('');
  
  //reload header index
  $("#stHeader .header_menu li").removeClass("active");
  $("#menusourcetype_"+FBI_source_type).addClass("active");

  //reload main menu
  $("#main_menu li").removeClass("active");
  $("#menubrandtype_"+FBI_brandtype_id).addClass("active");

  //selectbox
  $("select[name=selSource] option").removeAttr('selected');
  $("select[name=selSource] option").each(function(i){
    if($(this).val() == FBI_source_type)
      $(this).attr('selected',true);
  });

  //reload tabs
  $("#stFashionIndex .tabs li").removeClass("active");
  $("#stFashionIndex .tabs li."+FBI_index_type).addClass("active");
  $("#stFashionIndex .tabs li").show();
  $("#stFashionIndex .tabs li.websites").hide();

  //index_info
  $("#index_content .header .index_info p").show();
  $("#index_content .header .index_info p.index_websites").hide();
  //index_content
  $("#index_content").attr("class","");
  $("#index_content").addClass(FBI_index_type);
  $("#index_content .header p.index_type").html(getIndexTypeText(FBI_index_type));
  $("#index_content .header .ico_sourcetype").attr("src","images/index_"+FBI_source_type+".gif");
  brandtype_name = $("#main_menu li.active a span").html();
  $("#index_content .header .index_brandtype").html(brandtype_name);
  $("#index_content .header").show();

  //reload index content
  $.get(FBI_dataload_url+FBI_brandtype_id+"/"+FBI_source_type+"/"+FBI_index_type+"/"+FBI_selected_month,null,
    function(data)
    {
      $("#stFashionIndex .tblContainer .loading").hide();
      
      if(data.all_brands != "0")
      {
        start_index = 1;
        if(FBI_index_type == 'platinum')
        {
          tpl_all_brands = '<tr><td align="center" class="numField">1</td>'+
                            '<td id="fpg_all" class="link"><img onclick="loadChart(\'all\',\'All '+brandtype_name+' Brands\');" src="images/button_chart.jpg" alt="" /></td>'+
                            '<td>All Brands</td><td id="numfans_all" align="right">'+data.all_brands+'</td><td>&nbsp;</td></tr>';
          $("#stFashionIndex .tblContainer thead").html(tpl_all_brands);
          start_index = 2;
        }

        tpl = getIndexDOMRows(data.brand_index, start_index);
      }
      else
      {
        tpl = '<tr><td colspan="5" align="center"><b>No Brands</b></td></tr>';
      }

      $("#stFashionIndex .tblContainer tbody").html(tpl);

      //need for tablesorter
      $(".tblContainer table").trigger("update");
    }, "json");

  // refresh fashion feeds according to selected values
  loadFashionFeeds(FBI_source_type, null, FBI_brandtype_id);
  // load brand superstar content for selected brandtype
  loadBrandSuperstar(FBI_brandtype_id);

  return true;
}

/**
 * getIndexDOMRows - make table rows from the data array returned from the ajax request (json)
 *
 * @param   idx_arr data array
 * @param   start_index starting index (for the platinum index starts from 2 - All Brands at the first line)
 *
 * @return  string
 */
getIndexDOMRows = function(idx_arr, start_index)
{
  tpl = '';
  for ( var i in idx_arr )
  {
    bname = idx_arr[i].name.replace("\'","\\'");
//    burl = idx_arr[i].website_url;
    burl = idx_arr[i].index_url;
    if(burl.indexOf("http") == -1)
      burl = "http://"+burl;

    tpl += '<tr class="'+((i % 2 == 0)?'odd':'')+'">'+
           '<td align="center" class="numField">'+(parseInt(i)+start_index)+'</td>'+
           '<td class="link" id="fpg_'+idx_arr[i].fpid+'"><img src="images/button_chart.jpg" alt="" onclick="loadChart('+idx_arr[i].fpid+',\''+bname+'\','+idx_arr[i].id+');" /></td>'+
           '<td>'+
           '<a id="fp_'+idx_arr[i].fpid+'" href="'+burl+'" target="_blank">'+idx_arr[i].name+'</a>'+
           '</td>'+
           '<td align="right" id="numfans_'+idx_arr[i].fpid+'">'+idx_arr[i].cur_month_fans+'</td>'+
           '<td>'+idx_arr[i].sort_change+'</td>'+
           '</tr>';
  }

  return tpl;
}

/**
 * getIndexTypeText - make a index type description string
 *
 * @param   index_type platinum, gold, silver, bronze
 *
 * @return  string
 */
getIndexTypeText = function(index_type)
{
  var fname = 'fans';
  if(FBI_source_type == 'twitter')
    fname = 'followers';
  switch(index_type)
  {
    case "platinum":return "Platinum : 100,000 and more "+fname;
    case "gold":return "Gold : 10,000 - 100,000 "+fname;
    case "silver":return "Silver : 1,000 - 10,000 "+fname;
    case "bronze":return "Bronze : 10 - 1,000 "+fname;
      default:return "Platinum : 100,000 and more "+fname;
  }
}

/**
 * getAvailableDiv - return available div id to load a chart
 *
 * @return  int
 */
getAvailableDiv = function()
{
  if(FBI_hold_chart[0] && FBI_hold_chart[1])
    return 1;

  if(available_div>2)
    available_div = 1;

  if(!FBI_hold_chart[available_div-1])
    return available_div;
  else
  {
    available_div = available_div + 1;
    return getAvailableDiv();
  }
}

/**
 * fillChartDiv - fill the div container with chart's data and generated chart image
 *
 * @param   page_id     fanpage_id
 * @param   ad          available div number (1 or 2)
 * @param   title       chart's title
 * @param   content     image tag
 *
 * @return  boolean
 */
fillChartDiv = function(page_id, ad, title, content)
{
  if(FBI_hold_chart[0] && FBI_hold_chart[1])
  {
    alert("Please, unhold one of the charts.");
    return false;
  }

  if(title.length>20)
    title = title.substring(0,17)+"...";
  $("#dChart"+ad+" .title").html(title);
  $("#dChart"+ad+" .content").html(content);
  $("#dChart"+ad+" .holdCahrt").show();
  if(!reloadflag)
  {
    available_div = available_div + 1;
    $("#dChart"+ad+" .content").attr("id","chcontent_"+page_id);
  }

  return true;
}

/**
 * loadChart - load brand's chart (also show its info if it is not 'All Brands' record)
 *
 * @param   page_id     fanpage_id
 * @param   brand_name  
 * @param   brand_id    
 *
 * @return  boolean
 */
loadChart = function(page_id, brand_name, brand_id)
{
  var ad = getAvailableDiv();

  if(page_id == "all")
    req_url = page_id+"/"+FBI_brandtype_id+"/"+FBI_source_type+"/"+FBI_index_type;
  else
    req_url = page_id;
  $.ajax({
    url: FBI_chartload_url+req_url,
    success: function(html){
      fillChartDiv(page_id, ad, brand_name, html);
    }
  });

  if(brand_id)
    showBrandInfo(brand_id);

  return true;
}

/**
 * toggleBrandChartInfo - display brand's messages, hide charts and vice-versa
 *
 * @param     visible_item classname for the container to show
 *
 * @return    
 */
toggleBrandChartInfo = function(visible_item)
{
  var brand_data_class = "brand_index_data";
  var brand_chart_class = "charts";

  $(".brand_profile ."+brand_data_class).hide();
  $(".brand_profile ."+brand_chart_class).hide();

  if(visible_item != brand_data_class && visible_item != brand_chart_class)
    visible_item = brand_data_class;

  // toggle links
  $(".brand_profile .header span.link").removeClass("blue");
  $(".brand_profile .header span.lnk_"+visible_item).addClass("blue");

  $(".brand_profile ."+visible_item).show();
}

/**
 * loadFashionFeeds - display feeds according to selected values
 *
 * @param     source_type facebook/twitter
 * @param     feed_filter "All Posts","%","Contest","Coupon","Discount","Event","Giveway","New arrival","Promotion","Sale","Win","All of the above"
 * @param     brand_type id
 *
 * @return    
 */
loadFashionFeeds = function(source_type, feed_filter, brand_type)
{
  fpid = 0; // to retrieve messages only by source and filter

  if(source_type)
    FBI_feed_source = source_type;

  if(feed_filter)
    FBI_feed_filter = feed_filter;

  if(brand_type == null)
    brand_type = FBI_brandtype_id;

  //reload feeds menu
  $("#fashion_feeds .feeds_menu a").removeClass("active");
  $("#feedmenu_"+FBI_brandtype_id+" a").addClass("active");

  $('#fashion_feeds .links span').removeClass('blue');
  $('#fashion_feeds .links span.'+FBI_feed_source).addClass('blue');
  $('#fashion_feeds .content').hide();
  $('#fashion_feeds .loading').show();
  $('#fashion_feeds .greyA7').html("");

  $.get(FBI_messageload_url+fpid+"/"+FBI_feed_source+"/"+FBI_feed_filter+"/"+brand_type, null,
    function(data)
    {
      tpl = '';
      for ( var i in data )
        tpl += '<div class="message">'+
                '<p class="greyA7">'+data[i].created_at+'</p>'+
                '<a href="'+data[i].url+'" class="greylink" target="_blank">'+data[i].name+'</a>: '+data[i].message+
                '</div>';

      $('#fashion_feeds .content').html(tpl);
      $('#fashion_feeds .loading').hide();
      $('#fashion_feeds .content').show();
      if(tpl == "")
        $('#fashion_feeds .greyA7').html("N/A");
    }
  ,"json");
}

/**
 * searchHelper - display search helper list
 *
 * @param     search_value
 *
 * @return    
 */
searchHelper = function(search_value)
{
  $.get(FBI_search_url+search_value,null,
    function(data)
    {
      tpl = '';
      for ( var i in data )
        tpl += '<a href="javascript:void(0);" onclick="showBrandInfo('+data[i].id+',\''+data[i].name+'\');">'+data[i].name+'</a>';

      if(tpl == '')
        $('#stSearchHelper').hide();
      else
      {
        $('#stSearchHelper').html(tpl);
        $('#stSearchHelper').show();
      }
    }
  ,"json");
}

/**
 * searchBrand - get the brand by name
 *
 * @param     search_value
 *
 * @return
 */
searchBrand = function(search_value)
{
  $.get(FBI_search_url+search_value+"/find",null,
    function(data)
    {
      updateProfileContainer(data);
    }
  ,"json");
}

/**
 * showBrandInfo - get brands info and updateProfileContainer
 *
 * @param     id
 * @param     brand_name
 *
 * @return
 */
showBrandInfo = function(id, brand_name)
{
  if(brand_name) $('#inpt_search').val(brand_name);

  $.get(FBI_brandinfo_url+id,null,
    function(data)
    {
      updateProfileContainer(data);
      toggleBrandChartInfo();
    }
  ,"json");
}

/**
 * updateProfileContainer - fill DOM elements with data ajax-reques (json) data
 *                          also show brand NOT found (search action)
 *
 * @param     data array - brand's info
 *
 * @return
 */
updateProfileContainer = function(data)
{
  if(typeof(data.id) == "undefined")
  {
    $('.brand_messages').hide();
    $('.brand_info').hide();
    $('#brand_not_found').show();
    
    return;
  }

  $('#stSearchHelper').hide();
  $('#brand_profile_name').html(data.name);

  $('.brand_info .website_url a').html("");
  $('.brand_info .website_url a').attr('href',"#");
  $('.brand_info .website_url span.greyA7').html("N/A");
  
  if(data.website_url != "")
  {
    burl = data.website_url;
    if(burl.indexOf("http") == -1)
      burl = "http://"+burl;
    $('.brand_info .website_url span.greyA7').html("");
    $('.brand_info .website_url a').html(data.website_url);
    $('.brand_info .website_url a').attr('href',burl);
  }

  $('#brand_profile_chartico').html('<img src="images/brand_profile_icon.gif" alt="" align="absmiddle" onclick="loadChart('+data.pages['facebook'].fpid+',\''+data.name+'\');" />');
  for ( var i in data.pages )
  {
    $('#profile_messages_'+i+' .greyA7').html("N/A");
    $('#profile_messages_'+i+' .content').html("");
    //load brand messages
    if(data.pages[i].fpid > 0)
      loadBrandMessages(data.pages[i].fpid, i);
    //url
    if(data.pages[i].url !="")
    {
      $('.brand_info .'+i+'_url').attr('target',"_blank");
      $('.brand_info .'+i+'_url').attr('href',data.pages[i].url);
    }
    else
    {
      $('.brand_info .'+i+'_url').attr('href',"javascript:void(0);");
      $('.brand_info .'+i+'_url').attr('onclick',"showPopup('No twitter account for this brand.');");
      $('.brand_info .'+i+'_url').removeAttr('target');
    }
    //numfans
    $('.brand_info .'+i+'_fans').removeClass('greyA7');
    if(data.pages[i].numfans == 0 || data.pages[i].numfans == -1)
    {
      $('.brand_info .'+i+'_fans').html("N/A");
      $('.brand_info .'+i+'_fans').addClass('greyA7');
    }
    else
      $('.brand_info .'+i+'_fans').html(data.pages[i].numfans);
    //index_type
    $('.brand_info .'+i+'_index_type').html('');
    if(data.pages[i].index_type !="")
      $('.brand_info .'+i+'_index_type').html("("+data.pages[i].index_type+")");
  }//page_type

  $('#brand_not_found').hide();
  $('.brand_messages').show();
  $('.brand_info').show();

}

/**
 * loadBrandMessages - load brand's facebook/twitter messages
 * 
 * @param     fanpage_id 
 * @param     source_type facebook/twitter
 *
 * @return    boolean
 */
loadBrandMessages = function(fanpage_id, source_type)
{
  $('.brand_messages .content').hide();
  $('.brand_messages .loading').show();
  $.get(FBI_messageload_url+fanpage_id,null,
    function(data)
    {
      $('#profile_messages_'+source_type+' .greyA7').html("N/A");
      $('#profile_messages_'+source_type+' .content').html("");
      tpl = '';
      for ( var i in data )
        tpl += '<div class="message"><p class="greyA7">'+data[i].created_at+'</p>'+data[i].message+'</div>';

      if(tpl != '')
      {
        $('#profile_messages_'+source_type+' .greyA7').html("");
        $('#profile_messages_'+source_type+' .content').html(tpl);
      }
      else
        if(source_type == 'facebook')
          $('#profile_messages_'+source_type+' .content').html('<p class="greyA7" style="text-align:center; padding-top: 8px;">There are no \'published\' facebook status updates.</p>');

      $('.brand_messages .loading').hide();
      $('.brand_messages .content').show();
    }
  ,"json");

  return true;
}

/**
 * showWebsites - show websites in brand index list
 *
 * @return    boolean
 */
showWebsites = function()
{
  $("#stFashionIndex .tblContainer .loading").show();
  //tabs
  $("#stFashionIndex .tabs li").hide();
  $("#stFashionIndex .tabs li.websites").addClass("active");
  $("#stFashionIndex .tabs li.websites").show();

  $("#index_content .header .index_info p").hide();
  $("#index_content .header .index_info p.index_websites").show();
  $("#index_content").attr("class","");
  $("#index_content").addClass("platinum");
  $("#stFashionIndex .header .index_websites").show();
  $("#stFashionIndex .header .ico_sourcetype").attr("src","images/index_websites.gif");
  $("#stFashionIndex .tblContainer thead").html('<tr style="display:none;"><th></th><th></th><th></th><th></th><th></th></tr>');
  $("#stFashionIndex .tblContainer tbody").html('');

  //reload index content
  $.get(FBI_websitesload_url+FBI_brandtype_id,null,
    function(data)
    {
      $("#stFashionIndex .tblContainer .loading").hide();

        tpl = '';
        for ( var i in data.brand_index )
        {
          burl = data.brand_index[i].website_url;
          if(burl.indexOf("http") == -1) burl = "http://"+burl;

          tpl += '<tr class="'+((i % 2 == 0)?'odd':'')+'">'+
                 '<td align="center" class="numField">'+(parseInt(i)+1)+'</td>'+
                 '<td>&nbsp;</td>'+
                 '<td>'+
                 '<a href="'+burl+'" target="_blank">'+data.brand_index[i].name+'</a>'+
                 '</td>'+
                 '<td align="center"><span class="greyA7">N/A</span></td>'+
                 '<td align="center"><span class="greyA7">N/A</span></td>'+
                 '</tr>';
        }

      $("#stFashionIndex .tblContainer tbody").html(tpl);
      $(".tblContainer table").trigger("update");
    }, "json");

    return true;
}

/**
 * loadBrandSuperstar - show websites in brand index list
 *
 * @param     brand_type id
 *
 * @return    boolean
 */
loadBrandSuperstar = function(brand_type)
{
    $.get(FBI_brandsuperstar_url+brand_type,null,
      function(data)
      {
        $('.content_bottom .brand_superstar').remove();
        $('.content_bottom .brand_text').remove();
        $(data).appendTo('.content_bottom');
      }
    );

    return true;
}

/**
 * showHelpPopup - show help information
 *
 * @return    boolean
 */
showHelpPopup = function()
{
  $('#stHelpPopup').css("top",160);
  $('#stHelpPopup').css("left",parseInt($(window).width()/2) - 240);
  if($('#stHelpPopup').css("display") == "none")
    $('#stHelpPopup').show();
  else
    $('#stHelpPopup').hide();

  return true;
}

/**
 * showPopup - show popup div (used to show short message)
 *
 * @param     msg message to show in popup
 *
 * @return    boolean
 */
showPopup = function(msg)
{
  $('#stMsgPopup .content').html(msg);
  $('#stMsgPopup').css("top",parseInt($(window).height()/2) - 50);
  $('#stMsgPopup').css("left",parseInt($(window).width()/2) - 120);
  $('#stMsgPopup').show();

  return true;
}

/* ---- onevent functions (bind in document.ready section - index page) ---- */
/**
 * outsideSortingHeader - outside 'tablesorter' onclick event handler to sort items in 'tablesorter' element (brand index)
 *
 */
outsideSortingHeader = function()
{
  var sortid = getSplitId($(this).attr("id"));
  if(sortid>1)
  {
      var curclass = $(this).attr("class");
      $(".tblHeader td").each(function(i){
        if(i>1)
          $(this).attr("class","hdr");
      });

      changeto = "headerSortUp";
      sort_direct = 0;

      if(curclass == "headerSortUp")
      {
        changeto = "headerSortDown";
        sort_direct = 1;
      }
      $(this).attr("class",changeto);

      var sorting = [[sortid,sort_direct]];
      $(".tblContainer table").trigger("sorton",[sorting]);
  }
  return false;
}

/**
 * holdChart - onclick evene handler to hold chart 
 *
 */
holdChart = function()
{
  id = getSplitId($(this).attr('id')) - 1;
  if(FBI_hold_chart[id])
  {
    FBI_hold_chart[id] = 0;
    $("img",this).attr("src","images/chart_hold.gif");
  }
  else
  {
    FBI_hold_chart[id] = 1;
    $("img",this).attr("src","images/pin_in.gif");
  }
}

/* ---- other ---- */
/**
 * getSplitId - get id from string like 'content_{id}'
 *
 * @param   str
 * @return  string
 */
function getSplitId(str)
{
  if(!str)
    return 0;

  arr = str.split("_");
  if(arr.length>1)
    return arr[1];
  else
    return 0;
}