/**
 * Resizes floated image containers to the size of the image
 */
$.fn.imageWidth = function(threshold) {
	/**
	 * Function takes a jquery object and a css property (called dimension) and determines how many pixels the item is
	 * @param {jQuery Object} $item The jQuery object we're looking at
	 * @param {String} dimension The CSS property name to look for
	 * @returns The width or height of the CSS property with 'px' removed
	 * @type Number
	 */
	var	determineDimension = function($item, dimension) {
		$item = $($item);
		if ($item.css(dimension)) {
			return parseInt($item.css(dimension).replace('px', ''), 10);
		} else {
			return 0;
		};
		return false;
	};
	
	var	resizeImage = function($image, $parent, $container) {
		// Determine the width of the image along with borders and padding
		var imageWidth = $image.width();
		var paddingLeft = determineDimension($image, 'padding-left');
		var paddingRight = determineDimension($image, 'padding-right');
		var borderLeft = determineDimension($image, 'border-left');
		var borderRight = determineDimension($image, 'border-right');
		
		// Calculate total edge (padding and border) width and the total width (edge and image)
		var edgeWidth = parseInt(paddingLeft + paddingRight + borderLeft + borderRight);
		var totalWidth = imageWidth + edgeWidth;

		// Determine parent width
		var parentWidth = $parent.width();

		// If the image is greater then the threshold times the parent width resize the image and the container width
		// Otherwise set the image left's div to the size of the image plus the edge
		if ((threshold * parentWidth) <= totalWidth) {
			var revisedWidth = parentWidth * threshold;
			var revisedImageWidth = revisedWidth - edgeWidth;

			$image.width(revisedImageWidth);
			$container.width(parseInt(revisedWidth, 10));
		} else {
			$container.width(totalWidth);
		};
	};

	return this.each(function() {
		// Threshold is the maximum width an image plus its border and padding can be 
		// in relation to its parent container
		var threshold = (threshold) ? threshold : 2/3;

		// Find image within div
		var $image = $('img', $(this));
		var $parent = $(this).parent();
		var $container = $(this);

		$image.each(function(index) {
			resizeImage($image, $parent, $container);
			$(this).load(function() {			
				resizeImage($image, $parent, $container);
			});
		});
	});		
};

/**
 *  Get the outer html of the selected element
*/
$.fn.outerHTML = function() {
  return $(this).clone().wrap('<div></div>').parent().html();
}


/**
 * Calculates the height of a blockquote and adds appropriate bottom margin
 * to <span>"</span>.
 */
$.fn.add_quote_margin = function () {
	return this.each(function () {
		var blockquote_height = $(this).parents('blockquote').height();
		$(this).css('margin-bottom', blockquote_height+'px');
	});
}

/**
 * Makes all children with the selected container the same height.
 * Uses min-height, except for IE6 where height is used instead.
 */
$.fn.same_height = function() {
	return this.each(function() {
		tallest_height = 0;
		
		$(this).children().each(function(index) {
			tallest_height = ($(this).height() > tallest_height) ? $(this).height() : tallest_height;
		});
		
		if ($.browser.msie == true && $.browser.version <= 6) {
			$(this).children().css('height', tallest_height);
		} else {
			$(this).children().css('min-height', tallest_height);
		};
	});		
};

/**
 * Makes the placeholder attribute on input items useful by emulating the behavior
 */ 
var placeholder = function() {
		
	if ('placeholder' in document.createElement('input')) return this;
	
	$('#header input[placeholder]').each(function(index) {
		
		$(this).val($(this).attr('placeholder')).addClass('placeholder active')
			.focus(function() {
				if ($(this).val() === $(this).attr('placeholder')) {
			        $(this).val('').removeClass('placeholder active');
				}
			})
			.blur(function() {
				if ($(this).val() === ''){
					$(this).val($(this).attr('placeholder')).addClass('placeholder active');
				}
			});
	});
};


/**
 *  Sets up page transitions for the /learn page
 */ 
