$(function(){	
	/*!! almenüket is megoldani!*/
	
        //LINK kiterjesztése a tartalmazó elemekre
        links = '.btn > a, h3 > a';
	$(links).each(function(){
		$(this).parent().eq(0).click(function(e){
			e.preventDefault();
			location.href=($(this).find('a').eq(0).attr('href'));
		});
	});
	
        //FORM ELEMEK JS-e
	$('input.datepicker').datepicker({dateFormat: 'yy.mm.dd.'});
	$('img.datepicker').click(function(){
		$(this).siblings('input.datepicker').eq(0).datepicker('show');
	});	
	$('input.checkbox').each(function(){
		if($(this).val()!='')$(this).css('background-image','url("'+doc_root+'templates/template/img/close.png")');
	})
	$('input.checkbox').click(function(e){
		e.preventDefault();
		if($(this).val()!=''){
			$(this).val('');
			$(this).css('background-image','none');
			$(this).siblings('.checkbox').each(function(k,v){				
				$(v).css('background-image','url("'+doc_root+'templates/template/img/close.png")');	
				$(v).val('  ');
			});
		}else{
			$(this).val('  ');
			$(this).css('background-image','url("'+doc_root+'templates/template/img/close.png")');
			$this = $(this);	
			$(this).siblings('.checkbox').each(function(k,v){				
				$(v).css('background-image','none');	
				$(v).val('');
			});
		}			
	}).focus(function(e){
		e.preventDefault();
		$(this).blur();
		return false;
	});

	//galéria popup        
	$('.popup_bg').css('opacity','0');
	$('.gallery_popup').css('opacity','0');
	$('body').delegate('.popup_bg, .popup .close','click',function(){
		$('.popup, .popup_bg').animate({'opacity':0},500);
		setTimeout("$('.popup, .popup_bg').css('display','none');",500);
	});
	$('ul.galeria img, ul.galeria h5, ul.galeria h4, ul.galeria .btn').click(function(){
                id = $(this).parent('li').attr('alt');                          
                $('.gallery_popup').html($('#gal_'+id).html()).append(
                    $('<div />').addClass('close')
                );
                    $('.gallery_popup img:first-child').load(function(){
                        $(this).animate({'opacity':1},500);
                    });
                    $('.gallery_popup ul li img').click(function(){
                            $('.gallery_popup ul li.aktiv').attr('class','');
                            $(this).parent().attr('class','aktiv');
                            $('.gallery_popup img').eq(0).attr('src',$(this).attr('src').replace('108_77','702_391'));
                            $('.gallery_popup p').eq(0).html($(this).attr('alt')+'&nbsp;');
                    });
                
		$('.popup_bg, .gallery_popup').css('display','block');
		$('.popup_bg').animate({'opacity':0.7},500);
		$('.gallery_popup').animate({'opacity':1},500);
                $('.gallery_popup ul li.prev').click(function(){
                    pageGpopup(-5,this);
                });
                $('.gallery_popup ul li.next').click(function(){
                    pageGpopup(5,this);
                });
	});
	

	$('.popup .close').live('click',function(){		
		$(this).parent().css({'display':'none'});
	});        

        //Fejléc rotáló
       var ir = new image_rotator('ir','#head .bambus ul');	
       //login
       loginbox();
       login();
       //látogatás form
       latogatas();
       //hírlevél form
       hirlevel();
       //egyedi alert inicializálás
       init_alert();
       //pager beigazítása
       align_pager();
       //#main és #right magasság ekvivalálása
       equalHeights();    
       
       //FEJLÉC KATTINTHATÓSÁG
       $('#head .bambus')
            .css({ 'cursor':'pointer' })
            .click(function(){
                location.href= 'http://'+location.href.replace('http://','').split('/').shift();
            });
       $('#head #loginbox, #head #liggerin')
            .css('cursor','auto')
            .click(function(e){
                e.stopPropagation();
            });            
});
//Galéria lapozás
function pageGpopup(move,element){
    var $cntnr = $(element).parent();
    var $oneS = $cntnr.find('li').not('.prev').not('.next')
    oneWidth = 116;            
    var count = $oneS.length;
    var actual = $cntnr.attr('rel')?parseInt($cntnr.attr('rel')):0;    
    actual = actual + move;
    if( actual < 0 ) return;
    else if( actual >= count-1 ) return;
    $cntnr.attr('rel',actual);
    $oneS.each(function(k,v){
       if( k<actual || k>=actual+Math.abs(move) ) {
           $(v).fadeOut();
       }else{
           $(v).fadeIn();
       }
    });
}


