/*
Copyright (c) Copyright (c) 2007, Carl S. Yestrau All rights reserved.
Code licensed under the BSD License: http://www.featureblend.com/license.txt
Version: 1.0.4
*/
var FlashDetect = new function()
{
    var self = this;
    self.installed = false;
    self.raw = "";
    self.major = -1;
    self.minor = -1;
    self.revision = -1;
    self.revisionStr = "";
    var activeXDetectRules = [
        {
            "name":"ShockwaveFlash.ShockwaveFlash.7",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash.6",
            "version":function(obj){
                var version = "6,0,21";
                try{
                    obj.AllowScriptAccess = "always";
                    version = getActiveXVersion(obj);
                }catch(err){}
                return version;
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        }
    ];
    /**
     * Extract the ActiveX version of the plugin.
     * 
     * @param {Object} The flash ActiveX object.
     * @type String
     */
    var getActiveXVersion = function(activeXObj){
        var version = -1;
        try{
            version = activeXObj.GetVariable("$version");
        }catch(err){}
        return version;
    };
    /**
     * Try and retrieve an ActiveX object having a specified name.
     * 
     * @param {String} name The ActiveX object name lookup.
     * @return One of ActiveX object or a simple object having an attribute of activeXError with a value of true.
     * @type Object
     */
    var getActiveXObject = function(name){
        var obj = -1;
        try{
            obj = new ActiveXObject(name);
        }catch(err){
            obj = {activeXError:true};
        }
        return obj;
    };
    /**
     * Parse an ActiveX $version string into an object.
     * 
     * @param {String} str The ActiveX Object GetVariable($version) return value. 
     * @return An object having raw, major, minor, revision and revisionStr attributes.
     * @type Object
     */
    var parseActiveXVersion = function(str){
        var versionArray = str.split(",");//replace with regex
        return {
            "raw":str,
            "major":parseInt(versionArray[0].split(" ")[1], 10),
            "minor":parseInt(versionArray[1], 10),
            "revision":parseInt(versionArray[2], 10),
            "revisionStr":versionArray[2]
        };
    };
    /**
     * Parse a standard enabledPlugin.description into an object.
     * 
     * @param {String} str The enabledPlugin.description value.
     * @return An object having raw, major, minor, revision and revisionStr attributes.
     * @type Object
     */
    var parseStandardVersion = function(str){
        var descParts = str.split(/ +/);
        var majorMinor = descParts[2].split(/\./);
        var revisionStr = descParts[3];
        return {
            "raw":str,
            "major":parseInt(majorMinor[0], 10),
            "minor":parseInt(majorMinor[1], 10), 
            "revisionStr":revisionStr,
            "revision":parseRevisionStrToInt(revisionStr)
        };
    };
    /**
     * Parse the plugin revision string into an integer.
     * 
     * @param {String} The revision in string format.
     * @type Number
     */
    var parseRevisionStrToInt = function(str){
        return parseInt(str.replace(/[a-zA-Z]/g, ""), 10) || self.revision;
    };
    /**
     * Is the major version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required major version.
     * @type Boolean
     */
    self.majorAtLeast = function(version){
        return self.major >= version;
    };
    /**
     * Is the minor version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required minor version.
     * @type Boolean
     */
    self.minorAtLeast = function(version){
        return self.minor >= version;
    };
    /**
     * Is the revision version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required revision version.
     * @type Boolean
     */
    self.revisionAtLeast = function(version){
        return self.revision >= version;
    };
    /**
     * Is the version greater than or equal to a specified major, minor and revision.
     * 
     * @param {Number} major The minimum required major version.
     * @param {Number} (Optional) minor The minimum required minor version.
     * @param {Number} (Optional) revision The minimum required revision version.
     * @type Boolean
     */
    self.versionAtLeast = function(major){
        var properties = [self.major, self.minor, self.revision];
        var len = Math.min(properties.length, arguments.length);
        for(i=0; i<len; i++){
            if(properties[i]>=arguments[i]){
                if(i+1<len && properties[i]==arguments[i]){
                    continue;
                }else{
                    return true;
                }
            }else{
                return false;
            }
        }
    };
    /**
     * Constructor, sets raw, major, minor, revisionStr, revision and installed public properties.
     */
    self.FlashDetect = function(){
        if(navigator.plugins && navigator.plugins.length>0){
            var type = 'application/x-shockwave-flash';
            var mimeTypes = navigator.mimeTypes;
            if(mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin && mimeTypes[type].enabledPlugin.description){
                var version = mimeTypes[type].enabledPlugin.description;
                var versionObj = parseStandardVersion(version);
                self.raw = versionObj.raw;
                self.major = versionObj.major;
                self.minor = versionObj.minor; 
                self.revisionStr = versionObj.revisionStr;
                self.revision = versionObj.revision;
                self.installed = true;
            }
        }else if(navigator.appVersion.indexOf("Mac")==-1 && window.execScript){
            var version = -1;
            for(var i=0; i<activeXDetectRules.length && version==-1; i++){
                var obj = getActiveXObject(activeXDetectRules[i].name);
                if(!obj.activeXError){
                    self.installed = true;
                    version = activeXDetectRules[i].version(obj);
                    if(version!=-1){
                        var versionObj = parseActiveXVersion(version);
                        self.raw = versionObj.raw;
                        self.major = versionObj.major;
                        self.minor = versionObj.minor; 
                        self.revision = versionObj.revision;
                        self.revisionStr = versionObj.revisionStr;
                    }
                }
            }
        }
    }();
};
FlashDetect.JS_RELEASE = "1.0.4";

// Browser Window Size and Position
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
// you may copy these functions but please keep the copyright notice as well
function pageWidth()
{
	return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

function pageHeight()
{
	return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}

function posLeft()
{
	return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}

function posTop()
{
	return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}
	
function posRight()
{
	return posLeft() + pageWidth();
}

function posBottom()
{
	return posTop() + pageHeight();
}
                    
var MFGajaxPath = "";
var mfg_ImagePlaceholder = "";
var MFGgalleryId = -1;
var MFGeditedImage = -1;
var MFGoptions = {"enlarge": true, "reduce":true, "maxenlargement": 2.0 };

var mfg_FlashSlideShow_gallery = Array();
var mfg_SlideShow_piclist = Array();
var mfg_SlideShow_picObjs = Array();
var mfg_preloadedImages = Array();

function mfg_SetGalleryOptions(ap,ip,enlarge,reduce, maxenlarge)
{
	MFGajaxPath = ap;
	mfg_ImagePlaceholder = ip;
	MFGoptions.enlarge = (enlarge == 1 ? true : false);
	MFGoptions.reduce = (reduce == 1 ? true : false);
	MFGoptions.maxenlargement = maxenlarge;
}

//////////////////////////////////////////////////////////////////////////////////////
// Send AJAX response to server, with response to be handled by specified callback function
//////////////////////////////////////////////////////////////////////////////////////

function mfg_SendAjaxCallback(url,callbackfunction)
{
	// Add a time code onto the end of the request URL so that it will always be
	// different, even if we're asking for the same thing as something else
	// that we may have done in the recent past, in order to prevent browser caching.
	d = new Date()
	t = d.getTime();
	url = url + "&nc=" + t;
	
	var AjaxRequest = null;
	// Get a request object	
	try
	{
		AjaxRequest = new XMLHttpRequest();
	}
	catch (trymicrosoft)
	{
		try
		{
			AjaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (othermicrosoft)
		{
			try
			{
				AjaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (failed)
			{
				AjaxRequest = null;
				alert("Your web browser is incompatible with the editing functions on this page.");
			}
		}
	}

	// Send the request
	AjaxRequest.open("GET", url, true);
	
	// Use anonymous inner function as callback
	AjaxRequest.onreadystatechange = function() 
	{
		if (AjaxRequest.readyState == 4)
		{	
			// Check for zero because of stupid goddamn fucking Firefox
			if ( (AjaxRequest.status == 0) || (AjaxRequest.status == 200) )
			{
				if( callbackfunction )
					callbackfunction(AjaxRequest.responseText);
			}
			else if (AjaxRequest.status == 404 )
			{
				// file not found?
				msg = "Error!  Status = " + AjaxRequest.status + "\n";
			}
			else
			{
				//alert("Error! Request status is " + AjaxRequest.status);
			}
		}
	}
	
	AjaxRequest.send(" ");	// Firefox doesn't like NULL so send a space	
}


//////////////////////////////////////////////////////////////////////////////////////
// Event handler for when a gallery is selected from drop-down list menu
//////////////////////////////////////////////////////////////////////////////////////
function mfg_SelectGallery()
{
	var theMenu = document.getElementById('mfgGalleryMenu');
	
	if( theMenu.options[theMenu.selectedIndex].value == -1 )
		return;
	
	mfg_DisplayGallery(theMenu.options[theMenu.selectedIndex].value);
}

//////////////////////////////////////////////////////////////////////////////////////
// Load the gallery-specific buttons, uploader, thumbnails, etc.
//////////////////////////////////////////////////////////////////////////////////////
function mfg_DisplayGallery(id)
{
	MFGgalleryId = id;
	document.getElementById("mfgallerydisplay").innerHTML = "<span style='font-size:250%; font-weight: bold; text-decoration: italic;'>Loading...</span>";

	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryDisplayGallery";
	requestUrl += "&id=" + id;
	
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) 
										{ 
//alert(theText);
											 document.getElementById("mfgallerydisplay").innerHTML = theText;
											 document.body.style.cursor = "default";
										} );
}

//////////////////////////////////////////////////////////////////////////////////////

function mfg_GetElementHeight(e)
{
	var elem = document.getElementById(e);
	
	if( elem.style.pixelHeight )
		return elem.style.pixelHeight;
	else
		return elem.offsetHeight;
}

function mfg_GetElementWidth(e)
{
	var elem = document.getElementById(e);
	
	if( elem.style.pixelHeight )
		return elem.style.pixelWidth;
	else
		return elem.offsetWidth;
}

function mfg_ResizeWindow()
{
	var newLeft = (pageWidth() - mfg_GetElementWidth("mfgalleryphotoform")) / 2;
	document.getElementById("mfgalleryphotoform").style.left = newLeft + "px";
	
	var newTop = (pageHeight() -  mfg_GetElementHeight("mfgalleryphotoform")) / 2;
	document.getElementById("mfgalleryphotoform").style.top = newTop + "px";
}


function mfg_isParent( element, parent )
{
	var elem = element;
	while( elem != parent && elem.nodeName != "BODY" )
		elem = elem.parentNode;
		
	if( elem == parent )
		return true;
	else
		return false;
}

function mfg_ClickHandler(e)
{
	var clickedElement = e.target || e.srcElement;
	if( ! mfg_isParent( clickedElement, document.getElementById("mfgalleryphotoform") ) )
		mfg_ClearPhotoForm();
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

function mfg_EditImageInfo(id)
{
	MFGeditedImage = id;
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryGetPhotoInfo";
	requestUrl += "&id=" + id;
	
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { 	document.body.style.cursor = "default";
															//thePhotoInfo = eval("(" + theText + ")");															
															document.getElementById("mfgalleryphotoform").innerHTML = theText;
															document.getElementById("mfgalleryphotoform").style.visibility = "visible";
															document.getElementById("mfgalleryphotoform").style.display = "block";
															
															var copyright = document.getElementById("copyright").value;
															document.getElementById("copyright").value = copyright.replace("%26copy%3B", "&copy;");
															
															mfg_ResizeWindow();															
															
															if (window.attachEvent)
															{
																window.attachEvent("onresize", mfg_ResizeWindow );
																document.body.attachEvent("onclick", mfg_ClickHandler );
															}
															else
															{
																window.addEventListener("resize", mfg_ResizeWindow, false);
																document.body.addEventListener("click", mfg_ClickHandler, false);
															}
													  	} );
}

function mfg_SavePhotoInfo()
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGallerySavePhotoInfo";
	requestUrl += "&id=" + escape(document.getElementById("photoid").value);
	requestUrl += "&thumbdesc=" + escape(document.getElementById("thumbdesc").value);
	requestUrl += "&subject=" + escape(document.getElementById("subject").value);
	requestUrl += "&photographer=" + escape(document.getElementById("photographer").value);
	requestUrl += "&copyright=" + escape(document.getElementById("copyright").value);
	requestUrl += "&description=" + escape(document.getElementById("description").value);
	requestUrl += "&taglist=" + escape(document.getElementById("taglist").value);
	
	//alert(requestUrl);	
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { 	document.body.style.cursor = "default";
															//alert("Image Information Saved!");
															mfg_ClearPhotoForm();
													  } );
}

