﻿/*
Web Piston Photo Album Script
Displays photo albums in thumbnailpages/photos/slideshows
Author: Matt Munday
Copyright: Web Piston
*/
 if(getLangFromBrowser() == 'es'){
    LANG_STARTSLIDE='Empezar Diapositivas';
 }else{
    LANG_STARTSLIDE='Start Slideshow';
 }
  
  
/*
Album templates
*/
    /*zoomed photo template*/
    ALBM_PHOTO_TEMPLATE = '<table align="center" style="margin:auto"><tr><td><img width="500" id="photo0" onload="" src="[[SRC]]"/></td></tr><tr><td><a href="javascript:window.location.href=replaceQueryVariable(\'ph\')">back</a></td></tr></table>';
         
    /*Thumbnail template*/
    ALBM_THUMB_TEMPALTE = '<a href="javascript:PhotoAlbum.prototype.OnThumbClick([[IDX]]);" onmouseover="PhotoAlbum.prototype.OnThumbMouseOver([[IDX]]);" onmouseout="PhotoAlbum.prototype.OnThumbMouseOut([[IDX]]);" ><img id="photo[[IDX]]" onload="" id="photo" border="0" src="[[SRC]]" width="[[WIDTH]]" /></a>';
    
    /*Page row template*/
    ALBM_ROW_TEMPLATE = '<tr id="photorow">[[COLUMNS]]</tr>';
    
    /*Page column template*/
    ALBM_COL_TEMPALTE = '<td id="photocolumn">[[PHOTO]]</td>';
    
    /*Photo portion template*/
    ALBM_PHOTOS_TEMPLATE = '<table id="photoalbum" cellspacing="15" align="center">[[CONTENT]]</table>';
    
    /*Description portion template ( not used right now)*/
    ALBM_DESC_TEMPALTE='<table cellspacing="15"><tr><td valign="top"><h2>[[TITLE]]</h2>[[DESCRIPTION]]</td></tr></table>';
    
    /*Main page template*/
    ALBM_MAIN_TEMPLATE = '<table align="center" style="margin:auto;"><tr><td>[[ALBUM]]</td></tr></table>';
    
    /*page links list template*/
    ALBM_PAGEBAR_TEMPLATE = '<table width="100%"><tr><td align="left">[[PAGES]]</td><td align="right"><a href="javascript:document.location.href = replaceQueryVariable(\'ss\',\'1\');">' + LANG_STARTSLIDE + '</a></td></tr></table>';
    
    /*slideshow template*/
        SS_TEMPLATE = '<table align="center" style="margin:auto" width="501" border="0" cellpadding="0" cellspacing="0">' +
        '<tr>' +
        '   <td>' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_01.gif" width="9" height="27" alt=""></td>' +
        '   <td colspan="5">' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_02.gif" width="444" height="27" alt=""></td>' +
        '   <td>' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_03.gif" class="albumbtn" width="36" height="27" alt="Exit" border="0" onclick="javascript:document.location.href =replaceQueryVariable(\'ph\',null,replaceQueryVariable(\'ss\',null));"></td>' +
        '   <td>' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_04.gif" width="12" height="27" alt=""></td>' +
        '</tr>' +
        '<tr>' +
        '   <td colspan="8">' +
        '   [[SS_IMG]]' +
        '   </td>' +
        '</tr>' +
        '<tr>' +
        '   <td>' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_06.gif" width="9" height="53" alt=""></td>' +
        '   <td>' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_07.gif" class="albumbtn" width="35" height="53" alt="Previous" title="Previous" onclick="ss_obj.previous();"></td>' +
        '   <td>' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_08.gif" width="158" height="53" alt=""></td>' +
        '   <td>' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_09.gif" class="albumbtn" width="46" height="53" alt="Enlarge" title="Enlarge"" onclick="ss_obj.onEnlargeClick();"></td>' +
        '   <td>' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_pause.gif" class="albumbtn" id="playpause" onclick="ss_obj.toggleplay();" width="46" height="53" alt="Pause" title="="Pause"></td>' +
        '   <td>' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_11.gif" width="159" height="53" alt=""></td>' +
        '   <td>' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_12.gif" class="albumbtn" width="36" height="53" alt="Next" title="Next" onclick="ss_obj.next();"></td>' +
        '   <td>' +
        '       <img src="http://login.webpiston.com/images/photoalbum/slideshow_controls_13.gif" width="12" height="53" alt=""></td>' +
        '</tr>' +
        '</table>'
/*
End Album templates
*/
     
/* 
Photo album object
Displays photos in paged and zoomed views
Author: Matt Munday
Copyright: Web Pistton
*/
    /*Constructor*/
    function PhotoAlbum(photos){
        this._photos = Array;
        this._hrefs=photos;
        this._failedCount=0;
        this._loadedCount=0;
        this._totalImages = photos.length;
        this._rows=2;
        this._cols=3;
        this._itmsperpage = this._rows * this._cols;
    }
     
    /*
    PhotoAlbum member variables
    */
    
    /*collection of Photo Objects*/
    PhotoAlbum.prototype._photos;
    /*hrefs of each image*/
    PhotoAlbum.prototype._hrefs;
    /*total number of images in the album*/
    PhotoAlbum.prototype._totalImages;
    /*count of images that failed to load*/
    PhotoAlbum.prototype._failedCount;
    /*count of successfully loaded images*/
    PhotoAlbum.prototype._loadedCount;
    /*the current page being displayed*/
    PhotoAlbum.prototype._page;
    /*the index of the last image on the page*/
    PhotoAlbum.prototype._pageend;
    /*default thumbnail height*/
    PhotoAlbum.prototype._thumb_height=150;
    /*default thumbnail width*/
    PhotoAlbum.prototype._thumb_width=150;
    /*bool is slide show active?*/
    PhotoAlbum.prototype._slideshow_active;
    /*number of rows to draw*/
    PhotoAlbum.prototype._rows;
    /*number of colums per row*/
    PhotoAlbum.prototype._cols;
    /*number of items allowed on the page*/
    PhotoAlbum.prototype._itmsperpage;
    /*number of items allowed on the page*/
    PhotoAlbum.prototype._ss;
    /*
    End PhotoAlbum member variables
    */
    
    /*
    event functions
    */
     
    /*OnstatusChange can be overwritten to draw a progressbar*/
    PhotoAlbum.prototype.OnStatusChange;
     
    /*OnThumbClick can be overwritten to change thumbnail click action*/
    PhotoAlbum.prototype.OnThumbClick = function(idx){
        document.location.href= replaceQueryVariable('ph', parseInt(idx));//'?p=' + getQueryVariable('p') + '&l=1&ph=' + idx;
    }
     
    /*OnThumbMouseOver can be overwritten to change thumbnail mouse over action*/
    PhotoAlbum.prototype.OnThumbMouseOver = function(){};
     
    /*OnThumbMouseOut can be overwritten to change thumbnail mouse out action*/
    PhotoAlbum.prototype.OnThumbMouseOut = function(){};
     
    /*Fires when loading status of any image in the album changes*/
    PhotoAlbum.prototype.StatusChanged = function(status,obj){
        if(status)
            obj._album._loadedCount+=1;
        else
            obj._album._failedCount+=1;
        
        if((obj._album._loadedCount + obj._album._failedCount) >= obj._album.getTotalImagesOnPage())
            obj._album.OnStatusChange(obj._album._loadedCount,obj._album._failedCount,true);
        else
            obj._album.OnStatusChange(obj._album._loadedCount,obj._album._failedCount,false);
    }
    /*
    end event functions
    */
     
    /* 
    getTotalImagesOnPage
    Gets a count of the images on the current page 
    */
    PhotoAlbum.prototype.getTotalImagesOnPage = function(){
        var zoomPhoto = getQueryVariable('ph');
        if(isNaN(zoomPhoto))
            return (this._pageend - this._offset)
        else
            return 1;
    }
     
    /* 
    LoadImages
    Loads the images for the current page
    */
    PhotoAlbum.prototype.LoadImages = function(hrefs) {
        var count = hrefs.length;
        this._offset=0;
        this._page = getQueryVariable('p');
        
        if(isNaN(this._page))
            this._page=0; 
        
        if(! isNaN(arguments[1]))
            this._offset = arguments[1];
        
        this._totalImages = count;
        
        this._pageend = Math.min(this._itmsperpage*(parseInt(this._page)+1), this._totalImages);
        
        this.OnStatusChange(0,0,false)
        
        for(x=this._offset;x<this._pageend;x++){
            this._photos[x] = (new Photo);
            this._photos[x]._album = this;
            this._photos[x].OnStatusChange = PhotoAlbum.prototype.StatusChanged;
            this._photos[x].Load(hrefs[x]);
        }
    }
     
      /* 
          getPageList
          Gets a hyperlinked list of the pages in the album
      */
        PhotoAlbum.prototype.getPageList = function(){
            var pagecount = Math.ceil(parseFloat(this._totalImages)/parseFloat(this._itmsperpage));
            var curpage = parseInt(this._page)+1
            var ret = '';
            var num = 0;
            
            if(curpage > 1 && pagecount > 1){
                ret+= '<a href="javascript:document.location.href=replaceQueryVariable(\'p\',\'' + (curpage-2)  + '\');">&lt;</a>&nbsp';
            }
    
            for(x=0;x<pagecount;x++){
                num = x+1;
                if(num==curpage)
                    ret+= '<b>' + num + '</b>&nbsp;';
                else
                    ret+= '<a href="javascript:document.location.href=replaceQueryVariable(\'p\',\'' + x + '\');">' + num + '</a>&nbsp;';
            }
    
            if(pagecount > curpage){
                ret+= '<a href="javascript:document.location.href=replaceQueryVariable(\'p\',\'' + (curpage)  + '\');">&gt;</a>&nbsp';
            }       
    
            return ret;
        }

     
     /* 
      draw
      draws the album
     */
    PhotoAlbum.prototype.draw = function(targetelemId){
        var tmpcol;
        var tmprow;
        var tmpimg;
        var outelem = document.getElementById(targetelemId);
        var output;
        var loaded = getQueryVariable('l');
        var zoomPhoto = getQueryVariable('ph');
        var slideshow = getQueryVariable('ss');
        this._page = getQueryVariable('p');
        
        if(isNaN(this._page))
            this._page=0; 
        
        var imgcounter=this._page * this._itmsperpage; 
        this.LoadImages(this._hrefs,imgcounter);
        
        if(!isNaN(slideshow)){
            this._ss = new SlideShow(targetelemId, this._hrefs, 0);
            this._ss.draw();
            return;
        }else if(!isNaN(zoomPhoto)){
            this._ss = new SlideShow(targetelemId, this._hrefs, zoomPhoto);
            this._ss.draw();
            this._ss.toggleplay();
            clearTimeout(ref);
            return;
        }else{
            if(this._pageend<=this._offset){
                return;
            }
            
            tmprow='';
            
            for(r=1;r<=this._rows;r++){
                tmpcol='';
                for(c=1;c<=this._cols;c++){
                    tmpimg='';
                    if(imgcounter < this._pageend){
                    img = this._hrefs[imgcounter];
                        size = this.getThumbSize(this._photos[imgcounter]._img);
                        tmpimg = ALBM_THUMB_TEMPALTE.replace(/\[\[SRC\]\]/gi,img);
                        tmpimg = tmpimg.replace(/\[\[WIDTH\]\]/gi,size[0]);
                        tmpimg = tmpimg.replace(/\[\[HEIGHT\]\]/gi,size[1]);
                        tmpimg = tmpimg.replace(/\[\[IDX\]\]/gi,imgcounter);
                        imgcounter++;
                    }else
                        break;
                    tmpcol += ALBM_COL_TEMPALTE.replace(/\[\[PHOTO\]\]/gi,tmpimg);
                }
                tmprow += ALBM_ROW_TEMPLATE.replace(/\[\[COLUMNS\]\]/gi,tmpcol);
            }
            
            output = ALBM_PHOTOS_TEMPLATE.replace(/\[\[CONTENT\]\]/gi,tmprow)
            output = output.replace(/(\<tr id\=\"photorow\"\>\<\/tr\>)/gi,'')
            output += ALBM_PAGEBAR_TEMPLATE.replace(/\[\[PAGES\]\]/gi,this.getPageList());
            output = ALBM_MAIN_TEMPLATE.replace(/\[\[ALBUM\]\]/gi,output)
        }
        
        
        outelem.innerHTML=output;
    }
     
     /* 
      getThumbSize
      gets the scaled dimensions of an image 
      (scaled to _thumb_width or _thumb_height)
     */
    PhotoAlbum.prototype.getThumbSize = function(img){ 
        var targetW;
        var targetH;
        var base;
        var ret;
        var w,h;
        if(!isNaN(arguments[1]))
            targetW=arguments[1];
        else
            targetW = this._thumb_width;
        
        if(!isNaN(arguments[2]))
            targetH=arguments[2];
        else
            targetH = this._thumb_height;
        
        w = img.width;
        h = img.height;
        
        if(w==0)
            w=this._thumb_width;
        
        if(h==0)
            h=this._thumb_height;
        
        if(w<=targetW && h<=targetH)
            return [w,h];
        
        if(w>h){
            base = targetW/w;
        }else{
            base = targetH/h;
    }
    
    return [parseInt(w*base),parseInt(h*base)];
    
    
    }
     
     
     
 /*
  Slideshow object
  Displays a slideshow of images
  Author: Matt Munday
   Copyright: Web Pistton
 */
    var ss_obj;
    var ref;
    function SlideShow(elemId,hrefs,startIdx){
        this._elem=document.getElementById(elemId);
        this._hrefs = hrefs;
        this._current_photo=startIdx;
        this._interval = 5000;
        ss_obj = this;
    }
     
    SlideShow.prototype._elem;
    SlideShow.prototype._hrefs;
    SlideShow.prototype._interval=5000;
    SlideShow.prototype._paused;
    SlideShow.prototype._photo_height;
    SlideShow.prototype._photo_width;
    SlideShow.prototype._current_photo;
    SlideShow.prototype._back_buffer;
    SlideShow.prototype._canvas;
    SlideShow.prototype._controls;
     
    SlideShow.prototype.onEnlargeClick = function(){
        window.open(this._hrefs[this._current_photo]);
    }
     
    SlideShow.prototype.draw = function(){
        this._elem.innerHTML = '';
        this._elem.innerHTML += SS_TEMPLATE.replace('\[\[SS_IMG\]\]','<img alt="canvas" id="ss_canvas_img" src="' + this._hrefs[this._current_photo] + '" width="500" >');
        ref = setTimeout("ss_obj.initSwap()",ss_obj._interval);
    }
     
    SlideShow.prototype.next = function(){
        ss_obj._paused=true;
        clearTimeout(ref);
        ss_obj.swap(1);
    }
     
     
    SlideShow.prototype.previous = function(){
        ss_obj._paused=true;
        clearTimeout(ref);
        ss_obj.swap(-1);
    }
    
    SlideShow.prototype.toggleplay = function(){
        var btn = document.getElementById('playpause');
        if(ss_obj._paused==true){
            ss_obj.play();
            btn.alt = 'Pause';
            btn.title = 'Pause';
            btn.src='http://login.webpiston.com/images/photoalbum/slideshow_controls_pause.gif';
        }else{
            ss_obj.pause();
            btn.alt = 'Play';
            btn.title = 'Play';
            btn.src='http://login.webpiston.com/images/photoalbum/slideshow_controls_play.gif';
            
        }
    }
    
    SlideShow.prototype.pause = function(){
        ss_obj._paused=true;
        clearTimeout(ref);
        
    }
     
    SlideShow.prototype.play = function(){
        ss_obj._paused=false;
        clearTimeout(ref);
        ss_obj._initswap();
    }
     
    SlideShow.prototype._initswap = function(){
        if(!ss_obj._paused)
            ref = setTimeout("ss_obj.swap(1)",ss_obj._interval);
    }
     
    SlideShow.prototype.initSwap = function(){ 
        ss_obj._initswap(); 
    }
     
    SlideShow.prototype.swap = function(dir){
        var canvas_img = document.getElementById('ss_canvas_img');
        
        var next = parseInt(ss_obj._current_photo) + parseInt(dir)
        
        if(parseInt(next) > parseInt(ss_obj._hrefs.length-1)){
            next=0;
        }else if(parseInt(next) < 0){
            next=ss_obj._hrefs.length-1;
        }
        
        img = new Image()
        img.src=ss_obj._hrefs[next]
        canvas_img.src = img.src
        
        ss_obj._current_photo = next;
        
        
        if(!ss_obj._paused){
            ss_obj.initSwap();
        }
    }
     
     
 /*
  Photo object
  preloads and stores a single image with caption
  Author: Matt Munday
  Copyright: Web Pistton
 */
     
    function Photo(){
          this._img = new Image;
          this._caption='';
          this._loaded=false;
          this._errored=false;
    }
     
     Photo.prototype._img;
     Photo.prototype._caption;
     Photo.prototype._loaded;
     Photo.prototype.OnStatusChange;
     Photo.prototype._errored;
     Photo.prototype._album;
     
     
    Photo.prototype.onLoad = function(){
        this.oPhoto._loaded=true;
        this.oPhoto.OnStatusChange(true,this.oPhoto);
    }
     
    Photo.prototype.onError = function(){
        if(!this.oPhoto._loaded && !this.oPhoto._errored){
            this.oPhoto._errored=true;
            this.oPhoto.OnStatusChange(false,this.oPhoto);
        }
    }
     
    Photo.prototype.Load = function(){
        if(arguments[1])
            this._caption = arguments[1];
        
        this._img.oPhoto = this;
        this._img.onload = Photo.prototype.onLoad;
        this._img.onError = Photo.prototype.onError;
        this._img.onAbort = Photo.prototype.onError;
        this._img.src = arguments[0];
    
    }
     
     
/*Misc Functions*/
    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable)
                return pair[1];
        } 
        return variable;
    }
     
    function addQueryVariable(variable,value) {
        var query = window.location.search.substring(1);
        
        if( query.length > 0 )
            query = window.location.href + '&' + variable + '=' + value;
        else
            query = window.location.href + '?' + variable + '=' + value;
        
        return query;
    }
     
    function replaceQueryVariable(variable,value){
        
        var query;
        if(arguments[2]){
            query = arguments[2].split("?")[1];
        }else{ 
            query = window.location.search.substring(1);
        }
        var vars = query.split("&");
        var ret = '?';
        var found=false;
            for (var i=0;i<vars.length;i++) {
                var pair = vars[i].split("=");
                if (pair[0] != variable) {
                    if(ret.length>1) ret += "&";
                    ret += vars[i];
                }else{
                    found=true
                
                if(value!=null){
                    if(ret.length>1) ret += "&";
                    ret += pair[0]  + '=' + value
                }
            }
        }
        
        if(!found){
            if(value!=null){
                if(ret.length<=1){
                    ret += variable  + '=' + value
                }else
                    ret += '&' + variable  + '=' + value
            }
        }
        
        var loc = window.location.href.split('?')[0];
        return (loc + ret);
        
    }
     
    function getAttributeValue(node,attrname){
        if(!document.all){
            for(x=0;x<node.attributes.length;x++){
                var attr = node.attributes.item(x);
                if(attr.nodeName.toUpperCase()==attrname.toUpperCase()){
                    return(attr.nodeValue);
                }
            }
        }else{
            try{
                return node.attributes[attrname].value;
            }catch(e){}
        }
        
        return('');
    }
    
    function pause(millis)
    {
    date = new Date();
    var curDate = null;
    
    do { var curDate = new Date(); }
    while(curDate-date < millis);
    } 
     
     
     /*Misc Display Functions*/
    function setOpacity(obj, opacity) {
        if(!obj)return;
        opacity = (opacity >= 100)?99.999:opacity;
        /*IE/Win*/
if(opacity >= 0) {                  
          obj.style.filter = "alpha(opacity:"+opacity+")";
}else if(opacity >100){
obj.style.filter = "";
}else if(opacity < 0){
obj.style.filter = "alpha(opacity:0)";
}
        /*Safari<1.2, Konqueror*/
        obj.style.KHTMLOpacity = opacity/100;
        /* Older Mozilla and Firefox*/
        obj.style.MozOpacity = opacity/100;
        /* Safari 1.2, newer Firefox and Mozilla, CSS3*/
        obj.style.opacity = opacity/100;
    }
    
    function getOpacity(obj) {
        return( obj.style.opacity )
    }
     
    function fadeIn(objId,opacity) {
        if (document.getElementById) {
            obj = document.getElementById(objId);
            if (opacity < 100) {
                setOpacity(obj, opacity);
                opacity += 10;
                window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 10);
            }else
setOpacity(obj, 100);
        }
    }
     
    function fadeout(objId,opacity,speed){
        if (document.getElementById) {
            obj = document.getElementById(objId);
            if (opacity >= 0) {
                setOpacity(obj, opacity);
                opacity -= 10;
                window.setTimeout("fadeout('"+objId+"',"+opacity+"," + speed +")", speed);
            }
        }
    }
     
    function fadeout(objId,opacity,speed,callback){
        if (document.getElementById) {
            obj = document.getElementById(objId);
            if (opacity >= 0) {
                setOpacity(obj, opacity);
                opacity -= 10;
                fade = window.setTimeout("fadeout('"+objId+"',"+opacity+"," + speed +")", speed);
            }else{
                callback;
            }
        }
    }
     
    function FadeInAll(objId){
        var imgs = document.getElementsByTagName('img');
        
        var id;
        for(i=0;i<imgs.length;i++){
            id = getAttributeValue(imgs[i],'id');
            obj = document.getElementById(id);
            if(id!='' && id!=window.undefined){
                dimin(id,50,100);
            }
        }
    }
         
    function mozImgFix(album){
        var imgs = document.getElementsByTagName('img');
        var id;
        for(i=0;i<imgs.length;i++){
            id = getAttributeValue(imgs[i],'id');
            obj = document.getElementById(id);
            if(id!='' && id!=window.undefined){
                tmp = album.getThumbSize(album._photos);
                obj.style.width=tmp[0];
                obj.style.height=tmp[1];
            }
        } 
    } 

    function getLangFromBrowser(){
       if(document.all)
            var m = navigator.browserLanguage;
       else
            var m = navigator.language;
       
       m=m.substring(0,2);
       return m.toLowerCase();
       
    }
