var language='lv';
var xhrdata='0';

function makenumselect(element,start,end)
{
  var i,opts='<option value=""></option>';
  var cls=$(element).attr('class');
  for (i=start;i<=end;i++)
    opts=opts+'<option value="'+i+'">'+i+'</option>';
  $(element).replaceWith('<select class="'+cls+'">'+opts+'</select>');
}

function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }

var scrollElem;

function smoothhashchange(hash)
{
  target=$('a[name="'+hash+'"]');
  if ($(target).length>0)
  {
    var targetOffset = target.offset().top;
    $(scrollElem).animate({scrollTop: targetOffset}, 200, function() {
      location.hash = hash;
    });
  }
}

function flashnewcomment(subobj)
{
  subobj.css('background-color','#FFEECC');
  subobj.animate({
    backgroundColor:'white'
  },2000,function(){
    $(this).removeClass('new');
  });
}

function movetocomment(parent)
{
  target=$('a[name="wallmsg_'+parent+'"]');
  if (target.length>0)
  {
    var subobj=$('div.subMsgHandler div.subBlockBody.new:first',target.parent().parent().parent()).parent();
    if (subobj.length>0)
    {
      allowedtop=$('#wPostList').offset().top;
      if ($(scrollElem).scrollTop()>allowedtop)
        $(scrollElem).animate({scrollTop: allowedtop}, 100, function() {
          flashnewcomment(subobj);
        });
      else
        flashnewcomment(subobj);
    }
  }
}

function strtok (str, tokens) {
    // Tokenize a string  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/strtok    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: Use tab and newline as tokenizing characters as well
    // *     example 1: $string = "\t\t\t\nThis is\tan example\nstring\n";
    // *     example 1: $tok = strtok($string, " \n\t");
    // *     example 1: $b = '';    // *     example 1: while ($tok !== false) {$b += "Word="+$tok+"\n"; $tok = strtok(" \n\t");}
    // *     example 1: $b
    // *     returns 1: "Word=This\nWord=is\nWord=an\nWord=example\nWord=string\n"
    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};    // END REDUNDANT
    if (tokens === undefined) {
        tokens = str;
        str = this.php_js.strtokleftOver;
    }if (str.length === 0) {
        return false;
    }
    if (tokens.indexOf(str.charAt(0)) !== -1) {
        return this.strtok(str.substr(1), tokens);}
    for (var i = 0; i < str.length; i++) {
        if (tokens.indexOf(str.charAt(i)) !== -1) {
            break;
        }}
    this.php_js.strtokleftOver = str.substr(i + 1);
    return str.substring(0, i);
}

function base64_encode( data ) {	// Encodes data with MIME base64
	// 
	// +   original by: Tyler Akins (http://rumkin.com)
	// +   improved by: Bayron Guevara

	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i=0, enc='';

	do { // pack three octets into four hexets
		o1 = data.charCodeAt(i++);
		o2 = data.charCodeAt(i++);
		o3 = data.charCodeAt(i++);

		bits = o1<<16 | o2<<8 | o3;

		h1 = bits>>18 & 0x3f;
		h2 = bits>>12 & 0x3f;
		h3 = bits>>6 & 0x3f;
		h4 = bits & 0x3f;

		// use hexets to index into b64, and append result to encoded string
		enc += b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
	} while (i < data.length);

	switch( data.length % 3 ){
		case 1:
			enc = enc.slice(0, -2) + '==';
		break;
		case 2:
			enc = enc.slice(0, -1) + '=';
		break;
	}

	return enc;
}

function number_format( number, decimals, dec_point, thousands_sep ) {	// Format a number with grouped thousands
	// 
	// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +	 bugfix by: Michael White (http://crestidg.com)

	var i, j, kw, kd, km;

	// input sanitation & defaults
	if( isNaN(decimals = Math.abs(decimals)) ){
		decimals = 2;
	}
	if( dec_point == undefined ){
		dec_point = ",";
	}
	if( thousands_sep == undefined ){
		thousands_sep = ".";
	}

	i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

	if( (j = i.length) > 3 ){
		j = j % 3;
	} else{
		j = 0;
	}

	km = (j ? i.substr(0, j) + thousands_sep : "");
	kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
	//kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
	kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");


	return km + kw + kd;
}

