





var AIS_CultureCode;
var AIS_Location;
var AIS_ServicePage;
var AIS_pub;
var AIS_location="";
var AIS_long=0;
var AIS_lat=0;
var AIS_Key=0;
var AIS_id=0;
var AIS_ServerName="service.syngenta-ais.com"
var AIS_Protocol=((window.location.protocol == "https:") ? "https://" : "http://");


function AIS_getDomainName()
{
	var url=window.location.hostname;
	var sav=url;
	var result="";
	 
	// REMOVES '.??.??' OR '.???.??' FROM END - e.g. '.CO.UK', '.COM.AU'
	if (url.match(new RegExp(/\.[a-z]{2,3}\.[a-z]{2}$/i))) {
	      url = url.replace(new RegExp(/\.[a-z]{2,3}\.[a-z]{2}$/i),"");
 
	// REMOVES '.??' or '.???' or '.????' FROM END - e.g. '.US', '.COM', '.INFO', '.INTRA'
	} else if (url.match(new RegExp(/\.[a-z]{2,5}$/i))) {
	      url = url.replace(new RegExp(/\.[a-z]{2,5}$/i),"");
	}
	result=sav.replace(url,"");
	
	if(url.indexOf(".")>-1)
		result=url.substr(url.lastIndexOf("."))+result;
	else
		result=url+result;

	return(result);
}

function AIS_WriteCookie(name, value)
{
	var argv=AIS_WriteCookie.arguments;
	var argc=AIS_WriteCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var secure=(argc > 5) ? argv[5] : false;
	
	var longDate = new Date();
	longDate.setFullYear(2020);

	var CookieString= name+"="+escape(value)+
	((expires==null) ? ("; expires="+longDate.toGMTString()) : ("; expires="+expires.toGMTString()))+
	"; path=/"+
	((secure==true) ? "; secure" : "");

	var domain=AIS_getDomainName();
	document.cookie=CookieString+
	((domain==null) ? "" : ("; domain="+domain));
}

function AIS_getCookieVal(offset)
{
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1) endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function AIS_ReadCookie(name)
{
	var arg=name+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen)
	{
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg) return AIS_getCookieVal(j);
		i=document.cookie.indexOf(" ",i)+1;
		if (i==0) break;
	}
	return null;
}


function AIS_ShowWait(container)
{
	document.getElementById(container).innerHTML='<img id="AIS_Wait" src="'+AIS_Protocol+AIS_ServerName+'/media/41729/ais-logo-small-spinny.gif"/>'
}

function AIS_RemoveViewJS()
{
var JSs = document.getElementsByTagName("script")
for (var i=0; i<JSs .length; i++)
	if(JSs[i].id.indexOf("AIS_JS_C")==0) 
         	document.getElementsByTagName('head')[0].removeChild(JSs[i])
}

function AIS_addLoadEvent(func) 
{ 
	var oldonload = window.onload; 
	if (typeof window.onload != 'function') 
	{ 
		window.onload = func; 
	} 
	else 
	{ 
		window.onload = function() 
		{ 
	      		if (oldonload) 
			{ 
	        		oldonload(); 
	      		} 
	     		 func(); 
	    	} 
	  } 
} 

function AIS_LoadJS(id,url)
{
	//all mandatory informations are passed to the server
	//AIS_id : get from Cookie("AIS_InternalUserId");
	if(url.indexOf("?")!=-1)
		url += "&AIS_Key="+AIS_Key;
	else
		url += "?AIS_Key="+AIS_Key;

	url += "&protocol="+AIS_Protocol;

	//first, remove previous version of the JS
	var obj = document.getElementById(id);
	if (obj != null)
	    document.getElementsByTagName('head')[0].removeChild(obj)

	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src =url;
	script.id = id;
	document.getElementsByTagName('head')[0].appendChild(script);
}

function AIS_RemoveViewCSS()
{
var CSSs = document.getElementsByTagName("link")
for (var i=0; i<CSSs.length; i++)
	if(CSSs[i].id.indexOf("AIS_CSS_C")==0) 
         	document.getElementsByTagName('head')[0].removeChild(CSSs[i])
}

