function searchClear(target, searchText)
{
  if (target.value == searchText)
  {
    target.value = '';
  }
}

function searchRestore(target, searchText)
{
  if (target.value == '')
  {
    target.value = searchText;
  }
}

function bar(url, title) {
	wasOpen = false;
	win     = window.open(url, title);    
	return (typeof(win) == 'object') ? true : false;
}

function myPopImage(imageURL,imageTitle,imageWidth,imageHeight) {

  PositionX = 30;
  PositionY = 30;
  
  ratio = imageWidth/imageHeight;
  maxHeight = screen.height - 105;
  maxWidth = maxHeight*ratio;
  if (maxWidth > screen.width-30) {
    maxWidth = screen.width - 80;
    maxHeight = maxWidth/ratio;
  }
    
  var opt='width=320,height=240,left='+PositionX+',top='+PositionY+',status=0,toolbar=0,menubar=0,location=0';
  imgWin=window.open('about:blank','null',opt);
  with (imgWin.document) {
    writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');
    writeln('<sc'+'ript>');
    writeln('function reSizeToImage(){');
    writeln('if (document.images[0].height > '+maxHeight+' || document.images[0].width > '+maxWidth+'){');
    writeln('height = '+maxHeight+';');
    writeln('width = '+maxWidth+';');
    writeln('document.images[0].width = '+maxWidth+';');
    writeln('document.images[0].height = '+maxHeight+';');
    writeln('window.resizeTo(width+40,height+100);}');
    writeln('else {');
    writeln('height = document.images[0].height;');
    writeln('width = document.images[0].width;');
    writeln('window.resizeTo(width+40,height+100);}}');
    writeln('function doTitle(){document.title="'+imageTitle+'";}');
    writeln('</sc'+'ript>');
    writeln('</head><body bgcolor="FFFFFF" onload="reSizeToImage();doTitle();self.focus()">');
    writeln('<img alt="'+imageTitle+'" title="'+imageTitle+'" src="'+imageURL+'" style="display:block; margin:0 auto;" /></body></html>');
    close();
  }
}

function myPopWindow(windowURL, windowName, windowFeatures) {
  var defaultFeatures = {"status": 0, "toolbar": 0, "location": 0, "menubar": 0,
                         "directories": 0, "resizeable": 1, "scrollbars": 1,
                         "width": 640, "height": 480};
  var features = '';

  for (i in windowFeatures) { defaultFeatures[i] = windowFeatures[i]; }
  for (i in defaultFeatures) { features += i + '=' + defaultFeatures[i] + ','; }

  window.open(windowURL, windowName, features);
  return false;
}

function switchBmk(n, css) {
  if (document.getElementById('bmk_header')) {
    var num = document.getElementById('bmk_header').getElementsByTagName('div').length;
    for (var i=1;i<=num;i++) {
      var elt = document.getElementById('bmk_title_' + i);
      var elc = document.getElementById('bmk_content_' + i);
      if (i == n) {
        elt.className = css + '_title active';
        elc.className = css + '_content visible';
      }
      else {
        elt.className = css + '_title';
        elc.className = css + '_content invisible';
      }
    }
  }
}

function highlightWords(elCls, hCls, words) {
  if (typeof words == 'object') {
    words = Object.keys(words);
  }
  if ($$(elCls).length > 0 && words.length > 0) {
    words.each(
      function(c, i){
        words[i] = c.replace(/([\\\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:\-])/g, '\\$1');
        words[i] = words[i].replace(/ /g, '\\s');
      }
    );
    var re = new RegExp('([^a-zA-Z0-9_\\-]|^)('+words.join('|')+')([^a-zA-Z0-9_\\-]|$)', 'gim');
    $$(elCls).each(function(el) {
      highlightWordsElem(el, re, hCls);
    });
  }
}

