/**
 * Multiple number replacement script.
 *
 * @param   object  The parent object scope. This is where we assign the JSON-P
 *                  callback function.
 * @return  void
 */
var source, keyword_ppc, campaign, adcampaign, gclid, type, phone_number, ad_type, display_format, mm_c1, mm_c2, mm_c3, mm_aid, mm_protocol_json;
var number_placeholderarray = new Array("numberassigned","numberassigned_footer", "numberassigned_top","numberassigned_left","numberassigned_right","numberassigned_support","numberassigned_1","numberassigned_2","numberassigned_3","numberassigned_4","numberassigned_5","numberassigned_6","numberassigned_7","numberassigned_8","numberassigned_9","numberassigned_10");
var promo_placeholderarray = new Array("promoassigned","promoassigned_footer", "promoassigned_top","promoassigned_left","promoassigned_right","promoassigned_support","promoassigned_1","promoassigned_2","promoassigned_3","promoassigned_4","promoassigned_5","promoassigned_6","promoassigned_7","promoassigned_8","promoassigned_9","promoassigned_10");
var tnarray=new Array("","");
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
mm_protocol_json = (("https:" == document.location.protocol) ? "https://ssl" : "http://www");

if (typeof mm_debug == 'undefined'){
    mm_debug = 0;
}

if (typeof mm_logError === 'undefined'){
    mm_logError = function (value){
        if (!mm_debug){
            return;
        }

        if (typeof console != 'undefined'){
            //	alert (value);
            //}else{
            console.log(value);
        }
    };
}

//name of the campaign to fetch in trackable numbers associated with campaign, leave blank to fetch with no campaign association
campaign = getVar("mm_campaign");
if (!campaign && typeof mm_c != 'undefined'){
    campaign = mm_c;
}
mm_logError("[spc-prod] campaign="+campaign);

mm_logError("[spc-prod] GUID amd UUID creation");
if (campaign){
    if (!cookieExistsName("MM_GUID")){
        currentGUID = createGUID();
        setcookie("MM_GUID",currentGUID,2628000);
    }else{
        currentGUID = get_cookie("MM_GUID","")
    }
    if (!cookieExistsName("MM_UUID")){
        currentUUID = createUUID();
        setcookie("MM_UUID",currentUUID,1440);
    }else{
        currentUUID = get_cookie("MM_UUID","")
    }

    // This variable is used for UUID if this visit is determined to be a new 
    // session
    var spareUUID = createUUID();
}else{
    currentGUID = '';
    currentUUID = '';
    spareUUID = '';
}

mm_logError("[spc-prod] loading...");

