var clickToCall;

(function($)
{
	//return;
	
	// Hash selector
	$.expr[':'].hash = function(obj, index, meta, stack)
	{
		return meta[3] == obj.hash;
	};
	
	// Simple Tabs plugin
	$.fn.simpleTabs = function()
	{
		return this.each(function()
		{
			var panels = $(this).children('div:not(.contentWidgetContent, .config-container)');
			var tabs = $('ul:first li', this);
			
			$('ul:first a', this).click(function()
			{
				panels.hide();
				tabs.removeClass('tab-selected');
				
				$(this.hash).show();
				$(this).closest('li').addClass('tab-selected');
				
				return false;
			});
			
			var selectedTab = tabs.find('a:first');
			if (location.hash)
			{
				var  t = tabs.find('a:hash(' + location.hash + ')');
				if (t.length)
					selectedTab = t;
			}
			
			selectedTab.eq(0).click();
		});
	};
	
	// Vertical tabs plugin
	$.fn.verticalTabs = function()
	{
		return this.each(function()
		{
			var $this = $(this);
			var tabLinks = $this.find('ul.vertical-tabs a');
			var tabContents = $this.find('div.tab-content');
			
			tabLinks.click(function(e)
			{
				tabLinks.parent().removeClass('current');
				$(this).parent().addClass('current');
				
				var index = tabLinks.index(this);
				tabContents.removeClass('current');
				tabContents.eq(index).addClass('current');
				
				e.preventDefault();
			}); //.eq(0).click();
		});
	};
	

	// Truncate description plugin
	// Automatically add a "more" section for the readMore plugin
	$.fn.truncateText = function(options)
	{
		var settings = $.extend({
			height: 200
		}, options);
		
		return this.each(function()
		{
			var maxHeight = settings.height;
			var $this = $(this);
			
			var matches = $this.attr('class').match(/truncate-text-height-(\d+)/);
			if (matches)
				maxHeight = matches[1];
			
			var more = $('<div/>').addClass('more');
			var height = 0;
			var moveElements = false;
			
			var elm = $this;
			if ($this.find('.contentWidgetContent').length)
				elm = $this.find('.contentWidgetContent:first');
			
			elm.children().each(function()
			{
				var $this = $(this);
				
				if (!moveElements)
				{
					if (height + $this.height() <= maxHeight)
						height += $this.height();
					else if (height)
						moveElements = true;
				}
				
				if (moveElements)
					more.append(this);
			});
			
			if (moveElements)
				elm.append(more);
		});
	}
	
	// Read More plugin
	$.fn.readMore = function()
	{
		return this.each(function()
		{
			var more = $(this)
			
			more.after($('<a/>')
				.attr('href', '#')
				.addClass('read-more')
				.html('&raquo; <span>Read More</span>')
				.click(function()
				{
					var open = !more.is(':hidden');
					
					if (open)
					{
						$(this).html('&raquo; <span>Read More</span>').attr('id', 'read-more')
						more.slideUp();
					}
					else
					{
						$(this).html('&laquo; <span>Read Less</span>').attr('id', 'read-less')
						more.slideDown();
					}
					
					return false;
				})
				).hide();
		});
	};
	
	// Scrollable Products plugin
	$.fn.productScroll = function()
	{
		return this.each(function()
		{
			var $this = $(this);
			var productScrollId = $this.attr('id');
			
			// Stop wrapInner from executing the scripts again
			$this.find('script').remove();
			
			$this.css('overflow', 'hidden')
				.wrapInner($('<div/>').addClass('inner'))
				.prepend($('<a/>').addClass('left').attr('name', 'scroll-' + productScrollId + '-left-0'))
				.append($('<a/>').addClass('right').attr('name', 'scroll-' + productScrollId + '-right-0'));
			
			var $models = $('.inner > ul', this);
			
			var position = 0;
			var items = $models.find('li').length;
			var itemWidth = Math.round(Math.max(1, $models.find('li:first').width()));
			var innerWidth = $this.width() - (2 * $this.find('a.left').width());
			var itemsPerRow = Math.floor(innerWidth / itemWidth);
			// Resize the items wider so a whole number fit
			itemWidth = Math.round(innerWidth / itemsPerRow);
			$models.children('li').width(itemWidth);
			$this.find('.inner').width(itemsPerRow * itemWidth);
			
			$this.find('a.left, a.right').dblclick(function()
			{
				var sel;
				if (document.selection && document.selection.empty)
				{
					document.selection.empty();
				}
				else if (window.getSelection)
				{
					sel = window.getSelection();
					
					if (sel && sel.removeAllRanges)
						sel.removeAllRanges();
					else if (sel && sel.collapse)
						sel.collapse(document.getElementsByTagName("body")[0]);
				}
				
				return false;
			}).each(function()
			{
				this.onselectstart = function() { return false; };
				this.onmousedown = function() { return false; };
				
				this.style.MozUserSelect = 'none';
				this.style.KhtmlUserSelect = 'none';
				this.unselectable = 'on';
			});
			
			var updateButtons = function()
			{
				if (position >= 0)
					$this.find('a.left').addClass('left-disabled');
				else
					$this.find('a.left').removeClass('left-disabled');
				
				if (position < -itemWidth * (items - itemsPerRow - 1))
					$this.find('a.right').addClass('right-disabled');
				else
					$this.find('a.right').removeClass('right-disabled');
			}
			
			updateButtons();
			
			$this.find('a.left').click(function()
			{
				if (position >= 0)
					return;
				
				position += itemWidth;
				$models.stop().animate({marginLeft: position});
				
				$(this).attr('name', 'scroll-' + productScrollId + '-left-' + (-position / itemWidth).toFixed(0));
				
				updateButtons();
				
				return false;
			});
			
			$this.find('a.right').click(function()
			{
				if (position < -itemWidth * (items - itemsPerRow - 1))
					return;
				
				position -= itemWidth;
				$models.stop().animate({marginLeft: position});
				
				$(this).attr('name', 'scroll-' + productScrollId + '-right-' + (-position / itemWidth).toFixed(0));
				
				updateButtons();
				
				return false;
			});
			
			$models.css('width', itemWidth * items);
		});
	}
	
	/*
	 * jQuery Timer Plugin
	 * http://www.evanbot.com/article/jquery-timer-plugin/23
	 *
	 * @version      1.0
	 * @copyright    2009 Evan Byrne (http://www.evanbot.com)
	 */ 

	$.timer = function(time, func, callback){
		var a = {timer:setTimeout(func, time), callback:null}
		if(typeof(callback) == 'function'){a.callback = callback;}
		return a;
	};

	$.clearTimer = function(a){
		clearTimeout(a.timer);
		if(typeof(a.callback) == 'function'){a.callback();};
		return this;
	};
	
	clickToCall = function(retailerId, dealName)
	{
		var info = clickToCallInfo[retailerId];
		var ctc = $('div.click-to-call:first');
		
		ctc.find('.click-to-call-retailer-image img').attr('src', info.image).attr('alt', info.name).attr('title', info.name);
		ctc.find('.click-to-call-retailer-name').text(info.name);
		ctc.find('.click-to-call-deal-name').html(dealName);
		ctc.find('.click-to-call-number').text(info.phoneNumber);
		ctc.find('.click-to-call-opening-hours').text(info.phoneOpeningHours);
		
		if (dealName)
			ctc.find('.click-to-call-quote-deal').show();
		else
			ctc.find('.click-to-call-quote-deal').hide();
		
		if (info.phoneOpeningHours)
			ctc.find('.click-to-call-hours').show();
		else
			ctc.find('.click-to-call-hours').hide();
		
		ctc.modal();
	}
	
	$(function()
	{
		// Simplemodal defaults
		$.extend($.modal.defaults, {
			opacity: 25,
			zIndex: 10001,
			overlayClose: true,
			overlayCss: {backgroundColor: '#000000'}
		});
		
		$('a.modal-close, div.click-to-call-close span').live('click', function() { $.modal.close(); return false; });
		
		// TariffsWidget
		var lastTariffsPostData = '';
		var updateTariffs = function()
		{
			var postData = $('#d_form').serialize();
			
			// Don't reload the same data
			if (postData == lastTariffsPostData)
				return;
			
			lastPostData = postData;
			
			$('#tariffs-results').html('<div class="deals-results-loading">Loading...</div>');
			
			$.post(ROOT + '/tariffs-ajax/', postData, function(data, textStatus)
			{
				$('#tariffs-results').html(data);
			}, 'html');
		};
		
		$('#tariffs-tabs .refine select').change(function()
		{
			// Reset the page to 1 so we don't end up past the end
			$('#d_form input[name=page]').val(1);
			
			updateTariffs();
		});
		
		// TariffsWidget AJAX
		$('.tariffs-results-pages a').live('click', function()
		{
			$('#d_form input[name=page]').val(this.hash.replace(/[^\d]/g, ''));
			updateTariffs();
			
			return false;
		});
		
		// ModelsWidget
		var lastModelsPostData = '';
		var updateModels = function()
		{
			var postData = $('#d_form').serialize();
			
			// Don't reload the same data
			if (postData == lastModelsPostData)
				return;
			
			lastPostData = postData;
			
			$('#models-results').html('<div class="deals-results-loading">Loading...</div>');
			
			$.post(ROOT + '/models-ajax/', postData, function(data, textStatus)
			{
				$('#models-results').html(data);
			}, 'html');
		};
		
		$('.models-refine select').change(function()
		{
			updateModels();
		});
		
		// Descriptions and stuff...
		$('#tabs, .deals-tabs, #home-tabs').simpleTabs();
		$('div.vertical-tab-widget').verticalTabs();
		$('.truncate-text').truncateText();
		$('.more').readMore();
		
		$('.product-scroll').productScroll();
		
		var d = new DealsWidget('d');
		d.updateDeals();
		
		// Start MS code
		if ($.browser.msie && parseInt($.browser.version, 10) == 6) {
			try {
				document.execCommand("BackgroundImageCache", false, true);
			} catch (err) { }
		}

		$("div.subnav").append('<div class="subnav-shadow"></div>');
		
		var hiddenElements = $('#empty_set_hack');
		
		var config = {    
			sensitivity: 5,  
			interval: 100,
			over: function(){		
					$(".navigationbar > li").removeClass("current");
					$(this).addClass("current");
					//$("ul.navigationbar li:hover div.subnav").css("display","none");
					$("div.subnav").css("display","none");
					$("#nav_iframe").css("display","block");
					$("div.subnav", this).css("display","block");
					$("a", this).eq(0).focus();
					$("a", this).eq(0).blur();	
					
					// JSP Modifications
					
					if ((typeof oldIe != 'undefined') && oldIe)
						hiddenElements = $("select,iframe").not(':hidden');
					
					hiddenElements.css('visibility', 'hidden');
				},   
			 timeout: 99,  
			 out: function(){
					$("div.subnav").css("display","none");
					$("#nav_iframe").css("display","none");
					$(".navigationbar > li").removeClass("current");
					
					hiddenElements.css('visibility', 'visible');
				}   
		};
		
		$(".navigationbar > li[class!=navigationbar-item-nosubnav]").hoverIntent(config);	
			
		$.renderieframe = function(id,appendto){
			/*@cc_on@*/
				/*@if(@_jscript_version <= 5.6)
					$("#" + appendto).append('<iframe id="' + id + '"></iframe>');
					$("#" + id).attr("src","javascript:'<html></html>'");
					$("#" + id).attr("scrolling","no");
					$("#" + id).attr("frameBorder","0");
					$("#" + id).attr("style","zoom:1; filter:mask();");
			/*@end@*/			
		}

		$.renderieframe('nav_iframe','navigationbar');
		$("#nav_iframe").css("display","none");
		// End MS code
		
		// Lightboxes
		if ($("a[rel^='ms-lightbox']").length)
		{
			$("a[rel^='ms-lightbox']").slimbox({overlayOpacity: 0.2}, null, function (el)
			{
				return (this == el) || ((this.rel.length > 11) && (this.rel == el.rel));
			});
		}
		
		// Sitemap
		$('.sitemap-index a').click(function()
		{
			var letter = this.hash.split(/-/)[1];
			var li = $(this).closest('li');
			
			var nextLink = li.next().find('a:first');
			var nextLetter = nextLink.length ? nextLink.get(0).hash.split(/-/)[1] : false;
			
			$('.sitemap-index li.selected').removeClass('selected');
			li.addClass('selected');
			
			var show = false;
			$('.sitemap .letter').each(function()
			{
				if (this.id == 'sitemap-' + letter)
					show = true;
				
				if (this.id == 'sitemap-' + nextLetter)
					show = false;
				
				$(this)[show ? 'show' : 'hide']();
			});
			
			return false;
		});
		
		var selected = $('.sitemap-index a[href=' + location.hash + ']');
		if (selected.length)
			selected.click();
		else
			$('.sitemap-index a:first').click();
		
		// Homepage Brand + Model search
		$('#brand-search').change(function()
		{
			$('#brand-selects select').hide();
			$('#brand_' + $(this).val()).css('display', 'block');
		}).click( function() { $(this).change(); });
		
		$('#brand-selects select').change(function()
		{
			if ($(this).val())
				location.href = $(this).val();
		}).click( function() { $(this).change(); });
		
		// Competition page Brand + Model search
		$('#competition_brand').change(function()
		{
			$(this).closest('form').find('tr:has(select.brand-models)').hide();
			$('#competition_model_' + $(this).val()).closest('tr').show();
			
			if ($(this).val() == '-2')
				$('#competition-rate-phone').hide();
			else
				$('#competition-rate-phone').show();
		}).click( function() { $(this).change(); });
		
		// Model key features
		var featureDescriptions = $('<div/>').attr('id', 'feature-descriptions');
		$('body').append(featureDescriptions);
		
		$('#features dt').each(function()
		{
			var featureClass = $(this)[0].className;
			$(this).wrapInner($('<div class="feature-name"/>').addClass(featureClass));
			
			var dd = $(this).next('dd');
			if (!dd.length);
				return
			
			var content = $('<div class="feature-description hidden row-240-white"><div class="row-240-top"></div><div class="row-240"><div class="feature-icon ' + featureClass + '"></div>'
				+ dd.html()
				+ '</div><div class="row-240-bottom"></div></div>')
				.hover(function() { return false; }, function() { return null; });
			
			featureDescriptions.append(content);
			$(this).data('feature', content);
			
			dd.remove();
		});
		
		$('#features dt').hover(function(e)
		{
			$(this).addClass('hover');
			
			var feature = $(this).data('feature');
			
			if (feature)
				feature.show(200).css({left: e.pageX + 10, top: e.pageY + 10});
			
		}, function()
		{
			$(this).removeClass('hover');
			
			var feature = $(this).data('feature');
			
			if (feature)
				feature.hide(200);
		});
	});
	
})(jQuery);


