/*############################################################################################
##									Generic UI Functions									##
############################################################################################*/

function ReadCookie (name)
{
	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 "";
}

function WriteCookie (name,value,date)
{
	document.cookie = name+"="+value+"; expires="+date+"; path=/";
}


function GotoTop()
{
	if(document.body.scrollTop)
	{
		document.body.scrollTop=0;
	}else{
		document.body.pageYOffset=0;
	}
}

/*############################################################################################
##									InfoItem Functions										##
############################################################################################*/

function InfoItem (){};

//InfoItem.HTTPRequest	= null;
InfoItem.prototype.Initialised	= false;
InfoItem.prototype.Layer		= null;
InfoItem.prototype.Content		= null;
InfoItem.prototype.DropShadow	= null;
InfoItem.prototype.ContainerID	= null;
InfoItem.prototype.ContentID	= null;

InfoItem.prototype.Init = function ()
{
	if(this.Initialised) return;
	this.Initialised				= true;
	this.Layer						= document.getElementById(this.ContainerID);
	this.Layer.className			= "InfoItem";
	this.Layer.style.display		= "none";
	this.Content					= document.getElementById(this.ContentID);
	this.Content.className			= "InfoContent";
	this.Content.style.display		= "none";
	this.Content.style.height		= "412px" //This is the default height for backwards compatibility. 
}

InfoItem.prototype.Show = function(o,height)
{
	this.Content.src					= o.url;
	this.Layer.style.display			= "block";
	this.Content.style.display			= "block";
	this.Content.style.visibility		= "visible";
	var y = document.body.clientHeight? document.body.scrollTop : pageYOffset;
	document.getElementById(this.ContainerID).style.top = (y+30)+"px";
	if(height!=null) this.Content.style.height = height+"px" //dynamic height on iFrame
}

InfoItem.prototype.FlashShow = function(o,url)
{
	this.Layer.style.display			= "block";
	this.Content.style.display			= "block";
	this.Content.style.visibility		= "hidden";
	this.Content.src = url;
	this.Content.style.height			= "723px" //Fix the height for Dynamic Layout gallery Viewer
	
	var y = document.body.clientHeight? document.body.scrollTop : pageYOffset;
	document.getElementById(this.ContainerID).style.top = (y+60)+"px";
	document.getElementById(this.ContainerBgID).style.top = (y==0) ? "-60px" : (y-(y*3))+"px";
}

InfoItem.prototype.Close = function()
{
	this.Layer.style.display		= "none";
	this.Content.style.display		= "none";
	this.Content.style.visibility	= "hidden";
	this.Content.src				= "about:blank";
}

InfoItem.prototype.Create = function (o,url,height)
{
	this.Init();
	o.owner = this;
	o.onmousedown 	= null;
	o.url 			= url;
	o.onmouseup 	= function(e){ this.owner.Show(o,height);this.owner.ClearEvent(e)};
	o.onclick		= function(e){this.owner.ClearEvent(e)};
	o.target 		= "_self";
	o.href			= "javascript:void(0);";
	o.onmouseover	= function(){window.status = this.owner.innerText};
	o.onmouseout	= function(){window.status = ""};
}


InfoItem.prototype.ClearEvent = function(e)
{
	if(!e)e=window.event;
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
}


/*############################################################################################
##									Image Rotate Functions									##
############################################################################################*/
function RotateImage (strClientID)
{
	var consumerRotator = ReadCookie("Cookie" + strClientID);
	if(consumerRotator!="")
	{
		consumerRotator = parseInt(consumerRotator);
	} else {
		consumerRotator = 0;
	}
	var chpi = consumerRotator;
	
	eval('if(++consumerRotator>=' + strClientID + 'Images.length) consumerRotator = 0;');
	var d = new Date();
	d.setTime(d.getTime()+(365*24*60*60*1000));
	WriteCookie("Cookie" + strClientID,consumerRotator,d.toGMTString());
	
	//RMUInstance.SetMediaSrc(HPImages[chpi],'','');
	eval('document.getElementById(strClientID).src = ' + strClientID + 'Images[chpi];');
}


