var ie = navigator.appVersion.match(/MSIE/) ? true : false;
var ff = navigator.appName.match(/Netscape/) ? true : false;
var ie8 = navigator.appVersion.match(/MSIE 8\.0/) ? true : false;

var myimages = new Array();
function preloading(){
	for (x=0; x<preloading.arguments.length; x++){
		myimages[x] = new Image();
		myimages[x].src = preloading.arguments[x];
	}
}
preloading('../images/design/button-left-hover.png', '../images/design/button-right-hover.png', '../images/design/submit-right-hover.png', '../images/design/votes-button-hover.png', '../images/design/votes-note-bottom.png', '../images/design/votes-note-top.png', '../images/design/popup-button-left-hover.png', '../images/design/popup-button-right-hover.png');

function initVoteCounter() {
	b = $('#vote .counter b');
	votes = b.text();
	b.html('');
	for(var i=0; i<votes.length; i++) {
		b.append('<div class="num'+votes.charAt(i)+'"></div>');
	}
	b.append('<div class="clear"></div>');
}

function changeCounters()
{
	$.post("/ajax_phones.php", { "lang": lang, "action": "changeCounters"},
	  function(data){
		if( data.ok == 1 ){
			$("#vote_popupform").hide();
			var b=$('#thisMonthVoted b');
			var votes=String(data.total_votes);
			var vl=votes.length;
			var dl=6-vl;
			for(i=1;i<=dl;i++){
				votes="0"+votes;
			}
			b.html('');
			for(var i=0; i<votes.length; i++) {
				b.append('<div class="num'+votes.charAt(i)+'"></div>');
			}
			b.append('<div class="clear"></div>');
			$("#totalMoney").html(data.summ);
			$("#projectVotes_"+data.project_id).html(data.project_votes);
		}
	  }
   , "json");
} 

function fbs_click(link, title) {
	/*u = location.href;
	t = document.title;*/
	u=link;
	t=title;
	window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,resizable=1,width=626,height=436');
	return false;
}

