
/**
 * Main Indusnet JavaScript library.
 *
 * @package Indusnet
 * @subpackage INT
 * @author Bijay Rungta <bijay_rungta@indusnet.com>
 * @copyright Indus Net Technologies
 */

var INT = {
    isReady: false,
    isDebug: true,
    ready: function(f) {
        // If the DOM is already ready
        if (INT.isReady) {
            // Execute the function immediately
            if (typeof f == 'string') {
                eval(f);
            } else if (typeof f == 'function') {
                f.apply(document);
            }
        // Otherwise add the function to the wait list
        } else {
            INT.onReadyDomEvents.push(f);
        }
    },

    onReadyDomEvents: [],

    onReadyDom: function() {
        // make sure that the DOM is not already loaded
        if (!INT.isReady) {
            // Flag the DOM as ready
            INT.isReady = true;

            if (INT.onReadyDomEvents) {
                for (var i = 0, j = INT.onReadyDomEvents.length; i < j; i++) {
                    if (typeof INT.onReadyDomEvents[i] == 'string') {
                        eval(INT.onReadyDomEvents[i]);
                    } else if (typeof INT.onReadyDomEvents[i] == 'function') {
                        INT.onReadyDomEvents[i].apply(document);
                    }
                }
                // Reset the list of functions
                INT.onReadyDomEvents = null;
            }
        }
    },

    debugObject: function(obj) {
        var strMsg = '';
        switch (typeof obj) {
            case 'string':
                alert(obj);
            break;

            case 'object':
                for (var property in obj) {
                    strMsg += '\n ' + property + ' => ' + obj[property];
                }
                alert(strMsg);
            break;

            default:
                alert(obj.toString());
            break;
        }
    },

    logMessage: function(arg) {
        if (INT.isDebug) {
            INT.debugObject(arg);
        }
    }
};

/**
 * INT_Uri
 *
 * parseUri 1.2.1
 * (c) 2007 Steven Levithan <stevenlevithan.com>
 * MIT License
 */

INT.Uri = {
    parse: function(str) {
        var o   = INT.Uri.options,
            m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
            uri = {},
            i   = 14;

        while (i--) {
            uri[o.key[i]] = m[i] || "";
        }

        uri[o.q.name] = {};
        uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
            if ($1) uri[o.q.name][$1] = $2;
        });

        return uri;
    },

    options: {
        strictMode: false,
        key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
        q:   {
            name:   "queryKey",
            parser: /(?:^|&)([^&=]*)=?([^&]*)/g
        },
        parser: {
            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
            loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
        }
    }
};

/**
 * INT_Uri
 *
 * parseUri 1.2.1
 * (c) 2007 Steven Levithan <stevenlevithan.com>
 * MIT License
 */

//Get cookie routine by Shelley Powers
function get_cookie(Name) {
  var search = Name + "=";
  var returnvalue = "";
  if (document.cookie.length > 0) {
    offset = document.cookie.indexOf(search)
    // if cookie exists
    if (offset != -1) {
      offset += search.length
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1) end = document.cookie.length;
      returnvalue=unescape(document.cookie.substring(offset, end));
      }
   }
  return returnvalue;
}

INT.Cookie = {

    setCookie: function(name, value, expires, path, domain, secure) {
      // alert('Request to set Cookie => ' + name + ':' + value);
      var curCookie = name + "=" + escape(value) +
          ((expires) ? "; expires=" + expires.toGMTString() : "") +
          ((path) ? "; path=" + path : "") +
          ((domain) ? "; domain=" + domain : "") +
          ((secure) ? "; secure" : "");
      document.cookie = curCookie;
      // alert('Cookie set => ' + name + ':' + value);
    },

    /*
     * This reads a cookie by JavaScript
     *
     * @see http://www.webreference.com/js/column8/functions.html
     */
    getCookie: function(name) {
      var dc = document.cookie;
      var prefix = name + "=";
      var begin = dc.indexOf("; " + prefix);
      if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
      } else
        begin += 2;
      var end = document.cookie.indexOf(";", begin);
      if (end == -1)
        end = dc.length;
      return unescape(dc.substring(begin + prefix.length, end));
    }
};

/**
 * INT_Uri
 *
 * parseUri 1.2.1
 * (c) 2007 Steven Levithan <stevenlevithan.com>
 * MIT License
 */
INT.Tracker = {
    islandingPage: false,

    land: function() {
        now = new Date();
        validTill = now.getTime() + 1000 * 60 * 60 * 24 * 365;

        var expires = new Date(now.getTime() + 1000 * 60 * 60 * 24 * 365);

        oCurrentUri = INT.Uri.parse(location.href);
        name         = 'intref';
        value        = 'unknown';
        path         = '/';
        domain       = oCurrentUri.host;
        secure       = false;

        if (oCurrentUri.queryKey['intref']) {
            INT.Tracker.islandingPage  = true;
            value = oCurrentUri.queryKey['intref'];
        } else if (oCurrentUri.queryKey['ref']) {
            value = oCurrentUri.queryKey['ref'];
            INT.Tracker.islandingPage  = true;
        }

        if (INT.Tracker.islandingPage) {
            INT.Cookie.setCookie(name, value, expires, path, domain, secure);
            if (document.referrer != '') {
                referralUrl = document.referrer;
                INT.Cookie.setCookie('intReferralUrl', referralUrl, expires, path, domain, secure);
            }
            if (Boolean(typeof pageTracker != 'undefined')) {
                pageTracker._trackPageview('/gaPageViewRef_' + value);
            }
        }
    },

    track: function() {
        if (INT.Tracker.islandingPage) {
            return;
        }
        detectedReference = INT.Cookie.getCookie('intref');
        if (Boolean(typeof pageTracker != 'undefined')) {
            pageTracker._trackPageview('/gaReturnViewRef_' + detectedReference);
        }
        return detectedReference;
    }
};

// ----------
// --- BC ---
// ----------

/**
 * Used for async load of sourcefourge bloody button,
 */
function async_load()
{
    var node;
    try {
        // variable _asyncDom is set from JavaScript in the iframe
        // node = top._asyncDom.cloneNode(true); // kills Safari 1.2.4
        node = top._asyncDom;
        // try to remove the first script element, the one that
        // executed all document.writes().
        node.removeChild(node.getElementsByTagName('script')[0]);
    } catch (e) {}
    try {
        // insert DOM fragment at a DIV with id "async_demo" on current page
        document.getElementById('async_demo').appendChild(node);
    } catch (e) {
        try {
            // fallback for some non DOM compliant browsers
            document.getElementById('async_demo').innerHTML = node.innerHTML;
        } catch (e2) {};
    }
}

INT.ready(function() {
    var msg = document.getElementById('broadcastMessage');
    if (msg) {
        msg.getElementsByTagName('a')[0].onclick = function() {
            msg.style.display = 'none';
        }
    }
});

/*********************************
*** INT_Loader *******************
**********************************/
INT.Loader =
{
    include: function(url) {
        //alert('Including Url: ' + url);
        document.write('<script type="text/javascript" '
            + 'src="' + url + '"></script>');
    }
}


