
var siteid = 'uk';

var mobileDetect = {
	init: function() {
		this.userAgent = navigator.userAgent.toLowerCase();
	},
	isIphone: function() {
		this.isBrowser = (this.userAgent.indexOf(this.mobileAgent["iphone"].productFamily) == -1) ? false : true;
		return this.isBrowser;
	},
	isIpod: function() {
		this.isBrowser = (this.userAgent.indexOf(this.mobileAgent["ipod"].productFamily) == -1) ? false : true;
		return this.isBrowser;
	},
	isBlackberry: function() {
		this.isBrowser = (this.userAgent.indexOf(this.mobileAgent["blackberry"].productFamily) == -1) ? false : true;
		return this.isBrowser;
	},
	isAndroid: function() {
		this.isBrowser = (this.userAgent.indexOf(this.mobileAgent["android"].productFamily) == -1) ? false : true;
		return this.isBrowser;
	},
	isIemobile: function() {
		this.isBrowser = (this.userAgent.indexOf(this.mobileAgent["iemobile"].productFamily) == -1) ? false : true;
		return this.isBrowser;
	},
	isPalmPre: function() {
		this.isBrowser = (this.userAgent.indexOf(this.mobileAgent["palm pre"].productFamily) == -1) ? false : true;
		return this.isBrowser;
	},
	getMobileAgent: function() {
		var strMobile;
		for (var property in this.mobileAgent) {
			if (this.userAgent.indexOf(this.mobileAgent[property].productFamily) != -1) {
				strMobile = property;
				if (this.mobileAgent[property].model) {
					var tempProp = property;
					for (var property1 in this.mobileAgent[tempProp].model) {
						for (var i = 0; i < this.mobileAgent[tempProp].model[property1].length; i++) {
							if (this.userAgent.indexOf(this.mobileAgent[tempProp].model[property1][i]) != -1) {
								strMobile += ", " + property1;
							}
						}
					}
				}
				return strMobile;
			}
		}
		return null;
	},
	mobileAgent: {
		"iphone": {
			"productFamily": "iphone"
		},
		"ipod": {
			"productFamily": "ipod"
		},
		"blackberry": {
			"productFamily": "blackberry",
			"model": {
				"tour": ["blackberry9630"],
				"storm": ["blackberry9500", "blackberry9530"],
				"bold": ["blackberry9000", "blackberry9100"],
				"88XX": ["blackberry8800", "blackberry8820", "blackberry8830"],
				"electron": ["blackberry8700", "blackberry8700c", "blackberry8700f", "blackberry8700g", "blackberry8700r", "blackberry8700v", "blackberry8703", "blackberry8703e", "blackberry8705g", "blackberry8707", "blackberry8707v"],
				"curve": ["blackberry8300", "blackberry8310", "blackberry8320", "blackberry8330", "blackberry8350i", "blackberry8900"],
				"pearl flip": ["blackberry8220", "blackberry8230"],
				"pearl": ["blackberry8100", "blackberry8110", "blackberry8120", "blackberry8130"]
			}
		},
		"palm pre": {
			"productFamily": "pre/1.0"
		},
		"android": {
			"productFamily": "android"
		},
		"iemobile": {
			"productFamily": "iemobile"
		}
	}
};

mobileDetect.init();

if (siteid != 'aumeta') {
    var qs = new Querystring();
    var redir = qs.get('redir');
    if (redir != '0') {
        if (mobileDetect.isIphone() || mobileDetect.isIpod() || mobileDetect.isAndroid() || mobileDetect.isPalmPre()) {
            if (document.referrer == "")
            { window.location.href = "mobile/Index.aspx"; }
        } else if (mobileDetect.isBlackberry() || mobileDetect.isIemobile() || /midp/.test(mobileDetect.getMobileAgent())) {
            window.location.href = "http://wap.forex.com";
        }
    } 
}function currencyPairGuidedTourScript()
{
	var step1 = new GuidedTourStep('step1', 670, 285, 'left');
	var step2 = new GuidedTourStep('step2', 345, 585, 'left');
	var step3 = new GuidedTourStep('step3', 420, 895, 'right');
	var dashboardTour = new GuidedTour([step1, step2, step3]);			
}
function initDropdowns() {
	window.addEvent('domready', mainDropNav.init);
}
function StartGuidedTour() { }
function dashboardCarouselScript (){
    var dashboardCarousel = new Carousel('dashboard_interstitial_carousel');
}
function newToForex() {
	var newToForexToggle = new ContentToggle('new_to_forex_toggle');
}
function homepageCarousel() {
	var homepageCarousel = new Carousel('homepage_carousel'); 
}
function alertBox() {					
	$('alert_box_close').addEvent('click', function() {								
		$('alert_box_container').setStyle('display', 'none');		
	});		
}
function mediaPlayerScript() {
	var flashvars = {};
	flashvars.w = "303";
	flashvars.h = "227";
	flashvars.fn = "flv/cnbc-08-06-04-hi.flv";
	var params = {};
	var attributes = {};
	swfobject.embedSWF("resources/swf/MediaPlayer.swf", "video_player", "303", "227", "9.0.0", "/resources/swf/expressInstall.swf", flashvars, params, attributes);	
}
function formatInteger(v) 
{
    var re = new RegExp('(\\d{1,3})(?=(?:\\d{3})+(\\.|$))','g');
    return v.toString().replace(re,'$1,');
}
function displayPhoneNumber() {
	var countrySelect = $('country');
	var newNumber = countrySelect.options[countrySelect.selectedIndex].value;
	$('phone_number_display').set('html', newNumber);
}
function showCallbackRequest () {
    resetCallbackform();
    popLayer.popLayerFade = 'ZoomFadeCallback';
    popLayer.popLayerContent = 'ZoomShadowCallback';
    popLayer.shim = 'ZoomShimCallback';
    popLayer.shimYOffset = 30;
    popLayer.shimXOffset = 23;
    popLayer.show();
}
function resetCallbackform() {
    Ext.get('sales_call_back').dom.style.display = 'block';
    Ext.get('divSalesCallBackMsg').dom.style.display = 'none';
}
function showCallbackConfirmation ()
{ 
    if (popLayer != null)
    {
        popLayer.hide();
    }
    popLayer.popLayerFade = 'ZoomFadeCallbackConfirmation';
    popLayer.popLayerContent = 'ZoomShadowCallbackConfirmation';
    popLayer.shim = 'ZoomShimCallbackConfirmation';
    popLayer.shimYOffset = 30;
    popLayer.shimXOffset = 23;
    popLayer.show(); 
 }
function showNewsletter()
{ 
    popLayer.popLayerFade = 'ZoomFadeNewsletter';
    popLayer.popLayerContent = 'ZoomShadowNewsletter';
    popLayer.shim = 'ZoomShimNewsletter';
    popLayer.shimYOffset = 30;
    popLayer.shimXOffset = 23;
    
    var emailFieldID = document.getElementById('txtEmailField');
    var confirmEmailFieldID = document.getElementById('txtConfirmEmailField');
    var emailField = document.getElementById(emailFieldID.value);
    var confirmEmailField = document.getElementById(confirmEmailFieldID.value);       
    var enteredEmail = document.getElementById("email");   
    var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if (pattern.test(enteredEmail.value)){emailField.value = enteredEmail.value;}
    popLayer.show();
}
function showEuHostingRequestForm() {
    popLayer.popLayerFade = 'ZoomFadeNewsletter';
    popLayer.popLayerContent = 'ZoomShadowNewsletter';
    popLayer.shim = 'ZoomShimNewsletter';
    popLayer.shimYOffset = 30;
    popLayer.shimXOffset = 23;

    var emailFieldID = document.getElementById('txtEmailField');
    var emailField = document.getElementById(emailFieldID.value);
    var enteredEmail = document.getElementById("email");
    var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if (pattern.test(enteredEmail.value)) { emailField.value = enteredEmail.value; }
    
    popLayer.show();
}
function showReferAFriend() {
    resetReferFriendForm()
    popLayer.popLayerFade = 'ZoomFadeReferAFriend';
    popLayer.popLayerContent = 'ZoomShadowReferAFriend';
    popLayer.shim = 'ZoomShimReferAFriend';
    popLayer.shimYOffset = 30;
    popLayer.shimXOffset = 23;
    popLayer.show();
}
function resetReferFriendForm() {
    Ext.get('refer_pop').dom.style.display = 'block';
    Ext.get('divError').dom.style.display = 'none';
    Ext.get('div_Refer_Friend_Confirm').dom.style.display = 'none';
}
function showISInfoForm() {
	popLayer.popLayerFade = 'ZoomFadeISInfoForm';
	popLayer.popLayerContent = 'ZoomShadowISInfoForm';
	popLayer.shim = 'ZoomShimISInfoForm';
	popLayer.shimYOffset = 30;
	popLayer.shimXOffset = 23;
	popLayer.show();
}
function showOnlineSecurity()
{ 
    popLayer.popLayerFade = 'ZoomFadeOnlineSecurity';
    popLayer.popLayerContent = 'ZoomShadowOnlineSecurity';
    popLayer.shim = 'ZoomShimOnlineSecurity';
    popLayer.shimYOffset = 30;
    popLayer.shimXOffset = 23;
    popLayer.show();
}
function showToolsPopup()
{ 
    popLayer.popLayerFade = 'ZoomFadeToolsPopup';
    popLayer.popLayerContent = 'ZoomShadowToolsPopup';
    popLayer.shim = 'ZoomShimToolsPopup';
    popLayer.shimYOffset = 30;
    popLayer.shimXOffset = 23;
    popLayer.show();
}
function openWin(){window.open("https://secure.efxnow.com/NewOLS_FRXC_EN/agreement.aspx","popWin","status=no,toolbar=no,directories=no,menubar=no,location=no,resizable=yes,scrollbars=yes,left=0,top=0,width=568, height=500");}
function setModelPopUpCenter(inObject)
{
    var currentX = function()
    {
        if (self.pageYOffset)
            return self.pageXOffset;
        else if (document.documentElement && document.documentElement.scrollTop)
            return document.documentElement.scrollLeft;
        else if (document.body)
            return document.body.scrollLeft;
    }
    var currentY = function()
    {
        if (self.pageYOffset)
            return self.pageYOffset;
        else if (document.documentElement && document.documentElement.scrollTop)
            return document.documentElement.scrollTop;
        else if (document.body)
            return document.body.scrollTop;
    }
    var documentHeight = function()
    {
        if (self.innerHeight)
            return self.innerHeight;
        else if (document.documentElement && document.documentElement.clientHeight)
            return document.documentElement.clientHeight;
        else if (document.body)
            return document.body.clientHeight;
    }
    var documentWidth = function()
    {
     if (self.innerHeight)return self.innerWidth;
     else if (document.documentElement && document.documentElement.clientHeight)return document.documentElement.clientWidth;
     else if (document.body)return document.body.clientWidth;
    }
    var x = Math.round(documentWidth()/2) - Math.round(inObject.getWidth()/2)
    var y = currentY() + Math.round(documentHeight()/2) - Math.round(inObject.getHeight()/2);
    inObject.setLeftTop(x,y);
}
function hideLoginLink() {
	$("homepage_feature") != null && $("homepage_feature").getElements(".login_message").setStyle("display", "none")
}
function VideoControl (videofile, videoid) {
window.addEvent('domready', function(){
changeVideo(videofile, videoid);	
$$('#video_list_toggle .toggle_content_item').setStyles({
	'display' : 'block',
	'visibility' : 'hidden'
});

var bar1 = $('video_scrollbar_1');
var grip1 = $('video_scroll_grip_1');
var videoList1 = $('video_listing_1');
var listHeight1 = videoList1.getSize().y;
listHeight1 = listHeight1 - 232;

var Scrollbar1 = new Slider(bar1, grip1, {
	steps: listHeight1,	// There are 35 steps
	range: [0],	// Minimum value is 8
	mode: 'vertical',
	wheel: true,
	onChange: function(value){
		// Everytime the value changes, we change the font of an element
		videoList1.setStyle('margin-top', (value*-1));
	}
}).set(0);
	
var bar2 = $('video_scrollbar_2');
var grip2 = $('video_scroll_grip_2');
var videoList2 = $('video_listing_2');
var listHeight2 = videoList2.getSize().y;
listHeight2 = listHeight2 - 232;

var Scrollbar2 = new Slider(bar2, grip2, {
	steps: listHeight2,	// There are 35 steps
	range: [0],	// Minimum value is 8
	mode: 'vertical',
	wheel: true,
	onChange: function(value){
		videoList2.setStyle('margin-top', (value*-1));
	}
}).set(0);

$$('#video_list_toggle .toggle_content_item').setStyles({
	'display' : 'none',
	'visibility' : ''
});

VideoListToggle = new ContentToggle('video_list_toggle', 'beginner');
});
}
function numbersFilter(evt, setFocus){
    var charCode = (evt.which) ? evt.which : event.keyCode
	evt = (evt.target) ? evt.target : evt.srcElement;
    if(setFocus && evt.maxLength==evt.value.length)
    {
        if (charCode == 8 || (charCode>47 && charCode<58))
            setFocus.focus();
        return false;
    }
    if (charCode == 8 || (charCode>47 && charCode<58))
        return true;
    return false;
}
function isFlashAvailable(movieName) {
    var result = null;
    if (window.document[movieName])
        result = window.document[movieName];
    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        if (document.embeds && document.embeds[movieName])
            result = document.embeds[movieName];
    }
    else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
        result = document.getElementById(movieName);
    return (result == null) ? false : true;
}//MooTools, <http://mootools.net>, My Object Oriented (JavaScript) Tools. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

