$(document).ready(function () {
	$('a[rel="external"]').each(function(i) {
	    $(this).attr('target', '_blank');
    });
});

// theme right column style
$(document).ready(function () {
	if($("#theme_right h3").length > 0) {
		$("#theme_right h3").first().addClass("first");
	}	
});

$(document).ready(function(){

	var url = window.location.pathname;
	
	//alert("url is " + url);

	// go through the masthead links on the page and check if any of them are the same as the current page
	var themeLinks = $("a.theme-link");
	var re = /\/en\/themes\/\w+\//;
	var matched = url.match(re);

	if(matched) {
		for (var i = 0, j = themeLinks.length; i < j; i++) {
			var themeHref = $(themeLinks[i]).attr('href');
	
			if(themeHref.match(matched)) {
				$(themeLinks[i]).css("color", "#e3a82b");
				//$(themeLinks[i]).nextAll("a.arrow").first().addClass("active")
			}		
		}
	}
	
	// go through the masthead links on the page and check if any of them are the same as the current page
	var mastheadLinks = $("#masthead a");
	
	if(mastheadLinks.length > 0) {		
		for (var i = 0, j = mastheadLinks.length; i < j; i++) {
			var mastheadHref = $(mastheadLinks[i]).attr('href');
		
			if(url.match(mastheadHref)) {
				$(mastheadLinks[i]).css("color", "#e3a82b");
			}
			// special case for the Home link, when the browser URL is just the domain name followed by "/"
			var linktext = $(mastheadLinks[i]).text();
			if((url == "/") && (linktext == "Home")) {
				$(mastheadLinks[i]).css("color", "#e3a82b");
			}
			// special case for the DBC Data Catalogue page			
			if(url.match(/dbc\/search\/result.page/) && (linktext == "Data Catalogue")) {
				$(mastheadLinks[i]).css("color", "#e3a82b");
			}			
		}
	}		
});

/* Generic Cookie Code */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


function equalHeight(){

	//reset the heights for the elements 
	$('.equal').each(function(){
		$(this).height('100%');
	});
	$('.main-content').each(function(){
		$(this).height('100%');
	});

	//set the starting bigestHeight variable
	var biggestHeight = 0;
	//check each of them
	$('.equal').each(function(){
		//if the height of the current element is
		//bigger then the current biggestHeight value
		if($(this).height() > biggestHeight){
			//update the biggestHeight with the
			//height of the current elements
			biggestHeight = $(this).height();
		}
	});
	$('.main-content').each(function(){
		//if the height of the current element is
		//bigger then the current biggestHeight value
		if($(this).height() > biggestHeight){
			//update the biggestHeight with the
			//height of the current elements
			biggestHeight = $(this).height();
		}
	});	
	
	//when checking for biggestHeight is done set that
	//height to all the elements	
	$('.equal').height(biggestHeight);
	$('.main-content').height(biggestHeight);
}

/* Image Rollover (for the RSS feed image) */
if (document.images) {
	b_rsson = new Image(); // Active images
	b_rsson.src = "/shared/images/b_rss_over.gif";
	b_rssoff = new Image(); // Inactive images
	b_rssoff.src = "/shared/images/b_rss.gif";
}

function imgOn(imgName) {
	if (document.images) {
		document[imgName].src = eval(imgName + "on.src");
	}
}

function imgOff(imgName) {
	if (document.images) {
		document[imgName].src = eval(imgName + "off.src");
	}
}


//Create global references
var printWindow = null;
var blIsOpen = false;
var opener;
var objPrint;

function getHeader(){
	var header;
	//BC logo plus print buttons
	header = "<div id=\"header\">";
	header += "<a href=\"/\"><img id=\"logo\" src=\"/shared/images/logo_bcgov.gif\" width=\"163\" height=\"58\" alt=\"British Columbia - The Best Place on Earth\"></a>";
	header += getPrintButtons() ;
	header += "</div>";
	return header;
}

