// JavaScript Document

if (!document.all) {  
document.constructor.prototype.__defineGetter__('all', function() { return document.getElementsByTagName('*'); } );  
}  


//browser detection and action 
var ua = navigator.userAgent.toLowerCase();
isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1);
isOpera = (ua.indexOf("opera") != -1);
isGecko = (ua.indexOf("gecko") != -1);
isSafari = (ua.indexOf("safari") != -1);
isKonqueror = (ua.indexOf("konqueror") != -1);

 if(isIE){

 var vers = navigator.userAgent.substring(30,31);

   
 if((parseInt(vers)<8)){
 window.location = "browser.html";
 }

 }

 //-------------------------

 //flash version detection

      var isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1);
      var version = 0;
      var lastVersion = 11; 
      var i;
      if (isIE) { // browser == IE

            try {
                  for (i = 3; i <= lastVersion; i++) {

       if (eval('new ActiveXObject("ShockwaveFlash.ShockwaveFlash.'+i+'")')) {

                             version = i;
                        }
                  }

            } catch(e) {}

      } else { // browser != IE

            for (i = 0; i < navigator.plugins.length; i++) {

                  if (navigator.plugins[i].name.indexOf('Flash') > -1) {

						version = parseInt(navigator.plugins[i].description.charAt(16)+ navigator.plugins[i].description.charAt(17));

                  }

            }

      }

    

if((window.location.href.indexOf('eng')!=-1)||(window.location.href.indexOf('fin')!=-1)){
	
	 if(version<9){

		 window.location = "flash.html";

	 }

}


 //--------------------------

function hide(someID){

document.getElementById(someID).src = "color-"+someID+"-hotel.jpg"; 

}

function show(someID){

document.getElementById(someID).src = "bw-"+someID+"-hotel.jpg"; 

}



function pictureWindow(image,gal){

var hotel_gallery = gal;
Shadowbox.open([image]);	

}



function activateSpecials(){
var button = document.getElementById("activator");
var selector = document.getElementById("offerSelect");
if(button.checked){
selector.disabled = false;
}else{
selector.disabled = true;	
}

}



function langChoose(selected_lang){

var path  = window.location.toString();
var z = path.lastIndexOf("/");
var letter = new String("");
var doc_name = new String("");
str1 = new String("");
for(i=z+1;i<path.length;i++){

letter = path.charAt(i);

doc_name = doc_name.concat(letter);

}



if(doc_name==""){
	doc_name="index.html";
}


if(selected_lang.indexOf("rus")!=-1){
selected_lang = "";	
}


if((doc_name.indexOf("eng")!=-1)||(doc_name.indexOf("fin")!=-1)){

	var	new_doc_name = new String("");
	for(i=4;i<doc_name.length;i++){
    letter = doc_name.charAt(i);
    new_doc_name = new_doc_name.concat(letter);

	}
window.location = selected_lang+new_doc_name;

}else{

window.location = selected_lang+doc_name;

}

}


function showIfConfermed(checker, showObj){
	
	
	
	if(typeof(checker)=='string'){
		checker = document.getElementById(checker);
	}
	
	if(typeof(showObj)=='string'){
		showObj = document.getElementById(showObj);
	}
	
//var initAction = showObj.onclick;


	
	if(!checker.checked){
		
		showObj.style.opacity = "0.3";
		showObj.disabled = "disabled";
		/*showObj.onclick = function(){
		return false;
		}*/
	}else{
		showObj.style.opacity = "1.0";
		showObj.disabled = false;
		//showObj.onclick = function(){initAction();};
	}
	

}//end up func


//part from util_scripts_1

if((!document._cLang)||(document._cLang == undefined)){
document._cLang = "rus";	
}

if(!document._execOrders){
document._execOrders=[];
}


//common used funcs to work with spry ds's

