
/*
 * Create the Namespace Manager that we'll use to
 * make creating namespaces a little easier.
 */
if (typeof Namespace == 'undefined') var Namespace = {};
if (!Namespace.Manager) Namespace.Manager = {};

Namespace.Manager = {
  Register:function(namespace){
    namespace = namespace.split('.');

    if (!window[namespace[0]]) window[namespace[0]] = {};

    var strFullNamespace = namespace[0];
    for (var i = 1; i < namespace.length; i++) {
      strFullNamespace += "." + namespace[i];
      eval("if (!window." + strFullNamespace + ")window." + strFullNamespace + "={};");
    }
  }
};

// Register our Namespace
Namespace.Manager.Register("NestedMedia.Utility.Class");

NestedMedia.Utility.Class.NMCookieHandler = function(CookieName, DestroyDuration, CookiePath, domain, secure) {
  // In addVars variable we are adding the coockes destroy DestroyDuration, cookies saving path, domain details, secure boolean value.
  this.addVars = "";

  /*
   * Integer value that defines how many minutes the cookie should persist for.
   * If this parameter isn't specified, a session cookie is created.
   */
  if (DestroyDuration) {
    var date = new Date();
    var curTime = new Date().getTime();

    date.setTime(curTime + (1000 * 60 * DestroyDuration));
    this.addVars = "; expires=" + date.toGMTString();
  }

  /*
   * If we wanted to make the cookie globally accessible to any web page on the server,
   * Use this CookiePath ("/")
   */
  if (CookiePath) {
    this.addVars += "; path=" + CookiePath;
  }

  /*
   * String value. This parameter maps directly to the domain parameter described in the PCSHCS
   * [Click to open link in a new window] . This parameter is only necessary for sites that run multiple sub domains.
   */
  if (domain) {
    this.addVars += "; domain=" + domain;
  }

  // Boolean value. If this parameter is true, the cookie created will only be transmitted under Secure Sockets Layer (SSL).
  if (secure) {
    this.addVars += "; secure=" + secure;
  }

  // This getCookValue function we are using for getting the cookies value as per key CookieName
  function getCookValue() {
    var cookname = document.cookie.match(new RegExp("(" + CookieName + "=[^;]*)(;|$)"));
    return cookname ? cookname[1] : null;
  }

  // This expire function we are using for destroying the cookies key
  this.CookieExpire = function() {
    var date = new Date();
    date.setFullYear(date.getYear() - 1);
    document.cookie = CookieName + "=noop; expires=" + date.toGMTString();
  }

  this.cookieExists = function() {
    return getCookValue() ? true : false;
  }

  // This expire function we are using for destroying the cookies key and value by purab
  this.destroy = function(key) {
    var date = new Date();
    date.setFullYear(date.getYear() - 1);
    document.cookie = key+"=; expires="+ date.toGMTString();
    document.cookie = CookieName + "=noop; expires=" + date.toGMTString();

  }

  // This setCookievalue function we are using for saving the cookies key and value
  this.setCookieValue = function(key, value) {
    var temp_cookie = getCookValue();
    if (/[;, ]/.test(value)) {
      // Mac IE doesn't support encodeURI
      value = window.encodeURI ? encodeURI(value) : escape(value);
    }

    // If cookie kay value is present then we are storing the cookie
    if (value) {
      var attrPair = "@" + key + value;

      if (temp_cookie) {
        // If key and cookie value is present then we are replacing the cookies value
        if (new RegExp("@" + key).test(temp_cookie)) {
          //Regular expression is used for finding the key and cookie value of that cookie
          document.cookie =
          temp_cookie.replace(new RegExp("@" + key + "[^@;]*"), attrPair) + this.addVars;
        } else {
          /*
           * Regular expression is used for creating the new cookie as per format
           * Cookies format (NestedMedia=@uuid123456@disable_time55@monthOctober@dateThursday@hour11@languageEnglish
           */
          document.cookie =
          temp_cookie.replace(new RegExp("(" + CookieName + "=[^;]*)(;|$)"), "$1" + attrPair) + this.addVars;
        }
      } else{
        document.cookie = CookieName + "=" + attrPair + this.addVars;
      }
    } else{
      if (new RegExp("@" + key).test(temp_cookie)) {
        document.cookie = temp_cookie.replace(new RegExp("@" + key + "[^@;]*"), "") + this.addVars;
      }
    }
  }

  /*
   * This getCookievalue function we are using for getting the cookies value as per key CookieName
   * Here we written function for checking the cross brower issue
   */
  this.getCookieValue = function(key) {
    var temp_cookie = getCookValue();

    if (temp_cookie) {
      var cookname = temp_cookie.match(new RegExp("@" + key + "([^@;]*)"));
      if (cookname) {
        var value = cookname[1];
        if (value) {
          // Mac IE doesn't support decodeURI
          return window.decodeURI ? decodeURI(value) : unescape(value);
        }
      }
    }
  }
} // Here end of class called "NestedMedia.Utility.Class.NMCookieHandler"


