﻿var auth=0; var model=0; var model_name=""; var cachedGifts = new Array(); var cachedBrandGifts = new Array();

var NEED_REGISTRATION = '<p><strong>Для участия в голосовании Вам необходимо пройти процедуру регистрации или авторизоваться</strong>' +
						'<table><tr><td>Хотите зарегистрироваться?</td>' +
						'<td>Продолжить просмотр каталога?</td></tr>' +
						'<tr><td><input type="button" value="Да" class="jqmClick" href="/rules/registration/" /></td>' +
						'<td><input type="button" value="Да" class="jqmClose" /></td></tr></table>';

var NEED_REGISTRATION_TO_EXAM = '<p><strong>Для участия в розыгрыше приза Вам необходимо пройти процедуру регистрации или авторизоваться</strong>' +
						'<table><tr><td>Хотите зарегистрироваться?</td>' +
						'<td>Авторизоваться?</td></tr>' +
						'<tr><td><input type="button" value="Да" class="jqmClick" href="/rules/registration/" /></td>' +
						'<td><input type="button" value="Да" class="jqmClose" /></td></tr></table>';

var MAKE_CHOICE = '<p><strong>Вы выбрали %auto% в Классе %class%</strong></p>' +
					'<table><tr><td>Продолжить голосование в других классах?</td>' +
					'<td>Перейти в &laquo;Личный кабинет&raquo;?</td></tr>' +
					'<tr><td><input type="button" value="Да" class="jqmClick" href="%thispage%" /></td>' +
					'<td><input type="button" value="Да" class="jqmClick" href="/cabinet/" /></td></tr></table>';
					
var CHANGE_CHOICE = '<p>Вы уже выбрали автомобиль <strong>%auto%</strong> в Классе <strong>%class%</strong>.</p>' +
					'<table><tr><td>Заменить выбор?</td>' +
					'<td>Продолжить просмотр каталога?</td></tr>' +
					'<tr><td><input type="button" value="Да" class="jqmSubmit" /></td>' +
					'<td><input type="button" value="Да" class="jqmClose" /></td></tr></table>';

var CONFIRM_CHOICE = '<p class="black">После подтверждения Вы не сможете изменять свой выбор в классах, где выбраны автомобили.</p>' +
					'<table><tr><td>Подтвердить выбор?</td>' +
					'<td>Не подтверждать</td></tr>' +
					'<tr><td><input type="button" value="Да" class="jqmSubmit" /></td>' +
					'<td><input type="button" value="Да" class="jqmClose" /></td></tr></table>';

$(document).ready(function() {

	// showMainPagePrizes();
	// showMainPagePrizers();
	
	/* ------------------- Тулбар ------------------------*/
	initToolbar();
	/* ------------------- Тулбар end ------------------------*/
	
	initArrows();
	initBrandGift();
	initGiftList();
		initLoginForm();
		initTopFlash();
		initFlapperFlash();
		initSelector();
		initSearchModel();
		initSbrfSelector();
	showCalendar();
	catalogListActions();
	showSubmitButtons();
	
	initBanners();
	initPopup();
	
	initBigPrizes();
	initImgBlock()
	
	initElseButton();
	initExamRequest();
	
	rght = ($('body').width()-$('#top_wrapper').width())/2 + 180;
	$('#top_wrapper .error').css({ right: rght });
	
	var test = ("ford focus", "ford mondeo");
	
	autocompleteObjs = $('#search_part input, form[name=registrationForm] input[name="info[lm]"], form[name=changeForm] input[name="info[lm]"]');
	if(autocompleteObjs.length)
		autocompleteObjs.autocomplete('/catalog/search');

	if($('#login_form').length || $('.toolbar').length) {	// Тулбар
		$(document).click(function(e) {
			if($(e.target).attr('id') != 'login_form' && !$(e.target).parents('#login_form').length) closeLoginForm();
			/* ------------------- Тулбар ------------------------*/
			if($(e.target).attr('class') != 'toolbar' && !$(e.target).parents('.toolbar').length) closeToolbars();
			/* ------------------- Тулбар end ------------------------*/
		});
	}
	
	$('.xochu_priz').hover(function(){
		$(this).css('text-decoration', 'none');
						},function(){
		$(this).css('text-decoration', 'underline');
	});

});
/* ------------------- Тулбар ------------------------*/
function closeToolbars() {
	$('.toolbar').hide();
}

