var starsWidth = new Array(16,18,20,21,22);
var defaultRating = 0;
var tempDefaultRating = 0;
var myRating = 0;
var branchID;
var cityID;
var userAuthorizedRating = false;
var bIsCorporative = 0;

$(document).ready(function(){
	var bIsVipOnly = $('#features').hasClass('vip-only');
	if(!bIsVipOnly){
		initRating();
	}

	var type = getParam('type');
	if(type.indexOf('|') != -1){
		var types = type.split('|');
		for(var i = 0; i < types.length; i++){
			fnSwapBranchFilter(parseInt(types[i]));
		}
	}else{
		if(type != ''){
			fnSwapBranchFilter(parseInt(type));
		}
	}

	$('#leader-photo').click(function (){
		$('#leadership').slideToggle(200, function(){
			var color = $('#leader-photo').css('color');
			if(color == 'rgb(8, 98, 140)' || color == '#08628c'){
				$('#leader-photo').css('color', '#6b6b6b');
			}else {
				$('#leader-photo').css('color', '#08628c');
			}
		});
		return false;
	});
	$.each($("#FilterItems table td"),function(){var td=$(this);if(!td.find("span")[0]){td.css("display","none");}});

	// $("#region-switch option").each(function(){$(this).attr("value", $(this).attr("value").replace(/^\/([^\/]+)\/russia\/([^\/]+)\/$/, '/$1/address/').replace(/^\/russia\/[^\/]+\/$/, '/address/'))});

	$("#region-switch option").each(function(){
		$(this).attr("value", $(this).attr("value").replace(/\/russia(.*\/)/i, '/address/').replace(/\/moscow\//, '/'))
	});

});

function initRating(){
	var header = $('h2.branch-title:first').text();
	var address = $('#plhAddress').html();
	branchID = $('h2.branch-title:first').attr('id');
	cityID = $('h2.branch-title:first').attr('city_id');

	var starImages = '';
	var myRating = '';
	for(var i=1; i<=5; i++){
		starImages += '<img src="/f/1/global/d-t.gif" id="star'+i+'" width="'+starsWidth[(i-1)]+'" height="19" />';
	}

	var commentForm = '<textarea name="comment" id="comment" onkeyup="validateText();"></textarea><br /><input type="submit" name="btnSubmitComment" id="btnSubmitComment" value="Отправить"/>';
	var commentContent = '<div id="blockComment"><div id="blockCommentTop" class="frame-gray incut_header hidden"><div class="frame-gray-tl"><spacer></spacer></div><div class="frame-gray-tr"><spacer></spacer></div><nobr><a href="" onclick="hideCommentBlock(); return false;" id="closeBlock"><img src="/f/1/global/i-delete-gray.gif" width="13" height="13" alt="Закрыть" /></a><a href="" class="pseudo-href" onclick="hideCommentBlock(); return false;"><strong>Отправить отзыв</strong></a></nobr></div><div id="blockCommentBottom" class="frame-gray incut_body hidden"><div class="frame-gray-bl"><spacer></spacer></div><div class="frame-gray-br"><spacer></spacer></div><div class="frame-gray-tr"><spacer></spacer></div><form action="./" onsubmit="sendComment(); return false;" id="commentForm">'+ commentForm +'</form><p class="hidden" id="commentPosted">Комментарий добавлен.</p></div></div><div class="clear"></div>';
	var headerAdd = '<table id="ratingHeader"><tr><td><p id="ratingAddress">' + address + '</p></td><td id="ratingBlock"><div id="ratingTopTitle">Рейтинг: </div><div class="rating"><a href="" onclick="return false;">'+starImages+'</a></div><div id="ratingEvaluate"><a id="voteHref" href="/retail/client/form/?city_id='+ cityID +'&branch_id='+ branchID +'" onclick="cmnPopup( this.href, \'evaluate\', \'width=670,height=600,status=no\'); return false;">Оценить отделение</a></div><div class="clear"></div><div id="ratingBottomAvg"></div><div id="ratingBottomTitle" class="hidden"><nobr>Вы голосовали:</nobr></div><div id="ratingMy" class="hidden"></div><div id="nonAuthorized" class="hidden"><nobr>Авторизуйтесь для оценки отделения</nobr></div></td><td id="sendComment"><div id="authorizedComment" class="hidden">'+commentContent+'<a href="" class="pseudo-href" onclick="showCommentBlock(); return false;">Отправить отзыв</a> или <a href="/retail/client/">оценить по&#160;параметрам</a>.</div></td></tr></table>';

	$('p#plhAddress').replaceWith(headerAdd);

	//address.appendTo("#ratingAddress");
	loadMyRating();
}


function loadMyRating()
{
	$.ajax({
		url: '/_/ajax/_load_my_rating.html?id='+branchID,
		type: 'GET',
		dataType: 'xml',
		cache: false,
		timeout: 20000,
		success: function(xml) {
			var result = $(xml).find('result').text();
			if(result == 'ok'){

				var authStatus = $(xml).find('result').attr('auth');
				// if(authStatus == 1){
				// 	userAuthorizedRating = true;
				// 	$('#authorizedComment').show();
				// }else{
				// 	$('#nonAuthorizedComment').show();
				// 	$('#ratingBlock').attr('style', 'width: 220px');
				// }
				//$('#nonAuthorizedComment').show();

				fillAvgRating($(xml).find('result').attr('voters'));

				myRating = $(xml).find('result').attr('my');
				defaultRating = $(xml).find('result').attr('overall');
				bIsCorporative = $(xml).find('result').attr('iscorp');

				showDefaultRating();
			}
		},
		error: function() {
			showDefaultRating();
		}
	});
//	showDefaultRating();
}

function fillAvgRating(voters)
{
	var lastVotersDigit = voters.toString().substring(voters.toString().length-1);
	var sFinal = '';

	if(voters == 1){
		$('#ratingBottomAvg').html('Оценил ' + voters + ' человек');
	}else{
		if(voters >= 10 && voters <= 20){
			sFinal = '';
		}else{
			if(lastVotersDigit >= 2 && lastVotersDigit <= 4){
				sFinal = 'а';
			}
		}
		$('#ratingBottomAvg').html('Оценили ' + voters + ' человек' + sFinal);
	}


}

function showStars(starsAmt)
{
	if(userAuthorizedRating){
		for(var i=1; i<=5; i++){
			if(i <= starsAmt)
				$('#star' + i).attr('src', '/f/1/i/i-star-'+i+'.gif');
			else
				$('#star' + i).attr('src', '/f/1/global/d-t.gif');
		}

		if(myRating > 0){
			$('#ratingBottomTitle').show();
			$('#ratingMy').show();
			$('#ratingBottomAvg').hide();
		}
	}else{
		$('#nonAuthorized').show();
		$('#ratingBottomAvg').hide();
	}
}

function showDefaultRating()
{
	for(var i=1; i<=5; i++){
		if(i <= defaultRating)
			$('#star' + i).attr('src', '/f/1/i/i-star-'+i+'.gif');
		else{
			if (i <= (defaultRating*1 + 0.5))
				$('#star' + i).attr('src', '/f/1/i/i-star-'+i+'h.gif');
			else
				$('#star' + i).attr('src', '/f/1/global/d-t.gif');
		}
	}

	var myRatingStars = '';
	for(var i=1; i<=myRating; i++){
		myRatingStars += '<img src="/f/1/i/i-star-sm.gif" width="10" height="8" alt="" />';
	}
	$('#ratingMy').html(myRatingStars);

	if(bIsCorporative == '1'){
		$('#voteHref').attr('href', '/retail/client/form_reg/?city_id='+ cityID +'&branch_id='+ branchID);
	}

	$('#ratingBottomTitle').hide();
	$('#ratingMy').hide();
	$('#nonAuthorized').hide();
	$('#ratingBottomAvg').show();
}

function setRating( i )
{
	if(userAuthorizedRating){
		$.post('/_/ajax/_set_my_rating.html?id=' + branchID + '&rating=' + i,
		 function(){
		});

		myRating = i;

		animateStars(i);

		var myRatingStars = '';
		for(var i=1; i<=myRating; i++){
			myRatingStars += '<img src="/f/1/i/i-star-sm.gif" width="10" height="8" alt="" />';
		}
		$('#ratingMy').html(myRatingStars);
	}else{
		showAuthorizationBlock();
	}
}

function animateStars( stars )
{
	$('div.rating a').fadeOut('fast').fadeIn('fast').fadeOut('fast').fadeIn('fast');
	tempDefaultRating = defaultRating;
	defaultRating = stars;
	window.setTimeout(restoreDefaultRating, 1000);
}

function restoreDefaultRating()
{
	defaultRating = tempDefaultRating;
	showDefaultRating();
}

function showCommentBlock()
{
	$('#blockCommentTop').show();
	$('#blockCommentBottom').show('fast');
	if($('#comment').val() == ''){
		$('#btnSubmitComment').attr('disabled', 'disabled');
	}
}

function validateText()
{
	if($('#comment').val() == ''){
		$('#btnSubmitComment').attr('disabled', 'disabled');
	}else{
		$('#btnSubmitComment').attr('disabled', '');
	}
}

function hideCommentBlock()
{
	$('#blockCommentTop').hide();
	$('#blockCommentBottom').hide('fast');
}

function sendComment()
{
	$('#btnSubmitComment').attr('disabled', 'disabled');
	$.post('/_/ajax/_post_comment.html',{
		body: $('#comment').val(),
		branch_id: branchID
		},
		function(){
			showPostResult();
		});
}

function showPostResult()
{
	$('#btnSubmitComment').attr('disabled', '');
	$('#comment').val('');
	$('#commentForm').hide();
	$('#commentPosted').show();
	window.setTimeout(restorePostForm, 1000);
}

function restorePostForm()
{
	$('#commentForm').show();
	$('#commentPosted').hide();
	hideCommentBlock();
}

