﻿var jQueryScriptOutputted = false;
var jQueryUIScriptOutputted = false;

function initJQuery() {
    
    //if the jQuery object isn't available
    if (typeof(jQuery) == 'undefined') {
    
        if (! jQueryScriptOutputted) {
            //only output the script once..
            jQueryScriptOutputted = true;
            
            //output the script (load it from google api)
            document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\"></scr" + "ipt>");            
        }
        setTimeout("initJQuery()", 50);
    } else {
    	
    	   if (! jQueryUIScriptOutputted) {
              if($.ui){ // jQuery UI is loaded                    
                    if(window.console) console.log("already loaded ui.version:  "+$.ui.version);
              } else {
              	 jQueryUIScriptOutputted = true;              	 
              	 document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js\"></scr" + "ipt>");
              	 //if(window.console) console.log("loaded ui.version:  "+$.ui.version);
              }    	   	
    	   }
         if(!jQuery().ajaxSubmit) {
         	  if(window.console) console.log("loading jquery.form.js ");
         	  document.write("<scr" + "ipt type=\"text/javascript\" src=\"maestro/client/js/jquery.form.js\"></scr" + "ipt>");         	
         }
         if(!jQuery().combobox) {
         	  if(window.console) console.log("loading ui.combobox.js ");
         	  document.write("<scr" + "ipt type=\"text/javascript\" src=\"maestro/client/js/ui.combobox.js\"></scr" + "ipt>");         	
         }  
         if(!jQuery().metadata) {
         	  if(window.console) console.log("loading jquery.metadata.js ");
         	  document.write("<scr" + "ipt type=\"text/javascript\" src=\"maestro/client/js/jquery.metadata.js\"></scr" + "ipt>");         	
         }                                        
        $(function() {  
            //do anything that needs to be done on document.ready
        });
    }         
}
initJQuery();



