/*
This file contains Javascripts for the following functionalities:

- Charting
- Omniture
- Search Bar
- helper functions

*/
atlas = new Object();

atlas.charting =  
{    
    visibleCharts : [],
	
	createChartDisplay : function(refElement,data,type,size,showKey,legendpos)	
    {
		refElement.empty();
		refElement.html();
		var width = "320px";
		var height = "200px";
		if(size != undefined)	{
			width = size.w+"px";
			height = size.h+"px"
		}
		var appendKey = showKey == undefined ? true : showKey;
		var legendPos = legendpos == undefined ? 'normal' : 'right';
		var chart = refElement.visualize({type: type, height: height, width: width,dataProvider:data.data,appendKey:appendKey,legendPos:legendPos});
		this.visibleCharts.push(chart)
		this.visibleCharts.push(chart.next())
		
	},
	
	removeCharts : function()	
    {
		for(var i=0; i<this.visibleCharts.length; i++)	{
			$(this.visibleCharts[i]).remove();
		}
	},
    
    //data structure
    //{data:[{value:14,item:"Africa"}}
    mineGeoLand : function (data)	
    {
        data = data.replace(/\|\|/g, ' ');
            
        var landData = [{data:"",delimit:"Arable land",txt:""},{data:"",delimit:"Permanent crops",txt:""},{data:"",delimit:"Other",txt:""}]
        landData[0].txt = data.substring(data.indexOf(landData[0].delimit),data.indexOf(landData[1].delimit));
        landData[1].txt = data.substring(data.indexOf(landData[1].delimit),data.indexOf(landData[2].delimit));
        landData[2].txt = data.substring(data.indexOf(landData[2].delimit),data.length);
        landData[0].data = landData[0].txt.substring(landData[0].txt.indexOf(":")+1,landData[0].txt.indexOf("%"))
        landData[1].data = landData[1].txt.substring(landData[1].txt.indexOf(":")+1,landData[1].txt.indexOf("%"))
        landData[2].data = landData[2].txt.substring(landData[2].txt.indexOf(":")+1,landData[2].txt.indexOf("%"))
        var returnData = [];
        var currentNum = 0
        for(var i=0; i<landData.length; i++)	{
            currentNum =  Number(landData[i].data);
            if(!isNaN(currentNum))	{
                returnData.push({value:currentNum,item:landData[i].delimit})
            }
        }
        return {data:returnData};				
    },
    
    mineGeoArea : function(data)	
    {
        // total: 374 sq km||Land: 374 sq km||Water: 0 sq km
        data = data.replace(/\|\|/g, ' ');
        
        var areaData = [{data:"",delimit:"Land",txt:""},{data:"",delimit:"Water",txt:""}];
        areaData[0].txt = data.substring(data.indexOf(areaData[0].delimit),data.indexOf(areaData[1].delimit));
        areaData[1].txt = data.substring(data.indexOf(areaData[1].delimit),data.length);
        
        areaData[0].data = areaData[0].txt.substring(areaData[0].txt.indexOf(":")+1,areaData[0].txt.indexOf("sq km"));
        areaData[1].data = areaData[1].txt.substring(areaData[1].txt.indexOf(":")+1,areaData[1].txt.indexOf("sq km"))
        
        areaData[0].data.indexOf("million")>0 ?	areaData[0].data = Number(areaData[0].data.substring(0,areaData[0].data.indexOf("million"))) * 1000000 : undefined
        areaData[1].data.indexOf("million")>0 ?	areaData[1].data = Number(areaData[1].data.substring(0,areaData[1].data.indexOf("million"))) * 1000000 : undefined
        
        var returnData = [];
        for(var i=0; i<areaData.length; i++)	{
            var areaNum = isNaN(areaData[i].data)  ? Number(areaData[i].data.replace(/\,/g,'')) : Number(areaData[i].data)
            returnData.push({item:areaData[i].delimit,value:areaNum })
        }
        return {data:returnData};
    },
    
    
    mineAgeStructure : function(data)	{
        var ageData = [{data:"",delimit:"0-14 years",txt:""},{data:"",delimit:"15-64 years",txt:""},{data:"",delimit:"65 years and over",txt:""}]
        ageData[0].txt = data.substring(data.indexOf(ageData[0].delimit),data.indexOf(ageData[1].delimit));
        ageData[1].txt = data.substring(data.indexOf(ageData[1].delimit),data.indexOf(ageData[2].delimit));
        ageData[2].txt = data.substring(data.indexOf(ageData[2].delimit),data.length);
        ageData[0].data = ageData[0].txt.substring(ageData[0].txt.indexOf(":")+1,ageData[0].txt.indexOf("%"))
        ageData[1].data = ageData[1].txt.substring(ageData[1].txt.indexOf(":")+1,ageData[1].txt.indexOf("%"))
        ageData[2].data = ageData[2].txt.substring(ageData[2].txt.indexOf(":")+1,ageData[2].txt.indexOf("%"))
        
        var returnData = [];
        for(var i=0; i<ageData.length; i++)	{
            returnData.push({item:ageData[i].delimit, value:Number(ageData[i].data)})
        }
        return {data:returnData};
    },
    
    mineReligionsData : function(data,isPercent)	{
        var returnData = [];
        var rawData = data.split(",");
        var item = "";
        var itemNum = null;
        for(var i=0; i<rawData.length; i++)	{
            item = rawData[i];
            itemNum = item.match(/\d+/g);
            if(itemNum != null)	{
                if(Number(itemNum[0]) > 0)	
                if(isPercent)	{
                    Number(itemNum[0])<100 ? returnData.push({item:item.substring(0,item.indexOf(itemNum[0])),value:Number(itemNum[0])}) : undefined
                }
                else	{	
                    returnData.push({item:item.substring(0,item.indexOf(itemNum[0])),value:Number(itemNum[0])});
                }
            }
            
        }
        if(returnData.length>10)	returnData=returnData.splice(0,10)
        return ({data:returnData});				
    }
    
}

