function positionGirl() {
	if (!/msie|MSIE 6/.test(navigator.userAgent)) {
		document.getElementById("girl").style.width = (document.body.clientWidth - 1200) / 2 + 380 + 'px';
	}
	document.getElementById("arrow-left-gubki").style.left = (document.body.clientWidth - 1200) / 2 + 320 + 'px';
	document.getElementById("arrow-left-vote").style.left = (document.body.clientWidth - 1200) / 2 + 360 + 'px';
}

var swfu;
var skiesPosition = 0;
var innerPage = null;
var currentPage = 'index';
var movingSkies = null;
var curGubka = 1;
var code = null;
var name = null;
var city = null;
var phone = null;
var email = null;
var announceByEmail = null;
var announceByPhone = null;
var address = null;
var accepted = null;
var agreedForPresent = null;
var hash = null;
var currentRegistrationPage = 'registration';
var curRules = 1;
var userpic;
var story = null;
var positions = {
    'registration': 240,
    'registration-1500-question': 240,
    'registration-100': 240,
    'competition': 352,
    'competition-main': 352,
    'thanks-competition': 352,
    'rules': 428,
    'prizes': 540,
    'two-weeks': 540,
    'kinokarta': 540,
    'watch': 690,
    'about-sb': 840,
	'winner': 240
};
var xrexf5RTx = false;
var currentStory = -1;

var vStoryID = null;
var competitionStories = null;

function moveSkies() {
	if (skiesPosition < -2164)
		skiesPosition = 0;
	skiesPosition--;
	innerPage.style.backgroundPosition = skiesPosition + 'px 0px';
}

function showCardInfo() {
	if ($('#kinokarta-popup').css('display') == 'none') {
		$('#kinokarta-popup').fadeIn();
	}
}

function hideCardInfo() {
	if ($('#kinokarta-popup').css('display') != 'none') {
		$('#kinokarta-popup').fadeOut();
	}
}

function showOstrovInfo() {
	if ($('#ostrov-popup').css('display') == 'none') {
		$('#ostrov-popup').fadeIn();
	}
}

function showPopup(id) {
	if ($('#' + id).css('display') == 'none') {
		$('#' + id).fadeIn();
	}
}

function hideShopsInfo() {
	if ($('#shops-moscow').css('display') != 'none') {
		$('#shops-moscow').fadeOut();
	}
	if ($('#shops-stp').css('display') != 'none') {
		$('#shops-stp').fadeOut();
	}
}
function hideOstrovInfo() {
	if ($('#ostrov-popup').css('display') != 'none') {
		$('#ostrov-popup').fadeOut();
	}
}

function showTheatresInfo() {
	if ($('#theatres-popup').css('display') == 'none') {
		$('#theatres-popup').fadeIn();
	}
}

function hideTheatresInfo() {
	if ($('#theatres-popup').css('display') != 'none') {
		$('#theatres-popup').fadeOut();
	}
}

function openPage(id) {
	if (id == 'registration')
		id = currentRegistrationPage;

	if (currentPage == id)
		return;
        
    $('#current-part').css('left', positions[id] + 'px');
    
    if (id != 'index' && id != 'shops')
        $('#current-part').css('display', 'block');
    else
        $('#current-part').css('display', 'none');
        
	if (currentPage == 'about-sb') {
		$('#arrow-left-gubki').fadeOut();
	}
	
	if (id == 'about-sb') {
		$('#arrow-left-gubki').fadeIn();
	}
	
	if (id == 'vote') {
		$('#arrow-left-vote').fadeIn();
	}
	
	if (currentPage == 'vote') {
		$('#arrow-left-vote').fadeOut();
	}
	
	hideCardInfo();
	hideOstrovInfo();
	hideShopsInfo();
	hideTheatresInfo();
	
	$('#' + currentPage).fadeOut();
	currentPage = id;
	$('#' + currentPage).fadeIn();
}

function gubkiRight() {
	if (curGubka < 3)
		curGubka++;
	
	$('#slider').animate({
		left: -(curGubka - 1) * 730
	}, 800, 'easeOutQuint');
}

function gubkiLeft() {
	if (curGubka > 1)
		curGubka--;
	
	$('#slider').animate({
		left: -(curGubka - 1) * 730
	}, 800, 'easeOutQuint');
}

