function pictureShow(element){
  element.nextSibling.className = 'pictureFullSizeVisible';
}
function pictureHide(element){
  element.className = 'pictureFullSizeInvisible';
} 

function resizeFlash( uid, h, fullsize ) {
    var heightOfThumbails;
    if ( fullsize ) {
        heightOfThumbails = document.getElementById(uid + "_C").height;
        document.getElementById(uid + "_B").style.border = "1px solid black";
        document.getElementById(uid + "_B").style.top = "-" + ((parseInt(h) / 2) - (parseInt(heightOfThumbails) / 2)) + "px";
    } else {
        document.getElementById(uid + "_B").style.border = "none";
        document.getElementById(uid + "_B").style.top = "0";
        document.getElementById(uid + "_A").style.height = h + "px";
    }
  document.getElementById(uid + "_C").style.height = h + "px";
  document.getElementById(uid + "_D").style.height = h + "px";
}
function stripAt(str) {
    
   var res, pos, atstr;
   atstr = "(specialcharacter)";
   pos = str.indexOf(atstr);
   if (pos<0) return str;

   res = str.substring(0, pos) + "@" + str.substring(pos+atstr.length, str.length);

   return res;
}

function JGImage(thumbPath, imagePath, caption, width, height) {
    this.thumbPath = thumbPath;
    this.imagePath = imagePath;
    this.caption = caption;

    this.originalWidth = width;
    this.originalHeight = height;
}

function JGContext (galleryID) {

    this.galleryID = galleryID;
    this.galleryTitle = "";

    this.thumbWidth = 100;
    this.thumbHeight = 100;

    this.fullscreenDivID = "";
    this.imageViewDivID = "";
    this.imageLoaderDivID = "";
    this.titleDivID = "";
    this.captionDivID = "";
    this.pauseButtonID = "";
    this.playButtonID = "";

    this.rotateAutoPlay = true;
    this.intervalDuration = 3000;
    this.intervalID = null;

    this.currentThumbPage = 0;
    this.currentImage = 0;

    this.rows = 2;
    this.cols = 2;

    this.images = [];

    this.thumbsPerPage = 4;
    this.totalPics = 0;
    this.maxPages = 1;


    this.initialize = function() {
        JGGetStyleClass('JGGalleryThumbCell').style.width = this.thumbWidth + 'px';
        JGGetStyleClass('JGGalleryThumbCell').style.height = this.thumbHeight + 'px';
        JGGetStyleClass('JGThumbnailClick').style.width = this.thumbWidth + 'px';
        JGGetStyleClass('JGThumbnailClick').style.height = this.thumbHeight + 'px';
        /*
        if (JGIsIE()) {
            JGGetStyleClass('JGFullscreen').style.background = "transparent";
            JGGetStyleClass('JGFullscreen').style.filter = "progid:DXImageTransform.Microsoft.gradient(startColorstr=#F20A0A0A,endColorstr=#F20A0A0A)";
            JGGetStyleClass('JGFullscreen').style.zoom = "1";
        }
         */

        this.thumbsPerPage = this.rows * this.cols;
        this.totalPics = this.images.length;
        this.maxPages = Math.ceil(this.totalPics / this.thumbsPerPage);
        this.fullscreenDivID = this.galleryID + "-fullscreen";
        this.imageViewDivID = this.galleryID + "-imageview";
        this.imageLoaderDivID = this.galleryID + "-imageloader";
        this.playButtonID = this.galleryID + "-playbutton";
        this.pauseButtonID = this.galleryID + "-pausebutton";
        this.titleDivID = this.galleryID + "-title";
        this.captionDivID = this.galleryID + "-caption";
    }

    this.buildFullscreenDivIfNecessary = function() {
        if (document.getElementById(this.fullscreenDivID) == null) {
            var newdiv = document.createElement('div');
            newdiv.setAttribute('id', this.fullscreenDivID);
            newdiv.setAttribute('class', 'JGFullscreen');
            newdiv.setAttribute('className', 'JGFullscreen');
            newdiv.innerHTML = '<div id="' + this.titleDivID + '" class="JGFullscreenTitle">' + this.galleryTitle + '</div> \
                                <div id="' + this.captionDivID + '" class="JGFullscreenCaption"></div> \
                                <div class="JGFullscreenControl"> \
                                    <a href="javascript:JGFullscreenOff('+ this.galleryID +')" class="JGButtonLink"><img class="JGFullscreenFullscreenButton" src="widgets/35/fullscreen.png" alt="Fullscreen"/></a> \
                                    <a href="javascript:JGPreviousItem('+ this.galleryID +')" class="JGButtonLink"><img class="JGFullscreenPreviousButton" src="widgets/35/left.png" alt="Previous"/></a> \
                                    <a href="javascript:JGPause('+ this.galleryID +')" class="JGButtonLink"><img id="' + this.pauseButtonID + '" class="JGFullscreenPauseButton" src="widgets/35/pause.png" alt="Pause"/></a> \
                                    <a href="javascript:JGPlay('+ this.galleryID +')" class="JGButtonLink"><img id="' + this.playButtonID + '" class="JGFullscreenPlayButton" src="widgets/35/play.png" alt="Play"/></a> \
                                    <a href="javascript:JGNextItem('+ this.galleryID +')" class="JGButtonLink"><img class="JGFullscreenNextButton" src="widgets/35/right.png" alt="Next"/></a> \
                                </div> \
                                <img id="' + this.imageViewDivID + '" src="" alt="Image" class="JGImageView" />';
            document.body.appendChild(newdiv);
        }
    }


    this.hideFullscreen = function() {
        document.getElementById(this.fullscreenDivID).style.display = "none";

        document.onkeydown = null;
        window.onmousewheel = document.onmousewheel = null;
    }

    this.showFullscreen = function() {
        this.buildFullscreenDivIfNecessary();
        JGCurrentContext = this;

        window.onresize = JGResizeImage;
        document.onkeydown = JGKeyPressed;
        window.onmousewheel = document.onmousewheel = JGMouseWheelEvent;

        JGShowImage(this);
        document.getElementById(this.fullscreenDivID).style.display = "inline";
    }


}

