var xmlDoc;
var http_request = false;
var sPath = "images/pics/";
var sURLPath = "Pics_Det.aspx?pic=";
var sThumbSize = "200";
var sThumSize2 = "267";
var sGoBackID = "";


function GetData(oObj, sType, sImgObject) {
	//alert('hello....');
	if (oObj.readyState == 4) {
		if (oObj.status == 200) {
			//alert(oObj.responseText);
			if(sType == 'single')
			{
				//-- Single picture request
				loadSingleXLM(oObj, sImgObject);
			}
			
			if(sType == 'caption')
			{
				//-- Inital picture request
				loadCaption(oObj);
			}
			
		} else {
			//alert('There was a problem with the request.\nStatus: ' + oObj.responseText);
			alert('There was a problem with the request.');
		}
	}
}


function SetImageSource( object, inImage, inWidth, inHeight, lnkObject ){
	var sImgFile = GetFileName(inImage);
	if((sImgFile > 0) && (sImgFile < 10)) sImgFile = "00" + sImgFile;
	if((sImgFile >= 10) && (sImgFile < 100)) sImgFile = "0" + sImgFile;
	
	var sLink = "javascript:NoFunction()";
	if(inImage != "images/pic_loading.jpg") sLink = sURLPath + sImgFile;
	
	if (document.getElementById && document.getElementById(object) != null){
		node = document.getElementById(object).src = inImage;
		node2 = document.getElementById(object).width = inWidth;
		node3 = document.getElementById(object).height = inHeight;
		node4 = document.getElementById(lnkObject).href = sLink;
	}
	else if (document.layers && document.layers[object] != null){
		document.layers[object].src = inImage;
		document.layers[object].width = inWidth;
		document.layers[object].height = inHeight;
		document.layers[lnkObject].href = sLink;
	}
	else if (document.all){
		document.all[object].src = inImage;
		document.all[object].width = sWidth;
		document.all[object].height = inHeight;
		document.all[lnkObject].href = sLink;
	}
}


function SetCaption( object, sCaption ){
	if (document.getElementById && document.getElementById(object) != null){
		node = document.getElementById(object).innerHTML = sCaption;
	}
	else if (document.layers && document.layers[object] != null){
		document.layers[object].innerHTML = sCaption;
	}
	else if (document.all){
		//document.all[object].innerHTML = sCaption;
	}
}






function checkForParseError (xmlDocument) {
	var errorNamespace = 'http://www.mozilla.org/newlayout/xml/parsererror.xml';
	var documentElement = xmlDocument.documentElement;
	var parseError = { errorCode : 0 };
	if (documentElement.nodeName == 'parsererror' &&
		documentElement.namespaceURI == errorNamespace) {
		parseError.errorCode = 1;
		var sourceText = documentElement.getElementsByTagNameNS(errorNamespace, 'sourcetext')[0];
		if (sourceText != null) {
		parseError.srcText = sourceText.firstChild.data
		}
		parseError.reason = documentElement.firstChild.data;
	}
	return parseError;
}


function MyReplace(inString, inOldChars, inNewChars)
{
	var iCnt = 1;
	var sTemp = inString;
	var a = "";
	var b = "";
	
	while( iCnt != 0)
	{
		if(sTemp.indexOf(inOldChars) != -1)
		{
			a = sTemp.substring(0, sTemp.indexOf(inOldChars));
			b = sTemp.substring(sTemp.indexOf(inOldChars) + inOldChars.length);
			sTemp = a + inNewChars + b;
			iCnt = 1;
		}
		else
		{
			iCnt = 0;
		}
	}
	
	return sTemp;	
}




function GetFileName( sFile )
{
	//var sFile = "http://www.blah.com/images/pics/pics123.jpg";
	
	sFile.lastIndexOf("/");
	var sTemp = sFile.substring(sFile.lastIndexOf("/") + 1);
	sTemp = sTemp.substring(0, sTemp.lastIndexOf("."));
	sTemp = sTemp.toLowerCase();
	sTemp = sTemp.substring(sTemp.indexOf("pics") + 4);
	if(sTemp.indexOf("pic") > 0) sTemp = sTemp.substring(sTemp.indexOf("pic") + 3);

	var iCnt = 1;
	while (iCnt != 0)
	{
		//alert(sTemp.indexOf("0"));
		if((sTemp.indexOf("0") != -1) && (sTemp.indexOf("0") == 0))
		{
			sTemp = sTemp.substring(sTemp.indexOf("0") + 1);
		}
		else
		{
			iCnt = 0;
		}
	}
	
	//alert(sTemp);
	return sTemp;
}


function TestGetFileName( sFile )
{
	alert(GetFileName(sFile));
}