$(document).ready(function(){
	$('.menu-main li:first').find('a').addClass('first');
	$('.menu-main li:last').addClass('last').find('a').addClass('last-link');
	if ($('.menu-main li:first').hasClass('active')) $('.menu-main li:first img').attr('src', 'images/design/menu-main-home-active.gif');
	$('.supported li:last').addClass('last');
	
	$('.feedback input').focus(function(){
		$(this).addClass('focus');
	}).blur(function(){
		$(this).removeClass('focus');
	});

	chrcnt = function(e) {
		$text = $(e).val();
		$max = $(e).attr('rows');
		if ($text.length > $max) {
			$(e).val($text.substr(0, $max));
			chrcnt(this);
		} else {
			cur_len=$(e).val().length;
			$(e).prev().find('div').html(cur_len + ' / ' + $max);
		}		
	};
	$('#projectForm textarea').keydown(function(){
		chrcnt(this);
	}).keyup(function(){
		chrcnt(this);
	});
	
	
	if (document.getElementById('fld-comment') != null) {
		$symbolmax = $('#fld-comment').attr('rows');
		if (document.getElementById('fld-comment').defaultValue != $('#fld-comment').val()) $('.feedback form .words').html(document.getElementById('fld-comment').value.length + ' / ' + $symbolmax);
		else $('.feedback form .words').html('0 / ' + $symbolmax);
		$('#fld-comment').focus(function(){
			$(this).addClass('focus');
		}).blur(function(){
			$(this).removeClass('focus');
		}).keydown(function(){
			symbolcount(this);
		}).keyup(function(){
			symbolcount(this);
		});
		symbolcount = function(e){
			$text = $(e).val();
			if ($text.length > $symbolmax-1) {
				$(e).val($text.substr(0, $symbolmax));
				symbolcount(this);
			} else $('.feedback form .words').html(document.getElementById('fld-comment').value.length + ' / ' + $symbolmax);
		}
	}
	
	if (document.getElementById('answ_question') != null) {
		$symbolmax = $('#answ_question').attr('rows');
		if (document.getElementById('answ_question').defaultValue != $('#answ_question').val()) 
		{
			cur_len=$('#answ_question').val().length;
			$('.feedback-form .words').html(cur_len + ' / ' + $symbolmax);
		} 
		else $('.feedback-form .words').html('0 / ' + $symbolmax);
		$('#answ_question').focus(function(){
			$(this).addClass('focus');
		}).blur(function(){
			$(this).removeClass('focus');
		}).keydown(function(){
			symbolcount(this);
		}).keyup(function(){
			symbolcount(this);
		});
		symbolcount = function(e){
			$text = $(e).val();
			if ($text.length > $symbolmax-1) {
				$(e).val($text.substr(0, $symbolmax));
				symbolcount(this);
			} else {
				cur_len=$('#answ_question').val().length;
				$('.feedback-form .words').html(cur_len + ' / ' + $symbolmax);
			}
		}
	}
	
	initFormAct();
	
	

	if ($('#main-video .content:first').height() > $('#main-projects .content:first').height()) {
		$('#main-projects .content-inner:first').css({height: $('#main-video .content-inner:first').height() - 11});
	} else {
		$('#main-video .content-inner:first').css({height: $('#main-projects .content-inner:first').height() + 6});
	}

	if ($('#tell-block .content:first').height() > $('#vote-for .content:first').height()) {
		$('#vote-for .content-inner:first').css({height: $('#tell-block .content-inner:first').height()});
	} else {
		$('#tell-block .content-inner:first').css({height: $('#vote-for .content-inner:first').height()});
	}
	
	if ($('#vote-block .wht-content:first').height() > $('#supported-block .wht-content:first').height()) {
		$('#supported-block .wht-content:first').css({height: $('#vote-block .wht-content:first').height()});
	} else {
		$('#vote-block .wht-content:first').css({height: $('#supported-block .wht-content:first').height()});
	}
	
	if ($('#project-news .wht-content:first').height() > $('#comments .wht-content:first').height()) {
		$('#comments .wht-content:first').css({height: $('#project-news .wht-content:first').height()});
	} else {
		$('#project-news .wht-content:first').css({height: $('#comments .wht-content:first').height()});
	}
	
	if ($('#facebook-block .wht-content:first').height() > $('#draugiem-block .wht-content:first').height()) {
		$('#draugiem-block .wht-content:first').css({height: $('#facebook-block .wht-content:first').height()});
	} else {
		$('#facebook-block .wht-content:first').css({height: $('#draugiem-block .wht-content:first').height()});
	}
	
	if ($('#draugiem-block .wht-content:first').height() > $('#tweets-block .wht-content:first').height()) {
		$('#tweets-block .wht-content:first').css({height: $('#draugiem-block .wht-content:first').height()});
	} else {
		$('#draugiem-block .wht-content:first').css({height: $('#tweets-block .wht-content:first').height()});
		$('#facebook-block .wht-content:first').css({height: $('#tweets-block .wht-content:first').height()});
	}
		
	$('.project-list .votes').each(function(){
		$height = $(this).parent().height() - 16;
		$(this).find('.content').css({height: $height});
	});
	$('.project-list .pic').each(function(){
		$padding = $(this).parent().find('h2').height() + 7;
		$(this).css({'padding-top': $padding});
		$height = $(this).parent().height() - $padding;
		$(this).css({height: $height});
	});
	
	$('.votes .star .img').hover(function(){
		$note = $(this).parent().find('.note');
		$height = $note.height();
		$note.css({top: -$height}).show();
	}, function(){
		$(this).parent().find('.note').hide();
	});
	
	$('.votes .question .img').hover(function(){
		$note = $(this).parent().find('.note');
		$height = $note.height();
		$note.css({top: -$height}).show();
	}, function(){
		$(this).parent().find('.note').hide();
	});
	
	$('.popup-close').click(function(){
		
		if (ie) $('.popup').hide();
		else $('.popup').fadeOut();
		
		return false;
	});
	
	/*$('.send-form .add-line').click(function(){
		$label = $(this).parent().parent().find('li:last span').html();
		$num = $(this).parent().parent().find('li').size();
		if ($num < 10) {
			$('<li><label for="email' + $num + '">' + $num + '. <span>' + $label + '</span></label><input id="email' + $num + '" name="email' + $num + '" type="text" /></li>').appendTo('.send-form ul');
			popup_mail();
		}
		return false;
	});
	*/
		if ($('#mailFriendsForma').length) {

		$('.send-form .add-line').click(function(){
			$label = $(this).parent().parent().find('li:last span').html();
			$label = $label.replace('*', '');
			$num = $(this).parent().parent().find('li').size();
			if ($num < 10) {
				$('<li><label for="email' + $num + '">' + $num + '. <span>' + $label + '</span></label><input id="email' + $num + '" name="email[]" type="text" /></li>').appendTo('.send-form ul');
			}
			return false;
		});
		
		$('.send-form .button').click(function(){
			$('#mailFriendsForma').submit();
			return false;
		});
	}	
	else {
		$('.send-form .add-line').click(function(){
			$label = $(this).parent().parent().find('li:last span').html();
			$label = $label.replace('*', '');
			$num = $(this).parent().parent().find('li').size();
			if ($num < 10) {
				$('<li><label for="email' + $num + '">' + $num + '. <span>' + $label + '</span></label><input id="email' + $num + '" name="email[]" type="text" /></li>').appendTo('.send-form ul');
				popup_mail();
			}
			return false;
		});
		
		$('.send-form .button').click(function(){
			$('.send-form').submit();
			return false;
		});
	}
	
	$('.send-form .button').click(function(){
		$('.send-form').submit();
		return false;
	});
	
	$('.feedback-form .submit').click(function(){
		$('.feedback-form').submit();
		return false;
	});
	
	$('#answer_question .submit').click(function(){
		$('#answer_question').submit();
		return false;
	});
	
	$('.voting-form .submit').click(function(){
		$('.voting-form .submit').click(function() { return false; });
		$('.voting-form').submit();
		return false;
	});
	
	$('.reg-form .big-button').click(function(){
		
		if( $('.reg-form .big-button').hasClass('prjform') ){
			
			clearCookie();
			if( checkAgree() ){
				$('#projectForm').submit();
			}
			
		}else{
		
			$('.reg-form').submit();
		}
		
		return false;
	});
	
	/*$('#big-button').click(function(){
		if( checkAgree() ){
			$('#projectForm').submit();
		}
		return false;
	});
	*/
	//prjform
	
	$('.reg-form .add-line').click(function(){
	
		//for( $i=0; $i < limitFile-2; $i++ ){
		
		$num = $(this).parent().parent().find('li .file-field').size() + 1;
		/*if ($num < limitFile) {
			$note = $('.reg-form li:last').find('.note-content').html();
			$('<li><div class="note"><div class="note-top"></div><div class="note-content">' + $note + '</div><div class="note-bottom"></div></div><label></label><input id="file' + $num + '" name="projfile[]" type="file" class="file" size="1" onchange="fileChange(\'file' + $num + '\')" /><input name="file' + $num + '-text" type="text" class="file-field" /><a href="#" class="browse-button">Browse</a> <span class="icons"><a href="#"><img src="images/design/reg-form-i.gif" alt="" /></a><span></span></span></li>').appendTo('.reg-form ul:last');
			fileReady();
			
			if( $num == limitFile -1  ){
				
				$('.reg-form .add-line').hide();
			}
			
		}*/
		
		if ($num < limitFile) {
			$note = $('#file_cont li:last').find('.note-content').html();
			$('<li><div class="note"><div class="note-top"></div><div class="note-content">' + $note + '</div><div class="note-bottom"></div></div><label></label><input id="file' + $num + '" name="projfile[]" type="file" class="file" size="1" onchange="fileChange(\'file' + $num + '\')" /><input name="file' + $num + '-text" type="text" class="file-field" /><a href="#" class="browse-button">Browse</a> <span class="icons"><a href="#"><img src="images/design/reg-form-i.gif" alt="" /></a><span></span></span></li>').appendTo('#file_cont');
			fileReady();
			
			if( $num == limitFile -1  ){
				
				$('.reg-form .add-line').hide();
			}
			
		}
		
		//}
		//$('.reg-form .add-line').hide();
		
		return false;
	});
	
	$('.reg-form .add-ytline').click(function(){
		
		$num = $(this).parent().parent().find('li .yt-video').size() + 1;
		
		$note = $('#yt_cont li:last').find('.note-content').html();
		$('<li><div class="note"><div class="note-top"></div><div class="note-content">' + $note + '</div><div class="note-bottom"></div></div><label></label><input tabindex="21" type="text" name="ytvideo[]" id="ytvideo_'+$num+'" value="" maxlength="255" class="yt-video" /> <span class="icons"><a href="#"><img src="images/design/reg-form-i.gif" alt="" /></a><span></span></span></li>').appendTo('#yt_cont');
		fileReady();
		
		if( $num == limitYt  ){
			
			$('.reg-form .add-ytline').hide();
		}
		
		return false;
	});
	
	$('.chain li:last').addClass('last');
	
	$('.faq-block li h3 a').click(function(){
		$(this).toggleClass('active');
		if ($(this).hasClass('active')) $(this).parent().parent().find('.answer').stop(false, true).slideDown();
		else $(this).parent().parent().find('.answer').stop(false, true).slideUp();
		return false;
	});
	
	fileReady = function(){
		$('.reg-form .file').css({opacity: 0});
		if (ie) $('.reg-form input.file').css({'margin-left': 212, filter: 'alpha(opacity = 0)'});
		if (ie8) $('.reg-form input.file').css({'margin-left': 380});
		if (ff) $('.reg-form input.file').css({'margin-left': 330});
		$('.reg-form .file').hover(function(){
			$(this).parent().find('.browse-button').css({'text-decoration': 'underline'});
		}, function(){
			$(this).parent().find('.browse-button').css({'text-decoration': 'none'});
		});
		$('.reg-form .icons a').hover(function(){
			$note = $(this).parent().parent().find('.note');
			$height = $note.height();
			$top = $(this).position().top - $height - 5;
			$left = $(this).position().left + 15;
			$note.show().css({top: $top, left: $left});
		}, function(){
			$(this).parent().parent().find('.note').hide();
		}).click(function(){
			return false;
		});
	}
	fileReady();
	fileChange = function(obj){
		$input = '#' + obj;
		$($input).parent().find('.file-field').val($($input).val());
	}
	
	budgetChange = function(obj){
		$input = '#' + obj;
		$($input).parent().find('.budget-field').val($($input).val());
	}
	
	$('.sidemenu li:first').addClass('first');
	
	if ($('.heading').find('.tellafriend').size() == 0) $('.heading h1').css({width: 'auto'});
	
	$('.shadow-right').each(function(){
		if ($(this).height() > $(this).prev().height()) $(this).prev().find('.questions').css({height: $(this).find('.questions').height()});
		else $(this).find('.questions').css({height: $(this).prev().find('.questions').height()});
	});
	
	$('.smscredit-note').hover(function(){
		$note = $(this).parent().parent().parent().find('.note');
		$note.show().css({'margin-left': $(this).position().left - 85, 'margin-top': $(this).position().top - $note.height() - 70});
	}, function(){
		$(this).parent().parent().parent().find('.note').hide();
	});
	
	$('.popup3 .cover').css({opacity: 0.7, filter: 'alpha(opacity = 70)'});
	$('.popup-agreement .cover').css({opacity: 0.7, filter: 'alpha(opacity = 70)'});
	//$('.popup-agreement .container').css({top: ($('.popup-agreement').height() - $('.popup-agreement .container').height()) / 2});
	$('.popup-agreement .close').click(function(){
		if (ie) $('.popup-agreement').hide();
		else $('.popup-agreement').fadeOut();
		return false;
	});
	
	$('.popup3 .close').click(function(){
		if (ie) $('.popup3').hide();
		else $('.popup3').fadeOut();
		return false;
	});
		
	
	$('.readlicense').click(
								function(){
									$('.popup-agreement').css('display', '');
								}
							);
							
	/*$("a[rel=galerija]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
			return '<span id="fancybox-title-over">' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
		}
	});*/	

	initVoteCounter();
	// search input label
	$('.search .input').focus(function() {
		var current_val = $(this).val();
		if (current_val == DEFAULT_SEARCH_TEXT) {
			$(this).removeClass('blur');
	        $(this).val("");
		}		
	}).blur(function() {
		if ($(this).val() == "") {
			$(this).addClass('blur');
			$(this).val(DEFAULT_SEARCH_TEXT);
		}
	});
	
	if ($('.search .input').val() == '') {
		$('.search .input').val(DEFAULT_SEARCH_TEXT);
	}
	// hover for vote buttons
	$('#vote .vote-button').each(function() {
		$(this).hover(function() {
			$(this).parent().addClass('votes-active');
		},function() {

			$(this).parent().removeClass('votes-active');
		})
	});
	
	$('.project .favorite img').hover(function(){
		pos = $(this).position();
		$note = $(this).closest('div').find('.note');
		
		$note.css({top: -($note.height()-pos.top+5), left: pos.left+35, zIndex: 3}).show();
	}, function(){
		$(this).closest('div').find('.note').hide();
	});
	$('.project .question img').hover(function(){
		pos = $(this).position();
		$note = $(this).closest('div').find('.note');
		
		$note.css({top: -($note.height()-pos.top+5), left: pos.left+35, zIndex: 3}).show();
	}, function(){
		$(this).closest('div').find('.note').hide();
	});
});