function getTopBanner() {
	if (document.getElementById("image-header")) {
		return "<div id=\"image-header\">"+document.getElementById("image-header").innerHTML+"</div>";
	}
	else {
		return "";
	}
}

function hasAncestorOfClass(node, classname)
{
	var temp = node;
	while (temp.parentNode) {
		temp = temp.parentNode;
		if (temp.className == classname)
 {
			return true;
		}
	}
	return false;
}

function getElementsOfClass(classname, node)
{
	if(!node) 
		node = document.getElementsByTagName("body")[0];
	var result = [];
	var regexp = new RegExp('\\b' + classname + '\\b');
	var elements = node.getElementsByTagName("*");
	for(var i=0,j=elements.length; i<j; i++)
	//	if((regexp.test(elements[i].className)) && (!hasAncestorOfClass(elements[i], classname)))
		if((regexp.test(elements[i].className)) )
			result.push(elements[i]);
	return result;
}

function getMainCol()
{
	var components = getElementsOfClass("iw_component");

	var pattern = new RegExp(
		'((<form [^>]*class="?iw-form-builder-toolbox"?)|(<div [^>]*class="?(main-content|overview-content|list-content)"?))');
	
	/*
	var pattern = new RegExp(
		'((<form [^>]*class="?iw-form-builder-toolbox"?)|(<div [^>]*class="?(main-content|overview-content|list-content)"?)(<button))');
	*/
	var i = 0;
	//var content = "<div id=\"content\">";
	var content = "";
	var com;
	while (components[i]) {
		com = components[i];
		var testpattern = com.innerHTML.toLowerCase();
		if (pattern.test(testpattern) || testpattern.indexOf("<button ")!= -1)
			content = content + "<div>" + com.innerHTML + "</div>";
		++i;
	
	}
	//content = content + "</div>";
	return content;
}

function getFreeFormTop(){
	if (document.getElementById("right-col")) {
		return "<div id=\"freeFormTop\">"+document.getElementById("right-col").innerHTML+"</div>";
	}
	else {
		return "";
	}
}

function getFreeFormBottom(){
	if (document.getElementById("freeFormBottom")) {
		return "<div id=\"freeFormBottom\">"+document.getElementById("freeFormBottom").innerHTML+"</div>";
	}
	else {
		return "";
	}
}


function getPrintButtons(){
	var strFooter;
	strFooter = "<div class=\"print-buttons\">" +
			"<a href=\"javascript:print(); window.self.close();\">" + 
			"<img src=\"/shared/images/b_print-close.gif\" width=\"108\" height=\"28\" " +
			" alt=\"Print and close\"></a>&nbsp;&nbsp;&nbsp;" +
			"<a href=\"javascript:window.self.close();\">" + 
			"<img src=\"/shared/images/b_cancel.gif\" width=\"108\" height=\"28\" alt=\"Cancel\"></a>" +
			"</div>";
	return strFooter;
}