function mfg_ClearPhotoForm()
{
	document.getElementById("photoid").value = -1
	document.getElementById("photonumber").innerHTML = "NEW";
	document.getElementById("thumbdesc").value = "";
	document.getElementById("subject").value = "";
	document.getElementById("photographer").value = "";
	document.getElementById("copyright").value = "";
	document.getElementById("description").value = "";

	document.getElementById("submit").value = "Save Photo";
	
	document.getElementById("mfgalleryphotoform").innerHTML = "";
	document.getElementById("mfgalleryphotoform").style.visibility = "hidden";
	document.getElementById("mfgalleryphotoform").style.display = "none";
	if( window.detachEvent )
	{
		window.detachEvent( "onresize", mfg_ResizeWindow );
		document.body.detachEvent("onclick", mfg_ClickHandler );
	}
	else
	{
		window.removeEventListener("resize", mfg_ResizeWindow, false );
		document.body.addEventListener("click", mfg_ClickHandler, false);
	}
	MFGeditedImage = -1;
}
////////////////////////////

function mfg_DeleteImage(id)
{
	if( confirm( "Are you sure you want to delete this image?" ) )
	{
		requestUrl = MFGajaxPath;
		requestUrl += "?action=MFGalleryDeleteImage";
		requestUrl += "&id=" + id;
		//alert(requestUrl);
		document.body.style.cursor = "wait";
		mfg_SendAjaxCallback( requestUrl, function(theText) { document.body.style.cursor = "default";
															mfg_DisplayGallery(MFGgalleryId);															
														  } );
	}
}