function dsHandler(dataset,action,args,uniqID){
	
	if(uniqID==undefined){
		
		uniqID = document._execOrders.length;
		
	}
	
	//alert('checking action '+action+'  uniqID = '+uniqID);
	
	//------------------------------------------
	//a misssuccessfull try to fix the bug of unwished calling same funcs second time (do not work correctly for compare )
	/*for(c=0;c<document._execOrders.length;c++){
	someOrder = document._execOrders[c];
	
	for(i in args){
		if(args.i==undefined){
			emptyArgs=true;
		}else{
			emptyArgs=false;
		}
	}
	if((someOrder.ds == dataset)&&(someOrder.act==action)&&((someOrder.args==args)||(emptyArgs))&&(!someOrder.complete)&&(someOrder.id!=uniqID)){
		//alert('same order detected before first one completed');
		return;
	}
	}//end up for*/
	//--------------------------------------------
	
	
	if(!document._execOrders[uniqID]){
	order = {};
	order.ds = dataset;
	order.act = action;
	order.args = args;
	order.id = uniqID;
	order.counter = 0;
	order.complete = false;
	document._execOrders[uniqID] = order;	
	}//else{
	
	//test_tag = document.getElementById("test");
	//test_tag.innerHTML += ('uniqID = '+uniqID+" and _execOrders.length= "+document._execOrders.length+'</br>');
	
	
    stringCommand = "dsHandler(document._execOrders["+uniqID+"].ds,document._execOrders["+uniqID+"].act,document._execOrders["+uniqID+"].args,document._execOrders["+uniqID+"].id)";
	

	test = checkDS(dataset,stringCommand,uniqID);
	
	if(test){
	
	order.complete = true;
	order = document._execOrders[uniqID];
	
	//alert('ready to execute action '+action+"  uniqID = "+uniqID);
	
	var act = action(args);
	
	
	//test_tag.innerHTML+="<br>completed "+uniqID+"<br>";
	
	if(uniqID==document._execOrders.length-1){
		
	if(document._preloader){
	$(function(){
	if($('#all').ajaxloader){	
    $('#all').ajaxloader('hide');
	}
    })
	document._preloader = false;
	}
	}
	
	
	return act;
	
	}else{
	
	if((!document._preloader)||(document._preloader == undefined)){
	
	$(function(){
    var some = $('#all').ajaxloader('show');
    });
	document._preloader = true;
	}
	//alert('data not ready, start again');	
	return;	
	}
}


/*function check(){
	lastItem = document._execOrders.length-1;
	theOrder = document._execOrders[lastItem];
	test_tag = document.getElementById("test");
	test_tag.innerHTML+="<br> action= "+theOrder.act+"<br> args = "+theOrder.args+"<br> dataset = "+theOrder.ds.url+"<br> uniqID = "+theOrder.id;
}
*/

function checkDS(ds,refererFunc,orderNum){
	
	if(ds.getDataWasLoaded()){
	var isLoaded = true;
	
	if(document._execOrders[orderNum].timer){
		//clearInterval(document._execOrders[orderNum].timer);
		clearTimeout(document._execOrders[orderNum].timer); 
	}
	
	return isLoaded;
	}else{
		
		if(document._execOrders[orderNum].counter<10){
			document._execOrders[orderNum].counter++;
			document._execOrders[orderNum].timer = setTimeout(refererFunc,1000);
			
			
		}else{
			var isLoaded = false;
			//document._execOrders[orderNum].complete = true;
			//alert("Ошибка доступа к данным. Пожалуйста, сообщите об этом любому представителю ЗАО ТУРРИС. Error attepmting to load data, sorry. Please report about this to any Turris official");
			return isLoaded;
		}
	
	}
	
		
}//end up func


//automatic gallery funcs

function getLettersBefore(index,picture){

//alert('function getLettersBefore active');

var letter = new String("");

variable = new String("");

for(i=0;i<index;i++){

letter = picture.charAt(i);

variable = variable.concat(letter);

}//end up for

return variable;

}//end up func





function getLettersAfter(index,picture){

//alert('function getLettersAfter active');

var letter = new String("");

variable = new String("");

for(i=index;i<picture.length;i++){

letter = picture.charAt(i);

variable = variable.concat(letter);

}//end up for

return variable;

}//end up func





