/* Header GA code */
 GA = function( id, siteName ) {
	this.id = id;
	this.trackerName = ( this.id ? this.id + '.' : '' );
	//this.trackerName = '';
	if( !window._gaq ) window._gaq = [];

	var _self = this,
		//domain = document.location.href.replace(/https?:\/\/(?:www)?([^\/]+).*/, '$1');
		siteNames = {
			ar : '.alpari-ar.com',
			id : '.alpari-id.com',
			fa : '.alpari-fa.com',
			ru : '.alpari.ru',
			cn : '.alpari-markets.cn',
			en : '.alpari-forex.com',
			//es : '.alpari.com.mx',
			es : '.alpari-forex.com',
			fr : '.alpari-fr.com',
			tr : '.alpari-tr.com',
			jp : '.alpari.jp'
		};

	this.lang = ( window.PageStatus ? PageStatus.Lang() : ( window.lang ? window.lang : window.location.href.replace( /https?:\/\/([^\/]+)\/([^\/]+).*/, '$2' ) ) );
	if( this.lang.length != 2 ) {
		for( var c in siteNames ) {
			if( new RegExp( siteNames[c] ).test( window.location.href ) ) {
				this.lang = c;
				break;
			}
		}
	};
	this.domain = siteName || siteNames[this.lang];

    this.userIdentityParams = {}; // saves attributes to send them to server
    this.userIdentityParams.ga_profileID = this.id;
    this.userIdentityParams.ga_timeGAID = 'null';
    this.userIdentityParams.ga_randGAID = 'null';
	this.userIdentityParams.ga_user_id = 'null';

    this.addOrganic();
	_gaq.push( [this.trackerName + '_setAccount', this.id],
		[this.trackerName+'_setDomainName', this.domain],
		[this.trackerName+'_setAllowLinker', true],
		[this.trackerName+'_setAllowHash', false],
		
		//[this.trackerName+'_trackPageview', '?gaSkip=true'],
		function() {
			var tracker = _gat._getTrackerByName( _self.id ),
				track = tracker._trackPageview;

			_self.userIdentityParams.ga_user_id = tracker._visitCode();
			tracker._setCustomVar( 5, 'userGAID', _self.userIdentityParams.ga_user_id, 1 );
			tracker._initData();
			tracker._trackPageview = function( link ) {
				var link = link || document.location.href.replace(/https?:\/\/.+?(?=\/|$)/, ''),
                    timeGAID = new Date().getTime(),
                    randGAID = Math.random(),
					addition = 'timeGAID=' + timeGAID + '&randGAID=' + randGAID,
					pound_sign_pos = link.indexOf('#');

                _self.userIdentityParams.ga_timeGAID = timeGAID;
                _self.userIdentityParams.ga_randGAID = randGAID;
                if( !timeGAID )
                    _self.userIdentityParams.ga_timeGAID = 'null_1';
                if( !randGAID )
                    _self.userIdentityParams.ga_randGAID = 'null_1';

				if(pound_sign_pos == -1) {
					pound_sign_pos = link.length;
				}
				if( ( pos = link.substr( 0, pound_sign_pos ).indexOf( '?' ) ) != -1 ) {
					if( link.length != pos + 1) {
						if( link[pos + 1] != '#' ) {
							url = link.substr( 0, pos + 1 ) + addition + '&' + link.substr( pos + 1 );
						} else {
							url = link.substr( 0, pos + 1 ) + addition + link.substr( pos + 1 );
						}
					} else {
						url = link + addition;
					}
				} else {
					if( pound_sign_pos != link.length ) {
						url = link.substr( 0, pound_sign_pos ) + '?' + addition + link.substr( pound_sign_pos );
					} else {
						url = link + '?' + addition;
					}
				}


				track.call(tracker, url );
			};
		});
		/*
	try{
		_gaq.push( function() {
			var tracker = _gat._getTrackerByName( _self.id ),
			track = tracker._trackPageview;
			tracker._trackPageview = function( link ) {
				track.call(tracker, link);
			};
		});
	}catch(e){}
	*/
	this.sendAnalytics();
};

GA.prototype.trackPageview = function( url ) {
	_gaq.push( [this.trackerName + '_trackPageview', url] );
	
	return this;
}

GA.prototype.sendAnalytics = function() {
	if( _gaq instanceof Array )(function() {
		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	})();
}

