$(function() {

	//Twitter Feed
	load_tweets();

	//Initialize Tabs
	$('.tabs').tabs();
	$('div.ui-tabs ul.ui-tabs-nav li a').append('<span></span>');
	
	
	// set toggler defaults
	$.extend($.ui.toggler.defaults, {
		activeClass	: 'active',
		closeClass	: 'close'
	});
	
	// the product container needs a class for different view types
	$('.SI-partial-target').bind('viewchange', function(event, viewType, oldViewType) {
		$(this)
			.removeClass(oldViewType + '-view')
			.addClass(viewType + '-view');
	});
	
	// load the review list template via ajax on the product detail page
	$('#review-list-wrapper').load($('#review-page-link').attr('href'), function() {
		$(this)
			.removeClass('loading')
			.trigger('render');
	});
	
	//product gallery asset image swapping
	$('.si-product').not('.si-partial').bind('optionchange', function(event, option) {
		var $product = $(this),
			$target = $product.find('#opt' + option.id);
		$('#selected-color').empty().append(option.name);
		//only replace gallery if new one exists
		if($target.length > 0) {
			$product
			.find('.active-gallery')
			.removeClass('active-gallery')
			.fadeOut(function(){
				$target
					.addClass('active-gallery')
					.fadeIn()
					//trigger click on first image link to load new main image
					.find('a:first img').trigger('click');
				if ($target.find('.ui-item-slider-frame').length === 0) {
					$($target, event).itemSlider();
				}
			});
		}
	});

	
	//remove the entertainment <- HACKY
	$('ul.remove-last > li:last-child').remove();
	
	function init(target) {

		// initialize input hints
		$('input:text', target).hint();
		
		// initialize generic toggles
		$('a.toggle', target).toggler();
		
		// initialize context dialogs
		$('.context-dialog', target).contextDialog();
		
		// initialize sliders
		$('.callout-products', target).itemSlider();
		$('.product_collections .grid-view', target).itemSlider();
		$('.active-gallery', target).itemSlider();
		
		// initialize zebra striping on tables and lists
		$('table.zebra tr:even, ul.zebra li:even', target).addClass('stripe');
		
		// close wishlist context dialogs when a product gets added
		$('.si-wishlist-add-form').bind('addtowishlist.si', function() {
			$(this).parents('.ui-context-dialog').contextDialog('close');
		});
		
		// remove new review form and deactivate button when one is created
		$('.si-review-create-form', target).bind('success', function(event) {
			$('#new-review-toggle')
				.toggler('toggle')
				.toggler('destroy')
				.addClass('disabled');
			
			$('#new-review').remove();
		});
		
		// review edit form swapping
		$('.review-edit', target).swap({ replacementText: '[cancel]' });
		
		// hide review form when it's saved
		$('.si-review-edit-form', target).bind('success', function() {
			$(this).parents('.si-review').find('.review-edit').swap('restore');
		});
		
		// remove review helpful links when clicked
		$('.si-review-helpful-button').click(function() {
			$(this).parents('.review-helpful-wrapper').html('Thank you for voting.');
			return false;
		});
		
		$('.si-product').bind('productchange', function(event, product, productOption) {
			if (productOption.stock == 0) {
				$('.si-cart-add-form input.si-button').attr('disabled','disabled');
			} else {
				$('.si-cart-add-form input.si-button').removeAttr('disabled');
			}
		});
	}
	
    //product image switcheroo
    $('div.gallery img').click(function() {
			var href = $(this).attr('src').replace('_thumb', '');
			$('.main-image a').attr('href', href);
    });
    
    // #message stuff 
	$(document).click(function(){
		$('div#message').hide();
	});
	
	// make sure ui widgets get initialized when elements get added to the dom
	$(document).bind('render.si', function(event) {
		init(event.target);
	});

	// initialize ui widgets on the initial page load
	init(document);
	
	// initialize menu dropdowns
	$('#main-nav > ul').dropDown({arrows:false});
	
	//first swatch chosen on load
	$('.si-product').not('.si-partial').find('.si-option-swatches a:first-child').trigger('click');
	
});


function linkify(text) {
	
	return text.replace(/(https?:\/\/\S+)/, '<a target="_blank" href="$1">$1</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)@(\w+)/, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>')
		.replace(/(^|\s)#(\w+)/, '$1#<a target="_blank" href="http://search.twitter.com/search?q=%23$2">$2</a>')
		.replace(/(^|\s)#(\w+)/, '$1#<a target="_blank" href="http://search.twitter.com/search?q=%23$2">$2</a>')
		.replace(/(^|\s)#(\w+)/, '$1#<a target="_blank" href="http://search.twitter.com/search?q=%23$2">$2</a>')
		.replace(/(^|\s)#(\w+)/, '$1#<a target="_blank" href="http://search.twitter.com/search?q=%23$2">$2</a>')
		.replace(/(^|\s)#(\w+)/, '$1#<a target="_blank" href="http://search.twitter.com/search?q=%23$2">$2</a>')
		.replace(/(^|\s)#(\w+)/, '$1#<a target="_blank" href="http://search.twitter.com/search?q=%23$2">$2</a>');
}

function load_tweets() {

	var url,
		last_ID = $(".tweet_result:first").attr("ID");

	if (last_ID) {
		last_ID = last_ID.replace("tweet", "");
		url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=kaenon&count=5&callback=?&since_id=" + last_ID + "";
	} else {
		url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=kaenon&count=5&callback=?"; 
	}
	
	$.getJSON(url, function(json) { 
		var results = '';
		$(json).each(function() {
			if (this.id === undefined) return;
			results += "<div class='tweet_result si-clearfix' id='tweet" + this.user.id + "'><a target='_blank' href='http://twitter.com/" + this.user.screen_name + "' class='tweet_user'><img class='si-left' width='38' height='38' alt='" + this.user.screen_name + " on Twitter' src='" + this.user.profile_image_url + "' /></a><p>" + linkify(this.text) + "</p></div>";
		});

		if (last_ID) {
			$("#twitter_results").prepend(results);
		} else {
			$("#twitter_results").append(results);
		}
	});

	$(".tweet_result:gt(20)").remove();
}