function initFormAct(){
	
	if (document.getElementById('fld-comment2') != null) {
		$symbolmax2 = $('#fld-comment2').attr('rows');
		if (document.getElementById('fld-comment2').defaultValue != $('#fld-comment2').val()) $('.feedback form .words2').html(document.getElementById('fld-comment2').value.length + ' / ' + $symbolmax2);
		else $('.feedback form .words2').html('0 / ' + $symbolmax2);
		
		/*$('#fld-comment2').focus(function(){
			$(this).addClass('focus');
			if (document.getElementById('fld-comment2').defaultValue == $(this).val()) $(this).val('');
		}).blur(function(){
			$(this).removeClass('focus');
			if ($(this).val() == '') $(this).val(document.getElementById('fld-comment2').defaultValue);
		})*/
		$('#fld-comment2').keydown(function(){
			symbolcount2(this);
		}).keyup(function(){
			symbolcount2(this);
		});
		symbolcount2 = function(w){
			$text2 = $(w).val();
			if ($text2.length > $symbolmax2-1) {
				$(w).val($text2.substr(0, $symbolmax2));
				symbolcount2(this);
			} else $('.feedback form .words2').html(document.getElementById('fld-comment2').value.length + ' / ' + $symbolmax2);
		}
	}
	
}


function DraugiemSay(title, url, titlePrefix) {
	window.open('http://www.draugiem.lv/say/ext/add.php?title='+encodeURIComponent(title)+'&link='+encodeURIComponent(url)+(titlePrefix?'&titlePrefix='+encodeURIComponent(titlePrefix):''),'','location=1,status=1,scrollbars=0,resizable=0,width=530,height=400');
	return false;
}

