var lAlreadyRated = 'You have already rated this page.  Thank You';

var address = document.location.href;
var home_link = address;
home_link = home_link.split('?');


//we need to define Lang

/*--[ SEARCH BOX ]-------------------------------------------------------------------
*  Use the following 3 functions if a search box is required in the template.
*  Ensure you give the search box an id='txtSearch' attribute
*  callAdvancedSearch is for the 'search' button.  This will send the search criteria
*    useage: <a href="#" id="submitSearch" >Search</a>
*  getChars will check the box each keypress to see if they pressed Enter, which
*       will transfer them to the search page.
*    useage: <input class="search_box" type="text" width="115" id="txtSearch" name="txtSearch">
*	You will need to change the url in callAdvancedSearch function.
*-----------------------------------------------------------------------------------*/
function callAdvancedSearch(lang) { 
	var criteria = document.getElementById('txtSearch').value;
	//var url ="/cwm/index" + lang + ".aspx?ArticleID=16923@criteria=" + criteria;
	if (lang=='_e') {
		glang='eng';
		domain='civilization';
	} else {
		glang='fra';
		domain='civilisations';
	}
	url='http://recherche.'+domain+'.ca/search?q='+criteria+'&btnG=Search&entqr=0&sort=date_3AD_3AL_3Ad1&output=xml_no_dtd&client=cmc_'+glang+'_frontend&ud=1&oe=iso-8859-1&ie=iso-8859-1&proxystylesheet=cmc_'+glang+'_frontend&hl=fr&proxyreload=1&site=All&filter=0';
	window.location=url;
	return false;
}
function getChars(e, lang) {     
	if (!e) var e = window.event;        //Internet Explorer Event
	//Grab the keycode for all browsers
	var characterCode=(e.charCode)?e.charCode: ((e.keyCode)?e.keyCode:((e.which)?e.which:0));
	if (characterCode == 13) {        //13=Enter button    
		//Cancel default form submission action
		e.cancelBubble = true;        
		e.returnValue = false;    
		
		if (e.which ) e.preventDefault();
		
		//Run the search
		callAdvancedSearch(lang);       		
	}
	return false;
}

/*---[ Language Link ]-------------------------------------------------------------
*  This is used if the language link is inside an image map.
*  Otherwise, use the default language link by the WCMS.
*  Useage: change_links() to the window.onload function on the main page
*---------------------------------------------------------------------------------*/
function change_links()
{
	var address = document.location.href;
	var home_link = address;
	home_link = home_link.split('?');

	var rExp = 'index_e';
	start = address.search(rExp);		//check to see if its on english page
	if (start==(-1)){					//english, change to french
		address = address.replace("index_f","index_e");	//replace f with e
	} else {
		address = address.replace("index_e","index_f");	//replace e with f
	}
	
	document.getElementById('switch_lang').href = address;	//change switch_lang to whatever id you need
	document.getElementById('home_link').href = home_link[0];

}

/*---[ Resize Text ]-------------------------------------------------------------
*  Will change the text size
*  Useage: <a href="#" onClick="resizeText(1)">Change Text Size</a>
*---------------------------------------------------------------------------------*/
function resizeText(multiplier) {
  if (document.getElementById('main').style.fontSize == "") {
    document.getElementById('main').style.fontSize = "0.8em";
  }
  if (document.getElementById('main').style.fontSize == '1em') {multiplier = (-1);}
  document.getElementById('main').style.fontSize = parseFloat(document.getElementById('main').style.fontSize) + (multiplier * 0.2) + "em";
}