GA.prototype.link = function( link ) {
	var _self = this;
	_gaq.push(function() {
		var tracker = _gat._getTrackerByName( _self.id );
		window.open( tracker._getLinkerUrl( link.href ), link.target );
	});
	return this;
}

GA.prototype.standartCommand = function( name, param ) {
	_gaq.push( [this.trackerName + name, param] );
	return this;
}

GA.prototype.getCustomVar = function(){
	return {
		'web_property': this.userIdentityParams.ga_profileID,
		'ts': this.userIdentityParams.ga_timeGAID,
		'unique_id': this.userIdentityParams.ga_randGAID,
		'ga_user_id': this.userIdentityParams.ga_user_id||1
	};
}

GA.prototype.setCustomVar = function( slot, name, value, level ) {
	_gaq.push( [this.trackerName + '_setCustomVar', slot, name,  value, level] );

    this.userIdentityParams['ga_customVarName' + slot] = name;
    this.userIdentityParams['ga_customVarValue' + slot] = value;

	return this;
}

GA.prototype.setVar = function( name ) {
	_gaq.push( [this.trackerName + '_setVar', name] );
	
	this.userIdentityParams['ga_varName'] = name;

	return this;
}

GA.redirect = function( url, func ) {
	window.onunload = func;
	if( /opera/.test( navigator.userAgent ) ) {
        window.onunload();
        var time_to_redirect = 500;
    }
    window.setTimeout( function() {
        document.location.replace( url );
    }, time_to_redirect || 10 );           
}

GA._onReady = (function(ie){
 var d = document;
 return ie ? function(c){
   var n = d.firstChild,
    f = function(){
     try{
      c(n.doScroll('left'))
     }catch(e){
      setTimeout(f, 10)
     }
    }; f()
  } :
  /webkit|safari|khtml/i.test(navigator.userAgent) ? function(c){
   var f = function(){
     /loaded|complete/.test(d.readyState) ? c() : setTimeout(f, 10)
    }; f()
  } :
  function(c){
   d.addEventListener('DOMContentLoaded', c, false);
  }
})(/*@cc_on 1@*/);

GA._addGAHandler = function( el, ev, handler ) {
	if( !el ) return;
	var arg = arguments[3];
	if( el.addEventListener ) {
		el.addEventListener( ev, function(e) {
			if(arg)	handler(el, arg, e);
			else handler(el, e);
		}, false);
	} else {
		el.attachEvent( 'on' + ev, function() { handler( el, arg ) } );
	}
}