/*
 * Here we are creating the NestedMedia.Utility.Class.TimeFunctions class
 * You can get the date and time related functions in this class
 */
NestedMedia.Utility.Class.TimeFunctions = function() {

  function translate (i) {
    var j = Math.round(i * 100);
    return Math.floor(j / 100) + (j % 100 > 0 ? "." + p(j % 100) : "");
  }

    /*
     * In this function we are calculating the days, hous, minutes and seconds
     * We need to pass to different dates to this function and the retun format.
     * Format parameteres will be like this(Days, Hours, Minutes, Seconds)
     */
  this.getTheDiffTime = function(dateone, datetwo,format){
    if (dateone > datetwo) {
      var sec = dateone.getTime() - datetwo.getTime();
    } else {
      var sec = datetwo.getTime() - dateone.getTime();
    }
    var second = 1000; // getting the second from milisecond
    var minute = 60 * second; // Calculating the mintues from second
    var hour = 60 * minute; // Calculating the hour from minute
    var day = 24 * hour; // Calculating the day from hour

    if (format == "Days"){
      var rformat = Math.floor(sec / day);
      sec -= rformat * day;
    //alert("days: "+rformat);
    }else if (format == "Hours"){
      // find the hours
      rformat = translate(sec / hour);
    //alert("hours: "+rformat);
    }else if (format == "Minutes"){
      //find the mintues
      rformat= translate(sec / minute);
    //alert("minutes: "+ rformat);
    }else if (format == "Seconds"){
      //find the seconds
      rformat = translate(sec / second);
    //alert("seconds: "+rformat);
    }

    return rformat
  //alert(rformat);
  }

 /*
  * Finding the month string depending on date
  */
  this.getMonthString = function(date){
    var month_name = new Array(12);
    month_name[0] = "January"
    month_name[1] = "February"
    month_name[2] = "March"
    month_name[3] = "April"
    month_name[4] = "May"
    month_name[5] = "June"
    month_name[6] = "July"
    month_name[7] = "August"
    month_name[8] = "September"
    month_name[9] = "October"
    month_name[10] = "November"
    month_name[11] = "December"
    monstring = month_name[date.getMonth()];
    //alert ("Current month = " + month_name[date.getMonth()]);
    return monstring;
  }

 /*
  * Finding the weekday string depedning on date
  */
  this.getDayString = function(date){
    var weekday = new Array(7);
    weekday[0] = "Sunday";
    weekday[1] = "Monday";
    weekday[2] = "Tuesday";
    weekday[3] = "Wednesday";
    weekday[4] = "Thursday";
    weekday[5] = "Friday";
    weekday[6] = "Saturday";
    daystring = weekday[date.getDay()];
    return daystring
  }

}



/*
 * Here we are creating the NestedMedia.Utility.Class.EventManager class
 * You can get the event related functions in this class
 */
