window.addEvent('domready', function() {
//page navigation
    if($('pageNavigationPaginate')) {
        vNavigationPannelId = 'pageNavigationPaginate';
        vBlockClassName     = 'virtualpage';
        vBlockPerPage       = objectsPerPage;
        vPagesCount         = countVPages(vBlockPerPage);
        buildVPageNavigator(vPagesCount);
    }
//map
    if( $('flashcontent') ){
        var so = new SWFObject("/map/map.swf", "flash_obj", "445", "285", "8", "");
        so.addParam("quality", "high");
        so.addParam("loop", "true");
        so.addParam("wmode", "transparent");
        so.write("flashcontent");
    }
//top menu
    $$('#topmenu .anylinkcss').each(function(submenuElement) {
	 setSubMenuWidth(submenuElement);
    });
//other
    if($('tourSearchForm')){
        if(currentKurorts == 0) {         
            $('kurortSelectBlock').setStyle('display', 'none');
            $('kurortTitleBlock').setStyle('display', 'none');
        }

        $('country').addEvent('change', function() {
            getKurortList();
        });
        $('tourSearchForm').addEvent('submit', function(e) {
            if( !checkTourSearchForm() ) {
                var event = new Event(e).stop();
            }
        });
    }
//vote
    $$('img.image-contest-vote').each(function(voteImg) {
        voteImg.addEvent('click', function() {
            imgId = voteImg.id.replace('voteFor', '');
            vote( imgId ); 
        });    
    })

    if($('textSearchForm')){
        searchFromText = $('searchedWord').getProperty('value');
        $('searchedWord').addEvent('focus', function() {
            if($('searchedWord').getProperty('value') == searchFromText ) {
                $('searchedWord').setProperty('value', '');
            }
        });
        $('searchedWord').addEvent('blur', function() {
            if($('searchedWord').getProperty('value') == ''){
                $('searchedWord').setProperty('value', searchFromText);
            }
        });
        $('textSearchForm').addEvent('submit', function(e) {
            if( !checkTextSearchForm() ) {
                var event = new Event(e).stop();
            }
        });
    }

    if($('tourOrderForm')){
		
        $('order').addEvent('click', function() {
            orderTour('');
        });
        $('tourOrderForm').addEvent('submit', function(e) {
            var event = new Event(e).stop();
            orderTour('');
        });
    }
	if($('tourOrderForm2')){
        $('order2').addEvent('click', function() {
            orderTour2();
        });
        $('tourOrderForm2').addEvent('submit', function(e) {
            var event = new Event(e).stop();
            orderTour2();
        });
    }

    if($('feedbackForm')){
        $('feedbackButton').addEvent('click', function() {
            feedback();
        });
        $('feedbackForm').addEvent('submit', function(e) {
            var event = new Event(e).stop();
            feedback();
        });
    }

    if($('subscribeForm')){
        var subscribFromText = $('subscribeEmail').getProperty('value');
        $('subscribeEmail').addEvent('focus', function() {
            if($('subscribeEmail').getProperty('value') == subscribFromText ) {
                $('subscribeEmail').setProperty('value', '');
            }
        });
        $('subscribeEmail').addEvent('blur', function() {
            if($('subscribeEmail').getProperty('value') == ''){
                $('subscribeEmail').setProperty('value', subscribFromText);
            }
        });
        $('subscribeButton').addEvent('click', function() {
            subscribe();
        });
        $('subscribeForm').addEvent('submit', function(e) {
            var event = new Event(e).stop();
            subscribe();
        });
    }

    if($('agentLoginForm')){
        $('agentLoginForm').addEvent('submit', function(e) {
            var event = new Event(e).stop();

        });
        $('agentLoginButton').addEvent('click', function() {
            agentLogin();
        });
        $('passwordRemindButton').addEvent('click', function() {
            passwordRemind();
        });

        var passRememberSlide = new Fx.Slide('passRememerDiv');
        passRememberSlide.slideOut();
        $('passRemeberToggle').addEvent('click', function(e){
	     e = new Event(e);
            passRememberSlide.toggle();
	     e.stop();
        });
    }

    if($('agentRegisterForm')){
        $('agentRegisterButton').addEvent('click', function() {
            agentRegister();
        });
        $('agentRegisterForm').addEvent('submit', function(e) {
            var event = new Event(e).stop();
        });
    }

    if($('agentChangeInfoForm')){
        $('agentChangeInfoButton').addEvent('click', function() {
            agentCangeInfo();
        });
        $('agentChangeInfoForm').addEvent('submit', function(e) {
            var event = new Event(e).stop();
        });
    }

    if($('popular-tours')) {
        addTips($$('.tip'));
    }
    
    if ($('countrySelectForm')) {
        $('countryId').addEvent('change', function() {
            selectSimpleCountry();
        });        
    }

    if( $$('#maincontent .right-images a').length > 0) {
        $$('#maincontent table').each(function(table) {
            table.removeProperty('width');    
        })
    }
});



