var ADCENTRIC = ADCENTRIC || { };
ADCENTRIC.lang = ADCENTRIC.lang || { };
ADCENTRIC.env = ADCENTRIC.env || { };

ADCENTRIC.env.random_number = Math.random();
ADCENTRIC.env.util = ADCENTRIC.env.util || { };
ADCENTRIC.env.creatives = ADCENTRIC.env.creatives || { };

ADCENTRIC.lang.namespace = function(nsname) {
	var nodes = nsname.split(".");
	var obj = window;

	for (var i = 0; i < nodes.length; i++) {
		obj[nodes[i]] = obj[nodes[i]] || { };
		obj = obj[nodes[i]];
	}
	return obj;
};

ADCENTRIC.lang.namespace("ADCENTRIC.util");
ADCENTRIC.env.util['FlashTag_default_version'] = '8,0,0,0';
ADCENTRIC.env.util['FlashTag_default_bgcolor'] = 'ffffff';
ADCENTRIC.env.util['ExternalInterfaceProxy_pixel_swf_url'] = 'http://assets.adcentriconline.com/architectures/lcPixel.swf';
ADCENTRIC.env.util['ExternalInterfaceProxy_DOM_id_prefix'] = 'adceip';


ADCENTRIC.env.util.DetectFlashPlugin = function(){
	var FlashDetect = new function(){
		var self = this;
		self.installed = false;
		self.major = -1;
		self.minor = -1;
		self.revision = -1;
		self.revisionStr = "";
		self.activeXVersion = "";
		var activeXDetectRules = [
		{
			"name":"ShockwaveFlash.ShockwaveFlash.7",
			"version":function(obj){
				return getActiveXVersion(obj);
			}
		},
		{
			"name":"ShockwaveFlash.ShockwaveFlash.6",
			"version":function(obj){
				var version = "6,0,21";
				try{
					obj.AllowScriptAccess = "always";
					version = getActiveXVersion(obj);
				}catch(err){}
				return version;
			}
		},
		{
			"name":"ShockwaveFlash.ShockwaveFlash",
			"version":function(obj){
				return getActiveXVersion(obj);
			}
		}
		];
		var getActiveXVersion = function(activeXObj){
			var version = -1;
			try{
				version = activeXObj.GetVariable("$version");
			}catch(err){}
			return version;
		};
		var getActiveXObject = function(name){
			var obj = -1;
			try{
				obj = new ActiveXObject(name);
			}catch(err){}
			return obj;
		};
		var parseActiveXVersion = function(str){
			var versionArray = str.split(",");//replace with regex
			return {
				"major":parseInt(versionArray[0].split(" ")[1], 10),
				"minor":parseInt(versionArray[1], 10),
				"revision":parseInt(versionArray[2], 10),
				"revisionStr":versionArray[2]
			};
		};
		var parseRevisionStrToInt = function(str){
			return parseInt(str.replace(/[a-zA-Z]/g, ""), 10) || self.revision;
		};
		self.majorAtLeast = function(version){
			return self.major >= version;
		};
		self.FlashDetect = function(){
			if(navigator.plugins && navigator.plugins.length>0){
				var type = 'application/x-shockwave-flash';
				var mimeTypes = navigator.mimeTypes;
				if(mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin && mimeTypes[type].enabledPlugin.description){
					var desc = mimeTypes[type].enabledPlugin.description;
					var descParts = desc.split(' ');//replace with regex
					var majorMinor = descParts[2].split('.');
					self.major = parseInt(majorMinor[0], 10);
					self.minor = parseInt(majorMinor[1], 10);
					self.revisionStr = descParts[3];
					self.revision = parseRevisionStrToInt(self.revisionStr);
					self.installed = true;
				}
			}else if(navigator.appVersion.indexOf("Mac")==-1 && window.execScript){
				var version = -1;
				for(var i=0; i<activeXDetectRules.length && version==-1; i++){
					var obj = getActiveXObject(activeXDetectRules[i].name);
					if(typeof obj == "object"){
						self.installed = true;
						version = activeXDetectRules[i].version(obj);
						if(version!=-1){
							var versionObj = parseActiveXVersion(version);
							self.major = versionObj.major;
							self.minor = versionObj.minor;
							self.revision = versionObj.revision;
							self.revisionStr = versionObj.revisionStr;
							self.activeXVersion = version;
						}
					}
				}
			}
		}();
	};

	return FlashDetect;
}