Multi_Number = (function (parent_scope) {
    mm_logError("[spc-prod] running multi-number");
    var
    // Holds the HTML class name we expect to find wrapping destination
    // numbers
    DESTINATION_NUMBER_CLASS = 'mm-phone-number',
    // Holds the desired cookie name for the multi-number replace cache
    CACHE_COOKIE_NAME = 'MM_MULTICACHE',
    // Holds the desired lifetime for the cache cookie in minutes
    CACHE_COOKIE_LIFETIME = 720, // 720 minutes = 12 hours
    // Holds the prefix we will use for JSON-P function names
    JSONP_RECEIVER_FUNCTION_PREFIX = 'mm_';

    /**
     * Defines a simple for-each function that accepts either an object or an
     * array to loop over, invoking the passed callback function for each item.
     *
     * @param   mixed     The object or array to loop over.
     * @param   callback  The callback function to run for each item.
     * @return  void
     */
    var for_each = function (subject, callback) {
        var
        // Holds the key/index value
        index = null,
        // Shortcut variable to the current value
        value = null,
        // Holds the result of the callback function
        result = null;

        // Loop over the subject object/array
        for (index in subject) {
            // added this to filter out IE class erroneous returns
            if (!subject.hasOwnProperty(index)){
                continue;
            }
            // Grab a shortcut variable to the current value
            value = subject[index];

            // Invoke the callback function, passing the index and value
            result = callback(index, value);

            // If the result of the callback is anything other then undefined
            if (typeof result !== 'undefined' && result !== null) {
                // Return the result
                return result;
            }
        }
    };

    /**
     * Attempts to return a cookie string. If the cookie is unavailable, we
     * will return boolean false.
     *
     * @param   string  The name of the cookie to search for.
     * @return  mixed   If we find the cookie, we return the cookie string. If
     *                  we are unable to find the cookie, we return boolean
     *                  false.
     */
    var get_cookie_value = function (name) {
        var
        // Grab a shortcut value to the cookie string
        cookie = document.cookie,
        // Define a variable to hold the index of the cookie name
        name_index = null, equals_index = null, end_index = null;

        // If no cookie is defined
        if ( ! cookie) {
            return false; // Do nothing
        }

        // Attempt to find the string index for this cookie name
        name_index = cookie.indexOf(name);

        // If we are unable to find this cookie name in the cookie string
        if (name_index === -1) {
            return false; // Do nothing
        }

        // Attempt to find the index of the first equals sign after the cookie
        // name
        equals_index = cookie.indexOf('=', name_index) + 1;

        // If we were unable to find the equals sign
        if (equals_index === -1) {
            return false; // Do nothing
        }

        // Attempt to find the end of the cookie string
        end_index = cookie.indexOf(';', equals_index);

        // If we were unable to find the semicolon
        if (end_index === -1) {
            // Just use the end of the string as the last position
            end_index = cookie.length;
        }

        // Grab the substring of the cookie value and return it
        return cookie.substring(equals_index, end_index);
    };

    /**
     * Assigns or updates a cookie value.
     *
     * @param   string  The name of the cookie to update.
     * @param   string  The value to insert for the cookie.
     * @param   int     When to expire the cookie, in minutes.
     * @return  void
     */
    var set_cookie_value = function (name, value, expiration_in_minutes) {
        var
        // Holds the cookie string we will write
        cookie_string = name + '=' + value + '; ',
        // Create a new JavaScript date objct to get the current time
        today = new Date(),
        // Create a timestamp for when to expire the cookie
        cookie_expiration_timestamp = today.getTime() + (1000 * 60 *
            expiration_in_minutes),
        // Create a new date object to hold the expiration time
        cookie_expiration_object = new Date(cookie_expiration_timestamp),
        // Grab the actual cookie expiration date string
        cookie_expiration_gmt_string = cookie_expiration_object
        .toGMTString(),
        // Holds the subdomain
        subdomain = null;

        // Add on the expiration date and time
        cookie_string += 'expires=' + cookie_expiration_gmt_string + '; path=/; ';

        // Grab the subdomain from the hostname
        subdomain = getSubDomain(location.hostname);

        // Add the subdomain to the end of the cookie string
        cookie_string += 'domain=' + subdomain;

        // Assign the cookie
        document.cookie = cookie_string;
    };

    /**
     * Attempts to grab the serialized number cache from a cookie and return
     * the result fully deserialized. If we are unable to find the cookie, then
     * we just return boolean false.
     *
     * @return  object  If we find a cookie, we return the deserialized object.
     *                  If we are unable to find the cookie, we still return an
     *                  empty object.
     */
    var get_number_cache_object = function () {
        var
        // Attempt to grab the current value from the multi-number replace
        // cookie
        cookie_value = get_cookie_value(CACHE_COOKIE_NAME),
        // Define the cookie object variable
        cookie_object = null;

        // If we were unable to find the cookie
        if (cookie_value === false) {
            // Return an empty object
            return {};
        }

        try {
            // There should be a JSON-encoded object in the cookie value
            cookie_object = JSON.parse(cookie_value);
        } catch (exception) {
            // Return an empty object
            return {};
        }

        // If the deserialize does not work
        if (cookie_object === false) {
            // Return an empty object
            return {};
        }

        // Return the finished cookie object
        return cookie_object;
    };

    /**
     * Accepts an object of original-number => tracking-number pairs, and then
     * attempts to store them in the number cache cookie.
     *
     * @return  void
     */
    var set_number_cache_object = function (cache_object) {
        // Attempt to set the cookie value to the JSON-serialized string
        set_cookie_value(CACHE_COOKIE_NAME, JSON.stringify(cache_object),
            CACHE_COOKIE_LIFETIME);
    };

    /**
     * Generates a random string from an explicitly defined collection of
     * available characters.
     *
     * @param   int     The length of the string to return.
     * @return  string  The random alpha string.
     */
    var generate_random_alpha = function (desired_length) {
        var
        // The alpha characters to use. Note that there are no vowels. This
        // prevents most human-readable words from being accidentally
        // generated
        characters = 'BCDFGHJKLMNPQRSTVWXZbcdfghklmnpqrstvwxz',
        // Holds the completed result string
        result = '',
        // Define the variables to use in the for loop
        index = null, random_number = null;

        // Loop once for each character to generate
        for (index = 0; index < desired_length; index++) {
            // Generate a random number between 0 and the total number of
            // available characters
            random_number = Math.floor(Math.random() * characters.length);

            // Add this random character to the result string
            result += characters.substring(random_number,
                random_number + 1);
        }

        // return the random value we generated
        return result;
    };

    /**
     * Returns all of the elements in the document that have the passed class
     * assigned to them.
     *
     * @param   string  The class name to search for.
     * @return  array   An array of matching elements.
     */
    var get_elements_by_class_name = function (class_name) {
        // If "getElementsByClassName" is aleady defined, use it
        if (typeof document.getElementsByClassName !== 'undefined') {
            // Copy the result of "getElementsByClassName" into a simple array
            return Array.prototype.slice.call(
                document.getElementsByClassName(class_name), 0);
        }

        var
        // Pre-compile a regular expression for searching for the class
        // name in a string
        has_class_name = new RegExp('(?:^|\\s)' + class_name +
            '(?:$|\\s)'),
        // Grab all of the elements from the document into an array
        all_elements = document.getElementsByTagName('*'),
        // Define an array to hold the results we will return
        results = [],
        // Define the variables we use in the search loop
        index = null, element = null, element_class = null;

        // Loop over all of the elements in the document
        for (index = 0; (element = all_elements[index]) != null;
            index++) {
            // Grab a shortcut variable over to the class name
            element_class = element.className;

            // If we do not have the class name on this element
            if ( ! element_class || element_class.indexOf(class_name) === -1
                || ! has_class_name.test(element_class)) {
                // Move on to the next element
                continue;
            }

            // Add this element to the results we will return
            results.push(element);
        }

        // Return the results
        return results;
    };

    /**
     * Adds a single element to the request queue by its replace-number while
     * enforcing replace-number uniqueness.
     *
     * @param   array   A reference to the current request queue.
     * @param   string  A reference to the current replace number.
     * @param   object  A reference to the a DOM element.
     * @return  array   The updated request queue.
     */
    var add_to_request_queue = function (request_queue, replace_number,
        element) {
        var
        // Holds the matching queue item, if we find one
        found_item = null;

        // Search the request queue to determine if we already have this
        // replace number in it or not
        found_item = for_each(request_queue, function (index, current_item) {
            // If we do not have a matching number
            if (current_item.replace_number !== replace_number) {
                return; // Do nothing
            }

            // Found a match - return the current queue item
            return current_item;
        });

        // If we found a queue item
        if (typeof found_item !== 'undefined' && found_item !== null) {
            // Add this element to the existing queue item we found
            found_item.elements.push(element);

            // Return the updated request queue
            return request_queue;
        }

        // Create a brand new request queue item
        request_queue.push({
            'replace_number': replace_number,
            'elements': [element]
        });

        // Return the updated request queue
        return request_queue;
    };

    /**
     * Adds a single element to the pixelfire queue by its tracking-number while
     * enforcing tracking-number uniqueness.
     *
     * @param   array   A reference to the current pixelfire queue.
     * @param   string  A reference to the current tracking number.
     * @return  array   The updated request queue.
     */
    var add_to_pixelfire_queue = function (pixelfire_queue, tracking_number) {
        var
        // Flag to tell us if we found a matching tracking number or not
        found_item = false;

        // Search the pixelfire queue to determine if we already have this
        // tracking number in it or not
        found_item = for_each(pixelfire_queue, function (index, current_item) {
            // If we do not have a matching number
            if (current_item.tracking_number !== tracking_number) {
                return; // Do nothing
            }

            // We found a match
            return true;
        });

        // If we did not find a an existing queue item
        if (found_item !== true) {
            // Add this element to the pixelfire queue
            pixelfire_queue.push({
                'tracking_number': tracking_number
            });
        }

        // Return the potentially updated pixelfire queue
        return pixelfire_queue;
    };

    /**
     * Finds all of the elements on the page that have the desired number
     * replacement class, grabs the phone numbers inside of the elements, then
     * attempts to find matches in the number replacement cache.
     *
     * @return  object  An object structure with a summary of the information.
     */
    var replace_number_search = function () {
        var
        // Attempt to find any elements that have the multi-number-
        // replacement class assigned to them
        elements = get_elements_by_class_name(DESTINATION_NUMBER_CLASS),
        // Grab a reference to the number cache
        number_cache = get_number_cache_object(),
        // Define a place to hold the phone numbers we were able to replace
        // using the number cache
        cache_hits = [],
        // Define a place to hold the phone numbers we need to request
        // tracking numbers for
        request_queue = [];

        // Loop over the replace number elements
        for_each(elements, function (index, element) {
            var
            // Grab the replace number from the element
            replace_number = strip_non_numeric(element.innerHTML);

            // If we have a cache hit
            if (typeof number_cache[replace_number] !== 'undefined') {
                // Add this element to the cache hits collection
                cache_hits.push({
                    'element': element,
                    'replace_number': replace_number,
                    'tracking_number': number_cache[replace_number]
                });

                // Move on to the next number on the page
                return;
            }

            // Add this number to the request queue
            request_queue = add_to_request_queue(request_queue, replace_number,
                element);
        });

        // Return the cache hits and request queue collections
        return {
            'number_cache': number_cache,
            'cache_hits': cache_hits,
            'request_queue': request_queue
        };
    };

    /**
     * Removes all non-numeric characters from the passed string.
     *
     * @param   string  The string to strip non-numeric characters from.
     * @return  string  The value string with all non-numeric characters
     *                  stripped out.
     */
    var strip_non_numeric = function (value) {
        // Return the value string with non-numeric characters removed from it
        return value.replace(/[^0-9]/g, '');
    };

    /**
     * Generates a URI query string using the passed array of key/value
     * objects.
     *
     * @param   array   An array of objects. Each sub-object needs to have both
     *                  name and value members.
     * @return  string  A string which can be concatenated to the URI.
     */
    var generate_query_string = function (pairs) {
        var
        // Define an array to hold the string representation of the pairs
        pair_strings = [],
        // Define the variables we use in the for loop
        index = null, pairs_length = pairs.length, pair;

        // Loop over all of the variable pairs
        for (index = 0; index < pairs_length; index++) {
            // Grab a reference to the current pair
            pair = pairs[index];

            // Add this string to the result array
            pair_strings.push(pair.name + '=' + pair.value);
        }

        // Return the finished query string partial
        return '?' + pair_strings.join('&');
    };

    /**
     * Injects a script tag into the DOM pointed at the passed URI.
     *
     * @param   string  The URI to point the injected script tag at.
     * @return  void
     */
    var inject_script_tag = function (uri) {
        // Inject a script tag with the passed URI string
        // document.write('<script src="' + uri + '"></script>');
        var head = document.getElementsByTagName("head").item(0);
        var script = document.createElement("script");
        script.setAttribute("src", uri);
        // all set, add the script
        head.appendChild(script);
    };

    /**
     * Converts the passed object into a set of URI pairs that can be parsed by
     * the generate_query_string function.
     *
     * @param   object  A collection of key: value pairs to convert.
     * @return  array   An array of pairs with name and value properties.
     */
    var object_to_pairs = function (source_object) {
        var
        // Define a variable to hold the finished pairs
        pairs = [],
        // Define variables for the loop below
        name = null, value = null;

        // Loop over the passed object parameters
        for (name in source_object) {
            // Grab a shortcut variable to the value of the current object
            // parameter in the loop
            value = source_object[name];

            // Add this pair
            pairs.push({
                'name': name,
                'value': value
            });
        }

        // Return the finished pairs
        return pairs;
    };

    /**
     * Makes a JSON-P request out to the specified URI using the passed
     * GET parameters object.
     *
     * @param   string    The base URI to make the request against.
     * @param   object    An object with key: value pairs to transform into get
     *                    parameters on the URI.
     * @param   function  The callback function to invoke when we get a
     *                    response back.
     * @return  void
     */
    var jsonp_request = function (base_uri, parameters, callback) {
        var
        // Define the JSON-P receiver function name as a random string of
        // 20 alpha characters prefixed with the passed prefix string
        jsonp_receiver_function_name = JSONP_RECEIVER_FUNCTION_PREFIX +
        generate_random_alpha(20),
        // Define a variable to hold the parameter pairs
        pairs = null;

        // Define the JSON-P receiver function on the parent scope
        parent_scope[jsonp_receiver_function_name] = function (data) {
            // Invoke the callback function passing the data
            callback(data);
        };

        // Convert the passed key: value object to a set of URI pairs
        pairs = object_to_pairs(parameters);

        // Add a jsonp parameter to hold the callback name
        pairs.push({
            'name': 'jsonp',
            'value': jsonp_receiver_function_name
        });

        inject_script_tag(base_uri + generate_query_string(pairs));
    };

    /**
     * Executes a data-image request out to the specified URI using the passed
     * GET parameters object.
     *
     * @param   string    The base URI to make the request against.
     * @param   object    An object with key: value pairs to transform into get
     *                    parameters on the URI.
     */
    var data_image_request = function (base_uri, parameters) {
        mm_logError ("[data_image_request] init");
        var
        // Generate an array of name/value pairs from the passed parameters
        // object
        pairs = object_to_pairs(parameters),
        // Define the image object to do the request
        request_image = new Image();

        // Attempt to executed the data-image request
        mm_logError ("[data_image_request] image src="+base_uri + generate_query_string(pairs));
        request_image.src = base_uri + generate_query_string(pairs);
    };

    /**
     * Attempts to execute the pixelfire script using a data image request.
     *
     * @param   array  A queue of tracking numbers to send to the pixelfire
     *                 script.
     * @return  void
     */
    var execute_pixelfire = function (queue) {
        mm_logError ("[execute_pixelfire] init");
        var
        // Define a place to hold the parameters for the pixelfire request
        parameters = {
            'u': probeURL(),
            'c1': escape(mm_c1),
            'c2': escape(mm_c2),
            'c3': escape(mm_c3),
            'aid': mm_aid
        },
        // Determine the protocol
        http_protocol = ("https:" == document.location.protocol) ? "https://ssl" : "http://www",
        // Define the URL to load
        base_uri = http_protocol + '.mongoosemetrics.com/correlation/pixelfire_correlate.php';

        // Loop over the queue
        for_each(queue, function (index, item) {
            // Add the parameter for this replace number
            mm_logError ("[execute_pixelfire] adding n"+index.toString()+"="+item.tracking_number);
            parameters['n' + index.toString()] = item.tracking_number;
        });

        // Attempt to execute the pixelfire data-image request
        mm_logError ("[execute_pixelfire] base_uri: "+base_uri);
        data_image_request(base_uri, parameters);
    };

    /**
     * Return an object with the public functions we will expose to the
     * outside.
     */
    return {
        /**
       * @var  bool  Holds if this was a multi-number replacement or not.
       */
        'was_multi': null,
        /**
         * Makes the request out to JSON find correlation number using the
         * passed parameters. In the event that any elements are found in the
         * DOM that match the multi-number-replace class, the 'multi' flag will
         * be set to '1' and a series of n[0-9]* variables will be added to the
         * URIs GET string.
         *
         * @param   string    The base URI to make the request against.
         * @param   object    An object with key: value pairs to transform into get
         *                    parameters on the URI.
         * @param   function  The callback function to invoke when we get a
         *                    response back.
         */
        'find_correlation_number': function (uri, parameters, do_replacement, callback) {
            mm_logError ("[find_correlation_number] init");
            var
            // Search the DOM for elements with phone numbers to replace,
            // do some analysis and get the result
            search_result =  do_replacement ? replace_number_search() : {},
            // Grab shortcut variables out to the returned cache hits,
            // request queue, and number cache collections, if those object
            // members exist
            cache_hits = typeof search_result.cache_hits !== 'undefined' ?
            search_result.cache_hits : [],
            request_queue = typeof search_result.request_queue !== 'undefined' ?
            search_result.request_queue : [],
            number_cache = typeof search_result.number_cache !== 'undefined' ?
            search_result.number_cache : [],
            // Determine what to send up to the pixelfire script
            pixelfire_queue = [],
            // Hold on to a reference to this object
            self = this;

            mm_logError ("[find_correlation_number] do_replacement: "+do_replacement);
            mm_logError ("[find_correlation_number] search_result: "+search_result.length);
            mm_logError ("[find_correlation_number] cache_hits: "+cache_hits.length);
            mm_logError ("[find_correlation_number] request_queue: "+request_queue.length);
            mm_logError ("[find_correlation_number] number_cache: "+number_cache.length);

            // Replace all of the elements where we had cache hits
            for_each(cache_hits, function (index, cache_hit) {
                // Assign the replacement tracking number to the element
                cache_hit.element.innerHTML = formatnumber(
                    cache_hit.tracking_number, display_format);

                // Add this cached tracking number to the pixelfire queue if it
                // isnt already there
                pixelfire_queue = add_to_pixelfire_queue(pixelfire_queue,
                    cache_hit.tracking_number);
            });

            mm_logError ("[find_correlation_number] pixelfire_queue: "+pixelfire_queue.length);

            // If we have anything in the request queue
            if (request_queue.length > 0) {
                // Add the multi-number request GET variable
                parameters['multi'] = '1';
                this.was_multi = true;
            } else if (cache_hits.length > 0) {
                // This was a multi-number request, but we already handled
                // everything with the multi-number cache
                this.was_multi = true;
                mm_logError ("[find_correlation_number] request_queue or cache_hits > 0, was_multi = true, firing pixelfire");
                // We have no new numbers to request so we can kick-off the
                // pixelfire script right now
                execute_pixelfire(pixelfire_queue);

                // Forward the response data to the callback function
                return callback({
                    'SUID' : '1'
                });
            }

            // Loop over everything in the request queue
            for_each(request_queue, function (index, queue_item) {
                // Add this replace number to the URI
                mm_logError ("[find_correlation_number] adding to json uri: n"+index.toString()+"="+queue_item.replace_number);
                parameters['n' + index.toString()] = queue_item.replace_number;
            });

            // Make the JSON-P request out to the remote server
            mm_logError ("[find_correlation_number] firing jsonp_request");
            jsonp_request(uri, parameters, function (response_data) {
                // If somehow the response data is undefined or null
                if (typeof response_data !== 'object' ||
                    response_data === null) {
                    // Do nothing
                    return;
                }

                var
                // Grab a shortcut variable to the numbers collection, if
                // one exists
                numbers = typeof response_data.numbers !== 'undefined' ?
                response_data.numbers : [],
                // Gets set to boolean true if we update the cache object
                updated_number_cache = false;

                // If I got a numbers member back
                if (numbers.length > 0) {
                    // This was a multi-number replacement
                    self.was_multi = true;
                } else {
                    // This was not a multi-number replacement
                    self.was_multi = false;
                }

                // Loop over the numbers that were sent back from the server
                for_each(numbers, function (index, number_object) {
                    var
                    // Grab a shortcut variable to the tracking number
                    tracking_number = number_object.tracking_number,
                    // Grab a shortcut variable to the corresponding
                    // request queue object
                    request_object = request_queue[index],
                    // Grab a shortcut variable to the request number
                    replace_number = request_object.replace_number,
                    // Grab a shortcut variable to the element
                    elements = request_object.elements;

                    // If the tracking number came back as anything other then
                    // a 10-digit phone number
                    if (tracking_number.length !== 10) {
                        // Move on to the next result
                        return;
                    }

                    // Loop over each of the elements
                    for_each(elements, function (index, element) {
                        // Modify the HTML on the page
                        element.innerHTML = formatnumber(tracking_number,
                            display_format);
                    });

                    // Add this number to the number cache if it isnt already
                    // there
                    number_cache[replace_number] = tracking_number;

                    // Add this tracking number to the pixelfire parameters
                    pixelfire_queue = add_to_pixelfire_queue(pixelfire_queue,
                        tracking_number);

                    // Indicate that we updated the number cache
                    updated_number_cache = true;
                });

                // If we had response data that we added to the number cache
                if (updated_number_cache) {
                    // Save the updated version of the number cache
                    set_number_cache_object(number_cache);
                }

                // Execute the pixelfire call
                execute_pixelfire(pixelfire_queue);

                // Forward the response data to the callback function
                callback(response_data);
            });
        }
    };

}(window));