atlas.omniture = 
{
    getSubDirectory : function()	{
	    var subDir = window.location.href.replace(("http://"+getHostName()+"/"),"");
	    subDir=(subDir.indexOf("?")>=0)?subDir.substring(0, subDir.indexOf("?")):subDir;
	    return subDir;
	},
    
	getHostName : function()  
	{
	    return window.location.host;
	},
	
	getPageName : function()	{
		var url = window.location.toString();
		var pageName = url.substr(url.lastIndexOf("/")+1);
		return pageName;
	},
    
	getPageTrackingData : function()	{
		var pageName = window.location.toString();//pageaurls[pageId]
		var trackValue = {subdptmt:"",pgname:""};
		var pageSpit = [];
		var pageCategory,catsplit,countryValue = "";
		if(pageName.indexOf("world") > 0)	{
			pageSpit = pageName.split("/");
			pageCategory = pageSpit[pageSpit.length-2];
			pageCategory = unescape(pageCategory).split(" ").join("_").toLowerCase();
			trackValue = {subdptmt:"AtlasWorld",pgname:"atlas.world."+pageCategory};
		}
		else if(pageName.indexOf("continent")> 0)	{
			pageSpit = pageName.split("/");
			catsplit = pageName.substring(pageName.indexOf("continent")+9)
			catsplit =  unescape(catsplit.split("/")[1]).split(" ").join("");
			pageCategory = pageSpit[pageSpit.length-2];
			pageCategory = ("atlas."+catsplit+"."+(pageCategory == "People" ? "people_and_nation" : "land_and_enviornment")).toLowerCase();
			trackValue = {subdptmt:"Atlas"+catsplit,pgname:pageCategory};
		}
		else if(pageName.indexOf("country")> 0)	{
			pageSpit = pageName.split("/");
			catsplit = pageName.substring(pageName.indexOf("country")+7).split(" ").join("_").toLowerCase();
			countryValue =  (unescape(catsplit.split("/")[1]).split(" ").join("")).toLowerCase();
			pageCategory = catsplit.split("/")[2];
			if (catsplit.split("/")[2])
				pageCategory = (catsplit.split("/")[2] != "" ? catsplit.split("/")[2] : "Introduction").toLowerCase();
			trackValue = {subdptmt:"atlas."+countryValue,pgname:pageCategory};
		}
		else if(pageName.indexOf("oceans")> 0)	{
			trackValue = {subdptmt:"AtlasOceans",pgname:"atlas.oceans"};
		}
		else if(pageName.indexOf("compareCountries")> 0)	{
			trackValue = {subdptmt:"AtlasCompareCountries",pgname:"atlas.compare_countries"};
		}
		else if((pageName.lastIndexOf("com")> 0) || (pageName.lastIndexOf("com/")> 0) || (pageName.indexOf("index.jsp")> 0) || (pageName.lastIndexOf("/")> 0))	{
			trackValue = {subdptmt:"AtlasHome",pgname:"atlas.home"};
		}
		return trackValue;
	},
	
	action : "",
	trackData : [],
	selectedCoutry : "",
	trackingCode : {
						"MQAtlasDragMap":{prop21:'atlas.home',prop23:''},
						"MQAtlasOpen":{prop21:'atlas.home',prop23:'provide countrycode'},
						"MQAtlasInteractiveMap":{prop21:'atlas.countryName',prop23:''},
						"MQAtlasThumbnailScroll":{prop21:'atlas.countryName',prop23:''},
						"MQAtlasMoreDetails":{prop21:'atlas.countryName',prop23:''},
						"MQAtlasPhotoOpen":{prop21:'atlas.countryName',prop23:''},
						"MQAtlasPhotoScroll":{prop21:'atlas.countryName',prop23:''},
						"MQAtlasCompare":{prop21:'atlas.compare_countries',prop23:'provide countrynames'},
						"MQAtlasTabSelect":{prop21:'atlas.countryName',prop23:'',prop20:'selectedTab'},
						"MQAtlasCountryName":{prop21:'atlas.countryName',prop23:''}
						},
						
						
	applyTrackingData : function ()	{			
		var pageName = window.location.toString();
		var pageTrackingData = this.getPageTrackingData();
		s_265.prop2 = pageTrackingData.subdptmt;
		
		switch(this.action)	{
			case "MQAtlasDragMap":
				//add custome lin below
				s_265.pev2 = this.action
				s_265.prop21 = eval("this.trackingCode."+this.action).prop21;
				break
			case "MQAtlasOpen":
				//add custome lin below
				s_265.pev2 = this.action
				this.selectedCoutry = (this.trackData[0]).split(" ").join("");
				s_265.prop21 = eval("this.trackingCode."+this.action).prop21;
				s_265.prop23 = "MQAtlasMap."+this.selectedCoutry;
			break;
			case "MQAtlasInteractiveMap":
				s_265.pev2 = this.action;
				s_265.prop21 = "atlas."+pageTrackingData.subdptmt;
			break;
			case "MQAtlasThumbnailScroll":
				s_265.pev2 = this.action;
				s_265.prop21 = "atlas."+this.trackData[0];
			break;
			case "MQAtlasPhotoOpen":				
				s_265.prop20 = this.action;
				s_265.prop21 = "atlas."+this.trackData[0];
			break;
			case "MQAtlasMoreDetails":
				s_265.prop23 = "";
				s_265.prop20 = this.action;
				s_265.pageName = "atlas."+this.selectedCoutry;
			break;
			case "MQAtlasCountryName":
				s_265.prop23 = "";
				s_265.prop20 = "MQAtlas"+this.selectedCoutry;
				s_265.pageName = "atlas."+this.selectedCoutry;
			break;
			case "MQAtlasPhotoScroll":
				s_265.prop20 = this.action;			
			break;
			case "MQAtlasCompare":
				s_265.prop20 = this.action;
				//s_265.prop21 = eval("this.trackingCode."+this.action).prop21;
				s_265.prop23 = "MQAtlas."+(this.trackData[0]).split(" ").join("")+"_"+(this.trackData[1]).split(" ").join("");
			break;
			case "MQAtlasTabSelect":
				var tabNames = ["Introduction","Geography","People","Government","Economy","CommTranMil"]
				s_265.prop20 = "MQAtlas"+tabNames[this.trackData[0]];
				s_265.prop21 = this.trackData[1];
				s_265.pageName = "atlas."+this.trackData[1];				
			break;
			default:
				if(pageName.indexOf("country")> 0)	{
					s_265.pageName = pageTrackingData.subdptmt
					s_265.prop20 = "MQAtlas"+pageTrackingData.pgname;
				}
				else if((pageName.indexOf("world")> 0) ||
						(pageName.indexOf("continent")> 0)||
						(pageName.indexOf("compareCountries")> 0)||
						(pageName.indexOf("oceans")> 0)||
						(pageName.lastIndexOf("com")> 0) || 
						(pageName.lastIndexOf("com/")> 0) || 
						(pageName.indexOf("index.jsp")> 0) || 
						(pageName.lastIndexOf("/")> 0))	{
						s_265.pageName = pageTrackingData.pgname;
				}
				else	{
					s_265.pageName = pageTrackingData.subdptmt;
				}
			break;
			
		}
	},
	
	sendData : function(action)	{
		this.action = action;
		this.trackData = arguments[1];
		this.applyTrackingData();
		
		
		
		s_265.trackDownloadLinks=false;
		s_265.trackExternalLinks=false;
		s_265.trackInlineStats=false;
		s_265.linkLeaveQueryString=false;
		s_265.trackFormList=false;
		s_265.trackPageName=false;
		s_265.useCommerce=false;
		s_265.pfxID="atlas";
		s_265.mmxtitle="atlas";
		//s_265.pageName = s_265.pfxID +" : "+ s_265.pfxID + "." + pageTrackingData.subdptmt;
		s_265.channel="mq.mq";
		s_265.pageType="";
		s_265.server=this.getHostName();
		s_265.prop1= "MQAtlas";
		//s_265.prop2 = pageTrackingData.subdptmt;//"atlas";
		s_265.prop12 = window.location.toString();
		
		
		if(s_265.prop20 === "MQAtlasintroduction" || s_265.prop20 === "MQAtlasgeography" || s_265.prop20 === "MQAtlaspeople" || s_265.prop20 === "MQAtlasgovernment" || s_265.prop20 === "MQAtlaseconomy" || s_265.prop20 === "MQAtlascommunication")
		{
			s_265.mmxgo=true;
		}
		else{		
			s_265.mmxgo=false;
		}
		
		s_265.t();
		
	}

}

