jQuery(document).ready(function(){
	initLog(true);
	initPage();
	resizeFrame();
	getServerMessage();
});

jQuery(window).resize(function(){resizeFrame()});

function initPage() {

	// load page by hash
	if (window.location.hash!='' && window.location.hash!='#' && window.location.hash!='# '){
		loadPage(window.location.hash);
	}
	

	// left menu
	jQuery('#leftmenu > li').click(function(){
		jQuery(this).addClass('sel');
		jQuery(this).siblings().removeClass('sel open');
		jQuery(this).siblings().find('ul').slideUp(300).addClass('closed').removeClass('open').find('li.open').removeClass('sel').addClass('closed');

		if(jQuery(this).find('ul').length > 0) {
			jQuery(this).addClass('open').removeClass('closed').siblings('li').removeClass('sel open');
			jQuery(this).find(' > ul').slideDown(300);
		}
		if(jQuery(this).children('a').attr('href') != '' && jQuery(this).children('a').attr('href') != '#') {
			loadPage(jQuery(this).children('a').attr('href'));
		}
	});
	jQuery('#leftmenu > li > ul > li').click(function(){
		jQuery(this).siblings().removeClass('sel');
		jQuery(this).addClass('sel');
		loadPage(jQuery(this).children('a').attr('href'));
	});
	
	// maximize browser, top menu selected
	if(jQuery('#leftmenu').length > 0) {
		jQuery('#frame').css('margin-left',260);
		jQuery('#header p.buttons a:eq(1)').addClass('sel');
	} else {
		jQuery('#header p.buttons a:eq(0)').addClass('sel');
	}


	// edit mode check
	jQuery('#header p.buttons a').click(function(){
		if(jQuery('button:contains(SZERKESZTÉS BEFEJEZÉSE)').length>0){
			var answer = confirm("Figyelem!\nA kattintott hivatkozásra a költségvetés-kiírás szerkesztése befejeződik és el fog navigálni az oldalról!\nTovább megy a hivatkozott oldalra?");
			if(!answer){
				return false
			}
		}
	});
	// top nav bar
	/*jQuery('#header p.buttons a').click(function(){
		if(jQuery(this).attr('href') != '#') {
			jQuery(this).addClass('sel').siblings().removeClass('sel');
			loadPage(jQuery(this).attr('href'));
		}
	});*/
	
	
	// modal window
	jQuery('a.reg, a.modreg').live('click',function(){
		
		var modal = "frame/regmodal";
		if(jQuery(this).hasClass('modreg')) {
			modal = "frame/moduser";
		} 
		
		
		jQuery.get(modal,function(data){
			
			jQuery('html, body').css('overflow','hidden')
			jQuery('body').append(data);
			
			jQuery('#modal').show(300);
			
			// close
			jQuery('#modal h1 img').click(function(){
				jQuery('#modal .container').css('overflow','hidden');	
				jQuery('#modal').hide(300,function(){
					jQuery('#modal, #modalshadow').remove();
					jQuery('html, body').css('overflow','visible');
				})
			});
			
			
			// terms of use
			jQuery('#termsofuse').click(function(){
				jQuery('#modal .page h1:eq(0)').animate({marginLeft:"-759px"});
				jQuery('#modal .page div.container:eq(0)').animate({marginLeft:"-759px"},function(){
					jQuery('#modal .container').css({'overflow': 'hidden', 'overflow-y': 'scroll'});	
				});
			});
			
			jQuery('a.back').click(function(){
				jQuery('#modal .container').css('overflow','hidden');	
				jQuery('#modal .page h1:eq(0)').animate({marginLeft:"0px"});
				jQuery('#modal .page div.container:eq(0)').animate({marginLeft:"0px"});
				
			});
			
			// captcha image
			jQuery('label.codes img').live('click',function(){
				jQuery.getJSON('/frame/captcha_func', function(captcha){
					jQuery('#modal input[name=checkcode]').val('').prev('label').html(captcha.captcha_str);
					jQuery('label.codes img').attr('title','Kattintson a képre új kód kéréséhez.');
				},'json');
			}).attr('title','Kattintson a képre új kód kéréséhez.');

			
			// register
			jQuery('#modal button').click(function(){
				
				jQuery.post('frame/reguser',$("#modal form input").serializeArray(),function(data){
									
					jQuery('#modal label.error').html(data.errormsg);
					jQuery('#modal input, #modal span.chk').removeClass('error');
					
					if(typeof data.errfields != 'undefined') {

						for (var i = 0; i < data.errfields.length; i++) {
							jQuery('#modal input[name='+data.errfields[i]+']').addClass('error');
							
							if(data.errfields[i]=='accepted') {
								jQuery('#modal input[name='+data.errfields[i]+']').parents('span.chk').addClass('error');
							}
						}

						jQuery.getJSON('/frame/captcha_func', function(captcha){
							jQuery('#modal input[name=checkcode]').val('').prev('label').html(captcha.captcha_str);
						},'json');

					}

					if(!data.error) {
						jQuery('#modal label.error').addClass('ok');
						jQuery('#modal button').hide(0);
					} 
					
					jQuery('#modal label.error').slideDown(300);
					if(parseInt(jQuery('#modal').height()) < 420) {
						/// eldobalja a stilust, ha #modal, #modal .containter-nek van animate
						jQuery('#modal').animate({"height": "+=60px"}, 300);
						jQuery('#modal .container').animate({"height": "+=60px"}, 300);	
					}
					
				},"json");
			});
			
			// zip
/*			jQuery('#modal input[name=zip]').keypress(function(){
				if(jQuery(this).val().length == 3) {
					jQuery('#modal input[name=city]').focus();
				}
			});*/
			
		})
	});
	
	// login box
	jQuery('#header form input').focus(function(){
		jQuery(this).removeClass('empty').val('');
	});
	
	jQuery('#header form input[type=password]').blur(function(){
		if(jQuery(this).val()=='') {
			jQuery(this).addClass('empty');
		} 
	});
	
	jQuery('#header form input[type=text]').blur(function(){
		if(jQuery(this).val()=='') {
			jQuery(this).val('E-mail cím');
		} 
	});
	
	
	jQuery('#header form#passform a:contains(Bejelentkezés)').click(function(){
		jQuery('#header form#passform').hide(300);
		jQuery('#header form#loginform').show(300);
	});
	
	jQuery('#header form#loginform a:contains(Elfelejtette jelszavát?)').click(function(){
		jQuery('#header form#passform').show(300);
		jQuery('#header form#loginform').hide(300);
	});
	
	// login form
	jQuery('#header form#loginform button').click(function doLogin(){
		jQuery.post('/login/userauth',{login: jQuery('#header form#loginform input[name=login]').val(), password: jQuery('#header form#loginform input[name=password]').val()}, function(data){
			if(data.success) {
				window.location.href='/browser';
			} else {
				modalAlert(data.errormsg,'true',15,'error');
			}
		}, "json");
	});
	
	/*jQuery('#header form#loginform input').keypress(function(e){
		if (e.which == 13) {
			jQuery('#header form#loginform button').click();
		}
	});*/

	// forgot pass form
	jQuery('#header form#passform button').click(function(){
		jQuery.post(jQuery(this).parents('form').attr('action'),{login: jQuery('#header form#passform input[name=login]').val()}, function(data){
			modalAlert(data.errormsg,'true',15,'error');
		},"json")
	});
	
	
	
}


