// EVENTS
Event.observe( window, 'load', function(){
});


// LINKS
var Link = {  
  validate_form: function( f ){
    f.submit();
  }
};

// NOTE 
var Note = {
  validate_form: function( form ){
    form.submit();
  }
}

// TABBED FORM
var TabbedForm = {
  initialize: function(){
    $$('.tab.active').each( function( tab ){
      name = tab.id.replace("_tab","");
      TabbedForm.show_sidebar( name );
    });
    jQuery('a[rel*=facebox]').facebox();
  },
  cancel: function(){
    history.back(-1);
  },
  tabs: function(){
    return $$('.tab');
  },
  show_tab: function( id ){
    this.tabs().each( function( e ){
      var name = e.getAttribute('name');
      if( name == id ){
        $( "panel_" + name ).show();
        $( e ).removeClassName('inactive');
        $( e ).addClassName('active');
        
        TabbedForm.show_sidebar( name );
      }else{
        $( "panel_" + name ).hide();
        $( e ).removeClassName('active');
        $( e ).addClassName('inactive');
      }
    });
  },
  show_sidebar: function( name ){
    try { 
      $("sidebar").innerHTML = $( "sidebar_" + name ).innerHTML;
    }catch( e ){
      try{ $("sidebar").innerHTML = ""; }catch(e){ }
    }
  }
};

// USER
var User = {
  validate_form: function( form ){
    form.submit();
  }
};

// COMMENT
var Comment = {
  prepare_leave_comment_links: function(){
    $$('.leave_comment_link').each( function( link ){
      link.onclick = function(){
        $( this.id + "_comment_form" ).show();
        this.hide();
        Effect.ScrollTo( this.id + "_comment_body", { offset: 100 } );
        $( this.id + "_comment_body" ).focus();
      }
    });
  },
  post: function( id ){
    $( id + "_comment_buttons" ).hide();
    $( id + "_comment_spinner" ).show();
  },
  failed: function( id ){
    $( id + "_comment_buttons" ).show();
    $( id + "_comment_spinner" ).hide();    
  },
  complete: function( id ){
    this.failed( id )
  }
}

// MOBILE NOTES
var MobileNotes = {
  DELETE_MESSAGE: "Are you sure you want to delete this mobile note?\n\nThere is no undo.",
  destroy: function( id ){
    if( confirm( this.DELETE_MESSAGE ) ){
      new Ajax.Request('/iphone/delete_note', { parameters: { id: id } } );
    }
  }
};

// SITE NOTES
var SiteNote = {
  validate_form: function( form ){
    form.submit();
  }
};

// TEMPLATE
var WorkoutTemplate = {
  prepare_form: function(){
    $('save_btn').innerHTML = 'Save Template';
    $('save_btn').onclick = function(){ WorkoutTemplate.validate_form( $('workout_form') ) }
    var template_var = new Element('hidden', { name: 't', value: 1 });
    $('workout_form').insert( { bottom: template_var });
  },
  validate_form: function( form ){
    form.submit();
  }
};

