//CREATED 9/24/10

/**
  <p>A way to find a classname by supplying a prefix piece of a classname.
  This is used as a simple way to both have a selector and a meta string to the selector</p>

  @author <a href="dilltree.com">Jeremy Dill</a>
  @param {Object} obj The html dom object or jquery object that has class applied
  @param {String} cl The class begins with this.. example to find "lnk_test", set this param to "lnk_"
  @param {Bool} rip If true, remove the cl piece of the classname and return the remainder
*/
(function($){
$.es = $.es || {};

// AS A FUNCTION
$.findClass = function (obj,cl,rip) {
	var jobj=$(obj);
	if(!jobj.attr('class')) return "";
	var list=jobj.attr('class').split(" ");
	for(i = 0; i < list.length; i++){
 		if(list[i].indexOf(cl) >= 0) {
			if (rip) return list[i].substr(cl.length);
			else  return list[i];
		}
	};
	return "";
};

$.es = {
  Timer : function() {
    this.delay = 3000;
    this.timerId = null;
    this.running = false;
    this.tick = null;
    this.start = function() {
      if (this.running) this.stop();
      if (this.tick) this.timerId = setTimeout(this.tick, this.delay);
      this.running = true;
    }
    this.stop = function() {
      if(this.timerId) clearTimeout(this.timerId);
      this.running = false;
    }
  },

  vidRegex : /(?:\.mp4|\.mov|\.ogg|\.mkv|\.flv|\.swf|\.f4v)$/i,

  isVideo : function(url) {
    return this.vidRegex.test($.trim(url));
  }
}

$.es.setEqualHeight = function(columns, padding) {
    if (padding == undefined) padding = 30;
    var tallestcolumn = 0;
    columns.each( function() {
      currentHeight = $(this).height();
      if(currentHeight > tallestcolumn){
          tallestcolumn  = currentHeight;
      }
    }
  );

  columns.height(tallestcolumn + padding);
}

/* Home Billboard */
$.es.hb = function(slides, settings) {
  opts = $.extend({
    'nav':false,
    'random_start':false,
    'start_on':false
  }, settings);

  var self = this;
  self.activeId = -1;
  self.timerDisabled = false;

  self.navClick = function(e) {
    var clicked = parseInt(this.id.substring(4));
    if (clicked == self.activeId) return;

    self.timer.stop();
    self.getSlide({"id":clicked});
  }

  self.getSlide = function(e) {
    if (opts.nav) self.nav.find('a.active').removeClass('active').find('#nav_'+e.id).addClass('active');

    //Stop player
    if (typeof(swfobject) != 'undefined') if (self.swf && typeof(self.swf.sendEvent) == 'function') self.swf.sendEvent('stop');

    if (!$.es.isVideo(slides[e.id].src)) {
      // IS IMAGE
      if(!self.imgs[e.id]) {
        self.loader.load(slides[e.id].src, e.id);
      } else {
        self.showSlide(self.imgs[e.id]);
      }
    } else {
      // IS VIDEO
      if (typeof(swfobject) != 'undefined') {
        if(self.vids[e.id]) { $(self.vids[e.id]).remove(); }
        var id = 'video_'+e.id;
        self.vids[e.id] = $('<div id="vid_'+ e.id +'"><div id="'+id+'" width="940" height="400"></div></div>')[0];
        self.wrap.append(self.vids[e.id]);

        var attr = { data:"/_swf/player.swf", height:"400", width:"940", id:id, name:id };
        var par = { menu:false, wmode:'transparent', allowfullscreen:false, allowscriptaccess:'always', flashvars:"file="+slides[clicked].src+"&controlbar=none&autostart=true" };
        self.swf = swfobject.createSWF(attr, par, id);
        self.activeId = e.id;
      }
    }

    if (e.tick) {
      self.timer.delay = (slides[e.id].time > 0) ? slides[e.id].time * 1000 : 5000;
      self.timer.start();
    } else {
      self.timer.stop();
    }
  }

  self.showSlide = function(obj) {
    var visible = self.wrap.find('div:visible').not(obj);
    var clicked = $(obj);

    if (visible.index() > clicked.index()) {
      clicked.stop(1,1).show().animate({opacity:1},10,function() {
        visible.stop(1).animate({opacity:0},'medium',function() { $(this).hide(); });
      });
    } else {
      clicked.stop(1,1).show().animate({opacity:1},'medium',function() {
        visible.stop(1).animate({opacity:0},10,function() { $(this).hide(); });
      });
    }
    self.activeId = obj.id.substring(4);
    if (slides[self.activeId].url) clicked.css('cursor','pointer');
  }

  self.loader = new function() {
    this.timer = new $.es.Timer();
    this.timer.delay = 200;
    this.timer.tick = function() {
      self.loaderImg.show();
    }
    this.load = function(url,id) {
      var img = new Image();
      img.onload = function() {
        self.loader.stop();
        // this.useMap = "#map_"+(id+1); //img map
        self.imgs[id] = $('<div id="img_'+id+'">').hide().css('opacity',0).append($(this))[0];
        self.wrap.append(self.imgs[id]);
        self.showSlide(self.imgs[id]);
      }
      img.onerror = function() {
        self.loader.stop();
        self.activeId = id;
        self.wrap.find('div:visible').animate({opacity:0},'medium',function() { $(this).hide(); });
      }
      this.timer.start();
      img.src = url;
    }
    this.stop = function() {
      self.loader.timer.stop();
      self.loaderImg.hide();
    }
  }

  self.getNextSlide = function() {
    if (self.activeId < slides.length - 1) var next = (parseInt(self.activeId)+1);
    else var next = 0;
    self.getSlide({'id':next,'tick':1});
  }

  self.getPrevSlide = function() {
    if (self.activeId > 0) var prev = (parseInt(self.activeId)-1);
    else var prev = (slides.length-1);
    self.getSlide({'id':prev});
  }

  self.setTimer = function() {
    self.timer = new $.es.Timer();
    self.timer.tick = function() {
      self.getNextSlide();
      self.timer.stop();
      self.timer.start();
    }
  }

  self.init = function() {
    if (opts.nav) {
      var navHtml = '<ul>';
      for (var x in slides) {
        navHtml += '<li><a id="nav_'+ x +'"> '+ (parseInt(x)+1) +' </a></li>';
      }
      navHtml += '</ul>';
    }

    self.imgs = [];
    self.vids = [];
    self.wrap = $('#stage_wrap').click(function() {
      if (slides[self.activeId].url) {
        window.location = slides[self.activeId].url;
      }
    });
    self.loaderImg = $('#loader');

    if (opts.nav) {
      self.nav = $(opts.nav).html(navHtml).find('ul li a').click(this.navClick).end();
    }

    $('.bb_arrow').fadeIn();
    $('.bb_left').click(function() {
      self.timerDisabled = true;
      self.getPrevSlide();
    });
    $('.bb_right').click(function() {
      self.timerDisabled = true;
      self.getNextSlide();
    });
    
    var startInt = 0;
    if (opts.random_start) {
      startInt = Math.floor(Math.random() * slides.length)
    }
    if (opts.start_on) {
      startInt = opts.start_on;
    }

    self.setTimer();
    self.getSlide({'id':startInt,'tick':1});
  }

  self.init();
}


/* Resource Toggle */
$.es.toggle = function(options) {
  obj = $.extend({
    'nav':null,
    'panes':null,
    'time':null,
    'start':0
  }, options);

  if (!obj.panes) return false;
  var active = obj.start;
  var panes = $(obj.panes);
  panes.not(panes[active]).hide().css('opacity',0);
  var timer = null;

  var showPane = function(x) {
    $(x).stop(1).show().animate({'opacity':1},'medium');
    panes.not(x).stop(1).animate({'opacity':0},'medium',function() { $(this).hide(); });
  }

  var showNext = function() {
    if (timer) timer.start();
    if (active < panes.length-1) { showPane(panes[++active]); }
    else { active=0; showPane(panes[active]); }
  }

  // setup timer
  if (obj.time) {
    timer = new $.es.Timer();
    if (obj.time > 0) timer.delay = obj.time * 1000;
    else timer.delay = 5000;
    timer.tick = showNext;
  }

  // setup nav
  if (obj.nav) {
    var nav = $(obj.nav);
    $(nav[active]).addClass('active');

    nav.click(function(x) {
      if (timer) { timer.stop(); timer = null; }
      var clicked = $(x.target);
      var id = clicked.index();
      nav.removeClass('active');
      clicked.addClass('active');
      showPane(panes[id]);
      active = id;
      return false;
    });
  }

  if (timer) timer.start();
}


$.es.interstitial = function() {
  function showModal(e) {
    var u = $.trim(e.currentTarget.href);
    if (u != "") {
      //clean up clicked link.
      if (u.indexOf('http://') === 0) u = u.substr(7);
      if (u.indexOf('www.') === 0) u = u.substr(4);

      if (typeof(urls) != 'array') {
        urls = internal_urls.split(',');
        urls = [window.location.host].concat(urls);
      }

      for (var x in urls) {
        var reg = new RegExp(urls[x], "gi");
        var stat = u.search(reg);
        // URL NOT FOUND IN ARRAY. ALLOW CLICK.
        if (stat >= 0 && stat < 12) return;
      }

      leaving.find('img.continue').click(function() {
        window.location = e.currentTarget.href;
      });

      leaving.overlay().load();
      e.preventDefault();
    }
  }

  var leaving = $('#leaving').overlay({speed:100,mask:{color:'#FFF',loadSpeed:100,opacity:0.8}});

  var links = $('a[href^="http://"]');
  links.click(showModal);
}

/* // doesn't work.  can't emulate user click on anchor link.
$.fn.linkBlock = function(anchor,target) {
  return this.each(function() {
    var self = $(this);
    var link = self.find(anchor);
    if (typeof(link.attr('href')) != "undefined") {
      self.css('cursor','pointer').click(function(e) {
        if (target == '_blank') link.attr('target','_blank');
        // link.click(function(e){ e.stopPropagation(); }).click();
      });
    }
  });
}
*/

$.es.attorneySearch = function() {
  var self = this;
  var form = $('#attorney_search');
  var attorney_name = form.find('#attorney_name');
  var practice_area = form.find('#practice_area');
  var attorney_title = form.find('#attorney_title');
  var attorney_404;
  var sublist;

  var attorney_list = $('#attorney_list');
  var cat = '';
  var cat_all = false;
  var title = '';
  var title_all = false;

  var timer;

  form.show().submit(function(){ return false; });
  var result_head = attorney_list.find('li').hide().end().find('h3.result_head');

  $('#view_full').click(function() {
    self.reset();
    attorney_list.show().find('li').show();
    result_head.show();
    if (typeof(attorney_404) == 'undefined') attorney_404 = $('#attorney_404');
    attorney_404.hide();
    return false;
  });

  self.reset = function() {
    attorney_name.val('Enter Name');
    practice_area.find('option:first').attr('selected','selected');
    attorney_title.find('option:first').attr('selected','selected');
    cat = '';
    cat_all = false;
    title = '';
    title_all = false;
  }

  self.updateList = function() {
    attorney_list.show();
    result_head.show();
    if (typeof(attorney_404) == 'undefined') attorney_404 = $('#attorney_404');
    attorney_404.hide();

    var val = attorney_name.val().toLowerCase();
    var id = '';
    var show = '';
    var hide = '';

    if (val != "" && val != 'enter name') {
      for (var x in attorneys) {
        if (attorneys[x]['name'].toLowerCase().indexOf(val) > -1) show += '#x_'+ x + cat + title +',';
      }
      if (show == "") show = 'x';
    }

    if (show == "") show = cat + title +',';
    if (show == ',' && (val == '' || val == 'enter name') && (cat_all || title_all)) show = 'li,';

    attorney_list.find('li').not(show.slice(0,-1)).hide()
    var count = attorney_list.find(show.slice(0,-1)).show();

    self.updateHead();

    if (count.length < 1) {
      attorney_404.show();
    }
  }

  self.updateHead = function() {
    if (typeof(sublist) == 'undefined') sublist = attorney_list.find('ul.result_list');
    sublist.each(function() {
      if ($(this).find('li:visible').length < 1) {
        attorney_list.find('h3.'+this.id).hide();
      } else {
        attorney_list.find('h3.'+this.id).show();
      }
    });
  }

  function nameBind(e) {
    clearTimeout(timer);
    timer = setTimeout(self.updateList, 200);
  }

  attorney_name
    .bind('click focus', function() {
      var $this = $(this);
      if ($this.val() == 'Enter Name') $this.val('');
    })
    .blur(function() {
      var $this = $(this);
      if ($this.val() == "") $this.val('Enter Name');
    })
    .keyup(nameBind);

  practice_area.change(function() {
    var val = $(this).val();
    switch (val) {
      case 'all':
        cat = '';
        cat_all = true;
        break;
      case 'sel':
        cat = '';
        cat_all = false;
        break;
      default:
        cat = '.'+val;
        cat_all = false;
    }
    
    var hash = $(this).find(':selected').attr('class');
    if (hash != "sel" && hash != "") window.location.hash = hash;
    else window.location.hash = "";

    self.updateList();
  });

  attorney_title.change(function() {
    var val = $(this).val();
    switch (val) {
      case 'all':
        title = '';
        title_all = true;
        break;
      case 'sel':
        title = '';
        title_all = false;
        break;
      default:
        title = '.title_'+val;
        title_all = false;
    }

    self.updateList();
  });

  var hash = window.location.hash.substr(1).toLowerCase();
  if (hash != "") {
    if (hash == 'all') {
      practice_area.val('all').change();
      return;
    }
    for (var x in categories) {
      if (categories[x]['url_title'].toLowerCase() == hash) {
        practice_area.val('cat_'+x).change();
        break;
      }
    }
  } else self.reset();

  attorney_list.find('a').click(function() {
    var cat = practice_area.find(':selected').attr('class');
    var title = attorney_title.val().toLowerCase();
    var qs = '';
    if (cat != 'sel') {
      qs = '/?c='+cat;
    }
    
    // if (title != 'sel') {
      // if (qs != '') qs += '&t='+title;
      // else qs = '/?t='+title;
    // }
    
    $(this).attr('href',$(this).attr('href') + qs);
  });
}

$('a.external').attr('target','_blank');
$('#search_box .q_box')
  .focus(function() {
    var $this = $(this);
    if ($this.val() == 'Search') $this.val('');
  })
  .blur(function() {
    var $this = $(this);
    if ($this.val() == '') $this.val('Search');
  });

})(jQuery);
