// Form Validation Using jQuery
$(document).ready(function(){
	jQuery.validator.emailValidate = function(value, element) {
		if (this.optional(element)) {
			return this.optional(element);
		}
		if (/^[^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*@(\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([a-z\-0-9]+\.)+[a-z]{2,})$/i.test(value)) {
			if (typeof s !== 'undefined' && s.prop5 !== value){
				// prop5/eVar5 = E-mail Address
				s.prop5 = value;
				s.eVar5 = value;
				s.TrackingFunctions.SetTrackingTimeout(1000);	// Use a timeout to avoid sending multiple requests as the user types
			}
			return true;
		} else { 
			return false;
		}
	}
	
	jQuery.validator.addMethod("emailcustom", jQuery.validator.emailValidate, "Please enter a valid email address.");

	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,
				emailcustom: true
			},
			Email: {
				required: true,
				emailcustom: 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 */
	
});

/* jQuery Expander plugin
 * Version 0.4  (12/09/2008)
 * @requires jQuery v1.1.1+
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

(function($) {

  $.fn.expander = function(options) {

    var opts = $.extend({}, $.fn.expander.defaults, options);
    var delayedCollapse;
    return this.each(function() {
      var $this = $(this);
      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
     	var cleanedTag, startTags, endTags;	
     	var allText = $this.html();
     	var startText = allText.slice(0, o.slicePoint).replace(/\w+$/,'');
     	startTags = startText.match(/<\w[^>]*>/g);
   	  if (startTags) {startText = allText.slice(0,o.slicePoint + startTags.join('').length).replace(/\w+$/,'');}
   	  
     	if (startText.lastIndexOf('<') > startText.lastIndexOf('>') ) {
     	  startText = startText.slice(0,startText.lastIndexOf('<'));
     	}
     	var endText = allText.slice(startText.length);    	  
     	// create necessary expand/collapse elements if they don't already exist
   	  if (!$('span.details', this).length) {
        // end script if text length isn't long enough.
       	if ( endText.replace(/\s+$/,'').split(' ').length < o.widow ) { return; }
       	// otherwise, continue...    
       	if (endText.indexOf('</') > -1) {
         	endTags = endText.match(/<(\/)?[^>]*>/g);
          for (var i=0; i < endTags.length; i++) {

            if (endTags[i].indexOf('</') > -1) {
              var startTag, startTagExists = false;
              for (var j=0; j < i; j++) {
                startTag = endTags[j].slice(0, endTags[j].indexOf(' ')).replace(/(\w)$/,'$1>');
                if (startTag == rSlash(endTags[i])) {
                  startTagExists = true;
                }
              }              
              if (!startTagExists) {
                startText = startText + endTags[i];
                var matched = false;
                for (var s=startTags.length - 1; s >= 0; s--) {
                  if (startTags[s].slice(0, startTags[s].indexOf(' ')).replace(/(\w)$/,'$1>') == rSlash(endTags[i]) 
                  && matched == false) {
                    cleanedTag = cleanedTag ? startTags[s] + cleanedTag : startTags[s];
                    matched = true;
                  }
                };
              }
            }
          }

          endText = cleanedTag && cleanedTag + endText || endText;
        }
     	  $this.html([
     		startText,
     		'<span class="read-more">',
     		o.expandPrefix,
       		'<a href="#">',
       		  o.expandText,
       		'</a>',
        '</span>',
     		'<span class="details">',
     		  endText,
     		'</span>'
     		].join('')
     	  );
      }
      var $thisDetails = $('span.details', this),
        $readMore = $('span.read-more', this);
   	  $thisDetails.hide();
 	    $readMore.find('a').click(function() {
 	      $readMore.hide();

 	      if (o.expandEffect === 'show' && !o.expandSpeed) {
          o.beforeExpand($this);
 	        $thisDetails.show();
          o.afterExpand($this);
          delayCollapse(o, $thisDetails);
 	      } else {
          o.beforeExpand($this);
 	        $thisDetails[o.expandEffect](o.expandSpeed, function() {
            $thisDetails.css({zoom: ''});
            o.afterExpand($this);
            delayCollapse(o, $thisDetails);
 	        });
 	      }
        return false;
 	    });
      if (o.userCollapse) {
        $this
        .find('span.details').append('<span class="re-collapse">' + o.userCollapsePrefix + '<a href="#">' + o.userCollapseText + '</a></span>');
        $this.find('span.re-collapse a').click(function() {

          clearTimeout(delayedCollapse);
          var $detailsCollapsed = $(this).parents('span.details');
          reCollapse($detailsCollapsed);
          o.onCollapse($this, true);
          return false;
        });
      }
    });
    function reCollapse(el) {
       el.hide()
        .prev('span.read-more').show();
    }
    function delayCollapse(option, $collapseEl) {
      if (option.collapseTimer) {
        delayedCollapse = setTimeout(function() {  
          reCollapse($collapseEl);
          option.onCollapse($collapseEl.parent(), false);
          },
          option.collapseTimer
        );
      }
    }
    function rSlash(rString) {
      return rString.replace(/\//,'');
    }    
  };
    // plugin defaults
  $.fn.expander.defaults = {
    slicePoint:       100,  // the number of characters at which the contents will be sliced into two parts. 
                            // Note: any tag names in the HTML that appear inside the sliced element before 
                            // the slicePoint will be counted along with the text characters.
    widow:            4,  // a threshold of sorts for whether to initially hide/collapse part of the element's contents. 
                          // If after slicing the contents in two there are fewer words in the second part than 
                          // the value set by widow, we won't bother hiding/collapsing anything.
    expandText:       'read more', // text displayed in a link instead of the hidden part of the element. 
                                      // clicking this will expand/show the hidden/collapsed text
    expandPrefix:     '',
    collapseTimer:    0, // number of milliseconds after text has been expanded at which to collapse the text again
    expandEffect:     'fadeIn',
    expandSpeed:      '',   // speed in milliseconds of the animation effect for expanding the text
    userCollapse:     true, // allow the user to re-collapse the expanded text.
    userCollapseText: '[collapse expanded text]',  // text to use for the link to re-collapse the text
    userCollapsePrefix: ' ',
    beforeExpand: function($thisEl) {},
    afterExpand: function($thisEl) {},
    onCollapse: function($thisEl, byUser) {}
  };
})(jQuery);

// Language Selection
$(document).ready(function(){
	$("#langSelect").click(function(){
		$(this).toggleClass("toggle").children("div#langList").slideToggle(250);
	});
});

//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"; 
var demosrc_st = 'https://secure4.fxcorporate.com/fxtr/demo/?ib=strategy_trader_au';
var demosrc_tsg = 'https://secure2.fxcorporate.com/fxtr/demo/?ib=tsg';
var demosrc_mt4 = 'https://secure4.fxcorporate.com/fxtr/demo/?ib=fxcmau_bt&DB=MT4AUDDEMO';

function iframeLoad_100k() { iframeLoad( demosrc_100k_aud ); } 
function iframeLoad_active_trader() { iframeLoad( demosrc_active_trader ); } 
function iframeLoad_ST() { iframeLoad( demosrc_st ); }
function iframeLoad_TSG() { iframeLoad( demosrc_tsg ); }
function iframeLoad_MT4() { iframeLoad( demosrc_mt4 ); }

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;
	});
});

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

$(document).ready(function(){
	$('a.openChromelessTSweb').click(function(){
		var theURL = $(this).attr('href');
		launchTSweb(theURL);
		return false;
	 });
});
function launchTSweb(theURL) {
	var h = screen.availHeight-150;
	var w = screen.availWidth-150;
	var newwindow = window.open(theURL, 'TSG', 'height='+h+', width='+w+', top=25, left=50, scrolling=yes, toolbars=no, menubar=no, resizable=yes')
	if (window.focus) {newwindow.focus()}
}