function onLoad() {
	loadNewStory();
	$('#index-links a').click(function() {
		$('#index-links a').removeClass('active');
		$('#inner-links a').removeClass('active');
		$(this).addClass('active');
		openPage($(this).attr('href').substring(1));
		window.location = $(this).attr('href');
	});
	
	$('#inner-links a').click(function() {
		$('#index-links a').removeClass('active');
		$('#inner-links a').removeClass('active');
		$(this).addClass('active');
		openPage($(this).attr('href').substring(1));
		window.location = $(this).attr('href');
	});
	
	innerPage = document.getElementById('innerPage');
	movingSkies = setInterval('moveSkies()', 100);
	
/*	$('#code').bind('keyup', function() { checkCode(); } );
	$('#code').bind('keypress', function() { checkCode(); } );
	*/
	$('.city-option').click(function(){
		$('#personCity').val($(this).html());
		toggleCities();
	});
	
	initializeUploader();
	
	var windowHash = window.location.hash;
	
	if (windowHash.substring(1, 6) == 'shops') {
		openPage('shops');
	}
	
	if (windowHash.substring(1, 7) == 'prizes') {
		openPage('prizes');
	}
	
	if (windowHash.substring(1, 13) == 'participant=') {
		hash = windowHash.substring(13);
		
		$.post('getstory.php', {'hash':hash}, function(data) {
			if (data.status == 'completed') {
				openPage('thanks-competition');
				return;
			} else if (data.status == 'ok') {
				procedeToCompetition();
				return;
			}
			hash = null;
		}, 'json');
	}
	
	if (!/msie|MSIE 6/.test(navigator.userAgent)) {
		supersleight.init();
	}
	
	if (!/msie|MSIE 6/.test(navigator.userAgent)) {
		document.getElementById("girl").style.width = (document.body.clientWidth - 1200) / 2 + 380 + 'px';
	}
	document.getElementById("arrow-left-gubki").style.left = (document.body.clientWidth - 1200) / 2 + 320 + 'px';
	document.getElementById("arrow-left-vote").style.left = (document.body.clientWidth - 1200) / 2 + 360 + 'px';
	$('#girl').fadeIn();
}

function initializeUploader() {
	$('.swfupload-control').swfupload({
        // Backend Settings
        upload_url: "upload.php",    // Relative to the SWF file (or you can use absolute paths)
        
        // File Upload Settings
        file_size_limit : "2048", // 100MB
        file_types : "*.jpg",
        file_types_description : "All Files",
        file_upload_limit : "1",
        file_queue_limit : "0",
    	
        // Button Settings
        button_image_url : "images/choose.gif", // Relative to the SWF file
        button_placeholder_id : "spanButtonPlaceholder",
        button_width: 74,
        button_height: 20,
        
        // Flash Settings
        flash_url : "swfupload.swf"
    });
    
	$('.swfupload-control').swfupload({
			upload_url: "upload.php",
			file_size_limit : "10240",
			file_types : "*.*",
			file_types_description : "All Files",
			file_upload_limit : "0",
	        flash_url : "swfupload.swf",
	        button_image_url : "images/choose.gif", // Relative to the SWF file
	        button_width: 74,
	        button_height: 20,
			button_placeholder: "spanButtonPlaceholder",
			button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			debug: true
		})
			.bind('swfuploadLoaded', function(event){
				//console.log('<li>Loaded</li>');
			})
			.bind('fileQueued', function(event, file){
				//console.log('<li>File queued - '+file.name+'</li>');
				// start the upload since it's queued
				$(this).swfupload('startUpload');
			})
			.bind('fileQueueError', function(event, file, errorCode, message){
				//console.log('<li>File queue error - '+message+'</li>');
			})
			.bind('fileDialogStart', function(event){
				//console.log('<li>File dialog start</li>');
			})
			.bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){
				//console.log('<li>File dialog complete</li>');
			})
			.bind('uploadStart', function(event, file){
				//console.log('<li>Upload start - '+file.name+'</li>');
			})
			.bind('uploadProgress', function(event, file, bytesLoaded){
				//console.log('<li>Upload progress - '+bytesLoaded+'</li>');
			})
			.bind('uploadSuccess', function(event, file, serverData){
				//console.log('<li>Upload success - '+file.name+'</li>');
				
			})
			.bind('uploadComplete', function(event, file){
				//console.log('<li>Upload complete - '+file.name+'</li>');
				userpic = file.name;
				$('#user-photo').html('<img src="uploads/'+file.name+'" height="30">');
				// upload has completed, lets try the next one in the queue
				//$(this).swfupload('startUpload');
			})
			.bind('uploadError', function(event, file, errorCode, message){
				//console.log('<li>Upload error - '+message+'</li>');
			});
}
var prevCode = 0;
function checkCode() {
	if ($('#cities').css('display') != 'none') {
		toggleCities();
	}
	
	code = $('#code').val();
	if (code.length == 10 && prevCode != code) {
		$('#more-form').fadeOut();
		prevCode = code;
		$('#code-status').attr('src', 'images/ball-rotating.gif');
		$.post('check.php', {'code':code}, function(data) {
			if (data.status != 'correct') {
				$('#code-status').attr('src', 'images/code-no.gif');
			} else {
				$('#code-status').attr('src', 'images/code-yes.gif');
				$('#more-form').fadeIn();
			}
		}, 'json');
	} else if (prevCode != code) {
		$('#more-form').fadeOut();
		$('#code-status').attr('src', 'images/ball-still.gif');
	}
	
	prevCode = code;
}