GA.prototype.addLinkerEvents = function( flag_not_loaded ){
	var _self = this,
		eventTracker = function() {
			var eventDivClasses = {
					'/show/block' : /img-block/i,
					'/feedback' : /found-bugs/i
				},
				eventLinkClasses = {
					 '/show' : /\bshow(?![\-\w])/i
				},				
				eventLinkParentClasses = {
					 '/tabs' : /\btabs(?![\-\w])/i,
					 '/tabs-headers' : /\bheaders(?![\-\w])/i,
					 '/slider' : /\blavaLamp(?![\-\w])/i
				},
				as = document.getElementsByTagName('a'),
				divs = document.getElementsByTagName('div'),
				forms = document.forms,
				extDoc = ['.doc','.docx', '.xls', '.xlsx','.exe','.zip','.pdf','.js','.chm','.cab','.se','.rar','.mp3', '.jad']
				defaultLinkEvent = function( el, link ) {
					var splitResult = el.href.split( _self.domain ),
						info = ( splitResult[1] ? splitResult[1] : ( /(javascript|undefined)/i.test( el.href ) ? '' : el.href ) );
						( info.charAt(0) != '/' ) && ( info = '/' + info );
					_self.trackPageview( ( link ? link : '' ) + info );
				},
				default_url = document.location.href.replace(/https?:\/\/.+?(?=\/|$)/, '');

            // track form inputs blur
            for( var i = 0, length = forms.length; i < length; i++ ) {
                var form = forms[i];
                if( ( ( form.className && form.className.indexOf( 'ga-form-track') != -1 ) || /test1|localhost/.test( document.location.href ) ) && window.GAO ) {
                    var ga_track_change = function( ev ) {
                        if( ev && typeof ev.stopPropagation == 'function' )
                            ev.stopPropagation();
                        var name = $( this ).attr( 'id' ) || $( this ).attr( 'name' ),
                            url = document.location.href.split( document.location.hostname )[1];
						
						var replacements = [
							'?registration=full',
							'?registration=demo',
							'&registration=full',
							'&registration=demo'
						];
						for(var i = 0; i < replacements.length; i++) {
							var url = url.replace(replacements[i], '')
						}
					
						
                        if( url.charAt( url.length - 1 ) !== '/' )
                            url += '/';

                        window.GAO && GAO.trackPageview( '/ga-form-track' + url + form.id + '/' + name );
                    };

                    $( 'input, select', form ).bind( 'change', ga_track_change )
                }
            }

			for(var i = 0, length = divs.length; i < length; i++) {
				for( var c in eventDivClasses ) {
					if( eventDivClasses[c].test( divs[i].className ) ) {
						var tmp = divs[i].getAttribute( 'onclick' );
						if( tmp != null ) {
							tmp = String( tmp );
							if( tmp.indexOf( '_trackPageview' ) > -1 ) continue;
						}

						GA._addGAHandler( divs[i], 'click', function( el, link ) {
							var url = document.location.href.split( _self.domain )[1] ? document.location.href.split( _self.domain )[1] : document.location.href;
							
							var replacements = [
								'?registration=full',
								'?registration=demo',
								'&registration=full',
								'&registration=demo'
							];
							
							for(var i = 0; i < replacements.length; i++) {
								var url = url.replace(replacements[i], '')
							}
							
							_self.trackPageview( link + url + el.getAttribute( 'id' ) );
						}, c );
					}
				}
			}

			linkers : for( var i = 0; i < as.length; i++ ) {
				var flag = 0,
					tmp = as[i].getAttribute('onclick'),
					target = as[i],
					flag_break = false;

				if( tmp != null ) {
				  tmp = String( tmp );
				  if( tmp.indexOf( '_trackPageview' ) > -1 ) continue;
				}

				// Tracking outbound links off site - not the GATC
				//for( var j = 0; j < extTrack.length; j++ ) {
				if( as[i].href.indexOf( _self.domain ) == -1 && as[i].href.indexOf( 'google-analytics.com' ) == -1 ) {
					flag++;
				}
				//}

				if( flag == 1 && as[i].href.indexOf('mailto:') == -1 ){
					GA._addGAHandler( as[i], 'click', function( el ) {
						var info = ( /javascript/i.test( el.href ) ? '' : el.href );
						if( !info ) {
							if( /window\.open/.test( tmp ) )
								info = ( tmp.split( ',' )[1] ? tmp.split( ',' )[1] : tmp.split( ',' )[0] );
						}
                        if( info )
						    _self.trackPageview( '/ext/' + info );
					});
					continue linkers;
				}
				else if( as[i].href.indexOf('mailto:') != -1 ) {
					GA._addGAHandler( as[i], 'click', function( el ) {
						var splitResult = el.href.split(':');
						_self.trackPageview( '/mailto/' + splitResult[1] );
					});
					continue linkers;
				}

				// Tracking electronic documents - doc, xls, pdf, exe, zip
				for( var j = 0; j < extDoc.length; j++ ) {
					if( flag != 1 && as[i].href.indexOf( extDoc[j] ) != -1 ) {
						GA._addGAHandler( as[i], 'click', function( el, e ) {
							var splitResult = el.href.split( _self.domain );
							_self.trackPageview( '/downloads' + splitResult[1] );
							
							if(!/.pdf$/.test(el.href)&&navigator.appVersion.search('MSIE 8') == -1 && navigator.appVersion.search('MSIE 7') == -1){
								var ifr = createIFrame();
								ifr.src = el.href;
								
								if(e){
									e.stopPropagation();
									e.preventDefault();
								}else{
									event.cancelBubble = true;
									event.returnValue = false;
								}
								return false;
							}
						});
						continue linkers;
					}
				}

				for( c in eventLinkClasses ) {
					if( eventLinkClasses[c].test( as[i].className ) ) {
						GA._addGAHandler( as[i], 'click', defaultLinkEvent, c );
					 	continue linkers;
					}
				}

				while( target.nodeName != 'BODY' ) {
					for( c in eventLinkParentClasses ) {
						if( target.className && eventLinkParentClasses[c].test( target.className ) ) {
							GA._addGAHandler( as[i], 'click', defaultLinkEvent, c );
							continue linkers;
						}
					}
					target = target.parentNode;
				}
			}
		};

	if( flag_not_loaded )
		eventTracker();
	else if( window.$ )
        $( eventTracker );
	else
		GA._onReady( eventTracker );

	return this;
}