function showFullGallery(pict, objID){
	


document._fileExt = new String("");	

document._initPictName = new String("");

document._filePath = new String("");





//showing preloader

if(objID){

var preloader = document.getElementById(objID+"preloader");

var preloaderImg = document.createElement('img');

preloaderImg.src = "small_red_preloader.gif";

preloader.appendChild(preloaderImg);

}



var z = pict.lastIndexOf(".");

//getting to know the file extention

document._fileExt = getLettersAfter(z,pict);

//getting source without .jpg or .gif and or whatever

document._initPictName = getLettersBefore(z,pict);

//getting rid of slashes if they exist

var y = document._initPictName.lastIndexOf("/");

if(y!=-1){

document._filePath = getLettersBefore(y,pict)+"/";

document._initPictName = getLettersAfter(y+1,document._initPictName);

}

//deleting 'big_' suffix if it exists

var x = document._initPictName.indexOf('big_');

if(x==0){

	document._initPictName = getLettersAfter(x+4,document._initPictName);

}

//deleting number on the end if it exists

var lastItem = parseInt(document._initPictName.charAt(document._initPictName.length-1));

document._callerPictName = document._initPictName;

if(!isNaN(lastItem)){

document._initPictName = getLettersBefore(document._initPictName.length-2,document._initPictName);

}//end up else





//adding file path if needed

if(document._filePath==""){

var s = window.location.href.lastIndexOf("/");

document._filePath = getLettersBefore(s,window.location.href)+"/";

}







//getting to know existing fotos



$.ajax({

   type: "POST",

   cache: false,

   url: "file_check.php",

   data: "path="+document._filePath+"&url="+document._initPictName+"&extention="+document._fileExt+"&callerPict="+document._callerPictName,

   success: function(msg){

	   if(objID){

		preloader.removeChild(preloaderImg);   

	   }

	   var photoArr = [];

	   var shadowboxShowArr = [];

	  

	   

	  photoArr = ((msg.split(',')));

	  for(i=0;i<photoArr.length;i++){

		  var photo = {player:"img",title:"Галерея / Gallery", gallery:photoArr, content:photoArr[i]}; 

		  shadowboxShowArr.push(photo);

		  

	  }//end up for

	  if(shadowboxShowArr.length!=0){

     Shadowbox.open(shadowboxShowArr);

	  }else{

		  alert('Извините, медиа файлы не найдены. / Sorry, media files not found.');

	  }//end up else

   }

 });

	

}//end up func


function fillObjByHotel(Args){
	
	if(!Args.obj_DS){
		obj_ds = document._obj_list;
	}else{
		obj_ds = Args.obj_DS;
	}
	
	
	hotField = Args.hotField;
	
	if(Args.defaultHotel){
	for(op=0; op<hotField.options.length; op++){
		if(hotField.options[op].id == Args.defaultHotel){
			hotField.options[op].selected = true;
		}
	}//end up for
	}//end up if
	
	theAmeField = document.getElementById(Args.ameField);
	hotId = hotField.options[hotField.selectedIndex].id;
	if(Args.lang){
		inLang = Args.lang;
	}else{
		inLang = 'rus';
	}
	
	//clearing if ameField is not empty
	if((theAmeField!=null)&&(theAmeField!=undefined)&&(theAmeField.hasChildNodes())){

	for(w=theAmeField.childNodes.length-1;w>=0;w--){
		theAmeField.removeChild(theAmeField.childNodes[w]);
	}//end up for
	}//end up if
	
	
	for(x=0;x<obj_ds.getRowCount();x++){
		obj_ds.setCurrentRow(x);
		oRow = obj_ds.getCurrentRow();
		if((oRow['@type']=='hotel')&&(oRow['@id']==hotId)){
			objNode = obj_ds.data[x].ds_XMLNode;
			for(h=0;h<objNode.childNodes.length;h++){
				theObj = objNode.childNodes[h];
				
				if((theObj.attributes!=null)&&(theObj.attributes.length>0)){
					
					for(p=0;p<theObj.attributes.length;p++){
						if(theObj.attributes[p].nodeName=='id'){
							var the_id_is = theObj.attributes[p].nodeValue;
						}//end up if
						
						if(theObj.attributes[p].nodeName==inLang+'_name'){
							var the_name_is = theObj.attributes[p].nodeValue;
						}//end up if
						
					}//end up for
					
					
					for(g=0;g<theObj.attributes.length;g++){
						if((theObj.attributes[g].nodeName==Args.searchIn)&&(theObj.attributes[g].nodeValue==Args.searchFor)){
					
					//if(theObj.attributes[Args.searchIn].nodeValue==Args.searchFor){
						theOpt = document.createElement('option');
						theOpt.id = the_id_is;
						theOpt.value = the_name_is;
						theOpt.label = the_name_is;
						theOpt.textContent = the_name_is;
						
						if(Args.defaultObj){
						if(theOpt.id == Args.defaultObj){
							theOpt.selected = true;
						}
						}
											
						theAmeField.appendChild(theOpt);
						
					//}
						}
						
					}
				}//end up if
			}//end up for
		}//end up if
	}//end up for
}//end up func


function radioSelect(callerRadio,allRadios,saveInProperty,insertField){
	for(d=0;d<allRadios.length;d++){
		var radioBut = document.getElementById(allRadios[d]);
		if(radioBut){
		if(radioBut!=callerRadio){
			radioBut.checked = false;
		}else{
			
			document._lastSelectedRadio = callerRadio.id;
			document[saveInProperty] = callerRadio.value;
			inField = document.getElementById(insertField);
			inField.value = document[saveInProperty];

			
		}//end up if
	  }//end up if
	}//end up for
}//end up func



