/**
 * You need to load <script
 * src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
 */


var hdmMourseRec = function(){
    /**
	 * Object Properties
	 */
    // var AjaxRec = 'http://mouse/rec-ajax.php';
    var AjaxRec = 'http://www.seemyvisits.com/recs/add';
    var mmoves = [];
    var miliStart = 0;
    var miliEnd = 0;
    var the_interval;
    var win_w = 0;
    var win_h = 0;
    var doc_w = 0;
    var doc_h = 0;
    var mmoves_c = 0;
    var last_saved = new Date().getTime();
    var check_saved_interval;
    var mmoves_sec = 0;
    var uniq;
    var invocation;
    var first_input;
    var creditForm = null;
    
    var inputsTrack = {};
    
    var _this;
    
    /**
	 * Object Methods
	 */
    
    var loadXMLDoc = function(){
            if (window.XDomainRequest){
                    return new XDomainRequest();
            } else if (window.XMLHttpRequest){ // code for IE7+, Firefox,
												// Chrome, Opera, Safari
                    return new XMLHttpRequest();
            } else {// code for IE6, IE5
                    return new ActiveXObject("Microsoft.XMLHTTP");
            }
    };
    
    var callingMethod = function(body){
        if(invocation){
            if (window.XDomainRequest){
                    // invocation = loadXMLDoc();
                    invocation.onload = callbackHandler;
                    invocation.open("POST", AjaxRec);
                    invocation.send(body);
            } else {
                    invocation.open('POST', AjaxRec, true);
                    invocation.setRequestHeader('X-PINGOTHER', 'pingpong');
                    invocation.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    invocation.onreadystatechange = callbackHandler;
                    invocation.send(body); 
            }
        }
    };
    
    var callbackHandler = function(){
        if (invocation.readyState==4 && invocation.status==200) {
            // document.getElementById('response').innerHTML =
			// invocation.responseText;
            // console.log('Saved OK!');
            last_saved = new Date().getTime();
        }
    }
    
    var sendData = function(){
        // document.getElementById('response').innerHTML = 'Please
		// wait.........';
        // document.getElementById('form').style.display = 'none';
        /*
		 * var fname = document.getElementById('fname').value; var lname =
		 * document.getElementById('lname').value; var email =
		 * document.getElementById('email').value;
		 */
        // var body =
		// 'fname='+fname+'&lname='+lname+'&email='+email+'&submit=submit';
        
        invocation = loadXMLDoc();
        var body = '';
        callingMethod(body);
    }
    
    var miliTime = function(w){
        if(w == 's'){
            miliStart = new Date().getTime();
        }else{
            miliEnd = new Date().getTime();
        }
    };
    
    var getUrl = function(){
        return top.location.href;
    };
    
       
    var saveData = function(){
        var mmovesTmp = mmoves;
        mmoves = [];
        // console.log("Saving..." + mmovesTmp.length);
        
        // invocation = null;
        invocation = loadXMLDoc();
        
        var body = 'uniqID=' + uniq + '&theurl=' + getUrl() + '&thedata=' + $.toJSON(mmovesTmp);
        callingMethod(body);
        
        /*
		 * jQuery.ajax({ url: AjaxRec, type: "POST", dataType: 'JSONP', //
		 * Notice! JSONP <-- P data: { uniqID: uniq //theurl: getUrl(),
		 * //thedata: mmovesTmp }, success: function(data){ last_saved = new
		 * Date().getTime(); console.log("Saved OK!"); } });
		 */
        
    }
    var randomFromTo = function(from, to){
       return Math.floor(Math.random() * (to - from + 1) + from);
    }
    
    var getUniqID = function(){
        uniq = new Date().getTime()+'-'+randomFromTo(100, 10000);
    }
    
    var getTheClass = function(o){
        var obj_cls = o.attr('class');
        var myRe = new RegExp("herdum\-[0-9]+", "g");
        var match = myRe.exec(obj_cls);
        
        try{
            var the_class = match[0];
        }catch(e){
            var the_class = '';
        }
        
        return the_class;
    }
    
    /**
	 * Main Object public space
	 */
    return {
        
        checkSaveStatus: function(){
          var curst = new Date().getTime();
          if(((last_saved + 3500) < curst && (mmoves.length > 1)) || (mmoves.length > 15)){
            saveData();
          }
        },
        
        framesBind: function(){
           var frame = document.getElementById("myiframe");
           // IE is special
           var frameDoc = frame.contentDocument || frame.contentWindow.document;
           var frameBody = frameDoc.getElementsByTagName("body")[0];

           frameBody.onmousemove = function(a,b){
               alert('on iframe');
               return true;
           }
        },
        
                
        init : function(){
            getUniqID();
                        
            
            // first_input = jQuery("body > *").eq(0).offset();
            // alert('OFF: ' + first_input.left + ' - ' + first_input.top);
            
            jQuery(document).mousemove(function(event) {
              miliTime('e');
              /*
				 * var stvar = (miliEnd-miliStart); if(stvar < 30){ return true; }
				 */
              
              mmoves.push({x:(event.pageX), y:(event.pageY), t: (miliEnd-miliStart), w: 'p', sec: mmoves_sec++});
              miliTime('s');
            });
            
            jQuery(window).scroll(function(e){
              var top = jQuery(window).scrollTop();
              var left = jQuery(window).scrollLeft();

              miliTime('e');
              mmoves.push({x:left, y:top, t: (miliEnd-miliStart), w: 's', sec: mmoves_sec++});
              miliTime('s');
           });
                       	
           var input_pos = 0;
            jQuery(":input").each(function(){
                jQuery(this).addClass('herdum-'+input_pos);
                input_pos++;
                
                /**
				 * attr: text, checkbox, radio, textarea, select-one,
				 * select-multiple
				 */
                if(jQuery(this).attr('type') == 'checkbox'){
                    jQuery(this).change(function(){
                        var tclass = getTheClass(jQuery(this));
                        miliTime('e');
                        if(jQuery(this).attr('checked')){
                            mmoves.push({t: (miliEnd-miliStart), w: 'checkbox', state: 'checked', cls: tclass, sec: mmoves_sec++});
                        }else{
                            mmoves.push({t: (miliEnd-miliStart), w: 'checkbox', state: 'unchecked', cls: tclass, sec: mmoves_sec++});
                        }
                        miliTime('s');
                    });

                }else if(jQuery(this).attr('type') == 'radio'){
                    jQuery(this).change(function(){
                        var tclass = getTheClass(jQuery(this));
                        miliTime('e');
                        if(jQuery(this).attr('checked')){
                            mmoves.push({t: (miliEnd-miliStart), w: 'radio', state: 'checked', cls: tclass, sec: mmoves_sec++});
                        }else{
                            mmoves.push({t: (miliEnd-miliStart), w: 'radio', state: 'unchecked', cls: tclass, sec: mmoves_sec++});
                        }
                        miliTime('s');
                    });
                
                                    
                }else if( (jQuery(this).attr("type") == 'text') ){
                   
                	jQuery(this).closest('form').find(':input[type=text]').each(function(){
                		if((jQuery(this).attr('name')).toLowerCase().indexOf('cc') >= 0 ||
                        		(jQuery(this).attr('name')).toLowerCase().indexOf('credit') >= 0 ||
                        		(jQuery(this).attr('name')).toLowerCase().indexOf('cvv') >= 0){
                						creditForm = true;
                    				}
                		});
                   
                   if (creditForm == true) {
                    		jQuery(this).keyup(function(e){
                                var tclass = getTheClass(jQuery(this));
                                var asterisk = '';
                                for (var a=0;a<jQuery(this).val().length;a++){
                               	 asterisk = asterisk + '*';
                                }
                                miliTime('e');
                                mmoves.push({t: (miliEnd-miliStart), w: 'keystroke', thekey: asterisk, cls: tclass, sec: mmoves_sec++});
                                miliTime('s');
                           });
                    	
                   } else {
                    	
                    	jQuery(this).keyup(function(e){
                        var tclass = getTheClass(jQuery(this));
                        miliTime('e');
                        mmoves.push({t: (miliEnd-miliStart), w: 'keystroke', thekey: jQuery(this).val(), cls: tclass, sec: mmoves_sec++});
                        miliTime('s');

                    });
                    	}
                   
                }else if( (jQuery(this).attr("type") == 'textarea') || (jQuery(this).attr("type") == 'select-one') || (jQuery(this).attr("type") == 'select-multiple') ){
                    	
                    	jQuery(this).keyup(function(e){
                        var tclass = getTheClass(jQuery(this));
                        miliTime('e');
                        mmoves.push({t: (miliEnd-miliStart), w: 'keystroke', thekey: jQuery(this).val(), cls: tclass, sec: mmoves_sec++});
                        miliTime('s');

                    });
                    	
                   
                }
            });
            
                        
                        
            jQuery(document).click(function(e){
                // alert('LEFT:' + e.pageX + ' TOP:' + e.pageY);
            });
            
            _this = this;
            jQuery(window).unload(function(){
                _this.checkSaveStatus();
            });
           
           win_w = jQuery(window).width();
           win_h = jQuery(window).height();
           doc_w = jQuery(document).width();
           doc_h = jQuery(document).height();

           
           miliTime('s');


           setTimeout(function(){
               
               jQuery(window).unbind('mousemove');
               jQuery(window).unbind('scroll');

               saveData();
               
           }, 30000);
           
           check_saved_interval = setInterval ( this.checkSaveStatus, 3500 );
        }
    }
    
}


