// -------------------------------------------------------------------
// Image Thumbnail Viewer Script- By Dynamic Drive, available at: http://www.dynamicdrive.com
// Last updated: Jan 22nd, 2007
// -------------------------------------------------------------------

function AG_GetImgWidth(path)
{ 
	var img1;
	img1 = new Image();
	img1.src=path;
	retval = img1.width;
	return retval; 
} 

var thumbnailviewer={
enableTitle: true, //Should "title" attribute of link be used as description?
enableAnimation: false, //Enable fading animation?
definefooter: '<div class="footerbar">close</div>', //Define HTML for footer interface
defineLoading: 'Loading Image...', //Define HTML for "loading" div

/////////////No need to edit beyond here/////////////////////////

scrollbarwidth: 16,
opacitystring: 'filter:progid:DXImageTransform.Microsoft.alpha(opacity=10); -moz-opacity: 0.1; opacity: 0.1',
targetlinks:[], //Array to hold links with rel="thumbnail"

createthumbBox:function(){
//write out HTML for Image Thumbnail Viewer plus loading div
document.write('<div id="thumbBox" onClick="thumbnailviewer.closeit()"><div id="thumbImage"></div>'+this.definefooter+'</div>')
document.write('<div id="thumbLoading">'+this.defineLoading+'</div>')
this.thumbBox=document.getElementById("thumbBox")
this.thumbImage=document.getElementById("thumbImage") //Reference div that holds the shown image
this.thumbLoading=document.getElementById("thumbLoading") //Reference "loading" div that will be shown while image is fetched
this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
},


centerDiv:function(divobj){ //Centers a div element on the page
var ie=document.all && !window.opera
var dom=document.getElementById
var scroll_top=(ie)? this.standardbody.scrollTop : window.pageYOffset
var scroll_left=(ie)? this.standardbody.scrollLeft : window.pageXOffset
var docwidth=(ie)? this.standardbody.clientWidth : window.innerWidth-this.scrollbarwidth
var docheight=(ie)? this.standardbody.clientHeight: window.innerHeight
var docheightcomplete=(this.standardbody.offsetHeight>this.standardbody.scrollHeight)? this.standardbody.offsetHeight : this.standardbody.scrollHeight //Full scroll height of document
var objwidth=divobj.offsetWidth //width of div element
var objheight=divobj.offsetHeight //height of div element
var topposition=(docheight>objheight)? scroll_top+docheight/2-objheight/2+"px" : scroll_top+10+"px" //Vertical position of div element: Either centered, or if element height larger than viewpoint height, 10px from top of viewpoint
divobj.style.left=docwidth/2-objwidth/2+"px" //Center div element horizontally
divobj.style.top=Math.floor(parseInt(topposition))+"px"
divobj.style.visibility="visible"
},

showthumbBox:function(){ //Show ThumbBox div
	this.centerDiv(this.thumbBox)
	if (this.enableAnimation){ //If fading animation enabled
	this.currentopacity=0.1 //Starting opacity value
	this.opacitytimer=setInterval("thumbnailviewer.opacityanimation()", 20)
}
},


loadimage:function(link){ 
if (AG_DisablePop != 1)
{
//Load image function that gets attached to each link on the page with rel="thumbnail"
if (this.thumbBox.style.visibility=="visible") //if thumbox is visible on the page already
this.closeit() //Hide it first (not doing so causes triggers some positioning bug in Firefox
var imageHTML='<img src="'+link.getAttribute("href")+'" style="'+this.opacitystring+'" id="mainImage" />' //Construct HTML for shown image
if (this.enableTitle && link.getAttribute("title")) //Use title attr of the link as description?
{
	imageURL = link.getAttribute("href");
	text = link.getAttribute("title").replace(/\n/g, "<br />");
	imageHTML+='<br /><div style="width: 0px" id="thumbTitle">'+text+"</div>";
	isTitle = true;
}
else
{
	isTitle = false;
}

this.centerDiv(this.thumbLoading) //Center and display "loading" div while we set up the image to be shown
this.thumbImage.innerHTML=imageHTML //Populate thumbImage div with shown image's HTML (while still hidden)
this.featureImage=this.thumbImage.getElementsByTagName("img")[0] //Reference shown image itself
this.featureImage.onload=function(){ //When target image has completely loaded
if (isTitle)
{
	imageWidth = AG_GetImgWidth(imageURL);
	document.getElementById('thumbTitle').style.width = (imageWidth-10) + 'px';
}
thumbnailviewer.thumbLoading.style.visibility="hidden" //Hide "loading" div
thumbnailviewer.showthumbBox() //Display "thumbbox" div to the world!
}
if (document.all && !window.createPopup) //Target IE5.0 browsers only. Address IE image cache not firing onload bug: panoramio.com/blog/onload-event/
this.featureImage.src=link.getAttribute("href")
this.featureImage.onerror=function(){ //If an error has occurred while loading the image to show
thumbnailviewer.thumbLoading.style.visibility="hidden" //Hide "loading" div, game over
}
}
else
{
	AG_DisablePop = 0;
}
},

setimgopacity:function(value){ //Sets the opacity of "thumbimage" div per the passed in value setting (0 to 1 and in between)
var targetobject=this.featureImage
if (targetobject.filters && targetobject.filters[0]){ //IE syntax
if (typeof targetobject.filters[0].opacity=="number") //IE6
targetobject.filters[0].opacity=value*100
else //IE 5.5
targetobject.style.filter="alpha(opacity="+value*100+")"
}
else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
targetobject.style.MozOpacity=value
else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
targetobject.style.opacity=value
else //Non of the above, stop opacity animation
this.stopanimation()
},

opacityanimation:function(){ //Gradually increase opacity function
this.setimgopacity(this.currentopacity)
this.currentopacity+=0.1
if (this.currentopacity>1)
this.stopanimation()
},

stopanimation:function(){
if (typeof this.opacitytimer!="undefined")
clearInterval(this.opacitytimer)
},


closeit:function(){ //Close "thumbbox" div function
this.stopanimation()
this.thumbBox.style.visibility="hidden"
this.thumbImage.innerHTML=""
this.thumbBox.style.left="-2000px"
this.thumbBox.style.top="-2000px"
},

cleanup:function(){ //Clean up routine on page unload
this.thumbLoading=null
if (this.featureImage) this.featureImage.onload=null
this.featureImage=null
this.thumbImage=null
for (var i=0; i<this.targetlinks.length; i++)
this.targetlinks[i].onclick=null
this.thumbBox=null
},

dotask:function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
if (target.addEventListener)
target.addEventListener(tasktype, functionref, false)
else if (target.attachEvent)
target.attachEvent(tasktype, functionref)
},

