/* +------------------------------------------------------+
 * |                      pPPa                            |
 * |                    pPPAPPp                           |
 * |                   APP  PPa                           |
 * |                  APA  pPP  PapA  PapA                |
 * |                 PPA   APA pP  P pP  P                |
 * |             APPPPPPPA PPp Ap Ap Ap Ap                |
 * |             apPPA    aPP  P     P                    |
 * |              APA     pPP  p     p                    |
 * |             pPP      PPA                             |
 * |             PPp      PPPp                            |
 * |                                                      |
 * | Created by:    App Software                          |
 * | Email:         info@appsoftware.nl                   |
 * | Web:           http://www.appsoftware.nl/            |
 * |                                                      |
 * +------------------------------------------------------+
 * 
 */

MEB = {};

MEB.Main = function() {
        
    var main_config = {};
    
    return {
		/**
         * 
         */
        init : function(config) {            
            main_config = config;
			
            /**
             * Init the help window for MEB
             */
            if ($('.meb_help_text') && $('.meb_help_text').length == 1) {                
                this.showHelpMsg( $('.meb_help_text').html(), 'Mijn eigen bibliotheek - Help' );
                
        		$('#dlg_btn_close_help').click(function() {
        			$('#help_dialog').dialog('close');        			
        		});
        
        		$('#dlg_btn').toggle(function() {
                	$('#help_dialog').dialog('open');
                	return false;
            	},function() {
                	$('#help_dialog').dialog('close');
                	return false;
            	});
            	
            	$('#dlg_btn').css('display', 'block');
            }

        	// Set background image with phrase if resolution is 
        	// larger then 1280
			var int_rand_image = Math.ceil(Math.random()*6);
        	
        	if ($('body').width() >= 1280) {
    	    	$('body').css({
    	    		backgroundImage: 'url("system/meb/template/meb/images/bg_body_phrase'+int_rand_image+'.png")', 
    	       		backgroundPosition: 'top center',
    	       		backgroundRepeat: 'no-repeat'
    	     	});        					
    		} else {
				$('body').css({
					backgroundImage: 'none'
				});
			}
        	
			$(window).resize(function(){
				if ($('body').width() >= 1280) {
        	    	$('body').css({
        	    		backgroundImage: 'url("system/meb/template/meb/images/bg_body_phrase'+int_rand_image+'.png")', 
        	       		backgroundPosition: 'top center',
        	       		backgroundRepeat: 'no-repeat'
        	     	});        					
        		} else {
					$('body').css({
						backgroundImage: 'none'
					});
				}
			});
			
        	// 
        	$('#btn_font_resize').click(function() { MEB.Main.switchMEBStyle(true); return false; });        	
        	$('#meb_library_select').click(function() { MEB.Main.toggleLibrarySelect(); return false; });
        	$('a#btn_show_library_select_active').click(function() { MEB.Main.toggleLibrarySelect(); return false; });
        	$('a#btn_close_libray_select').click(function() { MEB.Main.toggleLibrarySelect(); return false; });
        	$('a#btn_meb_site_search').click(function() { MEB.Main.toggleSearchSite(); return false;	});       	
        	$('a#btn_meb_site_search_active').click(function() { MEB.Main.toggleSearchSite(); return false; });
        	
        	// Change the correct style if we need to.
        	MEB.Main.switchMEBStyle();
        },
		/**
		 * 
		 */
		printPage : function() {
			window.open("http://www.mijneigenbibliotheek.nl/printen","Printvriendelijk","width=550,height=400,scrollbars=yes");
		},
		/**
		 * 
		 */
		printMe: function() {
//			document.getElementById("meb_print_top").innerHTML = "<table class='printTable'>"+window.opener.document.getElementById("meb_main_panel_right").innerHTML+"</table>";

			document.getElementById("meb_print_top").innerHTML = window.opener.document.getElementById("meb_main_panel_right").innerHTML;			
			document.getElementById("meb_print_middle").innerHTML = window.opener.document.getElementById("meb_sub_left2").innerHTML;			
//			document.getElementById("meb_print_bottom").innerHTML = window.opener.document.getElementById("meb_sub_left1").innerHTML;									
			
			document.getElementById("meb_breadcrumb_bar").innerHTML = window.opener.document.getElementById("meb_breadcrumb_bar").innerHTML;			
			
			
			$('body').css({
				backgroundImage: 'none'
			});
		},
		/**
		 * 
		 * @param {Object} field
		 */
		setLastLogin : function() {
			if ($('body').hasClass('profile_active')) {
				var previous_login = MEB.Main.getUA('previous_login');
				
				if (previous_login) {
					$('#meb_lastlogin_bar').html('Laatste keer ingelogd: '+previous_login);
					$('#meb_lastlogin_bar').show();
					$('#meb_breadcrumb_bar').hide();				
				}				
			}
		},
        /**
         * 
         */
        get : function(field) {
            if (main_config[field]) {
                return main_config[field];            
            }
            return;
        },
        /**
         * 
         */
        getUA : function(attr) {            
            return BART.Front.Util.getUA(attr);
        },
        /**
         * 
         */
        setUA : function(attr) {
            return BART.Front.Util.setUA(attr);
        },
        /**
         * 
         */
        toggleLibrarySelect : function() {
            $("#meb_library_select_dialog").toggle();
        },
        /**
         * 
         */
        toggleSearchSite : function() {
            $("#meb_site_search_window").toggle();
        },
        /**
         * 
         */
        switchMEBStyle : function(bln_change_style) {        	
        	var c = BART.Front.Util.readCookie('style');
        	
        	if (c == null || c == undefined || (c != 'normal' && c != 'normal_large')) {
                c = 'normal'; 
        	}
        	
            if (bln_change_style) {
                c = ((c == 'normal_large') ? 'normal' : 'normal_large');            	
   	        }
   	        
   	        BART.Front.Util.switchStyle( c );
   	        
   	        if (bln_change_style) {
   	            BART.Front.Util.createCookie('style', c, 365);
   	        }   	        
        },
        /**
         * 
         */
        selectTheme : function(str_theme) {
    		$('a.btn_sfeer').each(function(i) {
        		if ((this.id == 'btn_'+str_theme)) {
        		    BART.Front.Util.setTheme(str_theme);
        		}
        		$(this).toggleClass('btn_sfeer_active');
        	});            
    		return false;
    	},
		/**
		 * 
		 * @param {Object} str_message
		 * @param {Object} str_title
		 */
		showMebDialog : function(dialog_id, str_message, dialog_width, dialog_height, str_title, dialog_resizable, position) {
			if (str_message) {    	
				if (dialog_resizable == undefined) {
					dialog_resizable = true;
				}
				
				if ($('#'+dialog_id).length > 0) {    	        	
					$('#'+dialog_id).html(str_message);					
				} else {
					$('body').append("<div id='"+dialog_id+"'>"+str_message+"</div>");
				}
    	        
				var options = {
        		    title: str_title,
		            resizable: dialog_resizable,
        			width: dialog_width,
        			height: dialog_height,
					minWidth: 320, 
					maxWidth: 1024,
					autoOpen: false,					
					buttons: {
		                "Sluiten": function(e) { $(this).dialog("close"); }
		            }					
        		}
				if (dialog_resizable != undefined) {
					options.position = position;					
				}
				
    	        $('#'+dialog_id).addClass('flora').dialog(options);
				$('.flora button').css({'z-index' : 200});
				
				$('.flora button').addClass('btn_main btn_orange btn_medium');
				$('.flora button').hover(function() { $(this).toggleClass('btn_medium_hover') },function() { $(this).toggleClass('btn_medium_hover') });
				$('.ui-dialog-buttonpane').append('<div class="filler1"></div>');
				$('.ui-dialog-buttonpane').append('<div class="filler2"></div>');
				$('.ui-dialog-buttonpane').append('<div class="filler3"></div>');
    	    }
		},
    	/**
    	 * 
    	 */
    	showSaveMsg : function(str_message, str_title) {    	    
    	    if (str_message != null && str_message) {    
				if (str_title == undefined) {
					str_title = '';
				}				        
    	        this.showMebDialog('meb_msg_box', '<span>'+str_message+'</span>', 360, 200, str_title);
				$('#meb_msg_box').dialog('open');
    	    }
    	},
    	/**
    	 * 
    	 */
    	showHelpMsg : function(str_message, str_title) {    	    

			if (str_message) {
				var int_begin_point = Math.ceil(( ((screen.width - 17) - $('#meb_library_bar').attr('offsetWidth')) / 2));
				
				var title = (pagetitle ? pagetitle : $(document).attr('title'));
				
				this.showMebDialog('help_dialog', str_message, 780, 265, 'HELP - ' + title, true, [int_begin_point, 55]);				
			}
			return;
    	},
    	/**
    	 *
    	 */
    	librarySearch : function() {
    		return false;
    		
    		if (val) {
    			BART.Front.Util.json_call('http://localhost/meb/index.php?q='+val, {});
    		}    		
    	},
    	/**
    	 * 
    	 */
    	doLibrarySearch : function() {

    		var val = $('#vubis_search').attr('value');
    		
    		//val = val.replace(' ', '%20');
    		
    		window.location = 'http://zoeken.mijneigenbibliotheek.nl/?q='+val;
    		
    		return false;
    	},
    	/**
    	 * 
    	 */
    	submitSearchEnter : function(myfield,e) {
    		var keycode;
    		if (window.event) keycode = window.event.keyCode;
    		else if (e) keycode = e.which;
    		else return true;

    		if (keycode == 13) {
    			MEB.Main.doLibrarySearch();
    		   return false;
    		} else {
    		   return true;
    		}

    	},
		/**
		 * 
		 */
		fixGids2Phone : function(phone_number) {
			var tel_vast_regex 			= new RegExp("^(0|0031|310|\\+31)(\\(0\\)|[\\s\\-])?" +
				"(10|111|113|114|115|117|118|13|15|161|162|164|165|166|167|168|172|174|180|181|182|183|184|186|187|" +
				 "20|222|223|224|226|227|228|229|23|24|251|252|255|26|294|297|299|" +
				 "30|313|314|315|316|317|318|320|321|33|341|342|343|344|345|346|347|348|35|36|38|" +
				 "40|411|412|413|416|418|43|45|46|475|478|481|485|486|487|488|492|493|495|497|499|" +
				 "50|511|512|513|514|515|516|517|518|519|521|522|523|524|525|527|528|529|53|541|543|544|545|546|547|548|" +
				 "55|561|562|566|570|571|572|573|575|577|578|58|591|592|593|594|595|596|597|598|599|" +
				 "70|71|72|73|74|75|76|77|78|79)[\\s\\-]?([0-9]{6,7})$");
			
			m = tel_vast_regex.exec(phone_number);
   			
			if(m != null) {
				phone_number =  '0' + m[3] + ' ' + m[4];	
			} else {
				phone_number = phone_number.replace('+31', '0');	
			}
			
			return phone_number;
		}
    }
}();