GA.prototype.addOrganic = function( ) {
	var aO = this.trackerName + '_addOrganic';

    _gaq.push(
        [aO, 'google.ru','q'],
        [aO, 'images.google.ru','q'],
        [aO, 'google.ru/search','q'],
        [aO, 'google.com.ua','q'],
        [aO, 'images.google.com.ua','q'],
        [aO, 'images.google.com','q'],
        [aO, 'images.google.md','q'],
        [aO, 'images.google.com.by','q'],
        [aO, 'images.google.lv','q'],
        [aO, 'google.co.uk','q'],
        [aO, 'google.md','q'],
        [aO, 'images.google.de','q'],
        [aO, 'images.google.lt','q'],
        [aO, 'images.google.pl','q'],
        [aO, 'images.google.bg','q'],
        [aO, 'google.com','q'],
        [aO, 'google.co.il','q'],
        [aO, 'google.com.br','q'],
        [aO, 'google.com.by','q'],
        [aO, 'google.com.bz','q'],
        [aO, 'google.com.tr','q'],
        [aO, 'google.com.tw','q'],
        [aO, 'google.ge','q'],
        [aO, 'google.kz','q'],
        [aO, 'google.lt','q'],
        [aO, 'google.lv','q'],
        [aO, 'google.pl','q'],
        [aO, 'google.se','q'],
        [aO, 'images.google.at','q'],
        [aO, 'images.google.be','q'],
        [aO, 'images.google.co.uk','q'],
        [aO, 'images.google.fr','q'],
        [aO, 'images.google.ie','q'],
        [aO, 'images.google.nl','q'],
        // russian search systems
        [aO, 'nova.rambler.ru', 'query'],
        [aO, 'search.qip.ru/search', 'query'],
        [aO, 'rambler.ru/srch', 'query'],
        [aO, 'rambler.ru/search', 'query'],
        [aO, 'search.tut.by', 'query'],
        [aO, 'poisk.ru', 'text'],
        [aO, 'ru.search.yahoo.com','p'],
        [aO, 'search.list.mail.ru','q'],
        [aO, 'search.otvet.mail.ru', 'q'],
        [aO, 'go.mail.ru', 'q', true],
        [aO, 'go.mail.ru/search', 'q', true],
        [aO, 'gogo.ru', 'q'],
        [aO, 'torg.mail.ru', 'q'],
        [aO, 'search.icq.com', 'clid'],
        [aO, 'search.icq.com', 'q'],
        [aO, 'search.qip.ru', 'query'],
        [aO, 'tyndex.ru','pnam'],
        [aO, 'search.ukr.net', 'q'],
        [aO, 'nigma.ru', 's'],
        [aO, 'nigma.ru/index.php', 's'],
        [aO, 'yaca.yandex.ru/yca', 'text'],
        [aO, 'search.list.mail.ru', 'q'],
        [aO, 'sm.aport.ru','r'],
        [aO, 'search.list.mail.ru','q'],
        [aO, 'blogs.yandex.ru', 'text'],
        [aO, 'webalta.ru', 'q'],
        [aO, 'meta.ua', 'q'],
        [aO, 'liveinternet.ru', 'ask'],
        [aO, 'gde.ru', 'keywords'],
        [aO, 'memori.qip.ru', 'search'],
        [aO, 'magna.qip.ru', 'q'],
        [aO, 'video.qip.ru', 'q'],
        [aO, 'referats.qip.ru', 'query'],
        [aO, 'blogs.yandex.ru', 'text'],
        [aO, 'wap.go.mail.ru', 'q'],
        [aO, 'bing.com', 'q']
    );

	return this;
}

var ifr;
function createIFrame(){
	if(ifr) return ifr;
	
	if(IE='\v'=='v'){
		ifr = document.createDocumentFragment()
		ifr.innerHTML = '<iframe></iframe>';
	}else{
		ifr = document.createElement('iframe');
	}
	
	document.body.appendChild(ifr);
	return ifr;
}
