galleryCookie = ReadCookie("AKGallery");if ( galleryCookie == null ) {    CreateCookie("AKGallery", Math.random(), 1000000);    galleryCookie = ReadCookie("AKGallery");}// Constructor for gallery class// scriptPath - Fully qualified path to the directory with the AKGallery files// gallerypath - Fully qualified path to the director with the initial gallery// loaderImage - The image to use to signifiy that a gallery is loadingfunction AKGalleryViewer(scriptPath, galleryPath, loaderImage){    this._loaderImage = loaderImage;    this._numImages = 0;    this._showImageCount = true;    this._allowRanking = 1;    this._scriptPath = scriptPath;    this._galleryPath = galleryPath;    this._mainWidth = 960;    this._mainHeight = 648;    this._mainBorderThickness = 1;    this._mainInsideWidth = this._mainWidth - this._mainBorderThickness * 2;    this._mainInsideHeight = this._mainHeight - this._mainBorderThickness * 2;    this._imageBorderThickness = 1;    this._imageBorderColour = "#082538";    this._thumbAreaInsideWidth = this._mainWidth;    this._thumbAreaInsideHeight = 30;    this._thumbAreaWidth = this._thumbAreaInsideWidth + this._mainBorderThickness * 2;    this._thumbAreaHeight = this._thumbAreaInsideHeight + this._mainBorderThickness * 2;    this._thumbHeight = 30;    this._thumbWidth = 30;    this._thumbSpacing = 1;    this._entireWidth = this._mainWidth + 2;    this._entireHeight = this._mainHeight + this._thumbAreaInsideHeight;    this._firstThumb = 0;    this._thumbsX = 0;    this._thumbsY = 0;    this._selectedImage = -1;    this._thumbsShown = false;    this._thumbsLeftToLoad = 0;    this._noThumbs = true;     // Attach handlers to items as necessary     this._AttachHandlers();}AKGalleryViewer.prototype._AttachHandlers = function(){     var arrow = this._GetElement("AKGalleryNavigationButtonsLeft");     if ( arrow ) {        arrow.onclick = function() { instance._Prev(); return false; };     }     arrow = this._GetElement("AKGalleryNavigationButtonsRight");     if ( arrow ) {        arrow.onclick = function() { instance._Next(); return false; };     }}AKGalleryViewer.prototype.Restart = function(){    this._AttachHandlers();}// Switches the displayed gallery// galleryDirectory - the fully qualified path to directory of the gallery you want to switch toAKGalleryViewer.prototype.SwitchGallery = function(galleryPath){    this._StartLoaderAnimation();    this._SetCurrentGallery(galleryPath);}// "Private" member variablesAKGalleryViewer.prototype._scriptPath;          // Fully qualifed path to the ajax scriptAKGalleryViewer.prototype._galleryPath;          // Fully qualifed path to the gallery that's currently being viewed//=============================================var instance;                                   // To keep track of the instance for callbacks which seem to lose the 'this'. Of course, this means that this                                                // class is effectively a singleton :(. Use it as multiple and it will die. TODO: Fix this// Instantiate and configure Loader:AKGalleryViewer.prototype.Insert = function(){    instance = this;    var loader = new YAHOO.util.YUILoader({        // Identify the components you want to load.  Loader will automatically identify        // any additional dependencies required for the specified components.        require: ["logger", "connection","json", "animation", "imageloader", "container"],        // Configure loader to pull in optional dependencies.  For example, animation        // is an optional dependency for slider.        loadOptional: true,        // The function to call when all script/css resources have been loaded        onSuccess: function() {            instance._Init();        },        // Configure the Get utility to timeout after 10 seconds for any given node insert        timeout: 10000,        // Combine YUI files into a single request (per file type) by using the Yahoo! CDN combo service.        combine: true    });    loader.insert();}// Initialise the entire viewer. Call this once before using the viewer.// Uses the arguments that were setup in the constructor for the paths to the scripts and initial galleryAKGalleryViewer.prototype._Init = function(){    this._SetCurrentGallery(this._galleryPath);}// Initialises the viewer to show a specific galleryAKGalleryViewer.prototype._SetCurrentGallery = function(gallery){    this._selectedImage = -1;    this._thumbsShown = true;    this._SetMainBorder();    this._InitialiseThumbArea(1);    var myAjax = new Ajax.Request(this._scriptPath + '/ajaxtest.php',      {        method:'get',        parameters: { q: gallery},        onComplete: function(transport) {            var response = transport.responseText || "no response text";            data = eval(transport.responseText );            instance._numImages = data.length;            instance._DisplayThumbs(data);            instance._SetViewedImage(0);            if ( data[0].error != "" ) {                //alert("Error! - " + data[0].error);            }            var entireAreaItem = document.getElementById("AKGalleryEntireArea");            if ( entireAreaItem ) {                entireAreaItem.style.visibility = "visible";            }        },        onFailure: function(){         //   alert('Something went wrong...')            },        onException: function(req, exception) {            //alert("Exception during image retrieval:" + exception)        }      }    );}// Returns the CSS id of a specific thumbnail's container// index = the 0 based index of the thumbnails whose id we want to returnAKGalleryViewer.prototype._ThumbDivId = function(index){    return "thumb" + index;}// Returns the CSS id of a specific thumbnail's <img> tag that holds the image// index = the 0 based index of the thumbnails whose id we want to returnAKGalleryViewer.prototype._ThumbDivImgId = function(index){    return this._ThumbDivId(index) + "img";}// Displays all the thumbnails in the thumbnail area.// data - the array of thumbnail objects to use to display the thumbsAKGalleryViewer.prototype._DisplayThumbs = function(data){        var thumbElement;        // Where are the thumbs going?        thumbElement = document.getElementById("AKGalleryThumbContainer");        var html="";        thumbElement.innerHTML = "";//            html += "<div style='float:left;width:80px;height:16px;'><img src='images/left.jpg' class='AKGalleryNavigationButtons'  onclick='instance._Prev(); return false;';></img> \  //          <span id='AKImageCount'></span><img src='images/right.jpg' class='AKGalleryNavigationButtons' onclick='instance._Next(); return false;'></img></div>";        if ( this._noThumbs ) {            thumbElement.innerHTML += html;            thumbElement.style.visibility = "visible";            return;        }        thumbElement.style.visibility = "hidden";        var numVisibleThumbs = Math.min(data.length, this._thumbsX + this._firstThumb);        this._thumbsLeftToLoad = numVisibleThumbs - this._firstThumb;        for (var i = this._firstThumb; i < numVisibleThumbs ; i++) {            var thumbJsPath = data[i].thumbJSPath;            html += '<div id = ' + this._ThumbDivId(i)  +'>';            var style = 'style = "opacity:1; cursor:pointer; float:left; margin-right:2px; border:' + this._GetUnselectedBorderStyle() ;            var adjust = 0;            if ( i == this._selectedImage ) {                style += "; border:" + this._GetSelectedBorderStyle();            }            style += '"';            html += '<img id = "' + this._ThumbDivImgId(i)  + '"' + style + ' onLoad="instance._ThumbLoaded(this)" onclick="instance._ClickImage(' + i + ');" width="' + (this._thumbWidth - adjust) + '" height="' + (this._thumbHeight - adjust) +'" src="' + thumbJsPath + '" /> ';            html += '</div>';        }        thumbElement.innerHTML += html;}AKGalleryViewer.prototype._Next = function(){    this._SetViewedImage(this._selectedImage + 1);}AKGalleryViewer.prototype._Prev = function(){    this._SetViewedImage(this._selectedImage - 1);}// Callback called when a thumb has been loadedAKGalleryViewer.prototype._ThumbLoaded = function(thumb){    if ( Math.max(0,--this._thumbsLeftToLoad) == 0 ) {        thumbElement = document.getElementById("AKGalleryThumbContainer");        thumbElement.style.visibility = "visible";    }}// Initialises the dimensions and limits of the thumbnail areaAKGalleryViewer.prototype._InitialiseThumbArea = function(){    this._thumbAreaWidth = this._mainWidth;    this._thumbAreaHeight = this._thumbHeight + this._thumbSpacing;    this._thumbsX = Math.floor((this._thumbAreaWidth + this._thumbSpacing * 2) / (this._thumbWidth + this._thumbSpacing * 2));    this._thumbsY = this._thumbAreaHeight / (this._thumbHeight + this._thumbSpacing);}// Sets up the main areas of the gallery viewer, sizing all the containers as requiredAKGalleryViewer.prototype._SetMainBorder = function(){    var description = document.getElementById("AKGalleryDescription");    if ( description != null ) {        var thumbBorderItem = document.getElementById("AKGalleryThumbBorder");        if ( thumbBorderItem ) {            description.style.width = thumbBorderItem.style.width;        }    // Need to adjust _entireHeight to take into account presence of the AKGalleryDescription div        this._entireHeight = this._mainHeight + this._thumbAreaInsideHeight + description.offsetHeight;    } else {        this._entireHeight = this._mainHeight + this._thumbAreaInsideHeight;    }    var entireAreaItem = document.getElementById("AKGalleryEntireArea");    entireAreaItem.style.width = this._entireWidth + "px";    entireAreaItem.style.height = this._entireHeight + "px";    var largeImageBorderItem = document.getElementById("AKGalleryLargeImageBorder");    largeImageBorderItem.style.width = this._entireWidth + "px";    largeImageBorderItem.style.height = this._mainHeight + "px";    var thumbBorderItem = document.getElementById("AKGalleryThumbBorder");    thumbBorderItem.style.width = this._thumbAreaWidth + "px";    thumbBorderItem.style.height = this._thumbAreaHeight + "px";}// Shows an item in the main areaAKGalleryViewer.prototype._SetViewedImage = function(index){    if ( index >= this._numImages ) {        return;    }    this._newSelected = index;    this._UpdateImageIndexText(index);    if ( !this._IsFlashMovie(index) ) {        this._FadeOutMainImage();    } else {        this._myOnCompleteFadeOutMainImage();    }}AKGalleryViewer.prototype._GetElement = function(id){    return document.getElementById(id);}AKGalleryViewer.prototype._UpdateImageIndexText = function(index){    var element = this._GetElement('AKImageCount');    if ( element ) {        element.innerHTML = ( (index >= 0) ? index + 1 : 1) + "/" + this._numImages;    }}// Called when a new thumb has been clicked// index = index of the thumb that was clickedAKGalleryViewer.prototype._ClickImage = function(index){    if ( index == this._selectedImage ) {        return;    }    this._IncrementAccess(index);    this._SetViewedImage(index);//    panel1 = new YAHOO.widget.Panel("panel1", { width:"320px", visible:false, constraintoviewport:true } );//panel1.setHeader("Panel #2 from Script");//panel1.setBody("This is a dynamically generated Panel.");//panel1.setFooter("End of Panel #2");//panel1.render('GalleryArea');}AKGalleryViewer.prototype._IncrementAccess = function(index){    var myAjax = new Ajax.Request(this._scriptPath + '/setmetrics.php',      {        method:'get',        parameters: { mode: 1, file: data[index].fulljspath },        onSuccess: function(transport, json) {//            alert(transport.responseText);        },        onFailure: function() {//            alert("Failed");        },        onException: function(req, exception) {//            alert("Exception during metrics:" + exception);        }      });}AKGalleryViewer.prototype._StartLoaderAnimation = function(){    var left = 10;    var width = this._entireWidth;    var height = this._entireHeight;    var loaderImageItem = document.getElementById("AKGalleryLoaderImage");    if ( loaderImageItem ) {        loaderImageItem.style.left = (left + ( width / 2)) + "px";        loaderImageItem.style.top = (height / 2) + "px";        loaderImageItem.innerHTML = '<img src="' + instance._loaderImage + '"/>';        loaderImageItem.style.visibility = "visible";    }}AKGalleryViewer.prototype._StopLoaderAnimation = function(){    var loaderImageItem = document.getElementById("AKGalleryLoaderImage");    if ( loaderImageItem ) {        loaderImageItem.style.visibility = "hidden";    }}// Callback for when the main image as finished fading out.// Shows the selected imageAKGalleryViewer.prototype._myOnCompleteFadeOutMainImage = function(){    var index = instance._newSelected;    var filepath = data[index].fulljspath;    var width = data[index].width;    var height = data[index].height;    var mainImageItem = document.getElementById("AKGalleryMainImage");    mainImageItem.style.visibility = "hidden";    mainImageItem.style.opacity = 0;    mainImageItem.style.position = "relative";    var left = ((instance._mainWidth - width - instance._imageBorderThickness * 2) / 2);    mainImageItem.style.left =  left + "px";    mainImageItem.style.top = Math.round((instance._mainHeight - height - instance._imageBorderThickness * 2) / 2) + "px";    mainImageItem.style.border = instance._imageBorderThickness + "px solid " + instance._imageBorderColour ;    mainImageItem.style.width = width + "px";    mainImageItem.style.height = height + "px";    // If this is a video file, then we add it    if ( instance._IsFlashMovie(index) == true ) {        var s1 = new SWFObject( this._scriptPath + "/player.swf","player","426","320", '9.0.124',"#FFFFFF");        s1.addParam("allowfullscreen","true");        s1.addParam("allowscriptaccess","always");        s1.addParam('wmode','opaque');        s1.addParam("flashvars","file=" + data[index].flvjspath + "&image=" + filepath);        s1.write('AKGalleryMainImage');        mainImageItem.style.opacity = 1;        mainImageItem.style.visibility = "visible";        mainImageItem.style.border = instance._imageBorderThickness + "px solid black" ;    } else {        $(mainImageItem).innerHTML = '<img onLoad="instance._MainImageLoaded()" src="' + filepath + '"/>';        instance._SetRankHtml(index);//        alert(data[index].rank);    }    var description = document.getElementById("AKGalleryDescription");    if ( description ) {        if ( data[index].description.length > 0 ) {            description.innerHTML = data[index].description;        } else {            description.innerHTML = "";        }    }    if ( !instance._noThumbs ) {        var thumbObject = document.getElementById("'" + instance._ThumbDivId(instance._selectedImage) + "'");        step = Math.round(instance._thumbsX / 2);        if ( index == instance._firstThumb ) {            instance._firstThumb = Math.max(instance._firstThumb-step, 0);        }        if ( index == instance._firstThumb + instance._thumbsX - 1 ) {            instance._firstThumb = Math.min(instance._firstThumb + step, data.length - instance._thumbsX);        }        instance._ChangeSelectedThumb(index);        instance._DisplayThumbs(data);        thumbElement.style.visibility = "visible";    } else {        instance._selectedImage = index;    }//    instance._UpdateImageIndexText();}AKGalleryViewer.prototype._SetRankHtml = function(index){    if ( !this.allowRanking ) {        return;    }//    alert(data[index].rank);    var entireArea = document.getElementById("AKGalleryRankArea");    if ( entireArea != null) {        var html = "<div>";        var averageRank =  data[index].rankcount > 0 ? data[index].rank / data[index].rankcount : 0;//        alert(data[index].rank + " " + data[index].rankcount);        entireArea.style.opacity = 1;        for( i = 0; i < averageRank; ++i ) {            html += '<img onclick="instance._RankIt(' + index + ',' + (i+1) + ');" src="' + instance._scriptPath + '/star.png" style="cursor: pointer;width:16px ;height:16px; float:left">';        }        for( ; i < 5; ++i ) {            html += '<img onclick="instance._RankIt(' + index + ',' + (i+1) + ');" src="' + instance._scriptPath + '/staroff.png" style="cursor: pointer;width:16px ;height:16px; float:left">';        }        entireArea.innerHTML = html + "</div>";    }}AKGalleryViewer.prototype._RankIt = function(index, rank){//    alert(galleryCookie);    var myAjax = new Ajax.Request(this._scriptPath + '/setmetrics.php',      {        method:'get',        parameters: { mode: 2, file: data[index].fulljspath, rank: rank, cookie: galleryCookie },        onComplete: function(transport, json) {            if ( transport.responseText == "true" ) {                data[index].rank = data[index].rank * 1 + rank; // The *1 turns data[index].rank into a number, because it comes back as a string                data[index].rankcount++;                instance._SetRankHtml(index);                instance._ShowThanksForRanking();            }//            alert(transport.responseText);        },        onFailure: function() {//            alert("Failed");        },        onException: function(req, exception) {//            alert("Exception during metrics:" + exception);        }      });}AKGalleryViewer.prototype._ShowThanksForRanking = function(){        /*    try {        var myAnim = new YAHOO.util.Anim('AKGalleryRankArea', {                left: { to: 100 }        }, 2, YAHOO.util.Easing.easeOut);        myAnim.onComplete.subscribe(this._FinishedFadingRankHtml);    } catch(e)    {    }    myAnim.animate();       */}AKGalleryViewer.prototype._FinishedFadingRankHtml = function(){    var entireArea = document.getElementById("AKGalleryRankArea");    if ( entireArea != null) {        html = '<div style="color:white">Thanks</div>';        entireArea.innerHTML = html;    }}AKGalleryViewer.prototype._FadeOutMainImage = function(){    try {        var myAnim = new YAHOO.util.Anim('AKGalleryMainImage', {                opacity: { to: 0 }        }, 0.1, YAHOO.util.Easing.easeNone);        myAnim.onComplete.subscribe(this._myOnCompleteFadeOutMainImage);    } catch(e)    {//        alert(e);    }    myAnim.animate();}// Called once the main image as finished loadingAKGalleryViewer.prototype._MainImageLoaded = function(){    this._StopLoaderAnimation();    try {        var mainImageItem = document.getElementById("AKGalleryMainImage");        mainImageItem.style.visibility="visible";        var myAnim = new YAHOO.util.Anim('AKGalleryMainImage', {                opacity: { to: 1 }                }, 0.1, YAHOO.util.Easing.easeNone);    } catch(e)    {//        alert(e);    }    myAnim.animate();}// Call this to change which thumbnail is currently selected.// Redraws the bordersAKGalleryViewer.prototype._ChangeSelectedThumb = function(index){    for (var i = this._firstThumb; i < Math.min(data.length, this._thumbsX + this._firstThumb) ; ++i) {        if ( i == this._selectedImage ) {            var item = document.getElementById(this._ThumbDivImgId(i));            item.style.border = this._GetUnselectedBorderStyle();        }        if ( i == index ) {            var item = document.getElementById(this._ThumbDivImgId(i));            item.style.border = this._GetSelectedBorderStyle();        }    }    this._selectedImage = index;}// Returns a style string for the look of the selected thumb borderAKGalleryViewer.prototype._GetSelectedBorderStyle = function(){    return this._thumbSpacing + "px solid white";}// Returns a style string for the look of an unselected thumb borderAKGalleryViewer.prototype._GetUnselectedBorderStyle = function(){    return 'solid ' + this._thumbSpacing + 'px gray';}// Returns whether an item is a movie or not// index - the index of the gallery item too checkAKGalleryViewer.prototype._IsFlashMovie = function(index){    return data[index].flvjspath != "";}function CreateCookie(name,value,days) {	if (days) {		var date = new Date();		date.setTime(date.getTime()+(days*24*60*60*1000));		var expires = "; expires="+date.toGMTString();	}	else var expires = "";	document.cookie = name+"="+value+expires+"; path=/";}function ReadCookie(name) {	var nameEQ = name + "=";	var ca = document.cookie.split(';');	for(var i=0;i < ca.length;i++) {		var c = ca[i];		while (c.charAt(0)==' ') c = c.substring(1,c.length);		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);	}	return null;}function EraseCookie(name) {	createCookie(name,"",-1);}
