﻿if (typeof (Vehix) == "undefined")
	Vehix = new Object();
if (typeof (Vehix.Widgets) == "undefined")
	Vehix.Widgets = new Object();

Vehix.Widgets.Utils = function()
{

}

Vehix.Widgets.Utils.prototype =
{
	FormatCurrency: function(num, hidecents)
	{
		if (!num)
			num = 0;
		num = num.toString().replace(/\$|\,/g, '');
		if (isNaN(num))
			num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num * 100 + 0.50000000001);
		cents = num % 100;
		num = Math.floor(num / 100).toString();
		if (cents < 10)
			cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
			num = num.substring(0, num.length - (4 * i + 3)) + ',' +
		num.substring(num.length - (4 * i + 3));
		if (hidecents)
			return (((sign) ? '' : '-') + '$' + num);
		return (((sign) ? '' : '-') + '$' + num + "." + cents);
	},

	AddCommas: function(n)
	{
		var num;
		if (isNaN(n)) n = 0;
		var sign = ((n == Math.abs(n)));
		num = Math.abs(n).toString().replace(/\$|\,/g, '');
		for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
			num = num.substring(0, num.length - (4 * i + 3)) + ',' +
			num.substring(num.length - (4 * i + 3));
		return (((sign) ? '' : '-') + num);
	},

	ZeroMeansNotAvailable: function(price)
	{
		var result = 'not available';
		var num = price.toString().replace(/\$|\,/g, '')
		if (num != 0 && !isNaN(num))
			result = formatCurrency(num, true);
		return result;
	},

	AssignBoundEventHandler: function(eventStringRepresentation, initiatingObject, objectToBind, handler, args)
	{
		switch (eventStringRepresentation)
		{
			case "onclick":
				this._assignBoundClickHandler(initiatingObject, objectToBind, handler, args);
				break;
			case "click":
				this._assignBoundClickHandler(initiatingObject, objectToBind, handler, args);
				break;
			case "mouseover":
				this._assignBoundMouseoverHandler(initiatingObject, objectToBind, handler, args);
				break;
		}
	},

	ValidateZipCode: function(zip)
	{
		if (zip.search(/^\d{5}$/) == -1)
		{
			window.VehixPresentationService._raiseError("Please enter a valid Zip Code.");
			return false;
		}
		return true;
	},

	GetCookie: function(name)
	{
		var result;
		var re = new RegExp('(?:; )?' + name + '=([^;]*);?');
		if (re.test(document.cookie))
		{
			result = decodeURIComponent(RegExp['$1']);
		}
		return result;
	},

	SetCookie: function(name, value, expires)
	{
		if (typeof (expires) == 'undefined')
		{
			expires = new Date();
			expires.setTime(expires.getTime() + (3600000 * 24 * 30));
		}
		document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + '; expires=' + expires.toGMTString();
	},

	ClearCookie: function(name)
	{
		this.SetCookie(name, '', new Date());
	},

	WriteString: function(str)
	{
		document.write(str);
	},

	OpenWindow: function(sURL, sWindowName, bToolbar, bScrollBars, lWidth, lHeight, lTop, lLeft)
	{
		if (typeof lTop == 'undefined')
		{
			lTop = (screen.height - lHeight) / 2
		}
		if (typeof lLeft == 'undefined')
		{
			lLeft = (screen.width - lWidth) / 2
		}
		if (bToolbar == true)
		{
			bToolbar = 'yes'
			bMenubar = 'yes'
		}
		else
		{
			bToolbar = 'no'
			bMenubar = 'no'
		}
		if (bScrollBars == true)
			bScrollBars = 'yes'
		else
			bScrollBars = 'no'
		var lsFeatures = 'toolbar=' + bToolbar + ',scrollbars=' + bScrollBars + ',resizable=yes,status=yes';
		lsFeatures += ',top=' + lTop
		lsFeatures += ',left=' + lLeft
		if (lWidth > 0) { lsFeatures += ',width=' + lWidth };
		if (lHeight > 0) { lsFeatures += ',height=' + lHeight };
		lsFeatures += ',menubar=' + bMenubar;
		popupWin = window.open(sURL, sWindowName, lsFeatures);
		popupWin.focus();
	},

	_assignBoundClickHandler: function(initiatingObject, objectToBind, handler, args)
	{
		var f = handler.bind(objectToBind);
		var a = args;
		initiatingObject.onclick = function(e)
		{
			VehixWidgetsUtils._cancelEvent(e);
			f(a, e);
		}
	},

	_assignBoundMouseoverHandler: function(initiatingObject, objectToBind, handler, args)
	{
		var f = handler.bind(objectToBind);
		var a = args;
		initiatingObject.onmouseover = function()
		{
			VehixWidgetsUtils._cancelEvent(e);
			f(a);
		}
	},

	_cancelEvent: function(e)
	{
		if (typeof (e) == "undefined")
		{
			if (typeof (event) != "undefined") e = event;
		}
		if (e && e.preventDefault)
		{
			e.preventDefault();
		}
		else if (e)
		{
			e.returnValue = false;
		}
	},

	_changeModel: function(w, v)
	{
		if (w._configObject.StopWidgetReload)
		{
			w.Vehicle = new Object();
			w.Vehicle.MakeName = v.MakeName;
			w.Vehicle.MakeID = v.MakeId;
			w.Vehicle.ModelName = v.ModelName;
			w.Vehicle.ModelID = v.ModelID;
			w.Vehicle.Year = v.Year;
			w._sendCommunication("ChangeModelClicked", true);
		}
		else
		{
			w._sendCommunication("ChangeModelClicked");
			w._vehicleSelector._reloadWidget();
		}
	},

	_sendCommunication: function(w, a, clearTrim, optdat)
	{
		var v = w.Vehicle;
		var t = w.CurrentTrim();
		var o;
		if (clearTrim)
		{
			o = { "Action": a, "MakeName": v.MakeName, "MakeID": v.MakeID, "ModelName": v.ModelName, "ModelID": v.ModelID, "Year": v.Year,
				"TrimID": null, "ChromeStyleID": null, "TrimBodyStyle": null
			};
		}
		else
		{
			o = { "Action": a, "MakeName": v.MakeName, "MakeID": v.MakeID, "ModelName": v.ModelName, "ModelID": v.ModelID, "Year": v.Year,
				"TrimID": t.TrimID, "ChromeStyleID": t.ChromeStyleID, "TrimBodyStyle": t.BodyStyle
			};
		}

		if (typeof (optdat) != "undefined")
			o.ExtensionObject = optdat;
		VehixCommunicationService._sendCommunication(w._callBackFunction, o);
	},

	_trycatchrepeat: function(fnc, bindobj, interval, args, loop, limit)
	{
		try
		{
			var f = fnc.bind(bindobj);
			f(args);
		}
		catch (er)
		{
			if (isNaN(loop)) loop = 0;
			if (isNaN(limit)) limit = 20;
			if (loop <= limit)
			{
				var cb = this._trycatchrepeat.bind(this);
				var inc = loop + 1;
				bindobj._trycatchrepeat_timeout = setTimeout
				(
					function()
					{
						cb(fnc, bindobj, interval, args, inc, limit);
					}
				, interval);
			}
		}
	},

	_wait: function(t)
	{
		var date = new Date();
		var curDate = null;
		do
		{
			curDate = new Date();
		}
		while (curDate - date < t);
	}
}