//Cufon.replace('h1, h2, #home-total-deals', {fontFamily: 'FS Albert ExtraBold'});

var _gaq = _gaq || [];

function track(model, tariff, gift, retailer)
{
	var src = 'http://www.mobiles4everyone.com/recordclick.asp?site=msm&h=' + encodeURIComponent(model)
		+ '&t=' + encodeURIComponent(tariff)
		+ '&g=' + encodeURIComponent(gift)
		+ '&r=' + encodeURIComponent(retailer);
	
	jQuery('.m4e-record').attr('src', src);
	
	_gaq.push(['_trackPageview', '/outgoing/retailer/' + retailer + '/model/' + model + '/tariff/' + tariff + '/gift/' + gift + '/']);
	
	var orderId = (new Date()).valueOf().toString() + Math.round(100 * Math.random()).toString();
	
	_gaq.push(['_addTrans',
		orderId,            // Order ID
		'',                 // Affiliation
		'0.51',             // Total
		'0',                // Tax
		'0',                // Shipping
		'Ewloe',            // City
		'Chester',          // State
		'UK'                // Country
		]);

	_gaq.push(['_addItem',
		orderId,                                            // Order ID
		retailer + '-' + model + '-' + tariff + '-' + gift, // SKU
		model,                                              // Product Name 
		retailer,                                           // Category
		'0.51',                                             // Price
		'1'                                                 // Quantity
		]);

	_gaq.push(['_trackTrans']);
	
	return true;
}

/*
(function($)
{
	$(function()
	{
		var zoom = 4;
		var zz = $('<div/>').css({
			zoom: zoom,
			position: 'absolute',
			clip: 'rect(0, 100px, 100px, 0)',
			overflow: 'hidden',
			top: 0,
			left: 0,
			zIndex: 999999,
			background:'#ffffff',
			width: $('body').outerWidth(),
			height: $('body').outerHeight()
			}).append($('body').clone().remove('script'));
		
		$('body').append(zz).mousemove(function(e)
		{
			var top = (e.pageY - 50) + 'px';
			var right = (e.pageX + 50) + 'px';
			var bottom = (e.pageY + 50) + 'px';
			var left = (e.pageX - 50) + 'px';
			
			zz.css({clip: 'rect(' + top + ', ' + right + ', ' + bottom + ', ' + left + ')'})
				.css({left: (e.pageX / zoom) - e.pageX, top: (e.pageY / zoom) - e.pageY});
		});
	});
})(jQuery);
*/