MEB.Dashboard = function() {
    var currentGidsItems = {};
	
    return {
        /**
    	 * 
    	 */
    	selectGidsItem : function(selector_id, selected_value, save_option) {    		

    		if (selected_value != '0') {
    			if(currentGidsItems[selector_id] != null && currentGidsItems[selector_id] != selected_value) {
					$('#gids_item'+selector_id.substring(9) + currentGidsItems[selector_id]).hide();
				}
				
				$('#gids_item'+selector_id.substring(9) + selected_value).show();
    			
				var field;
				if(selector_id.indexOf('selopengi') != -1) {
					field = 'gids_openinghours_org_id';	
				} else {
					field = 'gids_address_org_id';
				}
				
			if (save_option == undefined) {
			    var save_option1 = true;					
			} else {
			    var save_option1 = save_option;
			}
													
			if (save_option1 == true) {
        		    if (MEB.Main.getUA(field) != selected_value) {				
    				var param = {};
					param[field] = selected_value;
					MEB.Main.setUA(param);
    			    }
			}	
				currentGidsItems[selector_id] = selected_value;
    		}
    	},
    	/**
    	 * 
    	 */
    	selectDashboardItem : function() {
            $('.dashboard_select_address').each( function(){
                
                //console.log(MEB.Main.getUA('gids_address_org_id'));
                
                //MEB.Dashboard.selectGidsItem('seladdrgi<?smarty $rnd ?>', MEB.Main.getUA('gids_address_org_id'))
            });
    	},
    	/**
    	 * 
    	 */
    	toggleDashItem : function(btn_id, div_id) {    		
    		var div = $('#'+div_id);
    		
    		$('#'+btn_id).toggleClass('dashboard_expand_image_open');
    		
    		if(div.css('display') == 'none') {
    			div.fadeIn(); //'fast'
    		} else {
    			div.hide();
    		}   		
    	}
    }
}();