Vehix.Widgets.Utils.QueryString = function(s)
{
	if (s && s.length)
	{
		this._queryString = s.substring(s.indexOf("?") + 1);
	}
	else
	{
		this._queryString = window.location.search.substring(1);
	}
}

Vehix.Widgets.Utils.QueryString.prototype =
{
	Clear: function()
	{
		this._queryString = "";
	},

	GetValue: function(name)
	{
		var result;
		var q = this._queryString;
		if (q)
		{
			var a = q.split("&");
			for (i = 0; i < a.length; i++)
			{
				o = a[i].split("=");
				if (o[0].toLowerCase() == name.toLowerCase())
				{
					result = decodeURIComponent(o[1]);
				}
			}
		}
		return result;
	},

	ContainsKey: function(key)
	{
		var result = false;
		var q = "&" + this._queryString;
		if (q && key)
		{
			if (q.toLowerCase().search("&" + key.toLowerCase() + "=") != -1)
				result = true;
		}
		return result;
	},

	SetValue: function(key, value)
	{
		var q = this._queryString;
		var s = '';
		if (this.containsKey(key))
		{
			var a = q.split("&");
			for (i = 0; i < a.length; i++)
			{
				o = a[i].split("=");
				if (o[0].toLowerCase() == key.toLowerCase())
				{
					s += '&' + o[0] + '=' + encodeURIComponent(value);
				}
				else
				{
					if (o[0] && o[1])
						s += '&' + o[0] + '=' + o[1];
				}
			}
			this._queryString = s.substring(1);
		}
		else
		{
			this._queryString = q + '&' + key + '=' + encodeURIComponent(value);
		}
	}
}

if (typeof (this.VehixWidgetsUtils) == "undefined")
	this.VehixWidgetsUtils = new Vehix.Widgets.Utils();