function mfg_ShowImage(imgpath, displayelem, galleryelem, w, h, mw, mh, caption)
{
	mfg_displayelem = displayelem;
	mfg_galleryelem = galleryelem;
	
	document.getElementById(galleryelem).style.visibility = 'hidden';
	document.getElementById(galleryelem).style.display = 'none';

	// Make sure width & height are non-zero before we try futzing around
	if( w != 0 && h != 0 )
	{
		var wratio = w / mw;
		var hratio = h / mh;
		var multiplier = 1 / ((wratio > hratio) ? (wratio) : (hratio));
	
		// Enforce restrictions on enlarge/reduce
		//alert(MFGoptions.enlarge);
		//alert(MFGoptions.reduce);
		//alert(multiplier);
		if( multiplier > 1.0 )
		{
			if( ! MFGoptions.enlarge )
				multiplier = 1.0;
			else
				multiplier = (multiplier > MFGoptions.maxenlargement) ? MFGoptions.maxenlargement : multiplier;
		}
		else if( multiplier < 1.0 )
		{
			if( ! MFGoptions.reduce )
				multiplier = 1.0;
		}
		//alert(multiplier);
			
		w *= multiplier;
		h *= multiplier;
	}
	imagecode = "<span class='mfgalleryslideshowarea'>Click image to return to thumbnail view</span><br />";
	imagecode += "<img class='mfgalleryimagedisplay' ";
	
	if( w != 0 && h != 0 )
	{
		imagecode += "width='" + w + "' height='" + h + "' ";
	}

	imagecode += "src='" + imgpath + "' onClick='mfg_HideImage(" + '"' + displayelem + '", "' + galleryelem + '");' + "'>";
	
	imagecode += unescape(caption);
	
	//alert(imagecode);
	
	document.getElementById(displayelem).innerHTML = imagecode;
	document.getElementById(displayelem).style.visibility = 'visible';
	document.getElementById(displayelem).style.display = 'block';
}

