function Page(count, container, element_tag, prev, next, sortStrategy){
    this.per_page = count;
    this.page = 0;
    this.nav_prev = prev;
    this.nav_next = next;
    this.container = container;
    this.element_tag = element_tag;
    this.sortStrategy = sortStrategy;
};

Page.prototype.init = function() {
	this.insert_disabled_links();
  this.nav_prev.bind('click', {page: this}, function(e){ e.data.page.previous(); return false; });
  this.nav_next.bind('click', {page: this}, function(e){ e.data.page.next(); return false; });
};

Page.prototype.reorder_rows = function() {
    var ordered = new Array();
    this.container.children(this.element_tag).each(function(index){
        ordered.push(this);
    });

    if(this.sortStrategy)
        ordered.sort(this.sortStrategy);

    this.container.empty();

    for (var i=0; i < ordered.length; i++) {
        this.container.append(ordered[i]);
    };
};

Page.prototype.next = function(){
    if(this.page != this.last_page()){
	    this.page++;
	    this.refresh();
    }
};

Page.prototype.previous = function(){
	if(this.page != 0){
	 this.page--;
	 this.refresh();
	}
};

Page.prototype.total = function() {
	return this.container.find(this.element_tag).size();
};

Page.prototype.last_page = function() {
   return Math.ceil(this.total() / this.per_page) - 1;
};

Page.prototype.insert_disabled_links = function() {
	if(this.disabled_nav_prev == undefined){
		this.disabled_nav_prev = $('<span class="disabled">' + this.nav_prev.text() + '</span>')
		this.nav_prev.after(this.disabled_nav_prev);
	}
	
	if(this.disabled_nav_next == undefined){
		this.disabled_nav_next = $('<span class="disabled">' + this.nav_next.text() + '</span>')
		this.nav_next.after(this.disabled_nav_next);
	}
};

Page.prototype.update_navigators = function() {
	this.enable_navigator(this.nav_prev, this.disabled_nav_prev);
	this.enable_navigator(this.nav_next, this.disabled_nav_next);

	if(this.page == 0)
	    this.disable_navigator(this.nav_prev, this.disabled_nav_prev);

	if(this.page == this.last_page())
	    this.disable_navigator(this.nav_next, this.disabled_nav_next);

	if(this.total() <= this.per_page){
    this.disable_navigator(this.nav_prev, this.disabled_nav_prev);
    this.disable_navigator(this.nav_next, this.disabled_nav_next);
	}
};

Page.prototype.enable_navigator = function(link_ref, disabled_link_ref) {
	link_ref.show();
	disabled_link_ref.hide();
};

Page.prototype.disable_navigator = function(link_ref, disabled_link_ref) {
	link_ref.hide();
	disabled_link_ref.show();
};

Page.prototype.refresh = function(){
    this.container.find(this.element_tag).hide();
    var start = (this.page * this.per_page);
    var end = start + this.per_page;

    for (var i = start; i < end; i++) {
        this.container.find(this.element_tag + ':eq(' + i + ')').show();
    };
		this.update_navigators();
};

function Module(paginator, module, intro, defaults){
  this.paginator = paginator;
  this.module = module
  this.container = module.find('ul#listing');
  this.intro = intro;
  this.originCode = null;
  this.originBlurb = null;
  this.destinationCode = null;
  this.destinationBlurb = null;
  this.module.hide();
	this.populate(defaults.originCode, defaults.originBlurb, '', '');
}

Module.prototype.jsonURL = function(originCode, originBlurb, destinationCode, destinationBlurb) {
   var url = 'http://deals.wego.com/api/deals.js?feed=0&limit=48&wgz=87a36&currency=localize&callback=?';
   if(originCode.match(/[A-Z]{3}/))
     url += '&departs_from=' + originCode;

   if(destinationCode.match(/[A-Z]{3}/))
     url += '&arrives_at=' + destinationCode;
		
  return url;
};

Module.prototype.tpl = function() {
    if(this.tpl == null){
        this.tpl = ['li', {style: {'display':'none'}}, [
             'div', {className: 'wg_dealsdestination'}, [
                    'a', {href: this.url, target: 'blank'}, this.destination_city_name,
                    'span', {}, this.provider_id
                ],
                'img', {className: 'wg_dealsflightlogo', src: 'http://media.bezurk.net/images/flights/airlines/27x23/' + this.airline_code + '.gif', alt: this.airline_name}, null,
                'div', {className: 'wg_dealsprice'}, 'fr <span class="currency_code">' + this.money.currency + '</span> <span class="amount">' + this.money.amount + '</span>'
            ]
        ];
    }

    return this.tpl;
};

Module.prototype.routeBlurb = function(originCode, originName, destinationCode, destinationName) {
    if(this.loadingData)
        var prefix = 'Loading Flight Deals ';
    else
        var prefix = 'Flight Deals ';

    if(originCode.match(/[A-Z]{3}/) && destinationCode.match(/[A-Z]{3}/)){
        return prefix + 'from ' + originName + ' to ' + destinationName;
    }
    else if(originCode.match(/[A-Z]{3}/)){
        return prefix + 'from ' + originName;
    }
    else if(destinationCode.match(/[A-Z]{3}/)){
        return prefix + 'to ' + destinationName;
    }
};

Module.prototype.routeChanged = function(originCode, originBlurb, destinationCode, destinationBlurb) {
    return !(this.originCode == originCode && 
             this.originBlurb == originBlurb &&
             this.destinationCode == destinationCode &&
             this.destinationBlurb == destinationBlurb);
};

Module.prototype.completeRoute = function(originCode, destinationCode) {
	return originCode.match(/[A-Z]{3}/) && destinationCode.match(/[A-Z]{3}/);
};

Module.prototype.changeFlightSearchToAirfares = function(obj) {
	$.each(obj.url.split('?')[1].split('&'), function(){
		if(this.match(/^url/)){
			if(decodeURIComponent(this.split('=')[1]).indexOf('http://www.wego.com/flights/progress.html') > -1){
				obj.url = '/flights/airfares/' + obj.origin_city_code + '/' + obj.destination_city_code;
			}
		}
	})
};

Module.prototype.populate = function(originCode, originBlurb, destinationCode, destinationBlurb) {
	// if(originCode == '' || originBlurb == '')
	// 	return false;
		
	var self = this;
  $.getJSON(self.jsonURL(originCode, originBlurb, destinationCode, destinationBlurb), function(data, textStatus){
      if(data.length > 0){
          self.container.empty();
          self.module.find('h2').text(self.routeBlurb(originCode, originBlurb.split(',')[0], destinationCode, destinationBlurb.split(',')[0]));
          $.each(data, function(i, obj){
            self.changeFlightSearchToAirfares(obj);
            self.container.tplAppend(obj, self.tpl());
          });

          self.paginator.refresh();
          self.intro.hide();
          self.module.show();
      }
      else{
          self.module.hide();
          self.intro.show();
      }
  });
};

Module.prototype.handleRouteChange = function(fromTxt,from,toTxt,to) {

    var self = this;
    var originBlurb = fromTxt;
    var originCode = from;
    var destinationBlurb = toTxt;
    var destinationCode = to;
    if(!self.routeChanged(originCode, originBlurb, destinationCode, destinationBlurb))
    {
        return;
    }
    self.originCode = originCode;
    self.originBlurb = originBlurb;
    self.destinationCode = destinationCode;
    self.destinationBlurb = destinationBlurb;
    
		self.populate(originCode, originBlurb, destinationCode, destinationBlurb);
};
