$(function(){


window.App = Backbone.View.extend({
	el: $('html'),
	events: {
		'click .showForm': 'showForm',
		'click #form_bg': 'hideForm',
		'click .closeMess': 'hideForm',
		'click .submitbutt': 'submitClick'
	},
	initialize: function(){
		var that = this;
		$('#form_bg').show().css('opacity', 0);
		//////console.log('yyaaappp');
		
		$(window).resize(function(){
			that.setLayout();
		});
		that.setLayout();
		
		$('#forms .frm').hide();
		
		$('form.ajax').submit(function(){
			that.submitForm(this);
			return false;
		});
		
		if(typeof(dialogshow) != 'undefined'){
			if(dialogshow == 'emailvalid'){
				this.showMessage('Registrace','','Děkujeme za registraci, nyní se můžete přihlásit', '<a href="#" class="submitbutt showForm" type="login"><span>Přihlásit</span></a><div class="clearfix"></div>');
			} else if(dialogshow == 'myphotos'){
				this.showFormRun('myphotos');
			} else if(dialogshow == 'myvotes2'){
				this.showFormRun('myvotes');
			}
		}
		
		$('.frm button').remove();
		$('.frm form fieldset').append('<a href="#" class="submitbutt"><span>Odeslat</span></a><div class="clearfix"></div>');
		
		
//		if($('#top a.myphotos').length > 0){
//			$.getJSON('http://www.nikon-kalendar.cz/ajax/uploadlink?r=' + (new Date()).getTime(), {}, function(data){
//				if(data.result == true){
//					$('#form-upload-photo').attr('action', data.data);
//				}
//			});
//		}
		
	},
	submitClick: function(e){
		var el = $(e.currentTarget).parent().parent();
		el.submit();
	},
	showForm: function(e){
		var type = $(e.currentTarget).attr('type');
		this.showFormRun(type);
		return false;
	},
	showFormRun: function(type){
		$('#forms').fadeIn(500);
		$('#form_bg').animate({opacity: 0.8}, 1000);
		$('#forms .frm').hide();
		$('#forms .'+type).fadeIn(700);
		window.scrollTo(x-coord, y-coord);
		
		this.setLayout();
	},
	showMessage: function(nadpis, pop, text, button){
		$('#forms').fadeIn(500);
		$('#form_bg').animate({opacity: 0.8}, 1000);
		$('#forms .frm').hide();
		$('#forms .message h1').html(nadpis);
		$('#forms .message p.pop').html(pop);
		$('#forms .message p.text').html(text);
		$('#forms .message div.btnc').html(button);
		$('#forms .message').fadeIn(700);
		this.setLayout();
		
		return false;
	},
	hideForm: function(){
		$('#forms').fadeOut(300, function(){ 
			$('#form_bg').css('opacity', 0);
		});
	},
	setLayout: function(){
		var height = $(window).height();
		var dheight = $(document).height();
		var width = $(window).width();
		
		$form_bg = $('#form_bg');
		
		$form_bg.height(dheight);
	},
	submitForm: function(el){
		var that = this;
		var myForm = $(el);
		var type = myForm.attr('id');
		var action = myForm.attr('action');
		
		//////console.log(myForm);
		
		var $inputs = myForm.find('input');
		
		var valid = true;
		$.each(myForm.find('.required'), function(i, val){
			if($(val).val() == '' && valid){
				valid = false;
				alert('Nemáte vyplněny všechny povinné údaje.');
				return false;
			}
		});
		if(myForm.find('.required-chbox').length > 0){
			if(myForm.find('.required-chbox').attr('checked') != true){
				valid = false;
				alert('Pro pokračování v registraci je nutné souhlasit s provozními podmínkami.');
				return false;
			}
		}
		
		
		if(valid){
			var values = {};
			$inputs.each(function() {
				var name = this.name.split('_')[1];
				values[name] = $(this).val();
			});
			
			
			
			switch(type){
				case 'form-upload-photo':
					/*$("#loading").ajaxStart(function(){
						$(this).show();
					}).ajaxComplete(function(){
						$(this).hide();
					});*/
			
					$.ajaxFileUpload({
						url: action,
						secureuri: false,
						fileElementId: 'form-upload-photo_file',
						dataType: 'json',
						data: values,
						success: function (data, status){
							//////console.log(data);
						},
						error: function (data, status, e){
							alert(e);
						}
					});
				break;
				case 'form-mailreg':
					$.postJSON(action, values, function(data){
							//////console.log(['postJson', data, 'result', data.result, data.result == true]);
						if(data.result == true){
							
							that.showMessage($('#forms .regmail h1').html(), $('#forms .regmail p.pop').html(), 'Děkujeme za odeslání registračního formuláře. Pro dokončení registrace prosím potvrďte odkaz v aktivačním mailu, který Vám byl zaslán na Vaši adresu.');
						} else if(data.result == false){
							if(data.data.error == 3 ){
								alert('Zadaný email není ve správném formátu.');
							} else if(data.data.error == 4 ){
								alert('Zadané přihlašovací jméno již existuje, vyberte si jinou.');
							} else if(data.data.error == 5 ){
								alert('Zadaný email je již registrovaný.');
							} else if(data.data.error == 6 ){
								alert('Kontrola hesla nesouhlasí.');
							} else {
								alert('Při registraci došlo k chybě ['+data.data.error+']. Pokud potíže přetrvají, kontaktujte správce webu.');
							}
						}
					});
				break;
				case 'form-photos':
					$.postJSON(action, values, function(data){
							//////console.log(['postJson', data, 'result', data.result, data.result == true]);
						if(data.result == true){
														
						} else if(data.result == false){
							if(data.data.error == 3 ){
								alert('Nesprávne heslo');
							} else {
								alert('Došlo k chybě ['+data.data.error+']. Pokud potíže přetrvají, kontaktujte správce webu.');
							}
						}
					});
				break;

				default:
					$.postJSON(action, values, function(data){
						//////console.log(data);
					});
				break;
			}
		} else {
			
		}
		
		return false;
	}
});


var myapp = new App();
$('input').placeholderFunction('input-focused');



var rnd = Math.floor(Math.random()*14)+1;
if(rnd == 14) {
	$('#swfbanner1').append('<a href="http://www.fotoinstitut.cz/" target="_blank"><img src="http://www.nikon-kalendar.cz/img/banner_'+rnd+'.gif" width="800" height="80" alt="banner"/></a>');
} else {
	$('#swfbanner1').flash({
	    src: 'http://www.nikon-kalendar.cz/img/banner_'+rnd+'.swf',
	    width: 800,
	    height: 80,
	    wmode: 'opaque'
	});
}


});