function callPublish(name, link, description) {
	var facebookAttachment = {
		    'name':name,
		    'href':link,
		    'description':description,
		    'media' : []
		};

	
	FB.ensureInit(function () {
		FB.Connect.streamPublish('', facebookAttachment, null);
	});
}

var ajaxName = 'ajax_comments';
var project_id = 0;
var offset = 5;
//var project_loc= '';

function getAnswers( cid ){
	
	closeAllForm();
	$('.ans_link').css('visibility', '');
	$('.closeBtn').hide();
	$('#com_btn_' + cid).hide();
	
	$('#ans_'+cid).slideToggle("slow", function () {
		
		$('#closeBtnCom_'+cid).show();
	});

}

function getMoreComments(){
	
				$.post("/"+ajaxName+".php", { pos: items, action: 'more', lang: lang, pid: project_id },
							  function(data){
								if( data.ok == 1 ){
									
									$('#mainComments').append( data.content );
									
									if( data.content == '' ){
										
										$('.btn').hide();
									}
									
									items += offset;
								}
							  }
						   , "json");
	
}

function getMoreQuestions(){
	
				$.post("/"+ajaxName+".php", { pos: items, action: 'moreQuestions', lang: lang, pid: project_id },
							  function(data){
								if( data.ok == 1 ){
									
									$('#mainComments').append( data.content );
									
									if( data.content == '' ){
										
										$('.btn').hide();
									}
									
									items += offset;
								}
							  }
						   , "json");
	
}

