/*
  tjLog jQuery Plugin
  Copyright 2010 Randy Brandt
  Version: 0.95 18-Nov-2010
*/
function notes() {
/*
  Requires jQuery v1.4.0 or later; http://jquery.com
  Examples and docs:
   http://www.tiredjake.com/index.php?p=tjLog

  Licensed under the MIT license:
  http://www.opensource.org/licenses/mit-license.php

  Copyright (c) 2010 Randy Brandt, tiredjake.com
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/
}
/* */
(function($) {
  var defaults = {
    bgChange: true,
    bgColors: ["#ff80ff", "#80ff80", "#ffff80", "#80ffff",
               "fuchsia", "lime", "yellow", "aqua"],
    bgReset: true,
    dest: null,
    fName: "tjLog",
    logPHP: "/~lib/tjLog.php",
    outline: true,
    tLen: 40,
    wantHTML: true,
    wantData: true,
    wantTime: false
  };
  var opt=defaults;
  var iColor=0;
  var bColor=2;
 // var tjLog_hit1 = { outlineColor:'yellow', outlineStyle:'dotted', outlineWidth:'2px'};
 
  var jOL=[];
  var tjLog_hit1 = { outline:'2px dotted fuchsia' };
  var tjLog_hit2 = { outline:'2px dotted lime' };
  var tjLog_hit3 = { outline:'2px dotted yellow' };
  var tjLog_hit4 = { outline:'2px dotted aqua' };
  var tjLog_hit5 = { outline:'2px dotted #ff80ff"' };
  var tjLog_hit6 = { outline:'2px dotted #80ff80' };
  var tjLog_hit7 = { outline:'2px dotted #ffff80' };
  var tjLog_hit8 = { outline:'2px dotted #80ffff' };
  jOL[0]=tjLog_hit1;
  jOL[1]=tjLog_hit2;
  jOL[2]=tjLog_hit3;
  jOL[3]=tjLog_hit4;
  jOL[4]=tjLog_hit1;
  jOL[5]=tjLog_hit2;
  jOL[6]=tjLog_hit3;
  jOL[7]=tjLog_hit4;
  
$.fn.tjLog = function(opshuns) {
  opt = $.extend(defaults, opshuns);    
  dest = opt.dest;
 
 console.log (opt); 
  work="$('"+this.selector+"').tjLog(";
  if (opshuns) {
    work+=Stringify(opshuns)+");"; // html, need txt
  } else {
    work+=");";    
  }
/*
console.error("call tjBColor");
  $("[data-tjBColor]").each(function() {
    orig=$(this).data("tjBColor");
console.error("restore orig",orig);
    $(this).css("background-color",orig);
  });
  */
  
  if (dest=="file") {
    fWrite(work,"new"); // append
  } else {
    $.log (work,"war",dest);
  }
   
   num=0; //counter

  // walk thru jQuery collection
  return this.each(function() {
    jayLog(this, dest, num);
    num++;
  });
 };

function Stringify(jsonData) {
    var strJsonData = '{';
    var itemCount = 0;
    for (var item in jsonData) {
        if (itemCount > 0) {
            strJsonData += ', ';
        }
        strJsonData += '"' + item + '":"' + jsonData[item] + '"';
        itemCount++;
    }
    strJsonData += '}';
    return strJsonData;
}

///////////////////
function jayLog (e, dest, num) {	
    var tn=": "+e.tagName.toLowerCase();

  if (e.name==undefined) {
    var nam=" n:";
  } else {
    var nam=" n:"+e.name;
  }

    var id=" #"+e.id;
    var cn=" ."+e.className;
    
    // identify parent with id
    var parObj=$(e).parent();
    p=" #parent:"+$(parObj).attr("id");
    
    var ofs=$(e).offset();
    var d=" display:"+$(e).css("display");
    var w=" w:"+$(e).css("width");
    var x=" x:"+ofs.left;
    var y=" y:"+ofs.top;
    var z=" z:"+$(e).css("z-index");
    var pos=" pos:"+$(e).css("position");

    var zp=" zp:"+$(parObj).css("z-index");
  
    var t=$(e).text().substr(0,20);
    var txt=" txt:"+t.replace(/<\/?[a-z][a-z0-9]*[^<>]*>|\r|\n|\r|\n/ig, " ");

    work=num+tn+nam+id+cn+w+x+y+z+d+pos+p+txt;    

$.log("pre-wantHTML:");
  
    if (opt.wantHTML) {
      $.log (work,"group",dest);	//+bg+fg+txt); //+"<br \>");
      sHTML=$('<div>').append( $(e).clone() ).html();
      $.log ("html","group-",dest);
      $.log (sHTML,"gre",dest);
    } else {
      $.log (work,"",dest);	//+bg+fg+txt); //+"<br \>");      
    }
/*
 <span id="x" data-rules="rulez">span</span>
 <div id="container" data-container="marushka">
*/
    if (opt.wantData) {
      sData=$(e).data();
      for(var x in sData) {
        $.log("data-"+x+": "+sData[x]);
      }
    }

    if (e.checked) {
      var sVal="checked";
    } else {
      var sVal=$(e).val();  
    }
    if (sVal) {
      $.log ("Value: "+sVal,"",dest);	//+bg+fg+txt); //+"<br \>");      
    }

/* in the html    
    var styles=$(e).attr("style");
    if (styles) {
      $.log ("inline styles","group-",dest);
      $.log (styles,"grend",dest);


<div data-role="page" data-hidden="true" data-options='{"name":"John"}'></div>
All of the following jQuery code will work.

$("div").data("role") === "page";
$("div").data("hidden") === true;
$("div").data("options").name === "John";
    }
*/
    $.log ("","gre",dest);
    
    // grouping values
    // change background colors?
    if (opt.bgChange) {
      orig=$(e).data("tjBColor");
      if (!orig) {
        o=$(e).css("background-color");
//console.log("save color",o);
        $(e).data("tjBColor",o);
      orig=$(e).data("tjBColor");
//console.log("got saved",orig);
      } else {
//console.log("got color",orig);
      }
    
      if ($(e).css("background-color") != opt.bgColors[iColor]) {
        $(e).css("background-color",opt.bgColors[iColor]);
      } else {
        $(e).css("background-color","");
      }
      var bg=" bg:"+opt.bgColors[iColor];				
      iColor++;
      if (iColor>=opt.bgColors.length) {
        iColor=0;
      }
    } else {
      var bg=" bg:"+$(e).css("background-color");				
    }
    var fg=" fg:"+$(e).css("color");

    // outline elements?
    if (opt.outline) {
      $(e).css(jOL[bColor]);
      bColor++;
      if (bColor>=opt.bgColors.length) {
        bColor=0;
      }
    }  
  }

/*
 log function dumps to console, doc or file (eventually)
*/
  jQuery.log = function(msg, type, dest, pause) {
    t=getTheTime();
    
    if (!dest && window.console && console.log) {
      var typ;
      if (type) {
        if (typeof type =="string") {
//console.log(msg,type,dest);
          type=type.toLowerCase();
          typ=type.substr(0,3);
        }
      }

//$.log("type:"+type);

      switch (typ) {
        case 'war': console.warn(msg); break;
        case 'err': console.error(msg); break;
        case 'inf': console.info(msg); break;
        case 'tra': console.trace(msg); break;

        case 'tim':
          if (console.time) {
            console.time(msg);
          }
        break;
        
        case 'ten':
          if (console.timeEnd) {
           console.timeEnd(msg);
          }
        break;
        
        case 'tab':
          if (console.table) {
            console.group("table");
            console.table(msg);            
            console.groupEnd("table");
          } else {
            console.log(msg);            
          }
          break;
            
        case 'clr':
          if (console.clear) {
            console.clear();
          }
          console.log(msg);
          break;

        case 'gro': 
          if (console.group) {
            if (type=='group-') {
              console.groupCollapsed(msg);
            } else {
              console.group(msg);
            }
          } else {
            console.log(msg);
          }
          if (console.time) {
            console.time(msg);
          }
          break;

        case 'gre':
          if (msg) {
            console.log(msg);
          }
//          console.timeEnd(msg);
          if (console.groupEnd) {
            console.groupEnd();
          }
          break;

        default:
          if (opt.wantTime && (typeof(msg)!="object")) {
            msg="{"+t+"} "+msg;
          }
          console.log(msg);
      }
      if (pause) {
        alert(pause);     
      }
    } else if (dest=="file") {
      var init="";
      if (type=="init") {
        init="new";
      }
      if (opt.wantTime) { msg="{"+t+"} "+msg; }
console.log(msg,init);
      fWrite(msg,init); // straight append
    } else {
//$.log("add to div");
      // add to div
      if (opt.wantTime && (typeof(msg)!="object")) {
        msg="{"+t+"} "+msg;
      }
      msg+="<br>";
      $(dest).append(msg);
    }
    return; //this
  }
  
  /* write to file */
function fWrite(m, init) {
  if (init) {
//    t="_"+getTheTime("_");
    
    t="";
    init=t+".txt:init="+init;
  } else {
    init=".txt:init=x";
  }
  //window.location.pathname
  tjLogParms="tjLog="+opt.fName+init+":msg="+m;
//console.log(tjLogParms); /////////////////////
  $.ajax({
    type: "POST",
    data: tjLogParms,
    url: opt.logPHP,
    error: function (data) {
//console.error(data);
    },
    success: function(data) {
      if (data.substr(0,4)!="~OK:") {
//console.error(data);
      } else {
      }
    }
  });
}

function getTheTime(div) {
  if (!div) {div=":"};
  
  var d = new Date();
  var h = d.getHours();
  var m = d.getMinutes()+"";
  if (m.length==1) {m="0"+m};
  var s = d.getSeconds()+"";
  if (s.length==1) {s="0"+s};
  var t = h+div+m+div+s;
  return t;
}

})(jQuery);