var MooTools={version:"1.2.0",build:""};var Native=function(J){J=J||{};var F=J.afterImplement||function(){};var G=J.generics;G=(G!==false);var H=J.legacy;
var E=J.initialize;var B=J.protect;var A=J.name;var C=E||H;C.constructor=Native;C.$family={name:"native"};if(H&&E){C.prototype=H.prototype;}C.prototype.constructor=C;
if(A){var D=A.toLowerCase();C.prototype.$family={name:D};Native.typize(C,D);}var I=function(M,K,N,L){if(!B||L||!M.prototype[K]){M.prototype[K]=N;}if(G){Native.genericize(M,K,B);
}F.call(M,K,N);return M;};C.implement=function(L,K,N){if(typeof L=="string"){return I(this,L,K,N);}for(var M in L){I(this,M,L[M],K);}return this;};C.alias=function(M,K,N){if(typeof M=="string"){M=this.prototype[M];
if(M){I(this,K,M,N);}}else{for(var L in M){this.alias(L,M[L],K);}}return this;};return C;};Native.implement=function(D,C){for(var B=0,A=D.length;B<A;B++){D[B].implement(C);
}};Native.genericize=function(B,C,A){if((!A||!B[C])&&typeof B.prototype[C]=="function"){B[C]=function(){var D=Array.prototype.slice.call(arguments);return B.prototype[C].apply(D.shift(),D);
};}};Native.typize=function(A,B){if(!A.type){A.type=function(C){return($type(C)===B);};}};Native.alias=function(E,B,A,F){for(var D=0,C=E.length;D<C;D++){E[D].alias(B,A,F);
}};(function(B){for(var A in B){Native.typize(B[A],A);}})({"boolean":Boolean,"native":Native,object:Object});(function(B){for(var A in B){new Native({name:A,initialize:B[A],protect:true});
}})({String:String,Function:Function,Number:Number,Array:Array,RegExp:RegExp,Date:Date});(function(B,A){for(var C=A.length;C--;C){Native.genericize(B,A[C],true);
}return arguments.callee;})(Array,["pop","push","reverse","shift","sort","splice","unshift","concat","join","slice","toString","valueOf","indexOf","lastIndexOf"])(String,["charAt","charCodeAt","concat","indexOf","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","valueOf"]);
function $chk(A){return !!(A||A===0);}function $clear(A){clearTimeout(A);clearInterval(A);return null;}function $defined(A){return(A!=undefined);}function $empty(){}function $arguments(A){return function(){return arguments[A];
};}function $lambda(A){return(typeof A=="function")?A:function(){return A;};}function $extend(C,A){for(var B in (A||{})){C[B]=A[B];}return C;}function $unlink(C){var B;
switch($type(C)){case"object":B={};for(var E in C){B[E]=$unlink(C[E]);}break;case"hash":B=$unlink(C.getClean());break;case"array":B=[];for(var D=0,A=C.length;
D<A;D++){B[D]=$unlink(C[D]);}break;default:return C;}return B;}function $merge(){var E={};for(var D=0,A=arguments.length;D<A;D++){var B=arguments[D];if($type(B)!="object"){continue;
}for(var C in B){var G=B[C],F=E[C];E[C]=(F&&$type(G)=="object"&&$type(F)=="object")?$merge(F,G):$unlink(G);}}return E;}function $pick(){for(var B=0,A=arguments.length;
B<A;B++){if(arguments[B]!=undefined){return arguments[B];}}return null;}function $random(B,A){return Math.floor(Math.random()*(A-B+1)+B);}function $splat(B){var A=$type(B);
return(A)?((A!="array"&&A!="arguments")?[B]:B):[];}var $time=Date.now||function(){return new Date().getTime();};function $try(){for(var B=0,A=arguments.length;
B<A;B++){try{return arguments[B]();}catch(C){}}return null;}function $type(A){if(A==undefined){return false;}if(A.$family){return(A.$family.name=="number"&&!isFinite(A))?false:A.$family.name;
}if(A.nodeName){switch(A.nodeType){case 1:return"element";case 3:return(/\S/).test(A.nodeValue)?"textnode":"whitespace";}}else{if(typeof A.length=="number"){if(A.callee){return"arguments";
}else{if(A.item){return"collection";}}}}return typeof A;}var Hash=new Native({name:"Hash",initialize:function(A){if($type(A)=="hash"){A=$unlink(A.getClean());
}for(var B in A){this[B]=A[B];}return this;}});Hash.implement({getLength:function(){var B=0;for(var A in this){if(this.hasOwnProperty(A)){B++;}}return B;
},forEach:function(B,C){for(var A in this){if(this.hasOwnProperty(A)){B.call(C,this[A],A,this);}}},getClean:function(){var B={};for(var A in this){if(this.hasOwnProperty(A)){B[A]=this[A];
}}return B;}});Hash.alias("forEach","each");function $H(A){return new Hash(A);}Array.implement({forEach:function(C,D){for(var B=0,A=this.length;B<A;B++){C.call(D,this[B],B,this);
}}});Array.alias("forEach","each");function $A(C){if(C.item){var D=[];for(var B=0,A=C.length;B<A;B++){D[B]=C[B];}return D;}return Array.prototype.slice.call(C);
}function $each(C,B,D){var A=$type(C);((A=="arguments"||A=="collection"||A=="array")?Array:Hash).each(C,B,D);}var Browser=new Hash({Engine:{name:"unknown",version:""},Platform:{name:(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase()},Features:{xpath:!!(document.evaluate),air:!!(window.runtime)},Plugins:{}});
if(window.opera){Browser.Engine={name:"presto",version:(document.getElementsByClassName)?950:925};}else{if(window.ActiveXObject){Browser.Engine={name:"trident",version:(window.XMLHttpRequest)?5:4};
}else{if(!navigator.taintEnabled){Browser.Engine={name:"webkit",version:(Browser.Features.xpath)?420:419};}else{if(document.getBoxObjectFor!=null){Browser.Engine={name:"gecko",version:(document.getElementsByClassName)?19:18};
}}}}Browser.Engine[Browser.Engine.name]=Browser.Engine[Browser.Engine.name+Browser.Engine.version]=true;if(window.orientation!=undefined){Browser.Platform.name="ipod";
}Browser.Platform[Browser.Platform.name]=true;Browser.Request=function(){return $try(function(){return new XMLHttpRequest();},function(){return new ActiveXObject("MSXML2.XMLHTTP");
});};Browser.Features.xhr=!!(Browser.Request());Browser.Plugins.Flash=(function(){var A=($try(function(){return navigator.plugins["Shockwave Flash"].description;
},function(){return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version");})||"0 r0").match(/\d+/g);return{version:parseInt(A[0]||0+"."+A[1]||0),build:parseInt(A[2]||0)};
})();function $exec(B){if(!B){return B;}if(window.execScript){window.execScript(B);}else{var A=document.createElement("script");A.setAttribute("type","text/javascript");
A.text=B;document.head.appendChild(A);document.head.removeChild(A);}return B;}Native.UID=1;var $uid=(Browser.Engine.trident)?function(A){return(A.uid||(A.uid=[Native.UID++]))[0];
}:function(A){return A.uid||(A.uid=Native.UID++);};var Window=new Native({name:"Window",legacy:(Browser.Engine.trident)?null:window.Window,initialize:function(A){$uid(A);
if(!A.Element){A.Element=$empty;if(Browser.Engine.webkit){A.document.createElement("iframe");}A.Element.prototype=(Browser.Engine.webkit)?window["[[DOMElement.prototype]]"]:{};
}return $extend(A,Window.Prototype);},afterImplement:function(B,A){window[B]=Window.Prototype[B]=A;}});Window.Prototype={$family:{name:"window"}};new Window(window);
var Document=new Native({name:"Document",legacy:(Browser.Engine.trident)?null:window.Document,initialize:function(A){$uid(A);A.head=A.getElementsByTagName("head")[0];
A.html=A.getElementsByTagName("html")[0];A.window=A.defaultView||A.parentWindow;if(Browser.Engine.trident4){$try(function(){A.execCommand("BackgroundImageCache",false,true);
});}return $extend(A,Document.Prototype);},afterImplement:function(B,A){document[B]=Document.Prototype[B]=A;}});Document.Prototype={$family:{name:"document"}};
new Document(document);Array.implement({every:function(C,D){for(var B=0,A=this.length;B<A;B++){if(!C.call(D,this[B],B,this)){return false;}}return true;
},filter:function(D,E){var C=[];for(var B=0,A=this.length;B<A;B++){if(D.call(E,this[B],B,this)){C.push(this[B]);}}return C;},clean:function(){return this.filter($defined);
},indexOf:function(C,D){var A=this.length;for(var B=(D<0)?Math.max(0,A+D):D||0;B<A;B++){if(this[B]===C){return B;}}return -1;},map:function(D,E){var C=[];
for(var B=0,A=this.length;B<A;B++){C[B]=D.call(E,this[B],B,this);}return C;},some:function(C,D){for(var B=0,A=this.length;B<A;B++){if(C.call(D,this[B],B,this)){return true;
}}return false;},associate:function(C){var D={},B=Math.min(this.length,C.length);for(var A=0;A<B;A++){D[C[A]]=this[A];}return D;},link:function(C){var A={};
for(var E=0,B=this.length;E<B;E++){for(var D in C){if(C[D](this[E])){A[D]=this[E];delete C[D];break;}}}return A;},contains:function(A,B){return this.indexOf(A,B)!=-1;
},extend:function(C){for(var B=0,A=C.length;B<A;B++){this.push(C[B]);}return this;},getLast:function(){return(this.length)?this[this.length-1]:null;},getRandom:function(){return(this.length)?this[$random(0,this.length-1)]:null;
},include:function(A){if(!this.contains(A)){this.push(A);}return this;},combine:function(C){for(var B=0,A=C.length;B<A;B++){this.include(C[B]);}return this;
},erase:function(B){for(var A=this.length;A--;A){if(this[A]===B){this.splice(A,1);}}return this;},empty:function(){this.length=0;return this;},flatten:function(){var D=[];
for(var B=0,A=this.length;B<A;B++){var C=$type(this[B]);if(!C){continue;}D=D.concat((C=="array"||C=="collection"||C=="arguments")?Array.flatten(this[B]):this[B]);
}return D;},hexToRgb:function(B){if(this.length!=3){return null;}var A=this.map(function(C){if(C.length==1){C+=C;}return C.toInt(16);});return(B)?A:"rgb("+A+")";
},rgbToHex:function(D){if(this.length<3){return null;}if(this.length==4&&this[3]==0&&!D){return"transparent";}var B=[];for(var A=0;A<3;A++){var C=(this[A]-0).toString(16);
B.push((C.length==1)?"0"+C:C);}return(D)?B:"#"+B.join("");}});Function.implement({extend:function(A){for(var B in A){this[B]=A[B];}return this;},create:function(B){var A=this;
B=B||{};return function(D){var C=B.arguments;C=(C!=undefined)?$splat(C):Array.slice(arguments,(B.event)?1:0);if(B.event){C=[D||window.event].extend(C);
}var E=function(){return A.apply(B.bind||null,C);};if(B.delay){return setTimeout(E,B.delay);}if(B.periodical){return setInterval(E,B.periodical);}if(B.attempt){return $try(E);
}return E();};},pass:function(A,B){return this.create({arguments:A,bind:B});},attempt:function(A,B){return this.create({arguments:A,bind:B,attempt:true})();
},bind:function(B,A){return this.create({bind:B,arguments:A});},bindWithEvent:function(B,A){return this.create({bind:B,event:true,arguments:A});},delay:function(B,C,A){return this.create({delay:B,bind:C,arguments:A})();
},periodical:function(A,C,B){return this.create({periodical:A,bind:C,arguments:B})();},run:function(A,B){return this.apply(B,$splat(A));}});Number.implement({limit:function(B,A){return Math.min(A,Math.max(B,this));
},round:function(A){A=Math.pow(10,A||0);return Math.round(this*A)/A;},times:function(B,C){for(var A=0;A<this;A++){B.call(C,A,this);}},toFloat:function(){return parseFloat(this);
},toInt:function(A){return parseInt(this,A||10);}});Number.alias("times","each");(function(B){var A={};B.each(function(C){if(!Number[C]){A[C]=function(){return Math[C].apply(null,[this].concat($A(arguments)));
};}});Number.implement(A);})(["abs","acos","asin","atan","atan2","ceil","cos","exp","floor","log","max","min","pow","sin","sqrt","tan"]);String.implement({test:function(A,B){return((typeof A=="string")?new RegExp(A,B):A).test(this);
},contains:function(A,B){return(B)?(B+this+B).indexOf(B+A+B)>-1:this.indexOf(A)>-1;},trim:function(){return this.replace(/^\s+|\s+$/g,"");},clean:function(){return this.replace(/\s+/g," ").trim();
},camelCase:function(){return this.replace(/-\D/g,function(A){return A.charAt(1).toUpperCase();});},hyphenate:function(){return this.replace(/[A-Z]/g,function(A){return("-"+A.charAt(0).toLowerCase());
});},capitalize:function(){return this.replace(/\b[a-z]/g,function(A){return A.toUpperCase();});},escapeRegExp:function(){return this.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1");
},toInt:function(A){return parseInt(this,A||10);},toFloat:function(){return parseFloat(this);},hexToRgb:function(B){var A=this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return(A)?A.slice(1).hexToRgb(B):null;},rgbToHex:function(B){var A=this.match(/\d{1,3}/g);return(A)?A.rgbToHex(B):null;},stripScripts:function(B){var A="";
var C=this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi,function(){A+=arguments[1]+"\n";return"";});if(B===true){$exec(A);}else{if($type(B)=="function"){B(A,C);
}}return C;},substitute:function(A,B){return this.replace(B||(/\\?\{([^}]+)\}/g),function(D,C){if(D.charAt(0)=="\\"){return D.slice(1);}return(A[C]!=undefined)?A[C]:"";
});}});Hash.implement({has:Object.prototype.hasOwnProperty,keyOf:function(B){for(var A in this){if(this.hasOwnProperty(A)&&this[A]===B){return A;}}return null;
},hasValue:function(A){return(Hash.keyOf(this,A)!==null);},extend:function(A){Hash.each(A,function(C,B){Hash.set(this,B,C);},this);return this;},combine:function(A){Hash.each(A,function(C,B){Hash.include(this,B,C);
},this);return this;},erase:function(A){if(this.hasOwnProperty(A)){delete this[A];}return this;},get:function(A){return(this.hasOwnProperty(A))?this[A]:null;
},set:function(A,B){if(!this[A]||this.hasOwnProperty(A)){this[A]=B;}return this;},empty:function(){Hash.each(this,function(B,A){delete this[A];},this);
return this;},include:function(B,C){var A=this[B];if(A==undefined){this[B]=C;}return this;},map:function(B,C){var A=new Hash;Hash.each(this,function(E,D){A.set(D,B.call(C,E,D,this));
},this);return A;},filter:function(B,C){var A=new Hash;Hash.each(this,function(E,D){if(B.call(C,E,D,this)){A.set(D,E);}},this);return A;},every:function(B,C){for(var A in this){if(this.hasOwnProperty(A)&&!B.call(C,this[A],A)){return false;
}}return true;},some:function(B,C){for(var A in this){if(this.hasOwnProperty(A)&&B.call(C,this[A],A)){return true;}}return false;},getKeys:function(){var A=[];
Hash.each(this,function(C,B){A.push(B);});return A;},getValues:function(){var A=[];Hash.each(this,function(B){A.push(B);});return A;},toQueryString:function(A){var B=[];
Hash.each(this,function(F,E){if(A){E=A+"["+E+"]";}var D;switch($type(F)){case"object":D=Hash.toQueryString(F,E);break;case"array":var C={};F.each(function(H,G){C[G]=H;
});D=Hash.toQueryString(C,E);break;default:D=E+"="+encodeURIComponent(F);}if(F!=undefined){B.push(D);}});return B.join("&");}});Hash.alias({keyOf:"indexOf",hasValue:"contains"});
var Event=new Native({name:"Event",initialize:function(A,F){F=F||window;var K=F.document;A=A||F.event;if(A.$extended){return A;}this.$extended=true;var J=A.type;
var G=A.target||A.srcElement;while(G&&G.nodeType==3){G=G.parentNode;}if(J.test(/key/)){var B=A.which||A.keyCode;var M=Event.Keys.keyOf(B);if(J=="keydown"){var D=B-111;
if(D>0&&D<13){M="f"+D;}}M=M||String.fromCharCode(B).toLowerCase();}else{if(J.match(/(click|mouse|menu)/i)){K=(!K.compatMode||K.compatMode=="CSS1Compat")?K.html:K.body;
var I={x:A.pageX||A.clientX+K.scrollLeft,y:A.pageY||A.clientY+K.scrollTop};var C={x:(A.pageX)?A.pageX-F.pageXOffset:A.clientX,y:(A.pageY)?A.pageY-F.pageYOffset:A.clientY};
if(J.match(/DOMMouseScroll|mousewheel/)){var H=(A.wheelDelta)?A.wheelDelta/120:-(A.detail||0)/3;}var E=(A.which==3)||(A.button==2);var L=null;if(J.match(/over|out/)){switch(J){case"mouseover":L=A.relatedTarget||A.fromElement;
break;case"mouseout":L=A.relatedTarget||A.toElement;}if(!(function(){while(L&&L.nodeType==3){L=L.parentNode;}return true;}).create({attempt:Browser.Engine.gecko})()){L=false;
}}}}return $extend(this,{event:A,type:J,page:I,client:C,rightClick:E,wheel:H,relatedTarget:L,target:G,code:B,key:M,shift:A.shiftKey,control:A.ctrlKey,alt:A.altKey,meta:A.metaKey});
}});Event.Keys=new Hash({enter:13,up:38,down:40,left:37,right:39,esc:27,space:32,backspace:8,tab:9,"delete":46});Event.implement({stop:function(){return this.stopPropagation().preventDefault();
},stopPropagation:function(){if(this.event.stopPropagation){this.event.stopPropagation();}else{this.event.cancelBubble=true;}return this;},preventDefault:function(){if(this.event.preventDefault){this.event.preventDefault();
}else{this.event.returnValue=false;}return this;}});var Class=new Native({name:"Class",initialize:function(B){B=B||{};var A=function(E){for(var D in this){this[D]=$unlink(this[D]);
}for(var F in Class.Mutators){if(!this[F]){continue;}Class.Mutators[F](this,this[F]);delete this[F];}this.constructor=A;if(E===$empty){return this;}var C=(this.initialize)?this.initialize.apply(this,arguments):this;
if(this.options&&this.options.initialize){this.options.initialize.call(this);}return C;};$extend(A,this);A.constructor=Class;A.prototype=B;return A;}});
Class.implement({implement:function(){Class.Mutators.Implements(this.prototype,Array.slice(arguments));return this;}});Class.Mutators={Implements:function(A,B){$splat(B).each(function(C){$extend(A,($type(C)=="class")?new C($empty):C);
});},Extends:function(self,klass){var instance=new klass($empty);delete instance.parent;delete instance.parentOf;for(var key in instance){var current=self[key],previous=instance[key];
if(current==undefined){self[key]=previous;continue;}var ctype=$type(current),ptype=$type(previous);if(ctype!=ptype){continue;}switch(ctype){case"function":if(!arguments.callee.caller){self[key]=eval("("+String(current).replace(/\bthis\.parent\(\s*(\))?/g,function(full,close){return"arguments.callee._parent_.call(this"+(close||", ");
})+")");}self[key]._parent_=previous;break;case"object":self[key]=$merge(previous,current);}}self.parent=function(){return arguments.callee.caller._parent_.apply(this,arguments);
};self.parentOf=function(descendant){return descendant._parent_.apply(this,Array.slice(arguments,1));};}};var Chain=new Class({chain:function(){this.$chain=(this.$chain||[]).extend(arguments);
return this;},callChain:function(){return(this.$chain&&this.$chain.length)?this.$chain.shift().apply(this,arguments):false;},clearChain:function(){if(this.$chain){this.$chain.empty();
}return this;}});var Events=new Class({addEvent:function(C,B,A){C=Events.removeOn(C);if(B!=$empty){this.$events=this.$events||{};this.$events[C]=this.$events[C]||[];
this.$events[C].include(B);if(A){B.internal=true;}}return this;},addEvents:function(A){for(var B in A){this.addEvent(B,A[B]);}return this;},fireEvent:function(C,B,A){C=Events.removeOn(C);
if(!this.$events||!this.$events[C]){return this;}this.$events[C].each(function(D){D.create({bind:this,delay:A,"arguments":B})();},this);return this;},removeEvent:function(B,A){B=Events.removeOn(B);
if(!this.$events||!this.$events[B]){return this;}if(!A.internal){this.$events[B].erase(A);}return this;},removeEvents:function(C){for(var D in this.$events){if(C&&C!=D){continue;
}var B=this.$events[D];for(var A=B.length;A--;A){this.removeEvent(D,B[A]);}}return this;}});Events.removeOn=function(A){return A.replace(/^on([A-Z])/,function(B,C){return C.toLowerCase();
});};var Options=new Class({setOptions:function(){this.options=$merge.run([this.options].extend(arguments));if(!this.addEvent){return this;}for(var A in this.options){if($type(this.options[A])!="function"||!(/^on[A-Z]/).test(A)){continue;
}this.addEvent(A,this.options[A]);delete this.options[A];}return this;}});Document.implement({newElement:function(A,B){if(Browser.Engine.trident&&B){["name","type","checked"].each(function(C){if(!B[C]){return ;
}A+=" "+C+'="'+B[C]+'"';if(C!="checked"){delete B[C];}});A="<"+A+">";}return $.element(this.createElement(A)).set(B);},newTextNode:function(A){return this.createTextNode(A);
},getDocument:function(){return this;},getWindow:function(){return this.defaultView||this.parentWindow;},purge:function(){var C=this.getElementsByTagName("*");
for(var B=0,A=C.length;B<A;B++){Browser.freeMem(C[B]);}}});var Element=new Native({name:"Element",legacy:window.Element,initialize:function(A,B){var C=Element.Constructors.get(A);
if(C){return C(B);}if(typeof A=="string"){return document.newElement(A,B);}return $(A).set(B);},afterImplement:function(A,B){if(!Array[A]){Elements.implement(A,Elements.multi(A));
}Element.Prototype[A]=B;}});Element.Prototype={$family:{name:"element"}};Element.Constructors=new Hash;var IFrame=new Native({name:"IFrame",generics:false,initialize:function(){var E=Array.link(arguments,{properties:Object.type,iframe:$defined});
var C=E.properties||{};var B=$(E.iframe)||false;var D=C.onload||$empty;delete C.onload;C.id=C.name=$pick(C.id,C.name,B.id,B.name,"IFrame_"+$time());B=new Element(B||"iframe",C);
var A=function(){var F=$try(function(){return B.contentWindow.location.host;});if(F&&F==window.location.host){var H=new Window(B.contentWindow);var G=new Document(B.contentWindow.document);
$extend(H.Element.prototype,Element.Prototype);}D.call(B.contentWindow,B.contentWindow.document);};(!window.frames[C.id])?B.addListener("load",A):A();return B;
}});var Elements=new Native({initialize:function(F,B){B=$extend({ddup:true,cash:true},B);F=F||[];if(B.ddup||B.cash){var G={},E=[];for(var C=0,A=F.length;
C<A;C++){var D=$.element(F[C],!B.cash);if(B.ddup){if(G[D.uid]){continue;}G[D.uid]=true;}E.push(D);}F=E;}return(B.cash)?$extend(F,this):F;}});Elements.implement({filter:function(A,B){if(!A){return this;
}return new Elements(Array.filter(this,(typeof A=="string")?function(C){return C.match(A);}:A,B));}});Elements.multi=function(A){return function(){var B=[];
var F=true;for(var D=0,C=this.length;D<C;D++){var E=this[D][A].apply(this[D],arguments);B.push(E);if(F){F=($type(E)=="element");}}return(F)?new Elements(B):B;
};};Window.implement({$:function(B,C){if(B&&B.$family&&B.uid){return B;}var A=$type(B);return($[A])?$[A](B,C,this.document):null;},$$:function(A){if(arguments.length==1&&typeof A=="string"){return this.document.getElements(A);
}var F=[];var C=Array.flatten(arguments);for(var D=0,B=C.length;D<B;D++){var E=C[D];switch($type(E)){case"element":E=[E];break;case"string":E=this.document.getElements(E,true);
break;default:E=false;}if(E){F.extend(E);}}return new Elements(F);},getDocument:function(){return this.document;},getWindow:function(){return this;}});
$.string=function(C,B,A){C=A.getElementById(C);return(C)?$.element(C,B):null;};$.element=function(A,D){$uid(A);if(!D&&!A.$family&&!(/^object|embed$/i).test(A.tagName)){var B=Element.Prototype;
for(var C in B){A[C]=B[C];}}return A;};$.object=function(B,C,A){if(B.toElement){return $.element(B.toElement(A),C);}return null;};$.textnode=$.whitespace=$.window=$.document=$arguments(0);
Native.implement([Element,Document],{getElement:function(A,B){return $(this.getElements(A,true)[0]||null,B);},getElements:function(A,D){A=A.split(",");
var C=[];var B=(A.length>1);A.each(function(E){var F=this.getElementsByTagName(E.trim());(B)?C.extend(F):C=F;},this);return new Elements(C,{ddup:B,cash:!D});
}});Element.Storage={get:function(A){return(this[A]||(this[A]={}));}};Element.Inserters=new Hash({before:function(B,A){if(A.parentNode){A.parentNode.insertBefore(B,A);
}},after:function(B,A){if(!A.parentNode){return ;}var C=A.nextSibling;(C)?A.parentNode.insertBefore(B,C):A.parentNode.appendChild(B);},bottom:function(B,A){A.appendChild(B);
},top:function(B,A){var C=A.firstChild;(C)?A.insertBefore(B,C):A.appendChild(B);}});Element.Inserters.inside=Element.Inserters.bottom;Element.Inserters.each(function(C,B){var A=B.capitalize();
Element.implement("inject"+A,function(D){C(this,$(D,true));return this;});Element.implement("grab"+A,function(D){C($(D,true),this);return this;});});Element.implement({getDocument:function(){return this.ownerDocument;
},getWindow:function(){return this.ownerDocument.getWindow();},getElementById:function(D,C){var B=this.ownerDocument.getElementById(D);if(!B){return null;
}for(var A=B.parentNode;A!=this;A=A.parentNode){if(!A){return null;}}return $.element(B,C);},set:function(D,B){switch($type(D)){case"object":for(var C in D){this.set(C,D[C]);
}break;case"string":var A=Element.Properties.get(D);(A&&A.set)?A.set.apply(this,Array.slice(arguments,1)):this.setProperty(D,B);}return this;},get:function(B){var A=Element.Properties.get(B);
return(A&&A.get)?A.get.apply(this,Array.slice(arguments,1)):this.getProperty(B);},erase:function(B){var A=Element.Properties.get(B);(A&&A.erase)?A.erase.apply(this,Array.slice(arguments,1)):this.removeProperty(B);
return this;},match:function(A){return(!A||Element.get(this,"tag")==A);},inject:function(B,A){Element.Inserters.get(A||"bottom")(this,$(B,true));return this;
},wraps:function(B,A){B=$(B,true);return this.replaces(B).grab(B,A);},grab:function(B,A){Element.Inserters.get(A||"bottom")($(B,true),this);return this;
},appendText:function(B,A){return this.grab(this.getDocument().newTextNode(B),A);},adopt:function(){Array.flatten(arguments).each(function(A){A=$(A,true);
if(A){this.appendChild(A);}},this);return this;},dispose:function(){return(this.parentNode)?this.parentNode.removeChild(this):this;},clone:function(D,C){switch($type(this)){case"element":var H={};
for(var G=0,E=this.attributes.length;G<E;G++){var B=this.attributes[G],L=B.nodeName.toLowerCase();if(Browser.Engine.trident&&(/input/i).test(this.tagName)&&(/width|height/).test(L)){continue;
}var K=(L=="style"&&this.style)?this.style.cssText:B.nodeValue;if(!$chk(K)||L=="uid"||(L=="id"&&!C)){continue;}if(K!="inherit"&&["string","number"].contains($type(K))){H[L]=K;
}}var J=new Element(this.nodeName.toLowerCase(),H);if(D!==false){for(var I=0,F=this.childNodes.length;I<F;I++){var A=Element.clone(this.childNodes[I],true,C);
if(A){J.grab(A);}}}return J;case"textnode":return document.newTextNode(this.nodeValue);}return null;},replaces:function(A){A=$(A,true);A.parentNode.replaceChild(this,A);
return this;},hasClass:function(A){return this.className.contains(A," ");},addClass:function(A){if(!this.hasClass(A)){this.className=(this.className+" "+A).clean();
}return this;},removeClass:function(A){this.className=this.className.replace(new RegExp("(^|\\s)"+A+"(?:\\s|$)"),"$1").clean();return this;},toggleClass:function(A){return this.hasClass(A)?this.removeClass(A):this.addClass(A);
},getComputedStyle:function(B){if(this.currentStyle){return this.currentStyle[B.camelCase()];}var A=this.getWindow().getComputedStyle(this,null);return(A)?A.getPropertyValue([B.hyphenate()]):null;
},empty:function(){$A(this.childNodes).each(function(A){Browser.freeMem(A);Element.empty(A);Element.dispose(A);},this);return this;},destroy:function(){Browser.freeMem(this.empty().dispose());
return null;},getSelected:function(){return new Elements($A(this.options).filter(function(A){return A.selected;}));},toQueryString:function(){var A=[];
this.getElements("input, select, textarea").each(function(B){if(!B.name||B.disabled){return ;}var C=(B.tagName.toLowerCase()=="select")?Element.getSelected(B).map(function(D){return D.value;
}):((B.type=="radio"||B.type=="checkbox")&&!B.checked)?null:B.value;$splat(C).each(function(D){if(D){A.push(B.name+"="+encodeURIComponent(D));}});});return A.join("&");
},getProperty:function(C){var B=Element.Attributes,A=B.Props[C];var D=(A)?this[A]:this.getAttribute(C,2);return(B.Bools[C])?!!D:(A)?D:D||null;},getProperties:function(){var A=$A(arguments);
return A.map(function(B){return this.getProperty(B);},this).associate(A);},setProperty:function(D,E){var C=Element.Attributes,B=C.Props[D],A=$defined(E);
if(B&&C.Bools[D]){E=(E||!A)?true:false;}else{if(!A){return this.removeProperty(D);}}(B)?this[B]=E:this.setAttribute(D,E);return this;},setProperties:function(A){for(var B in A){this.setProperty(B,A[B]);
}return this;},removeProperty:function(D){var C=Element.Attributes,B=C.Props[D],A=(B&&C.Bools[D]);(B)?this[B]=(A)?false:"":this.removeAttribute(D);return this;
},removeProperties:function(){Array.each(arguments,this.removeProperty,this);return this;}});(function(){var A=function(D,B,I,C,F,H){var E=D[I||B];var G=[];
while(E){if(E.nodeType==1&&(!C||Element.match(E,C))){G.push(E);if(!F){break;}}E=E[B];}return(F)?new Elements(G,{ddup:false,cash:!H}):$(G[0],H);};Element.implement({getPrevious:function(B,C){return A(this,"previousSibling",null,B,false,C);
},getAllPrevious:function(B,C){return A(this,"previousSibling",null,B,true,C);},getNext:function(B,C){return A(this,"nextSibling",null,B,false,C);},getAllNext:function(B,C){return A(this,"nextSibling",null,B,true,C);
},getFirst:function(B,C){return A(this,"nextSibling","firstChild",B,false,C);},getLast:function(B,C){return A(this,"previousSibling","lastChild",B,false,C);
},getParent:function(B,C){return A(this,"parentNode",null,B,false,C);},getParents:function(B,C){return A(this,"parentNode",null,B,true,C);},getChildren:function(B,C){return A(this,"nextSibling","firstChild",B,true,C);
},hasChild:function(B){B=$(B,true);return(!!B&&$A(this.getElementsByTagName(B.tagName)).contains(B));}});})();Element.Properties=new Hash;Element.Properties.style={set:function(A){this.style.cssText=A;
},get:function(){return this.style.cssText;},erase:function(){this.style.cssText="";}};Element.Properties.tag={get:function(){return this.tagName.toLowerCase();
}};Element.Properties.href={get:function(){return(!this.href)?null:this.href.replace(new RegExp("^"+document.location.protocol+"//"+document.location.host),"");
}};Element.Properties.html={set:function(){return this.innerHTML=Array.flatten(arguments).join("");}};Native.implement([Element,Window,Document],{addListener:function(B,A){if(this.addEventListener){this.addEventListener(B,A,false);
}else{this.attachEvent("on"+B,A);}return this;},removeListener:function(B,A){if(this.removeEventListener){this.removeEventListener(B,A,false);}else{this.detachEvent("on"+B,A);
}return this;},retrieve:function(B,A){var D=Element.Storage.get(this.uid);var C=D[B];if($defined(A)&&!$defined(C)){C=D[B]=A;}return $pick(C);},store:function(B,A){var C=Element.Storage.get(this.uid);
C[B]=A;return this;},eliminate:function(A){var B=Element.Storage.get(this.uid);delete B[A];return this;}});Element.Attributes=new Hash({Props:{html:"innerHTML","class":"className","for":"htmlFor",text:(Browser.Engine.trident)?"innerText":"textContent"},Bools:["compact","nowrap","ismap","declare","noshade","checked","disabled","readonly","multiple","selected","noresize","defer"],Camels:["value","accessKey","cellPadding","cellSpacing","colSpan","frameBorder","maxLength","readOnly","rowSpan","tabIndex","useMap"]});
Browser.freeMem=function(A){if(!A){return ;}if(Browser.Engine.trident&&(/object/i).test(A.tagName)){for(var B in A){if(typeof A[B]=="function"){A[B]=$empty;
}}Element.dispose(A);}if(A.uid&&A.removeEvents){A.removeEvents();}};(function(B){var C=B.Bools,A=B.Camels;B.Bools=C=C.associate(C);Hash.extend(Hash.combine(B.Props,C),A.associate(A.map(function(D){return D.toLowerCase();
})));B.erase("Camels");})(Element.Attributes);window.addListener("unload",function(){window.removeListener("unload",arguments.callee);document.purge();
if(Browser.Engine.trident){CollectGarbage();}});Element.Properties.events={set:function(A){this.addEvents(A);}};Native.implement([Element,Window,Document],{addEvent:function(E,G){var H=this.retrieve("events",{});
H[E]=H[E]||{keys:[],values:[]};if(H[E].keys.contains(G)){return this;}H[E].keys.push(G);var F=E,A=Element.Events.get(E),C=G,I=this;if(A){if(A.onAdd){A.onAdd.call(this,G);
}if(A.condition){C=function(J){if(A.condition.call(this,J)){return G.call(this,J);}return false;};}F=A.base||F;}var D=function(){return G.call(I);};var B=Element.NativeEvents[F]||0;
if(B){if(B==2){D=function(J){J=new Event(J,I.getWindow());if(C.call(I,J)===false){J.stop();}};}this.addListener(F,D);}H[E].values.push(D);return this;},removeEvent:function(D,C){var B=this.retrieve("events");
if(!B||!B[D]){return this;}var G=B[D].keys.indexOf(C);if(G==-1){return this;}var A=B[D].keys.splice(G,1)[0];var F=B[D].values.splice(G,1)[0];var E=Element.Events.get(D);
if(E){if(E.onRemove){E.onRemove.call(this,C);}D=E.base||D;}return(Element.NativeEvents[D])?this.removeListener(D,F):this;},addEvents:function(A){for(var B in A){this.addEvent(B,A[B]);
}return this;},removeEvents:function(B){var A=this.retrieve("events");if(!A){return this;}if(!B){for(var C in A){this.removeEvents(C);}A=null;}else{if(A[B]){while(A[B].keys[0]){this.removeEvent(B,A[B].keys[0]);
}A[B]=null;}}return this;},fireEvent:function(D,B,A){var C=this.retrieve("events");if(!C||!C[D]){return this;}C[D].keys.each(function(E){E.create({bind:this,delay:A,"arguments":B})();
},this);return this;},cloneEvents:function(D,A){D=$(D);var C=D.retrieve("events");if(!C){return this;}if(!A){for(var B in C){this.cloneEvents(D,B);}}else{if(C[A]){C[A].keys.each(function(E){this.addEvent(A,E);
},this);}}return this;}});Element.NativeEvents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,DOMMouseScroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,load:1,unload:1,beforeunload:2,resize:1,move:1,DOMContentLoaded:1,readystatechange:1,error:1,abort:1,scroll:1};
(function(){var A=function(B){var C=B.relatedTarget;if(C==undefined){return true;}if(C===false){return false;}return($type(this)!="document"&&C!=this&&C.prefix!="xul"&&!this.hasChild(C));
};Element.Events=new Hash({mouseenter:{base:"mouseover",condition:A},mouseleave:{base:"mouseout",condition:A},mousewheel:{base:(Browser.Engine.gecko)?"DOMMouseScroll":"mousewheel"}});
})();Element.Properties.styles={set:function(A){this.setStyles(A);}};Element.Properties.opacity={set:function(A,B){if(!B){if(A==0){if(this.style.visibility!="hidden"){this.style.visibility="hidden";
}}else{if(this.style.visibility!="visible"){this.style.visibility="visible";}}}if(!this.currentStyle||!this.currentStyle.hasLayout){this.style.zoom=1;}if(Browser.Engine.trident){this.style.filter=(A==1)?"":"alpha(opacity="+A*100+")";
}this.style.opacity=A;this.store("opacity",A);},get:function(){return this.retrieve("opacity",1);}};Element.implement({setOpacity:function(A){return this.set("opacity",A,true);
},getOpacity:function(){return this.get("opacity");},setStyle:function(B,A){switch(B){case"opacity":return this.set("opacity",parseFloat(A));case"float":B=(Browser.Engine.trident)?"styleFloat":"cssFloat";
}B=B.camelCase();if($type(A)!="string"){var C=(Element.Styles.get(B)||"@").split(" ");A=$splat(A).map(function(E,D){if(!C[D]){return"";}return($type(E)=="number")?C[D].replace("@",Math.round(E)):E;
}).join(" ");}else{if(A==String(Number(A))){A=Math.round(A);}}this.style[B]=A;return this;},getStyle:function(G){switch(G){case"opacity":return this.get("opacity");
case"float":G=(Browser.Engine.trident)?"styleFloat":"cssFloat";}G=G.camelCase();var A=this.style[G];if(!$chk(A)){A=[];for(var F in Element.ShortStyles){if(G!=F){continue;
}for(var E in Element.ShortStyles[F]){A.push(this.getStyle(E));}return A.join(" ");}A=this.getComputedStyle(G);}if(A){A=String(A);var C=A.match(/rgba?\([\d\s,]+\)/);
if(C){A=A.replace(C[0],C[0].rgbToHex());}}if(Browser.Engine.presto||(Browser.Engine.trident&&!$chk(parseInt(A)))){if(G.test(/^(height|width)$/)){var B=(G=="width")?["left","right"]:["top","bottom"],D=0;
B.each(function(H){D+=this.getStyle("border-"+H+"-width").toInt()+this.getStyle("padding-"+H).toInt();},this);return this["offset"+G.capitalize()]-D+"px";
}if(Browser.Engine.presto&&String(A).test("px")){return A;}if(G.test(/(border(.+)Width|margin|padding)/)){return"0px";}}return A;},setStyles:function(B){for(var A in B){this.setStyle(A,B[A]);
}return this;},getStyles:function(){var A={};Array.each(arguments,function(B){A[B]=this.getStyle(B);},this);return A;}});Element.Styles=new Hash({left:"@px",top:"@px",bottom:"@px",right:"@px",width:"@px",height:"@px",maxWidth:"@px",maxHeight:"@px",minWidth:"@px",minHeight:"@px",backgroundColor:"rgb(@, @, @)",backgroundPosition:"@px @px",color:"rgb(@, @, @)",fontSize:"@px",letterSpacing:"@px",lineHeight:"@px",clip:"rect(@px @px @px @px)",margin:"@px @px @px @px",padding:"@px @px @px @px",border:"@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)",borderWidth:"@px @px @px @px",borderStyle:"@ @ @ @",borderColor:"rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)",zIndex:"@",zoom:"@",fontWeight:"@",textIndent:"@px",opacity:"@"});
Element.ShortStyles={margin:{},padding:{},border:{},borderWidth:{},borderStyle:{},borderColor:{}};["Top","Right","Bottom","Left"].each(function(G){var F=Element.ShortStyles;
var B=Element.Styles;["margin","padding"].each(function(H){var I=H+G;F[H][I]=B[I]="@px";});var E="border"+G;F.border[E]=B[E]="@px @ rgb(@, @, @)";var D=E+"Width",A=E+"Style",C=E+"Color";
F[E]={};F.borderWidth[D]=F[E][D]=B[D]="@px";F.borderStyle[A]=F[E][A]=B[A]="@";F.borderColor[C]=F[E][C]=B[C]="rgb(@, @, @)";});(function(){Element.implement({scrollTo:function(H,I){if(B(this)){this.getWindow().scrollTo(H,I);
}else{this.scrollLeft=H;this.scrollTop=I;}return this;},getSize:function(){if(B(this)){return this.getWindow().getSize();}return{x:this.offsetWidth,y:this.offsetHeight};
},getScrollSize:function(){if(B(this)){return this.getWindow().getScrollSize();}return{x:this.scrollWidth,y:this.scrollHeight};},getScroll:function(){if(B(this)){return this.getWindow().getScroll();
}return{x:this.scrollLeft,y:this.scrollTop};},getScrolls:function(){var I=this,H={x:0,y:0};while(I&&!B(I)){H.x+=I.scrollLeft;H.y+=I.scrollTop;I=I.parentNode;
}return H;},getOffsetParent:function(){var H=this;if(B(H)){return null;}if(!Browser.Engine.trident){return H.offsetParent;}while((H=H.parentNode)&&!B(H)){if(D(H,"position")!="static"){return H;
}}return null;},getOffsets:function(){var I=this,H={x:0,y:0};if(B(this)){return H;}while(I&&!B(I)){H.x+=I.offsetLeft;H.y+=I.offsetTop;if(Browser.Engine.gecko){if(!F(I)){H.x+=C(I);
H.y+=G(I);}var J=I.parentNode;if(J&&D(J,"overflow")!="visible"){H.x+=C(J);H.y+=G(J);}}else{if(I!=this&&(Browser.Engine.trident||Browser.Engine.webkit)){H.x+=C(I);
H.y+=G(I);}}I=I.offsetParent;if(Browser.Engine.trident){while(I&&!I.currentStyle.hasLayout){I=I.offsetParent;}}}if(Browser.Engine.gecko&&!F(this)){H.x-=C(this);
H.y-=G(this);}return H;},getPosition:function(K){if(B(this)){return{x:0,y:0};}var L=this.getOffsets(),I=this.getScrolls();var H={x:L.x-I.x,y:L.y-I.y};var J=(K&&(K=$(K)))?K.getPosition():{x:0,y:0};
return{x:H.x-J.x,y:H.y-J.y};},getCoordinates:function(J){if(B(this)){return this.getWindow().getCoordinates();}var H=this.getPosition(J),I=this.getSize();
var K={left:H.x,top:H.y,width:I.x,height:I.y};K.right=K.left+K.width;K.bottom=K.top+K.height;return K;},computePosition:function(H){return{left:H.x-E(this,"margin-left"),top:H.y-E(this,"margin-top")};
},position:function(H){return this.setStyles(this.computePosition(H));}});Native.implement([Document,Window],{getSize:function(){var I=this.getWindow();
if(Browser.Engine.presto||Browser.Engine.webkit){return{x:I.innerWidth,y:I.innerHeight};}var H=A(this);return{x:H.clientWidth,y:H.clientHeight};},getScroll:function(){var I=this.getWindow();
var H=A(this);return{x:I.pageXOffset||H.scrollLeft,y:I.pageYOffset||H.scrollTop};},getScrollSize:function(){var I=A(this);var H=this.getSize();return{x:Math.max(I.scrollWidth,H.x),y:Math.max(I.scrollHeight,H.y)};
},getPosition:function(){return{x:0,y:0};},getCoordinates:function(){var H=this.getSize();return{top:0,left:0,bottom:H.y,right:H.x,height:H.y,width:H.x};
}});var D=Element.getComputedStyle;function E(H,I){return D(H,I).toInt()||0;}function F(H){return D(H,"-moz-box-sizing")=="border-box";}function G(H){return E(H,"border-top-width");
}function C(H){return E(H,"border-left-width");}function B(H){return(/^(?:body|html)$/i).test(H.tagName);}function A(H){var I=H.getDocument();return(!I.compatMode||I.compatMode=="CSS1Compat")?I.html:I.body;
}})();Native.implement([Window,Document,Element],{getHeight:function(){return this.getSize().y;},getWidth:function(){return this.getSize().x;},getScrollTop:function(){return this.getScroll().y;
},getScrollLeft:function(){return this.getScroll().x;},getScrollHeight:function(){return this.getScrollSize().y;},getScrollWidth:function(){return this.getScrollSize().x;
},getTop:function(){return this.getPosition().y;},getLeft:function(){return this.getPosition().x;}});Native.implement([Document,Element],{getElements:function(H,G){H=H.split(",");
var C,E={};for(var D=0,B=H.length;D<B;D++){var A=H[D],F=Selectors.Utils.search(this,A,E);if(D!=0&&F.item){F=$A(F);}C=(D==0)?F:(C.item)?$A(C).concat(F):C.concat(F);
}return new Elements(C,{ddup:(H.length>1),cash:!G});}});Element.implement({match:function(B){if(!B){return true;}var D=Selectors.Utils.parseTagAndID(B);
var A=D[0],E=D[1];if(!Selectors.Filters.byID(this,E)||!Selectors.Filters.byTag(this,A)){return false;}var C=Selectors.Utils.parseSelector(B);return(C)?Selectors.Utils.filter(this,C,{}):true;
}});var Selectors={Cache:{nth:{},parsed:{}}};Selectors.RegExps={id:(/#([\w-]+)/),tag:(/^(\w+|\*)/),quick:(/^(\w+|\*)$/),splitter:(/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g),combined:(/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)["']?(.*?)["']?)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g)};
Selectors.Utils={chk:function(B,C){if(!C){return true;}var A=$uid(B);if(!C[A]){return C[A]=true;}return false;},parseNthArgument:function(F){if(Selectors.Cache.nth[F]){return Selectors.Cache.nth[F];
}var C=F.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/);if(!C){return false;}var E=parseInt(C[1]);var B=(E||E===0)?E:1;var D=C[2]||false;var A=parseInt(C[3])||0;
if(B!=0){A--;while(A<1){A+=B;}while(A>=B){A-=B;}}else{B=A;D="index";}switch(D){case"n":C={a:B,b:A,special:"n"};break;case"odd":C={a:2,b:0,special:"n"};
break;case"even":C={a:2,b:1,special:"n"};break;case"first":C={a:0,special:"index"};break;case"last":C={special:"last-child"};break;case"only":C={special:"only-child"};
break;default:C={a:(B-1),special:"index"};}return Selectors.Cache.nth[F]=C;},parseSelector:function(E){if(Selectors.Cache.parsed[E]){return Selectors.Cache.parsed[E];
}var D,H={classes:[],pseudos:[],attributes:[]};while((D=Selectors.RegExps.combined.exec(E))){var I=D[1],G=D[2],F=D[3],B=D[4],C=D[5],J=D[6];if(I){H.classes.push(I);
}else{if(C){var A=Selectors.Pseudo.get(C);if(A){H.pseudos.push({parser:A,argument:J});}else{H.attributes.push({name:C,operator:"=",value:J});}}else{if(G){H.attributes.push({name:G,operator:F,value:B});
}}}}if(!H.classes.length){delete H.classes;}if(!H.attributes.length){delete H.attributes;}if(!H.pseudos.length){delete H.pseudos;}if(!H.classes&&!H.attributes&&!H.pseudos){H=null;
}return Selectors.Cache.parsed[E]=H;},parseTagAndID:function(B){var A=B.match(Selectors.RegExps.tag);var C=B.match(Selectors.RegExps.id);return[(A)?A[1]:"*",(C)?C[1]:false];
},filter:function(F,C,E){var D;if(C.classes){for(D=C.classes.length;D--;D){var G=C.classes[D];if(!Selectors.Filters.byClass(F,G)){return false;}}}if(C.attributes){for(D=C.attributes.length;
D--;D){var B=C.attributes[D];if(!Selectors.Filters.byAttribute(F,B.name,B.operator,B.value)){return false;}}}if(C.pseudos){for(D=C.pseudos.length;D--;D){var A=C.pseudos[D];
if(!Selectors.Filters.byPseudo(F,A.parser,A.argument,E)){return false;}}}return true;},getByTagAndID:function(B,A,D){if(D){var C=(B.getElementById)?B.getElementById(D,true):Element.getElementById(B,D,true);
return(C&&Selectors.Filters.byTag(C,A))?[C]:[];}else{return B.getElementsByTagName(A);}},search:function(J,I,O){var B=[];var C=I.trim().replace(Selectors.RegExps.splitter,function(Z,Y,X){B.push(Y);
return":)"+X;}).split(":)");var K,F,E,V;for(var U=0,Q=C.length;U<Q;U++){var T=C[U];if(U==0&&Selectors.RegExps.quick.test(T)){K=J.getElementsByTagName(T);
continue;}var A=B[U-1];var L=Selectors.Utils.parseTagAndID(T);var W=L[0],M=L[1];if(U==0){K=Selectors.Utils.getByTagAndID(J,W,M);}else{var D={},H=[];for(var S=0,R=K.length;
S<R;S++){H=Selectors.Getters[A](H,K[S],W,M,D);}K=H;}var G=Selectors.Utils.parseSelector(T);if(G){E=[];for(var P=0,N=K.length;P<N;P++){V=K[P];if(Selectors.Utils.filter(V,G,O)){E.push(V);
}}K=E;}}return K;}};Selectors.Getters={" ":function(H,G,I,A,E){var D=Selectors.Utils.getByTagAndID(G,I,A);for(var C=0,B=D.length;C<B;C++){var F=D[C];if(Selectors.Utils.chk(F,E)){H.push(F);
}}return H;},">":function(H,G,I,A,F){var C=Selectors.Utils.getByTagAndID(G,I,A);for(var E=0,D=C.length;E<D;E++){var B=C[E];if(B.parentNode==G&&Selectors.Utils.chk(B,F)){H.push(B);
}}return H;},"+":function(C,B,A,E,D){while((B=B.nextSibling)){if(B.nodeType==1){if(Selectors.Utils.chk(B,D)&&Selectors.Filters.byTag(B,A)&&Selectors.Filters.byID(B,E)){C.push(B);
}break;}}return C;},"~":function(C,B,A,E,D){while((B=B.nextSibling)){if(B.nodeType==1){if(!Selectors.Utils.chk(B,D)){break;}if(Selectors.Filters.byTag(B,A)&&Selectors.Filters.byID(B,E)){C.push(B);
}}}return C;}};Selectors.Filters={byTag:function(B,A){return(A=="*"||(B.tagName&&B.tagName.toLowerCase()==A));},byID:function(A,B){return(!B||(A.id&&A.id==B));
},byClass:function(B,A){return(B.className&&B.className.contains(A," "));},byPseudo:function(A,D,C,B){return D.call(A,C,B);},byAttribute:function(C,D,B,E){var A=Element.prototype.getProperty.call(C,D);
if(!A){return false;}if(!B||E==undefined){return true;}switch(B){case"=":return(A==E);case"*=":return(A.contains(E));case"^=":return(A.substr(0,E.length)==E);
case"$=":return(A.substr(A.length-E.length)==E);case"!=":return(A!=E);case"~=":return A.contains(E," ");case"|=":return A.contains(E,"-");}return false;
}};Selectors.Pseudo=new Hash({empty:function(){return !(this.innerText||this.textContent||"").length;},not:function(A){return !Element.match(this,A);},contains:function(A){return(this.innerText||this.textContent||"").contains(A);
},"first-child":function(){return Selectors.Pseudo.index.call(this,0);},"last-child":function(){var A=this;while((A=A.nextSibling)){if(A.nodeType==1){return false;
}}return true;},"only-child":function(){var B=this;while((B=B.previousSibling)){if(B.nodeType==1){return false;}}var A=this;while((A=A.nextSibling)){if(A.nodeType==1){return false;
}}return true;},"nth-child":function(G,E){G=(G==undefined)?"n":G;var C=Selectors.Utils.parseNthArgument(G);if(C.special!="n"){return Selectors.Pseudo[C.special].call(this,C.a,E);
}var F=0;E.positions=E.positions||{};var D=$uid(this);if(!E.positions[D]){var B=this;while((B=B.previousSibling)){if(B.nodeType!=1){continue;}F++;var A=E.positions[$uid(B)];
if(A!=undefined){F=A+F;break;}}E.positions[D]=F;}return(E.positions[D]%C.a==C.b);},index:function(A){var B=this,C=0;while((B=B.previousSibling)){if(B.nodeType==1&&++C>A){return false;
}}return(C==A);},even:function(B,A){return Selectors.Pseudo["nth-child"].call(this,"2n+1",A);},odd:function(B,A){return Selectors.Pseudo["nth-child"].call(this,"2n",A);
}});Element.Events.domready={onAdd:function(A){if(Browser.loaded){A.call(this);}}};(function(){var B=function(){if(Browser.loaded){return ;}Browser.loaded=true;
window.fireEvent("domready");document.fireEvent("domready");};switch(Browser.Engine.name){case"webkit":(function(){(["loaded","complete"].contains(document.readyState))?B():arguments.callee.delay(50);
})();break;case"trident":var A=document.createElement("div");(function(){($try(function(){A.doScroll("left");return $(A).inject(document.body).set("html","temp").dispose();
}))?B():arguments.callee.delay(50);})();break;default:window.addEvent("load",B);document.addEvent("DOMContentLoaded",B);}})();var JSON=new Hash({encode:function(B){switch($type(B)){case"string":return'"'+B.replace(/[\x00-\x1f\\"]/g,JSON.$replaceChars)+'"';
case"array":return"["+String(B.map(JSON.encode).filter($defined))+"]";case"object":case"hash":var A=[];Hash.each(B,function(E,D){var C=JSON.encode(E);if(C){A.push(JSON.encode(D)+":"+C);
}});return"{"+A+"}";case"number":case"boolean":return String(B);case false:return"null";}return null;},$specialChars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},$replaceChars:function(A){return JSON.$specialChars[A]||"\\u00"+Math.floor(A.charCodeAt()/16).toString(16)+(A.charCodeAt()%16).toString(16);
},decode:function(string,secure){if($type(string)!="string"||!string.length){return null;}if(secure&&!(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,""))){return null;
}return eval("("+string+")");}});Native.implement([Hash,Array,String,Number],{toJSON:function(){return JSON.encode(this);}});var Cookie=new Class({Implements:Options,options:{path:false,domain:false,duration:false,secure:false,document:document},initialize:function(B,A){this.key=B;
this.setOptions(A);},write:function(B){B=encodeURIComponent(B);if(this.options.domain){B+="; domain="+this.options.domain;}if(this.options.path){B+="; path="+this.options.path;
}if(this.options.duration){var A=new Date();A.setTime(A.getTime()+this.options.duration*24*60*60*1000);B+="; expires="+A.toGMTString();}if(this.options.secure){B+="; secure";
}this.options.document.cookie=this.key+"="+B;return this;},read:function(){var A=this.options.document.cookie.match("(?:^|;)\\s*"+this.key.escapeRegExp()+"=([^;]*)");
return(A)?decodeURIComponent(A[1]):null;},dispose:function(){new Cookie(this.key,$merge(this.options,{duration:-1})).write("");return this;}});Cookie.write=function(B,C,A){return new Cookie(B,A).write(C);
};Cookie.read=function(A){return new Cookie(A).read();};Cookie.dispose=function(B,A){return new Cookie(B,A).dispose();};var Swiff=new Class({Implements:[Options],options:{id:null,height:1,width:1,container:null,properties:{},params:{quality:"high",allowScriptAccess:"always",wMode:"transparent",swLiveConnect:true},callBacks:{},vars:{}},toElement:function(){return this.object;
},initialize:function(L,M){this.instance="Swiff_"+$time();this.setOptions(M);M=this.options;var B=this.id=M.id||this.instance;var A=$(M.container);Swiff.CallBacks[this.instance]={};
var E=M.params,G=M.vars,F=M.callBacks;var H=$extend({height:M.height,width:M.width},M.properties);var K=this;for(var D in F){Swiff.CallBacks[this.instance][D]=(function(N){return function(){return N.apply(K.object,arguments);
};})(F[D]);G[D]="Swiff.CallBacks."+this.instance+"."+D;}E.flashVars=Hash.toQueryString(G);if(Browser.Engine.trident){H.classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
E.movie=L;}else{H.type="application/x-shockwave-flash";H.data=L;}var J='<object id="'+B+'"';for(var I in H){J+=" "+I+'="'+H[I]+'"';}J+=">";for(var C in E){if(E[C]){J+='<param name="'+C+'" value="'+E[C]+'" />';
}}J+="</object>";this.object=((A)?A.empty():new Element("div")).set("html",J).firstChild;},replaces:function(A){A=$(A,true);A.parentNode.replaceChild(this.toElement(),A);
return this;},inject:function(A){$(A,true).appendChild(this.toElement());return this;},remote:function(){return Swiff.remote.apply(Swiff,[this.toElement()].extend(arguments));
}});Swiff.CallBacks={};Swiff.remote=function(obj,fn){var rs=obj.CallFunction('<invoke name="'+fn+'" returntype="javascript">'+__flash__argumentsToXML(arguments,2)+"</invoke>");
return eval(rs);};var Fx=new Class({Implements:[Chain,Events,Options],options:{fps:50,unit:false,duration:500,link:"ignore",transition:function(A){return -(Math.cos(Math.PI*A)-1)/2;
}},initialize:function(A){this.subject=this.subject||this;this.setOptions(A);this.options.duration=Fx.Durations[this.options.duration]||this.options.duration.toInt();
var B=this.options.wait;if(B===false){this.options.link="cancel";}},step:function(){var A=$time();if(A<this.time+this.options.duration){var B=this.options.transition((A-this.time)/this.options.duration);
this.set(this.compute(this.from,this.to,B));}else{this.set(this.compute(this.from,this.to,1));this.complete();}},set:function(A){return A;},compute:function(C,B,A){return Fx.compute(C,B,A);
},check:function(A){if(!this.timer){return true;}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(A.bind(this,Array.slice(arguments,1)));
return false;}return false;},start:function(B,A){if(!this.check(arguments.callee,B,A)){return this;}this.from=B;this.to=A;this.time=0;this.startTimer();
this.onStart();return this;},complete:function(){if(this.stopTimer()){this.onComplete();}return this;},cancel:function(){if(this.stopTimer()){this.onCancel();
}return this;},onStart:function(){this.fireEvent("start",this.subject);},onComplete:function(){this.fireEvent("complete",this.subject);if(!this.callChain()){this.fireEvent("chainComplete",this.subject);
}},onCancel:function(){this.fireEvent("cancel",this.subject).clearChain();},pause:function(){this.stopTimer();return this;},resume:function(){this.startTimer();
return this;},stopTimer:function(){if(!this.timer){return false;}this.time=$time()-this.time;this.timer=$clear(this.timer);return true;},startTimer:function(){if(this.timer){return false;
}this.time=$time()-this.time;this.timer=this.step.periodical(Math.round(1000/this.options.fps),this);return true;}});Fx.compute=function(C,B,A){return(B-C)*A+C;
};Fx.Durations={"short":250,normal:500,"long":1000};Fx.CSS=new Class({Extends:Fx,prepare:function(D,E,B){B=$splat(B);var C=B[1];if(!$chk(C)){B[1]=B[0];
B[0]=D.getStyle(E);}var A=B.map(this.parse);return{from:A[0],to:A[1]};},parse:function(A){A=$lambda(A)();A=(typeof A=="string")?A.split(" "):$splat(A);
return A.map(function(C){C=String(C);var B=false;Fx.CSS.Parsers.each(function(F,E){if(B){return ;}var D=F.parse(C);if($chk(D)){B={value:D,parser:F};}});
B=B||{value:C,parser:Fx.CSS.Parsers.String};return B;});},compute:function(D,C,B){var A=[];(Math.min(D.length,C.length)).times(function(E){A.push({value:D[E].parser.compute(D[E].value,C[E].value,B),parser:D[E].parser});
});A.$family={name:"fx:css:value"};return A;},serve:function(C,B){if($type(C)!="fx:css:value"){C=this.parse(C);}var A=[];C.each(function(D){A=A.concat(D.parser.serve(D.value,B));
});return A;},render:function(A,D,C,B){A.setStyle(D,this.serve(C,B));},search:function(A){if(Fx.CSS.Cache[A]){return Fx.CSS.Cache[A];}var B={};Array.each(document.styleSheets,function(E,D){var C=E.href;
if(C&&C.contains("://")&&!C.contains(document.domain)){return ;}var F=E.rules||E.cssRules;Array.each(F,function(I,G){if(!I.style){return ;}var H=(I.selectorText)?I.selectorText.replace(/^\w+/,function(J){return J.toLowerCase();
}):null;if(!H||!H.test("^"+A+"$")){return ;}Element.Styles.each(function(K,J){if(!I.style[J]||Element.ShortStyles[J]){return ;}K=String(I.style[J]);B[J]=(K.test(/^rgb/))?K.rgbToHex():K;
});});});return Fx.CSS.Cache[A]=B;}});Fx.CSS.Cache={};Fx.CSS.Parsers=new Hash({Color:{parse:function(A){if(A.match(/^#[0-9a-f]{3,6}$/i)){return A.hexToRgb(true);
}return((A=A.match(/(\d+),\s*(\d+),\s*(\d+)/)))?[A[1],A[2],A[3]]:false;},compute:function(C,B,A){return C.map(function(E,D){return Math.round(Fx.compute(C[D],B[D],A));
});},serve:function(A){return A.map(Number);}},Number:{parse:parseFloat,compute:Fx.compute,serve:function(B,A){return(A)?B+A:B;}},String:{parse:$lambda(false),compute:$arguments(1),serve:$arguments(0)}});
Fx.Tween=new Class({Extends:Fx.CSS,initialize:function(B,A){this.element=this.subject=$(B);this.parent(A);},set:function(B,A){if(arguments.length==1){A=B;
B=this.property||this.options.property;}this.render(this.element,B,A,this.options.unit);return this;},start:function(C,E,D){if(!this.check(arguments.callee,C,E,D)){return this;
}var B=Array.flatten(arguments);this.property=this.options.property||B.shift();var A=this.prepare(this.element,this.property,B);return this.parent(A.from,A.to);
}});Element.Properties.tween={set:function(A){var B=this.retrieve("tween");if(B){B.cancel();}return this.eliminate("tween").store("tween:options",$extend({link:"cancel"},A));
},get:function(A){if(A||!this.retrieve("tween")){if(A||!this.retrieve("tween:options")){this.set("tween",A);}this.store("tween",new Fx.Tween(this,this.retrieve("tween:options")));
}return this.retrieve("tween");}};Element.implement({tween:function(A,C,B){this.get("tween").start(arguments);return this;},fade:function(C){var E=this.get("tween"),D="opacity",A;
C=$pick(C,"toggle");switch(C){case"in":E.start(D,1);break;case"out":E.start(D,0);break;case"show":E.set(D,1);break;case"hide":E.set(D,0);break;case"toggle":var B=this.retrieve("fade:flag",this.get("opacity")==1);
E.start(D,(B)?0:1);this.store("fade:flag",!B);A=true;break;default:E.start(D,arguments);}if(!A){this.eliminate("fade:flag");}return this;},highlight:function(C,A){if(!A){A=this.retrieve("highlight:original",this.getStyle("background-color"));
A=(A=="transparent")?"#fff":A;}var B=this.get("tween");B.start("background-color",C||"#ffff88",A).chain(function(){this.setStyle("background-color",this.retrieve("highlight:original"));
B.callChain();}.bind(this));return this;}});Fx.Morph=new Class({Extends:Fx.CSS,initialize:function(B,A){this.element=this.subject=$(B);this.parent(A);},set:function(A){if(typeof A=="string"){A=this.search(A);
}for(var B in A){this.render(this.element,B,A[B],this.options.unit);}return this;},compute:function(E,D,C){var A={};for(var B in E){A[B]=this.parent(E[B],D[B],C);
}return A;},start:function(B){if(!this.check(arguments.callee,B)){return this;}if(typeof B=="string"){B=this.search(B);}var E={},D={};for(var C in B){var A=this.prepare(this.element,C,B[C]);
E[C]=A.from;D[C]=A.to;}return this.parent(E,D);}});Element.Properties.morph={set:function(A){var B=this.retrieve("morph");if(B){B.cancel();}return this.eliminate("morph").store("morph:options",$extend({link:"cancel"},A));
},get:function(A){if(A||!this.retrieve("morph")){if(A||!this.retrieve("morph:options")){this.set("morph",A);}this.store("morph",new Fx.Morph(this,this.retrieve("morph:options")));
}return this.retrieve("morph");}};Element.implement({morph:function(A){this.get("morph").start(A);return this;}});(function(){var A=Fx.prototype.initialize;
Fx.prototype.initialize=function(B){A.call(this,B);var C=this.options.transition;if(typeof C=="string"&&(C=C.split(":"))){var D=Fx.Transitions;D=D[C[0]]||D[C[0].capitalize()];
if(C[1]){D=D["ease"+C[1].capitalize()+(C[2]?C[2].capitalize():"")];}this.options.transition=D;}};})();Fx.Transition=function(B,A){A=$splat(A);return $extend(B,{easeIn:function(C){return B(C,A);
},easeOut:function(C){return 1-B(1-C,A);},easeInOut:function(C){return(C<=0.5)?B(2*C,A)/2:(2-B(2*(1-C),A))/2;}});};Fx.Transitions=new Hash({linear:$arguments(0)});
Fx.Transitions.extend=function(A){for(var B in A){Fx.Transitions[B]=new Fx.Transition(A[B]);}};Fx.Transitions.extend({Pow:function(B,A){return Math.pow(B,A[0]||6);
},Expo:function(A){return Math.pow(2,8*(A-1));},Circ:function(A){return 1-Math.sin(Math.acos(A));},Sine:function(A){return 1-Math.sin((1-A)*Math.PI/2);
},Back:function(B,A){A=A[0]||1.618;return Math.pow(B,2)*((A+1)*B-A);},Bounce:function(D){var C;for(var B=0,A=1;1;B+=A,A/=2){if(D>=(7-4*B)/11){C=-Math.pow((11-6*B-11*D)/4,2)+A*A;
break;}}return C;},Elastic:function(B,A){return Math.pow(2,10*--B)*Math.cos(20*B*Math.PI*(A[0]||1)/3);}});["Quad","Cubic","Quart","Quint"].each(function(B,A){Fx.Transitions[B]=new Fx.Transition(function(C){return Math.pow(C,[A+2]);
});});var Request=new Class({Implements:[Chain,Events,Options],options:{url:"",data:"",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",isSuccess:null,emulation:true,urlEncoded:true,encoding:"utf-8",evalScripts:false,evalResponse:false},initialize:function(A){this.xhr=new Browser.Request();
this.setOptions(A);this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.headers=new Hash(this.options.headers);},onStateChange:function(){if(this.xhr.readyState!=4||!this.running){return ;
}this.running=false;this.status=0;$try(function(){this.status=this.xhr.status;}.bind(this));if(this.options.isSuccess.call(this,this.status)){this.response={text:this.xhr.responseText,xml:this.xhr.responseXML};
this.success(this.response.text,this.response.xml);}else{this.response={text:null,xml:null};this.failure();}this.xhr.onreadystatechange=$empty;},isSuccess:function(){return((this.status>=200)&&(this.status<300));
},processScripts:function(A){if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){return $exec(A);}return A.stripScripts(this.options.evalScripts);
},success:function(B,A){this.onSuccess(this.processScripts(B),A);},onSuccess:function(){this.fireEvent("complete",arguments).fireEvent("success",arguments).callChain();
},failure:function(){this.onFailure();},onFailure:function(){this.fireEvent("complete").fireEvent("failure",this.xhr);},setHeader:function(A,B){this.headers.set(A,B);
return this;},getHeader:function(A){return $try(function(){return this.xhr.getResponseHeader(A);}.bind(this));},check:function(A){if(!this.running){return true;
}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(A.bind(this,Array.slice(arguments,1)));return false;}return false;
},send:function(I){if(!this.check(arguments.callee,I)){return this;}this.running=true;var G=$type(I);if(G=="string"||G=="element"){I={data:I};}var D=this.options;
I=$extend({data:D.data,url:D.url,method:D.method},I);var E=I.data,B=I.url,A=I.method;switch($type(E)){case"element":E=$(E).toQueryString();break;case"object":case"hash":E=Hash.toQueryString(E);
}if(this.options.format){var H="format="+this.options.format;E=(E)?H+"&"+E:H;}if(this.options.emulation&&["put","delete"].contains(A)){var F="_method="+A;
E=(E)?F+"&"+E:F;A="post";}if(this.options.urlEncoded&&A=="post"){var C=(this.options.encoding)?"; charset="+this.options.encoding:"";this.headers.set("Content-type","application/x-www-form-urlencoded"+C);
}if(E&&A=="get"){B=B+(B.contains("?")?"&":"?")+E;E=null;}this.xhr.open(A.toUpperCase(),B,this.options.async);this.xhr.onreadystatechange=this.onStateChange.bind(this);
this.headers.each(function(K,J){if(!$try(function(){this.xhr.setRequestHeader(J,K);return true;}.bind(this))){this.fireEvent("exception",[J,K]);}},this);
this.fireEvent("request");this.xhr.send(E);if(!this.options.async){this.onStateChange();}return this;},cancel:function(){if(!this.running){return this;
}this.running=false;this.xhr.abort();this.xhr.onreadystatechange=$empty;this.xhr=new Browser.Request();this.fireEvent("cancel");return this;}});(function(){var A={};
["get","post","put","delete","GET","POST","PUT","DELETE"].each(function(B){A[B]=function(){var C=Array.link(arguments,{url:String.type,data:$defined});
return this.send($extend(C,{method:B.toLowerCase()}));};});Request.implement(A);})();Element.Properties.send={set:function(A){var B=this.retrieve("send");
if(B){B.cancel();}return this.eliminate("send").store("send:options",$extend({data:this,link:"cancel",method:this.get("method")||"post",url:this.get("action")},A));
},get:function(A){if(A||!this.retrieve("send")){if(A||!this.retrieve("send:options")){this.set("send",A);}this.store("send",new Request(this.retrieve("send:options")));
}return this.retrieve("send");}};Element.implement({send:function(A){var B=this.get("send");B.send({data:this,url:A||B.options.url});return this;}});Request.HTML=new Class({Extends:Request,options:{update:false,evalScripts:true,filter:false},processHTML:function(C){var B=C.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
C=(B)?B[1]:C;var A=new Element("div");return $try(function(){var D="<root>"+C+"</root>",G;if(Browser.Engine.trident){G=new ActiveXObject("Microsoft.XMLDOM");
G.async=false;G.loadXML(D);}else{G=new DOMParser().parseFromString(D,"text/xml");}D=G.getElementsByTagName("root")[0];for(var F=0,E=D.childNodes.length;
F<E;F++){var H=Element.clone(D.childNodes[F],true,true);if(H){A.grab(H);}}return A;})||A.set("html",C);},success:function(D){var C=this.options,B=this.response;
B.html=D.stripScripts(function(E){B.javascript=E;});var A=this.processHTML(B.html);B.tree=A.childNodes;B.elements=A.getElements("*");if(C.filter){B.tree=B.elements.filter(C.filter);
}if(C.update){$(C.update).empty().adopt(B.tree);}if(C.evalScripts){$exec(B.javascript);}this.onSuccess(B.tree,B.elements,B.html,B.javascript);}});Element.Properties.load={set:function(A){var B=this.retrieve("load");
if(B){send.cancel();}return this.eliminate("load").store("load:options",$extend({data:this,link:"cancel",update:this,method:"get"},A));},get:function(A){if(A||!this.retrieve("load")){if(A||!this.retrieve("load:options")){this.set("load",A);
}this.store("load",new Request.HTML(this.retrieve("load:options")));}return this.retrieve("load");}};Element.implement({load:function(){this.get("load").send(Array.link(arguments,{data:Object.type,url:String.type}));
return this;}});Request.JSON=new Class({Extends:Request,options:{secure:true},initialize:function(A){this.parent(A);this.headers.extend({Accept:"application/json","X-Request":"JSON"});
},success:function(A){this.response.json=JSON.decode(A,this.options.secure);this.onSuccess(this.response.json,A);}});
/*
Script: Assets.js
  Provides methods to dynamically load JavaScript, CSS, and Image files into the document.
 
License:
  MIT-style license.
*/
 