var _chooseAccordionSection = function() {
	var target = window.location.hash.replace('#', '');	
	var $targetSection = $('div.learn-about-group.' + target).find('div.intro');
	
	//console.log('target: "' + target + '"');
	
	$targetSection = (target.length ? $targetSection : $('#section > .learn-about-group:first').find('div.intro')); //default to the top section if no hash tag is defined
		
	_openAccordionSection($targetSection);
}


/*
	Opens an accordion section on the /learn page
*/
var _openAccordionSection = function($elem){
	
	//special margins for each section
	//pearls, metals, watches, colored-gemstones, bridal, diamonds
	var margins = [0, 10, 24, 2, 0, 0];
	
	var $siblings = $elem.parents('div.learn-about-group').siblings('div.learn-about-group:has(.content:visible)');
	var $content = $elem.siblings('div.content:first');
	var $tab = $elem.find('img.tab:first');
	var $dropShadow = $content.find('div.mid:first');
	var $bottomShadow = $('div.bottom-shadow');
	
	if ($content.is(':hidden')){
		//hide all other sections
		$siblings.find('div.mid:first, img.tab, div.bottom-shadow').animate({opacity:'0.0'}, 'slow');
		
		// special margins for each sibling section (based on header overflow)
		$siblings.filter('.pearls').animate({'margin-bottom':'-=' + margins[0]}, 'slow');
		$siblings.filter('.metals').animate({'margin-bottom':'-=' + margins[1]}, 'slow');
		$siblings.filter('.watches').animate({'margin-bottom':'-=' + margins[2]}, 'slow');
		$siblings.filter('.colored-gemstones').animate({'margin-bottom':'-=' + margins[3]}, 'slow');
		$siblings.filter('.bridal').animate({'margin-bottom':'-=' + margins[4]}, 'slow');
		$siblings.filter('.diamonds').animate({'margin-bottom':'-=' + margins[5]}, 'slow');
		//end special margins
		
		//fade the content out and slide it up
		$siblings.find('div.content').animate({height:'hide', opacity:'0'}, 'slow', function(){
			//callback for slide up
			$siblings.find('span.show-hide-hint').text('Expand').removeClass('active');
		});
		
		// special margins for this section (based on header overflow)
		$elem.parents('div.pearls').animate({'margin-bottom':'+=' + margins[0]}, 'slow');
		$elem.parents('div.metals').animate({'margin-bottom':'+=' + margins[1]}, 'slow');
		$elem.parents('div.watches').animate({'margin-bottom':'+=' + margins[2]}, 'slow');
		$elem.parents('div.colored-gemstones').animate({'margin-bottom':'+=' + margins[3]}, 'slow');
		$elem.parents('div.bridal').animate({'margin-bottom':'+=' + margins[4]}, 'slow');
		$elem.parents('div.diamonds').animate({'margin-bottom':'+=' + margins[5]}, 'slow');
		//end special margins
		
		//slide down and fade this content in
		$dropShadow.add($bottomShadow).animate({opacity:'1.0'}, 'slow');
		$tab.animate({opacity:'1.0'}, 'slow');
		$content.animate({opacity:'1.0', height:'show'}, 'slow', function(){
			//callback for slide down
			$elem.find('span.show-hide-hint').text('Collapse').addClass('active');
		});
		
	} //if
	else {
		
		// special margins for this section (based on header overflow)
		$elem.parents('div.pearls').animate({'margin-bottom':'-=' + margins[0]}, 'slow');
		$elem.parents('div.metals').animate({'margin-bottom':'-=' + margins[1]}, 'slow');
		$elem.parents('div.watches').animate({'margin-bottom':'-=' + margins[2]}, 'slow');
		$elem.parents('div.colored-gemstones').animate({'margin-bottom':'-=' + margins[3]}, 'slow');
		$elem.parents('div.bridal').animate({'margin-bottom':'-=' + margins[4]}, 'slow');
		$elem.parents('div.diamonds').animate({'margin-bottom':'-=' + margins[5]}, 'slow');
		//end special margins
		
		$content.animate({height:'hide', opacity: '0'}, 'slow', function(){
			//callback for slide up
			$elem.find('span.show-hide-hint').text('Expand').removeClass('active');
		});
		$dropShadow.add($bottomShadow).add($tab).animate({opacity:'0.0'}, 'slow');
	} //else
	
}