jQuery.extend({
   postJSON: function( url, data, callback) {
   	   data = JSON.stringify(data);
   	   //////console.log(['submit form > ',data]);
   	   return jQuery.ajax({
        'type': 'POST',
        'url': url,
        'contentType': 'application/json',
        'data': data,
        'dataType': 'json',
        'success': callback
       });
   }
});

if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
$(window).load(function(){
    $('input:-webkit-autofill').each(function(){
        var text = $(this).val();
        var name = $(this).attr('name');
        $(this).after(this.outerHTML).remove();
        $('input[name=' + name + ']').val(text);
    });
});}



/*
 Shadow animation jQuery-plugin 1.6
 http://www.bitstorm.org/jquery/shadow-animation/
 Copyright 2011 Edwin Martin <edwin@bitstorm.org>
 Contributors: Mark Carver, Xavier Lepretre
 Released under the MIT and GPL licenses.
*/
jQuery(function(e,i){function j(){var a=e("script:first"),b=a.css("color"),c=false;if(/^rgba/.test(b))c=true;else try{c=b!=a.css("color","rgba(0, 0, 0, 0.5)").css("color");a.css("color",b)}catch(d){}return c}function k(a,b,c){var d=[];a.c&&d.push("inset");typeof b.left!="undefined"&&d.push(parseInt(a.left+c*(b.left-a.left),10)+"px "+parseInt(a.top+c*(b.top-a.top),10)+"px");typeof b.blur!="undefined"&&d.push(parseInt(a.blur+c*(b.blur-a.blur),10)+"px");typeof b.a!="undefined"&&d.push(parseInt(a.a+c*
(b.a-a.a),10)+"px");if(typeof b.color!="undefined"){var g="rgb"+(e.support.rgba?"a":"")+"("+parseInt(a.color[0]+c*(b.color[0]-a.color[0]),10)+","+parseInt(a.color[1]+c*(b.color[1]-a.color[1]),10)+","+parseInt(a.color[2]+c*(b.color[2]-a.color[2]),10);if(e.support.rgba)g+=","+parseFloat(a.color[3]+c*(b.color[3]-a.color[3]));g+=")";d.push(g)}return d.join(" ")}function h(a){var b,c,d={};if(b=/#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(a))c=[parseInt(b[1],16),parseInt(b[2],16),parseInt(b[3],
16),1];else if(b=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(a))c=[parseInt(b[1],16)*17,parseInt(b[2],16)*17,parseInt(b[3],16)*17,1];else if(b=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(a))c=[parseInt(b[1],10),parseInt(b[2],10),parseInt(b[3],10),1];else if(b=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9\.]*)\s*\)/.exec(a))c=[parseInt(b[1],10),parseInt(b[2],10),parseInt(b[3],10),parseFloat(b[4])];d=(b=/(-?[0-9]+)(?:px)?\s+(-?[0-9]+)(?:px)?(?:\s+(-?[0-9]+)(?:px)?)?(?:\s+(-?[0-9]+)(?:px)?)?/.exec(a))?
{left:parseInt(b[1],10),top:parseInt(b[2],10),blur:b[3]?parseInt(b[3],10):0,a:b[4]?parseInt(b[4],10):0}:{left:0,top:0,blur:0,a:0};d.c=/inset/.test(a);d.color=c;return d}e.extend(true,e,{support:{rgba:j()}});var f;e.each(["boxShadow","MozBoxShadow","WebkitBoxShadow"],function(a,b){a=e("html").css(b);if(typeof a=="string"&&a!=""){f=b;return false}});if(f)e.fx.step.boxShadow=function(a){if(!a.init){a.b=h(e(a.elem).css(f));a.end=e.extend({},a.b,h(a.options.curAnim.boxShadow));if(a.b.color==i)a.b.color=
a.end.color||[0,0,0];a.init=true}a.elem.style[f]=k(a.b,a.end,a.pos)}});


