///<reference path="C:\Development\3rdParty\jQuery\jQuery.intellisense.js" />

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

/*************************************************************************
  This code is from Dynamic Web Coding at http://www.dyn-web.com/
  Copyright 2001-3 by Sharon Paine 
  See Terms of Use at http://www.dyn-web.com/bus/terms.html
  regarding conditions under which you may use this code.
  This notice must be retained in the code as is!
*************************************************************************/

// resize fix for ns4
var origWidth, origHeight;
if (document.layers) {
    origWidth = window.innerWidth; origHeight = window.innerHeight;
    window.onresize = function() { if (window.innerWidth != origWidth || window.innerHeight != origHeight) history.go(0); }
}

var cur_lyr;    // holds id of currently visible layer
function swapLayers(id) {
  if (cur_lyr) hideLayer(cur_lyr);
  showLayer(id);
  cur_lyr = id;
}

function showLayer(id) {
  var lyr = getElemRefs(id);
  if (lyr && lyr.css) lyr.css.visibility = "visible";
}

function hideLayer(id) {
  var lyr = getElemRefs(id);
  if (lyr && lyr.css) lyr.css.visibility = "hidden";
}

function getElemRefs(id) {
    var el = (document.getElementById)? document.getElementById(id): (document.all)? document.all[id]: (document.layers)? getLyrRef(id,document): null;
    if (el) el.css = (el.style)? el.style: el;
    return el;
}

// get reference to nested layer for ns4
// from old dhtmllib.js by Mike Hall of www.brainjar.com
function getLyrRef(lyr,doc) {
    if (document.layers) {
        var theLyr;
        for (var i=0; i<doc.layers.length; i++) {
        theLyr = doc.layers[i];
            if (theLyr.name == lyr) return theLyr;
            else if (theLyr.document.layers.length > 0) 
            if ((theLyr = getLyrRef(lyr,theLyr.document)) != null)
                    return theLyr;
      }
        return null;
  }
}


var Manager = {
    mStack: [],
    mInitialised: 0,
    
    Add: function(loader) {
        Manager.mStack.push(loader);        
    },
    
    Load: function() {
        var i,length;
        
        if (Manager.mInitialised == 0) {            
            length=Manager.mStack.length;
            for(i=0;i<length;i++) {
                Manager.mStack[i]();
            }
            Manager.mInitialised=1;
            Manager.mStack=[];
        }
    }
}

function Ticker(fireMethod, fireTime, oneShot, enabled)
{
    this.mFireMethod = fireMethod;
    this.mFireTime = fireTime;
    this.mOneShot = oneShot;
    
    this.Enable(enabled);
}

Ticker.prototype.Enable = function(enabled) {
    this.mEnabled = enabled;
    this.mTick = 0;
}

Ticker.prototype.Enabled = function() {
    return this.mEnabled;
}

Ticker.prototype.Tick = function(tickUnit) {
    if ( this.mEnabled ) {
        this.mTick += tickUnit;
        if ( this.mTick >= this.mFireTime ) {
            this.mTick -= this.mFireTime ;
            if ( this.mOneShot )
                this.mEnabled = 0 ;
            this.mFireMethod(this);
        }
    }
    
}

var TickerManager = {
    mTimers: [],
    mTickTime: 50,
    mEnabled: false,
    mTimeoutID: 0,

    Load: function() {  
    },
    
    Add: function(fireMethod,fireTime,oneShot,enabled) {
        var timer = new Ticker(fireMethod,fireTime,oneShot,enabled);
        TickerManager.mTimers.push(timer);
        return(timer);
        
    },
    
    Enable: function(enabled) {
    	if ( TickerManager.mEnabled != enabled ) {
	        TickerManager.mEnabled = enabled;
	        if ( enabled )
	        {
	            TickerManager.mTimeoutID = setTimeout(function(){TickerManager.Tick();},TickerManager.mTickTime);
	        } else {
	            if ( TickerManager.mTimeoutID )
	                clearTimeout(TickerManager.mTimeoutID);
	        }
	    }
    },
    
    Tick: function() {
        
        if ( TickerManager.mEnabled ) {
            var i,length;
            
            length = TickerManager.mTimers.length;
            for( i = 0;i < length; i++ ) {
                if ( TickerManager.mTimers[i].mEnabled ) 
                    TickerManager.mTimers[i].Tick(TickerManager.mTickTime);
            }
            TickerManager.mTimeoutID = setTimeout(function(){TickerManager.Tick();},TickerManager.mTickTime);
        }
    }
}
Manager.Add(function(){TickerManager.Load();});




function TrackURL(trackingURL, instanceID) {
    if (trackingURL) {
        if (typeof pageTracker != 'undefined') {
            pageTracker._trackPageview(trackingURL);
        }
        if (typeof Tracker != 'undefined') {
            Tracker(trackingURL, instanceID);       
        }
    }
}

function TrackExitPage(sender, instanceID) {
    if (sender) {
        TrackExitPageURL(sender.href, instanceID);
    }
    return false;
}