/*---[ NEWSLETTER ]---------------------------------------------------------------*/
function newsletter_action(language){
	var news_div =  document.getElementById('newsletter');
	
	var newsletterID = document.getElementById('newsletterID').value;
	var lang = document.getElementById('lang').value;
	var email = document.getElementById('email').value;
	if (!validate_email(email)) {
		news_div.innerHTML = (language=='e') ? 'The email address provided is not in the right format' : "L'adresse du courriel soumis n'est pas dans le bon format." ;
		return false;
	}
		
	if (document.getElementById('sub').checked ) {
		action = 0;
	} else if (document.getElementById('unsub').checked ) {
		action = 1;
	} else 	{
		var alertstr = (language=='e') ? "You must chose either Subscribe or Unsubscribe to the newsletter" : "Vous devez choisir soit: Enregistrer ou Retirer du bulletin" ;
		alert(alertstr);
		return false;
	}
		
	news_div.innerHTML = (language=='e') ? '<img style="position:relative; top:10px;" align="center" src="/app/Newsletter/images/ajax.gif" alt="Processing..." />' : '<img style="position:relative; top:10px;" align="center" src="/app/Newsletter/images/ajax.gif" alt="Veuillez patienter..." />' ;
	
		var xmlHttp=null; 
		 try {
			// Firefox, Opera 8.0+, Safari, IE7+
			xmlHttp = new XMLHttpRequest(); // xmlHttp is now a XMLHttpRequest.
		 } catch (e) {
			// Internet Explorer
			try {
			   xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
			   xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
		 }
		 xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) 
		 { 
		  /* try { // In some instances, status cannot be retrieved and will produce 
				 // an error (e.g. Port is not responsive)
	*/		  if (xmlHttp.status == 200) {
				 // Set the main HTML of the body to the info provided by the 
				 // Ajax Request
				// alert(xmlHttp.responseText);
				 var response=xmlHttp.responseText.toString();
				news_div.innerHTML = response;
			  } else {
				  var errstr = (language=='e') ? 'There was an error submitting your information.  Please try again' : "Une erreur s'est produite durant la transmission de votre information.  Veuillez réessayer" ;
				  news_div.innerHTML = errstr;
			  }
		/*   } catch (e) {
			   var errstr2 = (language=='e') ? 'There was an error submitting your information(2).  Please try again' : "Une erreur s'est produite durant la transmission de votre information.  Veuillez réessayer" ;
				news_div.innerHTML = errstr2;
				return false;
		   }*/
		  }				
		 }	
		 
		var vars='newsid=' + newsletterID + '&email=' + encodeURIComponent(email) + '&action=' + action + '&lang=' + lang;
		xmlHttp.open("get","/newsletter/signup.aspx?"+vars); // .open(RequestType, Source);
		xmlHttp.send(null); // Since there is no supplied form, null takes its place 
							 // as a new form.
							 
		return false;
}

function validate_email(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) == false) {
		return false;
	} else {
		return true;
	}
}

/*---[ Rate This Page ]-------------------------------------------------------------
*  Used for the Rate this page module
*  Requires AJAX request
*---------------------------------------------------------------------------------*/
var rated = false;
function star_hover(number) {
  if (rated == true) {return false;}
	for (var i=1; i<=(number); i++) {
		var img='star_' + i;
		$(img).src='/app/TemplateRepository/commonImages/yellow_star.png';
	}
}

function remove_hover(number) {
  if (rated == true) {return false;}
	for (var i=1; i<=(number); i++) {
		var img='star_' + i;
		$(img).src='/app/TemplateRepository/commonImages/grey_star.png';
	}
}

function rate(number) {
  if (rated == true) {alert(lAlreadyRated); return false;}
	var page_id = 0;
	var url = "counter.aspx?mode=rate&page_id=" + page_id + "&rating=" + number;

	var req = new Request({url:url,
		onSuccess: function(txt) {
			$('stars').fade(0);
			var message = new Element('div', {id: 'rate_message'});
			message.innerHTML=txt;
			message.style.position="absolute";
			message.style.visibility="hidden";
			message.inject($('rate_page'), 'top');
			setTimeout("$('rate_message').style.visibility='visible';",300);
			setTimeout("$('stars').fade(1); $('rate_message').fade(0);",2500)
			rated = true;
		},
		//Our request will most likely succeed, but just in case, we'll add an
		//onFailure method which will let the user know what happened.
		onFailure: function() {
			$('stars').fade(0);
			var message = new Element('div', {id: 'rate_message'});
			message.innerHTML='Please try again';
			message.style.position="absolute";
			message.style.visibility="hidden";
			message.inject($('rate_page'), 'top');
			setTimeout("$('rate_message').style.visibility='visible';",300);
			setTimeout("$('stars').fade(1); $('rate_message').fade(0);",2500)
		}
	});
	req.send();
	
	return false;	
}

function print_page() {
	var url = "counter.aspx?mode=print&page_id=" + page_id;
	var req = new Request({url:url,
		onSuccess: function(txt) {
		}
	});
	req.send();
	
	return false;	
}


