function Ready_up(type) {
  var self = this;
  this.root = $('#container');
  this.loaderChoose = function() {		
    self.jaxChoose();

    if (self.root.find('.page_tools').length > 0)
      new Page_tools(self.root.find('.page_tools'));
    
    if (self.root.find('#content').hasClass('home'))
      new Home_page(self.root.find('#content'));

		if (self.root.find('.location_finder').length > 0) {
		  new Locations_switcher(self.root.find('.location_finder'));
		}
    for (var i = 0; i < self.root.find('.tooltip').length; i++) {
		  new Note_tip(self.root.find('.tooltip').eq(i)).start_up();
	  }
    if (self.root.find('.expand').length > 0) {
      new Expander_setter(self.root.find('.expand'));
    }
  }
  this.jaxChoose = function() {	
    External_link.init("class","external_link", "");
    
    //if(self.root.find('.expand').length > 0)
      //new Expandable(self.root.find('.expand'), 0);
    
     if (self.root.find('.map_chose').length > 0) {
      new Map_choose(self.root.find('.map_chose'));
    }
    
    if(self.root.find('.timeline').length > 0) {
      new Timeline(self.root.find('.timeline'));
  }    
    for (var i = 0; i < self.root.find('blockquote').length; i++) {
      self.root.find('blockquote').eq(i).html('<p>' + self.root.find('blockquote').eq(i).html() + '</p>');
    }
    if (window.location.port !== "") {
      new Underdevelop_img(this.root, 'http://www.meetgoodwill.com');
    }
  }
  new Load_linker(this.root);
  
  
  if (type === 'load') 
    this.loaderChoose();
  else if (type === 'jax')
    this.jaxChoose();
}
function Note_tip(element) {
  var self = this;
  this.tip = element;
  this.tip.wrap('<div class="tipper"></div>').before('<img src="/images/global/icons/question.png" alt="tip" />');
  this.note = element.parent();
  this.tipped = false;
  
  this.show_note = function(e) {
    if (self.tipped) {
      self.tip.hide();
      self.tipped = false;
    } else{
      self.tip.show();
      self.tipped = true;
    }
  }
  
  this.start_up =function() {
    self.tip.show().css({ top : -self.tip.outerHeight()}).hide();
    self.note.bind('click', self.show_note);
  }
}

function Expander_setter(element) {
  var self = this;
  this.expanders = element;
  this.expand_act = function(e) {
    var me = $(e.currentTarget);
    if (me.hasClass('open')) {
      me.removeClass('open').data('wrapper').animate({
        height: 1
      }, {duration: 450, 
        easing: "easeOutQuad",
        queue: false,
        complete: function() {
          $(this).css('display', 'none');
        }
      });
    } else {
      me.addClass('open').data('wrapper').css('display', 'block').animate({
        height: me.data('wrapper_height')
      }, {duration: 450, 
        easing: "easeOutQuad",
        queue: false
      });
    }
  }
  
  this.large_expand = function(conatiner) {
    var trigger = conatiner.find('a.expand:first');
    var temp_wrap = new Wrap_up(trigger.eq(i), ':header')
    trigger.data('wrapper', temp_wrap);
    trigger.data('wrapper_height', temp_wrap.show().height());
    temp_wrap.css({'height' : '1px', 'display' : 'none'});
    trigger.bind('click', self.expand_act);
    if (trigger.attr('href') === "#open") trigger.trigger('click');
  }
  this.list_expander = function(conatiner) {
    var trigger = conatiner.find(':header');
    for (var i = 0; i < trigger.length; i++) {
      var temp_wrap = new Wrap_up(trigger.eq(i), ':header')
      trigger.eq(i).data('wrapper', temp_wrap);
      trigger.eq(i).data('wrapper_height', temp_wrap.show().height());
      temp_wrap.css({'height' : '1px', 'display' : 'none'});
      trigger.eq(i).bind('click', self.expand_act);
    }
  }
  this.start_up = function() {
    for (var i = 0; i < self.expanders.length; i++) {
      var temp_item = self.expanders.eq(i)
      if (temp_item.is('div.faqs')) {
        self.list_expander(temp_item);
      } else if (temp_item.is('div')) {
        self.large_expand(temp_item);
      } else {
        //self.large_expand(temp_item);
      }
    }
  }
  this.start_up();
}