function TrackExitPageURL(url, instanceID) {
    if (url) {
        TrackURL('/exit.html/' + url, instanceID);
    }
    return false;
}

function TrackExitPageURLEnc(url, instanceID) {
    if (url) {
        TrackURL('/exitenc.html/' + url, instanceID);
    }
    return false;
}

function trackTransferExitPage(url, instanceID) {
	if (url) {
		TrackExitPage(url,instanceID);
		if ( $('#transferPage').length == 0 ) {
			$(document.body)
				.append('<form name="transferPage" id="transferPage" action="' + gWebRoot + '/transfer.html" target="_blank" method="POST" style="display:none;"><input name="uid" id="uid" type="hidden" value="' + url + '"></form>');
		} else {
			$('#uid').val(url);
		}
		$('#transferPage').submit();
	}
	return false;
}


function ShowMenuItem(sender, container, showCSS, hideCSS) {
    var containerHTML = document.getElementById(container);
    if (containerHTML) {
        var items = containerHTML.getElementsByTagName('a');
        for (var i = 0 ; i < items.length ; i++) {
            itemDiv = document.getElementById(items[i].id + 'c');
            if (itemDiv) {
                if (items[i].id == sender.id) {
                    itemDiv.className = showCSS;
                } else {
                    itemDiv.className = hideCSS;
                }
            }
        }
    }
}

function TrackMenuItem(sender, container, showCSS, hideCSS, trackingURL, instanceID) {
    ShowMenuItem(sender, container, showCSS, hideCSS);
    TrackURL(trackingURL, instanceID);
}


var gaVersion = navigator.appVersion.split("MSIE");
var gVersion = parseFloat(gaVersion[1]);

function CorrectPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   if ((gVersion >= 5.5) && (gVersion < 7) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = "class='pngFix" 
            if ( img.className ) imgClass += " " + img.className ;
            imgClass += "' ";
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='crop');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}

function FixPNG(myImage) 
{
    if ((gVersion >= 5.5) && (gVersion < 7) && (document.body.filters)) 
    {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
       var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
       var imgTitle = (myImage.title) ? 
                     "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' "
       var imgStyle = "display:inline-block;" + myImage.style.cssText
       var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width 
                  + "px; height:" + myImage.height 
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
       myImage.outerHTML = strNewHTML     
    }
}

function AddHandler(target, fn, handlerName)
{
    if ( target.addEventListener )
        target.addEventListener(handlerName, fn, false)
    else if ( target.attachEvent )
        target.attachEvent('on' + handlerName, fn)
}



function Querystring()
{
    // get the query string, ignore the ? at the front.
    var querystring=location.search.substring(1,location.search.length);

    // parse out name/value pairs separated via &
    var args = querystring.split('&');

    // split out each name = value pair
    for (var i = 0; i < args.length; i++)
    {
        var pair = args[i].split('=');

        // Fix broken unescaping
        temp = unescape(pair[0]).split('+');
        name = temp.join(' ');

        temp = unescape(pair[1]).split('+');
        value = temp.join(' ');

        this[name]=value;
    }
}


Querystring.prototype.get = function (strKey,strDefault)
{
    var value=this[strKey];
    if (value==null)
    {
        value=strDefault;
    }

    return value;
}

var gQuerystring = new Querystring();

var gCookie = {
	get: function(name,defaultValue) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return defaultValue;
	},
	remove: function(name) {
		this.set(name,'',-1);
	},
	set: function(name,value,days) {
		var expires = '';
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			expires = '; expires='+date.toGMTString();
		}
		var cookie = name+'='+escape(value)+expires+'; path=/';
		document.cookie = cookie;
	}
	
}


function AddPageToFavourites()
{
    AddFavourite(document.location.href,document.title);
}

function AddFavourite(url,title)
{
    if (window.sidebar) { 
        window.sidebar.addPanel(title, url,""); 
    } else if( document.all ) {
        window.external.AddFavorite( url, title);
    } else if( window.opera && window.print ) {
        return true;
    }
}


function getScroll() {
    var p = {x: 0, y: 0};
    var e = document.documentElement;
    var b = document.body;
    if ( e && ( e.scrollLeft || e.scrollTop ) ) {
        p.x = e.scrollLeft;
        p.y = e.scrollTop;
    }
    else if ( b && ( b.scrollLeft || b.scrollTop ) ) {
        p.x = b.scrollLeft;
        p.y = b.scrollTop;
    }
    else if ( window.pageXOffset || window.pageYOffset ) {
        p.x = window.pageXOffset;
        p.y = window.pageYOffset;
    }
    else if( window.scrollX || window.scrollY ) {
        p.x = window.scrollX;
        p.y = window.scrollY;
    }
    return p;
}

function getOffset(element) {
    var o = {x: 0, y: 0};
    while (element && $(element).css("position") != "relative") {
        o.x += element.offsetLeft;
        o.y += element.offsetTop;
    element = element.offsetParent;
    }
    return o;
}

