var ajaxLoader   = '<img src="/assets/templates/rhz/images/ajax-loader.gif" width="16" height="16" />';
var enterPressed = false;

$(function(){

    // Kijk of de gebruiker remember me heeft:
    if(getCookie('remember-me') != null)
    {
        a = getCookie('remember-me').split('||');
        $("input#username").val(a[0]);
        $("input#password").val(a[1]);
        $("input#remember").attr("checked", "checked");
    }

    $("form.weblogin").submit(function(){
        if($("input#algemeen").attr("checked") != true)
        {
            alert('U dient akkoord te gaan met de algemene voorwaarden voor u in kunt loggen.');
            return false;
        }
    });

    if($.browser.msie && parseInt($.browser.version) <= 7)
    {
        // IE7 Quirks met JavaScript oplossen omdat IE7 crappy as HELL is!
        $("#navigation li a").each(function(){
            $(this).css({height: "auto"});
            var h = $(this).height();
            // 32: height: 48px, padding-top: 12px
            // 16: height: 38px, padding-top: 22px
            var nh = 38 + ((h-16) / 1.6);
            var np = 22 - ((h-16) / 1.6);
            $(this).css({height: nh, paddingTop: np});
        });
    }

    // Dropdowns:
    /*
    $("#navigation ul li").hover(function(){
        $("ul", this).show();
    }, function(){
        $("ul", this).hide();
    });
    */

    // Inbox:
    $("ul.tabs a").click(function(){
        idName = $(this).attr("rel");
        $("ul.tabs a, div.tab").removeClass("active");
        $(this).addClass("active");
        $("#"+idName).addClass("active");
        return false;
    });
    
	$("#subNavigation li").hover(function(){
		$(">ul", $(this)).show();
	}, function(){
		$(">ul", $(this)).hide();
	});
	
	$("table.adresgegevens tr.naam").hover(function(){
		$(this).addClass("hover");
	}, function(){
		$(this).removeClass("hover");
	}).click(function(){
		
		id = $(this).attr("id");		
		/* $("tr." + id + ":hidden").show(); */
		el = $("tr."+id);
		if(el.css("display")=="none") {
			el.show();
			$(this).addClass("active");
		} else {
			el.hide();
			$(this).removeClass("active");
		}
	});

    // Locked nieuws items:
    $("table.news span.locked").hover(function(){
        var pos = $(this).position();
        $("#lockedMessage").css({top: pos.top + 10}).show();
    }, function(){
        $("#lockedMessage").hide();
    }).click(accentLogin);
    $("#lockedMessage").hover(function(){
        $(this).show();
    }, function(){
        $(this).hide();
    }).click(accentLogin);

    // Huisartsen list
    $("#ha_nav span:not(:first)").hide();
    $("#ha_info, #ha_list").hide();
    $("#ha_nav a.ha_info").click(function(){
        $("#map, #ha_list, span.map, span.ha_list").hide();
        $("#ha_info, span.ha_info").show();
        return false;
    });
    $("#ha_nav a.ha_list").click(function(){
        $("#map, #ha_info, span.map, span.ha_info").hide();
        $("#ha_list, span.ha_list").show();
        return false;
    });
    $("#ha_nav a.map").click(function(){
        $("#ha_info, #ha_list, span.ha_info, span.ha_list").hide();
        $("#map, span.map").show();
        google.maps.event.trigger(map, 'resize');
        map.setCenter(new google.maps.LatLng(50.85, 5.7));
        return false;
    });
    if(parseInt($("var.document-id").text()) == 8)
    {
        $("#ha_nav a.ha_list").click();
    }


    // Ontvangers zoeken:
    /*
    $("input[name=ontvanger]").keydown(function(e){
        $("#suggestie").html(ajaxLoader);
        // Laad de eerste suggestie:
        $("#suggestie").load("/suggestie.html", {query: $(this).val()}, function(){
            if(enterPressed) {
                addOntvanger();
            }
        });
        if(e.which==13) {
            enterPressed = true;
            return false;
        } else {
            enterPressed = false;
            return true;
        }        
    });
    */
    
    $("input[name=add]").click(function(){
        id   = $("select[name=ontvanger]").val();
        if(id!=0) {
            name = $("select[name=ontvanger] option:selected").text();        
            addOntvanger(id, name);
        }
    });
    
    // Inschrijven voor een cursus:
    $("a.confirm").click(function(){
        var ScrollTop = document.body.scrollTop;
		if (ScrollTop == 0) {
		    if (window.pageYOffset) {
				ScrollTop = window.pageYOffset;
			} else {
				ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
			}
    	}
        $("#black").css({opacity: 0.7, height: $(document).height()}).show();
        $("#popup").css({top: ScrollTop + ($(window).height()/2 - $("#popup").height()/2) - 20}).show();
        return false;
    });
    
    $("#popup input[name=cancel]").click(function(){
        $("#black, #popup").hide();
    });
    
    if(location.hash=='#inschrijven') {
        $("a.confirm").click();
    }
    
    $("input[name=datum]").click(function(){
		if($("input[name=betaalwijze]:checked").val()!=undefined) {
			$("#popup input[type=submit]").removeAttr("disabled");
		}
    });
    
	$("input[name=betaalwijze]").change(function(){		
		$("p.hide").hide();
		$("p."+$(this).val()).show();
		if($("input[name=datum]:checked").val()!=undefined) {
			$("#popup input[type=submit]").removeAttr("disabled");
		}
	});
	
	
	// LetterSize:
	$("#utils a.normal").click(function(){ 
		$(this).blur();
		createCookie('letterSize', 'normal', 14);
		$("#navigation, #content, #footer").animate({fontSize: "1em"}); 
		return false;
	});
	$("#utils a.large").click(function(){ 
		$(this).blur();
		createCookie('letterSize', 'large', 14);
		$("#navigation, #content, #footer").animate({fontSize: "1.2em"}); 
		return false;
	});
	$("#utils a.xlarge").click(function(){ 
		$(this).blur();
		createCookie('letterSize', 'extraLarge', 14);
		$("#navigation, #content, #footer").animate({fontSize: "1.4em"}); 
		return false;
	});
	
	var letterSize = readCookie('letterSize');
	if(letterSize!=null) {
		switch(letterSize) {
			case 'normal':
				$("#navigation, #content, #footer").css({fontSize: "1em"});
				break;
			case 'large':
				$("#navigation, #content, #footer").css({fontSize: "1.2em"});
				break;
			case 'extraLarge':
				$("#navigation, #content, #footer").css({fontSize: "1.4em"});
				break;
		}
	}
    
    // Printen van formulieren:
    $("input[name=print]").click(function(){								
        var str = $("#mainForm").serialize();
        $.post($("#mainForm").attr("action")+"?print", str, function(data){
            var w = window.open("about:blank", "printWindow");
            w.document.write(data);
            w.print();
            w.close();
        });								
    });
    
    // Opslaan van een groep:
    $(".saveGroup input[name=saveGroupButton]").click(function(){
        $(".saveGroup .step1").hide();
        $(".saveGroup .step2").show();
    });
    
    $(".saveGroup input[name=saveGroup]").click(function(){
        vars = {
            ids: $("input[name=ontvangers]").val(),
            name: $("input[name=groupName]").val()
        };
        $(this).attr("disabled", "disabled");
        $.post('/index.php?id=71', vars, function(data){
            $(".saveGroup input[name=saveGroup]").removeAttr("disabled");
        });
    });
    
    $("input[name=addGroup]").click(function(){
        id   = $("select[name=groep]").val();
        if(id!=0) {
            $.post('/index.php?id=72', {group: id}, function(data){
                items = data.split('||');
                $(items).each(function(){
                    info = this.split('::');
                    addOntvanger(info[0], info[1]);
                });                
            });
        }
    });
    
    // Delimiters van tekst:
    // Een tekst wordt gespleten door '<p>---</p>'    
    tag = $(".innerContent p:contains(---)").replaceWith('<p class="delimiter"><a href="#" class="readMoreContent">Lees verder...</a></p>');
    if(tag.text()=='---') {
        // Hide all other paragraphs:
        var hideNow = false;
        $(".innerContent p").each(function(){
            if(hideNow) {
                $(this).hide();
            }
            if($(this).hasClass("delimiter")) {
                hideNow = true;
            }
        });
        // $(".innerContent p:not(:first):not(:first)").hide();
        $("a.readMoreContent").click(function(){
            $("p.delimiter").remove();
            $(".innerContent p").show();
            return false;
        });
    }
	
	// Safari remove title:
	$(".bottom a").removeAttr("title");
	
	// Cursus filter:
	$("#cursusFilter input[type=checkbox]").change(function(){
		/*
		checked = $(this).attr("checked");
		id      = $(this).attr("name").split('_')[1];
		$(".cursus").each(function(){
			ids = $("var.ids", this).text().split(',');
			if(in_array(id, ids)) {
				if(checked) {
					$(this).show();
				} else {
					$(this).hide();
				}
			} 
		});
		*/
		runFilters();
	});
	runFilters();
});