function isEmailValid(email) {
	re = /^[^@]+@[^@]+.[a-z]{2,}$/i;
	
	if (email.search(re) == -1) {
		return false;
	}
	
	return true;
}

function procedeToStepTwo() {
	if ($('#cities').css('display') != 'none') {
		toggleCities();
	}
	
	if ($('#personName').val().length < 5) {
		alert("Введите, пожалуйста, Ваше имя");
		return false;
	}
	
	if ($('#personPhone').val().length < 7) {
		alert("Введите, пожалуйста, Ваш телефон");
		return false;
	}
	
	if (!isEmailValid($('#personEmail').val())) {
		alert("Введите, пожалуйста, корректный адрес электронной почты");
		return false;
	}
	
	if (!document.getElementById('accepted').checked) {
		alert("Необходимо принять правила акции перед продолжением");
		return false;
	}
	
	code = $('#code').val();
	name = $('#personName').val();
	city = $('#personCity').val();
	phone = $('#personPhone').val();
	email = $('#personEmail').val();
	announceByEmail = document.getElementById('personSendAnnouncesByEmail').checked;
	announceByPhone = document.getElementById('personSendAnnouncesByPhone').checked;
	accepted = document.getElementById('accepted').checked;
	
	$.post('check1500.php', function(data) {
		//console.log(data.status);
		
		if (data.status == 'in1500') {
			currentRegistrationPage = 'registration-1500-question';
			openPage('registration-1500-question');
		} else {
			procedeToStepFour();
		}
	}, 'json');
}

function procedeToStepThree() {
	$('#anketaCode').html(code);
	$('#anketaName').html(name);
	$('#anketaCity').html(city);
	$('#anketaPhone').html(phone);
	$('#anketaEmail').html(email);
	if (announceByEmail && !announceByPhone) {
		$('#anketaAnnounces').html('По электронной почте');
	} else if (!announceByEmail && announceByPhone) {
		$('#anketaAnnounces').html('По телефону');
	} else if (!announceByEmail && !announceByPhone) {
		$('#anketaAnnounces').html('Не высылать уведомления');
	} else {
		$('#anketaAnnounces').html('По электронной почте и телефону');
	}
	
	currentRegistrationPage = 'registration-1500';
	openPage('registration-1500');
}

function procedeToStepFour() {
	$('#procede-2').attr('href', '').html('<img src="images/ani2.gif">');
	if (currentPage == 'registration-1500') {
		agreedForPresent = true;
		address = $('#anketaAddress').val();
		$('#thanks-text').html("<p>Дополнительная информация по получению Кинокарты будет представлена в письме, которое автоматически отправлено по Вашему электронному адресу. Обязательно сохраните чек покупки и промостикер с упаковки Scotch-Brite.</p>");
	} else {
		agreedForPresent = false;
		address = '';
	}

	$.post('register.php', { 'code': code, 'name': name, 'city': city, 'phone': phone, 'email': email, 'byemail': announceByEmail, 'byphone': announceByPhone, 'accepted':  accepted, 'agreed_for_present': agreedForPresent, 'address': address }, function(data) {

		if (data.status == 'used') {
			alert("Ошибка! Ваш код уже использован!");
			return;
		} else if (data.status != 'ok') {
			alert("Произошла ошибка. Пожалуйста, обновите страницу и заполните форму заново");
			return;
		} else {
			hash = data.hash;
		}
	}, 'json');
	
	currentRegistrationPage = 'registration-complete';
	openPage('registration-complete');
}