/*############################################################################################
##									Rich Media Unit Functions								##
############################################################################################*/
function RichMediaUnit()
{
	this.m_Index = RichMediaUnit.m_Instances.length;
	RichMediaUnit.m_Instances[this.m_Index] = this;
}
RichMediaUnit.m_Instances				= new Array();
RichMediaUnit.prototype.RMUID			= null;
RichMediaUnit.prototype.RMU				= null;
RichMediaUnit.prototype.m_CurrentSrc	= "";
RichMediaUnit.prototype.m_RetryCount	= 0;
RichMediaUnit.prototype.m_RetryMax		= 50;
RichMediaUnit.prototype.m_RetryItvl		= null;

RichMediaUnit.CallInstance = function (i,method,p0,p1,p2)
{
	RichMediaUnit.m_Instances[i][method](p0,p1,p2);
}

RichMediaUnit.prototype.GetSrcUrl = function(root,src)
{
	if(root.indexOf("?")==-1)
	{
		return root+"?mediaSrc="+src;
	} else {
		return root.indexOf("mediaSrc")==-1 ? root+"&mediaSrc="+src : root.split("mediaSrc=")[0]+"mediaSrc="+src;
	}
}

RichMediaUnit.prototype.SetMediaSrc=function(src,captionLeft,captionRight)
{
	var tmp = src+captionLeft+captionRight;
	if(tmp==this.m_CurrentSrc) return;
	
	if(window[this.RMUID])
	{
		this.RMU = window.document[this.RMUID] ? window.document[this.RMUID] : window[this.RMUID];
	} else if(document[this.RMUID]) {
		this.RMU = document[this.RMUID];
	} else {
		this.RMU = document.getElementById(this.RMUID);
	}
	
	var s = src.toLowerCase();
	if(!RichMediaUnit.FlashEnabled&&(s.indexOf(".flv")!=-1||s.indexOf(".swf"))!=-1)
	{
		self.location.href = this.GetSrcUrl(self.location.href,src);
		return;
	}
	if(RichMediaUnit.FlashEnabled)
	{
		try
		{
			if(++this.m_RetryCount<this.m_RetryMax) this.m_RetryItvl = setTimeout("RichMediaUnit.CallInstance("+this.m_Index+",'SetMediaSrc','"+src+"','"+captionLeft+"','"+captionRight+"')",100);
			this.RMU.SetVariable("captionLeft",captionLeft);
			this.RMU.SetVariable("captionRight",captionRight);
			this.RMU.SetVariable("mediaSrc",src);
			clearTimeout(this.m_RetryItvl);
		}
		catch (e)
		{
			if(RichMediaUnit.FlashEnabled)
			{
				var s = this.GetSrcUrl(RichMediaUnit.StubFileSource,src)+"&captionLeft="+captionLeft+"&captionRight="+captionRight;
				if(this.RMU.movie)
				{
					this.RMU.movie = s;
				} else {
					// trap browsers that can't even update the src attribute correctly :- safari
					if(navigator.userAgent.toLowerCase().indexOf("safari"))
					{
						var fvars = "mediaSrc="+src+"&amp;captionLeft="+captionLeft+"&amp;captionRight="+captionRight;
						var t = this.RMU.outerHTML;
						var fvi = t.indexOf("flashvars=");
						t = t.substring(0,fvi)+"flashvars=\"" +fvars+"\""+ t.substring(t.indexOf("\"",fvi+11)+1,t.length);
						this.RMU.outerHTML = t;
					} else {
						this.RMU.src = s;
					}
				}
			} else {
				this.RMU.src = src;
			}
		}
	} else {
		this.RMU.src = src;
		if(captionLeft!="")
		{
			var capDiv = document.getElementById(this.RMUID+"_Caption");
			if(capDiv!=null) capDiv.innerHTML = captionLeft;
		}
	}
	
	if(document.body.scrollTop)
	{
		document.body.scrollTop = 0;
	} else {
		document.body.pageYOffset = 0;
	}
	
	this.m_CurrentSrc = tmp;
}