function AIS_LoadCSS(id, URL, media)
{
     var obj = document.getElementById(id);
     if (obj != null)
         document.getElementsByTagName('head')[0].removeChild(obj)

      var css_style=document.createElement("link");
      css_style.setAttribute("rel", "stylesheet");
      css_style.setAttribute("type", "text/css");
      css_style.setAttribute("href", URL);
      css_style.setAttribute("media", media);
      css_style.setAttribute("id", id);
      document.getElementsByTagName("head")[0].appendChild(css_style);
}

function AIS_SwapNodes(node1, node2)
{
	var oldNodeAtPosition = document.getElementById(node1);
	var newNodeAtPosition = document.getElementById(node2);
	// swap DOM nodes
	// API: replaceChild(child1,child2) -- replace node child2 by node child1
	//if((oldNodeAtPosition != undefined) && (newNodeAtPosition != undefined))
	{
		oldNodeAtPosition.parentNode.replaceChild(newNodeAtPosition.cloneNode(true), oldNodeAtPosition);
		newNodeAtPosition.parentNode.replaceChild(oldNodeAtPosition.cloneNode(true), newNodeAtPosition);
	}
}

function AIS_SwapIfExistsAndInOrder(id1,id2)
{
  var node1=document.getElementById(id1);
  var node2=document.getElementById(id2);
  if( (node1 != undefined) && (node2!= undefined))
  {
 var nodes =node1.parentNode.childNodes;
    if(AIS_GetIndexOfANode(nodes,id1)<AIS_GetIndexOfANode(nodes,id2))
         AIS_SwapNodes(id1,id2);
  }
}

function AIS_GetIndexOfANode(nodeTable, nodeID)
{
   for(var i=0; i<nodeTable.length; i++)
      if(nodeTable[i].id == nodeID) return i
return -1
}

function AIS_GetAds()
{
	
	var tab = document.getElementById("AgriCast").getElementsByTagName("div")
	var s="";
	for(var i=0;i<tab.length;i++)
	{
		if(tab[i].className =="AIS_Advert")
			s+="_"+tab[i].id.split("_")[2];
	}

	if(s != "")
	{
		var currentTime = new Date()
		
		var GetAdssrc = AIS_Protocol+AIS_ServerName
		+ "/js/ais_GetAds"
		+ "?s=" + s
		+ "&time="+currentTime.getMinutes()+"_"+currentTime.getSeconds()+"_"+currentTime.getMilliseconds();
		AIS_LoadJS("AIS_GetAds", GetAdssrc);	
	}
}

function AIS_SaveClickAd(src, href, campaign)
{
	var currentTime = new Date();
	var ClickAdsrc = AIS_Protocol+AIS_ServerName
	+ "/js/ais_ClickAd"
	+ "?cultureCode=" + AIS_CultureCode
	+ "&ServicePage=" + AIS_ServicePage
	+ "&Location=" + AIS_Location
	+ "&src=" + encodeURI(src)
	+ "&href=" + encodeURI(href)
	+ "&campaign=" + encodeURI(campaign)
	+ "&time="+currentTime.getMinutes()+"_"+currentTime.getSeconds()+"_"+currentTime.getMilliseconds();
	AIS_LoadJS("AIS_ClickAd", ClickAdsrc);	
}

function AIS_loadView()
{
    if (AIS_CultureCode && AIS_Location && AIS_ServicePage)
    {
	AIS_ShowWait("AIS_View");

	var JSViewsrc = AIS_Protocol+AIS_ServerName
	+ "/js/ais_getview"
	+ "?cultureCode=" + AIS_CultureCode
	+ "&ServicePage=" + AIS_ServicePage
	+ "&Location=" + AIS_Location
	+ "&debug=";
	
	AIS_LoadJS("AIS_JSView", JSViewsrc);	
    }
    else
    {
    }
}

function AIS_LoadGroupContent(container, servicePage)
{
	AIS_ShowWait(container);

	var JSViewsrc = AIS_Protocol+AIS_ServerName
	+ "/js/ais_getGroup"
	+ "?cultureCode=" + AIS_CultureCode
	+ "&ServicePage=" + servicePage
	+ "&Location=" + AIS_Location
	+ "&debug="
        + "&Container=" + container;
	
	AIS_LoadJS("AIS_"+container, JSViewsrc);	
}