/**

    Usage example:

    Multi_Number.find_correlation_number(
        'multi.php',
        {
            'crap': '1',
            'crap2': '2'
        },
        function (data) {
            showNumber(data);
        }
    );

*/

mm_logError("[spc-prod] checking UserAgent");
var mm_UA = function() {
    return navigator.userAgent;
}();
var mm_blockedUA = function() {
    var blockUAs = ['Googlebot'];
    // return false;
    for (var i=0; i< blockUAs.length; i++) {
        if(mm_UA.match(blockUAs[i])) {
            mm_logError(blockUAs[i]);
        }
    }
    return false;
}();

// Getting URL variables
mm_logError("[spc-prod] getting URL variables");
var mm_url_vars = mm_extractVars(window.location.search.substring(1));

// Getting Referrer information
mm_logError("[spc-prod] getting referral URL");
var mm_referrer = mm_parseUri(mm_getReferrer());
if (mm_debug && getVar('organic').toLowerCase() == 'true'){
    mm_logError ("[spc-prod] organic testing mode: setting referring URL");
    mm_referrer = mm_parseUri('http://www.google.com/search?q=test_organic_raw_search');
}
mm_logError("[spc-prod] referrer="+mm_referrer.source);

source=getVar("mm_utm_source");

if (!source){
    source=getVar("utm_source");
}