function initToolbar() {
	$('#top #top_wrapper div.left:eq(1) a:last').unbind('hover').hover(function() { $('a', $(this).prev()).addClass('hovered'); }, function() { $('a', $(this).prev()).removeClass('hovered'); });
	
	$('#top #top_wrapper div.left:eq(1) a').unbind('click').click(function() {
		if($('.toolbar:visible').length) closeToolbars();
		else $('#toolbar1_1').show();
		return false;
	});
	
	if($.browser.msie) {
		$('#top .toolbar').each(function() {
			toolbarObj = $(this).clone();
			$(this).remove();
			$('#top').after(toolbarObj);
		});
	}

	$('.toolbar .item').hover(function() {
		$(this).addClass('hovered');

		if($('div.icon', this).length) subbarname = $('div.icon', this).attr('class').replace(/icon\s/, "");
		$('div[parent]').hide();
		$(this).parents('.toolbar:eq(0)').show();
		if($('div.arrow', this).length) {
			$('.toolbar[parent='+subbarname+']').show();
		} 
	}, function() { 
		$(this).removeClass('hovered');
	});
	
	$('.toolbar .item a').unbind('click').click(function() {
		if($('div.icon', this).length) subbarname = $('div.icon', $(this).parent()).attr('class').replace(/icon\s/, "");
		opened = $('.toolbar[parent='+subbarname+']:visible').length;
		
		$('div[parent]').hide();
		if($('div.arrow', $(this).parent()).length) {
			if(!opened) $('.toolbar[parent='+subbarname+']').show();
			return false;
		}
	});
	
	$('.toolbar .item').unbind('click').click(function() {
		if($('div.icon', this).length) subbarname = $('div.icon', this).attr('class').replace(/icon\s/, "");
		opened = $('.toolbar[parent='+subbarname+']:visible').length;
	
		$('div[parent]').hide();
		if($('div.arrow', this).length) {
			if(!opened) $('.toolbar[parent='+subbarname+']').show();
			return false;
		} else
			location.href = $('a', this).attr('href');
	});
}
/* ------------------- Тулбар end ------------------------*/
function initExamRequest(){
	$('.xochu_priz[examid]').unbind('click').click(function(e){
		if(!$('#top #top_wrapper .right .blue').length) {
			lft = e.pageX-300;
			tp = e.pageY-120;
		
			$('#popupBox').css({ left: lft, top: tp });
			text = NEED_REGISTRATION_TO_EXAM;
			$('#popupBoxMSG').html(text);
	
			$('#popupBoxMSG tr:first td:last, #popupBoxMSG tr:last td:last').css('border', '0px');
	
			$('#popupBoxMSG input.jqmClick').click(function() { document.location.href = $(this).attr('href'); });
			$('#popupBoxMSG input.jqmClose').click(function() { 
				$('#popupBox').jqmHide(); 
				window.scrollTo(0,0); 
				$('#login_form').show();
			});
			$('#popupBox').jqm({ modal:true }).jqDrag('#popupBoxTL');
			$('#popupBox').jqmShow().show();
			return false;
		} else {
			document.location.href = '/cabinet/exam/?'+$(this).attr('examid');
		}
	});
}

function initSbrfSelector() {
	$('#sbrf_selector #credit_select, #sbrf_selector #credit_select a').click(function() {
		if($('#credit_list:visible', $(this).parents('#sbrf_selector:eq(0)')).length) {
			$('#credit_list', $(this).parents('#sbrf_selector:eq(0)')).hide();
		} else {
			$('#credit_list', $(this).parents('#sbrf_selector:eq(0)')).show();
		}
		return false;
	});
}

function initLoginForm() {
	
	if($.browser.msie) {
		loginFormObj = $('#login_form').clone();
		$('#login_form').remove();
		$('#top').after(loginFormObj);
	}
	
	$('#top_wrapper div.right a:eq(1)').unbind('click').click(function() {
		if($(this).hasClass('blue')) return true;
		if($('#login_form:visible').length) closeLoginForm();
		else $('#login_form').show();
		return false;
	});
	
	$('#login_form #login p:eq(1) a').unbind('click').click(function() {
		obj = $(this).parents('#login:eq(0)');
		obj.hide();
		obj.next().show();
		return false;
	});
	
	$('#login_form #login a:last, #login_form #remember a:last').unbind('click').click(function() {
		$(this).parents('form:eq(0)').submit();
		return false;
	});
	
	$('#login_form input[name=password]').hide();
	$('#login_form input[name=psw][class=hidden]').show();
	
	$('#login_form input').focus(function() { fill($(this)); });
	$('#login_form input').blur(function() { fill($(this)); });
	
	$('#login_form input[name=psw]').focus(function() {
		$(this).hide();
		$('#login_form input[name=password]').show().focus();
	});
	$('#login_form input[name=password]').blur(function() {
		if($(this).val() == '') {
			$(this).hide();
			$('#login_form input[name=psw]').show();
		}
	});
}

function closeLoginForm() {
	$('#login_form, #login_form div').hide();
	$('#login_form #login').show();
	$('#login_form #login p.red:last').hide();
	$('#login_form #remember p:last.red').hide();
}

