/*
This file contains Javascripts for the following functionalities:

- Data Parsing and representing the same on the HTML Div elements.
- Menu and its handlers for various Menu and Sub-Menu items.
- Complete Data for continents.

*/

atlas.dataHandler =  {

	url_countryFlag : "/images/flag/large/",
	url_countryMap : "/images/maps/",
	countryInfo : "",
	selectedCountry : "",
	selectedCountryCode : "",
	selectedCountryTab : 0,
	ciaCode : "",
	selectedContinent : "",
	selectedContinentTab : 0,

    checkQueryParams : function(data) 
    {
		// The URL will come in as /country/india/Geography etc...
        var url = window.location;
        var urlParams = url.toString().split("/");
        var countryParam = "";
        urlParams[3] = urlParams[3].toLowerCase();
        var placeListArray = atlas.continentData.placeListArray;
        
        if (urlParams[3] == "country")
        {
            var countryName = unescape(urlParams[4]);
            
            for(var i=0; i<placeListArray.length; i++)
            {
                if(String(countryName).toLowerCase() == String(placeListArray[i]).toLowerCase())	
                {
                    selectedCountryCode = atlas.continentData.countryCodeArray[i];
                    ciaCode = atlas.continentData.ciaCountryCodeArray[i];
                    countryParam = countryName+"||"+selectedCountryCode+"||"+ciaCode;
                }
            }
            
            atlas.helper.showPreLoading(true);
            this.selectedCountryCode = countryParam.substring(countryParam.indexOf("||")+2,countryParam.lastIndexOf("||"));
            this.ciaCode = countryParam.substring(countryParam.lastIndexOf("||")+2);
            this.selectedCountry = countryParam.substring(0,countryParam.indexOf("||"));
            
            if (!urlParams[5])
            {
            	this.selectedCountryTab = 0;
            }
            else
            {
	            var tabParam = urlParams[5].toLowerCase();
	            if (tabParam && tabParam == "introduction")
	                this.selectedCountryTab = 0;
	            else if (tabParam && tabParam == "geography")
	                this.selectedCountryTab = 1;
	            else if (tabParam && tabParam == "people")
	                this.selectedCountryTab = 2;
	            else if (tabParam && tabParam == "government")
	                this.selectedCountryTab = 3;
	            else if (tabParam && tabParam == "economy")
	                this.selectedCountryTab = 4;
	            else if (tabParam && (tabParam.indexOf("communication") != -1) )
	                this.selectedCountryTab = 5;
	            else
	                this.selectedCountryTab = 0;
	        }   
            
            // Select this tab so that we display the contents in this tab...
            $('#tabs').tabs('select', this.selectedCountryTab);
            
            $('#searchErrorBox').fadeOut();
            $("#tags").val(atlas.constants.SEARCH_GHOST_TXT);
            this.parseCountryInfo(data);
            
		}
        else if (urlParams[3] == "continent")
        {
            var continentName = unescape(urlParams[4]);
            var continentSubTab = unescape(urlParams[5]).toLowerCase();
            
            //alert("Selected continent tab " + continentSubTab);
            
            if (continentSubTab && continentSubTab == "land" )
            {
                this.selectedContinentTab = 0;
            } 
            else if (continentSubTab && continentSubTab == "people" )
            {
                this.selectedContinentTab = 1;
            }
            
            this.selectedContinent = continentName;
            
            atlas.menu.showContinents(continentName);
            
        }
        else if (urlParams[3] == "world")
        {
            var worldTitle = urlParams[4];
            atlas.menu.showWorldPages(worldTitle);
        }
	},
	
	parseCountryInfo : function(data) 
    {
    	atlas.menu.countryTabs.show();
        atlas.helper.showPreLoading(false);
        
        this.countryInfo = data.Country;
        var tmpInfo = "";
        
        // Putting contents to the corresponding divs...

        var sections = ["this.countryInfo.geography.terrain", "this.countryInfo.introduction.background", "this.countryInfo.geography.naturalhazard", "this.countryInfo.geography.area", "this.countryInfo.geography.landuse",
                        "this.countryInfo.people.ethnicgroups", "this.countryInfo.people.literacy", "this.countryInfo.government.flagdescription", "this.countryInfo.government.capital", "this.countryInfo.government.executivebranch",
                        "this.countryInfo.economy.gdp", "this.countryInfo.economy.imports", "this.countryInfo.economy.exports", "this.countryInfo.economy.laborforce", "this.countryInfo.economy.budget",
                        "this.countryInfo.economy.unemploymentrate", "this.countryInfo.tranportation.waterways", "this.countryInfo.tranportation.railways", "this.countryInfo.military.service",
                         "this.countryInfo.geography.naturalresources"];
                        
        var divs = ["#countryDataTerrain", "#countryDataIntro", "#countryDataHazards", "#countryDataArea", "#countryDataLanduse", "#countryDataEthnic", "#countryDataLitracy", "#countryDataGovtFlagDesc",
                    "#countryDataGovtCapital", "#countryDataGovtExecs", "#countryDataEcoGdp", "#countryDataEcoImport", "#countryDataEcoExport", "#countryDataEcoLabour", "#countryDataEcoBudget",
                    "#countryDataEcoEmpRate", "#countryDataWaterways", "#countryDataRailway", "#countryDataDefAge", "#countryDataEnviornment"];
                    
        for (var i=0; i<sections.length; i++)
        {
        	tmpInfo = atlas.helper.checkEmptyString(eval(sections[i]));
            
            if (tmpInfo == "NA." || tmpInfo == "NA")
            	tmpInfo = atlas.constants.NO_INFO_MSG;
            
            if (divs[i] == "#countryDataIntro")
            {
            	tmpInfo = tmpInfo.replace(/:/g, " - ");
            }
            
            if (divs[i] == "#countryDataDefAge")
            {
                tmpInfo = tmpInfo.replace(/;/g, "||");
                $(divs[i]).html((tmpInfo!=atlas.constants.NO_INFO_MSG)?atlas.helper.parseInfo(tmpInfo,1):tmpInfo);
            }
            else
            {
                $(divs[i]).html((tmpInfo!=atlas.constants.NO_INFO_MSG)?atlas.helper.parseInfo(tmpInfo):tmpInfo);
            }
        }
        
        var sections2 = ["this.countryInfo.introduction.climate", "this.countryInfo.people.birthrate", "this.countryInfo.people.deathrate", "this.countryInfo.name",
                        "this.countryInfo.government.governmenttype", "this.countryInfo.government.nationalholiday", "this.countryInfo.government.independence",
                        "this.countryInfo.communications.internetusers", "this.countryInfo.tranportation.airports", "this.countryInfo.tranportation.ports", "this.countryInfo.military.branches"];
                        
        var divs2 = ["#countryDataClimate", "#countryDataBRate", "#countryDataDRate", "#countryDataCName", "#countryDataGovtType", "#countryDataGovtHdays", "#countryDataGovtIndpnc",
                    "#countryDataInternet", "#countryDataAirport", "#countryDataPort", "#countryDataDefBranch"];
                    
        for (var i=0; i<sections2.length; i++)
        {
            tmpInfo = atlas.helper.checkEmptyString(eval(sections2[i]));
            $(divs2[i]).html(tmpInfo);
        }
        
            
        tmpInfo = atlas.helper.checkEmptyString(this.countryInfo.introduction.landboundaries);
        $("#countryDataBoundries").html((tmpInfo!=atlas.constants.NO_INFO_MSG)?atlas.helper.parseLandAndBoundaries(this.countryInfo.introduction.landboundaries):tmpInfo);
        
        $("#quickFacts").html(this.getQuickFactsData());
        
        $("#countryDataEcoExngRate").html(atlas.helper.parseCurrency(this.countryInfo.economy.exchangerates));
        
        $("#countryDataTelephone").html(atlas.helper.checkEmptyString(this.countryInfo.communications["Telephones-mainlinesinuse"]));
        
        $("#countryDataMobile").html(atlas.helper.checkEmptyString(this.countryInfo.communications["telephones-mobilecellular"]));
        
        tmpInfo = atlas.helper.checkEmptyString(this.countryInfo.military.expenditure);
        $("#countryDataDefExpn").html((tmpInfo!=atlas.constants.NO_INFO_MSG)?(this.countryInfo.military.expenditure):tmpInfo);

        if( this.selectedCountryCode != undefined && this.selectedCountryCode != "" && this.selectedCountryCode != "undefined" && this.ciaCode != "ay")
        {
            var flagName = this.url_countryFlag+String(this.ciaCode).toLowerCase()+"-lgflag.gif"
            $(".introrightTopImage").attr('src',(this.url_countryMap+String(this.ciaCode).toLowerCase()+"-map.gif"));
            $(".introrightTopImage").attr('alt',"Map of "+unescape(this.selectedCountry));
            $("#imgCountryFlag").attr('src',(this.url_countryFlag+this.ciaCode)+"-lgflag.gif")
        }
        else	
        {
            $(".introrightTopImage").attr('src',this.url_countryMap+"undefinedMap.jpg");
            $("#imgCountryFlag").attr('src',this.url_countryFlag+"undefinedFlag.jpg")
            
        }
        
        /*****************Chart data************************/
        
        /*
         * refreshing the charts in the selected page, while the data is chnaged by searching the country and or by dropdown
         */
        if(this.selectedCountryTab == 2 || this.selectedCountryTab == 1 || this.selectedCountryTab == 5 || this.selectedCountryTab == 0 )	{
            atlas.charting.removeCharts();
            setTimeout("atlas.dataHandler.showChart("+this.selectedCountryTab+")",500);

        }
        
        atlas.helper.showTitleContent(this.selectedCountry, atlas.constants.MODE_COUNTRY);
        
        document.title = "MapQuest Atlas - "+unescape(this.selectedCountry);
        $("#mqmapLink").attr("href","http://www.mapquest.com/maps?country="+this.selectedCountry);
        $("#mqmapLink01").attr("href","http://www.mapquest.com/maps?country="+this.selectedCountry);	
        $("#mqmapLink").click(function(){
            atlas.omniture.sendData("MQAtlasInteractiveMap",[unescape(this.selectedCountry).split(" ").join("")]);
        })
        $("#mqmapLink01").click(function(){
            atlas.omniture.sendData("MQAtlasInteractiveMap",[unescape(this.selectedCountry).split(" ").join("")]);
        })

    
	},
	
	showChart : function(tabId) 
    {
        if(this.selectedCountryTab == tabId)	{
            switch(tabId){
            case 0:
                this.createPhotoGalleryTags();
                break;
            case 1:			
                if(this.countryInfo.geography.area != atlas.constants.DB_EMPTY_CODE)	{
                    var areaData = atlas.charting.mineGeoArea(this.countryInfo.geography.area);
                    if(areaData.data.length == 2 && (areaData.data[0].value == 0 || areaData.data[1].value == 0 ))	{
                        
                    }
                    else	{
                        atlas.charting.createChartDisplay($("#areaPieData"),areaData,"pie",{w:250,h:200});
                    }
                    
                }
                
                if(this.countryInfo.geography.landuse != atlas.constants.DB_EMPTY_CODE)	{
                    var landData = atlas.charting.mineGeoLand(this.countryInfo.geography.landuse);
                    atlas.charting.createChartDisplay($("#landPieData"),landData,"pie",{w:250,h:200});
                    atlas.charting.createChartDisplay($("#dummyPieChartTbl"),landData,"pie",{w:50,h:50});
                    $("#dummyPieChart").hide();
                }
                
        
                break;
            case 2:			
                // age structure
                if (this.countryInfo.people.agestructure != atlas.constants.DB_EMPTY_CODE)		{
                    $("#countryDataAge").empty()
                    var ageStructureData = atlas.charting.mineAgeStructure(this.countryInfo.people.agestructure)
                    atlas.charting.createChartDisplay($("#peopleAgePieData"),ageStructureData,"pie",{w:250,h:200});
                    atlas.charting.createChartDisplay($("#dummyPieChartTbl"),ageStructureData,"pie",{w:50,h:50});
                    $("#dummyPieChart").hide();
                }
                else	{
                    $("#countryDataAge").html("<br><br>"+atlas.constants.NO_INFO_MSG)
                }
                //religions
                if (this.countryInfo.people.religions != atlas.constants.DB_EMPTY_CODE)		{
                    $("#countryDataReligion").empty()
                    var religionData = atlas.charting.mineReligionsData(this.countryInfo.people.religions,false);
                    if(!religionData.data[0])
                    	$("#countryDataReligion").html("<br><br>"+atlas.constants.NO_INFO_MSG);
                    else
                    	atlas.charting.createChartDisplay($("#peopleReligionPieData"),religionData,"pie",{w:250,h:200});
                }
                else	{
                    $("#countryDataReligion").html("<br><br>"+atlas.constants.NO_INFO_MSG)
                }
                
                // languages
                if(this.countryInfo.people.languages != atlas.constants.DB_EMPTY_CODE)	
                {
                    var languageData = atlas.charting.mineReligionsData(this.countryInfo.people.languages.split("||")[0],true);
                    if(languageData.data.length>0)	
                    {
                        $("#countryDataLanguage").empty()
                        atlas.charting.createChartDisplay($("#languagePieData"),languageData,"pie",{w:250,h:200});
                    }
                    else	
                    {
                        //$("#countryDataLanguage").html(breakCommaSeperatedIntoLines2(this.countryInfo.people.languages.split("||")[0]));
                        $("#countryDataLanguage").html(atlas.helper.parseInfo(this.countryInfo.people.languages));
                    }
                }
                else	{
                    $("#countryDataLanguage").html(atlas.constants.NO_INFO_MSG);
                    
                }
                //ethnic groups
                if(this.countryInfo.people.ethnicgroups != atlas.constants.DB_EMPTY_CODE)	{
                    $("#ethnicinfo").empty();
                    var ethnicData = atlas.charting.mineReligionsData(this.countryInfo.people.ethnicgroups,true);
                    atlas.charting.createChartDisplay($("#ethnicPieData"),ethnicData,"pie",{w:250,h:200},true,'right');
                }
                /*else	{
                    $("#ethnicinfo").html("<br>No Charts available at this time.");
                }*/
                break;
            }
        }
	},
	
	getQuickFactsData : function() 
    {
        var str,
        capStr = this.countryInfo.government.capital,
        lng = this.countryInfo.people.languages.split("||"),
        religion = this.countryInfo.people.religions.split(","),
        pop=this.countryInfo.people.population,
        area = this.countryInfo.geography.area,
        exchRate = atlas.helper.parseCurrency(this.countryInfo.economy.exchangerates)+" per";
        var totArea = "";
        var populationData = "";
        
        if(area != atlas.constants.DB_EMPTY_CODE)	{
            totArea = area.substring(7, (area.indexOf("||")));
        }
        else	
        {
            totArea = atlas.constants.DB_EMPTY_CODE;
        }
        
        if(pop==atlas.constants.DB_EMPTY_CODE)	{
            populationData = "Not Available."
        }
        else	
        {
            if (pop.indexOf("||") != -1)
                populationData = pop.substring(0, (pop.indexOf("||")));
            else
                populationData = pop.substring(0);
        }			
        
        str = "<table cellpadding='1'><tr><td class='tdBold'>Capital </td><td class='tdBoldSpot padLtRt5'>:</td><td>"+ ((capStr==atlas.constants.DB_EMPTY_CODE)?"Not Available.":capStr.substring(6, capStr.indexOf("||"))) +"</td></tr>";
        str += "<tr><td class='tdBold'>Language </td><td class='tdBoldSpot padLtRt5'>:</td><td>"+ ((lng==atlas.constants.DB_EMPTY_CODE)?"Not Available.":lng[0])+"</td></tr>";
        str += "<tr><td class='tdBold'>Religions </td><td class='tdBoldSpot padLtRt5'>:</td><td>"+ ((religion==atlas.constants.DB_EMPTY_CODE)?"Not Available.":religion[0]) +"</td></tr>";
        str += "<tr><td class='tdBold'>Monetary Unit </td><td class='tdBoldSpot padLtRt5'>:</td><td>"+ ((exchRate==atlas.constants.DB_EMPTY_CODE)?"Not Available.":exchRate.substring(0, (exchRate.indexOf("per"))))+"</td></tr>";
        str += "<tr><td class='tdBold'>Population </td><td class='tdBoldSpot padLtRt5'>:</td><td>"+($.trim(populationData) == "no" ? "Not Available." : populationData)+"</td></tr>";
        str += "<tr><td class='tdBold'>Total Area </td><td class='tdBoldSpot padLtRt5'>:</td><td>"+totArea+"</td></tr></table>";
        return str;
			
	},
	
	createCountryPhotoGallery : function() 
    {
        $("#countryImageCarousal").jcarousel({scroll:8});
		$("a[rel=popupImage]").fancybox({'transitionIn'	: 'none','transitionOut': 'none','titlePosition' : 'inside','titleFormat': 
		function(title, currentArray, currentIndex, currentOpts) {	return '<span id="fancybox-title-over">'+ atlas.dataHandler.returnPopupCredit(title)+'</span><br>';}
		});
	},
	
	returnPopupCredit : function(title) {
        var pcredit = title;
		var credits = title.split("^^");
		pcredit = "<div class='creditPopupImage'>"+credits[1]+"</div><br>"+unescape(credits[0])
		pcredit = unescape(pcredit)
		return pcredit;
	},
	
	createCountryFlagGallery : function() 
    {
        var tabId = "";
		var flagId = "";
		var id = atlas.menu.selectedContinentId;
		if(!atlas.continentData.continents[id].isFlagged && id<6)	
        {
			atlas.continentData.continents[id].isFlagged = true;
			tabId = String(atlas.continentData.continents[id].tab.attr("id"))
			flagId = "flag"+tabId.substring(tabId.indexOf("-"));
		
            var countryFlags = String(atlas.continentData.continents[id].cia);
            
            //removing Gaza Strip
            if(id == 0 && countryFlags.indexOf("gz")>0)	
            {
                countryFlags0 = countryFlags.substring(0,countryFlags.indexOf("gz"));
                countryFlags1 = countryFlags.substring(countryFlags.indexOf("gz")+3);
                countryFlags = countryFlags0+countryFlags1;
                countryFlags = countryFlags.split(",");
            }
            else
            {
                countryFlags = countryFlags.split(",")
            }
            
            var ulId = "countryImageCarousal-"+id
            var liTags = "<ul id="+ulId+" class='jcarousel-skin-ie7'>";
            var flagName = "";
            var paramCountryName = "";
            //
            if(countryFlags.length > 1)	
            {
                for(var i=0; i<countryFlags.length; i++){
                    flagName = this.url_countryFlag+""+countryFlags[i]+"-lgflag.gif"
                    paramCountryName = atlas.continentData.continents[id].countries[i];
                    liTags += "<li title='"+atlas.continentData.continents[id].countries[i]+"' class='countryFlagList'><a href='/country/"+paramCountryName+"/'><img src='"+flagName+"' width='95' height='70'  border='0'/></a></li>";
                }
                liTags += "</ul>";
                
                $("#"+flagId).html(liTags);
                $("#"+ulId).jcarousel({scroll:8});
            }
        }
    },
	
	showWorldCharts : function(id) 
    {
        switch(Number(id))	{
		case 0:
			var peoplePieData = {data:[{value:14,item:"Africa"},{value:60,item:"Asia"},{value:11,item:"Europe"},{value:8,item:"North America"},{value:6,item:"South America"},{value:0.5,item:"Oceania"},{value:0.00015,item:"Antarctica"}]}
			atlas.charting.createChartDisplay($("#peopleChatData"),peoplePieData,"pie");
			
		    	
			break
		case 2:
			var religionData = {data:[{value:33.32,item:"Christians"},{value:21.01,item:"Muslims"},{value:13.26,item:"Hindus"},{value:5.84,item:"Buddhists"},{value: 0.35,item:"Sikhs"},{value:0.23,item:"Jews"},{value: 0.12,item:"Baha'is"},{value:11.78,item:"Other"},{value:11.77,item:"non-religious"}]}
			atlas.charting.createChartDisplay($("#religionPieChartData"),religionData,"pie",{w:300,h:230});

			break;
		case 3:
			var languageData = {data:[{value:12.65,item:"MandarinChinese"},{value:4.93,item:"Spanish"},{value:4.91,item:"English"},{value:3.31,item:"Arabic"},{value:2.73,item:"Hindi"},{value: 2.67,item:"Portuguese"},{value:2.71,item:"Bengali"},{value: 2.16,item:"Russian"},{value: 1.83,item:"Japanese"},{value:1.35,item:"Standard German"},{value:1.27,item:"Javanese"},{value:59.38,item:"Others"}]}
			atlas.charting.createChartDisplay($("#languageWorldPieData"),languageData,"pie");
			
			break;
		case 4:	
			var areaData = {data:[{value:70.9,item:"Water"},{value:29.1,item:"Land"}]}
			atlas.charting.createChartDisplay($("#areaWorldPieData"),areaData,"pie",{w:250,h:200});
			
			var landData = {data:[{value:10.75,item:"Arable Land"},{value:1.4,item:"Permanent Corps"},{value:88.39,item:"Other"}]}
			atlas.charting.createChartDisplay($("#landWorldPieData"),landData,"pie",{w:250,h:200});
			break;
			
		}
	},
	
	createPhotoGalleryTags : function() 
    {
	    $("#flagBox").html();
        $("#flagBox").empty();
        
        if(this.countryInfo.introduction.photos.length > 10)	{
            $("#flagBox").addClass("flagBorder")
            var photoData = this.countryInfo.introduction.photos.split("||");
            var photoItem;
            var photoTag = "<ul id='countryImageCarousal' class='jcarousel-skin-ie7'>";
            var creditTag = "<div class='photoGalleryCredits'>Photos, The World Factbook 2011. Washington DC: Central Intelligence Agency 2011, unless otherwise noted.</div>";
            var thumbNail = "";
            var countryImgPath = "/images/gallery/"+this.ciaCode+"/";
            var title = "";
            var liElement = "<li>"
            for(var i=0; i<photoData.length; i++)	{
                
                photoItem = photoData[i].split("|")
                title = escape(photoItem[1]);
                //checking NASA's credit
                if((Number(photoItem[2]) == 1))	{
                    //title = title.substring(0,title.length-3)
                    title += "^^NASA/CIA. The World Factbook 2011. Washington DC: Central Intelligence Agency 2011.";
                    liElement = "<li title='NASA'>"
                }
                else	{
                    liElement = "<li>";
                    title = title+"^^The World Factbook 2011. Washington, DC: Central Intelligence Agency, 2011.";
                }
                
                thumbNail = String(photoItem[0]).substring(0,photoItem[0].lastIndexOf("."))
                
                photoTag += liElement+" <a rel='popupImage' href='"+countryImgPath+""+photoItem[0]+"' rev='"+title+"' onclick='atlas.dataHandler.sendThumbnailClickTracking()'><img src='"+countryImgPath+""+thumbNail+"_THUMBNAIL.jpg' width='95' height='70'  border='0' /></a></li>"
                
            }
            photoTag += "</ul>"+creditTag;
            
            $("#flagBox").html(photoTag);
            
            this.createCountryPhotoGallery();
        }
        else	{
            $("#flagBox").removeClass("flagBorder")
        }
	},
	
	sendThumbnailClickTracking : function() 
    {
        atlas.omniture.sendData("MQAtlasPhotoOpen",[unescape(this.selectedCountry).split(" ").join("")]);
	},
	
	nasaMouseOutEvent : function(event,ui) 
    {
        $("#nasaDiv").hide();
	},
	
	nasaMouseOverEvent : function(event,ui) 
    {
        var xpos,ypos;
        if(event.pageX == undefined)	
        {
            xpos = event.clientX + document.documentElement.scrollLeft;
            ypos = event.clientY + document.documentElement.scrollTop;
        }
        else	
        {
            xpos = event.pageX;
            ypos = event.pageY;
        }

		var screenRes = atlas.helper.getViewPort();
        var offset = ((screenRes.swidth-atlas.constants.PAGE_WIDTH)/2)-4;
        $('#nasaDiv').css({left:xpos-offset-75,top:315}).show();
	},
	
	flagMouseOutEvent : function(event,ui) 
    {
        $("#flagDiv").hide();
	},
	
	flagMouseOverEvent : function(event,ui) 
    {
        var xpos,ypos;
        if(event.pageX == undefined)	
        {
            xpos = event.clientX + document.documentElement.scrollLeft;
            ypos = event.clientY + document.documentElement.scrollTop;
        }
        else	
        {
            xpos = event.pageX;
            ypos = event.pageY;
        }

		var screenRes = atlas.helper.getViewPort();
        var offset = ((screenRes.swidth-atlas.constants.PAGE_WIDTH)/2)-4;
        $('#flagDiv').html(event.currentTarget.title);		
        $('#flagDiv').css({left:atlas.helper.getX(event),top:308}).show();
	}
	
}