function runFilters()
{
	active = [];
	$("#cursusFilter input[type=checkbox]").each(function(){
		if($(this).attr("checked")) {
			active.push($(this).attr("name").split('_')[1]);
		}
	});
	
	$("div.cursus").each(function(){
		$(this).hide();
		ids = $("var.ids", this).text().split(',');
		for(i=0; i<active.length; i++) {			
			if(in_array(active[i], ids)) {
				$(this).show();
				break;
			}
		}
	});
}

function addOntvanger(id, name)
{
    if(id!=undefined) {
        ids = $("input[name=ontvangers]").val();
        if(ids=='') {
            idArray = [];
        } else {                
            idArray = ids.split(',');
        }
        if(!in_array(id, idArray) && id!=0) {
            idArray.push(id);
            ids = idArray.join(',');
            $("input[name=ontvangers]").val(ids);
            $("#ontvangersVisual li.none").remove();
            $("#ontvangersVisual ul").append('<li class="ontvanger">'+name+' <a href="#" rel="'+id+'">X</a></li>');
            $("li.ontvanger a").unbind("click");
            $("li.ontvanger a").click(function(){
                id  = $(this).attr("rel");
                ids = $("input[name=ontvangers]").val();
                idArray = ids.split(',');
                newArray = [];
                for(i=0; i<idArray.length; i++) {
                    if(idArray[i]!=id) {
                        newArray.push(idArray[i]);
                    }
                }
                ids = newArray.join(',');
                if(newArray.length==0) {
                    $("#ontvangersVisual ul").append('<li class="none"><em>Geen ontvangers geselecteerd</em></li>');
                    $(".saveGroup step2, .saveGroup").hide();
                }
                $("input[name=ontvangers]").val(ids);
                $(this).parent().remove();
                return false;
            });
            $("#suggestie").text('');
            $("input[name=ontvanger]").val('');
            $(".saveGroup, .saveGroup .step1").show();
            $(".saveGroup .step2").hide();
        }
    }
	
}

function in_array( what, where ) {
    var a=false;
    for(var i=0;i<where.length;i++) {
        if(what == where[i]) {
            a=true;
            break;
        }
    }
    return a;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function accentLogin()
{
    $("#lockedMessage").hide();
    blinkLogin(10);
}

function blinkLogin(nr)
{
    if(nr % 2 == 1) {
        $("form.weblogin").css({background: '#fff'});
    } else {
        $("form.weblogin").css({background: 'none'});
    }
    if(nr != 0)
    {
        setTimeout("blinkLogin("+(nr-1)+")", 100);
    }
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}