/*
 * ADCENTRIC.env.util.ParseQstring takes a query string as a parameter. Key=Value pairs can be seperated by either 
 * and ampersand (&) or a semicolon (;). When passing the query argument, make sure the key value pairs are seperated 
 * by ONE of these 2 characters. Any character that is meant to be a litteral semicolon or litteral ampersand should be 
 * URL ENCODED in order for parsing not to be confused.
 *
 * Return value for ParseQstring function is an array Object (Params) whose indexes are the keys.
 * values can be fetched with dot notation, ex: Params.key1 = value1, Params.key2 = value2, etc etc
 * 
 */
ADCENTRIC.env.util.ParseQstring = function(query){
	var Params = new Object ();
	if ( ! query ) return Params; // return empty object
	var Pairs = query.split(/[;&]/);
	for ( var i = 0; i < Pairs.length; i++ ) {
		var KeyVal = Pairs[i].split('=');
		if ( ! KeyVal || KeyVal.length != 2 ) continue;
		var key = unescape( KeyVal[0] );
		var val = unescape( KeyVal[1] );
		val = val.replace(/\+/g, ' ');
		Params[key] = val;
	}
	return Params;
}

/*
 * ADCENTRIC.env.util.getQstring takes no parameters. It returns it's own query string by fectching it's source URL and
 * deleting everything before the question mark '?' (inclusively)
 * IMPORTANT: getQstring cannot be used to get the qstring of the window location or any other qstring for that matter!!
 * getQstring is ONLY used to grab the current JS (core.js) script's qstring
 *
 */
ADCENTRIC.env.util.getQstring = function(){
	var scripts = document.getElementsByTagName('script');
	var index = scripts.length;
	var has_csise = false;

	while (index > 0 && !has_csise){
		index--;

		if(scripts[index].src.indexOf('csise') != -1){
			has_csise = true;
		}
	}


	var adc_script = scripts[index];

	return adc_script.src.replace(/^[^\?]+\??/,'');
}

/*
 * ADCENTRIC.util.Events is a simple procedural API for setting up events in a friendly way, for use
 * internally by adcentric.js
 */
ADCENTRIC.util.Events = {
add_window_onload: function(func) {
			   var oldonload = window.onload;
			   if (typeof window.onload != 'function') {
				   window.onload = func;
			   } else {
				   window.onload = function() {
					   oldonload();
					   func();
				   }
			   }
		   }
};





/*
 * ADCENTRIC.util.FlashTag is adapted from the JavaScript and Flash Integration Kit by Christian Cantrell,
 * Mike Chambers et al.  The JavaScript and Flash Integration Kit is distributed under the open-source
 * Apache 1.1 license.  See http://weblogs.macromedia.com/flashjavascript/ for more information.
 */