var Asset = new Hash({
 
  javascript: function(source, properties){
    properties = $extend({
      onload: $empty,
      document: document,
      check: $lambda(true)
    }, properties);
    
    var script = new Element('script', {'src': source, 'type': 'text/javascript'});
    
    var load = properties.onload.bind(script), check = properties.check, doc = properties.document;
    delete properties.onload; delete properties.check; delete properties.document;
    
    script.addEvents({
      load: load,
      readystatechange: function(){
        if (['loaded', 'complete'].contains(this.readyState)) load();
      }
    }).setProperties(properties);
    
    
    if (Browser.Engine.webkit419) var checker = (function(){
      if (!$try(check)) return;
      $clear(checker);
      load();
    }).periodical(50);
    
    return script.inject(doc.head);
  },
 
  css: function(source, properties){
    return new Element('link', $merge({
      'rel': 'stylesheet', 'media': 'screen', 'type': 'text/css', 'href': source
    }, properties)).inject(document.head);
  },
 
  image: function(source, properties){
    properties = $merge({
      'onload': $empty,
      'onabort': $empty,
      'onerror': $empty
    }, properties);
    var image = new Image();
    var element = $(image) || new Element('img');
    ['load', 'abort', 'error'].each(function(name){
      var type = 'on' + name;
      var event = properties[type];
      delete properties[type];
      image[type] = function(){
        if (!image) return;
        if (!element.parentNode){
          element.width = image.width;
          element.height = image.height;
        }
        image = image.onload = image.onabort = image.onerror = null;
        event.delay(1, element, element);
        element.fireEvent(name, element, 1);
      };
    });
    image.src = element.src = source;
    if (image && image.complete) image.onload.delay(1);
    return element.setProperties(properties);
  },
 
  images: function(sources, options){
    options = $merge({
      onComplete: $empty,
      onProgress: $empty
    }, options);
    if (!sources.push) sources = [sources];
    var images = [];
    var counter = 0;
    sources.each(function(source){
      var img = new Asset.image(source, {
        'onload': function(){
          options.onProgress.call(this, counter, sources.indexOf(source));
          counter++;
          if (counter == sources.length) options.onComplete();
        }
      });
      images.push(img);
    });
    return new Elements(images);
  }
 
});//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License.
// For more usage information please visit: http://docs.mootools.net/Plugins/Accordion
Fx.Elements=new Class({Extends:Fx.CSS,initialize:function(B,A){this.elements=this.subject=$$(B);this.parent(A);},compute:function(G,H,I){var C={};for(var D in G){var A=G[D],E=H[D],F=C[D]={};
for(var B in A){F[B]=this.parent(A[B],E[B],I);}}return C;},set:function(B){for(var C in B){var A=B[C];for(var D in A){this.render(this.elements[C],D,A[D],this.options.unit);
}}return this;},start:function(C){if(!this.check(arguments.callee,C)){return this;}var H={},I={};for(var D in C){var F=C[D],A=H[D]={},G=I[D]={};for(var B in F){var E=this.prepare(this.elements[D],B,F[B]);
A[B]=E.from;G[B]=E.to;}}return this.parent(H,I);}});var Accordion=new Class({Extends:Fx.Elements,options:{display:0,show:false,height:true,width:false,opacity:true,fixedHeight:false,fixedWidth:false,wait:false,alwaysHide:false},initialize:function(){var C=Array.link(arguments,{container:Element.type,options:Object.type,togglers:$defined,elements:$defined});
this.parent(C.elements,C.options);this.togglers=$$(C.togglers);this.container=$(C.container);this.previous=-1;if(this.options.alwaysHide){this.options.wait=true;
}if($chk(this.options.show)){this.options.display=false;this.previous=this.options.show;}if(this.options.start){this.options.display=false;this.options.show=false;
}this.effects={};if(this.options.opacity){this.effects.opacity="fullOpacity";}if(this.options.width){this.effects.width=this.options.fixedWidth?"fullWidth":"offsetWidth";
}if(this.options.height){this.effects.height=this.options.fixedHeight?"fullHeight":"scrollHeight";}for(var B=0,A=this.togglers.length;B<A;B++){this.addSection(this.togglers[B],this.elements[B]);
}this.elements.each(function(E,D){if(this.options.show===D){this.fireEvent("active",[this.togglers[D],E]);}else{for(var F in this.effects){E.setStyle(F,0);
}}},this);if($chk(this.options.display)){this.display(this.options.display);}},addSection:function(E,C,G){E=$(E);C=$(C);var F=this.togglers.contains(E);
var B=this.togglers.length;this.togglers.include(E);this.elements.include(C);if(B&&(!F||G)){G=$pick(G,B-1);E.inject(this.togglers[G],"before");C.inject(E,"after");
}else{if(this.container&&!F){E.inject(this.container);C.inject(this.container);}}var A=this.togglers.indexOf(E);E.addEvent("click",this.display.bind(this,A));
if(this.options.height){C.setStyles({"padding-top":0,"border-top":"none","padding-bottom":0,"border-bottom":"none"});}if(this.options.width){C.setStyles({"padding-left":0,"border-left":"none","padding-right":0,"border-right":"none"});
}C.fullOpacity=1;if(this.options.fixedWidth){C.fullWidth=this.options.fixedWidth;}if(this.options.fixedHeight){C.fullHeight=this.options.fixedHeight;}C.setStyle("overflow","hidden");
if(!F){for(var D in this.effects){C.setStyle(D,0);}}return this;},display:function(A){A=($type(A)=="element")?this.elements.indexOf(A):A;if((this.timer&&this.options.wait)||(A===this.previous&&!this.options.alwaysHide)){return this;
}this.previous=A;var B={};this.elements.each(function(E,D){B[D]={};var C=(D!=A)||(this.options.alwaysHide&&(E.offsetHeight>0));this.fireEvent(C?"background":"active",[this.togglers[D],E]);
for(var F in this.effects){B[D][F]=C?0:E[this.effects[F]];}},this);return this.start(B);}});//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

Fx.Scroll=new Class({Extends:Fx,options:{offset:{x:0,y:0},wheelStops:true},initialize:function(B,A){this.element=this.subject=$(B);this.parent(A);var D=this.cancel.bind(this,false);
if($type(this.element)!="element"){this.element=$(this.element.getDocument().body);}var C=this.element;if(this.options.wheelStops){this.addEvent("start",function(){C.addEvent("mousewheel",D);
},true);this.addEvent("complete",function(){C.removeEvent("mousewheel",D);},true);}},set:function(){var A=Array.flatten(arguments);this.element.scrollTo(A[0],A[1]);
},compute:function(E,D,C){var B=[];var A=2;A.times(function(F){B.push(Fx.compute(E[F],D[F],C));});return B;},start:function(C,H){if(!this.check(arguments.callee,C,H)){return this;
}var E=this.element.getSize(),F=this.element.getScrollSize();var B=this.element.getScroll(),D={x:C,y:H};for(var G in D){var A=F[G]-E[G];if($chk(D[G])){D[G]=($type(D[G])=="number")?D[G].limit(0,A):A;
}else{D[G]=B[G];}D[G]+=this.options.offset[G];}return this.parent([B.x,B.y],[D.x,D.y]);},toTop:function(){return this.start(false,0);},toLeft:function(){return this.start(0,false);
},toRight:function(){return this.start("right",false);},toBottom:function(){return this.start(false,"bottom");},toElement:function(B){var A=$(B).getPosition(this.element);
return this.start(A.x,A.y);}});//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