//órarend lapozás előra
function week_last(){
    $('#next_week').remove();
    $('#week_pager')[0].submit();
}
//órarend lapozás vissza
function week_next(){
    $('#last_week').remove();
    $('#week_pager')[0].submit();
}

//lapozó beigazítás
function align_pager(){
    $pager = $('ul.pager');
    if($pager.length > 0){
        full = $pager.width();
        inner = 0;
        $pager.find('li').each(function(k,v){
           $this = $(this);
           if($this.hasClass("clear"))return;
           inner+=$(this).width();
        });
        if( full!=inner ){
            $pager.find('li:first-child').css('margin-left',(full-inner)/2);
        }
    }
}
//foki popup
function doki_init(){
    $('.timetable_popup').remove();
    $('#doki_search').focus(function(){
        if($(this).val() == $(this).attr('alt'))$(this).val('');
    }).blur(function(){
        if($(this).val() == "")$(this).val($(this).attr('alt'));
    }).keyup(function(e){
        if(e.keyCode == 13){
            $this = $(this);
            if($this.val()){
                location.href = doc_root+site+'/filters/patient___name/'+$this.val()+'/#content_top';
            }else{
                location.href = doc_root+site+'#content_top';
            }
        }
    }).click(function(e){
      if(e.offsetX > 277 ){
           $this = $(this);
           if($this.val()){
                location.href = doc_root+site+'/filters/patient___name/'+$this.val()+'/#content_top';
           }else{
                location.href = doc_root+site+'#content_top';
           }
      }
    });
    $('.dokik .btn, .doki-right').live('click',function(){        
        $.ajax({       
            url:'/ajax.php?module=paciensekAjax',
            data:{ 'id':$(this).attr('rel') },
            type:'POST',
            dataType: 'html',
            success:function(html){
                $('.dokik_popup').html(html);
                $('.popup_bg, .dokik_popup').css('display','block');
                $('.popup_bg').animate({'opacity':0.7},500);                
                $('.dokik_popup').animate({'opacity':1},500);
            }
        });
    });
    $('.dokik_popup .btn').live('click',function(){
        postForm('#doki_form',dokik_post_callback);        
    });
}
function dokik_post_callback(frm,message){    
    if( message.status>=0 && message.nid ){
        console.log(message);
        row = $('table.dokik div[rel="'+message.nid+'"]');        
        if( row.length == 0 ){
            row = $('<tr/>')
                .append($('<td/>').text($('#doki_form input[name="patient___name"]').val()))
                .append($('<td/>').text($('#doki_form input[name="patient___bornday"]').val()))
                .append($('<td/>').append(
                    $('<div/>').addClass('btn').attr('rel',message.nid).text('Részletek')))
                .append($('<td/>').text('Nem jelentkezezz be').prepend(
                    $('<img/>').attr('src',doc_root+'templates/template/img/delete.png').attr('width','16').attr('height','16')
                ));            
            console.log(row);
            $('table.dokik').find('tr').eq(0).after(row);            
        }else{
            row.find('td').eq(0).text($('#doki_form input["patient___name"]').text());
            row.find('td').eq(1).text($('#doki_form input["patient___bornday"]').text());            
        }
        console.log(row);
    }
    post_callback(frm,message);
}
//órarend popup
function timetable_click(){
    $('table.times td.active').live('click',function(e){
        $('.gallery_popup').remove();
        os = $(this).offset();
        lt = os.left+$(this).width()-16;
        ltt = os.top-7;
        ttid = $(this).attr('rel');

        $.ajax({
            url:'/ajax.php?module=timetableAjax&action=getone',
            data:{ 'lessontime___id':ttid },
            type:'POST',
            dataType: 'html',
            async: false,
            success: function(html){
                if(html=='Üres'){
                    custom_alert(" Az óra megtelt ! ");
                }else{
                    $('.timetable_popup').html(html).css({'display':'block','opacity':'1','left':lt,'top':ltt});
                }
            }
        });
    });
}
//órarend, foglalás törlése
function del_reservation(ttid){
    if(confirm('Biztosan törli az időpont foglalást?')){
        $.ajax({
            url:'/ajax.php?module=timetableAjax&action=delete',
            data: { 'resid':ttid  },
            type: 'POST',
            dataType: 'json',
            async: false,
            success: function(resp){    
                
                custom_alert(resp.mess);                
                if(parseInt(resp.status) >= 0){   
                    
                    $('tr[rel="'+ttid+'"]').remove();
                    equalHeights();
                }                
            }
        });
        
        
       /* $('tr[rel="'+ttid+'"]').remove();
        equalHeights();*/
    }
}
//órarend foglalás click
function timetable_reserve_init(){
    $('.timetable_popup .btn').live('click',function(){        
        $this = $(this);
        $ttid = $(this).attr('rel');
        if( !$ttid ) return;
        $.ajax({
            url:'/ajax.php?module=timetableAjax&action=reserve',
            data: { 'lessontime___id':$ttid  },
            type: 'POST',
            dataType: 'json',
            async: false,
            success: function(resp){                           
                custom_alert(resp.mess);                
                if(resp.status >= 0){                    
                    ttid = $('.timetable_popup .btn').eq(0).attr('rel');                                   
                    cell = $('.times td[rel="'+ttid+'"]');   
                    if(resp.resp>0){
                        txt = cell.html();                                        
                        txt = txt.replace(/\(\+[0-9]+\)/i,'(+'+resp.resp+')');                   
                        cell.html(txt); 
                    }else{
                        cell.html('Betelt').removeClass('active');
                    }
                }
                $('.close').eq(0).trigger('click');
            }
        });
    });
}