function checkTourSearchForm() {
    var now = new Date();
    var curDate = new Date(now.getUTCFullYear(),now.getUTCMonth()+1,now.getUTCDate(),0,0,0);

    var firstDateArr = $('start_date').getProperty('value').split(".",3)
    var firstDate = new Date(firstDateArr[2],firstDateArr[1],firstDateArr[0],00,00,00);
    var secondDateArr = $('end_date').getProperty('value').split(".",3)
    var secondDate = new Date(secondDateArr[2],secondDateArr[1],secondDateArr[0],00,00,00);

    var startPrice = $('start_price').getProperty('value');
    if(startPrice=='') startPrice=0;
    startPrice = parseInt(startPrice);

    var endPrice   = $('end_price').getProperty('value');
    if(endPrice=='') endPrice=0;
    var endPrice   = parseInt(endPrice);

    if((secondDate < firstDate) && (secondDate.toString() != curDate.toString())) {
        alert('Дата отьезда должна быть позже даты прибытия');
        return false;
    } else if(isNaN(startPrice)) {
        alert('Минимальная стоимость указана неправильно');
        return false;
    } else if(isNaN(endPrice)) {
        alert('Максимальная стоимость указана неправильно');
        return false;
    } else if((startPrice > endPrice) && (startPrice > 0) && (endPrice > 0)) {
        alert('Минимальная стоимость должна быть менше максимальной');
        return false;
    } else {
        return true;
    }
}

function checkTextSearchForm() {
    if($('searchedWord').getProperty('value').length <= 3) {
        alert('Искомое слово должно быть длинее трёх символов');
        return false;
    } else if($('searchedWord').getProperty('value') == searchFromText) {
        alert('Вы не ввели искомое слово');
        return false;
    } else {
        return true;
    }
}

function selectSimpleCountry() {
    if($('countryId').getProperty('value') == '') {
        alert('Выберите пожалуйста страну');
    } else {
        $('countrySelectForm').setProperty('action', '/country/' + $('countryId').value + '/')  
        $('countrySelectForm').submit();
    }
}

function addTips(ojects) {
    new Tips(ojects, {
       className: 'mooTips',
       maxTitleChars: 70
    });
}
/****************************************************************************** MENU *********/
function setSubMenuWidth(submenuElement) {
   maxWidth = 0;
   $$('#' + submenuElement.id + ' a').each(function(subMenuLink) {
	if(subMenuLink.getText().length > maxWidth) {
           maxWidth = subMenuLink.getText().length;
       }
   });
   maxWidth  *= 9.2;
   if( maxWidth < 155 ) {
      maxWidth = 155;
   }
   
}

var disappeardelay=50  //menu disappear speed onMouseout (in miliseconds)
var enableanchorlink=0 //Enable or disable the anchor link when clicked on? (1=e, 0=d)
var hidemenu_onclick=1 //hide menu when user clicks within menu? (1=yes, 0=no)