//var ObjNMEventManager = new NestedMedia.Utility.Class.NMEventManager();
NestedMedia.Utility.Class.NMEventManager = function(clientID,class_key,userHost) {
var garbagelist = [];
//var base_url = "http://svcs.nestedmedia.com/nmjs/"; // "http://localhost/nmjs/"
var NM_VERSION = "0_6";

//var base_url = "http://174.143.130.113/nmjs/v" + NM_VERSION + "/"; //"http://localhost/nmjs/v" + NM_VERSION + "/";

var base_url = "http://svcs.nestedmedia.com/nmjs/"; // "http://localhost/nmjs/"

//var base_url = "http://192.168.2.15/nmjs/";
var debug = 0; // set to 0 to turn off jsonp debughandler callback from jsmsg.php, 1 to turn on

this.debugHandler = function(msg) {
  alert(msg);
  return;
}

function getResolution(){
//var NM_resolution = "UnCommon"
ObjNMEventManager.NM_resolution = "UnCommon"
if (navigator.appVersion.indexOf("4.") != -1 &&
    navigator.appName.indexOf("Explorer") != -1) {
//    var NM_resolution = screen.width + "x" + screen.height;
      ObjNMEventManager.NM_resolution = screen.width + "x" + screen.height;
} else {
//    var NM_resolution = screen.width + "x" + (screen.height);
      ObjNMEventManager.NM_resolution = screen.width + "x" + (screen.height);
}
}

/*
 * This getMousePosition function we are using for capturing the Mouse coordinates of on browser
 */
var isIE = document.all?true:false;
if (!isIE) document.captureEvents(Event.MOUSEMOVE);
document.load = getMousePosition;
document.onmousemove = getMousePosition;

//var NM_posX, NM_posY;
function getMousePosition(e) { // as per Document body
    
  //var _x;
  //var _y;
  if (!isIE) {
//    _x = e.pageX;
//    _y = e.pageY;
      ObjNMEventManager.NM_posX = e.pageX;
      ObjNMEventManager.NM_posY = e.pageY;
  }
  if (isIE) {
//    _x = event.clientX + document.body.scrollLeft;
//    _y = event.clientY + document.body.scrollTop;
      ObjNMEventManager.NM_posX = event.clientX + document.body.scrollLeft;
      ObjNMEventManager.NM_posY = event.clientY + document.body.scrollTop;
  }

//ObjNMEventManager.NM_posX = _x;
//ObjNMEventManager.NM_posY = _y;
//alert(NM_posY);
}

/*
 * This function we are using for capturing the Screen size of monitor
 */
function getScreenPosition() {
//this.ScrY = window.screenTop != undefined ? window.screenTop : window.screenY;
//this.ScrX = window.screenLeft != undefined ? window.screenLeft : window.screenX;
ObjNMEventManager.ScrY = window.screenTop != undefined ? window.screenTop : window.screenY;
ObjNMEventManager.ScrX = window.screenLeft != undefined ? window.screenLeft : window.screenX;
//window.ScrX = top;
//window.ScrY = left; 
}

/*
 * This function we are using for capturing the browser Window size
 */
function getbrowserWindowSize() {
  var browserWidth = 0, browserHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    browserWidth = window.innerWidth;
    browserHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    browserWidth = document.documentElement.clientWidth;
    browserHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    browserWidth = document.body.clientWidth;
    browserHeight = document.body.clientHeight;
  }
    //window.alert( 'Width = ' + browserWidth );
   // window.alert( 'Height = ' + browserHeight );
  
//   this.NM_browser_window_size = browserWidth + 'x' + browserHeight;
     ObjNMEventManager.NM_browser_window_size = browserWidth + 'x' + browserHeight;
}
document.load = getbrowserWindowSize;

/*
 * This function we are using for capturing the browser Unix Timestamp 
 */
function getbrowserUnixTime() {
// this.NM_browser_unix_time = Math.round(new Date().getTime() / 1000);
ObjNMEventManager.NM_browser_unix_time = Math.round(new Date().getTime() / 1000);
// alert(this.NM_browser_unix_time);
}

/*
 * This function we are using for capturing the browser name
 */
function whichBrs() {
var agt=navigator.userAgent.toLowerCase();
if (agt.indexOf("opera") != -1) return 'Opera';
if (agt.indexOf("staroffice") != -1) return 'Star Office';
if (agt.indexOf("webtv") != -1) return 'WebTV';
if (agt.indexOf("beonex") != -1) return 'Beonex';
if (agt.indexOf("chimera") != -1) return 'Chimera';
if (agt.indexOf("netpositive") != -1) return 'NetPositive';
if (agt.indexOf("phoenix") != -1) return 'Phoenix';
if (agt.indexOf("firefox") != -1) return 'Firefox';
if (agt.indexOf("chrome") != -1) return 'Chrome';
if (agt.indexOf("skipstone") != -1) return 'SkipStone';
if (agt.indexOf("safari") != -1) return 'Safari';
if (agt.indexOf("msie") != -1) return 'Internet Explorer';
if (agt.indexOf("netscape") != -1) return 'Netscape';
if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';

if (agt.indexOf('\/') != -1) {
if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
return navigator.userAgent.substr(0,agt.indexOf('\/'));}
else return 'Netscape';} else if (agt.indexOf(' ') != -1)
return navigator.userAgent.substr(0,agt.indexOf(' '));
else return navigator.userAgent;
}

function getbrowserName() {
var browserName = whichBrs();
ObjNMEventManager.NM_browser_name = browserName;
//alert("hai"+browserName);
}

function getloadevent(){
     var load_page = ObjNMEventManager.NM_pageload_id;
     //alert("load hai"+ObjNMEventManager.NM_pageload_id);
}