function mfg_HideImage(displayelem, galleryelem)
{
	document.getElementById(displayelem).innerHTML = "";
	
	document.getElementById(galleryelem).style.visibility = 'visible';
	document.getElementById(galleryelem).style.display = 'block';
	document.getElementById(displayelem).style.visibility = 'hidden';
	document.getElementById(displayelem).style.display = 'none';
}

function mfg_RebuildThumbnails(id,displayflag)
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryRebuildGalleryThumbnails";
	requestUrl += "&id=" + id;
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { 
											   			//if( theText.length > 0 )
															//alert(theText);
														
														if( displayflag )
															mfg_DisplayGallery(id);															
															
											   			document.body.style.cursor = "default";
													    alert("The thumbnails for this gallery have been rebuilt!\nNote that you may have to clear your browser\ncache to see the new versions.");
													  } );
}


function mfg_RebuildGalleryXML(id)
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryRebuildGalleryXML";
	requestUrl += "&id=" + id;
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { document.body.style.cursor = "default";
													      alert(theText + "\n\nThe slideshow XML for this gallery has been rebuilt!");
													  } );
}

function mfg_PhotoManagement(id)
{
	window.location = '/wp-admin/admin.php?page=MFGalleryPhotoManager&gallery=' + id;
}

function mfg_GetThumbnails(id,start, showdesc, targetelem)
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryGetThumbnails";
	requestUrl += "&id=" + id;
	requestUrl += "&start=" + start;
	requestUrl += "&showthumbdesc=" + showdesc;
	requestUrl += "&targetelem=" + targetelem;
	
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { 	document.body.style.cursor = "default";
															//alert(theText);
											   				document.getElementById(targetelem).innerHTML = theText;
													  } );
}

//////////////////////////
// Image rollover code
//////////////////////////

function mfg_ImageRollover( elem, normalstate, overstate, downstate, currentstate )
{
	switch( currentstate )
	{
		case 0:
			document.getElementById(elem).src = normalstate;
			break;
		case 1:
			document.getElementById(elem).src = overstate;
			break;
		case 2:
			document.getElementById(elem).src = downstate;
			break;
	}	
}

function mfg_ShowHelp(elem)
{
	var src = "&nbsp;";
	
	if( elem != -1 )
		src = document.getElementById(elem).innerHTML;
	
	document.getElementById("mfgallery_settings_help").innerHTML = src;
}

function mfg_InsertCopyright(mode)
{
	var d = new Date();
	var photographer = "";
	
	try
	{
		photographer = document.getElementById('photographer').value;
	}
	catch(e)
	{
	}
	
	var copyrightNotice = "Copyright &" + "copy; " + d.getFullYear();
	copyrightNotice += " " + photographer;
	copyrightNotice += (mode == 1 ? ", All Rights Reserved" : ", Used With Permission");
	
	document.getElementById("copyright").value = copyrightNotice;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

function mfg_MoveTop(id)
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryMoveTop";
	requestUrl += "&id=" + id;
	requestUrl += "&galleryid=" + MFGgalleryId;
	
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { 	document.getElementById("mfgallerydisplay").innerHTML = theText;
															document.body.style.cursor = "default";
													  } );
}

function mfg_MoveUp(id)
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryMoveUp";
	requestUrl += "&id=" + id;
	requestUrl += "&galleryid=" + MFGgalleryId;
	
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { 	document.getElementById("mfgallerydisplay").innerHTML = theText;
															document.body.style.cursor = "default";
													  } );
}

function mfg_MoveDown(id)
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryMoveDown";
	requestUrl += "&id=" + id;
	requestUrl += "&galleryid=" + MFGgalleryId;
	
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { 	document.getElementById("mfgallerydisplay").innerHTML = theText;
															document.body.style.cursor = "default";
													  } );
}

