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 setCookie(cookieName, cookieValue, expireDays) {
	var expirationDate = new Date();
	expirationDate.setDate(expirationDate.getDate() + expireDays);
	document.cookie = cookieName + "=" + escape(cookieValue) + ((expireDays == null) ? "" : ";expires=" + expirationDate.toGMTString());
}

function getCookie(cookieName) {
	if(document.cookie.length > 0) {
		cookieStart = document.cookie.indexOf(cookieName + "=");
		if(cookieStart != -1) {
			cookieStart = cookieStart + cookieName.length + 1;
			cookieEnd = document.cookie.indexOf(";", cookieStart);
			if(cookieEnd == -1) cookieEnd = document.cookie.length;
			return(unescape(document.cookie.substring(cookieStart, cookieEnd)));
		}
	}
	return("");
}

function getCookieActive() {
	var tm0 = getCookie('active');
	if(tm0 == "") {
		return(1);
	} else {
		return(tm0);
	}
}

function checkRefreshBox() {
  checkbox = $('incidents_refresh');
  if(getCookie('refreshIncs') == 'true') {
    checkbox.checked = true;
  } else {
    checkbox.checked = false;
  }
}

function switchBmk(active) {
	setCookie('active', active);
  $$('.bmk-tab').each(function(el){
    el = $(el);
    if (el.id == 'bmk-tab-' + active) {
      if (!el.hasClassName('active')) {
        el.addClassName('active');
      }
    } else {
      el.removeClassName('active');
    } //if
    if (active == 1) {
      $('bmk-left').className = 'bmk-left-a';
      $('bmk-middle-1').className = 'bmk-middle al';
      $('bmk-middle-2').className = 'bmk-middle';
      $('bmk-right').className = 'bmk-right';
    } else if (active == 2) {
      $('bmk-left').className = 'bmk-left';
      $('bmk-middle-1').className = 'bmk-middle ar';
      $('bmk-middle-2').className = 'bmk-middle al';
      $('bmk-right').className = 'bmk-right';
    } else if (active == 3) {
	    //checkRefreshBox();
      $('bmk-left').className = 'bmk-left';
      $('bmk-middle-1').className = 'bmk-middle';
      $('bmk-middle-2').className = 'bmk-middle ar';
      $('bmk-right').className = 'bmk-right-a';
    }
  });
  $$('.bmk-content').each(function(el){
    el = $(el);
    if (el.id == 'bmk-content-' + active) {
      el.removeClassName('inv');
    } else {
      if (!el.hasClassName('inv')) {
        el.addClassName('inv');
      }
    } //if
  });
}

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;
      }
    }
  }
}

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]);
    }
  }
});