function generateParams(target,event){ 
 // grab timestamp for this click event
//  var d = new Date();
ObjNMEventManager.d = new Date();
//We are calling getbrowserWindowSize function on each event
getbrowserWindowSize();
//We are calling getbrowserUnixTime function on each event
getbrowserUnixTime();
//We are calling getbrowserName function on each event
getbrowserName();
//We are calling getResolution function on each event
getResolution();
//We are calling page load function on each event
getloadevent();

// Fix for trans_id will return for only generic events
if (target != ''){    
    ObjNMEventManager.NM_transaction_id = "undefined";
    // Generating the new UUID as a trans_id for generic event handler
    //NM_smartlink_jsonpRequest(base_url+'getuuid.php?jsonp=mycallback&name=for_trans_id');
    var randomUUID = Math.uuid();
    ObjNMEventManager.NM_transaction_id = randomUUID;
    //alert("hai trans"+ObjNMEventManager.NM_transaction_id);
}

var ObjNMCookieHandler = new NestedMedia.Utility.Class.NMCookieHandler("NestedMedia", 44640);
var UUIDVal = ObjNMCookieHandler.getCookieValue("cookieid");
ObjNMEventManager.get_cookieid(UUIDVal);

 //code for getting the cookieid from cookies
//  var cookieid = (typeof(ObjNMCookieHandler) != "undefined") ? ObjNMCookieHandler.getCookieValue('cookieid') : '';
    ObjNMEventManager.cookieid = (typeof(ObjNMCookieHandler) != "undefined") ? ObjNMCookieHandler.getCookieValue('cookieid') : '';
  //var clientID = (typeof(window.NM_SmartSite_ID) != "undefined") ? window.NM_SmartSite_ID : '';
  return {'event':event,
          'url':location.href,
          'pageload_id':ObjNMEventManager.NM_pageload_id,
          'referrer':document.referrer,
          'target':target,
          'posx':ObjNMEventManager.NM_posX,
          'posy':ObjNMEventManager.NM_posY,
          'screen_res':ObjNMEventManager.NM_resolution,// resolution renamed to screen_res
          'browser_res':ObjNMEventManager.NM_browser_window_size, //browser_resolution renamed to browser_res
          'duration':ObjNMEventManager.NM_milisecond,
          'trans_id':ObjNMEventManager.NM_transaction_id,
          'client_id':ObjNMEventManager.clientID, //clientid renamed to client_id
          'cookie_id':ObjNMEventManager.cookieid, //cookieid renamed to cookie_id
          'content_id':ObjNMEventManager.adID, //adid renamed to content_id
          'browsertime':ObjNMEventManager.d,
          'browser_utimestamp' :ObjNMEventManager.NM_browser_unix_time, //browser_utimestamp added for unix timestamp
          'browsername':ObjNMEventManager.NM_browser_name, //browsername:navigator.appName,
          'browserversion':navigator.appVersion,
          'platform':navigator.platform,
          'lib_version':NM_VERSION
          };
}


function send_msg(data,debug){
// remove any previous script tag to avoid memory consumption
 //alert("this is clientid: " + data.client_id);
 //alert("this is adid: " + data.content_id);
 //alert("this is cookieid: " + data.cookie_id);
 //alert("this is browser resolution: " + data.browser_res);
 //alert("this is screen resolution: " + data.screen_res);
 //alert("this is trans id: " + data.trans_id);
 //alert("this is url: " + data.url);
 //alert("this is referrer: " + data.referrer);
 //alert("this is target: " + data.target);
 //alert("this is mouse x position: " + data.posx);
 //if(data.timer!='0'){alert("this is timer: " + data.timer);}
 //alert("duration: " + data.duration);
 //alert("browsertime" + data.browsertime);
 //alert("browser_utimestamp:" + data.browser_utimestamp);
 //alert("NM version:" + data.lib_version );
 //alert("Browser Name:" + data.browsername );
 //alert("this is load id: " + data.pageload_id);
    
  if(garbagelist.length > 0){
    document.body.removeChild(garbagelist[0]);
    // Remove any old script tags.
    //ObjNMEventManager.NM_remove_garbage('NM_smartlink_JSONP');
    // reset the garbage collection array
    garbagelist.splice(1,0);
  }

    if( data.trans_id != 'undefined' ) { // This if condition script We added for removing the garbage collection of Generic Event's '
     //Code for complete removing the code
     //ObjNMEventManager.NM_remove_garbage('NM_smartlink_JSONP');
      }

  // send msg to producer
  var url = base_url+'jsmsgr.php?client_id='+data.client_id+                    
                  '&content_id='+data.content_id+
                  '&cookie_id='+data.cookie_id+
                  '&pageload_id='+data.pageload_id+
                  '&event='+data.event+
                  '&posx='+data.posx+
                  '&posy='+data.posy+
                  '&duration='+data.duration+
                  '&trans_id='+data.trans_id+
                  '&url='+data.url+ 
                  '&referrer='+data.referrer+ 
                  '&target='+data.target+ 
                  '&screen_res='+data.screen_res+ //resolution renamed to screen_res                  
                  '&browser_res='+data.browser_res+ //browser_resolution renamed to browser_res
                  '&browsername='+data.browsername+
                  '&browserversion='+data.browserversion+
                  '&platform='+data.platform+
                  '&browsertime='+data.browsertime+
                  '&browser_utimestamp='+data.browser_utimestamp+ //browser_utimestamp added for unix timestamp
                  '&lib_version='+data.lib_version+ //Library version added
                  '&debug='+debug;
  var js = document.createElement("script");
  js.id = 'NM_smartlink_JSONP';
  // alert(url.length);
  js.setAttribute("src",url+"&CacheBuster="+Math.random());
  js.setAttribute("type","text/javascript");

  // add element to scriptlist for garbage removal later
  garbagelist[0] = js;
  // write the jsonp script tag
  document.body.appendChild(js);

  js.text = "";
  if( data.trans_id != 'undefined' ){return data.trans_id;}
  
}

