// JavaScript Document

//initialize the lightview (popup window)
document.observe('lightview:loaded', lightViewLoaded);

var issueID;

pages = new CookieJar({
	expires:4800, // seconds
	path: '/'
});

function lightViewLoaded() {
	var lvLoaded = true;	
	if(document.URL.include('index.html') || !(document.URL.include('.html'))) {
		if(!(document.URL.include('.asp'))) {
		 	loadHomepage();
		}
	 }
}

//Show the homepage lightview box
function loadHomepage () {
	Lightview.show({
      href: 'home.html',
      rel: 'iframe',
	  radius: 1,
      options: {
      	topclose: true,
      	width: 730,
	    height: 775
      }
  });
}

function closeHomepage () {
	Lightview.hide();
}

//fire this function after the DOM has loaded
document.observe("dom:loaded", function() {
	//location.replace("http://staging.jasperdesign.com/tobaccoatlas3/");
	 activateDropdowns();
  	 
	 if($('mapPage')) {
		showViewedPages();
		storePage($('titleHeading').firstChild.nodeValue);
		switchPage();
	 }
	 if($('mapTabs')) {
		new Control.Tabs($('mapTabs'),{   
    	   setClassOnContainer: true,  
    	   activeClassName: 'selected'
	 	}); 
		//var pagetabs = $$('.tab');
		//for (i=0; i < pagetabs.length; i++) {
			//if(i > 0) {
				//pagetabs[i].observe('click', function(event) { $('footer').hide();});
			//}
			//else {
				//tabs[0].observe('click', function (event){$('footer').show();});
			//}
		//}
	 }
	 
	 $('logo').down('a').replace("<a href='#'>The Tobacco Atlas</a>"); 
	 $('logo').observe('click', loadHomepage);
});

//make the top navigation drop down menus show/hide on rollover
function activateDropdowns () {
	$$(".nav li").each(function(node){

		// if there’s a ul
		var ul = $A(node.getElementsByTagName("ul")).first();
		if(ul != null){

				// toggle it’s visibility on these events
				node.onmouseover = node.onmouseout = function(){
						Element.toggle(ul);
				}
		}
    });
}

//go to a page from the selected issues drop down
function gotoPage(form){
    var url = form.issues.options[form.issues.selectedIndex].value;
    if (url != "") {
        location.href = url;
    }
}

//shows the recently viewed pages in the right navigation
function showViewedPages() {
	recentPages = pages.get('recentPages');
	if(recentPages) {
		for(var i = 0; i < recentPages.pageTitles.length; i=i+1) {
			var string = "<li><a href='" + recentPages.pageURLs[i] + "'>" + recentPages.pageTitles[i] + "</a></li>";
			$('recentlyViewed').insert(string);	
		}
	}
}

//creates a cookie with the recent page titles and urls
function storePage (txt) {
	
	if(pages.get('recentPages')) {
		pTitles = pages.get('recentPages').pageTitles;
		pURLs = pages.get('recentPages').pageURLs;
	}
	else {
		pTitles = [];
		pURLs = [];
	}
		
	if(pTitles.indexOf(txt) == -1) {
		pTitles.push(txt);
		pURLs.push(document.URL);
	}
	data = {pageTitles: pTitles, pageURLs: pURLs};
	pages.put('recentPages', data);
}


// Read a page's URL variables and return them as an associative array.
function getUrlVars() {
	var vars = [], hash;
	if(window.location.href.include('&amp;')) {
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&amp;');
	}
	else {
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	}
	for(var i = 0; i < hashes.length; i++) {
	  hash = hashes[i].split('=');
	  vars.push(hash[0]);
	  vars[hash[0]] = hash[1];
	}
	return vars;
}

