﻿var Core = {};
	
	// Core.DOM namespace
Core.DOM = {

    // Get element(s) by id/class
    GetEl: function(el, parent, returnFirst) {
        if (!parent) parent = document;
        // if we're already passing an element
        // return it straight away
        if (typeof (el) == 'string') {
            // are we looking for an element by it's class
            if (el.indexOf('.') == 0) {
                el = el.substring(1, el.length);
                var elements = Core.DOM.GetElementsByClassName(el, '*', parent);
                if (elements.length > 0) {
                    // if we only want the first object
                    if (returnFirst)
                        el = elements[0];
                    else
                        el = elements;
                } else
                    el = null;
                // are we looking for an element by it's class/parent
            } else if (el.indexOf('.') > 0) {
                var parts = el.split('.');
                var elements = Core.DOM.GetElementsByClassName(parts[1], parts[0], parent);
                if (elements.length == 1)
                    el = elements[0];
                else if (elements.length == 0)
                    el = null;
                else
                    el = elements;
            } else // are we looking for an element by its id
                el = document.getElementById(el);
        }
        return el
    },
    // set the elements text/html
    SetText: function(el, text, isHtml) {

        var el = Core.DOM.GetEl(el);
        if (el) {
            el.innerHTML = (isHtml ? text : '');
            if (!isHtml)
                el.appendChild(document.createTextNode(text));
        }

    },
    // gets an elements value
    GetValue: function(el) {

        var el = Core.DOM.GetEl(el);
        if (!el || !el.nodeName)
            return '';

        switch (el.nodeName.toLowerCase()) {
            case 'input':

                switch (el.type.toLowerCase()) {
                    case 'checkbox':
                    case 'radio':
                    return el.checked;
                        break;
                    case 'text':
                    case 'textarea':
                    case 'hidden':
                        return el.value;
                        break;
                }

                break;
            case 'select':

                if (el.options.length > 0)
                    return el.options[el.selectedIndex].value;

                break;
            case 'textarea':

                return el.value;

                break;
        }

        return '';

    },
    // get elements by class name
    GetElementsByClassName: function(className, tag, elm) {
        var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
        var tag = tag || "*";
        var elm = elm || document;
        var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
        var returnElements = [];
        var current;
        var length = elements.length;
        for (var i = 0; i < length; i++) {
            current = elements[i];
            if (testClass.test(current.className)) {
                returnElements.push(current);
            }
        }
        return returnElements;
    },
    // creates a dom element
    CreateEl: function(type, attributes, parent) {
        var el = document.createElement(type);
        if (attributes)
            Core.DOM.SetAttributes(el, attributes);
        if (typeof (parent) != 'undefined')
            parent.appendChild(el);
        return el;
    },
    // removes a dom element
    RemoveEl: function(el) {
        if (typeof (el) == 'string')
            el = Core.DOM.GetEl(el);
        if (el && el.parentNode)
            el.parentNode.removeChild(el);
    },
    // sets an elements attributes
    SetAttributes: function(el, attributes) {
        for (var attribute in attributes) {
            if (typeof (attributes[attribute]) == 'object') {
                try {
                    Core.DOM.SetAttributes(el[attribute], attributes[attribute]);
                } catch (e) {
                    return false;
                }
            }
            else {
                try {
                    el[attribute] = attributes[attribute];
                } catch (e) {
                    return false;
                }
            }
        }
    },
    // gets the body element
    GetBody: function() {
        var bodies = document.getElementsByTagName('BODY');
        if (bodies.length == 0)
            return false;
        return bodies[0];
    },
    // gets the first form of the page
    GetForm: function() {

        var forms = document.getElementsByTagName('FORM');
        if (!forms || forms.length == 0)
            return false;
        else
            return forms[0];

    },
    // gets the cursor position
    GetCursorPosition: function(e) {
        e = e || window.event;

        var cursor = { x: 0, y: 0 };

        if (e.pageX || e.pageY) {
            cursor.x = e.pageX;
            cursor.y = e.pageY;
        } else {
            cursor.x = e.clientX +
					(document.documentElement.scrollLeft ||
					document.body.scrollLeft) -
					document.documentElement.clientLeft;

            cursor.y = e.clientY +
					(document.documentElement.scrollTop ||
					document.body.scrollTop) -
					document.documentElement.clientTop;
        }
        return cursor;

    }

};

	// Core.Generic namespace
	Core.Generic = {

		// converts newlines to <br /> elements
		nl2br : function(str, is_xhtml) {
			// http://kevin.vanzonneveld.net
			// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
			// +   improved by: Philip Peterson
			// +   improved by: Onno Marsman
			// +   improved by: Atli Þór
			// +   bugfixed by: Onno Marsman
			// +      input by: Brett Zamir (http://brett-zamir.me)
			// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
			// *     example 1: nl2br('Kevin\nvan\nZonneveld');
			// *     returns 1: 'Kevin<br />\nvan<br />\nZonneveld'
			// *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
			// *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
			// *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
			// *     returns 3: '<br />\nOne<br />\nTwo<br />\n<br />\nThree<br />\n'
		 
			var breakTag = '';
		 
			breakTag = '<br />';
			if (typeof is_xhtml != 'undefined' && !is_xhtml) {
				breakTag = '<br>';
			}
		 
			return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
		},
		// formats a date
		FormatDate : function (date, format) {

			if(typeof(date) == 'string')
				date = new Date(date);

			if(isNaN(date))
				return '';
    
			var daysLong =    ["Sunday", "Monday", "Tuesday", "Wednesday", 
							   "Thursday", "Friday", "Saturday"];
			var daysShort =   ["Sun", "Mon", "Tue", "Wed", 
							   "Thu", "Fri", "Sat"];
			var monthsShort = ["Jan", "Feb", "Mar", "Apr",
							   "May", "Jun", "Jul", "Aug", "Sep",
							   "Oct", "Nov", "Dec"];
			var monthsLong =  ["January", "February", "March", "April",
							   "May", "June", "July", "August", "September",
							   "October", "November", "December"];

			var switches = { // switches object
				
				a : function () {
					// Lowercase Ante meridiem and Post meridiem
					return date.getHours() > 11? "pm" : "am";
				},
				
				A : function () {
					// Uppercase Ante meridiem and Post meridiem
					return (this.a().toUpperCase ());
				},
			
				B : function (){
					// Swatch internet time. code simply grabbed from ppk,
					// since I was feeling lazy:
					// http://www.xs4all.nl/~ppk/js/beat.html
					var off = (date.getTimezoneOffset() + 60)*60;
					var theSeconds = (date.getHours() * 3600) + 
									 (date.getMinutes() * 60) + 
									  date.getSeconds() + off;
					var beat = Math.floor(theSeconds/86.4);
					if (beat > 1000) beat -= 1000;
					if (beat < 0) beat += 1000;
					if ((String(beat)).length == 1) beat = "00"+beat;
					if ((String(beat)).length == 2) beat = "0"+beat;
					return beat;
				},
				
				c : function () {
					// ISO 8601 date (e.g.: "2004-02-12T15:19:21+00:00"), as per
					// http://www.cl.cam.ac.uk/~mgk25/iso-time.html
					return (this.Y() + "-" + this.m() + "-" + this.d() + "T" + 
							this.H() + ":" + this.i() + ":" + this.s() + this.P());
				},
				
				d : function () {
					// Day of the month, 2 digits with leading zeros
					var j = String(this.j());
					return (j.length == 1 ? "0"+j : j);
				},
				
				D : function () {
					// A textual representation of a day, three letters
					return daysShort[date.getDay()];
				},
				
				F : function () {
					// A full textual representation of a month
					return monthsLong[date.getMonth()];
				},
				
				g : function () {
				   // 12-hour format of an hour without leading zeros, 1 through 12!
				   if (date.getHours() == 0) {
					   return 12;
				   } else {
					   return date.getHours()>12 ? date.getHours()-12 : date.getHours();
				   }
			   },
				
				G : function () {
					// 24-hour format of an hour without leading zeros
					return date.getHours();
				},
				
				h : function () {
					// 12-hour format of an hour with leading zeros
					var g = String(this.g());
					return (g.length == 1 ? "0"+g : g);
				},
				
				H : function () {
					// 24-hour format of an hour with leading zeros
					var G = String(this.G());
					return (G.length == 1 ? "0"+G : G);
				},
				
				i : function () {
					// Minutes with leading zeros
					var min = String (date.getMinutes ());
					return (min.length == 1 ? "0" + min : min);
				},
				
				I : function () {
					// Whether or not the date is in daylight saving time (DST)
					// note that this has no bearing in actual DST mechanics,
					// and is just a pure guess. buyer beware.
					var noDST = new Date ("January 1 " + this.Y() + " 00:00:00");
					return (noDST.getTimezoneOffset () == 
							date.getTimezoneOffset () ? 0 : 1);
				},
				
				j : function () {
					// Day of the month without leading zeros
					return date.getDate();
				},
				
				l : function () {
					// A full textual representation of the day of the week
					return daysLong[date.getDay()];
				},
				
				L : function () {
					// leap year or not. 1 if leap year, 0 if not.
					// the logic should match iso's 8601 standard.
					// http://www.uic.edu/depts/accc/software/isodates/leapyear.html
					var Y = this.Y();
					if (         
						(Y % 4 == 0 && Y % 100 != 0) ||
						(Y % 4 == 0 && Y % 100 == 0 && Y % 400 == 0)
						) {
						return 1;
					} else {
						return 0;
					}
				},
				
				m : function () {
					// Numeric representation of a month, with leading zeros
					var n = String(this.n());
					return (n.length == 1 ? "0"+n : n);
				},
				
				M : function () {
					// A short textual representation of a month, three letters
					return monthsShort[date.getMonth()];
				},
				
				n : function () {
					// Numeric representation of a month, without leading zeros
					return date.getMonth()+1;
				},
				
				N : function () {
					// ISO-8601 numeric representation of the day of the week
					var w = this.w();
					return (w == 0 ? 7 : w);
				},
				
				O : function () {
					// Difference to Greenwich time (GMT) in hours
					var os = Math.abs(date.getTimezoneOffset());
					var h = String(Math.floor(os/60));
					var m = String(os%60);
					h.length == 1? h = "0"+h:1;
					m.length == 1? m = "0"+m:1;
					return date.getTimezoneOffset() < 0 ? "+"+h+m : "-"+h+m;
				},
				
				P : function () {
					// Difference to GMT, with colon between hours and minutes
					var O = this.O();
					return (O.substr(0, 3) + ":" + O.substr(3, 2));
				},      
				
				r : function () {
					// RFC 822 formatted date
					var r; // result
					//  Thu         ,     21               Dec              2000
					r = this.D() + ", " + this.d() + " " + this.M() + " " + this.Y() +
					//    16          :    01          :    07               0200
					" " + this.H() + ":" + this.i() + ":" + this.s() + " " + this.O();
					return r;
				},

				s : function () {
					// Seconds, with leading zeros
					var sec = String (date.getSeconds ());
					return (sec.length == 1 ? "0" + sec : sec);
				},        
				
				S : function () {
					// English ordinal suffix for the day of the month, 2 characters
					switch (date.getDate ()) {
						case  1: return ("st"); 
						case  2: return ("nd"); 
						case  3: return ("rd");
						case 21: return ("st"); 
						case 22: return ("nd"); 
						case 23: return ("rd");
						case 31: return ("st");
						default: return ("th");
					}
				},
				
				t : function () {
					// thanks to Matt Bannon for some much needed code-fixes here!
					var daysinmonths = [null,31,28,31,30,31,30,31,31,30,31,30,31];
					if (this.L()==1 && this.n()==2) return 29; // ~leap day
					return daysinmonths[this.n()];
				},
				
				U : function () {
					// Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
					return Math.round(date.getTime()/1000);
				},

				w : function () {
					// Numeric representation of the day of the week
					return date.getDay();
				},
				
				W : function () {
					// Weeknumber, as per ISO specification:
					// http://www.cl.cam.ac.uk/~mgk25/iso-time.html
				
					var DoW = this.N ();
					var DoY = this.z ();

					// If the day is 3 days before New Year's Eve and is Thursday or earlier,
					// it's week 1 of next year.
					var daysToNY = 364 + this.L () - DoY;
					if (daysToNY <= 2 && DoW <= (3 - daysToNY)) {
						return 1;
					}

					// If the day is within 3 days after New Year's Eve and is Friday or later,
					// it belongs to the old year.
					if (DoY <= 2 && DoW >= 5) {
						return new Date (this.Y () - 1, 11, 31).formatDate ("W");
					}
					
					var nyDoW = new Date (this.Y (), 0, 1).getDay ();
					nyDoW = nyDoW != 0 ? nyDoW - 1 : 6;

					if (nyDoW <= 3) { // First day of the year is a Thursday or earlier
						return (1 + Math.floor ((DoY + nyDoW) / 7));
					} else {  // First day of the year is a Friday or later
						return (1 + Math.floor ((DoY - (7 - nyDoW)) / 7));
					}
				},
				
				y : function () {
					// A two-digit representation of a year
					var y = String(this.Y());
					return y.substring(y.length-2,y.length);
				},        
				
				Y : function () {
					// A full numeric representation of a year, 4 digits
			
					// we first check, if getFullYear is supported. if it
					// is, we just use that. ppks code is nice, but wont
					// work with dates outside 1900-2038, or something like that
					if (date.getFullYear) {
						var newDate = new Date("January 1 2001 00:00:00 +0000");
						var x = newDate .getFullYear();
						if (x == 2001) {              
							// i trust the method now
							return date.getFullYear();
						}
					}
					// else, do this:
					// codes thanks to ppk:
					// http://www.xs4all.nl/~ppk/js/introdate.html
					var x = date.getYear();
					var y = x % 100;
					y += (y < 38) ? 2000 : 1900;
					return y;
				},

				
				z : function () {
					// The day of the year, zero indexed! 0 through 366
					var s = "January 1 " + this.Y() + " 00:00:00 GMT" + this.O();
					var t = new Date(s);
					var diff = date.getTime() - t.getTime();
					return Math.floor(diff/1000/60/60/24);
				},

				Z : function () {
					// Timezone offset in seconds
					return (date.getTimezoneOffset () * -60);
				}        
			
			}

			function getSwitch(str) {
				if (switches[str] != undefined) {
					return switches[str]();
				} else {
					return str;
				}
			}

			var formatString = format.split("");
			var i = 0;
			while (i < formatString.length) {
				if (formatString[i] == "%") {
					// this is our way of allowing users to escape stuff
					formatString.splice(i,1);
				} else {
					formatString[i] = getSwitch(formatString[i]);
				}
				i++;
			}
			
			return formatString.join("");

		},
		// replace
		Replace : function(str, find, replace) {
			
			return str.replace(find, replace);

		},
		// String.Format: instead of using {0} use %s
		// i.e. Core.Generic.SprintF('Hi my name is %s', 'Gavin');
		SprintF : function() {
			if (!arguments || arguments.length < 1 || !RegExp)
				return;
			var str = arguments[0];
			var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
			var a = b = [], numSubstitutions = 0, numMatches = 0;
			while (a = re.exec(str)) {
				var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
				var pPrecision = a[5], pType = a[6], rightPart = a[7];
				numMatches++;
				if (pType == '%')
					subst = '%';
				else {
					numSubstitutions++;
					if (numSubstitutions >= arguments.length) {
						alert('Error! Not enough function arguments (' + (arguments.length - 1) 
							+ ', excluding the string)\n'
							+ 'for the number of substitution parameters in string ('
							+ numSubstitutions + ' so far).');
					}
					var param = arguments[numSubstitutions];
					var pad = '';
					if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
					else if (pPad) pad = pPad;
					var justifyRight = true;
					if (pJustify && pJustify === "-") justifyRight = false;
					var minLength = -1;
					if (pMinLength) minLength = parseInt(pMinLength);
					var precision = -1;
					if (pPrecision && pType == 'f')
					precision = parseInt(pPrecision.substring(1));
					var subst = param;
					switch (pType) {
						case 'b':
							subst = parseInt(param).toString(2);
						break;
						case 'c':
							subst = String.fromCharCode(parseInt(param));
						break;
						case 'd':
							subst = parseInt(param) ? parseInt(param) : 0;
						break;
						case 'u':
							subst = Math.abs(param);
						break;
						case 'f':
							subst = (precision > -1)
								? Math.round(parseFloat(param) * Math.pow(10, precision))
									/ Math.pow(10, precision)
								: parseFloat(param);
						break;
						case 'o':
							subst = parseInt(param).toString(8);
						break;
						case 's':
							subst = param;
						break;
						case 'x':
							subst = ('' + parseInt(param).toString(16)).toLowerCase();
						break;
						case 'X':
							subst = ('' + parseInt(param).toString(16)).toUpperCase();
						break;
					}
					var padLeft = minLength - subst.toString().length;
					if (padLeft > 0) {
						var arrTmp = new Array(padLeft+1);
						var padding = arrTmp.join(pad?pad:" ");
					} else {
						var padding = "";
					}
				}
				str = leftpart + padding + subst + rightPart;
			}
			return str;
		}

	};

	// Core.EventHandler namespace
	Core.EventHandler = {

		// Calls a function when the page is ready.
		// This is based on a <div> being placed at the
		// very bottom of the page. Once it is visible within
		// the DOM, the callback will be called.
		OnPageReady : function(callback) {
			if(!Core.DOM.GetEl('jsloader')) {
				setTimeout(function() {
					Core.EventHandler.OnPageReady(callback);
				}, 10);
				return;
			}
			callback();
		},
		// Adds an event handler
		// i.e. Core.EventHandler.Add(Core.DOM.GetEl('button'), 'click', function() {
		//		alert('button clicked');
		// });
		Add : function(element, event, callback) {

			element["e"+event+callback] = callback;

			if (element.addEventListener)
				element.addEventListener(event, function(e) {
					if(!e) e = window.event;
					return element["e"+event+callback].call(element, e);
				}, false);
			else if (element.attachEvent) {
				element["e"+event+callback] = callback;
				element[event+callback] = function() {
					return element["e"+event+callback].call(element, window.event);
				};
				element.attachEvent("on"+event, element[event+callback]);
			}
		},
		// Removes an event handler
		Remove : function(element, event, callback) {

			if ( element.detachEvent ) {
				element.detachEvent( 'on'+event, element["e"+event+callback] );
				element[event+callback] = null;
			} else
				element.removeEventListener( event, element["e"+event+callback], false );
		},
		// Cancels an event from contining
		Cancel : function(e) {
			if(!e) e = window.event;

			try { e.preventDefault(); } catch(e){}
			try { e.cancelBubble = true; } catch(e){}
			try { e.stopPropagation(); } catch(e) {}
			try { e.returnValue = false; } catch(e){}

			return false;
		}

	};

	// Core.Overlay namespace
	Core.Overlay = {

	    Key: null,
	    // events
	    Events: {

	        OnOpen: null,
	        OnClose: null,
	        OnClosing: null,
	        PreventBack: function(e) {
	            return 'You may have unsaved data. If you press OK, you may lose this unsaved data';
	        }

	    },
	    // Create the overlay
	    Create: function(url, width, height, scrollbars, closeOnClick) {

	        //Core.EventHandler.Add(window, 'beforeunload', Core.Overlay.Events.PreventBack);
	        window.onbeforeunload = Core.Overlay.Events.PreventBack;

	        // remove any existing overlay
	        if (Core.DOM.GetEl('Overlay'))
	            Core.DOM.RemoveEl('Overlay');

	        // get the body
	        var body = Core.DOM.GetBody();

	        // construct the overlay
	        var overlay = Core.DOM.CreateEl('DIV', {
	            className: 'Overlay',
	            id: 'Overlay'
	        });
	        if (closeOnClick) {
	            Core.EventHandler.Add(overlay, 'click', function(e) {

	                var close = true;
	                if (typeof (Core.Overlay.Events.OnClosing) == 'function')
	                    close = Core.Overlay.Events.OnClosing();

	                if (close)
	                    Core.Overlay.Close();
	                return Core.EventHandler.Cancel(e);
	            });
	        }

	        // still constructing the overlay
	        var container = Core.DOM.CreateEl('DIV', {
	            className: 'Overlay_Inner',
	            style: {
	                width: width,
	                height: height,
	                marginLeft: '-' + (parseInt(Core.Generic.Replace(width, /[^0-9]+/g, '')) / 2) + 'px',
	                marginTop: '-' + (parseInt(Core.Generic.Replace(height, /[^0-9]+/g, '')) / 2) + 'px'
	            }
	        }, overlay);

	        // still constructing the overlay
	        var iframe = Core.DOM.CreateEl('IFRAME', {
	            id: 'Overlay_Frame',
	            className: 'Overlay_Frame',
	            frameBorder: 0,
	            style: {
	                width: '100%',
	                height: '100%',
	                borderWidth: 0,
	                scrolling: (scrollbars ? 'yes' : 'no')
	            },
	            scrolling: (scrollbars ? 'yes' : 'no'),
	            src: url
	        }, container);

	        // insert the overlay at the top
	        body.insertBefore(overlay, body.firstChild);

	        // hide all select boxes in IE as these appear
	        // above the overlay
	        if (navigator.userAgent.indexOf('MSIE') > -1) {

	            var select = document.getElementsByTagName('SELECT');
	            if (select) {
	                for (var i = 0; i < select.length; i++) {
	                    try {
	                        select[i].setAttribute('oldVisibility', select[i].style.visibility);
	                        select[i].style.visibility = 'hidden';
	                    }
	                    catch (e) { }
	                }
	            }

	        }

	        // if supersleight is available, run it.
	        // this enables alpha transparency support in IE6
	        if (typeof (supersleight) != 'undefined') {
	            supersleight.limitTo(document);
	            supersleight.run();
	        }

	        // creates a KeepAlive ping. Interval: 30 seconds
	        if (typeof ($.get) != 'undefined') {
	            //Core.Overlay.Key = setInterval(function() {
	                // add the epoch time to the request to ensure that
	                // IE doesn't return a cached result.
	            //    $.get('/Ajax/KeepAlive/' + new Date().getTime(), function(res) { });
	            //}, 30000);
	        }

	        // Call OnOpen event if it is hooked
	        if (typeof (Core.Overlay.Events.OnOpen) == 'function')
	            Core.Overlay.Events.OnOpen();
	    },
	    // destroys the overlay
	    Close: function() {

	        // stops the KeepAlive ping
	        //if (Core.Overlay.Key)
	        //    clearInterval(Core.Overlay.Key);

	        //Core.EventHandler.Remove(window, 'beforeunload', Core.Overlay.Events.PreventBack);
	        window.onbeforeunload = null;

	        // restores the select boxes within IE
	        if (navigator.userAgent.indexOf('MSIE') > -1) {

	            var select = document.getElementsByTagName('SELECT');
	            if (select) {
	                for (var i = 0; i < select.length; i++) {
	                    select[i].style.visibility = select[i].getAttribute('oldVisibility');
	                    select[i].removeAttribute('oldVisibility');
	                }
	            }

	        }

	        // removes the overlay
	        if (Core.DOM.GetEl('Overlay'))
	            Core.DOM.RemoveEl('Overlay');

	        // Call OnClose event if it is hooked
	        if (typeof (Core.Overlay.Events.OnClose) == 'function')
	            Core.Overlay.Events.OnClose();
	    },
	    CloseReload: function() {

	        Core.Overlay.Close();
	        window.location.reload();

	    },
	    Destroy: function() {
	        window.onbeforeunload = null;
	    }

	};

	// Core.Form namespace
	Core.Form = {

	    // toggles AutoComplete on inputs.
	    AutoComplete: function(enabled, parent) {
	        var form = Core.DOM.GetForm();
	        if (form) {
	            if (enabled)
	                form.removeAttribute('autocomplete');
	            else
	                form.setAttribute('autocomplete', 'off');
	        }
	        if (!parent) parent = document;
	        var input = parent.getElementsByTagName('INPUT');
	        if (input) {
	            for (var i = 0; i < input.length; i++) {
	                if (input[i].type.toLowerCase() == 'text') {
	                    if (enabled)
	                        input[i].removeAttribute('autocomplete');
	                    else
	                        input[i].setAttribute('autocomplete', 'off');
	                }
	            }
	        }
	    },
	    // toggles edit mode. 
	    // Textboxes, Textareas, buttons are set to readonly
	    // Select/Dropdowns are replaced with a span.
	    Toggle: function(editMode) {

	        window.onbeforeunload = null;
	        if (editMode) {
	            window.onbeforeunload = function() {
	                return 'You may have unsaved data. If you press OK, you may lose this unsaved data';
	            };
	        }

	        var Form_Input = Core.DOM.GetEl('.Form_Input');
	        if (Form_Input) {
	            for (var i = 0; i < Form_Input.length; i++) {
	                Form_Input[i].removeAttribute('readOnly');
	                Form_Input[i].readOnly = !editMode;
	            }
	        }

	        var Form_InputWithButton = Core.DOM.GetEl('.Form_InputWithButton');
	        if (Form_InputWithButton) {
	            for (var i = 0; i < Form_InputWithButton.length; i++) {
	                Form_InputWithButton[i].removeAttribute('readOnly');
	                Form_InputWithButton[i].readOnly = !editMode;
	            }
	        }

	        var Form_Textarea = Core.DOM.GetEl('.Form_Textarea');
	        if (Form_Textarea) {
	            for (var i = 0; i < Form_Textarea.length; i++) {
	                Form_Textarea[i].removeAttribute('readOnly');
	                Form_Textarea[i].readOnly = !editMode;
	            }
	        }

	        var Form_PostCode = Core.DOM.GetEl('.Form_PostCode');
	        if (Form_PostCode) {
	            for (var i = 0; i < Form_PostCode.length; i++) {
	                Form_PostCode[i].removeAttribute('readOnly');
	                Form_PostCode[i].readOnly = !editMode;
	            }
	        }

	        var Form_Short_DropDown = Core.DOM.GetEl('.Form_Short_DropDown');
	        if (Form_Short_DropDown) {
	            for (var i = 0; i < Form_Short_DropDown.length; i++) {
	                if (!editMode && Form_Short_DropDown[i].id.indexOf('READONLY') == -1) {
	                    var span = Core.DOM.CreateEl('SPAN', {
	                        id: Form_Short_DropDown[i].id + '_READONLY',
	                        className: 'Form_Short_DropDown'
	                    });
	                    // Confirm Form_Short_DropDown has some options before trying to find selected
	                    if (Form_Short_DropDown[i].length > 0) {
	                        var val = Form_Short_DropDown[i].options[Form_Short_DropDown[i].selectedIndex].text;
	                    }
	                    else {
	                        var val = "";
	                    }

	                    if (val == '')
	                        span.innerHTML = '&nbsp;';
	                    else
	                        span.appendChild(document.createTextNode(val));

	                    Form_Short_DropDown[i].parentNode.insertBefore(span, Form_Short_DropDown[i]);
	                    Form_Short_DropDown[i].parentNode.removeChild(Form_Short_DropDown[i]);
	                }
	            }
	        }

	        var Form_Long_DropDown = Core.DOM.GetEl('.Form_Long_DropDown');
	        if (Form_Long_DropDown) {
	            for (var i = 0; i < Form_Long_DropDown.length; i++) {

	                // Not in edit mode and dropdown id does not contain READONLY
	                if (!editMode && Form_Long_DropDown[i].id.indexOf('READONLY') == -1) {

	                    var span = Core.DOM.CreateEl('SPAN', {
	                        id: Form_Long_DropDown[i].id + '_READONLY',
	                        className: 'Form_Long_DropDown'
	                    });

	                    // Confirm Form_Long_DropDown has some options before trying to find selected
	                    if (Form_Long_DropDown[i].length > 0) {
	                        var val = Form_Long_DropDown[i].options[Form_Long_DropDown[i].selectedIndex].text;
	                    }
	                    else {
	                        var val = "";
	                    }

	                    if (val == '')
	                        span.innerHTML = '&nbsp;';
	                    else
	                        span.appendChild(document.createTextNode(val));

	                    Form_Long_DropDown[i].parentNode.insertBefore(span, Form_Long_DropDown[i]);
	                    Form_Long_DropDown[i].parentNode.removeChild(Form_Long_DropDown[i]);
	                }
	            }
	        }

	        var Form_Long_DropDown_2 = Core.DOM.GetEl('.Form_Long_DropDown_2');
	        if (Form_Long_DropDown_2) {
	            for (var i = 0; i < Form_Long_DropDown_2.length; i++) {
	                if (!editMode && Form_Long_DropDown_2[i].id.indexOf('READONLY') == -1) {
	                    var span = Core.DOM.CreateEl('SPAN', {
	                        id: Form_Long_DropDown_2[i].id + '_READONLY',
	                        className: 'Form_Long_DropDown_2'
	                    });

	                    // Confirm Form_Long_DropDown_2 has some options before trying to find selected
	                    if (Form_Long_DropDown_2[i].length > 0) {
	                        var val = Form_Long_DropDown_2[i].options[Form_Long_DropDown_2[i].selectedIndex].text;
	                    }
	                    else {
	                        var val = "";
	                    }

	                    if (val == '')
	                        span.innerHTML = '&nbsp;';
	                    else
	                        span.appendChild(document.createTextNode(val));

	                    Form_Long_DropDown_2[i].parentNode.insertBefore(span, Form_Long_DropDown_2[i]);
	                    Form_Long_DropDown_2[i].parentNode.removeChild(Form_Long_DropDown_2[i]);
	                }
	            }
	        }

	        var Form_DropDown = Core.DOM.GetEl('.Form_DropDown');
	        if (Form_DropDown) {
	            for (var i = 0; i < Form_DropDown.length; i++) {
	                if (!editMode && Form_DropDown[i].id.indexOf('READONLY') == -1) {
	                    var span = Core.DOM.CreateEl('SPAN', {
	                        id: Form_DropDown[i].id + '_READONLY',
	                        className: 'Form_DropDown'
	                    });

	                    // Confirm Form_DropDown has some options before trying to find selected
	                    if (Form_DropDown[i].length > 0) {
	                        var val = Form_DropDown[i].options[Form_DropDown[i].selectedIndex].text;
	                    }
	                    else {
	                        var val = "";
	                    }

	                    if (val == '')
	                        span.innerHTML = '&nbsp;';
	                    else
	                        span.appendChild(document.createTextNode(val));

	                    Form_DropDown[i].parentNode.insertBefore(span, Form_DropDown[i]);
	                    Form_DropDown[i].parentNode.removeChild(Form_DropDown[i]);
	                }
	            }
	        }

	        var Form_Upload = Core.DOM.GetEl('.Form_Upload');
	        if (Form_Upload) {
	            for (var i = 0; i < Form_Upload.length; i++) {
	                Form_Upload[i].removeAttribute('disabled');
	                Form_Upload[i].disabled = !editMode;
	            }
	        }

	        var Form_InputButton = Core.DOM.GetEl('.Form_InputButton');
	        if (Form_InputButton) {
	            for (var i = 0; i < Form_InputButton.length; i++) {
	                Form_InputButton[i].removeAttribute('disabled');
	                Form_InputButton[i].disabled = !editMode;
	            }
	        }

	        var Form_Long_Input = Core.DOM.GetEl('.Form_Long_Input');
	        if (Form_Long_Input) {
	            for (var i = 0; i < Form_Long_Input.length; i++) {
	                Form_Long_Input[i].removeAttribute('readOnly');
	                Form_Long_Input[i].readOnly = !editMode;
	            }
	        }

	        var Form_DateInput = Core.DOM.GetEl('.Form_DateInput');
	        if (Form_DateInput) {
	            for (var i = 0; i < Form_DateInput.length; i++) {
	                Form_DateInput[i].removeAttribute('readOnly');
	                Form_DateInput[i].readOnly = !editMode;
	            }
	        }

	        var Html_Checkbox = Core.DOM.GetEl('.Html_Checkbox');
	        if (Html_Checkbox) {
	            for (var i = 0; i < Html_Checkbox.length; i++) {
	                var checkbox = (Html_Checkbox[i].nodeName == 'SPAN' ? Html_Checkbox[i].getElementsByTagName('INPUT')[0] : Html_Checkbox[i]);
	                checkbox.onclick = function(e) {
	                    if (!editMode)
	                        return Core.EventHandler.Cancel(e);
	                };
	            }
	        }

	        var Form_Checkbox = Core.DOM.GetEl('.Form_Checkbox');
	        if (Form_Checkbox) {
	            for (var i = 0; i < Form_Checkbox.length; i++) {
	                var checkbox = (Form_Checkbox[i].nodeName == 'SPAN' ? Form_Checkbox[i].getElementsByTagName('INPUT')[0] : Form_Checkbox[i]);
	                checkbox.onclick = function(e) {
	                    if (!editMode)
	                        return Core.EventHandler.Cancel(e);
	                };
	            }
	        }

	        var Form_Checkbox_2 = Core.DOM.GetEl('.Form_Checkbox_2');
	        if (Form_Checkbox_2) {
	            for (var i = 0; i < Form_Checkbox_2.length; i++) {
	                var checkbox = (Form_Checkbox_2[i].nodeName == 'SPAN' ? Form_Checkbox_2[i].getElementsByTagName('INPUT')[0] : Form_Checkbox_2[i]);
	                if (typeof (checkbox.onclick) != 'function') {
	                    checkbox.onclick = function(e) {
	                        if (!editMode)
	                            return Core.EventHandler.Cancel(e);
	                    };
	                }
	            }
	        }

	    }

	};