/*
 * This Function will handle (load, onclick,onmouseover,onmouseout) the events for all links on browser page
 * For Using handleEvent from outside please pass following parameters
 * ObjNMEventManager.handleEvent(event,'Description goes here',1)
 */
this.handleEvent = function(evt_name,evt_desc,trans_flag) {
    //alert(evt_name.type);
 //  var clientID = (typeof(window.NM_SmartSite_ID) != "undefined") ? window.NM_SmartSite_ID : '';
//  var threshold = (typeof(window.NM_mouseevent_threshold) != "undefined") ? window.NM_mouseevent_threshold : '0';
  ObjNMEventManager.clientID = (typeof(window.NM_SmartSite_ID) != "undefined") ? window.NM_SmartSite_ID : '';
  ObjNMEventManager.threshold = (typeof(window.NM_mouseevent_threshold) != "undefined") ? window.NM_mouseevent_threshold : '0';
  ObjNMEventManager.adID = (typeof(window.NM_SmartSite_AdID) != "undefined") ? window.NM_SmartSite_AdID : '';
  
  if(evt_name.type !='undefined' && trans_flag != '1' ) {
            // Here We are handling the load event
            if(evt_name.type == 'load') {
                // Generating the new UUID as a trans_id for generic event handler(There is issue with JSONp request time)
                //NM_smartlink_jsonpRequest(base_url+'getuuid.php?jsonp=mycallback&name=for_trans_id&onload=yes');
                var randomUUID = Math.uuid();
                ObjNMEventManager.NM_transaction_id = randomUUID;
                ObjNMEventManager.NM_pageload_id = randomUUID;
                // write jsonp script to send message
                var data = generateParams('','load')
                send_msg(data,debug);

                

            
            } else {                
            // find target anchor tag
          var el;
          if (window.event && window.event.srcElement)
            el = window.event.srcElement;
          if (evt_name && evt_name.target)
            el = evt_name.target;
          if (!el)
            return;

          // find link href
          while (el.nodeName.toLowerCase() != 'a' &&
              el.nodeName.toLowerCase() != 'body')
            el = el.parentNode;
          if (el.nodeName.toLowerCase() == 'body')
            return;

            if(evt_name.type=='mouseover') {
                NM_timeCount();
            }
            if(evt_name.type=='mouseout' ) {
              NM_stopTimeCount();
            }

         // write jsonp script to send message
            var data = generateParams(el.href,evt_name.type);
         //For Mouseclick Event we are sending data to ActiveMQ
            if(evt_name.type == 'click') {
                send_msg(data,debug);
                if(data.url == data.target) {
                    NM_stopTimeCount();
                }
            }
        //check for mouseover events as they don't need to send messages and check for threshold which should be greater than or equal to the mouseover-duration
            if(evt_name.type != 'mouseover' && evt_name.type != 'click' && ObjNMEventManager.threshold > '0' && ObjNMEventManager.NM_milisecond >= ObjNMEventManager.threshold) {
                    //if(threshold) {
                        //if(threshold > '0' && ObjNMEventManager.NM_milisecond >= threshold){
                            send_msg(data,debug);
                          //  alert('coming here');
                       // }
                    //} else { //if threshold is not defined
                        //send_msg(data,debug);
                   // }
                }
            }
              
  } else if(ObjNMEventManager.clientID !='')  {
       // Generating the new UUID as a trans_id
      //NM_smartlink_jsonpRequest(base_url+'getuuid.php?jsonp=mycallback&name=for_trans_id');
      var randomUUID = Math.uuid();
      ObjNMEventManager.NM_transaction_id = randomUUID;
      //alert("sfsfd"+this.NM_transaction_id);
        // write jsonp script to send message       
        var data = generateParams('',evt_name);
        var NM_transaction_id = send_msg(data,debug);
        //alert(NM_transaction_id);
        return NM_transaction_id;
             
   }
  
}