function procedeToCompetition() {
	$('#code').val('');
	checkCode();
	$('#more-form').hide();
	$('#personName').val('');
	$('#personCity').val('Москва');
	$('#personPhone').val('');
	$('#personEmail').val('');
	document.getElementById('personSendAnnouncesByEmail').checked = false;
	document.getElementById('personSendAnnouncesByPhone').checked = false;
	document.getElementById('accepted').checked = false;
	$('#anketaAddress').val('');
	$('#procede-2').html('<a href="javascript:procedeToStepFour();"><img src="images/further.gif"></a>');

	currentRegistrationPage = 'registration';
	openPage('competition');
}

function toggleCities() {
	if ($('#cities').css('display') == 'none') {
		$('#cities').animate({height: 142, opacity: 1});
	} else {
		$('#cities').animate({height: 0, opacity: 0}, function() {$('#cities').css('display','none')});
	}
}

function goToCompetition() {
	openPage('registration');
}

function sendStory() {
	if ($('#story-text').val().length < 10) {
		alert("Вы не ввели свою историю");
        return;
	}
	
	story = $('#story-text').val();
	
	if (userpic == null) {
		userpic = '';
	}
	
	$.post('story.php', { 'hash': hash, 'userpic': userpic, 'story': story }, function(data) {
		if (data.status != "ok") {
			alert("Произошла ошибка, попробуйте отправить историю позднее");
			return;
		} else {
			$('#user-photo').html('<div class="swfupload-control"><span id="spanButtonPlaceholder"></span></div>');
			initializeUploader();
			$('#story-text').val('');
			openPage('thanks-competition');
			$('#konkurs-link2').attr('href', "javascript:openPage('thanks-competition')");
		}
	}, 'json');
}

function loadNewStory() {
	$('#vote-story').html('');
	$('#vote-count').html('');
	if (stories.length == 0) {
		$('#vote-story').html("<br><br>Больше историй, за которые вы можете проголосовать пока нет");
		$('#vote-button').hide();
		$('#vote-arrow-right').hide();
		$('#arrow-left-vote').hide();
	} else {
		if (currentStory + 1 >= stories.length) {
			currentStory = 0;
		} else {
			currentStory++;
		}
		//console.log(currentStory);
		//$('#arrow-left-vote').show();
		$('#vote-story').html(stories[currentStory].story.replace('\"', '"'));
		$('#vote-count').html(stories[currentStory].votes);
	
		if ($('#vote-button').css('display') == 'none') {
			$('#vote-button').show();
		}
	}
}

function loadPrevStory() {
	$('#vote-story').html('');
	$('#vote-count').html('');
	if (stories.length == 0) {
		$('#vote-story').html("<br><br>Больше историй, за которые вы можете проголосовать пока нет");
		$('#vote-button').hide();
		$('#vote-arrow-right').hide();
		$('#arrow-left-vote').hide();
	} else {
		if (!/Safari/.test(navigator.userAgent)) {
			console.log(currentStory);
		}
		
		if (currentStory < 1) {
			currentStory = stories.length - 1 ;
		} else {
			currentStory--;
		}
		//console.log(currentStory);
		//$('#arrow-left-vote').show();
		$('#vote-story').html(stories[currentStory].story.replace('\"', '"'));
		$('#vote-count').html(stories[currentStory].votes);
	
		if ($('#vote-button').css('display') == 'none') {
			$('#vote-button').show();
		}
	}
}

function voteForStory() {
	$.get('vote.php?action=vote', {'id': stories[currentStory].id}, function(data){
		alert("Спасибо за голос!");
		var tmp = new Array();
		j = 0;
		for (i = 0; i < stories.length; i++) {
			if (stories[i] != stories[currentStory] && stories[i] != undefined) {
				tmp[j] = stories[i];
				j++;
			}
		}
		stories = tmp;
		delete(tmp);
		loadNewStory();
	});
}