atlas.menu = {

	selectedContinentId : 0,
	currentSelectedWorldPage : "",
	countryTabs : "",
	clickPos : {x:0,y:0},
	isMenuActive : false,
	
	worldMenuClickHandler : function(event)
	{		
		this.menuBarClearArrow();
		//selectedUIMode = MODE_WORLD;
		var selectedWorldPage = event.currentTarget.title
		var url = window.location.href
		var redirectWorldPath = "/world/" + selectedWorldPage + "/";
		window.location.replace(redirectWorldPath);
		
    	event.stopPropagation();
		this.hideMenu();
	},
	
	continentMenuClickHandler : function(event)
	{
		this.menuBarClearArrow();
		//selectedUIMode = MODE_CONTINENT;
		var id = $(event.currentTarget).attr('id')
		id = id.substring(id.lastIndexOf("_")+1)
		
		var selectedContinent = event.currentTarget.title
		var url = window.location.href;
		var redirectPath = "/continent/" + selectedContinent + "/";
		
		window.location.replace(redirectPath);
		this.hideMenu();
		event.stopPropagation();
	},
	
	countryMenuClickHandler : function(event)
	{
		this.menuBarClearArrow();
		//selectedUIMode = atlas.constants.MODE_COUNTRY;
		var countryName = $(event.currentTarget).attr("id");
		var selectedCountry = (countryName.split("||"))[0];
        
		var url = window.location.href
		var redirectPath = "/country/"+selectedCountry + "/";
		
		atlas.charting.removeCharts();
		window.location.replace(redirectPath);
		event.stopPropagation();
		this.hideMenu();
		event.stopPropagation();
	},
	
	hideMenu : function()	
	{
     	$("#continents").css("display","none");
     	$("#worlds").css("display","none");
     	$("#headWorld").css("background-color","");
     	$("#headContinents").css("background-color","");
     	$("#arrow_World").attr("src","/images/arrow_menu_marron.png");
     	$("#arrow_Continents").attr("src","/images/arrow_menu_marron.png");
     	
     	$("#link_World").css("color","#039CD2");
     	$("#link_Continents").css("color","#039CD2");
     	this.isMenuActive = false;
	},

	showFirstLevelDropdown : function(selected,mainHead,arrowId)	
	{
		$("#continents").css("display","none");
		$("#worlds").css("display","none");
		$("#"+selected).css("display","block");
		$("#headWorld").css("background-color","");
		$("#headContinents").css("background-color","");
		$(mainHead).css("background-color","#61375D");
		
		var id = $(mainHead).attr("title");
		$("#arrow_World").attr("src","/images/arrow_menu_marron.png");
		$("#arrow_Continents").attr("src","/images/arrow_menu_marron.png");
		$("#arrow_"+arrowId+"").attr("src","/images/arrow_menu_white.png");

		this.isMenuActive = true;		
    },
                 
	buildComboDropDown : function()	
	{
		$(".errortxt").html("<b>No result found.</b><br/>Enter a valid country name.");
		$hasMenu = $('#nav-site .has-menu-a');
		$menu = $hasMenu.find('> li > .menu');
		$menu.hide();
		$hasMenu.find('> li.more > .label').click(function(){
			$hasMenu.toggleClass('has-menu-a-is-open');
			$menu.toggle();
			return false
		});
		
		$('body').click(function(event)
		{
			atlas.menu.hideMenu();
			atlas.menu.menuBarClearArrow();
			if (atlas.mapHandler && atlas.mapHandler.mapClickQueryRunning == true)
				return;
					
			var xpos = 0;
			var ypos = 0;
			//TODO 
			//check whether the page is in home?
			
			$("#popuup_div").html("");
			$("#popuup_div").empty();
			$("#popuup_div").hide();
			$hasMenu.removeClass('has-menu-a-is-open');
			$("#smartInputFloater").css("display","none");
			
			//$("#link_World").css("color","#039CD2");
			//$("#link_Continents").css("color","#039CD2");
			$menu.hide();
			this.isMenuActive ? this.hideMenu() : undefined
			if(event.pageX == undefined) {
				xpos = event.clientX + document.documentElement.scrollLeft;
				ypos = event.clientY + document.documentElement.scrollTop;
			}
			else {
				xpos = event.pageX;
				ypos = event.pageY;
			}
			
			var screenRes = atlas.helper.getViewPort();
			var offset = ((screenRes.swidth-atlas.constants.PAGE_WIDTH)/2)-4;
			atlas.menu.clickPos = {x:xpos-offset,y:ypos-14};
		});
	},

	createMenu : function()	
	{
		var menu = $("#menubar");
		var tags = "";
	
		var worldHead = $("#headWorld");
		
		tags = "<ul class='sMs subMenu00' id='worlds'>";
		
		var worldMenu = atlas.constants.worldMenu;
		for(i=0; i<worldMenu.length; i++){
			if(worldMenu[i].show == true)
			tags += "<li class='liWorld' title='"+worldMenu[i].name+"' id='cont"+worldMenu[i].name.substring(0,3)+"'>"+atlas.helper.createFancyBox(worldMenu[i].name,"WO")+"</li>"
		}
		tags += "</ul>";	
		worldHead.append(tags);
		
		worldHead.click(function(event){
			$("#continentsArrow").removeClass("dWArrow");
			$("#link_Continents").removeClass("whiteTxt");
			$("#worldArrow").addClass("dWArrow");
			$("#link_World").addClass("whiteTxt");
			atlas.menu.showFirstLevelDropdown("worlds",this,"World");
			event.stopPropagation();
		})
		$('.liWorld').click(function(event){atlas.menu.worldMenuClickHandler(event)});
		
		var continentHead = $("#headContinents");
		tags = "<ul class='subMenu01' id='continents'>";
		var countries = null;
		var ciaCode = null;
		var countryCode = null;
		
		var continents = atlas.continentData.continents;
		for(i=0; i<continents.length; i++){
			tags += "<li class='liContinent' title='"+continents[i].name+"' id='continentHolder_"+continents[i].name.substring(0,3)+"'>"+atlas.helper.createFancyBox(continents[i].name,"CO")+"<ul class='subMenu02'>"
			countries = continents[i].countries;
			ciaCode = continents[i].cia;
			countryCode = continents[i].codes;
			tags += this.splitCountries(countries,countryCode,ciaCode,i)
			tags += "</ul></li>";
		}
		tags += "</ul>";
		continentHead.append(tags);
		
		continentHead.click(function(event){
			$("#worldArrow").removeClass("dWArrow");
			$("#link_World").removeClass("whiteTxt");
			$("#continentsArrow").addClass("dWArrow");
			$("#link_Continents").addClass("whiteTxt");
			atlas.menu.showFirstLevelDropdown("continents",this,"Continents");
			event.stopPropagation();
		})
		$('.liContinent').click(function(event){atlas.menu.continentMenuClickHandler(event)});
		$('.liCountry').click(function(event){atlas.menu.countryMenuClickHandler(event)});
	},

	menuBarClearArrow : function()
	{
		$("#continentsArrow").removeClass("dWArrow");
		$("#worldArrow").removeClass("dWArrow");
		$("#link_World").removeClass("whiteTxt");
		$("#link_Continents").removeClass("whiteTxt");
	},
	
	splitCountries : function(countries,code,cia,continentId)	
	{
		var rows = 26;
		var len = countries.length;
		var mod = Math.ceil(len/rows);
		var count = 0;
		var countryTags = (mod === 1) ? "<li class='countryBg' style='width:308px'>" : "<li class='countryBg'>";
		var countryName = "";
		var liId = "";
		var isCountryPage = atlas.helper.checkIsCountryPage();
		//countries = countries.sort();
		var hrefHash = ""
		for (var i=0; i<mod; i++) {
			//bad hack for resizing the width of the menu;
			//countryTags += "<div class='countryListBox'><ul>";
			countryTags += (mod === 2 || mod === 1 ) ? "<ul class='countryListBox' style='width:300px;'>" : "<ul class='countryListBox'>";
			for (var j=0; j<rows; j++) {

				
				liId = countries[count]+"||"+code[count]+"||"+cia[count];
				// bad hack
				if(i == 0 && countries[count] == "Congo Democratic Republic of the")	{
					countryName = "Congo Democratic Republic...";
				}
				else	{
					countryName = countries[count];
				}
				
				countryTags += "<li title='"+countries[count]+"' id='"+liId+"' class='liCountry'><a "+hrefHash+" class='linkNode'>"+countryName+"</a></li>";
				count++;
				if (count == len || countryName == undefined) {
					break;
				}

			}
			//countryTags += "</ul></div>";
			countryTags += "</ul>";
		}
		countryTags += "</li>";
		return countryTags;
	},
	
	createWorldPages : function() 
    {
    	atlas.constants.worldMenu[0].container = $("#worldPopulation");
		atlas.constants.worldMenu[1].container = $("#worldClimate");
		atlas.constants.worldMenu[2].container = $("#worldReligion");
		atlas.constants.worldMenu[3].container = $("#worldLanguage");
		atlas.constants.worldMenu[4].container = $("#worldLandUse");
		atlas.constants.worldMenu[5].container = $("#worldPolitic");
		atlas.constants.worldMenu[6].container = $("#worldTime");
		atlas.constants.worldMenu[7].container = $("#worldLifes");
		
		for(var i=0; i<atlas.constants.worldMenu.length; i++)
		{
			atlas.constants.worldMenu[i].container.hide();
			atlas.constants.worldMenu[i].visited = false;
		}
		this.currentSelectedWorldPage = atlas.constants.worldMenu[0].container;
		this.currentSelectedWorldPage.show();
	},
	
	showWorldPages : function(worldItem) 
    {
        worldItem = unescape(worldItem);
		atlas.helper.showTitleContent(worldItem, atlas.constants.MODE_WORLD);
		this.currentSelectedWorldPage.hide();
		
		var worldMenu = atlas.constants.worldMenu;
        for(var i = 0; i<worldMenu.length; i++)	{
			if(worldItem.toLowerCase() == String(worldMenu[i].name).toLowerCase())	{
				this.currentSelectedWorldPage = worldMenu[i].container;
				break;
			}
		}
		this.currentSelectedWorldPage.show();
		$("#mainTitleBox").html(worldItem);
		if(!atlas.constants.worldMenu[i].visited)	{
			atlas.constants.worldMenu[i].visited = true;
			if( i == 0 || i == 2 || i == 3 || i == 4)	{
				setTimeout("atlas.dataHandler.showWorldCharts("+i+")",500);
				
			}
			
		}
	},
	
	createContinentTabs : function() 
    {
        atlas.continentData.continents[0].tab = $("#continent-africa").tabs({select:atlas.menu.continentTabEventHandler});
		atlas.continentData.continents[1].tab = $("#continent-asia").tabs({select:atlas.menu.continentTabEventHandler});
		atlas.continentData.continents[2].tab = $("#continent-europe").tabs({select:atlas.menu.continentTabEventHandler});
		atlas.continentData.continents[3].tab = $("#continent-namerica").tabs({select:atlas.menu.continentTabEventHandler});
		atlas.continentData.continents[4].tab = $("#continent-samerica").tabs({select:atlas.menu.continentTabEventHandler});
		atlas.continentData.continents[5].tab = $("#continent-oceania").tabs({select:atlas.menu.continentTabEventHandler});
		atlas.continentData.continents[6].tab = $("#continent-antarctica").tabs({select:atlas.menu.continentTabEventHandler});
		
		for(var i=0; i<atlas.continentData.continents.length; i++){
			atlas.continentData.continents[i].tab.hide();
			atlas.continentData.continents[i].isFlagged = false;
		}
		atlas.continentData.continents[0].tab.show();
		this.selectedContinentId = 0;
	},
	
	showContinents : function(continentName) 
    {
		continentName = unescape(continentName);
		atlas.helper.showTitleContent(continentName, atlas.constants.MODE_CONTINENT);
		var id = 0;
		for(var i=0; i<atlas.continentData.continents.length; i++){
			if(continentName.toLowerCase() == String(atlas.continentData.continents[i].name).toLowerCase())	{
            
				atlas.continentData.continents[i].tab.show();
				this.selectedContinentId = i;
			}
			else	{
				atlas.continentData.continents[i].tab.hide();
			}
		
		}
        
        var selectedContinentTab = atlas.dataHandler.selectedContinentTab;
        if (this.selectedContinentId == 0)
            $('#continent-africa').tabs('select', selectedContinentTab);
        else if (this.selectedContinentId == 1)
            $('#continent-asia').tabs('select', selectedContinentTab);
        else if (this.selectedContinentId == 2)
            $('#continent-europe').tabs('select', selectedContinentTab);
        else if (this.selectedContinentId == 3)
            $('#continent-namerica').tabs('select', selectedContinentTab);
        else if (this.selectedContinentId == 4)
            $('#continent-samerica').tabs('select', selectedContinentTab);
        else if (this.selectedContinentId == 5)
            $('#continent-oceania').tabs('select', selectedContinentTab);
        else if (this.selectedContinentId == 6)    
            $('#continent-antarctica').tabs('select', selectedContinentTab);
	},
	
	countryTabEventHandler : function(event,ui) 
    {
        var tabIndex =  ui.index;
        
        if (atlas.dataHandler.selectedCountryTab == tabIndex)
            return;
    
        var tabStr = "Introduction";
        if (tabIndex == 1)
            tabStr = "Geography";
        else if (tabIndex == 2)
            tabStr = "People";
        else if (tabIndex == 3)
            tabStr = "Government";
        else if (tabIndex == 4)
            tabStr = "Economy";
        else if (tabIndex == 5)
            tabStr = "Communication";
        
        var selectedCountry = atlas.dataHandler.selectedCountry;
        if (tabIndex == 0)
        	redirectPath = "/country/" + selectedCountry + "/";
		else
			redirectPath = "/country/" + selectedCountry + "/" + tabStr + "/";
			
		atlas.charting.removeCharts();
		atlas.omniture.sendData("MQAtlasTabSelect",[tabIndex,selectedCountry]);
        
        window.location.replace(redirectPath);
		event.stopPropagation();
        //this.hideMenu();
        atlas.helper.showPreLoading(true);  
        return false;
	},
	
	continentTabEventHandler : function(event,ui) 
    {
        var tabIndex =  ui.index;
        if (atlas.dataHandler.selectedContinentTab == tabIndex)
        {
            var methodName = "atlas.dataHandler.createCountryFlagGallery()";
            setTimeout(methodName,500);
            return;
        }
        else
        {
            var tabStr = "Land";
            if (tabIndex == 0)
                tabStr = "Land";
            else if (tabIndex == 1)
                tabStr = "People";
      		
      		if (tabIndex == 0)
      			redirectPath = "/continent/" + atlas.dataHandler.selectedContinent + "/";
      		else
            	redirectPath = "/continent/" + atlas.dataHandler.selectedContinent + "/" + tabStr + "/";
		
            atlas.charting.removeCharts();
		
            window.location.replace(redirectPath);
            event.stopPropagation();
            //this.hideMenu();
            atlas.helper.showPreLoading(true);  
        	return false;
        }
	}	
}