init:function(){ //Initialize thumbnail viewer script by scanning page and attaching appropriate function to links with rel="thumbnail"
if (!this.enableAnimation)
this.opacitystring=""
var pagelinks=document.getElementsByTagName("a")
for (var i=0; i<pagelinks.length; i++){ //BEGIN FOR LOOP
if (pagelinks[i].getAttribute("rel") && pagelinks[i].getAttribute("rel")=="thumbnail"){ //Begin if statement
pagelinks[i].onclick=function(){
thumbnailviewer.stopanimation() //Stop any currently running fade animation on "thumbbox" div before proceeding
thumbnailviewer.loadimage(this) //Load image
return false
}
this.targetlinks[this.targetlinks.length]=pagelinks[i] //store reference to target link
} //end if statement
} //END FOR LOOP
//Reposition "thumbbox" div when page is resized
this.dotask(window, function(){if (thumbnailviewer.thumbBox.style.visibility=="visible") thumbnailviewer.centerDiv(thumbnailviewer.thumbBox)}, "resize")


} //END init() function

}

thumbnailviewer.createthumbBox() //Output HTML for the image thumbnail viewer
thumbnailviewer.dotask(window, function(){thumbnailviewer.init()}, "load") //Initialize script on page load
thumbnailviewer.dotask(window, function(){thumbnailviewer.cleanup()}, "unload")

var DragHandler = {
    // private property.
    _oElem : null,
	
    // public method. Attach drag handler to an element.
    attach : function(oElem) {
        oElem.onmousedown = DragHandler._dragBegin;

        // callbacks
        oElem.dragBegin = new Function();
        oElem.drag = new Function();
        oElem.dragEnd = new Function();

        return oElem;
    },

    // private method. Begin drag process.
    _dragBegin : function(e) {
        var oElem = DragHandler._oElem = this;

        if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
        if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }

        var x = parseInt(oElem.style.left);
        var y = parseInt(oElem.style.top);

        e = e ? e : window.event;
        oElem.mouseX = e.clientX;
        oElem.mouseY = e.clientY;

        oElem.dragBegin(oElem, x, y);

        document.onmousemove = DragHandler._drag;
        document.onmouseup = DragHandler._dragEnd;
        return false;
    },

    // private method. Drag (move) element.
    _drag : function(e) {
        var oElem = DragHandler._oElem;

        var x = parseInt(oElem.style.left);
        var y = parseInt(oElem.style.top);

        e = e ? e : window.event;
        oElem.style.left = x + (e.clientX - oElem.mouseX) + 'px';
        oElem.style.top = y + (e.clientY - oElem.mouseY) + 'px';

        oElem.mouseX = e.clientX;
        oElem.mouseY = e.clientY;

        oElem.drag(oElem, x, y);

        return false;
    },

    // private method. Stop drag process.
    _dragEnd : function() {
        var oElem = DragHandler._oElem;

        var x = parseInt(oElem.style.left);
        var y = parseInt(oElem.style.top);

        oElem.dragEnd(oElem, x, y);

        document.onmousemove = null;
        document.onmouseup = null;
        DragHandler._oElem = null;
    }
}

