// remove the "$" namespace from jQuery, avoids conflicts with other libraries
jQuery.noConflict();

// closure, mapping jQuery to $, window, document and undefined - useful for minifing tools
(function($, window, document, undefined){
    var $body,$win,$overlay,$modal;
    
function modalOpen(d, t, w, c)
{
	$overlay.show();
	$modal.find('.content').append(d.clone().removeClass('hide').show());
	$modal.find('h2').html(t);
	$modal.width(w - parseInt($modal.css('paddingLeft')) - parseInt($modal.css('paddingRight')));
	var h = $modal.outerHeight(),
		hw = $win.height(),
		css = {
			marginLeft: '-' + Math.round(w/2) + 'px'
		};
	if (h < hw) {
		css['marginTop'] = '-' + Math.round(h/2) + 'px';
		css['top'] = '50%';
	}
	$modal.css(css).removeClass('inactive').addClass(c);
	
    var lat = $modal.find(".lat").html(),
        lng = $modal.find(".lng").html(),
        div = $modal.find(".map");
    var store = new google.maps.LatLng(lat, lng);
    var myOptions = {
      zoom: 14,
      center: store,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(div[0], myOptions);
    
    var marker = new google.maps.Marker({
      position: store, 
      map: map, 
      animation: google.maps.Animation.DROP
    });  
    
}

function modalClose()
{
	$overlay.hide();
	$modal.find('.content').empty();
	$modal.attr('class', 'modal inactive');
}



// document ready method
$(function(){

    $body = $(document.body),
	$win = $(window),
	$overlay = $('<div id="overlay" class="hide"/>').appendTo($body),
    $modal = $('<div id="modal" class="modal inactive"><h2></h2><div class="content cf"></div><a href="#" class="close">Close</a></div>').appendTo($body);

    $modal.find('a.close').add($overlay).click(function(){
        modalClose();
        return false;
    });

	//Swap images on thumbnail click
	if(typeof(productImages) != "undefined") {
	jQuery('a.thumb').click(function (event) {
		setupImageLinks(jQuery(this));
		event.preventDefault();
	});
	
	function setupImageLinks(obj) {
		var imageId = jQuery(obj).find('img').attr('rel');
		if (!imageId) return;
		
		var largeImagePath = productImages[imageId]['lrg'];
		var extraLargeImagePath = productImages[imageId]['xlrg'];
		
		jQuery('.photo').find('img').attr('src', largeImagePath);
		jQuery('#lrg-image').attr('href', extraLargeImagePath);
		
	}
	
	setupImageLinks(jQuery('a.thumb')[0])
	
	}
	
	/*
	//Show sizing chart
	function showSizingChart() {
		jQuery('#sizing-chart').show();
		jQuery('#product').hide();
	}
	
	function hideSizingChart() {
		jQuery('#sizing-chart').hide();
		jQuery('#product').show();
	}
	
	
	jQuery('.product-options label.help').click(function(event) {
		showSizingChart();
	});
	
	jQuery('a#closebutton').click(function(event) {
	event.preventDefault();
		hideSizingChart();
	});
	*/
	
	//Use FancyBox for lightbox product image
	jQuery('#lrg-image').fancybox({padding  : 30});
	jQuery('#sizing-chart-link').fancybox({padding : 30});


	
	

    $("#cart .trigger").hover(function() {
        if ($(this).find(".popup").length) {
            $(this).addClass("hover");
            $(this).stop().find(".popup").show();
        }
    },function() {
        $(this).removeClass("hover");
        $(this).stop().find(".popup").hide();
    });

	if ($.fn.selects)
	{
		/*$('#currency').selects({
			markup: '<a class="trigger" href="#"><span></span></a><div class="popup"><ul></ul></div>'
		}).bind('selectOpening', function(){
			return 2;
		}).each(function(){
			$(this).parent().find('.trigger span').html(this.options[this.selectedIndex].text + ' <em>Change currency</em>');
		}).bind('selectClosed', function(ev, sel, parent, i, item){
			parent.find('.trigger span').html(item.innerHTML + ' <em>Change currency</em>');
		});*/

		/*$('#container .select-1').selects({
			skipFirst: true
		}).bind('selectOpening', function(){
			return 2;
		});*/
        $('.option select').selects({
			skipFirst: true,
			className: "select-1"
		}).bind('selectOpening', function(){
			return 2;
		});
		$("#colour").bind("change selectClosed",function(ev, sel, parent, i, item) {
            window.location = $(this).find("option").eq(this.selectedIndex).attr("rel");
        });

	}


	if ($.fn.boxLinks)
	{
		$('#side1 .callout').boxLinks();
	}


	$overlay.height($body.height());


	var find = $('#store-find');
	if (find.length)
	{
		var list = find.find('.states a'),
			map = find.find('.map'),
			states = map.find('li');

		list.hover(function(){
			map.addClass('map-' + $(this).data('state'));
		}, function(){
			map[0].className = 'map';
		});
		states.hover(function(){
			map.addClass('map-hover map-' + this.className);
		}, function(){
			map[0].className = 'map';
		});
	}


	$('#store-results td').click(function(){
		var tr = $(this.parentNode), a = tr.find('a');
		if (a[0].hash.length > 1) {
			modalOpen($(a[0].hash), tr.find('td').eq(0).html(), 1000);
		}
		return false;
	});


});

// plugins


// selects plugin helper
$.selects = {
	zIndex: 99,
	timer: null,
	cancelTimer: function()
	{
		if ($.selects.timer)
		{
			clearTimeout($.selects.timer);
			$.selects.timer = null;
		}
	},
	setTimer: function(parent, active)
	{
		$.selects.timer = setTimeout(function(){
			parent.removeClass(active);
		}, 150);
	},
	height: function(ul, max)
	{
		setTimeout(function(){
			if (ul.height() > max)
				ul.addClass('scroll').css('height', max);
		}, 10);
	}
};

// selects - jQuery plugin - creates custom select elements from <select> elements - by Valentin Agachi http://agachi.name
$.fn.selects = function(args)
{
	if (!this.length) return this;

	var opts = $.extend({
			className: '',
			markup: '<a class="trigger" href="#"><span></span></a><div class="popup"><ul></ul></div>',
			skipFirst: false,
			maxHeight: 0
		}, args || {});

	return this.each(function(){
		var sel = $(this), 
			type = opts.className.length ? opts.className : this.className.split(' ')[0],
			actives = ['custom-select-active', type + '-active'],
			active = actives.join(' ');

		sel.hide().wrap('<div class="custom-select select-' + sel[0].name + ' ' + type + ' cf"></div>');

		var parent = sel.parent().css({ zIndex: $.selects.zIndex-- }).append(opts.markup),
			trigger = parent.find('.trigger'), popup = parent.find('.popup'), ul = parent.find('ul'),
			i = opts.skipFirst ? 1 : 0, s = '';

		for (; i < this.options.length; i++)
			s += '<li><a href="#" id="' + sel[0].name + '-' + i + '">' + this.options[i].text + '</a></li>';
		ul.append(s);

		if (opts.maxHeight)
			$.selects.height(ul, opts.maxHeight);
		
		if (parent.find("option").length > 1) {
            trigger.click(function(){
                $('.' + actives[0]).removeClass(active);
                var d = sel.triggerHandler('selectOpening', [sel, parent]) || 0;
                popup.width(trigger.outerWidth() - d);
                parent.toggleClass(active);
                return false;
            });
        } else {
            parent.addClass("select-1-disabled");
            trigger.attr("title",$(this).find("option").html());
            trigger.click(function(){
                return false;
            });
        }
        
        trigger.find('span').html(this.options[this.selectedIndex].text);
        
		popup.width(trigger.outerWidth());

		$(trigger).add(popup).hover(function(){
			if (parent.hasClass(actives[0]))
				$.selects.cancelTimer();
		}, function(){
			$.selects.setTimer(parent, active);
		});

		sel.bind('selectActive', function(ev, i){
			sel[0].selectedIndex = i;
			trigger.focus().find('span').html(ul.find('a:eq(' + ( opts.skipFirst ? i - 1 : i ) + ')').html());
			parent.removeClass(active);
		});

		ul.find('a').click(function(){
			var i = parseInt(this.id.split('-')[1]);
			sel.triggerHandler('selectActive', [i]);
			sel.triggerHandler('selectClosed', [sel, parent, i, this]);
			return false;
		});
	});
};



// boxLinks - jQuery plugin - transforms block elements into clickable items - by Valentin Agachi http://agachi.name
$.fn.boxLinks = function(args)
{
	if (!this.length) return this;

	var opts = $.extend({
		trigger: 'a',
		classHover: 'hover',
		classFocus: 'focus',
		onEnter: null,
		onLeave: null,
		onClick: function(){
			window.location = $(this).attr('href');
		}
	}, args || {});

	this.has(opts.trigger)
		.each(function(){
			var self = $(this), t = self.css('cursor', 'pointer').find(opts.trigger);
			$.data(this, 'trigger', t);		
			$.data(t[0], 'parent', self);
		}).bind('mouseenter', function(){
			var t = $.data(this, 'trigger'), self = $(this).addClass(opts.classHover);
			opts.onEnter && opts.onEnter(self);
			window.status = t.attr('href');
		}).bind('mouseleave', function(){
			var self = $(this).removeClass(opts.classHover);
			opts.onLeave && opts.onLeave(self);
			window.status = '';
		}).bind('click', function(ev){
			var t = $.data(this, 'trigger');
			t.trigger('click');
			ev.stopPropagation();
			return false;
		});

	this.find(opts.trigger).addClass('trigger')
		.bind('focus', function(){
			var p = $.data(this, 'parent');
			p.addClass(opts.classFocus);
		}).bind('blur', function(){
			var p = $.data(this, 'parent');
			p.removeClass(opts.classFocus);
		}).click(function(ev){
			opts.onClick.apply(this);
			ev.stopPropagation();
			return false;
		});

	this.find('a').not(opts.trigger).click(function(ev){
		ev.stopPropagation();
	});

	return this;
};


function setupHome() {
	
	$("#home .item").bind("mouseover", function() {
		$("#home .item").stop().fadeTo(250, 0.7);
		$(this).stop().fadeTo(250, 1);
	});
	
	$("#home .item").bind("mouseout", function() {
		$("#home .item").stop().fadeTo(250, 1);
	});
	
}

function setupMenu() {
	
	var slideDown = false;
	var timer;
	
	$("#menu .dropdown a").bind({
		mouseover: function(e) {
			e.stopImmediatePropagation();
		},
		mouseout: function(e) {
			e.stopImmediatePropagation();
		}		
	});
	
	$("#menu .dropdown").css("left", "-10px").hide();
	$("#menu li:hover .dropdown").css("left", "-10px");
	
	$("#menu .level0").hover(function(e) {
		e.stopImmediatePropagation();
		clearInterval(timer);
		$(this).children(".dropdown").css("z-index", 10);
		if(!slideDown) {
			$(this).children(".dropdown").slideDown(250, function() {
				slideDown = true;
				$(this).children().animate({"opacity": 1}, 250);
			});
		} else {
			$(".dropdown").hide();
			$(this).children(".dropdown").show().children().animate({"opacity": 1}, 0);
		}
	}, function(e) {
		e.stopImmediatePropagation();
		timer = setInterval(function() {
			$(".dropdown").slideUp(250, function() {
				$(this).children().animate({"opacity": 0}, 0);
				slideDown = false;
			});
		},500);
	});
	
}

if($("#home").length) setupHome();
if($("#menu").length && $("body.windsor").length) setupMenu();

})(jQuery, window, document);