/**
 *  Sets up page transitions for the /learn page
 */ 
var learnPageAccordion = function() {
	
	//if this isn't the learn page, don't bother doing anything else
	if ( ! $('body.learn').length) return;
	
	//determine which section of the accordion should be open initially, then open it
	_chooseAccordionSection();
	
	//css for hover effect
	$('div.intro').hover(function(){
		$(this).css({'cursor':'pointer'});
	},function(){
		//
	}).click(function(e){
		e.preventDefault();
		
		_openAccordionSection($(this));

	});
	
};

/*
	Helper function for the Google Map filtering on the store search page.
	Removes and adds markers to the map based on what has been selected in the filter section
*/
var _filterLocations = function(){
	var filters = _findActiveFilters();
	var displayMe = false;
	var visibleLocations = 0;
	
	if ( ! filters.length) //no active filters, so show all markers
		_showAllMarkers();
	else { //there are active filters, so only display the matching markers
		for (var i = 0; i < window.allMarkers.length; i++) { //for each marker...
			for (var j = 0; j < window.allMarkers[i].designers.length && ! displayMe; j++){ //for each marker's associated designers...
				if ($.inArray(window.allMarkers[i].designers[j], filters) >= 0){ //check to see if the current marker should be shown based on the current active filters
				
					displayMe = true; //set the match boolean
					visibleLocations++;
					window.allMarkers[i].marker.setMap(window.map); //show the marker
				
				} //if
			} //for
		
			if ( ! displayMe)
				window.allMarkers[i].marker.setMap(null); //no designer match, so remove the marker
			
			displayMe = false; //reset flag for next iteration
		} //for
	} //else

	if (visibleLocations)
		$('#filter-result-count').text(visibleLocations + ' location' + (visibleLocations == 1 ? '' : 's') + ' found. ');
	else if ( filters.length && ! visibleLocations) //if there are no active filters to display
		$('#filter-result-count').text('No locations carry the selected designer' + (filters.length == 1 ? '' : 's') + '. ');
	else if ( ! filters.length)
		$('#filter-result-count').text('');
		
}

/*
	Returns an array of arrays = where result[i] = url_title of active filter
*/
var _findActiveFilters = function(){
	
	var result = new Array();
	
	$('#sub li.active a').each(function(){		
		result.push($(this).attr('data-filter'));
	});
	
	return result;
	
}


/*
	Removes all markers from the map
*/
var _clearMarkers = function() {
	for (var i = 0; i < window.allMarkers.length; i++)
		window.allMarkers[i].marker.setMap(null);
}

/*
	Clears away all active filters
*/
var _clearFilters = function(){
	//remove all "active" filters
	$('#sub div.panes li').removeClass('active');
	
	_showAllMarkers();
}

/*
	Shows all markers
*/
var _showAllMarkers = function() {
	for (var i = 0; i < window.allMarkers.length; i++)
		window.allMarkers[i].marker.setMap(window.map);
}

