var imgs = new Array(
	'/images/us.png',
	'/images/thumbs-up-hover.png',
	'/images/thumbs-down-hover.png'
);

preloadImages(imgs);

function preloadImages(images) {
	var imageObjs = new Array();
	for (var i in images) {
		imageObjs[i] = new Image();
		imageObjs[i].src = images[i];
	}
}

$(window).load(function () {
	if ($('#twitter_update_list').size()) {
		(function() {
			var b = document.createElement('script'); b.type = 'text/javascript'; b.src = '/js/blogger.js'; b.defer = 'defer';
			var t = document.createElement('script'); t.type = 'text/javascript'; t.src = 'http://twitter.com/statuses/user_timeline/storeslike.json?callback=twitterCallback2&count=2'; t.defer = 'defer';
			var h = document.getElementsByTagName('head')[0]; h.appendChild(b); h.appendChild(t);
		})();
	}
});

$(document).ready(function() {
	$('#choose-site-link').click(function() {
		$('.choose-site-switcher').toggle();
		return false;
	});
	
	$('#add-shop-link').click(function() {
		$('.add-shop-form').toggle();
		return false;
	});
	
	if ($.isFunction($.fn.autocomplete)) {
		if ($('#query').size()) {
			var queryField = $('#query');
			queryField.autocomplete({
				source: '/search/autocomplete',
				select: function(event, ui) {
					window.location = ui.item.url
				}					
			})
			.data( "autocomplete" )._renderItem = function( ul, item ) {
				item.name = item.name.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
				return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( '<a href="' + item.url + '">' + item.name + '</a>' )
				.appendTo( ul );
			};
		}
		
		if ($('#add-similar-shop #name').size()) {
			var nameField = $('#add-similar-shop #name');
			var websiteField = $('#add-similar-shop #website');
			var captchaField = $('#add-similar-shop #captcha');
			nameField.autocomplete({
				source: '/misc/similar-autocomplete',
				select: function(event, ui) {
					nameField.val(ui.item.name);
					websiteField.val(ui.item.website);
					captchaField.focus();
				}
			})
			.data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a>" + item.formattedName + "</a>" )
				.appendTo( ul );
			};
		}	
	}
	
	if ($('#query').size()) {
		$('#query').focus(function() {
			$(this).css('color', '#373737').val('').unbind('focus');			
		});
		
		$('#query').blur(function() {
			if ($(this).val() == '') {
				$(this).css('color', '#AAAAAA').val('Enter a shop name to find similar shops').bind('focus', function() {
					$(this).css('color', '#373737').val('').unbind('focus');
				});
			}
		});
	}
	
	if (!$('#why-captcha-trigger').size()) {
		$('.captcha-element-wrapper label').append('<span class="why-captcha-wrap">(<a id="why-captcha-trigger" href="/misc/sum">What\'s this?</a>)<span>');
	}
	
	if ($.isFunction($.fn.colorbox)) {	
		if ($('#rules').size()) {
			$('#rules').colorbox({
				href: '/misc/rules',
				width: 400,
				height: 550,
				opacity: 0
			});
		}
		
		$('.report-link').colorbox({
			href: $(this).attr('href'),
			width: 400,
			height: 550,
			opacity: 0,
			iframe: true
		});
		
		if ($('#why-captcha-trigger').size()) {
			$('#why-captcha-trigger').colorbox({
				href: '/misc/sum',
				width: 400,
				height: 240,
				opacity: 0
			});
		}
	}
	
	if ($('.form-message').size()) {
		setTimeout(function() { $('.form-message').fadeOut('slow'); } , 5000 );
	}
	
	if ($.isFunction($.fn.ajaxSubmit)) {
		if ($('#report-form').size()) {
			bindAjaxForm('#report-form', '#report-form-wrap', '/misc/report-ajax');
		}
		
		if ($('#header-add-shop-form').size()) {
			bindAjaxForm('#header-add-shop-form', '#suggest-shop-inner-wrapper', '/ajax/suggest-shop');
		}
	}
	
	$('.hide-flash-message').click(function() {
    	$(this).parent().parent().parent().fadeOut('slow');    	
    });
	
	$('a.more-link').click(function() {
        if ($(this).hasClass('expand')) {
            $('div.child-hidden', $(this).parent().prev()).removeClass('child-hidden').addClass('was-hidden');
            $(this).removeClass('expand').addClass('collapse').text('Less');
        } else if ($(this).hasClass('collapse')) {
            $('div.was-hidden', $(this).parent().prev()).removeClass('was-hidden').addClass('child-hidden');
            $(this).removeClass('collapse').addClass('expand').text('More');
        }        
        return false;
    });
	
	$('#category-list-select').change(function() {
		if ($(this).val()) {
			window.location = $(this).val();
		}
	});
	
	if ($.isFunction($.fn.stars)) {
		$('.rating-input-wrapper').stars({
			cancelShow: false,
			inputType: 'select'			
		});
	}
	
	if ($.isFunction($.fn.cycle)) {
		$('div.promo-fader-outer').cycle({
			timeout: 10000
		});
	}
	
}); // End document ready