/////No further editting needed

var ie5=document.all
var ns6=document.getElementById&&!document.all

function getposOffset(what, offsettype)
{
 var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
 var parentEl=what.offsetParent;
 while (parentEl!=null)
 {
  totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
  parentEl=parentEl.offsetParent;
 }
 return totaloffset;
}

function showhide(obj, e, visible, hidden)
{
 if (ie5||ns6)
  dropmenuobj.style.left=dropmenuobj.style.top=-500
 if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover")
  obj.visibility=visible
 else if (e.type=="click")
  obj.visibility=hidden
}

function iecompattest()
{
 return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge)
{
 var edgeoffset=0
 if (whichedge=="rightedge")
 {
  var windowedge=ie5 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
  dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
  if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
  edgeoffset=dropmenuobj.contentmeasure-obj.offsetWidth
 }
 else
 {
  var topedge=ie5 && !window.opera? iecompattest().scrollTop : window.pageYOffset
  var windowedge=ie5 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
  dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
  if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)
  { //move up?
   edgeoffset=dropmenuobj.contentmeasure+obj.offsetHeight
   if ((dropmenuobj.y-topedge)<dropmenuobj.contentmeasure) //up no good either?
   edgeoffset=dropmenuobj.y+obj.offsetHeight-topedge
  }
 }
 return edgeoffset
}

function dropdownmenu(obj, e, dropmenuID)
{
 if (window.event) event.cancelBubble=true
 else if (e.stopPropagation) e.stopPropagation()
 if (typeof dropmenuobj!="undefined") //hide previous menu
  dropmenuobj.style.visibility="hidden"
 clearhidemenu()
 if (ie5||ns6)
 {
  obj.onmouseout=delayhidemenu
  dropmenuobj=document.getElementById(dropmenuID)
  if (hidemenu_onclick) dropmenuobj.onclick=function(){dropmenuobj.style.visibility='hidden'}
  dropmenuobj.onmouseover=clearhidemenu
  dropmenuobj.onmouseout=ie5? function(){ dynamichide(event)} : function(event){ dynamichide(event)}
  showhide(dropmenuobj.style, e, "visible", "hidden")
  dropmenuobj.x=getposOffset(obj, "left")
  dropmenuobj.y=getposOffset(obj, "top")
  dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px"
  dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px"
 }
 return clickreturnvalue()
}

function clickreturnvalue()
{
 if ((ie5||ns6) && !enableanchorlink) return false
 else return true
}

function contains_ns6(a, b)
{
 while (b.parentNode)
  if ((b = b.parentNode) == a)
 return true;
 return false;
}

function dynamichide(e)
{
 if (ie5&&!dropmenuobj.contains(e.toElement))
  delayhidemenu()
 else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
  delayhidemenu()
}

function delayhidemenu()
{
 delayhide=setTimeout("dropmenuobj.style.visibility='hidden'",disappeardelay)
}

function clearhidemenu()
{
 if (typeof delayhide!="undefined")
  clearTimeout(delayhide)
}


