// This jQuery extension was beautifully hand-coded by Stephen McElhinney, and is copyright of him. If you use it, please give him credit. Or praise. Or gold knuckledusters. He needs all of these.
(function($) {
	var slidefx_methods = {
		debug: function(options) {
			//console.log("Debug called: ", $(this));
		},
		init: function(options) {
			var defaults = {
				duration: 4000,
				transition: false,
				speed: 1000,
				index: 0
			}
			options = $.extend(defaults, options);
			return this.each(function() {
				var $a = $(this);
				$a.slidefx('debug');
			});
		}
	}; // Method calling logic - do not change!!
	$.fn.slidefx = function(method) {
		if (slidefx_methods[method]) {
			return slidefx_methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return slidefx_methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.slidefx');
		}
	}
	$.fn.fadeOverlay = function(options) {
		var $a = $(this);
		var defaults = {
			'hideElements': $(".box_Footer"),
			// Elements to hide
			'delay': 3500,
			// How long to delay the overlay for
			'width': 1030,
			// Width of the overlay div
			'height': 900,
			// Height of the overlay div
			'bgColor': '#FFF',
			// Default div backgroundColor
			'active': false,
			// Toggle the campaign on/off, handy when testing.
			'views': 1,
			// Configurable number of views *TODO
			'campaignName': 'defaultCampaign' // Will be used as cookie value for configuring number of views. 
		}; // Need to add logic to ensure that width and height are int values
		options.width = intify(options.width, defaults.width);
		options.height = intify(options.height, defaults.height);
		options = $.extend(defaults, options);
		if (options.active) {
			options.hideElements.css({
				"opacity": "0"
			});
			$a.show();
			$a.css({
				marginLeft: (options.width / 2) * -1 + 'px',
				marginRight: "auto",
				marginTop: 0,
				marginBottom: 0,
				backgroundColor: options.bgColor,
				width: options.width + 'px',
				position: 'absolute',
				left: '50%',
				top: 0,
				zIndex: 9999,
				height: options.height + 'px',
				cursor: 'pointer'
			}).click(function() {
				crossFade($(this), options.hideElements);
			});
			setTimeout(function() {
				$a.animate({
					opacity: 0
				}, 500, function() {
					crossFade($a, options.hideElements);
				});
			}, options.delay);
			
		} else {
			options.hideElements.css({
				"opacity": "1"
			});
			$a.remove();
		}
	};
	$.fn.stripey = function(options) { // Requires a table element
		var $a = this;
		var defaults = {
			'bgColor': '#CCC',
			// default bg color to stripe. 
			'firstRowStriped': false
		};
		$a.each(function(idx) {
			$(this).find("tr:odd").addClass("alt");
		});
	};
	$.fn.xfade = function(options) {
		var defaults = {
			duration: 4000,
			transition: false,
			speed: 1000,
			index: 0
		}
		options = $.extend(defaults, options);
		if (!options.transition) {
			options.transition = function(from, to) {
				from.fadeOut(options.speed, function() {
					to.fadeIn(options.speed);
				});
			};
		}
		var x = $(this).children().length;
		return $(this).each(function() {
			var self = $(this);
			var first = self.children().eq(options.index);
			if (x > 1) {
				var current = options.index;
				self.children().not(":eq(" + current + ")").hide();

				function transition() {
					var next = current + 1;
					if (next >= x) {
						next = 0;
					} //console.log(self.children(":eq(" + current + ")"), self.children(":eq(" + next + ")"));
					options.transition(self.children(":eq(" + current + ")"), self.children(":eq(" + next + ")"));
					current = next;
					setTimeout(transition, options.duration);
				}
				setTimeout(transition, options.duration);
			}
		});
	};
	var tabifyMethods = {
		debug: function(options) {
			//console.log($(this));
		},
		activate: function(options) {
			return this.each(function() {
				var $a = $(this);
				var c = $(document.createElement("img")).attr("src", "/imgs/backgrounds/cut-away-corner.gif").addClass("cut_away_image");
				$('.cut_away_image').remove();
				$a.parents("ul:first").find('.active_Link').removeClass('active_Link');
				$a.addClass('active_Link').parents("li:first").append(c);
				$('#breadcrumb-inactive').empty();
				var str = $(".active_Link").text();
				$('#breadcrumb-inactive').html(str);
			});
		},
		init: function(options) {
			options = $.extend({
				fixedWidth: false,
				startIndex: 0
			}, options);
			return this.each(function() {
				var list = $(this); // expects a ul
				var container = list.next("div"); //console.log(list, container);
				if (options.fixedWidth && typeof options.width != 'undefined') {
					list.children("li").css({
						"width": options.width + "px"
					});
				}
				container.show();
				var idx = options.startIndex;
				if (window.location.hash != '' && $('a[href*=' + window.location.hash + "]").length > 0) { // Do stuff. 
					$('a[href*=' + window.location.hash + "]").tabify("activate");
					$(window.location.hash).show(); // Then reset. 
					window.location.hash = '';
				} else {
					container.children("div:eq(" + idx + ")").show();
					list.children("li:eq(" + idx + ")").children("a").tabify("activate");
				}
				list.find("li a").each(function(e) {
					var $a = $(this);
					var $h = $a.attr("href");
					//console.log($h);
					$a.attr("href", "javascript:;");
					$a.bind({
						click: function() {
							if ($h.match(/\.htm/)) { // Its a URL. Load the content into a div.
								//console.log("Blah!");
								container.children("div:visible").fadeOut("fast", function() {
									var d = $(document.createElement("div")).addClass("html_container").appendTo(container);
									d.load($h).fadeIn("fast");
								});
							} else { // Remove all previously created html_container div's
								//console.log("Not a url");
								container.children("div:visible").fadeOut("fast", function() {
									$('.html_container').remove();
									$($h).fadeIn("fast");
								});
							}
							$a.tabify("activate");
						}
					}); //console.log($(this));
				})
			});
		}
	};
	var fxdisplay_methods = {
		debug: function(options) {
			//console.log("Debug called: ", $(this), options);
		},
		error: function(options) {
			alert("Debug called: ", $(this), options);
		},
		init: function(options) {
			var defaults = {
				duration: 4000,
				transition: false,
				speed: 1000,
				index: 0,
				h1_transition: 500,
				p_transition: 500
			}
			options = $.extend(defaults, options);
			return this.each(function() {
				var $a = $(this);
				//console.log(options);
				if (options.objects.length > 0) { // We have options!
					$a.children().remove(); // Clear it out!
					//console.log($a.position());
					for (var i in options.objects) {
						var c = options.objects[i];
						var outer_div = $(document.createElement("div")).addClass("fxd_outer").attr("direction", c.direction);
						var h1 = $(document.createElement("h1")).html(c.heading);
						var img = $(document.createElement("img")).attr("src", c.img_src);
						var p = $(document.createElement("p")).html(c.paragraph);
						h1.appendTo(outer_div);
						img.appendTo(outer_div);
						p.appendTo(outer_div);
						outer_div.appendTo($a);
						i++;
					} //Now lets select the first box
					var box = $a.children("div:first"); //Finally lets go through each box fading them in
					var counter = 0;
					var max = $a.children("div").size();
					box.fxdisplay('fx_animate', {
						idx: counter
					});
					var $id = setInterval(function() {
						if (box.length == 0) { // dont do anything, there's nothing there. 
							clearInterval($id);
						} else {
							counter++;
							box.fxdisplay('fx_animate', {
								idx: counter 
							});
							if (counter == (max - 1)) {
								counter = -1;
							} 
						}
					}, (options.h1_transition + options.p_transition) * 2); //set delay between each animation to 0.5 seconds
				} else {}
			});
		},
		fx_animate: function(options) {
			//console.log(this.children("div:eq(" + options.idx + ")"));
			return this.each(function() {
				var $box = $(this);
				$box.show();
				//console.log($box.children("h1"));
				$box.children("h1").animate({opacity: 1}, 1000, function(){ //console.log("Heading animation complete.")
				});
			});
		}
	}; // Method calling logic - do not change!!
	$.fn.fxdisplay = function(method) {
		if (fxdisplay_methods[method]) {
			return fxdisplay_methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return fxdisplay_methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.fxdisplay');
		}
	};
	$.fn.tabify = function(method) { // Method calling logic
		if (tabifyMethods[method]) {
			return tabifyMethods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return tabifyMethods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.tabify');
		};
		$.fn.carousel = function(options) {
			options = $.extend({
				duration: 4000,
				transition: false,
				speed: 1000
			}, options);
			$(this).bind('custom', function(event, param1, param2) {
				alert(param1 + "\n" + param2);
			});
			$(this).each(function() {
				var self = $(this);
				$nav = $(document.createElement("div")).addClass("carousel_Navigation");
				$ul = $(document.createElement("ul"));
				$items = self.children(); //console.log($items);
				$items.each(function() {
					$x = $(this).children("a:first");
					$li = $(document.createElement("li"));
					$a = $(document.createElement("a")).attr("href", "#").append($(document.createElement("span")).append($x.attr("title")));
					$a.live('click', function() {
						self.trigger('custom');
					});
					$li.append($a);
					$ul.append($li);
				});
				$nav.append($ul);
				$nav.hide();
				$nav_shown = false;
				self.after($nav);
				self.parent().bind({
					mouseenter: function(e) { //console.log("Mouseenter", $(e.target), $(e.target).is('div'));
						$nav.slideDown('fast');
					},
					mouseleave: function(e) { //console.log("Mouseleave", $(e.target), $(e.target).is('div'));
						$nav.slideUp('fast');
					}
				});
				var r = self.xfade({
					duration: 6000,
					speed: 800
				}); //console.log(self.children().length);
			});
		};
	}
})(jQuery); // This function extends jQuery with a utility function to create draggable mobile boxes for the comparison engine.
$.extend({
	createPanelElement: function(options) {
		var defaults = {
			'rootClass': 'mobilebox',
			'ribbonClass': null,
			'name': 'Default',
			'isBusiness': false,
			'summaryPoints': null,
			'panelsToRow': 3,
			'priceplanId': 1,
			'numberListItems': 3
		};
		options = $.extend(defaults, options);
		var $a = $(document.createElement("div")); // Main div - has a root class & title
		$a.addClass(options.rootClass);
		if (options.currentPos > 0 && (options.currentPos % options.panelsToRow == 0)) {
			$a.addClass("last");
		}
		$a.attr('title', options.name); // Add a ribbon class if one is passed		
		if (options.ribbonClass != null) {
			$a.addClass(options.ribbonClass);
		}
		var $list = $(document.createElement('ul')).addClass('arrowList'); // Add bullet points for Business mobiles.
		if (options.isBusiness) {
			if (options.summaryPoints != null) {
				var count = 0;
				$.each(options.summaryPoints, function(i, j) {
					if (count < options.numberListItems) {
						$list.append("<li>" + j + "</li>");
					}
					count++;
				});
			}
		} // Inner div
		var $ix = $(document.createElement('div')).addClass('mobile-wrapper'); // Handset detail 
		var $sp = $(document.createElement('div')).addClass('handsetDetails').append("<span class='model'>" + options.name + "<br/></span>"); // Image
		var $im = $(document.createElement('div')).addClass('handsetImage').append("<img border='0' height='98' width='49' src='/imgs/handsets/" + options.productCode + "-s.png' class='handsetImg' alt='" + options.name + "'>"); // Price
		var $ps;
		switch (options.priceplanId) {
		case 1:
		case 4:
			if (options.fromPrice == options.toPrice) {
				$ps = 'from ' + options.fromPrice;
			} else {
				$ps = 'from ' + options.fromPrice + " to " + options.toPrice;
			}
			break;
		case 3:
			$ps = 'only ' + options.fromPrice;
			break;
		default:
			$ps = 'Available';
			break;
		}
		var $pr = "<div class='handset-price'>" + $ps + "<span class='smaller'>on " + options.chosenPlan + "</span></div>"; // Controls 
		var $lk = $(document.createElement('a')).addClass('aleft').attr("href", options.isBusiness ? options.businessURL : options.consumerURL).text("Learn more");
		var $ct = $(document.createElement('div')).addClass('controls').append($lk);
		$ix.append($sp);
		$sp.appendTo($ix);
		if (isBusiness) $ix.append($list);
		$ix.append($im);
		if (!isBusiness) $ix.append($pr);
		$a.append($ix);
		$a.append($ct);
		$a.bind("click", function() {
			top.location.href = options.isBusiness ? options.businessURL : options.consumerURL;
		});
		return $a;
	}
});

function intify(str, defaultValue) {
	return /^\d+$/.test(str) ? parseInt(str) : defaultValue;
}
function crossFade(a, b) {
	a.remove();
	b.css({
		"opacity": 1
	});
}
function reachedMaxViews(cookieName, views) {
	if (typeof $.cookie(cookieName) != 'undefined' && $.cookie(cookieName) != 'null') { // Cookie is an object, and has a value.
		return parseInt($.cookie(cookieName)) > views;
	}
	return false;
}
function incrementViews(cookieName) {
	if (typeof $.cookie(cookieName) != 'undefined' && $.cookie(cookieName) != 'null' && $.cookie(cookieName) != 'NaN' && !isNaN($.cookie(cookieName))) { // Cookie is an object, and has a value.
		var p = parseInt($.cookie(cookieName));
		$.cookie(cookieName, p + 1);
	} else {
		$.cookie(cookieName, 1, {
			path: '/',
			expires: 1
		});
	}
}