function mfg_MoveBottom(id)
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryMoveBottom";
	requestUrl += "&id=" + id;
	requestUrl += "&galleryid=" + MFGgalleryId;
	
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { 	document.getElementById("mfgallerydisplay").innerHTML = theText;
															document.body.style.cursor = "default";
													  } );
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

function mfg_ClearOverlayForm()
{
	document.getElementById("overlayform").style.visibility = "hidden";
	document.getElementById("overlayform").style.display = "none";
}

function mfg_ClickHandlerOverlayForm(e)
{
	var clickedElement = e.target || e.srcElement;
	if( ! mfg_isParent( clickedElement, document.getElementById("overlayform") ) )
		mfg_ClearOverlayForm();
}

function mfg_ResizeOverlayForm()
{
	var newLeft = (pageWidth() - mfg_GetElementWidth("overlayform")) / 2;
	document.getElementById("overlayform").style.left = newLeft + "px";
	
	var newTop = (pageHeight() -  mfg_GetElementHeight("overlayform")) / 2;
	document.getElementById("overlayform").style.top = newTop + "px";
}

function mfg_ShowOverlayForm(forminfo)
{
	document.body.style.cursor = "default";
	document.getElementById("overlayform").innerHTML = forminfo;
	document.getElementById("overlayform").style.visibility = "visible";
	document.getElementById("overlayform").style.display = "block";
	
	mfg_ResizeOverlayForm();															
	
	if (window.attachEvent)
	{
		window.attachEvent("onresize", mfg_ResizeOverlayForm );
		document.body.attachEvent("onclick", mfg_ClickHandlerOverlayForm );
	}
	else
	{
		window.addEventListener("resize", mfg_ResizeOverlayForm, false);
		document.body.addEventListener("click", mfg_ClickHandlerOverlayForm, false);
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

function mfg_DeleteGallery(id)
{
	if( confirm( "Are you sure you want to delete gallery #" + id + "?\nThis will also delete all images associated with this gallery." ) )
	{
		requestUrl = MFGajaxPath;
		requestUrl += "?action=MFGalleryDeleteGallery";
		requestUrl += "&id=" + id;
		document.body.style.cursor = "wait";
		mfg_SendAjaxCallback( requestUrl, function(theText) { document.body.style.cursor = "default";
															mfg_GetGalleryList(); 
															document.getElementById("mfgallerydisplay").innerHTML = "";
															alert("The gallery has been deleted!");
														  } );
	}
}

function mfg_EditGallery(id)
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryAjax&func=GetGalleryEditorForm";
	requestUrl += "&id=" + id;
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, mfg_ShowOverlayForm );
}


function mfg_SaveGallery()
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryAjax&func=SaveGalleryInfo";
	
	requestUrl += "&id=" + escape(document.getElementById("galleryid").value);
	requestUrl += "&name=" + escape(document.getElementById("galleryname").value);
	requestUrl += "&imageurl=" + escape(document.getElementById("imageurl").value);
	requestUrl += "&maxwidth=" + escape(document.getElementById("maxwidth").value);
	requestUrl += "&maxheight=" + escape(document.getElementById("maxheight").value);
	
	requestUrl += "&autoslideshow=" + (document.getElementById("autoslideshow").checked ? "1" : "0");
	requestUrl += "&showname=" + (document.getElementById("showname").checked ? "1" : "0");
	requestUrl += "&membersonly=" + (document.getElementById("membersonly").checked ? "1" : "0");
	requestUrl += "&showthumbdesc=" + (document.getElementById("showthumbdesc").checked ? "1" : "0");
	requestUrl += "&published=" + (document.getElementById("published").checked ? "1" : "0");
	requestUrl += "&autoresize=" + (document.getElementById("autoresize").checked ? "1" : "0");
	
	document.getElementById("debuginfo").innerHTML = requestUrl;
	
	mfg_SendAjaxCallback( requestUrl, function(theText) { 
															alert(theText);
	
															mfg_ClearOverlayForm();
															mfg_GetGalleryList(); 
													  } );
}

function mfg_GetGalleryList()
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryAjax&func=UpdateGalleryMenu";
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText)
											{ 
											 	document.body.style.cursor = "default";
												document.getElementById("gallerymenu").innerHTML = theText;
											} );
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

function mfg_SlideshowOptions()
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryAjax&func=GetSlideshowOptionsForm";
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, mfg_ShowOverlayForm );
}

function mfg_SaveSlideshowOptions()
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryAjax&func=SaveSlideshowOptions";
	requestUrl += "&gwidth=" + document.getElementById("gwidth").value;
	requestUrl += "&gheight=" + document.getElementById("gheight").value;

	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { 	document.body.style.cursor = "default";
											   				//document.getElementById("debuginfo").innerHTML = "Options Are Saved!\n" + theText;
															mfg_ClearOverlayForm();
													  	} );
}

function mfg_ImageDisplayOptions()
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryAjax&func=GetImageDisplayOptionsForm";
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, mfg_ShowOverlayForm );
}