/******************************************************Slide_Show***************************************/
     window.addEvent('domready', function() {
     	if($$('.tour-slide').length >= 3){         
            mouseOnSlideshow = false;
            var maxSlideChanges = 10;
            $('slideShow').addEvent('mouseover', function() {
 	         mouseOnSlideshow = true;
            }).addEvent('mouseleave', function() {
 	         mouseOnSlideshow = false;
            });		

            tourSlides = new Array;
            $$('.tour-slide').each(function(slide,i) {
                tourSlides[i]  = slide;
				
				
            });
            setSlidesWidth();

            var changeSlideCounter = 1;
        //insert start tour slides (6 pieces)
	    //old slides
            tourSlideCounter = 0; i=0;
            while(tourSlideCounter <= 2){
                tourSlides[i].clone().inject($('oldSlides'));
                i++;
                if(i == tourSlides.length) i=0;
                tourSlideCounter++;
            }
            if(i == tourSlides.length) i=0;
             

            changeSlide = function() {
              if( changeSlideCounter > maxSlideChanges) {
                $clear(changeSlide);
                return false; 
              }
              if( !mouseOnSlideshow ) {           
           //remove slide
                $$('#oldSlides .tour-slide').each(function(slide,i) {
                    slide.getElement('.tour-slide-text').setStyle('opacity', 1).effect('opacity', {duration: 400}).start(0).chain(function() {
                          slide.effect('opacity', {duration: 700}).start(0).chain(function() { 
                                slide.remove();
                          });
                    });
                });
        //add slide
                tourSlideCounter = 0;
                while(tourSlideCounter <= 2){
                //add 1 tour slide
                   newSlide = tourSlides[i].clone();
                   newSlide.inject($('newSlides')).setStyle('opacity', 0).effect('opacity', {duration: 1000}).start(1);
                   i++;
                   if(i == tourSlides.length) i=0;
                   tourSlideCounter++;
                }
        //change id in new slides and old slides divs
                $('oldSlides').id     = 'slideShowTemp';
                $('newSlides').id     = 'oldSlides';
                $('slideShowTemp').id = 'newSlides';

                $('newSlides').injectAfter('oldSlides');

              }
              changeSlideCounter++; 
            }.periodical(1000+slideShowTimeout*1000);

            window.addEvent('resize', function() {
                setSlidesWidth();
            });
        }
    });

function setSlidesWidth() { 
    var newSlideWidth = (window.getWidth() / 3.22).round();
    if( newSlideWidth > 340 ) {
        newSlideWidth = 340
    }    

    tourSlides.each(function(slide) {
        slide.setStyle('width', newSlideWidth + 'px');
    });
    $$('.tour-slide').each(function(slide) {
        slide.setStyle('width', newSlideWidth + 'px');
    });
}


