/* -------------------------------------------------------------------------- */
/* Application Scripts */
/* -------------------------------------------------------------------------- */

var blocks = new Array(); // container for blocks
var paginator_page = 0;
var paginator_max = 1;
var paginator_working = 0;
var paginator_scroll_offset = 10;
var fetch_params = {};

/* -------------------------------------------------------------------------- */
/* Utils */
/* -------------------------------------------------------------------------- */

function go(url) { window.location = url; }
function redirect(url) { window.location = url; }
function redirect_to(path) { window.location = url; }


function iframe_get(iFrameName) {  
  var IFrame = document.getElementById(iFrameName);
  if (!IFrame.contentWindow.document.body) return '';
  var content = IFrame.contentWindow.document.body.innerHTML;       
  return content;
}

function iframe_clear(id) {
  var obj = document.getElementById(id);
  if (obj.contentWindow.document.body) {
    obj.contentWindow.document.body.innerHTML='';
  }
}

function cookie_delete(name) {
  try {
    if ($.cookie(name) != 'undefined') {
      $.cookie(name, null, {});
    }
  }
  catch(e) {}
}

/* -------------------------------------------------------------------------- */
/* Flash Messages */
/* -------------------------------------------------------------------------- */

/* add new flash message */
function flash_message(type, message) {
  d = new Date();
  uid = d.getTime() + '_' + d.getMilliseconds();
  str = "<div id='" + uid + "' class='item " + type + "' style='display:none;'>" + message + "</div>";
  $(str).appendTo('#flash_messages').fadeIn();
  setTimeout("$('#" + uid + "').fadeOut().remove();", 3000);
}

/* show successful flash message */
function flash_ok(message) { flash_message('ok', message); }

/* show error flash message */
function flash_error(message) { flash_message('fail', message); }

/* -------------------------------------------------------------------------- */
/* Pagination */
/* -------------------------------------------------------------------------- */

/* fetch companies */
function fetch_results() {
  if (paginator_page < paginator_max) {
    $.ajax({
      beforeSend: function() {
        $('#loading-overlay').show();
      },
      url: '/companies_fetch',
      data: ({
        category : fetch_params['category'],
        budget : fetch_params['budget'],
        city : fetch_params['city'],
        page : ++paginator_page,
        state : fetch_params['state']
      }),
      success: function(html) {
        $('#loading-overlay').hide();
        $('div.listings-grid').append(html);
      }
    });
  }
}

/* set maximum pagination value */
function paginator_set_max(value) {
  paginator_max = value;
}

/* -------------------------------------------------------------------------- */

$(document).ready(function() {
  if ($.cookie("free_trial_top")) {}
  else { setTimeout(function() { $("#promo_action").fadeIn(); }, 500); }
  
  // Click on header promotion
  $("#promo_close").click(function() {
    $.cookie("free_trial_top", "1", {expires: 365});
    $("#promo_action").hide().remove();
  });
  
  $("#fold_image_link").click(function() {
    $.cookie("fold_press", "1", {expires: 365});
  });
  
  
  $('#select_category').click(function() { dropdown('category'); });
  $('#select_city').click(function() { dropdown('city'); });
  $('#select_budget').click(function() { dropdown('budget'); });
  $('.suggest_city').autocomplete('/ajax/suggest_city', {delay: 100, minChars: 2, cacheLength: 10, width: 200});
  
  $('#fold_image_target').fold();
  
  // $(".company_image_medium").lazyload({placeholder: '/images/company-blank.jpg'});
  // $(".company_image_small").lazyload({placeholder: '/images/company-blank-small.jpg'});
  
  $('#cmd_share').click(function() {
    if (jQuery.trim($('#email_from').val()) == '') { flash_error("Please enter your name."); return; }
    if ($('#email_list').val() != '') {
      $('#cmd_share').hide();
      $('div.line-loading').show();
      $.post('/bookmarks/send_email', {name: $("#email_from").val(), emails: $('#email_list').val()}, function(resp) {
        $('#share_process').html('Emails have been sent!');
        flash_ok('Emails have been sent!');
      });
    }
      else { flash_error('Please enter at least one email to proceed!'); }
    });
  });