/*############################################################################################
##									Flash Iframe Resizer									##
############################################################################################*/
function SetHeightTracker(swfID)
{
	try
	{
		var h = Math.max(document.body.scrollHeight);			
		var o = document.embeds[0]!=null ? document.embeds[0] : document.getElementById(swfID);
		
		if(o.GetVariable("LOADED")=="true")
		{
			SetHeightTracker.count = 0;
			o.SetVariable('frameHeight',h.toString());
		} 
		else if(SetHeightTracker.count++<10)
		{
			setTimeout("SetHeightTracker('"+swfID+"')",250);
		}
	}
	catch(e)
	{
		if(SetHeightTracker.count++<10) setTimeout("SetHeightTracker('"+swfID+"')",250);
	}
}	
SetHeightTracker.count = 0;


/*############################################################################################
##									Write Flash Functions									##
############################################################################################*/
var swfQueryString = "";
function WriteFlash (nsid,fstring)
{
	if(fstring.indexOf(".swf?")==-1)
	{
		fstring = fstring.replace(/.swf/,".swf?"+swfQueryString);
	} else if(swfQueryString.length>0) {
		fstring = fstring.replace(/.swf\?/,".swf&");
		fstring = fstring.replace(/.swf/,".swf?"+swfQueryString);
	}
	nsTag = document.getElementById(nsid);
	nsTag.outerHTML = "<object "+fstring+"</object";
}


/*############################################################################################
##							     	Drop Shadow / Chrome functions							##
############################################################################################*/
function WriteDropShadowPanel (id,width,height,panelColour,shadowImgUrl,zIndexBase, left, top)
{
	//document.write("<div id=\""+id+"\" style=\"background-color:red\">");
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf("msie")>0)
	{
		document.write("<div id=\""+id+"_Shadow\" style=\"left:"+left+"px;top:"+top+"px;position:absolute;width:"+width+"px;height:"+(height+36)+
		"px;background-color:#666666;filter:progid:DXImageTransform.Microsoft.Blur(pixelradius=10);z-index:0\"></div>");
	} else {
		document.write("<div id=\""+id+"_Shadow\" style=\"position:absolute;left:-15px;top:-15px;\"><img width=\"898\" height=\""+(height+36)+"\" id=\""+id+"_DSImage\" src=\""+shadowImgUrl+"\"/></div>");
	}
}

/*############################################################################################
##							     	JC - NEW Side-shifting rollover code					##
############################################################################################*/
function RO(i,o)
{
	if(!i.id)
	{
		i.id="ROImg"+(++RO.id);
	}
	if(i.filters)
	{
		i.filters[0].apply();
		i.style.backgroundPosition=o?"-"+parseInt(i.parentNode.style.width)+"px 0":"0 0";
		i.filters[0].play();
	} else {
	
		if(o)
		{
			i.style.opacity = 1;
			i.style.zIndex = 2;
			i.clone = i.cloneNode(true);
			i.clone.id = "ROImg"+(++RO.id);
			delete i.clone.onmouseover;
			delete i.clone.onmouseout;
			i.clone.style.zIndex = 1;
			i.clone.style.left = 0;
			i.clone.style.top =  0;
			i.clone.style.backgroundPosition="-"+parseInt(i.parentNode.style.width)+"px 0";
			i.parentNode.appendChild(i.clone);
			i.timer = setTimeout("RF('"+i.id+"',-0.1)",10);
				
		} else {
			clearTimeout(i.timer);
			i.timer = setTimeout("RF('"+i.id+"',0.1)",10);
		}
	}
}
RO.id = 0;

function RF(id,inc)
{
	var i = document.getElementById(id);
	var opac = parseFloat(i.style.opacity);
	if((opac>0&&inc<0)||(opac<1&&inc>0))
	{
		i.style.opacity = opac+=inc;
		i.timer = setTimeout("RF('"+id+"',"+inc+")",10);
	} else if(opac>=1&&inc>0){
		try
		{
			clearTimeout(i.timer);
			i.parentNode.removeChild(i.clone);
			i.clone = null;
			i.style.opacity = 1;
		}
		catch(ex){}
	}
}

var querystringHash = null;
function GetQueryStringValue (key)
{
	if(querystringHash==null)
	{
		querystringHash = {};
		var s = document.location.search
		var pairs = s.substr(1,s.length-1).split("&");
		var pair;
		for(var i in pairs)
		{
			pair = pairs[i].split("=");
			querystringHash[pair[0]] = pair[1];
		}
	}
	return querystringHash[key]==null ? "" : querystringHash[key];
}