/****************************************************SWF object****************************************/
/**
 * SWFObject v1.4.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){if(!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();
if(c){this.addParam("bgcolor",c);}
var q=_8?_8:"high";
this.addParam("quality",q);
this.setAttribute("useExpressInstall",_7);
this.setAttribute("doExpressInstall",false);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){_16.push(key+"="+_18[key]);}
return _16;},getSWFHTML:function(){var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){
this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";
}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}
return _19;
},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
var n=(typeof _20=="string")?document.getElementById(_20):_20;
n.innerHTML=this.getSWFHTML();return true;
}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(){
var _23=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}
catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}
catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}
catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}
return _23;};
deconcept.PlayerVersion=function(_27){
this.major=_27[0]!=null?parseInt(_27[0]):0;
this.minor=_27[1]!=null?parseInt(_27[1]):0;
this.rev=_27[2]!=null?parseInt(_27[2]):0;
};
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){
return false;
}return true;};
deconcept.util={getRequestParameter:function(_29){
var q=document.location.search||document.location.hash;
if(q){var _2b=q.substring(1).split("&");
for(var i=0;i<_2b.length;i++){
if(_2b[i].substring(0,_2b[i].indexOf("="))==_29){
return _2b[i].substring((_2b[i].indexOf("=")+1));}}}
return "";}};
deconcept.SWFObjectUtil.cleanupSWFs=function(){if(window.opera||!document.all){return;}
var _2d=document.getElementsByTagName("OBJECT");
for(var i=0;i<_2d.length;i++){_2d[i].style.display="none";for(var x in _2d[i]){
if(typeof _2d[i][x]=="function"){_2d[i][x]=function(){};}}}};
deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};
__flash_savedUnloadHandler=function(){};
if(typeof window.onunload=="function"){
var _30=window.onunload;
window.onunload=function(){
deconcept.SWFObjectUtil.cleanupSWFs();_30();};
}else{window.onunload=deconcept.SWFObjectUtil.cleanupSWFs;}};
if(typeof window.onbeforeunload=="function"){
var oldBeforeUnload=window.onbeforeunload;
window.onbeforeunload=function(){
deconcept.SWFObjectUtil.prepUnload();
oldBeforeUnload();};
}else{window.onbeforeunload=deconcept.SWFObjectUtil.prepUnload;}
if(Array.prototype.push==null){
Array.prototype.push=function(_31){
this[this.length]=_31;
return this.length;};}
var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject;
var SWFObject=deconcept.SWFObject;


// -------------------------------------------------------------------
// Image Thumbnail Viewer Script- By Dynamic Drive, available at: http://www.dynamicdrive.com
// Last updated: Jan 22nd, 2007
// -------------------------------------------------------------------

var thumbnailviewer={
enableTitle: true, //Should "title" attribute of link be used as description?
enableAnimation: true, //Enable fading animation?
definefooter: '<div class="footerbar">Закрыть Х</div>', //Define HTML for footer interface
defineLoading: '<img src="/templates/images/loading.gif" /> Загрузка изображения...', //Define HTML for "loading" div

/////////////No need to edit beyond here/////////////////////////

scrollbarwidth: 16,
opacitystring: 'filter:progid:DXImageTransform.Microsoft.alpha(opacity=10); -moz-opacity: 0.1; opacity: 0.1',
targetlinks:[], //Array to hold links with rel="thumbnail"

createthumbBox:function(){
//write out HTML for Image Thumbnail Viewer plus loading div
document.write('<div id="thumbBox" onClick="thumbnailviewer.closeit()"><div id="thumbImage"></div>'+this.definefooter+'</div>')
document.write('<div id="thumbLoading">'+this.defineLoading+'</div>')
this.thumbBox=document.getElementById("thumbBox")
this.thumbImage=document.getElementById("thumbImage") //Reference div that holds the shown image
this.thumbLoading=document.getElementById("thumbLoading") //Reference "loading" div that will be shown while image is fetched
this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
},


centerDiv:function(divobj){ //Centers a div element on the page
var ie=document.all && !window.opera
var dom=document.getElementById
var scroll_top=(ie)? this.standardbody.scrollTop : window.pageYOffset
var scroll_left=(ie)? this.standardbody.scrollLeft : window.pageXOffset
var docwidth=(ie)? this.standardbody.clientWidth : window.innerWidth-this.scrollbarwidth
var docheight=(ie)? this.standardbody.clientHeight: window.innerHeight
var docheightcomplete=(this.standardbody.offsetHeight>this.standardbody.scrollHeight)? this.standardbody.offsetHeight : this.standardbody.scrollHeight //Full scroll height of document
var objwidth=divobj.offsetWidth //width of div element
var objheight=divobj.offsetHeight //height of div element
var topposition=(docheight>objheight)? scroll_top+docheight/2-objheight/2+"px" : scroll_top+10+"px" //Vertical position of div element: Either centered, or if element height larger than viewpoint height, 10px from top of viewpoint
divobj.style.left=docwidth/2-objwidth/2+"px" //Center div element horizontally
divobj.style.top=Math.floor(parseInt(topposition))+"px"
divobj.style.visibility="visible"
},

showthumbBox:function(){ //Show ThumbBox div
this.centerDiv(this.thumbBox)
if (this.enableAnimation){ //If fading animation enabled
this.currentopacity=0.1 //Starting opacity value
this.opacitytimer=setInterval("thumbnailviewer.opacityanimation()", 20)
}
},


loadimage:function(link){ //Load image function that gets attached to each link on the page with rel="thumbnail"
if (this.thumbBox.style.visibility=="visible") //if thumbox is visible on the page already
this.closeit() //Hide it first (not doing so causes triggers some positioning bug in Firefox
var imageHTML='<img src="'+link.getAttribute("href")+'" style="'+this.opacitystring+'" />' //Construct HTML for shown image
if (this.enableTitle && link.getAttribute("title")) //Use title attr of the link as description?
imageHTML+='<br />'+link.getAttribute("title")
this.centerDiv(this.thumbLoading) //Center and display "loading" div while we set up the image to be shown
this.thumbImage.innerHTML=imageHTML //Populate thumbImage div with shown image's HTML (while still hidden)
this.featureImage=this.thumbImage.getElementsByTagName("img")[0] //Reference shown image itself
this.featureImage.onload=function(){ //When target image has completely loaded
thumbnailviewer.thumbLoading.style.visibility="hidden" //Hide "loading" div
thumbnailviewer.showthumbBox() //Display "thumbbox" div to the world!
}
if (document.all && !window.createPopup) //Target IE5.0 browsers only. Address IE image cache not firing onload bug: panoramio.com/blog/onload-event/
this.featureImage.src=link.getAttribute("href")
this.featureImage.onerror=function(){ //If an error has occurred while loading the image to show
thumbnailviewer.thumbLoading.style.visibility="hidden" //Hide "loading" div, game over
}
},

setimgopacity:function(value){ //Sets the opacity of "thumbimage" div per the passed in value setting (0 to 1 and in between)
var targetobject=this.featureImage
if (targetobject.filters && targetobject.filters[0]){ //IE syntax
if (typeof targetobject.filters[0].opacity=="number") //IE6
targetobject.filters[0].opacity=value*100
else //IE 5.5
targetobject.style.filter="alpha(opacity="+value*100+")"
}
else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
targetobject.style.MozOpacity=value
else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
targetobject.style.opacity=value
else //Non of the above, stop opacity animation
this.stopanimation()
},

opacityanimation:function(){ //Gradually increase opacity function
this.setimgopacity(this.currentopacity)
this.currentopacity+=0.1
if (this.currentopacity>1)
this.stopanimation()
},

stopanimation:function(){
if (typeof this.opacitytimer!="undefined")
clearInterval(this.opacitytimer)
},


closeit:function(){ //Close "thumbbox" div function
this.stopanimation()
this.thumbBox.style.visibility="hidden"
this.thumbImage.innerHTML=""
this.thumbBox.style.left="-2000px"
this.thumbBox.style.top="-2000px"
},

cleanup:function(){ //Clean up routine on page unload
this.thumbLoading=null
if (this.featureImage) this.featureImage.onload=null
this.featureImage=null
this.thumbImage=null
for (var i=0; i<this.targetlinks.length; i++)
this.targetlinks[i].onclick=null
this.thumbBox=null
},

dotask:function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
if (target.addEventListener)
target.addEventListener(tasktype, functionref, false)
else if (target.attachEvent)
target.attachEvent(tasktype, functionref)
},

init:function(){ //Initialize thumbnail viewer script by scanning page and attaching appropriate function to links with rel="thumbnail"
if (!this.enableAnimation)
this.opacitystring=""
var pagelinks=document.getElementsByTagName("a")
for (var i=0; i<pagelinks.length; i++){ //BEGIN FOR LOOP
if (pagelinks[i].getAttribute("rel") && pagelinks[i].getAttribute("rel")=="thumbnail"){ //Begin if statement
pagelinks[i].onclick=function(){
thumbnailviewer.stopanimation() //Stop any currently running fade animation on "thumbbox" div before proceeding
thumbnailviewer.loadimage(this) //Load image
return false
}
this.targetlinks[this.targetlinks.length]=pagelinks[i] //store reference to target link
} //end if statement
} //END FOR LOOP
//Reposition "thumbbox" div when page is resized
this.dotask(window, function(){if (thumbnailviewer.thumbBox.style.visibility=="visible") thumbnailviewer.centerDiv(thumbnailviewer.thumbBox)}, "resize")


} //END init() function

}

thumbnailviewer.createthumbBox() //Output HTML for the image thumbnail viewer
thumbnailviewer.dotask(window, function(){thumbnailviewer.init()}, "load") //Initialize script on page load
thumbnailviewer.dotask(window, function(){thumbnailviewer.cleanup()}, "unload")



/********************************************Virtual pages**************************************/
function countVPages(objectsPerPage) {
    var vElementCount = $$('.' + vBlockClassName).length;
    var vPagesCount   = (vElementCount/vBlockPerPage);
    if( vPagesCount > vPagesCount.round() ) {
        return vPagesCount.round() + 1;
    } else {
        return vPagesCount.round();
    }
}