function initSearchModel() {
	$('#search_part a:first').unbind('click').click(function() {
		$('#search_part form').submit();
		return false;
	});
	$('#search_part form').unbind('submit').submit(function() {
		if(!$('#search_part input').val()) {
			$('#search_part input').addClass('error');
			setTimeout("$('#search_part input').removeClass('error')", 2000);
		} else {
			$.get("/catalog/search", { q: $('#search_part input').val() }, function(data) {
				models = data.split("\r\n");

				// alert(models);
				for(i=0; i<models.length; i++) {
					if(models[i] == $('#search_part input').val())
						$('#search_part form').unbind('submit').submit();
						return true;
				}
				
				$('#search_part input').addClass('error');
				setTimeout("$('#search_part input').removeClass('error')", 2000);
				// if(models.length == 2) $('#search_part form').unbind('submit').submit();
				// else {
					// $('#search_part input').addClass('error');
					// setTimeout("$('#search_part input').removeClass('error')", 2000);
				// }
			});
		}
		return false;
	});
}

var loginVal = "e-mail / телефон";
var mailVal = "e-mail";
var brandGifts = "";
var randomGifts = "";

function fill(obj) {
	if(obj.attr('name') == 'login') {
		if(obj.val() == '') obj.val(loginVal);
		else if(obj.val() == loginVal) obj.val('');
	}
	if(obj.attr('name') == 'mail') {
		if(obj.val() == '') obj.val(mailVal);
		else if(obj.val() == mailVal) obj.val('');
	}
}

function showMainPagePrizes() {
	$.get('/frontcache/randomgifts.html', null, function(data) {
		randomGifts = data.split('@@');
		setTimeout("showMainPagePrize(randomGifts)", 3000);
	});
}

function showMainPagePrizers() {
	$.get('/frontcache/randomprizers.html', null, function(data) {
		randomPrizers = data.split('@@');
		setTimeout("showMainPagePrizer(randomPrizers)", 5000);
	});
}

// function showMainPagePrize(randomGifts) {
	// rand_no = Math.ceil(Math.random() * randomGifts.length)-1;
	// $('p', $('#mainpage_menu table td').eq(2)).html(randomGifts[rand_no]);
	// setTimeout("showMainPagePrize(randomGifts)", 3000);
// }

// function showMainPagePrizer(randomPrizers) {
	// rand_no = Math.ceil(Math.random() * randomPrizers.length)-1;
	// $('span', $('#mainpage_menu table td').eq(3)).html(randomPrizers[rand_no]);
	// setTimeout("showMainPagePrizer(randomPrizers)", 5000);
// }

function initPopup() {
	$('fieldset#grandprix div#velo a').click(function(e) {
		box = $('fieldset#grandprix div#popupBox');
		boxText = $('#popupBoxMSG', box);
		txt = "<br/><p>Велосипед в комплектацию Главного приза, увы, не входит, но выиграть его, между тем, реально.</p><br/><p>Смотрите ниже!</p><br/>";
		boxText.html(txt);
		
		lft = e.pageX - 80;
		tp = e.pageY - 180;
		box.css({ left: lft, top: tp });
		$('input', box).show();
		
		box.jqm().jqDrag('#popupBoxTL');
		box.jqmShow().show();
		
		return false;
	});
}

function initBanners() {
	$('div[id*=banner] a').each(function() {
		w = $(this).parent().attr('width');
		h = $(this).parent().attr('height');
		
		if(w == undefined) w = '100%';
		if(h == undefined) h = "100%";
		
		if( $(this).parent().attr('bgcolor') != "" ) $(this).parent().css('background-color', $(this).parent().attr('bgcolor'));
		
		if($(this).attr('flash') != "") {
			var so = new SWFObject($(this).attr('flash'), "swfbanner", w, h, "6");
			so.addParam('wmode', 'transparent');
			so.write($(this).parents('div').attr('id'));
		}
	});
}

function hasFlash() {
	var UseFlash = 0;
	if (navigator.mimeTypes != undefined && navigator.mimeTypes["application/x-shockwave-flash"] != undefined ) {
		var plugin = navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin;
		if (plugin && parseInt(plugin.description.substring(plugin.description.indexOf(".")-2))>=5)
			UseFlash = 1;
	} else {
		try{
			var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			for (var i=3; axo!=null; i++) {
				axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
			}
		} catch(e) {}
		if(axo) UseFlash = 1;
	}
	return UseFlash;
}

function initFlapperFlash() {
	var so = new SWFObject("data/flapper.swf", "gpFlash", "335", "150", "9");
	so.addParam('wmode', 'transparent');
	so.addParam('FlashVars', 'linkURL=/prizes/');
	so.addVariable('width', '335');
	so.addVariable('height', '150');
	so.write("flapper");
	return false;
}