function GoAJAX_Next()
{
	//-- Show buttons
	ShowPic_NavButtons();
	
	//-- MAIN IMAGE current data ([0]:Source; [1]:Width; [2]:Height)
	var sMain_Current = new Array(3);
	sMain_Current = GetImageData( 'imgMain' );
	//alert('Main_Current: \n' + sMain_Current[0] + '\n' + sMain_Current[1] + '\n' + sMain_Current[2]);
	
	//-- Get the new MainID
	var sMainID = GetFileName( sMain_Current[0] );
	//alert("New MainID: " + sMainID);

	if((sMainID.length == 0) || (sMainID == '_loading'))
	{
		alert('Request failed. \nTry again.');
		//alert('Request failed. \nTry again. \n\nERROR: \n     ' + sMain_New[0] + '\n     ' + sMainID);
	}
	else
	{	
		//-- Now get the new data values for the new NEXT IMAGE through an AJAX call to the DB
		sGoBackID = sMainID;
		SetImageSource( 'imgMain', 'images/pic_loading.jpg', sThumSize2, sThumbSize, 'aMain' );
		SetCaption( 'divMainCaption', '&nbsp;' );
		SinglePicRequest('Controls/AJAX_PicInfo.aspx', 'type=next&main=' + sMainID, 'imgNext');
	}
	
}

function GoAJAX_Prev()
{
	//-- Show buttons
	ShowPic_NavButtons();
	
	//-- MAIN IMAGE current data ([0]:Source; [1]:Width; [2]:Height)
	var sMain_Current = new Array(3);
	sMain_Current = GetImageData( 'imgMain' );
	//alert('Main_Current: \n' + sMain_Current[0] + '\n' + sMain_Current[1] + '\n' + sMain_Current[2]);
	
	//-- Get the new MainID
	var sMainID = GetFileName( sMain_Current[0] );
	//alert("New MainID: " + sMainID);
	
	if((sMainID.length == 0) || (sMainID == '_loading'))
	{
		alert('Request failed. \nTry again.');
		//alert('Request failed. \nTry again. \n\nERROR: \n     ' + sMain_New[0] + '\n     ' + sMainID);
	}
	else
	{
		//-- Now get the new data values for the new PREV IMAGE through an AJAX call to the DB
		sGoBackID = sMainID;
		SetImageSource( 'imgMain', 'images/pic_loading.jpg',sThumSize2, sThumbSize, 'aMain' );
		SetCaption( 'divMainCaption', '&nbsp;' );
		SinglePicRequest('Controls/AJAX_PicInfo.aspx', 'type=prev&main=' + sMainID, 'imgPrev');
	}
}


function GoAJAX_CaptionOnly(inID)
{
	var sMainID = inID;
	//alert("New MainID: " + sMainID);
	
	if((sMainID.length == 0) || (sMainID == '_loading'))
	{
		alert('Request failed. \nTry again.');
		//alert('Request failed. \nTry again. \n\nERROR: \n     ' + sMain_New[0] + '\n     ' + sMainID);
	}
	else
	{
		//-- Now get the new data values for the new PREV IMAGE through an AJAX call to the DB
		CaptionRequest('Controls/AJAX_PicInfo.aspx', 'type=caption&main=' + sMainID);
	}
}


function GetNewDataVals( sData, inThumbSize )
{
	var sReturn = new Array(3);
	sReturn[0] = sData[0];
	
	//-- Get the new dimensions
	var iWidth = sData[1];
	var iHeight = sData[2];
	var boolPortrait = false;
	var iRatio, iThumbWidth, iThumbHeight;

    //-- Need to determine what the new dimensions will be for the new picture
    //-- First determine what the ratio is between the width and height, to do that
    //-- the first step is to determine whether this is a Landscape type picture (Width > Height) or
    //-- a Portrait type picture (Height > Width)
    if(iWidth < iHeight)
    {
		boolPortrait = true;
		inThumbSize += 20;
    }

    //-- Set the ratio
    if(boolPortrait == true)
    {
		//iRatio = iHeight/iWidth;
		iRatio = iWidth/iHeight;
    }
    else
    {
		iRatio = iWidth/iHeight;
    }

    //-- Based on the ratio of the original picture, set the dimensions of the Thumbnail
//    if(boolPortrait == true)
//    {
//		iThumbHeight = (iThumbWidth * iRatio);
//		iThumbWidth = inThumbSize;
//    }
//    else
//    {
		iThumbHeight = inThumbSize;
		iThumbWidth = (iThumbHeight * iRatio);
//    }
    iThumbWidth = Math.round(iThumbWidth);
    iThumbHeight = Math.round(iThumbHeight);

    //-- Make sure we aren't elarging the picture, if we are, just leave the dimensions at the original size
    //if(iThumbHeight > iHeight){ iThumbHeight = iHeight };
    //if(iThumbWidth > iWidth){ iThumbWidth = iWidth };

	//-- Set the output values
	sReturn[1] = iThumbWidth;
	sReturn[2] = iThumbHeight;

	return sReturn;
}