function isNumber(n) {
  n=n.replace(/,/g,'.');
  return !isNaN(parseFloat(n)) && isFinite(n);
}

var notifids='';

jQuery(function($){
	$('a[rel*=popup]').facebox({loadingImage : '/static/images/loading.gif'});
	$('a[rel*=window]').live('click', function(){$(this).facebox({loadingImage : '/static/images/loading.gif'});});
	$('a[rel*=close]').live('click', function(){$.facebox.close();});
  $('a.jslink').live('click',function(){
    newurl=strtok($(this).attr('href'),'#');
    newhash=strtok('');
    if (newhash)
      newhash='#'+newhash;
    else newhash='';
    oldurl=location.pathname;
    if (newurl==oldurl)
    {
      if (newhash)
        document.location.hash=newhash;
      document.location.reload(true);
    }
    else 
      document.location=newurl+newhash;
    return false;
  });
  $('div.expander').live('click',function(){
    if ($(this).hasClass('expanded'))
    {
      $(this).removeClass('expanded').animate({height:'28px'},100);  
    }
    else
    {
      $(this).addClass('expanded').animate({height:'100%'},200);  
    }
  });

	/**
	 * @Authorize
	 */
	$('#authorize').live('click', function(){
		var email = $('.popupFields').find('input#authEmail');
		var password = $('.popupFields').find('input#authPass');
		if(email.val() != '' && password.val() != ''){
			email.parent().removeClass('error');
			password.parent().removeClass('error');
			var data={User: true, email: email.val(), password: password.val()};
      if ($('input#rememberMe').attr('checked'))
        data['rememberme']='1';
			$.post('/'+language+'/authorize', data, function(response){
				if(response.length == 0){
					if($('.errorField').css('display') == 'block'){
//						$('.errorField').fadeOut('100', function(){
              document.location.reload();
//							document.location.href = '/';
	// 					});
					}else{
            document.location.reload();
//						document.location.href = '/';
					}
				}else{
					$('.errorField').remove();
          if (response.indexOf('<script')==0)
            $('.popupContent').prepend(response);
          else $('.popupContent').prepend('<div class="errorField">'+response+'</div>');
				}
			});
		}else{
			email.parent().addClass('error');
			password.parent().addClass('error');
		}
		
		return false;
	});

	/**
	 * @Popup Errors
	 */
	$('.popup .errorIcon').live('mouseover mouseout', function(e){
		if(e.type == 'mouseover')
			$(this).parent().find('.errorMsg').show();
		else
			$(this).parent().find('.errorMsg').hide();
	});

	/**
	 * @Send Message
	 */
	$('#send-message').live('click', function(){
		var $form = $('#compose-form');
		
		$.post($form.attr('action'), {Message: true, subject: $form.find('#Message_subject').val(), text: $form.find('#Message_message').val(), recipient: $form.find('#Message_recipient').val()}, function(response){
			$('.errorField').remove();
			
			if(response.length == 0){
				document.location.reload();
			}else{
				$('.popupContent').prepend('<div class="errorField">'+response+'</div><br />');
			}
		});
		
		return false;
	});

	$('#ajaxContent .pagination a').live('click', function(){
		var link = $(this);
		$('#ajaxContent').html('<div class="preload"></div>');
		setTimeout(function(){
			$.get(link.attr('href') + '&ajax=yw0', {}, function(response){
				$('#ajaxContent').html(response);
			});
		}, 1500);
		
		return false;
	});
	
	/**
	 * @Messages
	 */
	$('#ajaxContent .message .short').live('click', function(){
		$(this).hide().parent().find('.full').show();
	});
	
	$('#ajaxContent .message .full').live('click', function(){
		$(this).hide().parent().find('.short').show();
	});
	
	$('#ajaxContent .message a.sendMsg').live('click', function(){
		$(this).facebox({loadingImage : '/static/images/loading.gif'});
		return false;
	});
	
	$('table.userListTable a.sendMsg').live('click',function(){
		$(this).facebox({loadingImage : '/static/images/loading.gif'});
    $(this).click();
		return false;
	});
	
	/**
	 * @Langbar
	 */
	$('#langButton').live('click', function(){
		//$(this).next().slideToggle();
		$(this).next().fadeToggle();
	});
	/**
	 * @Wall
	 */
	$('#ajaxContent .addMsg a').live('click', function(){
		var addmsg = $(this).parent();
		addmsg.html('<textarea id="addMsg"></textarea>');
		$('#addMsg').focus();
		return false;
	});
	
	$('#ajaxContent .addComm a').live('click', function(){
		var addcm = $(this).parent();
		addcm.html('<textarea id="addComm"></textarea>');
		$('#addComm').focus();
		return false;
	});
	
	/**
	 * @Messages
	 */
	$('.message .short').live('click', function(){
		var message = $(this).parent();

		/*if(message.find('.short').css('display') == 'block'){
			message.find('.full').css('display','block');
			message.find('.short').css('display','none');
			*/
			$.post('/xhr/update/messages/' + $(this).attr('id'), function(){
				checkXHR('messages',notifids);
			});
		/*}else{
			message.find('.full').css('display','none');
			message.find('.short').css('display','block');
		}*/
		
		return false;
	});
	
	/**
	 * @Comments
	 */
	$('a.comet').live('click', function(){
		if($('#commHandler').find('.addComm').css('display') == 'block'){
			$('#commHandler').find('.addComm').remove();
		}else{
      $('#commList').fadeIn(200);
			$('#commHandler').append('<div class="subBlock addComm"><div class="area"><textarea></textarea></div></div>');
		}
		
		return false;
	});
	
	$('#commHandler textarea').live('keyup', function(){
		var handler = $(this);
		
		if(handler.parent().find('.save').css('display') != 'block'){
			if(handler.length > 0){
				handler.parent().append('<div class="save"><a href="javascript:;">Добавить</a></div>');
			}else{
				handler.parent().find('.save').remove();
			}
		}
	});
	
	$('#commHandler .save').live('click', function(){
		var type = $('#commHandler').find('input[name="type"]').val();
		var item = $('#commHandler').find('input[name="item"]').val();
		var message = $('#commHandler').find('textarea').val();
		$('#commHandler .addComm').fadeOut('fast', function(){$(this).remove();});
		$.post('/'+language+'/xhr/comments', {type: type, item: item, message: message}, function(response){
      res=$.parseJSON(response);
      $('div#commList span.error').remove();
      if (res)
      {
  			$('#commList').prepend(res['status']);
        //console.log($('#cmnum'));
        if (res['error']=='false')
          $('#cmnum').html(parseInt($('#cmnum').html())+1);
      }
		});
		
		return false;
	});
	
	/**
	 * @TabbedContent
	 */
	$('.orangeTabs .tabLink a,\n\
.purpleTabs .tabLink a,\n\
.msgreenTabs .tabLink a,\n\
.blueTabs.withjs .tabLink a,\n\
.greenTabs .tabLink a,').live('click', function(){
    location.hash=$(this).attr('rel');
		$(this).parent().parent().find('.active').removeClass('active');
		$(this).addClass('active');
		$('#tabContent').find('li').each(function(){
			$(this).css('display','none');
		});
		$('#tabContent li.'+$(this).attr('rel')).css('display','block');
	});
	
	/**
	 * @Footpanel
	 */
	$.fn.adjustPanel = function(){ 
		$(this).find('ul, .subpanel').css({'height' : 'auto'});
		
		var windowHeight = $(window).height();
		var panelsub = $(this).find('.subpanel').height();
		var panelAdjust = windowHeight - 100;
		var ulAdjust =  panelAdjust - 25;
		
		if(panelsub >= panelAdjust){
			$(this).find('.subpanel').css({'height' : panelAdjust});
			$(this).find('ul').css({'height' : ulAdjust});
		}
		else if(panelsub < panelAdjust){
			$(this).find('ul').css({'height' : 'auto'});
		}
	};
	
	$('#chatpanel').adjustPanel();
	$('#alertpanel').adjustPanel();
	$('#cartpanel').adjustPanel();
	
	$(window).resize(function(){ 
		$('#chatpanel').adjustPanel();
		$('#alertpanel').adjustPanel();
		$('#cartpanel').adjustPanel();
	});
	
	$('#chatpanel a:first, #cartpanel a:first, #alertpanel a:first').click(function(){
		if($(this).next('.subpanel').is(':visible')){
			$(this).next('.subpanel').hide();
			$('#footpanel li a').removeClass('active');
		}else{
			$('.subpanel').hide();
			$(this).next('.subpanel').toggle();
			$('#footpanel li a').removeClass('active');
			$(this).toggleClass('active');
		}
		return false;
	});
	
	$(document).click(function(){
		$('.subpanel').hide();
		$('#footpanel li a').removeClass('active');
	});
	$('.subpanel ul').click(function(e){ 
		e.stopPropagation();
	});

	$('#alertpanel li, #cartpanel li').hover(function(){
		$(this).find('a.delete').css({'visibility': 'visible'});
	},function(){
		$(this).find('a.delete').css({'visibility': 'hidden'});
	});
	
	$('#cartpanel li a.delete').click(function(){
		$(this).parent().remove();
		var total = 0;
		if($('#cartpanel li.product').attr('class') == undefined || $('#cartpanel li.product').attr('class') == null){
			$('#cartpanel li.view').html('Корзина пуста');
		}else{
			total = parseFloat($('#cartpanel span.total span').text())-parseFloat('0.99');
			$('#cartpanel span.total span').html(toFixed(total, 2));
		}
	});
});