/**
 * cross-browser event handling for IE5+, NS6 and Mozilla
 * By Scott Andrew
 */
//This addEvent function we are using for external class use
this.addEvent = function(elm, evType, fn, useCapture) {
  if (elm.addEventListener) { // Mozilla, Netscape, Firefox
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent) {  // IE5 +
    var r = elm.attachEvent('on' + evType, fn);    
    return r;
  } else {
    elm['on' + evType] = fn;
  }
}

/**
 * Install listeners
 */
this.addListeners = function() {
  if (!document.getElementById)
    return;

  var all_links = document.getElementsByTagName('a');
  var ObjNMEventManager = new NestedMedia.Utility.Class.NMEventManager(clientID,class_key,usrHost);

  for (var i = 0; i < all_links.length; i++) {
    if(class_key){
      if (all_links[i].className && (' ' + all_links[i].className + ' ').indexOf(' ' + class_key + ' ') != -1) {
        ObjNMEventManager.addEvent(all_links[i], 'click', ObjNMEventManager.handleEvent, false);
        ObjNMEventManager.addEvent(all_links[i], 'mouseover', ObjNMEventManager.handleEvent, false);
        ObjNMEventManager.addEvent(all_links[i], 'mouseout', ObjNMEventManager.handleEvent, false);
        //addEvent(all_links[i], 'mouseout', handleMouseOut, false);
      }
    } else { //if(all_links[i].href.startsWith('http://') && !all_links[i].href.match(usrHost)){
      ObjNMEventManager.addEvent(all_links[i], 'click', ObjNMEventManager.handleEvent, false);
      ObjNMEventManager.addEvent(all_links[i], 'mouseover', ObjNMEventManager.handleEvent, false);
      ObjNMEventManager.addEvent(all_links[i], 'mouseout', ObjNMEventManager.handleEvent, false);
      //addEvent(all_links[i], 'mouseout', handleMouseOut, false);
    }
  }
}

/*
 * Using the AddJsFile function we can add the javascript file dynamically from HTML
 */
  function AddJsFile(file) {
    var script  = document.createElement('script');
    script.src  = file;
    script.type = 'text/javascript';
    //script.defer = true;

    document.getElementsByTagName('head').item(0).appendChild(script);
  }

/*
 * Using the RemoveJsCssFile function we can remove the javascript or css file dynamically from HTML
 */
  function RemoveJsCssFile(filename, filetype) {
    var targetelement = (filetype=="js") ? "script" : (filetype=="css") ? "link" : "none" //determine element type to create nodelist from
    var targetattr = (filetype=="js") ? "src" : (filetype=="css") ? "href" : "none" //determine corresponding attribute to test for
    var allsuspects = document.getElementsByTagName(targetelement)
    for (var i = allsuspects.length; i >= 0; i--){ //search backwards within nodelist for matching elements to remove
      if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!= null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
        allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
    }
  }

/*
 * This is common jsonp function for making the NM_smartlink_jsonpRequest
 */
function NM_smartlink_jsonpRequest(url, removescript, callback, name, query){    

    if (url.indexOf("?") > -1)
        url += "&jsonp="
    else
        url += name + "&";
    if (query)
        url += encodeURIComponent(query) + "&";
    url += new Date().getTime().toString(); // prevent caching

    var JSONPscript = document.createElement("script");
    JSONPscript.id = 'NM_smartlink_jsonpRequest';
    JSONPscript.setAttribute("src", url + "&CacheBuster=" + Math.random());
    JSONPscript.setAttribute("type","text/javascript");
    // write the jsonp script tag
    document.body.appendChild(JSONPscript);
    //script.text = "";    
//alert("Here we are checking the dyanmically added script status, Status will be null: "+ script);
}

/*
 * This function we are calling after Using the JSONP request in DOM and for the destroying garbage collection of script
 */
