$(document).ready(function() {

    updateLeadSource();
    
    //set hidden input field on sign-up form
    $('#leadSource').val(getCookie('leadSource'));

    appendLeadSourceArgToBetaLinks();
    
});

/**
 * Checks URL arguments for 'ad' value.
 * If set, it stores the value as a cookie to be used later
 */
function updateLeadSource()
{
    var leadSource = getArgValue('ad');
    
    if (leadSource != '') {
        setCookie('leadSource', leadSource);
    }
}

/**
 * appends the ad query string to links to beta.mindflash.com if the leadSource cookie is set
 */
function appendLeadSourceArgToBetaLinks()
{
    var leadSource = getCookie('leadSource');
    
    var regexS = '(blog|beta).mindflash.com';
    var regex = new RegExp(regexS);

    if (leadSource != '') {
        //cycle through anchors
        $('a').each(function(index, item) {
            
            //if href contains (blog|beta).mindflash.com, append the ad query string
            //ie: links with href = http://beta.mindflash.com/ become http://beta.mindflash.com/?ad=leadSourceName
            if (regex.exec(item) != null) {
                $(item).attr('href', item + '?ad=' + leadSource);
            }

        });
    }
}

/**
 * Returns the value for a particular URL argument name
 */
function getArgValue(name)
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if (results == null) {
        return "";
    } else {
        return results[1];
    }
}

/**
 * Sets a cookie
 */
function setCookie(c_name,value,expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toUTCString())+ ';path=/';
}

/**
 * Gets a cookie
 */
function getCookie(c_name)
{
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1)
        {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}