function mfg_SaveImageDisplayOptions()
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryAjax&func=SaveImageDisplayOptions";
	requestUrl += "&maximagewidth=" + document.getElementById("maximagewidth").value;
	requestUrl += "&maximageheight=" + document.getElementById("maximageheight").value;
	requestUrl += "&maxenlargement=" + document.getElementById("maxenlargement").value;
	requestUrl += "&showsubject=" + (document.getElementById("showsubject").checked ? "1" : "0");
	requestUrl += "&showphotographer=" + (document.getElementById("showphotographer").checked ? "1" : "0");
	requestUrl += "&showcopyright=" + (document.getElementById("showcopyright").checked ? "1" : "0");
	requestUrl += "&showdescription=" + (document.getElementById("showdescription").checked ? "1" : "0");
	requestUrl += "&enlarge=" + (document.getElementById("enlarge").checked ? "1" : "0");
	requestUrl += "&reduce=" + (document.getElementById("reduce").checked ? "1" : "0");

	//alert(requestUrl);
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { 	document.body.style.cursor = "default";
											   				//document.getElementById("debuginfo").innerHTML = "Options Are Saved!\n" + theText;
															mfg_ClearOverlayForm();
															//document.getElementById("debuginfo").innerHTML = theText;
													  	} );
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

function mfg_UpdateThumbnailPreview()
{
	var w = document.getElementById("thumbnailsize").value * 0.6666;
	try
	{
		document.getElementById("mfgallery_thumbnail_box").style.width = document.getElementById("thumbgridsize").value + "px";
		document.getElementById("mfgallery_thumbnail_box").style.height = document.getElementById("thumbgridsize").value + "px";
		
		var toppadding = (document.getElementById("thumbgridsize").value - document.getElementById("thumbnailsize").value) / 2;
		document.getElementById("mfgallery_thumbnail_img").style.paddingTop = toppadding + "px";
		
		document.getElementById("mfgallery_thumbnail_box").style.backgroundColor = document.getElementById("thumbcolor").value;
	
		if( document.getElementById("thumbborder").checked )
		{
			var bw = document.getElementById("thumbborderwidth").value
			document.getElementById("mfgallery_thumbnail_box").style.border = bw + "px solid " + document.getElementById("thumbbordercolor").value;
		}
		else
		{
			document.getElementById("mfgallery_thumbnail_box").style.border = "none";
		}
		
		document.getElementById("mfgallery_thumbnail_img").style.width = w + "px";
		document.getElementById("mfgallery_thumbnail_img").style.height = document.getElementById("thumbnailsize").value + "px";
	}
	catch(e)
	{
		//document.getElementById("debuginfo").innerHTML = "error in mfg_UpdateThumbnailPreview()";
	}
}


function mfg_ThumbnailOptions()
{
	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryGetThumbnailOptionsForm";
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, mfg_ShowOverlayForm );
}

function mfg_SaveThumbnailOptions()
{
	// To do: Add field validation
	//document.getElementById("debuginfo").innerHTML = "mfg_SaveThumbnailOptions";

	requestUrl = MFGajaxPath;
	requestUrl += "?action=MFGalleryAjax&func=SaveThumbnailOptions";
	requestUrl += "&thumbgridsize=" + document.getElementById("thumbgridsize").value;
	requestUrl += "&thumbnailsize=" + document.getElementById("thumbnailsize").value;
	requestUrl += "&thumbcolor=" + escape(document.getElementById("thumbcolor").value);
	requestUrl += "&thumbjpeg=" + document.getElementById("thumbjpeg").value;
	requestUrl += "&thumbborder=" + (document.getElementById("thumbborder").checked ? "1" : "0");
	requestUrl += "&thumbborderwidth=" + document.getElementById("thumbborderwidth").value;
	requestUrl += "&thumbbordercolor=" + escape(document.getElementById("thumbbordercolor").value);
	requestUrl += "&thumbsperpage=" + document.getElementById("thumbsperpage").value;

	//alert(requestUrl);
	document.body.style.cursor = "wait";
	mfg_SendAjaxCallback( requestUrl, function(theText) { 	document.body.style.cursor = "default";
											   				mfg_ClearOverlayForm();
													  	} );
}


//////////////////////////
// This block of code contains functions called from Flash Uploader.
//////////////////////////

function mfg_FlashAlert(msg)
{
	alert(msg);
}

function mfg_ImageClicked()
{
	mfg_HideImage( mfg_displayelem, mfg_galleryelem );
}

function mfg_FlashUploadFinished(msg)
{
	document.getElementById("flashuploadstatus").innerHTML = msg;
	//alert(MFGgalleryId);
	mfg_DisplayGallery(MFGgalleryId);
	//mfg_ShowLogfiles();
}

function mfg_FlashUploadStarted(msg)
{
	document.getElementById("flashuploadstatus").innerHTML = msg;
}