/**
 * @toFixed
 */
function toFixed(value, precision){
    var power = Math.pow(10, precision || 0);
    return String(Math.round(value * power) / power);
}
/**
 * @XHR
 */


var notifflashing=false;
var messagesflashing=false;

function unflashnotif()
{
  if (notifflashing)
  {
    $('#footpanel > ul#mainpanel > li > a.notices').attr('class','notices');
    setTimeout('flashnotif()',250);
  }
}

function unflashmessages()
{
  if (messagesflashing)
  {
    $('#footpanel > ul#mainpanel > li > a.messages').attr('class','messages');
    setTimeout('flashmessages()',250);
  }
}

function flashmessages()
{
  if (messagesflashing)
  {
    $('#footpanel > ul#mainpanel > li > a.messages').attr('class','messages act');
    setTimeout('unflashmessages()',250);
  }
}

function startmessagesflashing()
{
  if (!messagesflashing)
  {
    messagesflashing=true;
    flashmessages();
  }
}

function setunreadmessages(count)
{
  if (count==0)
  {
    stopmessagesflashing();
    $('div#footpanel > ul#mainpanel > li > a.messages i').html('');
  }
  else
  {
    $('div#footpanel > ul#mainpanel > li > a.messages i').html('('+count+')');
    startmessagesflashing();
  }
}