function vote(direction, shopId, similarShopId)
{
	if (isNumeric(shopId) && isNumeric(similarShopId) && (direction == 'up' || direction == 'down')) {
		$.ajax({
	        url: '/misc/vote/direction/' + direction,
	        type: 'POST',
	        data: ({format: 'json', shopId: shopId, similarShopId: similarShopId}),
	        success: function(responseJson) {
				if (responseJson.type == 'success') {
					processVote(direction, shopId, similarShopId, responseJson);
				} else if (responseJson.type == 'error') {
					alert(responseJson.message);
				} else {
					alert('There was an error processing your vote');
				}
			}
	    });
	}
	
	return false;
}

function processVote(direction, shopId, similarShopId, responseJson)
{
	$('#score-' + similarShopId).animate({opacity: '0.0'}, 300, function() {
		$(this).html(responseJson.message).animate({opacity: '1.0'}, 300, function() {
			if ($.browser.msie) {
				this.style.removeAttribute('filter');
			}
			var score = responseJson.message;
			var position = responseJson.position;
			
			var $shopBox = $('#shop-box-' + similarShopId);
			var shopBoxClasses = $('#shop-box-' + similarShopId).attr('class').split(' ');
			shopBoxCurrentPosition = null;
			for (var k in shopBoxClasses) {
				if (shopBoxClasses[k].indexOf('position-') != -1) {
					shopBoxCurrentPosition = shopBoxClasses[k].replace('position-', '');
				}
			}
			
			var $targetPositionDiv = $('div.position-' + position);
			
			if (($shopBox.prev() || $shopBox.next()) && $targetPositionDiv.size() && shopBoxCurrentPosition != null && shopBoxCurrentPosition != position) {				
				$shopBox.fadeOut('slow', function() {
					if (position > shopBoxCurrentPosition) {
						$shopBox.insertAfter($targetPositionDiv);
					} else {
						$shopBox.insertBefore($targetPositionDiv);
					}
					
					$shopBox.fadeIn('slow', function() {
						if ($.browser.msie) {
							this.style.removeAttribute('filter');
						}
						$('.shop-box').each(function (i) {
							classes = $(this).attr('class').split(' ');;
							for (var j in classes) {
								if (classes[j].indexOf('position-') != -1) {
									$(this).removeClass(classes[j]);
									$(this).addClass(classes[j].replace(/position-.*/g, 'position-' + (i+1)));
								}
							}
						});
					});
				});
				
			}
		});
	});	
}

function like(direction, shopId)
{
	if (isNumeric(shopId) && (direction == 'up' || direction == 'down')) {
		$.ajax({
	        url: '/misc/like/',
	        type: 'POST',
	        data: ({format: 'json', id: shopId, direction: direction}),
	        success: function(responseJson) {
				if (responseJson.type == 'success') {
					if (direction == 'up') {
						$('#like-button').css('backgroundImage', 'url(/images/thumbs-up-hover.png)');
					} else {
						$('#dislike-button').css('backgroundImage', 'url(/images/thumbs-down-hover.png)');
					}
					$('#like-results').attr('title', responseJson.upVotes + ' likes, ' + responseJson.downVotes + ' dislikes');
					$('#up-vote-count').html(responseJson.upVotes);
					$('#down-vote-count').html(responseJson.downVotes);
				} else if (responseJson.type == 'error') {
					alert(responseJson.message);
				} else {
					alert('There was an error processing your vote');
				}
			}
	    });
	}
}

function isNumeric(value)
{
	if (isNaN(parseFloat(value))) {
        return false;
	}
	
    return true;
}

function bindAjaxForm(elemID, wrapperID, url)
{
	$element = $(elemID);
	$element.submit(function() {		
		$(this).ajaxSubmit({
			url: url,
			target: wrapperID,
			success: function() {
				bindAjaxForm(elemID, wrapperID, url);
			},
			data: {format: 'html'}
		});
		return false;
	});
}
