/********************
 *
 *	PUBLIC.JS
 *	Javascript for public webpages
 * 
********************/

IsMSIE = navigator.appVersion.indexOf('MSIE') != -1;






/////////////////////////////////////////////////////////
// GENERAL AJAX FUNCTIONS
/////////////////////////////////////////////////////////

// CREATES AJAX CONNECTION
// VOID()
function AJAX_initConn() {
	
	// Open IE connection
	if (IsMSIE)
		AJAXHTTPObj = new ActiveXObject("Microsoft.XMLHttp");
	
	// Open connection for any other browser
	else
		AJAXHTTPObj = new XMLHttpRequest;
	
	// Return object
	return AJAXHTTPObj;
}

AJAX_initConn();


// SENDS A GET REQUEST
// (STRING url, BOOL use GET/POST [0 = POST, 1 = GET], OBJ ajax http object [leave blank to use default])
function AJAX_sendRequest(UseGET, url, EvalCodeFromResponse, EvalCodeAfterOpen, GETVarStrForPostSubmit, Alt_AJAXHTTPObj) {
	
	// Which HTTP obj to use?
	UseAJAXHTTPObj = (Alt_AJAXHTTPObj)?Alt_AJAXHTTPObj:AJAXHTTPObj;

	// Generate URL
	if (url.indexOf('?') == 0)
		url = getScriptName() + url;
	
	// Make sure AJAX conn. obj is set
	if (typeof UseAJAXHTTPObj != "undefined") {
		
		// Sending POST request - split the URL
		if (!UseGET) {
			url_array = url.split('?');
			url       = url_array[0] + ((GETVarStrForPostSubmit)?'?' + GETVarStrForPostSubmit:'');
			QueryStr  = url_array[1];
		}
		else
			QueryStr = null;
		
		// Open GET connection and send NULL to start server-side processing...
		UseAJAXHTTPObj.open((UseGET)?'GET':'POST', url, true);
		
		if (EvalCodeAfterOpen)
			eval(EvalCodeAfterOpen);
		
		if (!UseGET)
			AJAXHTTPObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		
		UseAJAXHTTPObj.send(QueryStr);
		
		// On state change, check for ready state and return response text (if any)
		UseAJAXHTTPObj.onreadystatechange = function() {
			if (UseAJAXHTTPObj.readyState == 4) {
				response = UseAJAXHTTPObj.responseText;
				if (EvalCodeFromResponse != null)
					eval(EvalCodeFromResponse);
				else
					return response;
	
				return;
			}	
		}
	}
}


