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' && !Element.hasClassName(el, 'h_word')) {
      var text = el.childNodes[i].nodeValue;
      var html = text.replace(re, '<span>$1<span class="' + hCls + '"><span class="h_word">$2</span></span>$3</span>');
      if (html != text) {
        if (el.childNodes.length == 1) {
          el.innerHTML = html;
          if (Prototype.Browser.IE) {
            IEinnerHTMLSpaceFix(el, html);
          }
        } else {
          var hSpan = new Element('span');
          hSpan.innerHTML = html;
          if (Prototype.Browser.IE) {
            IEinnerHTMLSpaceFix(hSpan, html);
          }
          if (!!el.childNodes[i].nextSibling) {
            el.insertBefore(hSpan, el.childNodes[i].nextSibling);
            el.childNodes[i].nodeValue = '';
          } else if (!!el.childNodes[i].previousSibling) {
            el.appendChild(hSpan);
            el.childNodes[i].nodeValue = '';
          }
        }
      }
    } else {
      highlightWordsElem(el.childNodes[i], re, hCls);
    }
  }
}

function IEinnerHTMLSpaceFix(el, html) {
  var spaces = /^\s+/.exec(html);
  if(!!spaces) {
    if (el.childNodes[0].nodeName != '#text') {
      var space = document.createTextNode(spaces);
      el.insert({'top': space});
    } else if (!!el.childNodes[0].nodeValue) {
      if (el.childNodes[0].nodeValue.indexOf(spaces) != 0) {
        el.childNodes[0].nodeValue = spaces + el.childNodes[0].nodeValue;
      }
    }
  }
}

headReadyApply.push(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]);
    }
  }
  if ($('invest_counter')) {
    var num = $('invest_counter').innerHTML.toArray();
    var newHTML = '';
    for (var i=0;i<num.length;i++) {
      newHTML += '<span class="n'+num[i]+'">'+num[i]+'</span>';
    }
    if (!newHTML.empty()) {
      $('invest_counter').update(newHTML);
    }
  }
});

