var operator_search_resultID = 0;
var rotateNews = function() {
	$notr = true;
	var n = $('#promo-block-news > a.on').next();
		if(n.is('a') && !n.hasClass('control')) n.trigger('click');
	else
	  $('#promo-block-news > a:first').trigger('click');
}
var $tg = false;
var ie6 = navigator.appVersion.match(/MSIE 6/);
$(document).ready(function() {
	$('.image-block').lightBox();
	var current_page = self.document.location.hash;

	// DEFAULT

	$.makeFormArray = function (obj)
	{
		var a = new Array();
		for(t=0; t < obj.length; t++)
		{
			value = $(obj[t]).val();
			name = 	$(obj[t]).attr('name');
			if(!$(obj[t]).attr("disabled"))
			{
				switch($(obj[t]).attr("type")){
					case 'checkbox':
						if($(obj[t]).attr("checked"))
							a.push({name: name, value: value});
						break;
					default:
						a.push({name: name, value: value});
				}
			}
		}

		a.push({name: 'ajax_request', value: 1});

		return a;
	}

	$('.validate-form').submit(function() {
		var send = true;
		var error_message = '';
		var form = this;
		$('#error_form_message_div').remove();
		
		$(this).find('input').removeClass('error_input');
		
		$(this).find('div.error_block').remove();

		$(this).find('.required').each(function(i){
			if(($(this).attr("value")=='' || $(this).attr("value")=='http://') && !$(this).attr("disabled") || ($(this).attr("value")==$(this).attr('defaultValue') && !$(this).hasClass('nodef'))) {
				$(this).addClass('error_input');
				$error_message = $('<div class="error_block">' + messages.required + '</div>');				
				if($(form).hasClass('send_friend_form'))  $error_message.insertAfter(this); else $error_message.insertBefore(this);
				send = false;
			}
		});

		re_email = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2,}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/i;

		$(this).find('.validate-email').each(function() {
			if(!$(this).hasClass('error_input') && !$(this).attr("value").match(re_email)) {
				$(this).addClass('error_input');
				$error_message = $('<div class="error_block">' + messages.email + '</div>');
				if($(form).hasClass('send_friend_form'))  $error_message.insertAfter(this); else $error_message.insertBefore(this);
				send = false;
			}
		});
		
		$(this).find('#hashFriend').each(function() {
			
		});

		if(!send) {		   
		} else {
		   message = $('<div class="wait"   id="error_form_message_div"  style="display: none;">'+ message_loading +'</div>');
		   if($(form).hasClass('send_friend_form'))
				message.prependTo($(form).find('div.content'))   
		   else
			   message.insertBefore(this);

		   message.fadeIn();

		   if($(this).hasClass('ajax-post')) {

				send = false;

				form_array = $(this).map(function(){ return $.makeFormArray(this.elements); });

				var forma = $(this);		
	
				$.ajax({
				type: "POST",
				url: $(this).attr('action'),
				dataType: 'json',
				data: form_array,

				success: function(data) {
					if(data.result!= undefined && data.result) {
						if(data.redirect) {
							window.location.href = data.redirect;
						} else if(data.refresh) {
							window.location.href = window.location.href.replace(/\#.*$/, '');
						} else if(data.send) {
							send = true;
						}else {
							if(data.reload_link) {
								$('#' +$('#'+data.reload_link).attr('rel')).load($('#'+data.reload_link).attr('href') + '?ajax_request=1');
							} else {
								$(forma).map(function(){ return this.reset(); });
							}
						}
						if(data.success_element) {
							$('#forma-elements').hide();
							$(data.success_element).fadeIn();
							$('#error_form_message_div').remove();
						} else if($('#feedback-ok').is('div')) {
							forma.hide();
							$('#feedback-ok').fadeIn();
							$('#error_form_message_div').remove();
						} else if(data.message) {
							$('#error_form_message_div').removeClass('wait');
							$('#error_form_message_div').addClass('successful');
							$('#error_form_message_div').html(data.message);
							$('#error_form_message_div').show();

							setTimeout(function() {
								$('#error_form_message_div').slideUp();
							}, 7000);


						}
						if (data.script) {
							eval (data.script);
						}
					} else if(data.result == undefined) {
						$('#error_form_message_div').removeClass('wait');
						$('#error_form_message_div').addClass('error');
						$('#error_form_message_div').html(messages.form_not_send);
					} else {
						error_message = data.message;
						$('#error_form_message_div').removeClass('wait');
						$('#error_form_message_div').addClass('error');
						$('#error_form_message_div').html(data.message);

					}
				},
				error: function() {
					$('#error_form_message_div').removeClass('wait');
					$('#error_form_message_div').addClass('error');					
					$('#error_form_message_div').html(messages.form_not_send);
				}

				});
				

		   }
		}
		return send;

	});

	$('.mok-button').click(function(){		
		var f = $('#mok-form');		
		if(f.is(':visible'))
			f.hide();
		else {			
			f.show();
		}

		return false;
	});

	$('.sms-button').click(function(){		
		var f = $('#sms-form');		
		if(f.is(':visible'))
			f.hide();
		else {			
			f.show();
		}

		return false;
	});


/* -------------------------- VIESABONĒŠANA ----------------------- */

	$('#operator-region').click(function(e){
		var $t = $(e.target);
		if ($t.is('a') && !$t.hasClass('on')) {
			operator_search_resultID = 0;
			var regionID = $t.attr('rel');
			$(this).find('a.on').removeClass('on');
			$t.addClass('on');
			$('#operator-countries').html('<center><img src="/images/ajax-loader.gif" /></center>');
			$('#operator-info').html('');
			$('#operator-info2').html('');
			$('#operator-countries').load('/'+lng+'/operators_cities.inc.php?regionID=' + regionID);
		}
		return false;
	});	

	function updateOperatorList(countryID) {		
		$('#operator-info').load('/'+lng+'/operators_info.inc.php?countryID=' + countryID, null, function(){
			$('span.op-icons > a').hover(function(){			
				$(this).find('div').css('display','inline');
			}, function(){
				$(this).find('div').hide();
			});
		});
	}

	function updateOperatorList2(countryID, subID) {		
		$('#operator-info2').load('/'+lng+'/operators_info.inc.php?countryID=' + countryID + '&subID=' + subID, null, function(){
			$('#operator-info2').show();
			$('span.op-icons > a').hover(function(){			
				$(this).find('div').show();
			}, function(){
				$(this).find('div').hide();
			});
		});
	}

	function updateCountryList(countryIDs) {	
		$('#operator-countries').html('<center><img src="/images/ajax-loader.gif" /></center>');
		$('#operator-info').html('');
		$('#operator-info2').html('');
		$('#operator-countries').load('/'+lng+'/operators_cities.inc.php?countryIDs=' + countryIDs);
	}

	$('#operator-search').submit(function(){
		$('#operator-countries').html('');
		$('#operator-info2').html('');
		$('#operator-region  > a').removeClass('on');
		$('#operator-info').html('<center><img src="/images/ajax-loader.gif" /></center>');
		$.ajax({
				type: 'GET', 
				url: '/'+lng+'/operators_search.inc.php', 
				dataType: 'json', 
				data: 'search=' + encodeURIComponent($('#operator-searchterm').val()),
				success: function(result) {
					$('#operator-countries').html('<div class="search-header">' + messages.search_results + '</div>');
					if (result.result == 1 && result.countryIDs.length > 0) {
						if (result.countryIDs.length == 1) {
							updateOperatorList(result.countryIDs);
							operator_search_resultID = result.countryIDs;
						} else {
							updateCountryList(result.countryIDs);
						}
					} else {
					  $('#operator-info').html(messages.no_such_country);
					}
				}
			});
			return false;																									  
	});


	$('#operator-countries').click(function(e){
		var $t = $(e.target);
		if($t.is('a')) {			
			$('#operator-info2').html('');
			$(this).find('a.on').removeClass('on');
			$t.addClass('on');
			var countryID = operator_search_resultID = $t.attr('rel');
			$('#operator-info').html('<center><img src="/images/ajax-loader.gif" /></center>');
			updateOperatorList(countryID);		
			return false;
		}
	});

	$('#operator-info').click(function(e){
		var $t = $(e.target);
		if($t.is('a.reg')) {
			$(this).find('a.reg').removeClass('on');
			$t.addClass('on');
			var countryID =   operator_search_resultID ? operator_search_resultID : $('#operator-countries > a.on:first').attr('rel');
			var subID = $t.attr('rel');
			$('#operator-info2').html('<center><img src="/images/ajax-loader.gif" /></center>');
			updateOperatorList2(countryID, subID);		
			return false;
		}
	});

/* ---------------------- --------------------------- */

	$('.popblock').click(function(e){
		var $t = $(e.target);
		if($t.is('h2 a')  || $t.is('img.timg')) {
			if($t.is('img.timg')) $t = $t.parent();
			var $b = $(this).find('.box')
			if($b.is(':visible')) {
				$t.removeClass('on');
				$b.slideUp();
			} else {
				$t.addClass('on');
				$b.slideDown();
			}
			return false;
		} else if($t.is('h3 a') || $t.is('img.qimg')) {
			if($t.is('img.qimg')) $t = $t.parent();
			var $b = $(this).find('.box')
			if($b.is(':visible')) {
				$t.removeClass('on');
				$b.slideUp();
			} else {
				$t.addClass('on');
				$b.slideDown();
			}
			return false;
		}
	});

	$('.news_thumb > li').hover(function(){
		$(this).addClass('on');
	}, function(){
		$(this).removeClass('on');
	});

	$('.print > a').click(function() {
		window.print();
		return false;
	});

	if($('#promo-block-news').is('div')) {
		$tg = window.setTimeout('rotateNews()', 10000);
		
	}

	$('#promo-block-news').click(function(e){	
		var $t = $(e.target);
		if($t.is('a') && !$t.hasClass('control')) {				
			if(!$t.hasClass('on')) {		
				var c = parseInt($t.html());
				if($('.news-block-ab:animated').length==0) {						
					$('.news-block-ab').hide();
					$('.news-block-ab:nth-child(' + (c+1) + ')').slideDown();					
					$(this).find('a').removeClass('on');					
					$t.addClass('on');
					window.clearTimeout($tg);
					$tg = window.setTimeout('rotateNews()', 10000);
					$('#promo-block-news .control').removeClass ('resume');
					$('#promo-block-news .control').addClass ('pause');
				}
			}		
		}
		else if ($t.hasClass('pause')) {
			$t.removeClass ('pause');
			$t.addClass ('resume');
			clearTimeout($tg);
		}
		else if ($t.hasClass('resume')) {
			$t.removeClass ('resume');
			$t.addClass ('pause');
			$tg = window.setTimeout('rotateNews()', 0);
		}
		return false;
	});

	$('.google-map-box').click(function(){
			
		var pos = $(this).position();
		var link = $(this).attr('href');
		
		$('#google-map-div').remove();
		
		var $map = $('<div id="google-map-div" class="google-map-outter"><div class="close-map-div"><a href="#close" id="close-map-div-l" class="close-map-div-link"></a></div><div class="google-map"><div class="google-loading"><iframe id="iframe-map"  scrolling="no" frameborder="0" marginwidth="0" marginheight="0" style="display: none; padding: 0px; margin: 0px; width: 493px; height: 394px;"></iframe></div><div class="google-map-link-popup" ><a href="' + $(this).attr('href') + '">' + messages.view_full_map + '</a></div></div></div>');
		
		$map.css({top: (pos.top-260), left: pos.left+100});

		$map.insertAfter(this);
		$('#close-map-div-l').click(function(){	$('#google-map-div').remove(); return false; });
		$map.fadeIn();
		
		var $iframe  = $('#iframe-map');
		$iframe.attr('src', link.replace(/google\-map/, 'popup/google-map'));
		$iframe.fadeIn();
		
		return false;
	});
	

	$('#submit-feedback').click(function(){
		$('#feedback-form').trigger('submit');
		return false;
	});

	$('.ext-rate').mousemove(function(e) {
		$d = $(this).next('div.rate-extended');
		$d.show();
		$d.css({top: (e.pageY+10), left: (e.pageX+10)});
		$(this).css({cursor: 'help'});	
	});

	$('.ext-rate').mouseout(function(e) {
		$(this).next('div.rate-extended').hide();
		$(this).css({cursor: 'auto'});	
	});

	$('.rate-row').click(function(e) {
		var $t = $(e.target);
		if($t.is('a')) {
			
			var $bg = $(this).next('.country-row');

			if($bg.is(':visible')) { 
				$(this).removeClass('on bg');
				$bg.hide();
			} else {
				$(this).addClass('on bg');
				$bg.show();
			}
		}
	});

	$('.print').click(function() {
		window.print();
		return false;
	});


	$('#sms-okarte-main-link').click(function() {
		$(this).parent().addClass('on');
		$('#my-okarte-main-link').parent().removeClass('on');
		$('#my-okarte-main').hide();
		$('#sms-okarte-main').show();
		return false;
	});

	$('#my-okarte-main-link').click(function() {
		$(this).parent().addClass('on');
		$('#sms-okarte-main-link').parent().removeClass('on');
		$('#sms-okarte-main').hide();
		$('#my-okarte-main').show();
		return false;
	});

	$('#main-link-left').hover(function(){		 
	}, function(){

	});

	$('#toogle-feedback-form').click(function(){
		$('#feedback-ok').hide();
		$('#feedback-form').slideDown();
		return false;
	});


	$an = $('#anima');
	$('#motion-left').click(function() {
		$('#flash-block').hide();
		$an.animate({'left': '0.01%'}, 600, function(){ 
		/* filter validator obtain*/
		$('.friend .arrow img').css ('filter','progid:DXImageTransform.Microsoft.AlphaImageLoader(src="/images/friend_arrow.png?3")');
		pulsate ($('.motion-back'),'slow',3); 
		});	
		return false;
	});
	
	$('#motion-left').hover (function() {
		$('#motion-left .pic img').attr('src', '/images/index_promo_friend_logo_big.png');
		$('#motion-left .pic img').animate({height: 155, width: 155, top: '50%', left: '50%' }, {queue:false, duration:300});
	}, 
	function() {
		$('#motion-left .pic img').attr('src', '/images/index_promo_friend_logo.png');
		$('#motion-left .pic img').animate({height: 143, width: 143, top: '50%', left: '50%' }, {queue:false, duration:300});
	});
	$('#motion-right').hover (function() {
		$('#motion-right .pic img').attr('src', '/images/index_promo_int_tel_big.png?2');
		$('#motion-right .pic img').animate({height: 155, width: 155, top: '50%', left: '50%' }, {queue:false, duration:300});
	}, 
	function() {
		$('#motion-right .pic img').attr('src', '/images/index_promo_int_tel.png?2');
		$('#motion-right .pic img').animate({height: 143, width: 143, top: '50%', left: '50%' }, {queue:false, duration:300});
	});
	

	$('#motion-right').click(function() {
		$('#flash-block').hide();
		$an.animate({'left': ie6 ? '-200.2%' : '-200%'},  600, function(){ 
		/* filter validator obtain*/
		$('.discount .arrow img').css ('filter','progid:DXImageTransform.Microsoft.AlphaImageLoader(src="/images/discount_arrow.png?3")');
		pulsate ($('.motion-back'),'slow',3); 
		});				
		return false;
	});

	$('.motion-back').click(function() {
		$an.animate({'left': '-100%'}, 600, function(){$('#flash-block').show()});				
		return false;
	});
	
	if($('#ok-widget').is('ul')) {
		
		var $v = $('#ok-widget');

		var activated = $v.parent().hasClass('inner') ? 0 : 1;
			
		$v.accordionScada({ 
							header: '.title',  
							content: '.content', 
							active: activated,							
							beforeEvent: function (event, ui) {
								var new_block = ui.newBlock;
								var old_block = ui.oldBlock;
								
								if(new_block.hasClass('renew'))
									new_block.addClass('renewon');
								else
									if(old_block) old_block.removeClass('renewon');

							},
							afterEvent: function (event, ui) {
								clearSmsForm();
								var new_block = ui.newBlock;
								var old_block = ui.oldBlock;								
								new_block.addClass('on');
								if(old_block && old_block.attr('class')!=new_block.attr('class')) old_block.removeClass('on');
							},
							animatedClose: 0
						});	
		/* papildinat widget submit */
		$('#btntalak').click(function(){
			$('#frmpapild').trigger('submit');
			return false;
		});
	}
	
	$('.sendToFriend a').click(function(){
		$('#TPane1').fadeOut();
		
		var $f = $('#send-friend-form');
		if ($(this).hasClass('portation')) {
			$('h2', $f).html (lang_arr['sendvideotofriend']);
			$('form', $f).append ('<input id="subact" name="subact" type="hidden" value="portation" />');
		} else {
			$('h2', $f).html (lang_arr['sendtofriend']);
			$('#subact', $f).remove();
		}
		if($f.is(':visible'))
			$f.hide();
		else
			$f.fadeIn();
		$('#talkbutton').parent('a').animate({'opacity': '1'}, 200);
		$('#talkbutton').parent('a').css('visibility','visible');
		RegenerateCapcha ($('#TPane1 .capchax img'));
		return false; 
	});

	$('.close-send-friend').click(function(){
		$('#send-friend-form').hide();
		$('#forma-elements').show();
		$('#send-ok').hide();
		return false;
	});
	
	/* Social sharing */
	$('#talkbutton').parent('a').click(function() {
		$pos = $('#talkbutton').position();
		$('#TPane1').css({'left': ($pos.left-27)+'px', 'top': ($pos.top-3)+'px'}).fadeIn();
		//$(this).css('visibility','hidden');
		$(this).animate({'opacity': '0'}, 200);
		return false;
	});
	$('#TPane1 .close').click ( function () {
		//$('#talkbutton').parent('a').css('visibility','visible');
		$('#talkbutton').parent('a').animate({'opacity': '1'}, 200);
		$('#TPane1').fadeOut();
		$('#send-ok, #error_form_message_div, #TPane2 .error_block').hide();
		return false;
	});
	
		
	/* script expander for tarrifs table. universal */
	if ($('.init').length>0) {
		$('.init').click (function () {
			$table = $(this).parents ('table');
			$('.hide').toggleClass('none');
			// toggleClass doesnt works correct >
			if ($(this).parents('tr').hasClass ('more')) {	
				$(this).parents('tr').removeClass ('more');
				$(this).html ('');
			} else {
				$(this).parents('tr').addClass ('more');
				$(this).html ($(this).attr('rel'));
			}			
			return false;
		});
	}
	
	stripe_tables('table');

	if(!($.browser.msie && $.browser.version.substring(0,1) < 7)) {
		if ($(window).width() > 999) {
			if (lng == 'ru') {
				to_top = 'Наверх';
			} else if (lng == 'en') {
				to_top = 'Top';
			} else {
				to_top = 'Uz augšu';
			}
			$('body').append('<a href="#" id="to_top" title="'+to_top+'">'+to_top+'</a>');
			$('#to_top').topLink  ({
				min: 200,
				fadeSpeed: 500
			});
			$('#to_top').click(function() {				
				$('html,body').animate({scrollTop: 0}, 1000);
				return false;
			});
		}
	}
	
});