function hotel_change(){
	
for(i=0; i<document.getElementById("hotel_selection").options.length; i++){
if(document.getElementById("hotel_selection").options[i].selected){

//block from util_scripts for detecting an html document size
var path  = window.location.toString();
var z = path.lastIndexOf("/");
var letter = new String("");
var doc_name = new String("");
var selected_lang = new String("");
str1 = new String("");
for(n=z+1;n<path.length;n++){

	letter = path.charAt(n);
	doc_name = doc_name.concat(letter);
}

if(doc_name==""){
	doc_name="index.html";
}
//-----------------------------------------------

if((doc_name.indexOf("eng")!=-1)||(doc_name.indexOf("fin")!=-1)){
for(v=0; v<=2; v++){
letter = doc_name.charAt(v);
selected_lang = selected_lang.concat(letter);
				}
window.location = selected_lang+"_"+document.getElementById("hotel_selection").options[i].value+"-hotel-reservation.html";
}else{
window.location = document.getElementById("hotel_selection").options[i].value+"-hotel-reservation.html";
		}
	}
	}
}


function goto_hotel(url_args, theSelector, newWindow){
	
if(theSelector){
	if(typeof(theSelector)=='string'){
	mySel = document.getElementById(theSelector);
	}else{
		mySel = theSelector;
	}
}else{
	mySel = document.getElementById("hotel_selection");
}


if(newWindow){
	theWind = open("");
}else{
theWind = window;	
}
	
for(i=0; i<mySel.options.length; i++){
if(mySel.options[i].selected){
if(mySel.options[i].value!="none"){

if((url_args)&&(url_args!="")){
	theWind.location  = mySel.options[i].value+".html"+url_args;
}else{
theWind.location  = mySel.options[i].value+".html";
}

}
}
}
	
}




function hostHotelDetect(ds_var_name){
	
var ourRow = ds_var_name.getCurrentRow();
var ourNode = ourRow.ds_XMLNode;
var ourParent = ourNode.parentNode;

for(atr=0; atr<ourParent.attributes.length; atr++){
if(ourParent.attributes[atr].nodeName == "id"){
	document._hostHotelId = ourParent.attributes[atr].nodeValue;
}
}

}//end up func


function showSigns(jqry_selector){
$(jqry_selector).each(function(){
if(($(this).html())=='true'){
$(this).html('<img src="images/yes_2.png"/>');	
}//end up if

if(($(this).html())=='false'){
$(this).html('<img src="images/no.png"/>');	
}//end up if


});

}//end up func


function change_inAllNumbs (bySelector, byName){

var newIndexValue = bySelector.options[bySelector.selectedIndex].index;
var totalyNumbs = document._numbers.getRowCount();

if((document._hotel_ID)&&(document._hotel_ID.getDataWasLoaded())){
	cR = document._hotel_ID.getCurrentRow();
	if(cR['@roomNameSuffix']){
	numNameWord = cR['@roomNameSuffix'];
	}
	
}else{

cR = document._numbers.getCurrentRow();
	currNumName = cR['@id'];
	dashPosition = currNumName.indexOf('_');
	numNameWord = ""; 
	for(let=0; let<dashPosition; let++){
		numNameWord += currNumName.charAt(let);
	}//end up for
	
}//end up else

document._questionPermition = false;
for(s_num=1; s_num<=totalyNumbs; s_num++){
	var changeInSel = document.getElementById(numNameWord+"_"+s_num+byName);
	if(changeInSel.id!=bySelector.id){
		if(changeInSel.selectedIndex!=newIndexValue){
		changeInSel.options[newIndexValue].selected = true;
		var countFunc = changeInSel.onchange;
		countFunc();
	}//end up if
	}//end up if
	
}//end up for
document._questionPermition = true;
$("div.jGrowl").jGrowl("close");
//return;
}//end up func





function closeJGrowl(){
	$("div.jGrowl").jGrowl("close");
}//end up func




function askForAll(fromSel, forNames, useInHeader){	
if(document._questionPermition){	
sel = fromSel;
selName = forNames;


if(useInHeader){
$.jGrowl("<span onclick='change_inAllNumbs(sel, selName);' class='quest'>Да</span> <span onclick='closeJGrowl();' class='quest'>Нет<span>", {header: 'Изменить '+useInHeader+' для всех номеров?', life: 6000 });
}else{
$.jGrowl("<span onclick='change_inAllNumbs(sel, selName);' class='quest'>Да</span> <span onclick='closeJGrowl();' class='quest'>Нет<span>", {header: 'Изменить для всех номеров?', life: 6000 });
}


}//end up if
//return;
}//end up func