var gId = 0;

function newId(prefix) {
	if ( !prefix )
		prefix = 'id';
	prefix += gId ;
	gId += 1;
	return prefix;
}

var gWordDefinitions = new Object();

var TIMER_ENTER_PREFIX = 'timent';
var TIMER_LEAVE_PREFIX = 'timlea';
var ANIMATING_PREFIX = 'anim';
var VISIBLE_PREFIX = 'visible';
var DEFINITION_PREFIX = 'def';

function glossaryHide(id) {
	gWordDefinitions[ANIMATING_PREFIX + id] = true;
	$('#'+id).find('div.wg_popup')
		.fadeOut("fast",function() {
			var id = $(this).parent().attr('id');
			gWordDefinitions[ANIMATING_PREFIX + id] = false;
			gWordDefinitions[VISIBLE_PREFIX + id] = false;
			$(this).parent().attr('class','wg');
			$(this).hide();		// Fix to ensure popups are hidden when parent div is already hidden
		});
}

function glossaryShow(prefix, id) {
	if ( !gWordDefinitions[VISIBLE_PREFIX + id] ) {
		var jThis = $("#" + id);
		var elem = jThis.get(0);
		var popup = jThis.find('div.wg_popup');

		if ( popup.length == 0 ) {
			var def = jThis.find('span.wg_def').html();

			if ( !def )
				def = jThis.html();
			popup = $('<div class="wg_popup"><div class="wg_popup_def">Loading definition...</div><div class="wg_popup_close">close [x]</div></div>');
			$(popup).find('div.wg_popup_close')
				.click(function() {
					glossaryHide($(this).parent().parent().attr('id'));
				});
			jThis.append(popup);
		}
		var scroll = getScroll();
		var ofs = getOffset(elem);

		var x = ofs.x - 200;
		if ( x < scroll.x )
			x = ofs.x + elem.offsetWidth;

		var y = ofs.y - 150;
		if ( y < scroll.y)
			y = ofs.y + elem.offsetHeight;

		glossaryCloseAllExcept(id);
		gWordDefinitions[ANIMATING_PREFIX + id] = true;
		gWordDefinitions[VISIBLE_PREFIX + id] = true;
		popup.attr('style','left: ' + x + 'px; top: ' + y + 'px;')
			.fadeIn("fast",function() {
				var id = $(this).parent().attr('id');
				gWordDefinitions[ANIMATING_PREFIX + id] = false;
				if ( !gWordDefinitions[DEFINITION_PREFIX + id] ) {
					gWordDefinitions[DEFINITION_PREFIX + id] = true;
					$(this).find("div.wg_popup_def")
						.load(prefix+'/glossary.ajax',{word: def},function(responseText, textStatus, httpRequest) {
							if ( textStatus != 'success' )
								$(this).html('Definition not found');
						});
				}
			});

		elem.className = 'wg_hi';
	}
}

function glossaryCloseAllExcept(id) {
	$('span.wg_hi:not(#' + id + ')').each(function() {
		if ( gWordDefinitions[VISIBLE_PREFIX + this.id] ) {
			glossaryHide(this.id);
		}
	});
}