function AG_LoadImages(gallery)
{
	if (AG_Data[gallery+'_imagesPerPage'] > AG_Data[gallery+'_maxImages'])
	{
		max = AG_Data[gallery+'_imagesPerPage'];
	}
	else
	{
		max = AG_Data[gallery+'_maxImages'];
	}
	
	num = AG_Data[gallery+'_startNum'];
	for (i=0; i< max; i++)
	{
		container_id = "ajaxg_" + gallery + "_" + i;
		if (document.getElementById(container_id))
		{
			new Ajax.Updater(document.getElementById(container_id), "/plugins/ajax_gallery/file_image.php?gallery="+gallery+"&num="+num);
			num = num + 1;
		}
		else
		{
			break;
		}
	}
}

function AG_Next(gallery)
{
	startPos = AG_Data[gallery+'_startNum'] + 1;
	if ((startPos+AG_Data[gallery+'_imagesPerPage']) <= AG_Data[gallery+'_maxImages'])
	{
		AG_Data[gallery+'_startNum'] = startPos;
		AG_LoadImages(gallery);
	}
	AG_RestyleElements(gallery);
}
function AG_Prev(gallery)
{
	startPos = AG_Data[gallery+'_startNum'] - 1;
	if (startPos >= 0)
	{
		AG_Data[gallery+'_startNum'] = startPos;
		AG_LoadImages(gallery);
	}
	AG_RestyleElements(gallery);
}
function AG_NextPage(gallery)
{
	startPos = AG_Data[gallery+'_startNum'] + AG_Data[gallery+'_imagesPerPage'];
	if ((startPos+AG_Data[gallery+'_imagesPerPage']) < AG_Data[gallery+'_maxImages'])
	{
		AG_Data[gallery+'_startNum'] = startPos;
		AG_LoadImages(gallery);
	}
	else
	{
		maxIndex = (AG_Data[gallery+'_maxImages']-AG_Data[gallery+'_imagesPerPage']);
		if (maxIndex < 0)
		{
			maxIndex = 0;
		}
		if (AG_Data[gallery+'_startNum'] != maxIndex)
		{
			AG_Data[gallery+'_startNum'] = maxIndex;
			AG_LoadImages(gallery);
		}
		// change the class of the next element?
	}
	AG_RestyleElements(gallery);
}
function AG_PrevPage(gallery)
{
	startPos = AG_Data[gallery+'_startNum'] - AG_Data[gallery+'_imagesPerPage'];
	
	if (startPos >= 0)
	{
		AG_Data[gallery+'_startNum'] = startPos;
		AG_LoadImages(gallery);
	}
	else
	{
		if (AG_Data[gallery+'_startNum'] != 0)
		{
			AG_Data[gallery+'_startNum'] = 0;
			AG_LoadImages(gallery);
		}
		// change the class of the next element?
	}
	AG_RestyleElements(gallery);
}

function AG_RestyleElements(gallery)
{
	if (AG_Data[gallery+'_startNum'] == 0)
	{
		document.getElementById('ajaxg_'+gallery+'_prevpage').className = 'previous_page_disabled';
		document.getElementById('ajaxg_'+gallery+'_prev').className = 'previous_disabled';
	}
	else
	{
		document.getElementById('ajaxg_'+gallery+'_prevpage').className = 'previous_page';
		document.getElementById('ajaxg_'+gallery+'_prev').className = 'previous';
	}
	
	if ((AG_Data[gallery+'_startNum']+AG_Data[gallery+'_imagesPerPage']) >= AG_Data[gallery+'_maxImages'])
	{
		document.getElementById('ajaxg_'+gallery+'_nextpage').className = 'next_page_disabled';
		document.getElementById('ajaxg_'+gallery+'_next').className = 'next_disabled';
	}
	else
	{
		document.getElementById('ajaxg_'+gallery+'_nextpage').className = 'next_page';
		document.getElementById('ajaxg_'+gallery+'_next').className = 'next';
	}
	
	if ((AG_Data[gallery+'_startNum']+1) >= AG_Data[gallery+'_maxImages'])
	{
		
	}
	else
	{
		
	}
}