var Drag=new Class({Implements:[Events,Options],options:{snap:6,unit:"px",grid:false,style:true,limit:false,handle:false,invert:false,preventDefault:false,modifiers:{x:"left",y:"top"}},initialize:function(){var B=Array.link(arguments,{options:Object.type,element:$defined});
this.element=$(B.element);this.document=this.element.getDocument();this.setOptions(B.options||{});var A=$type(this.options.handle);this.handles=(A=="array"||A=="collection")?$$(this.options.handle):$(this.options.handle)||this.element;
this.mouse={now:{},pos:{}};this.value={start:{},now:{}};this.selection=(Browser.Engine.trident)?"selectstart":"mousedown";this.bound={start:this.start.bind(this),check:this.check.bind(this),drag:this.drag.bind(this),stop:this.stop.bind(this),cancel:this.cancel.bind(this),eventStop:$lambda(false)};
this.attach();},attach:function(){this.handles.addEvent("mousedown",this.bound.start);return this;},detach:function(){this.handles.removeEvent("mousedown",this.bound.start);
return this;},start:function(C){if(this.options.preventDefault){C.preventDefault();}this.fireEvent("beforeStart",this.element);this.mouse.start=C.page;
var A=this.options.limit;this.limit={x:[],y:[]};for(var D in this.options.modifiers){if(!this.options.modifiers[D]){continue;}if(this.options.style){this.value.now[D]=this.element.getStyle(this.options.modifiers[D]).toInt();
}else{this.value.now[D]=this.element[this.options.modifiers[D]];}if(this.options.invert){this.value.now[D]*=-1;}this.mouse.pos[D]=C.page[D]-this.value.now[D];
if(A&&A[D]){for(var B=2;B--;B){if($chk(A[D][B])){this.limit[D][B]=$lambda(A[D][B])();}}}}if($type(this.options.grid)=="number"){this.options.grid={x:this.options.grid,y:this.options.grid};
}this.document.addEvents({mousemove:this.bound.check,mouseup:this.bound.cancel});this.document.addEvent(this.selection,this.bound.eventStop);},check:function(A){if(this.options.preventDefault){A.preventDefault();
}var B=Math.round(Math.sqrt(Math.pow(A.page.x-this.mouse.start.x,2)+Math.pow(A.page.y-this.mouse.start.y,2)));if(B>this.options.snap){this.cancel();this.document.addEvents({mousemove:this.bound.drag,mouseup:this.bound.stop});
this.fireEvent("start",this.element).fireEvent("snap",this.element);}},drag:function(A){if(this.options.preventDefault){A.preventDefault();}this.mouse.now=A.page;
for(var B in this.options.modifiers){if(!this.options.modifiers[B]){continue;}this.value.now[B]=this.mouse.now[B]-this.mouse.pos[B];if(this.options.invert){this.value.now[B]*=-1;
}if(this.options.limit&&this.limit[B]){if($chk(this.limit[B][1])&&(this.value.now[B]>this.limit[B][1])){this.value.now[B]=this.limit[B][1];}else{if($chk(this.limit[B][0])&&(this.value.now[B]<this.limit[B][0])){this.value.now[B]=this.limit[B][0];
}}}if(this.options.grid[B]){this.value.now[B]-=(this.value.now[B]%this.options.grid[B]);}if(this.options.style){this.element.setStyle(this.options.modifiers[B],this.value.now[B]+this.options.unit);
}else{this.element[this.options.modifiers[B]]=this.value.now[B];}}this.fireEvent("drag",this.element);},cancel:function(A){this.document.removeEvent("mousemove",this.bound.check);
this.document.removeEvent("mouseup",this.bound.cancel);if(A){this.document.removeEvent(this.selection,this.bound.eventStop);this.fireEvent("cancel",this.element);
}},stop:function(A){this.document.removeEvent(this.selection,this.bound.eventStop);this.document.removeEvent("mousemove",this.bound.drag);this.document.removeEvent("mouseup",this.bound.stop);
if(A){this.fireEvent("complete",this.element);}}});Element.implement({makeResizable:function(A){return new Drag(this,$merge({modifiers:{x:"width",y:"height"}},A));
}});var Slider=new Class({Implements:[Events,Options],options:{onTick:function(A){if(this.options.snap){A=this.toPosition(this.step);}this.knob.setStyle(this.property,A);
},snap:false,offset:0,range:false,wheel:false,steps:100,mode:"horizontal"},initialize:function(E,A,D){this.setOptions(D);this.element=$(E);this.knob=$(A);
this.previousChange=this.previousEnd=this.step=-1;this.element.addEvent("mousedown",this.clickedElement.bind(this));if(this.options.wheel){this.element.addEvent("mousewheel",this.scrolledElement.bindWithEvent(this));
}var F,B={},C={x:false,y:false};switch(this.options.mode){case"vertical":this.axis="y";this.property="top";F="offsetHeight";break;case"horizontal":this.axis="x";
this.property="left";F="offsetWidth";}this.half=this.knob[F]/2;this.full=this.element[F]-this.knob[F]+(this.options.offset*2);this.min=$chk(this.options.range[0])?this.options.range[0]:0;
this.max=$chk(this.options.range[1])?this.options.range[1]:this.options.steps;this.range=this.max-this.min;this.steps=this.options.steps||this.full;this.stepSize=Math.abs(this.range)/this.steps;
this.stepWidth=this.stepSize*this.full/Math.abs(this.range);this.knob.setStyle("position","relative").setStyle(this.property,-this.options.offset);C[this.axis]=this.property;
B[this.axis]=[-this.options.offset,this.full-this.options.offset];this.drag=new Drag(this.knob,{snap:0,limit:B,modifiers:C,onDrag:this.draggedKnob.bind(this),onStart:this.draggedKnob.bind(this),onComplete:function(){this.draggedKnob();
this.end();}.bind(this)});if(this.options.snap){this.drag.options.grid=Math.ceil(this.stepWidth);this.drag.options.limit[this.axis][1]=this.full;}},set:function(A){if(!((this.range>0)^(A<this.min))){A=this.min;
}if(!((this.range>0)^(A>this.max))){A=this.max;}this.step=Math.round(A);this.checkStep();this.end();this.fireEvent("tick",this.toPosition(this.step));return this;
},clickedElement:function(C){var B=this.range<0?-1:1;var A=C.page[this.axis]-this.element.getPosition()[this.axis]-this.half;A=A.limit(-this.options.offset,this.full-this.options.offset);
this.step=Math.round(this.min+B*this.toStep(A));this.checkStep();this.end();this.fireEvent("tick",A);},scrolledElement:function(A){var B=(this.options.mode=="horizontal")?(A.wheel<0):(A.wheel>0);
this.set(B?this.step-this.stepSize:this.step+this.stepSize);A.stop();},draggedKnob:function(){var B=this.range<0?-1:1;var A=this.drag.value.now[this.axis];
A=A.limit(-this.options.offset,this.full-this.options.offset);this.step=Math.round(this.min+B*this.toStep(A));this.checkStep();},checkStep:function(){if(this.previousChange!=this.step){this.previousChange=this.step;
this.fireEvent("change",this.step);}},end:function(){if(this.previousEnd!==this.step){this.previousEnd=this.step;this.fireEvent("complete",this.step+"");
}},toStep:function(A){var B=(A+this.options.offset)*this.stepSize/this.full*this.steps;return this.options.steps?Math.round(B-=B%this.stepSize):B;},toPosition:function(A){return(this.full*Math.abs(this.min-A))/(this.steps*this.stepSize)-this.options.offset;
}});var swfobject = function() { var D = "undefined", r = "object", S = "Shockwave Flash", W = "ShockwaveFlash.ShockwaveFlash", q = "application/x-shockwave-flash", R = "SWFObjectExprInst", x = "onreadystatechange", O = window, j = document, t = navigator, T = false, U = [h], o = [], N = [], I = [], l, Q, E, B, J = false, a = false, n, G, m = true, M = function() { var aa = typeof j.getElementById != D && typeof j.getElementsByTagName != D && typeof j.createElement != D, ah = t.userAgent.toLowerCase(), Y = t.platform.toLowerCase(), ae = Y ? /win/.test(Y) : /win/.test(ah), ac = Y ? /mac/.test(Y) : /mac/.test(ah), af = /webkit/.test(ah) ? parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, X = ! +"\v1", ag = [0, 0, 0], ab = null; if (typeof t.plugins != D && typeof t.plugins[S] == r) { ab = t.plugins[S].description; if (ab && !(typeof t.mimeTypes != D && t.mimeTypes[q] && !t.mimeTypes[q].enabledPlugin)) { T = true; X = false; ab = ab.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); ag[0] = parseInt(ab.replace(/^(.*)\..*$/, "$1"), 10); ag[1] = parseInt(ab.replace(/^.*\.(.*)\s.*$/, "$1"), 10); ag[2] = /[a-zA-Z]/.test(ab) ? parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0 } } else { if (typeof O.ActiveXObject != D) { try { var ad = new ActiveXObject(W); if (ad) { ab = ad.GetVariable("$version"); if (ab) { X = true; ab = ab.split(" ")[1].split(","); ag = [parseInt(ab[0], 10), parseInt(ab[1], 10), parseInt(ab[2], 10)] } } } catch (Z) { } } } return { w3: aa, pv: ag, wk: af, ie: X, win: ae, mac: ac} } (), k = function() { if (!M.w3) { return } if ((typeof j.readyState != D && j.readyState == "complete") || (typeof j.readyState == D && (j.getElementsByTagName("body")[0] || j.body))) { f() } if (!J) { if (typeof j.addEventListener != D) { j.addEventListener("DOMContentLoaded", f, false) } if (M.ie && M.win) { j.attachEvent(x, function() { if (j.readyState == "complete") { j.detachEvent(x, arguments.callee); f() } }); if (O == top) { (function() { if (J) { return } try { j.documentElement.doScroll("left") } catch (X) { setTimeout(arguments.callee, 0); return } f() })() } } if (M.wk) { (function() { if (J) { return } if (!/loaded|complete/.test(j.readyState)) { setTimeout(arguments.callee, 0); return } f() })() } s(f) } } (); function f() { if (J) { return } try { var Z = j.getElementsByTagName("body")[0].appendChild(C("span")); Z.parentNode.removeChild(Z) } catch (aa) { return } J = true; var X = U.length; for (var Y = 0; Y < X; Y++) { U[Y]() } } function K(X) { if (J) { X() } else { U[U.length] = X } } function s(Y) { if (typeof O.addEventListener != D) { O.addEventListener("load", Y, false) } else { if (typeof j.addEventListener != D) { j.addEventListener("load", Y, false) } else { if (typeof O.attachEvent != D) { i(O, "onload", Y) } else { if (typeof O.onload == "function") { var X = O.onload; O.onload = function() { X(); Y() } } else { O.onload = Y } } } } } function h() { if (T) { V() } else { H() } } function V() { var X = j.getElementsByTagName("body")[0]; var aa = C(r); aa.setAttribute("type", q); var Z = X.appendChild(aa); if (Z) { var Y = 0; (function() { if (typeof Z.GetVariable != D) { var ab = Z.GetVariable("$version"); if (ab) { ab = ab.split(" ")[1].split(","); M.pv = [parseInt(ab[0], 10), parseInt(ab[1], 10), parseInt(ab[2], 10)] } } else { if (Y < 10) { Y++; setTimeout(arguments.callee, 10); return } } X.removeChild(aa); Z = null; H() })() } else { H() } } function H() { var ag = o.length; if (ag > 0) { for (var af = 0; af < ag; af++) { var Y = o[af].id; var ab = o[af].callbackFn; var aa = { success: false, id: Y }; if (M.pv[0] > 0) { var ae = c(Y); if (ae) { if (F(o[af].swfVersion) && !(M.wk && M.wk < 312)) { w(Y, true); if (ab) { aa.success = true; aa.ref = z(Y); ab(aa) } } else { if (o[af].expressInstall && A()) { var ai = {}; ai.data = o[af].expressInstall; ai.width = ae.getAttribute("width") || "0"; ai.height = ae.getAttribute("height") || "0"; if (ae.getAttribute("class")) { ai.styleclass = ae.getAttribute("class") } if (ae.getAttribute("align")) { ai.align = ae.getAttribute("align") } var ah = {}; var X = ae.getElementsByTagName("param"); var ac = X.length; for (var ad = 0; ad < ac; ad++) { if (X[ad].getAttribute("name").toLowerCase() != "movie") { ah[X[ad].getAttribute("name")] = X[ad].getAttribute("value") } } P(ai, ah, Y, ab) } else { p(ae); if (ab) { ab(aa) } } } } } else { w(Y, true); if (ab) { var Z = z(Y); if (Z && typeof Z.SetVariable != D) { aa.success = true; aa.ref = Z } ab(aa) } } } } } function z(aa) { var X = null; var Y = c(aa); if (Y && Y.nodeName == "OBJECT") { if (typeof Y.SetVariable != D) { X = Y } else { var Z = Y.getElementsByTagName(r)[0]; if (Z) { X = Z } } } return X } function A() { return !a && F("6.0.65") && (M.win || M.mac) && !(M.wk && M.wk < 312) } function P(aa, ab, X, Z) { a = true; E = Z || null; B = { success: false, id: X }; var ae = c(X); if (ae) { if (ae.nodeName == "OBJECT") { l = g(ae); Q = null } else { l = ae; Q = X } aa.id = R; if (typeof aa.width == D || (!/%$/.test(aa.width) && parseInt(aa.width, 10) < 310)) { aa.width = "310" } if (typeof aa.height == D || (!/%$/.test(aa.height) && parseInt(aa.height, 10) < 137)) { aa.height = "137" } j.title = j.title.slice(0, 47) + " - Flash Player Installation"; var ad = M.ie && M.win ? "ActiveX" : "PlugIn", ac = "MMredirectURL=" + O.location.toString().replace(/&/g, "%26") + "&MMplayerType=" + ad + "&MMdoctitle=" + j.title; if (typeof ab.flashvars != D) { ab.flashvars += "&" + ac } else { ab.flashvars = ac } if (M.ie && M.win && ae.readyState != 4) { var Y = C("div"); X += "SWFObjectNew"; Y.setAttribute("id", X); ae.parentNode.insertBefore(Y, ae); ae.style.display = "none"; (function() { if (ae.readyState == 4) { ae.parentNode.removeChild(ae) } else { setTimeout(arguments.callee, 10) } })() } u(aa, ab, X) } } function p(Y) { if (M.ie && M.win && Y.readyState != 4) { var X = C("div"); Y.parentNode.insertBefore(X, Y); X.parentNode.replaceChild(g(Y), X); Y.style.display = "none"; (function() { if (Y.readyState == 4) { Y.parentNode.removeChild(Y) } else { setTimeout(arguments.callee, 10) } })() } else { Y.parentNode.replaceChild(g(Y), Y) } } function g(ab) { var aa = C("div"); if (M.win && M.ie) { aa.innerHTML = ab.innerHTML } else { var Y = ab.getElementsByTagName(r)[0]; if (Y) { var ad = Y.childNodes; if (ad) { var X = ad.length; for (var Z = 0; Z < X; Z++) { if (!(ad[Z].nodeType == 1 && ad[Z].nodeName == "PARAM") && !(ad[Z].nodeType == 8)) { aa.appendChild(ad[Z].cloneNode(true)) } } } } } return aa } function u(ai, ag, Y) { var X, aa = c(Y); if (M.wk && M.wk < 312) { return X } if (aa) { if (typeof ai.id == D) { ai.id = Y } if (M.ie && M.win) { var ah = ""; for (var ae in ai) { if (ai[ae] != Object.prototype[ae]) { if (ae.toLowerCase() == "data") { ag.movie = ai[ae] } else { if (ae.toLowerCase() == "styleclass") { ah += ' class="' + ai[ae] + '"' } else { if (ae.toLowerCase() != "classid") { ah += " " + ae + '="' + ai[ae] + '"' } } } } } var af = ""; for (var ad in ag) { if (ag[ad] != Object.prototype[ad]) { af += '<param name="' + ad + '" value="' + ag[ad] + '" />' } } aa.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + ah + ">" + af + "</object>"; N[N.length] = ai.id; X = c(ai.id) } else { var Z = C(r); Z.setAttribute("type", q); for (var ac in ai) { if (ai[ac] != Object.prototype[ac]) { if (ac.toLowerCase() == "styleclass") { Z.setAttribute("class", ai[ac]) } else { if (ac.toLowerCase() != "classid") { Z.setAttribute(ac, ai[ac]) } } } } for (var ab in ag) { if (ag[ab] != Object.prototype[ab] && ab.toLowerCase() != "movie") { e(Z, ab, ag[ab]) } } aa.parentNode.replaceChild(Z, aa); X = Z } } return X } function e(Z, X, Y) { var aa = C("param"); aa.setAttribute("name", X); aa.setAttribute("value", Y); Z.appendChild(aa) } function y(Y) { var X = c(Y); if (X && X.nodeName == "OBJECT") { if (M.ie && M.win) { X.style.display = "none"; (function() { if (X.readyState == 4) { b(Y) } else { setTimeout(arguments.callee, 10) } })() } else { X.parentNode.removeChild(X) } } } function b(Z) { var Y = c(Z); if (Y) { for (var X in Y) { if (typeof Y[X] == "function") { Y[X] = null } } Y.parentNode.removeChild(Y) } } function c(Z) { var X = null; try { X = j.getElementById(Z) } catch (Y) { } return X } function C(X) { return j.createElement(X) } function i(Z, X, Y) { Z.attachEvent(X, Y); I[I.length] = [Z, X, Y] } function F(Z) { var Y = M.pv, X = Z.split("."); X[0] = parseInt(X[0], 10); X[1] = parseInt(X[1], 10) || 0; X[2] = parseInt(X[2], 10) || 0; return (Y[0] > X[0] || (Y[0] == X[0] && Y[1] > X[1]) || (Y[0] == X[0] && Y[1] == X[1] && Y[2] >= X[2])) ? true : false } function v(ac, Y, ad, ab) { if (M.ie && M.mac) { return } var aa = j.getElementsByTagName("head")[0]; if (!aa) { return } var X = (ad && typeof ad == "string") ? ad : "screen"; if (ab) { n = null; G = null } if (!n || G != X) { var Z = C("style"); Z.setAttribute("type", "text/css"); Z.setAttribute("media", X); n = aa.appendChild(Z); if (M.ie && M.win && typeof j.styleSheets != D && j.styleSheets.length > 0) { n = j.styleSheets[j.styleSheets.length - 1] } G = X } if (M.ie && M.win) { if (n && typeof n.addRule == r) { n.addRule(ac, Y) } } else { if (n && typeof j.createTextNode != D) { n.appendChild(j.createTextNode(ac + " {" + Y + "}")) } } } function w(Z, X) { if (!m) { return } var Y = X ? "visible" : "hidden"; if (J && c(Z)) { c(Z).style.visibility = Y } else { v("#" + Z, "visibility:" + Y) } } function L(Y) { var Z = /[\\\"<>\.;]/; var X = Z.exec(Y) != null; return X && typeof encodeURIComponent != D ? encodeURIComponent(Y) : Y } var d = function() { if (M.ie && M.win) { window.attachEvent("onunload", function() { var ac = I.length; for (var ab = 0; ab < ac; ab++) { I[ab][0].detachEvent(I[ab][1], I[ab][2]) } var Z = N.length; for (var aa = 0; aa < Z; aa++) { y(N[aa]) } for (var Y in M) { M[Y] = null } M = null; for (var X in swfobject) { swfobject[X] = null } swfobject = null }) } } (); return { registerObject: function(ab, X, aa, Z) { if (M.w3 && ab && X) { var Y = {}; Y.id = ab; Y.swfVersion = X; Y.expressInstall = aa; Y.callbackFn = Z; o[o.length] = Y; w(ab, false) } else { if (Z) { Z({ success: false, id: ab }) } } }, getObjectById: function(X) { if (M.w3) { return z(X) } }, embedSWF: function(ab, ah, ae, ag, Y, aa, Z, ad, af, ac) { var X = { success: false, id: ah }; if (M.w3 && !(M.wk && M.wk < 312) && ab && ah && ae && ag && Y) { w(ah, false); K(function() { ae += ""; ag += ""; var aj = {}; if (af && typeof af === r) { for (var al in af) { aj[al] = af[al] } } aj.data = ab; aj.width = ae; aj.height = ag; var am = {}; if (ad && typeof ad === r) { for (var ak in ad) { am[ak] = ad[ak] } } if (Z && typeof Z === r) { for (var ai in Z) { if (typeof am.flashvars != D) { am.flashvars += "&" + ai + "=" + Z[ai] } else { am.flashvars = ai + "=" + Z[ai] } } } if (F(Y)) { var an = u(aj, am, ah); if (aj.id == ah) { w(ah, true) } X.success = true; X.ref = an } else { if (aa && A()) { aj.data = aa; P(aj, am, ah, ac); return } else { w(ah, true) } } if (ac) { ac(X) } }) } else { if (ac) { ac(X) } } }, switchOffAutoHideShow: function() { m = false }, ua: M, getFlashPlayerVersion: function() { return { major: M.pv[0], minor: M.pv[1], release: M.pv[2]} }, hasFlashPlayerVersion: F, createSWF: function(Z, Y, X) { if (M.w3) { return u(Z, Y, X) } else { return undefined } }, showExpressInstall: function(Z, aa, X, Y) { if (M.w3 && A()) { P(Z, aa, X, Y) } }, removeSWF: function(X) { if (M.w3) { y(X) } }, createCSS: function(aa, Z, Y, X) { if (M.w3) { v(aa, Z, Y, X) } }, addDomLoadEvent: K, addLoadEvent: s, getQueryParamValue: function(aa) { var Z = j.location.search || j.location.hash; if (Z) { if (/\?/.test(Z)) { Z = Z.split("?")[1] } if (aa == null) { return L(Z) } var Y = Z.split("&"); for (var X = 0; X < Y.length; X++) { if (Y[X].substring(0, Y[X].indexOf("=")) == aa) { return L(Y[X].substring((Y[X].indexOf("=") + 1))) } } } return "" }, expressInstallCallback: function() { if (a) { var X = c(R); if (X && l) { X.parentNode.replaceChild(l, X); if (Q) { w(Q, true); if (M.ie && M.win) { l.style.display = "block" } } if (E) { E(B) } } a = false } } } } ();
if (typeof deconcept == "undefined") { var deconcept = {} } if (typeof deconcept.util == "undefined") { deconcept.util = {} } if (typeof deconcept.SWFObjectUtil == "undefined") { deconcept.SWFObjectUtil = {} } deconcept.SWFObject = function(g, d, p, k, m, o, r, l, a, e) { if (!document.getElementById) { return } this.DETECT_KEY = e ? e : "detectflash"; this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY); this.params = {}; this.variables = {}; this.attributes = []; if (g) { this.setAttribute("swf", g) } if (d) { this.setAttribute("id", d) } if (p) { this.setAttribute("width", p) } if (k) { this.setAttribute("height", k) } if (m) { this.setAttribute("version", new deconcept.PlayerVersion(m.toString().split("."))) } this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion(); if (!window.opera && document.all && this.installedVer.major > 7) { if (!deconcept.unloadSet) { deconcept.SWFObjectUtil.prepUnload = function() { __flash_unloadHandler = function() { }; __flash_savedUnloadHandler = function() { }; window.attachEvent("onunload", deconcept.SWFObjectUtil.cleanupSWFs) }; window.attachEvent("onbeforeunload", deconcept.SWFObjectUtil.prepUnload); deconcept.unloadSet = true } } if (o) { this.addParam("bgcolor", o) } var b = r ? r : "high"; this.addParam("quality", b); this.setAttribute("useExpressInstall", false); this.setAttribute("doExpressInstall", false); var n = (l) ? l : window.location; this.setAttribute("xiRedirectUrl", n); this.setAttribute("redirectUrl", ""); if (a) { this.setAttribute("redirectUrl", a) } }; deconcept.SWFObject.prototype = { useExpressInstall: function(a) { this.xiSWFPath = !a ? "expressinstall.swf" : a; this.setAttribute("useExpressInstall", true) }, setAttribute: function(a, b) { this.attributes[a] = b }, getAttribute: function(a) { return this.attributes[a] || "" }, addParam: function(a, b) { this.params[a] = b }, getParams: function() { return this.params }, addVariable: function(a, b) { this.variables[a] = b }, getVariable: function(a) { return this.variables[a] || "" }, getVariables: function() { return this.variables }, getVariablePairs: function() { var a = []; var b; var c = this.getVariables(); for (b in c) { a[a.length] = b + "=" + c[b] } return a }, getSWFHTML: function() { var d = ""; if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "PlugIn"); this.setAttribute("swf", this.xiSWFPath) } d = '<embed type="application/x-shockwave-flash" src="' + this.getAttribute("swf") + '" width="' + this.getAttribute("width") + '" height="' + this.getAttribute("height") + '" style="' + (this.getAttribute("style") || "") + '"'; d += ' id="' + this.getAttribute("id") + '" name="' + this.getAttribute("id") + '" '; var c = this.getParams(); for (var a in c) { d += [a] + '="' + c[a] + '" ' } var b = this.getVariablePairs().join("&"); if (b.length > 0) { d += 'flashvars="' + b + '"' } d += "/>" } else { if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "ActiveX"); this.setAttribute("swf", this.xiSWFPath) } d = '<object id="' + this.getAttribute("id") + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + this.getAttribute("width") + '" height="' + this.getAttribute("height") + '" style="' + (this.getAttribute("style") || "") + '">'; d += '<param name="movie" value="' + this.getAttribute("swf") + '" />'; var c = this.getParams(); for (var a in c) { d += '<param name="' + a + '" value="' + c[a] + '" />' } var b = this.getVariablePairs().join("&"); if (b.length > 0) { d += '<param name="flashvars" value="' + b + '" />' } d += "</object>" } return d }, write: function(a) { if (this.getAttribute("useExpressInstall")) { var b = new deconcept.PlayerVersion([6, 0, 65]); if (this.installedVer.versionIsValid(b) && !this.installedVer.versionIsValid(this.getAttribute("version"))) { this.setAttribute("doExpressInstall", true); this.addVariable("MMredirectURL", escape(this.getAttribute("xiRedirectUrl"))); document.title = document.title.slice(0, 47) + " - Flash Player Installation"; this.addVariable("MMdoctitle", document.title) } } if (this.skipDetect || this.getAttribute("doExpressInstall") || this.installedVer.versionIsValid(this.getAttribute("version"))) { var c = (typeof a == "string") ? document.getElementById(a) : a; c.innerHTML = this.getSWFHTML(); return true } else { if (this.getAttribute("redirectUrl") != "") { document.location.replace(this.getAttribute("redirectUrl")) } } return false } }; deconcept.SWFObjectUtil.getPlayerVersion = function() { var c = new deconcept.PlayerVersion([0, 0, 0]); if (navigator.plugins && navigator.mimeTypes.length) { var a = navigator.plugins["Shockwave Flash"]; if (a && a.description) { c = new deconcept.PlayerVersion(a.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split(".")) } } else { if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0) { var d = 1; var b = 3; while (d) { try { b++; d = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + b); c = new deconcept.PlayerVersion([b, 0, 0]) } catch (g) { d = null } } } else { try { var d = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7") } catch (g) { try { var d = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); c = new deconcept.PlayerVersion([6, 0, 21]); d.AllowScriptAccess = "always" } catch (g) { if (c.major == 6) { return c } } try { d = new ActiveXObject("ShockwaveFlash.ShockwaveFlash") } catch (g) { } } if (d != null) { c = new deconcept.PlayerVersion(d.GetVariable("$version").split(" ")[1].split(",")) } } } return c }; deconcept.PlayerVersion = function(a) { this.major = a[0] != null ? parseInt(a[0]) : 0; this.minor = a[1] != null ? parseInt(a[1]) : 0; this.rev = a[2] != null ? parseInt(a[2]) : 0 }; deconcept.PlayerVersion.prototype.versionIsValid = function(a) { if (this.major < a.major) { return false } if (this.major > a.major) { return true } if (this.minor < a.minor) { return false } if (this.minor > a.minor) { return true } if (this.rev < a.rev) { return false } return true }; deconcept.util = { getRequestParameter: function(e) { var d = document.location.search || document.location.hash; if (e == null) { return d } if (d) { var c = d.substring(1).split("&"); for (var a = 0; a < c.length; a++) { if (c[a].substring(0, c[a].indexOf("=")) == e) { var b = c[a].substring((c[a].indexOf("=") + 1)); return String.format("{0}/{1}", b.substring(0, 3), b.substring(3, 6)) } } } return "" } }; deconcept.SWFObjectUtil.cleanupSWFs = function() { var c = document.getElementsByTagName("OBJECT"); for (var b = c.length - 1; b >= 0; b--) { c[b].style.display = "none"; for (var a in c[b]) { if (typeof c[b][a] == "function") { c[b][a] = function() { } } } } }; if (!document.getElementById && document.all) { document.getElementById = function(a) { return document.all[a] } } var getQueryParamValue = deconcept.util.getRequestParameter; var FlashObject = deconcept.SWFObject; var SWFObject = deconcept.SWFObject;/******************************************************************************************************

	HOVER BUTTON
	-------------------------------------------------------------------------------------------
	searches for images with the class="hover_button" and adds event listeners to toggle over 
	and down states. 
	
	The images need be named yourImageName_off.gif, yourImageName_hover.gif, yourImageName_down.gif
	the file extension doesn't matter, just the _off. _hover. & _down.
	
	DEPENDECIES
	- mootools 1.2

******************************************************************************************************/

var hoverButton = new Class({
	initialize: function(options){
		this.options = options; //save our options.
		
		// set the properties for the object
		this.buttonElement = this.options.buttonElement;
		this.offState = this.buttonElement.src;
		this.hoverState = this.offState.replace('_off.', '_hover.');
		
		this.preloadImage([this.hoverState]);		
	},
	setState : function(newState) {
		this.buttonElement.src = newState;	
	},
	preloadImage : function(arrImagePaths) {
		var parentObject = this;
		var img = new Asset.images(arrImagePaths, { onComplete: function(){parentObject.addListeners()} });	
	},
	addListeners : function() {
		this.buttonElement.addEvent('mouseover', this.setState.pass(this.hoverState, this));
		this.buttonElement.addEvent('mouseleave', this.setState.pass(this.offState, this));
	}
});

var hoverButtonHandler = {
	arrHoverButtons : [],
	arrHoverInputs : [],
	
	init : function() {
		var arrButtons = $$('img.hover_button');
		var arrInputs = $$('input.hover_button');
	
		for (i=0; i<arrButtons.length; i++) {		
			hoverButtonHandler.arrHoverButtons[i] = new hoverButton({buttonElement: arrButtons[i]});		
		}	
		
		for (i=0; i<arrInputs.length; i++) {		
			hoverButtonHandler.arrHoverInputs[i] = new hoverButton({buttonElement: arrInputs[i]});		
		}
	}
}

window.addEvent('domready', hoverButtonHandler.init);


/******************************************************************************************************

	UTILITY NAV DROP DOWNS
	
*******************************************************************************************************/
var utilityDropNav = {	
    timeOut:100,
    closeTimer:0,
	init : function() {
		var arrNavs = $('master_container').getElements('.drop_nav');
		arrNavs.addEvent('mouseover', utilityDropNav.openNav);
		arrNavs.addEvent('mouseout', utilityDropNav.closeTime);
	},
	openNav : function() {
	    var arrNavs = $('master_container').getElements('.drop_nav');
	    arrNavs.removeClass('open');
	    utilityDropNav.cancelCloseTime();
		$(this.id).addClass('open');
	},
	cancelCloseTime : function() {
		if(utilityDropNav.closeTimer)
	    {
		    window.clearTimeout(utilityDropNav.closeTimer);
		    utilityDropNav.closeTimer = null;
	    }
	},
	closeTime : function() {
		utilityDropNav.closeTimer = window.setTimeout(String.format('utilityDropNav.closeNav("{0}")',this.id), utilityDropNav.timeOut);
	},
	closeNav : function(id) {
	    $(id).removeClass('open');
	}
}

window.addEvent('domready', utilityDropNav.init);





/******************************************************************************************************

	ACCOUNT LOGIN PANEL 
	
*******************************************************************************************************/
var accountLoginPanel = {
	triggerdByEnter: false,
	show : function(xPos, yPos) {
		var loginPanel = $('account_login_panel');
		loginPanel.setStyles({
			top: yPos,
			left: xPos,
			display: 'block'
		});
	},
	closePanel : function() {
		var loginPanel = $('account_login_panel');
		
		loginPanel.setStyle('display','none');
	},
	hideLoginInfo : function() {
		document.getElementById('userid').disabled=true;
		document.getElementById('userpass').disabled=true;
		document.getElementById('rememberme').disabled=true;	
		document.getElementById('useridLabel').style.color = "#a1b2c5";
		document.getElementById('userid').style.backgroundColor = "#a1b2c5";
		document.getElementById('userpass').style.backgroundColor = "#a1b2c5";
		document.getElementById('passLabel').style.color = "#a1b2c5";
		document.getElementById('rememberme').style.backgroundColor = "#a1b2c5";
		document.getElementById('rememberLabel').style.color = "#a1b2c5";			
	},
	showLoginInfo : function() {
		document.getElementById('userid').disabled=false;
		document.getElementById('userpass').disabled=false;
		document.getElementById('rememberme').disabled=false;
		document.getElementById('useridLabel').style.color = "#ffffff";
		document.getElementById('passLabel').style.color = "#ffffff";
		document.getElementById('userid').style.backgroundColor = "#ffffff";
		document.getElementById('userpass').style.backgroundColor = "#ffffff";
		document.getElementById('rememberme').style.backgroundColor = "#ffffff";
		document.getElementById('rememberLabel').style.color = "#ffffff";					
	}
}





/******************************************************************************************************

	POP LAYER 
	- used for the account settings pop-up
	
*******************************************************************************************************/
var popLayer = {

    popLayerFade: null,
    popLayerContent: null,
    shim: null,
    center: false,
    shimYOffset: 0,
    shimXOffset: 0,

    show: function() {
        var popLayerFade = $(popLayer.popLayerFade);
        var popLayerContent = $(popLayer.popLayerContent);
        var shim = $(popLayer.shim);

        var windowScrollSize = window.getScrollSize();
        var windowSize = window.getSize();

        popLayerContent.setStyles({
            display: 'block',
            visibility: 'hidden'
        });

        var popLayerContentSize = popLayerContent.getSize();

        popLayerFade.setStyles({
            opacity: 0.6,
            height: $('iefix').getScrollSize().y,
            display: 'block'
        });

        var popContentXPos = (windowSize.x / 2) - (popLayerContentSize.x / 2);
        var popContentYPos = (windowSize.y / 2) - (popLayerContentSize.y / 2);
        popContentYPos = (popContentYPos < 0) ? 125 : popContentYPos;

        var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
        if (isIE6) {
            popLayerContent.setStyles({
                top: popContentYPos,
                left: popContentXPos,
                visibility: 'visible'
            });

            shim.setStyles({
                top: (popLayer.center) ? popContentYPos + popLayer.shimYOffset : (125 + popLayer.shimYOffset),
                left: popContentXPos + (popLayer.shimXOffset),
                height: popLayerContentSize.y - (popLayer.shimYOffset * 2),
                display: 'block'
            });
        }
        else {
            var top = this.currentY() + Math.round(this.documentHeight() / 2) - Math.round(popLayerContent.getHeight() / 2);
            if (popLayerContent.getHeight() > this.documentHeight()) {
                top = this.currentY();
            }
            popLayerContent.setStyles({
                top: top,
                left: popContentXPos,
                visibility: 'visible',
                float: 'left'
            });
            shim.setStyles({
                top: top + (popLayer.shimYOffset),
                left: popContentXPos + (popLayer.shimXOffset),
                height: popLayerContentSize.y - (popLayer.shimYOffset * 2),
                display: 'block',
                float: 'left'
            });
        }
    },

    hide: function() {
        var popLayerFade = $(popLayer.popLayerFade);
        var popLayerContent = $(popLayer.popLayerContent);
        var shim = $(popLayer.shim);

        popLayerFade.setStyle('display', 'none');
        popLayerContent.setStyle('display', 'none');
        shim.setStyle('display', 'none');
    },
    currentY: function() {
        if (self.pageYOffset)
            return self.pageYOffset;
        else if (document.documentElement && document.documentElement.scrollTop)
            return document.documentElement.scrollTop;
        else if (document.body)
            return document.body.scrollTop;
    },
    documentHeight: function() {
        if (self.innerHeight)
            return self.innerHeight;
        else if (document.documentElement && document.documentElement.clientHeight)
            return document.documentElement.clientHeight;
        else if (document.body)
            return document.body.clientHeight;
    }
}




/******************************************************************************************************

	HOVER ROWS
	
	var yourTableReference = new HoverRows('tableID');
	
	- adds hover class to table rows on mouseover
	
*******************************************************************************************************/
var HoverRows = new Class({
    initialize: function(tableID){
    if ($(tableID) !== null)
            {
		            this.tableID = tableID;
		            this.arrRows = $(this.tableID).getElements('tr');
		            this.arrRows.addEvent('mouseover', this.toggleRow);
		            this.arrRows.addEvent('mouseout', this.toggleRow);
		    }
	},
	toggleRow: function() {
		var row = this;
		
		if (row.hasClass('hover')) {
			row.removeClass('hover');	
		}
		else {
			row.addClass('hover');	
		}
	}
})


/******************************************************************************************************

	ALL PAIRS DROP DOWN
	
*******************************************************************************************************/
var allPairsDropDown = {	
	init : function() {		
		$('all_pairs_drop_down_link').addEvent('click', allPairsDropDown.openNav);
							
		$('all_pairs_drop_down').addEvent('mouseenter', allPairsDropDown.openNav);		
		$('all_pairs_drop_down').addEvent('mouseleave', allPairsDropDown.closeNav);
		
	},
	openNav : function() {
		$('all_pairs_drop_down').addClass('open');

	},
	closeNav : function() {
		$('all_pairs_drop_down').removeClass('open');
	}
}

var TableRowsHighliter = new Class({
	initialize : function(listTable) {
		var listTableRows = $(listTable).getElements('tr');
		
		defaultChartRow = listTableRows[1];
		
		defaultChartRow.addClass('active');
		
		TableRowsHighliter.currChartRow = defaultChartRow;
		
		listTableRows.addEvent('mouseover', this.setHover);
		listTableRows.addEvent('mouseout', this.clearHover);
		listTableRows.addEvent('click', this.setActive);
	},
	
	setHover : function() {
		if(! this.hasClass('headings')) {
			this.addClass('hover');
		}
	},
	
	clearHover : function() {
		if(! this.hasClass('headings')) {
			this.removeClass('hover');
		}
	},
	
	setActive : function() {
		if(! this.hasClass('headings')) {
		TableRowsHighliter.currChartRow.removeClass('active');
		TableRowsHighliter.currChartRow = $(this.id);
		TableRowsHighliter.currChartRow.addClass('active');
	    }
	}
})

/*******************************************

added december 03

*******************************************/

function clearText(theText) 
{
    if (theText.value == theText.defaultValue)
 	{
    theText.value = ""
    }
}
		
function sms_providers(proText,example_id){

	if (proText == 'att'){
		document.getElementById(example_id).innerHTML = '1234567890@txt.att.net';
	}							
	else  if (proText == 'metropcs'){
		document.getElementById(example_id).innerHTML = '1234567890@mymetropcs.com';
	}
	else  if (proText == 'nextel'){
		document.getElementById(example_id).innerHTML = '1234567890@mymetropcs.com';
	}
	else  if (proText == 'sprint'){
		document.getElementById(example_id).innerHTML = '1234567890@messaging.sprintpcs.com';
	}				
	else if (proText == 'tmobile'){
		document.getElementById(example_id).innerHTML = '1234567890@tmomail.net';
	}			
	else if (proText == 'verizon'){
		document.getElementById(example_id).innerHTML = '1234567890@vtext.com';
	}					
	else if (proText == 'virgin'){
		document.getElementById(example_id).innerHTML = '1234567890@vmobl.com';
	}	
	
	else if (proText == 'selected'){
		document.getElementById(example_id).innerHTML = 'Select a Provider';
	}																																				
}
var BannerPlay = new Class({
    initialize: function(options) {
        this.pause = 0;
        this.ads = options.Ads;
        this.container = options.Container;
        this.counter = null;
        this.position = this.ads.length-1;
    },
    rotatenext: function() {
        if (this.counter != null) {
            clearTimeout(this.counter);
        }
        var tbl = document.getElementById(this.container);

        if (this.position == this.ads.length - 1) {
            this.position = 0;
        }
        else {
            this.position++;
        }
        tbl.innerHTML = this.ads[this.position];
        this.counter = setTimeout('rotatenext()', 10000);
        this.pause = 0;
    },
    pausebanner: function() {
        if (this.pause == 0) { clearTimeout(this.counter); this.pause = 1; } else { this.counter = setTimeout('rotatenext()', 1); this.pause = 0; }
    },
    rotateforward: function() {
        clearTimeout(this.counter);
        var tbl = document.getElementById(this.container);

        if (this.position == this.ads.length - 1) {
            this.position = 0;
        }
        else {
            this.position++;
        }
        tbl.innerHTML = this.ads[this.position];
        this.counter = setTimeout('rotatenext()', 10000);
        this.pause = 0;
    },
    rotateback: function() {
        clearTimeout(this.counter);

        var tbl = document.getElementById(this.container);

        if (this.position == 0) {
            this.position = this.ads.length-1;
        }
        else {
            this.position--;
        }
        tbl.innerHTML = this.ads[this.position];
        this.counter = setTimeout('rotatenext()', 10000);
        this.pause = 0;
    }
});/********************************************************************

	FOREX.COM - QUICKDOCK
	
	=========================================
	Author: Chris Erwin (chris@teehanlax.com)
	Agency: teehan+lax
	Date: July 15, 2008
	=========================================
	
	Public Methods
	-------------------------------------------------------------
	
	
	
	Dependencies
	-------------------------------------------------------------
	- MooTools 1.2
	
*********************************************************************/

var quickdock = {

    defaultPanel: 'panel_oco', // the panel that is shown when the dock is opened without specifying the panel to show
    currPanel: null, 		// id of the panel that's currently active
    currLink: null,
    currState: null, 		// open, closed
    currAnimating: false, 	// boolean
    animation: null, 		// the animation object
    EditingOrder: null,    //    {action:ActionType,orderID:OrderID, isASSP:isASSP, product:product};
    initialized: false,
    // list of panels and the panel nav links associated to them
    panelLinkList: {
        panel_oco: 'link_place_new_order',
        panel_place_limit_stop: 'link_place_new_order',
        panel_transaction_update: 'link_place_new_order',
        panel_ORDER_update: 'link_place_new_order2',
        panel_market_order: 'link_place_new_order',
        panel_orders: 'link_orders',
        panel_positions: 'link_positions',
        panel_account: 'link_account',
        error_panel: 'link_place_new_order',
        panel_ExecOrder : 'link_place_new_order'
    },


    init: function() {

        quickdock.animation = new Fx.Tween('quickdock_content', { duration: 500, transition: 'cubic:in:out' });
        quickdock.animation.addEvent('doneAnimating', function() { quickdock.currAnimating = false; });


        // grab the dock state from the cookie
        quickdock.retrieveDockState();


        // if the curr panel isn't set, set it to the default panel
        if (quickdock.currPanel == null || quickdock.currPanel == 'null') {
            quickdock.currPanel = quickdock.defaultPanel;
        }

        // if the dock state from the cookie is open, open the quickdock
        if (quickdock.currState == 'open') {
            var currPanel = $(quickdock.currPanel);
            var dockContent = $('quickdock_content');

            currPanel.setStyle('display', 'block');
            //dockContent.setStyle('height', currPanel.getSize().y);
            dockContent.setStyle('height', 'auto');
            quickdock.currHeight = currPanel.getSize().y;
            $('quickdock').addClass('open');

            arrowIndicator = $('quickdock').getElement('.logo_container .arrow');
            arrowIndicator.src = arrowIndicator.src.replace('_up.gif', '_down.gif');

            quickdock.setCurrentLink();
        }

        // add event listener to the quick dock nav bar
        var dockNav = $('quickdock').getElement('.dock_nav');
        dockNav.addEvent('click', quickdock.toggleDock);


        // adjust the dock size in IE6
        if (Browser.Engine.trident4) {
            quickdock.ieResizeDock();
            window.addEvent('resize', quickdock.ieResizeDock);
        }

    },

    showPanel: function(panelID) {
        if (!quickdock.initialized) { panelID = 'dock_transaction_initializing_ticket'; };
        if (quickdock.currAnimating != true) {
            if (quickdock.currState != 'open') {
                quickdock.currPanel = panelID;
                quickdock.openDock();
            }
            else {
                if (quickdock.currPanel != panelID) {
                    quickdock.changePanel(panelID);
                }
            }
        };

    },

    closeDock: function() {
        if (!quickdock.currAnimating) {

            arrowIndicator = $('quickdock').getElement('.logo_container .arrow');

            quickdock.currAnimating = true;
            $('quickdock_content').setStyle('height', quickdock.currHeight);
            quickdock.animation.start('height', 0).chain(
				function() { $('quickdock').removeClass('open'); this.callChain(); },
				function() { arrowIndicator.src = arrowIndicator.src.replace('_down.gif', '_up.gif'); this.callChain(); },
				function() { quickdock.currState = 'closed'; this.callChain(); },
				function() { this.fireEvent('doneAnimating'); }
			)
        }
    },

    openDock: function() {
        if (!quickdock.initialized) { return; };
        if (!quickdock.currAnimating && quickdock.currState != 'open') {
            var arrPanels = $('quickdock_content').getElements('.panel');
            var currPanelElement = $(quickdock.currPanel);

            arrPanels.setStyle('display', 'none');
            currPanelElement.setStyle('display', 'block');

            var currPanelHeight = currPanelElement.getSize().y;

            arrowIndicator = $('quickdock').getElement('.logo_container .arrow');

            quickdock.currAnimating = true;
            $('quickdock').addClass('open');
            arrowIndicator.src = arrowIndicator.src.replace('_up.gif', '_down.gif');
            quickdock.animation.start('height', 0, currPanelHeight).chain(
				function() { quickdock.currHeight = currPanelHeight; $('quickdock_content').setStyle('height', 'auto'); this.callChain(); },
				function() { quickdock.currState = 'open'; this.callChain(); },
				function() { quickdock.setCurrentLink(); this.callChain(); },
				function() { this.fireEvent('doneAnimating'); }
			)
        }
    },

    toggleDock: function() {
        if (!quickdock.currAnimating) {
            if (quickdock.currState == 'open') {
                quickdock.closeDock();
            }
            else {
                quickdock.openDock();
            }
        }
    },

    changePanel: function(panelID) {
        if (!quickdock.initialized) { return; };
        if (!quickdock.currAnimating) {
            var oldPanel = $(quickdock.currPanel);
            var newPanel = $(panelID);

            quickdock.currAnimating = true;
            quickdock.animation.start('opacity', 0).chain(
				function() { oldPanel.setStyle('display', 'none'); this.callChain(); },
				function() { newPanel.setStyle('display', 'block'); this.callChain(); },
				function() { $('quickdock_content').setStyle('height', quickdock.currHeight); this.callChain(); },
				function() { this.start('height', newPanel.getSize().y); },
				function() { this.start('opacity', 1); this.callChain(); },
				function() { quickdock.currHeight = newPanel.getSize().y; $('quickdock_content').setStyle('height', 'auto'); this.callChain(); },
				function() { quickdock.currPanel = panelID; this.callChain(); },
				function() { quickdock.setCurrentLink(); this.callChain(); },
				function() { this.fireEvent('doneAnimating'); }
			)
        }
    },

    setCurrentLink: function() {      
        currLinkID = eval('quickdock.panelLinkList.' + quickdock.currPanel);
        if (quickdock.currLink != null) {
            $(quickdock.currLink).removeClass('active');
        }
        if ($(currLinkID) !== null) {
            $(currLinkID).addClass('active');
            quickdock.currLink = currLinkID;
        }
    },

    saveDockState: function() {
        Cookie.write('dockState', quickdock.currState);
        Cookie.write('dockPanel', quickdock.currPanel);
    },

    retrieveDockState: function() {
        //		quickdock.currState = Cookie.read('dockState');
        //		quickdock.currPanel = Cookie.read('dockPanel');
        quickdock.currState = null;
        quickdock.currPanel = 'dock_transaction_initializing_ticket';
    },

    ieResizeDock: function() {
        windowWidth = $(iefix).getScrollSize().x;
        $('quickdock').setStyle('width', windowWidth);
    },

    initOrderPanel: function() {
        aTradingManager.initEditOrder();
        this.EditingOrder = aTradingManager.EditingOrder;
    },

    dockInitialized: function() {
        quickdock.initialized = true;
        quickdock.currPanel = "panel_account";
        if (quickdock.currState == "open") {
            quickdock.showPanel("panel_account")
        }
    }
}

//move the below script to usercontrol
//window.addEvent('domready', quickdock.init);
window.addEvent('unload', quickdock.saveDockState);/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	
	var value=this.params[key]
	if (value==null) value=default_;
	
	return value
}

var expDays = 365; // number of days the cookie should last
 
function SetCookie (name, value) {  
var argv = SetCookie.arguments;  
var argc = SetCookie.arguments.length;  
var expires = (argc > 2) ? argv[2] : null;  
var path = (argc > 3) ? argv[3] : null;  
var domain = (argc > 4) ? argv[4] : null;  
var secure = (argc > 5) ? argv[5] : false;  
document.cookie = name + "=" + escape (value) + 
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
((path == null) ? "" : ("; path=" + path)) +  
((domain == null) ? "" : ("; domain=" + domain)) +    
((secure == true) ? "; secure" : "");
}
function DeleteCookie (name) {  
var exp = new Date();  
exp.setTime (exp.getTime() - 1);  
var cval = GetCookie (name);  
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
var exp = new Date(); 
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function amt(){
var count = GetCookie('count')
if(count == null) {
SetCookie('count','1')
return 1
}
else {
var newcount = parseInt(count) + 1;
DeleteCookie('count')
SetCookie('count',newcount,exp)
return count
   }
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return getCookieVal(j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}

function getRootDomain(url) {
    var baseURL = (url == null) ? location.href : url;
    var rootURL = "";
    if (baseURL.indexOf('/', 7) < 1) {
        rootURL = baseURL;        
    }
    else {
        if ((baseURL.indexOf('https://')) > -1) {
            rootURL = baseURL.substring(0, baseURL.indexOf('/', 8));
        }
        else
        {
            rootURL = baseURL.substring(0, baseURL.indexOf('/', 7));
        }        
    }
    if (baseURL.indexOf('localhost') == -1) {
        if (rootURL.indexOf("http://") == 0) {
            rootURL = rootURL.substring(7);            
        }
        if (rootURL.indexOf("https://") == 0) {
            rootURL = rootURL.substring(8);            
        }
        while (rootURL.split(".").length > 2) {
            var index = rootURL.indexOf('.', 1) + 1;
            rootURL = rootURL.substring(index);            
        }        
        return rootURL;
    }
    else {
        return rootURL + baseURL.substring(baseURL.indexOf('/', 8), baseURL.indexOf('/', baseURL.indexOf('/', 8) + 1)) + "/";
    }
}

  var qs = new Querystring();
  
	var src = qs.get("src");
	var rURL = getRootDomain();
	
	if (src != null)
		SetCookie('adv', src, exp, '/', rURL);	
		
	var aid = qs.get("adused");
  
  if (aid != null)
    SetCookie('aid', aid, exp, '/', rURL);/********************************************************************

	FOREX.COM - QUICK PAIRS
	
	=========================================
	Author: Chris Erwin (chris@teehanlax.com)
	Agency: teehan+lax
	Date: July 30, 2008
	=========================================
	
	
	Public Methods
	-------------------------------------------------------------
	initialize (constructor)
		- Arguments:
			- maxPairs (integer): the maximum number of the quick pairs you can choose.
			- minPairs (integer): the minimum number of the quick pairs you can choose.
		- Returns: null
	
	parseCookie
		- Description: this grabs the cookie and parses the id's into an array
		- Arguments: none
		- Returns: null
		
	saveCookie
		- Description: this iterates through the quickpairs array and builds the string which gets stored in the cookie
		- Arguments: none
		- Returns: null
	
	loadQuickPairs 
		- Description: this iterates throught the quickparis array and calls the show method for each one, and then calls the checkMaxPairs method at the end
		- Arguments:
		- Returns:
	
	togglePair
		- Description: this show/hides the selected quickpair, adds or removes it from the array, calls saveCookie, and calls checkMaxPairs
		- Arguments:
		- Returns:
	
	showPair
		- Description: displays the link in the quickpairs nav (<ul id="quick_pair_links"> inside the "nav_bar" div), and sets the check box to checked
		- Arguments:
		- Returns:
	
	hidePair
		- Description: hides the link in the quickpairs nav (<ul id="quick_pair_links"> inside the "nav_bar" div), and unchecks the check box
		- Arguments:
		- Returns:
	
	checkMaxPairs
		- Description: checks to see if the number of quickpairs in the array exceeds the maximum number defined when instansiating
		- Arguments:
		- Returns:
		
	toggleChooser
		- Description: this simply opens & closes the quick pairs chooser
		- Arguments:
		- Returns:
		
		
	Quick Pairs Cookies
	-------------------------------------------------------------
	The quickpairs cookie stores the id's of the quickpairs the user has chosen. The id's are stored in a single string seperated by the vertical bar character '|'.
	When the cookie is saved it is saved for 14 days
	
	ie: quickpairs = usd_cad|chf_jpy|gbp_chf|jpy_usd
	
	
	HTML Files
	-------------------------------------------------------------
	See the /includes/quick_pairs_nav.shtml file for the quick pairs chooser
	See the /includes/nav_bar.shtml file for the nav
	
	
	CSS Files
	-------------------------------------------------------------
	all styles for the quickpairs nave and the quickpairs chooser reside in the global css file /resources/css/structure.css
	
	
	Dependencies
	-------------------------------------------------------------
	- MooTools 1.2
	
*********************************************************************/

var QuickPairs = new Class({
    initialize: function(maxPairs, minPairs, pairNavTable) {
        this.maxPairs = (maxPairs == null) ? 6 : maxPairs;
        this.minPairs = (minPairs == null) ? 1 : minPairs;

        this.quickPairsChooser = $('quick_pairs_chooser');
        this.arrCheckboxes = this.quickPairsChooser.getElements('.pairs_check');
        this.arrQuickPairs = [];

        // animation properties
        this.animation = new Fx.Tween(this.quickPairsChooser, { duration: 500, transition: Fx.Transitions.Quad.easeOut });
        //this.animation.addEvent('doneAnimating', function() { alert('kiran'); this.openCloseTicket(); } .bind(this));
        this.currAnimating = false;
        this.ticketClosedByQP = false;
        if ($("save_pairs")) {
            this.openHeight = $(pairNavTable).getHeight() + 80;
        }
        else {
            this.openHeight = $(pairNavTable).getHeight() + 50;
        }
        this.openState = false;

        // parse cookie and load pairs
        this.parseCookie();
        this.loadQuickPairs();

        // add event listeners
        if ($('edit_quick_pairs_link'))
            $('edit_quick_pairs_link').addEvent('click', this.toggleChooser.bind(this));
        //		if($('edit_quick_pairs_link_view_all'))
        //		    $('edit_quick_pairs_link_view_all').addEvent('click', this.toggleChooser.bind(this));
        $('quick_pairs_close_link').addEvent('click', this.toggleChooser.bind(this));
        $('save_pairs').addEvent('click', this.saveCookie.bind(this));
        this.arrCheckboxes.addEvent('click', this.togglePair.bind(this));
    },

    parseCookie: function() {
        var quickPairsCookie = Cookie.read('quickpairs');
        var newArrQuickPairs = "";
        for (var i = 0, arrCheckboxesLen = this.arrCheckboxes.length; i < arrCheckboxesLen; i++) {
            this.arrCheckboxes[i].checked = false;
            if (quickPairsCookie) {
                var arrPairs = quickPairsCookie.split('|');
                for (var a = 0; a < arrPairs.length; a++) {
                    if (this.arrCheckboxes[i].id.replace('_check', '') == arrPairs[a].toLowerCase()) {
                        newArrQuickPairs = newArrQuickPairs + arrPairs[a] + '|';
                        break;
                    }
                }
            }
        }
        if (newArrQuickPairs != '') {
            this.arrQuickPairs = newArrQuickPairs.split('|');
            this.arrQuickPairs.erase('');
        }
    },

    saveCookie: function() {
        var cookieString = '';
        var extMsg = Ext.get('minMaxQuickPairMsg');
        extMsg.setVisible(false);
        if (this.arrQuickPairs.length > this.maxPairs)
        { extMsg.update('Max pairs are restricted to 6.'); extMsg.setVisible(true, { duration: 0.5, scope: this, animType: 'motion' }); return false; }
        if (this.arrQuickPairs.length < this.minPairs)
        { extMsg.update('You are required to have at least one pair.'); extMsg.setVisible(true, { duration: 0.5, scope: this, animType: 'motion' }); return false; }
        for (var i = 0, arrQuickPairLen = this.arrQuickPairs.length; i < arrQuickPairLen; i++) {
            cookieString = cookieString + this.arrQuickPairs[i] + '|';
        }
        //check the changes
        var quickPairsCookie = Cookie.read('quickpairs');
        if (quickPairsCookie) {
            var arrPairs = quickPairsCookie.split('|');
            for (var a = 0; a < arrPairs.length; a++) {
                if (cookieString.indexOf(arrPairs[a].toLowerCase()) < 0)
                    this.hidePair(arrPairs[a].toLowerCase());
            }
        }
        cookieString = cookieString.substring(0, (cookieString.length - 1))
        if (cookieString) {
            var arrPairs2 = cookieString.split('|');
            for (var a1 = 0; a1 < arrPairs2.length; a1++) {
                if (quickPairsCookie.indexOf(arrPairs2[a1].toLowerCase()) < 0)
                    this.showPair(arrPairs2[a1].toLowerCase());
            }
        }

        userQuickPairSave(cookieString);
        var quickpairs = Cookie.write('quickpairs', cookieString, { duration: 14 });
        Ext.get('save_success_message').setStyle('display', 'inline');
        Ext.get('save_pairs').setStyle('display', 'none');
        this.toggleChooser();
    },

    loadQuickPairs: function() {
        for (var i = 0, arrQuickPairLen = this.arrQuickPairs.length; i < arrQuickPairLen; i++) {
            var pairID = this.arrQuickPairs[i].toLowerCase();
            this.showPair(pairID);
        }
    },

    togglePair: function(e) {
        Ext.get('save_success_message').setStyle('display', 'none');
        Ext.get('save_pairs').setStyle('display', 'inline');
        var checkedElement = e.target;
        var checkedID = checkedElement.id;
        var pairID = checkedID.replace('_check', '');

        if (checkedElement.checked) {
            this.arrQuickPairs.include(pairID.toLowerCase());
        }
        else {
            this.arrQuickPairs.erase(pairID.toLowerCase());
        }
    },

    showPair: function(pairID) {
        var pairLinkID = 'link_' + pairID;
        var pairLink = $(pairLinkID);
        var pairCheckbox = $(pairID + '_check');
        if (pairCheckbox) {
            if (pairLink) {
                pairLink.inject('quick_pair_links', 'bottom');
                pairLink.setStyle('display', 'block');
                pairCheckbox.checked = true;
            }
        }
    },

    hidePair: function(pairID) {
        var pairLinkID = 'link_' + pairID;
        var pairLink = $(pairLinkID);
        var pairCheckbox = $(pairID + '_check');

        if (pairLink) {
            pairLink.setStyle('display', 'none');
            pairCheckbox.checked = false;
        }
    },
    openCloseTicket: function() {
        alert(this.ticketClosedByQP);
        if (this.ticketClosedByQP) { OrderTicket.tempShow(); }
    },
    toggleChooser: function() {
        if (typeof (OrderTicket) != 'undefined') { if (OrderTicket.orderTicketElement.style.display == 'block') { OrderTicket.tempHide(); this.ticketClosedByQP = true; } }
        if (this.openState) {
            var e = Ext.get("minMaxQuickPairMsg");
            e.setVisible(false);

            this.animation.start('height', 0).chain(
				function() { this.openState = false; this.animation.callChain(); } .bind(this),
				function() { $('edit_quick_pairs_link').getParent().removeClass('open'); this.animation.callChain(); } .bind(this),
				function() { if (this.ticketClosedByQP) { OrderTicket.tempShow(); this.ticketClosedByQP = false; } this.animation.callChain(); } .bind(this)
			);
        }
        else {
            var quickPairsCookie = Cookie.read('quickpairs');
            if (this.arrCheckboxes && this.arrCheckboxes.length > 0) {
                this.arrQuickPairs = [];
                for (var i = 0; i < this.arrCheckboxes.length; i++) {
                    if (quickPairsCookie.indexOf(this.arrCheckboxes[i].id.replace('_check', '')) < 0)
                        this.arrCheckboxes[i].checked = false;
                    else {
                        this.arrCheckboxes[i].checked = true;
                        this.arrQuickPairs[this.arrQuickPairs.length] = this.arrCheckboxes[i].id.replace('_check', '');
                    }
                }

            }
            this.animation.start('height', this.openHeight).chain(
				function() { this.openState = true; this.animation.callChain(); } .bind(this),
				function() { $('edit_quick_pairs_link').getParent().addClass('open'); this.animation.callChain(); } .bind(this),
				function() { if (this.ticketClosedByQP) { OrderTicket.tempShow(); this.ticketClosedByQP = false; } this.animation.callChain(); } .bind(this)
			);
        }
        //        alert('sadfas');
        //        $('order_ticket').setStyles({
        //            top: ($('ctl00_ContentAreaPlaceHolder_trade_bar_1_SelectedPair_sell').getPosition('master_container').y - 8),
        //            left: ($('ctl00_ContentAreaPlaceHolder_trade_bar_1_SelectedPair_sell').getPosition('master_container').x - 8)
        //        });
        //        alert('klllll');
        return false;
    }
});

/********************************************************************

	FOREX.COM - LINKED FIELDS
	
	=========================================
	Author: Chris Erwin (chris@teehanlax.com)
	Agency: teehan+lax
	Date: July 15, 2008
	=========================================	
	
	
	Description
	-------------------------------------------------------------
	LinkedFields sets up a field so that it will change multiple other fields when it's value is changed based on a calculation you pass in
	
	
	Public Methods
	-------------------------------------------------------------
	initialize (constructor)
		Arguments:
			- sourceFieldID (string) : the id of the source field, the field that will trigger the calculations
			- arrLinkedFields (array) : an array that contains an array for each linked field ("two dimensional array")
				- linkedFieldID (string) : the id of the field that the source field is linked to
				- equation (string) : the equation that will get evaluated to determine the linked field's value when the source field is changed. The source field can be referenced in the equation using "this.source.value"
		Returns: null
				
	updateLinkedFields
		Description: iterates through the array of linked fields and runs the equation associated with them and updates the linked fields values
		Arguments: none
		Returns: null
		
		
	Events
	-------------------------------------------------------------
	valueChange
		- runs the updateLinkedFields method
		- fired from within the spinnerControl class
		
		
	HTML Sample File
	-------------------------------------------------------------
	/_widget_samples/linked_fields.html
	
	
	Dependencies
	-------------------------------------------------------------
	- MooTools 1.2
	
*********************************************************************/

var LinkedField = new Class({
    initialize: function(sourceFieldID, arrLinkedFields){
		this.sourceFieldID = sourceFieldID;
		this.arrLinkedFields = arrLinkedFields;
		
		this.source = $(this.sourceFieldID);
		
		this.source.addEvent('keyup', function(event){
			this.updateLinkedFields(event.key);
		}.bind(this));
		this.source.addEvent('valueChange', this.updateLinkedFields.bind(this, null));
    },
	
	updateLinkedFields : function(e) {
		// don't do the calculations if the tab key was pressed
		if(e != "tab") {				
			for(var i=0; i<this.arrLinkedFields.length; i++) {
				var linkedField = $(this.arrLinkedFields[i][0]);
				
				var calculation = this.arrLinkedFields[i][1];
				
				var newLinkedFieldValue = eval(calculation);			
				linkedField.value = newLinkedFieldValue;
			}	
		}
	}
});
var CurrencyMask = new Class({
	initialize: function(a) {
		this.config = a;
		this.config.field.addEvent('keypress', function(eve) { return this.changeEvent(eve); } .bind(this));
	},
	numbersFilter: function(evt) {
		var charCode = (evt.code) ? evt.code : event.keyCode;
		if (charCode == 8 || (charCode > 45 && charCode < 58))
			return true;
		return false;
	},
	changeEvent: function(evt) {
		if (this.numbersFilter(evt)) {
			var charCode = (evt.code) ? evt.code : event.keyCode;
			if (charCode == 8) { return true };
			if (charCode == 46 && this.config.decimalPlaces == 0) { return false; }
			if (charCode == 46 && this.config.field.value.indexOf(".") > 1) { return false; }
		}
		else {
			return false;
		}
		var a = this.config.field.id;
		var b = this.config.field.value;
		var c = this.config.minValue;
		var d = this.config.maxValue;
		var e = this.config.decimalPlaces;
		setTimeout(function() {
			var z = $(a).value.lastIndexOf(".") + 1 == $(a).value.length && $(a).value.lastIndexOf(".") != $(a).value.indexOf(".");
			if (z) { $(a).value = b; }
			//if ($(a).value.toFloat() > d) { $(a).value = b.toFloat().toFixed(e); }
			//else if ($(a).value.toFloat() < c) {
			if ($(a).value.toFloat() > d) { $(a).value = b; }
			else if ($(a).value.toFloat() < c) {
			    //$(a).value = $(a).value.toFloat().toFixed(e);
			}
			var f = $(a).value.indexOf(".");
			if (f > -1) {
				var g = $(a).value.substring(f + 1).length;
				if (g > e) { $(a).value = b; }
			}
			if ($(a).onchange) { $(a).onchange(); }
		}, 1);
		return true;
	}
});/********************************************************************

	FOREX.COM - SPINNER CONTROL
	
	=========================================
	Author: Chris Erwin (chris@teehanlax.com)
	Agency: teehan+lax
	Date: July 15, 2008
	=========================================
	CHANGES
	=======
	Author: Khalil Ahmad (kahmad@gaincapital.com)
	Agency: GainCapital
	Date:   September 5, 2008
	Desc:   Added new parameters "minValue, maxValue & defaultValue" for minimum, maximum and default selected values
	=========================================		
	
	Public Methods 
	-------------------------------------------------------------
	initialize (constructor) 
		- Arguments:
			- fieldID (string): the id of the HTML text field element we are adding a spinner control to
			- changeAmount (integer): the amount the field value should increment & decrement by
			- decimalPlaces (integer): the number of decimal places the value should have when changed
			- minValue (integer): the minimum start value - Khalil
			- maxValue (integer): the maximum start value - Khalil
			- defaultValue (integer): the default selected value - Khalil
		- Returns: null
		
	
	Internal 'Private' Methods
	-------------------------------------------------------------
	incrementValue
		- Description: increments the value in the text field by the amount specified when instanstiating
		- Arguments: none
		- Returns: null
		
	decrementValue
		- Description: decrements the value in the text field by the amount specified when instanstiating
		- Arguments: none
		- Returns: null
		
		
	Sample HTML File
	-------------------------------------------------------------
	/_widget_samples/spinner_control.html
	
	
	Dependencies
	-------------------------------------------------------------
	- MooTools 1.2
	
*********************************************************************/

var SpinnerControl = new Class({
    initialize: function(fieldID, changeAmount, decimalPlaces, minValue, maxValue, defaultValue, doEventbinding) {
        this.fieldID = fieldID;
        this.changeAmount = changeAmount;
        this.decimalPlaces = decimalPlaces;
        this.disabled = false;
        this.minValue = minValue;
        this.maxValue = maxValue;
        this.defaultValue = defaultValue;

        this.field = $(this.fieldID);
        this.field.value = this.defaultValue;   //Khalil
        this.currencyMask = new CurrencyMask(this);
        var spinnerControl = $(this.field.id + '_spin_div');

        if (spinnerControl == null) {
            spinnerControl = new Element('div');
        }
        else {
            spinnerControl.dispose();
            spinnerControl = new Element('div');
        }

        spinnerControl.set('id', this.field.id + '_spin_div');
        spinnerControl.set('class', 'spinner_buttons');

        this.upIMG = new Element('img');
        this.upIMG.set('alt', '+');
        this.upIMG.set('class', 'spin_up');
        this.upIMG.set('src', '/uk/resources/images/buttons/btn_spinner_control_up_off.gif');

        spinnerControl.grab(this.upIMG);

        this.downIMG = new Element('img');
        this.downIMG.set('alt', '-');
        this.downIMG.set('class', 'spin_down');
        this.downIMG.set('src', '/uk/resources/images/buttons/btn_spinner_control_down_off.gif');

        spinnerControl.grab(this.downIMG);
        spinnerControl.inject(this.field, 'after');

        if (doEventbinding == null) doEventbinding = true;
        if (doEventbinding) {
            this.downIMG.addEvent('click', this.decrementValue.bind(this));
            this.upIMG.addEvent('click', this.incrementValue.bind(this));
        };

    },

    incrementValue: function() {
        if (!this.disabled) {
            var newValue = this.field.value.toFloat() + this.changeAmount.toFloat();
            if (this.maxValue == null || newValue <= this.maxValue) { //Khalil - Let it work as it was, if value is null
                if (this.decimalPlaces != null) {
                    newValue = newValue.toFixed(this.decimalPlaces);
                };

                this.field.value = newValue;
                this.field.fireEvent('valueChange');
            };
        };
    },

    decrementValue: function() {
        if (!this.disabled) {
            var newValue = this.field.value.toFloat() - this.changeAmount.toFloat();
            if (this.minValue == null || newValue >= this.minValue) { //Khalil - Let it work as it was, if value is null
                if (this.decimalPlaces != null) {
                    newValue = newValue.toFixed(this.decimalPlaces);
                };
                this.field.value = newValue;
                this.field.fireEvent('valueChange');
            };
        };
    }


});
/********************************************************************

	FOREX.COM - CAROUSEL
	
	=========================================
	Author: Chris Erwin (chris@teehanlax.com)
	Agency: teehan+lax
	Date: July 7, 2008
	=========================================
	
	Public Methods
	-------------------------------------------------------------
	initialize (constructor)
		Arguments:
			- carouselID (string) : the id of the carousel container element
			
	goTo
		Arguments:
			- slideNum (int) : the number of the slide you want to change to 
					(note: that it will not display the slides between the current slide and the slide you are changing to)
		Returns: null
	
	
	Internal 'Private' Methods
	-------------------------------------------------------------
	goNext 
		Arguments: none		
		Returns: false
	
	goPrevious
		Arguments: none		
		Returns: false
	
	
	Dependencies
	-------------------------------------------------------------
	- MooTools 1.2
	
	
	HTML Markup Sample
	-------------------------------------------------------------
	_widget_samples/carousel.html
	
*********************************************************************/

var Carousel = new Class({
    initialize: function(carouselID){
		this.carouselID = carouselID;
		this.carouselWindow = $(carouselID).getElement('.carousel_window');
		this.arrSlides = $(carouselID).getElements('.carousel_item');
		this.nextButton = $(carouselID).getElement('.next_button a');
		this.prevButton = $(carouselID).getElement('.prev_button a');
		
		this.currSlideNum = null;
		this.carouselWindowWidth = this.carouselWindow.getSize().x;
		
		this.arrSlides[0].setStyle('right', 0);
		this.arrSlides.set('morph', {duration: 900, transition: 'cubic:in:out'});

		this.currSlideNum = 0;
		this.nextButton.addEvent('click', this.goNext.bind(this));
		this.prevButton.addEvent('click', this.goPrevious.bind(this));		
    },
	
	goTo : function(slideNum) {
		if(! this.Animating) {			
			//slide in from right
			
			var currEndPos = 0;
			var nextStartPos = 0;
			
			if(slideNum > this.currSlideNum) {
				currEndPos = this.carouselWindowWidth;
				nextStartPos = (this.carouselWindowWidth * -1);
				
				// make sure we're not passed the end
				if (slideNum > (this.arrSlides.length -1)) {
					slideNum = 0;	
				}
			}
			// slide in from left
			else {
				currEndPos = (this.carouselWindowWidth * -1);
				nextStartPos = this.carouselWindowWidth;
				
				// make sure we're not passed the start
				if (slideNum < 0) {
					slideNum = (this.arrSlides.length - 1);	
				}
			}
			
			// animate the slides
			this.arrSlides[slideNum].setStyles({
				right: nextStartPos,
				opacity: 0
			});
			this.arrSlides[this.currSlideNum].morph({right: currEndPos, opacity: 0});
			this.arrSlides[slideNum].morph({right: 0, opacity: 1});
			this.currSlideNum = slideNum;
		}	
	},
	
	goNext : function() {
		var slideNum = this.currSlideNum + 1;
		this.goTo(slideNum);
		
		return false;
	},
	
	goPrevious : function() {
		var slideNum = this.currSlideNum - 1;
		this.goTo(slideNum);
		
		return false;
	}	
});
/********************************************************************

 

      FOREX.COM - CONTENT TOGGLE

      

      =========================================

      Author: Chris Erwin (chris@teehanlax.com)

      Agency: teehan+lax

      Date: July 6, 2008

      =========================================

            

      Description

      -------------------------------------------------------------

      This class sets up a group of links that toggle between content.

      

      Each link has a matching content item that gets displayed when the link is clicked. The content that was previously visible becomes hidden.

      

      There is a content container that gets animated each time there is a change

            - the container fades out 

            - the container animates height to the height of the new content

            - the container fades in

      

      Public Methods

      -------------------------------------------------------------

      initialize (constructor)

            Arguments:

                  - toggleID (string) : the ID of the main toggle container that contains both the toggle nav and toggle content items

                  - defaultContentLinkID (string, null) : the id of the link associated to the content you want to display on load

            

      change

            Arguments:

                  - contentLinkID (string) : the id of the link associated to the content you want to change to.

            Returns:

                  - null

      

      

      Dependencies

      -------------------------------------------------------------

      - MooTools 1.2

      

      HTML Markup Sample

      -------------------------------------------------------------

      _widget_samples/content_toggle.html

      

*********************************************************************/

 

var ContentToggle = new Class({

    initialize: function(toggleID, defaultContentLinkID){

            // SET THE PROPERTIES

            this.toggleID = toggleID;

        this.defaultContentLinkID = defaultContentLinkID;

            this.currContentLinkID = null;

            this.currAnimating = false;

            

            // GRAB THE ELEMENTS

            this.arrToggleLinks = $(this.toggleID).getElements('.toggle_link');
		
				
            this.contentContainer = $(this.toggleID).getElement('.toggle_content_container');

      

            // SET UP THE ANIMATION

            this.animation = new Fx.Tween(this.contentContainer, {duration: 350, transition: Fx.Transitions.Quad.easeOut});

            this.animation.addEvent('doneAnimating', function(){ this.currAnimating = false; }.bind(this));

 

            // SET THE DEFAULT ACTIVE CONTENT
            
            var defaultContentLink = null;

            if (this.defaultContentLinkID != null) {

                  defaultContentLink = $(this.defaultContentLinkID);

            }

            else {

                  defaultContentLink = this.arrToggleLinks[0];

            }

 

            var defaultContent = $(defaultContentLink.id + '_content');       

            defaultContentLink.getParent().addClass('active');

            defaultContent.setStyle('display', 'block');          

            this.currContentLinkID = defaultContentLink.id;

            // ---

            

            // ADD THE LINK EVENTS

            

            this.arrToggleLinks.addEvent('click', this.clickChange.bind(this));     

    },

      

      clickChange : function(e) {

            var clickedID = null;

            var clickedElement = $(e.target);

 

            if(clickedElement.hasClass('toggle_link')){

                  clickedID = clickedElement.id;      

            }

            else {

                  clickedID = clickedElement.getParent().id;      

            }

            

            this.change(clickedID);

            return false;

      },

      

      change : function(contentLinkID) {

            if (!this.currAnimating && this.currContentLinkID != contentLinkID){

                  

                  this.currAnimating = true;

                  var newContentLink = $(contentLinkID);

                  var   newContent = $(contentLinkID + '_content');

                  

                  var currContentLink = $(this.currContentLinkID);

                  var currContent = $(this.currContentLinkID + '_content');

                  

                  var contentContainerRef = this.contentContainer;

                                    

                  currContentLink.getParent().removeClass('active');

                  newContentLink.getParent().addClass('active');        

                  

                  this.animation.start('opacity', 0).chain(

                        function() { contentContainerRef.setStyle('height', currContent.getScrollSize().y); this.callChain(); },

                        function(){ currContent.setStyle('display', 'none'); this.callChain(); },

                        function(){ newContent.setStyle('display', 'block'); this.callChain(); },

                        function() { this.start('height', newContent.getScrollSize().y); },

                        function(){ this.start('opacity', 1); this.callChain(); },

                        function(){ this.fireEvent('doneAnimating'); }

                  )

      

                  this.currContentLinkID = contentLinkID;

            }

      }     

});

 
/********************************************************************

	FOREX.COM - CAROUSEL
	
	=========================================
	Author: Chris Erwin (chris@teehanlax.com)
	Agency: teehan+lax
	=========================================
	
	Public Methods
	-------------------------------------------------------------
	init
		Arguments: none
		Returns: null
		
	zoom
		Arguments:
			- thumbID (string) : the id of the thumbnail image
			- fullsizeImagePath (string) : the path the fullsize version of the image
		
	
	Internal 'Private' Methods
	-------------------------------------------------------------
	loadImage 
		Description: loads the fullsize image and then calls the show image function when it's ready
		Arguments: none		
		Returns: null
	
	showImage
		Description: positions the fullsize image to match the thumbnail and then animates it to the calculated fullsize position (middle of the screen)
		Arguments: none		
		Returns: null
		
	showShadow
		Description: after the image animates to the fullsize position the shadow container and the black background fade in
		Arguments: none		
		Returns: null
		
	closeImage
		Description: the fullsize image animates to it's thumbnail position and size
		Arguments: none		
		Returns: null
	
	resetSize
		Desciption: once the fullsize image is no longer visible we return it to it's default size
		Arguments: none		
		Returns: null
	
	
	Dependencies
	-------------------------------------------------------------
	- MooTools 1.2
	
	
	HTML Markup Sample
	-------------------------------------------------------------
	_widget_samples/image_zoom.html
	
*********************************************************************/

var imageZoom = {
	
	imgFullSize : null,
	imgThumb : null,
	zoomShadow : null,

	fullSizePath : null,
	animation: null,
	shadowAnimation: null,
	fadeAnimation: null,
	animating: false,
	
	thumbCoords : null,
	fullSizeCoords : null,
	fullSizeTopPos : null,
	fullSizeLeftPos : null,
	
	init : function() {
		imageZoom.imgFullSize = $('ZoomImage');
		imageZoom.zoomShadow = $('ZoomShadow');
		imageZoom.zoomFade = $('ZoomFade');
		
		imageZoom.animation = new Fx.Morph(imageZoom.imgFullSize, {duration: 500, transition: Fx.Transitions.Quad.easeOut});
		imageZoom.shadowAnimation = new Fx.Morph(imageZoom.zoomShadow, {duration: 500, transition: Fx.Transitions.Quad.easeOut});
		imageZoom.fadeAnimation = new Fx.Morph(imageZoom.zoomFade, {duration: 500, transition: Fx.Transitions.Quad.easeOut});
		
		imageZoom.animation.addEvent('start', function() {imageZoom.animating = true});
		imageZoom.animation.addEvent('complete', function() {imageZoom.animating = false});
		
		imageZoom.shadowAnimation.addEvent('start', function() {imageZoom.animating = true});
		imageZoom.shadowAnimation.addEvent('complete', function() {imageZoom.animating = false});
		
		imageZoom.fadeAnimation.addEvent('start', function() {imageZoom.animating = true});
		imageZoom.fadeAnimation.addEvent('complete', function() {imageZoom.animating = false});
		
		imageZoom.imgFullSize.addEvent('click', imageZoom.closeImage);
	},
	
	zoom : function(thumbID, fullsizeImagePath) {
		if (! imageZoom.animating) {
			imageZoom.imgThumb = $(thumbID);
			imageZoom.fullSizePath = fullsizeImagePath;
			imageZoom.loadImage();
		}
	},
	
	loadImage : function() {
		var fullsizeLoader = new Asset.image(imageZoom.fullSizePath, {onload: imageZoom.showImage});
	},
	
	showImage : function() {
				
		//imageZoom.zoomShadow.setStyle('opacity', 0);
		
		var windowSize = (Browser.Engine.trident4) ? $('iefix').getSize() : window.getSize();
		var windowScrollPos = (Browser.Engine.trident4) ? $('iefix').getScroll() : window.getScroll();
		
		imageZoom.imgFullSize.src = imageZoom.fullSizePath;
		
		imageZoom.thumbCoords = (Browser.Engine.trident4) ? imageZoom.imgThumb.getCoordinates('iefix') : imageZoom.imgThumb.getCoordinates();			
		imageZoom.fullSizeCoords = imageZoom.imgFullSize.getCoordinates();		
		
		// calculate the open position of the fullsize image
		imageZoom.fullSizeTopPos = (windowSize.y / 2) - (imageZoom.fullSizeCoords.height / 2);
		imageZoom.fullSizeTopPos = (imageZoom.fullSizeTopPos < 30) ? 30 : imageZoom.fullSizeTopPos;
		imageZoom.fullSizeTopPos = imageZoom.fullSizeTopPos + windowScrollPos.y;
		
		imageZoom.fullSizeLeftPos = (windowSize.x / 2) - (imageZoom.fullSizeCoords.width / 2);
		imageZoom.fullSizeLeftPos = (imageZoom.fullSizeLeftPos < 30) ? 30 : imageZoom.fullSizeLeftPos;
		
		// move the fullsize image to the thumbnail size and position
		imageZoom.imgFullSize.setStyles({
			'width' : imageZoom.thumbCoords.width,
			'height' : imageZoom.thumbCoords.height,
			'top' : imageZoom.thumbCoords.top,
			'left' : imageZoom.thumbCoords.left,
			'opacity' : 0,
			'visibility' : 'visible'
		});
		
		// animate the fullsize image the fullsize size and position
		imageZoom.animation.start({
			'height' : imageZoom.fullSizeCoords.height, 
			'width' : imageZoom.fullSizeCoords.width,
			'top' : imageZoom.fullSizeTopPos + 26,
			'left' : imageZoom.fullSizeLeftPos,
			'opacity' : 1
		}).chain(
			imageZoom.showShadow
		);

		imageZoom.zoomFade.setStyles({
			'height' :  (Browser.Engine.trident4) ? $('iefix').getScrollSize().y : window.getScrollSize().y,
			'width' : windowSize.x,
			'opacity' : 0,
			'visibility' : 'visible'
		});
	},
	
	showShadow : function() {
		imageZoom.zoomShadow.setStyles({
			'height' : imageZoom.fullSizeCoords.height + 54, 
			'width' : imageZoom.fullSizeCoords.width + 54,
			'top' : imageZoom.fullSizeTopPos - 20,
			'left' : imageZoom.fullSizeLeftPos - 27,	
			'opacity' : 0
		});
		
		$('ZoomShadowSpacer').setStyles({
			'height' : imageZoom.fullSizeCoords.height,
			'width' : imageZoom.fullSizeCoords.width
		});
		
		imageZoom.shadowAnimation.start({
			'opacity': 1					
		});
		
		imageZoom.fadeAnimation.start({
			'opacity': 0.6					
		});
	},
	
	closeImage : function() {
		if (! imageZoom.animating) {
			imageZoom.zoomShadow.setStyle('opacity', 0);
			
			$('ZoomShadowSpacer').setStyles({
				'height' :'',
				'width' : ''
			});
			
			// animate the fullsize image the fullsize size and position
			imageZoom.animation.start({
				'height' : imageZoom.thumbCoords.height, 
				'width' : imageZoom.thumbCoords.width,
				'top' : imageZoom.thumbCoords.top,
				'left' : imageZoom.thumbCoords.left,
				'opacity' : 0
			}).chain(
				imageZoom.resetSize
			);
			
			imageZoom.fadeAnimation.start({
				'opacity': 0				
			});
			
			imageZoom.thumbCoords = null,
			imageZoom.fullSizeCoords = null
		}		
	},
	
	resetSize : function() {
		imageZoom.imgFullSize.setStyles({
			'width' : '',
			'height' : '',
			'top' : '-1000000px',
			'left' : '-1000000px'
		});
		
	}
	
};
/********************************************************************

	FOREX.COM - GUIDED TOUR
	
	=========================================
	Author: Chris Erwin (chris@teehanlax.com)
	Agency: teehan+lax
	Date: July 16, 2008
	=========================================	
	
	Description
	-------------------------------------------------------------
	There are two parts for the guided tour
	
	1. GuidedTourSteps - an object for each step in the tour
	2. GuidedTour - an array of all the steps and methods to move through them
	
	
	HTML Markup Sample
	-------------------------------------------------------------
	_widget_samples/guided_tour.html
	
	
	Dependencies
	-------------------------------------------------------------
	- MooTools 1.2

*********************************************************************/






/********************************************************************
	
	GUIDED TOUR STEP
	
	Public Methods
	-------------------------------------------------------------
	initialize (constructor)
		Arguments:
			- tourStepID (string) : the ID of the HTML element for the tour step
			- xPos (integer) : the number of pixels from the left of the page to position the tour step
			- yPos (integer) : the number of pixels from the top of the page to position the tour step
			- notchPos (string) : the position the notch on the tourstep should be ('right' or 'left')
			
	hide
		Description: fades out the tour step element
		Arguments: none
		Returns: null
		
	show
		Description: fades in the tour step element
		Arguments: none
		Returns: null
	
	
*********************************************************************/

var GuidedTourStep = new Class({
     initialize: function(tourStepID, xPos, yPos, notchPos) {
		this.tourStepID = tourStepID;		
		this.tourStep = $(this.tourStepID);
		this.xPos = xPos;
		this.yPos = yPos;
		this.notchPos = notchPos;
		
		this.animation =  new Fx.Morph(this.tourStep, {duration: 300, transition: 'cubic:in:out'});
		
		if (this.notchPos == 'right') {
			this.tourStep.addClass('right');		
		}
		else if (this.notchPos == 'none')
		{
			// do nothing
		}
		else {
			this.tourStep.addClass('left');	
		}
		
		this.tourStep.setStyles({
			opacity: 0,
			top : this.yPos,
			left: this.xPos
		});
		
		
    },
	
	hide : function() {
		this.animation.start({
			'opacity': 0, 
			'top': this.yPos + 50  
		});

		
		$('iframe_shim').setStyles({
			'top' : -1000000,
			'left' : -1000000
		});
	},
	
	show : function() {
		this.tourStep.setStyle('display', 'block');
		this.tourStep.setStyle('left', this.xPos);
		
		if(Browser.Engine.trident4) {
			$('iefix').scrollTo(0, (this.yPos- 150));	
		}
		else {
			window.scrollTo(0, (this.yPos- 150));
		}
		
		this.animation.start({
			'opacity': 1, 
			'top': [this.yPos - 50,  this.yPos] 
		});
		
		
		
		$('iframe_shim').setStyles({
			'top' : this.yPos,
			'left' : this.xPos,
			'height' : this.tourStep.getSize().y -4,
			'width' : this.tourStep.getSize().x - 4
		});
	}
});




/********************************************************************
	
	GUIDED TOUR
	
	Public Methods
	-------------------------------------------------------------
	initialize (constructor)
		Arguments:
			- arrTourSteps (array) : and array of GuidedTourStep instances
			
	start
		Description: fires the show method of the first object in the array 
		Arguments: none
		Returns: null
		
	end
		Description: fires the hide method of the current tour step object
		Arguments: none
		Returns: null
		
	nextStep
		Description: hides the current tour step object and shows the next one in the array
		Arguments:
		Returns:
	
	previousStep
		Description: hides the current tour step object and show the previous one in the array
		Arguments:
		Returns:
		
		
*********************************************************************/

var GuidedTour = new Class({
	initialize: function(arrTourSteps) {
		this.arrTourSteps = arrTourSteps;
		this.tourLength = this.arrTourSteps.length;
		this.currStepNum = null;
	},
	start : function() {
		this.arrTourSteps[0].show();
		this.currStepNum = 0;
	},
	end : function() {
		this.arrTourSteps[this.currStepNum].hide();
		this.currStepNum = null;
	},
	nextStep : function() {
		if( this.currStepNum + 1 < this.tourLength ) {
			var currStep = this.arrTourSteps[this.currStepNum];
			var nextStep = this.arrTourSteps[this.currStepNum + 1];
			
			currStep.hide();
			nextStep.show();
			
			this.currStepNum = this.currStepNum + 1;
		}
	},
	previousStep : function() {
		if( this.currStepNum - 1 >= 0 ) {
			var currStep = this.arrTourSteps[this.currStepNum];
			var nextStep = this.arrTourSteps[this.currStepNum - 1];
			
			currStep.hide();
			nextStep.show();
			
			this.currStepNum = this.currStepNum - 1;
		}
	}
});
Ext.namespace('GAIN');
var ui = '/uk/UIService.asmx';
GAIN.messageDealProcessing = "Deal request is processing.";
GAIN.messageOrderProcessing = "Order request is processing.";
GAIN.messageAnotherDealProcessing = "Another Deal request is processing. Please wait.";
GAIN.messageAnotherOrderProcessing = "Another Order request is processing. Please wait.";
GAIN.TrailingStopPipErrorMessage = "Pip specified in your trailling stop order is out of acceptable range";
GAIN.LABELS_ORDERRATE_OrderDefaultText = 'Order Rate';
GAIN.LABELS_ORDERRATE_TrailingStopText = 'Live Rate';
//-------TradingObject------------------------------------------------------------------------------------
GAIN.TradingObject = function (config){
    this.url = "";
    this.refreshInterval = 1000;//milli second
    this.data = null;
    this.jsonPara = {};
    this.status = {requesting:false, dataReady:false, init:false, repeatable:true, dataInit:false, enabled:true};
        
    GAIN.TradingObject.superclass.constructor.call(this);
    Ext.apply(this, config);
    this.aConnection = new Ext.data.Connection();
    
    this.addEvents({
        "dataInit": true,
        "Updating": true,
        "Loaded" : true,
        "LoadFailed": true
    });
    
    function TransformText(input, url){
        var temp;
        switch (url){
            case ui + "/GetUserRates3":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"Bid":').replace(/\"C\":/g,'"Offer":').replace(/\"D\":/g,'"Status":');
            case ui + "/GetUserRates4":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"Bid":').replace(/\"C\":/g,'"Offer":').replace(/\"D\":/g,'"ChangeInPoints":').replace(/\"E\":/g,'"Status":');
            break;
            case ui + "/GetUserRates3_3":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"Bid":').replace(/\"C\":/g,'"Offer":').replace(/\"D\":/g,'"ClosingBid":').replace(/\"E\":/g,'"High":').replace(/\"F\":/g,'"Low":').replace(/\"G\":/g,'"Status":');
            break;            
            case ui + "/GetUserRates5":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"Bid":').replace(/\"C\":/g,'"Offer":').replace(/\"D\":/g,'"ChangeInPoints":').replace(/\"E\":/g,'"High":').replace(/\"F\":/g,'"Low":').replace(/\"G\":/g,'"Status":');
            break;            
            case ui + "/GetUserRates6":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"Bid":').replace(/\"C\":/g,'"Offer":').replace(/\"D\":/g,'"ChangeInPoints":').replace(/\"E\":/g,'"High":').replace(/\"F\":/g,'"Low":').replace(/\"G\":/g,'"cPercent":').replace(/\"H\":/g,'"Status":');
            break;
            case ui + "/GetProductSettings2":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"IDecimals":');
            break;
            case ui + "/GetProductSettings3":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"IDecimals":').replace(/\"F\":/g,'"Notation":');
            break;            
            case ui + "/GetProductSettings6":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"IDecimals":').replace(/\"C\":/g,'"MaxOrderLots":').replace(/\"D\":/g,'"OrderSize":').replace(/\"E\":/g,'"DefaultOrderLots":').replace(/\"F\":/g,'"Notation":').replace(/\"G\":/g,'"CounterProduct":').replace(/\"H\":/g,'"MarginFactor":').replace(/\"I\":/g,'"MaxOrderPips":').replace(/\"J\":/g,'"PipDifference":').replace(/\"K\":/g,'"DefaultTradeLots":').replace(/\"L\":/g,'"TradeSize":').replace(/\"M\":/g,'"AliasName":').replace(/\"N\":/g,'"Description":').replace(/\"O\":/g,'"BoldIndex":').replace(/\"P\":/g,'"SuperScriptIndex":').replace(/\"Q\":/g,'"ContractExpiryDescription":').replace(/\"R\":/g,'"DailyClosureExpiryTimeDescription":').replace(/\"S\":/g,'"UnitsPerLotDescription":').replace(/\"T\":/g,'"MinimumTickDescription":').replace(/\"U\":/g,'"Type":').replace(/\"V\":/g,'"OrderPipsAway":');
            break;       
            case ui + "/GetMargins3":
                temp = input.replace(/\"A\":/g,'"MarginBalance":').replace(/\"B\":/g,'"UnrealizedProfit":').replace(/\"C\":/g,'"RealizedProfit":').replace(/\"D\":/g,'"USDPostedMargin":').replace(/\"E\":/g,'"USDRealizedProfit":').replace(/\"F\":/g,'"PostedMargin":');
            break; 
            case ui + "/GetPositions4":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"Contract":').replace(/\"C\":/g,'"Unrealized":').replace(/\"D\":/g,'"AverageRate":').replace(/\"E\":/g,'"USDValue":');
            break;            
            case ui + "/GetPositions8":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"Contract":').replace(/\"C\":/g,'"Unrealized":').replace(/\"D\":/g,'"AverageRate":').replace(/\"E\":/g,'"USDValue":').replace(/\"F\":/g,'"LimitRate":').replace(/\"G\":/g,'"StopRate":').replace(/\"H\":/g,'"ProfitLoss":');
            break;    
            case ui + "/GetProductDeals6":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"Dealsequence":').replace(/\"C\":/g,'"Contract":').replace(/\"D\":/g,'"Rate":').replace(/\"E\":/g,'"BuySell":').replace(/\"F\":/g,'"Status":');
            break;      
            case ui + "/GetOrders4":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"Legs":').replace(/\"W\":/g,'"Amount":').replace(/\"X\":/g,'"Rate":').replace(/\"Y\":/g,'"Basis":').replace(/\"Z\":/g,'"BuySell":');
            break;    
            case ui + "/GetOrdersC":
                temp = input.replace(/\"A\":/g,'"Product":').replace(/\"B\":/g,'"Legs":').replace(/\"C\":/g,'"Type":').replace(/\"D\":/g,'"ReferenceNumber":').replace(/\"E\":/g,'"Expiry":').replace(/\"F\":/g,'"Assp":').replace(/\"G\":/g,'"TrailingPoints":').replace(/\"W\":/g,'"Amount":').replace(/\"X\":/g,'"Rate":').replace(/\"Y\":/g,'"Basis":').replace(/\"Z\":/g,'"BuySell":').replace(/\"T\":/g,'"Seq":').replace(/\"U\":/g,'"Status":').replace(/\"V\":/g,'"TSP":');
            break;                                                          
            default:
                return input;
            break;            
        };
        return temp;
    };
    
    var ajob = function(index, isForceRun){
        if ( isForceRun || (this.status.enabled == true && (this.status.repeatable == true || this.status.dataInit != true) && !this.status.requesting ) ){
            
            this.status.requesting = true;
            this.fireEvent('Updating');
            this.aConnection.request(
            {
                url: this.url,
                method: "POST",
                headers:{"Content-Type":"application/json"},
                scope: this,
                jsonData: this.jsonPara,
                callback: function(options, success, response){
                    this.status.requesting = false;
                    if (success){
                        var aResponseText = TransformText(response.responseText, this.url);
                        var temp = Ext.util.JSON.decode(aResponseText);
                        if (temp.d == null){
                            this.fireEvent('LoadFailed');
                        }else{
                            if (this.data != null && this.data.clear) {
                                this.status.dataReady = false;
                                this.data.clear();
                                
                                for (var i =0; i < temp.d.length; i++)
                                {
                                    this.data.replace(temp.d[i]);
                                };   
                                this.status.dataReady = true;  
                            }else{
                                this.status.dataReady = false;
                                this.data = temp.d;
                                this.status.dataReady = true;
                            }
                            if (this.status.dataInit == false){
                                this.status.dataInit = true;
                                this.fireEvent('dataInit');
                            };
                            
                            this.fireEvent('Loaded');
                        };

                    }else{
                        this.fireEvent('LoadFailed');
                    }
                } 
             } 
            );
        };
    };
    
    var task; 

   this.init = function() {

        task = {
            run: ajob.createDelegate(this),
            interval: this.refreshInterval
        };
        ajob.call(this);
        var runner = new Ext.util.TaskRunner();
        runner.start(task);
        this.status.init = true;
    };

    this.requestData = ajob.createDelegate(this);
};

Ext.extend(GAIN.TradingObject, Ext.util.Observable, {});
//-------TradingObjects-----------------------------------------------------------------------------------

GAIN.CheckStatus = function (config){
    GAIN.CheckStatus.superclass.constructor.call(this);
    Ext.apply(this, config);
    
    this.data = null;
    this.init();
};
Ext.extend(GAIN.CheckStatus, GAIN.TradingObject, {});

GAIN.Rates = function (config){
    GAIN.Rates.superclass.constructor.call(this);
    Ext.apply(this, config);
    
    this.data = new Ext.util.MixedCollection(false, function(item){
        return item.Product;
    });  
    this.init();
};
Ext.extend(GAIN.Rates, GAIN.TradingObject, {});

GAIN.Positions = function (config){
    GAIN.Positions.superclass.constructor.call(this);
    this.hasPLPip = false;
    this.hasUnRealizedPL =false;
    Ext.apply(this, config);
    this.data = new Ext.util.MixedCollection(false, function(item){
        return item.Product;
    });  
    this.init();
};
Ext.extend(GAIN.Positions, GAIN.TradingObject, {});

GAIN.Deals = function (config){
    GAIN.Deals.superclass.constructor.call(this);
    this.status.enabled = false; 
    Ext.apply(this, config);
    this.data = new Ext.util.MixedCollection(false, function(item){
        return item.Dealsequence;
    });  
    this.init();
};
Ext.extend(GAIN.Deals, GAIN.TradingObject, {});

GAIN.Margin = function (config){
    GAIN.Margin.superclass.constructor.call(this);
    Ext.apply(this, config);
    this.data = null;
    this.init();
};
Ext.extend(GAIN.Margin, GAIN.TradingObject, {});

GAIN.Orders = function (config){
    GAIN.Orders.superclass.constructor.call(this);
    Ext.apply(this, config);
    this.data = new Ext.util.MixedCollection(false, function(item){
        return item.ReferenceNumber;
    });  
    this.init();
};
Ext.extend(GAIN.Orders, GAIN.TradingObject, {});

GAIN.ProductSettings = function (config){
    GAIN.ProductSettings.superclass.constructor.call(this);
    this.status.repeatable = false;   
    Ext.apply(this, config);
    this.data = new Ext.util.MixedCollection(false, function(item){
        return item.Product;
    });  
    this.init();
};
Ext.extend(GAIN.ProductSettings, GAIN.TradingObject, {});


GAIN.AccountSettings = function (config){
    GAIN.AccountSettings.superclass.constructor.call(this);
    this.status.repeatable = false;    
    Ext.apply(this, config);
    this.data = null; 
    this.init();
};
Ext.extend(GAIN.AccountSettings, GAIN.TradingObject, {});

GAIN.EconodayResearch = function (config){
    GAIN.EconodayResearch.superclass.constructor.call(this);
    this.status.repeatable = false;
    Ext.apply(this, config);
    this.data = null;  
    this.init();
};
Ext.extend(GAIN.EconodayResearch, GAIN.TradingObject, {});

GAIN.DealData = function(){
    this.Dealsequence = "";
    this.Product = "";
    this.BuySell = "";
    this.BankConfirmation = "";
    this.DealDate = "";
    this.Rate = "";
    this.Contract = "";
    this.Counter = "";
    this.Reference = "";
    this.Sequence = "";
    this.Status = "";
};

GAIN.OrderLegData = function(){
    this.BuySell = "";
    this.Amount = "";
    this.Basis = "";
    this.Rate = "";
    this.TPS = 0;
    this.Status = "";
    this.Seq = 0;
    this.ConfirmationNumber = "";
    this.Type = "";
};

GAIN.OrderData = function(){
    this.Assp = "";
    this.DealReference = "";
    this.Expiry = "";
    this.OrderDate = "";
    this.Product = "";
    this.ReferenceNumber = "";
    this.TrailingPoints = "";
    this.Type = "";
    this.Legs = [];
};

GAIN.Expires = {EOD:{text:'End of Day',value:'EOD'}, GTC:{text:'Good Till Cancelled',value:'GTC'}};

GAIN.BuySell = {B:{text:'Buy',value:'B'}, S:{text:'Sell',value:'S'}};

GAIN.BuySell = {T:{text:'Limit',value:'T'}, S:{text:'Stop',value:'S'}};

GAIN.OrderType = {
    MARKET_ORDER:{text:'Market',value:'MARKET_ORDER'},
    SINGLE_ORDER: { text: 'Single', value: 'SINGLE_ORDER' },
    SINGLE_ORDER_LIMIT: { text: 'Limit', value: 'SINGLE_ORDER_LIMIT' },
    SINGLE_ORDER_STOP: { text: 'Stop', value: 'SINGLE_ORDER_STOP' },
    OCO_ORDER:{text:'One Cancels Other',value:'OCO_ORDER'},
    IF_THEN:{text:'If Then',value:'IF_THEN'},
    IF_THEN_OCO:{text:'If Then OCO',value:'IF_THEN_OCO'},
    TRAILINGSTOP:{text:'Trailing Stop',value:'TRAILINGSTOP'},
    SINGLE_ASSP: { text: 'Single', value: 'SINGLE_ASSP' },
    SINGLE_ASSP_LIMIT: { text: 'Limit', value: 'SINGLE_ASSP_LIMIT' },
    SINGLE_ASSP_STOP: { text: 'Stop', value: 'SINGLE_ASSP_STOP' },        
    OCO_ASSP:{text:'One Cancels Other',value:'OCO_ASSP'},
    TRAILINGSTOP_ASSP:{text:'Trailing Stop',value:'TRAILINGSTOP_ASSP'}
};

GAIN.ActionType = {PLACE:'PLACE',MODIFY:'MODIFY', CANCEL:'CANCEL'};

GAIN.OrderDropDown = {
    PLACE_true: ['SINGLE_ASSP_LIMIT', 'SINGLE_ASSP_STOP', 'OCO_ASSP', 'TRAILINGSTOP_ASSP'],
    PLACE_false: ['MARKET_ORDER', 'SINGLE_ORDER_LIMIT', 'SINGLE_ORDER_STOP', 'OCO_ORDER', 'IF_THEN', 'IF_THEN_OCO', 'TRAILINGSTOP'],
    MODIFY_true: ['SINGLE_ASSP_LIMIT', 'SINGLE_ASSP_STOP', 'OCO_ASSP', 'TRAILINGSTOP_ASSP'],
    MODIFY_false: ['SINGLE_ORDER_LIMIT', 'SINGLE_ORDER_STOP' , 'OCO_ORDER', 'IF_THEN', 'IF_THEN_OCO', 'TRAILINGSTOP'],
    Cancel_true: ['SINGLE_ASSP_LIMIT', 'SINGLE_ASSP_STOP', 'OCO_ASSP', 'TRAILINGSTOP_ASSP'],
    Cancel_false: ['SINGLE_ORDER_LIMIT', 'SINGLE_ORDER_STOP', 'OCO_ORDER', 'IF_THEN', 'IF_THEN_OCO', 'TRAILINGSTOP']
};


GAIN.ORDERUI = {
PLACE_false_SINGLE_ORDER:{orderlabel:{visible:true},product:{visible:true,enable:true},orderType:{visible:true,enable:true},ASSP:{visible:false,enable:true},Expiry:{visible:true,enable:true},Legs:1,BuySell:{visible:true,enable:true},Contract:{visible:true,enable:true},Basis:{visible:true,enable:true},Rate:{visible:true,enable:true},Pip:{visible:true,enable:true}},
PLACE_false_SINGLE_ORDER_LIMIT: { orderlabel: { visible: true }, product: { visible: true, enable: true }, orderType: { visible: true, enable: true }, ASSP: { visible: false, enable: true }, Expiry: { visible: true, enable: true }, Legs: 1, BuySell: { visible: true, enable: true }, Contract: { visible: true, enable: true }, Basis: { visible: true, enable: false, value:'T' }, Rate: { visible: true, enable: true }, Pip: { visible: true, enable: true} },
PLACE_false_SINGLE_ORDER_STOP: { orderlabel: { visible: true }, product: { visible: true, enable: true }, orderType: { visible: true, enable: true }, ASSP: { visible: false, enable: true }, Expiry: { visible: true, enable: true }, Legs: 1, BuySell: { visible: true, enable: true }, Contract: { visible: true, enable: true }, Basis: { visible: true, enable: false, value: 'S' }, Rate: { visible: true, enable: true }, Pip: { visible: true, enable: true} },
PLACE_false_MARKET_ORDER: { orderlabel: { visible: false }, product: { visible: true, enable: true }, orderType: { visible: true, enable: true }, ASSP: { visible: false, enable: false }, Expiry: { visible: false }, Legs: 1, BuySell: { visible: true, enable: true }, Contract: { visible: true, enable: true }, Basis: { visible: false }, Rate: { visible: true, enable: false }, Pip: { visible: false, enable: false} },
PLACE_false_OCO_ORDER:{orderlabel:{visible:true},product:{visible:true,enable:true},orderType:{visible:true,enable:true},ASSP:{visible:false,enable:true},Expiry:{visible:true,enable:true},Legs:2,BuySell:{visible:true,enable:true},Contract:{visible:true,enable:true},Basis:{visible:true,enable:true},Rate:{visible:true,enable:true},Pip:{visible:true,enable:true}},
PLACE_false_IF_THEN:{orderlabel:{visible:true},product:{visible:true,enable:true},orderType:{visible:true,enable:true},ASSP:{visible:false,enable:true},Expiry:{visible:true,enable:true},Legs:2,BuySell:{visible:true,enable:true},Contract:{visible:true,enable:true},Basis:{visible:true,enable:true},Rate:{visible:true,enable:true},Pip:{visible:true,enable:true}},
PLACE_false_IF_THEN_OCO:{orderlabel:{visible:true},product:{visible:true,enable:true},orderType:{visible:true,enable:true},ASSP:{visible:false,enable:true},Expiry:{visible:true,enable:true},Legs:3,BuySell:{visible:true,enable:true},Contract:{visible:true,enable:true},Basis:{visible:true,enable:true},Rate:{visible:true,enable:true},Pip:{visible:true,enable:true}},
PLACE_false_TRAILINGSTOP:{orderlabel:{visible:true},product:{visible:true,enable:true},orderType:{visible:true,enable:true},ASSP:{visible:false,enable:true},Expiry:{visible:true,enable:true},Legs:1,BuySell:{visible:true,enable:true},Contract:{visible:true,enable:true},Basis:{visible:true,enable:false,value:'S'},Rate:{visible:true,enable:false},Pip:{visible:true,enable:true}},
PLACE_true_SINGLE_ASSP:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:true},ASSP:{visible:true,enable:false},Expiry:{visible:true,enable:false,value:'GTC'},Legs:1,BuySell:{visible:true,enable:false},Contract:{visible:true,enable:false},Basis:{visible:true,enable:true},Rate:{visible:true,enable:true},Pip:{visible:true,enable:true}},
PLACE_true_SINGLE_ASSP_LIMIT: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: true }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false, value: 'GTC' }, Legs: 1, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false, value: 'T' }, Rate: { visible: true, enable: true }, Pip: { visible: true, enable: true} },
PLACE_true_SINGLE_ASSP_STOP: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: true }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false, value: 'GTC' }, Legs: 1, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false, value: 'S' }, Rate: { visible: true, enable: true }, Pip: { visible: true, enable: true} },
PLACE_true_OCO_ASSP: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: true }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false, value: 'GTC' }, Legs: 2, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false }, Rate: { visible: true, enable: true }, Pip: { visible: true, enable: true} },
PLACE_true_TRAILINGSTOP_ASSP:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:true},ASSP:{visible:true,enable:false},Expiry:{visible:true,enable:false,value:'GTC'},Legs:1,BuySell:{visible:true,enable:false},Contract:{visible:true,enable:false},Basis:{visible:true,enable:false,value:'S'},Rate:{visible:true,enable:false},Pip:{visible:true,enable:true}},
MODIFY_false_SINGLE_ORDER:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:false},ASSP:{visible:false,enable:false},Expiry:{visible:true,enable:true},Legs:1,BuySell:{visible:true,enable:true},Contract:{visible:true,enable:true},Basis:{visible:true,enable:true},Rate:{visible:true,enable:true},Pip:{visible:true,enable:true}},
MODIFY_false_SINGLE_ORDER_LIMIT: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: false }, ASSP: { visible: false, enable: false }, Expiry: { visible: true, enable: true }, Legs: 1, BuySell: { visible: true, enable: true }, Contract: { visible: true, enable: true }, Basis: { visible: true, enable: false, value: 'T' }, Rate: { visible: true, enable: true }, Pip: { visible: true, enable: true} },
MODIFY_false_SINGLE_ORDER_STOP: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: false }, ASSP: { visible: false, enable: false }, Expiry: { visible: true, enable: true }, Legs: 1, BuySell: { visible: true, enable: true }, Contract: { visible: true, enable: true }, Basis: { visible: true, enable: false, value: 'S' }, Rate: { visible: true, enable: true }, Pip: { visible: true, enable: true} },
MODIFY_false_OCO_ORDER: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: false }, ASSP: { visible: false, enable: false }, Expiry: { visible: true, enable: true }, Legs: 2, BuySell: { visible: true, enable: true }, Contract: { visible: true, enable: true }, Basis: { visible: true, enable: true }, Rate: { visible: true, enable: true }, Pip: { visible: true, enable: true} },
MODIFY_false_IF_THEN:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:false},ASSP:{visible:false,enable:false},Expiry:{visible:true,enable:true},Legs:2,BuySell:{visible:true,enable:true},Contract:{visible:true,enable:true},Basis:{visible:true,enable:true},Rate:{visible:true,enable:true},Pip:{visible:true,enable:true}},
MODIFY_false_IF_THEN_OCO:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:false},ASSP:{visible:false,enable:false},Expiry:{visible:true,enable:true},Legs:3,BuySell:{visible:true,enable:true},Contract:{visible:true,enable:true},Basis:{visible:true,enable:true},Rate:{visible:true,enable:true},Pip:{visible:true,enable:true}},
MODIFY_true_SINGLE_ASSP:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:true},ASSP:{visible:true,enable:false},Expiry:{visible:true,enable:false},Legs:1,BuySell:{visible:true,enable:false},Contract:{visible:true,enable:false},Basis:{visible:true,enable:true},Rate:{visible:true,enable:true},Pip:{visible:true,enable:true}},
MODIFY_true_SINGLE_ASSP_LIMIT: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: true }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false }, Legs: 1, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false, value: 'T' }, Rate: { visible: true, enable: true }, Pip: { visible: true, enable: true} },
MODIFY_true_SINGLE_ASSP_STOP: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: true }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false }, Legs: 1, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false, value: 'S' }, Rate: { visible: true, enable: true }, Pip: { visible: true, enable: true} },
MODIFY_true_OCO_ASSP: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: true }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false }, Legs: 2, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false }, Rate: { visible: true, enable: true }, Pip: { visible: true, enable: true} },
MODIFY_true_TRAILINGSTOP_ASSP:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:true},ASSP:{visible:true,enable:false},Expiry:{visible:true,enable:false,value:'GTC'},Legs:1,BuySell:{visible:true,enable:false},Contract:{visible:true,enable:false},Basis:{visible:true,enable:false,value:'S'},Rate:{visible:true,enable:false},Pip:{visible:true,enable:true}},
CANCEL_false_SINGLE_ORDER:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:false},ASSP:{visible:true,enable:false},Expiry:{visible:true,enable:false},Legs:1,BuySell:{visible:true,enable:false},Contract:{visible:true,enable:false},Basis:{visible:true,enable:false},Rate:{visible:true,enable:false},Pip:{visible:true,enable:false}},
CANCEL_false_SINGLE_ORDER_LIMIT: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: false }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false }, Legs: 1, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false }, Rate: { visible: true, enable: false }, Pip: { visible: true, enable: false} },
CANCEL_false_SINGLE_ORDER_STOP: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: false }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false }, Legs: 1, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false }, Rate: { visible: true, enable: false }, Pip: { visible: true, enable: false} },
CANCEL_false_OCO_ORDER: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: false }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false }, Legs: 2, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false }, Rate: { visible: true, enable: false }, Pip: { visible: true, enable: false} },
CANCEL_false_IF_THEN:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:false},ASSP:{visible:true,enable:false},Expiry:{visible:true,enable:false},Legs:2,BuySell:{visible:true,enable:false},Contract:{visible:true,enable:false},Basis:{visible:true,enable:false},Rate:{visible:true,enable:false},Pip:{visible:true,enable:false}},
CANCEL_false_IF_THEN_OCO:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:false},ASSP:{visible:true,enable:false},Expiry:{visible:true,enable:false},Legs:3,BuySell:{visible:true,enable:false},Contract:{visible:true,enable:false},Basis:{visible:true,enable:false},Rate:{visible:true,enable:false},Pip:{visible:true,enable:false}},
CANCEL_false_TRAILINGSTOP:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:false},ASSP:{visible:true,enable:false},Expiry:{visible:true,enable:false},Legs:1,BuySell:{visible:true,enable:false},Contract:{visible:true,enable:false},Basis:{visible:true,enable:false},Rate:{visible:true,enable:false},Pip:{visible:true,enable:false}},
CANCEL_true_SINGLE_ASSP:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:false},ASSP:{visible:true,enable:false},Expiry:{visible:true,enable:false},Legs:1,BuySell:{visible:true,enable:false},Contract:{visible:true,enable:false},Basis:{visible:true,enable:false},Rate:{visible:true,enable:false},Pip:{visible:true,enable:false}},
CANCEL_true_SINGLE_ASSP_LIMIT: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: false }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false }, Legs: 1, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false }, Rate: { visible: true, enable: false }, Pip: { visible: true, enable: false} },
CANCEL_true_SINGLE_ASSP_STOP: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: false }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false }, Legs: 1, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false }, Rate: { visible: true, enable: false }, Pip: { visible: true, enable: false} },
CANCEL_true_OCO_ASSP: { orderlabel: { visible: true }, product: { visible: true, enable: false }, orderType: { visible: true, enable: false }, ASSP: { visible: true, enable: false }, Expiry: { visible: true, enable: false }, Legs: 2, BuySell: { visible: true, enable: false }, Contract: { visible: true, enable: false }, Basis: { visible: true, enable: false }, Rate: { visible: true, enable: false }, Pip: { visible: true, enable: false} },
CANCEL_true_TRAILINGSTOP_ASSP:{orderlabel:{visible:true},product:{visible:true,enable:false},orderType:{visible:true,enable:false},ASSP:{visible:true,enable:false},Expiry:{visible:true,enable:false},Legs:1,BuySell:{visible:true,enable:false},Contract:{visible:true,enable:false},Basis:{visible:true,enable:false},Rate:{visible:true,enable:false},Pip:{visible:true,enable:false}}
};