function glossaryInit(prefix) {	
	$.get(prefix+'/glossary.ajax',{gInit: 1},function(gStream) {
			var gTerms = gStream.split("#");
			for (def in gTerms) {
				if (gTerms[def].length == 1)
					break;	// Bug fix to prevent conflict with jEasyUI.js
				var gException = false;
				if (gTerms[def].substring(0,1) == '!') {
					gException = true;
					gTerms[def] = gTerms[def].substring(1);
				}
				var gRegEx = new RegExp('\\b' + gTerms[def] + '\\b','gi');
				var gDefined = false;
				$('.wg_src').each(function() {
					var gHtml = $(this).html();
					if (gHtml.search(gRegEx) != -1 && !gDefined) {
						var gTemp = gHtml;
						var gIndex = 0;
						gHtml = '';
						while (gTemp.search(gRegEx) != -1 && !gDefined) {
							gIndex = gTemp.search(gRegEx);
							var gSplit = gTemp.substring(0, gIndex);
							var gTestHtml = gHtml + gSplit;
							var gLastTagOpen = gTestHtml.lastIndexOf('<');
							var gLastTagClose = gTestHtml.lastIndexOf('>');
							if (gLastTagOpen > gLastTagClose) {
								gHtml += gSplit + gTemp.substring(gIndex, gIndex + gTerms[def].length);
								gTemp = gTemp.substring(gIndex + gTerms[def].length);
								continue;
							}
							var gIndexDef = gSplit.lastIndexOf('<span class="wg');
							if (gIndexDef > gSplit.indexOf('</span>', gSplit.indexOf('</span>', gIndexDef) + 1)) {
								var gIndexEnd = 0;
								if (gSplit.lastIndexOf('<span class="wgx">') == gIndexDef)
									gIndexEnd = gTemp.indexOf('</span>', gIndex) + 7;
								else
									gIndexEnd = gTemp.indexOf('</span>', gTemp.indexOf('</span>', gIndex) + 1) + 7;
								gHtml += gTemp.substring(0, gIndexEnd);
								gTemp = gTemp.substring(gIndexEnd);
							}
							else {
								if (gException) {
									gHtml += gSplit + '<span class="wgx">';
									gHtml += gTemp.substring(gIndex, gIndex + gTerms[def].length) + '</span>';
									gTemp = gTemp.substring(gIndex + gTerms[def].length);
								}
								else {
									gHtml += gSplit + '<span class="wg"><span class="wg_def">';
									gHtml += gTerms[def] + '</span>' + gTemp.substring(gIndex, gIndex + gTerms[def].length) + '</span>';
									gTemp = gTemp.substring(gIndex + gTerms[def].length);
									gDefined = true;
								}
							}
						}
						gHtml += gTemp;
						$(this).html(gHtml);
					}
				});
			}
			$('span.wg').each(function() {
				if ( !this.id ) this.id = newId('wg');
				var timer = TickerManager.Add(function(ticker){
					glossaryShow(this.mPrefix, this.mId);
				},200,true,false);
				timer.mId = this.id;
				timer.mPrefix = prefix;
				gWordDefinitions[TIMER_ENTER_PREFIX + this.id] = timer;
		
				timer = TickerManager.Add(function(ticker){
					glossaryHide(this.mId);
				},1500,true,false);
				timer.mId = this.id;
				gWordDefinitions[TIMER_LEAVE_PREFIX + this.id] = timer;
		
				gWordDefinitions[VISIBLE_PREFIX + this.id] = false;
				gWordDefinitions[ANIMATING_PREFIX + this.id] = false;
		
			}).hover(function(e)  {
				if ( !gWordDefinitions[ANIMATING_PREFIX + this.id] ) {
					gWordDefinitions[TIMER_ENTER_PREFIX + this.id].Enable(true);
					gWordDefinitions[TIMER_LEAVE_PREFIX + this.id].Enable(false);
				}
			},function () {
	
				gWordDefinitions[TIMER_ENTER_PREFIX + this.id].Enable(false);
				if ( gWordDefinitions[VISIBLE_PREFIX + this.id] )
					gWordDefinitions[TIMER_LEAVE_PREFIX + this.id].Enable(true);
			});
		    TickerManager.Enable(true);
		}
	);
}

function openMenu(id,noSlide) {
	var menuHide = $('.subMenuSide:visible');
	var menuShow = $('#'+id + ':hidden');
	var headId = id + 'head';
	var menuHead = $('#' + headId);

	if ( !noSlide || !menuHead.hasClass('subMenuHeaderOpen') ) {
		if ( noSlide ) {
			menuHide.hide();
			menuShow.show();
		} else {
			menuHide.slideUp('fast');
			menuShow.slideDown('fast');
		}
		$('.subMenuHeader[id!=\'' + headId + '\']')
			.removeClass('subMenuHeaderOpen');
		if ( menuHead.hasClass('subMenuHeaderOpen') ) {
			menuHead.removeClass('subMenuHeaderOpen');
			gCookie.remove('sideMenu');
		} else {
			menuHead.addClass('subMenuHeaderOpen');
			gCookie.set('sideMenu',id);
		}
	}
	return false;
}

function openSideMenu(defaultId) {
	var sideMenu = gCookie.get('sideMenu');
	if ( sideMenu ) {
		openMenu(sideMenu,true);
	} else if ( defaultId ) {
		openMenu(defaultId);
	}
		
}

/*
 * jQuery AntiLeak for IE
 *
 * Copyright (c) 2009 Barcode Computers Ltd.
 *
 */ 
(function($) { // hide the namespace

	function AntiLeak() { }
	$.preventLeaks = new AntiLeak();

	$.extend(AntiLeak.prototype, {
		_checkExternalClick: function(event) { }
	});

	$.fn.preventLeaks = function() {
		if ( !$.preventLeaks._isInit ) {
			$(document)
				.mousedown($.preventLeaks._checkExternalClick)
				.find('body')
				.append($.preventLeaks.dpDiv);
			$.preventLeaks._isInit = true;
		}
	};

})(jQuery); 

$(function() {
		$(this).preventLeaks(); 
	});

/* Gifts popup scripts */

function showHelp(sender) {
	// Opens a small popup to display help text
	// sender = element that triggers popup, containing help text content in a child element
	
	$("#pdl_help_wrapper").html($(sender).find(".helptext").html());
	$("#pdl_help").dialog("open");
}

var gi_cache = {};