//change the page based on the variables in its URL 
function switchPage() {
	var urlVars = getUrlVars();
	var pageName = "";
	
	switch(urlVars["issues"]) {
 	case "02":
		pageName= "males.html";
	    break;
	case "03":
		pageName= "females.html";
	break;
	case "04":
		pageName= "healthprofessionals.html";
	    break;
	case "05":
		pageName= "boys.html";
	    break;
	case "06":
		pageName= "girls.html";
	    break;
	case "07":
		pageName= "consumption.html";
	    break;
	case "08":
		pageName= "femaledeaths.html";
		break;
	case "09":
		pageName= "secondhandsmoke.html";
	    break;
	case "10":
		pageName= "maledeaths.html";
	    break;
	case "11":
		pageName= "costs.html";
	    break;
	case "12":
		pageName= "coststothesmoker.html";
	    break;
	case "13":
		pageName= "growing.html";
		break;
	case "14":
		pageName= "companies.html";
	    break;
	case "15":
		pageName= "trade.html";
	    break;
	case "16":
		pageName= "illegal.html";
	    break;
	case "17":
		pageName= "marketing.html";
	    break;
	case "19":
		pageName= "industrydocs.html";
	    break;
	case "21":
		pageName= "capacity.html";
	    break;
	case "22":
		pageName= "fctc.html";
	    break;
	case "23":
		pageName= "smokefreeareas.html";
	    break;
	case "24":
		pageName= "marketingbans.html";
	    break;
	case "25":
		pageName= "productlabeling.html";
	    break;
	case "27":
		pageName= "quitting.html";
	    break;
	case "28":
		pageName= "pricesandtaxes.html";
	    break;
	case "29":
		pageName= "litigation.html";
	    break;
	case "30":
		pageName= "religion.html";
	    break;
	case "31":
		pageName= "mpower.html";
	    break;
	default: 
	    //no issue variable
		if(urlVars["iss"]) {
			var issue = urlVars["iss"];	
		}
	}

	if(pageName != "") {
		location.replace(pageName + "?iss=" + urlVars["issues"] + "&amp;country=" + urlVars["countries"]);
	}
	
	if(!(urlVars["issue"]) && urlVars["country"] && urlVars["country"] != "0") {  
	  var country = urlVars["country"];
	  storeCountry(country);
	  mapLoad(issue, country);
	}
	
	if(!(urlVars["country"]) && issueID) {
	  mapLoad(issueID, getCountry());
	}
}

//loads a flashmap using the given issueID
function loadFlashMap (id) {
	issueID = id;
	if (DetectFlashVer(8,0,0)) {
		fmObjectActivateWrite("fmASEngine","fmASMap/fmASContainer.swf?issue=" + issueID, "800", "352", "true", "high", "#FFFFFF", ".");
	} 
	else {
		var alternateContent = 'This content requires version 8 or higher of the Adobe Flash Player. <a href="http://www.adobe.com/go/getflash/">Get Flash</a>';
		document.write(alternateContent);
	}
}

function mapLoad(issue_str, country_str) {
	if(country_str == 'xx' || country_str == 'undefined') {
		country_str = '';
	} 
	$('mapContent').replace('<div id="mapContent"><object id="fmASEngine" width="800" height="352" base="." data="fmASMap/fmASContainer.swf?issue=' + issue_str + '&country=' + country_str + '" type="application/x-shockwave-flash"><param value="fmASMap/fmASContainer.swf?issue=' + issue_str + '&country=' + country_str + '" name="movie"/><param value="." name="BASE"/><param value="true" name="play"/><param value="#FFFFFF" name="bgcolor"/><param value="high" name="quality"/><param value="false" name="menu"/><param value="sameDomain" name="allowScriptAccess"/><param value="true" name="allowFullScreen"/><param value="transparent" name="wmode"/></object></div>');
}

function loadPage(url) {
	if (url != "") {
		location.href = url;
	}
}

function storeCountry(countryCode) {
	document.cookie = "countries=" + escape(countryCode);
}

function getCountry() {
	var ck = document.cookie.split('countries=')[1];
	if(ck) {
		return ck.slice(0,2);
	}
}
	
//this function is called from the flashmap Flash file when a country is clicked
function sendCountries(list_str) { 
	storeCountry(list_str.split(',').last());
	
}

function sendWorldView (value){
	storeCountry('xx');
}