// **********************************************************************************
// Открытие изображения в отдельном окне
// **********************************************************************************
var resId=0;
var imgWndw;
function imgOpen(imgLink,Title,level)
{
	if (typeof(window.resizeBy)=='undefined')
		return true;
	imgWndw=window.open('',imgLink.target,'width=100,height=100,toolbar=no,menubar=no,location=no,status=no,resizable=yes,scrollbars=no,left='+(screen.width>>>2)+ ',top='+(screen.height>>>2));
	self.focus();
	var imgTitle=(Title)?Title:imgLink.href;
	with (imgWndw.document)
	{
		open();
		write('<html><head><title>'+imgTitle+'</title></head><body leftmargin="10" topmargin="10" rightmargin="10" bottommargin="10"><img src="'+imgLink.href+'" border="1" bordercolor="#000000" alt="'+imgTitle+'"></body></html>');
		close();
	}
	resId=setInterval('imgResize()',100);
	return false
}

function imgResize()
{
	var w=imgWndw.document.images[0].width+20;
	if (w>screen.availWidth)
		w=screen.availWidth;
	var h=imgWndw.document.images[0].height+20;
	if (h>screen.availHeight)
		h=screen.availHeight;
	if (w>50 && h>50)
	{
		var ww=(imgWndw.innerWidth)?imgWndw.innerWidth:((document.body)? imgWndw.document.body.clientWidth:null);
		var wh=(imgWndw.innerHeight)?imgWndw.innerHeight:((document.body)? imgWndw.document.body.clientHeight:null);
		if (ww && wh)
			imgWndw.resizeBy(w-ww+20,h-wh);
		imgWndw.focus();
		clearInterval(resId)
	}
}

// *************************************************************************************
// jquery
// *************************************************************************************
jQuery.noConflict()