GAIN.Utility = {};

GAIN.Utility.populateDropDown = function(dropdown, associateArray, keyArray) {
    dropdown.options.length = 0;
    var i = 0;
    if (keyArray != null) {
        if (associateArray != null) {

            for (i = 0; i < keyArray.length; i++) {
                try {
                    dropdown.options[i] = new Option(associateArray[keyArray[i]].text, keyArray[i]);
                } catch (e) {

                };
            };
        } else {

            for (i = 0; i < keyArray.length; i++) {
                try {
                    dropdown.options[i] = new Option(keyArray[i], keyArray[i]);
                } catch (e) { };
            };
        };

    } else {


        i = 0;
        for (key in associateArray) {
            dropdown.options[i] = new Option(associateArray[key].text, associateArray[key].value);
            i++;
        };
    };
};

GAIN.Utility.setDropDownValue = function (dropdown, value){
    if (isNaN(value)){
        if (value >= -1 && value < dropdown.options.length){
            dropdown.selectedIndex = value;
        };
    }else{
        
		for (var i=0;i < dropdown.options.length ; i++) {
			if (dropdown.options[i].value == value){
				dropdown.selectedIndex = i;
				break;
		    }
		};        
    };
};

GAIN.Utility.cutRateIn3Parts = function(rate, iDecimal){
    var index = rate.indexOf(".");
    if (index == 0) {rate = "0" + rate; index++;}
    else if (index == -1) {index = rate.length; rate = rate + ".";};
    var NoOfDecimal = iDecimal - (rate.length - (index + 1));
    for (var i=0; i < NoOfDecimal; i++){
        rate = rate + "0";
    }
    if (iDecimal == 5 || iDecimal == 3){
        return {first:rate.substr(0,rate.length -3),second:rate.substr(rate.length -3,2),third:rate.substr(rate.length -1,1)};
    }else{
        if (rate.substr(rate.length - 1, 1) == '.') {
            rate = rate.substr(0, rate.length - 1);
        }
        return {first:rate.substr(0,rate.length -2),second:rate.substr(rate.length -2,2),third:""};
    };
};