gclid=getVar("gclid");

// Capture Marin or Kenshoo variables
if (typeof mkwid == 'undefined' ) {
    var mkwid, mcreativeid;
    mkwid=getVar("mkwid");
    mcreativeid=getVar("mcreativeid");
}
if (!mkwid){
    mkwid=getVar("kshid");
}

adcampaign=unescape(getVar("mm_utm_campaign"));
if (!adcampaign){
    adcampaign=unescape(getVar("utm_campaign"));
}

//name of the campaign to fetch in trackable numbers associated with campaign, leave blank to fetch with no campaign association
keyword_ppc = unescape(getVar("keyword"));

if(keyword_ppc.length < 2){
    keyword_ppc = unescape(getVar("mm_keyword"));
}

if (type=="D" && keyword_ppc.length < 2){
    keyword_ppc="direct traffic";
    type="I";
}else{
    type="P";
}

//name of the campaign to fetch in trackable numbers associated with campaign, leave blank to fetch with no campaign association
phone_number = getVar("phone_number"); 

//ad type differentiation inside campaign, leave blank to fetch with for no ad type association
ad_type = getVar("ad_type");

if(ad_type.length < 2){
    if (typeof adtype != 'undefined'){
        ad_type = adtype;
    }
}

//set number display format 0 for XXX.XXX.XXXX 1 for (XXX) XXX-XXXX and 2 for xxx-xxx-xxxx
if (typeof customer_number_format != 'undefined')
    display_format = customer_number_format;