// function that compares 2 dates

function compareTwoDates(date1, date2, counter){ // yyyy.mm(m).dd
	
	if(!counter){
		counter = 0;
	}
	
	for(i=0;i<date1.length;i++){
		if(typeof(date1[i])!='number'){
		date1[i] = parseInt(date1[i]);
		}
	}
	
	for(i=0;i<date2.length;i++){
		if(typeof(date2[i])!='number'){
		date2[i] = parseInt(date2[i]);
		}
	}
	
	if(date1[counter]>date2[counter]){
		returnValue = true;
	}else{
	
	if(date1[counter]<date2[counter]){
		returnValue = false;
	}else{
	
	if((date1[counter]=date2[counter])&&(counter<3)){
		counter++;
		compareTwoDates(date1, date2, counter);
	}else{
	returnValue = true;	
	}
	
	}//end up else
	
	}//end up else
	
	return returnValue;
	
}//end up func


function period_inRange(period_StDate, period_EndDate, range_StDate, range_EndDate){ // yyyy.mm(m).dd
	
	returnValue = false;
	
	//case 1
	if((compareTwoDates(period_EndDate, range_StDate, 0))&&(compareTwoDates(range_EndDate, period_EndDate, 0))){
		//alert('came first way');
		returnValue = true;
	}else{
	//case 2
	if((compareTwoDates(period_StDate, range_StDate, 0))&&(compareTwoDates(range_EndDate, period_StDate, 0))){
		//alert('came second way');
		returnValue = true;
	}else{
	
	
	//case 3
	if((compareTwoDates(range_StDate, period_StDate, 0))&&(compareTwoDates(period_EndDate, range_EndDate, 0))){
		//alert('came third way');
		returnValue = true;
	}//end up if
	
	}//end up else
	}//end up else
	
	return returnValue;
	
}//end up func


var totalSortedOffers = 0;
offersLimitVar = 0;

function showMore(){

offersMaxLimit=totalSortedOffers+1;

offersLimitVar = 0;
totalSortedOffers = 0;

var rgn = Spry.Data.getRegion('specialoffers');
  if (rgn){
    rgn.updateContent();
	add_moreButton();
	dsHandler(specialoffers,filter_ByDate,{ds:specialoffers, showStat:false, st_calenderElem:'specialoffers_datepicker', end_calenderElem:'specialoffers_datepicker1'});
	
  }
  
}//end up func


function add_moreButton(){
	
	var fairCounter = offersMaxLimit;
	var exists = document.getElementById('showMoreButton');
	var but_container = document.getElementById('more_button_container');
if(totalSortedOffers>fairCounter){
	if(!exists){
		showMoreButton = document.createElement('p');
		showMoreButton.id = 'showMoreButton';
		showMoreButton.innerHTML = 'показать ещё ('+(totalSortedOffers-fairCounter)+')';
		showMoreButton.className = 'show_more_button';
		showMoreButton.onclick = function(){dsHandler(specialoffers,showMore);};
		if(but_container){
		but_container.appendChild(showMoreButton);
		}//end up if
	}//end up if
}else{
	if((exists)&&(but_container)){
		but_container.removeChild(but_container.childNodes[0]);
	}//end up if
}//end up else
}//end up func





function show_hide_collapsing_parts(action, elements, append_rest_elems, classSelector){

if(action == ""){
	return;
}

	
if(action == 'show'){
	actState = 'block';
	restState = 'none';
}else{
	actState = 'none';
	restState = 'block';
}


if(!classSelector){
	classSelector = 'collapsing_part';
}

if(!append_rest_elems){
	append_rest_elems = '1';
}

if(elements!=""){
ameNames = elements.split(',');
}




for(el=0; el<document.all.length; el++){
	if(document.all[el].className == classSelector){
		
		for(ame=0; ame<ameNames.length; ame++){
			
			if(document.all[el].id.indexOf(ameNames[ame])!=-1){
			
				document.all[el].style.display = actState;
				document.all[el]._stayExpanded = true;
				
			}else{
			if(append_rest_elems == '1'){
				if(!document.all[el]._stayExpanded){
				document.all[el].style.display = restState;
				}
				}	
			}//end up else
		}//end up for
		
	}//end up if the class matches
}//end up for

}//end up func
