/* Placeholder */
(function( $ ){
	$.fn.placeHolder = function(options) {
		var eo = this;
		var settings = {
			'text'		  : 'Placeholder',
			'placeholder' : '#999',
			'active' 	  : '#000'
		};
		return this.each(function() {        
			if ( options ) { 
				$.extend( settings, options );
			}			
			eo.val(settings.text);
			eo.css("color", settings.placeholder);
			eo.focus(function() {
				if(eo.val() == settings.text) {
					eo.css("color", settings.active);
					eo.val("");	
				}
			});
			eo.focusout(function() {
				$("#search_box img").css("display","none");
				if(eo.val() == "" || eo.val() == settings.text) {
					eo.val(settings.text);
					eo.css("color", settings.placeholder);
				}
			});
		});				
	
	};
})( jQuery );

/* Scrollers */
;(function($){var l=location.href.replace(/#.*/,'');var g=$.localScroll=function(a){$('body').localScroll(a)};g.defaults={duration:1e3,axis:'y',event:'click',stop:true,target:window,reset:true};g.hash=function(a){if(location.hash){a=$.extend({},g.defaults,a);a.hash=false;if(a.reset){var e=a.duration;delete a.duration;$(a.target).scrollTo(0,a);a.duration=e}i(0,location,a)}};$.fn.localScroll=function(b){b=$.extend({},g.defaults,b);return b.lazy?this.bind(b.event,function(a){var e=$([a.target,a.target.parentNode]).filter(d)[0];if(e)i(a,e,b)}):this.find('a,area').filter(d).bind(b.event,function(a){i(a,this,b)}).end().end();function d(){return!!this.href&&!!this.hash&&this.href.replace(this.hash,'')==l&&(!b.filter||$(this).is(b.filter))}};function i(a,e,b){var d=e.hash.slice(1),f=document.getElementById(d)||document.getElementsByName(d)[0];if(!f)return;if(a)a.preventDefault();var h=$(b.target);if(b.lock&&h.is(':animated')||b.onBefore&&b.onBefore.call(b,a,f,h)===false)return;if(b.stop)h.stop(true);if(b.hash){var j=f.id==d?'id':'name',k=$('<a> </a>').attr(j,d).css({position:'absolute',top:$(window).scrollTop(),left:$(window).scrollLeft()});f[j]='';$('body').prepend(k);location=e.hash;k.remove();f[j]=d}h.scrollTo(f,b).trigger('notify.serialScroll',[f])}})(jQuery);
;(function($){var m=$.scrollTo=function(b,h,f){$(window).scrollTo(b,h,f)};m.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1};m.window=function(b){return $(window).scrollable()};$.fn.scrollable=function(){return this.map(function(){var b=this,h=!b.nodeName||$.inArray(b.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!h)return b;var f=(b.contentWindow||b).document||b.ownerDocument||b;return $.browser.safari||f.compatMode=='BackCompat'?f.body:f.documentElement})};$.fn.scrollTo=function(l,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};if(l=='max')l=9e9;a=$.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=$(k),d=l,p,g={},q=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(d)){d=n(d);break}d=$(d,this);case'object':if(d.is||d.style)p=(d=$(d)).offset()}$.each(a.axis.split(''),function(b,h){var f=h=='x'?'Left':'Top',i=f.toLowerCase(),c='scroll'+f,r=k[c],s=h=='x'?'Width':'Height';if(p){g[c]=p[i]+(q?0:r-o.offset()[i]);if(a.margin){g[c]-=parseInt(d.css('margin'+f))||0;g[c]-=parseInt(d.css('border'+f+'Width'))||0}g[c]+=a.offset[i]||0;if(a.over[i])g[c]+=d[s.toLowerCase()]()*a.over[i]}else g[c]=d[i];if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],u(s));if(!b&&a.queue){if(r!=g[c])t(a.onAfterFirst);delete g[c]}});t(a.onAfter);function t(b){o.animate(g,j,a.easing,b&&function(){b.call(this,l,a)})};function u(b){var h='scroll'+b;if(!q)return k[h];var f='client'+b,i=k.ownerDocument.documentElement,c=k.ownerDocument.body;return Math.max(i[h],c[h])-Math.min(i[f],c[f])}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);
;(function(a){var b=a.serialScroll=function(c){return a(window).serialScroll(c)};b.defaults={duration:1e3,axis:"x",event:"click",start:0,step:1,lock:!0,cycle:!0,constant:!0};a.fn.serialScroll=function(c){return this.each(function(){var t=a.extend({},b.defaults,c),s=t.event,i=t.step,r=t.lazy,e=t.target?this:document,u=a(t.target||this,e),p=u[0],m=t.items,h=t.start,g=t.interval,k=t.navigation,l;if(!r){m=d()}if(t.force){f({},h)}a(t.prev||[],e).bind(s,-i,q);a(t.next||[],e).bind(s,i,q);if(!p.ssbound){u.bind("prev.serialScroll",-i,q).bind("next.serialScroll",i,q).bind("goto.serialScroll",f)}if(g){u.bind("start.serialScroll",function(v){if(!g){o();g=!0;n()}}).bind("stop.serialScroll",function(){o();g=!1})}u.bind("notify.serialScroll",function(x,w){var v=j(w);if(v>-1){h=v}});p.ssbound=!0;if(t.jump){(r?u:d()).bind(s,function(v){f(v,j(v.target))})}if(k){k=a(k,e).bind(s,function(v){v.data=Math.round(d().length/k.length)*k.index(this);f(v,this)})}function q(v){v.data+=h;f(v,this)}function f(B,z){if(!isNaN(z)){B.data=z;z=p}var C=B.data,v,D=B.type,A=t.exclude?d().slice(0,-t.exclude):d(),y=A.length,w=A[C],x=t.duration;if(D){B.preventDefault()}if(g){o();l=setTimeout(n,t.interval)}if(!w){v=C<0?0:y-1;if(h!=v){C=v}else{if(!t.cycle){return}else{C=y-v-1}}w=A[C]}if(!w||t.lock&&u.is(":animated")||D&&t.onBefore&&t.onBefore(B,w,u,d(),C)===!1){return}if(t.stop){u.queue("fx",[]).stop()}if(t.constant){x=Math.abs(x/i*(h-C))}u.scrollTo(w,x,t).trigger("notify.serialScroll",[C])}function n(){u.trigger("next.serialScroll")}function o(){clearTimeout(l)}function d(){return a(m,p)}function j(w){if(!isNaN(w)){return w}var x=d(),v;while((v=x.index(w))==-1&&w!=p){w=w.parentNode}return v}})}})(jQuery);