atlas.continentData = {

	placeListArray : [],
	countryCodeArray : [],
	ciaCountryCodeArray : [],
	ghostTextClicked : false,
	continents : [
					{id:1,name:"Africa",code:"AF",countries:[],codes:[],tab:{},capitals:[],cia:[],isFlagged:false},
					{id:2,name:"Asia",code:"AS",countries:[],codes:[],tab:{},capitals:[],cia:[],isFlagged:false},
					{id:3,name:"Europe",code:"EU",countries:[],codes:[],tab:{},capitals:[],cia:[],isFlagged:false},
					{id:4,name:"North America",code:"NA",countries:[],codes:[],tab:{},capitals:[],cia:[],isFlagged:false},
					{id:5,name:"South America",code:"SA",countries:[],codes:[],tab:{},capitals:[],cia:[],isFlagged:false},
					{id:6,name:"Oceania",code:"OC",countries:[],codes:[],tab:{},capitals:[],cia:[],isFlagged:false},
					{id:7,name:"Antarctica",code:"AN",countries:[],codes:[],tab:{},capitals:[],cia:[],isFlagged:false}
				 ],
	collection : [],
	
	getCountryList : function(data)	
	{
		atlas.menu.buildComboDropDown();
		//screenRes = atlas.helper.getViewPort();
		this.parseCountryListJson(data);
	},

	parseCountryListJson : function(data)	
	{
		var allContinentData = data.Continents;
		
		var countryListData;
		var countryCodeTempStore;
		var capitalList;
		var places = [];
		var codeOfCountries = [];
		var ciaCodes = [];
		
		for(var i=0; i<this.continents.length; i++)
		{
			countryListData = allContinentData[i].countryName.split(",");
			countryCodeTempStore = allContinentData[i].countryCode.split(",");
			capitalList = allContinentData[i].capital.split(",");
			ciaCodes = allContinentData[i].ciaCountryCode.split(",");
			
			this.continents[i].countries = countryListData;
			this.continents[i].codes = countryCodeTempStore;
			this.continents[i].capitals = capitalList;
			this.continents[i].cia = ciaCodes;
			
			places = places.concat(countryListData);
			codeOfCountries = codeOfCountries.concat(countryCodeTempStore);
			this.ciaCountryCodeArray = this.ciaCountryCodeArray.concat(ciaCodes);
		}
		
		this.placeListArray = places;
		this.collection = this.placeListArray;
		this.countryCodeArray = codeOfCountries;
		
		this.initialiseCountryList();
	},
	
	initialiseCountryList : function()	
	{
		var currentUrl = $(location).attr("href");
		var str = "";
		
		/*Ghost Text*/
		$("#tags").css("color","#999");
		$("#tags").val(atlas.constants.SEARCH_GHOST_TXT);
		
		$("#tags").focusout(function () {
			if($("#tags").val() == "")	{
				$("#tags").css("color","#999")
				$("#tags").val(atlas.constants.SEARCH_GHOST_TXT)
				
			}else{
				this.ghostTextClicked = true;
			}
		});
			
		$("#tags").focusin(function () {
			if(this.ghostTextClicked)$("#tags").select();
		});
		
		$("#tags").click(function(){
			atlas.search.clrInputBox();
		});
		
		$(".goButton").click(function(){
			var countryStr = $("#tags").val()
			if (!atlas.search.searchCountryList(countryStr)){
				$('#searchErrorBox').fadeIn('fast');
			}
		});
		
		$('#tags').bind('keypress', function(e) {
				atlas.search.clrInputBox();
				if(e.which==13) {
					var countryStr = $("#tags").val();
					if(countryStr != "" && countryStr != atlas.constants.SEARCH_GHOST_TXT)	{
						if (!atlas.search.searchCountryList(countryStr)){
							$('#searchErrorBox').fadeIn('fast');
						}
						$("#tags").val(countryStr)
					}
				}
		});
	
		$(".crossButton").click(function(){
			 $('#searchErrorBox').hide();
		});
		
		// only for compare countries
		/*if( (currentUrl.toLowerCase()).indexOf("comparecountries")>0)	{
			showCountryComboInCompareCountry();
		}*/
		
		/* creating drop down menu ends*/
		atlas.menu.createMenu();
	}

}


