/*
		Script:	DemandBase API Plugin
		Author:	Michael Langford, Manager of Web Development, Ariba, Inc.
		Version:	1.0

		Usage:	Set options in DemandbaseOptions, no other setup needs to be done.
						objectRef: String		Required.  You must set this to whatever you use as the object name when you instantiate this class.
						autorun: true|false		This will cause the script to pull and store demandbase data immediately on page load.
						debug:	true|false		A simple utility method that lets you print out the console (console must exist -- sorry IE7, you suX0rz).
						ip: false|String		This is a required value - should be set to use the CLIENT IP address, and generally is best practice to set
													this value using server-side code.  Pure client-side methods are not generally reliable, however, in the event
													no IP is included, the _getIP method will attempt to return it using the Java native method.
													Set to this option to false to enable the internal client-side method.

													Note, localhost loopback IP (127.0.0.1) does not work and will always result in an error from the DemandBase API,
													so the getData function aborts to save the roundtrip.
						hideOnAutocomplete	true|false		Set this to true to make text/select fields hide when they are populated by autocomplete api.

			***Add information on anchor_points***

			***Add information on InputFieldMaps***


		API:		If you do not use the autorun option or if you want to re-run the demandbase call after the fact, use the getData method:

							demandbase.getData( string IP )  // returns demandbase data object - must pass an IP address in - causes a JSONP call to fire.

							demandbase.getValue( string Parameter )  // returns string containing value of Parameter from demandbase data object or and empty string if none
																										NOTE: this is an asyncronous call, so the value may not be available immediatly on page load. Wrapping
																										your call in a jQuery ready function, though, will help:

																										$(demandbase.Data).ready(function(){  ...  });



*/

/*
	This mapping object is annoying and stupid and inefficient, but totally
	necessary because forms don't all have consistent form names. It is only
	necessary to include form fields that will be linked to demandbase data.

	The name of each map container should match a class name in the form that
	the map relates to..

	For each field put the field id on the left, and the demandbase property
	name on the right:  "AribaFormFieldID" : "DemandbaseFieldName"
*/