function getRezultMoreComments(){
	
				$.post("/"+ajaxName+".php", { pos: items, action: 'more', lang: lang, pid: project_id, rezult: 1 },
							  function(data){
								if( data.ok == 1 ){
									
									$('#mainComments').append( data.content );
									
									if( data.content == '' ){
										
										$('.btn').hide();
									}
									
									items += offset;
								}
							  }
						   , "json");
	
}

function getRezultMoreQuestions(){
	
	$.post("/"+ajaxName+".php", { pos: items, action: 'moreQuestions', lang: lang, pid: project_id, rezult:1 },
				  function(data){
					if( data.ok == 1 ){
						
						$('#mainComments').append( data.content );
						
						if( data.content == '' ){
							
							$('.btn').hide();
						}
						
						items += offset;
					}
				  }
			   , "json");

}

function postComments( cid, lang ){
			
			var name	 =  $('#fld-vards2').val();
			var comments     =  $('#fld-comment2').val();
			var code				=$('#fld-code2').val();

			$.post("/"+ajaxName+".php", { cid: cid, lang: lang, action: 'getAnswerForm', name: name, text: comments, commentsAction: 1, pid: project_id, code: code, captcha: 'proj_answ' },
							  function(data){
								if( data.ok == 1 ){
									
									closeAllForm();
									
									if( data.item != '' ){
									
										//$('.ans_link').css('visibility', '');
										$('#ans_' + data.cid).append( data.item );
										
										if( data.cnt != 0 ){
											
											$('#cnt_ans_' + cid).html( data.cnt );
											
											if( data.cnt == 1 ){
												
												
												$('#com_btn_'+cid).html( coment_lgrb + '(<span id="cnt_ans_'+cid+'">'+ data.cnt +'</span>)' );
											}
										}
										
										$('#ans_' + data.cid + ' .feedback-block').hide();
										
									}else{
										$('#ans_' + data.cid + ' .feedback-block').html( data.content );
									}
									
									initFormAct();
								}
							  }
						   , "json");
	
}