//*** RESIZE **************************************************************************

var JGCurrentContext;
function JGResizeImage() {
   var windowWidth = 0, windowHeight = 0;
   var image = JGCurrentContext.images[JGCurrentContext.currentImage];

   if (typeof(window.innerWidth) == 'number') {
       //Non-IE
       windowWidth = window.innerWidth;
       windowHeight = window.innerHeight;
   } else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
       //IE 6+ in 'standards compliant mode'
       windowWidth = document.documentElement.clientWidth;
       windowHeight = document.documentElement.clientHeight;
   } else if (document.body && ( document.body.clientWidth || document.body.clientHeight )) {
       //IE 4 compatible
       windowWidth = document.body.clientWidth;
       windowHeight = document.body.clientHeight;
   }

   //alert(windowWidth + ':' + windowHeight);

   var leftRightMargin = 100;
   var topBottomMargin = 120;

   var scaleViaWidth = (windowWidth - leftRightMargin) / image.originalWidth;
   var scaleViaHeight = (windowHeight - topBottomMargin) /
image.originalHeight;
   var scale = Math.min(Math.min(scaleViaWidth, scaleViaHeight), 1);

   var imageWidth = Math.round(image.originalWidth * scale);
   var imageHeight = Math.round(image.originalHeight * scale);

   var imageElement = document.getElementById(JGCurrentContext.imageViewDivID);
   imageElement.width = imageWidth;
   imageElement.height = imageHeight;

   var horizontalSpace = windowWidth - imageWidth - 12;
   var verticalSpace = windowHeight - imageHeight - 12;
   imageElement.style.top =  JGString(Math.max(45, (verticalSpace/2 + 5))) + "px";
   imageElement.style.left = JGString(Math.round(horizontalSpace/2)) + "px";
}

function JGString(number) {
    return number + '';
}


//*** FULLSCREEN VIEW ACTIONS **********************************************************

function JGFullscreenOff(context) {
    JGPause(context);
    context.hideFullscreen();
}

function JGPause(context) {
    document.getElementById(context.pauseButtonID).style.display = "none";
    document.getElementById(context.playButtonID).style.display = "inline";

    if (context.intervalID != null) {
        clearInterval(context.intervalID);
        context.intervalID = null;
    }
}

function JGPlay(context) {
    document.getElementById(context.playButtonID).style.display = "none";
    document.getElementById(context.pauseButtonID).style.display = "inline";

    context.intervalID = setInterval ("JGNextItem(JGCurrentContext)", context.intervalDuration);
}