//concatenate all selected groups id
function AIS_GetSelectedGroups()
{
	var groups=",";
	var inputs = document.getElementById("AgriCast").getElementsByTagName("input");
	for (var i=0; i<inputs.length; i++)
		if (inputs[i].name=="AIS_GroupContent")
			groups+=inputs[i].value+",";
	groups+=",";
	return groups;
}

function AIS_printPage(allgroups)
{
	var groups;
	if (allgroups) 
		groups="Allgroups"; 
	else 
		groups=AIS_GetSelectedGroups();

	var JSViewsrc1= AIS_Protocol+AIS_ServerName
	+ "/customer-configurations/"
	+ AIS_ServicePage
	+ "?cultureCode=" + AIS_CultureCode
	+ "&pub="+AIS_pub
	+ "&longitude="+AIS_Location.split(",")[2]
	+ "&latitude="+AIS_Location.split(",")[1]
	+ "&searchedLocation="+AIS_Location.split(",")[0]
	+ "&debug="
	+ "&print=1"
	+ "&groups="+groups
	var JSViewsrc = AIS_Protocol+AIS_ServerName+"/dynamicpdf?key="+AIS_Key+"&URL="+encodeURIComponent(JSViewsrc1)

	window.open (JSViewsrc ,
"mywindow","menubar=1,resizable=1,width=350,height=250"); 
}

function AIS_SendMail(allgroups)
{	


	AIS_ShowWait("AIS_EmailWait");

	var groups;
	if (allgroups) 
		groups="Allgroups" 
	else 
		groups=AIS_GetSelectedGroups();
	
	var JSViewsrc = AIS_Protocol+AIS_ServerName
	+ "/js/ais_sendemail"
	+ "?from=" + encodeURIComponent(document.getElementById('AIS_EmailFrom').value)
	+ "&fromName=" + encodeURIComponent(document.getElementById('AIS_EmailFromName').value)
	+ "&to=" + encodeURIComponent(document.getElementById('AIS_EmailTo').value)
	+ "&subject=" + encodeURIComponent(document.getElementById('AIS_EmailSubject').value)
	+ "&body="+encodeURIComponent(document.getElementById('AIS_EmailBody').value)
        + "&cultureCode=" + AIS_CultureCode
	+ "&publication="+AIS_pub
	+ "&longitude="+AIS_Location.split(",")[2]
	+ "&latitude="+AIS_Location.split(",")[1]
	+ "&searchedLocation="+AIS_Location.split(",")[0]
	+ "&ServicePage="+AIS_ServicePage
	+ "&debug="
	+ "&key="+AIS_Key
	+ "&groups="+groups

	AIS_LoadJS("JSEmail", JSViewsrc);

}

 
function SetGroupSelected(div1, style)
{
 var styletab = style.split(';');
 var sib = div1.parentNode.childNodes;

 for(var i=0;i<sib.length; i++)
 {
	sib[i].removeAttribute("style");
	sib[i].setAttribute("style",""); 
 }

 for(var j=0;j<styletab.length;j++)
 {
     div1.style[AIS_toCamelCase(styletab[j].split(':')[0])] = styletab[j].split(':')[1]
 }
} 

/** toCamelCase(input)
 * Converts string input to a camel cased version of itself.
 * For example:
 * toCamelCase("z-index"); // returns zIndex
 * toCamelCase("border-bottom-style"); // returns borderBottomStyle.
 */
function AIS_toCamelCase(s) {
	for(var exp = AIS_toCamelCase.exp; 
		exp.test(s); s = s.replace(exp, RegExp.$1.toUpperCase()) );
	return s;
}
AIS_toCamelCase.exp = /-([a-z])/;



 function SetGroupSelectedClass(div1, classSelected, classNonSelected)
{
	var sib = div1.parentNode.childNodes;
        for(var i=0;i<sib.length; i++)
	{
		sib[i].setAttribute('class',classNonSelected);
	}
	div1.setAttribute('class',classSelected);
   }
  
  


