var stack_separator = '_';
var medium_source_separator = '(';
var medium_keyword_separator = '(';
var space_char_replacement = '-';
var custom_var_max_char = 64; // do no edit unless you know what you are dealing with

// DO NOT EDIT BELOW THIS LINE
var cookie = document.cookie;

function getNumberOfPageviews(){
	var patt = new RegExp("__utmb=[^\.]+\.([0-9]+)\.");
	if(result = patt.exec(cookie)){
		return result[1];
	}
	return "";
}

function matchregex(regex){
	var patt = new RegExp(regex + "=([^(\||;)]+)");
	if(result = patt.exec(cookie)){
		return result[1];
	}
	return "";
}

function cut(string){ return string.substr(0,3); }

function check_max_char(source){
	var l = source.length;
	if(l > custom_var_max_char){
		new_source = source;
		i = new_source.indexOf(stack_separator);
		while(l-i-1 > custom_var_max_char && i != -1){
			new_source = new_source.substr(i+1);
			i = new_source.indexOf(stack_separator);
			l = new_source.length;
		}
		return new_source.substr(i+1);
	}else return source;
}

function gup( 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];
}

function getSourceFromUTMZCookie(type) {
// getting the value from the original Google Analytics cookie

	//get direct medium first
	if(document.referrer == "" && gup("utm_medium") == ""){
		return cut("direct");
	}
    source = cut(matchregex("utmcmd"));
    if(type=="mediumsource" && source != cut("direct")){
        source += medium_source_separator + matchregex("utmcsr");
    }
	else if(type=="mediumkeyword" && (source == cut("cpc") || source == cut("organic"))){
        source += medium_keyword_separator + matchregex("utmctr").replace(/%20/g,space_char_replacement);
    }
    if(source == '(none)') source = cut('direct');
    return source;
}      

function generateNewCampaignStacking(existing, source) {
// create the local cookie and append old values
	if(typeof(existing)=="undefined") existing = "";
	//var lastsource = existing.substr(existing.lastIndexOf(stack_separator)+1);
    //if (lastsource != source) {
    if(getNumberOfPageviews() == "0"){
        if (existing != "") {
            source = existing + stack_separator + source;
        }
    }else source = existing;
	return check_max_char(source);
}

function getCampaignStacking(existingCS,type){
	cookie = document.cookie;
	var source = getSourceFromUTMZCookie(type);
	return generateNewCampaignStacking(existingCS, source);
}

 