ADCENTRIC.util.FlashTag = function(src, width, height) {
	var src = src;
	var width = width;
	var height = height;
	var id = null;
	var flashvars = null;
	var version = ADCENTRIC.env.util['FlashTag_default_version'];
	var bgcolor = ADCENTRIC.env.util['FlashTag_default_bgcolor'];
	var msie_wmode = null;
	var ff_wmode = null;

	return {
set_msie_wmode: function(new_msie_wmode) {
			msie_wmode = new_msie_wmode;
		},
set_ff_wmode: function(new_ff_wmode) {
		      ff_wmode = new_ff_wmode;
	      },

set_version: function(new_version) {
		     version = new_version;
	     },

set_id: function(new_id) {
		id = new_id;
	},

set_bgcolor: function(new_bgcolor) {
		     bgcolor = new_bgcolor;
	     },

set_flashvars: function(new_flashvars) {
		       flashvars = new_flashvars;
	       },

to_string: function() {
		   var ie = (navigator.appName.indexOf("Microsoft") != -1) ? 1 : 0;
		   var flash_tag = new String();
		   var newsrc = src;
		   if (flashvars != null)
			   newsrc += "?" + flashvars;

		   if (ie) {
			   flash_tag += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
			   if (id != null) {
				   flash_tag += 'id="' + id + '" ';
			   }
			   flash_tag += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + version + '" ';
			   flash_tag += 'width="' + width + '" ';
			   flash_tag += 'height="' + height + '">';
			   flash_tag += '<param name="movie" value="' + newsrc + '"/>';
			   flash_tag += '<param name="quality" value="high"/>';
			   flash_tag += '<param name="allowScriptAccess" value="always"/>';
			   flash_tag += '<param name="scale" value="noscale"/>';
			   flash_tag += '<param name="bgcolor" value="#' + bgcolor + '"/>';
			   if(msie_wmode){
				   flash_tag += '<param name="wmode" value="' + msie_wmode + '"/>';
			   }
			   if (flashvars != null) {
				   flash_tag += '<param name="flashvars" value="' + flashvars + '"/>';
			   }
			   flash_tag += '</object>';
		   } else {
			   flash_tag += '<embed src="' + newsrc + '" ';
			   flash_tag += 'quality="high" ';
			   flash_tag += 'bgcolor="#' + bgcolor + '" ';
			   flash_tag += 'width="' + width + '" ';
			   flash_tag += 'height="' + height + '" ';
			   flash_tag += 'allowScriptAccess="always" ';
			   flash_tag += 'scale="noscale" ';
			   flash_tag += 'type="application/x-shockwave-flash" ';
			   if (flashvars != null) {
				   flash_tag += 'flashvars="' + flashvars + '" ';
			   }
			   if (id != null) {
				   flash_tag += 'name="' + id + '" ';
			   }
			   if(ff_wmode){
				   flash_tag += 'wmode="' + ff_wmode + '" ';
			   }
			   flash_tag += 'pluginspage="http://www.macromedia.com/go/getflashplayer">';
			   flash_tag += '</embed>';
		   }
		   return flash_tag;
	   },

write: function(doc) {
	       doc.write(this.to_string());
       },

this_movie: function() {
		    if (id == null)
			    return null;
		    if (navigator.appName.indexOf("Microsoft") != -1) {
			    return window[id];
		    } else {
			    return document[id];
		    }
	    }
	};
};

/*
 * XXX proper description required!
 *
 * EXAMPLE USAGE:
 *
 * // ... before creative is setup():
 * ADCENTRIC.env.creatives[creative_id].placements[placement_id].lcPix = ADCENTRIC.util.ExternalInterfaceProxy(creative_id, placement_id);
 * ADCENTRIC.env.creatives[creative_id].placements[placement_id].lcPix.setup();
 *
 * // ... after page and creative are loaded:
 * ADCENTRIC.env.creatives[creative_id].placements[placement_id].lcPix.call("someASFunction");
 */