MEB.Interest = function() {
	
	var interest_config = {};

	return {			
		/**
		 *
		 */
		init : function(config) {
			
			interest_config = config;
			
			/**
			 * Initialize the Tabs for interestprofile selection
			 */
			$("#interestChoices > ul").tabs();
			
			$('li a.open_categ').click(function() {
				// Enable a category 
				if($('#categ_arrow' + this.id.substring(12)).hasClass('arrow_ok')) {
					MEB.Interest.removeCategory( this.id.substring(12) );
				} else {
					MEB.Interest.addCategory( this.id.substring(12) );	
				}				
			});
			
			$('li a.select_categ').click(function() {
				// Unfold a new category layer
				MEB.Interest.openCategory( this.id.substring(6), 0);
			});
			
			// Change css attributes when we move over it with our mouse
//			$('li.categorylist').mouseover(function(i) { 
//				$('#addimg'+this.id.substring(10)).css('visibility', 'visible'); 
//			});	        	
//        	$('li.categorylist').mouseout(function(i) { 
//        		$('#addimg'+this.id.substring(10)).css('visibility', 'hidden'); 
//        	});	        	
//        	$('li.subscribedlist').mouseover(function(e) { 
//				$('#remimg'+this.id.substring(14)).css('visibility', 'visible'); 
//			});	        	
//        	$('li.subscribedlist').mouseout(function(e) { 
//        		$('#remimg'+this.id.substring(14)).css('visibility', 'hidden'); 
//        	});
        	
        	// 
        	$('li a.rem_lnk').click(function() {
				MEB.Interest.removeCategory( this.id.substring(6), 0);
			});
		},
		/**
		 *
		 */			
		openCategory : function(id, level) {			
			$('#subCategoriesDiv'+(level)+' a.open_categ').removeClass('current');				
			$('#opencatlnk' + (level) + '_' + id).addClass('current');
			
			BART.Front.Util.json_call( MEB.Main.get('SCRIPT_NAME')+'?id='+MEB.Main.get('page_id')+'&pi='+interest_config.panel_item_id+'&pida=yes&action=get_categories_ajax', 
				'category_id='+id, 
				function(response) {
					if(response.status && response.status == "200") {
						jsondata = Ext.util.JSON.decode(response.responseText);
					
						level++;
						
						var html 	= '<ul id="list'+level+'">';
						
						for(var i=0; i<jsondata.categories.length; i++) {
							var name = BART.Front.Util.truncate(jsondata.categories[i].name, 40);
						
							html += '<li class="categorylist" id="categ_list'+jsondata.categories[i].category_id+'">'+
									'<div id="categ_arrow'+jsondata.categories[i].category_id+'" class="categ_arrow '+(jsondata.categories[i].active == 1 ? 'arrow_ok' : '')+'"></div>'+
									(jsondata.categories[i].has_subcategories == true ? '<a id="opencatlnk' + level + '_' + jsondata.categories[i].category_id + '" title="'+jsondata.categories[i].name+'" class="open_categ">' + name + '</a>' : '<a class="open_categ nochild" id="opencatlnk' + level + '_' + jsondata.categories[i].category_id + '" title="'+jsondata.categories[i].name+'">'+name+'</a>')+
									(jsondata.categories[i].has_subcategories == true && level < 2 ? '<a id="addimg'+jsondata.categories[i].category_id+'" href="#avail_categ" class="select_categ"><img border="0" src="'+MEB.Main.get('WEB_ROOT')+'system/meb/template/meb/images/btn_interest_add.png" align="absmiddle"></a>' : '')+
									'</li>';
						}
						html += '</ul>';
						
						$('#subCategoriesDiv'+level).html(html);							
						
						$('#subCategoriesDiv'+level+' li.categorylist').mouseover(function(i) { 
//							$('#addimg'+this.id.substring(10)).css('visibility', 'visible'); 
							$(this).css({cursor: 'hand', cursor: 'pointer'});
						});
			        	$('#subCategoriesDiv'+level+' li.categorylist').mouseout(function(i) { 
//			        		$('#addimg'+this.id.substring(10)).css('visibility', 'hidden'); 
			        		//$(this).css({cursor: 'default'});
			        	});
						
			        	$('#subCategoriesDiv'+level+' li a.open_categ').click(function() {
							if($('#categ_arrow' + this.id.substring(12)).hasClass('arrow_ok')) {
								MEB.Interest.removeCategory( this.id.substring(12) );
							} else {
								MEB.Interest.addCategory( this.id.substring(12) );	
							}		
						});
						
						if (level != 2) {
							$('#subCategoriesDiv'+level+' li a.select_categ').click(function() {								
								MEB.Interest.openCategory( this.id.substring(6), (level));
							});
							
							var nextDiv = $('#subCategoriesDiv'+(level+1));
							
							if(nextDiv != null) {
								nextDiv.html('');;
							}
						}
					}	
				});
		},	
		/**
		 *
		 */
		addCategory : function(id) {
			BART.Front.Util.json_call( MEB.Main.get('SCRIPT_NAME')+'?id='+MEB.Main.get('page_id')+'&pi='+interest_config.panel_item_id+'&pida=yes&action=add_category_ajax', 
				'category_id='+id, 
				function(response) {
					if(response.status && response.status == "200") {
						jsondata = Ext.util.JSON.decode(response.responseText);
						
						if(jsondata.max_categories > 0) {					
							MEB.Main.showSaveMsg('U kunt maximaal '+jsondata.max_categories+' categorie'+BART.Front.Util.html_entity_decode('&euml;')+'n selecteren!');
						} else if(jsondata.already_subscribed) {
							MEB.Main.showSaveMsg('Categorie "'+jsondata.category.name+'" is reeds in uw profiel opgenomen.');
						} else if(jsondata.refined) {
							$('#categ_arrow' + id).addClass('arrow_ok');
							$('#categ_count').html(''+jsondata.subscribed.length);
							MEB.Interest.updateSubscribed(jsondata.subscribed);
							MEB.Main.showSaveMsg('U doet een verfijning van een reeds gekozen categorie.\nCategorie "'+jsondata.category.name+'" is aan uw profiel toegevoegd.');
						} else {
							$('#categ_arrow' + id).addClass('arrow_ok');
							$('#categ_count').html(''+jsondata.subscribed.length);
							MEB.Interest.updateSubscribed(jsondata.subscribed);
						}
					}	
				});
		},
		/**
		 *
		 */
		removeCategory : function(id) {
			BART.Front.Util.json_call( MEB.Main.get('SCRIPT_NAME')+'?id='+MEB.Main.get('page_id')+'&pi='+interest_config.panel_item_id+'&pida=yes&action=rem_category_ajax', 
				'category_id='+id,
				function(response, request) {											
					if(response.status && response.status == "200") {
						jsondata = Ext.util.JSON.decode(response.responseText);
						
						if($('#categ_arrow' + id) != null) {
							$('#categ_arrow' + id).removeClass('arrow_ok');	
						}						
						$('#subscribe_list'+id).remove();
						
						$('#categ_count').html(''+jsondata.subscribed.length);
					}	
				});
			
		},
		/**
		 *
		 */
		updateSubscribed : function(subscribed) {
			var subscribed_html = '<ul>';
			
			for(var i=0; i<subscribed.length; i++) {
				subscribed_html += '<li class="subscribedlist" id="subscribe_list'+subscribed[i].category_id+'">'+
									'<div class="categ_arrow"></div>'+		
									'<a href="#remove_categ" id="remlnk'+subscribed[i].category_id+'" class="rem_lnk" title="'+subscribed[i].name+'">'+subscribed[i].name+'</a>'+
									'<a href="#remove_categ" class="rem_categ"></a>'+ //<img src="">
									'</li>';
			}
			subscribed_html += '</ul>';
			
			$('#tab_select_categ').html(subscribed_html);
			
			$('li a.rem_lnk').click(function() {
				MEB.Interest.removeCategory( this.id.substring(6), 0);
			});
		}
	};
}();

String.prototype.parseJSON = function() {
	if (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(this.
    	replace(/\\./g, '@').
        replace(/"[^"\\\n\r]*"/g, ''))) {

    	j = eval('(' + this + ')');

        return j;
    }
    return;
}


