//preload the menu bg images
// preload the arrow hover images
$.each(['bg_nav_smaller_right_aligned.png','bg_nav_smaller_left_aligned.png'],function(i,e){
	new Image().src = ('/images/'+e);
});


$(function(){
	$('#main_nav').dropdownNav();
	
	$('#intro_slider').slider();
	$('#featured_news').newsFader();
	$('#client_list').logoSlider();
	$('.map').loadMap();
  if($('#mailer').length != 0) {
    $('#mailer').validate();
  }

  $('#login_form').flashMessage();

  //auto select contact form nature of request based on query
  $('#nature').preselectDropdown();

  $('#main_nav > li > a').each(function() { if($(this).attr('href').split('/')[1] == window.location.pathname.split('/')[1]) { $(this).parent('li').addClass('current'); }; });


  //  cbox
  if($('.lightbox a').length > 0) {
    $('.lightbox a').colorbox({
      opacity: .7
    });
  }
});

$.fn.preselectDropdown = function(){
  return this.each(function(){
    var search = window.location.search.slice(1);
    if (search.length) $(this).val(search);
  });
}

$.fn.dropdownNav = function(){
	return this.each(function(){
		// have to do it like this for IE7 compatibility :/
		var lis = $(this).children('li'), uls = lis.children('ul'), hiding;
		lis.mouseover(function(){
			lis.removeClass('over');
			uls.hide();
		}).children('ul').each(function(){
			var ul = $(this);
			var li = ul.parent();
			var overUl = false;
			var hide = function(){
				if (!overUl) {
					li.removeClass('over');
					ul.hide();
				}
			}
			li.mouseover(function(){
				li.addClass('over');
				ul.show();
			});
			li.mouseenter(function(){
				clearTimeout(hiding);
			}).mouseleave(function(){
				hiding = setTimeout(hide,500);
			});
			
			if ($.browser.msie && $.browser.version<8) {
				ul.show().css({
					top: ul.offset().top,
					left: ul.offset().left
				});
				if (li.is('#nav_resources,#nav_support')) {
					ul.find('a').css({backgroundImage: 'url(/images/bg_nav_smaller_right_aligned.png)'});
				}
				ul.appendTo('body').hide().mouseover(function(){
					overUl = true;
				}).mouseout(function(){
					overUl = false;
					hiding = setTimeout(hide,500);
				});
			}
		});
	});
}


$.fn.slider = function(){
	return this.each(function(){
		var container = $('#slides');
		var list = container.children('ul');
		var slides = list.children('li');
		var width = container.width();
		var links = $(this).find('a');
		var marker = $('<div id="nav_marker" />');
		var markerOffset = (links.first().width()/2)-marker.width()/2 + 13;
		var imageTicker;

		var slide = function(e){
			var currentPos = container.scrollLeft(), nextPos;
			e.preventDefault();
			if (!container.is(':animated')) {
				if (e.data.direction=='prev') {
					nextPos = currentPos==0 ? (slides.length-1)*width : currentPos-width;
				} else if (e.data.direction=='next') {
					nextPos = currentPos==(slides.length-1)*width ? 0 : currentPos+width;
				} else {
					nextPos = e.data.index*width;
				}
				container.animate({
					scrollLeft: nextPos
				},{
					queue: false,
					duration: 350,
					complete: function(){
						var images = slides.eq(Math.round(nextPos/width)).children('img,a');
						clearInterval(imageTicker);
						if (images.length>1) {
							imageTicker = setInterval(function(){
								var current = images.filter(':visible');
								var next = images.index(current)==(images.length-1) ? images.first() : current.next();
								current.fadeOut(300);
								next.fadeIn(300);
							},4500);
						}
					}
				});
				marker.animate({
					left: nextPos/links.length + markerOffset
				},{
					queue: false,
					duration: 350
				});
			}
		}
		
		list.width(slides.length*width);
		container.scrollLeft(0);
		
		marker.css({
			left: links.first().position().left + markerOffset
		}).appendTo(this);
		
		$('<button class="prev"><img src="/images/button_prev_large.png" alt="Previous slide" /></button>').bind('click',{direction:'prev'},slide).insertAfter(container);
		$('<button class="next"><img src="/images/button_next_large.png" alt="Next slide" /></button>').bind('click',{direction:'next'},slide).insertAfter(container);
		
		$(this).find('a').each(function(){
			var index = $(this).parent().data('index');
			$(this).bind('click',{index:index},slide);
		});
		
		// initialise all image tickers to first image
		slides.each(function(){
			$(this).children('img,a').not(':first').hide();
		});
	});
}


