/**
	\file	portfolio.js
	\note	Javascript & Ajax library for portfolio pages
**/

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function getHTTPObject() {
	// Create XMLHttpRequest object.
	// Includes testing for browser support
	var xhrObj = false;
	if ( window.XMLHttpRequest ) {
		// this is a modern, standards-compliant browser
		xhrObj = new XMLHttpRequest();
	} else if ( window.ActiveXObject ) {
		// it's smelly old IE
		try {
			// newer versions of IE
			xhrObj = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			// that didn't work, so try version for older IEs
			try {
				xhrObj = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				// that still didn't work, so give up
				xhrObj = false;
			}
		}
	}
	return xhrObj;
}

function changeImg ( imgFile, subDir, imgWidth, imgHeight,
		borderWidth, keylineWidth, protectImages,
		captionText, permalinkHTML, admineditHTML, alamyref, rbref ) {

	if(!document.getElementById) return false;

	if ( captionText ) {
		altText = captionText.replace('/\"/', "'");
	} else {
		altText = 'Copyright &copy; ' + cfg['copyright'];
	}
	// need to determine what it is we're changing
	if ( protectImages == 'Y' ) {

		var frameDiv = document.getElementById("img_frame");
		frameDiv.setAttribute("style",
			'width:' + imgWidth + 'px;'
			+ 'height:' + imgHeight + 'px;'
			+ 'padding:' + borderWidth + 'px;'
			+ 'border-width:' + keylineWidth + 'px;'
			);

		var imgBg = document.getElementById("image_bg");
		imgBg.setAttribute("width", imgWidth);
		imgBg.setAttribute("height", imgHeight);

		var imgDiv = document.getElementById("protected_image");
		var imgURL = cfg['site_url'] + '/' + cfg['portfolio_subdir']
			+ '/' + subDir + '/' + imgFile;
		//imgDiv.style.background = 'background-image: url('
		//	+ imgURL + ') center center no-repeat';
		imgDiv.setAttribute("style", 'background: transparent url('
			+ imgURL + ') center center no-repeat;'
			+ 'margin:0;padding:0;');

	} else {

		var imgId = document.getElementById("display_image");
		imgId.setAttribute("src", subDir + '/' + imgFile);
		imgId.setAttribute("width", imgWidth);
		imgId.setAttribute("height", imgHeight);
		imgId.setAttribute("alt", altText);
		imgId.setAttribute("style", 'padding:' + borderWidth + 'px;'
			+ 'border-width:' + keylineWidth + 'px;' );

	}

	// CHANGE CAPTION
	var captionDiv = document.getElementById("img_caption");
	captionDiv.setAttribute("style", 'width:' + imgWidth + 'px;');
	var captionPar = document.getElementById("caption_text");
	captionPar.innerHTML = captionText;
	if ( cfg['show_permalinks'] == 'Y' ) {
		var permalinkPar = document.getElementById("permalink_image");
		permalinkPar.innerHTML = permalinkHTML;
	}

	// CHANGE ADMIN 'EDIT CAPTION' LINK
	// This is a sample of what we're trying to change
	//<p id="admin_options">[ <span class="admin_link"><a href="/portfolio/index.php?pagemode=edit_caption&amp;section=editorial&amp;project=aviation&amp;img=08.jpg">add/edit caption &amp; metadata</a></span> ]</p>
	var editLinkPar = document.getElementById("admin_options");
	editLinkPar.innerHTML = admineditHTML;
	
	// Alamy & RedBubble
	var AlamyPar = document.getElementById("alamyLink");
	if ( alamyref && ( alamyref != 0 ) ) {
		AlamyPar.innerHTML = '<a href="http://www.alamy.com/stock-photography-search-results.asp?qt=' + alamyref
			+ '" title="Licence stock image via Alamy" target="_blank">'
			+ 'Licence this stock photo via Alamy'
			+ '</a>';
	} else {
		AlamyPar.innerHTML = ' '; 
	}
	var RBPar = document.getElementById("RedBubbleLink");
	if ( rbref && rbref != 0 ) {
		RBPar.innerHTML = '<a href="http://www.redbubble.com/people/webvivant/art/'
			+ rbref + '" title="Buy print, poster or card at RedBubble" target="_blank">'
			+ 'Buy a print, card or poster of this image at RedBubble'
			+ '</a>';
	} else {
		RBPar.innerHTML = ' '; 
	}
	

}