/* Replace text */
(function($){$.fn.replaceText=function(b,a,c){return this.each(function(){var f=this.firstChild,g,e,d=[];if(f){do{if(f.nodeType===3){g=f.nodeValue;e=g.replace(b,a);if(e!==g){if(!c&&/</.test(e)){$(f).before(e);d.push(f)}else{f.nodeValue=e}}}}while(f=f.nextSibling)}d.length&&$(d).remove()})}})(jQuery);

/* Geolocation script */

stg_countries = ['GB', 'GG', 'IM', 'JE'];
eur_countries = ['AT', 'BE', 'BG', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE'];

function getLocation() {
	script = document.createElement('script');
	script.src = "http://api.ipinfodb.com/v2/ip_query_country.php?key=5d73c0bedb25c7a81216394a550e0be4cd4a60619511dfaffeeaec958f996354&output=json"+unescape('%26')+"callback=showPlan";
	document.body.appendChild(script);
}

function showPlan(obj){
	country_code = obj['CountryCode'].toUpperCase();
	if(jQuery.inArray(country_code, stg_countries) != -1) {
	currency = 'stg';
	} else if(jQuery.inArray(country_code, eur_countries) != -1) {
	currency = 'eur';
	} else {
	currency = 'usd';
	}
	$('#pricing .price-find').hide();
	$('#pricing .price-' + currency).show();
	$('#pricing .price-month').show();
}

/* Quote Rotator */

(function($) {
	$.fn.quovolver = function(speed, delay) {
	
		$('blockquote').css('visibility', 'visible');
		
		/* Sets default values */
		if (!speed) speed = 500;
		if (!delay) delay = 6000;
		
		// If "delay" is less than 4 times the "speed", it will break the effect 
		// If that's the case, make "delay" exactly 4 times "speed"
		var quaSpd = (speed*4);
		if (quaSpd > (delay)) delay = quaSpd;
		
		// Create the variables needed
		var	quote = $(this),
			firstQuo = $(this).filter(':first'),
			lastQuo = $(this).filter(':last'),
			wrapElem = '<div id="quote_wrap"></div>';
		
		// Wrap the quotes
		$(this).wrapAll(wrapElem);
		
		// Hide all the quotes, then show the first
		$(this).hide();
		$(firstQuo).show();
		
		// Set the hight of the wrapper
		$(this).parent().css({height: $(firstQuo).height()});		
		
		// Where the magic happens
		setInterval(function(){
			
			// Set required hight and element in variables for animation
			if($(lastQuo).is(':visible')) {
				var nextElem = $(firstQuo);
				var wrapHeight = $(nextElem).height();
			} else {
				var nextElem = $(quote).filter(':visible').next();
				var wrapHeight = $(nextElem).height();
			}
			
			// Fadeout the quote that is currently visible
			$(quote).filter(':visible').fadeOut(speed);
			
			// Set the wrapper to the hight of the next element, then fade that element in
			setTimeout(function() {
				$(quote).parent().animate({height: wrapHeight}, speed);
			}, speed);
			
			if($(lastQuo).is(':visible')) {
				setTimeout(function() {
					$(firstQuo).fadeIn(speed*2);
				}, speed*2);
				
			} else {
				setTimeout(function() {
					$(nextElem).fadeIn(speed);
				}, speed*2);
			}
			
		}, delay);
	
	};
})(jQuery);


/* Login stuff */

function getUrlVars() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++)
		{
				hash = hashes[i].split('=');
				vars.push(hash[0]);
				vars[hash[0]] = hash[1];
		}
		return vars;
	}
			
	function noaccent(chaine) {
		temp = chaine.replace(/[àâä]/gi,"a")
		temp = temp.replace(/[éèêë]/gi,"e")
		temp = temp.replace(/[îï]/gi,"i")
		temp = temp.replace(/[ôö]/gi,"o")
		temp = temp.replace(/[ùûü]/gi,"u")
		return temp
	}

	function getLanguage() {
		// Get language from query url first
		var querystring = window.location.search.substring(1).split("&");
		for(i = 0; i < querystring.length; i++) {
		key_value = querystring[i].split("=");
		if(key_value[0].toLowerCase() == 'language' || key_value[0].toLowerCase() == 'locale') {
			return key_value[1];
		}
		}

		// Or try to detect it from browser
		var language = ((navigator.language) ? navigator.language : navigator.userLanguage) || 'en';

		return language.split('-')[0];
	}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^([a-zA-Z0-9_\.\-+])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/);
	return pattern.test(emailAddress);
}