function initTopFlash() {
	// if(hasFlash())
		/*
	bnrName = "data/showRoom.swf";

	var so = new SWFObject(bnrName, "gpFlash", "505", "235", "9");
	so.addVariable('loadfrom', '/img/' + bnrName);
	so.addParam('wmode', 'opaque');
	so.addParam('FlashVars', 'xmlFile=data/car003.xml');
	so.addVariable('width', '505');
	so.addVariable('height', '235');
	so.write("gp");*/
	return false;
}

function initSelector() {
	bnrName = "img/selector.swf";
	var so = new SWFObject(bnrName, "gpFlash", "1000", "90", "9");
	so.addParam('wmode', 'opaque');
	so.addVariable('width', '1000');
	so.addVariable('height', '90');
	so.write("selector");
	return false;
}

var lockRandom = false;

function initArrows() {
	//$('#arrows img.bottom').show();
	$('#arrows .bottom img, #arrows .top img').click(function() { lockRandom=true; showModelTopBlock(true, $(this).parent().hasClass('bottom')); });
	setTimeout("showModelTopBlock(false, 0)", 2000);
}

function showModelTopBlock(isClick, moveToBottom) {
	if(lockRandom && !isClick) return false;
	
	currentObj = $('#maincontent fieldset table.topmodels:visible');
	if(isClick && moveToBottom) nextObj = currentObj.next();
	else if(isClick && !moveToBottom) nextObj = currentObj.prev();
	else {
		blockNum = $('#maincontent fieldset table.topmodels').length;
		mTo = Math.ceil(Math.random() * blockNum)-1;
		nextObj = $('#maincontent fieldset table.topmodels').eq(mTo);
	}
	if(!nextObj.hasClass('topmodels') && moveToBottom) nextObj = $('#maincontent fieldset table.topmodels').eq(0);
	else if(!nextObj.hasClass('topmodels') && !moveToBottom) nextObj = $('#maincontent fieldset table.topmodels:last');
	nextObj.fadeIn('slow');
	if(currentObj.text() != nextObj.text()) currentObj.hide();
	
	if(!lockRandom) setTimeout("showModelTopBlock(false, 0)", 3000);
}

function initClassList() {
	$("#mycar li").mouseover(function() {
		$(this).addClass('active');
	});
	
	$("#mycar li").mouseout(function() {
		if(!$('a', $(this)).hasClass('active')) $(this).removeClass('active');
	});
}

function showSubmitButtons() {
	$("#org span").show().hover(function() { $(this).css('text-decoration', 'none'); }, function() { $(this).css('text-decoration', 'underline'); });
	$("#org span").click(function(e) {
		formObj = $(this).parents('form');
		if($(this).parents('#right').length > 0) {
			box = $('#right div#popupBox');
			boxText = $('#popupBoxMSG', box);
			boxText.html(CONFIRM_CHOICE);

			lft = -280;
			tp = e.pageY - 450;
			box.css({ left: lft, top: tp });
			$('tr:first td:last, #popupBoxMSG tr:last td:last', box).css('border', '0px');
			$('input.jqmSubmit', box).click(function() { submitForm(formObj); });
			
			box.jqm().jqDrag('#popupBoxTL');
			box.jqmShow().show();
			return false;
		}
		if(!checkRegistrationForm(formObj)) return false;
		formObj.submit();
		formObj.submit(function() { return false; });
	});
	
	$("#mycar p span").show();
	$("#mycar p span").click(function(e) { showPopup(e); });
	$("#mycar p input[type=checkbox]").click(function(e) { showPopup(e); return false; });
}

function checkRegistrationForm(formObj) {
	
	$('td.error p', formObj).remove();
	$('td.checkbox span.error', formObj).remove();
	$('td.error').removeClass('error');
	
	fl = true;
	$('input', formObj).each(function() {
		field_name = $(this).prevAll("label:eq(0)").text();

		msg = '';
		var mail_checking_regexp = /^([a-z\d]([a-z\d\_\-]*)?([\.][a-z\d]([a-z\d\_\-]*)?)*)(\@)([a-z\d]([a-z\d\_\-]*[a-z\d])?([\.][a-z\d]([a-z\d\_\-]*[a-z\d])?)*[\.][a-z]{2,4})$/i;
	
		if( $(this).hasClass('required') && $(this).attr('type') != 'checkbox' && $(this).val() == '' ) {
			msg = '<p>Поле "' + ((pos = field_name.indexOf('*')) ? field_name.substring(0, pos) : field_name) + '" не должно быть пустым</p>';
		} else if( $(this).hasClass('email') && !mail_checking_regexp.test($(this).val()) )
			msg = '<p>Поле "' + ((pos = field_name.indexOf('*')) ? field_name.substring(0, pos) : field_name) + '" неправильного формата</p>';
		else if( $(this).hasClass('pass') && $(this).val().length < 6 && !$(this).parents('form[name=changeForm]').length )
			msg = '<p>' + ((pos = field_name.indexOf('*')) ? field_name.substring(0, pos) : field_name) + ' должен быть не меньше 6 символов</p>';
		else if( $(this).hasClass('code') ) {
			if($(this).val().length > 6) msg = '<p>"Код города" должен быть не больше 4 цифр</p>';
			if($(this).val().length < 2) msg = '<p>"Код города" должен быть не меньше 2 цифр</p>';
			if( /[^\d]/.test($(this).val()) ) msg = '<p>"Код города" должен содержать только цифры</p>';
		} else if( $(this).hasClass('phone') ) {
			if($(this).val().length > 7) msg = '<p>"Номер телефона" должен быть не больше 7 цифр</p>';
			if($(this).val().length < 4) msg = '<p>"Номер телефона" должен быть не меньше 4 цифр</p>';
			if( /[^\d]/.test($(this).val()) ) msg = '<p>"Номер телефона" должен содержать только цифры</p>';
		}
		
		if(msg) {
			$(this).parents('td').eq(0).addClass('error').append(msg);
			//$(this).parents('td').eq(0).addClass('error');
			$(this).focus();
			fl = false;
			return false;
		}
		
		if( $(this).hasClass('required') && $(this).attr('type') == 'checkbox' && !$(this).attr('checked') ) {
			msg = '<p class="error">Для участия в конкурсе Вы должны согласиться с его <a href="/rules/">правилами</a><br/><br/></p>';
			$(this).before(msg);
			$(this).focus();
			fl = false;
			return false;
		}
	});
	
	return fl;
}