function stopmessagesflashing()
{
  if (messagesflashing)
    messagesflashing=false;
}

function flashnotif()
{
  if (notifflashing)
  {
    $('#footpanel > ul#mainpanel > li > a.notices').attr('class','notices act');
    setTimeout('unflashnotif()',250);
  }
}

function startnotifflashing()
{
  if (!notifflashing)
  {
    notifflashing=true;
    flashnotif();
  }
}

function stopnotifflashing()
{
  if (notifflashing)
    notifflashing=false;
}

function updnotifdiv()
{
  stopnotifflashing();
  if ($('div.notifications').is(':visible'))
  {
    $('div.notifications li.unread').attr('class','').css('background','#FFEECC');
    $('#footpanel > ul#mainpanel > li > a.notices').attr('class','notices act');
  }
  else
  {
    $('#footpanel > ul#mainpanel > li > a.notices').attr('class','notices');
    $('div.notifications li').css('background','transparent');
  }
}

var notifvisible=0;

function hidenotifdiv()
{
  $('div.notifications').fadeOut(200,function(){updnotifdiv();notifvisible=0;});
}

function shownotifdiv()
{
  $('div.notifications').fadeIn(200,function(){updnotifdiv();notifvisible=1;});
  $.post('/'+language+'/xhr/flashed/' + notifids);
}

function togglenotifdiv()
{
  if (notifvisible==1)
    hidenotifdiv();
  else shownotifdiv();
//  $('div.notifications').slideToggle(200,function(){updnotifdiv();});
}

function updatenotifhandlers()
{
  $('div#footpanel ul#mainpanel li div.notifications ul.list li div.info div.links a').each(function(a,e){
    $(e).click(function(){
      $.post($(this).attr('href'),{},function(ret){
        if (ret=='RM')
        {
          $(e).css('visibility','hidden');
          $(e).parent().parent().parent().fadeOut(200, function(){
            $(this).remove();
            if ($('div.notifications > ul.list > li').length==0)
            {
              hidenotifdiv();//$('div#footpanel ul#mainpanel a.actions').click();
            }
          });
        }
        else
          alert(ret);
      });
      return false;
    })
  });
}