function highlightWordsElem(el, re, hCls) {
  for (var i=0;i<el.childNodes.length;i++) {
    if (el.childNodes[i].nodeName == '#text' && !$(el).hasClassName('h_word')) {
      var text = el.childNodes[i].data || el.childNodes[i].textContent;
      if (text.match(re)) {
        var html = text.replace(re, '$1<span class="' + hCls + '"><span class="h_word">$2</span></span>$3');
        if (el.childNodes.length == 1) {
          el.innerHTML = html;
        } else {
          var hSpan = new Element('span');
          hSpan.innerHTML = html;
          if (typeof el.childNodes[i].nextSibling != 'undefined') {
            el.insertBefore(hSpan, el.childNodes[i].nextSibling);
            if (typeof el.childNodes[i].data != 'undefined') {
              el.childNodes[i].data = '';
            } else {
              el.childNodes[i].textContent = '';
            }
          } else if (typeof el.childNodes[i].previousSibling != 'undefined') {
            el.appendChild(hSpan);
            if (typeof el.childNodes[i].data != 'undefined') {
              el.childNodes[i].data = '';
            } else {
              el.childNodes[i].textContent = '';
            }
          }
        }
      }
    } else {
      highlightWordsElem(el.childNodes[i], re, hCls);
    }
  }
}

document.observe("dom:loaded", function() {
  if (window.location.hash && !window.location.hash.split('#')[1].empty()) {
    var hashValue = window.location.hash.split('#')[1];
    if (hashValue.indexOf('bmk') != -1) {
      var bmkVars = hashValue.split('-');
      switchBmk(bmkVars[1], bmkVars[0]);
    }
  }
});

// adding method getPageSize to prototype's Position method
// returns [width, height] and {width, height}
//
// usage:
// Position.getPageSize().width/height OR
// var pageSize = Position.getPageSize()
Position.getPageSize = function() {
  var array = [];
  var pageW, pageH;

  if (window.innerHeight && window.scrollMaxY) {
		pageW = document.body.scrollWidth;
		pageH = window.innerHeight + window.scrollMaxY;
  } else {
		pageW = document.body.scrollWidth || document.body.offsetWidth;
		pageH = document.body.scrollHeight || document.body.offsetHeight;
  }

	if(pageH < document.viewport.getHeight()) {
		pageH = document.viewport.getHeight();
	}

	if(pageW < document.viewport.getWidth()) {
		pageW = document.viewport.getWidth();
	}

  array.width = array[0] = pageW;
  array.height = array[1] = pageH;

  return array;
}

