//Set Flock version and download source exceptions here.
var flock_version = '2.5';
var flock_advertised_version = '2.5';

var is_stage = false;
if(document.location.href.match(/http:\/\/(stage|daryl|tim|brett)/)){
	is_stage = true;
}


if(is_stage){
	flock_version = '2.5';
	flock_advertised_version = '2.5';
}

var _download_source_exceptions = 	{
						tinypic:		'flock-2.0.3-afc2D752E58ECCE',
						photobucket: 		'flock-2.0.3-photobucket'
					}


var _interstitial = 'http://www.flock.com/download/';
if(is_stage){
	//_interstitial = 'http://stage.flock.com/download/?debug=1';
	_interstitial = 'http://stage.flock.com/download/';
}

//Instrumentation setting(s):

var inst_path_prefix = 'V4/'; //should have terminal slash

//Probably no need to edit anything below, generally speaking.

var flock_platform;
var flock_product_name;
var flock_download_link;
var flock_platform_name = 'Windows';

flock_product_name = 'flock-' + flock_version;


var PLATFORM_OTHER    = 0;
var PLATFORM_WINDOWS  = 1;
var PLATFORM_LINUX    = 2;
var PLATFORM_MACOSX   = 3;
var PLATFORM_MAC      = 4;
var PLATFORM_MACOSX_PPC = 5;

var gPlatform = PLATFORM_WINDOWS;

if (navigator.platform.indexOf("Win32") != -1)
  gPlatform = PLATFORM_WINDOWS;
else if (navigator.platform.indexOf("Linux") != -1)
  gPlatform = PLATFORM_LINUX;
else if (navigator.userAgent.indexOf("Mac OS X") != -1)
  gPlatform = PLATFORM_MACOSX;
else if (navigator.userAgent.indexOf("MSIE 5.2") != -1)
  gPlatform = PLATFORM_MACOSX;
else if (navigator.platform.indexOf("Mac") != -1)
  gPlatform = PLATFORM_MAC;
else
  gPlatform = PLATFORM_OTHER;


platform = getPlatformName (gPlatform) ;

if (platform == 'Linux i686') {
    flock_platform = 'linux';
    flock_platform_name = 'Linux';
}
else if (platform == 'Mac OS X') {
    flock_platform = 'mac';
    flock_platform_name = 'Mac';
}
else {
    flock_platform = 'win';
    flock_platform_name = 'Windows';
}

//Override platform
if(document.location.search.match(/platform=win/)){
  flock_platform = 'win';  
}
if(document.location.search.match(/platform=mac/)){
  flock_platform = 'mac';  
}
if(document.location.search.match(/platform=linux/)){
  flock_platform = 'linux';  
}

for(i in _download_source_exceptions){
	var source_re = eval('/utm_source=' + i + '/');
	var content_re = eval('/utm_content=' + i + '/');
	//Process this separately from the cookie so that it overrides
	if(document.location.search.match(source_re) || document.location.search.match(content_re)){
        	flock_product_name = _download_source_exceptions[i];
		break;
	}
	//If no query string param, look for a cookie if coming from browser host 
 	if(document.location.href.match('/^http:\/\/browser/') && readCookie('fl_utm_source') == i){
        	flock_product_name = _download_source_exceptions[i];
		break;
	}
}

flock_download_link = 'http://downloads.flock.com/index.php?os=' + flock_platform + '&product=' + flock_product_name;
if(is_stage){
	//flock_download_link += '&debug=1';
}

var query_string = document.location.search.substr(1);
if(query_string != ''){
    query_string = '&' + query_string;
}

flock_download_link += query_string;

var download = {
	email_req: 0,
	link: '',
	interstitial: '',
	platform: 'win',
	appVer: navigator.appVersion.toLowerCase(),

	get_email_req: function(){
		var val = readCookie("fl_mandatory_email");
		if (val == null || val == '' || val == 'null' || typeof val == 'undefined') {
			// Set mod to 2 for a 50/50 distribution (i.e. mandatory 50% of the time)
			//var mod = 2;
			// Set mod to 10 for a 90/10 distribution (i.e. mandatory 10% of the time)
			var mod = 10;
			val = Math.ceil(Math.random() * 10) % mod;
			createCookie("fl_mandatory_email", val, 60);
		}
		this.email_req = val;
		return val;
	},

	get_platform: function(){
		if(navigator.platform.indexOf('Linux') != -1){
			this.platform = 'linux';
		}
		if(navigator.platform.indexOf('Mac') != -1){
			this.platform = 'mac';
		}
	},

	init: function(link, interstitial){
		this.link = link;
		this.download_source_exceptions = _download_source_exceptions;
		this.get_platform();
		this.get_email_req();
		var new_os = '';
		var new_product = '';
                if(interstitial){
			//If we've set document.query_string in some other script (for partner
			//stuff), use that; else use document.location.search.
			if(typeof document.query_string != 'undefined'){
				interstitial += document.query_string;
			}
			else{
				interstitial += document.location.search;
			}
			if(interstitial.match(/platform=(\w*)/)){
                        	new_os = interstitial.replace(/(.*)platform=(mac|win|linux)(.*)/, "$2");
                        	this.link = this.link.replace(/os=(mac|win|linux)/, "os=" + new_os);
			}
			//for(var i = 0; i < this.download_source_exceptions.length; i++){
			for(i in this.download_source_exceptions){
				rexp = eval('/utm_source=' + i + '/');
				rexp2 = eval('/utm_content=' + i + '/');
				if(interstitial.match(rexp)){
					//this.link = this.link.replace(/product=(.*)&/, "product=$1-" + this.download_source_exceptions[i] + '&');
					var str = this.link + '\n';
					this.link = this.link.replace(/product=([^&]*)/, "product=" + this.download_source_exceptions[i]);
					break;
				}
			}
                }

		if(typeof campaignTracker != 'undefined'){
			for(var i in campaignTracker.keys){
				this.replace_or_append(i, campaignTracker.keys[i]);
			}
		}

		// Start the "pop-up" download for IE if entering the email isn't required
		if (this.appVer.indexOf('msie') != -1) {
			if (this.email_req != 1) {
				inst("interstitial_download");
				window.open(this.link, 'download_window_2', 'toolbar=0,location=no,directories=0,status=0,scrollbars=0,resizeable=0,width=1,height=1,top=0,left=0');
				window.focus();
			} else {
				createCookie("fl_download_link", this.link);
			}
		} else if (this.platform == 'linux' || new_os == 'linux') {
			if (this.email_req != 1) {
				inst("interstitial_download");
				document.location.href = this.link;
				return false;
			} else {
				createCookie("fl_download_link", this.link);
			}
		}

		if (interstitial && interstitial != '' && new_os != 'linux') {
			_interstitial = interstitial;
			window.setTimeout('goto_interstitial()', 0);
			return false;
		}

		return true;
	},
  
	replace_or_append: function(key, val){
		//alert(key + ': ' + val);
		var rexp = eval('/' + key + '=/');
		var rexp2 = eval('/' + key + '=([a-zA-Z0-9\-_]*)&?/');
		if(this.link.match(key)){
			this.link.replace(rexp2, key + '=' + campaignTracker.keys[key]);
		}
		else{
			if(this.link.match(/\?/)){
				this.link += '&' + key + '=' + val;
			}
			else{
				this.link += '?' + key + '=' + val;
			}
		}
		//alert(this.link);
	}
}