var stepcarousel={
	ajaxloadingmsg: '<div style="margin: 1em; font-weight: bold"><img src="ajaxloadr.gif" style="vertical-align: middle" /> Fetching Content. Please wait...</div>', //customize HTML to show while fetching Ajax content
	configholder: {},

	getCSSValue:function(val){ //Returns either 0 (if val contains 'auto') or val as an integer
		return (val=="auto")? 0 : parseInt(val)
	},

	getremotepanels:function($, config){ //function to fetch external page containing the panel DIVs
		config.$belt.html(this.ajaxloadingmsg)
		$.ajax({
			url: config.contenttype[1], //path to external content
			async: true,
			error:function(ajaxrequest){
				config.$belt.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
			},
			success:function(content){
				config.$belt.html(content)
				config.$panels=config.$gallery.find('.'+config.panelclass)
				stepcarousel.alignpanels($, config)
			}
		})
	},

	alignpanels:function($, config){
		var paneloffset=0
		config.paneloffsets=[paneloffset] //array to store upper left offset of each panel (1st element=0)
		config.panelwidths=[] //array to store widths of each panel
		config.$panels.each(function(index){ //loop through panels
			var $currentpanel=$(this)
			$currentpanel.css({float: 'none', position: 'absolute', left: paneloffset+'px'}) //position panel
			$currentpanel.bind('click', function(e){return config.onpanelclick(e.target)}) //bind onpanelclick() to onclick event
			paneloffset+=stepcarousel.getCSSValue($currentpanel.css('marginRight')) + parseInt($currentpanel.get(0).offsetWidth) //calculate next panel offset
			config.paneloffsets.push(paneloffset) //remember this offset
			config.panelwidths.push(paneloffset-config.paneloffsets[config.paneloffsets.length-2]) //remember panel width
		})
		config.paneloffsets.pop() //delete last offset (redundant)
		config.$belt.css({width: paneloffset+'px'}) //Set Belt DIV to total panels' widths
		this.statusreport(config.galleryid)
		config.oninit()
		config.onslideaction(this)
	},

	stepTo:function(galleryid, pindex){ /*User entered pindex starts at 1 for intuitiveness. Internally pindex still starts at 0 */
		var config=stepcarousel.configholder[galleryid]
		if (typeof config=="undefined"){
			alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
			return
		}
		var pindex=Math.min(pindex-1, config.paneloffsets.length-1)
		var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset)
		config.$belt.animate({left: -endpoint+'px'}, 'slow', function(){config.onslideaction(this)})
		config.currentpanel=pindex
		this.statusreport(galleryid)
	},

	stepBy:function(galleryid, steps){
		var config=stepcarousel.configholder[galleryid]
		if (typeof config=="undefined"){
			alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
			return
		}
		var direction=(steps>0)? 'forward' : 'back' //If "steps" is negative, that means backwards
		var pindex=config.currentpanel+steps //index of panel to stop at
		pindex=(pindex>config.paneloffsets.length-1 || pindex<0 && pindex-steps>0)? 0 : (pindex<0)? config.paneloffsets.length+steps : pindex //take into account end or starting panel and step direction
		var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset) //left distance for Belt DIV to travel to
		if (pindex==0 && direction=='forward' || config.currentpanel==0 && direction=='back'){ //decide whether to apply "push pull" effect
			config.$belt.animate({left: -config.paneloffsets[config.currentpanel]-(direction=='forward'? 100 : -30)+'px'}, 'normal', function(){
				config.$belt.animate({left: -endpoint+'px'}, 'slow', function(){config.onslideaction(this)})
			})
		}
		else
			config.$belt.animate({left: -endpoint+'px'}, 'slow', function(){config.onslideaction(this)})
		config.currentpanel=pindex
		this.statusreport(galleryid)
	},

	statusreport:function(galleryid){
		var config=stepcarousel.configholder[galleryid]
		var startpoint=config.currentpanel //index of first visible panel
		var visiblewidth=0
		for (var endpoint=startpoint; endpoint<config.paneloffsets.length; endpoint++){ //index (endpoint) of last visible panel
			visiblewidth+=config.panelwidths[endpoint]
			if (visiblewidth>config.gallerywidth){
				break
			}
		}
		startpoint+=1 //format startpoint for user friendiness
		endpoint=(endpoint+1==startpoint)? startpoint : endpoint //If only one image visible on the screen and partially hidden, set endpoint to startpoint
		var valuearray=[startpoint, endpoint, config.panelwidths.length]
		for (var i=0; i<config.statusvars.length; i++){
			window[config.statusvars[i]]=valuearray[i] //Define variable (with user specified name) and set to one of the status values
			config.$statusobjs[i].html(valuearray[i]) //Populate element on page with ID="user specified name" with one of the status values
		}
	},

	setup:function(config){
		//Disable Step Gallery scrollbars ASAP dynamically (enabled for sake of users with JS disabled)
		document.write('<style type="text/css">\n#'+config.galleryid+'{overflow: hidden;}\n</style>')
		jQuery(document).ready(function($){
			config.$gallery=$('#'+config.galleryid)
			config.gallerywidth=config.$gallery.width()
			config.$belt=config.$gallery.find('.'+config.beltclass) //Find Belt DIV that contains all the panels
			config.$panels=config.$gallery.find('.'+config.panelclass) //Find Panel DIVs that each contain a slide
			config.onpanelclick=(typeof config.onpanelclick=="undefined")? function(target){} : config.onpanelclick //attach custom "onpanelclick" event handler
			config.onslideaction=(typeof config.onslide=="undefined")? function(){} : function(beltobj){$(beltobj).stop(); config.onslide()} //attach custom "onslide" event handler
			config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
			config.beltoffset=stepcarousel.getCSSValue(config.$belt.css('marginLeft')) //Find length of Belt DIV's left margin
			config.statusvars=config.statusvars || []  //get variable names that will hold "start", "end", and "total" slides info
			config.$statusobjs=[$('#'+config.statusvars[0]), $('#'+config.statusvars[1]), $('#'+config.statusvars[2])]
			config.currentpanel=0
			stepcarousel.configholder[config.galleryid]=config //store config parameter as a variable
			if (config.contenttype[0]=="ajax" && typeof config.contenttype[1]!="undefined") //fetch ajax content?
				stepcarousel.getremotepanels($, config)
			else
				stepcarousel.alignpanels($, config) //align panels and initialize gallery
		}) //end document.ready
		jQuery(window).bind('unload', function(){ //clean up
			jQuery.each(config, function(ai, oi){
				oi=null
			})
			config=null
		})
	}
}