$.fn.newsFader = function(){
	return this.each(function(){
		var list = $(this).children('ul');
		var items = list.children('li');
		var markersList, markers;

		var fade = function(e){
			if(!list.is(':animated')) {
				var current = items.filter('.current'), next, index;
				e.preventDefault();
				
				if (e.data.direction == 'next') {
					next = current.is(':last-child') ? items.first() : current.next();
					index = items.index(next);
				} else if (e.data.direction == 'prev') {
					next = current.is(':first-child') ? items.last() : current.prev();
					index = items.index(next);
				} else {
					index = parseInt(e.data.direction,10);
					next = items.eq(index);
				}
				
				if (!current.is(next)) {
					current.fadeOut(150,function(){
						markers.removeClass('on').eq(index).addClass('on');
						current.removeClass('current');
						next.fadeIn(150).addClass('current');
					});
				}
			}
		}
		
		if (items.length>1) {
			items.first().addClass('current');
			items.not(':first').hide();
			$('<button class="prev"><img src="/images/button_prev.png" alt="Previous story" /></button>').bind('click',{direction:'prev'},fade).insertAfter(list);
			var markersList = $('<ol class="markers"></ol>').insertAfter(list);
			$('<button class="next"><img src="/images/button_next.png" alt="Next story" /></button>').bind('click',{direction:'next'},fade).insertAfter(list);
			
			items.each(function(i){
				var li = $('<li><a href="#" data-index="'+i+'">Story '+(i+1)+'</a></li>');
				li.children().bind('click',{direction:i},fade);
				if (i==0) li.addClass('on');
				li.appendTo(markersList);
			});
			markers = markersList.children();
		}
		
	});
}

$.fn.logoSlider = function(){
	return this.each(function(){
		var list = $(this).children();
		var ul = list.find('ul').randomize();
		var items = ul.children('li');
		
		var slide = function(e){
			if(!list.is(':animated')) {
				var currentScroll = list.scrollLeft();
				var scrollAmount = list.width();
				var itemsWidth = ul.width()/2;

				if (e.data.direction == 'next') {
					list.animate({scrollLeft: currentScroll+scrollAmount},{duration: 500, complete:function(){
						if (list.scrollLeft()>=itemsWidth) list.scrollLeft(list.scrollLeft()-itemsWidth);
					}});
				} else {
					list.animate({scrollLeft: currentScroll-scrollAmount},{duration: 500, complete:function(){
						if (list.scrollLeft()<=0) list.scrollLeft(itemsWidth);
					}});
				}
			}
		}
		
		if (items.length>4) {
			items.clone().appendTo(ul);
			items = ul.children('li');
			ul.width(items.first().width()*items.length);
			$('<button id="prev"><img src="/images/button_prev.png" alt="Previous clients" /></button>').bind('click',{direction:'prev'},slide).insertAfter(list);
			$('<button id="next"><img src="/images/button_next.png" alt="More clients" /></button>').bind('click',{direction:'next'},slide).insertAfter(list);
			list.scrollLeft(0);
		}
		
	});
}

$.fn.loadMap = function(){
	return this.each(function(){
		var container = $(this);
		var latlngValues = container.data('latlng').split(',');
		var latlng = new google.maps.LatLng(latlngValues[0],latlngValues[1]);
		var map = new google.maps.Map(container.get(0),{
			zoom: 14,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		});
		var marker = new google.maps.Marker({
			position: latlng, 
			map: map
		});
	});
}

$.fn.randomize = function() {
	return this.each(function() {
		var $this = $(this);
		var elems = $this.children();
		elems.sort(function() { return (Math.round(Math.random())-0.5); });  
		elems.detach();
		for(var i=0; i < elems.length; i++) {
			$this.append(elems[i]);
		}
	});
}

$.fn.flashMessage = function(){
  return this.each(function(){
    var form = $(this);
    var msg = $.cookie('flash');
    if (msg && msg.length){
      msg = $.parseJSON(msg);
      $.each(msg,function(key,value){
        $('<p class="flash '+key+'">'+value.replace(/\+/g,' ')+'</p>').prependTo(form);
      });
    }
  });
}

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
    

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


