/*
 * Generic AJAX object
 */

var INITIALISED = 0;
var LOADING = 1;
var LOADED = 2;
var INTERACTIVE = 3;
var COMPLETE = 4;

function AjaxObj()
{
	var xmlhttp = false;
	
	try
	{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e)
	{
		try
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (e2)
		{
			xmlhttp = false;
		}
	}
	
	if(!xmlhttp && typeof(XMLHttpRequest != 'undefined'))
		xmlhttp = new XMLHttpRequest();
	
	if(!xmlhttp)
		return false;
	
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == COMPLETE)
		{
			if(xmlhttp.responseText)
			{
				try
				{
					eval(xmlhttp.responseText);
					xmlhttp.onreadystatechange = function() {};
				}
				catch(e)
				{
					var str = '';
					for(var i in e)
						str += i + ' :: ' + e[i] + '\n';
					str += '\n\n' + xmlhttp.responseText;
					alert(str);
				}
			}
		}
	};
	
	return xmlhttp;
}



function addLoadEvent(func)
{
	var oldonload = window.onload;
	
	if (typeof window.onload != 'function')
	{
		window.onload = func;
	}
	else
	{
		window.onload = function()
		{
			if (oldonload)
				oldonload();
			
			func();
		};
	}
}

function showTab(tabGroupId, tabId)
{
	var elms = document.getElementById(tabGroupId).getElementsByTagName('div');
	var len = elms.length;
	
	for (var i = 0; i < len; i++)
	{
		if (elms[i].className == 'tabData')
		{
			elms[i].style.display = elms[i].id == tabId ? 'block' : 'none';
			document.getElementById(elms[i].id + '-tab').className = elms[i].id == tabId ? 'active' : '';
		}
	}
	
	return false;
}

function getOffset(elm)
{
	var x = 0;
	var y = 0;
	
	while (elm)
	{
		x += elm.offsetLeft;
		y += elm.offsetTop;
		elm = elm.offsetParent;
	}
	
	return {'x':x, 'y':y};
}

function getMouse(e)
{
	var x = (typeof e == 'undefined') ? event.clientX + document.body.scrollLeft : e.pageX;
	var y = (typeof e == 'undefined') ? event.clientY + document.body.scrollTop : e.pageY;
	
	return {'x':x, 'y':y};
}

function Balloon()
{
	this.balloon = null;
	this.elm = null;
	this.title = '';
	
	this.show = function(elm, text)
	{
		this.elm = elm;
		var self = this;
		
		if (!elm.onmouseout)
			elm.onmouseout = function() { self.hide(); };
		
		if (typeof text == 'undefined')
			text = elm.title;
		
		if (!text)
			return;
		
		if (!this.balloon)
		{
			this.balloon = document.createElement('div');
			this.balloon.id = 'balloon';
			document.body.appendChild(this.balloon);
		}
		
		this.balloon.innerHTML = '<div id="balloon-inner">' + text + '</div>';

		this.title = elm.title;
		elm.title = '';
		var offset = getOffset(elm);
		
		this.balloon.style.left = (offset.x + (elm.offsetWidth / 2) - 22) + 'px';
		this.balloon.style.top = (offset.y + elm.offsetHeight + 1) + 'px';
		this.balloon.style.display = 'block';
	};
	
	this.hide = function()
	{
		if (this.balloon)
			this.balloon.style.display = 'none';
		
		if (this.elm)
			this.elm.title = this.title;
	};
}

var b = new Balloon();

var activeSoftPop = null;