function AIS_checkNum(str) 
{
    if (
	str== "." 
		|| str == "," 
		|| str == "+" 
		|| str == "-" 
		|| str == "e" 
		|| str == "E" )
	{
            alert("Please enter a valid number.");
            return false;
        }
		
    for (var i = 0; i < str.length; i++) 
    {
        var ch = str.substring(i, i + 1); 
	if (ch != "." 
		&& ch != "," 
		&& ch != "+" 
		&& ch != "-" 
		&& ch != "e" 
		&& ch != "E" 
		&& (ch < "0" || ch > "9")) 
	{
            alert("Please enter a valid number.");
            return false;
        }
    }
    return true;
}

function AIS_CleanFloat(number)
{
	var num = (+number);
	if(num == 0) return 0;
	if(Math.abs(num)>1E6 || Math.abs(num)<1E-6)
		return number.toExponential(4);
	if(Math.abs(num)>1)
		return num.toFixed(2);
	if(Math.abs(num)<1)
		return Math.round(num*1E6)/1E6
	return num;
}

function AIS_CNVcompute(obj)
{
	var val = obj.value;
	val = eval(obj.nextSibling.value)

	var par=obj.parentNode.parentNode

	//first child= Physical measure label
	for(var i=1;i<par.childNodes.length-1;i++)
	{
		var child=par.childNodes[i];
		child.childNodes[1].value=AIS_CleanFloat(eval(child.childNodes[3].value))
	}
}


function AIS_CNVclearform(name)
{
	var par=document.getElementById(name)
	//first child= Physical measure label
	for(var i=1;i<par.childNodes.length-1;i++)
	{
		var child=par.childNodes[i];
		if(child.childNodes.length>1)
		{
			var childchild = child.childNodes[1];
			if(childchild.nodeName.toLowerCase()== 'input')
			if(childchild .type != 'button')
				childchild .value="";
		}
	}
}

function AIS_CNVcomputeCalc(obj)
{
	var par=obj;
	while(par.nodeName.toLowerCase() != 'div')
	{
//alert(par.nodeName);
		par=par.parentNode;
	}

	par=par.parentNode;
	for(var i=1;i<par.childNodes.length;i++)
	{
		var child=par.childNodes[i];
		if(child.childNodes.length>3)
		if(child.childNodes[2].value=='CNV Calculation Parameter')
		{
			var fieldValue;
			if(child.childNodes[1].nodeName.toLowerCase()=='table')
			{
				var tab = child.childNodes[1].getElementsByTagName('input');
				for (var rb=0; rb < tab.length;rb++)
				{
					if(tab[rb].checked)
					{
						fieldValue=tab[rb].value;
						break;	
					}
				}
			}
			else if (child.childNodes[1].nodeName.toLowerCase()=='select')
			{
				var nodeid = child.childNodes[1].id;
				fieldValue='document.getElementById("'+nodeid +'").options[document.getElementById("'+nodeid +'").selectedIndex]';
			}
			else 
			{
				fieldValue=child.childNodes[1].value
				if (child.childNodes[1].getAttribute("typedata")=="Textual box") fieldValue ='"'+fieldValue+'"';
			}



			if((fieldValue == '' || fieldValue == '""') && child.getAttribute("optional") != '1')
        		{
                       		return false;
        		}
			else
			{
				var newvalue;
				var s;
				try
				{
					newvalue=fieldValue.replace(/,/gi, ".");
					s=child.childNodes[3].value+'='+newvalue;
					eval(s);
				}
				catch(err) {}
			}
		}
	}
	for(var i=1;i<par.childNodes.length;i++)
    {
		var child=par.childNodes[i];
		if(child.childNodes.length>3)
		if(child.childNodes[2].value=='CNV Calculation Result')
		{
			try
			{
			var s=eval(child.childNodes[3].value);
			if(child.childNodes[1].getAttribute("typedata") =="Textual box")
				child.childNodes[1].value=eval(child.childNodes[3].value);
			else
            			child.childNodes[1].value=AIS_CleanFloat(eval(child.childNodes[3].value));
			}
			catch(err) {}
		}
    }
}


   
 