function checkXHR(type,xhrdata){
  if (!xhrdata)
    xhrdata='';
  xhrdata='/'+xhrdata;
	$.ajax({
		type: 'post',
		url: '/'+language+'/xhr/' + type + xhrdata,
		data: '',
		success: function(response){
      res=$.parseJSON(response);
      
      if (res)
      {
        setunreadmessages(res['messages']);
        res=res['notif'];
        if (res) for (i=0;i<res.length;i++)
        {
          if (res[i]['data']=='RM')
          {
            notifids=notifids.replace(','+res[i]['id'],'');
            $('div.notifications > ul.list > li#notif_'+res[i]['id']).fadeOut(200,function(){
              $(this).remove();
            });
            
          }
          else
          {
            notifids+=','+res[i]['id'];
            $('div.notifications ul.list').prepend('<li id="notif_'+res[i]['id']+'" class="unread">'+res[i]['data']+'</li>');
            if (!$('div.notifications').is(':visible'))
            {
              $('div.notifications ul.list li.unread').show();
              startnotifflashing();
            }
            else
            {
//              $('div.notifications li').css('background','transparent');
              $('div.notifications ul.list li.unread').fadeIn(200);
              $('div.notifications li.unread').css('background','#FFEECC').attr('class','');
              $.post('/'+language+'/xhr/flashed/' + notifids);
            }
          }
          updatenotifhandlers();
        }
      }
		}
	});
};

/**
 * @Email validation
 */
function validateEmail(email){
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) == false){
		return false;
	}else{
		return true;
	}
}

function addItems(url,elementid)
{
  var offset=$('#'+elementid+' div.items > div').length;
  $.post(url+'/'+offset,{},function(ret){
    var left=strtok(ret,'|');
    if (left<=0)
      $('a#more').fadeOut(200,function(){
        $(this).remove();
      })
    $('#'+elementid).append(ret.replace(left+'|',''));
    $('#'+elementid+' div.list-view:last').hide().fadeIn(200);
  })
}

function fcbox(href){
	jQuery.facebox({ajax: href, loadingImage : '/static/images/loading.gif'});
}

function hideflash(){
  $('div#innerBody > div.success,div#innerBody > div.flasherror').fadeOut(1000);
}

var votingendtimer;
function updatevotingend()
{
  var d=$('p.votingend span.d').html();
  var h=$('p.votingend span.h').html();
  var m=$('p.votingend span.m').html();
  var s=$('p.votingend span.s').html();
  
  s--;
  if (s<0) {
    s=59;
    m--;
    if (m<0) {
      m=59;
      h--;
      if (h<0) {
        h=23;
        d--;
        if (d<0) {
          d=0;
          h=0;
          m=0;
          s=0;
          clearInterval(votingendtimer);
        }
      }
    }
  }
  
  $('p.votingend span.d').html(d);
  $('p.votingend span.h').html(h);
  $('p.votingend span.m').html(m);
  $('p.votingend span.s').html(s);
}

$(window).hashchange(function(){
  $('a[rel="'+location.hash.replace('#','')+'"]').click();
});

$(window).ready(function(){
  $(window).hashchange();
  updatenotifhandlers();
  $('div.notifications ul.list li.unread').attr('class','').css('background','#FFEECC').show();
  if (notifflashing)
    flashnotif();
  checkXHR('messages',notifids);
  scrollElem = scrollableElement('html', 'body');
  
  setTimeout('hideflash()',3000);
  
  $('a.actionvote').live('click',function(){
    if ($(this).hasClass('mustreg'))
      $('#loginlink').click();
    else if ((!$(this).hasClass('voted'))&&(!$(this).hasClass('cantvote'))) {
      var me=$(this);
      $.get('/'+language+'/funds/vote/'+$(this).attr('rel'),function(ret){
        if (ret!='') {
          $('a.actionvote').addClass('cantvote');
          $('a.actionvote[rel="'+$(me).attr('rel')+'"]').replaceWith(ret);
//          $('a.actionvote[rel="'+$(me).attr('rel')+'"]').fadeIn(100);
        };
      });
    };
    return false;
  });
  
  if ($('p.votingend').length>0)
    votingendtimer=setInterval('updatevotingend()',1000);
  
})