function reloadCaptchaImage(sess)
{
	var ts = Math.round(new Date().getTime() / 1000);
	$("#captcha_"+sess).html('');
	$('#captcha_'+sess).html('<img class="code" alt="" src="/captcha.php?sess='+sess+'&ts='+ts+'" />');
}

function getSess()
{
	$.post("/"+ajaxName+".php", {action: 'get_sess'},
							  function(data){
								if( data.ok == 1 ){
									//firebugā redzams
								}
							  }
						   , "json");
}

function closeBtn( cid ){
	
	$('#ans_'+cid).slideToggle("slow", function () {
								$('.ans_link').css('visibility', '');
								$('.closeBtn').hide();
								$('#com_btn_' + cid).show();
								$('#fdblck_'+cid).hide();
								$('#closeBtnCom_'+cid).hide();
							});
	
}

function closeAllForm(){
	
	$('.feedback-block').html('');
	
}

function showAnswerForm( cid, lang, linkID ){
	
		$.post("/"+ajaxName+".php", { cid: cid, lang: lang, action: 'getAnswerForm', pid: project_id },
							  function(data){
								if( data.ok == 1 ){
									
									closeAllForm();
									$('.ans_link').css('visibility', '');
									$('#ans_' + data.cid + ' .feedback-block').html( data.content );
									$( linkID ).css('visibility', 'hidden');
									
									initFormAct();
									
									$('.closeBtn').hide();
									if( $('#ans_'+cid).css('display') == 'none' ){
										$('#ans_'+cid).slideToggle("slow", function () {
										});
									}
									
									$('#clform_'+cid).show();
									$('#fdblck_'+cid).show();
									$('#com_btn_' + cid).hide();
									$('#closeBtnCom_'+cid).hide();
								}
								if(data.reload_captcha)
							   {
									reloadCaptchaImage('proj_answ');
							   }
							  }
						   , "json");
	
}

function showVoteForm( pid ){

	$.post("/ajax_vote.php", { pid: pid, lang: lang },
							  function(data){
								if( data.ok == 1 ){
									$('#vote_content').html( data.content );
									$('#vote_popupform').show();
								}
							  }
						   , "json");
	
}

function doVote( ){
	
	var pid = $('#pid').val();
	var phone = $('#phone').val();
	var code = $('#code').val();
	var country=$('#country').val();
	var step=$("#step").val();
	var sms_alert=$("#sms-alert").attr('checked');
	
		var param = new Object();
		param['pid']   = pid;
		param['phone'] = phone;
		param['lang'] = lang;
		param['country']=country;
		param['smsVote'] = 1;
		param['step']=step;
		param['sms-alert']=sms_alert;
		
		if( typeof( code ) != 'undefined'){
		
			param['code'] = code;
		}
		
		$.post("/ajax_vote.php", param,
							  function(data){
								if( data.ok == 1 ){
								
									$('#vote_content').html( data.content );
									$('#vote_popupform').show();
								}
							  }
						   , "json");
	
}


function checkForm( id ){
	
	var validForm = true;
	var errorMsg = '';
	var formName = '';
	
	if( typeof( id ) != 'undefined' ){
				
				
		formName = $(id).attr('name');
		
		if( validateForm( formName ) ){
		
			$( id ).parent().removeClass('nook');
			$( id ).parent().addClass('ok');
			
		}else{
			
			$( id ).parent().removeClass('ok');
			$( id ).parent().addClass('nook');
		}
		
		return false;
	}
	
}

function isEmptyStr( str ){

		if( str == '' ){
					
				return false;
		}else{
					
				return true;
		}
	
}

function isFieldEmail( str ) {
 if (!/[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9.-]{2,4}$/.test( str )) {

  return true;
 }

 return false;
}

function isDigitStr( str ){
	
	var regex = /^\d{1}$/;
	
	if( str.length == 0 ){
		
		return false;
	}
	
	for ( var i = 0; i < str.length; i++ )
	{
		if ( !regex.test( str.charAt( i ) ) ){
		
			return false;
		}
	}
	
	return true;
}

function Age()
{

	var bday=parseInt( $('#birthdate-1').val() );
	var bmo=(parseInt( $('#birthdate-2').val() )-1);
	var byr=parseInt( $('#birthdate-3').val() );
	var byr;
	var age=0;
	var now = new Date();
	tday=now.getDate();
	tmo=(now.getMonth());
	tyr=(now.getFullYear());


	if((tmo > bmo)||(tmo==bmo & tday>=bday)){
	
		age=byr
	}else{
		age=byr+1
	}
	//alert("As of today, "+now+' \n'+", you are:"+(tyr-age)+ " years old");
	
	return (tyr-age);
}
	