function buildVPageNavigator( vPagesCount ) {
  if ( vPagesCount == 1 ) {
      return false;
  }

  var navTitleDiv = new Element('div', {'class': 'alignleft'});
  navTitleDiv.injectInside(vNavigationPannelId);
  navTitleDiv.setHTML('Навигация по страницам:');

  var vPagesLinks = new Element('div', {'id': 'vPagesLinks'});
  vPagesLinks.injectInside(vNavigationPannelId);

  var vBackLink = new Element('a', {
      'id'    : 'vPageBack',
      'href'  : '#top'
  });
  vBackLink.injectInside('vPagesLinks');
  vBackLink.setHTML('&laquo; Предыдущая');
  vBackLink.addEvent('click', function(e) {     
      new Event(e).stop();
      showBackVPage();
      var myFx = new Fx.Scroll(window).toTop();
  });

  var pageNumber = 1;
  while ( pageNumber <= vPagesCount ) {
      var link = new Element('a', {
          'id'    : 'vPage' + pageNumber,
          'href'  : '#top',
          'rel'   : pageNumber
      });

      link.injectInside('vPagesLinks');
      link.setHTML('<' + pageNumber + '>');
      link.addEvent('click', function(e) {
         new Event(e).stop();
         showVPage(this.rel);
         var myFx = new Fx.Scroll(window).toTop();   
      });
      pageNumber++;
  }

  var vForwardLink = new Element('a', {
      'id'    : 'vPageForward',
      'href'  : '#top'
  });
  vForwardLink.injectInside('vPagesLinks');
  vForwardLink.setHTML('Следующая &raquo;');
  vForwardLink.addEvent('click', function(e) {
      new Event(e).stop();
      showForwardVPage();
      var myFx = new Fx.Scroll(window).toTop();
  });

  vCurrentPage = 1;
  showVPage(vCurrentPage);
}

function showForwardVPage() {
    showVPage( vCurrentPage + 1 );
}
function showBackVPage() {
    showVPage( vCurrentPage - 1 );
}
function showVPage( i ) {
    if(i == 1) {
        $('vPageBack').setStyle('display', 'none');
        $('vPageForward').setStyle('display', 'inline');
    } else if(i == vPagesCount) {
        $('vPageBack').setStyle('display', 'inline');
        $('vPageForward').setStyle('display', 'none');
    } else {
        $('vPageBack').setStyle('display', 'inline');
        $('vPageForward').setStyle('display', 'inline');
    }
    $$('#pageNavigationPaginate a').each(function (pageNavLink) {
        pageNavLink.setStyle('font-weight', 'normal');
    });
    $('vPage' + i).setStyle('font-weight', 'bold');

    $$('.' + vBlockClassName).each(function(vBlock, index){
        if(index >= (i-1)*vBlockPerPage && index < i*vBlockPerPage) {
            vBlock.setStyle('display', 'block');
        } else {
            vBlock.setStyle('display', 'none');
        }
    });
    vCurrentPage = i.toInt();
}

/****************************************************Bookmars***************************************/
function CreateBookmarkLink(url, title) {
    if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera Hotlist
		return true;
    }
}