// WORKOUT
var Workout = {
  
  // TODO: UGLY -- this is just a test
  // basic client-side validation
  validate_form: function( form ){

    // 
    Results.assign_order();
    //try {
      errors = 0;
    
      // clear out error icons
      $$('.error_icon_div').each( function( icon ){ icon.hide(); } );
        
      // TIME MUST BE:
      //  6pm
      //  6:00pm
      //  6 pm
      //  13:00
        
      var re1 = / [\d\:]+am|pm$/i
      var re2= / [\d\:]+ am|pm$/i
      var re3= / [\d\:]+$/i
    
      // Date & Time
      if( !$('workout_occurred').value.match(re1) && !$('workout_occurred').value.match(re2) && !$('workout_occurred').value.match(re3) ){
        //$('time_reminder').innerHTML = "DON'T FORGET A VALID TIME!<br/>ie: 1:00pm or 13:00";
        //$('time_reminder').style.fontWeight = 'bold';
        //$('time_reminder').style.color = 'red';
        //new Effect.Shake('workout_occurred', { duration: 0.34, distance: 6, afterFinish: function(){ $('workout_occurred').focus(); } } );
        $('error_icon_div_for_occurred').show();
      }else{
        //$('time_reminder').innerHTML = "";
        //$('time_reminder').style.fontWeight = 'bold';
        //$('time_reminder').style.color = 'red';      
      }
    
      // Place
      if( !$('place').value ){
        $('error_icon_div_for_location').show();
      }

      // Elements/Focus
      var selected_elements_count = 0;
      $$('.element').each( function( e ){
        if( e.checked ){
          selected_elements_count += 1;
        }
      });

      if( selected_elements_count == 0 ){
        $('forgot_elements').innerHTML = "DON'T FORGET TO SELECT A FOCUS!";
        $('forgot_elements').style.fontWeight = 'bold';
        $('forgot_elements').style.color = 'red';
        $('forgot_elements').style.fontSize = "90%";
        $('error_icon_div_for_focus').show();
      }else{
        $('forgot_elements').innerHTML = "";      
      }
      
      // Event
      if( $('event_cb').checked ){
       if( !$('workout_e_name').value || !$('workout_e_category').value ){
          $('error_icon_div_for_event').show();
        }
      }
    
      // Result Set (name)
      $$('.result_set_name').each( function( input ){
        var is_visible = input.up('.result_set').visible();        
        var error_icon = input.up('.result_set').down('.error_icon_div');
        if( !input.value && is_visible ){
          error_icon.show();
        }
      });
        
      // Results (name/value)
      $A(['.result_name','.result_value']).each( function( klass_name ){
        $$( klass_name ).each( function( input ){
          var error_icon = input.up('.result_set').down('.error_icon_div');
          var is_visible = input.up('.result').visible();
          if( !input.value && is_visible ){
            error_icon.show();
          }
        });
      });
    
      // Records
      $$('.record_value').each( function( record ){
        var is_visible = record.visible();
        
        var errors = [];
        var error_icon = record.down('.error_icon_div');
        var error_msg = record.down('.record_errors');
         
        var category = record.down('.record_category');
        var name = record.down('.record_name');
        var value = record.down('.record_val');
        
        if( is_visible && ( !category.value || !name.value || !value.value) ){
          errors.push('Please make sure the category, name and value fields are filled in.<Br/>');
        }

        if( is_visible && ( value.value && !value.value.match(/^[\d:\.]+$/) ) ){
          errors.push("The 'Value' field must either be a time (HH:MM:SS or MM:SS) or a number. Please use the notes field for any additional details.<Br/>");
        }
  
        error_msg.update('');
        errors.each( function( msg ){
          var div = new Element('div');
          div.className = 'record_error';
          div.update(msg);
          
          error_msg.insert( { bottom: div } ); 
          error_icon.show();
        });
        
      });
      
      // Verify 'value' is a time or an integer
      $$('.record_val').each( function( input ){
        if( !input.value.match(/^[\d\:\.]+$/) ){
          var container = input.up('.record_value');
          if( container && container.visible() ){
            var error_div = container.down('.error_icon_div');   
            error_div.show();
          }
        }
      });
  
      tabs = ['details', 'results', 'results', 'records'];
      var errors = {};
      var total_errors = 0;
      tabs.each( function( tab ){

        // reset pills
        $(tab + '_pill').hide(); //style.display = 'none';
        $(tab + '_pill').update('0');
        //$(tab + '_pill').setAttribute("title", "This tab has errors!");

        errors[ tab ] = 0;
      
        // count errors
        $$('.error_icon_div_tab_' + tab ).each( function( div ){
          if( div.visible() ){
            errors[ tab ] += 1;
            total_errors += 1;
          
            $(tab + '_pill').update( errors[ tab ] );
            $(tab + '_pill').show();
          }
        });
      
      });

      // If the event checkbox is unchecked, clear the category/event name
      if( !$('event_cb').checked ){
        $('workout_e_category').value = '';
        $('workout_e_name').value = '';
      }

      if( total_errors == 0 ){
        $('form_errors_msg').hide();
        form.submit();
      }else{
        $('form_errors_msg').show();
      }
    //}catch(e){
    //  alert( e.message );
    //}
    
  },
  fields_with_errors: function(){
    var count = 0;
    $$('.error_icon_div').each( function( icon ){
      if( icon.style.display != 'none' ){
        count += 1;
      }
    });
    return count;
  },
  preview_crossfit_wod: function( wod_id ){
    if( wod_id ){
      new Ajax.Request('/workouts/preview_crossfit_wod', { evalScripts: true, parameters: { id: wod_id } } );
    }else{
      $$('#crossfit_wod_summary').each( function( e ){ e.innerHTML = ''; } );
    }
  },
  select_crossfit_wod: function(){
    id = $$('#facebox #crossfit_wod_id').first().value;
    new Ajax.Request('/workouts/select_crossfit_wod', { evalScripts: true, parameters: { id: id }, onComplete: function(){
      Workout.fillout_form_with_wod_details();
      jQuery.facebox.close();  
    }});
    
  },
  fillout_form_with_wod_details: function(){
     // title
      $('workout_name').value = wod['name'];

      // focus
      $$('.element').each( function( e ){ e.checked = false; } );
      $$('.element_li ul').each( function( e ){ e.hide(); } );
    
      $$('.element').each( function( element ){
        wod['focus'].each( function( focus_id ){ 
          if( element.value == focus_id ){
            element.checked = true;
            element.up().up().up().select('ul').first().show();
          }
        });
      });

      // description
      tinyMCE.activeEditor.setContent( wod['description'] );

      // links
      $('workout_links').value = wod['links'];

      // results
      results = wod['results'].split(',');
      $$('.add_results_link').first().onclick();        

      // add a measure (results.length - 1)
      for( var i=0; i<results.length-1; i++ ){
        $$('.add_measures_link').first().onclick();        
      }
    
      rows = $$('li.result_measure table tbody tr'); //.each( function( measure_row ){
    
      results.each( function( result, index ){
        kv = result.split('|');
        rows[ index ].select('.result_measure_name').first().value = kv[0];
        if( kv[1] ){
          rows[ index ].select('.result_measure_value').first().value = kv[1];
        }
      });
          
    //    measure_row.select('.result_measure_name').first().value = 
    //  });
      /*
      results.each( function( result ){
        $$('.add_measures_link').first().onclick();
        kv = result.split('|');
        $$('')
      });
      */
    
      $('workout_occurred').focus();
  }
}