function showGifts(did, prdid) {
	// Opens the gifts popup
	// did = product_deal_id, required to populate upper panel and to find gifts
	// prdid = (optional) product_reseller_deal_id, if only one gift is to be shown

	if (prdid != '' && typeof(gi_cache["prdid" + prdid]) != "undefined") {
		$(".gift_table").html(gi_cache["prdid" + prdid]);
		$(".gift_error").hide();
		$(".gift_wait").hide();
		$(".gift_table").show();
		$("#gifts_popup").dialog("open");
		return;
	}
	else if (prdid == '' && did != '' && typeof(gi_cache["did" + did]) != "undefined") {
		$(".gift_table").html(gi_cache["did" + did]);
		$(".gift_error").hide();
		$(".gift_wait").hide();
		$(".gift_table").show();
		$("#gifts_popup").dialog("open");
		return;
	}
	
	if ($("#BPDL" + did).length > 0)
		deal_row = "#BPDL" + did;
	else if ($("#TPDL" + did).length > 0)
		deal_row = "#TPDL" + did;
	else if ($("#APDL" + did).length > 0)
		deal_row = "#APDL" + did;
	else
		deal_row = "#DPDL" + did;
	
	var network_name = $(deal_row + " .detailbottomitem001a img").attr("alt");
	var network_image_name = $(deal_row + " .detailbottomitem001a img").attr("src");
	var tariff_name = $(deal_row + " .gi_tn").html();
	var contract_length = $(deal_row + " .gi_cl").text();
	var contract_length_text = $(deal_row + " .gi_clt").html();
	var monthly_cost_text = $(deal_row + " .detailbottomitem004 strong").html();
	var handset_cost_text = $(deal_row + " .detailbottomitem003").html();
	var previous_cost_text = $(deal_row + " .gi_pct").html();
	var freephone = $(deal_row + " .gi_fp").text();
	var deal_highlights = new Array;
	$(deal_row + " .gi_dh").each(function () {
		deal_highlights.push($(this).html());
	});

	if (monthly_cost_text.indexOf(".") >= 0)
		price_text = '<br /><strong>' + monthly_cost_text.replace(".", '<small>.') + '</small></strong><br />';
	else
		price_text = '<br /><strong>' + monthly_cost_text + '</strong><br />';
	if (contract_length > 0)
		price_text = price_text + "per month";

	$(".gi_network_name").text(network_name);
	$(".gift_reseller span").attr("title", $(".gift_reseller span").attr("title").replace(/\[network_name\]/, network_name));
	if (freephone != "" && freephone != undefined)
		$(".gift_dealsummary .freephone").show();
	else
		$(".gift_dealsummary .freephone").hide();
	$(".gift_dealnetwork img").attr("src", network_image_name.replace("/tariff/", "/callout/"));
	$(".gift_dealnetwork img").attr("alt", network_name);
	$(".gift_dealtitletext").html(tariff_name + "<br />" + contract_length_text);
	$(".gift_price").html(price_text);
	if (previous_cost_text != "" && previous_cost_text != undefined) {
		if (previous_cost_text.substr(0, 4) == "was ") {
			$(".gift_previouscost .floatLeft").text("Was:");
			$(".gift_previouscost .floatRight").text(previous_cost_text.substr(5));
		}
		else {
			$(".gift_previouscost .floatRight").text(previous_cost_text);
		}
		$(".gift_previouscost").show();
	}
	else
		$(".gift_previouscost").hide();
	if (contract_length > 0) {
		if (handset_cost_text.substr(0,5) == "From ") {
			$(".gift_handsetcost .floatLeft").text("From:");
			$(".gift_handsetcost .floatRight").text($(deal_row + " .detailbottomitem003 .gi_hc").text());
		}
		else {
			$(".gift_handsetcost .floatLeft").text($("#gi_inc").text() + ":");
			$(".gift_handsetcost .floatRight").text($(deal_row + " .detailbottomitem003 .gi_hc").text());
		}
		$(".gift_handsetcost").show();
	}
	else
		$(".gift_handsetcost").hide();
	
	$(".gift_dealhighlights ul").html("");
	if (deal_highlights.length > 0) {
		for (i in deal_highlights)
			$(".gift_dealhighlights ul").append("<li>" + deal_highlights[i] + "</li>");
	}
	else {
		$(".gift_dealhighlights ul").append("<li>" + $(deal_row + " .gi_min") + "</li>");
		$(".gift_dealhighlights ul").append("<li>" + $(deal_row + " .gi_txt") + "</li>");
		$(".gift_dealhighlights ul").append("<li>" + $(deal_row + " .gi_f1") + "</li>");
		$(".gift_dealhighlights ul").append("<li>" + $(deal_row + " .gi_f2") + "</li>");
	}
	
	$(".gift_table").hide();
	$(".gift_error").hide();
	$(".gift_wait").show();
		
	$("#gifts_popup").dialog("open");
	
	$.ajax({url: gWebRoot + '/gifts.ajax',
		type: 'GET',
		cache: false,
		data: { did: did, prdid: prdid, inline_name_cap: $("#gi_inc").text() },
		success: function(html) {
			if (html.replace(/^\s*/, "").replace(/\s*$/, "") != "") {
				$(".gift_table").html(html);
				$(".gift_table").show();
				$(".gift_wait").hide();
				if (prdid != "")
					gi_cache["prdid" + prdid] = html;
				else
					gi_cache["did" + did] = html;
			}
			else {
				$(".gift_error").show();
				$(".gift_wait").hide();
			}
		},
		error: function() {
			$(".gift_error").show();
			$(".gift_wait").hide();
		}
	});
}