/*ajax post-ok kezelése*/
function postForm(frm, callback){        
    action = $(frm).attr('action');
    dta = {};   
    $(frm).find('input, select, textarea').each(function(){
        if(!$(this).attr('name')) return;
        if($(this).attr('type')=='checkbox'){
            dta[$(this).attr('name')] = ($(this).attr('checked')?'1':'0');        
        }else if($(this).hasClass('checkbox')){
            dta[$(this).attr('name')] = ($(this).val().length)?'1':'0';
        }else{
            dta[$(this).attr('name')] = $(this).val();
        }
    });       
     $.ajax({
        url: doc_root+action,
        data: dta,
        type: 'POST',
        dataType: 'json',
        async: false,
        success: function(resp){                           
            callback(frm,resp);
        }
    });
}
//form ürítés
function clearForm(frm){
     $(frm).find('input[type!="hidden"], select, textarea').each(function(){
         $this = $(this);
         $this.val('');
         if($this.attr('name')=='code'){
             $this.siblings('img').each(function(){
                 $img = $(this);
                 $img.attr('src','/capcha.php?width='+$img.width()+'&amp;height='+$img.height()+'&amp;rnd='+Math.random());
             });
             
         }
     });
}
//egyedi alert inicializálás
function init_alert(){
    $('#custom_alert').dialog({
			modal: true,
                        autoOpen: false,
			buttons: {
				Ok: function() {
					$( this ).dialog( "close" );
				}
			}
		});
}
//egyedi alert
function custom_alert(message){
    $('#custom_alert').html(message).dialog( "open" )
}
//post utáni callback
function post_callback(frm,message){
    if( message.status < 0 ){
        $.each(message.resp,function(k,v){   
            if(v=='code'){
                $input = $('input[name="'+v+'"]');
                if($input.val()) $input.val('').siblings('img').each(function(){
                    $img = $(this);
                    $img.attr('src','/capcha.php?width='+$img.width()+'&amp;height='+$img.height()+'&amp;rnd='+Math.random());
             });
            }
            $(frm).find('input[name="'+v+'"], select[name="'+v+'"], textarea[name="'+v+'"]')
            .animate({'background-color':'#ffB0b0','color':'#fff'},500)
            .animate({'background-color':'#fffffff','color':'#868686'},500)
            .animate({'background-color':'#ffB0b0','color':'#fff'},500)
            .animate({'background-color':'#fffffff','color':'#868686'},500)
            .animate({'background-color':'#ffB0b0','color':'#fff'},500)
            .animate({'background-color':'#fffffff','color':'#868686'},500);        
        });
    }else{
        if(message.mess != 'Sikeres Mentés!') clearForm(frm);
        $('.popup_bg, .popup').animate({'opacity':0},500);
	setTimeout("$('.popup_bg, .popup').css('display','none');",500);
    }
    custom_alert(message.mess);
}