else
    display_format=0;

//check  custom JS variable values. If they are there then pass to pixelfire and set them in cookie, else fetch from cooke and assign else null

if (typeof custom1 != 'undefined') {
    setcookie("MM_custom1",custom1,720);
    mm_c1=custom1;
} else {
    mm_c1 = get_cookie("MM_custom1",null);
}

if (typeof custom2 != 'undefined') {
    setcookie("MM_custom2",custom2,720);
    mm_c2=custom2; 
} else {
    mm_c2 = get_cookie("MM_custom2",null);
}

if (typeof custom3 != 'undefined') {
    setcookie("MM_custom3",custom3,720);
    mm_c3=custom3;
} else {
    mm_c3 = get_cookie("MM_custom3",null);
}
if (typeof affiliate_id != 'undefined')
{
    setcookie("MM_affiliate_id",affiliate_id,720);
    mm_aid=affiliate_id;
}
else
    mm_aid = get_cookie("MM_affiliate_id",null);

if(getVar("type")=="I") 
{
    type="I";
    source=mm_referrer.source;
}

if(getVar("match")=="PPC") 
{
    type="S";
    source=encodeURIComponent(document.URL);
}

if (typeof promocode != 'undefined'){
    if (typeof default_promo == 'undefined'){
        default_promo = 0;
    }
}else{
    promocode = '';
    default_promo = 0;
}

// If this variable is set to N, then we do not always replace numbers
// with the default number
if (typeof overwrite_default_number == 'undefined'){
    var overwrite_default_number = 'Y';
}

mm_logError("[spc=prod] overwrite_default_number="+overwrite_default_number);
// These variables are used to override passed in variables
if (typeof override_keyword != 'undefined'){
    mm_logError ('override_keyword = '+ override_keyword);
    keyword_ppc = override_keyword;
    mm_logError ('keyword_ppc = '+ keyword_ppc);
}
if (typeof override_mmcampaign != 'undefined'){
    campaign = override_mmcampaign;
}
if (typeof override_source != 'undefined'){
    source = override_source;
}
if (typeof override_adcampaign != 'undefined'){
    adcampaign = override_adcampaign;
}
if (typeof override_type == 'undefined'){
    override_type = '';
}
if (typeof override_raw == 'undefined'){
    override_raw = '';
}
if (typeof override_referrer == 'undefined'){
    override_referrer = '';
}
if (typeof overflow_number == 'undefined'){
    overflow_number = '';
}

// This variable is for an organic 1:1 number
if (typeof organic_number == 'undefined'){
    organic_number = '';
}

// This variable is to define a 1:1 when session runs out of numbers
if (typeof failover_number == 'undefined'){
    failover_number = '';
}

// This variable is used to determine if web conversions are enabled
if (typeof mm_web_conversion != 'undefined'){
    if(mm_web_conversion == '1'){
        checkConversion();
    }
}

if (typeof mm_directories === 'undefined'){
    mm_directories = false;
}

mm_logError("[spc-prod] keyword_ppc = " + keyword_ppc);

/** Custom Number Replacement for Multiple Locations **/
/* 
* requires 2 variables set via client JS:
*  mm_customLocationUrlMatch : regex with group to match the location in the url.
*  mm_customLocationList : js object containing locations in the correct structure 
*/
mm_logError("[spc-prod] delcaring multi number replacement function");
var mm_customLocationNumber = {
    run : function() {
        if(typeof(mm_customLocationUrlMatch) === 'undefined' ||
            typeof(mm_customLocationList) !== 'object') {
            return;
        }
        var currentLocationName = this.getLocation();
        if(currentLocationName !== null) {
            // loop over numbers in location
            var locationRef = mm_customLocationList.locations[currentLocationName];
            for(var i=0;i<locationRef.length;i++) {
                if(typeof(locationRef[i] !== 'undefined')) {
                    domIterator(locationRef[i].origNumber, formatnumber(locationRef[i].replaceNumber, display_format));
                }
            }
        }
    },
    getLocation: function() {
        // get path, minus /our_schools and the trailing /, replacing dashes with underscores
        matchedLocation = location.pathname.match(mm_customLocationUrlMatch);
        if(matchedLocation === null) {
            return matchedLocation;
        }
        return matchedLocation[1].replace(/\-/g,'_');
    }

}.run();

mm_logError("[spc-prod] done loading");

// Functions to check if a conversion has happened
function checkConversion()
{
    var mm_protocol_json = (("https:" == document.location.protocol) ? "https://" : "http://");

    var mm_conv_url=mm_protocol_json+"webconvert.mongoosemetrics.com/conversion/convert.php?mm_conversion_uuid="+currentUUID;
    if(typeof mm_conversion_goal_id != 'undefined') mm_conv_url=mm_conv_url+"&mm_conversion_goal_id="+mm_conversion_goal_id;
    if(typeof mm_conversion_fname != 'undefined') mm_conv_url=mm_conv_url+"&mm_conversion_fname="+mm_conversion_fname;
    if(typeof mm_conversion_lname != 'undefined') mm_conv_url=mm_conv_url+"&mm_conversion_lname="+mm_conversion_lname;
    if(typeof mm_conversion_score != 'undefined') mm_conv_url=mm_conv_url+"&mm_conversion_score="+mm_conversion_score;
    if(typeof mm_conversion_email != 'undefined') mm_conv_url=mm_conv_url+"&mm_conversion_email="+mm_conversion_email;
    if(typeof mm_conversion_phone != 'undefined') mm_conv_url=mm_conv_url+"&mm_conversion_phone="+mm_conversion_phone;
    if(typeof mm_conversion_custom1 != 'undefined') mm_conv_url=mm_conv_url+"&mm_conversion_custom1="+mm_conversion_custom1;
    if(typeof mm_conversion_custom2 != 'undefined') mm_conv_url=mm_conv_url+"&mm_conversion_custom2="+mm_conversion_custom2;
    if(typeof mm_conversion_custom3 != 'undefined') mm_conv_url=mm_conv_url+"&mm_conversion_custom3="+mm_conversion_custom3;

    myImage= new Image();
    myImage.src=mm_conv_url;

}