function afterPageLoad() {
	
	// check if codecheck
	if($('#checkcode').length > 0){
		
		$('#checkcode').unbind().click(function(){
			
			$('div.modalAlert, #codeResult').stop().remove();
				
			$.post('/frame/checkcode', {code: $('#checkcodeval').val()}, function(data){
				if (data.error===true){
					modalAlert(data.errormsg,"true",10,"error");
					$('#checkcodeval').addClass('error').focus();
				} else {
					$('#innerContent').append('<div id="codeResult">'+data.errormsg+'</div>');
					$('#codeResult').slideDown(200);
				}
				
			},'json');
		});
	}
}

function resizeFrame() {
	jQuery('#frame, #frame_main').css('height', parseInt(jQuery(window).height())-112);
	jQuery('#frame div#innerContent').css('height', parseInt(jQuery(window).height())-174);
	
	afterPageLoad();	
}

function loadPage(page,attr){
	if(typeof page!='undefined') {
		var pattr = attr || {};
		var p = page.replace(/#/,'');
		jQuery.get('/frame/'+p,pattr,function(data){
			jQuery('#frame').html(data);
			resizeFrame();
		});
	}
}

function formatContent(){
    var content = jQuery('#frame').html();
    var p = new Ext.Panel({
            title: 'My Panel',
            collapsible:true,
            renderTo: 'frame',
            width:400,
            html: content
        });

}

function modalAlert(msg,autoHide,timeOut,type) {
		_autoHide = autoHide || "false";
		_timeOut = timeOut*1000 || 15000
		_type = type || "notice";
		jQuery('body').append('<div class="modalAlert"><p>'+msg+'</p></div>');
		var h = parseInt(jQuery('.modalAlert').height());
		jQuery('.modalAlert').css('top',0-h);
		jQuery('.modalAlert').animate({top: 0});
		jQuery('.modalAlert').click(function(){
			jQuery('.modalAlert:last-child').animate({top: 0-h},function(){
				jQuery('.modalAlert:last-child').remove();
			});
		});
		if(_autoHide == "true") {
			setTimeout(function(){jQuery('.modalAlert:last-child').click()},_timeOut);
		}
		if(_type=="error") {
			jQuery('.modalAlert p').addClass('error');
		}
}

function getServerMessage(){
		if(typeof serverMessage.message != 'undefined') {
			modalAlert(serverMessage.message, serverMessage.autohide, serverMessage.timeout, serverMessage.type);
		}
		
		jQuery('a.msg').click(function(){
			modalAlert(jQuery(this).attr('rel'), true, 20, 'notice');
		});
}


function initLog(debug){
	if(debug) {
		if(typeof console == 'undefined') {
			console = { log: function(msg) {alert('LOG: '+msg);} }
		}
	} else {
		return false
	}
}