window['SetupTips'] = function() {

	if(typeof($) == 'undefined' || typeof($.fn.qtip) == 'undefined')
		return false;

	var qtips = $.fn.qtip.interfaces,
	i = qtips.length; while(i--) qtips[i].destroy();

	$('a.SiteTip').qtip({
		style : {
			/*width : 200,*/
			name : 'cream',
			color: 'black'
		},
		adjust : {
			screen : true
		},
		hide : { fixed : true }
	});
	$('a.SiteTip2').qtip({
		style : {
			/*width : 200,*/
			name : 'cream',
			color: 'black'
		},
		adjust : {
			screen : true
		},
		position : {
			corner : {
				target : 'bottomMiddle',
				tooltip : 'topMiddle'
			}
		},
		hide : { fixed : true }
	});
	$('a.SiteTip3').qtip({
		style : {
			/*width : 200,*/
			name : 'cream',
			color: 'black'
		},
		adjust : {
			screen : true
		},
		position : {
			corner : {
				target : 'topMiddle',
				tooltip : 'bottomLeft'
			}
		},
		hide : { fixed : true }
	});
	$('a.SiteTip4').qtip({
		style : {
			/*width : 200,*/
			name : 'cream',
			color: 'black'
		},
		adjust : {
			screen : true
		},
		position : {
			corner : {
				target : 'bottomMiddle',
				tooltip : 'topMiddle'
			}
		},
		hide : { fixed : true }
	});
	$('a.SiteTip5').qtip({
		style : {
			/*width : 200,*/
			name : 'cream',
			color: 'black'
		},
		adjust : {
			screen : true
		},
		position : {
			corner : {
				target : 'rightMiddle',
				tooltip : 'leftMiddle'
			}
		},
		hide : { fixed : true }
	});
	$('a.SiteTip_Wizard').qtip({
		style : {
			/*width : 200,*/
			name : 'cream',
			color: 'black'
		},
		adjust : {
			screen : true
		},
		position : {
			corner : {
				target : 'leftMiddle',
				tooltip : 'rightMiddle'
			}
		},
		hide : { fixed : true }
	});
	$('select.SiteTip_Dropdown').qtip({
		style : {
			/*width : 200,*/
			name : 'cream',
			color: 'black'
		},
		adjust : {
			screen : true
		},
		position : {
			corner : {
				target : 'bottomMiddle',
				tooltip : 'topMiddle'
			}
		},
		hide : { event : 'unfocus', fixed : true }
	});
	$('select.SiteTip_Dropdown2').qtip({
		style : {
			/*width : 200,*/
			name : 'cream',
			color: 'black',
			tip : 'leftMiddle'
		},
		adjust : {
			screen : true
		},
		position : {
			corner : {
				target : 'rightMiddle',
				tooltip : 'leftMiddle'
			}
		},
		hide : { fixed : true, event : 'unfocus' }
	});
	$('input.SiteTip ').qtip({
		style : {
			width : 200,
			name : 'cream',
			color: 'black',
			tip : 'leftMiddle'
		},
		show : { when : 'focus' },
		hide : { when : 'blur', fixed : true },
		position : {
			corner : {
				target : 'rightMiddle',
				tooltip : 'leftMiddle'
			}
		},
		adjust : {
			screen : true
		}
	});

};

// Disable autocomplete
Core.EventHandler.OnPageReady(function() {
	Core.Form.AutoComplete(false);
	
	window['SetupTips']();

});

// Store Core within the DOM so we can access it's instance from
// overlay/popups
window['Core'] = Core;
