/* 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("open").children("div#langList").slideToggle(250);
	});
	//$('#langList .GR a').colorbox({inline:true,href:'.redirect-overlay.greek',transition:'elastic',onLoad: function() {$('#cboxClose').remove();}});
});

//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_active = "https://secure4.fxcorporate.com/fxtr/demo/?ib=xtp";
var demosrc_mini = "https://secure4.fxcorporate.com/fxtr/demo/?ib=FXCM&locale=MiniDemo&layout=FXCM2&DB=U10d3"; 
var demosrc_100k = "https://secure4.fxcorporate.com/fxtr/demo/?ib=fxcm&layout=FXCM2"; 
var demosrc_active_trader = "https://secure4.fxcorporate.com/fxtr/demo/?ib=active_trader"; 
var demosrc_fxcm_lp = "https://secure2.fxcorporate.com/fxtr/demo/?ib=fxcm-lp&DB=U100D1";
var demosrc_fxcm_leverage = "https://secure2.fxcorporate.com/fxtr/demo/?ib=fxcm_leverage";
var demosrc_st = 'https://secure2.fxcorporate.com/fxtr/demo/?ib=strategy_trader_llc&DB=U100D1';
var demosrc_tsg = 'https://secure2.fxcorporate.com/fxtr/demo/?ib=tsg_llc';
var demosrc_ndd = 'https://secure4.fxcorporate.com/fxtr/demo/?ib=fxcm_llc_ndd';
var demosrc_mt4 = 'https://secure4.fxcorporate.com/fxtr/demo/?ib=mt4&DB=MT4USDDEMO';
 
function iframeLoad_100k() { iframeLoad( demosrc_100k ); } 
function iframeLoad_mini() { iframeLoad( demosrc_mini ); } 
function iframeLoad_active() { iframeLoad( demosrc_active ); }
function iframeLoad_active_trader() { iframeLoad( demosrc_active_trader ); }
function iframeLoad_fxcm_lp() {	iframeLoad( demosrc_fxcm_lp ); }
function iframeLoad_fxcm_leverage() { iframeLoad( demosrc_fxcm_leverage ); }
function iframeLoad_ST() { iframeLoad( demosrc_st ); }
function iframeLoad_TSG() { iframeLoad( demosrc_tsg ); }
function iframeLoad_NDD() { iframeLoad( demosrc_ndd ); }
function iframeLoad_MT4() { iframeLoad( demosrc_mt4 ); }

function iframeLoad(name) {   
	var demosrc = name;
		var SessionID = '';
		var LastCampaign = '';
		var KeywordCookie = '';
		var TransactionID = '';
	
		if (window.document.cookie != null) {
			SessionID = getMyCookie('JSESSIONID');
			LastCampaign = GetCampaignID();
			KeywordCookie = getMyCookie('keyword');
			TransactionID = getMyCookie('tid');
	}
		if (SessionID == null){
			SessionID = getCookie2('jsessionid');
	}
		if (TransactionID == null) {
			TransactionID = getDate();
			if (SessionID == null) {
				TransactionID = TransactionID + '_' + Math.random()*100000000000000000;
		} else {
				TransactionID = TransactionID + '_' + SessionID;
		}
			createMyCookie('tid', TransactionID, 365);
	}
		demosrc += '&tid=' + TransactionID;
		
		if (LastCampaign) {
			demosrc += '&cmp=' + LastCampaign;
	}
		if (refdomain != null) {
			demosrc += '&refdomain=' + refdomain;
	}
		if (acctNum != null) {
			demosrc += '&acctNum=' + acctNum;
	}
		if (KeywordCookie != null) {
			demosrc += '&keyword=' + KeywordCookie;
	}
		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=Options','chatw','width=472,height=420', 'menubar=no,status=no,toolbar=no,dependent=yes,alwaysRaised=yes');
    b.focus();
}
function openForceClick2() {              
    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 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);
	});
});

//tooltip
$(document).ready(function(){
	//tooltip title (!! be sure to specify width of '.tooltip' on a per-case basis)
	$(".titleAttr[title]").tooltip({	
		  tip: '.tooltip',
		  relative:'true', 
		  effect: 'fade'
	});
	// replace spaces with non-breaking spaces, prevents line breaks
	var theText;
	$(".titleAttr").each(function() {
		theText = $(this).html();
		theText = theText.replace(/\s/g, "&nbsp;");
		$(this).html(theText);
	});
});

$(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()}
}

// holiday hours 
$(document).ready(function(){
	$('a.holidayHours').colorbox({href:"/img/global/holiday-hours/fxcm-holiday-hours-2011-en.gif"});
});