function CheckLang()
{
	// write test cookie. if cookies not enabled , don't bother with test
	var d = new Date();
	d.setTime(d.getTime()+60000);
	WriteCookie("LT","1",d.toGMTString());
	
	if(ReadCookie("LT")=="1"&&ReadCookie("LanguageID")=="") document.location.href="countryselector";
}
//Sets the language on the home page
function SetLang(domains,langIds)
{
	var d = new Date();
	d.setTime(d.getTime()+(365*24*60*60*1000));
	var host = new String(document.location);
	for(var i=0;i<domains.length;i++)
	{
		if(host.indexOf("."+domains[i])>-1)
		{
			WriteCookie("LanguageID",langIds[i],d);
			break;
		}
	}
}

/*############################################################################################
##									Email validation    									##
############################################################################################*/
function isEmail(sEmail)
{
    var ePattern = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    return ePattern.test(sEmail);
}

/*############################################################################################
##									eNewsLetter Functions									##
############################################################################################*/
function ErrorSignUp(msg)
{
	window.status = msg;
}

function UserSignedUp(data)
{
	eval(data);

	if(user.success=="True")
	{
		var ctl = document.getElementById(user.containerSignUpId);
		ctl.style.display = "none";
		ctl = document.getElementById(user.containerThankYouId);
		ctl.style.display = "";
	}
	else
	{
		document.getElementById(user.errorField).value =  user.message;
	}
}

function SetCountryDropDown(id, country, display)
{
	var ctl = document.getElementById(country);
	for (var i=0; i<ctl.length; i++)
	{
		if(ctl.options[i].value==id) ctl.selectedIndex=i
	}
	
	if(!display)
		ctl.style.display = "none";
}

function SignUp(obj, url, email, country, lang, brandID, marketingCommunicationID, externalSystemID, errColor, backgroundColor, webpageID)
{
	//Validate fields
	try
	{
		//obj.disabled =	true;
		var params   =	"&callback=1";
		var ctl = document.getElementById(email);
		if(!isEmail(ctl.value))
			throw ctl;
			
		ctl.style.backgroundColor = backgroundColor;
		
		params += "&email="+ctl.value;
		ctl = document.getElementById(country);
		if(ctl.selectedIndex==0)
			throw ctl

		ctl.style.backgroundColor = backgroundColor;
		params += "&countryId=" + ctl.value;
		
		ctl = document.getElementById(lang);
		if(ctl.selectedIndex==0)
			throw ctl;
			
		ctl.style.backgroundColor = backgroundColor;
		params += "&languageId=" + ctl.value;
		
		params += "&BrandID=" + brandID + "&MarketingCommunicationID=" + marketingCommunicationID + 
				  "&ExternalSystemID=" + externalSystemID + "&webpageID=" + webpageID;
		
		//Create AJAX
		var redirect = document.getElementById("txtRedirect");
		if(hasAJAX)
		{
			var dataRequest = new HTTPRequest();
			dataRequest.m_UseXML = false;
			dataRequest.m_Method = 'POST';
		
			dataRequest.SetErrorHandler(window, 'ErrorSignUp');
			dataRequest.Send(url + params,'', window, 'UserSignedUp');
		}
		else
		{
			var form = document.getElementsByTagName('form')[0];
			redirect.value = url;
			form.submit();
		}
	
	}
	catch(ex)
	{
		if(ex.style !=null)
			ex.style.backgroundColor = errColor;
			
		obj.disabled = false;
		return false;
	}
	
	return false;
}