// RESULTS
var Results = {
  DELETE_MESSAGE: "Are you sure you want to delete this result set?\n\nThere is no undo.",
  DELETE_MEASURE_MESSAGE: "Are you sure you want to delete this measure?\n\nThere is no undo.",
  build_sortables: function(){
    $$('.results').each( function( measures ){
      measures.id = Math.floor('res_' + Math.random() * 50000); // bad! this breaks safari. dont use ids that start with #s
      Sortable.create( measures, { onChange: Results.assign_order, tag: 'div' } );
    });    
  },
  adjust_measure_examples: function(){},
  assign_order: function(){
    $$('.results').each( function( div ){
      div.select(".result .position").each( function( e, index ){
        e.value = parseInt( index + 1 );
      });      
    });
    
  },
  prepare_choice_list: function( choice ){
    var opts = choice.rel.replace(', ',',').split(',');
    var link = choice.up('.result_set').down('.add_nested_item_lvl2');

    // remove blank
    var results = choice.up('.result_set').select('.result');
    results.each( function( r ){
      if( !r.down('.result_name').value ){
        r.remove();
      }
    });
    
    opts.each( function( opt ){
      // add new
      add_nested_level( link );
      
      results = choice.up('.result_set').select('.result');
      var last_result = results[ results.size()-1 ];
      last_result.down('.result_name').value = opt;
    });
    
    // hide list
    choice.up('.result_choice_list').hide();
  },
  display_no_result_sets_message: function(){
    var count = 0;
    $$('.result_set').each( function( rs ){
      if( rs.visible() ){
        count += 1;
      }
    });
    
    if( count == 0 ){
      $('no_result_sets').show();
    }else{
      $('no_result_sets').hide();
    }
  }
}