GAIN.Utility.cutProductRateIn3Parts = function(product, rate){
    var index = rate.indexOf(".");
    var aProductInfo = aTradingManager.ProductSettingObject.data.get(product);

    if (index == 0) {rate = "0" + rate; index++;}
    else if (index == -1) {index = rate.length; rate = rate + ".";};
    var NoOfDecimal = aProductInfo.IDecimals - (rate.length - (index + 1));
    for (var i=0; i < NoOfDecimal; i++){
        rate = rate + "0";
    }
    
    var BoldIndex = index + parseInt(aProductInfo.BoldIndex);
    if (index + parseInt(aProductInfo.SuperScriptIndex) > rate.length - 1){
        return {first:rate.substr(0,BoldIndex),second:rate.substr(BoldIndex,2),third:""};
    }else{
        return {first:rate.substr(0,BoldIndex),second:rate.substr(BoldIndex,2),third:rate.substr(index + parseInt(aProductInfo.SuperScriptIndex),1)};
    }
    
    /*if (iDecimal == 5 || iDecimal == 3){
        return {first:rate.substr(0,rate.length -3),second:rate.substr(rate.length -3,2),third:rate.substr(parseInt(aProductInfo.SuperScriptIndex),1)};
    }else{
        if (rate.substr(rate.length - 1, 1) == '.') {
            rate = rate.substr(0, rate.length - 1);
        }
        return {first:rate.substr(0,rate.length -2),second:rate.substr(rate.length -2,2),third:""};
    };*/
};