/*
	Helper function for the Google Map setup.
	Requests all markers needed and adds them to the map already created on the page.
	
	reset: whether to place all markers, or only place filtered markers
*/
var _placeMapMarkers = function(result){

	var last_window = new google.maps.InfoWindow();
	var icon = new google.maps.MarkerImage('/images/layout/map-marker.png', new google.maps.Size(30,45));
	
	//remove all existing markers from the map
	if (window.allMarkers)
		_clearMarkers();
	
	//reset the allMarkers array
	window.allMarkers = [];
	
	//set the map's center
	window.map.setCenter(new google.maps.LatLng(result.map_center.lat, result.map_center.lng));
	
	$.each(result.locations, function(index, i) {
		
		var title = i.title.replace(/\+/g, ' ');
		var my_position = new google.maps.LatLng(i.latitude, i.longitude);
		
		var infowindow = new google.maps.InfoWindow({
		    content: '<div class="infowindow"><h4><a href="/locations/detail/' +
		    	i.url_title + '">'  + title +  '</a></h4>' + '<p>' +
		    	(i.city != '' ? i.city + ', ' : '') + i.state + '<br>' + i.phone + '<a href="mailto:' + i.email + '">' + i.email + '</a>' + '<br></p>' + 
				'<ul><li><a href="/locations/detail/' + i.url_title + '">Discover <strong>events</strong>, <strong>designers</strong> we carry, and more about this store.</a></li>'
				+ '<li><a href="http://maps.google.com/maps?q=' + i.latitude + ',' + i.longitude + '+(' + i.title + ')&z=14&ll=' + i.latitude + ',' + i.longitude + '">Get directions</a></li></ul>'
				+ '</div>',
			maxWidth: 270
		});
		
		var marker = new google.maps.Marker({
		    position: my_position, 
		    map: window.map, 
		    title: title,
			icon: icon
		});
		
		window.allMarkers.push({
			marker: marker,
			designers: i.designers
		});
		
		google.maps.event.addListener(marker, 'click', function() {
			last_window.close();
			infowindow.open(map, marker);
			last_window = infowindow;
		});
		
	}); //each
	
}