var campaignTracker = {
	download_source_exceptions: _download_source_exceptions,
	query_string: document.location.search.substring(1),
	download_partner: 'flock',
	platform: 'win',
	keys: {},
	is_partner_link: function(key){
		//for(var i = 0; i < this.download_source_exceptions.length; i++){
		for(i in this.download_source_exceptions.length){
			if(key == i){
				return true;
			}	
		}
		return false;
	},
	init: function(){
		var has_qs = 0;
		var parts = this.query_string.split('&');
		for(var i = 0; i < parts.length; i++){
			has_qs++;
			var pieces = parts[i].split('=');
			//Store platform if specified and valid
			if(pieces[0] == 'platform' && (pieces[1] == 'win' || pieces[1] == 'linux' || pieces[1] == 'mac')){
				this.platform = pieces[1];
			}
			//Store the partner if specified and valid
			if((pieces[0] == 'utm_source' && this.is_partner_link(pieces[1])) || (pieces[0] == 'utm_content' && this.is_partner_link(pieces[1]))){
				this.download_partner = pieces[1];
			}
			//If it's a GA param...
			if(pieces[0].match(/^utm_/)){
				//See if we've got it in a cookie already so that we can persist 
				//the original source.
				var val = readCookie('fl_' + pieces[0]);
				//If in cookie, then store the value in the object.
				if(val != null && val != '' && val != 'null' && typeof val != 'undefined'){
					this.keys[pieces[0]] = val;	
				}
				//If not in cookie, then add current value to cookie and object.
				else{
					this.keys[pieces[0]] = pieces[1];
					createCookie('fl_' + pieces[0], pieces[1], 1);
				}
			}
			else{
				this.keys[pieces[0]] = pieces[1];
			}
		}

		//For pages loaded after initial hit, get params from cookies if no query string.
		if(has_qs == 0){
			this.keys['utm_content'] = readCookie('fl_utm_content');
			this.keys['utm_campaign'] = readCookie('fl_utm_campaign');
			this.keys['utm_source'] = readCookie('fl_utm_source');
			this.keys['utm_medium'] = readCookie('fl_utm_medium');

		}

		//Save referer if not already saved.
		if(typeof document.referrer != 'undefined' && readCookie('fl_referer') == null){
			createCookie('fl_referer', document.referrer, 1);
		}

		if(typeof urchinTracker != 'undefined'){
			var url = new String(document.location.href);
			url = url.replace(/\?.*$/, '');
			var qs = new Array();
			for(var j in this.keys){
				if(j != '' && this.keys[j] != 'undefined'){
					qs[qs.length] = j + '=' + this.keys[j];
				}
			}
			if(qs.length > 0){
				//alert(qs);
				url += '?' + qs.join('&');
			}
			urchinTracker(url);
		}
	}
}

function goto_interstitial(){
        document.location.href = _interstitial;
}

function getPlatformName(aPlatform) {
  if (aPlatform == PLATFORM_WINDOWS)
    return "Windows";
  if (aPlatform == PLATFORM_LINUX)
    return "Linux i686";
  if (aPlatform == PLATFORM_MACOSX)
    return "Mac OS X";
  if (aPlatform == PLATFORM_MACOSX_PPC)
    return "Mac OS X PowerPC";
  return "Unknown";
}

//Begin instrumentation stuff
var click_ref = 'welcome';

function inst(key, ref){
		if(ref){
		click_ref = ref;
	}

		key = key.replace(/no_nav_click/, click_ref);

	var path = inst_path_prefix + key;	

	var debug = false;
	if(document.location.search.match(/test=/)){
		debug = true;
	}

	if(debug){
		alert(path);
	}

	try{
		urchinTracker(path);
	}
	catch(e){
		if(debug !== false){
			alert(e);
		}
	}
}

//End instrumentation stuff