stepcarousel.setup({
		galleryid: 'mygallery', //id of carousel DIV
		beltclass: 'belt', //class of inner "belt" DIV containing all the panel DIVs
		panelclass: 'panel', //class of panel DIVs each holding content
		statusvars: ['statusA', 'statusB', 'statusC'], //register 3 variables that contain current panel (start), current panel (last), and total panels
		contenttype: ['inline'] //content setting ['inline'] or ['external', 'path_to_external_file']
	})

// *******************************************************************************
// Авторизация (куки)
// *******************************************************************************
function setCookie(name, value, expires, path, domain, secure)
{
	var curCookie = name + "=" + escape(value) +
  	((expires) ? "; expires=" + expires.toGMTString() : "") +
  	((path) ? "; path=" + path : "") +
  	((domain) ? "; domain=" + domain : "") +
  	((secure) ? "; secure" : "")
 	if ((name + "=" + escape(value)).length <= 4000)
  		document.cookie = curCookie
 	else
  		if (confirm("Cookie превышает 4KB и будет вырезан"))
   			document.cookie = curCookie
}

function getCookie(name)
{
	var prefix = name + "="
 	var cookieStartIndex = document.cookie.indexOf(prefix)
	if (cookieStartIndex == -1)
		return null
 	var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
 	if (cookieEndIndex == -1)
		cookieEndIndex = document.cookie.length
 	return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}