function showPopup(e) {
	formObj = $('form:last');
		
	currentAutoId = $('#mycar li a.active').attr('realid');
	currentModelName = $('#mycar li a.active').text();
	currentClassName = $('#auto .open div:first').text();
	thisPage = $('#mycar li a.active').attr('href');

	lft = e.pageX - 0;
	tp = e.pageY - 0;
	$('#popupBox').css({ left: 30, top: 340 });
	
	if(parseInt(auth) > 0) {
		if(parseInt(model) > 0 && currentAutoId != parseInt(model)) {
			text = CHANGE_CHOICE.replace(/%auto%/, model_name).replace(/%class%/, currentClassName);
		} else if(parseInt(model) > 0) submitForm(formObj);
		else if(!model) text = MAKE_CHOICE.replace(/%class%/, currentClassName).replace(/%auto%/, currentModelName).replace(/%thispage%/, thisPage);
		
	} else {
		text = NEED_REGISTRATION;
	}
	$('#popupBoxMSG').html(text);
	
	$('#popupBoxMSG tr:first td:last, #popupBoxMSG tr:last td:last').css('border', '0px');
	
	$('#popupBoxMSG input.jqmSubmit').click(function() { submitForm(formObj); });
	$('#popupBoxMSG input.jqmClick').click(function() {
		$('input[name=redirect]', formObj).val($(this).attr('href'));
		submitForm(formObj);
	});
	$('#popupBoxMSG input.jqmClose').click(function() { $('#popupBox').jqmHide(); });
	
	$('#popupBox').jqm({ modal:true }).jqDrag('#popupBoxTL');
	$('#popupBox').jqmShow().show();
}

function submitForm(formObj) {
	$("#mycar p input[type=checkbox]").attr('checked', 'true');
	setTimeout("formObj.submit()", 100);
}

function initImgList() {
	initListPaging();
	
	$('#model #nextpict').show();
		
	$("#model #nextpict a").click(function() {
		mainImg = $('#model img#largeImg');
		if(mainImg.attr('src') == $(this).attr('src')) return false;
		
		// if($('#model img[src=' + $(this).attr('src') + ']').length > 0) {
			// mainImg.hide();
			// $('#model img[src=' + $(this).attr('src') + ']').show();
		// } else {
			// newImg = mainImg.clone();
			// newImg.attr('src', $(this).attr('src'));
			// mainImg.after(newImg);
			// mainImg.hide();
		// }
		mainImg.attr('src', $(this).attr('src'));
		
		$('a[class*=rel]', $(this).parent()).removeClass('rel');
		$(this).addClass('rel');
		
		return false;
	});
}

function initListPaging() {
	currentPos = $('#mycar li[class=active]').offset().top - $('#mycar').offset().top;
	currentPage = Math.ceil(currentPos/235);
	if(!currentPos) currentPage=1;
	$('#mycar #ul').animate({scrollTop: (currentPage-1)*240 }, 500);
	
	out = "";
	page_num = Math.ceil($('#mycar ul').height()/240);
	if(page_num > 1) {
		for(i=1; i<=page_num; i++) {
			if(i == currentPage) out += '<a href="" to="'+i+'" class="noactive">'+i+'</a>';
			else out += '<a href="" to="'+i+'">'+i+'</a>';
			
			if(i != page_num) out += " | ";
		}
	}
	$('#mycar .count').html(out);
	
	$('#mycar .count a[to]').click(function() {
		if($(this).hasClass('noactive')) return false;
		
		scroll_to = ($(this).attr('to')-1) * 240;
		$('#mycar #ul').animate({scrollTop: scroll_to}, 500);
		$('a[to]', $(this).parent()).removeClass('noactive');
		$(this).addClass('noactive');
		
		return false;
	});
}