function getVisitor(){
    mm_logError ("[getVisitor] init");
    if(mm_blockedUA) {
        mm_logError('[getVisitor] blocked UserAgent: ' . mm_UA);
        return false;
    }
    var sourceurl=mm_referrer.host;
    var raw_search=mm_getParsedUrlVar(mm_referrer,'q');
    if(sourceurl == 'search.yahoo.com') {
        raw_search=mm_getParsedUrlVar(mm_referrer,'p');
    }
    var keyword;

    if(keyword_ppc.length < 2 || keyword_ppc == "direct traffic"){
        // organic Keyword
        if(mm_referrer.source) {
            if (type=="S") {
                keyword="source";
            } else {
                keyword=raw_search;
                type="O";
            }
        } else {
            if (keyword_ppc == "direct traffic" && type=="I"){
                keyword=keyword_ppc;
            }
        }
    } else {
        keyword=keyword_ppc;
    }
    var fullquery = encodeURIComponent(document.location.search);
    if (!source && mm_referrer.source) {
        source=sourceurl;
    }
    var ru = unescape(mm_referrer.source);
    ru = encodeURIComponent(ru);

    var
    // Determine if this site is HTTP or HTTPS then prefix our URI accordingly
    mm_protocol_json = (("https:" == document.location.protocol) ? "https://ssl" : "http://www"),
    // Determine the base URI for our JSON-P request
    mm_json_base_uri = mm_protocol_json + ".mongoosemetrics.com/correlation/json_find_correlation_number.php";

    //    var head = document.getElementsByTagName("head").item(0);
    //    script = document.createElement("script");
    //    script.setAttribute("src", mm_json_base_uri);
    //    // all set, add the script
    //    head.appendChild(script);

    // Make the JSON-P request using the new multi-number replacement wrapper
    if (campaign !== ''){
        var do_the_replacement = false;
        if (cookieExistsName("MM_MULTICACHE")){
            do_the_replacement = true;
            if (typeof get_cookie('MM_SDR') === 'undefined' && mm_directories){
                do_the_replacement = false;
            }
        }
        mm_logError ("[getVisitor] do_the_replacement="+do_the_replacement);
        mm_logError ("[getVisitor] mm_directories="+mm_directories);
        mm_logError ("[getVisitor] get_cookie('MM_SDR')="+get_cookie('MM_SDR'));
        mm_logError ("[getVisitor] firing json callback:visitorID");
        Multi_Number.find_correlation_number(
            mm_json_base_uri,
            // Forward all of the variables that we were forwarding before
            {
                'keyword': encodeURIComponent(keyword),
                'source': source,
                'adcampaign': adcampaign,
                'callback': 'visitorID',
                'fullquery': fullquery,
                'GUID': currentGUID,
                'UUID': currentUUID,
                'SUID': spareUUID,
                'campaign': campaign,
                'ref': ru,
                'q': raw_search,
                'or': override_raw
            }, 
            // If the cookie does not exist then don't do the replacement'
            do_the_replacement,
            /**
             * This response handler gets called whenever we get JSON-P
             * data back from the remote server. This is where we forward
             * the data back to the old response handler called
             * "visitorID".
             *
             * @param   object  The JSON data from the remote server.
             * @return  void
             */
            function (response_data) {
                // Invoke the old callback function

                visitorID(response_data);
            }
            );
    }

    keyword='';
}

function getNumber(campaign_alt)
{
    mm_logError ("[getNumber] init");
    if(mm_blockedUA) {
        mm_logError('blocked UserAgent: ' . mm_UA);
        return false;
    }

    var sourceurl=mm_referrer.host
    var raw_search=mm_getParsedUrlVar(mm_referrer,'q');
    if(sourceurl == 'search.yahoo.com') {
        raw_search=mm_getParsedUrlVar(mm_referrer,'p');
    }
    var keyword;
    if(!cookieExists()){
        mm_logError("[getNumber] cookie doesnt exist");
        mm_logError("[getNumber] keyword_ppc = " + keyword_ppc);

        if(campaign.length < 2)
            campaign=campaign_alt;
        
        if(keyword_ppc.length < 2 || keyword_ppc == "direct traffic" || override_type === 'O')
        {
            mm_logError("[getNumber] no keyword, direct traffic, or override type found");
            // organic Keyword
            if (override_referrer !== ''){
                mm_logError("[getNumber] override referrer found");
                mm_referrer.source=override_referrer;
            }
            mm_logError("[getNumber] refering URL = "+mm_referrer.source);
            if(mm_referrer.source) {
                if (type=="S"){
                    keyword="source";
                }else{
                    mm_logError("[getNumber] source = "+sourceurl);
                    mm_logError("[getNumber] keyword_organic = "+raw_search);
                    //document.write("keyword=" + keyword);
                    //document.write("referrererer");
                    if (override_type === 'O'){
                        keyword=override_keyword;
                    }else{
                        keyword=raw_search;
                    }
                    mm_logError("[getNumber] keyword = "+keyword);
                    type="O";
                    if (organic_number != ''){
                        showNumber({
                            "corelate_number":organic_number,
                            "interval":"43200",
                            "unique_cookie":"",
                            "promo_code":""
                        });
                        mm_logError("[getNumber] found organic number");
                        keyword='';
                    }
                }
            }else{ //added on 06.04
                if (keyword_ppc == "direct traffic" && type=="I"){
                    keyword=keyword_ppc;
                }
            }
        } else {
            keyword=keyword_ppc;
        }
        mm_logError("[getNumber] post logic keyword = " + keyword);
        if (typeof get_cookie('MM_SDR') === 'undefined' && mm_directories){
            keyword = false;
        }
        if(keyword)//added on 06.04 if keyword exist with the request
        { //added on 06.04
            //Hard code the url of the request
            mm_logError("[getNumber] no number cookie, keyword present");
            var lu = probeURL();
            var ru = unescape(mm_referrer.source);
            ru = encodeURIComponent(ru);
            mm_logError("ref = " + ru);
            var fullquery = encodeURIComponent(document.location.search);
            mm_logError("ref = " + source);
            if (!source && mm_referrer.source){
                source=sourceurl;
            }
            mm_logError("ref = " + source);
            var
            // Determine if this site is HTTP or HTTPS then prefix our URI accordingly
            mm_protocol_json = (("https:" == document.location.protocol) ? "https://ssl" : "http://www"),
            // Determine the base URI for our JSON-P request
            mm_json_base_uri = mm_protocol_json + ".mongoosemetrics.com/correlation/json_find_correlation_number.php";

            // Make the JSON-P request using the new multi-number replacement wrapper
            Multi_Number.find_correlation_number(
                mm_json_base_uri,
                // Forward all of the variables that we were forwarding before
                {
                    'keyword': encodeURIComponent(keyword),
                    'campaign': campaign,
                    'phone_number': phone_number,
                    'type': type,
                    'source': source,
                    'mkwid': mkwid,
                    'mcreativeid': mcreativeid,
                    'gclid': gclid,
                    'adcampaign': adcampaign,
                    'ad_type': ad_type,
                    'callback': 'showNumber',
                    'ref': ru,
                    'q': raw_search,
                    'u': lu,
                    'pc': promocode,
                    'GUID': currentGUID,
                    'UUID': currentUUID,
                    'SUID': spareUUID,
                    'fullquery': fullquery,
                    'or': override_raw
                },
                // We are request a number and always want a replacement to happen
                // if possible.
                true,
                /**
                 * This response handler gets called whenever we get JSON-P
                 * data back from the remote server. This is where we forward
                 * the data back to the old response handler called
                 * "showNumber".
                 *
                 * @param   object  The JSON data from the remote server.
                 * @return  void
                 */
                function (response_data) {
                    // Invoke the old callback function
                    showNumber(response_data);
                }
                );
		
        }else{
            //if cookie doesnt exist and keyword is not part of the request, its a straight access.
            mm_logError("[getNumber] no number cookie, no keyword present");
            var sessCheck=get_cookie("MM_session_ID",'');
            getVisitor();
            if (sessCheck){
                if (overflow_number != ''){
                    showNumber({
                        "corelate_number":overflow_number,
                        "interval":"43200",
                        "unique_cookie":"",
                        "promo_code":""
                    });
                }
            }
            show_cookie("MM_correlation_Number");
            if (promocode)
                show_cookie("MM_promo_code");
        }
        var tn=get_cookie("MM_correlation_Number",default_number);
        if(tn!=default_number)
            pixelfire(tn);
        return(tn);
		
    }else{
        //cookie exist
        mm_logError("[getNumber] cookie exists");
        if (typeof mm_redirect_url != 'undefined')
            window.location.href=mm_redirect_url;
        getVisitor();
        show_cookie("MM_correlation_Number");
        if (promocode)
            show_cookie("MM_promo_code");
        tn=get_cookie("MM_correlation_Number",default_number);
        if(tn!=default_number)
            pixelfire(tn);
        return(tn);
    }
    keyword = undefined;
    keyword_ppc = undefined;
}