ADCENTRIC.util.ExternalInterfaceProxy = function(creative_id, placement_id, swf_id) {
	/*
	 * XXX: not sure if we actually need to cache bust here; I assume no, but I'd rather be safe than sorry, as each instance of
	 * ExternalInterfaceProxy *must* force a loading of the pixel SWF with a new set of FlashVar values.
	 */
	var lc_rand_id = Math.floor(Math.random() * 1000000);
	var pixel_swf = ADCENTRIC.util.FlashTag(ADCENTRIC.env.util['ExternalInterfaceProxy_pixel_swf_url'], '1', '1');


	return {

write_container: function(){
	document.write('<div id="lcpix_container_' + String(creative_id) + '_' + String(placement_id) + '_' + String(swf_id) + '" style="visibility:visible;width:1px;height:1px;position:absolute;display:block;top:-1000px;left:-1000px;"></div>');
},
id: function() {
	    return ADCENTRIC.env.util['ExternalInterfaceProxy_DOM_id_prefix'] + "_" + String(creative_id) + "_" + String(placement_id)+ "_" + String(swf_id);
    },
lc_id: function() {
	       return String(lc_rand_id);
       },
new_lc_id: function() {
		// use this method only on local testing purpose
		if(adc_local_testing){
	    	lc_rand_id = Math.floor(Math.random() * 1000000);
		}
		return;
       },
setup: function() {

	       pixel_swf.set_flashvars("crID=" + String(creative_id) + "&lcRandID=" + this.lc_id());
	       pixel_swf.set_id(this.id());

	       //document.writeln(pixel_swf.to_string());
	       document.getElementById('lcpix_container_' + String(creative_id) + '_' + String(placement_id) + "_" + String(swf_id)).innerHTML = pixel_swf.to_string();


	       //REQUIRED FOR LOOP
	       //This enables swf_pixel object to be visible in the window object
	       //Bypasses the in FORM problems with external Interface

	       for(var i=0;i<document.forms.length;i++){
		       if(document.forms[i][ADCENTRIC.env.util['ExternalInterfaceProxy_DOM_id_prefix'] + "_" + String(creative_id) + "_" + String(placement_id) + "_" + String(swf_id)]){
			       window[ADCENTRIC.env.util['ExternalInterfaceProxy_DOM_id_prefix'] + "_" + String(creative_id) + "_" + String(placement_id) + "_" + String(swf_id)] = document.forms[i][ADCENTRIC.env.util['ExternalInterfaceProxy_DOM_id_prefix'] + "_" + String(creative_id) + "_" + String(placement_id) + "_" + String(swf_id)];
		       }
	       }

	       /*
		* deprecated, document write of the pixel swf now used for cross browser compliance
		var write_div = function() { write_container(pixel_swf.to_string()); };
		ADCENTRIC.util.Events.add_window_onload(write_div);
		*/
       },
call: function(func_name) {
		var args = new Array();
		for(var i=1; i<arguments.length; i++){
			args.push(arguments[i]);
		}
		pixel_swf.this_movie().dispatchFunc(this.lc_id(), func_name, args);
      }
	};
};

/* XXX TO BE DEPRECATED, LEGACY adcClick()/adcAction() global-namespace API: */
function adcClick(crID, _name) { }
function adcAction(crID, _name, _obj) { }

/*
 * qstring variable will contain the qstring contained in core.js's URL
 * params variable is an hash with indexes being the KEYs of the qstring
 *
 */

var qstring = ADCENTRIC.env.util.getQstring();
var params = ADCENTRIC.env.util.ParseQstring(qstring);
var publisher_click = params.url || false;
var adc_testing = params.adc_testing || false;
var adc_local_testing = params.adc_local_testing || false;
var plugin_obj = ADCENTRIC.env.util.DetectFlashPlugin();


ADCENTRIC.env.has_flash = plugin_obj.installed;

//TO IMPLEMENT: 
//	-Possibility of receiving info as to serve from secure or non secure server
//	-Possibility of passing a qstring to the adcentric js


if(publisher_click){
	document.writeln('<SCR'+'IPT language=\'JavaScript\' S'+'RC="http://adc2.adcentriconline.com/adcentric/tag/'+params.csise+'?url=' + publisher_click+ '&ADCadcifr=1&number='+ADCENTRIC.env.random_number+'"></SCR'+'IPT>');
}else if(adc_testing){
	document.writeln('<SCR'+'IPT language=\'JavaScript\' S'+'RC="http://stanley.adcentriconline.com/~paula/RIPPLE_TESTING/generic_tag.js?architecture=' +params.architecture+ '&format=' +params.format+ 'ADCadcifr=1"></SCR'+'IPT>');
}else if(adc_local_testing){
	ADCENTRIC.env.util['ExternalInterfaceProxy_pixel_swf_url'] = "swfLoaders/lcPixel.swf";
	document.writeln('<SCR'+'IPT language=\'JavaScript\' S'+'RC="script/adcentric_core/templates/generated_template.js?ADCadcifr=1&number='+ADCENTRIC.env.random_number+'"></SCR'+'IPT>');
}else{
	document.writeln('<SCR'+'IPT language=\'JavaScript\' S'+'RC="http://adc2.adcentriconline.com/adcentric/tag/'+params.csise+'?ADCadcifr=1&number='+ADCENTRIC.env.random_number+'"></SCR'+'IPT>');
}