/* -------------------- TABLE STRIPE ------------------------ */
// this function is needed to work around a bug in IE related to element attributes
function hasClass(obj) {
	var result = false;
	if (obj.getAttributeNode("class") != null) { result = obj.getAttributeNode("class").value; }
	return result;
}   

function stripe(table) {
	var even = false;
	var evenColor = arguments[1] ? arguments[1] : "#fff";
	var oddColor = arguments[2] ? arguments[2] : "#edf5de";
	var tbodies = table.getElementsByTagName("tbody");
	for (var h = 0; h < tbodies.length; h++) {
	var trs = tbodies[h].getElementsByTagName("tr");
		for (var i = 0; i < trs.length; i++) {
//			if (!hasClass(trs[i]) && !trs[i].style.backgroundColor) {
			if (!trs[i].style.backgroundColor && !$(trs[i]).hasClass('expander')) {
				var tds = trs[i].getElementsByTagName("td");
				for (var j = 0; j < tds.length; j++) {
					var mytd = tds[j];
//					if (! hasClass(mytd) && ! mytd.style.backgroundColor) {
					if (!mytd.style.backgroundColor) { mytd.style.backgroundColor = even ? evenColor : oddColor; }
				}
			}
			even =  ! even;
		}
	}
}

function stripe_tables(theClass) {
	var allHTMLTags = new Array();
	var allHTMLTags=document.getElementsByTagName("*");
	for (i=0; i<allHTMLTags.length; i++) { 
		if ($(allHTMLTags[i]).hasClass(theClass)) { stripe(allHTMLTags[i]); }
	}
}