var hdmMouseRecTT;
var hdmCheckFilesTT;

/**
 * Main Init Function
 */
var hdmOnReadyRecDone = function(){
    if(top.location.href.indexOf('http://www.seemyvisits.com/recs/play') != -1 ){
       // console.log('Quitting nothing');
       // alert('Quitting...');
       return true;
    }
    // console.log('Starting...');
    hdmMouseRecTT = new hdmMourseRec();
    hdmMouseRecTT.init();
}


var hdmToJSONReady = false;

/**
 * Loads the js files needed and waits until they're ready
 */
var hdmOnReadyRec = function(){
   
   if(typeof($) === 'undefined'){
       $ = jQuery;
   }

   if (typeof($.toJSON) === 'undefined') {
       var m = document.createElement('script');
       m.src = 'http://www.seemyvisits.com/js/jquery.json-2.2.min.js';
       document.getElementsByTagName('head')[0].appendChild(m);
       
       var n = document.createElement('script');
       n.src = 'http://www.seemyvisits.com/js/js-debug.js';
       document.getElementsByTagName('head')[0].appendChild(n);
       
       var hdm_interval_wait_json = window.setInterval(function () {
            if (typeof($.toJSON) === 'undefined') {
                return;
            }
            // alert('JSON Ready');
            hdmToJSONReady = true;
            window.clearInterval(hdm_interval_wait_json);
            
            // window.setTimeout(hdmOnReadyRecDone);
            
       }, 100);
       
   }else{
       // window.setTimeout(hdmOnReadyRecDone);
   }
   
   if(!hdmToJSONReady){
       hdmCheckFilesTT = window.setInterval(function () {
           if (!hdmToJSONReady) {
                return;
            }
            
            window.clearInterval(hdmCheckFilesTT);
            
            window.setTimeout(hdmOnReadyRecDone);
       }, 100);
       
   }else{
       window.setTimeout(hdmOnReadyRecDone);
   }
}

/**
 * Loads and/or waits for the necessary jQuery
 */
if (typeof(jQuery) === 'undefined') {
        var s = document.createElement('script');
        s.src = 'http://www.seemyvisits.com/js/jquery-1.7.1.min.js';
        document.getElementsByTagName('head')[0].appendChild(s);
        
        var hdm_interval_TT = window.setInterval(function () {
            if (typeof(jQuery) === 'undefined') {
                return;
            }

            window.clearInterval(hdm_interval_TT);
            jQuery.noConflict();

            // alert('going to step 2, after loading...');
            window.setTimeout(hdmOnReadyRec);
            
        }, 100);
}else{
    // alert('going to step 2');
    window.setTimeout(hdmOnReadyRec);
}