function deleteCookie(name, path, domain)
{
	if (getCookie(name))
	{
  		document.cookie = name + "=" + ((path) ? "; path=" + path : "") +
   		((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT"
 	}
}

//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs)
{
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();

    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}


// ********************************************************************************************
// Работа с полями в форме редактирования данных в личном кабинете
// ********************************************************************************************
function _prof(name, value, a, type_id)
{
	if(type_id == 1)
	{
		name  += '_another';
		field = eval("document.forms['fm_aprivate']." + name);
		if(field)
		{
			if(value == 'another')
			{
				field.disabled = false;
			}
			else
			{
				field.disabled = true;
				field.value = '';
			}
		}
	}
	else if(type_id == 2)
	{
		if (a == 1)
			document.getElementById('turop').style.display='none';
		else
			document.getElementById('turop').style.display='block';
	}
}
function _enabled(name)
{
	name  += '_another';
	field = eval("document.forms['fm_aprivate']." + name);
	if(field)
		field.disabled = false;
}
function _disabled(name)
{
	name  += '_another';
	field = eval("document.forms['fm_aprivate']." + name);
	if(field)
	{
		field.disabled = true;
		field.value = '';
	}
}
function _profload()
{
	_fld = document.getElementById('fld_profil1').checked;

	if ( _fld == true )
		document.getElementById('turop').style.display='none';
	else
		document.getElementById('turop').style.display='block';
}

// ***************************************************************************************************
// Функции для календаря в курсах валют
// ***************************************************************************************************
function submit_calendar(day)
{
	document.forms['calendar'].day.value = day;
	document.forms['calendar'].submit();
}
function ClickDay(day)
{
	if (day < 10)
	{
		date = "0"+day+"/"+document.calendar.month.value+"/"+document.calendar.year.value;
	}
	else
	{
		date = day+"/"+document.calendar.month.value+"/"+document.calendar.year.value;
	}
	if(document.calendar.select_date[0].checked)
	{
		document.calendar.date_from.value = date;
		document.calendar.select_date[1].checked = true;
	}
	else
	{
		document.calendar.date_to.value = date;
	}
}

// *****************************************************************************************************
// Функция динамического изменения высоты фрейма
// *****************************************************************************************************
function autoIframe(frameId)
{
        try{
                frame = document.getElementById(frameId);
                innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
                objToResize = (frame.style) ? frame.style : frame;
                objToResize.height = innerDoc.body.scrollHeight + 10;
        }
        catch(err)
	{
                window.status = err.message;
        }
}

// ******************************************************************************************************
// Функция для отображения формы поиска
// ******************************************************************************************************
function showSearchForm(formId, unrollId, rollId)
{
	formId = document.getElementById(formId);
	rollId = document.getElementById(rollId);
	unrollId = document.getElementById(unrollId);
	
	if(unrollId.style.display == 'inline')
	{
		unrollId.style.display = 'none';	
		rollId.style.display = 'inline';
		formId.style.display = 'block'; 
	}
	else	
	{
		unrollId.style.display = 'inline';	
		rollId.style.display = 'none';
		formId.style.display = 'none';
	}

	return false;
}

// *****************************************************************************************************
// Функция ограничения длины текста в textarea
// *****************************************************************************************************
function limitText(limitField, limitNum) 
{
	if (limitField.value.length > limitNum) 
		limitField.value = limitField.value.substring(0, limitNum);
}

// *****************************************************************************************************
// Устанавливаем минимальную дату в поле from (поиск попутчика)
// *****************************************************************************************************
function setMinDate()
{
	if(document.getElementById('date_from').value > document.getElementById('date_to').value)
		document.getElementById('date_to').value = document.getElementById('date_from').value;
}

function my_zeroFill(value) 
{
	return (value < 10?'0':'') + value;
}

// Получить дату в строковом формате
function my_GetStrDate(date) 
{
	if(!date) 
	{
		return "";
	}
	else 
	{
		var Day=my_zeroFill(date.getDate());
		var Month=my_zeroFill(date.getMonth()+1);
		var Year=date.getFullYear();
		var shortYear=date.getYear();
	
		if(shortYear>=2000) { shortYear-=2000; } // перегибы на местах
		else if(shortYear>=100) { shortYear-=100; } // перегибы на местах
	
		shortYear=my_zeroFill(shortYear);
	
		return Day+'.'+Month+'.'+Year;
	}
}

// *****************************************************************************************************
// Устанавливаем минимальную дату в поле from (быстрый поиск тура)
// *****************************************************************************************************
function setMinDateTourSearch()
{
	var date = document.getElementById('df').value;
	var a_date = date.split('.');
	var date = Date.parse(a_date[1]+'/'+a_date[0]+'/'+a_date[2]);
	var date = new Date(date);
	date0 = new Number(a_date[0]);
	date.setDate(date0+7);
	document.getElementById('dt').value = my_GetStrDate(date);
}

// *****************************************************************************************************
// Инициализация формы быстрого поиска тура (быстрый поиск тура)
// *****************************************************************************************************
function tour_search_block_init()
{
	if(document.getElementById('co').value == 0)
	{
		document.getElementById('re').disabled = true;
		document.getElementById('al').disabled = true;
	}
	if(document.getElementById('re').value == 0)
	{
		document.getElementById('al').disabled = true;
	}
}

// ****************************************************************************************************
// Открытие окна для заказа тура из туриндекса
// ****************************************************************************************************
function ShowWin(url,x,y,name,isscrollbars) 
{
	cx=screen.width/2-(x/2);
	cy=screen.height/2-(y/2);
	isscrollbars=(isscrollbars=="no")?"no":"yes";
	window.open(url,name,"toolbar=no,status=no,directories=no,menubar=no,resizable=yes,width="+x+",height="+y+",scrollbars="+isscrollbars+",top="+cy+",left="+cx);
}