function pixelfire(tn)
{
    var lu = probeURL();
    var mm_protocol_json = (("https:" == document.location.protocol) ? "https://ssl" : "http://www");
    var url=mm_protocol_json+".mongoosemetrics.com/correlation/pixelfire_correlate.php?phone_number="+tn+"&u="+lu+"&c1="+escape(mm_c1)+"&c2="+escape(mm_c2)+"&c3="+escape(mm_c3)+"&aid="+mm_aid;

    //mm_logError("url is "+ url);
    // alert(url);
    myImage= new Image();
    myImage.src=url;
}

/**
 * THis function is called when the JSON string is returned from json-encode.php
*/
function findurl(url)
{
    var ref = document.createElement('a');
    ref.href = url;
    return ref.hostname;
}

function visitorID(number)
{
    sessioncheck = number.SUID;
    //mm_logError("reply:"+sessioncheck);
    if (sessioncheck != 1)
        setcookie("MM_UUID",sessioncheck,1440);
}

function showNumber(number) 
{
    //mm_logError(response);
    response = number.corelate_number;
    interval = number.interval;
    unique_cookie = number.unique_cookie;
    promo_code = number.promo_code;
    sessioncheck = number.SUID;

    var is_multi = (typeof number.numbers !== 'undefined');

    if (sessioncheck != 1){
        setcookie("MM_UUID",sessioncheck,1440);
    }
    if (response==-2 && ! is_multi){
        if(failover_number != ''){
            response = failover_number;
            interval = 5;
        }else{
            response = -1;
        }
    }
    if(response!=-1 && ! is_multi)
    {	//document.write(response);
        setcookie("MM_correlation_Number",response,interval);
        //setcookie("MM_keyword",keyword,720)
        //setcookie("MM_source",source,720)
        setcookie("MM_session_ID",unique_cookie,43200);
        if (promo_code)
            setcookie("MM_promo_code",promo_code,interval);
    }
    if ( ! is_multi ) {
        show_cookie("MM_correlation_Number");
        if (promo_code){
            show_cookie("MM_promo_code");
        }
        pixelfire(response);
    }

    //Redirect page to a different URL after assignment, the variable defined on client web page
    if (typeof mm_redirect_url != 'undefined')
        window.location.href=mm_redirect_url;
		
    //reload the page after number assignment of customer has set var mm_reload=1;
    if (typeof mm_reload != 'undefined')
    {
        if(mm_reload == 1)
        {
            window.location.reload();
        }
    }

}

//FUNCTION TO FETCH THE URL VALUE FOR A NAME E.G: ?CAMPAIGN=INSULATED WATER HEATER -->getVAR("CAMPAIGN")
function getVar(name)
{
    return mm_getUrlVar(name);
}

//FUNCTION TO SET PUBLISHED NUMBER TO COOKIE FOR INTERVAL SPECIFIED
function setcookie(cookie_name,val, interval)
{
    //mm_logError(interval);
    if(val!="")
    {
        var today = new Date();
        today.setTime( today.getTime() );
        vtime = today.getTime()+ 1000 * 60 * interval;
        var cookie_expire_date = new Date(vtime);

        var cookie_string =  cookie_name +"="+val+";expires="+cookie_expire_date.toGMTString()+"; path=/; ";

        var sub_domain = getSubDomain(location.hostname);

        // do not set domain if dotless
        //if(sub_domain !== false) {
        cookie_string += "domain="+sub_domain;
        //}

        document.cookie = cookie_string;
    }
}

function show_cookie(name)
{
    var ret_one;
    var ret_two;
    //var default_number = "8002931174";
    if(document.cookie)
    {
        var cookie_index=document.cookie.indexOf(name);
        if (cookie_index != -1)
        {
            namestart = (document.cookie.indexOf("=", cookie_index) + 1);
            nameend = document.cookie.indexOf(";", cookie_index);
            if (nameend == -1) {
                nameend = document.cookie.length;
            }
            ret_one = document.cookie.substring(namestart, nameend);
            ret_two = document.cookie.substring(namestart, nameend);
        }else{
            ret_one = default_number;
            ret_two = default_promo;
        }

    }else{
        ret_one = default_number;
        ret_two = default_promo;
    }
    if (name == "MM_promo_code"){
        for (i=0; i<promo_placeholderarray.length;i++)
        {
            if(document.getElementById(promo_placeholderarray[i]))
            {
				
                document.getElementById(promo_placeholderarray[i]).innerHTML = ret_two;
            }
				
        }
    }else{
        for (i=0; i<number_placeholderarray.length;i++){
            if(document.getElementById(number_placeholderarray[i]))
            {
                if(ret_one != default_number || overwrite_default_number != 'N')
                {
					
                    document.getElementById(number_placeholderarray[i]).innerHTML = formatnumber(ret_one,display_format);
					
                }
            }
			
        }
    }
    tnarray[0]=ret_one;
    tnarray[1]=formatnumber(ret_one,display_format);
    //mm_logError('shownumber');
    //mm_logError(tnarray[0]);

    if(ret_one != default_number || overwrite_default_number != 'N'){
        if (typeof our_function != 'undefined' && ! Multi_Number.was_multi)
            eval(our_function+"();")
    }

    if (typeof callback_function != 'undefined') {
        if(mm_cookie_num === null) {
            mm_cookie_num = tnarray[0];
        }
      
        eval(callback_function+"();")
    }


}