function toggleGiftRow(id) {
	// Toggles the 'more info' area of a gift row so as to
	// show or hide the long description and image gallery
	// and hides other open 'more info' rows and reseller info
	// id = product_reseller_deal_id, 'id' of parent 'gift_row' class
	
	var visible = true;
	if ($("#prdid_" + id + " .gift_expander:first a").text() == "More...")
		visible = false;
	
	$(".gift_row").each(function() {
		$(this).find(".gift_expander:first a").text("More...");
		$(this).find(".gift_moreinfo:visible").slideUp();
		$(this).find(".gift_resellerinfo").hide();
	});
	if (!visible) {
		$("#prdid_" + id + " .gift_expander:first a").text("Hide details");
		$("#prdid_" + id + " .gift_moreinfo").slideDown();
	}
}

function toggleResellerInfo(id) {
	// Toggles the 'why buy from this reseller' area of a gift row
	// when the 'more info' area is showing
	// id = product_reseller_deal_id, 'id' of parent 'gift_row' class
	$("#prdid_" + id + " .gift_resellerinfo").slideToggle();
}

function giftGallery(id, step) {
	// Controls the image gallery for a gift row
	// id = product_reseller_deal_id, 'id' of parent 'gift_row' class
	// step = step by which to cycle through images, either -1 or +1
	if (step != -1 && step != 1)
		return;
	step = parseInt(step);
	
	var index = parseInt($("#prdid_" + id + " .gift_gallery_index").text());
	var count = parseInt($("#prdid_" + id + " .gift_gallery_count").text());

	var next = 0;
	if ((index + step) < 1)
		next = count;
	else if ((index + step) > count)
		next = 1;
	else
		next = index + step;
	
	$("#giftImg_" + id + "_" + index).fadeOut();
	$("#giftImg_" + id + "_" + next).fadeIn();
	$("#prdid_" + id + " .gift_gallery_index").text(next);
}

/* End of gifts popup scrips */

function addRecentProduct(id) {
	// Adds a product to the recent products cookie
	// id - product_class_id
	if (id === undefined || id == '')
		return;
	var maxRp = 4;	// Only 3 will be shown, but space left for product currently being viewed
	var newRp = id;
	var rp = gCookie.get('recentProducts');
	if (rp) {
		rp = decodeURIComponent(rp);
		var rpArr = rp.split(',');
		for (i = 0; i < maxRp - 1; i++) {
			if (i >= rpArr.length)
				break;
			else if (rpArr[i] != id)
				newRp = newRp + ',' + rpArr[i];
			else
				maxRp++;
		}
	}
	gCookie.remove('recentProducts');
	gCookie.set('recentProducts', newRp);
}

function showRecentProducts(id) {
	// Updates recent products box using JQuery AJAX call
	// id - current product_class_id being viewed (if applicable)
	if (id == undefined)
		id = '';
	$('#recentproducts').hide();
	var prods = gCookie.get('recentProducts');
	if (prods) {
		$.get(gWebRoot + '/recent-products.ajax', { pcid: decodeURIComponent(prods), id: id }, function(html) {
				if ($.trim(html)) {
					$('#recentproducts').html(html);
					$('#recentproducts').show();
				}
			}
		);
	}
}

/* Specifications & compare phones scripts */

var gSpecsIndex2 = 0;
var gSpecsIndex3 = 0;
var gSpecsStep = 10;

function specsChange(group_id) {
	if (group_id < 1) {
		if ($('#specs_expander').hasClass('specs_active')) {
			$('.specs_table .specs_item').hide();
			$('.specs_table .specs_active').removeClass('specs_active');
			$('#specs_expander span').html('Show <b>all</b> specifications');
		}
		else {
			$('.specs_table .specs_item').show();
			$('.specs_table .specs_header a').addClass('specs_active');
			$('#specs_expander').addClass('specs_active');
			$('#specs_expander span').html('Hide <b>all</b> specifications');
		}
	}
	else {
		if ($('.specs_table #specs-' + group_id).hasClass('specs_active')) {
			$('.specs_table .specs-' + group_id).hide();
			$('.specs_table #specs-' + group_id).removeClass('specs_active');
		}
		else {
			$('.specs_table .specs-' + group_id).show();
			$('.specs_table #specs-' + group_id).addClass('specs_active');
		}
	}
	
	if ($('.specs_table .specs_header a.specs_active').length == $('.specs_table .specs_header a').length) {
		$('#specs_expander').addClass('specs_active');
		$('#specs_expander span').html('Hide <b>all</b> specifications');
	}
	else if ($('#specs_expander').hasClass('specs_active')) {
		$('#specs_expander').removeClass('specs_active');
		$('#specs_expander span').html('Show <b>all</b> specifications');
	}
}