this.NM_remove_garbage = function(id) {
    // Remove any old script tags.    
    while (JSONPscript = document.getElementById(id)) {
      JSONPscript.parentNode.removeChild(JSONPscript);
      // Browsers won't garbage collect this object.
      // So empty it to avoid a major memory leak.
      for (var prop in JSONPscript) {
         if(!isIE) delete JSONPscript[prop];
      }
    }
    id.text = "";    
}

/*
 * This is jsonp function for making the NM_smartlink_jsonpRequest_forcookie only
 */
function NM_smartlink_jsonpRequest_forcookie(url, name, query){
    if (url.indexOf("?") > -1)
        url += "&jsonp="
    else
        url += name + "&";
    if (query)
        url += encodeURIComponent(query) + "&";
    url += new Date().getTime().toString(); // prevent caching

  script = document.createElement('script');
  script.src = url+ "&CacheBuster=" + Math.random();
  script.id = 'JSONP_forcookie';
  script.type = 'text/javascript';
  script.charset = 'utf-8';
  // Add the script to the head, upon which it will load and execute.
  var head = document.getElementsByTagName('head')[0];
  head.appendChild(script);
   // script.text = "";
}

/*
File: Math.uuid.js
Version: 1.3
Change History:
  v1.0 - first release
  v1.1 - less code and 2x performance boost (by minimizing calls to Math.random())
  v1.2 - Add support for generating non-standard uuids of arbitrary length
  v1.3 - Fixed IE7 bug (can't use []'s to access string chars.  Thanks, Brian R.)
  v1.4 - Changed method to be "Math.uuid". Added support for radix argument.  Use module pattern for better encapsulation.

Latest version:   http://www.broofa.com/Tools/Math.uuid.js
Information:      http://www.broofa.com/blog/?p=151
Contact:          robert@broofa.com
----
Copyright (c) 2008, Robert Kieffer
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of Robert Kieffer nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*
 * Generate a random uuid.
 *
 * USAGE: Math.uuid(length, radix)
 *   length - the desired number of characters
 *   radix  - the number of allowable values for each character.
 *
 * EXAMPLES:
 *   // No arguments  - returns RFC4122, version 4 ID
 *   >>> Math.uuid()
 *   "92329D39-6F5C-4520-ABFC-AAB64544E172"
 *
 *   // One argument - returns ID of the specified length
 *   >>> Math.uuid(15)     // 15 character ID (default base=62)
 *   "VcydxgltxrVZSTV"
 *
 *   // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
 *   >>> Math.uuid(8, 2)  // 8 character ID (base=2)
 *   "01001010"
 *   >>> Math.uuid(8, 10) // 8 character ID (base=10)
 *   "47473046"
 *   >>> Math.uuid(8, 16) // 8 character ID (base=16)
 *   "098F4D35"
 */
Math.uuid = (function() {
  // Private array of chars to use
  var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

  return function (len, radix) {
    var chars = CHARS, uuid = [], rnd = Math.random;
    radix = radix || chars.length;

    if (len) {
      // Compact form
      for (var i = 0; i < len; i++) uuid[i] = chars[0 | rnd()*radix];
    } else {
      // rfc4122, version 4 form
      var r;

      // rfc4122 requires these characters
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';

      // Fill in random data.  At i==19 set the high bits of clock sequence as
      // per rfc4122, sec. 4.1.5
      for (var i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | rnd()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
        }
      }
    }

    return uuid.join('');

  };
})();

// Deprecated - only here for backward compatability
var randomUUID = Math.uuid;





/*
 * gettting the Random UUID as data variable and uuid saving into cookies.
 */
this.get_cookieid = function(UUID) {
  //alert("I got cookie_id(uuid) in cookies"+UUID);
//ObjNMEventManager.NM_remove_garbage('JSONP_forcookie');
  if (!UUID) { //if uuid not present then we are creating or saving the cookies
    //alert("I did not got cookie_id(uuid) in cookies"+UUID);
/*
 * Making the jsonp request and fetching the random uuid
 * through this call we are saving uuid as cookieid in browser cookies
 */
    //NM_smartlink_jsonpRequest(base_url+'getuuid.php?jsonp=mycallback&name=for_UUID');
    var randomUUID = Math.uuid();
    var ObjNMCookieHandler = new NestedMedia.Utility.Class.NMCookieHandler("NestedMedia", 44640);
    ObjNMCookieHandler.setCookieValue("cookieid",randomUUID);

   }
}

/**
 * authenticate the calling usr/host
 */