function doPrint(objWindow){
	if (blPrintWindowOpen()){
		printWindow.focus();//make the preview window bubble to surface
	}else{
	objPrint = new objPrintObject();
	blIsOpen = true;
	
	opener = objWindow;
	printWindow = window.open("", "PrintVersion", 'left=100,screenX=200,top=50,screeny=100,resizable=yes,toolbar=yes,menubar=yes,width=760,height=500,modal=yes,scrollbars=yes,status=yes');
	printWindow.document.bgColor="white";
	printWindow.document.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n");
	var reloadFlag=false;
	var title = document.title;
	printWindow.document.write("<html><head>\n");
	if(title == ""){
		printWindow.document.write("<title>Province of British Columbia (Printer Version)</title>\n");
	}else{
		printWindow.document.write("<title>"+title+" (Printer Version)</title>\n");
	}
	printWindow.document.write("<style type=\"text/css\" media=\"all\">\n" + 
		"@import \"/shared/css/main.css\"; \n" +
		"@import \"/shared/css/fonts.css\"; \n"+
		"@import \"/shared/css/media_gallery.css\"; \n" +
		"@import \"/shared/css/print.css\"; \n" +			// This is the name of the print style sheet for the ministry pop-up printer version windows. It must replace the previously used "print.css" entirely, since the styles conflict with each other.
		"@import \"/shared/css/visual-styles.css\"; \n" +
		"</style>\n");
		
	if (objPrint.mainCol.indexOf("IwFormBuilderToolbox") != -1) {
		reloadFlag = true;
		printWindow.document.write('<SCRIPT src="/shared/scripts/form-builder-pv.js" type="text/javascript"></SCRIPT>\n<SCRIPT src="/shared/scripts/AjaxRequest.class.js" type="text/javascript"></SCRIPT>\n');
	}
	printWindow.document.write("</head>\n");

	printWindow.document.write("<body class=\"one-column\">\n");
	printWindow.document.write("<div id=\"wrapper\"><a name=\"top\"></a>\n");
	printWindow.document.write(objPrint.header);
	//printWindow.document.write(objPrint.imageHeader);
	printWindow.document.write("<div id=\"content\">\n");
	printWindow.document.write(objPrint.freeFormTop);
	printWindow.document.write(objPrint.mainCol+objPrint.freeFormBottom+"</div><div id=\"footer\">" + objPrint.printButtons + "</div></div></body></html>");

	var browser=navigator.appName;
	if (browser=="Microsoft Internet Explorer" ){
		printWindow.location.reload(false);
	}
	printWindow.document.close();
	}
}

function objPrintObject(){
	this.header = getHeader();
	this.imageHeader = getTopBanner();
	this.mainCol = getMainCol();
	this.freeFormTop = getFreeFormTop();
	this.freeFormBottom = getFreeFormBottom();
	this.printButtons = getPrintButtons();
	this.ParentWindow = window;
}

function blPrintWindowOpen(){
	if ((printWindow != null) && (blIsOpen == true)){
		return (! printWindow.closed);
	}else{
		blIsOpen = false;
		return false;
	}
}

function closeWindow(){
	if((printWindow != null) && (blIsOpen == true)){
		printWindow.close();
		printWindow=null;
		blIsOpen = false;
		return true;
	}
	return false;
}

function HideDIV(d) { document.getElementById(d).style.display = "none"; }
function DisplayDIV(d) { document.getElementById(d).style.display = "block"; }  


/* Generic search behaviour */
$(document).ready(function() {

	/* if search field is empty, add the default background for it */
	if($("#search_box input").val() == '') {								   	
		$("#search_box input").css("background", "url(/common/images/saquery/bg_generic_defaulttext.gif) 0 50% no-repeat");
	}
  	
	/* when user clicks in input field */
	$("#search_box input").focus(function() {
    	$(this).css("background", "none");
    
		/* when user clicks out of input field */
		$(this).blur(function() {
			if(this.value == "")					  
			$("#search_box input").css("background", "url(/common/images/saquery/bg_generic_defaulttext.gif) 0 50% no-repeat");
		});		
	});

	/* check for empty search */
	$("#form form").submit(function() {
		if($("#search_box input").val() == '') {								   
			alert("Please enter one or more search terms and click the 'Search' button to view the results.");
			return false;
		}
	});	
});

//function to disable the "Search for more services and forms" widget link in IE9 only
$(document).ready(function () {
	if($("#searchmore").length > 0) {	
		var ie = getInternetExplorerVersion();
		if(ie == 9.0) {
			$("#searchmore").attr('href', 'http://www2.gov.bc.ca/en/services_finder/finder.page');
			$("#searchmore").removeAttr('onclick');
		}			
		//if(ie == -1) {
		//	alert("this is non-IE browser")
		//}
	}	
});

function getInternetExplorerVersion() {
// Returns the version of Internet Explorer or a -1 (indicating the use of another browser).
var rv = -1; // Return value assumes failure.

if (navigator.appName == 'Microsoft Internet Explorer') {
	var ua = navigator.userAgent;
	var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
	if (re.exec(ua) != null)
		rv = parseFloat( RegExp.$1 );
	}
	return rv;
}