function AG_CheckVar(what)
{
	return Boolean(typeof what != 'undefined' && what);
}

var AG_MovingObject;
var AG_DeleteObject;
var AG_TrashObject;
var AG_EditObject;
var AG_StartX;
var AG_StartY;
var AG_DisablePop = 0;
var AG_SwapImage;
var AG_Alias;
var AG_Edited;

function AG_ToggleDragOn(element, x, y)
{
	AG_MovingObject = element.id;
	element.style.zIndex = 0;
}
function AG_ToggleDragOff(element, x, y)
{
	element.style.zIndex = 1;
	if (AG_CheckVar(AG_DeleteObject))
	{
		if (AG_DeleteObject.length > 0)
		{
			var src = /src\=\"([^\"]+)\"/i.exec(document.getElementById(AG_DeleteObject).innerHTML);
			var thumb = src[1];
			thumb = thumb.replace('http://','');
			var path = thumb.split(/\//);
			//var fileToDelete = path[path.length-1];
			
			var gallery = path[3];
			var image = path[5];

			var url = '/' + path[1] + '/' + path[2] + '/delete_image.php?data='+thumb;
			
			new Ajax.Request(url, {onComplete: function() {AG_Data[gallery+'_startNum'] = 0; AG_Data[gallery+'_maxImages'] = AG_Data[gallery+'_maxImages'] - 1; AG_LoadImages(gallery);}})
		}
	}
	if ((x != 0) && (y != 0))
	{
		AG_ReturnObject(AG_MovingObject, 0, 0);
	}
	
	if (AG_CheckVar(AG_SwapImage))
	{
		if (AG_SwapImage.length > 0)
		{
			var src = /src\=\"([^\"]+)\"/i.exec(document.getElementById(AG_SwapImage).innerHTML);
			var thumb = src[1];
			thumb = thumb.replace('http://','');
			var path = thumb.split(/\//);
			var gallery = path[3];
			var image_dest = path[5];
			
			var src = /src\=\"([^\"]+)\"/i.exec(document.getElementById(AG_MovingObject).innerHTML);
			var thumb = src[1];
			thumb = thumb.replace('http://','');
			var path = thumb.split(/\//);
			var image_src = path[5];

			var url = '/' + path[1] + '/' + path[2] + '/swap_image.php?gallery='+gallery+'&src='+image_src+'&dest='+image_dest;
			
			new Ajax.Request(url, {onComplete: function() { AG_LoadImages(gallery);}})
		}
	}
	
	if (AG_CheckVar(AG_Edited))
	{
		if (AG_Edited.length > 0)
		{
			var src = /src\=\"([^\"]+)\"/i.exec(document.getElementById(AG_Edited).innerHTML);
			var thumb = src[1];
			thumb = thumb.replace('http://','');
			var path = thumb.split(/\//);
			var gallery = path[3];
			var image = path[5];
			
			var url = '/' + path[1] + '/' + path[2] + '/edit_image.php?gallery='+gallery+'&img='+image+'&target='+AG_Alias;
			var editform = document.getElementById('ajaxg_'+gallery+'_editform');
			
			new Ajax.Updater(editform, url, {onComplete: function() { editform.style.display='block' }})
		}
	}
	
	AG_MovingObject = '';
}

function AG_EnterTrash(object)
{
	AG_TrashObject = object;
	if (AG_CheckVar(AG_MovingObject))
	{
		if (AG_MovingObject.length > 0)
		{
			AG_DeleteObject = AG_MovingObject;
		}
	}
}

function AG_LeaveTrash()
{
	AG_DeleteObject = '';
}

function AG_EnterEdit(object, alias)
{
	AG_Alias = alias;
	
	if (AG_CheckVar(AG_MovingObject))
	{
		if (AG_MovingObject.length > 0)
		{
			AG_Edited = AG_MovingObject;
		}
	}
}

function AG_LeaveEdit()
{
	AG_Alias = '';
	AG_Edited = '';
}

function AG_ReturnObject(obj, x, y)
{
	//alert(obj + " " + x + " " + y);
	document.getElementById(obj).style.left = x+"px";
	document.getElementById(obj).style.top = y+"px";
	AG_DisablePop = 1;
}

function AG_CheckSwap(obj)
{
	if (AG_CheckVar(AG_MovingObject))
	{
		if (AG_MovingObject.length > 0)
		{
			if (AG_MovingObject != obj.id)
			{
				obj.className = 'imageHover';
				AG_SwapImage = obj.id;
			}
		}
	}
}

function AG_RemoveHighlight(obj)
{
	obj.className = "image";
	AG_SwapImage = '';
}