/* filter selector binding */
$(document).bind('click', function(e) {
  var clicked = $(e.target);  
  is_target = clicked.is('div.options') || clicked.is('a.dropdown');
  if (!is_target) dropdown(false);
});

/* filter dropdown function */
function dropdown(value) {
  if (value != false) {
    $('div.options:not(#options_' + value + ')').hide();
    $('#options_' + value).toggle();
  }
  else $('div.options').hide();
}

function delete_picture(id) {
  $.get('/account/delete_picture/' + id, {}, function(resp) {
    if (resp && resp.result == 1) {
      $('#image' + id).fadeOut();
      setTimeout("$('#image" + id + "').remove()", 1000);
    }
  }, 'json');
}

function set_picture_desc(id) {
    params = {description: $('#desc' + id).val(), primary: 0};
    $.get('/account/update_picture/' + id, params, function(resp) {
        if (resp && resp.result == 1) {
            alert('+');
        }
    }, 'json');
}

function set_picture(id) {
    $.get('/account/set_picture', {id: id}, function(resp) {
        if (resp && resp.result == 1) {
            // todo
        }
    }, 'json');
}

/* -------------------------------------------------------------------------- */
/* Image Slider */
/* -------------------------------------------------------------------------- */

function slider_change(id, src) {
    obj = $('#company_image_' + id);
    if (obj.attr('src') != src) {
        $(obj).attr('src', src);
    }
}

function slider_next(id) {
    num = blocks[id]['num']; if (num == 1) return;
    current = parseInt(blocks[id]['current']); 
    current += 1; if (current >= num) current = 0;
    blocks[id]['current'] = current;
    
    $('#slideitems' + id + ' a').removeClass('selected');
    $('#pic' + id + '_' + current).addClass('selected');

    slider_change(id, blocks[id]['images'][current]);
}

function slider_prev(id) {
    num = blocks[id]['num']; if (num == 1) return;
    current = parseInt(blocks[id]['current']);
    current -= 1; if (current < 0) current = num - 1;
    blocks[id]['current'] = current;
    
    $('#slideitems' + id + ' a').removeClass('selected');
    $('#pic' + id + '_' + current).addClass('selected');

    slider_change(id, blocks[id]['images'][current]);
}

function slider_set(id, offset) {
    blocks[id]['current'] = offset;

    $('#slideitems' + id + ' a').removeClass('selected');
    $('#pic' + id + '_' + offset).addClass('selected');

    slider_change(id, blocks[id]['images'][offset]);
}

/* -------------------------------------------------------------------------- */
/* Bookmarks */
/* -------------------------------------------------------------------------- */

function bookmark_add(company_id) {
  $.get('/bookmarks/add', {company: company_id}, function(resp) {
    if (resp && resp.result == true) {
      flash_ok('You have added company "' + $('#company_title_' + company_id).html() + '" to your bookmarks!');
      if ($('#bookmark' + company_id).length > 0) {
        $('#bookmark' + company_id).addClass('bookmark-selected');
      }
      $('#bookmarks_num').html(resp.num);
    }
    else {
      flash_error(resp.error);
    }
  }, 'json');
}

function bookmark_remove(company_id) {
  $.get('/bookmarks/delete', {company: company_id}, function(resp) {
    if (resp && resp.result == true) {
      flash_ok('You have removed company "' + $('#company_title_' + company_id).html() + '" from your bookmarks.');
      $('#bookmarks_num').html(resp.num);
      if ($('#bookmark' + company_id).length > 0) {
        $('#bookmark' + company_id).removeClass('bookmark-selected');
      }
    }
    else {
      flash_error(resp.error);
    }
  }, 'json');
}

/* -------------------------------------------------------------------------- */
/* Portfolio pictures */
/* -------------------------------------------------------------------------- */

function portfolio_delete_image(image_id, form_id) {
  $('#loading' + form_id).show();
  $.get('/settings/image_delete', {id: image_id}, function(resp) {
    $('#loading' + form_id).hide();
    $('#result' + form_id).hide();
    $('#form' + form_id).show();
  }, 'json');
}