function AIS_ShowLocationSearchTable(show)
{
/*to be overrwritten*/
}


function AIS_ShowToolControls(controlsToShow)
{
	var emailCtrl=document.getElementById(controlsToShow); 
	var toolCtrlDiv=document.getElementById('AIS_ToolsControls');
	toolCtrlDiv.innerHTML=emailCtrl.innerHTML.split("_temp").join("");
	toolCtrlDiv.firstChild.style.display = 'block'


}

function AIS_RemoveSuffixID(obj, suff)
{
	for(var x=0; x<obj.childNodes.length;x++)
		AIS_RemoveSuffixID(obj.childNodes[x], suff);
	if(obj.id != undefined)
		obj.id=obj.id.replace(suff,'');
}


function AIS_HideToolControls()
{
	var toolCtrlDiv=document.getElementById('AIS_ToolsControls');
	toolCtrlDiv.innerHTML='';
}


function AIS_LoadNavigation()
{
	var JSNavigationSrc=AIS_Protocol+AIS_ServerName
	+ "/js/ais_getnavigation"
	+ "?ServicePage=gb-cp/blightcast/main"
	+ "&debug="
	+ "&cultureCode="+AIS_CultureCode;
	
	AIS_LoadJS ("AIS_JSNavigation", JSNavigationSrc);
}

function AIS_Init()
{

	AIS_RemoveViewCSS();
	document.getElementById('AIS_Content').innerHTML = ""
        + "<div id='AIS_forPositionning'>"
	+ "<div id='AIS_Message'></div>"
	+ "<div id='AIS_CultureCode'></div>"
	+ "<div id='AIS_Navigation'></div>"
	+ "<div id='AIS_Location'>"
	+ "<div id='AIS_LocationControls'>"
	+ "<div id='AIS_LocationSearch' class='LocationToolControls' style='display:block'>"
		+ "<div id='AIS_LocationSearchControls'></div>"
		+ "<div id='AIS_showLocationSearch'></div>"
		+ "<div id='AIS_LocationSearchResults'></div>"
	+ "</div>"
	+ "</div>"
	+ "</div>"
	+ "<div id='AIS_View'></div>";
        + "</div>";

	var JSCultureCodeSrc=AIS_Protocol+AIS_ServerName
	+ "/js/ais_getculturecodepicker"
	+ "?ServicePage=gb-cp/blightcast/main"
	+ "&lastLocation=" + AIS_ReadCookie("LastLocation")
	+ "&lastCultureCode=" + AIS_ReadCookie("LastCultureCode")
	+ "&DefaultCultureCode="
	+ "&DefaultLocation=,,,1"
	+ "&OverrideLastLocation=true"
	+ "&debug="
	+ "&UserCanChangeCultureCode=";

	AIS_LoadJS ("AIS_JSCultureCode", JSCultureCodeSrc);
}

if(window.location.protocol == "x-gadget:")
	{
		document.getElementById('AIS_Content').innerHTML = ""
       		 + "<div id='AIS_forPositionning'>"
			+ "<div id='AIS_View'></div>"
			+ "<div id='AIS_showLocationSearch'></div>"
       		 + "</div>";

		AIS_ServicePage = "gb-cp/blightcast/main";
		AIS_CultureCode = 'en-GB';
		AIS_Location = currentLocString;
		AIS_loadView();		
	}

function AIS_ShowSearchResult()
{
/* to be overwritten if necessary*/
}




AIS_LoadCSS('AIS_CSS_SC8342', AIS_Protocol+AIS_ServerName+'/customer-configurations/gb-cp/blightcast/greencast', 'screen');
AIS_LoadCSS('AIS_CSS_SC8343', AIS_Protocol+AIS_ServerName+'/customer-configurations/gb-cp/blightcast/blightcast', 'screen');
AIS_LoadCSS('AIS_CSS_C2009', AIS_Protocol+AIS_ServerName+'/customer-configurations/gb-cp/blightcast/main/main', 'screen');