QCM.Carousel = function() {
  this.options = {
    formats: {
      detail: 'detail',
      thumb: 'thumbnail'
    },
    showThumbs: true,
    infinite: true,
    duration: 5,
    selected: 0,
    photos: []
  },
  this.page = 1,
  this.redirect = '',
  this.thumbsPerPage = 1,
  this.totalImages = 0,
  this.loop = null,
  this.isFading = false,
  this.isMoving = false
}
QCM.Carousel.prototype = {
  init: function(options) {
    var t = this;
    t.options = Object.extend(t.options, options);
    if (typeof t.options.photos == 'string') {
      new Ajax.Request(t.options.photos, {
        method: 'post',
        onSuccess: function(transport) {
          var photos = transport.responseText.evalJSON();
          if (typeof photos == 'object' && photos.each) {
            t.options.photos = [];
            photos.each(function(photo) {
              t.options.photos.push({
                detail: '/uploads/gallery/'+t.options.formats.detail+'/'+photo.id+'.jpg',
                thumb: '/uploads/gallery/'+t.options.formats.thumb+'/'+photo.id+'.jpg',
                name: photo.name,
                desc: photo.desc,
                redirect: photo.redirect
              });
            });
            t.build();
          }
        }
      });
    } else {
      t.build();
    } // if
  },
  
  build: function() {
    var t = this;
    if (!$(t.options.container)) {
      throw('No container defined!');
      return;
    } else {
      var carousel = new Element('div', {'class': 'carousel_cnt'});
      carousel.insert(new Element('div', {'class': 'carousel_detail'})
                      .insert(new Element('img', {'class': 'carousel_img'}))
                      .insert(new Element('img', {'class': 'carousel_img'}).hide())
                      .insert(new Element('div', {'class': 'img_name'}))
                      .insert(new Element('div', {'class': 'img_desc'}))
                      .insert(new Element('img', {'class': 'carousel_preload'})))
              .insert(new Element('div', {'class': 'carousel_thumbs'})
                      .insert(new Element('div', {'class': 'arr_left disabled'}))
                      .insert(new Element('div', {'class': 'slider'})
                              .insert(new Element('div', {'class': 'visor'})))
                      .insert(new Element('div', {'class': 'arr_right disabled'}))
                      .insert(new Element('div', {'class': 'cleaner'})));
      $(t.options.container).update(carousel);
      t.activate();
    }
  },
  
  activate: function() {
    var t = this;
    var actual = t.options.photos[t.options.selected];
    var detail = $(t.options.container).down('.carousel_detail');
    var img = $(t.options.container).down('.carousel_img');
    var img_name = $(t.options.container).down('.img_name');
    var img_desc = $(t.options.container).down('.img_desc');
    var preload = $(t.options.container).down('.carousel_preload');
    
    t.redirect = actual.redirect;
    if (!t.redirect.blank()){
      detail.addClassName('redirect');
    } else {
      detail.removeClassName('redirect');
    }
    detail.observe('click', function(e){
      Event.stop(e);
      if (!t.redirect.blank()){
        window.location = t.redirect;
      }
    });
    img_name.update(actual.name);
    img_desc.update(actual.desc);
    if (actual.name.blank()) {
      img_name.hide();
    }
    if (actual.desc.blank()) {
      img_desc.hide();
    }
    img.src = actual.detail;
    img.observe('load', function(){
      img.writeAttribute({width: img.getWidth(), height: img.getHeight()});
    });
    
    preload.observe('load', t.preLoader.bind(t, detail, preload, img_name, img_desc));
    preload.hide();
    
    t.options.photos.each(t.thumbsObserve.bind(t));
    
    var imgThumb = $(t.options.container).down('.visor').select('img').first();
    if (Prototype.Browser.IE) {
      t.prevNextObserve();
    } else {
      imgThumb.observe('load', t.prevNextObserve.bind(t));
    }
    
    t.loop = t.imgLoop.delay(t.options.duration, t);
  },
  
  preLoader: function(detail, preload, img_name, img_desc) {
    var t = this;
    if (!t.isFading) {
      t.isFading = true;
      var selected = t.options.photos[t.options.selected];
      var images = detail.select('img.carousel_img');
      images.each(function(img) {
        img = $(img);
        if (img.visible()) {
          img.fade({duration: 0.5});
        } else {
          img.src = preload.src;
          img.appear({duration: 0.5, afterFinish: function(){t.isFading = false}});
          img.writeAttribute({width: img.getWidth(), height: img.getHeight()});
          img_name.update(selected.name);
          if (selected.name.blank()) {
            img_name.hide();
          } else {
            img_name.show();
          }
          img_desc.update(selected.desc);
          if (selected.desc.blank()) {
            img_desc.hide();
          } else {
            img_desc.show();
          }
        }
      }); // each      
    }
  },
  
  changeImg: function(key) {
    var t = this;
    var actualPage = (Math.ceil((key+1)/t.thumbsPerPage));
    if (t.page != actualPage) {
      if (key > 0) {
        t.moveSlider(-1);
      } else {
        t.moveSlider(0);
      }
    }
    var preload = $(t.options.container).down('.carousel_preload');
    var detail = $(t.options.container).down('.carousel_detail');
    var thumbs = $(t.options.container).select('img.thumb');
    t.options.selected = key;
    thumbs.invoke('removeClassName', 'selected');
    thumbs[key].addClassName('selected');
    t.redirect = t.options.photos[key].redirect;
    if (!t.redirect.blank()){
      detail.addClassName('redirect');
    } else {
      detail.removeClassName('redirect');
    }
    preload.src = t.options.photos[key].detail;
  },
  
  moveSlider: function(dir) {
    var t = this;
    if (!t.isMoving) {
      t.isMoving = true;
      var prev = $(t.options.container).down('.arr_left');
      var next = $(t.options.container).down('.arr_right');
      var slider = $(t.options.container).down('.slider');
      var visor = $(t.options.container).down('.visor');
      var moveX = 0;
      t.page = t.page - (dir);
      if (dir != 0) {
        moveX = dir * slider.getWidth();
      } else {
        moveX = slider.getWidth() * (t.page - 1);
        t.page = 1;
      }
      if (t.page < (t.totalImages/t.thumbsPerPage)) {
        next.removeClassName('disabled');
      } else {
        next.addClassName('disabled');
      }
      if (t.page > 1) {
        prev.removeClassName('disabled');
      } else {
        prev.addClassName('disabled');
      }
      new Effect.Move(visor, {x: moveX, y: 0, afterFinish: function(){t.isMoving = false}});
    }
  },
  
  imgLoop: function(t) {
    if (t.options.photos[t.options.selected + 1]) {
      t.changeImg(t.options.selected + 1);
      t.loop = t.imgLoop.delay(t.options.duration, t);
    } else if (!t.options.photos[t.options.selected + 1] && t.options.infinite) {
      t.changeImg(0);
      t.loop = t.imgLoop.delay(t.options.duration, t);
    }
  },
  
  thumbsObserve: function(photo, i) {
    var t = this;
    var thumb = new Element('img', {'src': photo.thumb, 'class': 'thumb'});
    $(t.options.container).down('.visor').insert(thumb);
    thumb.observe('click', function(key, e){
      Event.stop(e);
      window.clearTimeout(t.loop);
      if (key != t.options.selected) {
        t.changeImg(key, thumb);
      }
    }.curry(i));
    thumb.observe('load', function(){
      thumb.writeAttribute({width: thumb.width, height: thumb.height});
    });
    if (t.options.selected == i) {
      $(t.options.container).down('.visor').select('img').last().addClassName('selected');
    }
  },
  
  prevNextObserve: function() {
    var t = this;
    var prev = $(t.options.container).down('.arr_left');
    var next = $(t.options.container).down('.arr_right');
    var sliderWidth = $(t.options.container).down('.slider').getWidth();
    var imgThumb = $(t.options.container).down('.visor').select('img').first();
    var thumbWidth = imgThumb.getWidth();
    t.totalImages = $(t.options.container).down('.visor').select('img').length;
    t.thumbsPerPage = Math.floor(sliderWidth/thumbWidth);
    if (t.options.photos.length > t.thumbsPerPage) {
      next.removeClassName('disabled');
      next.observe('click', function(e){
        Event.stop(e);
        if (t.page < (t.totalImages/t.thumbsPerPage)) {
          window.clearTimeout(t.loop);
          t.moveSlider(-1);
        }
      });
      prev.observe('click', function(e){
        Event.stop(e);
        if (t.page > 1) {
          window.clearTimeout(t.loop);
          t.moveSlider(1);
        }
      });
    }
  }
}