//-------TradingManager-----------------------------------------------------------------------------------

GAIN.TradingManager = function(config, initPara) {
    GAIN.TradingManager.superclass.constructor.call(this);
    this.addEvents({
        "RatesUpdating": true,
        "PositionUpdating": true,
        "OrderUpdating": true,
        "MarginUpdating": true,
        "AccountSettingUpdating": true,
        "ProductSettingUpdating": true,
        "RatesUpdated": true,
        "PositionUpdated": true,
        "OrderUpdated": true,
        "MarginUpdated": true,
        "AccountSettingUpdated": true,
        "ProductSettingUpdated": true,
        "RatesUpdateFailed": true,
        "PositionUpdateFailed": true,
        "OrderUpdateFailed": true,
        "MarginUpdateFailed": true,
        "AccountSettingUpdateFailed": true,
        "ProductSettingUpdateFailed": true,
        "DealUpdateFailed": true,
        "EditOrder": true,
        "Logout": true,
        "NetworkFailure": true,
        "Initialized": true
    });

    /*Reading from ProductSettingObj//this.defaultOrderPip = 30;*/
    this.defaultTrailingPip = 10;
    this.isPlacingDeal = false;
    this.isPlacingOrder = false;
    this.LoginStatus = false;
    this.NetworkFailureThrehold = 15;
    this.EditingOrder = null; //action, OrderID, isASSP

    //var DealListingPair = null; // = null;
    var preRates = null;
    this.Rates = null;
    this.Positions = null;
    this.Margin = null;
    this.Orders = null;
    this.Deals = null;
    Ext.apply(this, config);

    var noOfconsecutiveFailure = 0;
    this.LoginStatus = (initPara.LoginStatus) ? initPara.LoginStatus : this.LoginStatus;
    this.NetworkFailureThrehold = (initPara.NetworkFailureThrehold) ? initPara.NetworkFailureThrehold : this.NetworkFailureThrehold;

    function reset_noOfconsecutiveFailure() {
        noOfconsecutiveFailure = 0;
    };
    this.isInitialized = function() {
        //should be replaced by actual object status
        try {
            //            alert(this.AccountSettingObject.status.enabled  + " " + this.AccountSettingObject.status.dataInit + " " + this.ProductSettingObject.status.enabled + " "
            //            + this.ProductSettingObject.status.dataInit  + " " + this.RateObject.status.enabled + " " + this.RateObject.status.dataInit + " "
            //            + this.DealsObject.status.enabled  + " " + this.DealsObject.status.dataInit + " " + this.PositionsObject.status.enabled + " "
            //            + this.PositionsObject.status.dataInit  + " " + this.MarginObject.status.enabled + " " + this.MarginObject.status.dataInit + " "
            //            + this.OrdersObject.status.enabled  + " " + this.OrdersObject.status.dataInit 
            //               );
            if (this.AccountSettingObject.status.enabled && !this.AccountSettingObject.status.dataInit) return false;
            if (this.ProductSettingObject.status.enabled && !this.ProductSettingObject.status.dataInit) return false;
            if (this.RateObject.status.enabled && (!this.RateObject.status.dataInit || this.Rates == null)) return false;
            if (this.DealsObject.status.enabled && !this.DealsObject.status.dataInit) return false;
            if (this.PositionsObject.status.enabled && (!this.PositionsObject.status.dataInit || this.Positions == null)) return false;
            if (this.MarginObject.status.enabled && (!this.MarginObject.status.dataInit || this.Margin == null)) return false;
            if (this.OrdersObject.status.enabled && (!this.OrdersObject.status.dataInit || this.Orders == null)) return false;

            return true;
        } catch (e) { return false; };

    };

    function checkInitialization() {
        if (this.isInitialized()) {
            this.fireEvent('Initialized');
        };
    }





    var ratesUpdated = function() {
        //        if (preRates == null)
        //        {
        //            preRates = this.Rates.clone(); 
        //        }else{
        //            this.Rates.eachKey(function(){
        //                if (preRates.get(key)){
        //                    preRates.get(key).Bid = item.Bid;
        //                };
        //            }, this);
        //        }
        //Ext.destroy(preRates);
        if (this.RateObject.data.getcount == 0) return;
        preRates = this.Rates;
        var isInit = (this.Rates == null);
        this.Rates = this.RateObject.data.clone();
        if (isInit) { checkInitialization.call(this) };

        // update rate change up/down
        if (preRates == null) {
            for (var i = 0; i < this.Rates.getCount; i++) {
                this.Rates.get(i).upDown = 0;
            };
        } else {

            for (var i1 = 0; i1 < this.Rates.getCount(); i1++) {
                var key = this.Rates.getKey(this.Rates.get(i1));
                if (!preRates.get(key)) {
                    this.Rates.get(i1).upDown = 0;
                } else {
                    var comparsion = 0;
                    try {
                        var temp = parseFloat(this.Rates.get(key).Bid) - parseFloat(preRates.get(key).Bid);

                        if (isNaN(temp)) {
                            comparsion = 0;
                        } else {

                            if (temp > 0) comparsion = 1;
                            if (temp == 0) comparsion = 0;
                            if (temp < 0) comparsion = -1;
                        };

                    } catch (e) { }
                    this.Rates.get(i1).upDown = comparsion;

                    comparsion = 0;
                    try {
                        var temp2 = parseFloat(this.Rates.get(key).Offer) - parseFloat(preRates.get(key).Offer);
                        if (isNaN(temp2)) {
                            comparsion = 0;
                        } else {

                            if (temp2 > 0) comparsion = 1;
                            if (temp2 == 0) comparsion = 0;
                            if (temp2 < 0) comparsion = -1;
                        };
                    } catch (e) { }
                    this.Rates.get(i1).OfferupDown = comparsion;

                    try {
                        if (this.Rates.get(key).ChangeInPoints) {
                            this.Rates.get(key).ChangeInPip = this.getPipDifference(key, 0, this.Rates.get(key).ChangeInPoints);
                        }
                    } catch (e) { }


                };

            };
        };
        this.fireEvent('RatesUpdated');

        //update position
        positionsUpdated.call(this, false);   //positionUpdate will call Margin Update at the end and it also include deals update
        
        //update order
        ordersUpdated.call(this, false);

        return true;
    };

    var positionsUpdated = function(isPositionUpdate) {
        if (this.PositionsObject.status.enabled == false && !isPositionUpdate) {
            return false;
        };

        var tempPositions;
        if (isPositionUpdate) {
            tempPositions = this.PositionsObject.data.clone();
            for (var i = 0; i < tempPositions.getCount(); i++) {
                tempPositions.get(i).Deals = [];
            }
        } else {
            if (this.Positions == null)
                return false;
            else
                tempPositions = this.Positions;
        };
        var tempRates = this.Rates;
        for (var i2 = 0; i2 < tempPositions.getCount(); i2++) {
            var aposition = tempPositions.get(i2);
            try {

                var key = tempPositions.getKey(tempPositions.get(i2));
                if (tempRates.get(key)) {
                    aposition.LRate = tempRates.get(key).Bid;
                    aposition.upDown = tempRates.get(key).upDown;
                    if (this.PositionsObject.hasPLPip) {
                        if (parseInt(aposition.Contract) > 0) {
                            aposition.PLPip = this.getPipDifference(key, aposition.AverageRate, tempRates.get(key).Bid);
                        } else {
                            aposition.PLPip = this.getPipDifference(key, tempRates.get(key).Offer, aposition.AverageRate);
                        };
                    };
                }
            } catch (e) { };
            try {
                if (this.PositionsObject.hasUnRealizedPL) {
                    this.getUnRealizedPnl(aposition);
                };
            } catch (e) { };

        };
        var isInit = (this.Positions == null);
        this.Positions = tempPositions;
        if (isInit) { checkInitialization.call(this) };
        //do P/L calculation

        //update Deals
        if (updateDeals.call(this, isPositionUpdate) == false)
            this.fireEvent('PositionUpdated');
        
        dealsUpdated.call(this,false);
        
        marginUpdated.call(this, false);

        return true;
    };


    var dealsUpdated = function() {
        if (!this.DealsObject.jsonPara.product || this.DealsObject.jsonPara.product == "") {
            return false;
        };

        var tempDeals;
        tempDeals = this.DealsObject.data.clone();
        var tempRates = this.Rates;
        for (var i = 0; i < tempDeals.getCount(); i++) {
            try {
                var key = tempDeals.get(i).Product;
                if (tempRates.get(key)) {
                    tempDeals.get(i).LRate = tempRates.get(key).Bid;
                    tempDeals.get(i).upDown = tempRates.get(key).upDown;
                    if (this.PositionsObject.hasPLPip) {
                        if (parseInt(tempDeals.get(i).Contract) > 0) {
                            tempDeals.get(i).PLPip = this.getPipDifference(key, tempDeals.get(i).Rate, tempRates.get(key).Bid);
                        } else {
                            tempDeals.get(i).PLPip = this.getPipDifference(key, tempRates.get(key).Offer, tempDeals.get(i).Rate);
                        };
                    };
                    if (this.PositionsObject.hasUnRealizedPL) {
                        tempDeals.get(i).AverageRate = tempDeals.get(i).Rate;
                        this.getUnRealizedPnl(tempDeals.get(i));
                    };
                };
            } catch (e) { };

        };
        //do P/L calculation        

        this.Deals = tempDeals;


        //update Deals
        try {
            for (var i2 = 0; i2 < this.Positions.getCount(); i2++) {
                this.Positions.get(i2).Deals = [];
            };
            for (var i3 = 0; i3 < tempDeals.getCount(); i3++) {
                var aPair = tempDeals.get(i3).Product;
                this.Positions.get(aPair).Deals.push(tempDeals.get(i3));
            };
        } catch (e) { };

        this.fireEvent('PositionUpdated');

        return true;
    };


    var updateDeals = function(isPositionUpdate) {
        if (!this.DealsObject.jsonPara.product || this.DealsObject.jsonPara.product == null || this.DealsObject.jsonPara.product == '') {
            return false;
        };

        if (!isPositionUpdate) {
            //update rates on deals collection
            var tempRates = this.Rates;
            for (var i = 0; i < this.Positions.getCount(); i++) {
                if (this.Positions.get(i).Deals && this.Positions.get(i).Deals.length > 0) {
                    var key = this.Positions.getKey(this.Positions.get(i));
                    if (tempRates.get(key)) {
                        try {
                            for (var j; j < this.Positions.get(i).Deals.length; j++) {
                                this.Positions.get(key).Deals[j].LRate = tempRates.get(key).Bid;
                                this.Positions.get(key).Deals[j].upDown = tempRates.get(key).upDown;
                                
                                if (this.PositionsObject.hasPLPip) {
                                    if (parseInt(this.Positions.get(key).Deals[j].Contract) > 0) {
                                        this.Positions.get(key).Deals[j].PLPip = this.getPipDifference(key, this.Positions.get(key).Deals[j].Rate, tempRates.get(key).Bid);
                                    } else {
                                        this.Positions.get(key).Deals[j].PLPip = this.getPipDifference(key, tempRates.get(key).Offer, this.Positions.get(key).Deals[j].Rate);
                                    };
                                };
                                if (this.PositionsObject.hasUnRealizedPL) {
                                    this.Positions.get(key).Deals[j].AverageRate = this.Positions.get(key).Deals[j].Rate;
                                    this.getUnRealizedPnl(tempDeals.get(i));
                                };
                            };
                        } catch (e) { };
                    };
                };


            };
            // P/L update for deals

            this.fireEvent('PositionUpdated');
            return true;

        } else {
            //make ajax call to get latest deal list
            this.DealsObject.requestData(1, true);
            return true;
        };

    };


    var marginUpdated = function(isMarginUpdate) {

        if (this.MarginObject.status.enabled == false) {
            return false;
        };

        if (isMarginUpdate) {
            var isInit = (this.Margin == null);
            this.Margin = this.MarginObject.data;
            if (isInit) { checkInitialization.call(this) };
        };

        //Margin Calculation
        try {
            var tempPositions = this.Positions;
            var tempUnrealised = 0;
            var tempUnrealisedInUSD = 0;
            var RequiredMargin = 0;
            //console.log('start margin');
            var BlowoutLevel = parseFloat(this.AccountSettingObject.data.BlowOutLevel);
            //console.log('BlowoutLevel ' + BlowoutLevel);
            for (var i = 0; i < tempPositions.getCount(); i++) {
                tempUnrealised = tempUnrealised + parseFloat(tempPositions.get(i).Unrealized);
                //console.log('tempUnrealised ' + tempUnrealised);
                tempUnrealisedInUSD = tempUnrealisedInUSD + tempPositions.get(i).UnrealizedinUSD;
                //console.log('tempUnrealisedInUSD ' + tempUnrealisedInUSD);
                var MarginFactor = this.ProductSettingObject.data.get(tempPositions.get(i).Product).MarginFactor;
                //console.log('MarginFactor ' + MarginFactor);
                RequiredMargin = RequiredMargin + Math.abs(parseFloat(tempPositions.get(i).USDValue)) * MarginFactor / 100;
                //console.log('RequiredMargin ' + RequiredMargin);
            }

            this.Margin[0].UnrealizedProfit = tempUnrealised.toFixed(2);

            var MarginBalanceUSD = parseFloat(this.Margin[0].USDPostedMargin) + parseFloat(this.Margin[0].USDRealizedProfit) + tempUnrealisedInUSD;
            //console.log('MarginBalanceUSD ' + MarginBalanceUSD);
            if (MarginBalanceUSD > 0) {
                this.Margin[0].Meter = 100 * (1 - RequiredMargin * BlowoutLevel / 100 / MarginBalanceUSD);
            } else {
                this.Margin[0].Meter = 0;
            };
            //console.log('Meter ' +  this.Margin[0].Meter);    

        } catch (e) { };


        this.fireEvent('MarginUpdated');
        return true;
    };


    var ordersUpdated = function(isOrderUpdate) {
        if (this.OrdersObject.status.enabled == false) {
            return false;
        };

        var tempOrder;
        if (isOrderUpdate) {
            tempOrder = this.OrdersObject.data.clone();
        } else {
            if (this.Orders == null)
                return false;
            else
                tempOrder = this.Orders;
        };
        
        var tempRates = this.Rates;
        if (tempRates != null) {
            for (var i = 0; i < tempOrder.getCount(); i++) {
                var key = tempOrder.get(i).Product;
                if (tempRates.get(key)) {
                    tempOrder.get(i).LRate = tempRates.get(key).Bid;
                    tempOrder.get(i).upDown = tempRates.get(key).upDown;
                    for (var j = 0; j < tempOrder.get(i).Legs.length; j++) {
                        tempOrder.get(i).Legs[j].RDiff = this.getRateDifference(key, tempOrder.get(i).Legs[j].Rate, tempRates.get(key).Bid);
                    }
                }
            };
        };

        var isInit = (this.Orders == null);
        this.Orders = tempOrder;
        if (isInit) { checkInitialization.call(this) };

        this.fireEvent('OrderUpdated');
        return true;
    };

    function AccountSettingUpdated() {
        this.fireEvent('AccountSettingUpdated');
    };

    function ProductSettingUpdated() {
        this.fireEvent('ProductSettingUpdated');
    };

    function disableTradingObjects() {
        this.CheckStatusObject.status.enabled = false;
        this.AccountSettingObject.status.enabled = false;
        this.ProductSettingObject.status.enabled = false;
        this.RateObject.status.enabled = false;
        this.DealsObject.status.enabled = false;
        this.PositionsObject.status.enabled = false;
        this.MarginObject.status.enabled = false;
        this.OrdersObject.status.enabled = false;
    };

    function fireInternalEvent(eventName) {
        if (eventName.indexOf('Failed' > -1)) {
            noOfconsecutiveFailure++;
            if (noOfconsecutiveFailure > this.NetworkFailureThrehold) {
                //disableTradingObjects.call(this);
                reset_noOfconsecutiveFailure();
                this.fireEvent("NetworkFailure");

            };
        };

        this.fireEvent(eventName);
    };

    function CheckStatusUpdated() {
        reset_noOfconsecutiveFailure();

        if (this.LoginStatus == true && this.CheckStatusObject.data != true) {
            disableTradingObjects.call(this);
            this.fireEvent("Logout");
        }
    };

    this.CheckStatusObject = new GAIN.CheckStatus({ url: ui + "/GetStatus", refreshInterval: 30000 });
    this.CheckStatusObject.addListener('Loaded', CheckStatusUpdated.createDelegate(this));
    this.CheckStatusObject.addListener('LoadFailed', fireInternalEvent.createDelegate(this, ["CheckStatusUpdateFailed"]));

    var AccountSettingsPara = initPara.AccountSettings;
    if (!AccountSettingsPara) AccountSettingsPara = { url: ui + "/GetAccountSettings", refreshInterval: 2000, status: { requesting: false, dataReady: false, init: false, repeatable: false, dataInit: false, enabled: true} };
    this.AccountSettingObject = new GAIN.AccountSettings(AccountSettingsPara);
    this.AccountSettingObject.addListener('dataInit', checkInitialization.createDelegate(this));
    this.AccountSettingObject.addListener('Loaded', AccountSettingUpdated.createDelegate(this));
    this.AccountSettingObject.addListener('Loaded', reset_noOfconsecutiveFailure);
    this.AccountSettingObject.addListener('Updating', fireInternalEvent.createDelegate(this, ["AccountSettingUpdating"]));
    this.AccountSettingObject.addListener('LoadFailed', fireInternalEvent.createDelegate(this, ["AccountSettingUpdateFailed"]));

    var ProductSettingsPara = initPara.ProductSettings;
    if (!ProductSettingsPara) ProductSettingsPara = { url: ui + "/GetProductSettings", refreshInterval: 2000, status: { requesting: false, dataReady: false, init: false, repeatable: false, dataInit: false, enabled: true} };
    this.ProductSettingObject = new GAIN.ProductSettings(ProductSettingsPara);
    this.ProductSettingObject.addListener('dataInit', checkInitialization.createDelegate(this));
    this.ProductSettingObject.addListener('Loaded', ProductSettingUpdated.createDelegate(this));
    this.ProductSettingObject.addListener('Loaded', reset_noOfconsecutiveFailure);
    this.ProductSettingObject.addListener('Updating', fireInternalEvent.createDelegate(this, ["ProductSettingUpdating"]));
    this.ProductSettingObject.addListener('LoadFailed', fireInternalEvent.createDelegate(this, ["ProductSettingUpdateFailed"]));

    var RatesPara = initPara.Rates;
    if (!RatesPara) RatesPara = { url: ui + "/GetUserRates", refreshInterval: 2000 };
    this.RateObject = new GAIN.Rates(RatesPara);
    this.RateObject.addListener('dataInit', checkInitialization.createDelegate(this));
    this.RateObject.addListener('Loaded', ratesUpdated.createDelegate(this));
    this.RateObject.addListener('Loaded', reset_noOfconsecutiveFailure);
    this.RateObject.addListener('Updating', fireInternalEvent.createDelegate(this, ["RatesUpdating"]));
    this.RateObject.addListener('LoadFailed', fireInternalEvent.createDelegate(this, ["RatesUpdateFailed"]));

    var DealsPara = initPara.Deals;
    if (!RatesPara) DealsPara = { url: ui + "/GetProductDeals", refreshInterval: 30000, status: { requesting: false, dataReady: false, init: false, repeatable: false, dataInit: false, enabled: false }, jsonPara: { product: ''} };
    this.DealsObject = new GAIN.Deals(DealsPara);
    this.DealsObject.addListener('dataInit', checkInitialization.createDelegate(this));
    this.DealsObject.addListener('Loaded', dealsUpdated.createDelegate(this));
    this.DealsObject.addListener('Loaded', reset_noOfconsecutiveFailure);
    this.DealsObject.addListener('LoadFailed', fireInternalEvent.createDelegate(this, ["DealUpdateFailed"]));


    var PositionsPara = initPara.Positions;
    if (!PositionsPara) PositionsPara = { url: ui + "/GetPositions", refreshInterval: 30000 };
    this.PositionsObject = new GAIN.Positions(PositionsPara);
    this.PositionsObject.addListener('dataInit', checkInitialization.createDelegate(this));
    this.PositionsObject.addListener('Loaded', positionsUpdated.createDelegate(this, [true]));
    this.PositionsObject.addListener('Loaded', reset_noOfconsecutiveFailure);
    this.PositionsObject.addListener('Updating', fireInternalEvent.createDelegate(this, ["PositionUpdating"]));
    this.PositionsObject.addListener('LoadFailed', fireInternalEvent.createDelegate(this, ["PositionUpdateFailed"]));

    var MarginPara = initPara.Margin;
    if (!MarginPara) MarginPara = { url: ui + "/GetMargins", refreshInterval: 30000 };
    this.MarginObject = new GAIN.Margin(MarginPara);
    this.MarginObject.addListener('dataInit', checkInitialization.createDelegate(this));
    this.MarginObject.addListener('Loaded', marginUpdated.createDelegate(this, [true]));
    this.MarginObject.addListener('Loaded', reset_noOfconsecutiveFailure);
    this.MarginObject.addListener('Updating', fireInternalEvent.createDelegate(this, ["MarginUpdating"]));
    this.MarginObject.addListener('LoadFailed', fireInternalEvent.createDelegate(this, ["MarginUpdateFailed"]));

    var OrdersPara = initPara.Orders;
    if (!OrdersPara) OrdersPara = { url: ui + "/GetOrders", refreshInterval: 30000 };
    this.OrdersObject = new GAIN.Orders(OrdersPara);
    this.OrdersObject.addListener('dataInit', checkInitialization.createDelegate(this));
    this.OrdersObject.addListener('Loaded', ordersUpdated.createDelegate(this, [true]));
    this.OrdersObject.addListener('Loaded', reset_noOfconsecutiveFailure);
    this.OrdersObject.addListener('Updating', fireInternalEvent.createDelegate(this, ["OrderUpdating"]));
    this.OrdersObject.addListener('LoadFailed', fireInternalEvent.createDelegate(this, ["OrderUpdateFailed"]));

    //Place Deal method
    //Close Deal
    this.PlaceDeal = function(dealType, aDealData, isClose, aCallback) {
        if (!this.isPlacingDeal) {
            this.isPlacingDeal = true;
            var aConnection = new Ext.data.Connection();
            aConnection.request(
                    {
                        url: ui + "/PlaceDeal",
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        scope: this,
                        jsonData: { aType: dealType, aDeal: aDealData, isClose: isClose },
                        callback: function(options, success, response) {
                
                            var temp = null;
                            
                            if (success) {
                                temp = Ext.util.JSON.decode(response.responseText);
                                this.PositionsObject.requestData(1, true);
                                this.OrdersObject.requestData(1, true);
                            }
                            try{
                            aCallback(success, temp);}
                            catch(e){;}
                            this.isPlacingDeal = false;
                        }
                    });
            return { success: true, message: GAIN.messageDealProcessing };
        } else {
            return { success: false, message: GAIN.messageAnotherDealProcessing };
        };
    };
    //place Order method
    //Modify Order method
    this.PlaceOrder = function PlaceOrder(action, aOrderData, aCallback) {

        if (!this.isPlacingOrder) {
            if (action != 'CANCEL' && (aOrderData.Type == 'TRAILINGSTOP' || aOrderData.Type == 'TRAILINGSTOP_ASSP')) {
                var tempPS = this.ProductSettingObject.data.get(aOrderData.Product);
                if (parseFloat(aOrderData.TrailingPoints) < tempPS.PipDifference || parseFloat(aOrderData.TrailingPoints) > tempPS.MaxOrderPips) {
                    return { success: false, message: GAIN.TrailingStopPipErrorMessage + '(' + tempPS.PipDifference + ' - ' + tempPS.MaxOrderPips + ' )' };
                };
            };
            this.isPlacingOrder = true;
            var aConnection = new Ext.data.Connection();
            aConnection.request(
                {
                    url: ui + "/OrderRequest",
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    scope: this,
                    jsonData: { aAction: action, aOrder: aOrderData },
                    callback: function(options, success, response) {
                        this.isPlacingOrder = false;
                        var temp = null;
                        if (success) {
                            temp = Ext.util.JSON.decode(response.responseText);
                            this.PositionsObject.requestData(1, true);
                            this.OrdersObject.requestData(1, true);
                        }

                        aCallback(success, temp);
                    }
                })
            return { success: true, message: GAIN.messageOrderProcessing };
        } else {
            return { success: false, message: GAIN.messageAnotherOrderProcessing };
        };
    };

    //Edit Order 
    this.EditOrderInDock = function(ActionType, OrderID, isASSP, product, LimitStop, fromDeal) {
        if (this.isPlacingDeal || this.isPlacingOrder) return;

        var OrderType = null;
        if (OrderID == null && isASSP == true) {
            var aposition;
            try {
                aposition = this.Positions.get(product);
            } catch (e) { };

            if (fromDeal) {
                OrderType = 'OCO_ASSP';
            } else {
                if (aposition) {
                    if (aposition.LimitRate != 0 || aposition.StopRate != 0) {
                        ActionType = 'MODIFY';
                        var tempOrders = this.Orders;
                        try {
                            
                            for (var i = 0; i < tempOrders.getCount(); i++) {
                                if (tempOrders.get(i).Product == product && tempOrders.get(i).Assp == 'True') {
                                    var aOrder = tempOrders.get(i);
                                    OrderID = aOrder.ReferenceNumber;
                                    if (aOrder.Type == 'TRAILINGSTOP_ASSP') {
                                        //alert('Trailing stop cannot be modified!!');
                                        //return;
                                        ActionType = 'CANCEL';
                                        OrderType = 'TRAILINGSTOP_ASSP';
                                        break;
                                    }
                                    if ((aOrder.Type == 'SINGLE_ASSP' || aOrder.Type == 'SINGLE_ASSP_LIMIT' || aOrder.Type == 'SINGLE_ASSP_STOP') && aOrder.Legs[0].Basis != LimitStop) {
                                        OrderType = 'OCO_ASSP';
                                        break;
                                    };
                                };
                            };
                        } catch (e) { };
                    } else { OrderType = 'OCO_ASSP'; };
                } else {
                    //not decide yet
                    OrderType = 'OCO_ASSP';
                };
            };


        }

        this.EditingOrder = { action: ActionType, orderID: OrderID, isASSP: isASSP, product: product, LimitStop: LimitStop, OrderType: OrderType };
        this.fireEvent('EditOrder');
    };

    this.updateDealListingPair = function(Pair) {
        this.DealsObject.jsonPara.product = Pair;
        if (Pair == '') {
            for (var i = 0; i < this.Positions.getCount(); i++) {
                this.Positions.get(i).Deals = [];
            };
            this.fireEvent('PositionUpdated');
        } else {
            this.DealsObject.requestData(1, true);
        };
    };

    this.getOrderSpinnerInfoModify = function(Order, OrderSeq) {

        var aOrder = this.Orders.get(Order);
        var aOrderType = aOrder.Type;
//        if (newOrderType != null) {
//            aOrderType = newOrderType;
//        };

        if (!aOrder) return null;

        var aLeg = aOrder.Legs[OrderSeq];
        if (!aLeg) {
            aLeg = {};
            if (aOrder.Type == 'SINGLE_ASSP' || aOrder.Type == 'SINGLE_ASSP_LIMIT' || aOrder.Type == 'SINGLE_ASSP_STOP') {
                aLeg.BuySell = aOrder.Legs[0].BuySell;
                if (aOrder.Legs[0].Basis == 'T') {
                    aLeg.Basis = 'S';
                }
                else {
                };
                aLeg.Rate = null;
                aLeg.TSP = 0;
                aLeg.Amount = aOrder.Legs[0].Amount;
                aOrderType = "OCO_ASSP";
            } else {
                return null;
            };

        };

        var tempPip = null;
        if (aLeg.TSP != 0) tempPip = aLeg.TSP;

        return this.getOrderSpinnerInfoNew(aOrder.Product, aLeg.BuySell, aLeg.Basis, aLeg.Rate, tempPip, aOrderType, aLeg.Amount, aOrder.Legs[0].Rate, OrderSeq);
    };

    this.getOrderSpinnerInfoNew = function(product, BuySell, LimitStop, inputRate, inputPip, OrderType, orderAmount, firstLegRate, seq) {
        var increment;
        var outputRate;
        var outputPip;
        var outputLimitStop;
        var outputBuySell;
        var outputSize;
        var noOfDecimal;

        var aposition = null;
        try {
            aposition = this.Positions.get(product);
        } catch (e) { };

        var aLRate = this.Rates.get(product);
        var aProductInfo = this.ProductSettingObject.data.get(product);
        if (!aLRate) return null;

        noOfDecimal = this.getNoOfDemicalPlace(product);
        if (noOfDecimal==null) return null;
        increment = 1 / Math.pow(10, noOfDecimal);
        //logic for getting increment, rate and pip
        //alert(OrderType);
        switch (OrderType) {
            case "MARKET_ORDER":

                if (BuySell == 'B')
                    return { BuySell: BuySell, LimitStop: null, Rate: aLRate.Offer, Pip: 0, increment: increment, size: outputSize, decimalPlaces: noOfDecimal };
                else
                    return { BuySell: BuySell, LimitStop: null, Rate: aLRate.Bid, Pip: 0, increment: increment, size: outputSize, decimalPlaces: noOfDecimal };
                break;
            case "SINGLE_ORDER":
            case "SINGLE_ORDER_STOP":
            case "SINGLE_ORDER_LIMIT":
            case "OCO_ORDER":

                outputRate = inputRate;
                outputLimitStop = LimitStop;
                outputBuySell = BuySell;

                if (outputBuySell == 'B') {
                    if (inputRate) {
                        outputPip = this.getPipDifference(product, aLRate.Offer, inputRate);
                    } else {
                        if (inputPip) {
                            outputPip = inputPip;
                        } else {
                            if (LimitStop == 'T') {
                                outputPip = aProductInfo.OrderPipsAway * -1;
                            } else {
                                outputPip = aProductInfo.OrderPipsAway;
                            };
                        };
                        outputRate = this.getRatePlusPip(product, aLRate.Offer, outputPip);
                    };
                } else {
                    if (inputRate) {
                        outputPip = this.getPipDifference(product, aLRate.Bid, inputRate);
                    } else {
                        if (inputPip) {
                            outputPip = inputPip;
                        } else {
                            if (LimitStop == 'T') {
                                outputPip = aProductInfo.OrderPipsAway;
                            } else {
                                outputPip = aProductInfo.OrderPipsAway * -1;
                            };
                        };
                        outputRate = this.getRatePlusPip(product, aLRate.Bid, outputPip);
                    };
                };
                if (orderAmount != null) {
                    outputSize = orderAmount.replace("-", "");
                };

                break;
            case "IF_THEN":
            case "IF_THEN_OCO":
                outputRate = inputRate;
                outputLimitStop = LimitStop;
                outputBuySell = BuySell;


                if (outputBuySell == 'B') {
                    if (inputRate) {

                        if (seq != 0) {
                            outputPip = this.getPipDifference(product, firstLegRate, inputRate);
                        } else {
                            outputPip = this.getPipDifference(product, aLRate.Offer, inputRate);
                        };
                    } else {
                        if (inputPip) {
                            outputPip = inputPip;
                        } else {
                            if (LimitStop == 'T') {
                                outputPip = aProductInfo.OrderPipsAway * -1;
                            } else {
                                outputPip = aProductInfo.OrderPipsAway;
                            };
                        };
                        if (seq != 0) {
                            outputRate = this.getRatePlusPip(product, firstLegRate, outputPip);
                        } else {
                            outputRate = this.getRatePlusPip(product, aLRate.Offer, outputPip);
                        };

                    };
                } else {
                    if (inputRate) {
                        if (seq != 0) {
                            outputPip = this.getPipDifference(product, firstLegRate, inputRate);
                        } else {
                            outputPip = this.getPipDifference(product, aLRate.Bid, inputRate);
                        };
                    } else {
                        if (inputPip) {
                            outputPip = inputPip;
                        } else {
                            if (LimitStop == 'T') {
                                outputPip = aProductInfo.OrderPipsAway;
                            } else {
                                outputPip = aProductInfo.OrderPipsAway * -1;
                            };
                        };

                        if (seq != 0) {
                            outputRate = this.getRatePlusPip(product, firstLegRate, outputPip);
                        } else {
                            outputRate = this.getRatePlusPip(product, aLRate.Bid, outputPip);
                        };
                    };
                };
                if (orderAmount != null) {
                    outputSize = orderAmount.replace("-", "");
                };

                break;
            case "SINGLE_ASSP":
            case "SINGLE_ASSP_STOP":
            case "SINGLE_ASSP_LIMIT":
            case "OCO_ASSP":
                if (!aposition) return null;
                if (parseInt(aposition.Contract) >= 0) outputBuySell = "S";
                else outputBuySell = "B";

                outputRate = inputRate;
                outputLimitStop = LimitStop;
                //alert(aposition.Contract);
                outputSize = Math.abs(aposition.Contract);
                //alert(outputSize);
                if (outputBuySell == 'B') {
                    if (inputRate) {
                        outputPip = this.getPipDifference(product, aposition.AverageRate, inputRate);
                    } else {
                        if (inputPip) {
                            outputPip = inputPip;
                        } else {
                            if (LimitStop == 'T') {
                                outputPip = aProductInfo.OrderPipsAway * -1;
                            } else {
                                outputPip = aProductInfo.OrderPipsAway;
                            };
                        };
                        outputRate = this.getRatePlusPip(product, aposition.AverageRate, outputPip);
                    };
                } else {
                    if (inputRate) {
                        outputPip = this.getPipDifference(product, aposition.AverageRate, inputRate);
                    } else {
                        if (inputPip) {
                            outputPip = inputPip;
                        } else {
                            if (LimitStop == 'T') {
                                outputPip = aProductInfo.OrderPipsAway;
                            } else {
                                outputPip = aProductInfo.OrderPipsAway * -1;
                            };
                        };
                        outputRate = this.getRatePlusPip(product, aposition.AverageRate, outputPip);
                    };
                };
                break;
            case "TRAILINGSTOP_ASSP":
                if (!aposition) return null;
                if (parseInt(aposition.Contract) >= 0) outputBuySell = "S";
                else outputBuySell = "B";
                outputLimitStop = "S";
                outputSize = Math.abs(aposition.Contract);
                if (inputPip) outputPip = inputPip; else outputPip = this.defaultTrailingPip;
                if (outputBuySell == 'B') {
                    outputRate = aLRate.Offer;
                } else {
                    outputRate = aLRate.Bid;
                };


                break;
            case "TRAILINGSTOP":
                //                if (parseInt(aposition.Contract) >= 0) outputBuySell = "S";
                //                else outputBuySell = "B";
                outputBuySell = BuySell;
                outputLimitStop = LimitStop;
                outputSize = orderAmount;
                if (outputBuySell == 'B') {
                    outputRate = aLRate.Offer;
                } else {
                    outputRate = aLRate.Bid;
                };


                if (inputPip) outputPip = inputPip; else outputPip = this.defaultTrailingPip;
                if (outputBuySell == 'B') {
                    outputRate = aLRate.Offer;
                } else {
                    outputRate = aLRate.Bid;
                };
                if (orderAmount != null) {
                    outputSize = orderAmount.replace("-", "");
                };
                break;
            default:
                return null;
                break;
        }


        return { BuySell: outputBuySell, LimitStop: outputLimitStop, Rate: outputRate, Pip: outputPip, increment: increment, size: outputSize, decimalPlaces: noOfDecimal };

    };


    this.getRateDifference = function(product, rate1, rate2) {
        var decmialPlace = this.getNoOfDemicalPlace(product);
        if (decmialPlace!=null) {
            return (parseFloat(rate2) - parseFloat(rate1)).toFixed(decmialPlace);
        } else {
            return null;
        };
    };

    this.getPipDifference = function(product, rate1, rate2) {
        var decimalPlace = this.getNoOfDemicalPlace(product);
        /*
          [iDecimal-(iDecimal MOD 2)]*-1
        10
        */
        if (decimalPlace!=null) {
            var temp;
            //if (decimalPlace == 3 || decimalPlace == 5) temp = decimalPlace - 1; else temp = decimalPlace;
            //return ((parseFloat(rate2) - parseFloat(rate1)) * Math.pow(10, temp)).toFixed(1);
            temp = decimalPlace-(decimalPlace % 2);
            if(isNaN(rate2)){rate2=0;}
            return ((parseFloat(rate2) - parseFloat(rate1)) * Math.pow(10, temp)).toFixed(1);
        } else {

            return null;
        };
    };

    this.getRatePlusPip = function(product, rate, pip) {
        var decimalPlace = this.getNoOfDemicalPlace(product);
        if (decimalPlace!=null) {
            var temp;
            //if (decimalPlace == 3 || decimalPlace == 5) temp = decimalPlace - 1; else temp = decimalPlace;
            temp = decimalPlace-(decimalPlace % 2);
            if(isNaN(pip)){pip=0;}
            return ((parseFloat(rate) + pip / Math.pow(10, temp))).toFixed(decimalPlace);
        } else {
            return null;
        };
    };

    this.getNoOfDemicalPlace = function(product) {
        var temp = this.ProductSettingObject.data.get(product);

        if (temp != null) return temp.IDecimals; else return null;

    };

    this.getRateIncrement = function(product) {
        var decimalPlace = this.getNoOfDemicalPlace(product);
        if (decimalPlace!=null) {
            return 1 / Math.pow(10, decimalPlace);
        } else {
            return null;
        };
    };

    this.getUnRealizedPnl = function(aposition) {
        var BasePair = this.AccountSettingObject.data.BasePair;
        var BaseCurrency = (BasePair == "USD/USD") ? "USD" : BasePair.replace("USD", "").replace("/", "");
        var RateDifference;
        var tempRate = this.Rates;
        if (parseInt(aposition.Contract) > 0) {
            RateDifference = parseFloat(tempRate.get(aposition.Product).Bid) - parseFloat(aposition.AverageRate);
        } else {
            RateDifference = parseFloat(tempRate.get(aposition.Product).Offer) - parseFloat(aposition.AverageRate);
        };
        //console.log("aposition.Product " + aposition.Product); 
        //console.log("RateDifference " + RateDifference); 
        var CurrencyPnL = parseInt(aposition.Contract) * RateDifference
        //console.log("CurrencyPnL " + CurrencyPnL);
        var Unrealized = null;
        if (aposition.Product.substr(4, 3) == BaseCurrency) {
            Unrealized = CurrencyPnL;
            //console.log("right side = basecurrency " + Unrealized);
        } else {
            //console.log("Unrealized F " + Unrealized);
        };


        var RevalRate;
        //console.log(aposition.Product.substr(4,3));
        if (aposition.Product.substr(0, 3) == "USD") {
            if (CurrencyPnL > 0) {
                RevalRate = parseFloat(tempRate.get(aposition.Product).Offer);
            } else {
                RevalRate = parseFloat(tempRate.get(aposition.Product).Bid);
            };
        };
        //console.log("RevalRate " + RevalRate);
        var UnRealizedDollarPnL;
        if (aposition.Product.substr(4, 3) == "USD") {
            UnRealizedDollarPnL = CurrencyPnL;
            //console.log("usd right " + UnRealizedDollarPnL);
        } else if (aposition.Product.substr(0, 3) == "USD") {
            UnRealizedDollarPnL = CurrencyPnL / RevalRate;
            //console.log("usd left " + UnRealizedDollarPnL);
        } else {
            var CounterProduct = this.ProductSettingObject.data.get(aposition.Product).CounterProduct;
            var CounterProductNotation = this.ProductSettingObject.data.get(CounterProduct).Notation;
            //console.log("CounterProduct " + CounterProduct + " " + CounterProductNotation);
            if (CounterProductNotation == "E") {
                if (CurrencyPnL > 0) {
                    UnRealizedDollarPnL = CurrencyPnL / parseFloat(tempRate.get(CounterProduct).Offer);
                } else {
                    UnRealizedDollarPnL = CurrencyPnL / parseFloat(tempRate.get(CounterProduct).Bid);
                };
            } else {
                if (CurrencyPnL > 0) {
                    UnRealizedDollarPnL = CurrencyPnL * parseFloat(tempRate.get(CounterProduct).Bid);
                } else {
                    UnRealizedDollarPnL = CurrencyPnL * parseFloat(tempRate.get(CounterProduct).Offer);
                };
            };
        };

        aposition.UnrealizedinUSD = UnRealizedDollarPnL;

        if (Unrealized == null) {
            //console.log("UnRealizedDollarPnL " + UnRealizedDollarPnL);
            if (BasePair != "USD/USD") {
                var BaseProductNotation = this.ProductSettingObject.data.get(BasePair).Notation;
                //console.log("BaseProductNotation " + CounterProduct + " " + CounterProductNotation);
                if (BaseProductNotation == "E") {
                    if (UnRealizedDollarPnL < 0) {
                        Unrealized = UnRealizedDollarPnL * parseFloat(tempRate.get(BasePair).Offer);
                    } else {
                        Unrealized = UnRealizedDollarPnL * parseFloat(tempRate.get(BasePair).Bid);
                    };
                } else {
                    if (UnRealizedDollarPnL < 0) {
                        Unrealized = UnRealizedDollarPnL / parseFloat(tempRate.get(BasePair).Bid);
                    } else {
                        Unrealized = UnRealizedDollarPnL / parseFloat(tempRate.get(BasePair).Offer);
                    };
                };
            } else {
                Unrealized = UnRealizedDollarPnL;
            };
        };

        aposition.Unrealized = Unrealized.toFixed(2);
    };

    this.initEditOrder = function() {
        var temp = this.ProductSettingObject.data.get(0).Product;
        this.EditingOrder = { action: 'PLACE', orderID: null, isASSP: false, product: temp };
    };
    
    this.getProductAlias = function(product,contract) {
        if(this.ProductSettingObject!=null && this.ProductSettingObject.data!=null & this.ProductSettingObject.data.length>0)
        {
            var pro = this.ProductSettingObject.data.get(product);
            if(pro!=null){
                if(contract && pro.AliasName.indexOf("/")>-1){
                    return pro.AliasName.substr(0,pro.AliasName.indexOf("/"));
                }
                else{return pro.AliasName;}
            }
        }
        return product;
    };
    this.isFlagVisible = function(product) {
        if(this.ProductSettingObject!=null && this.ProductSettingObject.data!=null & this.ProductSettingObject.data.length>0)
        {
            var pro = this.ProductSettingObject.data.get(product);
            if(pro!=null){
                if(pro.AliasName.indexOf("/")>-1){
                    return true;
                }
                else{return false;}
            }
        }
        return true;
    };    
    
};


Ext.extend(GAIN.TradingManager, Ext.util.Observable, {});
/*
this script block is used for closing l=the login panel
if user clicks outside.
*/
var Pnl_State = 0;
Ext.onReady(function() {
	addHandler("click", doOnDocumentClick)
});

function doOnDocumentClick(e) {
	if (Pnl_State == 1) {
		e = e || event;
		var target = e.target || e.srcElement;
		var box = document.getElementById("account_login_panel");
		do {
			if (box == target) {
				return
			}
			target = target.parentNode
		} while (target);
		if (accountLoginPanel.triggerdByEnter) { accountLoginPanel.triggerdByEnter = false; return false; }
		accountLoginPanel.closePanel();
		Pnl_State = 0
	}
}

function addHandler(eventName, handler) {
	if (window.addEventListener) {
		window.addEventListener(eventName, handler, false)
	} else {
		if (window.attachEvent && $("master_body") != null) {
			$("master_body").addEvent("click", function() {
				doOnDocumentClick()
			})
		} else {
			var origHandler = window["on" + eventName];
			if (origHandler) {
				var h = new object();
				h.origHandler = origHandler;
				h.newHandler = handler;
				h.both = new 
                function(e) {
                	this.origHandler(e);
                	this.handler(e)
                };
				window["on" + eventName] = h.both
			} else {
				window["on" + eventName] = handler
			}
		}
	}
};