(function($){
   
    $.fn.maestro= function(options) {

        var defaults = { thescript: 'maestro.php',
        	 container : 'div.maestro_c:first',
           duration: 2000
        };
             	       
        $options = $.extend(defaults, options);        
        $(this).tabs({spinner: 'Retrieving data...',
        	 cache: true ,
        	  select: function(event, ui) { 
        	  	    //$(ui.panel).html('');
        	        return true; 
            },
            load: function(event, ui) {
            	    if(window.console) console.log("load: "+($(ui.panel).attr('id')));
            	    if ( $(ui.panel).attr('id') == 'tabs4' ) {
            	    } 
            	    initialiseInputWidgets($(ui.panel)); 
            }
         });

      	$("table.maestro_list tr").live("click", function(event) {
      		maestroclick($(this));
        }); 
               
        $(".maestroclick").live("click", function(event) {           	        	  
        	  maestroclick($(this));
        });
          
        $(".submit_maestro_form").live("click", function(event) {
        	
        	$(this).attr("disabled", "true");
      		event.preventDefault(); //Prevent the normal submission action
      	  var mform = $(this).parents('form:first');
      		var valid =  validateform($(mform).attr('id'));
      		
              if ( valid == true  ) {
              	
                 var submit_options = { 
                     url:  $(mform).attr('action'), 
                     type:          'post',
                     error :            function() { if(window.console) console.log("error  ");  }  ,
                     success:    function(responseText, statusText, xhr, $form) {
                     	      
                     	      var container__ = $(mform).parents($options.container);                     	       
                            container__.html(responseText);
                            initialiseInputWidgets(container__);   
                      }  
                  };
              	  $(mform).ajaxSubmit(submit_options);
              }  else {
              	   if(window.console) console.log("submit_maestro_form validation: false ");
              }
              return false;
      	});
      	
  
        
        return this.each(function() {        
        });
    };
    
    // private function
    function maestroclick(obj) {
    	
        	  var container_ = obj.parents($options.container);
        	  jQuery.metadata.setType("attr", "data");
            if ( ($(obj).metadata().rel) && ($(obj).metadata().tbl) ) {
            	if ($(obj).metadata().id) {
      		     $.post($options.thescript, { rel: $(obj).metadata().rel , obj: $(obj).metadata().tbl, id: $(obj).metadata().id }, function(data) {
            	          container_.html(data);
            	          initialiseInputWidgets(container_);
               });		
            	} else {
      		     $.post($options.thescript, { rel: $(obj).metadata().rel , obj: $(obj).metadata().tbl }, function(data) {
            	          container_.html(data);
            	          initialiseInputWidgets(container_);
               });            		         		
            	}            	
            }   	
    };
    
    function initialiseInputWidgets(container) {
    	   if(window.console) console.log("initialiseInputWidgets: "+($(container).attr('id')));
    	   container.find(".datepicker").datepicker({ dateFormat: 'yy-mm-dd' });
         // container.find("textarea").resizable({handles: "se" });
         container.find("input[hint]").each(function() {
         	  var hintId = 'hint_'+$(this).attr('name');
            $(this).after('<span id="'+hintId+'" class="hint">'+$(this).attr('hint')+'<span class="hint-pointer"> </span></span>');
            $(this).focus(function() { $('#'+hintId).show(); });
            $(this).blur(function() { $('#'+hintId).hide(); });
         });
//         container.find(".autocomplete").each(function() {
//         	         $(this).autocomplete({ source: $(this).attr('autocomplete').split(',')});
//         	 });
         
//         container.find(".combobox").each(function() {
//             if(window.console) console.log("elem combo: "+($(this).attr('combo')));
//         	   var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
//             // $(this).autocomplete({ source: $(this).attr('combo').split(',')}); 
//             $(this).combobox({ data : myArray , autoShow: false, arrowURL: 'maestro/client/drop_down.png'
//            
//             });         	   
//         }); 
    }
    
    
    // private function
    function validateform(formId) {
    	
    	  var resu = true;
        $(':input', '#'+formId).each(function() {
        	   if(window.console) console.log(this.name+" "+this.value);
        	   var p = $(this).parent();
        	   var v = $(this).parent().find('.validation');
        	   var rule = $(v).attr('rule');   
        	   if ("undefined" !== typeof rule) {  
        	   		   
        	   if (rule.startsWith('maxlen:')) {
        	        var maxlen = rule.substr(7);
        	        // if ( this.value.length > maxlen ) 
        	            if(window.console) console.log(this.name+" len: "+this.value.length+" maxlen: "+maxlen);
        	   }
        	   
        	   if (rule.startsWith('req')) {
        	   	       
        	   	       if ( (this.value).trim().length == 0 ) { 
        	   	    	     $(this).parent().find('span').html('* required field');
        	   	    	     
        	   	    	     resu = false;
        	   	    	     return false;
        	   	        }     	   	     
        	   }
        	   var value = this.value.trim();
        	   switch (rule) {
        	   	     case "req:email":
        	   	     case "email":
        	   	       if (  validateEmail(value) == false ) {  	   	     
        	   	    	     $(this).parent().find('span').html('* invalid email');
        	   	    	     resu = false;
        	   	    	     return false;
        	   	       }     	   	     
        	   	     break;
        	   	     
        	   	     case "req:phone":
        	   	     case "phone":
        	   	       if (  validatePhone(value) == false ) {  	   	     
        	   	    	     $(this).parent().find('span').html('* invalid telephone number');
        	   	    	     resu = false;
        	   	    	     return false;
        	   	       }    	   	     
        	   	     break; 	   
        	   }   
        	  }
        });
        return resu;
    };
    
})(jQuery);

function autoComplete (field, select, property, forcematch) {
	var found = false;
	for (var i = 0; i < select.options.length; i++) {
	if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
		found=true; break;
		}
	}
	if (found) { select.selectedIndex = i; }
	else { select.selectedIndex = -1; }
	if (field.createTextRange) {
		if (forcematch && !found) {
			field.value=field.value.substring(0,field.value.length-1); 
			return;
			}
		var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
		if (cursorKeys.indexOf(event.keyCode+";") == -1) {
			var r1 = field.createTextRange();
			var oldValue = r1.text;
			var newValue = found ? select.options[i][property] : oldValue;
			if (newValue != field.value) {
				field.value = newValue;
				var rNew = field.createTextRange();
				rNew.moveStart('character', oldValue.length) ;
				rNew.select();
				}
			}
		}
	}
	
	/*--------------------------------------------------------------------------*/
String.prototype.trim = function () 
{ return this.replace(/^\s*/, "").replace(/\s*$/, ""); }
/*--------------------------------------------------------------------------*/
String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)}
/*--------------------------------------------------------------------------*/
String.prototype.endsWith = function(str) 
{return (this.match(str+"$")==str)}
/*--------------------------------------------------------------------------*/
function validateEmail( strValue) {
  var objRegExp  = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;
  return objRegExp.test(strValue);
}
/*--------------------------------------------------------------------------*/
function validatePhone( strValue ) {
  var objRegExp  = /^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/;
  return objRegExp.test(strValue);
}