function get_cookie(name,default_value)
{
    var get_cookie_ret_one;
    //mm_logError(document.cookie);
    //var default_number = "8001234567";
    if(document.cookie)
    {
        //mm_logError(document.cookie);
        var cookie_index=document.cookie.indexOf(name);
        //mm_logError(cookie_index);
        if (cookie_index != -1)
        {
            namestart = (document.cookie.indexOf("=", cookie_index) + 1);
            nameend = document.cookie.indexOf(";", cookie_index);
            if (nameend == -1) {
                nameend = document.cookie.length;
            }
            get_cookie_ret_one = document.cookie.substring(namestart, nameend);
        }
        else
            get_cookie_ret_one = default_value;
    }
    else
        get_cookie_ret_one = default_value;
    return(get_cookie_ret_one);
}

//FUNCTION TO CHECK IF COOKIE WITH MM_CORRELATION_NUMBER EXISTS FOR THE VISITOR BROWSER
function cookieExists()
{
    //mm_logError(document.cookie);
    if(document.cookie)
    {
        var cookie_index=document.cookie.indexOf("MM_correlation_Number");
        var multicache_index = document.cookie.indexOf('MM_MULTICACHE');
        if (cookie_index != -1 || multicache_index != -1)
            return true;
        else
            return false;
    }
    else
        return false;
}

function cookieExistsName(name)
{
    //mm_logError(document.cookie);
    if(document.cookie)
    {
        var cookie_index=document.cookie.indexOf(name);
        if (cookie_index != -1)
            return true;
        else
            return false;
    }
    else
        return false;
}

function formatnumber(num,display_format)
{
    var country_code, ini, st, end;
    if (typeof 	prefix_countrycode != 'undefined'){
        country_code = prefix_countrycode;
    }else{
        country_code = "";
    }

    //format 0 --  xxx.xxx.xxxx
    //format 1 --  (xxx) xxx-xxxx
    //format 2 --   xxx-xxx-xxxx
    if(display_format==0)
    {
        _return="";

        if(country_code!="")
            _return+=country_code+".";

        ini = num.substring(0,3);
        _return+=ini+".";
        st = num.substring(3,6);
        _return+=st+".";
        end = num.substring(6,10);
        _return+=end;
        return _return;
    }
    else if(display_format==1)
    {
        _return="";

        if(country_code!="")
            _return+=country_code;

        ini = "("+num.substring(0,3)+")";
        _return+=ini+" ";
        st = num.substring(3,6);
        _return+=st+"-";
        end = num.substring(6,10);
        _return+=end;
        return _return;
    }
    else if(display_format==3)
    {
        _return="";

        if(country_code!="")
            _return+=country_code;

        ini = num.substring(0,3);
        _return+=ini+" ";
        st = num.substring(3,6);
        _return+=st+" ";
        end = num.substring(6,10);
        _return+=end;
        return _return;
    }
    else if(display_format==4)
    {
        _return="";

        if(country_code!="")
            _return+=country_code;

        ini = num.substring(0,4);
        _return+=ini+" ";
        st = num.substring(4,7);
        _return+=st+" ";
        end = num.substring(7,11);
        _return+=end;
        return _return;
    }
    else if(display_format==5)
    {
        _return="";

        if(country_code!="")
            _return+=country_code;

        ini = num.substring(0,5);
        _return+=ini+" ";
        st = num.substring(5,8);
        _return+=st+" ";
        end = num.substring(8,11);
        _return+=end;
        return _return;
    }
    else
    {
        _return="";

        if(country_code!="")
            _return+=country_code+"-";

        ini = num.substring(0,3);
        _return+=ini+"-";
        st = num.substring(3,6);
        _return+=st+"-";
        end = num.substring(6,10);
        _return+=end;
        return _return;
    }
}

function probeURL ()
{
    var checkURL = 'NA';
    checkURL = document.URL;
    if (checkURL.length < 3){
        checkURL = window.location.href;
    }
    if (checkURL.length < 3){
        checkURL = document.location.href;
    }
    if (checkURL.length < 3){
        checkURL = location.href;
    }
    checkURL = unescape(checkURL);
    var checkPOS = checkURL.indexOf('?');
    if (checkPOS != -1){
        splitURL=checkURL.split('?');
        checkURL=splitURL[0];
    }
    return encodeURIComponent(checkURL);
}

function showExt () {
    if (tnarray[0].length == 10){
        return 1;
    }else{
        return -1;
    }
}

function genS4() {
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

function createGUID() {
    return (genS4()+genS4()+"-"+genS4()+"-"+genS4()+"-"+genS4()+"-"+genS4()+genS4()+genS4());
}

function createUUID (len, radix) {
    var chars = CHARS, uuid = [];
    radix = radix || chars.length;

    if (len) {
        // Compact form
        for (var i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*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 | Math.random()*16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
}

function Delete_Cookie( name, path, domain ) {
    //mm_logError('del');
    if ( Get_Cookie( name ) ) document.cookie = name + "=" +
        ( ( path ) ? ";path=" + path : "") +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function Get_Cookie( name ) {

    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) &&
        ( name != document.cookie.substring( 0, name.length ) ) )
        {
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ";", len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}

function getSubDomain(url) {
    if(!url.match(/\./)) {
        return false;
    }
    var dp = url.split(/\./);
    var lp = slp = tlp = '';
    pn = dp[dp.length-1].split(/\:/)
    lp = pn[0];
    slp = dp[dp.length-2];
    tlp = dp[dp.length-3];
    if(lp.length===2 && slp.length===2) {
        lp = slp + '.' + lp;
        slp = tlp;
    }
    return  '.' + slp + '.' + lp;
}

function mm_getUrlVar(name) 
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS , 'i');
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
}

function mm_getParsedUrlVar(referrerObj,variableName) 
{
    return typeof referrerObj.queryKey[variableName] === 'undefined' ? '' : referrerObj.queryKey[variableName];
}

function mm_extractVars (obj) {
    if(typeof obj === 'undefined') {
        return {};
    }
    var urlvars = {};
    var s = obj.split('&');
    for (var i=0;i<s.length;i++) {
        var uv = s[i].split("=");
        urlvars[uv[0].toLowerCase()] = uv[1];
    }
    return urlvars;
}

function mm_getReferrer() {
    if(typeof document.referrer != 'undefined') {
        r = document.referrer;
    } else {
        r = document.location.href;
    }
    return r;
}


function mm_parseUri (str) {
    var	o = {
        strictMode: true,
        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*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
        }
    };
    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;
}