/*
var ResultsOLD = {
  DELETE_MESSAGE: "Are you sure you want to delete this result set?\n\nThere is no undo.",
  DELETE_MEASURE_MESSAGE: "Are you sure you want to delete this measure?\n\nThere is no undo.",
  visible_result_sets: function(){
    var count = 0;
    $$('.result_set').each( function( e ){
      if( e.style.display != 'none' ){
        count++;
      }
    });
    return count;
  },
  destroy: function( e, id ){
    if( confirm( this.DELETE_MESSAGE ) ){
      $( e ).up().up().remove(); 
      if( id ){
        $('workout_result_sets_attributes_' + id + '__delete').value = '1';
      }
      this.adjust_no_results_message();
    }
  },
  delete_measure: function( e, result_id, result_set_id ){
    var parent = $( e ).up().up().up().up().up();
    if( confirm( this.DELETE_MEASURE_MESSAGE ) ){
        
      // existing
      if( result_id && result_set_id ){
        try {
          parent.hide(); 
          $('workout_result_sets_attributes_' + result_set_id + '_results_attributes_' + result_id + '__delete').value = 1;
        }catch( e ){
          console.log( e );
          // existing records only
        }
      // new
      }else{
        parent.remove();
      }

      this.adjust_measure_examples();
    }
  },
  adjust_no_results_message: function(){
    if( Results.visible_result_sets() == 0 ){ 
      $('no_result_sets').show(); 
    }
  },
  adjust_measure_examples: function(){
    $$('.xmeasure_list').each( function( list ){ 
      var children = $A([]);
      // find visible children
      list.childElements().each( function( child ){
        if( child.visible() ){
          children.push( child );
        }
      });
      
      children.each( function( child, index ){
        if( index == 0 ){
          child.select('.result_measure_name_example').first().show();
          child.select('.result_measure_value_example').first().show();
        }else{
          child.select('.result_measure_name_example').first().hide();
          child.select('.result_measure_value_example').first().hide();        
        }
      });
    });
  },
  build_sortables: function(){
    $$('.xmeasure_list').each( function( measures ){
      measures.id = Math.floor(Math.random() * 50000);
      Sortable.create( measures, { onChange: function( li ){
        list = li.up();
        list.select("li input[class='position']").each( function( e, index ){
          e.value = index + 1;
        });
        Results.adjust_measure_examples();
      }} );
    });
  },
  add_measures_for_result_set: function( list, result_set_id, measures ){
    var self = this;

    try {
      var result_set = list.up().up().up().up().up();
      
      var id_to_use = result_set.select('.result_set_name')[0].name.match(/(new_[\d]+)/)[1];
      if( id_to_use ){
        result_set_id = id_to_use;
      }
    }catch(e){
    
    }
      
    // jQuery
    if( measures[0].length > 0 ){
      jQuery(list).find(".result_measure" ).each( function( i1, rm ){
        blank = true;
        jQuery(rm).find('.result_measure_name').each( function( i2, input ){
          if( input.value == '' || !input.value ){
            blank = false;
          }
        });
        if( blank == false ){
          rm.remove();
        }
      });
    }
    
    // Prototype
    measures.each( function( m ){ 
      var result_measure_id = "new_" + new Date().getTime();
      html = NEW_RESULT_MEASURE_HTML.replace(/RESULTSETID/g, result_set_id );
      html = html.replace(/RESULTMEASUREID/g, result_measure_id );
      html = html.replace(/RESULTMEASURENAME/g, m)
      list.insert( { bottom: html } );
      
      
      Results.build_sortables();
      list.childElements().last().select('.result_measure_name').first().focus();
      self.adjust_measure_examples();
    });
    
    
    // jQuery
    if( measures[0].length > 0 ){
      first = null;
      jQuery( list ).find('.result_measure_value').each( function( i, val ){
        if( val.value == '' && first == null ){
          first = val;
        }
      });
      first.focus();
      list.next().next().onclick(); // Prototype
    }

  }
}
*/