SignupAjax = {
	data : {
		email:"",
		lyrisSegment:"",
		serialise : function() {
            var s = new String("?mthd=signup");
            for(var att in this) {
                if(att != "serialise")
                    s+="&"+ att + "=" + escape(this[att]);
            }
            if (_langId != undefined && _langId!= "")s+="&langid="+_langId;
            return s;
        }	
	},
	signup : function (appDir, emailId, lyrisSegment) {
		var data = this.data;
		this.writeMessage("Signing up...");
		data.lyrisSegment = lyrisSegment;
		data.email = document.getElementById(emailId).value;
		var qs = data.serialise();
		var url = appDir + 'Ajax/AjaxHandler.ashx' + qs;
		//alert(url + ' , ' + lyrisSegment);
		AjaxHandler.send(url, SignupAjax.onSuccess, SignupAjax.onFailure);
		return false;
	},
	onSuccess : function(data)
	{
		if(this.readyState==4)
		{
			eval(this.responseText);
			if(user.success=="True") {
				HideAllExcept("successMessage");}
			SignupAjax.writeMessage(user.message);
			
		}
	},
	onFailure : function(data) {
		window.status = data;
	},
	writeMessage : function(msg) {
		var messageDiv = document.getElementById("successMessage");
		messageDiv.style.display = 'block';
		messageDiv.innerHTML = msg;
	}
}
AjaxHandler = {
	send : function(url, success, failure) {
        try {
            var req = getXmlHttpRequest();
            req.onreadystatechange = success;
            req.open("POST", url, true);
            req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            req.send(url);
        }
        catch(e)
        {
            alert(e);
        }
	}
}

function HideAllExcept(objId)
{
	var elements = document.getElementById(objId).parentNode.childNodes;
	for (var i=0;i<elements.length;i++) 
	{
		if (elements[i].id != undefined && elements[i].id != objId)
			{elements[i].style.display = 'none';}
	}
	var successDiv = document.getElementById(objId);
	successDiv.style.display = 'block';
}

/* Returns the HTML Request object
-------------------------------------*/
function getXmlHttpRequest() {
    var xhr;
	if(isIE&&isWin) {
		try	{ xhr = new ActiveXObject("Msxml2.XMLHTTP.4.0"); }
		catch(e) {
			try	{xhr	= new ActiveXObject("Microsoft.XMLHTTP");}
			catch(e){}
		}
	}
	else {
		try {
			//netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
			xhr = new XMLHttpRequest();
		}
		catch(e) { }
	}
	return xhr;
};

function GetKey (e)
{
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	return code;
}

var searchBoxID;
function submitSearch (e)
{
	var code = GetKey(e);
	return code==13||code==10? doSearch(searchBoxID) : true;
}

function doSearch(id)
{
	if(!searchDefault) searchDefault = "";
	var search = document.getElementById(id);
	if(search!=null&&search.value!=""&&search.value!=searchDefault)
	{
		var searchText = search.value.replace("&","%26");
		
		var intCheckWP	= 0;
		var intCheckPDF	= 0;
		
		if(document.getElementById("Check_WebPage")!=null&&document.getElementById("Check_WebPage").checked) intCheckWP = 1;
		if(document.getElementById("Check_Pdf")!=null&&document.getElementById("Check_Pdf").checked) intCheckPDF = 1;

		document.location.href=serverVars.searchUrl+searchText+'&swp='+intCheckWP+'&spdf='+intCheckPDF;
		
		return false;
	}
	return false;
}

function SubmitTrial (e)
{
	/*var code = GetKey(e);
	if(code==13||code==10) DoTrialSignUp();*/
}

function DoTrialSignUp()
{
	var f		= document.createElement("form");
	var e		= document.createElement("input");
	e.name		= "email";
	e.value		= document.getElementById("Email").value;
	var v		= document.createElement("input");
	v.name		= "voucher";
	v.value		= document.getElementById("Voucher").value;
	var a		= document.createElement("input");
	a.name		= "ajax";
	a.value		= "0";
	f.style.display = "none";
	f.appendChild(e);
	f.appendChild(v);
	f.appendChild(a);
	f.action	= document.location.href;
	f.method	= "POST";
	document.body.appendChild(f);
	f.submit();
}
/* Google Conversion
-------------------------------------*/
GoogleConversion = {
	track : function(conversionId, label) {
		var img = new Image(1,1);
		img.src = String.format("http://www.googleadservices.com/pagead/conversion/{0}/?label={1}&amp;guid=ON&amp;script=0", conversionId, label);
		alert(img.src);
		return true;
	}
}
/* Viewer 360
-------------------------------------*/
Viewer = {
	open : function(obj) {
		window.open (obj.href,"viewer360","menubar=0,resizable=0,width=800,height=450"); 
		return false;	
	}
}