function GetImageData( object ){
	var sData = new Array(3);

	if (document.getElementById && document.getElementById(object) != null){
		sData[0] = document.getElementById(object).src;
		sData[1] = document.getElementById(object).width;
		sData[2] = document.getElementById(object).height;
	}
	else if (document.layers && document.layers[object] != null){
		sData[0] = document.layers[object].src;
		sData[1] = document.layers[object].width;
		sData[2] = document.layers[object].height;
	}
	else if (document.all){
		sData[0] = document.all[object].src;
		sData[1] = document.all[object].width;
		sData[2] = document.all[object].height;
	}
	return sData;
}






//**************************************************************************************************
//*********** SINGLE ITEM REQUEST CODE

function SinglePicRequest(sURL, sPostString, sImgObject) {
	http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	
	//http_request.onreadystatechange = function() { alertContents(http_request); };
	http_request.onreadystatechange = function() { GetData(http_request, 'single', sImgObject); };
	//http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	//http_request.open("POST",sURL,true);
	//http_request.send(sPostString);
	http_request.open("GET", sURL + "?" + sPostString, true);
    http_request.send(null);
	
	//-- Can't always just check the results right away, you have to give the server of the page you requested time to respond.
	//-- Options:  You can do a loop, or kick off a timer or whatever.
	//alertContents();
}

function CaptionRequest(sURL, sPostString) {
	http_request = false;
	var sImgObject = 'imgMain';

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	
	//http_request.onreadystatechange = function() { alertContents(http_request); };
	http_request.onreadystatechange = function() { GetData(http_request, 'caption', sImgObject); };
	//http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	//http_request.open("POST",sURL,true);
	//http_request.send(sPostString);
	http_request.open("GET", sURL + "?" + sPostString, true);
    http_request.send(null);
	
	//-- Can't always just check the results right away, you have to give the server of the page you requested time to respond.
	//-- Options:  You can do a loop, or kick off a timer or whatever.
	//alertContents();
}

function loadSingleXLM(oObj, sImgObject)
{
	//load xml file
	// code for IE
	if (window.ActiveXObject)
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.loadXML(oObj.responseText);
		//xmlDoc.load("Test.xml");
		modifySinglePic(sImgObject);
	}
	// code for Mozilla, etc.
	else if (document.implementation && document.implementation.createDocument)
	{
		xmlDoc = document.implementation.createDocument("","",null);
		
		var domParser = new DOMParser();
		var sXML = oObj.responseText;
		xmlDoc = domParser.parseFromString(sXML, 'application/xml');
		var parseError = checkForParseError(xmlDoc);
		if (parseError.errorCode == 0) {
			modifySinglePic(sImgObject);
		}
		else{
			alert('error: ' + parseError.srcText);	
			return;
		}
		//xmlDoc.onload=createTable;
	}
	else
	{
		alert('Your browser cannot handle this script');
	}
}


function loadCaption(oObj)
{
	//load xml file
	// code for IE
	if (window.ActiveXObject)
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.loadXML(oObj.responseText);
		//xmlDoc.load("Test.xml");
		ModifyCaption();
	}
	// code for Mozilla, etc.
	else if (document.implementation && document.implementation.createDocument)
	{
		xmlDoc = document.implementation.createDocument("","",null);
		
		var domParser = new DOMParser();
		var sXML = oObj.responseText;
		xmlDoc = domParser.parseFromString(sXML, 'application/xml');
		var parseError = checkForParseError(xmlDoc);
		if (parseError.errorCode == 0) {
			ModifyCaption();
		}
		else{
			alert('error: ' + parseError.srcText);	
			return;
		}
		//xmlDoc.onload=createTable;
	}
	else
	{
		alert('Your browser cannot handle this script');
	}
}