// e: Event
// id:: The ID of the soft poup to show
function showSoftPop(e, elm, popupID, options)
{
	hideSoftPop();
	
	if (typeof options == 'undefined')
		options = {};
	
	var p = document.getElementById(popupID);
	
	if (!p)
	{
		alert('Could not find soft popup div ID: ' + popupID);
		return false;
	}
	
	// Properly create the popup
	if (!document.getElementById(popupID + '_close'))
	{
		var div = document.createElement('div');
		div.innerHTML = p.innerHTML;
		div.className = 'softPopInner';
		
		var content = div;
		
		while (p.firstChild)
			p.removeChild(p.firstChild);
		
		var div = document.createElement('div');
		div.className = 'softPopClose';
		div.id = popupID + '_close';
		div.onclick = hideSoftPop;
		div.title = 'Close';
		div.onmouseover = function(e) { b.show(this); };
		div.onmouseout = function(e) { b.hide(); };
		//p.appendChild(div);
		
		content.insertBefore(div, content.getElementsByTagName('h3')[0].nextSibling);
		
		var br = document.createElement('br');
		br.style.clear = 'both';
		content.insertBefore(br, div.nextSibling);
		
		p.appendChild(content);
		
		if (options.autosize)
		{
			p.style.display = 'block';
			p.style.width = (content.scrollWidth) + 'px';
			p.style.height = (content.scrollHeight) + 'px';
		}
	}
	
	var offset = getMouse(e); //getOffset(elm);
	
	p.style.display = 'block';
	var x = offset.x  - parseInt(p.offsetWidth, 10) - 10;
	var y = offset.y  - parseInt(p.offsetHeight, 10) - 10;

	// Stop it going off the edge of the screen, or overlapping the flash banners
	// Use the breadcrumbs as a position reference to prevent overlapping flash banners
	var scrollElm = document.body;
	if (document.documentElement && (typeof document.documentElement.scrollTop != 'undefined'))
		scrollElm = document.documentElement;
	
	var bc = document.getElementById('breadcrumbs');
	var minx = Math.max(scrollElm.scrollLeft, bc ? bc.offsetLeft : 0);
	if (x < minx)
		x = minx;
	var miny = Math.max(scrollElm.scrollTop, (bc ? bc.offsetTop : 0) + (bc ? bc.offsetHeight : 0));
	if (y < miny)
		y = miny;
		
	p.style.left = x + 'px';
	p.style.top = y + 'px';
	
	activeSoftPop = p;
	
	cancelEvent(e);
	
	return false;
}

function showSoftPopAjax(e, elm, type, id)
{
	hideSoftPop();
	
	var popupId = 'softPop_' + type + '_' + id;
	var p = document.getElementById(popupId);
	
	if (p)
		return showSoftPop(e, elm, popupId);
	
	var p = document.createElement('div');
	p.className = 'softPop';
	p.id = popupId;
	p.innerHTML = '<h3>Loading..</h3><div>Loading...</div>';
	
	document.getElementsByTagName('body')[0].appendChild(p);
	
	var a = new AjaxObj();
	a.open('GET', ROOT + '/ajax-soft-popup/?type=' + type + '&id=' + id, true);
	a.send(null);

	return showSoftPop(e, elm, popupId);
}

function hideSoftPop()
{
	if (activeSoftPop)
		activeSoftPop.style.display = 'none';
	
	return false;
}

function cancelEvent(e)
{
	if (e)
		e.stopPropagation();
	else if (window.event)
		window.event.cancelBubble = true;
	
	return false;
}

function showDisabledNetwork(network)
{
	var clientHeight;
	var clientWidth;
	if (window.innerHeight)
	{
		clientHeight = window.innerHeight;
		clientWidth = window.innerWidth;
	}
	else if (document.documentElement.clientHeight)
	{
		clientHeight = document.documentElement.clientHeight;
		clientWidth = document.documentElement.clientWidth;
	}
	else
	{
		clientHeight = document.body.clientHeight;
		clientWidth = document.body.clientWidth;
	}
	
	e = document.getElementById('disabled' + network);
	e.style.top  = (document.body.scrollTop  + (clientHeight - parseInt(e.style.height, 10)) / 2) + 'px';
	e.style.left = (document.body.scrollLeft + (clientWidth - parseInt(e.style.width, 10)) / 2) + 'px';
	e.style.display = 'block';
}


function modelListShow(elm, num, offset)
{
	while (elm.tagName.toLowerCase() != 'table')
		elm = elm.parentNode;
	elm = elm.rows[0].cells[1].getElementsByTagName('div')[1];
	
	
	margin = elm.style.marginLeft ? parseInt(elm.style.marginLeft, 10) : 0;
	
	if (num == -1)
		num = (margin / -239) + offset;
		
	var highlightNum = num;
	
	if (num < 0)
		num = 0;
	else if (num > 3)
		num = 3;
	
	if (highlightNum < 0)
		highlightNum = 0;
	else if (highlightNum > 4)
		highlightNum = 4;
	
	//elm.style.marginLeft = (-239 * num) + 'px';
	modelListSlide(elm, -239 * num, (-239 * num) - margin);
	
	if (!offset)
		modelListHighlight(elm, highlightNum);
	
	return false;
}