// RECORDS
var Records = {
  record_name_autocomplete: function( input ){
    var category = input.up('.record_value').down('.record_category').value;
    if( record_name_map[ category ] ){
      return record_name_map[ category ];
    }else{
      all = [];
      $H( record_name_map ).each( function( h ){
        all.push( h[1] );
      });
      return all.flatten();
    }
  },
  bind_autocompleters: function(){
    $$('.record_category').each( function( input ){
      if( !input.autocomplete ){
        var div = input.up().down('.r_category_autocomplete');
        var indicator = input.up().down('.indicator');
        var categories = ['a','b','c']; 
        input.autocomplete = new Autocompleter.Local( input, div, record_category_map, { indicator: indicator, frequency: 0.1 } );
      }
    })

    $$('.record_name').each( function( input ){
      if( !input.autocomplete ){
        var div = input.up().down('.r_name_autocomplete');
        var indicator = input.up().down('.indicator');
        input.autocomplete = new Autocompleter.Local( input, div, function(){ return Records.record_name_autocomplete( input ) }, { indicator: indicator, frequency: 0.1 } );
      }
    });
  },
  display_no_records_message: function(){
    var count = 0;
    $$('.record_value').each( function( rs ){
      if( rs.visible() ){
        count += 1;
      }
    });
    
    if( count == 0 ){
      $('no_records').show();
    }else{
      $('no_records').hide();
    }
  }
}

// IMAGES
var Images = {
 images: [],
 form_data: function(){
   images = [];
   $$('.image').each( function( image ){
     var img = {
       id: image.id.match(/([\d]+)/)[1],
       name: image.select('.image_title').first().value,
       description: image.select('.image_description').first().value,
       tag_list: image.select('.image_tags').first().value,
       copy_id: image.select('.image_copy_id').first().value
     };
     images.push( img );
   });
   return images;
 }
};

// NOTIFICATIONS
var Notifications = {
  send: function( error, msg ){
    new Ajax.Request('/notifications', { parameters: { type: 'javascript', error: error + "\n" + msg  } } );
  }
}

// NESTED FORM HELPERS
replace_ids = function(s){
  var new_id = new Date().getTime();
  return s.replace(/NEW_RECORD/g, new_id);
}