function JGPreviousItem(context) {
    if (context.rotateAutoPlay) {  //at the beginning we go to the end
        context.currentImage = (context.currentImage - 1 + context.totalPics) % context.totalPics;
        JGShowImage(context);

    } else if (context.currentImage > 0) { //at the beginning we stop
        context.currentImage = context.currentImage - 1;
        JGShowImage(context);
    }
}

function JGNextItem(context) {
    if (context.rotateAutoPlay) {  //at the end start from beginning
        context.currentImage = (context.currentImage + 1) % context.totalPics;
        JGShowImage(context);

    } else if (context.currentImage < context.totalPics - 1) {   //we finish at the last image
        if (context.currentImage == context.totalPics - 2) {
            JGPause(context);
        }

        context.currentImage = context.currentImage + 1;
        JGShowImage(context);
    }
}

function JGShowImage(context) {
    document.getElementById(context.imageViewDivID).src = "";
    JGResizeImage();
    document.getElementById(context.imageViewDivID).src = context.images[context.currentImage].imagePath;
    
    var startText = (context.currentImage+1) + '/' + context.totalPics + " - ";
    document.getElementById(context.captionDivID).innerHTML = startText + context.images[context.currentImage].caption;
}


//*** KEYBOARD AND MOUSE **********************************************************

function JGHandleMouseScroll(delta) {
    if (delta < 0) {//scroll down
        JGPause(JGCurrentContext);
        JGNextItem(JGCurrentContext);
    } else {  //scroll up
        JGPause(JGCurrentContext);
        JGPreviousItem(JGCurrentContext);
    }
}

function JGMouseWheelEvent(event){
    var delta = 0;
    if (!event) event = window.event;
    if (event.wheelDelta) {
        delta = event.wheelDelta / 120;
        //if (window.opera) delta = -delta;
    } else if (event.detail) {
        delta = -event.detail / 3;
    }
    if (delta) {
        JGHandleMouseScroll(delta);
    }
}

function JGKeyPressed(e) {
    var KeyID = (window.event) ? event.keyCode : e.keyCode;

    switch (KeyID) {

        case 27: //"Esc"
            JGFullscreenOff(JGCurrentContext);
            break;

        case 37: //"Arrow Left"
            JGPause(JGCurrentContext);
            JGPreviousItem(JGCurrentContext);
            break;

        case 38: //"Arrow Up"
            JGPause(JGCurrentContext);
            JGPreviousItem(JGCurrentContext);
            break;

        case 39: //"Arrow Right"
            JGPause(JGCurrentContext);
            JGNextItem(JGCurrentContext);
            break;

        case 40: //"Arrow Down"
            JGPause(JGCurrentContext);
            JGNextItem(JGCurrentContext);
            break;
    }

}


//**** THUMBGRID VIEW ACTIONS *********************************************************

function JGEnlargeImage(context, relativeImageIndex) {
    var pastPicsCount = context.currentThumbPage * context.thumbsPerPage;
    context.currentImage = pastPicsCount + relativeImageIndex;
    JGFullscreenOn(context);
}

function JGFullscreenOn(context) {
    context.showFullscreen();
}

function JGFullscreenAndPlay(context) {
    context.showFullscreen();
    JGPlay(context);
}

function JGNextThumbPage(context) {
    if (context.currentThumbPage < context.maxPages-1) {
        //increase the page and display the page
        context.currentThumbPage = context.currentThumbPage + 1;
        JGDisplayThumbPage(context);
    }
}

function JGPreviousThumbPage(context) {
    if (context.currentThumbPage > 0) {
        //decrease the page and display the page
        context.currentThumbPage = context.currentThumbPage - 1;
        JGDisplayThumbPage(context);
    }
}

function JGDisplayThumbPage(context) {
    //count how many pics were on previous pages
    var pastPicsCount = context.currentThumbPage * context.thumbsPerPage;
    context.currentImage = pastPicsCount;

    var r,c,picId;

    //set loading
    for (r = 0; r < context.rows; r++) {
        for (c = 0; c < context.cols; c++) {
            picId = pastPicsCount + (r * context.cols) + c;

            if (picId < context.totalPics) {
                JGSetLoadingThumb(context.galleryID, r, c);
            } else {
                JGClearThumb(context.galleryID, r, c);
            }
        }
    }

    //change thumbs
    for (r = 0; r < context.rows; r++) {
        for (c = 0; c < context.cols; c++) {
            picId = pastPicsCount + (r * context.cols) + c;

            if (picId < context.totalPics) {
                JGSetThumbnail(context.images[picId].thumbPath, context.galleryID, r, c);
            } else {
                JGClearThumb(context.galleryID, r, c);
            }
        }
    }
}