function specsPopup() {
	$('.specs_popup_table .specs_input').val('');
	$('#specs_popup').dialog('open');
	if ($('#specs_input_2:visible').length > 0)
		$('#specs_input_2').focus();
	else if ($('#specs_input_3:visible').length > 0)
		$('#specs_input_3').focus();
}

function specsClose() {
	$('#specs_popup').dialog('close');
}

function specsClear(col) {
	$('#specs_name_' + col + ' h3').text('Search for a phone to compare:');
	$('#specs_image_' + col + ' .specs_status').remove();
	$('#specs_image_' + col + ' .specs_button').remove();
	$('#specs_image_' + col + ' .specs_clear').remove();
	$('#specs_image_' + col + ' .specs_image').remove();
	$('.specs_popup_table .specs_item').each(function() {
		$(this).find('td:nth-child(' + (parseInt(col) + 1) + ')').html('');
		$(this).find('td:nth-child(' + (parseInt(col) + 1) + ')').addClass('specs_item_default');
	});
	$('#specs_image_' + col + ' form').show();
	$('#specs_input_' + col).focus();
	specsReview();
}

function specsReview() {
	$('.specs_popup_table .specs_item').each(function() {
		if ($(this).find('td:nth-child(2)').hasClass('specs_item_default')
				&& $(this).find('td:nth-child(3)').hasClass('specs_item_default')
				&& $(this).find('td:nth-child(4)').hasClass('specs_item_default')
				&& $(this).hasClass('specs_hide'))
			$(this).hide();
		else
			$(this).show();
	});
}

function specsList(col, dir) {
	var start = 0;
	
	if (col == 2)
		start = gSpecsIndex2;
	else if (col == 3)
		start = gSpecsIndex3;
	else
		return false;
		
	if (dir < 0)
		start -= gSpecsStep;
	else if (dir > 0)
		start += gSpecsStep;
	else
		return false;
	
	if (start < 0)
		start = 0;
	else if (start >= $('#specs_image_' + col + ' li').length - 2)
		start = $('#specs_image_' + col + ' li').length - 2 - gSpecsStep;

	$('#specs_image_' + col + ' li').each(function(i) {
		if (!$(this).hasClass('specs_list_prev') && !$(this).hasClass('specs_list_next')) {
			if (i < start || i >= start + gSpecsStep)
				$(this).hide();
			else
				$(this).show();
		}
	});
	
	if (start >= gSpecsStep)
		$('#specs_image_' + col + ' .specs_list_prev').show();
	else
		$('#specs_image_' + col + ' .specs_list_prev').hide();
	
	if (start < $('#specs_image_' + col + ' li').length - 2 - gSpecsStep)
		$('#specs_image_' + col + ' .specs_list_next').show();
	else
		$('#specs_image_' + col + ' .specs_list_next').hide();
		
	if (col == 2)
		gSpecsIndex2 = start;
	else if (col == 3)
		gSpecsIndex3 = start;
}

