﻿(function($) {
  $.fn.leadFeature = function(title, cats) {
  
    var curPage = 1;
    var maxPage = 4;
    var height = 220;
    var timeoutVar;
    var map;
    var bounds;
  
    function artItemClicked() {
      curPage = parseInt($(this).attr('title'));
      LoadNewBanner(true);
      return false;
    }
    
    function LoadNewBanner(forced){
      if (forced) {
        clearTimeout(timeoutVar);
      } else {
        timeoutVar = setTimeout(function() {
          runNext();
        }, 5000);
      }
      var oldPage = curPage;
      if (curPage < 1) {
        curPage = 1;
      } else if(curPage > maxPage) {
        curPage = maxPage;
      }
      var speed = parseInt(Math.abs(curPage - oldPage) * 5000);
      speed += '';
      for (var x=1; x<=maxPage; x++) {
        $('.leadFeature ul.scrollbtns .a' + x).attr('class','a' + x);
      }
      $('.leadFeature ul.scrollbtns .a' + curPage).attr('class','a' + curPage + ' on');
        
      $('.leadFeature .frameWrap .hold').animate({marginTop: -((curPage - 1) * height) + "px"}, speed);
    }
  
    function getWrappingMarkup() {
      var str = '<a href="/news.aspx" class="floatRight linkBtn">More News</a><h1>' + title + '</h1>';
      str += '<div class="controls"><ul class="scrollbtns"></ul></div>';
      str += '<div class="frameWrap"><div class="hold"></div></div>';
      str += '<div id="leadMapFeature" class="leadMap"></div>';
      return str;
    }
    
    function appendArticleListItem(that, title, id, i, isOn) {
      $('ul.scrollbtns', that).append('<li><a href="#" class="a'+(i+1)+(isOn ? ' on' : '')+'" title="'+(i+1)+'" id="art_'+id+'"><!--span class="calendar">Jan <span class="num">18</span></span--> '+title+'</a></li>');
      $('#art_' + id).click(artItemClicked);
    }
  
    function appendArticleMarkup(that, title, summary, imageUrl, videoCount, commentCount, imageCount, isOn, href, latitude, longitude, i, date) {
      i++;
      $('div.frameWrap > div.hold', that).append('<div class="slide"><div class="leadImg"><img src="'+imageUrl+'" alt="" height="220" width="222" /><ul class="articleMedia"><li class="photos"><a href="'+href+'#image">Photos: '+imageCount+'</a></li><li class="vids"><a href="'+href+'#video">Videos: '+videoCount+'</a></li><li class="comm"><a href="'+href+'#comments">Comments: '+commentCount+'</a></li></ul></div><div class="txt"><h2><a href="'+href+'">'+title+'</a></h2><p class="date">' + date + '</p><div class="hr"><hr /></div><p class="summary">'+summary+'</p><p><a href="'+href+'"><strong>Full article &gt;</strong></a> <span class="divider">|</span> <a href="/news/map.aspx"><strong>View news map &gt;</strong></a></p></div></div>');
      if (!(isNullOrNothing(map)) && latitude != 0 && longitude != 0) {
        addMarker(latitude, longitude, i);
      }
    }
    
    function addMap() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById('leadMapFeature'));
        map.setCenter(new GLatLng(53.16785, -3.14242), 6);
        bounds = new GLatLngBounds();
      }
    }
    
    function addMarker(lat, lng, i) {
      var latLng = new GLatLng(lat, lng);
      var marker = new GMarker(latLng);
      map.addOverlay(marker);
      GEvent.addListener(marker, 'click', function() {
        $('.leadFeature ul.scrollbtns .a' + i).trigger('click');
      });
      bounds.extend(latLng);
      //alert(latLng);
    }
    
    function isNullOrNothing(o) {
      return typeof(o) == 'nothing' || o === null;
    }

    this.each(function() {
      var that = $(this);
      $.ajax({
        type: 'POST',
        url: 'leadfeatureconnector.ashx',
        data: 'command=Init&categories=' + cats,
        beforeSend: function() {
        },
        success: function (xml) {
          that.html(getWrappingMarkup());
          var news = $(xml).children('Connector').children('NewsCollection').find('News');
          if (news.size() > 0 && news.find('LocationData').size() > 0) {
            addMap();
          }
          news.each( function(i, val) {
            var id = $(val).attr('id');
            var title = $('Title', val).text();
            var summary = $('Summary', val).text();
            var imageUrl = $(val).attr('imageUrl');
            var videoCount = $(val).attr('videoCount');
            var commentCount = $(val).attr('commentCount');
            var imageCount = $(val).attr('imageCount');
            var href = $(val).attr('href');
			      var date = $('Date', val).text();
			      date = date.substring(0, 10);
            var locationElement = $('LocationData', val);
            var latitude = 0;
            var longitude = 0;
            if (!(isNullOrNothing(locationElement)) && locationElement.size() > 0) {
              latitude = $(locationElement).attr('Latitude');
              longitude = $(locationElement).attr('Longitude');
            }
            
            appendArticleListItem(that, title, id, i, i == 0);
            appendArticleMarkup(that, title, summary, imageUrl, videoCount, commentCount, imageCount, i == 0, href, latitude, longitude, i, date);
          });
          
          if (!(isNullOrNothing(map))) {
            map.setZoom(map.getBoundsZoomLevel(bounds));
            map.setCenter(bounds.getCenter());
          }
        },
        complete: function () {
        }
      });
    });
    
    function runNext() {
      curPage++;
      if (curPage > maxPage) {
        curPage = 1;
      }
      LoadNewBanner(false);
    }
    
    timeoutVar = setTimeout(function() {
      runNext();
    }, 5000);
    
    return this;
  };
})(jQuery);
