jQuery(document).ready(function ($) {
	// NOTE this runs on every non-admin page but for admin users
	/*   
	genolve_customize_class -	if we find CLASS:gnlv_wpadmin_links, rejigger those to start up eloop.HTMLswap mode, passing in an id like: 				
			wp-admin-bar-gnlv_header
	the last word being the tag to customize
		 
	*/
	genolve_customize_class = function() {
		var self=this;
		var verbose=false;
		var vpr={name:'stub',vprint:function(tag,stuff){if(verbose)console.log(stuff);} ,dumpvar:function(inval){return JSON.stringify(inval)}};
		if(typeof eloop!='undefined' && eloop.pvpr !=null)
			vpr=eloop.pvpr;
		self.htmlTargetSvg=null;
		self.blockid=null;
		if(typeof(eloop)=='undefined' || eloop.version=="stub")
			;
		else
			self.htmlTargetSvg=eloop.htmlTargetSvg;
		//
		// These scripts are needed by the   =   G E N O L V E     D E S I G N     E D I T O R   =	 
		// The design editor is a service provided by genolve.com
		// 
		js_list = [  		 
			"jquery-validation-1.9.0/jquery.validate.js",
			"jquery.metadata.js",
			"js.cookie.js",
			"jquery.cookie.js",
			"jquery.browser.min.js",
	//		"/js/jquery-ui.min.js",
			"dat.gui.min.js",
			"d3/d3.min.js",
			"genolve-vector.js",
			"genolve-3rdparty.js",
			"genolve-utils"+(genolveO.GENOLVE_VER=="notset"?'':genolveO.GENOLVE_VER)+".js",
			"genolve-physics-native.js",
			"genolve-sound.js",
			"bootstrap-multiselect.js",
			"jquery.ui.touch-punch.min.js",
			"/jquery-emoji-picker/js/jquery.emojipicker.js",
			//20200422 combined "/jquery-emoji-picker/js/jquery.emojis.js",
			//20190512 moved plugin local
			//"bootstrap-4.0.0/js/popper.min.js",// '//cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js',
			//"bootstrap-4.0.0/js/bootstrap.min.js",// '//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js',
			"snap-0.5.1.js",
			"sheppard.js",
			"genolve-eloop"+(genolveO.GENOLVE_VER=="notset"?'':genolveO.GENOLVE_VER)+".js"];
		css_list = [
			//20190512 still need jq styles! https://stackoverflow.com/questions/8849684/wordpress-jquery-ui-css-files
			"js/jquery-ui.min.css",
			"css/gnlvStyles.css",
			"jquery-emoji-picker/css/jquery.emojipicker.css",
			"jquery-emoji-picker/css/jquery.emojipicker.tw.css",
			"css/oswald_font.css"
			//20190512 moved to plugin's local js directory
			//"open-iconic/font/css/open-iconic-bootstrap.css",
			//"bootstrap-4.0.0/css/bootstrap.min.css"//'//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'
			];
		//
		// dynaload - dynamic load javascript and styles
		//
		// alternate methode $.getScript()
		this.dynaload =  function(basepath,filename){
        var mytype = filename.match(/css$/)? "link":"script";
				vpr.vprint("card","genolve-customize = = = loading:"+basepath+filename);
        var script = document.createElement( mytype );
				if(mytype=="script")
        	script.setAttribute( "src", basepath+filename );
				else {
					script.setAttribute( "href", basepath+filename );
					script.setAttribute( "type", "text/css" );
					script.setAttribute( "rel", "stylesheet" );
					}
        document.getElementsByTagName( "head" )[0].appendChild( script );
      	}; // end dynaload
			//
			// startupGenolve - start up genolve with link id providing start mode
			//
			//this function is a click callback for the page dropdown (set below)
			this.startupGenolve= function (myid,blockid){
					/*	e.cancelBubble = true;
						e.returnValue = false;
						e.stopPropagation();
						e.preventDefault();*/
				console.log("genolve-customize.startupGenolve = = = this nodename:"+$(this).prop('nodeName') +" passed arg:"+myid+ " blockid:"+ blockid+" beyonce_customize:"+genolveO.beyonce_customize );
				if(myid==null || typeof(myid)=="object")
					myid=$(this).parent().prop('id');
					//                                         start:wp-admin-bar-gnlv_element
					vpr.vprint("card","genolve-customize = = = parent id:"+myid);
					if(myid=="wp-admin-bar-gnlv_falling" && document.fallingtimeout!=null) {// clear it 
						clearTimeout(document.fallingtimeout);
						document.fallingtimeout=null;
						}
					//alert('genolve_customize ahah it worked, id:'+myid+ " have eloop?"+typeof(eloop));
					if(typeof(eloop)=="undefined"||eloop.version=="stub"){// load now and hope it is ready by callback!
							vpr.vprint("card","genolve-customize = = = eloop was not defined! loading it now ! = = =");
							// LOAD CSS    LOAD CSS   LOAD CSS
							for(ii=0;ii<css_list.length;ii++)
								self.dynaload(genolveO.jsbasedir,css_list[ii]);
							for(ii=0;ii<js_list.length;ii++)
								self.dynaload(genolveO.jsbasedir,js_list[ii]);
						} // end dynaload
					self.htmlTargetSelector = myid;
					self.blockid = blockid;
					vpr.vprint("card","genolve-customize = = = calling check apikey, wpAjaxUrl:"+self.wpAjaxUrl);
					//self.elsubmit({action:self.wpAjaxUrl, paction:self.actionZ.replace(/ZlistControl/,"track"),CMD:"checkapikey",apikey:apikey, redir:"JSON"},self.setupHtmlTemplate,"dontAbortOld");
					// damn
					$.ajax({
									url : self.wpAjaxUrl,
									type : 'post',
									//async: false,
									dataType : 'json',
									data : {
										action : 'genolve_proxy',
										faction : 'track',
										beyonce_customize: self.beyonce_customize,
										CMD:'checkapikey',
										keylist:'CMD,faction,beyonce_customize'
									},
									//                                              S U C C E S S
									success :function(payload){
										console.log("genolve_customize apikey callback START do I have id:"+self.htmlTargetSelector+ " have blocktype?"+myid+" have eloop?"+typeof(eloop)+" document.eloop?"+typeof(document.eloop));
										self.beyonce_customize = payload.beyonce_customize;
										// start watching for SVG
										$(window).on('eloopsvgready',function(evt){
											vpr.vprint("card","^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
											vpr.vprint("card","genolve_customize reports svg ready should fire block.setBackground:"+evt.message);
											self.htmlTargetSvg=evt.message;
										});
										// sometimes not ready, watch for load event
										if(typeof(eloop)=="undefined"||eloop.version=="stub"){
											$(document).on("eloopready",function(){ // 
												vpr.vprint("card","genolve_customize apikey callback CASE:slow eloopready , do I have id:"+self.htmlTargetSelector+" payload:"+payload);
												payload.htmlTargetSelector=self.htmlTargetSelector;
												payload.blockid           =self.blockid;
												payload.blocktype         =myid;
												payload.wpAjaxUrl         =self.wpAjaxUrl;
												eloop.wp_action(payload);
												});
											}
									
										else { // good2go
											vpr.vprint("card","genolve_customize apikey callback CASE:STANDARD good2go, nonce:"+payload.beyonce_customize+" version:"+eloop.version);
											payload.htmlTargetSelector=self.htmlTargetSelector;
											payload.blockid           =self.blockid;
											payload.blocktype         =myid;
											payload.wpAjaxUrl         =self.wpAjaxUrl;
											eloop.wp_action(payload);
											}
									},// end success
									//                                              E R R O R
									error   :function(jqhdl, textStatus, errorThrown)     { 
										alert("ajaxSubmitProxy: There was an Error!"+errorThrown)   ; 
										},
									complete:function()     {  }
									}); //end ajax call
					}; // end startupGenolve
		// START     S T A R T   
		admlink = $('.gnlv_wpadmin_links'); //look for admin links and set click handler
		self.wpAjaxUrl = genolveO.wpajaxurl;
		self.beyonce_customize = genolveO.beyonce_customize;
		if(admlink.length>0){
			// the HREF will be ajax link: get then reset
			self.wpAjaxUrl = admlink.first().find('a').prop('href');
			admlink.find('a').prop('href','#');
			console.warn("genolve:found no templatediv or cardsdiv, configure search mode handler or admin link? "+admlink.length+" wpajax?"+self.wpAjaxUrl);
			// CLICK  handler  gnlv_wpadmin_links            CLICK   handler    gnlv_wpadmin_links
			// CLICK  handler  gnlv_wpadmin_links            CLICK   handler    gnlv_wpadmin_links
			admlink.find('a').off('click.gnlv').off('click').on('click.gnlv',self.startupGenolve);
			} // end had admin links
		else
			console.log("genolve:found no admin links gnlv_wpadmin_links .. check for cardsdiv");
		//look for cards div
		if($('#cardsdiv').length>0){
			console.log("genolve:found cardsdiv! starting Genolve");
			self.startupGenolve();
			}
	} // end class
	genolve_customize =  new genolve_customize_class(); // Execute immediately
});