var mycmps = [];
var mynum = 0;
var myrub = 0;
var doc = window.document;
var browser = new Browser();

//drag
// Determine browser and version.

function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isOpera    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;
  
  s = "Opera";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isOpera = true;
    return;
  }

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
  
  this.isIE = true;
  this.version = parseFloat(ua.substr(i + s.length));
  return;
  
}

function getClientWidth()
{
  return !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}

function getClientHeight()
{
  return !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

function GetXYScroll () {
	
	myPageX=parseInt(document.body.scrollLeft);
	myPageY=parseInt(document.body.scrollTop);
	
	if (!myPageY && (document.documentElement.scrollTop > 0)) {
		myPageX=parseInt(document.documentElement.scrollLeft);
		myPageY=parseInt(document.documentElement.scrollTop);
	}
	if (!myPageY && (window.pageYOffset > 0)) {
		myPageX=parseInt(window.pageXOffset);
		myPageY=parseInt(window.pageYOffset);
	}
	temp = new Array();
	temp[0] = myPageX;
	temp[1] = myPageY;
	return temp;
}

function CenterLayer (layer,width,height,target,xoffset,yoffset) {
	if (!target)
		target=window.document;
	
	LeftX = LeftY = 0;

	aXY = GetXYScroll();
	
	topLayer = aXY[1];
	nScrollTop = target.body.scrollTop;
	
	clW = getClientWidth();
	clH = getClientHeight();
	
	if ((LeftX+width) > clW)
		LeftX = 0;

	if ((LeftY+height) > clH)
		LeftY = 0;

	if ((LeftX > 0) && (LeftY > 0)) {
		target.getElementById(layer).style.left = LeftX+'px';
		target.getElementById(layer).style.top = LeftY+topLayer+'px';
	}
	else {
		if (!xoffset)
			xoffset = 0;
			
		if (!yoffset)
			yoffset = 0;
	
		leftLayer = ((clW - width)/2);
		topLayerABS = (clH - height)/2;
		
		newTop = topLayer + topLayerABS;
		if (newTop < 0)
			newTop=0;
			
		nTop = topLayer + topLayerABS + yoffset;
		nLeft = leftLayer + xoffset;
		
		if (nTop < aXY[1])
			nTop = aXY[1] + 5;
		
		target.getElementById(layer).style.left = nLeft + 'px';
		target.getElementById(layer).style.top = nTop + 'px';
	}
}

function MarketSw () {
	obj=SfindObj('mlist');
	obj1=SfindObj('mcurr');
	obji=SfindObj('mswi');
	if (!obj.style.display || obj.style.display == 'block') {
		obj.style.display = 'none';
		obj1.style.display = 'block';
		obji.src = '/i/default/down.png';
	}
	else {
		obj.style.display = 'block';
		obj1.style.display = 'none';
		obji.src = '/i/default/up.png';
	}
}

var previewvisible = false;
var previewtimeout = 0;

var IE = document.all?true:false;

function hideSpec () {
	$('#preview').hide();
}

function ShowSpec (sText) {
	$('#preview').val(sText);
	$('#preview').show();
}

function Vote (nVote) {
	obj = $('#vote');
	objv = $('#votev');
	if (!obj.length) return;
	
	obj.css('width', nVote * 25 + 'px');
	objv.attr('value', nVote); 
}

function echeck(str) {

		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		if (str.indexOf(at)==-1){
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		   return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		   return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		   return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		   return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		   return false;
		 }

 		 return true;
}

function trim(s,what) {
	while (s.substring(0,1) == what) {
	s = s.substring(1,s.length);
	}
	while (s.substring(s.length-1,s.length) == what) {
	s = s.substring(0,s.length-1);
	}
	return s;
}

function ValidateSendForm (formname,aFields) {
	
	f = window.document.forms[formname];

	
	for (i = 0; i < aFields.length; i++) {
		if (f.elements[aFields[i]]) {
		
			if (aFields[i] == 'email') {
				if (f.email && f.email.value && !echeck(f.email.value)) {
					msg('error','error');
					f.email.focus();
					return false;
				}
			}
		
			if (((f.elements[aFields[i]].getAttribute('type') == 'select-one') && (f.elements[aFields[i]].selectedIndex == 0) && (f.elements[aFields[i]].style.display != 'none')) 
			|| 
			((f.elements[aFields[i]].getAttribute('type') == 'text') && (trim(f.elements[aFields[i]].value,' ') == '') && (f.elements[aFields[i]].style.display != 'none'))
			|| 
			((f.elements[aFields[i]].getAttribute('type') == 'password') && (trim(f.elements[aFields[i]].value,' ') == '') && (f.elements[aFields[i]].style.display != 'none'))
			|| 
			((f.elements[aFields[i]].getAttribute('type') == 'textarea') && (trim(f.elements[aFields[i]].value,' ') == '') && (f.elements[aFields[i]].style.display != 'none'))
			|| 
			((f.elements[aFields[i]].getAttribute('type') == 'hidden') && ((trim(f.elements[aFields[i]].value,' ') == '') || (trim(f.elements[aFields[i]].value,' ') == '0')) && (f.elements[aFields[i]].style.display != 'none'))
			|| 
			((f.elements[aFields[i]].getAttribute('type') == 'checkbox') &&  (!f.elements[aFields[i]].checked))
			|| 
			((f.elements[aFields[i]].getAttribute('type') == null) && (trim(f.elements[aFields[i]].value,' ') == '') && (f.elements[aFields[i]].style.display != 'none'))
			) {
				
				if(error_messages[formname] && error_messages[formname][aFields[i]])
					msg(error_messages[formname][aFields[i]],'err');
				else {
					msg('fillfield','Err');
				}
				try {
					f.elements[aFields[i]].focus();
				}
				catch(e) {;}
				return false;
			}
		}
	}

	return true;
}

function msg(msg,title,func)
{
	alert(msg);
}

function ShowProd (wwidth,wheight,isrc,modelid) {
	if(isrc=='/') return;

	var obj1=doc.getElementById('previewi');
	var obj2=doc.getElementById('previewimg');
	var obj3=doc.getElementById('previewtbl');
	var obj4=doc.getElementById('loading');
	
	if (modelid >=0 ) {
		var objLoad=doc.getElementById("loaddata");
		objLoad.innerHTML='';
		objLoad.style.display='none';
	}

	obj2.src='/i/dot.gif';
	wheight = wheight*1+20;
	obj1.style.width=wwidth+'px';
	obj1.style.height=wheight+'px';
	
	obj3.style.width=wwidth+'px';
	obj3.style.height=wheight+'px';
	
	obj4.style.width=wwidth+'px';
	obj4.style.height=wheight+'px';

	CenterLayer('previewi',wwidth,wheight,doc);
	obj1.style.visibility='visible';

	obj2.src=isrc;
}

function HideProd () {
	var obj1=doc.getElementById('previewi');
	var obj2=doc.getElementById('previewimg');
	var objLoad=doc.getElementById("loaddata");
	objLoad.innerHTML='';
	objLoad.style.display='none';
	obj2.src='/i/dot.gif';
	obj1.style.visibility='hidden';
	
}

function ShowHideSearchRub () {
	$('div#searchrub').toggle();
	$('div#searchrubactivatorshow').toggle();
	$('div#searchrubactivatorhide').toggle();
}

var wndids = new Array();
function parse_json(json) {
	if(json == undefined || !json || json == '') return;
	//json = json.replace('<pre>','');
	//json = json.replace('</pre>','');
	json = eval( "(" + json + ")");
	if(json == undefined || !json || !json.length) return;
	
	for(var i in json)
	{
		if(json[i] == null || typeof(json[i].type)=='undefined') continue;
		
		switch(json[i].type)
		{
			case 'html':
				if(!json[i].id || json[i].id.length < 2) continue;
				var obj = $(json[i].id); if(!obj.length) continue;
				if (json[i].value) {
					obj.html(json[i].value);
					obj.show('fast');
				}
				else {
					obj.hide('fast');
				}
				
				//if (json[i].name == 'actions') {
				//bindaction();
				//}
				
				break;
			case 'html2':
				if(!json[i].id) continue;
				var obj = $(json[i].id); if(!obj.length) continue;
				
				var $new = $('<span></span>').html(json[i].value);
				
				if (json[i].subtype == 'prepend') 
					obj.prepend($new);
				else 
				if (json[i].subtype == 'append') 
					obj.append($new);
				else 
				{
					obj.empty().append($new);
				}
				break;
			case 'inscr':
				apply_scripts(json[i].name);
				break;
				
			case 'code':
				eval(json[i].value);
				break;

			case 'alert':
			case 'msg':
				alert(json[i].value);
				continue;

			case 'go':
				window.location.href = json[i].value;
				continue;

			case 'remove':
				var obj = $('#'+json[i].name); if(!obj.length) continue;
				obj.remove();
				continue;

			case 'wnd':
					if (!wndids[json[i].wndid]) {
						obj = $("<div></div>");
						obj.html(json[i].value);
						ok = lang['line']['ok'];
						
						var buttons = {};
						if (json[i].form)
							buttons[lang['line']['ok']] = function() {$(this).dialog("close");wndids[json[i].wndid] = null;}
						else
							buttons[lang['line']['ok']] = function() {}
						buttons[lang['line']['cancel']] = function() {$(this).dialog("close");wndids[json[i].wndid] = null;}

						$(obj).dialog({
							title: json[i].caption,
							width:json[i].width,
							height:json[i].height,
							resizable: false,
							draggable: true,
							close: function(ev, ui) { wndids[json[i].wndid] = null; },
							position: "center"
						 }).
						 bind('dialogclose', function(event, ui) {	$(this).dialog('destroy').remove(); });
						 wndids[json[i].wndid] = 1;
						// set_form(obj);
					}
				break;
			case 'upl':
				make_upload(json[i]);
				continue;
			case '_msg':
				var wnd = $('#msg');
				if(wnd.length) wnd.dialog('destroy').empty(); else $('<div id=msg></div>').appendTo(document.body);
				
				$('#msg').html(json[i].value).
				dialog({
					bgiframe:false,
                    autoOpen:true,
					resizable: false,
                    title:json[i].title?json[i].title:'',
                    modal:true,
					buttons: { Ok: function() { $(this).dialog('close'); } }
					}).
				bind('dialogclose', function(event, ui) {	$(this).dialog('destroy').empty(); });
				continue;
			case 'wnd2':
				var wnd = $(json[i].id);
				if(wnd.length) wnd.dialog('destroy').remove();
				
				$(json[i].value).appendTo(document.body);
				
				$(json[i].id).
				dialog({
					bgiframe:false,
                    autoOpen:true,
                    title:json[i].title,
                    modal:true,
					width: json[i].width?json[i].width:600}).
				bind('dialogclose', function(event, ui) {	$(this).dialog('destroy').remove(); });
				
				continue;
		}
	}
}

function chimage (id) {
    $.post("/goods/chimage", {id:id}, parse_json);
	return false;
}

function abuse (id) {
    $.post("/price/abuse", {id:id}, parse_json);
	return false;
}

function msg (sMsg) {
	alert(sMsg)
}



function trim(s,what) {
	for (i = 0; i < what.length; i++) {
		while (s.substring(0,1) == what[i]) {
			s = s.substring(1,s.length);
		}
		while (s.substring(s.length-1,s.length) == what[i]) {
			s = s.substring(0,s.length-1);
		}
	}
	return s;
}

function SetCookie(name, value) {
   var argv    = SetCookie.arguments;
   var argc    = SetCookie.arguments.length;
   var expires = (argc > 3) ? new Date(argv[3]) : null;
   //var path    = (argc > 4) ? argv[4] : null;
	var path    = '/';
   var domain  = (argc > 5) ? argv[5] : null;
   var secure  = (argc > 6) ? argv[6] : false;
   expires = 'Friday, 01-Jan-2399 00:00:00 GMT';

   document.cookie = name + "=" + escape(value)
      + ((expires == null) ? "" : ("; expires=" + expires))
      + ((path == null) ? "" : ("; path=" + path))
      + ((domain == null) ? "" : ("; domain=" + domain))
      + ((secure == true) ? "; secure" : "");
}

function GetCookie(name) {
   var arg  = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i    = 0;

   while(i < clen) {
      var offset = i + alen;

      if(document.cookie.substring(i, offset) == arg) {
         var iEnd  = document.cookie.indexOf(";", offset);

         if(iEnd == -1) {
            iEnd = document.cookie.length;
         }

         return unescape(document.cookie.substring(offset, iEnd));
      }

      i = document.cookie.indexOf(" ", i) + 1;

      if(i == 0) {
         break;
      }
   }

   return null;
}

function find(link)
{
	var obj = $('#phrase');
	if(!obj.length) return;

	var str = obj.val().toString().substr(0,100).replace(/^\s+/, '').replace(/\s+$/, '').replace(/\s+/g, ' ').replace(/\%/g,'').replace(/\?/g,'').replace(/\//g,'').replace(/_/g,'');
	obj.val(str);
	if(!str || str.length < 3) return;
	window.location.href = link+'se_'+encodeURIComponent(str);
}

function highlightwords(words, elems) 
{
	if(!elems.length) return;
	var awords = words.toUpperCase().split(' ');
	var len = awords.length;
	if(!len) return;
	for (var i = 0; i < len; i++) elems.highlight(awords[i]);
}

function sethintfocus()
{
	var $this = $(this);
	var name = $this.attr('name');
	$this.addClass('active');
	$('label.rowl[for="'+name+'"]', $this.parent()).css('font-weight', 'bold');
}

function sethintbluer()
{
	var $this = $(this);
	var name = $this.attr('name');
	$this.removeClass('active');
	$('label.rowl[for="'+name+'"]', $this.parent()).css('font-weight', 'normal');
}

function ajblock(url, name)
{
	$.post(url, {name:name}, parse_json);
	return false;
}

function clearform () {
	var $obj = $('#filters');
	$('input[type=text]', $obj).each(function() { $(this).val(''); });
	$('input[type=checkbox]', $obj).each(function() { $(this).attr("checked", false); });
	$("select option[value='0']", $obj).attr('selected', 'selected');
}

function checkzi($this, st)
{
	$p = $this.parent();
	if($p.attr('id') != 'specprice') return;
	
	if(st) 
		$this.addClass('spi').css('z-index', 101) 
	else 
		$this.removeClass('spi');
	$('.hovmenu', $p).not('.spi').css('z-index', 100);
}	

function overzin()
{
	var $this = $(this);
  	if ($.browser.msie) checkzi($this, 1);
	
 	$this.children(".hmenu").slideDown();
}

function overzout()
{
	var $this = $(this);
	$this.data('curr', 0);
	if ($.browser.msie) checkzi($this, 0);
 	$this.children(".hmenu").slideUp();
}

function setfilter (nFilterId, sParam1, sParam2) {
	var $obj = $('#filters');
	var $old = $('input[name="filter['+nFilterId+'][0]"][type="text"]', $obj).parent();var $new = $old.clone().appendTo('#filter_ch');$old.remove();
	var $old = $('input[name="filter['+nFilterId+'][1]"][type="text"]', $obj).parent();var $new = $old.clone().appendTo('#filter_ch');$old.remove();
	var $old = $('input[name="filter['+nFilterId+'][0]"][type="checkbox"]', $obj).parent();var $new = $old.clone().appendTo('#filter_ch');$old.remove();
	var $old = $('select[name="filter['+nFilterId+'][0]"]', $obj).parent();var $new = $old.clone().appendTo('#filter_ch');$old.remove();
	
	$('input[name="filter['+nFilterId+'][0]"][type="text"]', $obj).val(sParam1);
	$('input[name="filter['+nFilterId+'][1]"][type="text"]', $obj).val(sParam2);
	$('input[name="filter['+nFilterId+'][0]"][type="checkbox"]', $obj).attr('checked', 'checked');
	$('select[name="filter['+nFilterId+'][0]"] option[value='+sParam1+']', $obj).attr('selected', 'yes');
}

function setfrf () {
	var $obj = $('#filters');
	var $li = $('input[name=pf][type="text"]', $obj).parent().parent().parent();
	var $old = $('input[name=pf][type="text"]', $obj).parent();var $new = $old.clone().appendTo('#filter_ch');$old.remove();
	$li.remove();
}

function setpf (sValue) {
	$('#filters input[name=pf][type="text"]').val(sValue);
}

function setpt (sValue) {
	$('#filters input[name=pt][type="text"]').val(sValue);
}

function setven (sValue) {
	var $obj = $('#filters');
	var $li = $('select[name=ven]', $obj).parent().parent().parent();
	var $old = $('select[name=ven]', $obj).parent();var $new = $old.clone().appendTo('#filter_ch');$old.remove();
	$('select[name=ven] option[value="'+sValue+'"]', $obj).attr('selected', 'yes');
	$li.remove();
}

function checkcompare () {
	var haschecked = false;
	$('input[type=checkbox][name="com[]"]').each (function () {if ($(this).is(':checked')) haschecked = true; });
	if (!haschecked) {
		$('div.compare-button input').attr('disabled', true);
		$('div.compare-button input').addClass('disabled');
	}
	else {
		$('div.compare-button input').attr('disabled', false);
		$('div.compare-button input').removeClass('disabled');
	}
}

function init_compare()
{
	if (typeof(myrub) == 'undefined' || typeof(mynum) == 'undefined') {
		$('.compare input, .compare span').style('display', 'none');
		return;
	} 
	
	var compares = $.cookie('compare_' + myrub);
	compares = compares?compares.toString().split(';'):'';
	if(compares && compares.length)
	{
		mycmps = [];
		//for each (var v in compares) {
		for (i=0; i < compares.length; i++) {
			v = compares[i];
			if (!v || $.inArray(v, mycmps) != -1) continue;
			if (mycmps.push(v) >= mynum) break; 
		}
		$.cookie('compare_' + myrub, mycmps.join(';'), { path: '/' });
	}
	$('.compare input, .compare span').bind('click', compareclick);
}

function remcmp(id)
{
	if (typeof(myrub) == 'undefined' || typeof(mynum) == 'undefined') {
		return false;
	} 
	if(mycmps.length < 1) return;
	var i = $.inArray(id, mycmps); if(i != -1) mycmps.splice(i, 1);
	$.cookie('compare_' + myrub, mycmps.join(';'), { path: '/' });
	window.location.href = '/goods/compare/'+mycmps.join('-').replace(/-$/,'');
	return false;
}



function compareclick()
{	
	var $this = $(this);
	var tagname = this.tagName;
	if (tagname == 'SPAN') 
	{
		if($this.hasClass('href'))
		{
			if (mycmps.length > 1) 
				window.location.href = '/goods/compare/'+mycmps.join('-').replace(/-$/,'');
			else 
				alert(lang['compare']['addmore']);
			
			return true;
		}
		else
		{
			$this = $this.parent().find('input');
			$this.attr('checked', 'checked');
			tagname = 'INPUT';
		}
	}
	
	if (tagname == 'INPUT') {
		var id = $this.val(); if (!id) return true;
		var checked = $this.attr('checked');
		
		if (checked) {
			if(mycmps.length <= mynum && $.inArray(id, mycmps) == -1) mycmps.push(id);
			 
			$this.parent().find('span').addClass('href');
		}
		else 
		{
			var i = $.inArray(id, mycmps); if(i != -1) mycmps.splice(i, 1);
			$this.parent().find('span').removeClass('href');
		}
		
		$.cookie('compare_' + myrub, mycmps.join(';'), { path: '/' });
	}
	
}

function toursdb () {
	FromTownID = $('select[name=FromTownID] option:selected').val();
	Country = $('select[name=Country] option:selected').val();
	StartDate = $('input[name=StartDate]').val();
	EndDate =  $('input[name=EndDate]').val();
	nfrom =  $('input[name=nfrom]').val();
	nto =  $('input[name=nto]').val();
	priceFrom =  $('input[name=priceFrom]').val();
	priceTo =  $('input[name=priceTo]').val();

	$.post('/ajax/tours_get', {FromTownID:FromTownID, Country:Country, StartDate:StartDate, EndDate:EndDate, nfrom:nfrom, nto:nto, priceFrom:priceFrom, priceTo:priceTo}, parse_json);
	return false;
}

$(function() 
{
	$('.ajaxform').livequery(function() {
		$(this).ajaxForm({ dataType:'xjson', success: parse_json });		
	}, function(){
		$(this).ajaxFormUnbind();
	});
	
	$("a.fotoimg").livequery(function(){
		$(this).fancybox({ 'mageScale': true, 'hideOnContentClick': true, 'overlayShow': false, 'zoomOpacity': true, 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, easingIn: 'easeOutBack', easingOut: 'easeInBack' });	
	});
	
	$('form.validate').livequery(function(){
		var $this = $(this); 
		$this.validate({
			submitHandler: function(form) {
		        $(form).ajaxSubmit({ dataType:'xjson', success: parse_json });
	        }
		});
		$this.find('.input, .textarea').focus(sethintfocus).blur(sethintbluer);
	});


	$(document).ajaxStart(function(){
		$.fn.fancybox.showLoading();
	}).ajaxStop(function(){ 
		$("#fancy_loading").hide();
	});
	
	$.ajaxSetup({ data: {ajax: 1}});
	
	$(".hovmenu").hoverIntent({
		sensitivity: 1,
		interval: 20,
		over: overzin, 
		timeout: 300,
		out: overzout
	});
	
	init_compare();
		
});