function getImageDetails ( imgFile, subDir ) {
	if ( !document.getElementById ) { return false };
	if ( !document.getElementsByTagName ) { return false };
	var xhr = getHTTPObject();
	var xml = false;
	if ( xhr ) {
		if ( cfg['protect_images'] == 'Y' ) {
			var imgId = document.getElementById("display_image");
			imgId.setAttribute("src", 'graphics/screen_image.gif' );
			var captionPar = document.getElementById("caption_text");
			captionPar.innerHTML = '<img src="/graphics/icon_spinning_wait_sml_black.gif" alt="please wait..." />&nbsp;loading image...';
		} else {
			var imgId = document.getElementById("display_image");
			imgId.setAttribute("src", 'graphics/screen_image.gif' );
			imgId.setAttribute("style", 'background: url(/graphics/icon_spinning_wait_sml_black.gif) center center no-repeat;' );
		}

		xhr.onreadystatechange = function() {

			xml = getXMLresponse ( xhr );
			if ( xml ) {
				if ( xml.getElementsByTagName("errorcode")[0] ) {
					var captionPar = document.getElementById("caption_text");
					captionPar.innerHTML = '<span class="warning">'
						+ xml.getElementsByTagName("errormsg")[0].firstChild.nodeValue
						+ '</span>';
				} else {
					// XML was okay, let's display the image
					var width = xml.getElementsByTagName("imgWidth")[0].firstChild.nodeValue;
					var height = xml.getElementsByTagName("imgHeight")[0].firstChild.nodeValue;
					var caption = xml.getElementsByTagName("caption")[0].firstChild.nodeValue;
					var permalink = xml.getElementsByTagName("permalinkImgHTML")[0].firstChild.nodeValue;
					var editlink = xml.getElementsByTagName("captionEditLink")[0].firstChild.nodeValue;
					var alamyRef = xml.getElementsByTagName("alamyref")[0].firstChild.nodeValue;
					var RedBubbleRef = xml.getElementsByTagName("rbref")[0].firstChild.nodeValue;
					changeImg ( imgFile, subDir, width, height,
						cfg['border_width'], cfg['keyline_width'], cfg['protect_images'], caption, permalink, editlink, alamyRef, RedBubbleRef );
				}
			}
		};
//alert ( cfg['site_url'] + '/pAjaxSvr/imgdata/' + cfg['portfolio_subdir'] + '/' + imgFile + '/' + subDir );
		xhr.open ("GET", cfg['site_url'] + '/pAjaxSvr/imgdata/'
			+ cfg['portfolio_subdir'] + '/' + imgFile + '/' + subDir, true);
//		xhr.open ("GET", cfg['site_url'] + '/portfolioAjaxSvr.php?pm=imgdata'
//			+ '&pdir=' + cfg['portfolio_subdir']
//			+ '&img=' + imgFile + '&dir=' + subDir, true);
		xhr.send(null);

	} else {
		return false;
	}
}

function getXMLresponse ( xhrObj ) {
	var xmlResponse = false;
	if ( xhrObj.readyState == 4 ) {
		if ( xhrObj.status == 200 || xhrObj.status == 304 ) {
			xmlResponse = xhrObj.responseXML;
		} else {
			//xml = 'response failed';
		}
	} else {
		//alert('waiting'); // for debugging
	}
	return xmlResponse;
}

function readPortfolioConfig () {
	var xhr = getHTTPObject();
	var xml = false;
	if ( xhr ) {
		xhr.onreadystatechange = function() {
			xml = getXMLresponse ( xhr );
			if ( xml ) {
				cfg['keyline_width'] = xml.getElementsByTagName("image_keyline_width")[0].firstChild.nodeValue;
				cfg['border_width'] = xml.getElementsByTagName("image_border_width")[0].firstChild.nodeValue;
				cfg['protect_images'] = xml.getElementsByTagName('protect_images')[0].firstChild.nodeValue;
				cfg['show_permalinks'] = xml.getElementsByTagName('show_permalinks')[0].firstChild.nodeValue;
				cfg['last_updated'] = xml.getElementsByTagName('last_updated')[0].firstChild.nodeValue;
				cfg['site_url'] = xml.getElementsByTagName('site_url')[0].firstChild.nodeValue;
				cfg['portfolio_subdir'] = xml.getElementsByTagName('portfolio_subdir')[0].firstChild.nodeValue;
				cfg['copyright'] = xml.getElementsByTagName('copyright')[0].firstChild.nodeValue;
			}
		}
		xhr.open ("GET", "portfolio.local.xml", true);
		xhr.send(null);
	}
	//return cfg;
}

function image_index_links() {
	var index_links = document.getElementsByTagName("img");
	for ( var i=0; i < index_links.length; i++ ) {
		var classAttr = index_links[i].getAttribute("class");
		if ( classAttr == 'index_thumbnail' ) {
			index_links[i].onmouseover = function() {
				this.setAttribute("class", "index_thumbnail_hi" );
			}
			index_links[i].onmouseout = function() {
				this.setAttribute("class", "index_thumbnail" );
			}
		}
	}
}
function subdir_menu_links() {
	var index_links = document.getElementsByTagName("div");
	for ( var i=0; i < index_links.length; i++ ) {
		var classAttr = index_links[i].getAttribute("class");
		if ( classAttr == 'subdir_menu_row sidebar_menu' ) {
			index_links[i].onmouseover = function() {
				this.setAttribute("class", "subdir_menu_row hi sidebar_menu" );
			}
			index_links[i].onmouseout = function() {
				this.setAttribute("class", "subdir_menu_row sidebar_menu" );
			}
		}
	}
}

function prepareContactForm () {
	if ( !document.getElementById("contact_form") ) { return; }

	document.getElementById("contact_form").onsubmit = function () {
		var sendPar = document.getElementById("submit");
		sendPar.innerHTML = '<p><img src="/graphics/icon_spinning_wait_sml_black.gif" alt="please wait" />&nbsp;&nbsp;Sending...</p>';
		var data = '';
		for ( var i=0; i < this.elements.length; i++ ) {
			data+= this.elements[i].name;
			data+= '=';
			data+= escape ( this.elements[i].value );
			data+= '&';
		}
		return !sendFormData ( data );
	};
}

function sendFormData ( data ) {
	var xhr = getHTTPObject();
	if ( xhr ) {
		xhr.onreadystatechange = function () {
			parseFormResponse(xhr);
		};
		xhr.open ( "POST", cfg['site_url'] + '/fSvr/rspform', true );
		xhr.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
		xhr.send ( data );
		return true;
	} else {
		return false;
	}
}

function parseFormResponse ( reqObj ) {
	if ( reqObj.readyState == 4 ) {
		if ( reqObj.status == 200 || reqObj.status == 304 ) {
			var pageDiv = document.getElementById("contact_page");
			pageDiv.innerHTML = reqObj.responseText;
			prepareContactForm();
		}
	}
}


var cfg = Array();
readPortfolioConfig();
addLoadEvent ( image_index_links );
addLoadEvent ( subdir_menu_links );
// addLoadEvent ( prepareContactForm ); // not required for signapse