function checkDate(){
	if( $('#birthdate-1').val() == '' || $('#birthdate-2').val() == '' || $('#birthdate-3').val() == ''){
		$('#acceptText').html( $('#more18').html() );
		return false;
	}else{
		$('#userAge').val( Age() );
		
		if( Age() >= 18 ){
			$('#acceptText').html( $('#more18').html() );
		}else{
			$('#acceptText').html( $('#m18').html() );
		}
		return true;
	}
}

function clearCookie(){
	
							$(".iform", "#projectForm").each( function(i, domElement){
															if($(this).attr("name") != "youare"){

																$.cookie('cf_'+$(this).attr("name"), '', { expires: 10 });
															}
														});
	
}

function checkAgree(){
	if( $('#accept').attr('checked') ){
		
		$('#chckAge').css('display', 'none');
		return true;
	}else{
		
		$('#chckAge').css('display', '');
		return false;
	}
}


function DraugiemSay(title, url, titlePrefix) {
	window.open('http://www.draugiem.lv/say/ext/add.php?title='+encodeURIComponent(title)+'&link='+encodeURIComponent(url)+(titlePrefix?'&titlePrefix='+encodeURIComponent(titlePrefix):''),'','location=1,status=1,scrollbars=0,resizable=0,width=530,height=400');
	return false;
}

function callPublish(name, link, description) {
	var facebookAttachment = {
		    'name':name,
		    'href':link,
		    'description':description,
		    'media' : []
		};

	
	FB.ensureInit(function () {
		FB.Connect.streamPublish('', facebookAttachment, null);
	});
}



/*function checkForm( id ){
	var validForm = true;
	var errorMsg = '';
	var formName = '';
	
	if( typeof( id ) != 'undefined' ){
				
				
		formName = $(id).attr('name');
		
		if( validateForm( formName ) ){
		
			$( id ).parent().removeClass('nook');
			$( id ).parent().addClass('ok');
			
		}else{
			
			$( id ).parent().removeClass('ok');
			$( id ).parent().addClass('nook');
		}
		
		return false;
	}
	
}

function isEmptyStr( str ){

		if( str == '' ){
					
				return false;
		}else{
					
				return true;
		}
	
}

function isFieldEmail( str ) {
 if (!/[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9.-]{2,4}$/.test( str )) {

  return true;
 }

 return false;
}

function isDigitStr( str ){
	
	var regex = /^\d{1}$/;
	
	if( str.length == 0 ){
		
		return false;
	}
	
	for ( var i = 0; i < str.length; i++ )
	{
		if ( !regex.test( str.charAt( i ) ) ){
		
			return false;
		}
	}
	
	return true;
}

function Age()
{

	var bday=parseInt( $('#birthdate-1').val() );
	var bmo=(parseInt( $('#birthdate-2').val() )-1);
	var byr=parseInt( $('#birthdate-3').val() );
	var byr;
	var age=0;
	var now = new Date();
	tday=now.getDate();
	tmo=(now.getMonth());
	tyr=(now.getFullYear());


	if((tmo > bmo)||(tmo==bmo & tday>=bday)){
	
		age=byr
	}else{
		age=byr+1
	}
	//alert("As of today, "+now+' \n'+", you are:"+(tyr-age)+ " years old");
	
	return (tyr-age);
}
	
function checkDate(){
	
	if( $('#birthdate-1').val() == '' || $('#birthdate-2').val() == '' || $('#birthdate-3').val() == ''){
		
		return false;
	}else{
		
		
		$('#userAge').val( Age() );
		
		if( Age() >= 18 ){
			$('#acceptText').html( $('#more18').html() );
		}else{
			$('#acceptText').html( $('#m18').html() );
		}
		return true;
	}
}

function clearCookie(){
	
							$(".iform", "#projectForm").each( function(i, domElement){
															if($(this).attr("name") != "youare"){

																$.cookie('cf_'+$(this).attr("name"), '', { expires: 10 });
															}
														});
	
}

function checkAgree(){
	if( $('#accept').attr('checked') ){
		
		$('#chckAge').css('display', 'none');
		return true;
	}else{
		
		$('#chckAge').css('display', '');
		return false;
	}
}*/