function getSpecs(col, pcid) {
	$('#specs_image_' + col + ' center b').html('Searching...');
	var kw = $('#specs_input_' + col).val();
	if (pcid == undefined)
		pcid = '';
	$.ajax({url: gWebRoot + '/specifications.ajax',
		type: 'GET',
		cache: false,
		data: { kw: kw, pcid: pcid, col: col },
		dataType: 'json',
		success: function(data) {
			if (data.results != undefined) {
				if (data.results.length == 0) {
					$('#specs_image_' + col + ' center b').html('No results found');
					return false;
				}
				if (col == 2)
					gSpecsIndex2 = 0;
				else if (col == 3)
					gSpecsIndex3 = 0;
				$('#specs_image_' + col + ' center b').html(data.results.length + ' results found');
				if ($('#specs_image_' + col + ' ul').length > 0)
					$('#specs_image_' + col + ' ul').remove();
				$('#specs_image_' + col).append('<ul></ul>');
				$.each(data.results, function(i, result) {
					$('#specs_image_' + col + ' ul').append('<li' + (i > (gSpecsStep - 1) ? ' style="display:none;"' : '') + '><a onclick="getSpecs(' + col + ', ' + result.id + ')" title="' + result.name + '">' + result.name + '</a>' + (result.status != '' ? ' (' + result.status + ')' : '') + '</li>');
				});
				if (data.results.length > gSpecsStep)
					$('#specs_image_' + col + ' ul').append('<li class="specs_list_prev"><a onclick="specsList(' + col + ', -1);">&laquo; Back</a></li><li class="specs_list_next"><a onclick="specsList(' + col + ', 1);">More &raquo;</a></li>');
			}
			else if (data.product != undefined) {
				$('#specs_image_' + col + ' center b').html('');
				$('#specs_image_' + col + ' ul').remove('');
				$('#specs_image_' + col + ' form').hide();
				$('#specs_input_' + col).val('');
				if ($('#specs_image_' + col + ' .specs_image').length > 0)
					$('#specs_image_' + col + ' .specs_image').remove();
				if ($('#specs_image_' + col + ' .specs_status').length > 0)
					$('#specs_image_' + col + ' .specs_status').remove();
				if ($('#specs_image_' + col + ' .specs_button').length > 0)
					$('#specs_image_' + col + ' .specs_button').remove();
				if ($('#specs_image_' + col + ' .specs_clear').length > 0)
					$('#specs_image_' + col + ' .specs_clear').remove();
				if (data.product.url != '') {
					$('#specs_name_' + col + ' h3').html('<a href="' + data.product.url + '?ref=compare" title="' + data.product.name + '">' + data.product.name + '</a>');
					$('#specs_image_' + col).append('<a class="specs_image" href="' + data.product.url + '?ref=compare" title="' + data.product.name + '"><img src="' + data.product.imageUrl + '" /></a>');
					$('#specs_image_' + col).append('<span class="specs_status">' + data.product.status + '</span><a class="specs_button" href="' + data.product.url + '?ref=compare" title="' + data.product.name + '">MORE INFO</a><a class="specs_clear" onclick="specsClear(' + col + ');">Search for another phone</a>');
				}
				else {
					$('#specs_name_' + col + ' h3').html(data.product.name);
					$('#specs_image_' + col).append('<img class="specs_image" src="' + data.product.imageUrl + '" />');
					$('#specs_image_' + col).append('<span class="specs_status">' + data.product.status + '</span><a class="specs_clear" onclick="specsClear(' + col + ');">Search for another phone</a>');
				}
				$.each(data.product.specifications, function(i, specification) {
					var td = $('#specs_item_' + specification.id + '_' + col);
					var def = $('#specs_item_' + specification.id + '_0');
					if (def.hasClass('specs_boolean')) {
						if (specification.value == '') {
							td.html(def.html());
							td.addClass('specs_item_default');
						}
						else if (specification.value == '0.00') {
							td.html(def.html().replace('tick.gif', 'cross.gif').replace('alt="Yes"', 'alt="No"') + '  ' + specification.text);
							td.removeClass('specs_item_default');
						}
						else {
							td.html(def.html().replace('cross.gif', 'tick.gif').replace('alt="No"', 'alt="Yes"') + '  ' + specification.text);
							td.removeClass('specs_item_default');
						}
					}
					else if (specification.text == '') {
							td.html(def.html());
							td.addClass('specs_item_default');
					}
					else {
						td.html(specification.text);
						td.removeClass('specs_item_default');
					}
				});
				specsReview();
			}
			else {
				$('#specs_image_' + col + ' center b').html('An error occurred');
			}
		},
		error: function(x, y, z) {
			$('#specs_image_' + col + ' center b').html('An unknown error occurred');
		}
	});
	return false;
}

/* End of specifications & compare phones scripts */

function extractParamFromUri(uri, paramName) {
	if (!uri)
		return;
	var uri = uri.split('#')[0];	// Remove anchor.
	var parts = uri.split('?');		// Check for query params.
	if (parts.length == 1)
		return;
	var query = decodeURI(parts[1]);

	// Find url param.
	paramName += '=';
	var params = query.split('&');
	for (var i = 0, param; param = params[i]; i++) {
		if (param.indexOf(paramName) === 0)
			return unescape(param.split('=')[1]);
	}
}

var _gaq = _gaq || [];
var socialFBLoaded = false;
var socialTimer = setInterval("socialInit()", 500);
var socialTimeout = setTimeout("socialDone()", 5000);

function socialInit() {
	try {
		if (socialFBLoaded && twttr && twttr.events)
			socialDone();
		if (FB && FB.Event && FB.Event.subscribe)
			FB.Event.subscribe('xfbml.render', function(r) {
				socialFBLoaded = true;
			});
	}
	catch (e) {
	}
}

function socialDone() {
	clearInterval(socialTimer);
	clearInterval(socialTimeout);
	try {
		if (FB && FB.Event && FB.Event.subscribe) {
			FB.Event.subscribe('edge.create', function(targetUrl) {
				_gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]);
			});
			FB.Event.subscribe('edge.remove', function(targetUrl) {
				_gaq.push(['_trackSocial', 'facebook', 'unlike', targetUrl]);
			});
			/* FB.Event.subscribe('message.send', function(targetUrl) {
				_gaq.push(['_trackSocial', 'facebook', 'send', targetUrl]);
			});	*/
		}
		if (twttr && twttr.events) {
			twttr.events.bind('tweet', function(event) {
				if (event) {
					var targetUrl;
					if (event.target && event.target.nodeName == 'IFRAME') {
						targetUrl = extractParamFromUri(event.target.src, 'url');
					}
					_gaq.push(['_trackSocial', 'twitter', 'tweet', targetUrl]);
				}
			});
		}
		$('#emailContent input[type=submit]').bind('click', function() {
			_gaq.push(['_trackSocial', 'email', 'send', window.location.href]);
		});
	}
	catch(e) {
	}
	$('.socials-fade').fadeIn('fast');
}