function modelListNext(elm)
{
	modelListShow(elm, -1, 1);
}

function modelListPrev(elm)
{
	modelListShow(elm, -1, -1);
}

function modelListSlide(elm, dest, step)
{
	margin = elm.style.marginLeft ? parseInt(elm.style.marginLeft, 10) : 0;
	
	if (step > 0)
	{
		step = Math.ceil(step / 2);
		if (margin + step > dest)
			step = dest - margin;
	}
	else
	{
		step = Math.floor(step / 2);
		if (margin + step < dest)
			step = dest - margin;
	}
	
	elm.style.marginLeft = (margin + step) + 'px';
	
	if (margin + step != dest)
		setTimeout(function() { modelListSlide(elm, dest, step); }, 50);
}

function modelListHighlight(elm, num)
{
	var div = elm.getElementsByTagName('table')[0].rows[0].cells[num].getElementsByTagName('div')[0];
	
	for (var i = 0; i < 8; i+=2)
	{
		setTimeout(function() { div.style.backgroundColor = '#eeeeff'; }, 250 * i);
		setTimeout(function() { div.style.backgroundColor = ''; }, 250 * (i + 1));
	}
}


// Check for screen size
var lastScreenWidth = 0;
setInterval(function()
{
	if (document.getElementsByTagName('body').length && (document.getElementsByTagName('body')[0].id == 'iframe'))
		return;
	
	var width = 0;
	if (window.innerWidth)
		width = window.innerWidth;
	
	if (document.body && document.body.offsetWidth)
		width = document.body.offsetWidth;
	
	if (document.body && document.body.clientWidth)
		width = document.body.clientWidth;
	
	if (document.documentElement && document.documentElement.clientWidth)
		width = document.documentElement.clientWidth;
	
	if (!width || (width == lastScreenWidth))
		return;
	
	var display = width < 1200 ? 'none' : 'block';
	var pageWidth = width < 1200 ? 1100 : 1200;
	
	if (document.getElementById('outer-left'))
		document.getElementById('outer-left').style.display = display;
	
	var display = width < 1100 ? 'none' : 'block';
	var pageWidth = width < 1100 ? 1000 : pageWidth;
	
	if (document.getElementById('outer-right'))
	{
		document.getElementById('outer-right').style.display = display;
		
		// This is the last element to load so only save the last width if it exists
		// otherwise we might never get here
		lastScreenWidth = width;
	}
	
	if (document.getElementById('wrapper'))
		document.getElementById('wrapper').style.width = pageWidth + 'px';
}, 200);


function showBrandSelect(elm)
{
	var selects = document.getElementById('brand-selects');
	
	if (!selects)
		return;
	
	selects = selects.getElementsByTagName('select');
	
	for (var i = 0; i < selects.length; i++)
		selects[i].style.display = 'none';
	
	var s = document.getElementById('brand_' + elm.options[elm.selectedIndex].value);
	s.style.display = 'inline';
	s.onchange = function() { location.href = this.options[this.selectedIndex].value; };
}


function doSearch(form)
{
	var brand = document.getElementById('brand');
	if (brand && (brand.options[brand.selectedIndex].value != '0'))
	{
		brand = brand.options[brand.selectedIndex].value;
		var model = document.getElementById('brand_' + brand);
		if (model)
			model = model.options[model.selectedIndex].value;
		
		if (model)
			location.href = ROOT + '/' + model;
		//else
			//location.href = ROOT + '/' + brandUrls[brand];
	}
}


function paginatorGetElement(id)
{
	var elm = document.getElementById(id);
	if (!elm)
		return false;
	
	var h = elm.offsetHeight;
	var totalH = elm.scrollHeight;
	
	// Make it work in edit mode
	var divs = elm.getElementsByTagName('div');
	for (var i = 0; i < divs.length; i++)
	{
		if (divs[i].className.match(/\bcontentWidgetContent\b/))
		{
			elm = divs[i];
			break;
		}
	}
	
	return elm;
}