function mfg_GetGalleryId()
{
	return MFGgalleryId;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
function mfg_BrowserSupportsLoadCheck()
{
	txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
	txt+= "<p>Browser Name: " + navigator.appName + "</p>";
	txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
	txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
	txt+= "<p>Platform: " + navigator.platform + "</p>";
	txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
 
 	var ii = navigator.appName.indexOf("Internet Explorer");
	
	if( ii > 0 )
		return true;

	return false;
}

///////////////////////////////////////////////////////////////////////////////////////////////////

var mfg_SlideshowImageList = new Array();
var mfg_PreloadedImage = new Image;
var mfg_SlideshowDuration = 3000;
var mfg_SlideshowTimer = -1;
mfg_SlideshowCurrentImage = -1;
var mfg_WaitForLoad = true;mfg_BrowserSupportsLoadCheck();

function mfg_SlideshowImageStateChange()
{
	// This is all for Firefox...
	
	if( mfg_PreloadedImage.complete )
		mfg_PreloadedImage.readyState = "complete";
	
	var msg = "not loaded";
	try{ msg = mfg_PreloadedImage.readyState; } catch(e){}
	document.getElementById("mfgJSSlideshowCaption").innerHTML = "preload of next image (" + mfg_PreloadedImage.src + "): " + msg;
}

function mfg_SlideshowPreloadNextImage()
{
	
	nextimg = mfg_SlideshowCurrentImage + 1;
	if( nextimg > (mfg_SlideshowImageList.length-1) )
		nextimg = 0;

	mfg_PreloadedImage = new Image;
	try{ mfg_PreloadedImage.complete = false; } catch(e){}
		
	try
	{
		mfg_PreloadedImage.addEventListener( "readystatechange", mfg_SlideshowImageStateChange, true );
		mfg_PreloadedImage.addEventListener( "load", mfg_SlideshowImageStateChange, true );
	}
	catch(e)
	{
		mfg_PreloadedImage.attachEvent('onreadystatechange', mfg_SlideshowImageStateChange ); 
	}
	mfg_PreloadedImage.src = mfg_SlideshowImageList[ nextimg ];
	var msg = mfg_PreloadedImage.readyState;
	document.getElementById("mfgJSSlideshowCaption").innerHTML = "preload of next image (" + mfg_PreloadedImage.src + "): " + msg;
}

function mfg_SlideshowGotoNextImage()
{
	// If next image is not finished loading yet...
	if( mfg_WaitForLoad )
	{
		try
		{
			document.getElementById("mfgJSSlideshowCaption").innerHTML = mfg_PreloadedImage.readyState;
			if( mfg_PreloadedImage.readyState != "complete" )
			{
				// Set timer to check again in 500ms.
				window.setTimeout( mfg_SlideshowGotoNextImage, 500 );
		
				// And exit without switching image
				return;
			}
		}
		catch(e)
		{
			// Do nothing... probably got here 'cos readyState property wasn't supported by browser.
		}
	}
	
	var picObjList = mfg_SlideShow_picObjs[MFGgalleryId];
	
	mfg_SlideshowCurrentImage++;
	if( mfg_SlideshowCurrentImage > (mfg_SlideshowImageList.length-1) )
		mfg_SlideshowCurrentImage = 0;

	var picObj = picObjList[mfg_SlideshowCurrentImage];
	
	var pw = pageWidth() - 40;
	var ph = pageHeight() - 80;
	var w = picObj.width;
	var h = picObj.height;
	
//	picObj.caption = pw + "x" + ph + ", " + w + "x" + h + ", ";
	
	if( h > ph )
	{
		var scalefactor = ph / picObj.height;
		h = h * scalefactor;
		w = w * scalefactor;
	}
	
	// If width is still too big after scaling height, then scale by width
	if( w > pw )
	{
		var scalefactor = pw / picObj.width;
		h = h * scalefactor;
		w = w * scalefactor;
	}
	
	if( mfg_SlideshowAllowEnlargement )
	{
		if( h < ph )
		{
			var scalefactor1 = pw / picObj.width;
			var scalefactor2 = ph / picObj.height;
			scalefactor = Math.min( scalefactor1, scalefactor2 );
			w = picObj.width * scalefactor;
			h = picObj.height * scalefactor;
		}
	}

//	picObj.caption += w + "x" + h + ", SCALE:" + scalefactor + ", " + scalefactor1 + ", " + scalefactor2;
	
	try
	{
		var filterList = mfgJSSlideshowImage.filters;
		filterList[0].Apply();
		document.getElementById("mfgJSSlideshowImage").src = mfg_ImagePlaceholder;
		filterList[0].Play();
		
		window.setTimeout( function() {
										document.getElementById("mfgJSSlideshowImage").style.width = w + "px";
										document.getElementById("mfgJSSlideshowImage").style.height = h + "px";
										document.getElementById("mfgJSSlideshowImage").width = w;
										document.getElementById("mfgJSSlideshowImage").height = h;
									
										filterList[0].Apply();
										document.getElementById("mfgJSSlideshowImage").src = mfg_SlideshowImageList[mfg_SlideshowCurrentImage];
										filterList[0].Play();
										document.getElementById("mfgJSSlideshowCaption").innerHTML = picObj.caption;	
										document.getElementById("mfgJSSlideshowCaption2").innerHTML = picObj.imageurl;	
									}, 500 );
	}
	catch(e) // Presume exception is caused by browser not supporting transition filters...
	{
		document.getElementById("mfgJSSlideshowImage").style.width = w + "px";
		document.getElementById("mfgJSSlideshowImage").style.height = h + "px";
		document.getElementById("mfgJSSlideshowImage").width = w;
		document.getElementById("mfgJSSlideshowImage").height = h;
	
		document.getElementById("mfgJSSlideshowImage").src = mfg_SlideshowImageList[mfg_SlideshowCurrentImage];
		document.getElementById("mfgJSSlideshowCaption").innerHTML = picObj.caption;	
	}
	
	// Wait and then go switch image again
	clearTimeout( mfg_SlideshowTimer );
	mfg_SlideshowTimer = setTimeout("mfg_SlideshowGotoNextImage()", mfg_SlideshowDuration );

	mfg_SlideshowPreloadNextImage();
}

function mfg_SlideshowControl(func, piclist)
{
	//alert( "pagewidth = " + pageWidth() + ", pageheight = " + pageHeight() );
	
	if( func == 'Play' )
	{
		var ssHtml = document.getElementById("mfgJSSlideshowContainer").innerHTML;
		if( ssHtml.length > 0 )
		{
			document.getElementById("mfgJSSlideshowContainer").innerHTML = "";
			var bodyElem = document.getElementsByTagName("body")[0];
			bodyElem.innerHTML = ssHtml + bodyElem.innerHTML;
		}
		
		mfg_SlideshowImageList = piclist;
		
		// Get all images loading...
		for(i = 0; i < piclist.length; i++ )
		{
			mfg_preloadedImages[i] = new Image;
			mfg_preloadedImages[i].src = piclist.imageurl;
		}
		
		// Make sure we're starting on correct image...
		document.getElementById("mfgJSSlideshowImage").src = mfg_SlideshowImageList[0];
		document.getElementById("mfgJSSlideshowImage").style.width = "0px";
		document.getElementById("mfgJSSlideshowImage").style.height = "0px";
		document.getElementById("mfgJSSlideshowImage").width = 0;
		document.getElementById("mfgJSSlideshowImage").height = 0;
		
		document.getElementById("mfgJSSlideshow").style.top = posTop();
		document.getElementById("mfgJSSlideshow").style.visibility = "visible";
		document.getElementById("mfgJSSlideshow").style.display = "block";
		mfg_SlideshowCurrentImage = -1;
		mfg_SlideshowPreloadNextImage();
		mfg_SlideshowGotoNextImage();
	}
	else if( func == "Stop" )
	{
		document.getElementById("mfgJSSlideshow").style.visibility = "hidden";
		document.getElementById("mfgJSSlideshow").style.display = "none";
		clearTimeout( mfg_SlideshowTimer );
	}
}

function mfg_FlashSlideshowPlay(galleryid)
{
	var elemname = "mfgFlashSlideShow_" + galleryid;
	
	document.getElementById(elemname).style.visibility='visible';
	document.getElementById(elemname).style.display='block';
	
	elemname = "mfgallerythumbs" + galleryid;
	document.getElementById(elemname).style.visibility='hidden';
	document.getElementById(elemname).style.display='none';

	var flashMovie = getFlashMovieObject("mfgFlashPlayer_" + galleryid);
	flashMovie.Rewind();
	flashMovie.Play();
}

function mfg_FlashSlideShowStop(galleryid)
{
	var elemname = "mfgFlashSlideShow_" + galleryid;

	document.getElementById(elemname).style.visibility='hidden';
	document.getElementById(elemname).style.display='none';

	elemname = "mfgallerythumbs" + galleryid;
	document.getElementById(elemname).style.visibility='visible';
	document.getElementById(elemname).style.display='block';

	try
	{
		var flashMovie = getFlashMovieObject("mfgFlashPlayer_" + galleryid);
		flashMovie.StopPlay();
		flashMovie.Rewind();
		flashMovie.Stop();
	}
	catch(e)
	{
	}
}

function mfg_SlideshowPlay(galleryid)
{
	MFGgalleryId = galleryid;
	
	mfg_SlideshowMode = FlashDetect.installed ? 1 : 2;	

	//mfg_SlideshowMode = 2; // Javascript
	
	if( mfg_SlideshowMode == 1 ) // Flash
	{
		mfg_FlashSlideshowPlay(galleryid);
	}
	else
	{
		mfg_SlideshowControl("Play",mfg_SlideShow_piclist[galleryid]);
	}
}

function mfg_SlideshowStop()
{
	if( mfg_SlideshowMode == 1 ) // Flash
	{
		mfg_FlashSlideshowStop(MFGgalleryId);
	}
	else
	{
		mfg_SlideshowControl("Stop",0);
	}
}

function getFlashMovieObject(movieName)
{
	if (window.document[movieName]) 
	{
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1)
	{
		if (document.embeds && document.embeds[movieName])
			return document.embeds[movieName]; 
	}
	else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
	{
		return document.getElementById(movieName);
	}
}