// Gets the name of script/page from a url
function getScriptName(OverrideURL, IncludeQueryStr) {
	UseURL         = (OverrideURL)?OverrideURL:document.location.href;
	UseURL         = UseURL.replace(/#.*/, '');
	QueryStrExists = UseURL.indexOf('?') != -1;
	
	QueryStr = '';

	if (QueryStrExists) {
		QueryStr = UseURL.substr(UseURL.indexOf('?'));
		UseURL   = UseURL.substr(0, UseURL.indexOf('?'));
	}
		
	if (!QueryStrExists || IncludeQueryStr)
		return UseURL.substr(UseURL.lastIndexOf('/')+1) + QueryStr;	
	
	else if (QueryStrExists)
		return UseURL.substr(UseURL.lastIndexOf('/')+1);
}



// GETS A SPECIFIED GET VARIABLE FROM A GIVEN OR CURRENT URL
function fetchGETVar(GETVar, OverrideURL) {
	
	// Figure out what URL to use and then parse out the unnecessary parts
	UseURL = (OverrideURL)?OverrideURL:document.location.href;
	if (UseURL.indexOf('?') != -1 && UseURL.indexOf(GETVar) != -1) {
		URLArray      = UseURL.split('?');
		QueryStrArray = URLArray[1].split('&');
		
		// Set array of get vars
		GETVarArray = new Array(QueryStrArray.length);
		
		// Set the array values
		for (i in QueryStrArray) {
			CurrentVarSplit = QueryStrArray[i].split('=');
			CurrentVarName  = CurrentVarSplit[0];
			CurrentVarValue = CurrentVarSplit[1];
			eval('GETVarArray[\'' + CurrentVarName + '\'] = CurrentVarValue;');
		}
		
		if (GETVar)
			return GETVarArray[GETVar];
	}
	else
		return null;
}








/////////////////////////////////////////////////////////
// GENERAL PUBLIC FUNCTIONS
///////////////////////////////////////////////////////// 



// Opens preview image
/*
function openImgPreview(ImgURL, ImageW, ImageH) {
	WinDoc = window.open('', 'ImgPreviewWin', 'width=' + (ImageW + 50) + ',height=' + (ImageH + 75) + ',scrollbars,status');
	
	with (WinDoc.document) {
		open();
		write('<html><head><title>Enlarged Image</title></head>');
		write('<body onLoad="window.focus()" onClick="window.close()">');
		write('<center><img src="' + ImgURL + '" style="margin-bottom: 25px; display: block">');
		write('<font face="Arial" size=1>(click anywhere to close window)</font></center>');
		write('</body></html>');
		close();
	}
}
*/


// Generates email address safe from harvesters
function generateAntiSpiderEmail(Username, DomainName, TLD, OutputText, NoLink) {
	EmailAddress = Username + "&#64;" + DomainName + "&#46;" + TLD;
	OutputText   = ((OutputText)?OutputText:EmailAddress);
	
	document.write((NoLink)?OutputText:"<a href=\"ma" + "il" + "to:" + EmailAddress + "\">" + OutputText + "</a>");
}

// Toggles the css 'display' property between 'none' and 'block'
function toggleCSSdisplay(Obj) {
	CurrentDisplay = Obj.style.display;
	Obj.style.display = (CurrentDisplay == 'none' || CurrentDisplay == '')?'block':'none';		
}


// ASSIGNS A JAVASCRIPT EVENT TO A SPECIFIED OBJECT ACCORDING TO THE BROWSER
function setEvent(Obj, Event, Action) {
	
	// For IE, use attachEvent
	if (IsMSIE) {
		eval("Obj.attachEvent('" + Event.toLowerCase() + "', function() { " + Action + " });");
	}
	
	// For proper browsers, simply use setAttribute
	else
		Obj.setAttribute(Event, Action);
}


// Function to create image overlay
function enlargeImg(ImgSrc, ImgLabel, ImgIndex, Surfing) {
	
	with (document) {
		NewContainerDiv	= createElement('div');
		NewLinksDiv	= createElement('div');
		NewDisableDiv	= createElement('div');
		NewImg		= createElement('img');
		NewXImg		= createElement('img');
	}
	
	with (NewImg) {
		src		= ImgSrc;
		style.cursor	= 'pointer';
		style.display	= 'block';
	
		TmpLabel = ImgLabel + ' [click to close]';		
		setAttribute('alt', TmpLabel);
		setAttribute('title', TmpLabel);
		setAttribute('id', 'MainImg');
	}
	
	with (NewXImg) {
		src = 'images/x.gif';
		
		style.position	= 'absolute';
		style.margin	= '-30px 0px 0px ' + ((IsMSIE)?NewImg.width:NewImg.width) + 'px';
		style.cursor	= 'pointer';
		
		setAttribute('width', '30');
		setAttribute('height', '35');
		setAttribute('alt', 'close');
		setAttribute('title', 'close');
		setAttribute('id', 'XImg');
	}
	
	setEvent(NewImg, 'onClick', 'closeMainImg()');
	setEvent(NewXImg, 'onClick', 'closeMainImg()');
	
	if (NewImg.width == 0) {
		setTimeout('enlargeImg("' + ImgSrc + '", "' + ImgLabel + '", "' + ImgIndex + '", "' + Surfing + '")', 500);
		return;
	}
	
	
	setLeft = (Math.round(document.body.clientWidth / 2)*1)/1 - ((NewImg.width + 10) / 2);
	setLeft = (String(setLeft).lastIndexOf('.') != '-1')
		  ?String(setLeft).substr(0, String(setLeft).lastIndexOf('.')):String(setLeft) + 'px';
	
	setTop = String(document.body.scrollTop + 35) + 'px';
	
	with (NewContainerDiv) {
		setAttribute('id', 'MainImgContainer');
		
		style.position	= 'absolute';
		style.top	= setTop;
		style.left	= setLeft;
		style.zIndex	= '2';
		style.background= '#FFFFFF';
		style.padding	= '15px';
		style.marginBottom = '15px';
	}
	
	with (NewDisableDiv.style) {
		top        = '0px';
		left       = '0px';
		width      = '100%';
		position   = 'absolute';
		height     = String(document.body.scrollHeight) + 'px';
		zIndex     = '1';
		
		if (IsMSIE) {
			//toggleSelectMenuVisibility(true, 'hidden');
			filter = 'alpha(opacity=75)';
		}
		else {
			setProperty('-moz-opacity', '.75', ''); 
			setProperty('opacity', '.75', '');			
		}			
	}
	
	NewDisableDiv.setAttribute('id', 'DisableDiv');
	
	// Links
	with (NewLinksDiv) {
		
		setAttribute('id', 'LinksDiv');
	
		innerHTML
		= '<table border=0 cellpadding=0 cellspacing=0 align="center" style="margin-top: 10px" width="' + NewImg.width + 'px">'
		+ '<tr>'
		
		+ '<td><a href="javascript: getPrevNext(0, ' + ImgIndex + ')" title="Show Previous Photo" id="PrevPhotoLink"'
		+ 'style="font-family: \'Arial\'; font-size: 14; font-weight: bold">&lt; PREVIOUS</a></td>'
		
		+ '<td align="right"><a href="javascript: getPrevNext(1, ' + ImgIndex + ')" title="Show Next Photo" id="NextPhotoLink"' 
		+ 'style="font-family: \'Arial\'; font-size: 14; font-weight: bold">NEXT &gt;</a></td>'
		
		+ '</tr>';
		+ '</table>';
	}
	
	with (document.body) {
		if (!Surfing || Surfing == undefined || Surfing == 'undefined')
			appendChild(NewDisableDiv);
		
		appendChild(NewContainerDiv);
	}
	
	NewContainerDiv.appendChild(NewXImg);
	NewContainerDiv.appendChild(NewImg);
	
	if (MoreThanOneImage)
		NewContainerDiv.appendChild(NewLinksDiv);
}


// Get previous or next image
function getPrevNext(Direction, CurrentImgIndex) {	
	AJAX_sendRequest(true,
	
	'?WebPageID=' + fetchGETVar('WebPageID') + '&GetPrevNext=' + CurrentImgIndex + '&Direction=' + Direction,
	
	"if (response.substr(0,7) == 'OUTPUT:') { setPrevNext(response); } else { alert('Error fetching image: ' + response); }");
}


// Set prev/next image according to AJAX response
function setPrevNext(output) {
	closeMainImg(true);
	
	ImgData = output.substr(7).split('|');
	enlargeImg(ImgData[0], ImgData[1], ImgData[2], true);
}


// Function to close overlay
function closeMainImg(Surfing) {
	with (NewContainerDiv) {
		removeChild(document.getElementById('MainImg'));
		removeChild(document.getElementById('XImg'));
		
		if (MoreThanOneImage)
			removeChild(document.getElementById('LinksDiv'));
	}
	
	with (document.body) {
		if (!Surfing)
			removeChild(document.getElementById('DisableDiv'));
		
		removeChild(document.getElementById('MainImgContainer'));
	}
}

// opacity() and changeOpac() functions from http://brainerror.net/scripts/javascript/blendtrans/
function opacity(id, opacStart, opacEnd, millisec) {
    
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
        
        setTimeout("document.getElementById('" + id + "').style.display = 'none'", FadeTime + 1);
        
    } else if(opacStart < opacEnd) {
    
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
        
        document.getElementById(id).style.display = 'block';
    }
}

// change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}