$(document).ready(function() {
	$('#form-landing, #form-panda').submit(function(){
		if (isValidEmailAddress($('#user_email').val())) {
			if (readCookie('wbsrc')) { $('.wbsrc').val(readCookie('wbsrc')); }
			else if (getUrlVars()['wbsrc']) {
				$('.wbsrc').val(getUrlVars()['wbsrc']);
			}
			if (readCookie('partner_code')) { $('.partner_code').val(readCookie('partner_code')); }
			if (getUrlVars()['partner_code']) {
				$('.partner_code').val(getUrlVars()['partner_code']);
			} 
		} else return false;
	});
	
	$('#form-footer').submit(function(){
		if (isValidEmailAddress($('#user_email_footer').val())) {
			if (readCookie('wbsrc')) { $('.wbsrc').val(readCookie('wbsrc')); }
			else if (getUrlVars()['wbsrc']) {
				$('.wbsrc').val(getUrlVars()['wbsrc']);
			}
			if (readCookie('partner_code')) { $('.partner_code').val(readCookie('partner_code')); }
			if (getUrlVars()['partner_code']) {
				$('.partner_code').val(getUrlVars()['partner_code']);
			} 
		} else return false;
	});
});

function pawse(millis) {
 var date = new Date();
 var curDate = null;

 do { curDate = new Date(); } 
 while(curDate-date < millis);
}

/* On document load */

$(document).ready(function() {

	// Removes empty p tags introduced by pb-easyDiv
	$("p").filter( function() {
		return $.trim($(this).html()) == '';
	}).remove()

	// Removes empty a tags
	$("#top-menu a").each(function() {
		var href = $(this).attr("href");
		if(href == undefined) {
			$(this).parent().remove();
			}
	});

	// Geolocation execute
	getLocation();

	// Submit form		
	$('#form-landing').submit(function() {
		if ($('#user_email').val() == 'Your email address...') {
			$('#user_email').val('');
		}
	});

	// Accordion menu	
	if($('.acc_container').length) {
		$('.acc_container').hide();
		$('.acc_trigger:first').addClass('active').next().show();

		$('.acc_trigger').click(function(){
			if( $(this).next().is(':hidden') ) {
				$('.acc_trigger').removeClass('active').next().slideUp();
				$(this).toggleClass('active').next().slideDown();
			}
			return false;
		});
	}
	
	// Rotating text on home & landing pages
	if ($("#header-graphics .rotating:eq(1)").length) {
		$("#header-graphics .rotating:first").fadeIn(1100);
		setInterval(function(){
			$('#header-graphics .rotating').filter(":visible").fadeOut(700, function(){
			if($(this).next('.rotating').size()){
					$(this).next().fadeIn(1100);
				}
				else{
					$('#header-graphics .rotating').eq(0).fadeIn(1100);
				}
			});
		}, 5000);
	} else { $("#header-graphics .rotating").show(); }
	
	// Pricing page fallback in case the infodb API page doesn`t answer (Using EUR)
	// Make sure this is the last one in document.ready
	/* pawse(2000);
	if ($('.price-find').is(':visible')) {
		$('.price-find').hide();
		$('.price-eur').show();
		$('.price-month').show();
	} */
});