var inlineGallery = {

  cssRule: 'a[rel="ig"]',
  contentBefore: '',
  contentAfter: '',
  galleryArr: new Array(),
  imgKey: 0,

  init: function(newCssRule, contentBefore, contentAfter) {
    if (typeof newCssRule != 'undefined' && newCssRule != '') {
      inlineGallery.cssRule = newCssRule;
    }
    if (typeof contentBefore != 'undefined' && contentBefore != '') {
      inlineGallery.contentBefore = contentBefore;
    }
    if (typeof contentAfter != 'undefined' && contentAfter != '') {
      inlineGallery.contentAfter = contentAfter;
    }
    $$(inlineGallery.cssRule).each(function(s, key) {
      inlineGallery.galleryArr[key] = [];
      inlineGallery.galleryArr[key][0] = s.href;
      inlineGallery.galleryArr[key][1] = s.title;
      s.observe('click', inlineGallery.openGallery.bind(key));
    }); // set onclick on each image which matches cssRule
    $('inlineGallery').observe('click', inlineGallery.close); // set close observing
    $('inlineGalleryBg').observe('click', inlineGallery.close); // set close observing
    inlineGallery.updateNav(inlineGallery.imgKey);
    $('prevImg').setOpacity(0.6);
    $('nextImg').setOpacity(0.6);
  },

  openGallery: function(event) {
    var key = this;
    $$('select').each(function(s){s.hide();});
    $('imgInfoBox').hide();
    $('customContentBefore').hide();
    $('customContentAfter').hide();
    $('inlineGalleryBg').setOpacity(0.8);
    $('inlineGalleryBg').style.height = Position.getPageSize().height + 'px';
    $('inlineGalleryBg').style.width = Position.getPageSize().width + 'px';
    $('inlineGalleryBg').show();
    var galleryOffset = document.viewport.getScrollOffsets().top + document.viewport.getHeight()/20;
    $('inlineGallery').style.top = galleryOffset + 'px';
    $('inlineGallery').show();
    inlineGallery.loadImage(key, true);
    Event.stop(event);
  },

  loadImage: function(key, opened) {
    inlineGallery.imgKey = key;
    if (key == 0) {
      $('prevImg').hide();
    } else {
      if (!$('prevImg').visible()) {
        $('prevImg').show();
      }
    }
    if (key == inlineGallery.galleryArr.length-1) {
      $('nextImg').hide();
    } else {
      if (!$('nextImg').visible()) {
        $('nextImg').show();
      }
    }
    inlineGallery.updateNav(key);
    $('galleryImg').hide();
    $('imgLoading').show();
    $('galleryImg').alt = inlineGallery.galleryArr[key][1];
    $('galleryImg').title = inlineGallery.galleryArr[key][1];
    if ($('galleryImg').title != '') {
      $('imgTitle').innerHTML = $('galleryImg').title;
    }
    var pos = key+1;
    $('imgPos').innerHTML = pos + ' z ' + inlineGallery.galleryArr.length;

		imgPreloader = new Image();
		imgPreloader.onload = function() {
      $('imgLoading').hide();
      $('imgInfoBox').hide();
      var boxHeight = imgPreloader.height + $('imgInfoBox').getHeight();
      $('galleryImg').src = inlineGallery.galleryArr[key][0];
      /*if (opened) {*/
        $('customContentBefore').morph('width:'+imgPreloader.width+'px;', {duration: 0.4});
        $('customContentAfter').morph('width:'+imgPreloader.width+'px;', {duration: 0.4});
        $('imgOuterBox').morph('height:'+boxHeight+'px;width:'+imgPreloader.width+'px;', {duration: 0.4});
        setTimeout("inlineGallery.showImage(imgPreloader.width, imgPreloader.height)", 400);
      /*} else {
        $('imgOuterBox').style.width = imgPreloader.width + 'px';
        $('imgOuterBox').style.height = boxHeight + 'px';
        inlineGallery.showImage(imgPreloader.width, imgPreloader.height);
      }*/ // uncomment if you want faster move between photos
		}
    imgPreloader.src = inlineGallery.galleryArr[key][0];
    inlineGallery.preloadImages(key);
  },

  showImage: function(w, h) {
    $('imgInnerBox').style.width = w + 'px';
    $('imgInnerBox').style.height = h + 'px';
    var navHeight = h + 10;
    $('galleryNav').style.height = navHeight + 'px';
    $('galleryImg').appear({ duration: 0.3 });
    $('imgInfoBox').appear({ duration: 0.3 });
    if (inlineGallery.contentBefore != '') {
      $('customContentBefore').innerHTML = inlineGallery.contentBefore;
      $('customContentBefore').appear({ duration: 0.3 });
    }
    if (inlineGallery.contentAfter != '') {
      $('customContentAfter').innerHTML = inlineGallery.contentAfter;
      $('customContentAfter').appear({ duration: 0.3 });
    }
  },

  updateNav: function(key) {
    if (key > 0) {
      $('prevImg').onclick = function(event) {
        inlineGallery.imgKey--;
        inlineGallery.loadImage(inlineGallery.imgKey, false);
        return false;
      }
    }
    if (key < inlineGallery.galleryArr.length-1) {
      $('nextImg').onclick = function(event) {
        inlineGallery.imgKey++;
        inlineGallery.loadImage(inlineGallery.imgKey, false);
        return false;
      }
    }
  },

  preloadImages: function(key) {
    if((inlineGallery.galleryArr.length - 1) > key){
      var preloadNextImage = new Image();
      preloadNextImage.src = inlineGallery.galleryArr[key + 1][0];
    }
    if(key > 0){
      var preloadPrevImage = new Image();
      preloadPrevImage.src = inlineGallery.galleryArr[key - 1][0];
    }
  },

  close: function(event) {
    if (Event.element(event).id == 'inlineGallery' || Event.element(event).id == 'closeImg' || Event.element(event).id == 'inlineGalleryBg') {
      $('inlineGallery').fade({ duration: 0.3 });
      $('inlineGalleryBg').fade({ duration: 0.3 });
      setTimeout("$('imgOuterBox').style.width = '32px'", 300);
      setTimeout("$('imgOuterBox').style.height = '32px'", 300);
      setTimeout("$('imgInnerBox').style.width = 'auto'", 300);
      setTimeout("$('imgInnerBox').style.height = 'auto'", 300);
      $$('select').each(function(s){s.show();});
    }
  }
}