if(($.browser.msie) && (parseInt($.browser.version) == 7)){
//	$("#faildiv").html("IE 7 makes me cry.");
}else{


var InputFieldMaps = {
	"id_contactme_form":{
		"cf_C_Annual_Revenue1": "revenue_range",
		"cf_C_Industry1": "industry",
		"cf_C_SubIndustry1": "sub_industry",
		"company_cm": "company_name",
		"country_cm":"country_name",
		"state_cm": "state",
		"phone_cm": "phone"
	},
	"LiveDemo":{
		"ld-annualrevenues" :"revenue_range",
		"ld-company" :"company_name",
		"ld-country" :"country_name",
		"ld-industry" :"industry",
		"ld-phone" :"phone",
		"ld-state" :"state",
		"ld-sub_industry" :"sub_industry"
	},
	"ResourceLibrary":{
		"annualrevenues_rl" :"revenue_range",
		"company_rl" :"company_name",
		"country_rl" :"country_name",
		"industry_rl" :"industry",
		"phone_rl" :"phone",
		"state_rl" :"state",
		"sub_industry_rl" :"sub_industry"
	},
	"StartSourcingForm":{
		"dbd_annual_sales": "annual_sales",
		"dbd_city": "city",
		"dbd_registry_city": "registry_city",
		"dbd_company_name": "company_name",
		"dbd_registry_state":"registry_state",
		"dbd_country": "country_name",
		"dbd_state": "state",
		"dbd_stock_ticker": "stock_ticker",
		"dbd_street_address": "street_address",
		"dbd_web_site": "web_site",
		"dbd_zip": "zip",
		"dbd_marketing_alias": "marketing_alias"
	},
	"SomeOtherTestForm":{
		"revenue2": "revenue_range",
		"industry2": "industry",
		"SubIndustry2": "sub_industry",
		"company2": "company_name",
		"country2":"country_name",
		"phone2": "phone",
		"state2": "state"
	}
};

var DemandbaseOptions = {
	"objectRef": "objDemandbase",
	"useAutoComplete": false,
	"autorun": true,
	"debug": function(){
//		if(!console){ return false; }
		if(window.location.hostname == "localhost"){ return true }
		else{return false}
	},
	"ip_address": ip,
	"hideOnAutocomplete": false,
	"anchor_points": {
		"contact_me":{
			"form_id":"id_contactme_form",
			"company":"company_cm",
			"email":"email_cm"
		},
		"live_demo":{
			"form_id":"id_demo_form",
			"company":"ld-company",
			"email":"email_ld"
		}
	}
};

$.Class.extend("DemandbaseClass",{},{
	init:function(config){
		this.DemandbaseKey = "40cd257919979f0956bd52b0ef7de581d843e7d8";
		this.config = config;
		this.config.protocol = ("https:"==document.location.protocol?"https://":"http://");
		this.Data = new Object();
		if(!this.config.ip_address){ this._getIP(); }
		if(this.config.autorun){ this.getData(this.config.ip_address); }

//		if(this.config.debug){ console.log("from init: READY"); }
//		if(this.config.debug){ console.log("from init:", this.Data); }


		if(this.useAutoComplete){
			var api_url = this.config.protocol + "api.demandbase.com/autocomplete/widget.js";
			$.getScript(api_url, function(){
				var _this = eval(window.DemandbaseOptions.objectRef);

				window.Demandbase.CompanyAutocomplete.widget({
					company: "company",
					email: "email",
					key: _this.DemandbaseKey,
					callback: eval(_this.config.objectRef + "._jsoncallback")
				});

			});
		}
	},

	/* Public Method */

	getData: function(ip){
		if(ip && ip != "127.0.0.1"){
			var api_url = this.config.protocol + "api.demandbase.com/api/v2/ip.json?" + this._useJSONP();
			var api_params = { "query":ip, "token":this.DemandbaseKey };
			$.getJSON(api_url,api_params, function(data) {
				var _this = eval(DemandbaseOptions.objectRef);
				_this.Data = data;
//				if(_this.config.debug){ console.log("from getData: ", _this.Data); }

/*
				_this.config.formkey = window.location.href.split("/").pop().split(".cfm")[0];
				_this.config.currentAnchor = eval("_this.config.anchor_points." + _this.config.formkey);

				if(_this.config.currentAnchor){
					_this.config.InputFieldMaps = window.InputFieldMaps;
					var anchorID = _this.config.currentAnchor.form_id;

					if(_this.config.debug){
						console.log("anchor object ID: ", eval("_this.config.InputFieldMaps." + anchorID));
					}

					$("#" + anchorID + " input").each(function(){
						var _this = eval(DemandbaseOptions.objectRef);
						//if($(this).attr("id") == eval("_this.config.InputFieldMaps" + _this.config.currentAnchor.form_id ".))
					})
*/

					_this.applyValueByClass("company_name","fldCompany",{"hide":"yes"});
					_this.applyValueByClass("state","fldState",{"hide":"yes"});
					_this.applyValueByClass("country_name","fldCountry",{"modifier":"toUpperCase()", "hide":"yes"});
					_this.applyValueByClass("revenue_range","fldAnnualRevenue",{"hide":"yes"});
					_this.applyValueByClass("industry","fldIndustry",{"hide":"yes"});
					_this.applyValueByClass("sub_industry","fldSubIndustry",{"hide":"no"});
					_this.applyValueByClass("phone","fldPhone",{"hide":"yes"});
					_this.applyValueByClass("annual_sales","fldAnnualSales",{"hide":"yes"});
					_this.applyValueByClass("city","fldCity",{"hide":"yes"});
					_this.applyValueByClass("registry_city","fldRegistryCity",{"hide":"yes"});
					_this.applyValueByClass("registry_state","fldRegistryState",{"hide":"yes"});
					_this.applyValueByClass("state","fldState",{"hide":"yes"});
					_this.applyValueByClass("stock_ticker","fldStockTicker",{"hide":"yes"});
					_this.applyValueByClass("street_address","fldStreetAddress",{"hide":"yes"});
					_this.applyValueByClass("web_site","fldWebSite",{"hide":"yes"});
					_this.applyValueByClass("zip","fldZip",{"hide":"yes"});
					_this.applyValueByClass("marketing_alias","fldMarketingAlias",{"hide":"yes"});


					//_this._apply();
/*

					if(_this.config.debug){
						console.log($("#" + _this.config.currentAnchor.form_id));
						console.log($("#" + _this.config.currentAnchor.company));
						console.log($("#" + _this.config.currentAnchor.email));
					}
				}
				else{
					if(_this.config.debug){
						console.log("_this.config.currentAnchor: " , _this.config.currentAnchor);
					}

				}
*/
			});
		}
		else if(ip == "127.0.0.1"){
//			if(_this.config.debug){ console.log("Loopback IP cannot be used: " + ip); }
		}
		else{
//			if(_this.config.debug){ console.log("Error: Invalid or no client IP specified: " + ip); }
		}
	},

	getValue: function(param){
		try{ output = eval("this.Data." + param); }
		catch(err){ output = false; }
		if(output){
			if(param == "country_name"){ output = output.toUpperCase(); }
//			if(this.config.debug){ console.log("from getValue: ", output); }
			return output;
		}
		else{ return ""; }
	},

	applyValueByClass: function(demandbase_key,classname,options){
		try{
//				console.log(demandbase_key,classname,options);
			$("."+classname).val(this.getValue(demandbase_key));

			if(options.hide == "yes" && $("."+classname).val() != ""){
				if(!$("."+classname).is(':hidden')){
					$("."+classname).parent().parent().hide();
				}
			}
/*
			if(options.modifier == "toUpperCase()" && $("."+classname).val() != ""){
				var ThisValue = $("."+classname).val();
				$("."+classname).val(ThisValue.toUpperCase());
			}
*/
		}catch(err){};

//			if(this.config.debug){ console.log("."+classname+": ", $("."+classname).val()); }

	},

	/* Private Method */
	_useJSONP: function(){
//		if($.browser.webkit){ //Stupid Chrome.
//			return "";
//		}
//		else{
			return "callback=?";
//		}
	},

	_jsoncallback: function(data){
		/*
			Note scope is lost here. So, in options, you need to
			configure the name of the global object that contains
			this class. Make sure it matches or this method will explode.
		*/
		var _this = eval(DemandbaseOptions.objectRef);

		if(data.pick){
			var pick = data.pick;
			if(pick.company_name){
				_this.Data = pick;
			}
		}
		if(data.person){ /* this comes from email address domain - it's not really a person per se */
			var person = data.person;
			_this.Data = person;
		}
		if(data.input_match){
			var input_match = data.input_match;
			_this.Data = input_match;
		}

/*
		if(this.config.debug){
			console.log(data);
			console.log(this.textField[0]);
		}
*/
		_this._apply(this.textField[0]);
	},

	_getIP: function(){
		try{
			if(java && java.net){
				this.config.ip_address = ''+java.net.InetAddress.getLocalHost().getHostAddress();
			}
			else{
				this.config.ip_address = false;
			}
		}catch(err){}
	},
	_apply: function(element){
		var _form = $(element).parents("form");
		_form = $(_form);
		var _fieldmap = eval("InputFieldMaps." + $(element).parents("form").attr("id"));
		$.each(_fieldmap,this.callback(function(htmlfield,demandbasefield){
			var field = $(_form).find('#' + htmlfield)[0];

//			if(this.config.debug){ console.log($(field)[0], demandbasefield, "value: ", this.getValue(demandbasefield)); }

			var row = $(field).parents("tr")[0];
			$(field).val(this.getValue(demandbasefield));
			if($(field).attr("type") == "text" && this.hideOnAutocomplete){
				$(row).hide();
			}
		}));

	}

});

var objDemandbase = new DemandbaseClass(DemandbaseOptions);

}

/*
	API Field Refererence:

	The following are the fields returned by demandbase.  All fields listed
	below are returned by from the IP API call. Items	marked with an X are the only fields returned
	whenthe IP does not match a corporate IP address.  Items marked with an O are returned via autocomplete
	widget when the email domain matches a domain in the registry, or the company is selected from the dropdown.

O	annual_sales
O	city
O	company_name
O	country
O	country_name
O	demandbase_sid
O	employee_count
O	employee_range
O	forbes_2000
O	fortune_1000
O	industry
X	ip
X	isp
O	latitude
O	location_contacts
O	longitude
O	marketing_alias
O	phone
O	primary_sic
X	registry_area_code
X	registry_city
X	registry_company_name
X	registry_country
X	registry_country_code
X	registry_latitude
X	registry_longitude
X	registry_state
X	registry_zip_code
O	revenue_range
O	state
O	stock_ticker
O	street_address
O	sub_industry
O	total_contacts
O	web_site
O	zip


*/