function paginate(id, prevLinkId, nextLinkId)
{
	var elm = document.getElementById(id);
	if (!elm)
		return false;
	
	var h = elm.offsetHeight;
	var totalH = elm.scrollHeight;
	
	var elm = paginatorGetElement(id);
	
	// See if there's more than one page
	if (totalH <= h)
	{
		document.getElementById(prevLinkId).className = 'paginatorLinkDisabled';
		document.getElementById(nextLinkId).className = 'paginatorLinkDisabled';
		return;
	}
	
	// Replace all text nodes with spans
	var child = elm.firstChild;
	while (child)
	{
		var nextChild = child.nextSibling;
		
		switch (child.nodeType)
		{
			case 1: // Element
				// Replace any empty <p> or <div>
				if (((child.tagName.toLowerCase() == 'p') || (child.tagName.toLowerCase() == 'div')) && !child.innerHTML.replace(/\s|&nbsp;?/gi, ''))
					child.parentNode.removeChild(child);
				break;
			
			case 3: // Text node
				if (child.data.toString().replace(/^[\s\u00a0]*/, '').replace(/[\s\u00a0]*$/, ''))
				{
					var span = document.createElement('span');
					span.appendChild(document.createTextNode(child.data));
					child.parentNode.insertBefore(span, child);
				}
				child.parentNode.removeChild(child);
				break;
			
			default:
				child.parentNode.removeChild(child);
		}
		
		child = nextChild;
	}
	
	var divs = new Array();
	divs[0] = document.createElement('div');
	var currentDiv = 0;
	
	// top records the offsetTop of the first element on the page
	var top = 0;
	var child = elm.firstChild;
	while (child)
	{
		var clone = child.cloneNode(true);
		divs[currentDiv].appendChild(clone);
		
		// Add a new page, if there's still any nodes left
		if (child.nextSibling && (child.nextSibling.offsetTop + child.nextSibling.offsetHeight > top + h))
		{
			currentDiv++;
			divs[currentDiv] = document.createElement('div');
			clone.style.marginBottom = '0px';
			child.nextSibling.style.marginTop = '0px';
			top = child.nextSibling.offsetTop;
		}
		
		child = child.nextSibling;
	}
	
	while (elm.firstChild)
		elm.removeChild(elm.firstChild);
	
	for (var i = 0; i < divs.length; i++)
	{
		divs[i].className = 'paginator_page';
		divs[i].style.display = i ? 'none' : 'block';
		divs[i].id = id + '_page_' + i;
		elm.appendChild(divs[i]);
	}
	
	paginatorSetPage(id, prevLinkId, nextLinkId, 0);
}

function paginatorSetPage(id, prevLinkId, nextLinkId, page)
{
	var elm = paginatorGetElement(id).firstChild;
	var i = 0;
	while (elm)
	{
		if ((elm.nodeType == 1) && (elm.tagName.toLowerCase() == 'div'))
		{
			elm.style.display = (i == page) ? 'block' : 'none';
			i++;
		}
		
		elm = elm.nextSibling;
	}
	
	var prevPage = page ? page - 1 : 0;
	var nextPage = Math.min(page + 1, i - 1);
	
	document.getElementById(prevLinkId).onclick = function() {paginatorSetPage(id, prevLinkId, nextLinkId, prevPage); return false;}
	document.getElementById(nextLinkId).onclick = function() {paginatorSetPage(id, prevLinkId, nextLinkId, nextPage); return false;}
	
	document.getElementById(prevLinkId).className = page ? 'paginatorLink' : 'paginatorLinkDisabled';
	document.getElementById(nextLinkId).className = page != i - 1 ? 'paginatorLink' : 'paginatorLinkDisabled';
}



function toggleDisplay(elm, force)
{
	if (typeof elm == 'string')
		elm = document.getElementById(elm);
	
	var display = elm.style.display == 'none' ? '' : 'none';
	
	try
	{
		elm.style.display = force ? force : display;
	}
	catch (e)
	{
		elm.style.display = 'block';
	}
	
	return false;
}

function feature(elm)
{
	elm = elm.parentNode;
	
	while (elm.nodeType != 1 || elm.tagName.toLowerCase() != 'dd')
		elm = elm.nextSibling;
	
	toggleDisplay(elm, elm.style.display == 'block' ? 'none' : 'block');
	
	return false;
}


var leftMenuWidth = 0;
function showMenu(firstCall)
{
	if (firstCall)
		leftMenuDirection = 1;
	
	if (leftMenuDirection != 1)
		return;
	
	var targetWidth = 168;
	
	document.getElementById('left-handle').style.display = 'none';
	
	leftMenuWidth += Math.ceil((targetWidth - leftMenuWidth) / 2) ;
	if (leftMenuWidth > targetWidth)
		leftMenuWidth = targetWidth;
	
	document.getElementById('left').style.width = leftMenuWidth + 'px';
	
	if (leftMenuWidth < targetWidth)
		setTimeout(function() { showMenu(); }, 50);
}