var c = new QCM.Carousel();
c.init({container: 'carousel',
        photos: '/modules/obscura/obscuraJSGallery.php?filter[id_albums][0]=9&limit=0',
        formats: {detail: 'proj_detail', thumb: 'proj_thumb'},
        duration: 7
      });
      
      
/* tinyMCE embed functions */
function writeFlash(p) {
	writeEmbed(
		'D27CDB6E-AE6D-11cf-96B8-444553540000',
		'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0',
		'application/x-shockwave-flash',
		p
	);
}

function writeShockWave(p) {
	writeEmbed(
	'166B1BCA-3F9C-11CF-8075-444553540000',
	'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0',
	'application/x-director',
		p
	);
}

function writeQuickTime(p) {
	writeEmbed(
		'02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
		'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0',
		'video/quicktime',
		p
	);
}

function writeRealMedia(p) {
	writeEmbed(
		'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA',
		'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0',
		'audio/x-pn-realaudio-plugin',
		p
	);
}

function writeWindowsMedia(p) {
	p.url = p.src;
	writeEmbed(
		'6BF52A52-394A-11D3-B153-00C04F79FAA6',
		'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701',
		'application/x-mplayer2',
		p
	);
}

function writeEmbed(cls, cb, mt, p) {
	var h = '', n, playerURL = '/class/tiny_mce/plugins/media/moxieplayer.swf';
  
	h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"';
	h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : '';
	h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : '';
	h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : '';
	h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : '';
	h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : '';
	h += '>';

	for (n in p) {
    p[n] = p[n].replace(/(\&)(amp;)+/gi, '$1$2');
    if (n == 'src' && /\.flv$/i.test(p[n]) && !/\.swf/i.test(p[n])) {
      h += '<param name="src" value="'+playerURL+'" />';
      h += '<param name="flashvars" value="url='+p[n]+'" />';
    } else {
      h += '<param name="' + n + '" value="' + p[n] + '" />';
    }
  }

	h += '<embed type="' + mt + '"';

	for (n in p) {
    if (n == 'src' && /\.flv$/i.test(p[n]) && !/\.swf/i.test(p[n])) {
      h += 'src="'+playerURL+'" ';
      h += 'flashvars="url='+p[n]+'" ';
    } else {
      h += n + '="' + p[n] + '" ';
    }
  }

	h += '></embed></object>';

	document.write(h);
}