/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "placeholder support for non webkit browsers"
 * Version: 1.0, 08.05.2011
 * by Christian Fillies, contact@christianfillies.com
 *                       http://christianfillies.com/
 *
 * Copyright (c) 2011 Christian Fillies
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * (en) specify the elements to get the placeholder function
 *		the passing value is the CSS Class that gets added to the parent <DIV> when the input is in focus
 *		you need to have a <DIV> around the <INPUT> to use for focusing css styles
 *
 *	EXAMPLE: $('input').placeholderFunction('input-focused');
 */ 
 
 // Value as Placeholder including focusing Styles for the parent DIV
	// (en) setup a placeholder using the html5 placeholder attribute as supported by webkit browsers, 
	//		it then gets replaced into a standard value technique supported by all browsers.
	if ($.browser.webkit) {
		$.fn.extend  ({
			placeholderFunction : function (focusClass) {
				return this.each(function() {
					$(this).focus(function() {
						$(this).parentsUntil('div').parent().addClass(focusClass);
					$(this).blur(function () {
						$(this).parentsUntil('div').parent().removeClass(focusClass);
				});
				});
			});
		} });
	} else {
		$.fn.extend  ({
			placeholderFunction : function (focusClass) {
				return this.each(function() {
					var placeholder = $(this).attr("placeholder");
						$(this).val(placeholder);
						$(this).removeAttr("placeholder");
					$(this).focus(function() {
						$(this).parentsUntil('div').parent().addClass(focusClass);
						if ($(this).val() == placeholder) { $(this).val(''); }
					$(this).blur(function () {
						$(this).parentsUntil('div').parent().removeClass(focusClass);
						if ($.trim($(this).val()) == '') { $(this).val(placeholder); }
					});
				});
			});
		} });
	};

