// For the contribute form
function toggle(thing){
	var t = document.getElementById(thing);
	t.style.display = (t.style.display == 'none' ? 'block' : 'none');
};

function changeInput(type){
	var label = document.getElementById('contribution_content_label');
	var textarea = document.getElementById('contribution_content');
	
	if(type == 'full'){
		label.innerHTML = 'Your content <span>(required)</span>';
		textarea.className = 'full';
	} else {
		label.innerHTML = 'Additional Information';
		textarea.className = 'upload';			
	}
}

function processPage(){
	var upload = document.getElementById("upload");
	var typer = document.getElementById("type");
	
	upload.onclick = function(){
		changeInput('file'); 
		document.getElementById('upload_form').style.display = 'block'; 
		document.getElementById('content_creation').style.display = 'block';
	};
	
	typer.onclick = function(param){
		changeInput('full');
	 	document.getElementById('upload_form').style.display = 'none';
		document.getElementById('content_creation').style.display = 'block';
		if(param != 'skip'){
			document.getElementById('contribution_content').focus();
		}
	};
	
	if(upload.checked){upload.onclick();}
	if(typer.checked){typer.onclick('skip');}
};

// Put icon next to external links
function externalLinks(){
    var c=document.getElementById('container');
		var b=document.getElementsByTagName('body')[0].id;
    if(c && b != 'section-4')
    {
        var ls=c.getElementsByTagName('a');
        for(var i=0;i<ls.length;i++){
						var lnk = ls[i].getAttribute('href');
						var rx = new RegExp(/^http:\/\//);
						var rx2 = new RegExp(/^http:\/\/cap2020/);
            if(rx.test(lnk) && !rx2.test(lnk))
            {
                ls[i].className+=ls[i].className?' extlink':'extlink';
                ls[i].title+=' (external link opens in a new window)';
                ls[i].onclick=function(){window.open(this.href);return false;};
            }
        };
    }
};

// Print this page link
function printPage(){
	var header = document.getElementById('header');
	if(header && window.print){
		var link = document.createElement('a');
		link.id = 'print_page';
		link.href = "#";
		link.innerHTML = 'Print this page';
		link.onclick = function(){window.print(); return false;};
		header.appendChild(link);
	}
};

function forwardPage(){
	var header = $('header');
	if(header){
		header.insert('<a href="#" id="forward_page">Forward this page</a>');
		$('forward_page').observe('click', function(){
			Lightbox.showBoxByAJAX('/m/forward_page', 700, 800);
			return false;
		});
	}
};

// Dropdown on homepage
function mapSelect(){
	var sel = document.getElementById('state');
	if(sel){
		sel.onchange = function(){
			if(this.value != ''){ 
				window.location = this.value;
			}
		};
	}
};

// Clickable form labels safari 2
function formLabelsSafari(){
	if (navigator.userAgent.indexOf("Safari") > 0){
		
		isSafari3 = false;
		if(window.devicePixelRatio) isSafari3 = true;
		
		if(!isSafari3){
		  var labels = document.getElementsByTagName("label");
			if(labels){
			  for (i = 0; i < labels.length; i++){
			    labels[i].addEventListener("click", addLabelFocus, false);
			  };			
			}			
		}
	}
	
	function addLabelFocus(){
	  var item = document.getElementById(this.getAttribute("for"));
	  item.focus();
	  if (item.getAttribute("type") == "checkbox"){
	    if (!item["checked"]){
	      item["checked"] = true;
	    } else {
	    	item["checked"] = false;
	    }
	  } else if (item.getAttribute("type") == "radio"){
			item.onclick();
	    var allRadios = document.getElementsByTagName("input");
	    var radios = new Array();
	    for (i = 0; i < allRadios.length; i++){
	      if (allRadios[i].getAttribute("name") == item.getAttribute("name")){
	        radios.push(allRadios[i]);
	      }
	    };
	    for (i = 0; i < radios.length; i++){
	      if (radios[i]["checked"] && radios[i].getAttribute("id") != item.getAttribute("id")){
	        radios[i]["checked"] = false;					
	      }
	    };
	    item["checked"] = true;
	  }
	};
};

// Encoded email address
function em(where,subject,classes,id,link_only,domain){
	var subject = subject.replace(/ /g, '%20');
	var domain = (domain ? domain : 'ieep');
	var link =  where + "@" + domain + "." + "eu";
	if(link_only){
		return "mailto:" + link;
	} else {
		document.write("<a class=" + classes +" id=" + id + " hre" + "f=ma" + "ilto:" + link + "?subject=" + subject + ">" + link + "</a>"); 	
	}
};

// On Events page for toggling information about submissions
function suggestionToggler(){
	var suggest = $('suggest');

	if(suggest){		
		suggest.hide();
		$('suggest_on').hide();
		
		// Insert the off state adding the proper email address link (instead of image) and close link
		suggest.insert({bottom: '<div id="suggest_off"><p>Have an event you\'d like<br />to add to the diary?</p><a id="suggest_link_on" href=""><img src="/images/button_suggest.png" width="156" height="23" alt="Suggest an event" /></a></div>'});		
		$('suggest_on').insert({bottom: '<a href="" id="close">Close</a>'});
		$('email_to').replace('To: <a href="mailto:cap2020@ieep.eu?subject=Policy Diary event suggestion">cap2020.ieep.eu</a>');
		
		// After all insertion is done, show everything.
		suggest.show();
		
		Event.observe('suggest_link_on', 'click', function(e){
			$('suggest_on').show();
			$('suggest_off').hide();			
			Event.stop(e)
		});
		
		Event.observe('close', 'click', function(e){
			$('suggest_on').hide();
			$('suggest_off').show();
			Event.stop(e);			
		});
	}
};

function toggleSize(id){
	var myobj = document.getElementById(id);	
	if(myobj){
		log.info(myobj.style.height);
		myobj.style.height = (myobj.style.height == '75px' ? 'auto' : '75px');
		
	}
};

function haveYourSayIntro(){
	var link = document.getElementById('read_topic_description');
	var desc = document.getElementById('topic_description');
	if(link && desc){
		link.onclick = function(){
			toggleSize('topic_description');
			return false;
		};
	}
};

function setupSubscribeForm(){
	var subscribe = $('subscribe');
	
	if(subscribe){
		
		var hash = getUrlVars();
		if(hash['EMAIL'] == ''){
			$('subscribe_form').show();
			validate('email');
		} else {
			$('subscribe_form').hide(); 			
		}
		
		$('subscribe_form').onsubmit = function(){
			validate('email');
			return false;
		};
		
		$('subscribe_link').replace('<a id="subscribe_link" href="#">Subscribe to receive email updates</a>');
		$('subscribe_link').onclick = function(){
			$('subscribe_form').toggle(); 
			resetForm(); 
			return false;
		};
		
		
		$('subscribe_submit').insert('<span>or <a id="cancel_link" href="#">Cancel</a></span>');
		$('cancel_link').onclick = function(){
			$('subscribe_form').toggle(); 			
			return false;
		};
				
	}

	function validate(field){
		if($('email').value == ''){
			$('email_error').toggle();
			$('email_address').className = 'error';
			return false;
		} else {
			$('subscribe_form').submit();
		}
	};
	
	function resetForm(){
		$('subscribe_form').reset();
		$('email_address').className = '';
		$('email_error').hide();
	}	
};

function getUrlVars(){
    var vars = [], hash;
    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;
};

Element.observe(document, 'dom:loaded', function(){
	setupSubscribeForm();
	haveYourSayIntro();
	mapSelect();
	externalLinks();
	printPage();
	forwardPage();
	formLabelsSafari();
	// suggestionToggler();
});