/*látogatás form*/
function latogatas(){    
    $('#send_visit').click(function(){
        postForm('#visit',post_callback);
    });
    $('#frm input[type="text"]').keydown(function(){
        
    });
}

/*kapcsolat form*/
function kapcsolat(){
    $('#submit_contact').click(function(){
        postForm('#contact',post_callback);
    });
}
/*reg form*/
function regisztracio(){
    $('#submit_reg').click(function(){
        postForm('#reg',post_callback);
    });
}

/*hírlevélre iratkozás form*/
function hirlevel(){    
    $('#send_newsletter').click(function(){
        postForm('#newsletter',post_callback);
    });
    
}

/*login*/
function login(){
    $('#submit_login').click(function(){
        $('#login_form').submit();
    });
    $('#submit_logout').click(function(){        
        $('#logout_form').submit();
    });
    $('#submit_idopont').click(function(){
        alert('ido');        
        location.href=doc_root+'orarend#idopontok'; 
    });
    $('#submit_adatmod').click(function(){        
        location.href=doc_root+'adatlap'; 
    });     
    $('#submit_patient').click(function(){
        location.href=doc_root+'orvosok'; 
    });
    //elfelejtett jelszó
    
    
    $('#forgotten_open').click(function(){        
        $.ajax({       
            url:'/ajax.php?module=loginAjax',
            data:{ 'action':'forgotten' },
            type:'POST',
            dataType: 'html',
            success:function(html){
                $('.forgotten_popup').html(html);
                $('.popup_bg, .forgotten_popup').css('display','block');
                $('.popup_bg').animate({'opacity':0.7},500);                
                $('.forgotten_popup').animate({'opacity':1},500);
            }
        });
    });
    $('.forgotten_popup .btn').live('click',function(){
        postForm('#elfelejtett_form',post_callback);        
    });
}
//ez nem kell mert csak egy link
function logout(){}

function loginbox(){
    $('#main_login').click(function(){
            $('#loginbox').fadeIn(500);
            $('#loggedinbox').fadeOut(500);
            $('#liggerin').fadeOut(500);
    });
}

/*main és jobb oldali box magasságának összeigazítása*/
function equalHeights(){
    $('.twitter').css({'position':'relative','bottom':'0px','left':'0px'});
    $('#right').css('height','auto');
    $('#main').css('height','auto');
    m = $('#main').height();
    r = $('#right').height() + 6;
    if(m>r){
        $('#right').css('height',m-6);
        $('.twitter').css({'position':'absolute','bottom':'27px','left':'19px'});
    }else if(r>m){
        $('#main').css('height',r+6);
    }
}

/*google map*/
function initMap(address){
  var geocoder = new google.maps.Geocoder();
  var myOptions = {
    zoom: 15,
    center: new google.maps.LatLng(-34.397, 150.644),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("gmap"), myOptions);
  geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
            custom_alert("Geocode was not successful for the following reason: " + status);
      }
    });
}

/*Képrotáló `ovjektum`*/	
image_rotator = function(name,selector){
	//VARS
	var $gallery = $(selector);        
	var $images = $gallery.find('li');
	var current = 0;
	var all = $images.length;								
	//INIT
	$images.each(function(k,v){
		$v = $(v);
		$v.css('display',(k==0)?'block':'none');
	});	
	var rotate = function(){
		$images.eq(current).fadeOut(2500);
		current = ((current+1) % all);
		//console.log(current);
		$images.eq(current).fadeIn(2500);
	}
	if( all > 1 ){
                $gallery.parent().css('background','none');
		setInterval(rotate,6500);
	}

	//PUBLIC METHODS	
	return{
		rotate: rotate		
	}
}	
