jQuery(document).ready(function($)
{
	/**
	 * Configuration options
	 */
	var transitionOverlaySpeed	= 250;
	// when the page has left hand nav, the hover tooltip - should this animate/slide to the correct position
	var animatePointer			= true;
	// when you hover over the left hand nav and the tooltip is displayed, should the main page devices fade out or not
	var fadeOutBackground		= false;
	var fadeOpacity				= 0.6;
	var isIE6					= false;

	// this is temporaty while a fix is found, without this, for some reason, on the devices landing page
	// with the navigation, when you roll out and the 'pop-out' is hidden, the 'Showing' filter disappears
	if($.browser.msie) {
		fadeOutBackground		= false;

		var ieVersion			= Number($.browser.version.substr(0,1));
		transitionOverlaySpeed	= ieVersion > 6 ? 0 : transitionOverlaySpeed;
		isIE6					= ieVersion == 6;
	}

	// add a class of 'js' to the body so we can add additional styles
	$('body').addClass('js');

	/**
	 * Sorting the phones by either 'latest' or 'by family'
	 */
	// need to dynamically work this out
	var phoneColumns	= $('#devices-container').hasClass('span-2') ? 2 : 3;

	// function to compare the model name so they can be ordered alphabetically
	var sortPhones	= function(itemA, itemB)
	{
		var itemAModel	= $(itemA).find('.model').text().toLowerCase();
		var itemBModel	= $(itemB).find('.model').text().toLowerCase();
		if(itemAModel < itemBModel){ return -1;}
		if(itemAModel > itemBModel){ return 1; }
		return 0;
	}
	
	// function to compare the popularity so they can be sorted accordingly
	var orderPhones	= function(itemA, itemB)
	{
		var itemAPop = $(itemA).find('a:first').attr('rel');
		var itemBPop = $(itemB).find('a:first').attr('rel');
		if(itemAPop < itemBPop){ return -1;}
		if(itemAPop > itemBPop){ return 1; }
		return 0;
	}

	// create an array of all the phones on the page
	var phones		= $('#latest .item');
	// an array to hold all of the new family phones
	var family		= new Array;
	var popular		= new Array;

	// loop through all of the phones, create a copy, and remove the first and last classes - as they will be re-ordered
	$(phones).each(function(i)
	{
		var item	= $(this).clone();
		$(item).removeClass('first');
		$(item).removeClass('last');
		family.push(item);
		popular.push(item);
	})

	// sort the phones alphabetically
	family.sort(sortPhones);
	popular.sort(orderPhones);

	// create a new latest family & popular div beneath the latest phones
	$('#latest').after('<div id="family"></div><div id="popular"></div>');

	// define variable
	var current_row, current_row_p;

	// loop through all the phones in the family
	for(var i = 0; i < family.length; i++)
	{
		// if the counter is divisible by phoneColumns, create a new row
		if(i%phoneColumns == 0)
		{
			current_row		= $('<div class="row"></div>');
			$('#family').append($(current_row));
		}
		// push the phone into the row
		var item = '<div class="item">'+family[i].html()+'</div>';
		$(current_row).append(item);
	}
	
	// loop through all the phones in the popular array
	for(var e = 0; e < popular.length; e++)
	{
		// if the counter is divisible by phoneColumns, create a new row
		if(e%phoneColumns == 0)
		{
			current_row_p		= $('<div class="row"></div>');
			$('#popular').append($(current_row_p));
		}
		// push the phone into the row
		$(current_row_p).append($(popular[e]));
	}

	// finally, loop through all the rows and apply 'first' and 'last' classes to the phones - for css styling
	$('#family .row').each(function(i)
	{
		var items	= $(this).find('.item');
		$(items[0]).addClass('first');
		$(items[items.length - 1]).addClass('last');
	})
	
	$('#popular .row').each(function(i)
	{
		var items	= $(this).find('.item');
		$(items[0]).addClass('first');
		$(items[items.length - 1]).addClass('last');
	})

	// lastly, call SIFR to do font replacement on the phone items
	if(typeof sIFR == "function") {
		sIFR.replaceElement(named({sSelector:".row h3 span", sFlashSrc:"/assets/flash/quay_medium.swf", sColor:"#4c4c4c", sLinkColor:"#000000", sBgColor:"transparent", sHoverColor:"#000000", sWmode: "transparent"}));
	}

	// hide the family view - as it's not the default
	$('#family').css('display', 'none');
	$('#popular').css('display', 'none');

	// watch for changes to the filter dropdown, and hide/show the correct view accordingly
	$('#showing').change(function(i)
	{
		switch($(this).val().toLowerCase())
		{
			case 'family':
				$('#family').css('display', 'block');
				$('#latest').css('display', 'none');
				$('#popular').css('display', 'none');
				break;
			case 'latest' :
				$('#family').css('display', 'none');
				$('#latest').css('display', 'block');
				$('#popular').css('display', 'none');
				break;
			case 'popular' :
				$('#family').css('display', 'none');
				$('#latest').css('display', 'none');
				$('#popular').css('display', 'block');
				break;
		}
	}).change();

	/**
	 * Handle the menu pop-out
	 */
	var devicesRegEx	= /\/devices\/(blackberry[\w]+)\//
	var contentMatch	= new Object;

	// loop through all the items/phones
	$('#latest .item').each(function(i)
	{
		// get the link of the find out more link/button
		var moreLink	= $(this).find('.find-out-more')[0];
		var href		= $(moreLink).attr('href');
		// atampt to match the [hone
		var matches		= href.match(devicesRegEx);

		if(matches)	{
			// add a reference to the content
			contentMatch[matches[1]]	= $(this);
		}
	})

	var hoverTimer;

	// loop through all the links in the side navigation - ideally this process wouldn't happen
	// and we'd be able to create some kind of connection based on id's or classes, however, as
	// we want to avoid changing the navigation in any way, we need to find the connections with
	// javascript
	$('#sidenav a').each(function(i)
	{
		var href			= $(this).attr('href');
		var matches			= href.match(devicesRegEx);

		if(matches)
		{
			// cross reference the tooltip content from the in-page content
			var toolTipContent	= contentMatch[matches[1]];
			// apply a hover event/effect to the navigations links
			$(this).hover(
				function()
				{
					if (hoverTimer) {
						clearTimeout(hoverTimer);
						hoverTimer = null;
					}

					$('#device-popout .content').html($(toolTipContent).clone());

					$('#device-popout h3 .sIFR-replaced').removeClass('sIFR-replaced').each(function(i)
					{
						$(this).html($(this).find('.sIFR-alternate:first').html())
					});

					sIFR.replaceElement(named({sSelector:"#device-popout h3 span", sFlashSrc:"/assets/flash/quay_medium.swf", sColor:"#4c4c4c", sLinkColor:"#000000", sBgColor:"transparent", sHoverColor:"#000000", sWmode: "transparent"}));

					var handset		= $('#device-popout .content img.handset:first');
					handset.attr('src', handset.attr('src').replace('-med', '-sml'));

					$('#device-popout .content .column-2:first').after($('#device-popout .content .column-1:first'))

					var topOffset		= $(this).parent().parent().position().top;
					var popoutOffset	= parseFloat($('#device-popout').css('top'));
					var pointerTarget	= topOffset - popoutOffset;

					if(animatePointer)
					{
						$('#pointer').animate({
							top	:(pointerTarget)
						}, 100)
					}
					else
					{
						$('#pointer').css('top', (pointerTarget) + 'px');
					}

					if(fadeOutBackground) {
						$('#devices-container').animate({opacity:fadeOpacity}, 100);
					}

					$('#device-popout').fadeIn(transitionOverlaySpeed);
				},
				function()
				{
					hoverTimer = setTimeout(function()
					{
						$("#device-popout").fadeOut(transitionOverlaySpeed);

						if(fadeOutBackground) {
							$('#devices-container').animate({opacity:1}, 100);
						}
					}, 500);
				}
			)
		}
		else
		{
			// there is no match - so assume that there is no pop-out for this, and kill the hover events - and return to normal
			$(this).hover(
				function()
				{
					if (hoverTimer) {
						clearTimeout(hoverTimer);
						hoverTimer = null;
					}

					$("#device-popout").fadeOut(transitionOverlaySpeed);

					if(fadeOutBackground) {
						$('#devices-container').animate({opacity:1}, 100);
					}
				}
			)
		}
	})

	// add a container for the tool-tip content
	$('#content-start').prepend('<div id="device-popout" style="display:none"><div class="content"></div><span id="pointer"></span></div>');

	$('#device-popout').hover(
		function()
		{
			if (hoverTimer) {
				clearTimeout(hoverTimer);
				hoverTimer = null;
			}
		},
		function()
		{
			$(this).fadeOut(transitionOverlaySpeed);

			if(fadeOutBackground) {
				$('#devices-container').animate({opacity:1}, 100);
			}
		}
	);




	$('#choose-a-provider').click(function()
	{
		if(isIE6)
		{
			$('#content select').css('visibility', 'hidden')
		}

		$('#overlay').fadeTo('fast', 0.8, function()
		{
			$('#providers').show()
		})

		return false;
	})

	$('body').append('<div id="overlay" style="display:none;"></div>')

	if(isIE6){
		$('#overlay').css('height', $(document).height() + 'px')
	}

	$('body').append($('#providers'))
	$('#providers').hide()

	$('#providers .container').prepend($('<a href="#" class="close">Close</a>').click(function()
	{
		$('#providers').hide();
		$('#overlay').hide();

		if(isIE6)
		{
			$('#content select').css('visibility', 'visible')
		}

		return false;
	}))

	$('#wrapper').append($('.family'))

	$('.family').hide();

	$('.family .container .row').prepend('<a href="#" class="close">Close</a>')
	$('.family .container .close').click(function()
	{
		$('#nav-device .dropdown a').each(function(i)
		{
			$(this).removeClass('here');
			$($(this).attr('href')).hide()

			if(isIE6)
			{
				$('#content select').css('visibility', 'visible')
			}
		})

		return false;
	})

	$('#nav-device .dropdown a').click(function()
	{
		if($(this).hasClass('here'))
		{
			$(this).removeClass('here');
			$($(this).attr('href')).hide();

			if(isIE6)
			{
				$('#content select').css('visibility', 'visible')
			}

			return false;
		}
		else
		{
			$('#nav-device .dropdown a').each(function(i)
			{
				$(this).removeClass('here');
				$($(this).attr('href')).hide()
			})

			if($($(this).attr('href')).length)
			{
				$($(this).attr('href')).show()
				$(this).addClass('here');

				if(isIE6)
				{
					$('#content select').css('visibility', 'hidden')
				}

				return false;
			}
		}
	})

	$('dl.handset-colours li').wrapInner('<a href="#"></a>');
	$('dl.handset-colours li a').click(function()
	{
		var colour	= $(this).parent().attr('class').split(' ')[0];

		if(colour == 'default')
		{
			colour	= '';
		}
		else
		{
			colour	= '-clr-' + colour;
		}
		var phone	= $(this).parents('.item').find('img.handset')[0];
		var src		= $(phone).attr('src')
		var regEx	= /(-clr-[a-zA-Z]+)?.(jpg|gif|png)$/
		var parts	= src.match(regEx);

		if(parts)
		{
			if(parts[1])
			{
				src		= src.replace(parts[1], colour)
			}
			else
			{
				src		= src.replace(parts[0], colour + parts[0])
			}

			$(phone).attr('src', src)
		}

		return false;
	})

	if($.browser.msie) {
		$.ajaxSetup({dataFilter: function(data, dataType){return data.split(/(<body[^>]*>|<\/body>)/ig)[1];}});
	}

	//$.get("carriers.html", function(data) {
	$.get("carriers.jsp", function(data) {
		var data = $(data);
		$('.ajaxHeading').html( $("h1", data).html() );
		$('.ajaxCopy').html( $("#tab_carrier > p", data).html() );
		$("form > select", data).appendTo('.ajaxSelector');
	});

});


// onchange function for dropdown list
function changeCarrier(providerSelect){
		// reset result div and show loader
	jQuery('.ajaxResults').addClass("loading").removeClass("done");
	jQuery('.ajaxResults').empty();

	// get provider
	var provider = providerSelect.options[providerSelect.selectedIndex].value;

		// load/display results
//	jQuery.get("carrier_" + provider + ".html", function(data) {
	jQuery.get("/devices/" + provider, function(data) {
		// hide loader
		jQuery('.ajaxResults').removeClass("loading").addClass("done");

		// set H1
		jQuery('.ajaxHeading').html( jQuery("h1", data).html() );

		// populate results div
		var pcopy = jQuery("#tab_carrier > p", data)[0];
		jQuery(pcopy).appendTo('.ajaxResults');
		jQuery('<div class="devices-list">').appendTo('.ajaxResults');
		jQuery("div.inside", data).appendTo('.ajaxResults .devices-list');

		jQuery('.devices-list .inside a').click(function()
		{
			doOmnitureCarrierEventFromA(this);
		})
	});
}