var inlineGallery = {

  cssRule: 'a[rel="ig"]',
  cssRuleAjax: 'a[rel^="ig["]',
  contentBefore: '',
  contentAfter: '',
  galleryArr: new Array(),
  galleryArrAjax: new Array(),
  ajaxURL: '',
  ajaxLimit: 10,
  ajaxOffset: 0,
  ajaxLimitName: 'limit',
  ajaxOffsetName: 'offset',
  ajaxGalleryIdName: 'filter[id_albums][0]',
  ajaxAlbumId: null,
  imgKey: 0,
  
  init: function(varNames, ajaxURL, contentBefore, contentAfter) {
    if (typeof varNames.limitName != 'undefined') {
      inlineGallery.ajaxLimitName = varNames.limitName;
      inlineGallery.ajaxOffsetName = varNames.offsetName;
      inlineGallery.ajaxGalleryIdName = varNames.galleryIdName;
    }
    if (typeof ajaxURL != 'undefined' && ajaxURL != '') {
      inlineGallery.ajaxURL = ajaxURL;
    }
    if (typeof contentBefore != 'undefined' && contentBefore != '') {
      inlineGallery.contentBefore = contentBefore;
    }
    if (typeof contentAfter != 'undefined' && contentAfter != '') {
      inlineGallery.contentAfter = contentAfter;
    }
    if ($$(inlineGallery.cssRuleAjax).size() > 0) {
      $$(inlineGallery.cssRuleAjax).each(function(s, key) {
        var albumId = s.rel.slice(s.rel.indexOf('[')+1, s.rel.lastIndexOf(']'));
        if (albumId != '') {
          var ajaxParams = {};
          ajaxParams[inlineGallery.ajaxGalleryIdName] = albumId;
          ajaxParams[inlineGallery.ajaxLimitName] = inlineGallery.ajaxLimit;
          ajaxParams[inlineGallery.ajaxOffsetName] = inlineGallery.ajaxOffset;
          new Ajax.Request(inlineGallery.ajaxURL, {
            method: 'get',
            parameters: ajaxParams,
            onSuccess: function(transport) {
              console.log(transport.responseText.evalJSON(true));
              inlineGallery.galleryArrAjax[albumId] = transport.responseText.evalJSON(true);
              s.observe('click', inlineGallery.openAjaxGallery.bind(albumId));
            }
          });
        }
      });
    }
    var gKey = 0;
    $$(inlineGallery.cssRule).each(function(s, key) {
      if (s.firstDescendant() != null) {
        if (typeof s.firstDescendant().src != 'undefined') {
          var imgSrc = s.firstDescendant().src.replace(/gallery\/([a-z]*)\//, 'gallery/full/');
          inlineGallery.galleryArr.push({link: imgSrc, name: s.title});
          s.observe('click', inlineGallery.openGallery.bind(gKey));
          gKey++;
        }
      }
    }); // set onclick on each image which matches cssRule
    $('prevImg').setOpacity(0.6);
    $('nextImg').setOpacity(0.6);
    $('inlineGallery').observe('click', inlineGallery.close); // set close observing
    $('inlineGalleryBg').observe('click', inlineGallery.close); // set close observing
  },
  
  openAjaxGallery: function(event) {
    inlineGallery.ajaxAlbumId = parseInt(this);
    console.log(inlineGallery.galleryArrAjax[inlineGallery.ajaxAlbumId]);
    $$('select,object').each(function(s){s.hide();});
    $('imgInfoBox').hide();
    $('customContentBefore').hide();
    $('customContentAfter').hide();
    $('inlineGalleryBg').setOpacity(0.8);
    $('inlineGalleryBg').style.height = QCM.Methods.getPageSize().height + 'px';
    $('inlineGalleryBg').style.width = QCM.Methods.getPageSize().width + 'px';
    $('inlineGalleryBg').show();
    var galleryOffset = document.viewport.getScrollOffsets().top + document.viewport.getHeight()/20;
    $('inlineGallery').style.top = galleryOffset + 'px';
    $('inlineGallery').show();
    Event.stop(event);
  },
  
  openGallery: function(event) {
    var key = this;
    $$('select,object').each(function(s){s.hide();});
    $('imgInfoBox').hide();
    $('customContentBefore').hide();
    $('customContentAfter').hide();
    $('inlineGalleryBg').setOpacity(0.8);
    $('inlineGalleryBg').style.height = QCM.Methods.getPageSize().height + 'px';
    $('inlineGalleryBg').style.width = QCM.Methods.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, inlineGallery.galleryArr);
    Event.stop(event);
  },
  
  loadImage: function(key, opened, imgArr) {
    inlineGallery.imgKey = key;

    if (key == 0 && inlineGallery.ajaxOffset == 0) {
      $('prevImg').hide();
    } else {
      if (!$('prevImg').visible()) {
        $('prevImg').show();
      }
    }

    if (inlineGallery.ajaxOffset > 0) {
      var pos = key+1+inlineGallery.ajaxOffset;
    } else {
      var pos = key+1;
    }
    if (typeof imgArr[key].count != 'undefined') {
      var count = imgArr[key].count;
    } else {
      var count = imgArr.length;
    }

    if (pos == count) {
      $('nextImg').hide();
    } else {
      if (!$('nextImg').visible()) {
        $('nextImg').show();
      }
    }
    inlineGallery.updateNav(key, imgArr);
    $('galleryImg').hide();
    $('imgLoading').show();
    if (typeof imgArr[key].name != 'undefined') {
      $('galleryImg').alt = imgArr[key].name;
      $('galleryImg').title = imgArr[key].name;
      if ($('galleryImg').title != '') {
        $('imgTitle').innerHTML = $('galleryImg').title;
      }
    }

    $('imgPos').innerHTML = pos + ' z ' + count;

		$('galleryImg').src = imgArr[key].link;
    
    imgPreloader = new Image();
		imgPreloader.onload = function() {
      $('imgLoading').hide();
      $('imgInfoBox').hide();
      var boxHeight = imgPreloader.height + $('imgInfoBox').getHeight();
      $('galleryImg').src = imgArr[key].link;
      /*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 = imgArr[key].link;
    inlineGallery.preloadImages(key, imgArr);
  },
  
  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, imgArr) {
    if (typeof imgArr[key].count != 'undefined') {
      if (key+inlineGallery.ajaxOffset > 0) {
        $('prevImg').onclick = function(event) {
          if (key == 0 && inlineGallery.ajaxOffset > 0) {
            inlineGallery.imgKey = inlineGallery.ajaxLimit-1;
            inlineGallery.getImagesFromServer(-10);
          } else {
            inlineGallery.imgKey--;
            inlineGallery.loadImage(inlineGallery.imgKey, false, inlineGallery.galleryArrAjax[inlineGallery.ajaxAlbumId]);
          }
          return false;
        }
      }
      if (key+1+inlineGallery.ajaxOffset < imgArr[key].count) {
        $('nextImg').onclick = function(event) {
          if (key == inlineGallery.ajaxLimit-1) {
            inlineGallery.imgKey = 0;
            inlineGallery.getImagesFromServer(10);
          } else {
            inlineGallery.imgKey++;
            inlineGallery.loadImage(inlineGallery.imgKey, false, inlineGallery.galleryArrAjax[inlineGallery.ajaxAlbumId]);
          }
          return false;
        }
      }
    } else {
      if (key > 0) {
        $('prevImg').onclick = function(event) {
          inlineGallery.imgKey--;
          inlineGallery.loadImage(inlineGallery.imgKey, false, imgArr);
          return false;
        }
      }
      if (key < imgArr.length-1) {
        $('nextImg').onclick = function(event) {
          inlineGallery.imgKey++;
          inlineGallery.loadImage(inlineGallery.imgKey, false, imgArr);
          return false;
        }
      }
    }
  },
  
  preloadImages: function(key, imgArr) {
    if((imgArr.length - 1) > key){
      var preloadNextImage = new Image();
      preloadNextImage.src = imgArr[key + 1][0];
    }
    if(key > 0){
      var preloadPrevImage = new Image();
      preloadPrevImage.src = imgArr[key - 1][0];
    }
  },
  
  getImagesFromServer: function(offsetChange) {
    inlineGallery.ajaxOffset += offsetChange;
    var ajaxParams = {};
    ajaxParams[inlineGallery.ajaxGalleryIdName] = inlineGallery.ajaxAlbumId;
    ajaxParams[inlineGallery.ajaxLimitName] = inlineGallery.ajaxLimit;
    ajaxParams[inlineGallery.ajaxOffsetName] = inlineGallery.ajaxOffset;
    new Ajax.Request(inlineGallery.ajaxURL, {
      method: 'get',
      parameters: ajaxParams,
      onSuccess: function(transport) {
        inlineGallery.galleryArrAjax[inlineGallery.ajaxAlbumId] = transport.responseText.evalJSON(true);
        inlineGallery.loadImage(inlineGallery.imgKey, false, inlineGallery.galleryArrAjax[inlineGallery.ajaxAlbumId]);
      }
    });
  },
  
  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);
      inlineGallery.ajaxOffset = 0;
      inlineGallery.ajaxAlbumId = null;
      $$('select,object').each(function(s){s.show();});
    }
  }
}