function hideMenu(firstCall, e)
{
	var menu = document.getElementById('left');
	if (firstCall)
	{
		e = e ? e : window.event;
		var relatedTarget = e.relatedTarget ? e.relatedTarget : e.toElement;
		
		while (relatedTarget)
		{
			if (relatedTarget == menu)
				return;
			
			relatedTarget = relatedTarget.parentNode;
		}
		
		leftMenuDirection = -1;
	}
	
	if (leftMenuDirection != -1)
		return;
	
	var targetWidth = 0;
	
	leftMenuWidth -= Math.ceil(leftMenuWidth / 2) ;
	if (leftMenuWidth < targetWidth)
		leftMenuWidth = targetWidth;
	
	menu.style.width = leftMenuWidth + 'px';
	
	if (leftMenuWidth > targetWidth)
		setTimeout(function() { hideMenu(); }, 50);
	else
		document.getElementById('left-handle').style.display = '';
}

addLoadEvent(function()
{
	if (!document.getElementsByTagName('body')[0].className.match(/\b(M4EModel|M4ETariff|M4EGift|M4ERetailer)\b/))
		return;
	
	jQuery('#left-handle').mouseover(function() { showMenu(true); });
	jQuery('#left').mouseout(function(e) { hideMenu(true); });
});

var _gaq = _gaq || [];

function track(model, tariff, gift, retailer)
{
	var src = 'http://www.mobiles4everyone.com/recordclick.asp?site=mp&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
		'',                 // City
		'',                 // 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;
}


var retailers;
function scrollRetailers(dir)
{
	if (!retailers)
	{
		var ul = document.getElementById('retailers-box-retailers');
		retailers = 
		{
			ul : ul,
			position : 0,
			elements : ul.getElementsByTagName('li').length,
			elementWidth : ul.getElementsByTagName('li')[0].offsetWidth,
			dir : 0,
			target: 0,
			interval : 0,
			scroll : function(dir)
			{
				var self = this;
				
				this.dir = dir;
				
				this.target = this.position / this.elementWidth;
				this.target = (dir == 1 ? Math.floor : Math.ceil)(this.target);
				this.target = (this.target - dir) * this.elementWidth;
				this.target = Math.min(0, Math.max(this.target, -(this.elementWidth * this.elements) + ul.parentNode.offsetWidth));
				
				if (this.interval)
					return;
				
				this.interval = setInterval(function()
				{
					self.position -= self.dir * Math.ceil(Math.abs(self.position - self.target) / 4);
					self.ul.style.marginLeft = self.position + 'px';
					if (self.position == self.target)
					{
						clearInterval(self.interval);
						self.interval = 0;
					}
				}, 50);
			}
		}
		
		retailers.ul.style.width = (retailers.elements * retailers.elementWidth) + 'px';
	}
	
	retailers.scroll(dir);
	
	return false;
}





(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();
		});
	};
	
	$(function()
	{
		// TariffsWidget
		var lastTariffsPostData = '';
		var updateTariffs = function()
		{
			var postData = $('#d_form').serialize();
			
			// Don't reload the same data
			if (postData == lastTariffsPostData)
				return;
			
			lastTariffsPostData = 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 = $('#m_form').serialize();
			
			// Don't reload the same data
			if (postData == lastModelsPostData)
				return;
			
			lastModelsPostData = postData;
			
			$('#models-results').html('<div class="deals-results-loading">Loading...</div>');
			
			$.post(ROOT + '/models-ajax/', postData, function(data, textStatus)
			{
				$('#models-results').html(data);
			}, 'html');
			
			return false;
		};
		
		$('#m_form select, #m_form input').change(updateModels).click(updateModels);
		$('#m_form').submit(updateModels);
		
		// Tabs
		$('#tabs, .deals-tabs, #home-tabs, .phone-features').simpleTabs();
		
		// Model search dropdowns
		$('#brand-search').change(function() { showBrandSelect(this); });
		
		var d = new DealsWidget('d');
		d.updateDeals();
	});
	
})(jQuery);