var myrules = {
  '.remove': function(e){
    if( confirm("Are you sure?") ){
      el = Event.findElement(e);
      target = "." + el.getAttribute('obj'); //href.replace(/.*#/, '.')
      if(hidden_input = el.previous("input[type=hidden]")){
        hidden_input.value = '1';
        el.up(target).hide();
      }else{
        el.up(target).remove();
      } 
    }
  },
  '.add_nested_item': function(e){
    el = Event.findElement(e);
    template = eval(el.href.replace(/.*#/, ''))
    $(el.rel).insert({     
      bottom: replace_ids(template)
    });
  },
  '.add_nested_item_lvl2': function(e){
    el = Event.findElement(e);
    add_nested_level( el );
  },
  '.result_choice': function(e){
    var el = Event.findElement(e);
    Results.prepare_choice_list( el );
  },
  '.add_record': function(e){
    Records.bind_autocompleters()
    Records.display_no_records_message();
  },
  '.remove_record_value': function(e){
    Records.display_no_records_message();    
  },
  '.add_result_set': function(e){
    Results.display_no_result_sets_message();
  },
  '.remove_result_set': function( e ){
    Results.display_no_result_sets_message();
  },
  '.add_result_set_link': function( e ){
    var names = new Hash();
    $$('.result_set_name').each( function( input ){
      if( !input.value ){
        var c = 0;
        $$('.result_set_name').each( function( input ){
          if( input.value.match(/Results[\d ]?/) && input.up('.result_set').visible() ){
            c += 1;
          }
        });
        
        input.value = 'Results';
        
        if( c > 0 ){
          input.value += ' ' +c;
        }
      }
    });
  }
};


function add_nested_level( el ){
  
  elements = el.getAttribute('rel').match(/(\w+)/g)
  
  var parent = '.'+elements[0];
  var child = '.'+elements[1];

  var child_container = el.up(parent).down(child);
  var parent_object_id = el.up(parent).down('input').name.match(/.*\[(\d+)\]/)[1];

  var template = eval(el.href.replace(/.*#/, ''));
  template = template.replace(/(attributes[_\]\[]+)\d+/g, "$1"+parent_object_id);
  
  child_container.insert({     
    bottom: replace_ids(template)
   });
   
  // For now this method is only called when building results
  Results.build_sortables();
}


function import_from_garmin_connect(){
  document.location = '/garmin';
}

// DATE MANIPULATION
var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x){return(x<0||x>9?"":"0")+x}
function isDate(val,format){var date=getDateFromFormat(val,format);if(date==0){return false;}return true;}
function compareDates(date1,dateformat1,date2,dateformat2){var d1=getDateFromFormat(date1,dateformat1);var d2=getDateFromFormat(date2,dateformat2);if(d1==0 || d2==0){return -1;}else if(d1 > d2){return 1;}return 0;}
function formatDate(date,format){format=format+"";var result="";var i_format=0;var c="";var token="";var y=date.getYear()+"";var M=date.getMonth()+1;var d=date.getDate();var E=date.getDay();var H=date.getHours();var m=date.getMinutes();var s=date.getSeconds();var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;var value=new Object();if(y.length < 4){y=""+(y-0+1900);}value["y"]=""+y;value["yyyy"]=y;value["yy"]=y.substring(2,4);value["M"]=M;value["MM"]=LZ(M);value["MMM"]=MONTH_NAMES[M-1];value["NNN"]=MONTH_NAMES[M+11];value["d"]=d;value["dd"]=LZ(d);value["E"]=DAY_NAMES[E+7];value["EE"]=DAY_NAMES[E];value["H"]=H;value["HH"]=LZ(H);if(H==0){value["h"]=12;}else if(H>12){value["h"]=H-12;}else{value["h"]=H;}value["hh"]=LZ(value["h"]);if(H>11){value["K"]=H-12;}else{value["K"]=H;}value["k"]=H+1;value["KK"]=LZ(value["K"]);value["kk"]=LZ(value["k"]);if(H > 11){value["a"]="PM";}else{value["a"]="AM";}value["m"]=m;value["mm"]=LZ(m);value["s"]=s;value["ss"]=LZ(s);while(i_format < format.length){c=format.charAt(i_format);token="";while((format.charAt(i_format)==c) &&(i_format < format.length)){token += format.charAt(i_format++);}if(value[token] != null){result=result + value[token];}else{result=result + token;}}return result;}
function _isInteger(val){var digits="1234567890";for(var i=0;i < val.length;i++){if(digits.indexOf(val.charAt(i))==-1){return false;}}return true;}
function _getInt(str,i,minlength,maxlength){for(var x=maxlength;x>=minlength;x--){var token=str.substring(i,i+x);if(token.length < minlength){return null;}if(_isInteger(token)){return token;}}return null;}
function getDateFromFormat(val,format){val=val+"";format=format+"";var i_val=0;var i_format=0;var c="";var token="";var token2="";var x,y;var now=new Date();var year=now.getYear();var month=now.getMonth()+1;var date=1;var hh=now.getHours();var mm=now.getMinutes();var ss=now.getSeconds();var ampm="";while(i_format < format.length){c=format.charAt(i_format);token="";while((format.charAt(i_format)==c) &&(i_format < format.length)){token += format.charAt(i_format++);}if(token=="yyyy" || token=="yy" || token=="y"){if(token=="yyyy"){x=4;y=4;}if(token=="yy"){x=2;y=2;}if(token=="y"){x=2;y=4;}year=_getInt(val,i_val,x,y);if(year==null){return 0;}i_val += year.length;if(year.length==2){if(year > 70){year=1900+(year-0);}else{year=2000+(year-0);}}}else if(token=="MMM"||token=="NNN"){month=0;for(var i=0;i<MONTH_NAMES.length;i++){var month_name=MONTH_NAMES[i];if(val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()){if(token=="MMM"||(token=="NNN"&&i>11)){month=i+1;if(month>12){month -= 12;}i_val += month_name.length;break;}}}if((month < 1)||(month>12)){return 0;}}else if(token=="EE"||token=="E"){for(var i=0;i<DAY_NAMES.length;i++){var day_name=DAY_NAMES[i];if(val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()){i_val += day_name.length;break;}}}else if(token=="MM"||token=="M"){month=_getInt(val,i_val,token.length,2);if(month==null||(month<1)||(month>12)){return 0;}i_val+=month.length;}else if(token=="dd"||token=="d"){date=_getInt(val,i_val,token.length,2);if(date==null||(date<1)||(date>31)){return 0;}i_val+=date.length;}else if(token=="hh"||token=="h"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<1)||(hh>12)){return 0;}i_val+=hh.length;}else if(token=="HH"||token=="H"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<0)||(hh>23)){return 0;}i_val+=hh.length;}else if(token=="KK"||token=="K"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<0)||(hh>11)){return 0;}i_val+=hh.length;}else if(token=="kk"||token=="k"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<1)||(hh>24)){return 0;}i_val+=hh.length;hh--;}else if(token=="mm"||token=="m"){mm=_getInt(val,i_val,token.length,2);if(mm==null||(mm<0)||(mm>59)){return 0;}i_val+=mm.length;}else if(token=="ss"||token=="s"){ss=_getInt(val,i_val,token.length,2);if(ss==null||(ss<0)||(ss>59)){return 0;}i_val+=ss.length;}else if(token=="a"){if(val.substring(i_val,i_val+2).toLowerCase()=="am"){ampm="AM";}else if(val.substring(i_val,i_val+2).toLowerCase()=="pm"){ampm="PM";}else{return 0;}i_val+=2;}else{if(val.substring(i_val,i_val+token.length)!=token){return 0;}else{i_val+=token.length;}}}if(i_val != val.length){return 0;}if(month==2){if( ((year%4==0)&&(year%100 != 0) ) ||(year%400==0) ){if(date > 29){return 0;}}else{if(date > 28){return 0;}}}if((month==4)||(month==6)||(month==9)||(month==11)){if(date > 30){return 0;}}if(hh<12 && ampm=="PM"){hh=hh-0+12;}else if(hh>11 && ampm=="AM"){hh-=12;}var newdate=new Date(year,month-1,date,hh,mm,ss);return newdate.getTime();}
function parseDate(val){var preferEuro=(arguments.length==2)?arguments[1]:false;generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');var d=null;for(var i=0;i<checkList.length;i++){var l=window[checkList[i]];for(var j=0;j<l.length;j++){d=getDateFromFormat(val,l[j]);if(d!=0){return new Date(d);}}}return null;}