atlas.search = {

	searchCountryList : function(countryName)
	{
		$("#searchErrorBox").hide();
		var isResultFound = false;
		var countryParam = "";
		var placeListArray = atlas.continentData.placeListArray;
		
		for(var i=0; i<placeListArray.length; i++)
		{
			if(String(countryName).toLowerCase() == String(placeListArray[i]).toLowerCase())	
			{
				atlas.dataHandler.selectedCountryCode = atlas.continentData.countryCodeArray[i];
				atlas.dataHandler.ciaCode = atlas.continentData.ciaCountryCodeArray[i];
				countryParam = countryName;
				atlas.helper.populateCountryInfo(countryParam);
				
				isResultFound = true;
				break;
			}
			
		}
		
		if(!isResultFound)	{
			return false;
		}
		return true;
	},
	
	clrInputBox : function()
	{
		$('#searchErrorBox').hide();
		if($("#tags").val() == atlas.constants.SEARCH_GHOST_TXT)
		{
			$("#tags").css("color","#000");
			atlas.continentData.ghostTextClicked =false;
			$("#tags").val("");
		}
	}

}

atlas.helper = {
	
	showPreLoading : function(isShow) 
    {
        if(isShow)	
        {
            $("#page-container").mask("Loading...    ");
        }
        else	
        {
            $("#page-container").unmask();
        }
    },
	
	capitalizeSentences : function(rawString) 
    {
        rawString = rawString.replace(/^\s+/,"");
        rawString = rawString.replace(/\.\n/g,".[-<br>-]. ");
        rawString = rawString.replace(/\.\s\n/g,". [-<br>-]. ");
        	
        var length = rawString.length;
        var endOfSentence;
        var result = rawString.charAt(0).toUpperCase();
       
        for (var i=1; i<length; i++)
        {
            var tmp = rawString.charAt(i);
            if (tmp == ".")
            {
                endOfSentence = true;
                result += tmp;
            }
            else
            {
                if (endOfSentence == true && tmp != ' ')
                {
                    result += tmp.toUpperCase();
                    endOfSentence = false;
                }
                else
                {
                    result += tmp;
                }
            }
        }
        
        rawString = result;
        rawString = rawString.replace(/\[-<br>-\]\.\s/g,"\n");
        rawString = rawString.replace(/\si\s/g," I "); 
        
        if(rawString.length==2 || rawString == atlas.constants.NO_INFO_MSG){
            rawString = atlas.constants.NO_INFO_MSG;
        }
        return rawString;
	},
	
	checkEmptyString : function(rawString) 
    {
        if(rawString == atlas.constants.DB_EMPTY_CODE)return atlas.constants.NO_INFO_MSG;
        else 
        {
            if (rawString.charAt( (rawString.length) - 1) != '.')
            {
                rawString += ".";
            }
            return rawString;
        }
	},
	
	parseInfo : function(rawString, capitalize) 
    {
        var parsedHTMLString = "";
		var tmp = rawString.split("||");
		parsedHTMLString += "<div> <ul class='quickfactscntner landinfo' style='margin-top:5px;'>";
		for (var i=0; i<tmp.length; i++)
		{
			parsedHTMLString += "<li style='margin-top:5px;'>"; 
			if (capitalize)
			{
				tmp[i] = this.setInternalLink(tmp[i]);
				parsedHTMLString += '<span> ' + this.capitalizeSentences(tmp[i]) + ' </span></li>';
			}
			else
			{
				if (tmp[i].indexOf(":") != -1)
				{
					tmp[i] = "<B>" + tmp[i].substring(0, tmp[i].indexOf(":")+1) + "</B>" + tmp[i].substring(tmp[i].indexOf(":")+1);
				}
				
				if (tmp[i][tmp[i].length - 1] != '.')
				{
					tmp[i] += ".";
				}
				tmp[i] = this.setInternalLink(tmp[i]);
				parsedHTMLString += '<span> ' + tmp[i] + ' </span></li>';
			}
		}
		parsedHTMLString += "</ul> </div>";
		return parsedHTMLString;
	},
	
	setInternalLink : function(countryString) 
    {
        var result = countryString;
		var placeLists = atlas.continentData.placeListArray;
		
		for(var j=0; j<placeLists.length; j++)	
		{	
			if(result.indexOf(placeLists[j]) != -1)	
			{
				result = result.replace(placeLists[j] + " ", "<a class='normalLink' href='/country/" + placeLists[j] + "'>" + placeLists[j] + " </a>");
			}
		}
		
		return result;
	},
	
	parseLandAndBoundaries : function(info) 
    {
        if (info.charAt(0) == '0' || info.charAt(1) == '0')
			return "None";
			
		var result = "";
		var tempStr1 = info.split("||");
		if (info.charAt(0) == '0' || info.charAt(1) == '0')
			return "None";
			
		var result = "";
		var tempStr1 = info.split("||");
		if (tempStr1.length > 1)
		{
			var border = tempStr1[1].split("Border countries:");
			if (border.length > 1)
			{
				// Now Split on "km," for border countries...
				result += "<div> <label> <B> Bordering Countries: </B> </label> </div>";
			
				var tempStr2 = (border[1]).split("km,");
				result += "<div> <ul class='quickfactscntner landinfo' style='margin-top:5px;'>";
				for (var i=0; i<tempStr2.length - 1; i++)
				{
					result += '<li>'; 
					tempStr2[i] = this.setInternalLink(tempStr2[i]);
					result += '<span> ' + tempStr2[i] + ' Km</span></li>';
				}
				
				tempStr2[i] = this.setInternalLink(tempStr2[i]);
				result += '<span> ' + tempStr2[i] + '</span></li> </ul> </div>';
				
				// Now Split on "km," for Regional countries...
				if (tempStr1[2])
				{
					tempRB = tempStr1[2].split("Regional borders:");
					if (tempRB[1])
					{
						result += "<div style='margin-top:5px;'> <label> <B> Regional Borders: </B> </label> </div>";
						var tempStr2 = (tempRB[1]).split("km,");
						result += "<div> <ul class='quickfactscntner landinfo' style='margin-top:5px;'>";
						for (var i=0; i<tempStr2.length - 1; i++)
						{
							result += '<li>'; 
							tempStr2[i] = this.setInternalLink(tempStr2[i]);
							result += '<span> ' + tempStr2[i] + ' Km</span></li>';
						}
						
						tempStr2[i] = this.setInternalLink(tempStr2[i]);
						result += '<span> ' + tempStr2[i] + '</span></li> </ul> </div>';
					}
					else
					{
						result += "<div style='margin-top:5px;'> " + this.setInternalLink(tempStr1[2]) + " </div>";
					}
				}
			}
		}
		
		result += "<div style='margin-top:5px;'> <label> <B> " + this.setInternalLink(tempStr1[0].substring(0,tempStr1[0].indexOf("km")+2)) + " </B> </label> </div>";
		
		return result;
	},
	
	getX : function(e) 
    {
        var evtOffsetVal = $(e.currentTarget).offset();
        var evtTitleTxt = e.currentTarget.title;		
        var resultVal, resultVal01, finalVal;
        var yOn = evtTitleTxt.length <= 8 ? true : false;					
    
        resultVal = evtOffsetVal.left + 50 -((evtTitleTxt.length * (yOn ? 4 : 3)));
        resultVal01 = evtOffsetVal.left - ( 90 + (evtTitleTxt.length * (yOn ? 4 : 3)));
        
        finalVal = $(window).width() <= 800 ? resultVal : resultVal01;
        
        return finalVal;
	},
	
	parseCurrency : function(info) 
    {
        var returnData = "";
		if(info != atlas.constants.DB_EMPTY_CODE)	{
			if(selectedCountryCode == "US"){
				 returnData ="US dollar (USD)";
				 return returnData;
	        	}			 
			returnData =  info.substring(0,info.indexOf(")")+1);
		}
		else	{
			returnData =  atlas.constants.NO_INFO_MSG;
		}
		return returnData;
	},
	
	getGeoLocationFromOSM : function(data)
	{
		atlas.mapHandler.mapClickQueryRunning = false;
		$('#loaderCntner').css('display','none');
		
		if (data === ""){		
			$('#loaderCntner').css('display','none');
			return ;
		}
		
		var jsonResponse = eval("(" + data + ")");
		var countryName = jsonResponse.countryName;
		var ciaCountryCode = jsonResponse.ciaCountryCode;
		var capital = jsonResponse.countryCapital;
		var time = jsonResponse.time;
		var weather = jsonResponse.weather;
		var dstFlag = jsonResponse.dstFlag;
		var dstStartDate = jsonResponse.dstStartDate;
		var dstEndDate = jsonResponse.dstEndDate;
		
		weather = weather.split("|")
		var countryCode = "";
		
		// Calculate the Time of the capital using the timezone provided...
		var offset = Number(time.substring(3));
		var diff = time.substring(3,4);		
		
		// create Date object for current location
		var d = new Date();
	   
		// convert to msec
		// add local time zone offset
		// get UTC time in msec
		var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
	   
		// create new Date object for different city
		// using supplied offset
		var newDateObj = new Date(utc + (3600000*offset));
	   
		var capitalTime = (newDateObj).toLocaleTimeString();
		temp1 = capitalTime.split(" ");
		capitalTime = temp1[0].split(":");
		
		var tempHour = Number(capitalTime[0]);
		// Check if DST...
		if (atlas.helper.isDSTPeriod(newDateObj, dstStartDate, dstEndDate))
			tempHour += 1;
	   
		if (temp1.length == 1)
		{
			var temp2 = "AM";
			
			if (tempHour > 11) { temp2 = "PM"; }
			if (tempHour > 12) { tempHour -= 12; }
			if (tempHour == 0) { tempHour = 12; }
				capitalTime = tempHour + ":" + capitalTime[1] + " " + temp2;
		}
		else
			capitalTime = tempHour + ":" + capitalTime[1] + " " + temp1[1];
		
		// Use the weather info from the response...
		if (weather[0] == "-")
			weather[0] = "";
		var weatherData = weather[0] != "" ? "| "+weather[0]+"&#176;F " : "";
		
		if (countryCode == "" && ciaCountryCode == "")
		{
			return;
		}
		else
		{		
			var ciaCountryCodeArray = atlas.continentData.ciaCountryCodeArray;
			var countryCodeArray = atlas.continentData.countryCodeArray;
			
			//Get the Country Name corresponding to the country code...
			for(var i=0; i<ciaCountryCodeArray.length; i++)	
			{
				if(ciaCountryCode.toLowerCase() == ciaCountryCodeArray[i].toLowerCase())	
				{
					countryCode = countryCodeArray[i];
					countryName = atlas.continentData.placeListArray[i];
					break;
				}
			}
			atlas.omniture.sendData("MQAtlasOpen",[countryName]);		
			// Redirect to the Country Page...
			var infoBox = "";
			if (countryCode == "")
			{
						var infoBox = "<div class='beakl'><img src='/images/leftBeak.png' border='0'/></div><div class='atlas-helper-fleft'>" +
						"<a id='fancybox-close-country' style='display: inline;'></a><div ><a href='#'class='mapInfoBox' style='color:#039CD2' onclick='atlas.helper.omnitureHelper(this)'>"+
				"<img src='/images/flag/small/"+ciaCountryCode+"-flag.gif' width='33' height='23' border='0'>&nbsp;&nbsp;"+countryName+"</a></div>	"+
				"<div style='font-weight:bold;' class='padTB5'>Capital : "+capital+"</div><div style='font-size:18px'>"+capitalTime+" "+weatherData+"</div>" +
						"<div class='padTB5'><a href='#' style='color:#039CD2;font-weight:bold' onclick='atlas.helper.omnitureHelper(this)'>More details</div></div><div class='beakr'><img src='/images/rightBeak.png' border='0'/></div>"
				$("#popuup_div").html(infoBox);	
			}
			else
			{	var redirectPath = "/country/" + countryName + "/";
				var infoBox = "<div class='beakl'><img src='/images/leftBeak.png' border='0'/></div><div class='atlas-helper-fleft'>" +
						"<a id='fancybox-close-country' style='display: inline;'></a><div ><a class='mapInfoBox' style='color:#039CD2' href='"+redirectPath+"' onclick='atlas.helper.omnitureHelper(this)'>"+
				"<img src='/images/flag/small/"+ciaCountryCode+"-flag.gif' width='33' height='23' border='0'>&nbsp;&nbsp;"+countryName+"</a></div>	"+
				"<div style='font-weight:bold;' class='padTB5'>Capital : "+capital+"</div><div style='font-size:18px'>"+capitalTime+" "+weatherData+"</div>" +
						"<div class='padTB5'><a href='"+redirectPath+"' style='color:#039CD2;font-weight:bold' onclick='atlas.helper.omnitureHelper(this)'>More details</div></div><div class='beakr'><img src='/images/rightBeak.png' border='0'/></div>"
				$("#popuup_div").html(infoBox);			
			}
		
		}
		
		var screenRes = atlas.helper.getViewPort();
		var offset = ((screenRes.swidth-atlas.constants.PAGE_WIDTH)/2)+10
		var isWin7  = ((document.documentMode == 7 ) && ( (navigator.userAgent.indexOf("MSIE 7.0") != -1 ) || (navigator.userAgent.indexOf("MSIE 8.0") != -1 ) )) ? true : false;
		//getting height and width of the message box
		var height = 82//$('#popuup_div').height();
		var width = 180;//$('#popuup_div').width();
		
		var clickPos = atlas.menu.clickPos;
		var xpos = (clickPos.x)+15
		var ypos = clickPos.y - (height/2)
		
		$(".beakl").show();
		$(".beakr").hide()	
		
		if((xpos +width) >(atlas.constants.PAGE_WIDTH+offset))	{
			xpos = clickPos.x - (isWin7 ? 240 : width)
			$(".beakl").hide()
			$(".beakr").show()
			
		}
		if(atlas.constants.PAGE_TOP >ypos )	{
			ypos = atlas.constants.PAGE_TOP+5;
		}
		else if((clickPos.y +height)>(atlas.constants.PAGE_TOP+atlas.constants.MAP_HEIGHT))	{
			ypos = ((atlas.constants.PAGE_TOP+atlas.constants.MAP_HEIGHT)-100);
		}	
		
	    //calculdating offset for displaying popup message
		leftVal= xpos+"px";
		topVal = ypos+"px";
	    $('#popuup_div').css({left:leftVal,top:topVal}).show();
	    $("#fancybox-close-country").click(function(){$("#popuup_div").hide();})	
		
	},

	isDSTPeriod : function(oDate, startDateMonth, endDateMonth)
	{
		var bInDST = false;
		
		var startMonth = Number((startDateMonth.split("-"))[0]);
		var startDate = Number((startDateMonth.split("-"))[1]);
		var endMonth = Number((endDateMonth.split("-"))[0]);
		var endDate = Number((endDateMonth.split("-"))[1]);
		
		var dstStartDate = new Date();
		dstStartDate.setMonth(startMonth-1);
		dstStartDate.setDate(startDate);
		dstStartDate.setYear(oDate.getYear());
		
		var dstEndDate = new Date();
		dstEndDate.setMonth(endMonth-1);
		dstEndDate.setDate(endDate);
		dstEndDate.setYear(oDate.getYear());
		
		if ((oDate.getMonth() > dstStartDate.getMonth()) && (oDate.getMonth() < dstEndDate.getMonth())){
			bInDST = true;
		} else if (oDate.getMonth() == dstStartDate.getMonth()) {
			if (oDate.getDate() >= dstStartDate.getDate()) {
				bInDST = true;
			} else {
				bInDST = false;
			}
		} else if (oDate.getMonth() == dstEndDate.getMonth()) {
			if (oDate.getDate() < dstEndDate.getDate()) {
				bInDST = true;
			} else {
				bInDST = false;
			}
		} else {
			bInDST = false;
		}
		return bInDST;
	},
	
	getViewPort : function()	
	{
		var viewportwidth;
		var viewportheight;
	
		if (typeof window.innerWidth != 'undefined')
		{
			
		  	viewportwidth = window.innerWidth,
			viewportheight = window.innerHeight
		}
		// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		else if (typeof document.documentElement != 'undefined'
			 && typeof document.documentElement.clientWidth !=
			 'undefined' && document.documentElement.clientWidth != 0)
		{
			viewportwidth = document.documentElement.clientWidth,
			viewportheight = document.documentElement.clientHeight
		}
		// older versions of IE
		else
		{
			viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
			viewportheight = document.getElementsByTagName('body')[0].clientHeight
		}
		return {swidth:viewportwidth,sheight:viewportheight};
	},
	
	
	createFancyBox : function(boxName,type)
	{
		var blurb = [];
		var worldBlurb = [];
		
		blurb ["AFRICA"] = "Sahara, the world's largest hot desert, covers nearly a third of the African continent."
		blurb ["ASIA"] = "Taj Mahal, one of the most popular Asian destinations, was built over 22 years by thousands of artisans."
		blurb ["EUROPE"] = "The Alps mountain ranges of Europe, a popular destination for sightseeing and sports, attracts nearly 100 million visitors a year."
		blurb ["NORTH AMERICA"] = "The statue of Liberty, a 151-foot statue in North America, has become an iconic symbol of freedom and of the United States."
		blurb ["SOUTH AMERICA"] = "The ruins of Machu Picchu, located in Peru, are one of the most beautiful ancient sites in South America."
		blurb ["OCEANIA"] = "The Kangaroo, a marsupial that is considered the national symbol of Australia, can hop at speeds of upto 44 mph."
		blurb ["ANTARCTICA"] = "About 98% of Antarctica, the fifth largest continent of the world, is covered by ice averaging at least 1 mile thick.";
		
		worldBlurb["Population"] = "China is the most populated country in the world with an estimated population of over 1.3 billion.";
		worldBlurb["Climate"] = "With a temperature of -128.6 degrees F, Antarctica has the lowest temperature ever recorded on earth.";
		worldBlurb["Religions"] = "Christianity, Islam and Hinduism are among the most followed religions of the world.";
		worldBlurb["Languages"] = "There are more than 5,000 actively spoken languages in the world.";
		worldBlurb["Land use and Resources"] = "The United States is the largest producer of electricity";
		worldBlurb["Political"] = "";
		worldBlurb["Timezones"] = "China is the largest country with only one time zone.";
		worldBlurb["Life Systems"] = "";

		var blurTxt = type == "CO" ? blurb[boxName.toUpperCase()] : worldBlurb[boxName];
		var boxCaps = type == "CO" ? boxName.toUpperCase() : boxName;
		var img =  type == "CO" ? boxCaps+".jpg" : boxName.substring(0,4)+".png";                                                             

		 var fancyBox = "<div class='sM01List' id='menu_"+boxName.substring(0,3)+"'><div class='sM01ListImgSec'>"+
		"<img src='/images/Menu_"+img+"'></div> <div class='sM01ListTxtSec'>" +
		"<b class='sM01ListTxtHd'>"+boxCaps+"</b><br><span class='blurbTxtsss'>"+blurTxt+"</span></div></div>"
		
		return fancyBox;
	},

	populateCountryInfo : function(countryName)
	{
		var url = window.location.href;
		var redirectPath = "/country/" + countryName + "/";
		window.location.replace(redirectPath);
	},

	checkIsCountryPage : function()
	{
		var isCountryPage = false;
		var url = window.location.href;
		if(url.indexOf("/country")>0)	{
			isCountryPage = true;
		}
		return isCountryPage;
	},
	
	omnitureHelper : function(e)
	{
		if(e.innerHTML === "More details"){
			atlas.omniture.sendData("MQAtlasMoreDetails");
		}
		else{
			atlas.omniture.sendData("MQAtlasCountryName");
		}
	},
	
	showTitleContent : function(titleContent, selectedUIMode)	
	{
		var titleTag = "";
		switch(selectedUIMode)
		{
			case atlas.constants.MODE_CONTINENT:
				titleTag = titleContent;
				break;
			case atlas.constants.MODE_WORLD:
				titleTag = titleContent;
				break;
			case atlas.constants.MODE_COUNTRY:
				titleTag = unescape(titleContent);
				break;
		}
		$("#mainTitleBox").html(titleTag);		
	}
	
}

atlas.constants = {
	NO_INFO_MSG : "No information available at this time.",
	DB_EMPTY_CODE : "Not Available",
	SEARCH_GHOST_TXT : "Enter a Country Name",
	MODE_COUNTRY : "countryMode",
	MODE_CONTINENT : "continentMode",
	MODE_LAND : "landMode",
	MODE_PEOPLE : "peopleMode",
	MODE_HOME : "homeMode",
	MODE_WORLD : "worldMode",
	PAGE_WIDTH : 983,
	PAGE_TOP : 154,
	MAP_HEIGHT : 610,
	worldMenu : [{name:"Population",container:{},visited:false,show:true},
                 {name:"Climate",container:{},visited:false,show:true},
                 {name:"Religions",container:{},visited:false,show:true},
                 {name:"Languages",container:{},visited:false,show:true},
                 {name:"Land use and Resources",container:{},visited:false,show:true},
                 {name:"Political",container:{},visited:false,show:false},
                 {name:"Timezones",container:{},visited:false,show:true},
                 {name:"Life Systems",container:{},visited:false,show:false}]
    
                 
	
}