function modifySinglePic(sImgObject)
{
	var sType = "";
	var sData = new Array(5);
	//alert(xmlDoc.getElementsByTagName("Pic").length);
	//alert(xmlDoc.getElementsByTagName("Pic")[0].attributes.getNamedItem("Type").value);
	//alert(xmlDoc.getElementsByTagName("Pic")[0].getAttribute("Type"));
	//alert(xmlDoc.xml);
	if(xmlDoc.getElementsByTagName("PicError").length > 0){
		alert("You have reached the end of the pictures.\n\n(Error: " + xmlDoc.getElementsByTagName("PicError")[0].getAttribute("ErrText") + ")");
		//-- Do something to show no more pics
		NotifyEnd(sImgObject, 1);
		return;
	}
	
	//alert("Type: " + xmlDoc.getElementsByTagName("Pic")[0].getAttribute("Type"));
	sType = "imgMain";
	sLinkObj = "aMain";
	//-- Call the method that changes the image
	//alert(sType + "\n" + 
	//				sPath + xmlDoc.getElementsByTagName("Pic")[0].getAttribute("File") + "\n" + 
	//				xmlDoc.getElementsByTagName("Pic")[0].getAttribute("Width") + "\n" + 
	//				xmlDoc.getElementsByTagName("Pic")[0].getAttribute("Height"));
	
	sData[0] = sPath + xmlDoc.getElementsByTagName("Pic")[0].getAttribute("File");
	sData[1] = xmlDoc.getElementsByTagName("Pic")[0].getAttribute("Width");
	sData[2] = xmlDoc.getElementsByTagName("Pic")[0].getAttribute("Height");
	sData[3] = xmlDoc.getElementsByTagName("Pic")[0].getAttribute("PicEnd");
	sData[4] = xmlDoc.getElementsByTagName("Pic")[0].getAttribute("PicCaption");
	
	//alert(sData[4]);
	if(sData[4] == null) sData[4] = "&nbsp;";
	
	if(sData[4].length > 0){
		sData[4] = MyReplace(sData[4], "[", "<");
		sData[4] = MyReplace(sData[4], "]", ">");
	}else{
		sData[4] = '&nbsp;';
	}
	
	//alert(sData[0] + '\n' + sData[1] + '\n' + sData[2]);
	//alert('new ID: ' + xmlDoc.getElementsByTagName("Pic")[0].getAttribute("File") + '\nPath: ' + sData[0]);
	
	//-- Set the image source
	//SetImageSource( sImgObject, sData[0], sData[1], sData[2], sLinkObj );
	SetImageSource( 'imgMain', sData[0], sData[1], sData[2], sLinkObj );
	SetCaption( 'divMainCaption', sData[4] );
	
	//-- Disable the buttons
	if(sData[3] == 1) NotifyEnd(sImgObject, 0);
}

function ModifyCaption()
{
	var sData = "";

	if(xmlDoc.getElementsByTagName("PicError").length > 0){
		alert("Error: " + xmlDoc.getElementsByTagName("PicError")[0].getAttribute("ErrText"));
		return;
	}

	//alert(xmlDoc.xml);	
	sData = xmlDoc.getElementsByTagName("Pic")[0].getAttribute("PicCaption");

	//alert(sData[4]);
	if(sData == null) sData = "&nbsp;";
	
	if(sData.length > 0){
		sData = MyReplace(sData, "[", "<");
		sData = MyReplace(sData, "]", ">");
	}else{
		sData = '&nbsp;';
	}
	
	SetCaption( 'divMainCaption', sData );
}

function NotifyEnd(sImgObject, iOldPicFlag)
{
	//alert("You have reached the end of the pictures...");
	if(sImgObject == "imgNext")
	{
		hideItem('lnkNext');
		showItem('noLnkNext');
		//SetImageSource( 'imgMain', 'images/pic_end.jpg',sThumSize2, sThumbSize, 'aMain' );
	}
	
	if(sImgObject == "imgPrev")
	{
		hideItem('lnkPrev');
		showItem('noLnkPrev');
		//SetImageSource( 'imgMain', 'images/pic_end.jpg',sThumSize2,sThumbSize, 'aMain' );
	}
	
	if(iOldPicFlag == 1)
	{
		if((sGoBackID > 0) && (sGoBackID < 10)) sGoBackID = "00" + sGoBackID;
		if((sGoBackID >= 10) && (sGoBackID < 100)) sGoBackID = "0" + sGoBackID;
		SetImageSource( 'imgMain', 'images/pics/pics' + sGoBackID + '.jpg', sThumSize2, sThumbSize, 'aMain' );
		SetCaption( 'divMainCaption', '&nbsp;' );
	}
}

function ShowPic_NavButtons()
{
	hideItem('noLnkNext');
	hideItem('noLnkPrev');
	showItem('lnkNext');
	showItem('lnkPrev');
}








function showItem(object){
	//-- Show the item...
	if (document.getElementById && document.getElementById(object) != null){
		node = document.getElementById(object).style.display='';}
	else if (document.layers && document.layers[object] != null){
		document.layers[object].display = '';}
	else if (document.all){
		document.all[object].style.display = '';}
}
function hideItem(object){
	//-- Hide the item...
	if (document.getElementById && document.getElementById(object) != null){
		node = document.getElementById(object).style.display='none';}
	else if (document.layers && document.layers[object] != null){
		document.layers[object].display = 'none';}
	else if (document.all){
		document.all[object].style.display = 'none';}
}

function NoFunction()
{
	return;
}