// check redirect
var mainHref = location.href.replace('http://' + location.host + '/', '');

if (!jsEnabled) {
  if (!mainHref)
    mainHref = '/#/welcome';
  else if (mainHref.substr(0, 1) != '#')
    mainHref = '/#/' + mainHref;
  $.get('/enable_js.php', function() {
		var reload = location.href.indexOf('#') == -1 && mainHref.indexOf('/#/welcome') == -1 ? false : true;
		location.href = mainHref;
		if (reload)
			location.reload();
	});
}
else if (mainHref && mainHref.substr(0, 1) != '#')
  location.href = '/#/' + mainHref;
else {

// center site vertically
jQuery.vertCenter = function() {
  var hw = $(window).height();
  var hs = 705;
  var h = 0;
  if (hw > hs)
    h = Math.round((hw - hs)/ 2);
  $('#header').css('paddingTop', h + 'px');
  $('#footer').css('paddingBottom', h + 'px');
};

// slideshow
jQuery.slideshow = function(cont) {
  var parent = $(cont),
    img = parent.find('img'),
    clipWidth = parent.width(),
    count = 0,
    preloadedImgs = [],
    active = true,
    running = false;
  
  for (var i = 0; i < slideshowPhotos.length; i++) {
    preloadedImgs[i] = new Image();
    preloadedImgs[i].src = slideshowPhotos[i];
  }

  $.slideshow.update = function() {
    if (!active) {
      running  = false;
      return;
    }

    if (parent.scrollLeft() == 0) {
      var width = preloadedImgs[count].width - clipWidth;
      var duration = Math.round(preloadedImgs[count].width / clipWidth * 2500);
      parent
        .css('background', 'url(' + preloadedImgs[count].src + ') -' + width + 'px 0px scroll no-repeat')
        .animate({scrollLeft: width}, {duration: duration, complete: function() {setTimeout('$.slideshow.update()', 500);}});
      count = (count + 1) % preloadedImgs.length;
      running  = true;
    }
    else {
      if (!preloadedImgs[count].complete) {
        setTimeout('$.slideshow.update()', 50);
        return;
      }
      if (preloadedImgs[count].width == 0 || preloadedImgs[count].height == 0) {
        count = (count + 1) % preloadedImgs.length;
        $.slideshow.update();
        return;
      }

      img.css({opacity: 0, display: 'none'});
      parent.scrollLeft(0);
      img
        .attr('src', preloadedImgs[count].src)
        .css('display', 'inline')
        .animate({opacity: 1}, {duration: 2000, complete: function() {$.slideshow.update();}});
      running  = true;
    }
  };

  $.slideshow.stop = function() {
    active = false;
  };

  $.slideshow.start = function() {
    if (active) return;
    active = true;
    if (!running)
      setTimeout('$.slideshow.update()', 2000);
  };

  setTimeout('$.slideshow.update()', 1000);
};

// bottom menu nav functionality
jQuery.bottomMenuNav = function() {
  var marginLeft, opened = null, openedWidth = 0;
  
  // center nav
  $('#nav > div').find('div').css('display', 'none');
  marginLeft = Math.round((1000 - $('#nav > div').width()) / 2)
  $('#nav > div').find('div').css('display', 'block');
  $('#nav > div').css('marginLeft', marginLeft);

  // calculate submenu widths
  $('#nav p').each(function() {
    var width = 0;
    $(this).find('a').each(function() {width += $(this).outerWidth(true);});
    $(this).css('width', width);
  });

  // open smenu support
  $.bottomMenuNav.toItem = function(a) {
    var smenu = null;
    if (a) {
      smenu = a.next();
      if (smenu.length == 0 || smenu[0].tagName != 'DIV') smenu = null;
    }
    if ((opened == null && smenu == null) || (opened && smenu && opened[0] == smenu[0])) return;

    var width = 0;
    if (smenu) {
      width = smenu.children('p:eq(0)').width();
      smenu.animate({width: width});
    }
    if (opened)
      opened.animate({width: 0});
    marginLeft -= Math.round((width - openedWidth) / 2);
    $('#nav > div').animate({marginLeft: marginLeft});

    opened = smenu;
    openedWidth = width;
  };

  // bind functionality
  $('#nav div > a').click(function() {
		if ($(this).attr('target')) return true;

    $(this)[0].blur();
    $.bottomMenuNav.toItem($(this));

    return false;
  });
};

// nav functionality
jQuery.mainNavSupport = function() {
  var slides = null, slideQueue = [], zIndex = 1, links = $('a[rel=nav]'), currMenu = null;

  $.mainNavSupport.afterEffect = function() {
    if (arguments.length == 0 && slideQueue.length > 0) {
      var currSlides = slideQueue.shift();
      if (slides[0] != currSlides[0]) {
        $(currSlides[0]).css('display', 'none');
        $(currSlides[1]).css('display', 'none');
        if (currSlides.length == 3 && currSlides[2] != currMenu) {
          if (!currMenu)
            $(currSlides[2]).animate({right: -204}, {duration: 500, complete: function() {$(this).css('display', 'none')}});
          else
            $(currSlides[2]).css('display', 'none');
        }
      }
      if (slideQueue.length > 0) return;
    }

		if (arguments.length == 0) {
			zIndex = 1;
			slides.css('zIndex', zIndex);
		}

		if ($(slides[0]).attr('id') == 'location-map' && !$(slides[0]).data('loaded')) {
			$('#location-map').data('loaded', true);
			$.googleMap($('#location-map')[0], {points: [{lat: 42.053436, lon: -88.046913}], panel: $('#location-panel')[0]});
		}
		
    var scrollable = $(slides[1]).find('.scrollable');
    if (!scrollable.data('scroll'))
			scrollable.data('scroll', true).jScrollPane({showArrows: true, scrollbarWidth: 10});
		if (slides.length == 3) {
			scrollable = $(slides[2]).find('.scrollable');
			if (!scrollable.data('scroll')) {
				scrollable.data('scroll', true);
				if (scrollable.height() < scrollable.find('.fxd').height())
					scrollable.jScrollPane({showArrows: true, scrollbarWidth: 10});
			}
		}
  }

  $.mainNavSupport.slideDoors = function() {
    $('#sliding-doors .slide1').animate({left: -490}, {duration: 2000});
    $('#sliding-doors .slide2 a').animate({marginLeft: 276}, {
      duration: 2000,
      complete: function() {
				$('#sliding-doors').remove();
        $.mainNavSupport.afterEffect(1);
      }
    });
  };

  $.mainNavSupport.changeSlides = function(path) {
    var newSlides = $.mainNavSupport.getSlides(path);
    if (newSlides.length < 2) return;
    if (slides) {
			if (slides[0] == newSlides[0])
				return;
			slideQueue.push(slides);
		}
    slides = newSlides;

    $.mainNavSupport.setMenuFocus(path);

    var slidingDoorsMode = false;
    if ($('#sliding-doors').length && $('#sliding-doors .slide1').css('left') == '0px')
      slidingDoorsMode = true;

    if (slides.length == 3) {
      if (currMenu != slides[2]) {
        $(slides[2]).css('right', -204).animate({right: 0}, {duration: slidingDoorsMode ? 2000 : 1000});
        currMenu = slides[2];
        $.slideshow.stop();
      }
    }
    else {
      currMenu = null;
      $.slideshow.start();
    }
		slides.css({display: 'block', zIndex: ++zIndex});

    if (slidingDoorsMode)
      $.mainNavSupport.slideDoors();
    else {
      if ($(slides[0]).attr('id') == 'contact-form' && $.contactForm.isShown())
        $.contactForm.hide(1);
      else {
        if ($.contactForm.isShown())
          $.contactForm.hide(2);
        $(slides[0]).css({top: -490, left: 0}).animate({top: 0}, {duration: 1000});
      }
      $(slides[1]).css('top', 490).animate({top: 0}, {
        duration: 1000,
        complete: function() {
          $.mainNavSupport.afterEffect();
        }
      });
    }

    var scrollable = $(slides[1]).find('.scrollable');
    if (!scrollable.data('scroll')) {
			var maxHeight = 415 - scrollable.prev().height();
      if (maxHeight > scrollable.height())
        scrollable.data('scroll', true);
			scrollable.css('height', maxHeight);
    }
  };

  $.mainNavSupport.getSlides = function(p) {
    var ps = p.replace(/\./g, '').split(' ');
    var elem = ps[0];
    if (!$('.' + elem + '.slide3').length)
      elem = ps.length > 1 && $('.' + ps[0] + '-' + ps[1] + '.slide3').length ? ps[0] + '-' + ps[1] : ps[0] + '-';
    var elems = $(p + ' .slide1:first').add(p + ' .slide2:first').add('.' + elem + '.slide3');

    return elems;
  };

  $.mainNavSupport.setMenuFocus = function(path) {
    var pathItems = path.replace(/\./g, '').split(' ');
    links.removeClass('on');

    // check top menu
    var a = $('#header .menu a.' + pathItems[0]);
    if (a.length) {
      a.addClass('on').blur().children('span').scrollTop(0);
      $.bottomMenuNav.toItem(null);
    }
    else {
      a = $('#nav a.' + pathItems[0]);
      if (a.length) {
        $.bottomMenuNav.toItem(a);
        var smenu = a.next();
        if (pathItems.length > 1 && smenu.length && smenu[0].tagName == 'DIV')
          smenu.find('p a.' + pathItems[1]).addClass('on').scrollTop(0).blur();
        else
          a.addClass('on').scrollTop(0).blur();
      }
      else {
        a = $('#footer a.' + pathItems[0]);
				if (a.length) {
					a.addClass('on').blur();
					$.bottomMenuNav.toItem(null);
				}
      }
    }

    if (!$(slides[2]).length) return;
    if (pathItems.length == 1 || (pathItems.length == 2 && $(slides[2]).hasClass(pathItems[0] + '-' + pathItems[1])))
      a = $(slides[2]).find('a:first').blur();
    else
      a = $(slides[2]).find('a.' + pathItems[pathItems.length - 1]).blur();
    var next = a.next();
    if (next.length && next[0].tagName == 'UL' && next.find('li:first').css('display') != 'none')
      a = next.find('a:first').blur();
    a.addClass('on');
		var parent = a.parents('ul:eq(0)');
		if (parent.length && parent.hasClass('hidden')) {
			parent.parent().find('ul').not(parent[0]).hide();
			parent.slideDown(function() {
				var scrollable = $(this).parents('.scrollable:eq(0)');
				if (scrollable.height() < scrollable.find('.fxd').height())
					scrollable.jScrollPane({showArrows: true, scrollbarWidth: 10});
			});
		}
  };

  $('.slide1').add('.slide2').add('.slide3').not('.ignore').css({display: 'none', visibility: 'visible'});
  links.click(function() {
    var path = $(this).attr('href');
    $.mainNavSupport.changeSlides('.' + path.substr(1).replace(/\//g, ' .'));
    location.href = '#' + path;
    return false;
  });
}

// show contact form
jQuery.contactForm = function() {
  var shown = false, slide = $('#contact-form');

  $.contactForm.isShown = function() {
    return shown;
  };

  $.contactForm.show = function() {
    if (shown) return;
    shown = true;

    slide.find('input[type=button]').css('visibility', 'visible');
    slide.stop().css({zIndex: 2, display: 'block', left: -490}).animate({left: 0}, {duration: 1000});
  };

  $.contactForm.hide = function() {
    if (!shown) return;
    shown = false;

    if (arguments.length == 0)
      slide.stop().animate({left: -490}, {
        duration: 1000,
        complete: function() {
          $(this).css('display', 'none');
          $(this).find('input[type=button]').css('visibility', 'hidden');
        }
      });
    else if (arguments[0] == 1)
      slide.find('input[type=button]').css('visibility', 'hidden');
    else if (arguments[0] == 2)
      slide.css('display', 'none');
  };

  // bind functionality
  $('a[rel=contact-form]').click(function() {
    $.contactForm.show();
    return false;
  });
  $("#contact-date").datepicker({minDate: new Date()});
  $("#contact-date").datepicker('hide');
};

// show contact form
$.locationOp = function() {

	$('#location-from').keydown(function(event) {
		if (event.keyCode == 13)
			$.locationOp.getDirections();
	});
	$('#location-button').click(function() {
		$.locationOp.getDirections();
	});

	$.locationOp.getDirections = function() {
		if ($('#location-button').attr('disabled')) return;

		$('#location-button').attr('value', 'please wait...').attr('disabled', true);

		$.googleMap.getDirections({
			origin: $('#location-from').attr('value'),
			destination: '1325 Remington Rd, Schaumburg, IL 60173',
			success: function() {
				$('#location-from').parents('.scrollable').jScrollPane({showArrows: true, scrollbarWidth: 10});
			},
			complete: function() {
				$('#location-button').attr('value', 'get directions').attr('disabled', false);
			}
		});
	}

};

// gallery support
$.fn.gallery = function() {
	return $(this).each(function() {
		var g = $(this);

		g.find('.thumbs li:first').addClass('on').find('img').css('opacity', 0.4);

		g.data('thumbs', g.find('.thumbs li').length);
		g.data('thumb', 0);
		g.find('.slide1 a:first').css('display', 'none')

		g.find('.slide1 a')
			.css({visibility: 'visible', opacity: 0})
			.mouseenter(function() {
				$(this).css('opacity', 1);
			})
			.mouseleave(function() {
				$(this).css('opacity', 0);
			})
			.click(function() {
				$(this).blur();
				var dir = $(this).attr('class');
				var thumb = g.data('thumb');
				var thumbs = g.data('thumbs');

				var old = thumb;
				thumb += dir == 'right' ? 1 : -1;
				g.data('thumb', thumb);

				g.galleryChange(old);

				return false;
			});

		g.find('.thumbs li').click(function() {
			if ($(this).hasClass('on')) return;
			var thumb = g.data('thumb');
			var thumbs = g.data('thumbs');

			var old = thumb;
			thumb = parseInt($(this).attr('class'), 10);
			g.data('thumb', thumb);

			g.galleryChange(old);
		});
	});
}
$.fn.galleryChange = function(old) {
	var g = $(this);
	var thumb = g.data('thumb');
	var thumbs = g.data('thumbs');
	var dir = thumb > old ? 'right' : 'left';

	g.find('.slide1 a:eq(0)').css('display', thumb == 0 ? 'none' : 'block');
	g.find('.slide1 a:eq(1)').css('display', thumb + 1 == thumbs ? 'none' : 'block');

	g.find('.thumbs li.' + old).removeClass('on').find('img').css('opacity', 1);
	g.find('.thumbs li.' + thumb).addClass('on').find('img').css('opacity', 0.4);

	var src = g.find('.thumbs li.' + thumb + ' img').attr('src').replace('_t', '');

	g.find('.slide1 img:last').css('zIndex', 0).animate({opacity: 0}, {duration: 500, queue: false});
	g.find('.slide1').append('<img src="' + src + '" style="margin-left: ' + (dir == 'right' ? 490 : -490) + 'px">');
	var img = g.find('.slide1 img:last');
		
	if (img[0].complete) {
		g.find('.slide1 .loading').css('display', 'none');
		img.animate({marginLeft: 0}, {
			duration: 1000,
			queue: false,
			complete: function() {
				if ($(this).next().length == 0)
					$(this).parent().css('backgroundImage', 'url(' + $(this).attr('src') + ')');
				$(this).remove();
			}
		});
	}
	else {
		g.find('.slide1 .loading').css({display: 'block', opacity: 0.5});
		img.load(function() {
			if ($(this).next().length > 0) return;
			$(this).parent().find('.loading').css('display', 'none');
			$(this).animate({marginLeft: 0}, {
				duration: 1000,
				queue: false,
				complete: function() {
					if ($(this).next().length == 0)
						$(this).parent().css('backgroundImage', 'url(' + $(this).attr('src') + ')');
					$(this).remove();
				}
			});
		});
	}

	return g;
}

$.preload = function() {
	var length = document.images.length;
	for (var i = 0; i < arguments.length; i++) {
		document.images[++length] = new Image();
		document.images[length].src = arguments[i];
	}
}

// survey support
$.fn.survey = function() {
	this.find('.scrollable').jScrollPane({showArrows: true, scrollbarWidth: 10});
}

// linen order form support
$.fn.linenOrder = function() {
	var parent = this;
	parent.find('.scrollable').jScrollPane({showArrows: true, scrollbarWidth: 10});

	this.find('a.add').click(function() {
		var table = $(this).parent().prev();
		var tr = table.find('tr:last');
		var trNew = tr.clone();
		tr.after(trNew);
		var trCount = table.find('tr').length;
		trNew.find('td:first').text((trCount - 2) + '.');
		trNew.find(':input')
			.attr('value', '')
			.each(function() {
				var name = $(this).attr('name');
				$(this).attr('name', name.replace(trCount - 4, trCount - 3));
			});

		$(this).blur().next().css('display', 'inline');
		parent.find('.scrollable').jScrollPane({showArrows: true, scrollbarWidth: 10});

		return false;
	});

	this.find('a.remove').click(function() {
		var table = $(this).parent().prev();
		var trCount = table.find('tr').length;
		if (trCount == 3) return false;

		table.find('tr:last').remove();

		$(this).blur()
		if (trCount == 4)
			$(this).css('display', 'none');
		parent.find('.scrollable').jScrollPane({showArrows: true, scrollbarWidth: 10});

		return false;
	});
}

// on dom ready stuff
$(function() {
	// deny right click
	$(document.body).rightClick(function() {alert('Attention! Copyrighted materials. Copyright infringement is punishable by law.');});

  // center content vertically
	$.vertCenter();
  $(window).resize(function() {$.vertCenter();});

  // menu and nav items hover
  $('#header .menu a').add('#nav a').hover(
    function() {
      if ($(this).hasClass('on')) return;
      var elem = $(this).children('span').length ? $(this).children('span') : $(this);
      elem.stop().animate({scrollTop: 12}, {duration: 100});
    },
    function() {
      if ($(this).hasClass('on')) return;
      var elem = $(this).children('span').length ? $(this).children('span') : $(this);
      elem.stop().animate({scrollTop: 0}, {duration: 500});
    }
  );

  // contact form
  $.contactForm();

	// leads form
	if ($("#leads-date").length > 0) {
		$("#leads-date").datepicker({minDate: new Date()});
		$("#leads-date").datepicker('hide');
	}

	// location
	$.locationOp();

	// galleries
	$('.gallery-cont').gallery();

	// survey
	$('#survey').survey();

	// survey
	$('#linen-order').linenOrder();

	// preload images
	$.preload('/images/scroll_track.gif', '/images/scroll_arr_up.gif', '/images/scroll_arr_down.gif', '/images/loading.gif');

	// generate another captcha validation code
	$('.captcha').dblclick(function() {
		var src = $(this).attr('src').replace(/\?.*$/, '') + '?' + (new Date()).getTime();
		$(this).parent().css('background', 'url(/images/captcha_loader.gif) 20px 10px no-repeat');
		$(this)
			.css('visibility', 'hidden')
			.attr('src', src)
			.load(function() { $(this).css('visibility', 'visible'); });
	});
});

// on load stuff
$(window).load(function() {
	// enable all internal photos
	$('.slide1').each(function() {
		if (!$(this).attr('lang')) return;
		$(this).css('backgroundImage', 'url(' + $(this).attr('lang') + ')');
	});
	$('.slide2 img').each(function() {
		if (!$(this).attr('lang')) return;
		$(this)
			.attr('src', $(this).attr('lang'))
			.load(function() {
				$(this).parent().css('backgroundImage', 'none');
			});
	});

  $.bottomMenuNav();

  if ($('#slideshow'))
    $.slideshow($('#slideshow'));

  $.mainNavSupport();
  if (mainHref && mainHref != '#')
    $.mainNavSupport.changeSlides('.' + mainHref.replace(/#\//, '').replace(/\//g, ' .'));

	// check changes in location hash
	setInterval(LocationHash.check, 100);
});

LocationHash = {};
LocationHash.current = null;
LocationHash.check = function() {
	var hash = location.href.replace(/^[^#]+#\//, '').replace(/\//g, ' .');
	if (hash && hash != this.current) {
		this.current = hash;
		$.mainNavSupport.changeSlides('.' + this.current);
	}
}

}