function gen_menu(){
 if(navigator.appVersion.indexOf("MSIE")==-1){return;}
 
 var i,k,g,lg,r=/\s*hover/,nn='',c,cs='hover',bv='mainMenu';
 
 for(i=0;i<10;i++) {
	g=document.getElementById(bv+nn);
	if(g){
		lg=g.getElementsByTagName("LI");
		if(lg) {
			for(k=0;k<lg.length;k++) {
				lg[k].onmouseover=function(){
					c = this.className;
					cl = (c)?c+' '+cs:cs;
					this.className=cl;
					};
				lg[k].onmouseout=function(){
					c = this.className;
					this.className=(c)?c.replace(r,''):'';
					};
			}
		}
	}
	nn=i+1;
  }
}

function scbkmrk_click() {
	setTimeout("$('social_bookmark').style.display='block'", 20);
	setTimeout("$('social_bookmark').fade(1)", 50);
	setTimeout("$('social_bookmark').fade(0)", 5000);
}

function scbkmrk_hide() {
	/*$('social_bookmark').style.display = 'none';
	$('social_bookmark').fade(0);*/
	setTimeout("$('social_bookmark').fade(0)", 5000);
}

function quickpick_click() {
	setTimeout("$('CalendarPop').style.display='block'", 20);
	setTimeout("$('CalendarPop').fade(1)", 50);
	return false;
	
}

function quickpick_hide() {
	if ($('CalendarPop')) {$('CalendarPop').fade(0); setTimeout('$("CalendarPop").style.display="none";',500); }
	return false;
}


 
/*********************************************
* QUICK PICK CALENDAR AJAX CODE
*********************************************/
function change_month(month,year,detail) {
	if ($('lang').value=='fr-CA'){					//english, change to french
		cmc_path='/mcc/calendrier/calendrier';		
	} else {
		cmc_path='/cmc/whats-on/whats-on';
	}

	
	/*detail = home_link[1].replace('#','');
	detail=detail.split('&');
	dump(detail);*/
	if (month) {
		var url = "/app/calendar/picker.aspx?" + "month="+month+"&year="+year+"&path="+cmc_path;
	} else {
		var url = "/app/calendar/picker.aspx?" +"path="+cmc_path;
	}
	$('dates').fade(0);
	var message = new Element('div', {id: 'loading_img'});
	message.innerHTML='<img src="/app/extTemplates/google/cmc/ajax.gif" />';
	message.style.position="absolute";
	message.style.visibility="hidden";
	message.inject($('CalendarPop'), 'top');

	var req = new Request({url:url,
		onSuccess: function(txt) {
			txt=txt.substr(txt.indexOf('<table'),txt.lastIndexOf('</table>'));
			$('dates').set('html',txt);
			$('dates').fade(1);
		},
		//Our request will most likely succeed, but just in case, we'll add an
		//onFailure method which will let the user know what happened.
		onFailure: function() {
		}
	});
	req.send();
	
	return false;	
}

var theid = '';
var thesubmit = '';
var emailspan = 'emailspan';

function emailtest() {
	var tag = document.getElementsByTagName('input');
	for (var i = 0 ; i < tag.length ; ++i) {
		if (tag[i].getAttribute("name") && tag[i].getAttribute("name").indexOf('email') > 0 && !theid.length) {
			theid = tag[i].getAttribute("id");
		} else if (tag[i].getAttribute("name") && tag[i].getAttribute("name").indexOf('btnSubmit') > 0 && !thesubmit.length) {
			thesubmit = tag[i].getAttribute("id");
		}
	}
	$(theid).setAttribute('onblur','testEmailAddr(this.value)');
	$(thesubmit).setAttribute('type','button');
	$(thesubmit).setAttribute('onclick','changeWarnMessage(\''+thesubmit+'\')');
}

function testEmailAddr(theemail) {
	var re = new RegExp('^[A-Za-z0-9](([_.+-]?[a-zA-Z0-9]+)*)@([a-zA-Z0-9]+)(([.-]?[a-zA-Z0-9]+)*).([A-Za-z]{2,4})$');
	if ( theemail.match(re) ) return true;
	return false;
}

function changeWarnMessage(thesubmit) {
	var emailok = testEmailAddr(document.getElementById(theid).value);
	if (emailok) {
		$(emailspan).innerHTML = '';
	} else {
		$(emailspan).innerHTML = 'invalid email.';
	}
}

function changeEmailMessage() {
	var emailok = testEmailAddr(document.getElementById(theid).value);
	//alert('About to submit, emailok is '+emailok);
	if (emailok) {
		document.__aspnetForm.submit();
	} else {
		$(emailspan).innerHTML = 'invalid email.';
	}
}