function JGSetThumbnail(imageUrl, galleryId, row, column) {
    document.getElementById(galleryId + "-" + row + "-" + column).style.backgroundImage = "url(" + imageUrl + ")";
}

function JGClearThumb(galleryId, row, column) {
    document.getElementById(galleryId + "-" + row + "-" + column).style.backgroundImage = "";
}

function JGSetLoadingThumb(galleryId, row, column) {
    document.getElementById(galleryId + "-" + row + "-" + column).style.backgroundImage = "url(widgets/35/loading2.gif)";
}


//*** STYLE CHANGE ************************************************************

function JGGetStyleClass(className) {
    var s,r;
    for (s = 0; s < document.styleSheets.length; s++) {
        if (document.styleSheets[s].rules){
            for (r = 0; r < document.styleSheets[s].rules.length; r++) {
                if (document.styleSheets[s].rules[r].selectorText == '.' + className) {
                    return document.styleSheets[s].rules[r];
                }
            }
        } else if (document.styleSheets[s].cssRules) {
            for (r = 0; r < document.styleSheets[s].cssRules.length; r++) {
                if (document.styleSheets[s].cssRules[r].selectorText == '.' + className)
                    return document.styleSheets[s].cssRules[r];
            }
        }
    }

    return null;
}

function JGIsIE() {
  return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}



//alert('base js loaded');
function Querystring2(qs) { // optionally pass a querystring to parse
    	this.params = {};
    
    	if (qs == null) qs = location.search.substring(1, location.search.length);
    	if (qs.length == 0) return;
    
    	qs = qs.replace("+", " ");
    	var args = qs.split('&'); // parse out name/value pairs separated via &
    
    	for (var i = 0; i < args.length; i++) {
    		var pair = args[i].split('=');
    		var name = decodeURIComponent(pair[0]);
    
    		var value = (pair.length==2)
    			? decodeURIComponent(pair[1])
    			: name;
    
    		this.params[name] = value;
    	}
    }
  
    Querystring2.prototype.get = function(key, default_) {
    	var value = this.params[key];
    	return (value != null) ? value : default_;
    }
    
    Querystring2.prototype.contains = function(key) {
    	var value = this.params[key];
    	return (value != null);
    }
    
    var query = "";
    
    function searchInQ() {
    	var qs = new Querystring2();
      var q = qs.get("q", "").toLowerCase();
      if ( q != "" ) {
          var code = q.charCodeAt(0);
	        if ( files[code] != undefined ) {
            query = q;
            loadScript(files[code], searchFinish);
    	    }
      }
    }
    
    window.onload = searchInQ;
  
    function searchFinish(){
        var options = words[query];
	          if ( options != undefined ) {
	              var elementRes = document.getElementById('search_content');
	              var out = "";
	              for (x in options) {
	                 var ind = options[x];
	                 out = out + "<a class='searchResultA' href='" + pageUrls[ind] + "'>" + pageTitles[ind] + "</a><br><span class='searchResultLink'>" + pageUrls[ind] + "<span><br><br>";
	              }
	              elementRes.innerHTML = out;
	          }
    }
  
    function loadScript(url, callback){
  
      var script = document.createElement("script")
      script.type = "text/javascript";
  
      if (script.readyState){  //IE
          script.onreadystatechange = function(){
              if (script.readyState == "loaded" ||
                      script.readyState == "complete"){
                  script.onreadystatechange = null;
                  callback();
              }
          };
      } else {  //Others
          script.onload = function(){
              callback();
          };
      }
  
      script.src = url;
      document.body.appendChild(script);
  }
function pictureShow(element){
  element.nextSibling.className = 'pictureFullSizeVisible';
}
function pictureHide(element){
  element.className = 'pictureFullSizeInvisible';
} 
function stripAt(str) {
    
   var res, pos, atstr;
   atstr = "(specialcharacter)";
   pos = str.indexOf(atstr);
   if (pos<0) return str;

   res = str.substring(0, pos) + "@" + str.substring(pos+atstr.length, str.length);

   return res;
}

