function mock_console() {
  if(!window.console) {
    window.console = new function() {
      this.log = function(str) {};
      this.dir = function(str) {};
    };
  }
}

function attach_superfish() {
  jQuery('ul.sf-menu').superfish();
}

//var pause = 3500;
// news ticker inspired by http://geschke.name/asap/article/38/newsticker-with-jquery-and-three-lines-of-code.html
function update_news_list() {
    var last = $('ul#news_list li:last').hide().remove();
    $('ul#news_list').prepend(last);
    $('ul#news_list li:first').slideDown("slow");
}

function bind_search_selectors() {
  $('.search_options li').click(function(){
    // console.log('click!')
    var selection = $(this).attr('option').split('-')[1];
    // console.log('selection is ' + selection)
    $('.search_options li').removeClass('active');
    $(this).addClass('active');
    $('.search_results').hide();
    $('#show-' + selection).show();
  })
}

function clear_search_box() {
  $(".clear_on_focus").focus(function() {
    if ($(this).val() == $(this).attr('defaultValue')) {
      $(this).val("");
    }
    $(this).addClass("text-focused");
  });

  $(".clear_on_focus").blur(function() {
    if ($(this).val() == "") {
      $(this).val($(this).attr('defaultValue'));
    }
    $(this).removeClass("text-focused");
  });
}

function show_initial_search() {
  if (!$('.project_browser').length) {
    return;
  }
  if (window.location.href.split('#')[1] === undefined) {
    // console.log("showing countries")
    $('#show-countries').show();
  }
  else {
    var loc = window.location.href.split('#')[1];
    // console.log('showing ' + loc)
    $('#show-' + loc).show();
  }
}

function alpha_selector() {
  $('#default').show()
  $('li.alpha_selector.multi-projects').click(function() {
    $('.selector_prompt').hide();
    $('.alpha_selector').removeClass('selected');
    $('.project_group').hide();
    $('#projects-' + $(this).attr('id')).show();
    $(this).addClass('selected');
  })
}

function image_selector() {
  $('#image_chooser').children().attr('id', $('this').value)
};

function ctag(tag_type, content, opts) {
  if (opts !== undefined && opts.klass != null) {
    var klass = (' class="' + opts.klass + '"');
  } else {
    var klass = '';
  };
  var str = ('<' + tag_type + klass + '>' + content + '</' + tag_type + '>');
  return str;
};

jQuery.preloadImages = function(){
  //Loop through the images
  for(var i = 0; i<arguments.length; i++){
    jQuery("<img>").attr("src", arguments[i]);
  }
}



function FormSelect(caller_id) {
  var self = this;

  self.div_id = caller_id;
  self.div_object = $('#' + caller_id);
  self.css_class = '.js_select';
  self.form_id = caller_id.split('-')[0];
  self.form_object = $('#' + self.form_id);
  self.all_options = self.div_object.data('options')
  self.expanded = false;

  // self.selected = JSON.parse(self.form_object.val());
  self.selected = self.div_object.data('selected') || [];


  self.write_expanded = function() {
    console.log('selected is ' + self.selected)
    // console.log("div is $('" + caller_id + "')")
    self.expanded = true
    self.div_object.removeClass('small')
    self.div_object.addClass('expanded')
    self.div_object.html('')
    self.write_close_button()
    // console.log(self.all_options)
    // console.log(typeof(self.all_options))
    self.div_object.append('<h4>Select from the below options</h4>')
    $.each(self.all_options, function() {
      var k = this.toString();
      var divid = ('js_select_item-' + k.replace(/[ |&|,|(|)]/gi, '_'));
      var str = ('<div class="select_item" id="' + divid + '">' + k + '</div>');
      self.div_object.append(str);

      if (self.item_in_selected(k)) {
        $('#' + divid).addClass('highlight');
      };
    })

    $('.select_item').click(function(e) {
      var val = $(this).html();
      //self.selected.push($(this).html())
      if (!self.item_in_selected(val)) {
        self.selected.push(val);
      } else {
        self.delete_item_from_selected(val);
      };
      
      self.write_expanded();
      return false;
    })
  }

  self.item_in_selected = function(item) {
    var res = false;
    for (var key in self.selected) {
      if (item == self.selected[key]) {
        res = true;
      };
    }
    return res;
  }

  self.delete_item_from_selected = function(item) {
    for (var key in self.selected) {
      if (item == self.selected[key]) {
       self.selected.splice(key, 1)
      };
    }
  }

  self.write_close_button = function() {
    self.div_object.append('<div class="close_selector" data-parent="' + self.div_id + '">save & close</div>');
    $('.close_selector').click(function() {
   //   self.write_small()
      parent = window.form_selectors[self.div_id];
      parent.write_small();
      return false;
    })
  };

  self.write_small = function(arr) {
    console.log('received write small');
    self.expanded = false;
    self.div_object.html('');
    
    self.div_object.addClass('small');
    self.div_object.removeClass('expanded');
    for (key in self.selected)
      self.div_object.append(ctag('div', self.selected[key], {klass: 'select_item'}));
    // console.log(self.selected)
    self.form_object.val(JSON.stringify(self.selected))
  }

  self.insert_choice = function(caller) {
    var id = caller.attr('id');
    console.log(id);
  };
  console.log('new formselect with ID ' + self.form_id + 'with self id ' + self.caller_id)

  self.make_clickable = function() {
    self.div_object.click(function() {
      if (self.expanded) {
        self.write_small()
      } else {
        console.log(self.expanded)
        self.write_expanded()
      };
      // console.log('changed self.expanded to ' + self.expanded)
    });
  }
  
  
  self.write_small()
  self.make_clickable()
}

function associate_js_select() {
  $(".js_select").each(function() { 
    if (!window.form_selectors) {window.form_selectors = {}};
    window.form_selectors[this.id] = (new FormSelect(this.id))
   })
}


function MediaSelect () {
  var self = this;

  self.css_class = '#media_selector';
  self.active_slot = null;

  self.jquery_object = $(self.css_class);

  self.toggle_me = function() {
    if (!self.jquery_object.is(":visible")) {
      self.jquery_object.show()
      } else {
      self.jquery_object.hide()
    };
  };


  self.insert_choice = function(caller) {
    var id = caller.attr('id');
    console.log(id);
    $('#input_slot_' + self.active_slot).val(id);
  };

  self.associate_links = function() {
    $(".show_media_selector").live('click', function() {
      self.active_slot = $(this).closest('.slide-edit').attr('id');
      self.jquery_object.toggle();
    });
    $(".select_picture").live('click', function(ev) {
      self.insert_choice($(this));
    });
  };
  self.associate_links();
}

function ShowProject() {
   $('li.project_line').click(function() {
     var project_id = $(this).attr("project_id");
     var project_div = $("#" + project_id);
     if (!project_div.is(":visible")) {
       project_div.show();
       } else {
       project_div.hide();
     };
     return false;
   })
}

jQuery(document).ready(function($) {
  ShowProject();
  mock_console();
  expand_links();
  attach_superfish();
  init_slideshow();
  show_initial_search();
  bind_search_selectors();
  clear_search_box();
  alpha_selector();
  ms = new MediaSelect();
  associate_js_select();
})
