/* Author: Slash2 - www.slash2.nl
	
   jQuery functions
   
*/

var emailRegExp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var phone_regexp = /(^\+[0-9]{2}|^\+[0-9]{2}\(0\)|^\(\+[0-9]{2}\)\(0\)|^00[0-9]{2}|^0)([0-9]{9}$|[0-9\-\s]{10}$)/;
var zipcode_regexp = /^[1-9]{1}[0-9]{3}\s?[a-zA-Z]{2}$/;
var bank_regexp = /^[P]{0,1}[0-9]{7,}$/;
var studentNr_regexp = /^[S]{0,1}[0-9]{5,}$/;
var file_regexp = /^.*\.(jpg|JPG)$/;
var amount_regexp = /^[0-9]{0,7}\,[0-9]{0,2}$/;

function calculateMenuOffset(){
		
	var totalMenuWidth = $("nav#menu").outerWidth();
	
	//get first element in list
	var firstLiLeft = Math.floor($("nav#menu > ul > li").eq(0).offset().left);
	
	//Recalulate the Left offset
	$("nav#menu > ul > li .dropshadow").each(function(){
		
		submenu = $(this);
		
		//check how many submenus
		subListCount = submenu.children('div.submenu').children('ul.linklist').length;
		
		if(subListCount < 4) {
			
			//width for this submenu item
			var subOuterWidth = submenu.outerWidth();
			//what is the spacing to the right?
			var spacingRight = totalMenuWidth-(subOuterWidth+2);
			
			var spacingFromLiToRight = Math.round(submenu.prev().offset().left);			
			
			var startPoint = (spacingFromLiToRight-firstLiLeft);
			
			var spaceFromStartToRight = (totalMenuWidth-startPoint);
			
			if(spaceFromStartToRight > subOuterWidth){
				//Align to start point menu item
				submenu.css("left", startPoint);
			} else {
				//Align to right
				submenu.css("left", spacingRight);				
			}
			
		}
	});
}
	
	
$(document).ready(function(){

	$('.content_tabs').tabs();

	if(document.getElementById("fb-like")){
	
		var fb = document.createElement('fb:like'); 
		fb.setAttribute("href","https://www.facebook.com/profile.php?id=207801505948937"); 
		fb.setAttribute("send","false");
		fb.setAttribute("show_faces","false");
		fb.setAttribute("width","376");

		document.getElementById("fb-like").appendChild(fb);
	}

	/* Load validation script when needed */
	/*
	if($("form").not("#login_form").length > 0){
		$.ajaxSetup({async: false});
		$.getScript(ajax_rel_path+'includes/js/validate.php?lang='+ajax_language, function() {
			$.ajaxSetup({async: true});
		});
	}
	*/
	
	$("#commissie-downloads #table_download").tablesorter({ headers: { 0: { sorter: false}, 5: {sorter: false} }}); 
	
	$("a.cofirm_file_delete").click(function(e){
		//Prevent for action
		var c = confirm("Weet je het zeker dat je dit bestand wilt verwijderen?");		
		if(!c){
			e.preventDefault();
		}
	});
	
	$("#subsite_select_url").change(function() {
		var url = $(this).val();
		
		if (url) {
			window.location = url;
        }
        return false;

	});
	
	$("#first_year").click(function(){
		
		$("#first_year_options").toggle();
		
		if($("#first_year").is(':checked')){
			
		} else {
			$("#order_books").attr("checked", false);
			$("#introkamp").attr("checked", false);
		}
		
	});
		
	$('#login_form input').keyup(function(){
		if($(this).val() == ''){
			$(this).removeClass('active');
		} else {
			$(this).addClass('active');
		}
	});
	
	if (!Modernizr.input.placeholder) {
		
		// no placeholder support
		$('#login_form input').each(function(){
			
			var placeholder = $(this).attr('placeholder'); 			
			$(this).attr("value", placeholder);
			
			//save the placeholder for this item
			$.data(this, "ph", placeholder);
			
			$(this).focus(function(){
			
				if($.data(this, "ph") == $(this).attr("value")){
					$(this).attr("value", "");
				}
			});
		});
		
	}


	$('#login_submit').click(function(){
	
		var cmsid = $('#login_cmsid'),
			lang_id = $('#login_lang_id'),
			email = $('#login_email'),
			password = $('#login_password'),
			form_valid = 1;
		
		if( email.val() != "" ){
			email.removeClass('error');
			
		} else {
			email.addClass('error');
			form_valid = 0;
		}
		
		if(emailRegExp.test(email.val())){
			email.removeClass('error');
		} else {
			email.addClass('error');
			form_valid = 0;
		}
		
		if( password.val() != ""){
			password.removeClass('error');
		} else {
			password.addClass('error');
			form_valid = 0;
		}
				
		if(form_valid == 1){
			$.ajax({
				type: 'POST',
				url: ajax_rel_path +'ajax_login_action.php',
				data: 'cmsid=' + cmsid.val() + '&lang_id=' + lang_id.val() + '&email=' + email.val() + '&password=' + password.val(),
				success: function(data) {
					
					if(data){
						if(in_webshop){
							window.location.reload();
						} else {
							$("#login_form").replaceWith(data);
						}
					} else {
						email.addClass('error');
						password.addClass('error');
					}
				}
			});	
		}
	
	});


	//
	$(".bank_type").click(function(){
		
		var bankVal = $("#bank_account").val();
		
		//check type
		if($(this).is("#bank_bank")){
			$("#bank_account").val("");			
		} else {
			//Check if first item is a P > do not add
			if(bankVal.charAt(0) != "P"){
				$("#bank_account").val("P"+bankVal);
			}
		}
		
		
	});
	
	if($("#birthdate").length > 0){
		$("#birthdate").mask("99-99-9999");
	}		
	
	
	$(".fe_fancy").fancybox({ 
		type: 'iframe', 
		titleShow: false,
		width: 780,
		height: 500
	});
	
	
	$(".open_member_info").click(function(){
		
		
		var s = this.id.replace("result_member_", "member_panel_");
		$("#"+s).slideToggle();
		
		$(this).children("span.member_info_name").toggleClass("active");
		//toggle the less info
		$(this).children("span.member_more_info").toggle();
		//toggle the more info
		$(this).children("span.member_less_info").toggle();
		
	});
	
	$("a[rel=fancy]").lightBox({
		overlayBgColor: '#000'
	});
	
	$("section.default img").imageSubscription({
		baseClass			: "imagebasesub",
		subScriptClass		: "imagebasesubtitle",
		ignoreImgWithClass	: "no_sub"
	});
	
	$('.submenu').each(function () {
		
		$(this).parent().parent().eq(0).hoverIntent({
			interval: 50,
			timeout: 0,
			over: function () {
				var current = $('.dropshadow:eq(0)', this);
				current.show();
				$("#menu_hover_overlay").show();
			},
			out: function () {
				var current = $('.dropshadow:eq(0)', this);
				current.hide();
				$("#menu_hover_overlay").hide();
			}
		});
	});
	
	$('.subsite_menu').each(function () {
		
		var menu_id = $(this).attr('id');
		
		$(this).parent().eq(0).hoverIntent({
			interval: 50,
			timeout: 0,
			over: function () {
				$('#'+menu_id).show();
			},
			out: function () {
				$('#'+menu_id).hide();
			}
		});
	});	
	
	
	//Add class and remove class for the submenu arrow
	$("nav#menu ul li a").mouseenter(function(){
		$(this).children("span").addClass("hover");
	}).mouseleave(function(){
		$(this).children("span").removeClass("hover");
	});
	
	
	$("#home_slider").easySlider(
		{ 
			controlsBefore: '<div id="home_slider_controls">',
			controlsAfter: '</div>', 
			numeric: true,
			auto: true,
			pause: 4000,
			continuous: true
		}
	);
	
	
	//Add tabs to agenda
	$("#main_agenda").tabs({
		select: function(e, u) { Cufon.replace('#main_agenda .agenda_list span');	}
	});
	
	$("#commissie-tabs").tabs();
	
	var $tabs = $("#agenda-tabs").tabs();
	
	
	//Count in JSON
	function count(obj){
		c = 0;
		for(i in obj){
			if (obj.hasOwnProperty(i)){
				c++;
			}
		};
		return c;
	
	}
	/* FORUM WRITE DOWN */
	$(".write_msg").click(function(){		
		var id = this.id.replace("write_","");		
		$("#"+id+"_form").slideToggle("medium");		
		$("#write_msg").toggleClass("active");
	});
	
	/* INTERN FORUM*/
	/* new topic */
	$(".write_topic").click(function(){		
		var id = this.id.replace("write_","");		
		$("#"+id+"_form").slideToggle("medium");
		$(this).toggleClass("bold");		
	});
	/* new reply*/
	$(".write_reply").click(function(){		
		var id = this.id.replace("_reply","");		
		$("#"+id+"_form").slideToggle("medium");
		$(this).toggleClass("bold");		
	});
	
	$(".remove_forum_msg").click(function(){
		//call confirm box
		var conf = window.confirm("Weet je het zeker dat je dit bericht wilt verwijderen?");
			
		if(conf) {
			window.location.href = sitebase + this.id;
		}
	});
	
	/*Wie betaalt wat*/
	$("#wbw_onetime").click(function(){
		$(".small_select option[value='1']").attr("selected","selected"); 
	});
	$(".open_row").click(function(){		
		var id = this.id.replace("pay_","");
		$("#payrow_"+id).slideToggle("medium");
		$(this).toggleClass("bold");
	});
	$(".remove_payment").click(function(){
		//call confirm box
		var conf = window.confirm("Weet je het zeker dat je deze betaling wilt verwijderen?");
		
		if(conf) {
			window.location.href = sitebase + this.id;
		}
	});
	$(".wbw_final").click(function(){
		//call confirm box
		var conf = window.confirm("Weet je het zeker dat je de betalingen wilt afrekenen? Alle betalingen worden hierbij verwijderd!");
		
		if(conf) {
			window.location.href = sitebase + this.id;
		}
	});
	$(".remove_file").click(function(){
		//call confirm box
		var conf = window.confirm("Weet je het zeker dat je dit bestand wilt verwijderen?");
		
		if(conf) {
			window.location.href = sitebase + this.id;
		}
	});
	$(".remove_folder").click(function(){
		//call confirm box
		var conf = window.confirm("Weet je het zeker dat je deze map wilt verwijderen? Alle onderliggende bestanden en mappen worden ook verwijderd!");
		
		if(conf) {
			window.location.href = sitebase + this.id;
		}
	});
	$("#history").click(function(){	
	 	$("#history_overview").slideToggle("medium");
		$(this).toggleClass("bold");
	});
	//print function
	$("#print_payment").click(function(){
		print_window = window.open();
		print_window.document.write("<html><head><title></title><link rel=\"stylesheet\" type=\"text/css\" href=\"/css/sIFR-print.css\"><link rel=\"stylesheet\" type=\"text/css\" href=\"/css/print.css\"></head><body>");
		print_window.document.write($('#payment_div').html());
		print_window.document.write("</body></html>");
		print_window.document.close();
		print_window.focus();
		print_window.print();
	});
	/*SMILEY*/
	var smiley_array = new Array(":)",":(",":p",":d",":r",";)",":s",":+","_O_",":w","^O^",":?","8)",":z","}>",":h",":o",":fu",":|",":*",":#",":j",":]",":b",":n","|:(");
	
	$(".smiley").click(function(){
		var id = this.id.replace("smiley", "");		
		var textarea = $("textarea#message");    
		textarea.val(textarea.val() +" "+ smiley_array[id-1]);								
	});
	
	/*UBB Tags*/
	$(".ubb_icon").click(function(){
		
		var ubb_code_start = "["+this.id+"]";
		var ubb_code_end = "[/"+this.id+"]";
		
		var textarea = document.getElementById('message');
		var txt = textarea.value;
		
		var txt_length = txt.length;
		
		if(document.selection) { //IE

			var bm = document.selection.createRange().getBookmark();
			var sel = textarea.createTextRange();
			sel.moveToBookmark(bm);
	
			var sleft = textarea.createTextRange();
			sleft.collapse(true);
			sleft.setEndPoint("EndToStart", sel);
			textarea.selectionStart = sleft.text.length
			textarea.selectionEnd = sleft.text.length + sel.text.length;
			textarea.selectedText = sel.text;
		} else { //FF	 
			var start_select = $(textarea)[0].selectionStart;
			var end_select = $(textarea)[0].selectionEnd;
				
			textarea.selectedText = txt.substring(start_select,end_select);
		}
		
				
		var replace_ubb = ubb_code_start+textarea.selectedText+ubb_code_end;
		
		$(textarea).val(txt.substring(0,textarea.selectionStart) + replace_ubb + txt.substring(textarea.selectionEnd,txt_length));
		
	});

	//check if item is in page > do getScript
	if($(".agenda_nav").length > 0){
		
		var options = { 
			items_per_page: 4, 
			prev_text: "Vorige", 
			next_text: "Volgende", 
			prev_show_always: false, 
			next_show_always: false,
			callback: parseAgendaItems
		};
	
		var totalCats = 0;
		var totalItems = 0;
		
		var totalItemsArray = new Array();
		var jsonItems;
		
		$.getJSON(ajax_rel_path+'ajax_json_agenda.php?lang='+ajax_language+"&id="+ new Date().getTime(), function(json) {
			
			jsonItems = json;
			
			for (var i = 0; i < count(json); i++) {				
				
				//Count total items
				totalItems += count(json[i]);
				
				//Count foreach element
				$("#agenda_nav_"+(i+1)).pagination(count(json[i]), options);
				
				for(var x=0; x < count(json[i]);x++) {
					totalItemsArray.push(json[i][x]);				
				}
				
			}
			
			totalItemsArray.sort(dateSort);
			
			options.callback = parseAllAgendaItems;
			$("#agenda_nav_0").pagination(totalItems, options);
			
		});
		
	}
	
	function dateSort(a, b) {
		return new Date(a.date) - new Date(b.date);
	}
	
	function parseAllAgendaItems(page_index, jq){
		
		//Parse from the complete array
		var items_per_page = options.items_per_page;
		var max_elem = Math.min((page_index+1) * items_per_page, totalItemsArray.length);
        var newItems = '';
		
		for(var i=page_index*items_per_page; i < max_elem;i++) {
			
			newItems += '<article class="agenda_item '+(i%2?"last":"")+'">';
			newItems += '<hgroup>';
			newItems += '<h2 style="display:block">'+stripslashes(totalItemsArray[i].title)+'</h2>';
			newItems += '<h3 style="display:block">'+stripslashes(totalItemsArray[i].day)+'</h3>';
			newItems += '</hgroup>';			
			newItems += '<p>'+totalItemsArray[i].text+'</p>';
			newItems += '<span>'+totalItemsArray[i].link+'</span>';
			newItems += '</article>';
        }
		
		$(jq).prev("div.agenda_items").html(newItems);
		Cufon.refresh();
		
        return false;
		
	}
    function stripslashes(str) {
        str=str.replace(/\\'/g,'\'');
        str=str.replace(/\\"/g,'"');
        str=str.replace(/\\0/g,'\0');
        str=str.replace(/\\\\/g,'\\');
        return str;
    }
	
	function parseAgendaItems(page_index, jq){
		
		var id = jq.id.replace("agenda_nav_", "")-1;
		
		var items_per_page = options.items_per_page;
		var max_elem = Math.min((page_index+1) * items_per_page, jsonItems[id].length);
        var newItems = '';
		
		for(var i=page_index*items_per_page; i < max_elem;i++) {		
			newItems += '<article class="agenda_item '+(i%2?"last":"")+'">';
			newItems += '<hgroup>';
			newItems += '<h2>'+jsonItems[id][i].title+'</h2>';
			newItems += '<h3>'+jsonItems[id][i].day+'</h3>';
			newItems += '</hgroup>';
			newItems += '<p>'+jsonItems[id][i].text+'</p>';
			newItems += '<span>'+jsonItems[id][i].link+'</span>';
			newItems += '</article>';
        }
		
		$(jq).prev("div.agenda_items").html(newItems);
		
        return false;
	}
	
	
	
	//Add class and remove class for the linklist
	$("ul.linklist li a").mouseenter(function(){
		
		$(this).addClass("hover");
		
		$(this).children("span.linklist_arrow").show();
		//check if this is the first item in the list
		if(firstInList(this)){
			$(this).addClass("borderTop");
		}
		
	}).mouseleave(function(){
		
		$(this).removeClass("hover");		
		$(this).children("span.linklist_arrow").hide();
		//check if this is the first item in the list
		if(firstInList(this)){
			$(this).removeClass("borderTop");
		}

	});
	
	function firstInList(el){
		
		$first = $(el).parent();
		
		if($first.index() == 0){
			return true;
		} else {
			return false;
		}
	}
    
	$("#export_select").click(function() {
	   var selected = new Array();
	   $(":checkbox").each( function() {
			if($(this).attr('checked') == 'checked')
                selected.push(($(this)).val())
		});
        if(count(selected) > 0)
            window.location.href = $(this).attr("href") + "&selected=" + selected;
        else
            alert('Er zijn geen velden geselecteerd');
	});
    
	$("#select_all").click(function() {
		$(":checkbox").each( function() {
				$(this).attr('checked', 'checked');
		});
	});
	
	$("#deselect_all").click(function() {
		$(":checkbox").each( function() {
				$(this).removeAttr('checked');
		});
	});
	
	
	function make_headcontact(id) {
		
		var contact = id;
		var current_head = $(".current_head").attr("id");
		var current_head_id = current_head.replace('contact_','');
		
		$.ajax({
				type: "POST",
				url: ajax_rel_path+"crm_company_action.php",
				data: "action=head_contact&contact="+contact,
				
				success: function(data){	
					//replace the text old
					$(".contact .head_contact").html("<span class=\"head_contact\"><a href=\"javascript:void(0);\" class=\"make_headcontact\" id=\""+current_head+"\">Maak hoofdcontactpersoon</a></span>");
					
					//$("#"+current_head).bind("click", function(){ make_headcontact(current_head) });
					
					//replace the text new
					$("#contact_"+contact+" .head_contact").html("<span class=\"head_contact\"><strong>Hoofdcontactpersoon</strong></span>");
					
					$(".make_headcontact").click(function(){
						contact_id = $(this).parents('.contact').attr('id');
						contact_id = contact_id.replace('contact_', '');
						
						make_headcontact(contact_id);
					});
					
				}
				
		});
		
	}
		
	$(".make_headcontact").click(function(){
		contact_id = $(this).parents('.contact').attr('id');
		contact_id = contact_id.replace('contact_', '');
		
		make_headcontact(contact_id);
	});

    //Youtube z-index fix
    $('iframe').each(function(){
    var youtubeUrl = $(this).attr("src");
    $(this).attr("src",youtubeUrl+"?wmode=transparent");
    });
});

function confirm_goto(question, url) {
	var cbox= confirm(question);
	if(cbox==true) {
		window.location=url;
	}
}

function delete_note(note_id){
	$.ajax({
			type: "POST",
			url: ajax_rel_path+"crm_note_action.php",
			data: "action=delete&note_id="+note_id,
			
			success: function(data){	
				$('#reminder_'+note_id).remove();
			}
			
	});
}

function show_multi_form(form_id){

	$('.multi_form').removeClass('visible'); 
	$('#multi_form_'+form_id).addClass('visible');

}