/*
	Sets up the Google Map for the locations search page
*/
var locationsMap = function(tabs_api){
	
	//prevent all the following code from running for any other page
	if ( ! $('body.locations').length) return;
	
	var latlng = new google.maps.LatLng(37.3570894, -78.8252911);
	var myOptions = {
		zoom: 7,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	//set up the Google map
	window.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	$.ajax({
		url: '/helpers/_location-data',
		dataType: 'json',
		type: 'GET',
		success: function(result){
			_placeMapMarkers(result);
			
			_filterByHash(tabs_api);
			
			_filterLocations();
			
			//set up click handlers for right-hand filters
			$('#sub div.panes a').click(function(e){
				e.preventDefault();

				$(this).parent('li').toggleClass('active'); //activate this filter
				_filterLocations(); //refresh the markers on the map
			});
		} //fn
	}); //ajax
	
	
	/*
		Remove all filters from the map
	*/
	$('#remove-designer-filter').click(function(e){
		e.preventDefault();
		
		$('#filter-result-count').text('');
		
		_clearFilters();
	});

}


/*
	filters map markers if a hash value exists
*/
var _filterByHash = function(tabs_api){
	//if there's a designer url title available as a hash tag, filter the map accordingly
	var hash = location.hash.replace('#', '');
	if ( ! hash.length) return;
	
	var hash_sections = hash.split('_'); //format: designer_type+url_title
	
	//check to see if there's a designer type specified in the hash
	if (hash_sections.length == 2){
		var hash_filter = hash_sections[1];
		
		//switch the tabs to the appropriate designer category
		switch (hash_sections[0]){
			case 'jewelry':
				tabs_api.click(0);
			break;
			case 'bridal':
				tabs_api.click(1);
			break;
			case 'watch':
				tabs_api.click(2);
			break;
		}
	} //if
	else {
		var hash_filter = hash_sections[0];
	} //else
		
	$('#sub div.panes a[data-filter="' + hash_filter + '"]').parent('li').addClass('active');
}


/*
	Sets up the store location search form functionality
*/
var locationsSearch = function() {
	
	//if not locations page, don't even bother
	if ( ! $('body.locations').length) return;
	
	$('#store_search_glass').click(function(e){
		formAction(e);
	});
	
	$('#store_search').keypress(function(e){
		if (e.keyCode == 13) // "Enter"
			formAction(e);
	});
	
	var formAction = function(e) {
		e.preventDefault();
		var originalVal = $('#store_search').val();
		
		$.post(
			'/helpers/_location-search',
			{query: originalVal},
			function(result){
				
				//re-place markers with new data	
				_placeMapMarkers(result);
				
				//filter the markers based on what filters have been selected
				_filterLocations();
				
				//zoom map in
				window.map.setZoom(10);
				
				$('#store_search_results').text('The nearest location is  ' + result.nearest_location_distance + ' mile' + (result.nearest_location_distance == 1 ? '' : 's') + ' away.');
			},
			'json'
		);
	}
}


var shortenLink = function(full_url){
	
	//shorten the URL through bit.ly's API
	var apiKey = 'R_6497f45f47e712f275d1412e5788238c';
	var login = 'newc1ty';
	var url = full_url;
	
	var return_url = full_url;
	
	$.ajax({
		url: 'http://api.bitly.com/v3/shorten?login=' + login + '&apiKey=' + apiKey + '&longUrl='  + url + '&format=json',
		type: 'GET',
		dataType: 'json',
		statusCode: {
			200: function(short){
				return short.data.url;
			},
			500: function(){ //error getting shortened URL
				return '';
			}
		}
	});

}

/*
	Sets up click listeners and the content for the social media icons in the footer
*/
var footerTooltips = {
	
	/*
		Position footer tooltips based on their height after content goes in
	*/
	setTooltipPositions: function($tooltips){
		$tooltips.each(function(){
			$(this).css({'top':- ($(this).height() + 65)});
		});
	},
	
	/**
	 * Insert the Facebook feed into the FB tooltip
	 * This is called from newcity.js on store.finks.com 
	 * and facebook.js on finks.com
	*/
	insertFacebookFeed: function(result){
		//we only care about the top result
		result = result[0];
		
		$('#footer span.facebook.social-media').each(function(){
			
			$elem = $(this);
			shortenMe = '';
			
			if (result.type == 'photo'){
				shortenMe = result.link;
			}
			else{
				shortenMe = 'http://www.facebook.com/FinksJewelers/posts/' + result.id.split('_')[1]; //get the post ID from the concatinated id
			}
			
			$elem.find('span.content').html(result.message);
			
			//shorten the URL through bit.ly's API
			apiKey = 'R_6497f45f47e712f275d1412e5788238c';
			login = 'newc1ty';

			$.ajax({
				url: 'http://api.bitly.com/v3/shorten?login=' + login + '&apiKey=' + apiKey + '&longUrl='  + shortenMe + '&format=json',
				type: 'GET',
				dataType: 'json',
				statusCode: {
					200: function(short){
						if (short.data.url.length)
							$elem.find('span.content').append('<br><a href="' + short.data.url + '" target="_blank">More on Facebook</a>');
						
						footerTooltips.setTooltipPositions($elem.find('.social-media-tooltip'));
					},
					500: function(){ //error getting shortened URL
						$elem.find('span.content').append('<br><a href="' + shortenMe + '" target="_blank">More on Facebook</a>');
						
						footerTooltips.setTooltipPositions($elem.find('.social-media-tooltip'));
					}
				}
			});
			
			$elem.find('span.date-time').html(result.created_time + ' <a href="http://www.facebook.com/FinksJewelers" style="position:absolute;top:0pt;width:125px;right:-162px;">Follow Us on Facebook</a>');

		}); //each
		
		footerTooltips.setTooltipPositions($('#footer span.social-media-tooltip'));
	},
	
	/*
		Insert the top tweet into the Twitter tooltip
	*/
	insertTwitterFeed: function () {
		var url = "http://twitter.com/status/user_timeline/FinksJewelers.json?count=1&callback=?";
		$.getJSON(url, function(data){

			$.each(data, function(i, item) {

				date = Date.parse(item.created_at);			
				gmtHours = -date.getTimezoneOffset() / 60;
				date = date.add(gmtHours).hours();

				$("#footer span.twitter span.content").html(linkify(item.text));
				$('#footer span.twitter span.date-time').html(date.toString('h:mm tt MMM d') + ' <a href="http://www.twitter.com/FinksJewelers" style="position:absolute;top:0pt;width:110px;right:-155px;">Follow Us on Twitter</a>');

				footerTooltips.setTooltipPositions($('#footer span.social-media-tooltip'));
		    }); //each
		});
		
	},
	
	/**
	 * show the tooltip when a social media icon is clicked and
	 * hide the tooltip when the "close" X is clicked
	*/
	toggleTooltip: function () {
		
		//show
		$('#footer span.social-media').click(function(e){
			$(this).find('span.social-media-tooltip').css({'display':'block'});
			$(this).siblings('span.social-media').find('span.social-media-tooltip').css({'display':'none'});
		});
		
		//hide
		$('#footer span.social-media a.close').click(function(e){
			$(this).parents('span.social-media').find('span.social-media-tooltip').css({'display':'none'});

			return false; // returning false to prevent it from being shown again on this click
		});
		
	},
	
	init: function () {
		this.toggleTooltip();
		this.insertTwitterFeed();
	}
}


/*
	Fade photos on click for location detail page
*/
var locationDetailPhotos = function(){
	
	//ignore if not on the store detail page
	if ( ! $('body.store-detail').length) return;
	
	$('ul.photo-box li a').click(function(){
		
		var rel = $(this).attr('rel');
		
		$('div.photo-box > img:not(#' + rel + ')').stop().animate({opacity:0}, 500);
		$('#' + rel).stop().animate({opacity:1}, 500);
		
	});
}


/*
	Populate the Twitter feed box on the store detail pages
*/
var locationDetailTwitter = function(){
	
	//ignore if not on store detial page
	if ( ! $('body.store-detail').length) return;
	
	var $wrapper = $('div.social-media-quote.twttr');
	var $content_wrapper = $('> div p:first', $wrapper);
	var $date_time = $('p.quiet', $wrapper);
	
	//console.log(.html());
	var handle = $('span.handle a', $wrapper).text().replace(':', ''); //get the twitter handle and remove the trailing colon
	var url = "http://twitter.com/status/user_timeline/" + handle + ".json?count=1&callback=?";
	
	$.getJSON(url, function(data){
		
		$.each(data, function(i, item) {
			
			date = Date.parse(item.created_at);			
			gmtHours = -date.getTimezoneOffset() / 60;
			date = date.add(gmtHours).hours();
			
			$content_wrapper.append(linkify(item.text));
			$date_time.text(date.toString('h:mm tt MMM d') + ' via Twitter');

	    }); //each
	
	});
}

/*
	Locaiton detail Facebook feed
*/
//insert the Facebook feed into the FB tooltip
var locationDetailFacebook = function(){
	
	if ( ! $('body.store-detail').length) return;
	
	var $elem = $('div.social-media-quote.fb');
	
	//get the url_title of the current page
	var last_segment = window.location.pathname.substr(window.location.pathname.lastIndexOf('/') + 1);
	
	//insert the Facebook feed into the FB tooltip
	$.ajax({
		url: '/helpers/_top-fb-post/' + last_segment,
		dataType: 'json',
		type: 'POST',
		success: function(result){
						
			//we only care about the top result
			var result = result[0];
			var post_id = result.id.split('_')[1];
			var $handle_anchor = $elem.find('a.handle');
			
			$handle_anchor.attr('href', $handle_anchor.attr('href') + '/posts/' + post_id);
			$elem.find('p:first').append(result.message);
			$elem.find('p.quiet').text(result.created_time + ' via Facebook');

		} //fn
	}); //ajax
	
}

var designerDetailLayout = function(){
	
	if ( ! $('body.designer').length) return;
	
	var $img_column = $('#section-top .designer-image-column');
	
	//set the height of the image column so it doesn't wrap
	//$img_column.height(Math.max($('#section-top div.story-text').height(), $img_column.height()) + 0);
	
	//set the width of the text column based on the image width next to it
	//525 is the total width allowed for the column, 29 is the right-hand padding of the image column
	$('#section-top .story-text').width(525 - 29 - $('#section-top .designer-image-column').width());
	
}

/*
	Set up the listeners for the gray dropdown
*/
var dropdown = function () {
	
	$('a.dropdown-link, div.dropdown-content').hover(function(){
		$(this).siblings('a.dropdown-link, div.dropdown-content').andSelf().addClass('active');
		$('div.dropdown-wrap').css({'height':'255px'});
	},function(){
		$(this).siblings('a.dropdown-link, div.dropdown-content').andSelf().removeClass('active');
		$('div.dropdown-wrap').css({'height':'25px'});
	});
}
	
/**
 * Adds the class 'last' and 'first' to the last list items, and the last table item in a row. 
 * Also adds alt class to odd table rows.
 */
var markupPrep = function() {
	var listPrep = function() {
		$('> li:last', 'ul, ol').addClass('last');
		$('> li:first', 'ul, ol').addClass('first');
	};	

	var	tablePrep = function() {
		$('table tr:odd').addClass('alt');
		$('table td:last, table th:last').addClass('last');
	};

	listPrep();
	tablePrep();
}

var scrollableSlideShow = function () {
	if ($('#slide-show .scrollable li').length > 1) {
		$('#slide-show .scrollable').scrollable({
			'circular': false, 
			'keyboard': true
		}).navigator({
			'navi': '#slide-controls'
		}).autoscroll({
			'autoplay': true,
			'interval': 10000
		});
	}
}

var articleSidebar = function(){
	
	var $list = $('#sub ul.related-articles');
	var $elem = null;
	
	$('> li:first', $list).addClass('active');
	
	$list.find('> li > a').click(function(e){
		e.preventDefault();
		
		$elem = $(this).parent('li:first');
		$elem.find('ul').slideToggle('fast', function(){
			if ($elem.is('.active')) {
				$elem.removeClass('active');
			}
			else {
				$elem.addClass('active');
			}
		});
		
	});
	
}

/*
	Handle the click action on a look slideshow image
*/
var lookSlideshowClick = function(){
	
	$('#slide-show').bind('click mousemove', function(e){		
		var x = e.pageX;
		var y = e.pageY;
	
		// X : 64 through 697
		// Y : 115 through 420
		
		//determine if click was inside the slideshow box where the image is displayed
		var inBox = x >= 64 && x <= 770 && y >= 115 && y <= 420;
		
		//set the cursor to indicate a clickable region based on where the mouse is
		if (inBox)
			$(this).css({cursor:"pointer"});
		else
			$(this).css({cursor:"default"});
			
		//box was clicked, so relocate the page to the appropriate target URI
		if (e.type == "click"){
			
			//find out which slide is currently active by dividing the UL's left margin by slide width
			var activeSlide = -parseInt($('#slide-show ul.slides').css('left').replace('px', '')) / 736;
			
			activeSlide += 1; //add plus 1, because jQuery starts indexing at 1 not 0
			
			var newURL = $('#slide-show ul.slides li:nth-child(' + activeSlide + ')').find('> a').attr('href');
			
			//only redirect if one of the correct elements were clicked
			if ($(e.target).is('img, div.nav') && ! $(this).parents('#slide-controls').length){
				e.preventDefault();
				window.location = newURL;
			} //if
		} //if
			
	});
	
}

$(document).ready(function() {
	placeholder();
	footerTooltips.init();
	learnPageAccordion();
	dropdown();
	
	locationDetailPhotos(); //store detail image gallery
	locationDetailTwitter(); //store detail twitter feed
	locationDetailFacebook(); //store detail facebook feed
	
	designerDetailLayout();
	
	//set up the tabs
	$("body.locations #sub ul.tabs, body.store-detail ul.tabs").tabs("div.panes > div");
	
	//load store locations map, pass in locations tab api
	locationsMap($('#sub ul.tabs').data("tabs"));

	//locations search form functionality
	locationsSearch();
	
	$('div.image-left, div.image-right, a.image-left, a.image-right').imageWidth();
	$('blockquote p span').add_quote_margin();
	
	//activate the carousel for watch boutique and look pages
	$('div.carousel-wrapper').cp_carousel();
	
	lookSlideshowClick();
	scrollableSlideShow();
	
	articleSidebar();
	
	markupPrep();
});