function in_array(arr, str) {
	for(i=0; i<arr.length; i++) {
		if(arr[i] == str) return true;
	}
	return false;
}

function getGiftIndexById(str, arr) {
	if(arr.length) {
		for(i=0; i<arr.length; i++) {
			if(arr[i][0] == str) return i;
		}
	}
}

var blockBrandGiftChange = false;

function changeNoBrandGift(obj, clicked) {
	if(blockBrandGiftChange && !clicked) return false;
	
	curImg = $('#brandgift #foto img[order]:visible');
	curOrder = curImg.attr('order');
	curImg.hide();
	if(obj.parent().hasClass('left')) {
		curOrder--; if(curOrder < 1) curOrder = imgNum;
	}
	if(obj.parent().hasClass('right')) {
		curOrder++; if(curOrder > imgNum) curOrder = 1;
	}
	$('#brandgift #foto img[order='+curOrder+']').show();

	if(!blockBrandGiftChange) setTimeout("changeNoBrandGift( $('#brandgift #foto div.right a'), 0)", 3000);
}

function initBrandGift() {
	if( parseInt($('#brandgift').attr('total')) > 1 || $('#brandgift').hasClass('no')) $('#brandgift #foto div[class]').show();

	if($('#brandgift').hasClass('no')) {
		imgNum = $('#brandgift #foto img[order]').hide().length;
		rand_no = Math.ceil(Math.random()*imgNum);
		$('#brandgift #foto img[order='+rand_no+']').show();
		
		$('#brandgift #foto div[class] a').click(function() {
			blockBrandGiftChange = true;
			changeNoBrandGift($(this), 1);
			return false;
		});
		
		changeNoBrandGift( $('#brandgift #foto div.right a'), 0);
		return;
	}

	if( $('#brandgift #foto div[class] a').length > 0 ) {
		$.get('/frontcache/prizes.html', null, function(data) {
			var gifts = data.split('@@');
			
			lm = $('#brandgift #foto').attr('lm');
			if(lm == undefined) lm = "";
			
			for(i=0; i<gifts.length; i++) {
				flds = gifts[i].split('%%');
				if(lm != '' && lm != flds[5].toLowerCase()) continue;
				cachedBrandGifts[cachedBrandGifts.length] = flds;
			}
			
			setTimeout("clickToRightArrow()", 3000);
		});
	}

	$('#brandgift #foto div[class] a').click(function() {
		$('#brandgift').attr('clicked', '1');
		changeBrandGift($(this));
		return false;
	});
	
	$('#brandgift #foto img:first').unbind('click').click(function(e) {
		goToExam($(this), e);
		return false;
	});
	
	$('#right2 .box form select').change(function() {
		if(!parseInt($(this).val())) return false;
		$(this).parents('form').submit();
	});
	
}

function clickToRightArrow() {
	if(!$('#brandgift[clicked]').length) {
		changeBrandGift($('#brandgift #foto div[class=right] a'));
		setTimeout("clickToRightArrow()", 3000);
	}
}

function changeBrandGift(obj) {
	// alert(cachedBrandGifts.length);
	// alert(cachedBrandGifts[0]);
	realid = $('#brandgift #foto').attr('realid');
	cIndex = getGiftIndexById(realid, cachedBrandGifts);
	
	if(obj.parent().attr('class') == 'left') {
		cIndex--;
		if(cIndex < 0) cIndex = cachedBrandGifts.length-1;
	} else if(obj.parent().attr('class') == 'right') {
		cIndex++;
		if(cIndex > cachedBrandGifts.length-1) cIndex = 0;
	}
	if(cIndex == undefined) cIndex = 0;
	gift = cachedBrandGifts[cIndex];

	questions = gift[6].split('$$');
	rand_no = Math.ceil(Math.random() * questions.length) - 1;

	//alert(questions[rand_no]);
	$('#brandgift .blue div:first').html( "<p><span>"+questions[rand_no].replace(/\[br\]/i, "</span></p><p><span>")+"</span></p>" );
	$('#brandgift #foto').attr('realid', gift[0]);
	$('#brandgift #foto img:first').attr('src', gift[2]).attr('alt', gift[1]).attr('title', gift[1]);
	
	$('#brandgift #foto img:first').unbind('click').click(function(e) {
		goToExam($(this), e);
		return false;
	});
	
	// $('#brandgift #foto div:eq(1) strong').text(gift[1]);
	// $('#brandgift #foto div:eq(1) span').text('');

	$('#brandgift img:last').attr('src', gift[4]).attr('alt', gift[5]);
	
	logo_link = gift[3].replace("<br/>", "");
	$('#brandgift a:eq(3)').attr('href', 'http://' + logo_link).html(gift[3]);
	$('#brandgift a:eq(2)').attr('href', 'http://' + logo_link).attr('src', gift[4]);
}