function portfolio_upload_start(form_id) {
  $('#loading' + form_id).show();
  $('#form' + form_id).hide();
  $('#upload_form' + form_id).submit();
  portfolio_upload_wait(form_id);
}

function portfolio_upload_wait(form_id) {
  content = iframe_get("upload" + form_id);
  if (!content) {
    setTimeout("portfolio_upload_wait('" + form_id + "');", 200);
    return;
  }
  else iframe_clear("upload" + form_id);

  obj = eval('(' + content + ')');
  if (obj.result == 1) {
    $('#result' + form_id + ' > img').attr('src', obj.image);
    $('#result' + form_id).show();
    $('#loading' + form_id).hide();
    $('#input' + form_id).val('');

    $('#result' + form_id + ' > div.delete').click(function() {portfolio_delete_image(obj.image_id, form_id);});
  }
  else {
    flash_error('Cannot process your file!');
    $('#loading' + form_id).hide();
    $('#result' + form_id).hide();
    $('#form' + form_id).show();
  }
}

/* -------------------------------------------------------------------------- */
/* Controllers */
/* -------------------------------------------------------------------------- */

var CompaniesController = new function() {
  this.Index = function() {
    var has_scrolled = false;
    var offset  = $('div.topline').offset();
    var offset_y = parseInt(offset.top);
    var bar_height = $('div.topline').height();
    var grid_pos = parseInt($('div.listings-grid').offset().top);
    var diff = grid_pos-offset_y;
    
    
    window.scrollTo(0,0);
    $('div.listings-grid').css('margin-top', bar_height+50);
        
    $(window).scroll(function(event) {
      var scroll_y = $(this).scrollTop();
      var top_is_fixed = $('div.topline').hasClass('topline-fixed');

      if (scroll_y <= offset_y) {
        if (top_is_fixed) {
          $('div.topline').removeClass('topline-fixed');
          $('div.listings-grid').attr('style', 'margin-bottom: 50px; margin-top: ' + parseInt(bar_height + 50) + 'px;');
        }
      }
      else {
        if (!top_is_fixed) {
          $('div.topline').addClass('topline-fixed');
        }
      }
      
      if (!has_scrolled) paginator_scroll_offset = 50;
      else {
      }
      
      if (!paginator_working) {
        if ($(this).scrollTop() >= ($(document).height() - $(this).height()-paginator_scroll_offset)) {
          fetch_results();
          if (!has_scrolled && paginator_max > 1) {
            $('div.topline').addClass('topline-fixed');
            $('div.footer').attr('style', 'position: fixed; width: 100%; bottom: 0px; z-index: 999;');
            $('div.listings-grid').attr('style', 'margin-bottom: 50px; margin-top: 100px;');
            has_scrolled = true;
          }
        }
      }
    });
  }
}

/* -------------------------------------------------------------------------- */
/* Analytics Controller */
/* -------------------------------------------------------------------------- */
/*
var SettingsController = new function() {
  this.Analytics = function() {
    $('#report_range').change(function() {
      
    });
    
    var so = new SWFObject("/flash/amcharts/amline.swf", "amline", "780", "300", "8", "#F9F9F9");
    so.addVariable("path", "/flash/amcharts/");
    so.addVariable("settings_file", encodeURIComponent("/charts/profile_traffic.xml?123123"));
    so.addVariable("data_file", encodeURIComponent("/analytics/testdata"));
    so.write("chart_views");
  
    var so2 = new SWFObject("/flash/amcharts/ampie.swf", "ampie", "780", "300", "8", "#F9F9F9");
    so2.addVariable("path", "/flash/amcharts/");
    so2.addVariable("settings_file", encodeURIComponent("/charts/profile_traffic_summary.xml"));
    //so2.addVariable("data_file", encodeURIComponent("/charts/traffic_sources.txt"));
    so2.addVariable("data_file", encodeURIComponent("/companies/1/stats"));
    so2.write("chart_traffic_summary");
  }
}
*/
