/*jslint nomen:true, white:true, sloppy:true, plusplus:true, browser:true, regexp:true */
function checkJQuery(onload, f, own) {
    if (typeof window.jQuery === 'undefined') {
        if (!f) {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'http://tracker.icmconsulting.com/jquery.js';
            document.getElementsByTagName("head")[0].appendChild(script);
            own = true;
        }
        window.setTimeout(function() { checkJQuery(onload, true, own); }, 100);
    } else {
        if (own) {
            window.jQuery.noConflict();
        }
        if (typeof window.jQuery.noop === 'undefined') {
            window.jQuery.noop = function(){};
        }
        onload(window.jQuery);
    }
}

var _IcmTracker = (function() {
    // helpers
    var some = function(pred, array) {
        var i, l;
        for (i = 0, l = array.length; i < l; i++) {
            if (pred(array[i])) {
                return true;
            }
        }
        return false;
    },
    in_array = function(val, array) {
        return some(function(t){return t === val;}, array);
    },
    find = function(pred, array) {
        var i, l;
        for (i = 0, l = array.length; i < l; i++) {
            if (pred(array[i])) {
                return array[i];
            }
        }
        return null;
    },
    map = function(func, array) {
        var i, l, r = [];
        for (i = 0, l = array.length; i < l; i++) {
            r.push(func(array[i]));
        }
        return r;
    },
    get_param = function(url, p) {
        var m = (new RegExp("[\\?&]"+p+"=([^&#]*)")).exec(url);
        if (m) {
            return decodeURIComponent(m[1]);
        } else {
            return "";
        }
    },
    condition_in_url = function(param, values) {
        return in_array(
            get_param(document.location.search, param),
            values || ['y', 'm', 'g']);
    },
    search_engines = {
        google: {
            re: /^http\:\/\/(www\.)?google\.[a-zA-Z]{2,3}\/.*$/i,
            query: 'q'
        },
        yahoo: {
            re: /^http\:\/\/[a-zA-Z.]{0,8}search\.yahoo\.com\/.*$/i,
            query: 'p'
        },
        bing: {
            re: /^http\:\/\/(www\.)?bing\.com\/.*$/i,
            query: 'q'
        },
        yandex: {
            re: /^http\:\/\/(www\.)?yandex\.[a-zA-Z]{2,3}\/.*$/i,
            query: 'text'
        },
        rambler: {
            re: /^http\:\/\/[a-zA-Z.]{0,8}rambler\.ru\/.*$/i,
            query: 'query'
        }
    },
    is_s_referrer = function() {
        if (search_engines.google.re.test(document.referrer)) {
            return search_engines.google;
        } else if (search_engines.yahoo.re.test(document.referrer)) {
            return search_engines.yahoo;
        } else if (search_engines.bing.re.test(document.referrer)) {
            return search_engines.bing;
        } else {
            return null;
        }
    },
    is_r_referrer = function() {
        if (search_engines.yandex.re.test(document.referrer)) {
            return search_engines.yandex;
        } else if (search_engines.rambler.re.test(document.referrer)) {
            return search_engines.rambler;
        } else {
            return null;
        }
    },
    is_f_referrer = function() {
        return (/^http\:\/\/[a-zA-Z.]{0,8}facebook\.com\/.*$/i).test(document.referrer);
    },
    is_e_referrer = function() {
        if (!document.referrer || !document.domain) {
            return false;
        }
        var qd = document.domain.replace('.', '\\.'),
            r = new RegExp('^(http(s?):\\/\\/)?(www\\.)?' + qd + '(\\/.*)?$');
        return !r.test(document.referrer);
    },
    get_cookie = function(name) {
        var matches = new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+\^])/g, '\\$1') + "=([^;]*)").exec(document.cookie);
        return matches ? decodeURIComponent(matches[1]) : undefined;
    },
    set_url = function(param, val) {
        document.cookie = "_icm_"+param+"d_on="+(val?'on':'off')+";path=/";
    },
    set_s = function(query) {
        document.cookie = "_icm_seo_on=on;path=/";
        if (query) {
            document.cookie = "_icm_search_query="+encodeURIComponent(query)+";path=/";
        }
    },
    set_r = function(query) {
        document.cookie = "_icm_russeo_on=on;path=/";
        if (query) {
            document.cookie = "_icm_search_query="+encodeURIComponent(query)+";path=/";
        }
    },
    set_f = function() {
        document.cookie = "_icm_fbseo_on=on;path=/";
    },
    set_e = function() {
        document.cookie = "_icm_ext_on=on;path=/";
    };

    return {
        Init: function(Conditions) {
            var i, l, L, s;

            L = find(condition_in_url, Conditions);
            if (L) {
                for (i = 0, l = Conditions.length; i < l; i++) {
                    set_url(Conditions[i], Conditions[i] === L);
                }
            }

            s = is_s_referrer();
            if (s) {
                set_s(get_param(document.referrer, s.query));
            }
            s = is_r_referrer();
            if (s) {
                set_r(get_param(document.referrer, s.query));
            }
            if (is_f_referrer()) {
                set_f();
            }

            if (is_e_referrer()) {
                set_e();
            }
        },

        ShowPhone: function(flds) {
            var PhoneDiv = document.createElement('div');
            PhoneDiv.innerHTML = flds[0];
            PhoneDiv.setAttribute('id', 'icm_tracker_phone');
            document.body.insertBefore(PhoneDiv, document.body.childNodes[0]);
            PhoneDiv.style.font = flds[1];
            PhoneDiv.style.padding = flds[2];
            PhoneDiv.style.height = flds[3];
            PhoneDiv.style.textAlign = flds[4];
            PhoneDiv.style.border = flds[5];
            PhoneDiv.style.background = flds[6];
            PhoneDiv.style.color = flds[7];
            if (flds[8]) {
                PhoneDiv.style.zIndex = flds[8];
            }
            return true;
        },

        add_param: function(url, param, value) {
            var data, u, p;
            if (/^mailto:/.test(url)) {
                return url;
            }
            data = url.split('?');
            u = data.shift();
            p = data.join('');
            return u + '?' + encodeURIComponent(param) + '=' + encodeURIComponent(value) +'&' + p;
        },

        // checks
        is_url: function(param) {
            return condition_in_url(param) || document.cookie.indexOf('_icm_'+param+'d_on=on') !== -1;
        },

        is_s: function() {
            return is_s_referrer() || document.cookie.indexOf('_icm_seo_on=on') !== -1;
        },

        is_r: function() {
            return is_r_referrer() || document.cookie.indexOf('_icm_russeo_on=on') !== -1;
        },

        is_f: function() {
            return is_f_referrer() || document.cookie.indexOf('_icm_fbseo_on=on') !== -1;
        },

        is_e: function() {
            return is_e_referrer() || document.cookie.indexOf('_icm_ext_on=on') !== -1;
        },

        has_keyword: function(keyword) {
            return get_cookie('_icm_search_query').toLowerCase().indexOf(keyword.toLowerCase()) !== -1;
        }
    };
}());

// Deprecated functions

function processICMTracker(clientID, Conditions, showPhone) {
    _IcmTracker.Init(Conditions);
}

function handleICMTracker(clientID, Conditions) {
    _IcmTracker.Init(Conditions);
}

// Public Checks

function isICMTrackerUrl(param) { return _IcmTracker.is_url(param); }
function isICMTrackerSeo() { return _IcmTracker.is_s(); }
function isICMTrackerRusSeo() { return _IcmTracker.is_r(); }
function isReferrerExternal() { return _IcmTracker.is_e(); }

function isICMTrackerAds() { return _IcmTracker.is_url('a') || _IcmTracker.is_s(); }
function isICMTrackerAdsWOSeo() { return _IcmTracker.is_url('a'); }
function isICMTrackerBds() { return _IcmTracker.is_url('b'); }
function isICMTrackerCds() { return _IcmTracker.is_url('c'); }