function goToExam(obj, e) {
	if($('#top #top_wrapper form').length) {
		lft = e.pageX - 350;
		tp = e.pageY - 120;
		
		$('#popupBox').css({ left: lft, top: tp });
		txt = '<p><strong>Экзамен проводится в Личном кабинете. Зарегистрируйтесь или авторизуйтесь в верхней панели.<br/>И... удачи!</strong></p>';
		txt += '<p>Зарегистрироваться?</p><input type="button" value="Да" class="jqmClick" href="/rules/registration/" />';
		$('#popupBoxMSG').html(txt);
		
		$('#popupBoxMSG input.jqmClick').click(function() {
			location.href = $(this).attr('href');
		});
		
		$('#popupBox input').show();
		$('#popupBox').jqm().jqDrag('#popupBoxTL');
		$('#popupBox').jqmShow().show();
		return false;
	}
	
	if(parseInt(obj.parent().attr('realid')) > 0) location.href = "/cabinet/exam/?" + obj.parent().attr('realid');
	else location.href = "/cabinet/exam/";
}

function initGiftList() {
	$('#gifts #foto div[class] a').show();

	$.get('/frontcache/allprizes.html', null, function(data) {
		var gifts = data.split("@@");
		for(i=0; i<gifts.length; i++) {
			cachedGifts[cachedGifts.length] = gifts[i].split('%%');
		}
		setTimeout("clickToRightArrow_allGifts()", 3000);
	});
	$('#gifts #foto div[class] a').click(function() {
		$('#gifts').attr('clicked', '1');
		changeGift($(this));
		return false;
	});
}
function clickToRightArrow_allGifts() {
	if(!$('#gifts[clicked]').length) {
		changeGift($('#gifts #foto div[class=right] a'));
		setTimeout("clickToRightArrow_allGifts()", 3000);
	}
}

function changeGift(obj) {
	realid = $('#gifts #foto').attr('realid');
	cIndex = getGiftIndexById(realid, cachedGifts);
	
	if(obj.parent().attr('class') == 'left') {
		cIndex--;
		if(cIndex < 0) cIndex = cachedGifts.length-1;
	} else if(obj.parent().attr('class') == 'right') {
		cIndex++;
		if(cIndex > cachedGifts.length-1) cIndex = 0;
	}
	if(cIndex == undefined) cIndex = 0;
	gift = cachedGifts[cIndex];

	// $('#gifts #foto').attr('realid', gift[0]);
	// $('#gifts #foto a:eq(0)').attr('title', gift[1]);
	// $('#gifts #foto img').attr('src', gift[2]).attr('alt', gift[1]);
	// $('#gifts #foto div:eq(1)').text(gift[1]);
}

function showCalendar() {
		$('div[month] div[class] a').click(function() {
			cls = $(this).parent().attr('class');
			month = $(this).parents('#calendar').attr('month');
			
			newmonth = '';
			if(cls == 'left') {
				if(month == 'jan') newmonth = 'dec';
				else if(month == 'feb') newmonth = 'jan';
			} else if(cls == 'right') {
				if(month == 'jan') newmonth = 'feb';
				else if(month == 'dec') newmonth = 'jan';
			}
			
			$('div[month=' + month + ']').hide();
			$('div[month=' + newmonth + ']').show();
			
			return false;
		});
}

function catalogListActions() {
	$("#auto .open a").click(function() {
		prnt = $(this).parents('.open');
		loadBlock = prnt.next();
		realid = $(this).attr('realid');
		
		if(loadBlock.text() == "") {
			if(prnt.hasClass('brand')) {
				$.get("/catalog/brand-list/", { bid: realid }, function(data) {
					loadBlock.html(data);
					loadBlock.slideToggle(500);
				});
			} else if(prnt.hasClass('prizer')) {
				$.get("/prizers/prizer-list/", { tid: realid }, function(data) {
					loadBlock.html(data);
					loadBlock.slideToggle(500);
					initBigPrizers();
				});
			} else {
				$.get("/catalog/class-list/", { id: realid }, function(data) {
					loadBlock.html(data);
					loadBlock.slideToggle(500);
				});
			}
		} else loadBlock.slideToggle(500);

		if($(this).hasClass('active')) $(this).removeClass('active');
		else $(this).addClass('active');
		
		return false;
	});
}

function initBigPrizes() {
	$('td.gift-foto img').mousemove(function(e) {
		lft = e.pageX - ($('#top').width()-$('#outer').width())/2 + 10;
		tp = e.pageY - 230;
		$('#tooltip img').attr('src', $(this).attr('bigimg'));
		txt = $('td', $(this).parent().parent()).eq(2).html();

		$('#tooltip #img p').html(txt);
		$('#tooltip').css('top', tp).css('left', lft).show();
	});
	$('td.gift-foto img').mouseout(function() {
		$('#tooltip').hide();
	});
}