function pulsate (wht, period, times) {
	for (i=0; i<times; i++) {
		$(wht).fadeOut(period);
		$(wht).fadeIn(period);
	}
}

function checkInteger( strValue ) {
  var objRegExp  = /(^-?\d\d*$)/;
  return objRegExp.test(strValue);
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
	{
	c_start=c_start + c_name.length+1;
	c_end=document.cookie.indexOf(";",c_start);
	if (c_end==-1) c_end=document.cookie.length;
	return unescape(document.cookie.substring(c_start,c_end));
	}
  }
return "";
}
function setCookie(NameOfCookie, value, expiredays)
{
var ExpireDate = new Date ();
ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
document.cookie = NameOfCookie + "=" + escape(value) +
((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}

/* Transparent shadowed PNG FIX for IE7 */
(function ($) {
    if (!$) return;
    $.fn.extend({
        fixPNG: function(sizingMethod, forceBG) {
                if (!($.browser.msie)) return this;
                var emptyimg = "/images/1px.gif"; //Path to empty 1x1px GIF goes here
                sizingMethod = sizingMethod || "scale"; //sizingMethod, defaults to scale (matches image dimensions)
                this.each(function() {
                        var isImg = (forceBG) ? false : jQuery.nodeName(this, "img"),
                                imgname = (isImg) ? this.src : this.currentStyle.backgroundImage,
                                src = (isImg) ? imgname : imgname.substring(5,imgname.length-2);
                        this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + sizingMethod + "')";
                        if (isImg) this.src = emptyimg;
                        else this.style.backgroundImage = "url(" + emptyimg + ")";
                });
                return this;
        }
    });
})(jQuery);

//To top plugin
$.fn.topLink   = function(settings) {
	settings = $.extend({
		min: 1,
		fadeSpeed: 200
	}, settings);
	return this.each(function() {
		var el = $(this);
		el.hide();
		$(window).scroll(function() {
			if ($(window).scrollTop() >= settings.min) {
				el.fadeIn(settings.fadeSpeed);
			} else {
				el.fadeOut(settings.fadeSpeed);
			}
		});
	});
};

jQuery.extend(
	{ reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
);

// vertically center something in the viewport
(function($) {
  $.fn.vCenter = function(options) {
 var pos = {
   sTop : function() {
  return window.pageYOffset
  || document.documentElement && document.documentElement.scrollTop
  ||  document.body.scrollTop;
   },
   wHeight : function() {
  return window.innerHeight
  || document.documentElement && document.documentElement.clientHeight
  || document.body.clientHeight;
   }
 };
 return this.each(function(index) {
   if (index == 0) {
  var $this = $(this);
  var elHeight = $this.height();
  var elTop = pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2);
  $this.css({
    position: 'absolute',
    marginTop: '0',
    top: elTop
  });
   }
 });
  };
})(jQuery); 