this.authenticate = function(client) {
  // 1) need cookie check here for credentials caching
/*
 * here we are making the jsonp request and fetching the cookieid from browser cookies
 * This base_url will call the get_cookieid function in return function.
 */
  //NM_smartlink_jsonpRequest_forcookie(base_url+'getcookies.php?jsonp=mycallback&name=test');
var ObjNMCookieHandler = new NestedMedia.Utility.Class.NMCookieHandler("NestedMedia", 44640);
var UUIDVal = ObjNMCookieHandler.getCookieValue("cookieid");
//var ObjNMEventManager = new NestedMedia.Utility.Class.NMEventManager();
ObjNMEventManager.cookieid  = ObjNMEventManager.get_cookieid(UUIDVal);

  // 2) if no session cookie, authenticate from db (simulated here)

  // client authentication db proxy - to be replaced by db lookup through server-side script include
  var client_arr = new Array(['123456','localhost'],['654321','projectwordhatch.com'],['a221ece3-3765-483c-ab8a-e087ff7cde28','30ninjas.com'],['425955c2-428b-4094-8e99-6f338a5fbdc0','hellomovies.com'],['96ae44e0-4046-490c-ad26-b19275a850a3','videolectures.net'],['96ae44e0-4046-490c-ad26-b19275a850a4','wrapnatural.com']); //['96ae44e0-4046-490c-ad26-b19275a850a3','videolectures.net'],
  //var client_arr = new Array(['123456','localhost'],['654321','projectwordhatch.com'],['a221ece3-3765-483c-ab8a-e087ff7cde28','30ninjas.com'],['425955c2-428b-4094-8e99-6f338a5fbdc0','hellomovies.com'],['89d4706e-221b-4be4-bcab-1b94ca6b444b','expotv.com'],['96ae44e0-4046-490c-ad26-b19275a850a3','videolectures.net']);

  // 3) compare client side credentials with user list from db, match the registered host to the calling host
  for(i=0; i<client_arr.length; i++){
    if(client_arr[i][0] == client && location.hostname.match(client_arr[i][1])){
      return client_arr[i][1];
    }
  }
  return 0;
}

/**
 *  protype startsWith function
 */
String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

/**
 * prototype cleanString function to help prevent cross-site scripting attacks
 * -- use on all client configuration variables
 */
this.cleanString = function(str) {
  str = unescape( str.toString() );
  str = str.replace(/</g, '&lt;');
  str = str.replace(/>/g, '&gt;');
  return str;
}

}

var NM_temp_milisecond = 0;
var NM_milisecond;
function NM_timeCount() {

ObjNMEventManager.NM_milisecond = NM_temp_milisecond;
NM_temp_milisecond = NM_temp_milisecond + 1;
NM_milisecond = setTimeout("NM_timeCount()",1);
}

function NM_stopTimeCount() {
NM_temp_milisecond = 0;
clearTimeout(NM_milisecond);
}


/************************ main loop **************************/

// get user ID from client side config variable
var clientID = (typeof(window.NM_SmartSite_ID) != "undefined") ? window.NM_SmartSite_ID : '';
var adID = (typeof(window.NM_SmartSite_AdID) != "undefined") ? window.NM_SmartSite_AdID : '';
var adID_flag = (typeof(window.NM_AD_FLAG) != "undefined") ? window.NM_AD_FLAG : '';
var class_key = ((typeof(window.NM_SmartSite_ClassKey) != "undefined") && window.NM_SmartSite_ClassKey != null) ? window.NM_SmartSite_ClassKey : '';

var usrHost = '';

var ObjNMEventManager = new NestedMedia.Utility.Class.NMEventManager(clientID,class_key,usrHost);

if (clientID) {
    if (adID) { //true for ad delivered unit
        //do no authenticate
        class_key = ObjNMEventManager.cleanString(class_key);
        usrHost = location.hostname;
        ObjNMEventManager.addEvent(window, 'load', ObjNMEventManager.handleEvent, false);
        ObjNMEventManager.addEvent(window, 'load', ObjNMEventManager.addListeners, false);
    } else {//publisher tag
        // do the authentication
        //load UUID, Cookie
        clientID = ObjNMEventManager.cleanString(clientID);
        usrHost = ObjNMEventManager.authenticate(clientID);
        if(usrHost){
            class_key = ObjNMEventManager.cleanString(class_key);
            ObjNMEventManager.addEvent(window, 'load', ObjNMEventManager.handleEvent, false);
            ObjNMEventManager.addEvent(window, 'load', ObjNMEventManager.addListeners, false);
        }
    }
} else {
//Dont run at all
}