function initImgBlock() {
	defaultElem = $('p.foto a[href=' + $('p.foto img:first').attr('src') + ']');
	if(defaultElem.length > 0) makeNoActive(defaultElem);
	
	$('p.foto a[href*=tube]').click(function() {
		showBlockVideo($(this));
		return false;
	});
	
	$('p.foto a[href*=narod.tv]').click(function() {
		showBlockVideo2($(this));
		return false;
	});
	
	$('p.foto a[href*=.jpg]').click(function() {
		showBlockImg($(this));
		return false;
	});
}

function showBlockImg(obj) {
	path = obj.attr('href');
	imgObj = '<img src="' + path + '" width="380" height="245" alt="" />';
	$('img:first, object:first, embed:first', obj.parents('p.foto')).remove();
	obj.parents('p.foto').prepend(imgObj);

	makeNoActive(obj);
}

function showBlockVideo(obj) {
	path = obj.attr('href');
	videoObj = '<OBJECT width="380" height="245"><PARAM name="movie" value="' + path + '"></PARAM><PARAM name="wmode" value="window"></PARAM><PARAM name="allowFullScreen" value="true"></PARAM><EMBED src="' + path + '" type="application/x-shockwave-flash" wmode="window" width="380" height="245" allowFullScreen="true" ></EMBED></OBJECT>';
	$('img:first, object:first, embed:first', obj.parents('p.foto')).remove();
	obj.parents('p.foto').prepend(videoObj);

	makeNoActive(obj);
}

function showBlockVideo2(obj) {
	path = obj.attr('href');
	videoObj = '<embed type="application/x-shockwave-flash" src="' + path + '" width="380" height="245" id="narodtv" name="narodtv" quality="high" allowfullscreen="true" allowscriptaccess="always" flashvars=""></embed>';
	$('img:first, object:first, embed:first', obj.parents('p.foto')).remove();
	obj.parents('p.foto').prepend(videoObj);

	makeNoActive(obj);
}

function makeNoActive(obj) {
	actElem = $('p.foto a[class=red]');
	actElem.attr('href', actElem.attr('rel'));
	actElem.removeClass('red');
	
	if( /tube/.test(actElem.attr('href')) ) actElem.click(function() { showBlockVideo($(this)); return false; });
	else if( /narod\.tv/.test(actElem.attr('href')) ) actElem.click(function() { showBlockVideo2($(this)); return false; });
	else if( /jpg$/.test(actElem.attr('href')) ) actElem.click(function() { showBlockImg($(this)); return false; });
	
	obj.attr('rel', obj.attr('href'));
	obj.removeAttr('href');
	obj.addClass('red');
	obj.unbind('click');
}

function initBigPrizers() {
	$('div.our td img', $('div.prizer').parents('#auto')).mousemove(function(e) {
		delta = Math.ceil(($('#top').width()-$('#center').width())/2);
		lft = e.pageX + 10 - delta;
		tp = e.pageY - 200;
		
		if(/msie/.test(navigator.userAgent.toLowerCase()) && $('#right').offset().left < e.pageX+$('#tooltip').width()) 
			lft = e.pageX - delta - (e.pageX+$('#tooltip').width()-$('#right').offset().left);
		
		$('#tooltip img').attr('src', $(this).attr('bigimg'));
		txt = $('div', $(this).parent()).html();

		$('#tooltip #img p').html(txt);
		$('#tooltip').css('top', tp).css('left', lft).show();
	});
	$('div.our td img', $('div.prizer').parents('#auto')).mouseout(function() {
		$('#tooltip').hide();
	});
}

function initElseButton() {
	$('#ars_wrap .userbars p.left').show();
	$('#ars_wrap .userbars p.left a').click(function() {
		$.get('/cabinet/mychoice/arsenal-list', { bid: $(this).attr('realid') }, function(data) {
			dt = $(data);
			$('.ars_row, p', dt).hide();
			$('.ars_row:last').after( $('div:first', dt).html() );
			$('.userbars p:last').after( $('div:last', dt).html() );
			$('.ars_row:hidden, p:hidden').show('slow');
		});
		$(this).hide();
		return false;
	});
}

var css_browser_selector = function() {var ua=navigator.userAgent.toLowerCase(),is=function(t){return ua.indexOf(t) != -1;},h=document.getElementsByTagName('html')[0],b=(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?'gecko ff2':is('firefox/3')?'gecko ff3':is('gecko/')?'gecko':is('opera/9')?'opera opera9':/opera\s(\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('chrome')?'chrome webkit safari':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';var c=b+os+' js'; h.className += h.className?' '+c:c;}();