function validateForm( formName ){
	
	var formValue = $('#' + formName).val();
	
	$.cookie('cf_'+formName, formValue, { expires: 10 });
	
	switch( formName ){	
		case 'name':
				
				return isEmptyStr( formValue );

			break;
		case 'phone':
				
				return isDigitStr( formValue );
				
			break;
		case 'email':
					
					return !isFieldEmail( formValue );
			break;
		case 'title':
				
				return isEmptyStr( formValue );
				
			break;
		case 'description':
				
				return isEmptyStr( formValue );
				
			break;
		case 'proj_info':
				
				return isEmptyStr( formValue );
				
			break;
		case 'youare':
				return isEmptyStr( formValue );
			break; 
		case 'birthdate-1':
				return checkDate();
			break;
		case 'birthdate-2':
				return checkDate();
			break;
		case 'birthdate-3':
				return checkDate();
			break;
		case 'fname':
		
				return isEmptyStr( formValue );
			break;
		case 'lname':
		
				return isEmptyStr( formValue );
			break;
		case 'regnr':
				
				return isDigitStr( formValue );
				
			break;
		case 'amount':
			
			return isEmptyStr( formValue );
			
		break;
		case 'address':
				
				return isEmptyStr( formValue );	
			break;
		case 'address_j':
			
			return isEmptyStr( formValue );	
			break;
		case 'address_f':
			
			return isEmptyStr( formValue );	
			break;
		case 'fphone':
				
				return isDigitStr( formValue );
			break;
		case 'type':
			return isEmptyStr( formValue );
			break;
		case 'dislocation':
			
			return isEmptyStr( formValue );
			break;
		case 'term':
			
			return isEmptyStr( formValue );
			break;
		case 'project_objectives':
			
			return isEmptyStr( formValue );
			break;
		case 'project_tasks':
			
			return isEmptyStr( formValue );
			break;
		case 'proj_info':
			
			return isEmptyStr( formValue );
			break;
		case 'situation_description':
			return isEmptyStr( formValue );
			break;
		case 'fphone':
			
			return isDigitStr( formValue );
			break;
		default: 
			return true;
	}
}

function popup_mail3(url) {
	if (ie) $('.popup').show();
	else $('.popup').fadeIn();
	$('.popup .cover').css({opacity: 0.7, filter: 'alpha(opacity = 70)'});
	$docheight = $('.popup').height();
	$blockheight = $('.popup .container-inner').height();
	$('.popup .container').css({top: ($docheight - $blockheight) / 2});
	$('#url').val(url);
	return false;
}

popup_mail = function() {
	if (ie) $('#mail_popup').show();
	else $('#mail_popup').fadeIn();
	$('#mail_popup .cover').css({opacity: 0.7, filter: 'alpha(opacity = 70)'});
	$docheight = $('#mail_popup').height();
	$blockheight = $('#mail_popup .container-inner').height();
	$('#mail_popup .container').css({top: ($docheight - $blockheight) / 2});
	return false;
}

jQuery.timer = function(interval, callback, options) {
	var options = jQuery.extend({ reset: 500 }, options); // Create options for the default reset value
	var interval = interval || options.reset;
	
	if(!callback) { return false; }
	
	timer = function(interval, callback) {
		// Only used by internal code to call the callback
		this.internalCallback = function() { callback(self); };
	
		// Clears any timers
		this.stop = function() { clearInterval(self.id); };
		// Resets timers to a new time
		this.reset = function(time) {
			if(self.id) { clearInterval(self.id); }
			var time = time || options.reset;
			
			this.id = setInterval(this.internalCallback, time);
		};
		
		// Set the interval time again
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		
		var self = this;
	};
	
	// Create a new timer object
	return new timer(interval, callback);
};

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Works with jQuery +1.2.6. Tested on FF 2/3, IE 6/7/8, Opera 9.5/6, Safari 3, Chrome 1 on WinXP.
 *
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * @id jQuery.scrollTo
 * @id jQuery.fn.scrollTo
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
 *	  The different options for target are:
 *		- A number position (will be applied to all axes).
 *		- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *		- A jQuery/DOM element ( logically, child of the element to scroll )
 *		- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *		- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
*		- A percentage of the container's dimension/s, for example: 50% to go to the middle.
 *		- The string 'max' for go-to-end. 
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
 * @param {Object,Function} settings Optional set of settings or the onAfter callback.
 *	 @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 *	 @option {Number} duration The OVERALL length of the animation.
 *	 @option {String} easing The easing method for the animation.
 *	 @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 *	 @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
 *	 @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
 *	 @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 *	 @option {Function} onAfter Function to be called after the scrolling ends. 
 *	 @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @desc Scroll to a fixed position
 * @example $('div').scrollTo( 340 );
 *
 * @desc Scroll relatively to the actual position
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @dec Scroll using a selector (relative to the scrolled element)
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
 *
 * @ Scroll to a DOM element (same for jQuery object)
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *			$('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
 *				alert('scrolled!!');																   
 *			}});
 *
 * @desc Scroll on both axes, to different values
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
 */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );
