// Form Validation Using jQuery
$(document).ready(function(){
	jQuery.validator.messages.required = "";
	jQuery.validator.addMethod("DateOfBirth", function(value, element) {  
	return this.optional(element) || /^\s*(0[1-9]|[12][0-9]|3[01])[-\/.](0[1-9]|1[012])[-\/.](19|20)\d\d\s*$/.test(value);  
	}, "Please enter a valid date of birth.");
	$("form.std_validate").validate({
		errorElement: "span",
		errorClass: "invalid",
		rules: {
			email: {
				required: true,
				email: true
			},
			Email: {
				required: true,
				email: true
			},
			TransferAmount: {
				required: "#transferConsent:checked"
			}
		},
		messages: {
			youherbebyacknowledgethatyou: {
				required: "Please agree to the statement"
			},
			consent: {
				required: "Please agree to the statement"
			},
			Consent: {
				required: "Please agree to the statement"
			},
			transferConsent: {
				required: "Please agree to the statement"
			},
			consentTransfer: {
				required: "Please agree to the statement"
			},
			Confirm: {
				required: "Please agree to the statement"
			}
		}
	});
	$("form").submit(function(){
		$("input.invalid,select.invalid, textarea.invalid").prevAll("label").addClass("validate");
		$("input[type='radio'].invalid").parent().parent().children("label").addClass("validate");
	});
	$("input,select,textarea").change(function(){
		$(this).prevAll("label").removeClass("validate");
	});
	$("input[type='radio']").change(function(){
		$(this).parent().parent().children("label").removeClass("validate");
	});	
	
/* enforce max character length in textarea */
/**
* maxChar jQuery plugin
* @author Mitch Wilson
* @version 0.1.0
* @requires jQuery
* @description Enforces max character limit on any input or textarea HTML element and provides user feedback.
* @see http://mitchwilson.net/2009/08/03/new-jquery-plugin-maxchar/
*/
(function($){  
	$.fn.maxChar = function(limit, options) {
		// Define default settings and override w/ options.	
		settings = jQuery.extend({
			indicator: 'indicator',
			pluralMessage: ' characters remaining',
			rate: 200,
			singularMessage: ' character remaining',
			spaceBeforeMessage: ' '
		}, options);
		// Define local variables.
		var limit = limit;
		var remaining = limit;
		var rate = settings.rate;
		var timer = null;
		var target = $(this);
		var indicator = getIndicator();
		var singularMessage = settings.singularMessage;
		var pluralMessage = settings.pluralMessage;
		// If user did not create indicator, we will create default one for them.
		if(indicator.size() == 0) {
			createIndicator();
			indicator = getIndicator();
		}
		// Create helper functions.
		function update(limit){
			var remaining = limit - target.val().length;
			if(remaining < 1) {
				target.val(target.val().slice(0,limit));
				remaining = 0; // Prevents displaying negative remaining character amounts, such as -1.
			}
			if(remaining == 1) {
				indicator.text(remaining + singularMessage);//'1,000 character limit. ' + 
			} else {
				indicator.text(remaining + pluralMessage);//'1,000 character limit. ' + 
			}
			try {
				if(console) {
					console.log(remaining);
				}
			} catch(e) {
				// Do nothing on error.
			}
		}
		function createIndicator(){
			target.after(settings.spaceBeforeMessage + '<span id="'+settings.indicator+'"></span>');
		}
		function getIndicator(){
			return $('#'+settings.indicator);
		}
		// Call update once on code initialization to update view if text is already in textarea,
		// eg, if user relaoads page or hits back button and form textarea retains previoulsy entered text.
		update(limit);
		// Bind to focus event to active when user starts interacting with textarea.
		$(this).focus(function(){
			if(timer == null) {
				timer = setInterval(function(){update(limit)}, rate);
			}
		});
		// 
		$(this).blur(function() {
			if(timer != null) {
				clearInterval(timer);
				timer = null;
				// Clear manually in case blur happened between timer updates.
				update(limit);
			}
		});
	};
})(jQuery);
/* end maxcharacter textarea */
	
});

// Language Selection
$(document).ready(function(){
	$("#langSelect").click(function(e){
		e.stopPropagation();
		e.cancelBubble = true;
		$(this).toggleClass("toggle").children("ul#langList").slideToggle(250);
	});
	$("body").click(function(){
		$("ul#langList").slideUp(250);
		$("#langSelect").removeClass("toggle");
	});
});

//SetTrendID
function getTrendIdentifier() 
{
    var theDate = "";
    var theCookie = "";
    if ( window.document.cookie != null ) {			 
        theDate = getFxCookie( "tid" );	
        theCookie = getFxCookie( "JSESSIONID" );		 	    
    }		 
    if ( theCookie == null ){
        theCookie = getCookieFx( "jsessionid" );
    }
    if ( theDate  == null ){
        theDate = getCookieFx( "tid" );
    }		 
    if ( theDate == null ) {
        theDate = getFxDate();
        if ( theCookie == null ) {
            theDate = theDate + "_" + Math.random()*1000000000000000000;
        } else {
        theDate = theDate + "_" + theCookie;
    }
    createFxCookie( "tid", theDate, 365 );		 
}		 		 
return theDate;  
}
function getFxDate() {
    var d = new Date();
    var year = "" + d.getFullYear();		 
    year = year.substring(( year.length - 2 ), year.length ); 
    var month = "" + ( d.getMonth() + 1 );
    if ( month.length == 1 ) {
        month = "0" + month;
    }
    var data = "" + d.getDate();
    if ( data.length == 1 ) {
        data = "0" + data;
    }		 
    return ( year + month + data );
} 
function getFxCookie( name ) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf( "; " + prefix );
    if ( begin == -1 ) {
        begin = dc.indexOf( prefix );
        if ( begin != 0 ) return null;
    } else {
    begin += 2;
}
var end = document.cookie.indexOf( ";", begin );
if ( end == -1 ) {
    end = dc.length;
}    
return unescape( dc.substring( begin + prefix.length, end ));
}
function getCookieFx( name ) {
    parm = new Array;
    value = new Array;
    var beg = "" + location.href; 
    
    beg = beg.substring( beg.indexOf( name ) );
    parm = beg.split( '&' );
    for ( i = 0; i < parm.length; i++ ) {
        value[ i ] = parm[ i ].split( '=' ); 
        if ( value[ i ][ 0 ] == name )  return value[ i ][ 1 ];
    }
    return null;
}   
function createFxCookie( name, value, days ) {
    if ( days )	{
        var date = new Date();
        date.setTime( date.getTime() + ( days*24*60*60*1000 ));
        var expires = "; expires=" + date.toGMTString();
    } else {
    var expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}  

// Domain Parser
var reg = /(\w+):\/\/([wW]{3}\.)*([^\/]+)([^# ]*)/;

var url = window.location.href;

var match = url.match(reg);

if ( ! url.match(reg) ) {
    var refdomain = "unknown+domain";
}  else {
var refdomain = match[3];
}

// Account Parser

switch(refdomain) {
    case "refcofx.ca":
    var acctNum="DM540515K0CZ;DM540515HBSB";
    break;
    case "fxcmespanol.com":
    var acctNum="DM540515LFAD;DM540515HBSB";
    break;
    case "fxcm.com":
    var acctNum="DM540515IFZE;DM540515HBSB";
    break;
    case "fxcmfrench.com":
    var acctNum="DM54051579NM;DM540515HBSB";
    break;
    case "fxcmgerman.com":
    var acctNum="DM5405154NDB;DM540515HBSB";
    break;
    case "fxcmitalian.com":
    var acctNum="DM55053168AM;DM540515HBSB";
    break;
    case "fxcmportuguese.com":
    var acctNum="DM551108M9VA;DM540515HBSB";
    break;
    case "fxcmtr.com":
    var acctNum="DM551021HGDA;DM540515HBSB";
    break;
    case "thomsonfx.com":
    var acctNum="DM550405KODN;DM540515HBSB";
    break;
    case "fxcmarabic.com":
    var acctNum="DM551021AKEZ;DM540515HBSB";
    break;
    case "fxpowercourse.com":
    var acctNum="DM540515DFED;DM540515HBSB";
    break;
    case "fxpowercourse-asia.com":
    var acctNum="DM55040574ER;DM540515HBSB";
    break;
    case "forex-signal.com":
    var acctNum="DM550531CHBE;DM540515HBSB";
    break;
    case "fxcmpro.com":
    var acctNum="DM55091448DA;DM540515HBSB";
    break;
    case "fxcmasia.com":
    var acctNum="DM550405BBCN;DM540515HBSB";
    break;
    case "dailyfx.com":
    var acctNum="DM540515G0EV;DM540515HBSB";
    break;
    case "fxcm.co.uk":
    var acctNum="DM5405155JMM;DM540515HBSB";
    break;
    case "fxplaza.com":
    var acctNum="DM551215O8EM;DM540515HBSB";
    break;
    case "gocurrency.com":
    var acctNum="DM5507214MFB;DM540515HBSB";
    break;
    
    
    default: 
    var acctNum="DM540515HBSB"; // refcofx.ca & global account
    break;
}


// Filename Parser

var docHref=window.location.pathname;
var docPageName=docHref.substring(docHref.lastIndexOf("/")+1, docHref.length);
if ((docPageName == "") || (docPageName == "null")) {
	docPageName="Homepage";
}


// Demo Account
var demosrc_100k_aud = "https://secure2.fxcorporate.com/fxtr/demo/?ib=fxcmau&DB=AUDMINIDEMO";  
var demosrc_active_trader = "https://secure2.fxcorporate.com/fxtr/demo/?ib=fxcmau_active_trader"; 

function iframeLoad_100k() { iframeLoad( demosrc_100k_aud ); } 
function iframeLoad_active_trader() { iframeLoad( demosrc_active_trader ); } 

function iframeLoad(name) {   
	var demosrc = name;
	var theCookie = "";
	var theCookie3 = "";
	var theDate = "";
	
	var theCookie2 = GetCampaignID();
	if ( window.document.cookie != null ) {
		theCookie = getMyCookie( "JSESSIONID" );
		theCookie3 = getMyCookie( "keyword" );
		theDate = getMyCookie( "tid" );
	}
	if ( theCookie  == null ){
		theCookie = getCookie2( "jsessionid" );
	}
	if ( theDate == null ) {
		theDate = getDate();
		if ( theCookie == null ) {
			theDate = theDate + "_" + Math.random()*100000000000000000;
		} else {
			theDate = theDate + "_" + theCookie;
		}
		createMyCookie("tid", theDate, 365 );
	}
	demosrc += "&tid=" + theDate;
	if ( theCookie2 != null ) {
		demosrc += "&cmp=" + theCookie2;
	}
	if ( refdomain != null ) {
		demosrc += "&refdomain=" + refdomain;
	}
	if ( acctNum != null ) {
		demosrc += "&acctNum=" + acctNum;
	}
	if ( theCookie3 != null ) {
		demosrc += "&keyword=" + theCookie3;
	}
	document.getElementById( "demo_reg" ).src = demosrc;
}

function cutSFS( cookie ){
    var ret = cookie;	 
    if ( cookie.indexOf( "SFS-" ) > -1 ) {
        ret = ret.substring( 4 );	
    }	 	
    return ret;
} 

// live_help.js: Live Chat Function
var uri = new Object();

startList = function() {
	if (document.all&&document.getElementById&&document.getElementById("nav")) {
		navRoot = document.getElementById("nav");
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
		}
	}	 
    getURL( uri );
    setKeyword( "keyword" );
}
window.onload=startList; 

function getURL( uri ) { 
    uri.dir = location.href.substring( 0, location.href.lastIndexOf( '\/' )); 
    return uri;	 
}
function poponload() {	 
    testwindow= window.open ("/live_help/popup.html", "",
        'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=578,height=314,top=300,left=300,right=0');
    //if(testwindow) testwindow.focus();
    //testwindow.moveTo(450,300);
}
function setKeyword( name ) { 
    parm = new Array;
    value = new Array;
    var beg = "" + location.href; 	 
    beg = beg.substring( beg.indexOf( name ) );
    parm = beg.split( '&' );
    for ( i = 0; i < parm.length; i++ ) {
        value[ i ] = parm[ i ].split( '=' ); 
        if ( value[ i ][ 0 ] == name ) {                
            createMyCookie( "keyword", value[ i ][ 1 ] ); 
        }
    }
}
function createMyCookie( name, value, days ) {
    if ( days )	{
        var date = new Date();
        date.setTime( date.getTime() + ( days*24*60*60*1000 ));
        var expires = "; expires=" + date.toGMTString();
    } else {
    var expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
} 
function getDate() {
    var d = new Date();
    var year = "" + d.getFullYear();		 
    year = year.substring(( year.length - 2 ), year.length ); 
    var month = "" + ( d.getMonth() + 1 );
    if ( month.length == 1 ) {
        month = "0" + month;
    }
    var data = "" + d.getDate();
    if ( data.length == 1 ) {
        data = "0" + data;
    }		 
    return ( year + month + data );
}
function getMyCookie( name ) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf( "; " + prefix );
    if ( begin == -1 ) {
        begin = dc.indexOf( prefix );
        if ( begin != 0 ) return null;
    } else {
    begin += 2;
}
var end = document.cookie.indexOf( ";", begin );
if ( end == -1 ) {
    end = dc.length;
}    
return unescape( dc.substring( begin + prefix.length, end ));
}
function getCookie2( name ) {
    parm = new Array;
    value = new Array;
    var beg = "" + location.href; 
    
    beg = beg.substring( beg.indexOf( name ) );
    parm = beg.split( '&' );
    for ( i = 0; i < parm.length; i++ ) {
        value[ i ] = parm[ i ].split( '=' ); 
        if ( value[ i ][ 0 ] == name )  return value[ i ][ 1 ];
    }
    return null;
}   
function openForceClick() {
    var b = window.open('http://server.iad.liveperson.net/hc/17621448/?cmd=file&file=visitorWantsToChat&site=17621448&byhref=1&SESSIONVAR!skill=australia','chatw','width=472,height=420', 'menubar=no,status=no,toolbar=no,dependent=yes,alwaysRaised=yes');
    b.focus();
}
function openForceClick2() {              
    var b = window.open('https://server.iad.liveperson.net/hc/17621448/?cmd=file&file=visitorWantsToChat&site=17621448&byhref=1&SESSIONVAR!skill=australia','chatw','width=472,height=420', 'menubar=no,status=no,toolbar=no,dependent=yes,alwaysRaised=yes');
    b.focus();
}
function openForceClick3() {
    // alert ( "uri.dir" + uri.dir );              
    var b = window.open('http://server.iad.liveperson.net/hc/17621448/?cmd=file&file=visitorWantsToChat&site=17621448&byhref=1&SESSIONVAR!skill=Course','chatw','width=472,height=320', 'menubar=no,status=no,toolbar=no,dependent=yes,alwaysRaised=yes');
    b.focus();
}

function openOptionTrading( src ) {	 
    var b = window.open("http://www.forex-options.com");	 
    b.focus();	 
}

function check_tou_box( src ) {	
    if ( src.yes && src.yes.checked) {
        var toolbar_window = window.open("http://www.fxcm-toolbar.com/html/fxcm_toolbar_v1_9.exe");
        return true;
    } else {
        alert("You must agree to the \"Terms of Use\" to download the FXCM Toolbar.");
        return false;
    }
 
}
function track_atdmt( action, tag ) { 
    if ( tag != null && tag.length > 0 && action != null && action.length > 0 && document.getElementById( "trakingImage" ) != null ) {	 
        
        document.getElementById( "trakingImage" ).src = "http://switch.atdmt.com/" + action + "/" + tag;
    }
    //alert( tag.length + "  " + document.getElementById( "trakingImage" ).src );    
} 

/* toggle content visibility (expander) */
$(document).ready(function(){
	var expander = $(".expander");
	var closeLink = $(".expandable").children(".closeLink").children("a");
	$(expander).click(function(){
		var theHREF = $(expander).attr("href");
		var targetEl = "#" + theHREF.slice(1);
		$(this).toggleClass("on");
		$(targetEl).slideToggle(120);
		return false;
	});
	$(closeLink).click(function(){
		var thisID = "#" + $(this).parents(".expandable").attr("id");
		$(this).parents(".expandable").slideToggle(90);
		$(expander).attr("href", thisID).toggleClass("on");
		return false;
	});
});

function GetCampaignID(){
        var CampaignID = getURLParameter('CMP');
        if (CampaignID == null) {
                var CampaignString;
                if (CampaignString = getMyCookie("s_cpm")) {
                        eval("var CampaignArray = " + CampaignString);
                       CampaignID = CampaignArray[CampaignArray.length - 1][0];
                }
        }
        return (CampaignID == null ? '' : CampaignID); //Do not return null
}

function getURLParameter (ParameterName) {
	if (document.location.href.indexOf('?') > -1)
	{
	  var URLParameters = document.location.href.substr(document.location.href.indexOf('?')+1);
	  URLParameters = URLParameters.split('&');
	  for (URLParameterIndex in URLParameters)
	  {
		if (escape(unescape(URLParameters[URLParameterIndex].split('=')[0].toUpperCase())) == ParameterName.toUpperCase())
		{
		  return URLParameters[URLParameterIndex].split("=")[1];
		}
	  }
	}
	return null;
}

// scroll to top
$(document).ready(function(){
	$("a.scrollToTop").click(function(){
		document.getElementById("backToTop").scrollIntoView(true);
	});
});