function Wrap_up(element, stoper_seletor) {
  element = element.next();
  var wrap = element;
  while (!element.is(stoper_seletor) && element.html()) {
    wrap = wrap.add(element);
    element = element.next();
  }
  return wrap.wrapAll('<div class="wrapper"></div>').parent();
}


function Underdevelop_img(element, domain) {
  var self = this;
  this.root = element.find('img');
  for (var i = 0; i < this.root.length; i++) {
    if (this.root.eq(i).attr('src').match(/^\/system\//i)) {
      this.root.eq(i).attr('src', domain + this.root.eq(i).attr('src'))
    }
  }
}

function Grid_fixer(element, number_in_row)  {
	var self = this;
	this.root = element;
	this.items = this.root.children();
	this.num_columns = number_in_row;
	this.current_row = new Array();
	this.row_height = 0;
	this.fix_heights = function()  {
	  for (var i = 0; i < self.items.length; i++) {
      if (i % self.num_columns == 0) {
        self.current_row = new Array();
        self.row_height = 0;
      }
      self.current_row.push(self.items.eq(i));
      
	    if (self.items.eq(i).height() > self.row_height) {
	      self.row_height = self.items.eq(i).height();
      }
      for (var j = 0; j < self.current_row.length; j++) {
	      self.current_row[j].height(self.row_height);
	    }
    }
  }
	this.fix_heights();
}


function File_extension(filename) {
	return (/[.]/).exec(filename) ? (/[^.]+$/).exec(filename) : null;
}
function File_directory(filepath) {
	return (/[\/]/).exec(filepath) ? (/.+[\/^]/).exec(filepath) : null;
}

function Linker(element) {
  var self = this;
  this.root = element.find('a').filter(function(index) {return $(this).attr('href')});
  
  this.popin_filter = function(index) {
    return $(this).attr('href').match(/\/popin\//i);
  }
  
  this.indy_linkup = function(linker, hookshot) {
    if (hookshot.match('#email_page') || hookshot.match(/^\/contact\/refer/i)) {
      new Email_page(linker);
    } else if (hookshot.match(/^\/contact\/personal_contact/i)) {
      new Personal_contact(linker);
    } else {
      new Load_shadow_box(linker, File_extension(hookshot))
    }
  }
  
  for (var i = 0; i < this.root.length; i++) {
    this.indy_linkup(this.root.eq(i), this.root.eq(i).attr('href'));
  }
}

function Load_linker(element) {
  Linker.call(this, element);
  new Popin(this.root.filter(this.popin_filter));
}


function Locations_switcher(element) {
  var self = this;
  this.root = element;
  this.tabs = this.root.children('h4');
  this.tabs.click( function(e) {
    var me = $(this);
    self.root.find('input[type=hidden]').attr('name', me.attr('title'));
    if (me.hasClass('active')) {
      return false;
    }
    me.siblings('h4').removeClass('active').next('p').hide();
    me.addClass('active').next('p').show();
  });
  this.tabs.eq(0).click();
}

function Load_shadow_box(element, extention) {
  var self = this;
	this.root = element;
	this.playa = false;
	// open a welcome message
	
	switch (String(extention)) {
	  case "mp4":
	    this.playa = "qt";
	    break;
	  case "flv":
	    this.playa = "flv";
	    break;
	  case "swf":
	    this.playa = "swf";
	    break;
	  case "html":
	    this.playa = "iframe";
	    break;
	  case "jpg": case "jpeg": case "png": case "tiff": case "gif":
	    this.playa = false;
	    break;
	  default : 
	    return false;
  }
  
  this.load_gallery = function(e) {
		e.preventDefault();
		jQuery.getJSON("files/listing" + dir.toString().replace('/system/uploads', ""), function(data) {
			var shadow_hidden = new Array();
			for (var i = 0; i < data.assets.length; i++) {
				shadow_hidden[i] = new Object();
				shadow_hidden[i].content = File_directory(self.root.attr('href')) + data.assets[i].filename;
				shadow_hidden[i].player = 'img';
				shadow_hidden[i].gallery = (/[^.]+$/).exec(dir);
			}
			Shadowbox.open(shadow_hidden);
		});
  }
  this.load_media = function(e) {
		e.preventDefault();
		if(self.playa == "iframe")
		{
			Shadowbox.open({
				title: $(this).attr('title'),
				player: self.playa,
				content:	$(this).attr('href'),
				height: 485,
				width: 645
			});
		}else{
			Shadowbox.open({
			    title: $(this).attr('title'),
				player: self.playa,
				content:	$(this).attr('href')
			});
		}
  }
  
  if (this.playa) {
    this.root.bind('click', this.load_media);
  } else {
    this.root.bind('click', this.load_gallery);
  }
}

function Map_choose(element) {
  var self = this;
  this.root = element;
  new Grid_fixer(this.root.children('.body'), 3);
  this.root.children('.head').children('h6:last').toggle(function() {
    $(this).html('Hide Map');
    self.root.animate({
      width: '30%'
    }, {duration: 450, 
      easing: "easeOutQuad",
      queue: false
    });
  }, function() {
    $(this).html('Show Map');
    self.root.animate({
      width: '100%'
    }, {duration: 450, 
      easing: "easeOutQuad",
      queue: false
    });
  });
  this.root.children('.head').children('h6:last').click();
}

function Expandable(element, first_open) {
  var self = this;
  this.root = element;
  this.expander = this.root.find('h3');
  
  this.set_slide = function(target) {
    this.slides = target.next();
    this.temp = this.slides.next();
    target.append('<span>&nbsp;</span>');
    while (!this.temp.is('h3') && this.temp.html()) {
      this.slides = this.slides.add(this.temp);
      this.temp = this.temp.next();
    }
    this.slides.wrapAll('<div class="wrapper"></div>');
    target.toggle(function() {
      $(this).next().slideDown(300, "easeOutQuad");
      $(this).addClass('open');
    }, function() {
      $(this).next().slideUp(300, "easeOutQuad");
      $(this).removeClass('open');
    });
  }
  for (var i = 0; i < this.expander.length; i++) {
    this.set_slide(this.expander.eq(i));
  }
  this.root.find('.wrapper').slideUp(0);
  if (typeof(first_open) === "number") {
    this.expander.eq(first_open).click();
  }
}

function Main_home_links(element) {
  Expandable.call(this, element, null)

  for (var i = 0; i < this.root.find('.wrapper').length; i++) {
    this.root.find('.wrapper').eq(i).prev().andSelf().wrapAll('<div></div>')
  }
  this.root.children().eq(0).addClass('first');
}

function Home_page(element) {
  var self = this;
  this.root = element;
  new Carousel(this.root.find('.carousel'), 7, 'goodwill_carousel');
//  new Main_home_links( this.root.find('.main_home_links'));
}

function CookieHandler() {
  this.setCookie = function (name, value, days_around) {
    if (typeof(seconds) != 'undefined') {
      this.date = new Date();
      date.setTime(date.getDate() + days_around);
      this.expires = "; expires=" + date.toGMTString();
    }
    else {
      this.expires = "";
    }
    document.cookie = name + "=" + value + this.expires + "; path=/";
  }
  this.getCookie = function (name) {
    name += "=";
    var carray = document.cookie.split(';');
    for(var i=0;i < carray.length;i++) {
      var c = carray[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return null;
  }
  this.deleteCookie = function (name) {
    this.setCookie(name, "", -1);
  }
}

function Carousel(element, delay, name_of_cookie) {
  var self = this;
  this.root = element;
  this.delay = delay;

  this.main_items = this.root.find('dt');
  this.new_items = new Array();
  this.thumbs = this.root.children('dd');
  this.active = this.thumbs.eq(0);
  this.on_own = null;
  
  this.cookie_name = name_of_cookie;
  this.cookier = new CookieHandler();

  this.thumbs.each( function(iter) {
    self.thumbs.eq(iter).data('item', self.main_items.eq(iter));
    self.thumbs.eq(iter).data('iter', iter);
  });
  this.large_switch = function(new_item, old_item) {
    self.root.prepend(new_item);
    old_item.animate({
      opacity: 0
    }, {duration: 800, 
      easing: "easeOutQuad",
      queue: false,
      complete:  function() {
        old_item.removeAttr('style').remove();
      }
    });
  }
  this.button_down = function(e) {
    clearTimeout(self.timeout);
    self.timeout = setTimeout( function() {
      for (var i = 0; i < self.thumbs.length; i++) {
        self.thumbs.eq(i).animate({
          top: 550
        }, {duration: 120*i+700, 
          easing: "easeOutBack",
          queue: false
        });
      }
    }, 400);
  }
  this.button_over = function(e) {
    $(this).animate({
      top: 460
    }, {duration: 250, 
      easing: "easeOutQuad",
      queue: false
    });
  }
  this.button_out = function(e) {
    $(this).stop(true);
    $(this).animate({
      top: 465
    }, {duration: 250, 
      easing: "easeOutQuad",
      queue: false
    });
  }
  this.button_on = function(e) {
    var me = $(this)
    if (me.data('iter') == self.active.data('iter')) {
      return false;
    }
    self.cookier.setCookie(self.cookie_name, me.data('iter'), 10);
    self.large_switch(me.data('item'), self.active.data('item'));
    self.thumbs.animate({
      paddingTop: 20,
      marginTop: 0,
      opacity: .9
    }, {duration: 250, 
      easing: "easeOutQuad",
      queue: false
    });
    me.animate({
      paddingTop: 15,
      marginTop: 5,
      opacity: .7
    }, {duration: 500, 
      easing: "easeOutQuad",
      queue: false
    });
    self.active = me;
    self.timer_set();
  }
  this.button_up = function(e) {
    clearTimeout(self.timeout);
    self.timeout = setTimeout( function() {
      for (var i = 0; i < self.thumbs.length; i++) {
        self.thumbs.eq(i).animate({
          top: 465
        }, {duration: 120*i+700, 
          easing: "easeOutBack",
          queue: false
        });
      }
    }, 400);
  }
  this.next_up = function() {
    if (self.active.next().html()) {
      self.active.next().trigger('click');
    } else {
      self.thumbs.eq(0).trigger('click');
    }
  }
  this.timer_set = function() {
    if (self.on_own != null) {
      clearTimeout(self.on_own);
    }
    self.on_own = setTimeout(function() {
      self.next_up();
    }, self.delay * 1000);

  }
  this.thumbs.bind('click', self.button_on);
  this.thumbs.hover(self.button_over, self.button_out);
  this.root.hover(self.button_up, self.button_down);
  
  this.tempIter = Number(this.cookier.getCookie(self.cookie_name));
  if (!this.tempIter) {
    this.tempIter = 0;
  }
  this.main_items.remove();
  this.active = this.thumbs.eq(this.tempIter);
  this.root.append(this.active.data('item'));
  
  this.thumbs.eq((this.tempIter + 1) % this.main_items.length).trigger('click');
}

function Page_tools(element) {
  var self = this;
  this.root = element;
  new Text_resizer(self.root.find('#text_resize'));
}

function Text_resizer(element) {
  var self = this;
  this.root = element;
  this.content_basins = $('.deskman');
  
  this.cookier = new CookieHandler();
  this.cookie_name = 'text_size'
  this.current_size = Number(this.cookier.getCookie(this.cookie_name));;
  if (!this.current_size) {
    this.current_size = 10;
  } else {
    this.content_basins.css({fontSize: this.current_size});
  }
  
  this.increase_size = function(e) {
    ++self.current_size
    self.cookier.setCookie(self.cookie_name, self.current_size, 10);
    self.content_basins.css({fontSize: self.current_size});
  }
  this.decrease_size = function(e) {
    if (self.current_size > 10) {
      --self.current_size
      self.cookier.setCookie(self.cookie_name, self.current_size, 10);
      self.content_basins.css({fontSize: self.current_size});
    }
  }

  this.root.children('a[href="#increase"]').bind('click', this.increase_size);
  this.root.children('a[href="#decrease"]').bind('click', this.decrease_size);
}

function Email_page(element) {
  Popn_form.call(this, element);
  this.url = '/contact/refer?ajax=true';
  this.form_title = 'Email this Page to a Friend';
}

function Personal_contact(element) {
  Popn_form.call(this, element);
  this.url = element.attr('href') + '&ajax=true';
  this.form_title = 'Send a personal Email';
}

$(document).ready(function() {
  new Ready_up('load');
});



